xylnao commited on
Commit
c730351
·
verified ·
1 Parent(s): 9d04178

Add how to generate

Browse files
Files changed (1) hide show
  1. README.md +214 -0
README.md CHANGED
@@ -20,3 +20,217 @@ 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
+ how to generate:
25
+ ```
26
+ !pip uninstall unsloth -y
27
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
28
+
29
+ # Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
30
+ !pip install --upgrade torch
31
+ !pip install --upgrade xformers
32
+
33
+ # notebookでインタラクティブな表示を可能とする(ただし、うまく動かない場合あり)
34
+ !pip install ipywidgets --upgrade
35
+
36
+ # Install Flash Attention 2 for softcapping support
37
+ import torch
38
+ if torch.cuda.get_device_capability()[0] >= 8:
39
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
40
+
41
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
42
+
43
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
44
+ from unsloth import FastLanguageModel
45
+ import torch
46
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
47
+ dtype = None # Noneにしておけば自動で設定
48
+ load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
49
+
50
+ model_id = "llm-jp/llm-jp-3-13b"
51
+ new_model_id = "llm-jp-3-13b-finetune-2" #Fine-Tuningしたモデルにつけたい名前
52
+ # FastLanguageModel インスタンスを作成
53
+ model, tokenizer = FastLanguageModel.from_pretrained(
54
+ model_name=model_id,
55
+ dtype=dtype,
56
+ load_in_4bit=load_in_4bit,
57
+ trust_remote_code=True,
58
+ )
59
+
60
+ # SFT用のモデルを用意
61
+ model = FastLanguageModel.get_peft_model(
62
+ model,
63
+ r = 32,
64
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
65
+ "gate_proj", "up_proj", "down_proj",],
66
+ lora_alpha = 32,
67
+ lora_dropout = 0.05,
68
+ bias = "none",
69
+ use_gradient_checkpointing = "unsloth",
70
+ random_state = 3407,
71
+ use_rslora = False,
72
+ loftq_config = None,
73
+ max_seq_length = max_seq_length,
74
+ )
75
+
76
+ # Hugging Face Token を指定
77
+ from google.colab import userdata
78
+ HF_TOKEN=userdata.get('HF_TOKEN')
79
+
80
+ # 学習に用いるデータセットの指定
81
+
82
+ # 以下のデータセットをすべて使用。
83
+ # https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
84
+ # 関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)
85
+
86
+ from datasets import load_dataset
87
+
88
+ dataset = load_dataset("json", data_files="/content/*.json")
89
+
90
+ # 学習時のプロンプトフォーマットの定義
91
+ prompt = """### 指示
92
+ {}
93
+ ### 回答
94
+ {}"""
95
+
96
+
97
+
98
+ """
99
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
100
+ """
101
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
102
+ def formatting_prompts_func(examples):
103
+ input = examples["text"] # 入力データ
104
+ output = examples["output"] # 出力データ
105
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
106
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
107
+ pass
108
+
109
+ # # 各データにフォーマットを適用
110
+ dataset = dataset.map(
111
+ formatting_prompts_func,
112
+ num_proc= 4, # 並列処理数を指定
113
+ )
114
+
115
+ # 10%を評価データセットに分割
116
+ split_dataset = dataset['train'].train_test_split(test_size=0.1, seed=42)
117
+
118
+ from datasets import DatasetDict
119
+ # 元のDatasetDictに評価データセットを追加
120
+ dataset = DatasetDict({
121
+ 'train': split_dataset['train'],
122
+ 'eval': split_dataset['test']
123
+ })
124
+
125
+ dataset
126
+
127
+ # データを確認
128
+ print(dataset["train"]["formatted_text"][3])
129
+
130
+ """
131
+ training_arguments: 学習の設定
132
+
133
+ - output_dir:
134
+ -トレーニング後のモデルを保存するディレクトリ
135
+
136
+ - per_device_train_batch_size:
137
+ - デバイスごとのトレーニングバッチサイズ
138
+
139
+ - per_device_eval_batch_size:
140
+ - デバイスごとの評価バッチサイズ
141
+
142
+ - gradient_accumulation_steps:
143
+ - 勾配を更新する前にステップを積み重ねる回数
144
+
145
+ - optim:
146
+ - オプティマイザの設定
147
+
148
+ - num_train_epochs:
149
+ - エポック数
150
+
151
+ - eval_strategy:
152
+ - 評価の戦略 ("no"/"steps"/"epoch")
153
+
154
+ - eval_steps:
155
+ - eval_strategyが"steps"のとき、評価を行うstep間隔
156
+
157
+ - logging_strategy:
158
+ - ログ記録の戦略
159
+
160
+ - logging_steps:
161
+ - ログを出力するステップ間隔
162
+
163
+ - warmup_steps:
164
+ - 学習率のウォームアップステップ数
165
+
166
+ - save_steps:
167
+ - モデルを保存するステップ間隔
168
+
169
+ - save_total_limit:
170
+ - 保存しておくcheckpointの数
171
+
172
+ - max_steps:
173
+ - トレーニングの最大ステップ数
174
+
175
+ - learning_rate:
176
+ - 学習率
177
+
178
+ - fp16:
179
+ - 16bit浮動小数点の使用設定(第8回演習を参考にすると良いです)
180
+
181
+ - bf16:
182
+ - BFloat16の使用設定
183
+
184
+ - group_by_length:
185
+ - 入力シーケンスの長さによりバッチをグループ化 (トレーニングの効率化)
186
+
187
+ - report_to:
188
+ - ログの送信先 ("wandb"/"tensorboard"など)
189
+ """
190
+ from trl import SFTTrainer
191
+ from transformers import TrainingArguments
192
+ from unsloth import is_bfloat16_supported
193
+
194
+ trainer = SFTTrainer(
195
+ model = model,
196
+ tokenizer = tokenizer,
197
+ train_dataset=dataset["train"],
198
+ max_seq_length = max_seq_length,
199
+ dataset_text_field="formatted_text",
200
+ packing = False,
201
+ eval_dataset=dataset["eval"],
202
+ args = TrainingArguments(
203
+ per_device_train_batch_size = 2,
204
+ gradient_accumulation_steps = 4,
205
+ num_train_epochs = 2,
206
+ logging_steps = 10,
207
+ warmup_steps = 10,
208
+ optim = "adamw_torch",
209
+ # weight_decay = 0.01,
210
+ save_steps=100,
211
+ save_total_limit=2,
212
+ max_steps=-1,
213
+ learning_rate = 2.1e-4,
214
+ fp16 = not is_bfloat16_supported(),
215
+ bf16 = is_bfloat16_supported(),
216
+ group_by_length=True,
217
+ seed = 3407,
218
+ output_dir = "outputs",
219
+ report_to = "none",
220
+ eval_strategy="steps",
221
+ eval_steps=10,
222
+ ),
223
+ )
224
+
225
+ # モデルとトークナイザーをHugging Faceにアップロード。
226
+ model.push_to_hub_merged(
227
+ new_model_id,
228
+ tokenizer=tokenizer,
229
+ save_method="lora",
230
+ token=HF_TOKEN,
231
+ private=True
232
+ )
233
+
234
+ # model.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving
235
+ # tokenizer.push_to_hub(new_model_id, token=HF_TOKEN) # Online saving
236
+ ```