yunda commited on
Commit
a9af8b7
·
verified ·
1 Parent(s): 46eca17

Update README.md

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