kei0902 commited on
Commit
9734536
·
verified ·
1 Parent(s): c9ff1c1

Update README.md

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