File size: 48,799 Bytes
611d08c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "873f35d6-df57-48e0-a60a-45d3c9e15c96",
   "metadata": {},
   "source": [
    "# Bonito: Synthetic Data Generation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c283bd6d-ea2f-4a6f-99ac-8887e7621bcb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:32:57.354413Z",
     "iopub.status.busy": "2024-09-17T08:32:57.354090Z",
     "iopub.status.idle": "2024-09-17T08:32:57.357571Z",
     "shell.execute_reply": "2024-09-17T08:32:57.356909Z",
     "shell.execute_reply.started": "2024-09-17T08:32:57.354388Z"
    }
   },
   "source": [
    "#### Environment Setup"
   ]
  },
  {
   "cell_type": "raw",
   "id": "df65c34e-9080-4e11-9b21-12fa6f459736",
   "metadata": {},
   "source": [
    "pip freeze >> requirements_bonito.txt"
   ]
  },
  {
   "cell_type": "raw",
   "id": "3502e6ea-1ce9-497a-8bfa-dfc6ff215d07",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:26:59.911435Z",
     "iopub.status.busy": "2024-09-17T08:26:59.911244Z",
     "iopub.status.idle": "2024-09-17T08:26:59.913754Z",
     "shell.execute_reply": "2024-09-17T08:26:59.913427Z",
     "shell.execute_reply.started": "2024-09-17T08:26:59.911420Z"
    }
   },
   "source": [
    "conda create -n bonito python=3.9\n",
    "conda activate bonito\n",
    "pip install -e ."
   ]
  },
  {
   "cell_type": "raw",
   "id": "0940de6a-0e05-41f0-9d72-2f206bf77ff0",
   "metadata": {},
   "source": [
    "pip install autoawq\n",
    "pip install flash-attn==2.5.6 --no-build-isolation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b33c2d03-9cb9-4f31-bcae-d81941486e25",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:33:56.866768Z",
     "iopub.status.busy": "2024-09-17T08:33:56.866424Z",
     "iopub.status.idle": "2024-09-17T08:33:56.872656Z",
     "shell.execute_reply": "2024-09-17T08:33:56.872137Z",
     "shell.execute_reply.started": "2024-09-17T08:33:56.866742Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('2.4.0+cu121', '4.44.2', '0.6.1.post2', '0.2.6')"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import transformers\n",
    "import torch\n",
    "import vllm\n",
    "import awq\n",
    "\n",
    "torch.__version__, transformers.__version__, vllm.__version__, awq.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "987a88f2-2240-47ab-b0b7-d1589a6da59e",
   "metadata": {},
   "source": [
    "#### Quantized Bonito Wrapper\n",
    "This is a simplified quantized bonito class to generate a single synthetic input-output instruction for a given text and task type.\n",
    "This code uses huggingface `transformers` library for generation.\n",
    "For complete functionality and faster generations, we recommend using the `Bonito` class from the package."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "20855b3e-e864-4875-9135-bf1242a99242",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:26:25.162113Z",
     "iopub.status.busy": "2024-09-17T08:26:25.161926Z",
     "iopub.status.idle": "2024-09-17T08:26:25.167686Z",
     "shell.execute_reply": "2024-09-17T08:26:25.166893Z",
     "shell.execute_reply.started": "2024-09-17T08:26:25.162099Z"
    }
   },
   "outputs": [],
   "source": [
    "from typing import Dict, Optional, Union\n",
    "from datasets import Dataset\n",
    "\n",
    "SHORTFORM_TO_FULL_TASK_TYPES = {\n",
    "    \"exqa\": \"extractive question answering\",\n",
    "    \"mcqa\": \"multiple-choice question answering\",\n",
    "    \"qg\": \"question generation\",\n",
    "    \"qa\": \"question answering without choices\",\n",
    "    \"ynqa\": \"yes-no question answering\",\n",
    "    \"coref\": \"coreference resolution\",\n",
    "    \"paraphrase\": \"paraphrase generation\",\n",
    "    \"paraphrase_id\": \"paraphrase identification\",\n",
    "    \"sent_comp\": \"sentence completion\",\n",
    "    \"sentiment\": \"sentiment\",\n",
    "    \"summarization\": \"summarization\",\n",
    "    \"text_gen\": \"text generation\",\n",
    "    \"topic_class\": \"topic classification\",\n",
    "    \"wsd\": \"word sense disambiguation\",\n",
    "    \"te\": \"textual entailment\",\n",
    "    \"nli\": \"natural language inference\",\n",
    "}\n",
    "\n",
    "class AbstractBonito:\n",
    "    def _prepare_bonito_input(\n",
    "        self, context_dataset: Dataset, task_type: str, context_col: str, **kwargs\n",
    "    ) -> Dataset:\n",
    "        \"\"\"\n",
    "        Prepares the input for the Bonito model.\n",
    "\n",
    "        This method takes a context dataset, a task type, and a context\n",
    "        column name, and prepares the dataset for the Bonito model.\n",
    "        If the task type is not recognized, it raises a ValueError.\n",
    "\n",
    "        Args:\n",
    "            context_dataset (Dataset): The dataset that provides the\n",
    "                context for the task.\n",
    "            task_type (str): The type of the task. This can be a\n",
    "                short form or a full form. If the task type is not\n",
    "                recognized, a ValueError is raised.\n",
    "            context_col (str): The name of the column in the dataset\n",
    "                that provides the context for the task.\n",
    "            **kwargs: Additional keyword arguments.\n",
    "\n",
    "        Returns:\n",
    "            Dataset: The prepared dataset for the Bonito model.\n",
    "        \"\"\"\n",
    "        # get the task type name\n",
    "        if task_type in SHORTFORM_TO_FULL_TASK_TYPES.values():\n",
    "            full_task_type = task_type\n",
    "        elif task_type in SHORTFORM_TO_FULL_TASK_TYPES:\n",
    "            full_task_type = SHORTFORM_TO_FULL_TASK_TYPES[task_type]\n",
    "        else:\n",
    "            raise ValueError(f\"Task type {task_type} not recognized\")\n",
    "\n",
    "        def process(example):\n",
    "            input_text = \"<|tasktype|>\\n\" + full_task_type.strip()\n",
    "            input_text += (\n",
    "                \"\\n<|context|>\\n\" + example[context_col].strip() + \"\\n<|task|>\\n\"\n",
    "            )\n",
    "            return {\n",
    "                \"input\": input_text,\n",
    "            }\n",
    "\n",
    "        return context_dataset.map(\n",
    "            process,\n",
    "            remove_columns=context_dataset.column_names,\n",
    "            num_proc=kwargs.get(\"num_proc\", 1),\n",
    "        )\n",
    "\n",
    "    def _postprocess_dataset(\n",
    "        self, synthetic_dataset: Dataset, context_col: str, **kwargs\n",
    "    ) -> Dataset:\n",
    "        \"\"\"\n",
    "        Post-processes the synthetic dataset.\n",
    "\n",
    "        This method takes a synthetic dataset and a context column\n",
    "        name, and post-processes the dataset. It filters out\n",
    "        examples where the prediction does not contain exactly two\n",
    "        parts separated by \"<|pipe|>\", and then maps each example to a\n",
    "        new format where the context is inserted into the first part of\n",
    "        the prediction and the second part of the prediction is used as\n",
    "        the output.\n",
    "\n",
    "        Args:\n",
    "            synthetic_dataset (Dataset): The synthetic dataset to be\n",
    "                post-processed.\n",
    "            context_col (str): The name of the column in the dataset\n",
    "                that provides the context for the tasks.\n",
    "            **kwargs: Additional keyword arguments.\n",
    "\n",
    "        Returns:\n",
    "            Dataset: The post-processed synthetic dataset.\n",
    "        \"\"\"\n",
    "        synthetic_dataset = synthetic_dataset.filter(\n",
    "            lambda example: len(example[\"prediction\"].split(\"<|pipe|>\")) == 2\n",
    "        )\n",
    "\n",
    "        def process(example):\n",
    "            pair = example[\"prediction\"].split(\"<|pipe|>\")\n",
    "            context = example[context_col].strip()\n",
    "            return {\n",
    "                \"input\": pair[0].strip().replace(\"{{context}}\", context),\n",
    "                \"output\": pair[1].strip(),\n",
    "            }\n",
    "\n",
    "        synthetic_dataset = synthetic_dataset.map(\n",
    "            process,\n",
    "            remove_columns=synthetic_dataset.column_names,\n",
    "            num_proc=kwargs.get(\"num_proc\", 1),\n",
    "        )\n",
    "\n",
    "        return synthetic_dataset\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ea7d9840-162e-4c1e-b25d-354b1e110bdc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:19:16.539490Z",
     "iopub.status.busy": "2024-09-17T08:19:16.539225Z",
     "iopub.status.idle": "2024-09-17T08:19:16.807696Z",
     "shell.execute_reply": "2024-09-17T08:19:16.807297Z",
     "shell.execute_reply.started": "2024-09-17T08:19:16.539469Z"
    }
   },
   "outputs": [],
   "source": [
    "from typing import Optional, List, Dict\n",
    "from datasets import Dataset\n",
    "from awq import AutoAWQForCausalLM\n",
    "from transformers import AutoTokenizer\n",
    "\n",
    "class AWQBonito(AbstractBonito):\n",
    "    def __init__(self, model_name_or_path):\n",
    "        self.model = AutoAWQForCausalLM.from_quantized(model_name_or_path, fuse_layers=True, torch_dtype=torch.float16)\n",
    "        self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)        \n",
    "    \n",
    "    def generate_task(\n",
    "        self,\n",
    "        unannotated_paragraph: str,\n",
    "        task_type: str,\n",
    "        sampling_params: dict,\n",
    "        context_col=\"input\"\n",
    "    ) -> Dict:\n",
    "        \"\"\"\n",
    "        Generates synthetic instruction tuning pair using the Quantized Bonito model.\n",
    "        This method takes a text unannotated text, a task type, and sampling parameters,\n",
    "        and generates synthetic input-output pair.\n",
    "\n",
    "        Args:\n",
    "            unannotated_paragraph (str): The unannotated text or a paragraph\n",
    "            task_type (str): The type of the tasks. This can be a\n",
    "                short form or a full form.\n",
    "            sampling_params (dict): The parameters for\n",
    "                sampling.\n",
    "            **kwargs: Additional keyword arguments.\n",
    "\n",
    "        Returns:\n",
    "            Dict: The synthetic input-output pair for the task type.\n",
    "        \"\"\"\n",
    "\n",
    "        text_dataset = Dataset.from_list([{context_col: unannotated_paragraph}])\n",
    "\n",
    "        processed_dataset = self._prepare_bonito_input(\n",
    "            text_dataset, task_type, context_col=context_col\n",
    "        )\n",
    "\n",
    "        outputs = self._generate_text(processed_dataset[\"input\"], sampling_params)\n",
    "        examples = []\n",
    "        for i, example in enumerate(text_dataset.to_list()):\n",
    "            output = outputs[i]\n",
    "            example[\"prediction\"] = output.strip()\n",
    "            examples.append(example)\n",
    "\n",
    "        synthetic_dataset = Dataset.from_list(examples)\n",
    "\n",
    "        # filter out the examples that cannot be parsed\n",
    "        synthetic_dataset_dict = self._postprocess_dataset(\n",
    "            synthetic_dataset, context_col=context_col\n",
    "        ).to_list()[0]\n",
    "\n",
    "        return synthetic_dataset_dict\n",
    "\n",
    "    def _generate_text(\n",
    "        self,\n",
    "        dataset: Dataset,\n",
    "        sampling_params: dict,\n",
    "    ) -> List[str]:\n",
    "        \"\"\"\n",
    "        Generate text using huggingface transformers generate function.\n",
    "\n",
    "        This method takes a dataset of prompts, encodes them,\n",
    "        generates text using the model, decodes the generated\n",
    "        text, and appends it to a list.\n",
    "\n",
    "        Args:\n",
    "            dataset (Dataset): A dataset containing prompts for text generation.\n",
    "            sampling_params (dict): Parameters for sampling during generation.\n",
    "\n",
    "        Returns:\n",
    "            List[str]: A list of generated texts corresponding to the prompts.\n",
    "        \"\"\"\n",
    "        generated_texts = []\n",
    "\n",
    "        for prompt in dataset:\n",
    "            input_ids = self.tokenizer.encode(prompt, return_tensors=\"pt\")\n",
    "            input_ids = input_ids.cuda()\n",
    "\n",
    "            output = self.model.generate(input_ids, do_sample=True, **sampling_params)\n",
    "\n",
    "            generated_text = self.tokenizer.decode(\n",
    "                output[0][len(input_ids[0]) :], skip_special_tokens=True\n",
    "            )\n",
    "            generated_texts.append(generated_text)\n",
    "\n",
    "        return generated_texts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7f773af6-b700-4368-aaed-6bda08560e16",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:19:17.123688Z",
     "iopub.status.busy": "2024-09-17T08:19:17.123507Z",
     "iopub.status.idle": "2024-09-17T08:19:17.127238Z",
     "shell.execute_reply": "2024-09-17T08:19:17.126899Z",
     "shell.execute_reply.started": "2024-09-17T08:19:17.123674Z"
    }
   },
   "outputs": [],
   "source": [
    "from datasets import Dataset\n",
    "from vllm import LLM, SamplingParams\n",
    "\n",
    "class VLLMBonito(LLM, AbstractBonito):\n",
    "    \n",
    "    def generate_tasks(\n",
    "        self,\n",
    "        text_dataset: Dataset,\n",
    "        context_col: str,\n",
    "        task_type: str,\n",
    "        sampling_params: SamplingParams,\n",
    "        **kwargs,\n",
    "    ):\n",
    "        \"\"\"\n",
    "        Generates tasks using the Bonito model.\n",
    "\n",
    "        This method takes a text dataset, a context column name,\n",
    "        a task type, and sampling parameters, and generates tasks\n",
    "        using the Bonito model. It processes the input dataset,\n",
    "        generates outputs, collects multiple generations into\n",
    "        one dataset object, and filters out the examples that\n",
    "        cannot be parsed.\n",
    "\n",
    "        Args:\n",
    "            text_dataset (Dataset): The dataset that provides the text\n",
    "                for the tasks.\n",
    "            context_col (str): The name of the column in the dataset\n",
    "                that provides the context for the tasks.\n",
    "            task_type (str): The type of the tasks. This can be a\n",
    "                short form or a full form.\n",
    "            sampling_params (SamplingParams): The parameters for\n",
    "                sampling.\n",
    "            **kwargs: Additional keyword arguments.\n",
    "\n",
    "        Returns:\n",
    "            Dataset: The synthetic dataset with the generated tasks.\n",
    "        \"\"\"\n",
    "        processed_dataset = self._prepare_bonito_input(\n",
    "            text_dataset, task_type, context_col, **kwargs\n",
    "        )\n",
    "        outputs = self.generate(processed_dataset[\"input\"], sampling_params)\n",
    "\n",
    "        # collect multiple generations into one dataset object\n",
    "        examples = []\n",
    "        for i, example in enumerate(text_dataset.to_list()):\n",
    "            for output in outputs[i].outputs:\n",
    "                examples.append(\n",
    "                    {\"context\": example[context_col], \"prediction\": output.text.strip()}\n",
    "                )\n",
    "\n",
    "        synthetic_dataset = Dataset.from_list(examples)\n",
    "\n",
    "        # filter out the examples that cannot be parsed\n",
    "        synthetic_dataset = self._postprocess_dataset(\n",
    "            synthetic_dataset, context_col=\"context\", **kwargs\n",
    "        )\n",
    "\n",
    "        return synthetic_dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d666ab6-7722-4afd-9bde-dad5039f442e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T07:41:42.559750Z",
     "iopub.status.busy": "2024-09-17T07:41:42.559531Z",
     "iopub.status.idle": "2024-09-17T07:41:42.563349Z",
     "shell.execute_reply": "2024-09-17T07:41:42.562597Z",
     "shell.execute_reply.started": "2024-09-17T07:41:42.559738Z"
    }
   },
   "source": [
    "## Synthetic Data Generation\n",
    "Here we will load the quantized bonito model and generate synthetic instruction for the unannotated text.\n",
    "\n",
    "```\n",
    "SHORTFORM_TO_FULL_TASK_TYPES = {\n",
    "    \"exqa\": \"extractive question answering\",\n",
    "    \"mcqa\": \"multiple-choice question answering\",\n",
    "    \"qg\": \"question generation\",\n",
    "    \"qa\": \"question answering without choices\",\n",
    "    \"ynqa\": \"yes-no question answering\",\n",
    "    \"coref\": \"coreference resolution\",\n",
    "    \"paraphrase\": \"paraphrase generation\",\n",
    "    \"paraphrase_id\": \"paraphrase identification\",\n",
    "    \"sent_comp\": \"sentence completion\",\n",
    "    \"sentiment\": \"sentiment\",\n",
    "    \"summarization\": \"summarization\",\n",
    "    \"text_gen\": \"text generation\",\n",
    "    \"topic_class\": \"topic classification\",\n",
    "    \"wsd\": \"word sense disambiguation\",\n",
    "    \"te\": \"textual entailment\",\n",
    "    \"nli\": \"natural language inference\",\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a577b15a-fd75-48bb-8faf-bb97a424db48",
   "metadata": {},
   "source": [
    "### Generate the synthetic instructions\n",
    "After loading the model, we pass the unannotated paragraph and the task type to generate the instructions.\n",
    "Here we generate an NLI task:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3704550e-e109-404c-8d0e-127bcebf28e6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:22:59.468174Z",
     "iopub.status.busy": "2024-09-17T08:22:59.467863Z",
     "iopub.status.idle": "2024-09-17T08:22:59.472978Z",
     "shell.execute_reply": "2024-09-17T08:22:59.472332Z",
     "shell.execute_reply.started": "2024-09-17T08:22:59.468149Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\n1. “Confidential Information”, whenever used in this Agreement, shall mean any data, document, specification and other information or material, that is delivered or disclosed by UNHCR to the Recipient in any form whatsoever, whether orally, visually in writing or otherwise (including computerized form), and that, at the time of disclosure to the Recipient, is designated as confidential.\\n'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## sample text\n",
    "unannotated_paragraph = \"\"\"\n",
    "1. “Confidential Information”, whenever used in this Agreement, shall mean any data, document, specification and other information or material, that is delivered or disclosed by UNHCR to the Recipient in any form whatsoever, whether orally, visually in writing or otherwise (including computerized form), and that, at the time of disclosure to the Recipient, is designated as confidential.\n",
    "\"\"\"\n",
    "unannotated_paragraph"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa1e941d-317d-415d-b2fb-5177394f68f9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:31:33.945680Z",
     "iopub.status.busy": "2024-09-17T08:31:33.945338Z",
     "iopub.status.idle": "2024-09-17T08:31:33.949066Z",
     "shell.execute_reply": "2024-09-17T08:31:33.948384Z",
     "shell.execute_reply.started": "2024-09-17T08:31:33.945653Z"
    }
   },
   "source": [
    "### Quantized Bonito : AWQ Inference"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "012d7f03-3629-45a0-be38-64b90dc6ce0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "model_id = 'mychen76/Llama-3.1-8B-bonito-v1-awq'\n",
    "bonito = AWQBonito(model_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c70d39e-f790-47c3-9b2c-ed5212cc6416",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:17:55.265931Z",
     "iopub.status.busy": "2024-09-17T08:17:55.265618Z",
     "iopub.status.idle": "2024-09-17T08:17:55.269425Z",
     "shell.execute_reply": "2024-09-17T08:17:55.268769Z",
     "shell.execute_reply.started": "2024-09-17T08:17:55.265905Z"
    }
   },
   "source": [
    "### generate nli"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ede84178-63b1-4df0-a1c5-1dfefa0a986e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import set_seed\n",
    "from pprint import pprint\n",
    "set_seed(2)\n",
    "\n",
    "# Generate synthetic instruction tuning dataset\n",
    "sampling_params = {\n",
    "    \"max_new_tokens\": 256,\n",
    "    \"top_p\": 0.95,\n",
    "    \"temperature\": 0.7,\n",
    "    \"num_return_sequences\": 1,\n",
    "}\n",
    "synthetic_dataset = bonito.generate_task(\n",
    "    unannotated_paragraph, task_type=\"nli\", sampling_params=sampling_params\n",
    ")\n",
    "pprint(\"----Generated Instructions----\")\n",
    "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
    "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7fcf6e8-f6cb-4ac8-b37b-f193ffd6f924",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:18:08.288818Z",
     "iopub.status.busy": "2024-09-17T08:18:08.288500Z",
     "iopub.status.idle": "2024-09-17T08:18:08.292090Z",
     "shell.execute_reply": "2024-09-17T08:18:08.291481Z",
     "shell.execute_reply.started": "2024-09-17T08:18:08.288792Z"
    }
   },
   "source": [
    "### generate qa"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef1d3ba1-5a2f-4a7b-adce-5b030df2fb73",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import set_seed\n",
    "from pprint import pprint\n",
    "set_seed(2)\n",
    "\n",
    "# Generate synthetic instruction tuning dataset\n",
    "sampling_params = {\n",
    "    \"max_new_tokens\": 256,\n",
    "    \"top_p\": 0.95,\n",
    "    \"temperature\": 0.7,\n",
    "    \"num_return_sequences\": 1,\n",
    "}\n",
    "synthetic_dataset = bonito.generate_task(\n",
    "    unannotated_paragraph, task_type=\"qa\", sampling_params=sampling_params\n",
    ")\n",
    "pprint(\"----Generated Instructions----\")\n",
    "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
    "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9f79b37-d1bc-49bf-8d7d-fc2d088846c0",
   "metadata": {},
   "source": [
    "### vLLM Bonito : AWQ Inference\n",
    "ValueError: The model's max seq len (131072) is larger than the maximum number of tokens that can be stored in KV cache (129248). Try increasing `gpu_memory_utilization` or decreasing `max_model_len` when initializing the engine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1a3ffd80-94f0-47bc-b1fe-47444bda66b6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:19:02.242069Z",
     "iopub.status.busy": "2024-09-17T08:19:02.241824Z",
     "iopub.status.idle": "2024-09-17T08:19:04.107622Z",
     "shell.execute_reply": "2024-09-17T08:19:04.107273Z",
     "shell.execute_reply.started": "2024-09-17T08:19:02.242049Z"
    }
   },
   "outputs": [],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "# load dataaset with unannotated text\n",
    "unannotated_text_ds = load_dataset(\n",
    "    \"BatsResearch/bonito-experiment\",\n",
    "    \"unannotated_contract_nli\"\n",
    ")[\"train\"].select(range(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "98f9a917-070d-4c10-9d29-5ecce6c786bb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:19:22.658366Z",
     "iopub.status.busy": "2024-09-17T08:19:22.658098Z",
     "iopub.status.idle": "2024-09-17T08:19:39.785070Z",
     "shell.execute_reply": "2024-09-17T08:19:39.784677Z",
     "shell.execute_reply.started": "2024-09-17T08:19:22.658345Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO 09-17 04:19:22 awq_marlin.py:93] Detected that the model can run with awq_marlin, however you specified quantization=awq explicitly, so forcing awq. Use quantization=awq_marlin for faster inference\n",
      "WARNING 09-17 04:19:22 config.py:338] awq quantization is not fully optimized yet. The speed can be slower than non-quantized models.\n",
      "INFO 09-17 04:19:22 llm_engine.py:223] Initializing an LLM engine (v0.6.1.post2) with config: model='mychen76/Llama-3.1-8B-bonito-v1-awq', speculative_config=None, tokenizer='mychen76/Llama-3.1-8B-bonito-v1-awq', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config=None, rope_scaling=None, rope_theta=None, tokenizer_revision=None, trust_remote_code=False, dtype=torch.float16, max_seq_len=4096, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=awq, enforce_eager=False, kv_cache_dtype=auto, quantization_param_path=None, device_config=cuda, decoding_config=DecodingConfig(guided_decoding_backend='outlines'), observability_config=ObservabilityConfig(otlp_traces_endpoint=None, collect_model_forward_time=False, collect_model_execute_time=False), seed=0, served_model_name=mychen76/Llama-3.1-8B-bonito-v1-awq, use_v2_block_manager=False, num_scheduler_steps=1, enable_prefix_caching=False, use_async_output_proc=True)\n",
      "INFO 09-17 04:19:23 model_runner.py:997] Starting to load model mychen76/Llama-3.1-8B-bonito-v1-awq...\n",
      "INFO 09-17 04:19:23 weight_utils.py:242] Using model weights format ['*.safetensors']\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0e53544149e94bacbc0a1c854690f32a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading safetensors checkpoint shards:   0% Completed | 0/2 [00:00<?, ?it/s]\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO 09-17 04:19:24 model_runner.py:1008] Loading model weights took 5.3745 GB\n",
      "INFO 09-17 04:19:26 gpu_executor.py:122] # GPU blocks: 6132, # CPU blocks: 2048\n",
      "INFO 09-17 04:19:28 model_runner.py:1311] Capturing the model for CUDA graphs. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or use '--enforce-eager' in the CLI.\n",
      "INFO 09-17 04:19:28 model_runner.py:1315] CUDA graphs can take additional 1~3 GiB memory per GPU. If you are running out of memory, consider decreasing `gpu_memory_utilization` or enforcing eager mode. You can also reduce the `max_num_seqs` as needed to decrease memory usage.\n",
      "INFO 09-17 04:19:39 model_runner.py:1430] Graph capturing finished in 11 secs.\n"
     ]
    }
   ],
   "source": [
    "from vllm import LLM, SamplingParams\n",
    "import torch \n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "model_id = 'mychen76/Llama-3.1-8B-bonito-v1-awq'\n",
    "\n",
    "# Create an LLM.\n",
    "vbonito = VLLMBonito(model=model_id, \n",
    "              quantization=\"AWQ\",\n",
    "              gpu_memory_utilization=0.80,\n",
    "              max_seq_len_to_capture=4096,\n",
    "              max_model_len=4096,\n",
    "              speculative_max_model_len = 4096)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e04ccba5-907b-406f-8396-f880d371273d",
   "metadata": {},
   "source": [
    "#### generate \"nli\": \"natural language inference\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "50b8baac-18c8-41bd-b126-190119087ccc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:20:10.531375Z",
     "iopub.status.busy": "2024-09-17T08:20:10.531202Z",
     "iopub.status.idle": "2024-09-17T08:20:11.851687Z",
     "shell.execute_reply": "2024-09-17T08:20:11.851225Z",
     "shell.execute_reply.started": "2024-09-17T08:20:10.531362Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processed prompts: 100%|██████████████████| 10/10 [00:01<00:00,  7.72it/s, est. speed input: 757.82 toks/s, output: 359.21 toks/s]\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "37f9beb99d0448fba399cd2cb1dad305",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Filter:   0%|          | 0/10 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "90458d9887d04da3b2b2bc5d101e6fee",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/10 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'----Generated Instructions----'\n",
      "(\"Input: ['Given that 2.3 Provided that the Recipient has a written agreement \"\n",
      " 'with the following persons or entities requiring them to treat the '\n",
      " 'Confidential Information in accordance with this Agreement, the Recipient '\n",
      " 'may disclose the Confidential Information to: 2.3.1  Any other party with '\n",
      " 'the Discloser’s prior written consent; and 2.3.2 the Recipient’s employees, '\n",
      " 'officials, representatives and agents who have a strict need to know the '\n",
      " 'contents of the Confidential Information, and employees, officials, '\n",
      " 'representatives and agents of any legal entity that it controls, controls '\n",
      " 'it, or with which it is under common control, who have a similar need to '\n",
      " 'know the contents of the Confidential Information, provided that, for these '\n",
      " 'purposes a controlled legal entity means: Does it follow that The Recipient '\n",
      " \"is a person Yes, no, or maybe?', '5. All Confidential Information in any \"\n",
      " 'form and any medium, including all copies thereof, disclosed to the '\n",
      " 'Recipient shall be returned to UNHCR or destroyed:  (a) if a business '\n",
      " 'relationship is not entered into with UNHCR on or before the date which is '\n",
      " 'three (3) months after the date both Parties have signed the Agreement; or '\n",
      " 'Based on that information, is the claim: \"The UNHCR is not a recipient.\" '\n",
      " \"true, false, or inconclusive?', 'Given 4. Nothing in this Agreement is to be \"\n",
      " 'construed as granting the Recipient, by implication or otherwise, any right '\n",
      " 'whatsoever with respect to the Confidential Information or part thereof. Is '\n",
      " 'it guaranteed true that \"The Recipient is not granted any rights to the '\n",
      " 'Confidential Information.\"? Yes, no, or maybe?\\', \\'11. The Recipient shall '\n",
      " 'not advertise or otherwise make public the fact that it has a confidential '\n",
      " 'relationship with UNHCR, nor shall the Recipient, in any manner whatsoever '\n",
      " 'use the name, emblem, or official seal of the United Nations or UNHCR, or '\n",
      " 'any abbreviation of the name of the United Nations or UNHCR in connection '\n",
      " 'with its business or otherwise. \\\\n\\\\nQuestion: Does this imply that \"The '\n",
      " 'United Nations is a good organization.\"? Yes, no, or maybe?\\', \\'1. '\n",
      " '“Confidential Information”, whenever used in this Agreement, shall mean any '\n",
      " 'data, document, specification and other information or material, that is '\n",
      " 'delivered or disclosed by UNHCR to the Recipient in any form whatsoever, '\n",
      " 'whether orally, visually in writing or otherwise (including computerized '\n",
      " 'form), and that, at the time of disclosure to the Recipient, is designated '\n",
      " 'as confidential.\\\\nQuestion: The UNHCR is a non-governmental organization. '\n",
      " \"True, False, or Neither?', '1. “Confidential Information”, whenever used in \"\n",
      " 'this Agreement, shall mean any data, document, specification and other '\n",
      " 'information or material, that is delivered or disclosed by UNHCR to the '\n",
      " 'Recipient in any form whatsoever, whether orally, visually in writing or '\n",
      " 'otherwise (including computerized form), and that, at the time of disclosure '\n",
      " 'to the Recipient, is designated as confidential. Based on that information, '\n",
      " 'is the claim: \"Confidential Information is only delivered to the Recipient '\n",
      " 'in written form.\" true, false, or inconclusive?\\', \\'Either Party may '\n",
      " 'terminate the working relationship contemplated by this Agreement by '\n",
      " 'providing written notice to the other, provided, however, that the '\n",
      " 'obligations and restrictions hereunder regarding the Confidential '\n",
      " 'Information shall remain effective following any such termination or any '\n",
      " 'other termination or expiration of this Agreement. Using only the above '\n",
      " 'description and the fact that \"The obligations and restrictions hereunder '\n",
      " 'regarding the Confidential Information shall remain effective following any '\n",
      " 'such termination or any other termination or expiration of this Agreement.\" '\n",
      " 'is true, is \"The obligations and restrictions hereunder regarding the '\n",
      " 'Confidential Information shall remain effective following any such '\n",
      " 'termination or any other termination or expiration of this Agreement. It is '\n",
      " 'a very long sentence.\" always, sometimes, or never true?\\', \\'The Recipient '\n",
      " 'shall not be precluded from disclosing the Confidential Information that is  '\n",
      " '(i) obtained by the Recipient without restriction from a third party who is '\n",
      " 'not in breach of any obligation as to confidentiality to the owner of such '\n",
      " 'Confidential Information or any other person, or  (ii) disclosed by the '\n",
      " 'Discloser to a third party without any obligation of confidentiality, or  '\n",
      " '(iii) previously known by the Recipient, or  (iv) at any time is developed '\n",
      " 'by the Recipient completely independently of any disclosures hereunder. '\n",
      " '\\\\n\\\\nQuestion: Does this imply that \"Confidential Information has been seen '\n",
      " 'by carl\"? Yes, no, or maybe?\\', \\'Assume it is true that The Recipient shall '\n",
      " 'not be precluded from disclosing the Confidential Information that is  (i) '\n",
      " 'obtained by the Recipient without restriction from a third party who is not '\n",
      " 'in breach of any obligation as to confidentiality to the owner of such '\n",
      " 'Confidential Information or any other person, or \\\\n\\\\nTherefore, \"The '\n",
      " 'Recipient shall not be precluded from disclosing the Confidential '\n",
      " 'Information that is obtained by the Recipient without restriction from a '\n",
      " 'third party who is not in breach of any obligation as to confidentiality to '\n",
      " 'the owner of such Confidential Information or any other person, or the owner '\n",
      " 'of such Confidential Information.\" is guaranteed, possible, or '\n",
      " \"impossible?', '1. “Confidential Information”, whenever used in this \"\n",
      " 'Agreement, shall mean any data, document, specification and other '\n",
      " 'information or material, that is delivered or disclosed by UNHCR to the '\n",
      " 'Recipient in any form whatsoever, whether orally, visually in writing or '\n",
      " 'otherwise (including computerized form), and that, at the time of disclosure '\n",
      " 'to the Recipient, is designated as confidential. \\\\n\\\\nKeeping in mind the '\n",
      " 'above text, consider: Confidential Information is not protected by the '\n",
      " \"agreement. Is this always, sometimes, or never correct?']\")\n",
      "(\"Output: ['Maybe', 'False', 'Yes', 'Maybe', 'Neither', 'False', 'Sometimes', \"\n",
      " \"'Maybe', 'Guaranteed', 'Never']\")\n"
     ]
    }
   ],
   "source": [
    "from vllm import SamplingParams\n",
    "from transformers import set_seed\n",
    "from pprint import pprint\n",
    "set_seed(2)\n",
    "\n",
    "# Generate synthetic instruction tuning dataset\n",
    "sampling_params = SamplingParams(max_tokens=256, top_p=0.95, temperature=0.5, n=1)\n",
    "\n",
    "synthetic_dataset = vbonito.generate_tasks(\n",
    "    unannotated_text_ds,\n",
    "    context_col=\"input\",\n",
    "    task_type=\"nli\",\n",
    "    sampling_params=sampling_params\n",
    ")\n",
    "\n",
    "pprint(\"----Generated Instructions----\")\n",
    "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
    "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ddedcdb4-6d2c-4fa0-8508-3521285d460d",
   "metadata": {},
   "source": [
    "#### \"exqa\": \"extractive question answering\","
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "38b09b41-d044-48f4-aabc-16634e8e99c4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-09-17T08:24:37.023979Z",
     "iopub.status.busy": "2024-09-17T08:24:37.023731Z",
     "iopub.status.idle": "2024-09-17T08:24:38.025746Z",
     "shell.execute_reply": "2024-09-17T08:24:38.025384Z",
     "shell.execute_reply.started": "2024-09-17T08:24:37.023955Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5a59db3acc764c03b00c3a683f5c2827",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/10 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processed prompts: 100%|█████████████████| 10/10 [00:00<00:00, 10.39it/s, est. speed input: 1030.27 toks/s, output: 429.36 toks/s]\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1b8deb9aa5564b498249d91d6534e912",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Filter:   0%|          | 0/10 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "489786c4cc6f4a67bbc2f2df0fe36506",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/10 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'----Generated Instructions----'\n",
      "('Input: [\\'Given the following passage\\\\n\\\\n\"2.3 Provided that the Recipient '\n",
      " 'has a written agreement with the following persons or entities requiring '\n",
      " 'them to treat the Confidential Information in accordance with this '\n",
      " 'Agreement, the Recipient may disclose the Confidential Information to: '\n",
      " '2.3.1  Any other party with the Discloser’s prior written consent; and 2.3.2 '\n",
      " 'the Recipient’s employees, officials, representatives and agents who have a '\n",
      " 'strict need to know the contents of the Confidential Information, and '\n",
      " 'employees, officials, representatives and agents of any legal entity that it '\n",
      " 'controls, controls it, or with which it is under common control, who have a '\n",
      " 'similar need to know the contents of the Confidential Information, provided '\n",
      " 'that, for these purposes a controlled legal entity means:\",\\\\n\\\\nanswer the '\n",
      " 'following question: What is the third requirement for the Recipient to '\n",
      " \"disclose the Confidential Information?', '5. All Confidential Information in \"\n",
      " 'any form and any medium, including all copies thereof, disclosed to the '\n",
      " 'Recipient shall be returned to UNHCR or destroyed:  (a) if a business '\n",
      " 'relationship is not entered into with UNHCR on or before the date which is '\n",
      " 'three (3) months after the date both Parties have signed the Agreement; '\n",
      " 'or\\\\n\\\\nQ: What is the maximum time allowed for a business relationship to '\n",
      " 'be entered into?\\\\n\\\\nA:\\', \\'Question: \"What is the name of the person that '\n",
      " 'is receiving information?\"\\\\n\\\\nContext: \"4. Nothing in this Agreement is to '\n",
      " 'be construed as granting the Recipient, by implication or otherwise, any '\n",
      " 'right whatsoever with respect to the Confidential Information or part '\n",
      " 'thereof.\"\\\\n\\\\nAnswer:\\', \\'Refer to the passage below and answer the '\n",
      " 'following question:\\\\n\\\\nPassage: 11. The Recipient shall not advertise or '\n",
      " 'otherwise make public the fact that it has a confidential relationship with '\n",
      " 'UNHCR, nor shall the Recipient, in any manner whatsoever use the name, '\n",
      " 'emblem, or official seal of the United Nations or UNHCR, or any abbreviation '\n",
      " 'of the name of the United Nations or UNHCR in connection with its business '\n",
      " 'or otherwise.\\\\n\\\\nQuestion: What is the Recipient prohibited from doing '\n",
      " \"with the name, emblem, or official seal of the United Nations?', '1. \"\n",
      " '“Confidential Information”, whenever used in this Agreement, shall mean any '\n",
      " 'data, document, specification and other information or material, that is '\n",
      " 'delivered or disclosed by UNHCR to the Recipient in any form whatsoever, '\n",
      " 'whether orally, visually in writing or otherwise (including computerized '\n",
      " 'form), and that, at the time of disclosure to the Recipient, is designated '\n",
      " 'as confidential.\\\\n\\\\nQ: What is the term for information that is delivered '\n",
      " \"or disclosed by UNHCR to the Recipient?\\\\n\\\\nA:', '1. “Confidential \"\n",
      " 'Information”, whenever used in this Agreement, shall mean any data, '\n",
      " 'document, specification and other information or material, that is delivered '\n",
      " 'or disclosed by UNHCR to the Recipient in any form whatsoever, whether '\n",
      " 'orally, visually in writing or otherwise (including computerized form), and '\n",
      " 'that, at the time of disclosure to the Recipient, is designated as '\n",
      " 'confidential.\\\\n\\\\nQ: What is the term for information that is given to the '\n",
      " 'Recipient?\\\\n\\\\nReferring to the passage above, the correct answer to the '\n",
      " \"question is', 'Either Party may terminate the working relationship \"\n",
      " 'contemplated by this Agreement by providing written notice to the other, '\n",
      " 'provided, however, that the obligations and restrictions hereunder regarding '\n",
      " 'the Confidential Information shall remain effective following any such '\n",
      " 'termination or any other termination or expiration of this '\n",
      " 'Agreement.\\\\n\\\\nWith reference to the above context, What is the only way '\n",
      " \"the working relationship can be terminated?', 'The Recipient shall not be \"\n",
      " 'precluded from disclosing the Confidential Information that is  (i) obtained '\n",
      " 'by the Recipient without restriction from a third party who is not in breach '\n",
      " 'of any obligation as to confidentiality to the owner of such Confidential '\n",
      " 'Information or any other person, or  (ii) disclosed by the Discloser to a '\n",
      " 'third party without any obligation of confidentiality, or  (iii) previously '\n",
      " 'known by the Recipient, or  (iv) at any time is developed by the Recipient '\n",
      " 'completely independently of any disclosures hereunder.\\\\n\\\\nQ: Who can the '\n",
      " 'Recipient disclose confidential information to without breaching the '\n",
      " \"agreement?\\\\n\\\\nA:', 'The Recipient shall not be precluded from disclosing \"\n",
      " 'the Confidential Information that is  (i) obtained by the Recipient without '\n",
      " 'restriction from a third party who is not in breach of any obligation as to '\n",
      " 'confidentiality to the owner of such Confidential Information or any other '\n",
      " 'person, or\\\\n\\\\nQ: What is a third party not in breach of any obligation as '\n",
      " 'to confidentiality to the owner of such Confidential Information or any '\n",
      " 'other person?\\\\n\\\\nReferring to the passage above, the correct answer to the '\n",
      " \"question is', '1. “Confidential Information”, whenever used in this \"\n",
      " 'Agreement, shall mean any data, document, specification and other '\n",
      " 'information or material, that is delivered or disclosed by UNHCR to the '\n",
      " 'Recipient in any form whatsoever, whether orally, visually in writing or '\n",
      " 'otherwise (including computerized form), and that, at the time of disclosure '\n",
      " 'to the Recipient, is designated as confidential.\\\\n\\\\nWith reference to the '\n",
      " \"above context, What is Confidential Information?']\")\n",
      "(\"Output: ['a strict need to know', 'three (3) months', 'Recipient', 'use', \"\n",
      " \"'Confidential Information', 'Confidential Information', 'written notice to \"\n",
      " \"the other', 'a third party who is not in breach of any obligation as to \"\n",
      " \"confidentiality', 'obtained by the Recipient without restriction', 'any \"\n",
      " 'data, document, specification and other information or material, that is '\n",
      " \"delivered or disclosed by UNHCR to the Recipient']\")\n"
     ]
    }
   ],
   "source": [
    "from vllm import SamplingParams\n",
    "from transformers import set_seed\n",
    "from pprint import pprint\n",
    "set_seed(2)\n",
    "\n",
    "# Generate synthetic instruction tuning dataset\n",
    "sampling_params = SamplingParams(max_tokens=256, top_p=0.95, temperature=0.5, n=1)\n",
    "\n",
    "synthetic_dataset = vbonito.generate_tasks(\n",
    "    unannotated_text_ds,\n",
    "    context_col=\"input\",\n",
    "    task_type=\"exqa\",\n",
    "    sampling_params=sampling_params\n",
    ")\n",
    "\n",
    "pprint(\"----Generated Instructions----\")\n",
    "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
    "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3b45cc5-e863-413e-939f-ac00b2c2565a",
   "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.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}