LLM-FineTuning-Large-Language-Models

Форк
0
/
Jamba_Finetuning_Colab-Pro.ipynb 
250 строк · 8.1 Кб
1
{
2
  "cells": [
3
    {
4
      "cell_type": "markdown",
5
      "metadata": {
6
        "id": "sOfeXQXBtLVO"
7
      },
8
      "source": [
9
        "# Fine-tune Jamba-v0.1 on A100 - 40GB VRAM using QLoRA in Google Colab Pro"
10
      ]
11
    },
12
    {
13
      "cell_type": "code",
14
      "execution_count": null,
15
      "metadata": {
16
        "id": "panZSjSVq6Cc"
17
      },
18
      "outputs": [],
19
      "source": [
20
        "!pip install ninja packaging\n",
21
        "!pip install flash-attn --no-build-isolation\n",
22
        "!pip install -U \"transformers>=4.39.0\"\n",
23
        "!pip install mamba-ssm \"causal-conv1d>=1.2.0\"\n",
24
        "!pip install peft trl bitsandbytes"
25
      ]
26
    },
27
    {
28
      "cell_type": "code",
29
      "execution_count": null,
30
      "metadata": {},
31
      "outputs": [],
32
      "source": [
33
        "!nvidia-smi"
34
      ]
35
    },
36
    {
37
      "cell_type": "code",
38
      "execution_count": null,
39
      "metadata": {
40
        "id": "zhmfYJMopcB3"
41
      },
42
      "outputs": [],
43
      "source": [
44
        "from datasets import load_dataset\n",
45
        "from trl import SFTTrainer\n",
46
        "from peft import LoraConfig\n",
47
        "from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, BitsAndBytesConfig"
48
      ]
49
    },
50
    {
51
      "cell_type": "code",
52
      "execution_count": null,
53
      "metadata": {},
54
      "outputs": [],
55
      "source": [
56
        "model_id = \"ai21labs/Jamba-v0.1\"\n",
57
        "\n",
58
        "quantization_config = BitsAndBytesConfig(\n",
59
        "    load_in_4bit=True,\n",
60
        "    llm_int4_skip_modules=[\"mamba\"]\n",
61
        ")"
62
      ]
63
    },
64
    {
65
      "cell_type": "markdown",
66
      "metadata": {},
67
      "source": [
68
        "📌 The `llm_int8_skip_modules` parameter allows you to specify a list of module names that should be skipped or excluded from the quantization process. These modules will remain in their original data type (typically 32-bit floating-point) without being converted to 8-bit integers.\n",
69
        "\n",
70
        "📌 This parameter is particularly useful for models with multiple heads or output layers in different parts of the model architecture, not necessarily at the last position. For example, in the case of Causal Language Models (CausalLM), the last layer (often called `lm_head`) is responsible for generating the final output logits or probabilities. Keeping this layer in its original data type can help preserve accuracy and prevent potential degradation caused by quantizing this crucial output layer.\n",
71
        "\n",
72
        "📌 The strategic positioning of these heads is crucial for the model's effectiveness. Placing a head at a specific layer allows it to leverage the representations formed up to that point, which might contain the most relevant information for the head's task. \n",
73
        "\n",
74
        "📌 In the context of models like Jukebox, which may have multiple output heads positioned at various locations within the model architecture, it's crucial to maintain the precision of certain modules for maintaining overall model performance. For example, if a model utilizes various heads to generate different aspects of output, converting all modules to int8 might degrade the quality of the output or the model's effectiveness due to reduced numerical precision."
75
      ]
76
    },
77
    {
78
      "cell_type": "code",
79
      "execution_count": null,
80
      "metadata": {
81
        "colab": {
82
          "background_save": true
83
        },
84
        "id": "ktiiRqlgp8bI"
85
      },
86
      "outputs": [],
87
      "source": [
88
        "tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
89
        "model = AutoModelForCausalLM.from_pretrained(\n",
90
        "    model_id,\n",
91
        "    trust_remote_code=True,\n",
92
        "    device_map='auto',\n",
93
        "    attn_implementation=\"flash_attention_2\",\n",
94
        "    quantization_config=quantization_config,\n",
95
        "    use_mamba_kernels=False #Disabling the mamba kernels since I have a recurrent error.\n",
96
        "    )"
97
      ]
98
    },
99
    {
100
      "cell_type": "code",
101
      "execution_count": null,
102
      "metadata": {
103
        "colab": {
104
          "background_save": true
105
        },
106
        "id": "WNZbOoUKrCBt"
107
      },
108
      "outputs": [],
109
      "source": [
110
        "model.save_pretrained(\"/content/drive/MyDrive/jamba_ft\")\n",
111
        "tokenizer.save_pretrained(\"/content/drive/MyDrive/jamba_ft\")"
112
      ]
113
    },
114
    {
115
      "cell_type": "code",
116
      "execution_count": null,
117
      "metadata": {
118
        "colab": {
119
          "background_save": true
120
        },
121
        "id": "I2TWny5tqU8I"
122
      },
123
      "outputs": [],
124
      "source": [
125
        "dataset = load_dataset(\"Abirate/english_quotes\", split=\"train\")"
126
      ]
127
    },
128
    {
129
      "cell_type": "code",
130
      "execution_count": null,
131
      "metadata": {
132
        "colab": {
133
          "background_save": true
134
        },
135
        "id": "ee1IMXszqWyU"
136
      },
137
      "outputs": [],
138
      "source": [
139
        "training_args = TrainingArguments(\n",
140
        "    output_dir=\"./results\",\n",
141
        "    num_train_epochs=3,\n",
142
        "    per_device_train_batch_size=4,\n",
143
        "    logging_dir='./logs',\n",
144
        "    logging_steps=10,\n",
145
        "    learning_rate=2e-3 # 2.5e-5\n",
146
        ")"
147
      ]
148
    },
149
    {
150
      "cell_type": "code",
151
      "execution_count": null,
152
      "metadata": {
153
        "colab": {
154
          "background_save": true
155
        },
156
        "id": "iyipI7FyqZHI"
157
      },
158
      "outputs": [],
159
      "source": [
160
        "lora_config = LoraConfig(\n",
161
        "    r=8,\n",
162
        "    target_modules=[\"embed_tokens\", \"x_proj\", \"in_proj\", \"out_proj\"],\n",
163
        "    task_type=\"CAUSAL_LM\",\n",
164
        "    bias=\"none\"\n",
165
        ")"
166
      ]
167
    },
168
    {
169
      "cell_type": "markdown",
170
      "metadata": {},
171
      "source": [
172
        "## Note the structure of our training dataset\n",
173
        "\n",
174
        "`english_quotes` is a dataset of all the quotes retrieved from goodreads quotes. This dataset can be used for multi-label text classification and text generation. \n",
175
        "\n",
176
        "The dataset can be used to train a model to generate quotes by fine-tuning an existing pretrained model or to train a model for text-classification, which consists of classifying quotes by author as well as by topic (using tags). \n",
177
        "\n",
178
        "![](assets/2024-03-31-19-30-22.png)"
179
      ]
180
    },
181
    {
182
      "cell_type": "code",
183
      "execution_count": null,
184
      "metadata": {
185
        "colab": {
186
          "background_save": true
187
        },
188
        "id": "6gMx9J6Eqas3"
189
      },
190
      "outputs": [],
191
      "source": [
192
        "trainer = SFTTrainer(\n",
193
        "    model=model,\n",
194
        "    tokenizer=tokenizer,\n",
195
        "    args=training_args,\n",
196
        "    peft_config=lora_config,\n",
197
        "    train_dataset=dataset,\n",
198
        "    dataset_text_field=\"quote\",\n",
199
        "    max_seq_length=256\n",
200
        ")"
201
      ]
202
    },
203
    {
204
      "cell_type": "markdown",
205
      "metadata": {},
206
      "source": [
207
        "`dataset_text_field` (Optional[str]) — The name of the text field of the dataset, in case this is passed by a user, the trainer will automatically create a ConstantLengthDataset based on the dataset_text_field argument.\n",
208
        "\n",
209
        "\n",
210
        "So `dataset_text_field` will be used for training only if `formatting_func` is `None`.\n",
211
        "\n",
212
        "You should be careful because if you do this:\n",
213
        "\n",
214
        "`dataset_text_field='instruction'`\n",
215
        "\n",
216
        "SFTTrainer will only read the text saved in `train_dataset['instruction']`.\n",
217
        "\n",
218
        "So that the model being trained will only learn to predict the instructions without the answers."
219
      ]
220
    },
221
    {
222
      "cell_type": "code",
223
      "execution_count": null,
224
      "metadata": {
225
        "id": "9gGKIIyQrZTi"
226
      },
227
      "outputs": [],
228
      "source": [
229
        "trainer.train()"
230
      ]
231
    }
232
  ],
233
  "metadata": {
234
    "accelerator": "GPU",
235
    "colab": {
236
      "gpuType": "A100",
237
      "machine_shape": "hm",
238
      "provenance": []
239
    },
240
    "kernelspec": {
241
      "display_name": "Python 3",
242
      "name": "python3"
243
    },
244
    "language_info": {
245
      "name": "python"
246
    }
247
  },
248
  "nbformat": 4,
249
  "nbformat_minor": 0
250
}
251

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.