mychen76 commited on
Commit
611d08c
1 Parent(s): 2f917c2

Upload AWQ_Inference-Bonito.ipynb

Browse files
Files changed (1) hide show
  1. AWQ_Inference-Bonito.ipynb +1089 -0
AWQ_Inference-Bonito.ipynb ADDED
@@ -0,0 +1,1089 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "873f35d6-df57-48e0-a60a-45d3c9e15c96",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Bonito: Synthetic Data Generation"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "c283bd6d-ea2f-4a6f-99ac-8887e7621bcb",
14
+ "metadata": {
15
+ "execution": {
16
+ "iopub.execute_input": "2024-09-17T08:32:57.354413Z",
17
+ "iopub.status.busy": "2024-09-17T08:32:57.354090Z",
18
+ "iopub.status.idle": "2024-09-17T08:32:57.357571Z",
19
+ "shell.execute_reply": "2024-09-17T08:32:57.356909Z",
20
+ "shell.execute_reply.started": "2024-09-17T08:32:57.354388Z"
21
+ }
22
+ },
23
+ "source": [
24
+ "#### Environment Setup"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "raw",
29
+ "id": "df65c34e-9080-4e11-9b21-12fa6f459736",
30
+ "metadata": {},
31
+ "source": [
32
+ "pip freeze >> requirements_bonito.txt"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "raw",
37
+ "id": "3502e6ea-1ce9-497a-8bfa-dfc6ff215d07",
38
+ "metadata": {
39
+ "execution": {
40
+ "iopub.execute_input": "2024-09-17T08:26:59.911435Z",
41
+ "iopub.status.busy": "2024-09-17T08:26:59.911244Z",
42
+ "iopub.status.idle": "2024-09-17T08:26:59.913754Z",
43
+ "shell.execute_reply": "2024-09-17T08:26:59.913427Z",
44
+ "shell.execute_reply.started": "2024-09-17T08:26:59.911420Z"
45
+ }
46
+ },
47
+ "source": [
48
+ "conda create -n bonito python=3.9\n",
49
+ "conda activate bonito\n",
50
+ "pip install -e ."
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "raw",
55
+ "id": "0940de6a-0e05-41f0-9d72-2f206bf77ff0",
56
+ "metadata": {},
57
+ "source": [
58
+ "pip install autoawq\n",
59
+ "pip install flash-attn==2.5.6 --no-build-isolation"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": 18,
65
+ "id": "b33c2d03-9cb9-4f31-bcae-d81941486e25",
66
+ "metadata": {
67
+ "execution": {
68
+ "iopub.execute_input": "2024-09-17T08:33:56.866768Z",
69
+ "iopub.status.busy": "2024-09-17T08:33:56.866424Z",
70
+ "iopub.status.idle": "2024-09-17T08:33:56.872656Z",
71
+ "shell.execute_reply": "2024-09-17T08:33:56.872137Z",
72
+ "shell.execute_reply.started": "2024-09-17T08:33:56.866742Z"
73
+ }
74
+ },
75
+ "outputs": [
76
+ {
77
+ "data": {
78
+ "text/plain": [
79
+ "('2.4.0+cu121', '4.44.2', '0.6.1.post2', '0.2.6')"
80
+ ]
81
+ },
82
+ "execution_count": 18,
83
+ "metadata": {},
84
+ "output_type": "execute_result"
85
+ }
86
+ ],
87
+ "source": [
88
+ "import transformers\n",
89
+ "import torch\n",
90
+ "import vllm\n",
91
+ "import awq\n",
92
+ "\n",
93
+ "torch.__version__, transformers.__version__, vllm.__version__, awq.__version__"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "markdown",
98
+ "id": "987a88f2-2240-47ab-b0b7-d1589a6da59e",
99
+ "metadata": {},
100
+ "source": [
101
+ "#### Quantized Bonito Wrapper\n",
102
+ "This is a simplified quantized bonito class to generate a single synthetic input-output instruction for a given text and task type.\n",
103
+ "This code uses huggingface `transformers` library for generation.\n",
104
+ "For complete functionality and faster generations, we recommend using the `Bonito` class from the package."
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "execution_count": 13,
110
+ "id": "20855b3e-e864-4875-9135-bf1242a99242",
111
+ "metadata": {
112
+ "execution": {
113
+ "iopub.execute_input": "2024-09-17T08:26:25.162113Z",
114
+ "iopub.status.busy": "2024-09-17T08:26:25.161926Z",
115
+ "iopub.status.idle": "2024-09-17T08:26:25.167686Z",
116
+ "shell.execute_reply": "2024-09-17T08:26:25.166893Z",
117
+ "shell.execute_reply.started": "2024-09-17T08:26:25.162099Z"
118
+ }
119
+ },
120
+ "outputs": [],
121
+ "source": [
122
+ "from typing import Dict, Optional, Union\n",
123
+ "from datasets import Dataset\n",
124
+ "\n",
125
+ "SHORTFORM_TO_FULL_TASK_TYPES = {\n",
126
+ " \"exqa\": \"extractive question answering\",\n",
127
+ " \"mcqa\": \"multiple-choice question answering\",\n",
128
+ " \"qg\": \"question generation\",\n",
129
+ " \"qa\": \"question answering without choices\",\n",
130
+ " \"ynqa\": \"yes-no question answering\",\n",
131
+ " \"coref\": \"coreference resolution\",\n",
132
+ " \"paraphrase\": \"paraphrase generation\",\n",
133
+ " \"paraphrase_id\": \"paraphrase identification\",\n",
134
+ " \"sent_comp\": \"sentence completion\",\n",
135
+ " \"sentiment\": \"sentiment\",\n",
136
+ " \"summarization\": \"summarization\",\n",
137
+ " \"text_gen\": \"text generation\",\n",
138
+ " \"topic_class\": \"topic classification\",\n",
139
+ " \"wsd\": \"word sense disambiguation\",\n",
140
+ " \"te\": \"textual entailment\",\n",
141
+ " \"nli\": \"natural language inference\",\n",
142
+ "}\n",
143
+ "\n",
144
+ "class AbstractBonito:\n",
145
+ " def _prepare_bonito_input(\n",
146
+ " self, context_dataset: Dataset, task_type: str, context_col: str, **kwargs\n",
147
+ " ) -> Dataset:\n",
148
+ " \"\"\"\n",
149
+ " Prepares the input for the Bonito model.\n",
150
+ "\n",
151
+ " This method takes a context dataset, a task type, and a context\n",
152
+ " column name, and prepares the dataset for the Bonito model.\n",
153
+ " If the task type is not recognized, it raises a ValueError.\n",
154
+ "\n",
155
+ " Args:\n",
156
+ " context_dataset (Dataset): The dataset that provides the\n",
157
+ " context for the task.\n",
158
+ " task_type (str): The type of the task. This can be a\n",
159
+ " short form or a full form. If the task type is not\n",
160
+ " recognized, a ValueError is raised.\n",
161
+ " context_col (str): The name of the column in the dataset\n",
162
+ " that provides the context for the task.\n",
163
+ " **kwargs: Additional keyword arguments.\n",
164
+ "\n",
165
+ " Returns:\n",
166
+ " Dataset: The prepared dataset for the Bonito model.\n",
167
+ " \"\"\"\n",
168
+ " # get the task type name\n",
169
+ " if task_type in SHORTFORM_TO_FULL_TASK_TYPES.values():\n",
170
+ " full_task_type = task_type\n",
171
+ " elif task_type in SHORTFORM_TO_FULL_TASK_TYPES:\n",
172
+ " full_task_type = SHORTFORM_TO_FULL_TASK_TYPES[task_type]\n",
173
+ " else:\n",
174
+ " raise ValueError(f\"Task type {task_type} not recognized\")\n",
175
+ "\n",
176
+ " def process(example):\n",
177
+ " input_text = \"<|tasktype|>\\n\" + full_task_type.strip()\n",
178
+ " input_text += (\n",
179
+ " \"\\n<|context|>\\n\" + example[context_col].strip() + \"\\n<|task|>\\n\"\n",
180
+ " )\n",
181
+ " return {\n",
182
+ " \"input\": input_text,\n",
183
+ " }\n",
184
+ "\n",
185
+ " return context_dataset.map(\n",
186
+ " process,\n",
187
+ " remove_columns=context_dataset.column_names,\n",
188
+ " num_proc=kwargs.get(\"num_proc\", 1),\n",
189
+ " )\n",
190
+ "\n",
191
+ " def _postprocess_dataset(\n",
192
+ " self, synthetic_dataset: Dataset, context_col: str, **kwargs\n",
193
+ " ) -> Dataset:\n",
194
+ " \"\"\"\n",
195
+ " Post-processes the synthetic dataset.\n",
196
+ "\n",
197
+ " This method takes a synthetic dataset and a context column\n",
198
+ " name, and post-processes the dataset. It filters out\n",
199
+ " examples where the prediction does not contain exactly two\n",
200
+ " parts separated by \"<|pipe|>\", and then maps each example to a\n",
201
+ " new format where the context is inserted into the first part of\n",
202
+ " the prediction and the second part of the prediction is used as\n",
203
+ " the output.\n",
204
+ "\n",
205
+ " Args:\n",
206
+ " synthetic_dataset (Dataset): The synthetic dataset to be\n",
207
+ " post-processed.\n",
208
+ " context_col (str): The name of the column in the dataset\n",
209
+ " that provides the context for the tasks.\n",
210
+ " **kwargs: Additional keyword arguments.\n",
211
+ "\n",
212
+ " Returns:\n",
213
+ " Dataset: The post-processed synthetic dataset.\n",
214
+ " \"\"\"\n",
215
+ " synthetic_dataset = synthetic_dataset.filter(\n",
216
+ " lambda example: len(example[\"prediction\"].split(\"<|pipe|>\")) == 2\n",
217
+ " )\n",
218
+ "\n",
219
+ " def process(example):\n",
220
+ " pair = example[\"prediction\"].split(\"<|pipe|>\")\n",
221
+ " context = example[context_col].strip()\n",
222
+ " return {\n",
223
+ " \"input\": pair[0].strip().replace(\"{{context}}\", context),\n",
224
+ " \"output\": pair[1].strip(),\n",
225
+ " }\n",
226
+ "\n",
227
+ " synthetic_dataset = synthetic_dataset.map(\n",
228
+ " process,\n",
229
+ " remove_columns=synthetic_dataset.column_names,\n",
230
+ " num_proc=kwargs.get(\"num_proc\", 1),\n",
231
+ " )\n",
232
+ "\n",
233
+ " return synthetic_dataset\n"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "execution_count": 4,
239
+ "id": "ea7d9840-162e-4c1e-b25d-354b1e110bdc",
240
+ "metadata": {
241
+ "execution": {
242
+ "iopub.execute_input": "2024-09-17T08:19:16.539490Z",
243
+ "iopub.status.busy": "2024-09-17T08:19:16.539225Z",
244
+ "iopub.status.idle": "2024-09-17T08:19:16.807696Z",
245
+ "shell.execute_reply": "2024-09-17T08:19:16.807297Z",
246
+ "shell.execute_reply.started": "2024-09-17T08:19:16.539469Z"
247
+ }
248
+ },
249
+ "outputs": [],
250
+ "source": [
251
+ "from typing import Optional, List, Dict\n",
252
+ "from datasets import Dataset\n",
253
+ "from awq import AutoAWQForCausalLM\n",
254
+ "from transformers import AutoTokenizer\n",
255
+ "\n",
256
+ "class AWQBonito(AbstractBonito):\n",
257
+ " def __init__(self, model_name_or_path):\n",
258
+ " self.model = AutoAWQForCausalLM.from_quantized(model_name_or_path, fuse_layers=True, torch_dtype=torch.float16)\n",
259
+ " self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True) \n",
260
+ " \n",
261
+ " def generate_task(\n",
262
+ " self,\n",
263
+ " unannotated_paragraph: str,\n",
264
+ " task_type: str,\n",
265
+ " sampling_params: dict,\n",
266
+ " context_col=\"input\"\n",
267
+ " ) -> Dict:\n",
268
+ " \"\"\"\n",
269
+ " Generates synthetic instruction tuning pair using the Quantized Bonito model.\n",
270
+ " This method takes a text unannotated text, a task type, and sampling parameters,\n",
271
+ " and generates synthetic input-output pair.\n",
272
+ "\n",
273
+ " Args:\n",
274
+ " unannotated_paragraph (str): The unannotated text or a paragraph\n",
275
+ " task_type (str): The type of the tasks. This can be a\n",
276
+ " short form or a full form.\n",
277
+ " sampling_params (dict): The parameters for\n",
278
+ " sampling.\n",
279
+ " **kwargs: Additional keyword arguments.\n",
280
+ "\n",
281
+ " Returns:\n",
282
+ " Dict: The synthetic input-output pair for the task type.\n",
283
+ " \"\"\"\n",
284
+ "\n",
285
+ " text_dataset = Dataset.from_list([{context_col: unannotated_paragraph}])\n",
286
+ "\n",
287
+ " processed_dataset = self._prepare_bonito_input(\n",
288
+ " text_dataset, task_type, context_col=context_col\n",
289
+ " )\n",
290
+ "\n",
291
+ " outputs = self._generate_text(processed_dataset[\"input\"], sampling_params)\n",
292
+ " examples = []\n",
293
+ " for i, example in enumerate(text_dataset.to_list()):\n",
294
+ " output = outputs[i]\n",
295
+ " example[\"prediction\"] = output.strip()\n",
296
+ " examples.append(example)\n",
297
+ "\n",
298
+ " synthetic_dataset = Dataset.from_list(examples)\n",
299
+ "\n",
300
+ " # filter out the examples that cannot be parsed\n",
301
+ " synthetic_dataset_dict = self._postprocess_dataset(\n",
302
+ " synthetic_dataset, context_col=context_col\n",
303
+ " ).to_list()[0]\n",
304
+ "\n",
305
+ " return synthetic_dataset_dict\n",
306
+ "\n",
307
+ " def _generate_text(\n",
308
+ " self,\n",
309
+ " dataset: Dataset,\n",
310
+ " sampling_params: dict,\n",
311
+ " ) -> List[str]:\n",
312
+ " \"\"\"\n",
313
+ " Generate text using huggingface transformers generate function.\n",
314
+ "\n",
315
+ " This method takes a dataset of prompts, encodes them,\n",
316
+ " generates text using the model, decodes the generated\n",
317
+ " text, and appends it to a list.\n",
318
+ "\n",
319
+ " Args:\n",
320
+ " dataset (Dataset): A dataset containing prompts for text generation.\n",
321
+ " sampling_params (dict): Parameters for sampling during generation.\n",
322
+ "\n",
323
+ " Returns:\n",
324
+ " List[str]: A list of generated texts corresponding to the prompts.\n",
325
+ " \"\"\"\n",
326
+ " generated_texts = []\n",
327
+ "\n",
328
+ " for prompt in dataset:\n",
329
+ " input_ids = self.tokenizer.encode(prompt, return_tensors=\"pt\")\n",
330
+ " input_ids = input_ids.cuda()\n",
331
+ "\n",
332
+ " output = self.model.generate(input_ids, do_sample=True, **sampling_params)\n",
333
+ "\n",
334
+ " generated_text = self.tokenizer.decode(\n",
335
+ " output[0][len(input_ids[0]) :], skip_special_tokens=True\n",
336
+ " )\n",
337
+ " generated_texts.append(generated_text)\n",
338
+ "\n",
339
+ " return generated_texts"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "execution_count": 5,
345
+ "id": "7f773af6-b700-4368-aaed-6bda08560e16",
346
+ "metadata": {
347
+ "execution": {
348
+ "iopub.execute_input": "2024-09-17T08:19:17.123688Z",
349
+ "iopub.status.busy": "2024-09-17T08:19:17.123507Z",
350
+ "iopub.status.idle": "2024-09-17T08:19:17.127238Z",
351
+ "shell.execute_reply": "2024-09-17T08:19:17.126899Z",
352
+ "shell.execute_reply.started": "2024-09-17T08:19:17.123674Z"
353
+ }
354
+ },
355
+ "outputs": [],
356
+ "source": [
357
+ "from datasets import Dataset\n",
358
+ "from vllm import LLM, SamplingParams\n",
359
+ "\n",
360
+ "class VLLMBonito(LLM, AbstractBonito):\n",
361
+ " \n",
362
+ " def generate_tasks(\n",
363
+ " self,\n",
364
+ " text_dataset: Dataset,\n",
365
+ " context_col: str,\n",
366
+ " task_type: str,\n",
367
+ " sampling_params: SamplingParams,\n",
368
+ " **kwargs,\n",
369
+ " ):\n",
370
+ " \"\"\"\n",
371
+ " Generates tasks using the Bonito model.\n",
372
+ "\n",
373
+ " This method takes a text dataset, a context column name,\n",
374
+ " a task type, and sampling parameters, and generates tasks\n",
375
+ " using the Bonito model. It processes the input dataset,\n",
376
+ " generates outputs, collects multiple generations into\n",
377
+ " one dataset object, and filters out the examples that\n",
378
+ " cannot be parsed.\n",
379
+ "\n",
380
+ " Args:\n",
381
+ " text_dataset (Dataset): The dataset that provides the text\n",
382
+ " for the tasks.\n",
383
+ " context_col (str): The name of the column in the dataset\n",
384
+ " that provides the context for the tasks.\n",
385
+ " task_type (str): The type of the tasks. This can be a\n",
386
+ " short form or a full form.\n",
387
+ " sampling_params (SamplingParams): The parameters for\n",
388
+ " sampling.\n",
389
+ " **kwargs: Additional keyword arguments.\n",
390
+ "\n",
391
+ " Returns:\n",
392
+ " Dataset: The synthetic dataset with the generated tasks.\n",
393
+ " \"\"\"\n",
394
+ " processed_dataset = self._prepare_bonito_input(\n",
395
+ " text_dataset, task_type, context_col, **kwargs\n",
396
+ " )\n",
397
+ " outputs = self.generate(processed_dataset[\"input\"], sampling_params)\n",
398
+ "\n",
399
+ " # collect multiple generations into one dataset object\n",
400
+ " examples = []\n",
401
+ " for i, example in enumerate(text_dataset.to_list()):\n",
402
+ " for output in outputs[i].outputs:\n",
403
+ " examples.append(\n",
404
+ " {\"context\": example[context_col], \"prediction\": output.text.strip()}\n",
405
+ " )\n",
406
+ "\n",
407
+ " synthetic_dataset = Dataset.from_list(examples)\n",
408
+ "\n",
409
+ " # filter out the examples that cannot be parsed\n",
410
+ " synthetic_dataset = self._postprocess_dataset(\n",
411
+ " synthetic_dataset, context_col=\"context\", **kwargs\n",
412
+ " )\n",
413
+ "\n",
414
+ " return synthetic_dataset"
415
+ ]
416
+ },
417
+ {
418
+ "cell_type": "markdown",
419
+ "id": "5d666ab6-7722-4afd-9bde-dad5039f442e",
420
+ "metadata": {
421
+ "execution": {
422
+ "iopub.execute_input": "2024-09-17T07:41:42.559750Z",
423
+ "iopub.status.busy": "2024-09-17T07:41:42.559531Z",
424
+ "iopub.status.idle": "2024-09-17T07:41:42.563349Z",
425
+ "shell.execute_reply": "2024-09-17T07:41:42.562597Z",
426
+ "shell.execute_reply.started": "2024-09-17T07:41:42.559738Z"
427
+ }
428
+ },
429
+ "source": [
430
+ "## Synthetic Data Generation\n",
431
+ "Here we will load the quantized bonito model and generate synthetic instruction for the unannotated text.\n",
432
+ "\n",
433
+ "```\n",
434
+ "SHORTFORM_TO_FULL_TASK_TYPES = {\n",
435
+ " \"exqa\": \"extractive question answering\",\n",
436
+ " \"mcqa\": \"multiple-choice question answering\",\n",
437
+ " \"qg\": \"question generation\",\n",
438
+ " \"qa\": \"question answering without choices\",\n",
439
+ " \"ynqa\": \"yes-no question answering\",\n",
440
+ " \"coref\": \"coreference resolution\",\n",
441
+ " \"paraphrase\": \"paraphrase generation\",\n",
442
+ " \"paraphrase_id\": \"paraphrase identification\",\n",
443
+ " \"sent_comp\": \"sentence completion\",\n",
444
+ " \"sentiment\": \"sentiment\",\n",
445
+ " \"summarization\": \"summarization\",\n",
446
+ " \"text_gen\": \"text generation\",\n",
447
+ " \"topic_class\": \"topic classification\",\n",
448
+ " \"wsd\": \"word sense disambiguation\",\n",
449
+ " \"te\": \"textual entailment\",\n",
450
+ " \"nli\": \"natural language inference\",\n",
451
+ "}\n",
452
+ "```"
453
+ ]
454
+ },
455
+ {
456
+ "cell_type": "markdown",
457
+ "id": "a577b15a-fd75-48bb-8faf-bb97a424db48",
458
+ "metadata": {},
459
+ "source": [
460
+ "### Generate the synthetic instructions\n",
461
+ "After loading the model, we pass the unannotated paragraph and the task type to generate the instructions.\n",
462
+ "Here we generate an NLI task:"
463
+ ]
464
+ },
465
+ {
466
+ "cell_type": "code",
467
+ "execution_count": 11,
468
+ "id": "3704550e-e109-404c-8d0e-127bcebf28e6",
469
+ "metadata": {
470
+ "execution": {
471
+ "iopub.execute_input": "2024-09-17T08:22:59.468174Z",
472
+ "iopub.status.busy": "2024-09-17T08:22:59.467863Z",
473
+ "iopub.status.idle": "2024-09-17T08:22:59.472978Z",
474
+ "shell.execute_reply": "2024-09-17T08:22:59.472332Z",
475
+ "shell.execute_reply.started": "2024-09-17T08:22:59.468149Z"
476
+ }
477
+ },
478
+ "outputs": [
479
+ {
480
+ "data": {
481
+ "text/plain": [
482
+ "'\\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'"
483
+ ]
484
+ },
485
+ "execution_count": 11,
486
+ "metadata": {},
487
+ "output_type": "execute_result"
488
+ }
489
+ ],
490
+ "source": [
491
+ "## sample text\n",
492
+ "unannotated_paragraph = \"\"\"\n",
493
+ "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",
494
+ "\"\"\"\n",
495
+ "unannotated_paragraph"
496
+ ]
497
+ },
498
+ {
499
+ "cell_type": "markdown",
500
+ "id": "aa1e941d-317d-415d-b2fb-5177394f68f9",
501
+ "metadata": {
502
+ "execution": {
503
+ "iopub.execute_input": "2024-09-17T08:31:33.945680Z",
504
+ "iopub.status.busy": "2024-09-17T08:31:33.945338Z",
505
+ "iopub.status.idle": "2024-09-17T08:31:33.949066Z",
506
+ "shell.execute_reply": "2024-09-17T08:31:33.948384Z",
507
+ "shell.execute_reply.started": "2024-09-17T08:31:33.945653Z"
508
+ }
509
+ },
510
+ "source": [
511
+ "### Quantized Bonito : AWQ Inference"
512
+ ]
513
+ },
514
+ {
515
+ "cell_type": "code",
516
+ "execution_count": null,
517
+ "id": "012d7f03-3629-45a0-be38-64b90dc6ce0a",
518
+ "metadata": {},
519
+ "outputs": [],
520
+ "source": [
521
+ "import torch\n",
522
+ "\n",
523
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
524
+ "model_id = 'mychen76/Llama-3.1-8B-bonito-v1-awq'\n",
525
+ "bonito = AWQBonito(model_id)"
526
+ ]
527
+ },
528
+ {
529
+ "cell_type": "markdown",
530
+ "id": "4c70d39e-f790-47c3-9b2c-ed5212cc6416",
531
+ "metadata": {
532
+ "execution": {
533
+ "iopub.execute_input": "2024-09-17T08:17:55.265931Z",
534
+ "iopub.status.busy": "2024-09-17T08:17:55.265618Z",
535
+ "iopub.status.idle": "2024-09-17T08:17:55.269425Z",
536
+ "shell.execute_reply": "2024-09-17T08:17:55.268769Z",
537
+ "shell.execute_reply.started": "2024-09-17T08:17:55.265905Z"
538
+ }
539
+ },
540
+ "source": [
541
+ "### generate nli"
542
+ ]
543
+ },
544
+ {
545
+ "cell_type": "code",
546
+ "execution_count": null,
547
+ "id": "ede84178-63b1-4df0-a1c5-1dfefa0a986e",
548
+ "metadata": {},
549
+ "outputs": [],
550
+ "source": [
551
+ "from transformers import set_seed\n",
552
+ "from pprint import pprint\n",
553
+ "set_seed(2)\n",
554
+ "\n",
555
+ "# Generate synthetic instruction tuning dataset\n",
556
+ "sampling_params = {\n",
557
+ " \"max_new_tokens\": 256,\n",
558
+ " \"top_p\": 0.95,\n",
559
+ " \"temperature\": 0.7,\n",
560
+ " \"num_return_sequences\": 1,\n",
561
+ "}\n",
562
+ "synthetic_dataset = bonito.generate_task(\n",
563
+ " unannotated_paragraph, task_type=\"nli\", sampling_params=sampling_params\n",
564
+ ")\n",
565
+ "pprint(\"----Generated Instructions----\")\n",
566
+ "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
567
+ "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
568
+ ]
569
+ },
570
+ {
571
+ "cell_type": "markdown",
572
+ "id": "a7fcf6e8-f6cb-4ac8-b37b-f193ffd6f924",
573
+ "metadata": {
574
+ "execution": {
575
+ "iopub.execute_input": "2024-09-17T08:18:08.288818Z",
576
+ "iopub.status.busy": "2024-09-17T08:18:08.288500Z",
577
+ "iopub.status.idle": "2024-09-17T08:18:08.292090Z",
578
+ "shell.execute_reply": "2024-09-17T08:18:08.291481Z",
579
+ "shell.execute_reply.started": "2024-09-17T08:18:08.288792Z"
580
+ }
581
+ },
582
+ "source": [
583
+ "### generate qa"
584
+ ]
585
+ },
586
+ {
587
+ "cell_type": "code",
588
+ "execution_count": null,
589
+ "id": "ef1d3ba1-5a2f-4a7b-adce-5b030df2fb73",
590
+ "metadata": {},
591
+ "outputs": [],
592
+ "source": [
593
+ "from transformers import set_seed\n",
594
+ "from pprint import pprint\n",
595
+ "set_seed(2)\n",
596
+ "\n",
597
+ "# Generate synthetic instruction tuning dataset\n",
598
+ "sampling_params = {\n",
599
+ " \"max_new_tokens\": 256,\n",
600
+ " \"top_p\": 0.95,\n",
601
+ " \"temperature\": 0.7,\n",
602
+ " \"num_return_sequences\": 1,\n",
603
+ "}\n",
604
+ "synthetic_dataset = bonito.generate_task(\n",
605
+ " unannotated_paragraph, task_type=\"qa\", sampling_params=sampling_params\n",
606
+ ")\n",
607
+ "pprint(\"----Generated Instructions----\")\n",
608
+ "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
609
+ "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
610
+ ]
611
+ },
612
+ {
613
+ "cell_type": "markdown",
614
+ "id": "e9f79b37-d1bc-49bf-8d7d-fc2d088846c0",
615
+ "metadata": {},
616
+ "source": [
617
+ "### vLLM Bonito : AWQ Inference\n",
618
+ "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."
619
+ ]
620
+ },
621
+ {
622
+ "cell_type": "code",
623
+ "execution_count": 1,
624
+ "id": "1a3ffd80-94f0-47bc-b1fe-47444bda66b6",
625
+ "metadata": {
626
+ "execution": {
627
+ "iopub.execute_input": "2024-09-17T08:19:02.242069Z",
628
+ "iopub.status.busy": "2024-09-17T08:19:02.241824Z",
629
+ "iopub.status.idle": "2024-09-17T08:19:04.107622Z",
630
+ "shell.execute_reply": "2024-09-17T08:19:04.107273Z",
631
+ "shell.execute_reply.started": "2024-09-17T08:19:02.242049Z"
632
+ }
633
+ },
634
+ "outputs": [],
635
+ "source": [
636
+ "from datasets import load_dataset\n",
637
+ "\n",
638
+ "# load dataaset with unannotated text\n",
639
+ "unannotated_text_ds = load_dataset(\n",
640
+ " \"BatsResearch/bonito-experiment\",\n",
641
+ " \"unannotated_contract_nli\"\n",
642
+ ")[\"train\"].select(range(10))"
643
+ ]
644
+ },
645
+ {
646
+ "cell_type": "code",
647
+ "execution_count": 6,
648
+ "id": "98f9a917-070d-4c10-9d29-5ecce6c786bb",
649
+ "metadata": {
650
+ "execution": {
651
+ "iopub.execute_input": "2024-09-17T08:19:22.658366Z",
652
+ "iopub.status.busy": "2024-09-17T08:19:22.658098Z",
653
+ "iopub.status.idle": "2024-09-17T08:19:39.785070Z",
654
+ "shell.execute_reply": "2024-09-17T08:19:39.784677Z",
655
+ "shell.execute_reply.started": "2024-09-17T08:19:22.658345Z"
656
+ }
657
+ },
658
+ "outputs": [
659
+ {
660
+ "name": "stdout",
661
+ "output_type": "stream",
662
+ "text": [
663
+ "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",
664
+ "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",
665
+ "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",
666
+ "INFO 09-17 04:19:23 model_runner.py:997] Starting to load model mychen76/Llama-3.1-8B-bonito-v1-awq...\n",
667
+ "INFO 09-17 04:19:23 weight_utils.py:242] Using model weights format ['*.safetensors']\n"
668
+ ]
669
+ },
670
+ {
671
+ "data": {
672
+ "application/vnd.jupyter.widget-view+json": {
673
+ "model_id": "0e53544149e94bacbc0a1c854690f32a",
674
+ "version_major": 2,
675
+ "version_minor": 0
676
+ },
677
+ "text/plain": [
678
+ "Loading safetensors checkpoint shards: 0% Completed | 0/2 [00:00<?, ?it/s]\n"
679
+ ]
680
+ },
681
+ "metadata": {},
682
+ "output_type": "display_data"
683
+ },
684
+ {
685
+ "name": "stdout",
686
+ "output_type": "stream",
687
+ "text": [
688
+ "INFO 09-17 04:19:24 model_runner.py:1008] Loading model weights took 5.3745 GB\n",
689
+ "INFO 09-17 04:19:26 gpu_executor.py:122] # GPU blocks: 6132, # CPU blocks: 2048\n",
690
+ "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",
691
+ "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",
692
+ "INFO 09-17 04:19:39 model_runner.py:1430] Graph capturing finished in 11 secs.\n"
693
+ ]
694
+ }
695
+ ],
696
+ "source": [
697
+ "from vllm import LLM, SamplingParams\n",
698
+ "import torch \n",
699
+ "\n",
700
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
701
+ "model_id = 'mychen76/Llama-3.1-8B-bonito-v1-awq'\n",
702
+ "\n",
703
+ "# Create an LLM.\n",
704
+ "vbonito = VLLMBonito(model=model_id, \n",
705
+ " quantization=\"AWQ\",\n",
706
+ " gpu_memory_utilization=0.80,\n",
707
+ " max_seq_len_to_capture=4096,\n",
708
+ " max_model_len=4096,\n",
709
+ " speculative_max_model_len = 4096)\n"
710
+ ]
711
+ },
712
+ {
713
+ "cell_type": "markdown",
714
+ "id": "e04ccba5-907b-406f-8396-f880d371273d",
715
+ "metadata": {},
716
+ "source": [
717
+ "#### generate \"nli\": \"natural language inference\""
718
+ ]
719
+ },
720
+ {
721
+ "cell_type": "code",
722
+ "execution_count": 8,
723
+ "id": "50b8baac-18c8-41bd-b126-190119087ccc",
724
+ "metadata": {
725
+ "execution": {
726
+ "iopub.execute_input": "2024-09-17T08:20:10.531375Z",
727
+ "iopub.status.busy": "2024-09-17T08:20:10.531202Z",
728
+ "iopub.status.idle": "2024-09-17T08:20:11.851687Z",
729
+ "shell.execute_reply": "2024-09-17T08:20:11.851225Z",
730
+ "shell.execute_reply.started": "2024-09-17T08:20:10.531362Z"
731
+ }
732
+ },
733
+ "outputs": [
734
+ {
735
+ "name": "stderr",
736
+ "output_type": "stream",
737
+ "text": [
738
+ "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"
739
+ ]
740
+ },
741
+ {
742
+ "data": {
743
+ "application/vnd.jupyter.widget-view+json": {
744
+ "model_id": "37f9beb99d0448fba399cd2cb1dad305",
745
+ "version_major": 2,
746
+ "version_minor": 0
747
+ },
748
+ "text/plain": [
749
+ "Filter: 0%| | 0/10 [00:00<?, ? examples/s]"
750
+ ]
751
+ },
752
+ "metadata": {},
753
+ "output_type": "display_data"
754
+ },
755
+ {
756
+ "data": {
757
+ "application/vnd.jupyter.widget-view+json": {
758
+ "model_id": "90458d9887d04da3b2b2bc5d101e6fee",
759
+ "version_major": 2,
760
+ "version_minor": 0
761
+ },
762
+ "text/plain": [
763
+ "Map: 0%| | 0/10 [00:00<?, ? examples/s]"
764
+ ]
765
+ },
766
+ "metadata": {},
767
+ "output_type": "display_data"
768
+ },
769
+ {
770
+ "name": "stdout",
771
+ "output_type": "stream",
772
+ "text": [
773
+ "'----Generated Instructions----'\n",
774
+ "(\"Input: ['Given that 2.3 Provided that the Recipient has a written agreement \"\n",
775
+ " 'with the following persons or entities requiring them to treat the '\n",
776
+ " 'Confidential Information in accordance with this Agreement, the Recipient '\n",
777
+ " 'may disclose the Confidential Information to: 2.3.1 Any other party with '\n",
778
+ " 'the Discloser’s prior written consent; and 2.3.2 the Recipient’s employees, '\n",
779
+ " 'officials, representatives and agents who have a strict need to know the '\n",
780
+ " 'contents of the Confidential Information, and employees, officials, '\n",
781
+ " 'representatives and agents of any legal entity that it controls, controls '\n",
782
+ " 'it, or with which it is under common control, who have a similar need to '\n",
783
+ " 'know the contents of the Confidential Information, provided that, for these '\n",
784
+ " 'purposes a controlled legal entity means: Does it follow that The Recipient '\n",
785
+ " \"is a person Yes, no, or maybe?', '5. All Confidential Information in any \"\n",
786
+ " 'form and any medium, including all copies thereof, disclosed to the '\n",
787
+ " 'Recipient shall be returned to UNHCR or destroyed: (a) if a business '\n",
788
+ " 'relationship is not entered into with UNHCR on or before the date which is '\n",
789
+ " 'three (3) months after the date both Parties have signed the Agreement; or '\n",
790
+ " 'Based on that information, is the claim: \"The UNHCR is not a recipient.\" '\n",
791
+ " \"true, false, or inconclusive?', 'Given 4. Nothing in this Agreement is to be \"\n",
792
+ " 'construed as granting the Recipient, by implication or otherwise, any right '\n",
793
+ " 'whatsoever with respect to the Confidential Information or part thereof. Is '\n",
794
+ " 'it guaranteed true that \"The Recipient is not granted any rights to the '\n",
795
+ " 'Confidential Information.\"? Yes, no, or maybe?\\', \\'11. The Recipient shall '\n",
796
+ " 'not advertise or otherwise make public the fact that it has a confidential '\n",
797
+ " 'relationship with UNHCR, nor shall the Recipient, in any manner whatsoever '\n",
798
+ " 'use the name, emblem, or official seal of the United Nations or UNHCR, or '\n",
799
+ " 'any abbreviation of the name of the United Nations or UNHCR in connection '\n",
800
+ " 'with its business or otherwise. \\\\n\\\\nQuestion: Does this imply that \"The '\n",
801
+ " 'United Nations is a good organization.\"? Yes, no, or maybe?\\', \\'1. '\n",
802
+ " '“Confidential Information”, whenever used in this Agreement, shall mean any '\n",
803
+ " 'data, document, specification and other information or material, that is '\n",
804
+ " 'delivered or disclosed by UNHCR to the Recipient in any form whatsoever, '\n",
805
+ " 'whether orally, visually in writing or otherwise (including computerized '\n",
806
+ " 'form), and that, at the time of disclosure to the Recipient, is designated '\n",
807
+ " 'as confidential.\\\\nQuestion: The UNHCR is a non-governmental organization. '\n",
808
+ " \"True, False, or Neither?', '1. “Confidential Information”, whenever used in \"\n",
809
+ " 'this Agreement, shall mean any data, document, specification and other '\n",
810
+ " 'information or material, that is delivered or disclosed by UNHCR to the '\n",
811
+ " 'Recipient in any form whatsoever, whether orally, visually in writing or '\n",
812
+ " 'otherwise (including computerized form), and that, at the time of disclosure '\n",
813
+ " 'to the Recipient, is designated as confidential. Based on that information, '\n",
814
+ " 'is the claim: \"Confidential Information is only delivered to the Recipient '\n",
815
+ " 'in written form.\" true, false, or inconclusive?\\', \\'Either Party may '\n",
816
+ " 'terminate the working relationship contemplated by this Agreement by '\n",
817
+ " 'providing written notice to the other, provided, however, that the '\n",
818
+ " 'obligations and restrictions hereunder regarding the Confidential '\n",
819
+ " 'Information shall remain effective following any such termination or any '\n",
820
+ " 'other termination or expiration of this Agreement. Using only the above '\n",
821
+ " 'description and the fact that \"The obligations and restrictions hereunder '\n",
822
+ " 'regarding the Confidential Information shall remain effective following any '\n",
823
+ " 'such termination or any other termination or expiration of this Agreement.\" '\n",
824
+ " 'is true, is \"The obligations and restrictions hereunder regarding the '\n",
825
+ " 'Confidential Information shall remain effective following any such '\n",
826
+ " 'termination or any other termination or expiration of this Agreement. It is '\n",
827
+ " 'a very long sentence.\" always, sometimes, or never true?\\', \\'The Recipient '\n",
828
+ " 'shall not be precluded from disclosing the Confidential Information that is '\n",
829
+ " '(i) obtained by the Recipient without restriction from a third party who is '\n",
830
+ " 'not in breach of any obligation as to confidentiality to the owner of such '\n",
831
+ " 'Confidential Information or any other person, or (ii) disclosed by the '\n",
832
+ " 'Discloser to a third party without any obligation of confidentiality, or '\n",
833
+ " '(iii) previously known by the Recipient, or (iv) at any time is developed '\n",
834
+ " 'by the Recipient completely independently of any disclosures hereunder. '\n",
835
+ " '\\\\n\\\\nQuestion: Does this imply that \"Confidential Information has been seen '\n",
836
+ " 'by carl\"? Yes, no, or maybe?\\', \\'Assume it is true that The Recipient shall '\n",
837
+ " 'not be precluded from disclosing the Confidential Information that is (i) '\n",
838
+ " 'obtained by the Recipient without restriction from a third party who is not '\n",
839
+ " 'in breach of any obligation as to confidentiality to the owner of such '\n",
840
+ " 'Confidential Information or any other person, or \\\\n\\\\nTherefore, \"The '\n",
841
+ " 'Recipient shall not be precluded from disclosing the Confidential '\n",
842
+ " 'Information that is obtained by the Recipient without restriction from a '\n",
843
+ " 'third party who is not in breach of any obligation as to confidentiality to '\n",
844
+ " 'the owner of such Confidential Information or any other person, or the owner '\n",
845
+ " 'of such Confidential Information.\" is guaranteed, possible, or '\n",
846
+ " \"impossible?', '1. “Confidential Information”, whenever used in this \"\n",
847
+ " 'Agreement, shall mean any data, document, specification and other '\n",
848
+ " 'information or material, that is delivered or disclosed by UNHCR to the '\n",
849
+ " 'Recipient in any form whatsoever, whether orally, visually in writing or '\n",
850
+ " 'otherwise (including computerized form), and that, at the time of disclosure '\n",
851
+ " 'to the Recipient, is designated as confidential. \\\\n\\\\nKeeping in mind the '\n",
852
+ " 'above text, consider: Confidential Information is not protected by the '\n",
853
+ " \"agreement. Is this always, sometimes, or never correct?']\")\n",
854
+ "(\"Output: ['Maybe', 'False', 'Yes', 'Maybe', 'Neither', 'False', 'Sometimes', \"\n",
855
+ " \"'Maybe', 'Guaranteed', 'Never']\")\n"
856
+ ]
857
+ }
858
+ ],
859
+ "source": [
860
+ "from vllm import SamplingParams\n",
861
+ "from transformers import set_seed\n",
862
+ "from pprint import pprint\n",
863
+ "set_seed(2)\n",
864
+ "\n",
865
+ "# Generate synthetic instruction tuning dataset\n",
866
+ "sampling_params = SamplingParams(max_tokens=256, top_p=0.95, temperature=0.5, n=1)\n",
867
+ "\n",
868
+ "synthetic_dataset = vbonito.generate_tasks(\n",
869
+ " unannotated_text_ds,\n",
870
+ " context_col=\"input\",\n",
871
+ " task_type=\"nli\",\n",
872
+ " sampling_params=sampling_params\n",
873
+ ")\n",
874
+ "\n",
875
+ "pprint(\"----Generated Instructions----\")\n",
876
+ "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
877
+ "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
878
+ ]
879
+ },
880
+ {
881
+ "cell_type": "markdown",
882
+ "id": "ddedcdb4-6d2c-4fa0-8508-3521285d460d",
883
+ "metadata": {},
884
+ "source": [
885
+ "#### \"exqa\": \"extractive question answering\","
886
+ ]
887
+ },
888
+ {
889
+ "cell_type": "code",
890
+ "execution_count": 12,
891
+ "id": "38b09b41-d044-48f4-aabc-16634e8e99c4",
892
+ "metadata": {
893
+ "execution": {
894
+ "iopub.execute_input": "2024-09-17T08:24:37.023979Z",
895
+ "iopub.status.busy": "2024-09-17T08:24:37.023731Z",
896
+ "iopub.status.idle": "2024-09-17T08:24:38.025746Z",
897
+ "shell.execute_reply": "2024-09-17T08:24:38.025384Z",
898
+ "shell.execute_reply.started": "2024-09-17T08:24:37.023955Z"
899
+ }
900
+ },
901
+ "outputs": [
902
+ {
903
+ "data": {
904
+ "application/vnd.jupyter.widget-view+json": {
905
+ "model_id": "5a59db3acc764c03b00c3a683f5c2827",
906
+ "version_major": 2,
907
+ "version_minor": 0
908
+ },
909
+ "text/plain": [
910
+ "Map: 0%| | 0/10 [00:00<?, ? examples/s]"
911
+ ]
912
+ },
913
+ "metadata": {},
914
+ "output_type": "display_data"
915
+ },
916
+ {
917
+ "name": "stderr",
918
+ "output_type": "stream",
919
+ "text": [
920
+ "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"
921
+ ]
922
+ },
923
+ {
924
+ "data": {
925
+ "application/vnd.jupyter.widget-view+json": {
926
+ "model_id": "1b8deb9aa5564b498249d91d6534e912",
927
+ "version_major": 2,
928
+ "version_minor": 0
929
+ },
930
+ "text/plain": [
931
+ "Filter: 0%| | 0/10 [00:00<?, ? examples/s]"
932
+ ]
933
+ },
934
+ "metadata": {},
935
+ "output_type": "display_data"
936
+ },
937
+ {
938
+ "data": {
939
+ "application/vnd.jupyter.widget-view+json": {
940
+ "model_id": "489786c4cc6f4a67bbc2f2df0fe36506",
941
+ "version_major": 2,
942
+ "version_minor": 0
943
+ },
944
+ "text/plain": [
945
+ "Map: 0%| | 0/10 [00:00<?, ? examples/s]"
946
+ ]
947
+ },
948
+ "metadata": {},
949
+ "output_type": "display_data"
950
+ },
951
+ {
952
+ "name": "stdout",
953
+ "output_type": "stream",
954
+ "text": [
955
+ "'----Generated Instructions----'\n",
956
+ "('Input: [\\'Given the following passage\\\\n\\\\n\"2.3 Provided that the Recipient '\n",
957
+ " 'has a written agreement with the following persons or entities requiring '\n",
958
+ " 'them to treat the Confidential Information in accordance with this '\n",
959
+ " 'Agreement, the Recipient may disclose the Confidential Information to: '\n",
960
+ " '2.3.1 Any other party with the Discloser’s prior written consent; and 2.3.2 '\n",
961
+ " 'the Recipient’s employees, officials, representatives and agents who have a '\n",
962
+ " 'strict need to know the contents of the Confidential Information, and '\n",
963
+ " 'employees, officials, representatives and agents of any legal entity that it '\n",
964
+ " 'controls, controls it, or with which it is under common control, who have a '\n",
965
+ " 'similar need to know the contents of the Confidential Information, provided '\n",
966
+ " 'that, for these purposes a controlled legal entity means:\",\\\\n\\\\nanswer the '\n",
967
+ " 'following question: What is the third requirement for the Recipient to '\n",
968
+ " \"disclose the Confidential Information?', '5. All Confidential Information in \"\n",
969
+ " 'any form and any medium, including all copies thereof, disclosed to the '\n",
970
+ " 'Recipient shall be returned to UNHCR or destroyed: (a) if a business '\n",
971
+ " 'relationship is not entered into with UNHCR on or before the date which is '\n",
972
+ " 'three (3) months after the date both Parties have signed the Agreement; '\n",
973
+ " 'or\\\\n\\\\nQ: What is the maximum time allowed for a business relationship to '\n",
974
+ " 'be entered into?\\\\n\\\\nA:\\', \\'Question: \"What is the name of the person that '\n",
975
+ " 'is receiving information?\"\\\\n\\\\nContext: \"4. Nothing in this Agreement is to '\n",
976
+ " 'be construed as granting the Recipient, by implication or otherwise, any '\n",
977
+ " 'right whatsoever with respect to the Confidential Information or part '\n",
978
+ " 'thereof.\"\\\\n\\\\nAnswer:\\', \\'Refer to the passage below and answer the '\n",
979
+ " 'following question:\\\\n\\\\nPassage: 11. The Recipient shall not advertise or '\n",
980
+ " 'otherwise make public the fact that it has a confidential relationship with '\n",
981
+ " 'UNHCR, nor shall the Recipient, in any manner whatsoever use the name, '\n",
982
+ " 'emblem, or official seal of the United Nations or UNHCR, or any abbreviation '\n",
983
+ " 'of the name of the United Nations or UNHCR in connection with its business '\n",
984
+ " 'or otherwise.\\\\n\\\\nQuestion: What is the Recipient prohibited from doing '\n",
985
+ " \"with the name, emblem, or official seal of the United Nations?', '1. \"\n",
986
+ " '“Confidential Information”, whenever used in this Agreement, shall mean any '\n",
987
+ " 'data, document, specification and other information or material, that is '\n",
988
+ " 'delivered or disclosed by UNHCR to the Recipient in any form whatsoever, '\n",
989
+ " 'whether orally, visually in writing or otherwise (including computerized '\n",
990
+ " 'form), and that, at the time of disclosure to the Recipient, is designated '\n",
991
+ " 'as confidential.\\\\n\\\\nQ: What is the term for information that is delivered '\n",
992
+ " \"or disclosed by UNHCR to the Recipient?\\\\n\\\\nA:', '1. “Confidential \"\n",
993
+ " 'Information”, whenever used in this Agreement, shall mean any data, '\n",
994
+ " 'document, specification and other information or material, that is delivered '\n",
995
+ " 'or disclosed by UNHCR to the Recipient in any form whatsoever, whether '\n",
996
+ " 'orally, visually in writing or otherwise (including computerized form), and '\n",
997
+ " 'that, at the time of disclosure to the Recipient, is designated as '\n",
998
+ " 'confidential.\\\\n\\\\nQ: What is the term for information that is given to the '\n",
999
+ " 'Recipient?\\\\n\\\\nReferring to the passage above, the correct answer to the '\n",
1000
+ " \"question is', 'Either Party may terminate the working relationship \"\n",
1001
+ " 'contemplated by this Agreement by providing written notice to the other, '\n",
1002
+ " 'provided, however, that the obligations and restrictions hereunder regarding '\n",
1003
+ " 'the Confidential Information shall remain effective following any such '\n",
1004
+ " 'termination or any other termination or expiration of this '\n",
1005
+ " 'Agreement.\\\\n\\\\nWith reference to the above context, What is the only way '\n",
1006
+ " \"the working relationship can be terminated?', 'The Recipient shall not be \"\n",
1007
+ " 'precluded from disclosing the Confidential Information that is (i) obtained '\n",
1008
+ " 'by the Recipient without restriction from a third party who is not in breach '\n",
1009
+ " 'of any obligation as to confidentiality to the owner of such Confidential '\n",
1010
+ " 'Information or any other person, or (ii) disclosed by the Discloser to a '\n",
1011
+ " 'third party without any obligation of confidentiality, or (iii) previously '\n",
1012
+ " 'known by the Recipient, or (iv) at any time is developed by the Recipient '\n",
1013
+ " 'completely independently of any disclosures hereunder.\\\\n\\\\nQ: Who can the '\n",
1014
+ " 'Recipient disclose confidential information to without breaching the '\n",
1015
+ " \"agreement?\\\\n\\\\nA:', 'The Recipient shall not be precluded from disclosing \"\n",
1016
+ " 'the Confidential Information that is (i) obtained by the Recipient without '\n",
1017
+ " 'restriction from a third party who is not in breach of any obligation as to '\n",
1018
+ " 'confidentiality to the owner of such Confidential Information or any other '\n",
1019
+ " 'person, or\\\\n\\\\nQ: What is a third party not in breach of any obligation as '\n",
1020
+ " 'to confidentiality to the owner of such Confidential Information or any '\n",
1021
+ " 'other person?\\\\n\\\\nReferring to the passage above, the correct answer to the '\n",
1022
+ " \"question is', '1. “Confidential Information”, whenever used in this \"\n",
1023
+ " 'Agreement, shall mean any data, document, specification and other '\n",
1024
+ " 'information or material, that is delivered or disclosed by UNHCR to the '\n",
1025
+ " 'Recipient in any form whatsoever, whether orally, visually in writing or '\n",
1026
+ " 'otherwise (including computerized form), and that, at the time of disclosure '\n",
1027
+ " 'to the Recipient, is designated as confidential.\\\\n\\\\nWith reference to the '\n",
1028
+ " \"above context, What is Confidential Information?']\")\n",
1029
+ "(\"Output: ['a strict need to know', 'three (3) months', 'Recipient', 'use', \"\n",
1030
+ " \"'Confidential Information', 'Confidential Information', 'written notice to \"\n",
1031
+ " \"the other', 'a third party who is not in breach of any obligation as to \"\n",
1032
+ " \"confidentiality', 'obtained by the Recipient without restriction', 'any \"\n",
1033
+ " 'data, document, specification and other information or material, that is '\n",
1034
+ " \"delivered or disclosed by UNHCR to the Recipient']\")\n"
1035
+ ]
1036
+ }
1037
+ ],
1038
+ "source": [
1039
+ "from vllm import SamplingParams\n",
1040
+ "from transformers import set_seed\n",
1041
+ "from pprint import pprint\n",
1042
+ "set_seed(2)\n",
1043
+ "\n",
1044
+ "# Generate synthetic instruction tuning dataset\n",
1045
+ "sampling_params = SamplingParams(max_tokens=256, top_p=0.95, temperature=0.5, n=1)\n",
1046
+ "\n",
1047
+ "synthetic_dataset = vbonito.generate_tasks(\n",
1048
+ " unannotated_text_ds,\n",
1049
+ " context_col=\"input\",\n",
1050
+ " task_type=\"exqa\",\n",
1051
+ " sampling_params=sampling_params\n",
1052
+ ")\n",
1053
+ "\n",
1054
+ "pprint(\"----Generated Instructions----\")\n",
1055
+ "pprint(f'Input: {synthetic_dataset[\"input\"]}')\n",
1056
+ "pprint(f'Output: {synthetic_dataset[\"output\"]}')"
1057
+ ]
1058
+ },
1059
+ {
1060
+ "cell_type": "code",
1061
+ "execution_count": null,
1062
+ "id": "b3b45cc5-e863-413e-939f-ac00b2c2565a",
1063
+ "metadata": {},
1064
+ "outputs": [],
1065
+ "source": []
1066
+ }
1067
+ ],
1068
+ "metadata": {
1069
+ "kernelspec": {
1070
+ "display_name": "Python 3 (ipykernel)",
1071
+ "language": "python",
1072
+ "name": "python3"
1073
+ },
1074
+ "language_info": {
1075
+ "codemirror_mode": {
1076
+ "name": "ipython",
1077
+ "version": 3
1078
+ },
1079
+ "file_extension": ".py",
1080
+ "mimetype": "text/x-python",
1081
+ "name": "python",
1082
+ "nbconvert_exporter": "python",
1083
+ "pygments_lexer": "ipython3",
1084
+ "version": "3.10.12"
1085
+ }
1086
+ },
1087
+ "nbformat": 4,
1088
+ "nbformat_minor": 5
1089
+ }