Hizaneko commited on
Commit
134b59a
1 Parent(s): 6eda7ca

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +237 -9
README.md CHANGED
@@ -2,6 +2,13 @@
2
  library_name: transformers
3
  tags:
4
  - unsloth
 
 
 
 
 
 
 
5
  ---
6
 
7
  # Model Card for Model ID
@@ -13,18 +20,19 @@ tags:
13
  ## Model Details
14
 
15
  ### Model Description
 
16
 
17
- <!-- Provide a longer summary of what this model is. -->
18
 
19
  This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
20
 
21
- - **Developed by:** [More Information Needed]
22
  - **Funded by [optional]:** [More Information Needed]
23
  - **Shared by [optional]:** [More Information Needed]
24
- - **Model type:** [More Information Needed]
25
- - **Language(s) (NLP):** [More Information Needed]
26
- - **License:** [More Information Needed]
27
- - **Finetuned from model [optional]:** [More Information Needed]
28
 
29
  ### Model Sources [optional]
30
 
@@ -36,6 +44,217 @@ This is the model card of a 🤗 transformers model that has been pushed on the
36
 
37
  ## Uses
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
40
 
41
  ### Direct Use
@@ -77,8 +296,9 @@ Use the code below to get started with the model.
77
  ## Training Details
78
 
79
  ### Training Data
 
 
80
 
81
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
82
 
83
  [More Information Needed]
84
 
@@ -92,6 +312,14 @@ Use the code below to get started with the model.
92
 
93
 
94
  #### Training Hyperparameters
 
 
 
 
 
 
 
 
95
 
96
  - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
97
 
@@ -145,8 +373,8 @@ Use the code below to get started with the model.
145
 
146
  Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
147
 
148
- - **Hardware Type:** [More Information Needed]
149
- - **Hours used:** [More Information Needed]
150
  - **Cloud Provider:** [More Information Needed]
151
  - **Compute Region:** [More Information Needed]
152
  - **Carbon Emitted:** [More Information Needed]
 
2
  library_name: transformers
3
  tags:
4
  - unsloth
5
+ license: apache-2.0
6
+ datasets:
7
+ - llm-jp/magpie-sft-v1.0
8
+ language:
9
+ - ja
10
+ base_model:
11
+ - google/gemma-2-9b
12
  ---
13
 
14
  # Model Card for Model ID
 
20
  ## Model Details
21
 
22
  ### Model Description
23
+ gemma-2-9b-nyan100
24
 
25
+ gemma-2-9b-nyan100 は、Google Gemma-2-9b を基に、日本語の指示追従タスクに特化して微調整されたモデルです。本モデルは、特に日本語での指示応答や対話生成、文書要約などのタスクに優れた性能を発揮します。
26
 
27
  This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
28
 
29
+ - **Developed by:** [Hizaneko]
30
  - **Funded by [optional]:** [More Information Needed]
31
  - **Shared by [optional]:** [More Information Needed]
32
+ - **Model type:** [指示追従型大規模言語モデル (Instruction-Following LLM)]
33
+ - **Language(s) (NLP):** [日本語]
34
+ - **License:** [Gemma 利用規約 に従う]
35
+ - **Finetuned from model [optional]:** [google/gemma-2-9b]
36
 
37
  ### Model Sources [optional]
38
 
 
44
 
45
  ## Uses
46
 
47
+ !pip uninstall unsloth -y
48
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
49
+
50
+ # Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
51
+ !pip install --upgrade torch
52
+ !pip install --upgrade xformers
53
+
54
+ # notebookでインタラクティブな表示を可能とする(ただし、うまく動かない場合あり)
55
+ # Google Colabでは実行不要
56
+ !pip install ipywidgets --upgrade
57
+
58
+ # Install Flash Attention 2 for softcapping support
59
+ import torch
60
+ if torch.cuda.get_device_capability()[0] >= 8:
61
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
62
+
63
+ # Hugging Face Token を指定
64
+ #HF_TOKEN = "" #@param {type:"string"}
65
+
66
+ # あるいはGoogle Colab シークレットを使う場合、左のサイドバーより🔑マークをクリック
67
+ # HF_TOKEN という名前で Value に Hugging Face Token を入れてください。
68
+ # ノートブックからのアクセスのトグルをオンにし、下記の二行のコードのコメントアウトを外してください。
69
+ from google.colab import userdata
70
+ HF_TOKEN=userdata.get('HF_TOKEN')
71
+
72
+ # google/gemma-2-9bを4bit量子化のqLoRA設定でロード。
73
+
74
+ from unsloth import FastLanguageModel
75
+ import torch
76
+ #max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
77
+ max_seq_length = 1024
78
+ dtype = None # Noneにしておけば自動で設定
79
+ load_in_4bit = True # 今回は9Bモデルを扱うためTrue
80
+
81
+ # HFからモデルリポジトリをダウンロード
82
+ !huggingface-cli login --token $HF_TOKEN
83
+ !huggingface-cli download google/gemma-2-9b --local-dir gemma-2-9b/
84
+ model_id = "./gemma-2-9b"
85
+ new_model_id = "gemma-2-9b-nyan100" #Fine-Tuningしたモデルにつけたい名前
86
+ # FastLanguageModel インスタンスを作成
87
+ model, tokenizer = FastLanguageModel.from_pretrained(
88
+ model_name=model_id,
89
+ dtype=dtype,
90
+ load_in_4bit=load_in_4bit,
91
+ trust_remote_code=True,
92
+ )
93
+
94
+ # SFT用のモデルを用意
95
+ model = FastLanguageModel.get_peft_model(
96
+ model,
97
+ r = 32,
98
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
99
+ "gate_proj", "up_proj", "down_proj",],
100
+ lora_alpha = 32,
101
+ lora_dropout = 0.05,
102
+ #lora_dropout = 0.1,
103
+ bias = "none",
104
+ use_gradient_checkpointing = "unsloth",
105
+ random_state = 3407,
106
+ use_rslora = False,
107
+ loftq_config = None,
108
+ max_seq_length = max_seq_length,
109
+ )
110
+
111
+ from datasets import load_dataset
112
+
113
+ # データセットのロード
114
+ dataset_name = "llm-jp/magpie-sft-v1.0"
115
+ dataset = load_dataset(dataset_name)
116
+
117
+ # データセットの10分の1を使用(train split前提)
118
+ train_length = len(dataset["train"])
119
+ #dataset["train"] = dataset["train"].select(range(train_length // 10))
120
+ dataset["train"] = dataset["train"].select(range(train_length // 100))
121
+
122
+ # フォーマット整形関数の定義
123
+ def format_dataset(examples):
124
+ conversations = examples["conversations"] # conversationsカラムを取得
125
+ user_inputs = []
126
+ assistant_outputs = []
127
+
128
+ for turn in conversations:
129
+ if turn["role"] == "user":
130
+ user_inputs.append(turn["content"])
131
+ elif turn["role"] == "assistant":
132
+ assistant_outputs.append(turn["content"])
133
+
134
+ input_text = " ".join(user_inputs) # ユーザー発話を結合
135
+ output_text = " ".join(assistant_outputs) # アシスタント発話を��合
136
+
137
+ return {
138
+ "text": input_text, # 入力部分
139
+ "output": output_text # 出力部分
140
+ }
141
+
142
+ # データセットを整形
143
+ formatted_dataset = dataset.map(
144
+ format_dataset,
145
+ num_proc=4,
146
+ remove_columns=["conversations"]
147
+ )
148
+
149
+ # 結果の表示
150
+ print(formatted_dataset)
151
+
152
+ # プロンプトフォーマットの定義
153
+ prompt = """### 指示
154
+ {}
155
+ ### 回答
156
+ {}"""
157
+
158
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン
159
+
160
+ # プロンプト生成関数
161
+ def formatting_prompts_func(examples):
162
+ input_text = examples["text"]
163
+ output_text = examples["output"]
164
+ formatted_text = prompt.format(input_text, output_text) + EOS_TOKEN
165
+ return {"formatted_text": formatted_text}
166
+
167
+ # プロンプト適用
168
+ final_dataset = formatted_dataset.map(
169
+ formatting_prompts_func,
170
+ num_proc=4
171
+ )
172
+
173
+ from trl import SFTTrainer
174
+ from transformers import TrainingArguments
175
+ from unsloth import is_bfloat16_supported
176
+
177
+ trainer = SFTTrainer(
178
+ model = model,
179
+ tokenizer = tokenizer,
180
+ train_dataset=final_dataset["train"],
181
+ max_seq_length = max_seq_length,
182
+ dataset_text_field="formatted_text",
183
+ packing = False,
184
+ args = TrainingArguments(
185
+ per_device_train_batch_size = 2,
186
+ gradient_accumulation_steps = 4,
187
+ num_train_epochs = 1,
188
+ logging_steps = 10,
189
+ warmup_steps = 10,
190
+ save_steps=100,
191
+ save_total_limit=2,
192
+ max_steps=-1,
193
+ learning_rate = 2e-4,
194
+ #learning_rate = 1e-4,
195
+ fp16 = not is_bfloat16_supported(),
196
+ bf16 = is_bfloat16_supported(),
197
+ group_by_length=True,
198
+ seed = 3407,
199
+ output_dir = "outputs",
200
+ report_to = "none",
201
+ ),
202
+ )
203
+
204
+ trainer_stats = trainer.train()
205
+
206
+ # ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
207
+ # データセットの読み込み。
208
+ # omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
209
+ import json
210
+ datasets = []
211
+ with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
212
+ item = ""
213
+ for line in f:
214
+ line = line.strip()
215
+ item += line
216
+ if item.endswith("}"):
217
+ datasets.append(json.loads(item))
218
+ item = ""
219
+
220
+ # 学習したモデルを用いてタスクを実行
221
+ from tqdm import tqdm
222
+
223
+ # 推論するためにモデルのモードを変更
224
+ FastLanguageModel.for_inference(model)
225
+
226
+ results = []
227
+ for dt in tqdm(datasets):
228
+ input = dt["input"]
229
+
230
+ #prompt = f"""### 指示\n{input}\n### 回答\n"""
231
+ prompt = f"""### 指示\n{input} 簡潔に回答してください \n### 回答\n"""
232
+
233
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
234
+
235
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
236
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
237
+
238
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
239
+
240
+ # jsonlで保存
241
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
242
+ for result in results:
243
+ json.dump(result, f, ensure_ascii=False)
244
+ f.write('\n')
245
+
246
+ #モデルとトークナイザーをHugging Faceにアップロード。
247
+ # 一旦privateでアップロードしてください。
248
+ # 最終成果物が決まったらpublicにするようお願いします。
249
+ # 現在公開しているModel_Inference_Template.ipynbはunslothを想定していないためそのままでは動かない可能性があります。
250
+ model.push_to_hub_merged(
251
+ new_model_id,
252
+ tokenizer=tokenizer,
253
+ save_method="lora",
254
+ token=HF_TOKEN,
255
+ private=True
256
+ )
257
+
258
  <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
259
 
260
  ### Direct Use
 
296
  ## Training Details
297
 
298
  ### Training Data
299
+ データセット: llm-jp/magpie-sft-v1.0
300
+ データ量: 約50,000件の日本語サンプルのうちランダムに抽出した5000件
301
 
 
302
 
303
  [More Information Needed]
304
 
 
312
 
313
 
314
  #### Training Hyperparameters
315
+ LoRA 設定:
316
+ r=32
317
+ lora_alpha=32
318
+ lora_dropout=0.05
319
+ バッチサイズ: デバイスごとに 2
320
+ 勾配累積ステップ: 4
321
+ 学習率: 2e-4
322
+ 学習エポック数: 1
323
 
324
  - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
325
 
 
373
 
374
  Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
375
 
376
+ - **Hardware Type:** [NVIDIA L4]
377
+ - **Hours used:** [約1時間]
378
  - **Cloud Provider:** [More Information Needed]
379
  - **Compute Region:** [More Information Needed]
380
  - **Carbon Emitted:** [More Information Needed]