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