File size: 9,420 Bytes
b3ec055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# QA Legal Refugees Project"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Environment\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "! pip install -U \"transformers==4.38.0\" --upgrade\n",
    "! pip install git+https://github.com/huggingface/trl\n",
    "! pip install peft\n",
    "! pip install accelerate\n",
    "! pip intall datasets\n",
    "! pip install bitsandbytes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Base Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We used Gemma 7b as base model for 3 reason\n",
    "- Tokenizer size with multiple [languages](https://www.shelpuk.com/post/llm-practitioner-s-guide-gemma-a-game-changing-multilingual-llm)\n",
    "- is SOTA for its size \n",
    "- A lot of material available to consult"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset preparation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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",
    "\n",
    "we identified the special tokens so the model could understand the different roles in the conversation\n",
    "\n",
    "Example \n",
    "```\n",
    "<bos><|im_start|>system\n",
    "You are Gemma.<|im_end|>\n",
    "<|im_start|>user\n",
    "Hello, how are you?<|im_end|>\n",
    "<|im_start|>assistant\n",
    "I'm doing great. How can I help you today?<|im_end|>\\n<eos>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "so we used [Phil Schmid's gemma chatml tokenizer](https://huggingface.co/philschmid/gemma-tokenizer-chatml) to adapt our dataset for training"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## load dataset\n",
    "from datasets import load_dataset\n",
    "\n",
    "dataset = load_dataset(\"somosnlp/instruct-legal-refugiados-es\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load tokenizer \n",
    "tokenizer_id = \"philschmid/gemma-tokenizer-chatml\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)\n",
    "tokenizer.padding_side = 'right' # to prevent warnings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Map functions\n",
    "def create_message_column(row):\n",
    "    messages = []\n",
    "    user = {\n",
    "        \"content\": f\"{row['instruction']}/n{row['input']}\",\n",
    "        \"role\": \"user\"\n",
    "    }\n",
    "    messages.append(user)\n",
    "    assistant = {\n",
    "        \"content\": f\"{row['output']}\",\n",
    "        \"role\": \"assistant\"\n",
    "    }\n",
    "    messages.append(assistant)\n",
    "    return {\"messages\": messages}\n",
    "\n",
    "def format_dataset_chatml(row):\n",
    "    return {\"text\": tokenizer.apply_chat_template(row[\"messages\"], add_generation_prompt=False, tokenize=False)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## prepare the dataset\n",
    "dataset = dataset.map(create_message_column)\n",
    "dataset = dataset.map(format_dataset_chatml)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To finetune Gemma we used PEFT, Lora and SFTTtrainer. The model was trained in a RTX 4090 from Vast.ai founded by the author"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import AutoModelForCausalLM, BitsAndBytesConfig\n",
    "\n",
    "# cache_dir was set because the rent machine didn't have space in default directory\n",
    "# Hugging Face model id\n",
    "model_id = \"google/gemma-7b\"\n",
    "\n",
    "# BitsAndBytesConfig int-4 config\n",
    "bnb_config = BitsAndBytesConfig(\n",
    "    load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type=\"nf4\", bnb_4bit_compute_dtype=torch.bfloat16\n",
    ")\n",
    "\n",
    "# Load model and tokenizer\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    model_id,\n",
    "    device_map=\"auto\",\n",
    "    attn_implementation=\"flash_attention_2\",\n",
    "    torch_dtype=torch.bfloat16,\n",
    "    quantization_config=bnb_config,\n",
    "    cache_dir=\"/sys/fs/cgroup/models\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from peft import LoraConfig\n",
    "\n",
    "peft_config = LoraConfig(\n",
    "    lora_alpha=8,\n",
    "    lora_dropout=0.05,\n",
    "    r=6,\n",
    "    bias=\"none\",\n",
    "    target_modules=\"all-linear\",\n",
    "    task_type=\"CAUSAL_LM\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import TrainingArguments\n",
    "\n",
    "args = TrainingArguments(\n",
    "    output_dir=\"/sys/fs/cgroup/models/model/location\",\n",
    "    num_train_epochs=3,\n",
    "    per_device_train_batch_size=2,\n",
    "    gradient_accumulation_steps=2,\n",
    "    gradient_checkpointing=True,\n",
    "    optim=\"adamw_torch_fused\",\n",
    "    logging_steps=10,\n",
    "    save_strategy=\"epoch\",\n",
    "    bf16=True,\n",
    "    tf32=True,\n",
    "    max_grad_norm=0.3,                      # max gradient norm based on QLoRA paper\n",
    "    warmup_ratio=0.03,                      # warmup ratio based on QLoRA paper\n",
    "    lr_scheduler_type=\"constant\",           # use constant learning rate scheduler\n",
    "    push_to_hub=True,\n",
    "    hub_private_repo=True,\n",
    "    hub_model_id=\"model_name\",                      # push model to hub\n",
    "    report_to=\"wandb\",\n",
    "    seed=66,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from trl import SFTTrainer\n",
    "\n",
    "max_seq_length =1512\n",
    "\n",
    "trainer = SFTTrainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=dataset,\n",
    "    dataset_text_field=\"text\",\n",
    "    peft_config=peft_config,\n",
    "    max_seq_length=max_seq_length,\n",
    "    tokenizer=tokenizer,\n",
    "    packing=True,\n",
    "    dataset_kwargs={\n",
    "        \"add_special_tokens\": False, # We template with special tokens\n",
    "        \"append_concat_token\": False, # No need to add additional separator token\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer.push_to_hub()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Merge adapter into original model\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from peft import PeftModel, PeftConfig\n",
    "from transformers import AutoModelForCausalLM\n",
    "\n",
    "peft_model_id = \"model_name\"\n",
    "base_model_id = \"google/gemma-7b-it\"\n",
    "config = PeftConfig.from_pretrained(peft_model_id, cache_dir=\"/sys/fs/cgroup/models\")\n",
    "model = AutoModelForCausalLM.from_pretrained(base_model_id, cache_dir=\"/sys/fs/cgroup/models\")\n",
    "model = PeftModel.from_pretrained(model, peft_model_id ,cache_dir=\"/sys/fs/cgroup/models\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(peft_model_id, cache_dir=\"/sys/fs/cgroup/models\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = model.merge_and_unload()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save_pretrained(\"/sys/fs/cgroup/model/location\", push_to_hub=True, private=True)\n",
    "tokenizer.save_pretrained(\"/sys/fs/cgroup/model/location\", push_to_hub=True, private=True)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}