taka-y commited on
Commit
f4fa121
·
verified ·
1 Parent(s): 1c54906
Files changed (1) hide show
  1. README.md +317 -0
README.md CHANGED
@@ -20,3 +20,320 @@ language:
20
  This llama model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
21
 
22
  [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  This llama model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
21
 
22
  [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
23
+
24
+ # sample Use
25
+ 以下に回答コードを記載します。
26
+ ```python
27
+ # -*- coding: utf-8 -*-
28
+ """LoRA_template_unsloth2.ipynb のコピー のコピー
29
+
30
+ Automatically generated by Colab.
31
+
32
+ Original file is located at
33
+ https://colab.research.google.com/drive/14jPqmvNhz8-lIvN1xyWsjFBWW_DYs67W
34
+
35
+ ## 最終課題コンペ用 Fine-tuning テンプレート(unsloth)
36
+
37
+ 最終課題コンペにて Fine-tuning を行ないたい方に向けの Fine-tuning コードです。
38
+ Unsloth を使うことで Google Colab の無料で利用可能な T4 でも動作可能になっています。
39
+ 環境設定の難易度が高いので、慎重に取り組んでいただければと思います。
40
+
41
+
42
+ ### terminalでのconda環境構築
43
+ 事前にterminalで環境構築の必要があります。Google Colabでは不要です。
44
+ ```
45
+ # conda環境の構築
46
+ wget "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
47
+
48
+ # このコマンドではいくつか質問があるので答えて下さい。おそらくインストール先のデフォルトは/root/miniforge3かと思います
49
+ bash Miniforge3-$(uname)-$(uname -m).sh
50
+
51
+ # 以下、インストール先が/root/miniforge3であることを前提とします
52
+ export PATH=/root/miniforge3/bin:$PATH
53
+ conda init
54
+
55
+ # ここで一度、terminalを立ち上げ直す必要があります。
56
+ # 以下のリンク先に従い環境を作ります。
57
+ # https://docs.unsloth.ai/get-started/installation/conda-install
58
+ conda create --name unsloth_env python=3.10 pytorch-cuda=12.1 pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers -y
59
+ conda activate unsloth_env
60
+ pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
61
+ pip install --no-deps "trl<0.9.0" peft accelerate bitsandbytes
62
+
63
+ # jupyter notebook用のセットアップ。
64
+ conda install -c conda-forge ipykernel
65
+ python -m ipykernel install --user --name=unsloth_env --display-name "Python (unsloth_env)"
66
+ ```
67
+ """
68
+
69
+ # Google Colab の場合は上記の環境構築手順を行なわず、単にこのセルから実行していってください。
70
+ !pip uninstall unsloth -y
71
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
72
+
73
+ # Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
74
+ !pip install --upgrade torch
75
+ !pip install --upgrade xformers
76
+
77
+ # notebookでインタラクティブな表示を可能とする(ただし、うまく動かない場合あり)
78
+ !pip install ipywidgets --upgrade
79
+
80
+ # Install Flash Attention 2 for softcapping support
81
+ import torch
82
+ if torch.cuda.get_device_capability()[0] >= 8:
83
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
84
+
85
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
86
+
87
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
88
+ from unsloth import FastLanguageModel
89
+ import torch
90
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
91
+ dtype = None # Noneにしておけば自動で設定
92
+ load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
93
+
94
+ model_id = "llm-jp/llm-jp-3-13b"
95
+ new_model_id = "llm-jp-3-13b-finetune-2" #Fine-Tuningしたモデルにつけたい名前
96
+ # FastLanguageModel インスタンスを作成
97
+ model, tokenizer = FastLanguageModel.from_pretrained(
98
+ model_name=model_id,
99
+ dtype=dtype,
100
+ load_in_4bit=load_in_4bit,
101
+ trust_remote_code=True,
102
+ )
103
+
104
+ # SFT用のモデルを用意
105
+ model = FastLanguageModel.get_peft_model(
106
+ model,
107
+ r = 32,
108
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
109
+ "gate_proj", "up_proj", "down_proj",],
110
+ lora_alpha = 32,
111
+ lora_dropout = 0.05,
112
+ bias = "none",
113
+ use_gradient_checkpointing = "unsloth",
114
+ random_state = 3407,
115
+ use_rslora = False,
116
+ loftq_config = None,
117
+ max_seq_length = max_seq_length,
118
+ )
119
+
120
+ # Hugging Face Token を指定
121
+ # 下記の URL から Hugging Face Token を取得できますので下記の HF_TOKEN に入れてください。
122
+ # https://huggingface.co/settings/tokens
123
+ HF_TOKEN = "your-token" #@param {type:"string"}
124
+
125
+ # あるいは Google Colab シークレットを使う場合、左のサイドバーより🔑マークをクリック
126
+ # HF_TOKEN という名前で Value に Hugging Face Token を入れてください。
127
+ # ノートブックからのアクセスのトグルをオンにし、下記の二行のコードのコメントアウトを外してください。
128
+
129
+ # from google.colab import userdata
130
+ # HF_TOKEN=userdata.get('HF_TOKEN')
131
+
132
+ from google.colab import drive
133
+ drive.mount('/content/drive')
134
+
135
+ # 学習に用いるデータセットの指定
136
+ # 今回はLLM-jp の公開している Ichikara Instruction を使います。データにアクセスするためには申請が必要ですので、使いたい方のみ申請をしてください。
137
+ # Ichikara Instruciton を Hugging Face Hub にて公開することはお控えください。
138
+
139
+ # 下記のリンクから申請を終えた先に Google Drive があり、Distribution20241221_all というフォルダごとダウンロードしてください。
140
+ # 今回は「ichikara-instruction-003-001-1.json」を使います。必要であれば展開(!unzip など)し、データセットのパスを適切に指定してください。
141
+ # omnicampusの開発環境では取得したデータを左側にドラッグアンドドロップしてお使いください。
142
+ # Google Colab の場合も左のサイドバーよりドラッグ&ドロップでアップデートしてください。
143
+
144
+ # https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
145
+ # 関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)
146
+
147
+ from datasets import load_dataset
148
+
149
+ dataset = load_dataset("json", data_files="/content/drive/MyDrive/Colab Notebooks/LLM2024コンペ/ichikara-instruction-003-001-1.json")
150
+ # パスの指定にご注意ください。アップロードしたファイルを右クリックし、「パスをコピー」をクリック、上記の data_files と合致していることをご確認ください。Omnicampus のディレクトリ構造とは異なるかもしれません。
151
+
152
+ # 学習時のプロンプトフォーマットの定義
153
+ prompt = """### 指示
154
+ {}
155
+ ### 回答
156
+ {}"""
157
+
158
+
159
+
160
+ """
161
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
162
+ """
163
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
164
+ def formatting_prompts_func(examples):
165
+ input = examples["text"] # 入力データ
166
+ output = examples["output"] # 出力データ
167
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
168
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
169
+ pass
170
+
171
+ # # 各データにフォーマットを適用
172
+ dataset = dataset.map(
173
+ formatting_prompts_func,
174
+ num_proc= 4, # 並列処理数を指定
175
+ )
176
+
177
+ dataset
178
+
179
+ # データを確認
180
+ print(dataset["train"]["formatted_text"][3])
181
+
182
+ """
183
+ training_arguments: 学習の設定
184
+
185
+ - output_dir:
186
+ -トレーニング後のモデルを保存するディレクトリ
187
+
188
+ - per_device_train_batch_size:
189
+ - デバイスごとのトレーニングバッチサイズ
190
+
191
+ - per_device_eval_batch_size:
192
+ - デバイスごとの評価バッチサイズ
193
+
194
+ - gradient_accumulation_steps:
195
+ - 勾配を更新する前にステップを積み重ねる回数
196
+
197
+ - optim:
198
+ - オプティマイザの設定
199
+
200
+ - num_train_epochs:
201
+ - エポック数
202
+
203
+ - eval_strategy:
204
+ - 評価の戦略 ("no"/"steps"/"epoch")
205
+
206
+ - eval_steps:
207
+ - eval_strategyが"steps"のとき、評価を行うstep間隔
208
+
209
+ - logging_strategy:
210
+ - ログ記録の戦略
211
+
212
+ - logging_steps:
213
+ - ログを出力するステップ間隔
214
+
215
+ - warmup_steps:
216
+ - 学習率のウォームアップステップ数
217
+
218
+ - save_steps:
219
+ - モデルを保存するステップ間隔
220
+
221
+ - save_total_limit:
222
+ - 保存しておくcheckpointの数
223
+
224
+ - max_steps:
225
+ - トレーニングの最大ステップ数
226
+
227
+ - learning_rate:
228
+ - 学習率
229
+
230
+ - fp16:
231
+ - 16bit浮動小数点の使用設定(第8回演習を参考にすると良いです)
232
+
233
+ - bf16:
234
+ - BFloat16の使用設定
235
+
236
+ - group_by_length:
237
+ - 入力シーケンスの長さによりバッチをグループ化 (トレーニングの効率化)
238
+
239
+ - report_to:
240
+ - ログの送信先 ("wandb"/"tensorboard"など)
241
+ """
242
+ from trl import SFTTrainer
243
+ from transformers import TrainingArguments
244
+ from unsloth import is_bfloat16_supported
245
+
246
+ trainer = SFTTrainer(
247
+ model = model,
248
+ tokenizer = tokenizer,
249
+ train_dataset=dataset["train"],
250
+ max_seq_length = max_seq_length,
251
+ dataset_text_field="formatted_text",
252
+ packing = False,
253
+ args = TrainingArguments(
254
+ per_device_train_batch_size = 2,
255
+ gradient_accumulation_steps = 4,
256
+ num_train_epochs = 1,
257
+ logging_steps = 10,
258
+ warmup_steps = 10,
259
+ save_steps=100,
260
+ save_total_limit=2,
261
+ max_steps=-1,
262
+ learning_rate = 5e-5, # 学習率を1e-4から5e-5に変更(計算コストを増やさずにモデルの安定性を向上)
263
+ fp16 = not is_bfloat16_supported(),
264
+ bf16 = is_bfloat16_supported(),
265
+ group_by_length=True,
266
+ seed = 3407,
267
+ output_dir = "outputs",
268
+ report_to = "none",
269
+ ),
270
+ )
271
+
272
+ #@title 現在のメモリ使用量を表示
273
+ gpu_stats = torch.cuda.get_device_properties(0)
274
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
275
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
276
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
277
+ print(f"{start_gpu_memory} GB of memory reserved.")
278
+
279
+ #@title 学習実行
280
+ trainer_stats = trainer.train()
281
+
282
+ # ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
283
+ # データセットの読み込み。
284
+ # omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
285
+ import json
286
+ datasets = []
287
+ with open("/content/drive/MyDrive/Colab Notebooks/LLM2024コンペ/elyza-tasks-100-TV_0.jsonl", "r") as f:
288
+ item = ""
289
+ for line in f:
290
+ line = line.strip()
291
+ item += line
292
+ if item.endswith("}"):
293
+ datasets.append(json.loads(item))
294
+ item = ""
295
+
296
+ # 学習したモデルを用いてタスクを実行
297
+ from tqdm import tqdm
298
+
299
+ # 推論するためにモデルのモードを変更
300
+ FastLanguageModel.for_inference(model)
301
+
302
+ results = []
303
+ for dt in tqdm(datasets):
304
+ input = dt["input"]
305
+
306
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
307
+
308
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
309
+
310
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
311
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
312
+
313
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
314
+
315
+ # jsonlで保存
316
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
317
+ for result in results:
318
+ json.dump(result, f, ensure_ascii=False)
319
+ f.write('\n')
320
+
321
+ # モデルとトークナイザーをHugging Faceにアップロード。
322
+ # 一旦privateでアップロードしてください。
323
+ # 最終成果物が決まったらpublicにするようお願いします。
324
+ # 現在公開しているModel_Inference_Template.ipynbはunslothを想定していないためそのままでは動かない可能性があります。
325
+ model.push_to_hub_merged(
326
+ new_model_id,
327
+ tokenizer=tokenizer,
328
+ save_method="lora",
329
+ token=HF_TOKEN,
330
+ private=True
331
+ )
332
+
333
+ # model.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving
334
+ # tokenizer.push_to_hub(new_model_id, token=HF_TOKEN) # Online saving
335
+ ```
336
+
337
+
338
+
339
+