|
a |
|
b/notebooks/inference_lora.ipynb |
|
|
1 |
{ |
|
|
2 |
"cells": [ |
|
|
3 |
{ |
|
|
4 |
"cell_type": "code", |
|
|
5 |
"execution_count": null, |
|
|
6 |
"id": "8ae13342-5979-42df-9fea-5bb97c60be23", |
|
|
7 |
"metadata": {}, |
|
|
8 |
"outputs": [], |
|
|
9 |
"source": [ |
|
|
10 |
"import json\n", |
|
|
11 |
"import sys\n", |
|
|
12 |
"import time\n", |
|
|
13 |
"from pathlib import Path\n", |
|
|
14 |
"from typing import Literal, Optional\n", |
|
|
15 |
"\n", |
|
|
16 |
"import lightning as L\n", |
|
|
17 |
"import torch\n", |
|
|
18 |
"from lightning.fabric.plugins import BitsandbytesPrecision\n", |
|
|
19 |
"from lightning.fabric.strategies import FSDPStrategy\n", |
|
|
20 |
"\n", |
|
|
21 |
"import os\n", |
|
|
22 |
"## Add the lit_gpt folder to the path\n", |
|
|
23 |
"sys.path.insert(0, os.path.abspath('../'))\n", |
|
|
24 |
"\n", |
|
|
25 |
"from generate.base import generate\n", |
|
|
26 |
"from lit_gpt import Tokenizer\n", |
|
|
27 |
"from lit_gpt.lora import GPT, Block, Config, merge_lora_weights\n", |
|
|
28 |
"from lit_gpt.utils import check_valid_checkpoint_dir, get_default_supported_precision, gptq_quantization, lazy_load\n", |
|
|
29 |
"from scripts.prepare_entity_extraction_data import generate_prompt" |
|
|
30 |
] |
|
|
31 |
}, |
|
|
32 |
{ |
|
|
33 |
"cell_type": "code", |
|
|
34 |
"execution_count": null, |
|
|
35 |
"id": "7ac87e9a-6846-4f84-9c02-27f46fa417ce", |
|
|
36 |
"metadata": { |
|
|
37 |
"tags": [] |
|
|
38 |
}, |
|
|
39 |
"outputs": [], |
|
|
40 |
"source": [ |
|
|
41 |
"lora_r = 8\n", |
|
|
42 |
"lora_alpha = 16\n", |
|
|
43 |
"lora_dropout = 0.05\n", |
|
|
44 |
"lora_query = True\n", |
|
|
45 |
"lora_key = False\n", |
|
|
46 |
"lora_value = True\n", |
|
|
47 |
"lora_projection = False\n", |
|
|
48 |
"lora_mlp = False\n", |
|
|
49 |
"lora_head = False\n", |
|
|
50 |
"\n", |
|
|
51 |
"torch.set_float32_matmul_precision(\"high\")" |
|
|
52 |
] |
|
|
53 |
}, |
|
|
54 |
{ |
|
|
55 |
"cell_type": "code", |
|
|
56 |
"execution_count": null, |
|
|
57 |
"id": "e6eec0b2-81d9-4a88-b20c-0be57ec6b2a2", |
|
|
58 |
"metadata": {}, |
|
|
59 |
"outputs": [], |
|
|
60 |
"source": [ |
|
|
61 |
"with open('..data/entity_extraction/entity-extraction-test-data.json', 'r') as file:\n", |
|
|
62 |
" test_data = json.load(file)" |
|
|
63 |
] |
|
|
64 |
}, |
|
|
65 |
{ |
|
|
66 |
"cell_type": "code", |
|
|
67 |
"execution_count": null, |
|
|
68 |
"id": "4d92ad07", |
|
|
69 |
"metadata": {}, |
|
|
70 |
"outputs": [], |
|
|
71 |
"source": [ |
|
|
72 |
"sample = {\n", |
|
|
73 |
" \"input\": \"Natalie Cooper,\\nncooper@example.com\\n6789 Birch Street, Denver, CO 80203,\\n303-555-6543, United States\\n\\nRelationship to XYZ Pharma Inc.: Patient\\nReason for contacting: Adverse Event\\n\\nMessage: Hi, after starting Abilify for bipolar I disorder, I've noticed that I am experiencing nausea and vomiting. Are these typical reactions? Best, Natalie Cooper\",\n", |
|
|
74 |
" \"output\": \"{\\\"drug_name\\\": \\\"Abilify\\\", \\\"adverse_events\\\": [\\\"nausea\\\", \\\"vomiting\\\"]}\"\n", |
|
|
75 |
" }" |
|
|
76 |
] |
|
|
77 |
}, |
|
|
78 |
{ |
|
|
79 |
"cell_type": "code", |
|
|
80 |
"execution_count": null, |
|
|
81 |
"id": "c7e65d14-07f2-4889-849f-277df3887c76", |
|
|
82 |
"metadata": {}, |
|
|
83 |
"outputs": [], |
|
|
84 |
"source": [ |
|
|
85 |
"## Choose one\n", |
|
|
86 |
"#model_type = 'stablelm'\n", |
|
|
87 |
"model_type = 'llama2'" |
|
|
88 |
] |
|
|
89 |
}, |
|
|
90 |
{ |
|
|
91 |
"cell_type": "code", |
|
|
92 |
"execution_count": null, |
|
|
93 |
"id": "e3c30b09-e631-44b8-a45b-ac79dbbab52f", |
|
|
94 |
"metadata": { |
|
|
95 |
"tags": [] |
|
|
96 |
}, |
|
|
97 |
"outputs": [], |
|
|
98 |
"source": [ |
|
|
99 |
"input: str = sample[\"input\"]\n", |
|
|
100 |
"if model_type == \"stablelm\":\n", |
|
|
101 |
" print(\"[INFO] Using StableLM-3B LoRA Fine-tuned\")\n", |
|
|
102 |
" lora_path: Path = Path(\"../out/lora/Stable-LM/entity_extraction/lit_model_lora_finetuned.pth\")\n", |
|
|
103 |
" checkpoint_dir: Path = Path(\"../checkpoints/stabilityai/stablelm-base-alpha-3b\")\n", |
|
|
104 |
" predictions_file_name = '../data/predictions-stablelm-lora.json'\n", |
|
|
105 |
"\n", |
|
|
106 |
"if model_type == \"llama2\":\n", |
|
|
107 |
" print(\"[INFO] Using LLaMa-2-7B LoRA Fine-tuned\")\n", |
|
|
108 |
" lora_path: Path = Path(\"../out/lora/Llama-2/entity_extraction/lit_model_lora_finetuned.pth\")\n", |
|
|
109 |
" checkpoint_dir: Path = Path(\"../checkpoints/meta-llama/Llama-2-7b-hf\")\n", |
|
|
110 |
" predictions_file_name = '../data/predictions-llama2-lora.json'\n", |
|
|
111 |
"\n", |
|
|
112 |
"quantize: Optional[Literal[\"bnb.nf4\", \"bnb.nf4-dq\", \"bnb.fp4\", \"bnb.fp4-dq\", \"bnb.int8\", \"gptq.int4\"]] = None\n", |
|
|
113 |
"max_new_tokens: int = 100\n", |
|
|
114 |
"top_k: int = 200\n", |
|
|
115 |
"temperature: float = 0.1\n", |
|
|
116 |
"strategy: str = \"auto\"\n", |
|
|
117 |
"devices: int = 1\n", |
|
|
118 |
"precision: Optional[str] = None" |
|
|
119 |
] |
|
|
120 |
}, |
|
|
121 |
{ |
|
|
122 |
"cell_type": "code", |
|
|
123 |
"execution_count": null, |
|
|
124 |
"id": "b842b257-2c9c-4c64-b011-f97e215c3794", |
|
|
125 |
"metadata": {}, |
|
|
126 |
"outputs": [], |
|
|
127 |
"source": [ |
|
|
128 |
"if strategy == \"fsdp\":\n", |
|
|
129 |
" strategy = FSDPStrategy(auto_wrap_policy={Block}, cpu_offload=False)\n", |
|
|
130 |
"fabric = L.Fabric(devices=devices, precision=precision, strategy=strategy)\n", |
|
|
131 |
"fabric.launch()\n", |
|
|
132 |
"\n", |
|
|
133 |
"check_valid_checkpoint_dir(checkpoint_dir)\n", |
|
|
134 |
"\n", |
|
|
135 |
"config = Config.from_json(\n", |
|
|
136 |
" checkpoint_dir / \"lit_config.json\",\n", |
|
|
137 |
" r=lora_r,\n", |
|
|
138 |
" alpha=lora_alpha,\n", |
|
|
139 |
" dropout=lora_dropout,\n", |
|
|
140 |
" to_query=lora_query,\n", |
|
|
141 |
" to_key=lora_key,\n", |
|
|
142 |
" to_value=lora_value,\n", |
|
|
143 |
" to_projection=lora_projection,\n", |
|
|
144 |
" to_mlp=lora_mlp,\n", |
|
|
145 |
" to_head=lora_head,\n", |
|
|
146 |
")\n", |
|
|
147 |
"\n", |
|
|
148 |
"if quantize is not None and devices > 1:\n", |
|
|
149 |
" raise NotImplementedError\n", |
|
|
150 |
"if quantize == \"gptq.int4\":\n", |
|
|
151 |
" model_file = \"lit_model_gptq.4bit.pth\"\n", |
|
|
152 |
" if not (checkpoint_dir / model_file).is_file():\n", |
|
|
153 |
" raise ValueError(\"Please run `python quantize/gptq.py` first\")\n", |
|
|
154 |
"else:\n", |
|
|
155 |
" model_file = \"lit_model.pth\"\n", |
|
|
156 |
"checkpoint_path = checkpoint_dir / model_file\n", |
|
|
157 |
"\n", |
|
|
158 |
"tokenizer = Tokenizer(checkpoint_dir)\n", |
|
|
159 |
"prompt = generate_prompt(sample)\n", |
|
|
160 |
"encoded = tokenizer.encode(prompt, device=fabric.device)\n", |
|
|
161 |
"prompt_length = encoded.size(0)\n", |
|
|
162 |
"max_returned_tokens = prompt_length + max_new_tokens\n", |
|
|
163 |
"\n", |
|
|
164 |
"fabric.print(f\"Loading model {str(checkpoint_path)!r} with {config.__dict__}\", file=sys.stderr)\n", |
|
|
165 |
"t0 = time.perf_counter()\n", |
|
|
166 |
"with fabric.init_module(empty_init=True), gptq_quantization(quantize == \"gptq.int4\"):\n", |
|
|
167 |
" model = GPT(config)\n", |
|
|
168 |
"fabric.print(f\"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.\", file=sys.stderr)\n", |
|
|
169 |
"with fabric.init_tensor():\n", |
|
|
170 |
" # set the max_seq_length to limit the memory usage to what we need\n", |
|
|
171 |
" model.max_seq_length = max_returned_tokens\n", |
|
|
172 |
" # enable the kv cache\n", |
|
|
173 |
" model.set_kv_cache(batch_size=1)\n", |
|
|
174 |
"model.eval()\n", |
|
|
175 |
"\n", |
|
|
176 |
"t0 = time.perf_counter()\n", |
|
|
177 |
"checkpoint = lazy_load(checkpoint_path)\n", |
|
|
178 |
"lora_checkpoint = lazy_load(lora_path)\n", |
|
|
179 |
"checkpoint.update(lora_checkpoint.get(\"model\", lora_checkpoint))\n", |
|
|
180 |
"\n", |
|
|
181 |
"model.load_state_dict(checkpoint)\n", |
|
|
182 |
"fabric.print(f\"Time to load the model weights: {time.perf_counter() - t0:.02f} seconds.\", file=sys.stderr)\n", |
|
|
183 |
"\n", |
|
|
184 |
"merge_lora_weights(model)\n", |
|
|
185 |
"model = fabric.setup(model)" |
|
|
186 |
] |
|
|
187 |
}, |
|
|
188 |
{ |
|
|
189 |
"cell_type": "code", |
|
|
190 |
"execution_count": null, |
|
|
191 |
"id": "59e00f69-d9fd-4cf5-a4ed-f142991b870f", |
|
|
192 |
"metadata": { |
|
|
193 |
"tags": [] |
|
|
194 |
}, |
|
|
195 |
"outputs": [], |
|
|
196 |
"source": [ |
|
|
197 |
"prompt" |
|
|
198 |
] |
|
|
199 |
}, |
|
|
200 |
{ |
|
|
201 |
"cell_type": "code", |
|
|
202 |
"execution_count": null, |
|
|
203 |
"id": "3eeaa237-7a95-4c9d-aeda-8a3c246d02fe", |
|
|
204 |
"metadata": {}, |
|
|
205 |
"outputs": [], |
|
|
206 |
"source": [ |
|
|
207 |
"L.seed_everything(1234)\n", |
|
|
208 |
"t0 = time.perf_counter()\n", |
|
|
209 |
"\n", |
|
|
210 |
"y = generate(model, encoded, max_returned_tokens, temperature=temperature, top_k=top_k, eos_id=tokenizer.eos_id)\n", |
|
|
211 |
"t = time.perf_counter() - t0\n", |
|
|
212 |
"\n", |
|
|
213 |
"output = tokenizer.decode(y)\n", |
|
|
214 |
"output = output.split(\"### Response:\")[1].strip()\n", |
|
|
215 |
"fabric.print(output)\n", |
|
|
216 |
"\n", |
|
|
217 |
"tokens_generated = y.size(0) - prompt_length\n", |
|
|
218 |
"fabric.print(f\"\\n\\nTime for inference: {t:.02f} sec total, {tokens_generated / t:.02f} tokens/sec\", file=sys.stderr)\n", |
|
|
219 |
"if fabric.device.type == \"cuda\":\n", |
|
|
220 |
" fabric.print(f\"Memory used: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB\", file=sys.stderr)" |
|
|
221 |
] |
|
|
222 |
}, |
|
|
223 |
{ |
|
|
224 |
"cell_type": "code", |
|
|
225 |
"execution_count": null, |
|
|
226 |
"id": "09d286fb-d595-4d8c-94a1-06ec7357722f", |
|
|
227 |
"metadata": {}, |
|
|
228 |
"outputs": [], |
|
|
229 |
"source": [ |
|
|
230 |
"def parse_model_response(response):\n", |
|
|
231 |
" \"\"\"\n", |
|
|
232 |
" Parse the model response to extract entities.\n", |
|
|
233 |
"\n", |
|
|
234 |
" Args:\n", |
|
|
235 |
" - response: A string representing the model's response.\n", |
|
|
236 |
"\n", |
|
|
237 |
" Returns:\n", |
|
|
238 |
" - A dictionary containing the extracted entities.\n", |
|
|
239 |
" \"\"\"\n", |
|
|
240 |
" return json.loads(response)" |
|
|
241 |
] |
|
|
242 |
}, |
|
|
243 |
{ |
|
|
244 |
"cell_type": "code", |
|
|
245 |
"execution_count": null, |
|
|
246 |
"id": "faee8a5e-9e3c-4d95-b351-d19a46c3f0a2", |
|
|
247 |
"metadata": { |
|
|
248 |
"scrolled": true, |
|
|
249 |
"tags": [] |
|
|
250 |
}, |
|
|
251 |
"outputs": [], |
|
|
252 |
"source": [ |
|
|
253 |
"test_data_with_prediction = []\n", |
|
|
254 |
"for sample in test_data:\n", |
|
|
255 |
" # Generate prompt from sample\n", |
|
|
256 |
" prompt = generate_prompt(sample)\n", |
|
|
257 |
" fabric.print(prompt)\n", |
|
|
258 |
" \n", |
|
|
259 |
" # Encode the prompt\n", |
|
|
260 |
" encoded = tokenizer.encode(prompt, device=fabric.device)\n", |
|
|
261 |
" \n", |
|
|
262 |
" # Generate the prediction from the LLM\n", |
|
|
263 |
" y = generate(model, encoded, max_returned_tokens, temperature=temperature, top_k=top_k, eos_id=tokenizer.eos_id)\n", |
|
|
264 |
" output = tokenizer.decode(y)\n", |
|
|
265 |
" \n", |
|
|
266 |
" # Process the predicted completion\n", |
|
|
267 |
" output = output.split(\"### Response:\")[1].strip()\n", |
|
|
268 |
" \n", |
|
|
269 |
" # Store prediction along with input and ground truth\n", |
|
|
270 |
" sample['prediction'] = output\n", |
|
|
271 |
" test_data_with_prediction.append(sample)\n", |
|
|
272 |
" \n", |
|
|
273 |
" fabric.print(output)\n", |
|
|
274 |
" fabric.print(\"---------------------------------------------------------\\n\\n\")" |
|
|
275 |
] |
|
|
276 |
}, |
|
|
277 |
{ |
|
|
278 |
"cell_type": "code", |
|
|
279 |
"execution_count": null, |
|
|
280 |
"id": "1616278a-0dca-48b7-b254-f1bd957942ef", |
|
|
281 |
"metadata": {}, |
|
|
282 |
"outputs": [], |
|
|
283 |
"source": [ |
|
|
284 |
"# Write the predictions data to a file\n", |
|
|
285 |
"with open(predictions_file_name, 'w') as file:\n", |
|
|
286 |
" json.dump(test_data_with_prediction, file, indent=4)" |
|
|
287 |
] |
|
|
288 |
}, |
|
|
289 |
{ |
|
|
290 |
"cell_type": "code", |
|
|
291 |
"execution_count": null, |
|
|
292 |
"id": "047cb010-58dd-4913-a0e5-fe167d32c320", |
|
|
293 |
"metadata": {}, |
|
|
294 |
"outputs": [], |
|
|
295 |
"source": [] |
|
|
296 |
} |
|
|
297 |
], |
|
|
298 |
"metadata": { |
|
|
299 |
"kernelspec": { |
|
|
300 |
"display_name": "new", |
|
|
301 |
"language": "python", |
|
|
302 |
"name": "new" |
|
|
303 |
}, |
|
|
304 |
"language_info": { |
|
|
305 |
"codemirror_mode": { |
|
|
306 |
"name": "ipython", |
|
|
307 |
"version": 3 |
|
|
308 |
}, |
|
|
309 |
"file_extension": ".py", |
|
|
310 |
"mimetype": "text/x-python", |
|
|
311 |
"name": "python", |
|
|
312 |
"nbconvert_exporter": "python", |
|
|
313 |
"pygments_lexer": "ipython3", |
|
|
314 |
"version": "3.10.13" |
|
|
315 |
} |
|
|
316 |
}, |
|
|
317 |
"nbformat": 4, |
|
|
318 |
"nbformat_minor": 5 |
|
|
319 |
} |