hacendado commited on
Commit
b3ec055
1 Parent(s): 7d5326d

added train notebook

Browse files
Files changed (1) hide show
  1. train_notebook.ipynb +334 -0
train_notebook.ipynb ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# QA Legal Refugees Project"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "markdown",
12
+ "metadata": {},
13
+ "source": [
14
+ "## Environment\n"
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "markdown",
19
+ "metadata": {},
20
+ "source": [
21
+ "! pip install -U \"transformers==4.38.0\" --upgrade\n",
22
+ "! pip install git+https://github.com/huggingface/trl\n",
23
+ "! pip install peft\n",
24
+ "! pip install accelerate\n",
25
+ "! pip intall datasets\n",
26
+ "! pip install bitsandbytes"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "markdown",
31
+ "metadata": {},
32
+ "source": [
33
+ "## Base Model"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "markdown",
38
+ "metadata": {},
39
+ "source": [
40
+ "We used Gemma 7b as base model for 3 reason\n",
41
+ "- Tokenizer size with multiple [languages](https://www.shelpuk.com/post/llm-practitioner-s-guide-gemma-a-game-changing-multilingual-llm)\n",
42
+ "- is SOTA for its size \n",
43
+ "- A lot of material available to consult"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "metadata": {},
49
+ "source": [
50
+ "## Dataset preparation"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "markdown",
55
+ "metadata": {},
56
+ "source": [
57
+ "We wanted to make a conversation model so we investigated the base model prompt in order to make conversational base on [chatml format](https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/ai-services/openai/includes/chat-markup-language.md#working-with-chat-markup-language-chatml)\n",
58
+ "\n",
59
+ "we identified the special tokens so the model could understand the different roles in the conversation\n",
60
+ "\n",
61
+ "Example \n",
62
+ "```\n",
63
+ "<bos><|im_start|>system\n",
64
+ "You are Gemma.<|im_end|>\n",
65
+ "<|im_start|>user\n",
66
+ "Hello, how are you?<|im_end|>\n",
67
+ "<|im_start|>assistant\n",
68
+ "I'm doing great. How can I help you today?<|im_end|>\\n<eos>\n",
69
+ "```"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "markdown",
74
+ "metadata": {},
75
+ "source": [
76
+ "so we used [Phil Schmid's gemma chatml tokenizer](https://huggingface.co/philschmid/gemma-tokenizer-chatml) to adapt our dataset for training"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "execution_count": null,
82
+ "metadata": {},
83
+ "outputs": [],
84
+ "source": [
85
+ "## load dataset\n",
86
+ "from datasets import load_dataset\n",
87
+ "\n",
88
+ "dataset = load_dataset(\"somosnlp/instruct-legal-refugiados-es\")"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "# load tokenizer \n",
98
+ "tokenizer_id = \"philschmid/gemma-tokenizer-chatml\"\n",
99
+ "tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)\n",
100
+ "tokenizer.padding_side = 'right' # to prevent warnings"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": null,
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "## Map functions\n",
110
+ "def create_message_column(row):\n",
111
+ " messages = []\n",
112
+ " user = {\n",
113
+ " \"content\": f\"{row['instruction']}/n{row['input']}\",\n",
114
+ " \"role\": \"user\"\n",
115
+ " }\n",
116
+ " messages.append(user)\n",
117
+ " assistant = {\n",
118
+ " \"content\": f\"{row['output']}\",\n",
119
+ " \"role\": \"assistant\"\n",
120
+ " }\n",
121
+ " messages.append(assistant)\n",
122
+ " return {\"messages\": messages}\n",
123
+ "\n",
124
+ "def format_dataset_chatml(row):\n",
125
+ " return {\"text\": tokenizer.apply_chat_template(row[\"messages\"], add_generation_prompt=False, tokenize=False)}"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "execution_count": null,
131
+ "metadata": {},
132
+ "outputs": [],
133
+ "source": [
134
+ "## prepare the dataset\n",
135
+ "dataset = dataset.map(create_message_column)\n",
136
+ "dataset = dataset.map(format_dataset_chatml)"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "markdown",
141
+ "metadata": {},
142
+ "source": [
143
+ "## Train Model"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "markdown",
148
+ "metadata": {},
149
+ "source": [
150
+ "To finetune Gemma we used PEFT, Lora and SFTTtrainer. The model was trained in a RTX 4090 from Vast.ai founded by the author"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": null,
156
+ "metadata": {},
157
+ "outputs": [],
158
+ "source": [
159
+ "import torch\n",
160
+ "from transformers import AutoModelForCausalLM, BitsAndBytesConfig\n",
161
+ "\n",
162
+ "# cache_dir was set because the rent machine didn't have space in default directory\n",
163
+ "# Hugging Face model id\n",
164
+ "model_id = \"google/gemma-7b\"\n",
165
+ "\n",
166
+ "# BitsAndBytesConfig int-4 config\n",
167
+ "bnb_config = BitsAndBytesConfig(\n",
168
+ " load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type=\"nf4\", bnb_4bit_compute_dtype=torch.bfloat16\n",
169
+ ")\n",
170
+ "\n",
171
+ "# Load model and tokenizer\n",
172
+ "model = AutoModelForCausalLM.from_pretrained(\n",
173
+ " model_id,\n",
174
+ " device_map=\"auto\",\n",
175
+ " attn_implementation=\"flash_attention_2\",\n",
176
+ " torch_dtype=torch.bfloat16,\n",
177
+ " quantization_config=bnb_config,\n",
178
+ " cache_dir=\"/sys/fs/cgroup/models\"\n",
179
+ ")"
180
+ ]
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "execution_count": null,
185
+ "metadata": {},
186
+ "outputs": [],
187
+ "source": [
188
+ "from peft import LoraConfig\n",
189
+ "\n",
190
+ "peft_config = LoraConfig(\n",
191
+ " lora_alpha=8,\n",
192
+ " lora_dropout=0.05,\n",
193
+ " r=6,\n",
194
+ " bias=\"none\",\n",
195
+ " target_modules=\"all-linear\",\n",
196
+ " task_type=\"CAUSAL_LM\"\n",
197
+ ")"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "execution_count": null,
203
+ "metadata": {},
204
+ "outputs": [],
205
+ "source": [
206
+ "from transformers import TrainingArguments\n",
207
+ "\n",
208
+ "args = TrainingArguments(\n",
209
+ " output_dir=\"/sys/fs/cgroup/models/model/location\",\n",
210
+ " num_train_epochs=3,\n",
211
+ " per_device_train_batch_size=2,\n",
212
+ " gradient_accumulation_steps=2,\n",
213
+ " gradient_checkpointing=True,\n",
214
+ " optim=\"adamw_torch_fused\",\n",
215
+ " logging_steps=10,\n",
216
+ " save_strategy=\"epoch\",\n",
217
+ " bf16=True,\n",
218
+ " tf32=True,\n",
219
+ " max_grad_norm=0.3, # max gradient norm based on QLoRA paper\n",
220
+ " warmup_ratio=0.03, # warmup ratio based on QLoRA paper\n",
221
+ " lr_scheduler_type=\"constant\", # use constant learning rate scheduler\n",
222
+ " push_to_hub=True,\n",
223
+ " hub_private_repo=True,\n",
224
+ " hub_model_id=\"model_name\", # push model to hub\n",
225
+ " report_to=\"wandb\",\n",
226
+ " seed=66,\n",
227
+ ")"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": null,
233
+ "metadata": {},
234
+ "outputs": [],
235
+ "source": [
236
+ "from trl import SFTTrainer\n",
237
+ "\n",
238
+ "max_seq_length =1512\n",
239
+ "\n",
240
+ "trainer = SFTTrainer(\n",
241
+ " model=model,\n",
242
+ " args=args,\n",
243
+ " train_dataset=dataset,\n",
244
+ " dataset_text_field=\"text\",\n",
245
+ " peft_config=peft_config,\n",
246
+ " max_seq_length=max_seq_length,\n",
247
+ " tokenizer=tokenizer,\n",
248
+ " packing=True,\n",
249
+ " dataset_kwargs={\n",
250
+ " \"add_special_tokens\": False, # We template with special tokens\n",
251
+ " \"append_concat_token\": False, # No need to add additional separator token\n",
252
+ " }\n",
253
+ ")"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "execution_count": null,
259
+ "metadata": {},
260
+ "outputs": [],
261
+ "source": [
262
+ "trainer.train()"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": null,
268
+ "metadata": {},
269
+ "outputs": [],
270
+ "source": [
271
+ "trainer.push_to_hub()"
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "markdown",
276
+ "metadata": {},
277
+ "source": [
278
+ "## Merge adapter into original model\n",
279
+ "When using QLoRA, we only train adapters and not the full model. This means when saving the model during training we only save the adapter weights and not the full model. You can merge the adapter weights into the model weights using the `merge_and_unload` method and then save the model with the `save_pretrained` method."
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": null,
285
+ "metadata": {},
286
+ "outputs": [],
287
+ "source": [
288
+ "from peft import PeftModel, PeftConfig\n",
289
+ "from transformers import AutoModelForCausalLM\n",
290
+ "\n",
291
+ "peft_model_id = \"model_name\"\n",
292
+ "base_model_id = \"google/gemma-7b-it\"\n",
293
+ "config = PeftConfig.from_pretrained(peft_model_id, cache_dir=\"/sys/fs/cgroup/models\")\n",
294
+ "model = AutoModelForCausalLM.from_pretrained(base_model_id, cache_dir=\"/sys/fs/cgroup/models\")\n",
295
+ "model = PeftModel.from_pretrained(model, peft_model_id ,cache_dir=\"/sys/fs/cgroup/models\")"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "execution_count": null,
301
+ "metadata": {},
302
+ "outputs": [],
303
+ "source": [
304
+ "tokenizer = AutoTokenizer.from_pretrained(peft_model_id, cache_dir=\"/sys/fs/cgroup/models\")"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": null,
310
+ "metadata": {},
311
+ "outputs": [],
312
+ "source": [
313
+ "model = model.merge_and_unload()"
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": null,
319
+ "metadata": {},
320
+ "outputs": [],
321
+ "source": [
322
+ "model.save_pretrained(\"/sys/fs/cgroup/model/location\", push_to_hub=True, private=True)\n",
323
+ "tokenizer.save_pretrained(\"/sys/fs/cgroup/model/location\", push_to_hub=True, private=True)"
324
+ ]
325
+ }
326
+ ],
327
+ "metadata": {
328
+ "language_info": {
329
+ "name": "python"
330
+ }
331
+ },
332
+ "nbformat": 4,
333
+ "nbformat_minor": 2
334
+ }