File size: 73,313 Bytes
3916521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "68e9310f-109d-4f30-b263-d1e6c058ee80",
   "metadata": {},
   "source": [
    "# Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6805b3b5-782b-437c-82b3-9392abb5a599",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# %pip install -q -r requirements.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94f0fcdd-1653-440e-8ebc-9c33d931163a",
   "metadata": {},
   "source": [
    "## Config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5d0bd22f-293e-4c15-9dfe-8070553f42b5",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "INPUT_DATASET = 'derek-thomas/labeled-multiple-choice-explained-mistral-reasoning'\n",
    "REVISION = '536f3b8'\n",
    "OUTPUT_DATASET = 'derek-thomas/labeled-multiple-choice-explained-mistral-tokenized'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a1fc7a29-6b60-446d-b708-012f897de6a9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "85ca07b896804801b5ccd629341e965c",
       "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"
    }
   ],
   "source": [
    "from transformers import AutoTokenizer\n",
    "from huggingface_hub import get_token, login\n",
    "\n",
    "login()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f17edf80-7318-4b65-ae60-7433a12ad8cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "BASE_MODEL = 'mistralai/Mistral-7B-Instruct-v0.3'\n",
    "tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, token=get_token())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df697715-3cff-4177-bfa0-348a76d00a73",
   "metadata": {},
   "source": [
    "# Prompt Experiment\n",
    "## Goal\n",
    "I want to explore a few scenarios for prompt fine-tuning. Lets consider a scenario where we have the following available:\n",
    "- (Q) Question\n",
    "- (AC) Answer Choices\n",
    "- (R) Reasoning\n",
    "- (FA) Final Answer\n",
    "\n",
    "How would performance differ if we tried changing the order?\n",
    "\n",
    "Scenario 1: `Q - AC - R - FA`\n",
    "This is the most natural, we want the model to generate reasoning before the final answer. Based on how decoding works, this will give the most information before selecting the Final Answer.\n",
    "\n",
    "Scenario 2: `Q - AC - FA - R`\n",
    "This is quite awkward. Why would we put our reasoning last? Its faster. Could the model be trained in such a way to \"know\" the reasoning before responding with it? If so we could save a lot of tokens. Im skeptical, but its worth testing.\n",
    "\n",
    "Scenario 3: `Q - AC - FA`\n",
    "This is our fine-tuning control.\n",
    "\n",
    "Scenario 4: Base\n",
    "This is our un-fine-tuned control.\n",
    "\n",
    "In each of these scenarios I will build prompts with strucutred generation to fine-tune with. I noticed some difficulty in a first pass with getting consistent response formats, but thats out of scope, so structured generation can help a lot here.\n",
    "\n",
    "Datasets wont store complex structures like lists of dicts of different types (needed for structured generation, so its easiest if I tokenize. Ill be using Mistral, so Ill skip the system prompt. Its simple enough to come back and change this for a different model in this notebook.\n",
    "\n",
    "## Implementation\n",
    "To explore this goal, we will start with [layoric/labeled-multiple-choice-explained](https://huggingface.co/datasets/layoric/labeled-multiple-choice-explained) as our dataset. It has explanations already provided by GPT-3.5-turbo. Given that these explanations are a bit different than what mistral would do, it might be useful if we generate some from mistral as well. Based on [this notebook](./poe-generate-mistral-reasoning.ipynb) we have been able to generate mistral reasoning in this refined dataset [derek-thomas/labeled-multiple-choice-explained-mistral-reasoning](https://huggingface.co/datasets/derek-thomas/labeled-multiple-choice-explained-mistral-reasoning).\n",
    "\n",
    "In this notebook we will format our data such that we can try each experiment and then we will push it to my repo: [derek-thomas/labeled-multiple-choice-explained](https://huggingface.co/datasets/derek-thomas/labeled-multiple-choice-explained)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13cc5c85-0642-4348-8167-60b5ed5d37d5",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7925796f-6b90-4c43-8c22-e3906cfbdf3b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from datasets import load_dataset\n",
    "import json"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5750868-8442-4d0b-9259-4e7e490793bb",
   "metadata": {},
   "source": [
    "## Load and Preprocess the Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d8d7a40a-57af-45b9-bcea-8ac4c3ec0e61",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before Cleaning: 8413 rows\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>formatted_question</th>\n",
       "      <th>combined_fact</th>\n",
       "      <th>answer_key</th>\n",
       "      <th>topic</th>\n",
       "      <th>gpt3_5_reasoning</th>\n",
       "      <th>question_text</th>\n",
       "      <th>answer_choices</th>\n",
       "      <th>mistral_reasoning</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>what is satellite technology used for predicti...</td>\n",
       "      <td>satellite technology is used for predicting wh...</td>\n",
       "      <td>c</td>\n",
       "      <td>Technology</td>\n",
       "      <td>a) Seconds and minutes: This option is incorre...</td>\n",
       "      <td>What is satellite technology used for predicting?</td>\n",
       "      <td>(a) Seconds and minutes (b) The strength and m...</td>\n",
       "      <td>Incorrect answers and explanations:\\n\\n1. Elec...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>what does irradiating food do? (a) relieve pai...</td>\n",
       "      <td>irradiated food improves food safety.</td>\n",
       "      <td>c</td>\n",
       "      <td>Food science</td>\n",
       "      <td>(a) Relieve pain: This option is not correct b...</td>\n",
       "      <td>What does irradiating food do?</td>\n",
       "      <td>(a) Relieve pain (b) Enhance food's nutrients ...</td>\n",
       "      <td>Sure, let's examine each answer and justify wh...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>what protects a mammal's skin? (a) fiber folli...</td>\n",
       "      <td>fiber follicles protect mammal skin</td>\n",
       "      <td>a</td>\n",
       "      <td>Biology</td>\n",
       "      <td>b) Exfoliation: Exfoliation is the process of ...</td>\n",
       "      <td>What protects a mammal's skin?</td>\n",
       "      <td>(a) Fiber follicles (b) Exfoliation (c) Resist...</td>\n",
       "      <td>Sure, let's go through each of the provided an...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>what do earthworms do when a segment breaks of...</td>\n",
       "      <td>earthworms can regrow segments that break off</td>\n",
       "      <td>b</td>\n",
       "      <td>Biology</td>\n",
       "      <td>a) Dies: This option is not correct because ea...</td>\n",
       "      <td>What do earthworms do when a segment breaks off?</td>\n",
       "      <td>(a) Dies (b) Regrows it (c) Reproduces (d) Sed...</td>\n",
       "      <td>1. Reading the question carefully, we can see ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>lightning can be bad for what? (a) the environ...</td>\n",
       "      <td>lightning can be bad for the environment.</td>\n",
       "      <td>a</td>\n",
       "      <td>Electricity</td>\n",
       "      <td>b) Rainstorms: Lightning is actually a natural...</td>\n",
       "      <td>Lightning can be bad for what?</td>\n",
       "      <td>(a) The environment (b) Rainstorms (c) Destruc...</td>\n",
       "      <td>1. Food: While essential for the growth and he...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8408</th>\n",
       "      <td>organisms that can cause infection do what? (a...</td>\n",
       "      <td>organisms that can cause infection make humans...</td>\n",
       "      <td>g</td>\n",
       "      <td>Biology</td>\n",
       "      <td>a) Bandaging open sores is not the correct ans...</td>\n",
       "      <td>Organisms that can cause infection do what?</td>\n",
       "      <td>(a) Bandage open sores (b) Keep flesh clean (c...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8409</th>\n",
       "      <td>fungi are living things that cannot make thei...</td>\n",
       "      <td>fungi are living things that cannot make their...</td>\n",
       "      <td>a</td>\n",
       "      <td>Biology</td>\n",
       "      <td>b) Fungi are living things that can make their...</td>\n",
       "      <td>Fungi are living things that cannot make their...</td>\n",
       "      <td>(a) Food (b) Cells (c) Energy (d) Fruits (e) H...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8410</th>\n",
       "      <td>an overheated body can use water for: (a) meta...</td>\n",
       "      <td>the evaporation of water from the skin cools t...</td>\n",
       "      <td>g</td>\n",
       "      <td>Biology</td>\n",
       "      <td>a) Metabolic reaction: This option is incorrec...</td>\n",
       "      <td>An overheated body can use water for:?</td>\n",
       "      <td>(a) Metabolic reaction (b) Dehydrating (c) Rai...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8411</th>\n",
       "      <td>what is essential for cellular respiration for...</td>\n",
       "      <td>plants are essential for cellular respiration ...</td>\n",
       "      <td>f</td>\n",
       "      <td>Biology</td>\n",
       "      <td>a) Electrons are involved in cellular respirat...</td>\n",
       "      <td>What is essential for cellular respiration for...</td>\n",
       "      <td>(a) Electron (b) Glucose (c) Energy (d) Energy...</td>\n",
       "      <td>1. First, let's read the question and options ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8412</th>\n",
       "      <td>what helps insulate and protect the body? (a) ...</td>\n",
       "      <td>living cells in follicles help insulate and pr...</td>\n",
       "      <td>b</td>\n",
       "      <td>Biology</td>\n",
       "      <td>a) H2O: Water is essential for life, but it do...</td>\n",
       "      <td>What helps insulate and protect the body?</td>\n",
       "      <td>(a) H2o (b) Living cells in follicles (c) Laye...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>8413 rows × 8 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                                     formatted_question  \\\n",
       "0     what is satellite technology used for predicti...   \n",
       "1     what does irradiating food do? (a) relieve pai...   \n",
       "2     what protects a mammal's skin? (a) fiber folli...   \n",
       "3     what do earthworms do when a segment breaks of...   \n",
       "4     lightning can be bad for what? (a) the environ...   \n",
       "...                                                 ...   \n",
       "8408  organisms that can cause infection do what? (a...   \n",
       "8409   fungi are living things that cannot make thei...   \n",
       "8410  an overheated body can use water for: (a) meta...   \n",
       "8411  what is essential for cellular respiration for...   \n",
       "8412  what helps insulate and protect the body? (a) ...   \n",
       "\n",
       "                                          combined_fact answer_key  \\\n",
       "0     satellite technology is used for predicting wh...          c   \n",
       "1                 irradiated food improves food safety.          c   \n",
       "2                   fiber follicles protect mammal skin          a   \n",
       "3         earthworms can regrow segments that break off          b   \n",
       "4             lightning can be bad for the environment.          a   \n",
       "...                                                 ...        ...   \n",
       "8408  organisms that can cause infection make humans...          g   \n",
       "8409  fungi are living things that cannot make their...          a   \n",
       "8410  the evaporation of water from the skin cools t...          g   \n",
       "8411  plants are essential for cellular respiration ...          f   \n",
       "8412  living cells in follicles help insulate and pr...          b   \n",
       "\n",
       "             topic                                   gpt3_5_reasoning  \\\n",
       "0       Technology  a) Seconds and minutes: This option is incorre...   \n",
       "1     Food science  (a) Relieve pain: This option is not correct b...   \n",
       "2          Biology  b) Exfoliation: Exfoliation is the process of ...   \n",
       "3          Biology  a) Dies: This option is not correct because ea...   \n",
       "4      Electricity  b) Rainstorms: Lightning is actually a natural...   \n",
       "...            ...                                                ...   \n",
       "8408       Biology  a) Bandaging open sores is not the correct ans...   \n",
       "8409       Biology  b) Fungi are living things that can make their...   \n",
       "8410       Biology  a) Metabolic reaction: This option is incorrec...   \n",
       "8411       Biology  a) Electrons are involved in cellular respirat...   \n",
       "8412       Biology  a) H2O: Water is essential for life, but it do...   \n",
       "\n",
       "                                          question_text  \\\n",
       "0     What is satellite technology used for predicting?   \n",
       "1                        What does irradiating food do?   \n",
       "2                        What protects a mammal's skin?   \n",
       "3      What do earthworms do when a segment breaks off?   \n",
       "4                        Lightning can be bad for what?   \n",
       "...                                                 ...   \n",
       "8408        Organisms that can cause infection do what?   \n",
       "8409  Fungi are living things that cannot make their...   \n",
       "8410             An overheated body can use water for:?   \n",
       "8411  What is essential for cellular respiration for...   \n",
       "8412          What helps insulate and protect the body?   \n",
       "\n",
       "                                         answer_choices  \\\n",
       "0     (a) Seconds and minutes (b) The strength and m...   \n",
       "1     (a) Relieve pain (b) Enhance food's nutrients ...   \n",
       "2     (a) Fiber follicles (b) Exfoliation (c) Resist...   \n",
       "3     (a) Dies (b) Regrows it (c) Reproduces (d) Sed...   \n",
       "4     (a) The environment (b) Rainstorms (c) Destruc...   \n",
       "...                                                 ...   \n",
       "8408  (a) Bandage open sores (b) Keep flesh clean (c...   \n",
       "8409  (a) Food (b) Cells (c) Energy (d) Fruits (e) H...   \n",
       "8410  (a) Metabolic reaction (b) Dehydrating (c) Rai...   \n",
       "8411  (a) Electron (b) Glucose (c) Energy (d) Energy...   \n",
       "8412  (a) H2o (b) Living cells in follicles (c) Laye...   \n",
       "\n",
       "                                      mistral_reasoning  \n",
       "0     Incorrect answers and explanations:\\n\\n1. Elec...  \n",
       "1     Sure, let's examine each answer and justify wh...  \n",
       "2     Sure, let's go through each of the provided an...  \n",
       "3     1. Reading the question carefully, we can see ...  \n",
       "4     1. Food: While essential for the growth and he...  \n",
       "...                                                 ...  \n",
       "8408  1. Read the question and options carefully: Th...  \n",
       "8409  1. Read the question and options carefully: Th...  \n",
       "8410  1. Read the question and options carefully: Th...  \n",
       "8411  1. First, let's read the question and options ...  \n",
       "8412  1. Read the question and options carefully: Th...  \n",
       "\n",
       "[8413 rows x 8 columns]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Load dataset from Hugging Face Hub\n",
    "dataset = load_dataset(INPUT_DATASET, split='train')\n",
    "\n",
    "# Convert to pandas dataframe\n",
    "df = dataset.to_pandas()\n",
    "print(f\"Before Cleaning: {len(df)} rows\")\n",
    "\n",
    "# Drop the __index_level_0__ column if it exists\n",
    "df.drop(columns=['mistral_reasoning_prompt'], errors='ignore', inplace=True)\n",
    "\n",
    "# Ensure all values in 'formatted_question' are strings\n",
    "df.rename(columns={\n",
    "    'explanation': 'gpt3_5_reasoning',\n",
    "}, inplace=True)\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2511bc04-f611-4dc7-b3ed-e477907b0200",
   "metadata": {},
   "source": [
    "## Create Prompts from Processed Data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d124c7cf-a369-46a9-94db-069894145959",
   "metadata": {},
   "source": [
    "We need to convert our sample into a format similar to below for each of the scenarios.\n",
    "\n",
    "```\n",
    "[\n",
    "    {\"content\": user_content, \"role\": \"user\"},\n",
    "    {\"content\": assistant_response, \"role\": \"assistant\"}\n",
    "]\n",
    "```\n",
    "\n",
    "We should include a helpful system_prompt with a general trivia prefix, and a suffix that contains instructions that fit each scenario.\n",
    "The `user_content` will have the Question and answer choices.\n",
    "The `assistant_response` should reflect the scenario. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1c6554a6-4717-4bf0-ae51-102630d40fd7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "df['user_prompt'] = df.apply(lambda row: f\"Question: {row['question_text']}\\nAnswer Choices: {row['answer_choices']}\", axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1391b7e1-2462-41e3-b2f0-5a8f6c95859b",
   "metadata": {},
   "source": [
    "Here we need to create the structure of our conversation. Each system prompt should reflect the instructions we want, so we can start with a prefix and add in the specifics for each scenario."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c817304-9ecc-43d9-83b9-5bb8dd662797",
   "metadata": {},
   "source": [
    "### Reasoning Final Answer Structured Generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "878727dc-4801-4376-be26-1cc601cb5f92",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s>[INST] Answer the Question and include your Reasoning and the Final Answer in a json like: {\"Reasoning: \"...\", \"Final Answer\": \"x\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.\n",
      "Question: What is satellite technology used for predicting?\n",
      "Answer Choices: (a) Seconds and minutes (b) The strength and magnitude of an earthquake (c) What it's like outside each day (d) 70-75 degrees fahrenheit (e) Rapid changes occur (f) Dead-ends and false starts. (g) Snow, ice, and rock (h) Around 5 to 27 degrees celsius[/INST] {'Reasoning': \"a) Seconds and minutes: This option is incorrect because satellite technology is not used for predicting time intervals. Satellite technology is used for various purposes such as communication, navigation, and weather forecasting, but it is not used for predicting time intervals.\\n\\nb) The strength and magnitude of an earthquake: This option is incorrect because satellite technology is not used for predicting earthquakes. Earthquake prediction is a complex process that involves seismology and other scientific methods, but satellite technology is not one of them.\\n\\nd) 70-75 degrees Fahrenheit: This option is incorrect because satellite technology is not used for predicting specific temperature ranges. While satellite technology can provide temperature data, it is not used for predicting specific temperature ranges.\\n\\ne) Rapid changes occur: This option is too vague and does not provide enough information to determine whether it is correct or not. Satellite technology can be used to monitor changes in various environmental factors, but it is not used specifically for predicting rapid changes.\\n\\nf) Dead-ends and false starts: This option is incorrect because it is not related to satellite technology or any type of prediction.\\n\\ng) Snow, ice, and rock: This option is incorrect because it is too specific and does not cover the broad range of predictions that satellite technology can be used for. While satellite technology can be used to monitor snow, ice, and rock formations, it is not used exclusively for this purpose.\\n\\nh) Around 5 to 27 degrees Celsius: This option is incorrect because it is too specific and does not cover the broad range of temperature predictions that satellite technology can be used for. While satellite technology can provide temperature data, it is not used exclusively for predicting temperatures within a specific range.\\n\\nTherefore, the correct answer is c) what it's like outside each day, as satellite technology is commonly used for weather forecasting and predicting daily weather conditions.\", 'Final Answer': 'c'}</s>\n",
      "\n",
      "\n",
      "\n",
      "<s>[INST] Answer the Question and include your Reasoning and the Final Answer in a json like: {\"Reasoning: \"...\", \"Final Answer\": \"x\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.\n",
      "Question: What is satellite technology used for predicting?\n",
      "Answer Choices: (a) Seconds and minutes (b) The strength and magnitude of an earthquake (c) What it's like outside each day (d) 70-75 degrees fahrenheit (e) Rapid changes occur (f) Dead-ends and false starts. (g) Snow, ice, and rock (h) Around 5 to 27 degrees celsius[/INST] {'Reasoning': 'Incorrect answers and explanations:\\n\\n1. Electrical energy: Cells are not visible with electrical energy. Cells are physical structures and need to be observed visually, not through electrical means.\\n\\n2. By indirect light or Bright lights: Cells are so small that they are not visible to the naked eye under normal lighting conditions. Indirect light or bright lights are not a viable method to observe cells.\\n\\n3. Camera lenses: Camera lenses are used to focus and capture images, not to observe live objects. In order to observe cells, they must be viewed through a microscope which has a lens.\\n\\n4. Colors: Because cells are transparent, they do not have any specific color. They can appear as white or translucent when observed under a microscope.\\n\\n5. Telescope: A telescope is used for observing distant stars, galaxies, and other celestial objects, not for observing cells which are much smaller and earthbound.\\n\\n6. Rays or beams: Cells cannot be observed using rays or beams. Observation of cells is usually done via light microscopy.\\n\\n7. None of the above do not provide the means to observe cells, as they are not the tools or methods designed for cellular observation.\\n\\nThe correct answer (d) A microscope is the tool that allows us to see cells due to its magnifying capabilities making the cells visible to the naked eye effectively.', 'Final Answer': 'c'}</s>\n"
     ]
    }
   ],
   "source": [
    "# Define system prompt\n",
    "system_prompt_RFA = 'Answer the Question and include your Reasoning and the Final Answer in a json like: {\"Reasoning: \"...\", \"Final Answer\": \"x\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.'\n",
    "\n",
    "df['assistant_prompt_RFA_gpt3_5'] = df.apply(lambda row: {\"Reasoning\": row[\"gpt3_5_reasoning\"].strip(), \"Final Answer\": row[\"answer_key\"]}, axis=1)\n",
    "df['assistant_prompt_RFA_mistral'] = df.apply(lambda row: {\"Reasoning\": row[\"mistral_reasoning\"].strip(), \"Final Answer\": row[\"answer_key\"]}, axis=1)\n",
    "\n",
    "# Step 1: Create user prompt for both gpt3_5 and mistral\n",
    "df['user_prompt_RFA'] = df.apply(lambda row: {\n",
    "    \"content\": system_prompt_RFA + '\\n' + row['user_prompt'],\n",
    "    \"role\": \"user\"\n",
    "}, axis=1)\n",
    "\n",
    "# Step 2: Create conversation_RFA column using user_prompt_RFA\n",
    "df['conversation_RFA_gpt3_5'] = df.apply(lambda row: tokenizer.apply_chat_template([\n",
    "    row['user_prompt_RFA'],  # Use the precomputed user prompt\n",
    "    {\"content\": row['assistant_prompt_RFA_gpt3_5'], \"role\": \"assistant\"}\n",
    "], tokenize=False), axis=1)\n",
    "\n",
    "df['conversation_RFA_mistral'] = df.apply(lambda row: tokenizer.apply_chat_template([\n",
    "    row['user_prompt_RFA'],  # Use the precomputed user prompt\n",
    "    {\"content\": row['assistant_prompt_RFA_mistral'], \"role\": \"assistant\"}\n",
    "], tokenize=False), axis=1)\n",
    "\n",
    "df['user_prompt_RFA'] = df['user_prompt_RFA'].apply(lambda row: tokenizer.apply_chat_template([row], tokenize=False))\n",
    "\n",
    "df.drop(['assistant_prompt_RFA_gpt3_5', 'assistant_prompt_RFA_mistral'], inplace=True, axis=1)\n",
    "\n",
    "# Example output\n",
    "gpt3_5_example = df['conversation_RFA_gpt3_5'].iloc[0]\n",
    "mistral_example = df['conversation_RFA_mistral'].iloc[0]\n",
    "\n",
    "print(gpt3_5_example)\n",
    "print('\\n\\n')\n",
    "print(mistral_example)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1150ae9-cc22-44c6-8a36-0e3d7c16111b",
   "metadata": {},
   "source": [
    "### Final Answer Reasoning Structured Generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c0234242-7389-4c28-ae85-78a82498d0ac",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s>[INST] Answer the Question and include your Final Answer and the Reasoning in a json like: {\"Final Answer\": \"x\", \"Reasoning: \"...\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.\n",
      "Question: What is satellite technology used for predicting?\n",
      "Answer Choices: (a) Seconds and minutes (b) The strength and magnitude of an earthquake (c) What it's like outside each day (d) 70-75 degrees fahrenheit (e) Rapid changes occur (f) Dead-ends and false starts. (g) Snow, ice, and rock (h) Around 5 to 27 degrees celsius[/INST] {'Final Answer': 'c', 'Reasoning': \"a) Seconds and minutes: This option is incorrect because satellite technology is not used for predicting time intervals. Satellite technology is used for various purposes such as communication, navigation, and weather forecasting, but it is not used for predicting time intervals.\\n\\nb) The strength and magnitude of an earthquake: This option is incorrect because satellite technology is not used for predicting earthquakes. Earthquake prediction is a complex process that involves seismology and other scientific methods, but satellite technology is not one of them.\\n\\nd) 70-75 degrees Fahrenheit: This option is incorrect because satellite technology is not used for predicting specific temperature ranges. While satellite technology can provide temperature data, it is not used for predicting specific temperature ranges.\\n\\ne) Rapid changes occur: This option is too vague and does not provide enough information to determine whether it is correct or not. Satellite technology can be used to monitor changes in various environmental factors, but it is not used specifically for predicting rapid changes.\\n\\nf) Dead-ends and false starts: This option is incorrect because it is not related to satellite technology or any type of prediction.\\n\\ng) Snow, ice, and rock: This option is incorrect because it is too specific and does not cover the broad range of predictions that satellite technology can be used for. While satellite technology can be used to monitor snow, ice, and rock formations, it is not used exclusively for this purpose.\\n\\nh) Around 5 to 27 degrees Celsius: This option is incorrect because it is too specific and does not cover the broad range of temperature predictions that satellite technology can be used for. While satellite technology can provide temperature data, it is not used exclusively for predicting temperatures within a specific range.\\n\\nTherefore, the correct answer is c) what it's like outside each day, as satellite technology is commonly used for weather forecasting and predicting daily weather conditions.\"}</s>\n",
      "\n",
      "\n",
      "\n",
      "<s>[INST] Answer the Question and include your Final Answer and the Reasoning in a json like: {\"Final Answer\": \"x\", \"Reasoning: \"...\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.\n",
      "Question: What is satellite technology used for predicting?\n",
      "Answer Choices: (a) Seconds and minutes (b) The strength and magnitude of an earthquake (c) What it's like outside each day (d) 70-75 degrees fahrenheit (e) Rapid changes occur (f) Dead-ends and false starts. (g) Snow, ice, and rock (h) Around 5 to 27 degrees celsius[/INST] {'Final Answer': 'c', 'Reasoning': 'Incorrect answers and explanations:\\n\\n1. Electrical energy: Cells are not visible with electrical energy. Cells are physical structures and need to be observed visually, not through electrical means.\\n\\n2. By indirect light or Bright lights: Cells are so small that they are not visible to the naked eye under normal lighting conditions. Indirect light or bright lights are not a viable method to observe cells.\\n\\n3. Camera lenses: Camera lenses are used to focus and capture images, not to observe live objects. In order to observe cells, they must be viewed through a microscope which has a lens.\\n\\n4. Colors: Because cells are transparent, they do not have any specific color. They can appear as white or translucent when observed under a microscope.\\n\\n5. Telescope: A telescope is used for observing distant stars, galaxies, and other celestial objects, not for observing cells which are much smaller and earthbound.\\n\\n6. Rays or beams: Cells cannot be observed using rays or beams. Observation of cells is usually done via light microscopy.\\n\\n7. None of the above do not provide the means to observe cells, as they are not the tools or methods designed for cellular observation.\\n\\nThe correct answer (d) A microscope is the tool that allows us to see cells due to its magnifying capabilities making the cells visible to the naked eye effectively.'}</s>\n"
     ]
    }
   ],
   "source": [
    "system_prompt_FAR = 'Answer the Question and include your Final Answer and the Reasoning in a json like: {\"Final Answer\": \"x\", \"Reasoning: \"...\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.'\n",
    "\n",
    "df['assistant_prompt_FAR_gpt3_5'] = df.apply(lambda row: {\"Final Answer\": row[\"answer_key\"], \"Reasoning\": row[\"gpt3_5_reasoning\"].strip()}, axis=1)\n",
    "df['assistant_prompt_FAR_mistral'] = df.apply(lambda row: {\"Final Answer\": row[\"answer_key\"], \"Reasoning\": row[\"mistral_reasoning\"].strip()}, axis=1)\n",
    "\n",
    "# Step 1: Create user_prompt_FAR column\n",
    "df['user_prompt_FAR'] = df.apply(lambda row: {\n",
    "    \"content\": system_prompt_FAR + '\\n' + row['user_prompt'],\n",
    "    \"role\": \"user\"\n",
    "}, axis=1)\n",
    "\n",
    "# Step 2: Create conversation_FAR column using user_prompt_FAR\n",
    "df['conversation_FAR_gpt3_5'] = df.apply(lambda row: tokenizer.apply_chat_template([\n",
    "    row['user_prompt_FAR'],  # Use the precomputed user prompt\n",
    "    {\"content\": row['assistant_prompt_FAR_gpt3_5'], \"role\": \"assistant\"}\n",
    "], tokenize=False), axis=1)\n",
    "\n",
    "df['conversation_FAR_mistral'] = df.apply(lambda row: tokenizer.apply_chat_template([\n",
    "    row['user_prompt_FAR'],  # Use the precomputed user prompt\n",
    "    {\"content\": row['assistant_prompt_FAR_mistral'], \"role\": \"assistant\"}\n",
    "], tokenize=False), axis=1)\n",
    "\n",
    "df['user_prompt_FAR'] = df['user_prompt_FAR'].apply(lambda row: tokenizer.apply_chat_template([row], tokenize=False))\n",
    "\n",
    "df.drop(['assistant_prompt_FAR_gpt3_5', 'assistant_prompt_FAR_mistral'], inplace=True, axis=1)\n",
    "\n",
    "# Example output\n",
    "gpt3_5_example = df['conversation_FAR_gpt3_5'].iloc[0]\n",
    "mistral_example = df['conversation_FAR_mistral'].iloc[0]\n",
    "\n",
    "print(gpt3_5_example)\n",
    "print('\\n\\n')\n",
    "print(mistral_example)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c9f0619-1467-4b4e-ad69-b5ca2c4e58a7",
   "metadata": {},
   "source": [
    "### Final Answer Structured Generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "64dd3601-a40e-478d-97a5-5728005e5787",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s>[INST] Answer the Question and include your Final Answer in a json like: {\"Final Answer\": \"x\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.\n",
      "Question: What is satellite technology used for predicting?\n",
      "Answer Choices: (a) Seconds and minutes (b) The strength and magnitude of an earthquake (c) What it's like outside each day (d) 70-75 degrees fahrenheit (e) Rapid changes occur (f) Dead-ends and false starts. (g) Snow, ice, and rock (h) Around 5 to 27 degrees celsius[/INST] {'Final Answer': 'c'}</s>\n"
     ]
    }
   ],
   "source": [
    "system_prompt_FA = 'Answer the Question and include your Final Answer in a json like: {\"Final Answer\": \"x\"} where x is a letter that corresponds to the answer choice which is a letter between a and h.'\n",
    "df['assistant_prompt_FA'] = df.apply(lambda row: {\"Final Answer\": row[\"answer_key\"]}, axis=1)\n",
    "\n",
    "# Step 1: Create user_prompt_FA column\n",
    "df['user_prompt_FA'] = df.apply(lambda row: {\n",
    "    \"content\": system_prompt_FA + '\\n' + row['user_prompt'],\n",
    "    \"role\": \"user\"\n",
    "}, axis=1)\n",
    "\n",
    "# Step 2: Create conversation_FA_R column using user_prompt_FA\n",
    "df['conversation_FA'] = df.apply(lambda row: tokenizer.apply_chat_template([\n",
    "    row['user_prompt_FA'],  # Use the precomputed user prompt\n",
    "    {\"content\": row['assistant_prompt_FA'], \"role\": \"assistant\"}\n",
    "    # {\"content\": json.dumps(row['assistant_prompt_FA']), \"role\": \"assistant\"}\n",
    "], tokenize=False), axis=1)\n",
    "\n",
    "\n",
    "df['user_prompt_FA'] = df['user_prompt_FA'].apply(lambda row: tokenizer.apply_chat_template([row], tokenize=False))\n",
    "\n",
    "df.drop(['assistant_prompt_FA'], inplace=True, axis=1)\n",
    "\n",
    "\n",
    "# Example output\n",
    "example = df['conversation_FA'].iloc[0]\n",
    "\n",
    "print(example)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad51b99b-cf67-43d8-833c-5ec57d9d4613",
   "metadata": {},
   "source": [
    "### Cleanup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "69a687d5-35ab-4abb-8bb8-f975fa7be3f7",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['formatted_question', 'combined_fact', 'answer_key', 'topic',\n",
       "       'gpt3_5_reasoning', 'question_text', 'answer_choices',\n",
       "       'mistral_reasoning', 'user_prompt', 'user_prompt_RFA',\n",
       "       'conversation_RFA_gpt3_5', 'conversation_RFA_mistral',\n",
       "       'user_prompt_FAR', 'conversation_FAR_gpt3_5',\n",
       "       'conversation_FAR_mistral', 'user_prompt_FA', 'conversation_FA'],\n",
       "      dtype='object')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "6ec3b6b5-a359-4da8-98c8-4dae75b8a2d4",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "df = df[['topic', 'question_text', 'answer_key', 'gpt3_5_reasoning', 'mistral_reasoning', 'answer_choices', 'user_prompt', \n",
    "         'user_prompt_RFA', 'conversation_RFA_gpt3_5', 'conversation_RFA_mistral',\n",
    "         'user_prompt_FAR', 'conversation_FAR_gpt3_5', 'conversation_FAR_mistral',\n",
    "         'user_prompt_FA', 'conversation_FA']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f9f3a5a8-e4ea-4ed9-9fc0-fdd1a19b1c92",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>topic</th>\n",
       "      <th>question_text</th>\n",
       "      <th>answer_key</th>\n",
       "      <th>gpt3_5_reasoning</th>\n",
       "      <th>mistral_reasoning</th>\n",
       "      <th>answer_choices</th>\n",
       "      <th>user_prompt</th>\n",
       "      <th>user_prompt_RFA</th>\n",
       "      <th>conversation_RFA_gpt3_5</th>\n",
       "      <th>conversation_RFA_mistral</th>\n",
       "      <th>user_prompt_FAR</th>\n",
       "      <th>conversation_FAR_gpt3_5</th>\n",
       "      <th>conversation_FAR_mistral</th>\n",
       "      <th>user_prompt_FA</th>\n",
       "      <th>conversation_FA</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Technology</td>\n",
       "      <td>What is satellite technology used for predicting?</td>\n",
       "      <td>c</td>\n",
       "      <td>a) Seconds and minutes: This option is incorre...</td>\n",
       "      <td>Incorrect answers and explanations:\\n\\n1. Elec...</td>\n",
       "      <td>(a) Seconds and minutes (b) The strength and m...</td>\n",
       "      <td>Question: What is satellite technology used fo...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Food science</td>\n",
       "      <td>What does irradiating food do?</td>\n",
       "      <td>c</td>\n",
       "      <td>(a) Relieve pain: This option is not correct b...</td>\n",
       "      <td>Sure, let's examine each answer and justify wh...</td>\n",
       "      <td>(a) Relieve pain (b) Enhance food's nutrients ...</td>\n",
       "      <td>Question: What does irradiating food do?\\nAnsw...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Biology</td>\n",
       "      <td>What protects a mammal's skin?</td>\n",
       "      <td>a</td>\n",
       "      <td>b) Exfoliation: Exfoliation is the process of ...</td>\n",
       "      <td>Sure, let's go through each of the provided an...</td>\n",
       "      <td>(a) Fiber follicles (b) Exfoliation (c) Resist...</td>\n",
       "      <td>Question: What protects a mammal's skin?\\nAnsw...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Biology</td>\n",
       "      <td>What do earthworms do when a segment breaks off?</td>\n",
       "      <td>b</td>\n",
       "      <td>a) Dies: This option is not correct because ea...</td>\n",
       "      <td>1. Reading the question carefully, we can see ...</td>\n",
       "      <td>(a) Dies (b) Regrows it (c) Reproduces (d) Sed...</td>\n",
       "      <td>Question: What do earthworms do when a segment...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Electricity</td>\n",
       "      <td>Lightning can be bad for what?</td>\n",
       "      <td>a</td>\n",
       "      <td>b) Rainstorms: Lightning is actually a natural...</td>\n",
       "      <td>1. Food: While essential for the growth and he...</td>\n",
       "      <td>(a) The environment (b) Rainstorms (c) Destruc...</td>\n",
       "      <td>Question: Lightning can be bad for what?\\nAnsw...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8408</th>\n",
       "      <td>Biology</td>\n",
       "      <td>Organisms that can cause infection do what?</td>\n",
       "      <td>g</td>\n",
       "      <td>a) Bandaging open sores is not the correct ans...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "      <td>(a) Bandage open sores (b) Keep flesh clean (c...</td>\n",
       "      <td>Question: Organisms that can cause infection d...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8409</th>\n",
       "      <td>Biology</td>\n",
       "      <td>Fungi are living things that cannot make their...</td>\n",
       "      <td>a</td>\n",
       "      <td>b) Fungi are living things that can make their...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "      <td>(a) Food (b) Cells (c) Energy (d) Fruits (e) H...</td>\n",
       "      <td>Question: Fungi are living things that cannot ...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8410</th>\n",
       "      <td>Biology</td>\n",
       "      <td>An overheated body can use water for:?</td>\n",
       "      <td>g</td>\n",
       "      <td>a) Metabolic reaction: This option is incorrec...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "      <td>(a) Metabolic reaction (b) Dehydrating (c) Rai...</td>\n",
       "      <td>Question: An overheated body can use water for...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8411</th>\n",
       "      <td>Biology</td>\n",
       "      <td>What is essential for cellular respiration for...</td>\n",
       "      <td>f</td>\n",
       "      <td>a) Electrons are involved in cellular respirat...</td>\n",
       "      <td>1. First, let's read the question and options ...</td>\n",
       "      <td>(a) Electron (b) Glucose (c) Energy (d) Energy...</td>\n",
       "      <td>Question: What is essential for cellular respi...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8412</th>\n",
       "      <td>Biology</td>\n",
       "      <td>What helps insulate and protect the body?</td>\n",
       "      <td>b</td>\n",
       "      <td>a) H2O: Water is essential for life, but it do...</td>\n",
       "      <td>1. Read the question and options carefully: Th...</td>\n",
       "      <td>(a) H2o (b) Living cells in follicles (c) Laye...</td>\n",
       "      <td>Question: What helps insulate and protect the ...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "      <td>&lt;s&gt;[INST] Answer the Question and include your...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>8413 rows × 15 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "             topic                                      question_text  \\\n",
       "0       Technology  What is satellite technology used for predicting?   \n",
       "1     Food science                     What does irradiating food do?   \n",
       "2          Biology                     What protects a mammal's skin?   \n",
       "3          Biology   What do earthworms do when a segment breaks off?   \n",
       "4      Electricity                     Lightning can be bad for what?   \n",
       "...            ...                                                ...   \n",
       "8408       Biology        Organisms that can cause infection do what?   \n",
       "8409       Biology  Fungi are living things that cannot make their...   \n",
       "8410       Biology             An overheated body can use water for:?   \n",
       "8411       Biology  What is essential for cellular respiration for...   \n",
       "8412       Biology          What helps insulate and protect the body?   \n",
       "\n",
       "     answer_key                                   gpt3_5_reasoning  \\\n",
       "0             c  a) Seconds and minutes: This option is incorre...   \n",
       "1             c  (a) Relieve pain: This option is not correct b...   \n",
       "2             a  b) Exfoliation: Exfoliation is the process of ...   \n",
       "3             b  a) Dies: This option is not correct because ea...   \n",
       "4             a  b) Rainstorms: Lightning is actually a natural...   \n",
       "...         ...                                                ...   \n",
       "8408          g  a) Bandaging open sores is not the correct ans...   \n",
       "8409          a  b) Fungi are living things that can make their...   \n",
       "8410          g  a) Metabolic reaction: This option is incorrec...   \n",
       "8411          f  a) Electrons are involved in cellular respirat...   \n",
       "8412          b  a) H2O: Water is essential for life, but it do...   \n",
       "\n",
       "                                      mistral_reasoning  \\\n",
       "0     Incorrect answers and explanations:\\n\\n1. Elec...   \n",
       "1     Sure, let's examine each answer and justify wh...   \n",
       "2     Sure, let's go through each of the provided an...   \n",
       "3     1. Reading the question carefully, we can see ...   \n",
       "4     1. Food: While essential for the growth and he...   \n",
       "...                                                 ...   \n",
       "8408  1. Read the question and options carefully: Th...   \n",
       "8409  1. Read the question and options carefully: Th...   \n",
       "8410  1. Read the question and options carefully: Th...   \n",
       "8411  1. First, let's read the question and options ...   \n",
       "8412  1. Read the question and options carefully: Th...   \n",
       "\n",
       "                                         answer_choices  \\\n",
       "0     (a) Seconds and minutes (b) The strength and m...   \n",
       "1     (a) Relieve pain (b) Enhance food's nutrients ...   \n",
       "2     (a) Fiber follicles (b) Exfoliation (c) Resist...   \n",
       "3     (a) Dies (b) Regrows it (c) Reproduces (d) Sed...   \n",
       "4     (a) The environment (b) Rainstorms (c) Destruc...   \n",
       "...                                                 ...   \n",
       "8408  (a) Bandage open sores (b) Keep flesh clean (c...   \n",
       "8409  (a) Food (b) Cells (c) Energy (d) Fruits (e) H...   \n",
       "8410  (a) Metabolic reaction (b) Dehydrating (c) Rai...   \n",
       "8411  (a) Electron (b) Glucose (c) Energy (d) Energy...   \n",
       "8412  (a) H2o (b) Living cells in follicles (c) Laye...   \n",
       "\n",
       "                                            user_prompt  \\\n",
       "0     Question: What is satellite technology used fo...   \n",
       "1     Question: What does irradiating food do?\\nAnsw...   \n",
       "2     Question: What protects a mammal's skin?\\nAnsw...   \n",
       "3     Question: What do earthworms do when a segment...   \n",
       "4     Question: Lightning can be bad for what?\\nAnsw...   \n",
       "...                                                 ...   \n",
       "8408  Question: Organisms that can cause infection d...   \n",
       "8409  Question: Fungi are living things that cannot ...   \n",
       "8410  Question: An overheated body can use water for...   \n",
       "8411  Question: What is essential for cellular respi...   \n",
       "8412  Question: What helps insulate and protect the ...   \n",
       "\n",
       "                                        user_prompt_RFA  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                                conversation_RFA_gpt3_5  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                               conversation_RFA_mistral  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                                        user_prompt_FAR  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                                conversation_FAR_gpt3_5  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                               conversation_FAR_mistral  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                                         user_prompt_FA  \\\n",
       "0     <s>[INST] Answer the Question and include your...   \n",
       "1     <s>[INST] Answer the Question and include your...   \n",
       "2     <s>[INST] Answer the Question and include your...   \n",
       "3     <s>[INST] Answer the Question and include your...   \n",
       "4     <s>[INST] Answer the Question and include your...   \n",
       "...                                                 ...   \n",
       "8408  <s>[INST] Answer the Question and include your...   \n",
       "8409  <s>[INST] Answer the Question and include your...   \n",
       "8410  <s>[INST] Answer the Question and include your...   \n",
       "8411  <s>[INST] Answer the Question and include your...   \n",
       "8412  <s>[INST] Answer the Question and include your...   \n",
       "\n",
       "                                        conversation_FA  \n",
       "0     <s>[INST] Answer the Question and include your...  \n",
       "1     <s>[INST] Answer the Question and include your...  \n",
       "2     <s>[INST] Answer the Question and include your...  \n",
       "3     <s>[INST] Answer the Question and include your...  \n",
       "4     <s>[INST] Answer the Question and include your...  \n",
       "...                                                 ...  \n",
       "8408  <s>[INST] Answer the Question and include your...  \n",
       "8409  <s>[INST] Answer the Question and include your...  \n",
       "8410  <s>[INST] Answer the Question and include your...  \n",
       "8411  <s>[INST] Answer the Question and include your...  \n",
       "8412  <s>[INST] Answer the Question and include your...  \n",
       "\n",
       "[8413 rows x 15 columns]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fe52e77-0985-49d4-964e-7a17372d7007",
   "metadata": {},
   "source": [
    "## Explore Prompts\n",
    "Gradio can be really useful for quick inline apps. Here I want to make sure everything is as I expect.\n",
    "\n",
    "While the above print statements helped me see the format, the gradio app helps me explore a large volume of output easily. \n",
    "\n",
    "Note: Its tricky as I cant easily render newlines in strings. So be careful!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a50d9d6c-18e6-476d-9a40-ed7a3f699477",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7861\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7861/\" width=\"100%\" height=\"840\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "import gradio as gr\n",
    "\n",
    "# Gradio app to browse prompts with left and right buttons\n",
    "# index = 0\n",
    "\n",
    "# Functions to handle prompts\n",
    "def get_prompt(index, prompt_type):\n",
    "    return df.iloc[index][prompt_type]\n",
    "\n",
    "def next_prompt(index, prompt_type):\n",
    "    if index < len(df) - 1:\n",
    "        index += 1\n",
    "    return index, get_prompt(index, prompt_type)\n",
    "\n",
    "def previous_prompt(index, prompt_type):\n",
    "    if index > 0:\n",
    "        index -= 1\n",
    "    return index, get_prompt(index, prompt_type)\n",
    "\n",
    "# Gradio App\n",
    "with gr.Blocks() as demo:\n",
    "    gr.Markdown(\"# Prompt Browser\")\n",
    "    with gr.Row():\n",
    "        prompt_type_dropdown = gr.Dropdown(\n",
    "            choices=['conversation_RFA_gpt3_5', 'conversation_RFA_mistral', 'conversation_FAR_gpt3_5', 'conversation_FAR_mistral', 'conversation_FA_gpt3_5', 'conversation_FA_mistral'],\n",
    "            value='conversation_RFA_gpt3_5',\n",
    "            label=\"Select Prompt Type\"\n",
    "        )\n",
    "        index_display = gr.Textbox(\"0\", label=\"Index\", interactive=False)\n",
    "\n",
    "    prompt_display = gr.Textbox(value=df.iloc[0]['conversation_RFA_gpt3_5'], label=\"Prompt\")\n",
    "    \n",
    "    with gr.Row():\n",
    "        prev_button = gr.Button(\"⬅️ Previous\")\n",
    "        next_button = gr.Button(\"Next ➡️\")\n",
    "    \n",
    "    # State to hold the current index\n",
    "    index_state = gr.State(value=0)\n",
    "\n",
    "    # Button click events\n",
    "    prev_button.click(\n",
    "        fn=previous_prompt,\n",
    "        inputs=[index_state, prompt_type_dropdown],\n",
    "        outputs=[index_state, prompt_display]\n",
    "    )\n",
    "    next_button.click(\n",
    "        fn=next_prompt,\n",
    "        inputs=[index_state, prompt_type_dropdown],\n",
    "        outputs=[index_state, prompt_display]\n",
    "    )\n",
    "\n",
    "    # Dropdown change event\n",
    "    prompt_type_dropdown.change(\n",
    "        fn=lambda index, prompt_type: get_prompt(index, prompt_type),\n",
    "        inputs=[index_state, prompt_type_dropdown],\n",
    "        outputs=prompt_display\n",
    "    )\n",
    "\n",
    "    # Update index display\n",
    "    index_state.change(\n",
    "        fn=lambda index: str(index),\n",
    "        inputs=index_state,\n",
    "        outputs=index_display\n",
    "    )\n",
    "\n",
    "# Launch the app\n",
    "demo.launch(height=840)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3838daf0-8a3a-4513-ad2b-3589d60dfa3d",
   "metadata": {},
   "source": [
    "## Push Dataset to the Hub\n",
    "Its useful to get a train, test split, then we convert to `Dataset` and push to the hub. We also want to stratify on `'topic'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "25f62e9b-09f8-4912-94fd-0ded680614b2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from datasets import Dataset, DatasetDict\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# First split to create train and remaining (val + test)\n",
    "train_df, test_df = train_test_split(df, test_size=0.2, stratify=df['topic'], random_state=42)\n",
    "\n",
    "# Reset index to avoid index column in the Hugging Face Dataset\n",
    "train_df.reset_index(drop=True, inplace=True)\n",
    "test_df.reset_index(drop=True, inplace=True)\n",
    "\n",
    "# Convert each DataFrame to a Dataset object\n",
    "train_dataset = Dataset.from_pandas(train_df)\n",
    "test_dataset = Dataset.from_pandas(test_df)\n",
    "\n",
    "# Create a DatasetDict with the train, validation, and test datasets\n",
    "dataset_dict = DatasetDict({\n",
    "    'train': train_dataset,\n",
    "    'test': test_dataset\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "18a206c5-0e40-46b3-8dfb-20000789b6b5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0e40274a780c4da0868362339d48e6de",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Uploading the dataset shards:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d8ed56081baa4b4a98af22b3d904a231",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Creating parquet from Arrow format:   0%|          | 0/7 [00:00<?, ?ba/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c6b2c92b5aaa4943ab8b086f58455440",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Uploading the dataset shards:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f4a05ea3069c4f60bca73b488f8221d5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Creating parquet from Arrow format:   0%|          | 0/2 [00:00<?, ?ba/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/datasets/derek-thomas/labeled-multiple-choice-explained-mistral-tokenized/commit/f96a8487961dcfe6077df67b5351c041a4523eb1', commit_message='Upload dataset', commit_description='', oid='f96a8487961dcfe6077df67b5351c041a4523eb1', pr_url=None, repo_url=RepoUrl('https://huggingface.co/datasets/derek-thomas/labeled-multiple-choice-explained-mistral-tokenized', endpoint='https://huggingface.co', repo_type='dataset', repo_id='derek-thomas/labeled-multiple-choice-explained-mistral-tokenized'), pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Push the dataset to the Hugging Face Hub\n",
    "dataset_dict.push_to_hub(OUTPUT_DATASET)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14c279ea-4f3b-40bd-9795-edd5ea3694f7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}