daichira commited on
Commit
772dd33
·
verified ·
1 Parent(s): 1bc814c

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +263 -1
README.md CHANGED
@@ -19,4 +19,266 @@ language:
19
 
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
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
+ ### **README.md**
25
+
26
+ ```markdown
27
+ # LLM-JP-3-13B-ITNEW9
28
+
29
+ ## **概要**
30
+ このモデルは、日本語対応の大規模言語モデル(LLM)`llm-jp/llm-jp-3-13b-finetune2`を基にして、さらなる指示応答タスク向けに微調整(SFT: Supervised Fine-Tuning)を施したモデルです。本モデルでは、4bit量子化(qLoRA)を使用して計算効率を向上させつつ、データセット「TengenToppa-SFT-v1.0」を活用して高品質な指示応答能力を実現しました。
31
+
32
+ ---
33
+
34
+ ## **特徴**
35
+ - **モデル名:** `llm-jp-3-13b-itnew9`
36
+ - **ベースモデル:** `llm-jp/llm-jp-3-13b-finetune2`
37
+ - **微調整目的:** 日本語の指示応答能力を強化。
38
+ - **量子化:** 4bit (qLoRA)
39
+ - **LoRA設定:**
40
+ - ランク (r): 32
41
+ - ドロップアウト率: 5%
42
+ - ターゲットモジュール: `q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`
43
+
44
+ ---
45
+
46
+ ## **微調整の詳細**
47
+
48
+ ### **使用データセット**
49
+ - **データセット名:** `DeL-TaiseiOzaki/Tengentoppa-sft-v1.0`
50
+ - **データ数:** 約30,000行を抽出して使用。
51
+ - **データフォーマット:** 各データが「instruction」(指示)と「output」(回答)のペア形式。
52
+ - **プロンプト変換例:**
53
+ ```plaintext
54
+ ### 指示
55
+ 次の文章を要約してください。
56
+ ### 回答
57
+ この文章の要約です。
58
+ ```
59
+
60
+ ---
61
+
62
+ ### **ハードウェアと設定**
63
+ - **使用GPU:** NVIDIA L4 24GB
64
+ - **シーケンス長:** 1024(RoPEサポート)
65
+ - **バッチサイズ(デバイスごと):** 6
66
+ - **学習率:** 3e-4
67
+ - **エポック数:** 1
68
+ - **量子化:** 4bit (qLoRA)
69
+ - **最適化アルゴリズム:** AdamW
70
+
71
+ ---
72
+
73
+ ### **LoRA設定**
74
+ - **ランク (r):** 32
75
+ - **スケーリング係数 (lora_alpha):** 32
76
+ - **ドロップアウト率:** 0.05
77
+ - **適用モジュール:** モデル内の線形層(`q_proj`, `k_proj`, `v_proj`, 他)
78
+
79
+ ---
80
+
81
+ ## **使用方法**
82
+ 以下のコードを使用して、このモデルで日本語の指示応答を生成できます。
83
+
84
+ ```python
85
+ from transformers import AutoTokenizer, AutoModelForCausalLM
86
+
87
+ # モデルとトークナイザーのロード
88
+ model_name = "your-hf-username/llm-jp-3-13b-itnew9"
89
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
90
+ model = AutoModelForCausalLM.from_pretrained(model_name)
91
+
92
+ # 指示応答の生成
93
+ instruction = "次の文章を要約してください。"
94
+ prompt = f"### 指示\n{instruction}\n### 回答\n"
95
+ inputs = tokenizer(prompt, return_tensors="pt")
96
+ outputs = model.generate(**inputs, max_new_tokens=128)
97
+
98
+ # 応答を表示
99
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
100
+ print(response)
101
+ ```
102
+
103
+ ---
104
+
105
+ ## **謝辞**
106
+ 本モデルの開発に以下のライブラリとツールを活用しました:
107
+ - [Hugging Face Transformers](https://huggingface.co/transformers): トレーニングとモデル管理。
108
+ - [Unsloth](https://github.com/unslothai/unsloth): 高効率なqLoRA微調整。
109
+ - [BitsAndBytes](https://github.com/TimDettmers/bitsandbytes): 量子化処理。
110
+
111
+ ---
112
+
113
+ ## **ライセンス**
114
+ 本モデルは **CC-BY-NC-SA 4.0** ライセンスのもとで提供されています。このため、商用利用は制限されています。また、ベースモデル(`llm-jp/llm-jp-3-13b-finetune2`)および使用データセットのライセンス条件も遵守してください。
115
+
116
+ ---
117
+
118
+ ## **注意点と制約**
119
+ - 本モデルは日本語の指示応答タスクに特化しており、他のタスクや言語での性能は保証されません。
120
+ - ライセンス条件により、商用利用は許可されていません。
121
+ ```
122
+
123
+
124
+ #実行コード
125
+
126
+
127
+ # Google Colabの場合はunslothのインストールのみを行ってください
128
+ !pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
129
+
130
+ # notebookでインタラクティブな表示を可能とする
131
+ !pip install ipywidgets --upgrade
132
+
133
+ # Install Flash Attention 2 for softcapping support
134
+ import torch
135
+ if torch.cuda.get_device_capability()[0] >= 8:
136
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
137
+
138
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
139
+
140
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
141
+ from unsloth import FastLanguageModel
142
+ import torch
143
+ #max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
144
+ max_seq_length = 1024 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
145
+
146
+ dtype = None # Noneにしておけば自動で設定
147
+ load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
148
+
149
+ model_id = "daichira/llm-jp-3-13b-finetune2"
150
+
151
+
152
+ #llm-jp-3-13b-finetune2:ベースモデルをichikara-instruction-003-001-1.jsonでsft
153
+
154
+
155
+ new_model_id = "llm-jp-3-13b-itnew9" #Fine-Tuningしたモデルにつけたい名前
156
+ # FastLanguageModel インスタンスを作成
157
+ model, tokenizer = FastLanguageModel.from_pretrained(
158
+ model_name=model_id,
159
+ dtype=dtype,
160
+ load_in_4bit=load_in_4bit,
161
+ trust_remote_code=True,
162
+ )
163
+
164
+ # SFT用のモデルを用意
165
+ model = FastLanguageModel.get_peft_model(
166
+ model,
167
+ r = 32,
168
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
169
+ "gate_proj", "up_proj", "down_proj",],
170
+ lora_alpha = 32,
171
+ lora_dropout = 0.05,
172
+ bias = "none",
173
+ use_gradient_checkpointing = "unsloth",
174
+ random_state = 3407,
175
+ use_rslora = False,
176
+ loftq_config = None,
177
+ max_seq_length = max_seq_length,
178
+ )
179
+
180
+ from google.colab import output
181
+ output.disable_custom_widget_manager()
182
+
183
+ # Hugging Faceで取得したTokenをこちらに貼る。
184
+ HF_TOKEN =
185
+
186
+ !pip install datasets
187
+
188
+ #全データを抽出する場合
189
+ import os
190
+ from datasets import load_dataset
191
+
192
+ # データセットをロード
193
+ dataset = load_dataset("DeL-TaiseiOzaki/Tengentoppa-sft-v1.0", split="train")
194
+
195
+ # 1ファイルあたりの行数
196
+ chunk_size = 30000
197
+
198
+ # データセットを分割して保存
199
+ output_dir = "/content/tengentoppa_chunks" # 保存先ディレクトリ
200
+ os.makedirs(output_dir, exist_ok=True)
201
+
202
+ # 全データを分割し、番号付きでJSON形式で保存
203
+ total_rows = len(dataset)
204
+ num_chunks = (total_rows + chunk_size - 1) // chunk_size # 切り上げでチャンク数を計算
205
+
206
+ for i in range(num_chunks):
207
+ start_idx = i * chunk_size
208
+ end_idx = min(start_idx + chunk_size, total_rows)
209
+ chunk = dataset.select(range(start_idx, end_idx)) # 分割部分を選択
210
+ chunk_file = f"{output_dir}/tengentoppa_chunk_{i+1}.json"
211
+ chunk.to_json(chunk_file) # JSON形式で保存
212
+ print(f"Saved chunk {i+1}/{num_chunks} to {chunk_file}")
213
+
214
+ print("All chunks have been saved!")
215
+
216
+
217
+ # Step 2: JSON形式で保存
218
+ json_path = "/content/tengentoppa_chunks/tengentoppa_chunk_3.json"
219
+ #subset.to_json(json_path)
220
+
221
+ # Step 3: JSON形式で再読み込み
222
+ from datasets import load_dataset
223
+
224
+ # JSONファイルをロード
225
+ dataset = load_dataset("json", data_files=json_path)
226
+
227
+ # 学習時のプロンプトフォーマットの定義
228
+ prompt = """### 指示
229
+ {}
230
+ ### 回答
231
+ {}"""
232
+
233
+ """
234
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
235
+ """
236
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
237
+ def formatting_prompts_func(examples):
238
+ # input = examples["text"] # 入力データ
239
+ input = examples["instruction"] # 入力データ
240
+ output = examples["output"] # 出力データ
241
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
242
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
243
+ pass
244
+
245
+ # # 各データにフォーマットを適用
246
+ dataset = dataset.map(
247
+ formatting_prompts_func,
248
+ num_proc= 4, # 並列処理数を指定
249
+ )
250
+
251
+ from trl import SFTTrainer
252
+ from transformers import TrainingArguments
253
+ from unsloth import is_bfloat16_supported
254
+
255
+ trainer = SFTTrainer(
256
+ model=model,
257
+ tokenizer=tokenizer,
258
+ train_dataset=dataset["train"],
259
+ max_seq_length=max_seq_length,
260
+ dataset_text_field="formatted_text",
261
+ packing=False,
262
+ args=TrainingArguments(
263
+ per_device_train_batch_size=6, # デバイスごとのバッチサイズ
264
+ gradient_accumulation_steps=4, # 勾配蓄積
265
+ num_train_epochs=1, # エポック数
266
+ logging_steps=50, # ログ記録の間隔
267
+ warmup_steps=500, # ウォームアップステップ
268
+ save_steps=500, # チェックポイント保存間隔
269
+ save_total_limit=2, # 保存するモデルの数
270
+ max_steps=-1, # 全データを1エポック分学習する設定
271
+ learning_rate=3e-4, # 学習率
272
+ fp16=not is_bfloat16_supported(), # FP16使用
273
+ bf16=is_bfloat16_supported(), # BF16使用
274
+ group_by_length=True, # シーケンス長でバッチをグループ化
275
+ seed=3407, # ランダムシード
276
+ output_dir="outputs", # 出力先ディレクトリ
277
+ ),
278
+ )
279
+
280
+
281
+ # 学習実行前にCUDAキャッシュをクリア
282
+ torch.cuda.empty_cache()
283
+ #@title 学習実行
284
+ trainer_stats = trainer.train()