Hide101111001111000 commited on
Commit
ca149e0
·
verified ·
1 Parent(s): dba413a

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +262 -0
README.md CHANGED
@@ -20,3 +20,265 @@ 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
+ --python--
25
+
26
+ # Google Colab の場合は上記の環境構築手順を行なわず、単にこのセルから実行していってください。
27
+ !pip uninstall unsloth -y
28
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
29
+
30
+ # Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
31
+ !pip install --upgrade torch
32
+ !pip install --upgrade xformers
33
+
34
+ # Install Flash Attention 2 for softcapping support
35
+ import torch
36
+ if torch.cuda.get_device_capability()[0] >= 8:
37
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
38
+
39
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
40
+
41
+ from unsloth import FastLanguageModel
42
+ import torch
43
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
44
+ dtype = None # Noneにしておけば自動で設定
45
+ load_in_4bit = True # 今回は13Bモデルを扱うためTrue
46
+
47
+ model_id = "llm-jp/llm-jp-3-13b"
48
+ new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
49
+ # FastLanguageModel インスタンスを作成
50
+ model, tokenizer = FastLanguageModel.from_pretrained(
51
+ model_name=model_id,
52
+ dtype=dtype,
53
+ load_in_4bit=load_in_4bit,
54
+ trust_remote_code=True,
55
+ )
56
+
57
+ # SFT用のモデルを用意
58
+ model = FastLanguageModel.get_peft_model(
59
+ model,
60
+ r = 32,
61
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
62
+ "gate_proj", "up_proj", "down_proj",],
63
+ lora_alpha = 56,
64
+ lora_dropout = 0.07489221108975741,
65
+ bias = "none",
66
+ use_gradient_checkpointing = "unsloth",
67
+ random_state = 3407,
68
+ use_rslora = False,
69
+ loftq_config = None,
70
+ max_seq_length = max_seq_length,
71
+ )
72
+
73
+ from datasets import load_dataset
74
+ import os
75
+
76
+ # データセットのロードとフォーマット関数
77
+ data_dir = "Distribute"
78
+ files = os.listdir(data_dir) #
79
+ json_files = [f"{data_dir}/{f}" for f in files if f.endswith(".json") == True]
80
+ dataset = load_dataset("json", data_files=json_files)
81
+
82
+ dataset_hf = load_dataset("json", data_files="combined_dataset.json")
83
+
84
+ # 学習時のプロンプトフォーマットの定義
85
+ prompt = """### 指示
86
+ {}
87
+ ### 回答
88
+ {}"""
89
+
90
+
91
+ """
92
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
93
+ """
94
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
95
+
96
+ def formatting_prompts_func(examples):
97
+ input = examples["text"] # 入力データ
98
+ output = examples["output"] # 出力データ
99
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
100
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
101
+ pass
102
+
103
+
104
+
105
+ # # 各データにフォーマットを適用
106
+ dataset = dataset.map(
107
+ formatting_prompts_func,
108
+ num_proc= 4, # 並列処理数を指定
109
+ )
110
+
111
+
112
+
113
+ dataset
114
+
115
+ def formatting_prompts_func_a(examples):
116
+ if examples["input"] == None:
117
+ input = examples["instruction"] # 入力データ
118
+ else:
119
+ input = examples["instruction"] + examples["input"]
120
+ output = examples["output"] # 出力データ
121
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
122
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
123
+ pass
124
+
125
+
126
+ dataset_hf = dataset_hf.map(
127
+ formatting_prompts_func_a,
128
+ num_proc= 4, # 並列処理数を指定
129
+ )
130
+
131
+
132
+
133
+ dataset_hf = dataset_hf["train"].shuffle(seed=42).select(range(6000))
134
+
135
+ dataset_hf
136
+
137
+ from datasets import concatenate_datasets
138
+
139
+ # それぞれのデータセットで残るカラムを基に統一
140
+ unified_dataset = concatenate_datasets([dataset["train"], dataset_hf])
141
+
142
+ unified_dataset
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=unified_dataset,
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 = 32,
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 = 7.950711327648347e-05,
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
+ #@title 学習実行
235
+ trainer_stats = trainer.train()
236
+
237
+ # ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
238
+ # データセットの読み込み。
239
+ # omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
240
+ import json
241
+ datasets = []
242
+ with open("elyza-tasks-100-TV_0 .jsonl", "r") as f:
243
+ item = ""
244
+ for line in f:
245
+ line = line.strip()
246
+ item += line
247
+ if item.endswith("}"):
248
+ datasets.append(json.loads(item))
249
+ item = ""
250
+
251
+ # 学習したモデルを用いてタスクを実行
252
+ from tqdm import tqdm
253
+
254
+ # 推論するためにモデルのモードを変更
255
+ FastLanguageModel.for_inference(model)
256
+
257
+ results = []
258
+ for dt in tqdm(datasets):
259
+ input = dt["input"]
260
+
261
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
262
+
263
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
264
+
265
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
266
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
267
+
268
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
269
+
270
+ # jsonlで保存
271
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
272
+ for result in results:
273
+ json.dump(result, f, ensure_ascii=False)
274
+ f.write('\n')
275
+
276
+ # LoRAアダプタだけ保存
277
+ model.push_to_hub_merged(
278
+ new_model_id+"_lora_3",
279
+ tokenizer=tokenizer,
280
+ save_method="lora",
281
+ token="token_name",
282
+ private=True
283
+ )
284
+