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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {
|
6 |
+
"id": "WE5GJ6s7y0Xo"
|
7 |
+
},
|
8 |
+
"source": [
|
9 |
+
"## Eluwa training notebook\n",
|
10 |
+
"\n",
|
11 |
+
"This is a straightforward mash-up of two sources - [a tutorial notebook on retraining OPT](https://colab.research.google.com/drive/1jCkpikz0J2o20FBQmYmAGdiKmJGOMo-o) and settings + data from the [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) github."
|
12 |
+
]
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"cell_type": "markdown",
|
16 |
+
"metadata": {
|
17 |
+
"id": "TfBzP8gWzkpv"
|
18 |
+
},
|
19 |
+
"source": [
|
20 |
+
"### Install requirements\n",
|
21 |
+
"\n",
|
22 |
+
"First, run the cells below to install the requirements:"
|
23 |
+
]
|
24 |
+
},
|
25 |
+
{
|
26 |
+
"cell_type": "code",
|
27 |
+
"execution_count": null,
|
28 |
+
"metadata": {
|
29 |
+
"id": "otj46qRbtpnd"
|
30 |
+
},
|
31 |
+
"outputs": [],
|
32 |
+
"source": [
|
33 |
+
"!pip install -q bitsandbytes datasets accelerate loralib transformers peft\n",
|
34 |
+
"import os\n",
|
35 |
+
"import torch\n",
|
36 |
+
"import torch.nn as nn\n",
|
37 |
+
"import bitsandbytes as bnb\n",
|
38 |
+
"from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM\n"
|
39 |
+
]
|
40 |
+
},
|
41 |
+
{
|
42 |
+
"cell_type": "markdown",
|
43 |
+
"metadata": {
|
44 |
+
"id": "FOtwYRI3zzXI"
|
45 |
+
},
|
46 |
+
"source": [
|
47 |
+
"### Model loading\n",
|
48 |
+
"\n",
|
49 |
+
"Here let's load the `opt` model and tokenizer from their huggingface link. The model is loaded in [8bit](https://) mode. This drastically reduces the amount of memory required to run the model. Without it, any attempt to train models above a certain size (say, something like `pythia1b`) will max out the available RAM/VRAM and get your nowhere. To understand what's going on with that `8bit` flag, it might be useful to read [this first](https://https://huggingface.co/blog/hf-bitsandbytes-integration)."
|
50 |
+
]
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"cell_type": "code",
|
54 |
+
"execution_count": null,
|
55 |
+
"metadata": {
|
56 |
+
"id": "cg3fiQOvmI3Q"
|
57 |
+
},
|
58 |
+
"outputs": [],
|
59 |
+
"source": [
|
60 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
61 |
+
" \"facebook/opt-1.3b\", \n",
|
62 |
+
" load_in_8bit=True, \n",
|
63 |
+
" device_map='auto',\n",
|
64 |
+
")\n",
|
65 |
+
"\n",
|
66 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"facebook/opt-1.3b\")"
|
67 |
+
]
|
68 |
+
},
|
69 |
+
{
|
70 |
+
"cell_type": "markdown",
|
71 |
+
"metadata": {
|
72 |
+
"id": "QdjWif4CVXR6"
|
73 |
+
},
|
74 |
+
"source": [
|
75 |
+
"### Training\n",
|
76 |
+
"Here we load the alpaca dataset. "
|
77 |
+
]
|
78 |
+
},
|
79 |
+
{
|
80 |
+
"cell_type": "code",
|
81 |
+
"execution_count": null,
|
82 |
+
"metadata": {
|
83 |
+
"id": "AQ_HCYruWIHU"
|
84 |
+
},
|
85 |
+
"outputs": [],
|
86 |
+
"source": [
|
87 |
+
"import transformers\n",
|
88 |
+
"from datasets import load_dataset\n",
|
89 |
+
"data = load_dataset(\"tatsu-lab/alpaca\")\n",
|
90 |
+
"data = data.map(lambda samples: tokenizer(samples['instruction']), batched=True)\n"
|
91 |
+
]
|
92 |
+
},
|
93 |
+
{
|
94 |
+
"cell_type": "markdown",
|
95 |
+
"metadata": {
|
96 |
+
"id": "9fTSZntA1iUG"
|
97 |
+
},
|
98 |
+
"source": [
|
99 |
+
"### Post-processing on the model\n",
|
100 |
+
"\n",
|
101 |
+
"We need to apply some post-processing on the 8-bit model to enable training, let's freeze all our layers, and cast the layer-norm in `float32` for stability. We also cast the output of the last layer in `float32` for the same reasons."
|
102 |
+
]
|
103 |
+
},
|
104 |
+
{
|
105 |
+
"cell_type": "code",
|
106 |
+
"execution_count": null,
|
107 |
+
"metadata": {
|
108 |
+
"id": "T-gy-LxM0yAi"
|
109 |
+
},
|
110 |
+
"outputs": [],
|
111 |
+
"source": [
|
112 |
+
"for param in model.parameters():\n",
|
113 |
+
" param.requires_grad = False # freeze the model - train adapters later\n",
|
114 |
+
" if param.ndim == 1:\n",
|
115 |
+
" # cast the small parameters (e.g. layernorm) to fp32 for stability\n",
|
116 |
+
" param.data = param.data.to(torch.float32)\n",
|
117 |
+
"\n",
|
118 |
+
"model.gradient_checkpointing_enable() # reduce number of stored activations\n",
|
119 |
+
"model.enable_input_require_grads()\n",
|
120 |
+
"\n",
|
121 |
+
"class CastOutputToFloat(nn.Sequential):\n",
|
122 |
+
" def forward(self, x): return super().forward(x).to(torch.float32)\n",
|
123 |
+
"model.lm_head = CastOutputToFloat(model.lm_head)"
|
124 |
+
]
|
125 |
+
},
|
126 |
+
{
|
127 |
+
"cell_type": "markdown",
|
128 |
+
"metadata": {
|
129 |
+
"id": "KwOTr7B3NlM3"
|
130 |
+
},
|
131 |
+
"source": [
|
132 |
+
"### Apply LoRA\n",
|
133 |
+
"\n",
|
134 |
+
"A LoRA (Low-Rank Adapter) is a way of training a portion of a model, instead of training the entire model. In inference, the LoRA then fits 'on top' of the existing model to modify its outputs. It takes only a fraction of the memory required to store. I highly recommend [reading the paper](https://arxiv.org/pdf/2106.09685.pdf): without it we'd be stuck retraining entire models from scratch every time. \n",
|
135 |
+
"\n",
|
136 |
+
"This magic happens with `peft`! Let's load a `PeftModel` and specify that we are going to use low-rank adapters (LoRA) using `get_peft_model` utility function from `peft`. This code will output how many parameters we can actually train here with this method. "
|
137 |
+
]
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"cell_type": "code",
|
141 |
+
"execution_count": null,
|
142 |
+
"metadata": {
|
143 |
+
"id": "4W1j6lxaNnxC"
|
144 |
+
},
|
145 |
+
"outputs": [],
|
146 |
+
"source": [
|
147 |
+
"def print_trainable_parameters(model):\n",
|
148 |
+
" \"\"\"\n",
|
149 |
+
" Prints the number of trainable parameters in the model.\n",
|
150 |
+
" \"\"\"\n",
|
151 |
+
" trainable_params = 0\n",
|
152 |
+
" all_param = 0\n",
|
153 |
+
" for _, param in model.named_parameters():\n",
|
154 |
+
" all_param += param.numel()\n",
|
155 |
+
" if param.requires_grad:\n",
|
156 |
+
" trainable_params += param.numel()\n",
|
157 |
+
" print(\n",
|
158 |
+
" f\"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}\"\n",
|
159 |
+
" )\n",
|
160 |
+
"\n",
|
161 |
+
"from peft import LoraConfig, get_peft_model \n",
|
162 |
+
"\n",
|
163 |
+
"config = LoraConfig(\n",
|
164 |
+
" r=16,\n",
|
165 |
+
" lora_alpha=32,\n",
|
166 |
+
" target_modules=[\"q_proj\", \"v_proj\"],\n",
|
167 |
+
" lora_dropout=0.05,\n",
|
168 |
+
" bias=\"none\",\n",
|
169 |
+
" task_type=\"CAUSAL_LM\"\n",
|
170 |
+
")\n",
|
171 |
+
"\n",
|
172 |
+
"model = get_peft_model(model, config)\n",
|
173 |
+
"print_trainable_parameters(model)\n"
|
174 |
+
]
|
175 |
+
},
|
176 |
+
{
|
177 |
+
"cell_type": "markdown",
|
178 |
+
"source": [
|
179 |
+
"### Defining the training arguments\n",
|
180 |
+
"The `trainer` function here specifies important things. [The documentation](https://huggingface.co/transformers/v3.0.2/main_classes/trainer.html#transformers.TrainingArguments) covers all these parameters and then some. \n",
|
181 |
+
"Things you typically want to pay attention to:\n",
|
182 |
+
" is the \n",
|
183 |
+
"\n",
|
184 |
+
"* `learning rate` (3e-4 is commonly seen, although that may have been a joke by Karpathy) \n",
|
185 |
+
"* `num_train_epochs`: a measure of how long you want to train your model for. Each time a dataset passes through an algorithm, it is said to have completed an epoch. `max_steps ` is an alternate way of controlling how long you're going to train for. Helps to comment out one if you're using the other.\n",
|
186 |
+
"\n"
|
187 |
+
],
|
188 |
+
"metadata": {
|
189 |
+
"id": "JdEnTEr-_yWN"
|
190 |
+
}
|
191 |
+
},
|
192 |
+
{
|
193 |
+
"cell_type": "code",
|
194 |
+
"source": [
|
195 |
+
"\n",
|
196 |
+
"trainer = transformers.Trainer(\n",
|
197 |
+
" model=model, \n",
|
198 |
+
" train_dataset=data['train'],\n",
|
199 |
+
" args=transformers.TrainingArguments(\n",
|
200 |
+
" per_device_train_batch_size=8, \n",
|
201 |
+
" gradient_accumulation_steps=4,\n",
|
202 |
+
" warmup_steps=100, \n",
|
203 |
+
" num_train_epochs=1,\n",
|
204 |
+
" #max_steps=1000, \n",
|
205 |
+
" learning_rate=2e-4, \n",
|
206 |
+
" fp16=True,\n",
|
207 |
+
" logging_steps=10, \n",
|
208 |
+
" output_dir='outputs'\n",
|
209 |
+
" ),\n",
|
210 |
+
" data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False)\n",
|
211 |
+
")\n",
|
212 |
+
"model.config.use_cache = False # silence the warnings. Please re-enable for inference!"
|
213 |
+
],
|
214 |
+
"metadata": {
|
215 |
+
"id": "5FmaIP5T_xqW"
|
216 |
+
},
|
217 |
+
"execution_count": null,
|
218 |
+
"outputs": []
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"cell_type": "markdown",
|
222 |
+
"source": [
|
223 |
+
"###The actual training"
|
224 |
+
],
|
225 |
+
"metadata": {
|
226 |
+
"id": "Mmzb7aNRBN6V"
|
227 |
+
}
|
228 |
+
},
|
229 |
+
{
|
230 |
+
"cell_type": "markdown",
|
231 |
+
"source": [
|
232 |
+
"I keep `resume_from_checkpoint = False` because the function can't seem to handle quantized models very well. This does mean that you're starting from scratch every time. Colab has an annoying habit of restarting runtimes out of nowhere, so if you're training for a long time, say a prayer before you press the button."
|
233 |
+
],
|
234 |
+
"metadata": {
|
235 |
+
"id": "AgQ_A39WBRgN"
|
236 |
+
}
|
237 |
+
},
|
238 |
+
{
|
239 |
+
"cell_type": "code",
|
240 |
+
"source": [
|
241 |
+
"trainer.train(resume_from_checkpoint = False)"
|
242 |
+
],
|
243 |
+
"metadata": {
|
244 |
+
"id": "_5GaD7dMfMR3"
|
245 |
+
},
|
246 |
+
"execution_count": null,
|
247 |
+
"outputs": []
|
248 |
+
},
|
249 |
+
{
|
250 |
+
"cell_type": "markdown",
|
251 |
+
"source": [
|
252 |
+
"### Saving your LoRA\n",
|
253 |
+
"\n",
|
254 |
+
"Important! Remember to run this so you can save and download your LoRa. The training process will generate .bin files, but they aren't the models you're looking for.\n",
|
255 |
+
"\n"
|
256 |
+
],
|
257 |
+
"metadata": {
|
258 |
+
"id": "GXMR53MrBgAn"
|
259 |
+
}
|
260 |
+
},
|
261 |
+
{
|
262 |
+
"cell_type": "code",
|
263 |
+
"source": [
|
264 |
+
"model.save_pretrained(\"lora-eluwa-opt\")"
|
265 |
+
],
|
266 |
+
"metadata": {
|
267 |
+
"id": "iQDSGcfQehDc"
|
268 |
+
},
|
269 |
+
"execution_count": null,
|
270 |
+
"outputs": []
|
271 |
+
}
|
272 |
+
],
|
273 |
+
"metadata": {
|
274 |
+
"accelerator": "GPU",
|
275 |
+
"colab": {
|
276 |
+
"machine_shape": "hm",
|
277 |
+
"provenance": []
|
278 |
+
},
|
279 |
+
"gpuClass": "standard",
|
280 |
+
"kernelspec": {
|
281 |
+
"display_name": "Python 3 (ipykernel)",
|
282 |
+
"language": "python",
|
283 |
+
"name": "python3"
|
284 |
+
},
|
285 |
+
"language_info": {
|
286 |
+
"codemirror_mode": {
|
287 |
+
"name": "ipython",
|
288 |
+
"version": 3
|
289 |
+
},
|
290 |
+
"file_extension": ".py",
|
291 |
+
"mimetype": "text/x-python",
|
292 |
+
"name": "python",
|
293 |
+
"nbconvert_exporter": "python",
|
294 |
+
"pygments_lexer": "ipython3",
|
295 |
+
"version": "3.10.4"
|
296 |
+
}
|
297 |
+
},
|
298 |
+
"nbformat": 4,
|
299 |
+
"nbformat_minor": 0
|
300 |
+
}
|