okaba815 commited on
Commit
e0fb38b
·
verified ·
1 Parent(s): 04bb877

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +330 -0
README.md CHANGED
@@ -20,3 +20,333 @@ 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
+
26
+
27
+ モデルのuploadまで
28
+
29
+ '''
30
+
31
+ %%capture #結果を非表示にするセルマジックコマンド
32
+ # Google Colab の場合は上記の環境構築手順を行なわず、単にこのセルから実行していってください。
33
+ !pip uninstall unsloth -y
34
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
35
+
36
+ %%capture #結果を非表示にするセルマジックコマンド
37
+ # Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
38
+ !pip install --upgrade torch
39
+ !pip install --upgrade xformers
40
+
41
+ %%capture #結果を非表示にするセルマジックコマンド
42
+ # notebookでインタラクティブな表示を可能とする(ただし、うまく動かない場合あり)
43
+ # Google Colabでは実行不要
44
+ !pip install ipywidgets --upgrade
45
+
46
+ # Install Flash Attention 2 for softcapping support
47
+ import torch
48
+ if torch.cuda.get_device_capability()[0] >= 8:
49
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
50
+
51
+ HF_TOKEN = "your token"
52
+
53
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
54
+
55
+ from unsloth import FastLanguageModel
56
+ import torch
57
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
58
+ dtype = None # Noneにしておけば自動で設定
59
+ load_in_4bit = True # 今回は13Bモデルを扱うためTrue
60
+
61
+ model_id = "llm-jp/llm-jp-3-13b"
62
+ new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
63
+ # FastLanguageModel インスタンスを作成
64
+ model, tokenizer = FastLanguageModel.from_pretrained(
65
+ model_name=model_id,
66
+ dtype=dtype,
67
+ load_in_4bit=load_in_4bit,
68
+ trust_remote_code=True,
69
+ )
70
+
71
+ # SFT用のモデルを用意
72
+ model = FastLanguageModel.get_peft_model(
73
+ model,
74
+ r = 32,
75
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
76
+ "gate_proj", "up_proj", "down_proj",],
77
+ lora_alpha = 32,
78
+ lora_dropout = 0.05,
79
+ bias = "none",
80
+ use_gradient_checkpointing = "unsloth",
81
+ random_state = 3407,
82
+ use_rslora = False,
83
+ loftq_config = None,
84
+ max_seq_length = max_seq_length,
85
+ )
86
+
87
+ # 学習に用いるデータセットの指定
88
+ from datasets import load_dataset
89
+
90
+ dataset = load_dataset("json", data_files="./ichikara-instruction-003-001-1.json")
91
+
92
+ # 学習時のプロンプトフォーマットの定義
93
+ prompt = """### 指示
94
+ {}
95
+ ### 回答
96
+ {}"""
97
+
98
+
99
+ """
100
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
101
+ """
102
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
103
+ def formatting_prompts_func(examples):
104
+ input = examples["text"] # 入力データ
105
+ output = examples["output"] # 出力データ
106
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
107
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
108
+ pass
109
+
110
+ # # 各データにフォーマットを適用
111
+ dataset = dataset.map(
112
+ formatting_prompts_func,
113
+ num_proc= 4, # 並列処理数を指定
114
+ )
115
+
116
+ dataset
117
+
118
+ # データを確認
119
+ print(dataset["train"]["formatted_text"][3])
120
+
121
+ """
122
+ training_arguments: 学習の設定
123
+
124
+ - output_dir:
125
+ -トレーニング後のモデルを保存するディレクトリ
126
+
127
+ - per_device_train_batch_size:
128
+ - デバイスごとのトレーニングバッチサイズ
129
+
130
+ - per_device_eval_batch_size:
131
+ - デバイスごとの評価バッチサイズ
132
+
133
+ - gradient_accumulation_steps:
134
+ - 勾配を更新する前にステップを積み重ねる回数
135
+
136
+ - optim:
137
+ - オプティマイザの設定
138
+
139
+ - num_train_epochs:
140
+ - エポック数
141
+
142
+ - eval_strategy:
143
+ - 評価の戦略 ("no"/"steps"/"epoch")
144
+
145
+ - eval_steps:
146
+ - eval_strategyが"steps"のとき、評価を行うstep間隔
147
+
148
+ - logging_strategy:
149
+ - ログ記録の戦略
150
+
151
+ - logging_steps:
152
+ - ログを出力するステップ間隔
153
+
154
+ - warmup_steps:
155
+ - 学習率のウォームアップステップ数
156
+
157
+ - save_steps:
158
+ - モデルを保存するステップ間隔
159
+
160
+ - save_total_limit:
161
+ - 保存しておくcheckpointの数
162
+
163
+ - max_steps:
164
+ - トレーニングの最大ステップ数
165
+
166
+ - learning_rate:
167
+ - 学習率
168
+
169
+ - fp16:
170
+ - 16bit浮動小数点の使用設定(第8回演習を参考にすると良いです)
171
+
172
+ - bf16:
173
+ - BFloat16の使用設定
174
+
175
+ - group_by_length:
176
+ - 入力シーケンスの長さによりバッチをグループ化 (トレーニングの効率化)
177
+
178
+ - report_to:
179
+ - ログの送信先 ("wandb"/"tensorboard"など)
180
+ """
181
+ from trl import SFTTrainer
182
+ from transformers import TrainingArguments
183
+ from unsloth import is_bfloat16_supported
184
+
185
+ trainer = SFTTrainer(
186
+ model = model,
187
+ tokenizer = tokenizer,
188
+ train_dataset=dataset["train"],
189
+ max_seq_length = max_seq_length,
190
+ dataset_text_field="formatted_text",
191
+ packing = False,
192
+ args = TrainingArguments(
193
+ per_device_train_batch_size = 2,
194
+ gradient_accumulation_steps = 4,
195
+ num_train_epochs = 1,
196
+ logging_steps = 10,
197
+ warmup_steps = 10,
198
+ save_steps=100,
199
+ save_total_limit=2,
200
+ max_steps=-1,
201
+ learning_rate = 2e-4,
202
+ fp16 = not is_bfloat16_supported(),
203
+ bf16 = is_bfloat16_supported(),
204
+ group_by_length=True,
205
+ seed = 3407,
206
+ output_dir = "outputs",
207
+ report_to = "none",
208
+ ),
209
+ )
210
+
211
+ #@title 現在のメモリ使用量を表示
212
+ gpu_stats = torch.cuda.get_device_properties(0)
213
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
214
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
215
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
216
+ print(f"{start_gpu_memory} GB of memory reserved.")
217
+
218
+ #@title 学習実行
219
+ trainer_stats = trainer.train()
220
+
221
+ # ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
222
+ # データセットの読み込み。
223
+ # omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
224
+ import json
225
+ datasets = []
226
+ with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
227
+ item = ""
228
+ for line in f:
229
+ line = line.strip()
230
+ item += line
231
+ if item.endswith("}"):
232
+ datasets.append(json.loads(item))
233
+ item = ""
234
+
235
+ # 学習したモデルを用いてタスクを実行
236
+ from tqdm import tqdm
237
+
238
+ # 推論するためにモデルのモードを変更
239
+ FastLanguageModel.for_inference(model)
240
+
241
+ results = []
242
+ for dt in tqdm(datasets):
243
+ input = dt["input"]
244
+
245
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
246
+
247
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
248
+
249
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
250
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
251
+
252
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
253
+
254
+ # jsonlで保存
255
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
256
+ for result in results:
257
+ json.dump(result, f, ensure_ascii=False)
258
+ f.write('\n')
259
+
260
+ # LoRAアダプタだけ保存
261
+ # 書き込み可能なtoken
262
+ HF_TOKEN = "your token"
263
+
264
+ model.push_to_hub_merged(
265
+ new_model_id+"_lora",
266
+ tokenizer=tokenizer,
267
+ save_method="lora",
268
+ token=HF_TOKEN,
269
+ private=True
270
+ )
271
+
272
+ '''
273
+
274
+
275
+ 保存したモデルの使い方
276
+ '''
277
+ # 必要なライブラリをインストール
278
+ %%capture
279
+ !pip install unsloth
280
+ !pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
281
+ !pip install -U torch
282
+ !pip install -U peft
283
+
284
+ # 必要なライブラリを読み込み
285
+ from unsloth import FastLanguageModel
286
+ from peft import PeftModel
287
+ import torch
288
+ import json
289
+ from tqdm import tqdm
290
+ import re
291
+
292
+ # ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
293
+ model_id = "llm-jp/llm-jp-3-13b"
294
+ adapter_id = "okaba815/llm-jp-3-13b-it_lora"
295
+
296
+ HF_TOKEN = "your token"
297
+
298
+ # unslothのFastLanguageModelで元のモデルをロード。
299
+ dtype = None # Noneにしておけば自動で設定
300
+ load_in_4bit = True # 今回は13Bモデルを扱うためTrue
301
+
302
+ model, tokenizer = FastLanguageModel.from_pretrained(
303
+ model_name=model_id,
304
+ dtype=dtype,
305
+ load_in_4bit=load_in_4bit,
306
+ trust_remote_code=True,
307
+ )
308
+
309
+ # 元のモデルにLoRAのアダプタを統合。
310
+ model = PeftModel.from_pretrained(model, adapter_id, token = HF_TOKEN)
311
+
312
+
313
+ # タスクとなるデータの読み込み。
314
+ # 事前にデータをアップロードしてください。
315
+ datasets = []
316
+ with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
317
+ item = ""
318
+ for line in f:
319
+ line = line.strip()
320
+ item += line
321
+ if item.endswith("}"):
322
+ datasets.append(json.loads(item))
323
+ item = ""
324
+
325
+ # モデルを用いてタスクの推論。
326
+
327
+ # 推論するためにモデルのモードを変更
328
+ FastLanguageModel.for_inference(model)
329
+
330
+ results = []
331
+ for dt in tqdm(datasets):
332
+ input = dt["input"]
333
+
334
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
335
+
336
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
337
+
338
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
339
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
340
+
341
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
342
+
343
+ # 結果をjsonlで保存。
344
+
345
+ # ここではadapter_idを元にファイル名を決定しているが、ファイル名は任意で問題なし。
346
+ json_file_id = re.sub(".*/", "", adapter_id)
347
+ with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
348
+ for result in results:
349
+ json.dump(result, f, ensure_ascii=False)
350
+ f.write('\n')
351
+
352
+ '''