kachi129 commited on
Commit
e6fe467
·
verified ·
1 Parent(s): 42d25f6
Files changed (1) hide show
  1. README.md +223 -0
README.md CHANGED
@@ -20,3 +20,226 @@ 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
+ # Smple Use
25
+ '''python
26
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
27
+ from unsloth import FastLanguageModel
28
+ import torch
29
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
30
+ dtype = None # Noneにしておけば自動で設定
31
+ load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
32
+
33
+ model_id = "llm-jp/llm-jp-3-13b"
34
+ new_model_id = "kachi-1216/llm-jp-3-13b-finetune-2" #Fine-Tuningしたモデルにつけたい名前
35
+ # FastLanguageModel インスタンスを作成
36
+ model, tokenizer = FastLanguageModel.from_pretrained(
37
+ model_name=model_id,
38
+ dtype=dtype,
39
+ load_in_4bit=load_in_4bit,
40
+ trust_remote_code=True,
41
+ )
42
+
43
+ # SFT用のモデルを用意
44
+ model = FastLanguageModel.get_peft_model(
45
+ model,
46
+ r = 32,
47
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
48
+ "gate_proj", "up_proj", "down_proj",],
49
+ lora_alpha = 32,
50
+ lora_dropout = 0.05,
51
+ bias = "none",
52
+ use_gradient_checkpointing = "unsloth",
53
+ random_state = 3407,
54
+ use_rslora = False,
55
+ loftq_config = None,
56
+ max_seq_length = max_seq_length,
57
+ )
58
+
59
+ from datasets import load_dataset
60
+
61
+ dataset = load_dataset("json", data_files="/content/ichikara-instruction-003-001-1.json")
62
+ # パスの指定にご注意ください。アップロードしたファイルを右クリックし、「パスをコピー」をクリック、上記の data_files と合致していることをご確認ください。Omnicampus のディレクトリ構造とは異なるかもしれません。
63
+
64
+ # 学習時のプロンプトフォーマットの定義
65
+ prompt = """### 指示
66
+ {}
67
+ ### 回答
68
+ {}"""
69
+
70
+
71
+
72
+ """
73
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
74
+ """
75
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
76
+ def formatting_prompts_func(examples):
77
+ input = examples["text"] # 入力データ
78
+ output = examples["output"] # 出力データ
79
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
80
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
81
+ pass
82
+
83
+ # # 各データにフォーマットを適用
84
+ dataset = dataset.map(
85
+ formatting_prompts_func,
86
+ num_proc= 4, # 並列処理数を指定
87
+ )
88
+
89
+ dataset
90
+
91
+ # データを確認
92
+ print(dataset["train"]["formatted_text"][3])
93
+
94
+ """
95
+ training_arguments: 学習の設定
96
+
97
+ - output_dir:
98
+ -トレーニング後のモデルを保存するディレクトリ
99
+
100
+ - per_device_train_batch_size:
101
+ - デバイスごとのトレーニングバッチサイズ
102
+
103
+ - per_device_eval_batch_size:
104
+ - デバイスごとの評価バッチサイズ
105
+
106
+ - gradient_accumulation_steps:
107
+ - 勾配を更新する前にステップを積み重ねる回数
108
+
109
+ - optim:
110
+ - オプティマイザの設定
111
+
112
+ - num_train_epochs:
113
+ - エポック数
114
+
115
+ - eval_strategy:
116
+ - 評価の戦略 ("no"/"steps"/"epoch")
117
+
118
+ - eval_steps:
119
+ - eval_strategyが"steps"のとき、評価を行うstep間隔
120
+
121
+ - logging_strategy:
122
+ - ログ記録の戦略
123
+
124
+ - logging_steps:
125
+ - ログを出力するステップ間隔
126
+
127
+ - warmup_steps:
128
+ - 学習率のウォームアップステップ数
129
+
130
+ - save_steps:
131
+ - モデルを保存するステップ間隔
132
+
133
+ - save_total_limit:
134
+ - 保存しておくcheckpointの数
135
+
136
+ - max_steps:
137
+ - トレーニングの最大ステップ数
138
+
139
+ - learning_rate:
140
+ - 学習率
141
+
142
+ - fp16:
143
+ - 16bit浮動小数点の使用設定(第8回演習を参考にすると良いです)
144
+
145
+ - bf16:
146
+ - BFloat16の使用設定
147
+
148
+ - group_by_length:
149
+ - 入力シーケンスの長さによりバッチをグループ化 (トレーニングの効率化)
150
+
151
+ - report_to:
152
+ - ログの送信先 ("wandb"/"tensorboard"など)
153
+ """
154
+ from trl import SFTTrainer
155
+ from transformers import TrainingArguments
156
+ from unsloth import is_bfloat16_supported
157
+
158
+ trainer = SFTTrainer(
159
+ model = model,
160
+ tokenizer = tokenizer,
161
+ train_dataset=dataset["train"],
162
+ max_seq_length = max_seq_length,
163
+ dataset_text_field="formatted_text",
164
+ packing = False,
165
+ args = TrainingArguments(
166
+ per_device_train_batch_size = 2,
167
+ gradient_accumulation_steps = 4,
168
+ num_train_epochs = 1,
169
+ logging_steps = 10,
170
+ warmup_steps = 10,
171
+ save_steps=100,
172
+ save_total_limit=2,
173
+ max_steps=-1,
174
+ learning_rate = 2e-4,
175
+ fp16 = not is_bfloat16_supported(),
176
+ bf16 = is_bfloat16_supported(),
177
+ group_by_length=True,
178
+ seed = 3407,
179
+ output_dir = "outputs",
180
+ report_to = "none",
181
+ ),
182
+ )
183
+
184
+ #@title 現在のメモリ使用量を表示
185
+ gpu_stats = torch.cuda.get_device_properties(0)
186
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
187
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
188
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
189
+ print(f"{start_gpu_memory} GB of memory reserved.")
190
+
191
+ #@title 学習実行
192
+ trainer_stats = trainer.train()
193
+
194
+ # ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
195
+ # データセットの読み込み。
196
+ # omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
197
+ import json
198
+ datasets = []
199
+ with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
200
+ item = ""
201
+ for line in f:
202
+ line = line.strip()
203
+ item += line
204
+ if item.endswith("}"):
205
+ datasets.append(json.loads(item))
206
+ item = ""
207
+
208
+ # 学習したモデルを用いてタスクを実行
209
+ from tqdm import tqdm
210
+
211
+ # 推論するためにモデルのモードを変更
212
+ FastLanguageModel.for_inference(model)
213
+
214
+ results = []
215
+ for dt in tqdm(datasets):
216
+ input = dt["input"]
217
+
218
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
219
+
220
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
221
+
222
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
223
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
224
+
225
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
226
+
227
+ # jsonlで保存
228
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
229
+ for result in results:
230
+ json.dump(result, f, ensure_ascii=False)
231
+ f.write('\n')
232
+
233
+ # モデルとトークナイザーをHugging Faceにアップロード。
234
+ # 一旦privateでアップロードしてください。
235
+ # 最終成果物が決まったらpublicにするようお願いします。
236
+ # 現在公開しているModel_Inference_Template.ipynbはunslothを想定していないためそのままでは動かない可能性があります。
237
+ new_model_id = "kachi129/llm-jp-3-13b-finetune-2"
238
+ model.push_to_hub_merged(
239
+ new_model_id,
240
+ tokenizer=tokenizer,
241
+ save_method="lora",
242
+ token=HF_TOKEN,
243
+ private=True
244
+ )
245
+ '''