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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# PyTorch Differential Privacy Experiment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -qqq torch torchvision opacus numpy pandas\n",
    "%pip install -qqq wandb datasets tqdm\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch \n",
    "from dotenv import load_dotenv\n",
    "import wandb \n",
    "import logging\n",
    "import shutil\n",
    "import sys\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "import argparse\n",
    "from collections import Counter\n",
    "from pathlib import Path\n",
    "from statistics import mean\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from opacus import PrivacyEngine\n",
    "from opacus.layers import DPGRU, DPLSTM, DPRNN\n",
    "from torch.nn.utils.rnn import pad_sequence\n",
    "from torch.utils.data import DataLoader, Dataset\n",
    "from tqdm import tqdm, tqdm_notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n",
    "if os.path.exists('.env'):\n",
    "    load_dotenv('.env')\n",
    "device\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "logging.basicConfig(\n",
    "    format=\"%(asctime)s:%(levelname)s:%(message)s\",\n",
    "    datefmt=\"%m/%d/%Y %H:%M:%S\",\n",
    "    stream=sys.stdout,\n",
    ")\n",
    "logger = logging.getLogger(\"ddp\")\n",
    "logger.setLevel(level=logging.INFO)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wandb.login(key=os.getenv('WANDB_API_KEY'))\n",
    "wandb.init(project=\"verida-pii\", name=\"deberta_finetune\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fine Tuning w/ Unsloth (Colab Only)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Datasets\n",
    "# Original data_name = 'Ezi/medical_and_legislators_synthetic'\n",
    "# Tutorial: https://huggingface.co/blog/Andyrasika/finetune-unsloth-qlora\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the major and minor version of the current CUDA device (GPU)\n",
    "major_version, minor_version = torch.cuda.get_device_capability()\n",
    "\n",
    "# Apply the following if the GPU has Ampere or Hopper architecture (RTX 30xx, RTX 40xx, A100, H100, L40, etc.)\n",
    "if major_version >= 8:\n",
    "    # Install the Unsloth library for Ampere and Hopper architecture from GitHub\n",
    "    !pip install \"unsloth[colab_ampere] @ git+https://github.com/unslothai/unsloth.git\" -q\n",
    "\n",
    "# Apply the following for older GPUs (V100, Tesla T4, RTX 20xx, etc.)\n",
    "else:\n",
    "    # Install the Unsloth library for older GPUs from GitHub\n",
    "    !pip install \"unsloth[colab] @ git+https://github.com/unslothai/unsloth.git\" -q\n",
    "\n",
    "# Placeholder statement (does nothing)\n",
    "pass\n",
    "\n",
    "# Install the Hugging Face Transformers library from GitHub, which allows native 4-bit loading\n",
    "!pip install \"git+https://github.com/huggingface/transformers.git\" -q\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, AutoModelForTokenClassification\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"lakshyakh93/deberta_finetuned_pii\")\n",
    "model = AutoModelForTokenClassification.from_pretrained(\"lakshyakh93/deberta_finetuned_pii\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = FastLanguageModel.get_peft_model(\n",
    "    model,\n",
    "    # Specify the existing model\n",
    "\n",
    "    r=16,  # Choose any positive number! Recommended values include 8, 16, 32, 64, 128, etc.\n",
    "    # Rank parameter for LoRA. The smaller this value, the fewer parameters will be modified.\n",
    "\n",
    "    target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n",
    "                    \"gate_proj\", \"up_proj\", \"down_proj\",],\n",
    "    # Specify the modules to which LoRA will be applied\n",
    "\n",
    "    lora_alpha=16,\n",
    "    # Alpha parameter for LoRA. This value determines the strength of the applied LoRA.\n",
    "\n",
    "    lora_dropout=0,  # Currently, only supports dropout = 0\n",
    "    # Dropout rate for LoRA. Currently supports only 0.\n",
    "\n",
    "    bias=\"none\",  # Currently, only supports bias = \"none\"\n",
    "    # Bias usage setting. Currently supports only the setting without bias.\n",
    "\n",
    "    use_gradient_checkpointing=True,\n",
    "    # Whether to use gradient checkpointing to improve memory efficiency\n",
    "\n",
    "    random_state=3407,\n",
    "    # Seed value for random number generation\n",
    "\n",
    "    max_seq_length=max_seq_length,\n",
    "    # Set the maximum sequence length\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# @TODO - Add the relevant prompt\n",
    "alpaca_prompt = \"\"\"Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n",
    "\n",
    "### Instruction:\n",
    "{}\n",
    "\n",
    "### Input:\n",
    "{}\n",
    "\n",
    "### Response:\n",
    "{}\"\"\"\n",
    "# Define the prompt format for the Alpaca dataset\n",
    "\n",
    "def formatting_prompts_func(examples):\n",
    "    # Define a function to format each example in the dataset\n",
    "\n",
    "    instructions = examples[\"instruction\"]\n",
    "    inputs       = examples[\"input\"]\n",
    "    outputs      = examples[\"output\"]\n",
    "    # Get instructions, inputs, and outputs\n",
    "\n",
    "    texts = []\n",
    "    for instruction, input, output in zip(instructions, inputs, outputs):\n",
    "        # Generate text by combining instructions, inputs, and outputs\n",
    "\n",
    "        text = alpaca_prompt.format(instruction, input, output)\n",
    "        # Format the text according to the prompt format\n",
    "\n",
    "        texts.append(text)\n",
    "    return { \"text\" : texts, }\n",
    "    # Return a list of formatted texts\n",
    "\n",
    "pass\n",
    "# Placeholder (does nothing)\n",
    "\n",
    "from datasets import load_dataset\n",
    "# Import the load_dataset function from the datasets library\n",
    "\n",
    "dataset = load_dataset(\"yahma/alpaca-cleaned\", split=\"train\")\n",
    "# Load the training data of the cleaned version of the Alpaca dataset from yahma\n",
    "\n",
    "dataset = dataset.map(formatting_prompts_func, batched=True,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from trl import SFTTrainer\n",
    "# Import SFTTrainer from the TRL library\n",
    "\n",
    "from transformers import TrainingArguments\n",
    "# Import TrainingArguments from the Transformers library\n",
    "\n",
    "trainer = SFTTrainer(\n",
    "    # Initialize the SFTTrainer\n",
    "\n",
    "    model=model,\n",
    "    # Specify the model to be used\n",
    "\n",
    "    train_dataset=dataset,\n",
    "    # Specify the training dataset\n",
    "\n",
    "    dataset_text_field=\"text\",\n",
    "    # Specify the text field in the dataset\n",
    "\n",
    "    max_seq_length=max_seq_length,\n",
    "    # Specify the maximum sequence length\n",
    "\n",
    "    args=TrainingArguments(\n",
    "        # Specify training arguments\n",
    "\n",
    "        per_device_train_batch_size=2,\n",
    "        # Specify the training batch size per device\n",
    "\n",
    "        gradient_accumulation_steps=4,\n",
    "        # Specify the number of steps for gradient accumulation\n",
    "\n",
    "        warmup_steps=5,\n",
    "        # Specify the number of warm-up steps\n",
    "\n",
    "        max_steps=20,\n",
    "        # Specify the maximum number of steps\n",
    "\n",
    "        learning_rate=2e-4,\n",
    "        # Specify the learning rate\n",
    "\n",
    "        fp16=not torch.cuda.is_bf16_supported(),\n",
    "        # Set whether to use 16-bit floating-point precision (fp16)\n",
    "\n",
    "        bf16=torch.cuda.is_bf16_supported(),\n",
    "        # Set whether to use Bfloat16\n",
    "\n",
    "        logging_steps=1,\n",
    "        # Specify the logging steps\n",
    "\n",
    "        optim=\"adamw_8bit\",\n",
    "        # Specify the optimizer (here using 8-bit AdamW)\n",
    "\n",
    "        weight_decay=0.01,\n",
    "        # Specify the weight decay value\n",
    "\n",
    "        lr_scheduler_type=\"linear\",\n",
    "        # Specify the type of learning rate scheduler (linear)\n",
    "\n",
    "        seed=3407,\n",
    "        # Specify the random seed\n",
    "\n",
    "        output_dir=\"outputs\",\n",
    "        # Specify the output directory\n",
    "\n",
    "    ),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gpu_stats = torch.cuda.get_device_properties(0)\n",
    "# Get properties of the GPU device at index 0\n",
    "\n",
    "start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)\n",
    "# Get the maximum reserved GPU memory in GB and round to 3 decimal places\n",
    "\n",
    "max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)\n",
    "# Get the total GPU memory in GB and round to 3 decimal places\n",
    "\n",
    "print(f\"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.\")\n",
    "# Display the GPU name and maximum memory\n",
    "\n",
    "print(f\"{start_gpu_memory} GB of memory reserved.\")\n",
    "# Display the reserved memory amount"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer_stats = trainer.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convert to GGUF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def colab_quantize_to_gguf(save_directory, quantization_method=\"q4_k_m\"):\n",
    "    # Define a function for conversion to GGUF\n",
    "\n",
    "    from transformers.models.llama.modeling_llama import logger\n",
    "    import os\n",
    "    # Import necessary libraries\n",
    "\n",
    "    logger.warning_once(\n",
    "        \"Unsloth: `colab_quantize_to_gguf` is still in development mode.\\n\"\\\n",
    "        \"If anything errors or breaks, please file a ticket on Github.\\n\"\\\n",
    "        \"Also, if you used this successfully, please tell us on Discord!\"\n",
    "    )\n",
    "    # Warn that it's still in development mode and encourage reporting any issues\n",
    "\n",
    "    # From https://mlabonne.github.io/blog/posts/Quantize_Llama_2_models_using_ggml.html\n",
    "    ALLOWED_QUANTS = \\\n",
    "    {\n",
    "        # Define currently allowed quantization methods\n",
    "        # Including descriptions for each quantization method\n",
    "        \"q2_k\"   : \"Uses Q4_K for the attention.vw and feed_forward.w2 tensors, Q2_K for the other tensors.\",\n",
    "        \"q3_k_l\" : \"Uses Q5_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K\",\n",
    "        \"q3_k_m\" : \"Uses Q4_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K\",\n",
    "        \"q3_k_s\" : \"Uses Q3_K for all tensors\",\n",
    "        \"q4_0\"   : \"Original quant method, 4-bit.\",\n",
    "        \"q4_1\"   : \"Higher accuracy than q4_0 but not as high as q5_0. However has quicker inference than q5 models.\",\n",
    "        \"q4_k_m\" : \"Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q4_K\",\n",
    "        \"q4_k_s\" : \"Uses Q4_K for all tensors\",\n",
    "        \"q5_0\"   : \"Higher accuracy, higher resource usage and slower inference.\",\n",
    "        \"q5_1\"   : \"Even higher accuracy, resource usage and slower inference.\",\n",
    "        \"q5_k_m\" : \"Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q5_K\",\n",
    "        \"q5_k_s\" : \"Uses Q5_K for all tensors\",\n",
    "        \"q6_k\"   : \"Uses Q8_K for all tensors\",\n",
    "        \"q8_0\"   : \"Almost indistinguishable from float16. High resource use and slow. Not recommended for most users.\",\n",
    "    }\n",
    "\n",
    "    if quantization_method not in ALLOWED_QUANTS.keys():\n",
    "        # If the specified quantization method is not allowed, raise an error\n",
    "        error = f\"Unsloth: Quant method = [{quantization_method}] not supported. Choose from below:\\n\"\n",
    "        for key, value in ALLOWED_QUANTS.items():\n",
    "            error += f\"[{key}] => {value}\\n\"\n",
    "        raise RuntimeError(error)\n",
    "\n",
    "    # Display information about the conversion\n",
    "    print_info = \\\n",
    "        f\"==((====))==  Unsloth: Conversion from QLoRA to GGUF information\\n\"\\\n",
    "        f\"   \\\\\\   /|    [0] Installing llama.cpp will take 3 minutes.\\n\"\\\n",
    "        f\"O^O/ \\_/ \\\\    [1] Converting HF to GUUF 16bits will take 3 minutes.\\n\"\\\n",
    "        f\"\\        /    [2] Converting GGUF 16bits to q4_k_m will take 20 minutes.\\n\"\\\n",
    "        f' \"-____-\"     In total, you will have to wait around 26 minutes.\\n'\n",
    "    print(print_info)\n",
    "    # Display information about the conversion process\n",
    "\n",
    "    if not os.path.exists(\"llama.cpp\"):\n",
    "        # If llama.cpp does not exist, install it\n",
    "        print(\"Unsloth: [0] Installing llama.cpp. This will take 3 minutes...\")\n",
    "        !git clone https://github.com/ggerganov/llama.cpp\n",
    "        !cd llama.cpp && make clean && LLAMA_CUBLAS=1 make -j\n",
    "        !pip install gguf protobuf\n",
    "        pass\n",
    "\n",
    "    print(\"Unsloth: Starting conversion from HF to GGUF 16bit...\")\n",
    "    # Display that conversion from HF to GGUF 16bit is starting\n",
    "    # print(\"Unsloth: [1] Converting HF into GGUF 16bit. This will take 3 minutes...\")\n",
    "    !python llama.cpp/convert.py {save_directory} \\\n",
    "        --outfile {save_directory}-unsloth.gguf \\\n",
    "        --outtype f16\n",
    "\n",
    "    print(\"Unsloth: Starting conversion from GGUF 16bit to q4_k_m...\")\n",
    "    # Display that conversion from GGUF 16bit to the specified quantization method is starting\n",
    "    # print(\"Unsloth: [2] Converting GGUF 16bit into q4_k_m. This will take 20 minutes...\")\n",
    "    final_location = f\"./{save_directory}-{quantization_method}-unsloth.gguf\"\n",
    "    !./llama.cpp/quantize ./{save_directory}-unsloth.gguf \\\n",
    "        {final_location} {quantization_method}\n",
    "\n",
    "    print(f\"Unsloth: Output location: {final_location}\")\n",
    "    # Display the output location of the converted file\n",
    "pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from unsloth import unsloth_save_model\n",
    "# Import the unsloth_save_model function from the Unsloth library\n",
    "\n",
    "# unsloth_save_model has the same args as model.save_pretrained\n",
    "# unsloth_save_model has the same arguments as model.save_pretrained\n",
    "unsloth_save_model(model, tokenizer, \"output_model\", push_to_hub=False, token=None)\n",
    "# Save the model and tokenizer as \"output_model\". Do not push to the Hugging Face Hub\n",
    "\n",
    "colab_quantize_to_gguf(\"output_model\", quantization_method=\"q4_k_m\")\n",
    "# Convert \"output_model\" to GGUF format. Use the quantization method \"q4_k_m\""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}