Spaces:
Runtime error
Runtime error
File size: 10,570 Bytes
feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb e51648a feee6eb |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"from trl import SFTTrainer\n",
"from peft import LoraConfig, get_peft_model\n",
"\n",
"import os\n",
"from uuid import uuid4\n",
"import pandas as pd\n",
"\n",
"import subprocess\n",
"import evaluate\n",
"import transformers\n",
"from transformers import AutoModelForCausalLM, AutoTokenizer\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def max_token_len(dataset):\n",
" max_seq_length = 0\n",
" for row in dataset:\n",
" tokens = len(tokenizer(row['text'])['input_ids'])\n",
" if tokens > max_seq_length:\n",
" max_seq_length = tokens\n",
" return max_seq_length"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# model_name='TinyLlama/TinyLlama-1.1B-Chat-v0.1'\n",
"model_name = 'mistralai/Mistral-7B-v0.1'\n",
"# model_name = 'distilbert-base-uncased'\n",
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"model_max_length = tokenizer.model_max_length\n",
"print(\"Model Max Length:\", model_max_length)\n",
"\n",
"# dataset = load_dataset(\"imdb\", split=\"train\")\n",
"dataset_name = 'ai-aerospace/ams_data_train_generic_v0.1_100'\n",
"dataset = load_dataset(dataset_name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Write dataset files into data directory\n",
"data_directory = './fine_tune_data/'\n",
"\n",
"# Create the data directory if it doesn't exist\n",
"os.makedirs(data_directory, exist_ok=True)\n",
"\n",
"# Write the train data to a CSV file\n",
"train_data='train_data'\n",
"train_filename = os.path.join(data_directory, train_data)\n",
"dataset['train'].to_pandas().to_csv(train_filename+'.csv', columns=['text'], index=False)\n",
"max_token_length_train=max_token_len(dataset['train'])\n",
"print('Max token length train: '+str(max_token_length_train))\n",
"\n",
"# Write the validation data to a CSV file\n",
"validation_data='validation_data'\n",
"validation_filename = os.path.join(data_directory, validation_data)\n",
"dataset['validation'].to_pandas().to_csv(validation_filename+'.csv', columns=['text'], index=False)\n",
"max_token_length_validation=max_token_len(dataset['validation'])\n",
"print('Max token length validation: '+str(max_token_length_validation))\n",
" \n",
"max_token_length=max(max_token_length_train,max_token_length_validation)\n",
"# max_token_length=max_token_length_train\n",
"if max_token_length > model_max_length:\n",
" raise ValueError(\"Maximum token length exceeds model limits.\")\n",
"block_size=2*max_token_length\n",
"print('Block size: '+str(block_size))\n",
"\n",
"# Define project parameters\n",
"username='ai-aerospace'\n",
"project_name='./llms/'+'ams_data_train-100_'+str(uuid4())\n",
"repo_name='ams-data-train-100-'+str(uuid4())\n",
"\n",
"model_params={\n",
" \"project_name\": project_name,\n",
" \"model_name\": model_name,\n",
" \"repo_id\": username+'/'+repo_name,\n",
" \"train_data\": train_data,\n",
" \"validation_data\": validation_data,\n",
" \"data_directory\": data_directory,\n",
" \"block_size\": block_size,\n",
" \"model_max_length\": max_token_length,\n",
" \"logging_steps\": -1,\n",
" \"evaluation_strategy\": \"epoch\",\n",
" \"save_total_limit\": 1,\n",
" \"save_strategy\": \"epoch\",\n",
" \"mixed_precision\": \"fp16\",\n",
" \"lr\": 0.00003,\n",
" \"epochs\": 3,\n",
" \"batch_size\": 2,\n",
" \"warmup_ratio\": 0.1,\n",
" \"gradient_accumulation\": 1,\n",
" \"optimizer\": \"adamw_torch\",\n",
" \"scheduler\": \"linear\",\n",
" \"weight_decay\": 0,\n",
" \"max_grad_norm\": 1,\n",
" \"seed\": 42,\n",
" \"quantization\": \"int4\",\n",
" \"lora_r\": 16,\n",
" \"lora_alpha\": 32,\n",
" \"lora_dropout\": 0.05\n",
"}\n",
"for key, value in model_params.items():\n",
" os.environ[key] = str(value)\n",
"\n",
"print(model_params)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"args_custom=transformers.TrainingArguments(\n",
" per_device_train_batch_size=model_params['batch_size'],\n",
" per_device_eval_batch_size=model_params['batch_size'],\n",
" gradient_accumulation_steps=model_params['gradient_accumulation'],\n",
" warmup_ratio=model_params['warmup_ratio'],\n",
" num_epochs=model_params['epochs'],\n",
" learning_rate=model_params['lr'],\n",
" fp16=True,\n",
" logging_steps=model_params['logging_steps'],\n",
" save_total_limit=model_params['save_total_limit'],\n",
" evaluation_strategy=model_params['evaluation_strategy'],\n",
" metric_for_best_model=\"f1\",\n",
" output_dir='model_outputs',\n",
" logging_dir='model_outputs',\n",
" optim=model_params['optimizer'],\n",
" max_grad_norm=model_params['max_grad_norm'],\n",
" weight_decay=model_params['weight_decay'],\n",
" lr_scheduler_type=model_params['scheduler']\n",
")\n",
"\n",
"# Args from medium article\n",
"args_medium=transformers.TrainingArguments(\n",
" per_device_train_batch_size=8,\n",
" per_device_eval_batch_size=32,\n",
" gradient_accumulation_steps=4,\n",
" warmup_steps=100,\n",
" max_steps=12276,\n",
" learning_rate=2e-4,\n",
" fp16=True,\n",
" eval_steps= 1000,\n",
" logging_steps=1000,\n",
" save_steps=1000,\n",
" evaluation_strategy=\"steps\",\n",
" do_eval=True,\n",
" load_best_model_at_end=True,\n",
" metric_for_best_model=\"f1\",\n",
" output_dir='model_outputs',\n",
" logging_dir='model_outputs',\n",
" remove_unused_columns =False, \n",
" report_to='wandb' # enable logging to W&B\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"### Start trainer\n",
"# trainer = SFTTrainer(\n",
"# model_name,\n",
"# train_dataset=dataset,\n",
"# dataset_text_field=\"text\",\n",
"# max_seq_length=512,\n",
"# )\n",
"\n",
"peft_config = LoraConfig(\n",
" r=model_params['lora_r'],\n",
" lora_alpha=model_params['lora_alpha'],\n",
" lora_dropout=model_params['lora_dropout']\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load the model\n",
"model = AutoModelForCausalLM.from_pretrained(\n",
" model_name,\n",
" load_in_4bit=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Setting up the LoRA model\n",
"# import os\n",
"# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n",
"# from transformers import AutoModelForSequenceClassification\n",
"# from peft import LoraConfig, get_peft_model, TaskType\n",
"\n",
"# MODEL =\"xlm-roberta-large\"\n",
"\n",
"# config = LoraConfig(\n",
"# task_type=\"SEQ_CLS\",\n",
"# r=16,\n",
"# lora_alpha=16,\n",
"# target_modules=[\"query\", \"value\"], # Targets the attention blocks in the model\n",
"# lora_dropout=0.1,\n",
"# bias=\"none\",\n",
"# modules_to_save=[\"classifier\"],\n",
"# )\n",
"\n",
"# model = AutoModelForSequenceClassification.from_pretrained(\n",
"# MODEL,\n",
"# num_labels=len(unique_subissues),\n",
"# id2label=id2label,\n",
"# label2id=label2id,\n",
"# ignore_mismatched_sizes=True\n",
"# ) \n",
"\n",
"lora_model = get_peft_model(model, peft_config)\n",
"lora_model.print_trainable_parameters()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# trainer = SFTTrainer(\n",
"# model,\n",
"# train_dataset=dataset,\n",
"# dataset_text_field=\"text\",\n",
"# peft_config=peft_config,\n",
"# max_seq_length=model_params['model_max_length']\n",
"# )\n",
"\n",
"# trainer.train()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f1_metric = evaluate.load(\"f1\")\n",
"recall_metric = evaluate.load(\"recall\")\n",
"accuracy_metric = evaluate.load(\"accuracy\")\n",
"precision_metric = evaluate.load(\"precision\")\n",
"\n",
"def compute_metrics(eval_pred):\n",
" logits, labels = eval_pred\n",
" predictions = np.argmax(logits, axis=-1)\n",
" results = {}\n",
" results.update(f1_metric.compute(predictions=predictions, references = labels, average=\"macro\"))\n",
" results.update(recall_metric.compute(predictions=predictions, references = labels, average=\"macro\"))\n",
" results.update(accuracy_metric.compute(predictions=predictions, references = labels))\n",
" results.update(precision_metric.compute(predictions=predictions, references = labels, average=\"macro\"))\n",
"\n",
" return results\n",
"\n",
"# See https://towardsdatascience.com/fine-tune-your-llm-without-maxing-out-your-gpu-db2278603d78 for details\n",
"trainer = transformers.Trainer(\n",
" model=lora_model,\n",
" train_dataset=model_params['train_data'],\n",
" eval_dataset=model_params['validation_data'],\n",
" compute_metrics=compute_metrics,\n",
" args=args_custom\n",
")\n",
"trainer.train()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|