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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
library_name: transformers
|
3 |
-
tags: []
|
4 |
---
|
5 |
|
6 |
# Model Card for Model ID
|
7 |
|
8 |
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
|
10 |
-
|
11 |
-
|
12 |
## Model Details
|
13 |
|
14 |
### Model Description
|
|
|
1 |
+
---
|
2 |
+
datasets:
|
3 |
+
- kinokokoro/ichikara-instruction-003
|
4 |
+
language:
|
5 |
+
- ja
|
6 |
+
base_model:
|
7 |
+
- llm-jp/llm-jp-3-13b
|
8 |
+
---
|
9 |
+
|
10 |
+
elyza-tasks-100-TV_0.jsonl の回答モデルの作成のためのコードです。
|
11 |
+
サンプルコードに対して以下の変更を行いスコア改善を試みました。
|
12 |
+
- データセットを ichikara-instruction-003 の全てのファイルを利用するよう変更
|
13 |
+
- 学習率(learning_rate) を 2e-5へ変更
|
14 |
+
- 累積勾配(gradient_accumulation_steps) を 4 に変更
|
15 |
+
- RoRAのRANKを 32 に変更
|
16 |
+
|
17 |
+
自宅のPC(RTX3090) でコードを実行し、解答を出力しました。
|
18 |
+
|
19 |
+
```python
|
20 |
+
|
21 |
+
import wandb
|
22 |
+
import os
|
23 |
+
|
24 |
+
WANDB_API_KEY = "my-token"
|
25 |
+
wandb.login(key=WANDB_API_KEY)
|
26 |
+
wandb.init(project='llm2024-competition')
|
27 |
+
|
28 |
+
HF_TOKEN = "my-token"
|
29 |
+
|
30 |
+
from transformers import (
|
31 |
+
AutoModelForCausalLM,
|
32 |
+
AutoTokenizer,
|
33 |
+
BitsAndBytesConfig,
|
34 |
+
TrainingArguments,
|
35 |
+
logging,
|
36 |
+
)
|
37 |
+
from peft import (
|
38 |
+
LoraConfig,
|
39 |
+
PeftModel,
|
40 |
+
get_peft_model,
|
41 |
+
)
|
42 |
+
import os, torch, gc
|
43 |
+
from datasets import load_dataset
|
44 |
+
import bitsandbytes as bnb
|
45 |
+
from trl import SFTTrainer
|
46 |
+
|
47 |
+
SEED_VALUE = 42
|
48 |
+
|
49 |
+
base_model_id = "llm-jp/llm-jp-3-13b"
|
50 |
+
new_model_id = "llm-jp-3-13b-finetune" #Fine-Tuningしたモデルにつけたい名前
|
51 |
+
|
52 |
+
bnb_config = BitsAndBytesConfig(
|
53 |
+
load_in_4bit=True,
|
54 |
+
bnb_4bit_quant_type="nf4", # nf4は通常のINT4より精度が高く、ニューラルネットワークの分布に最適です
|
55 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
56 |
+
)
|
57 |
+
|
58 |
+
|
59 |
+
model = AutoModelForCausalLM.from_pretrained(
|
60 |
+
base_model_id,
|
61 |
+
quantization_config=bnb_config,
|
62 |
+
device_map="cuda:0" #auto"
|
63 |
+
)
|
64 |
+
|
65 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
|
66 |
+
|
67 |
+
|
68 |
+
def find_all_linear_names(model):
|
69 |
+
cls = bnb.nn.Linear4bit # 4bit量子化線形層クラスを指定
|
70 |
+
lora_module_names = set() # ここに取得した線形層を保持します。
|
71 |
+
|
72 |
+
# モデル内の全てのモジュールを探索します
|
73 |
+
for name, module in model.named_modules():
|
74 |
+
if isinstance(module, cls): # モジュールが4bit量子化線形層の場合
|
75 |
+
names = name.split('.') # モジュールの名前を分割 (ネストされてる際などに対処)
|
76 |
+
lora_module_names.add(names[0] if len(names) == 1 else names[-1]) # 最下層の名前をlora_module_namesに追加
|
77 |
+
|
78 |
+
# 'lm_head' は16ビット演算の際に除外する必要があるため、lora_module_namesから削除
|
79 |
+
if 'lm_head' in lora_module_names:
|
80 |
+
lora_module_names.remove('lm_head')
|
81 |
+
|
82 |
+
return list(lora_module_names) # lora_module_namesをリストに変換して返します。
|
83 |
+
|
84 |
+
modules = find_all_linear_names(model)
|
85 |
+
|
86 |
+
peft_config = LoraConfig(
|
87 |
+
r=32, #16,
|
88 |
+
lora_alpha=32,
|
89 |
+
lora_dropout=0.05,
|
90 |
+
bias="none",
|
91 |
+
task_type="CAUSAL_LM",
|
92 |
+
target_modules=modules,
|
93 |
+
)
|
94 |
+
|
95 |
+
model = get_peft_model(model, peft_config)
|
96 |
+
|
97 |
+
|
98 |
+
from datasets import concatenate_datasets, DatasetDict
|
99 |
+
|
100 |
+
# 全てのデータセットを読み込み
|
101 |
+
dataset0 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-001-1.json")
|
102 |
+
dataset1 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-001-1.json")
|
103 |
+
dataset2 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-001-2.2.json")
|
104 |
+
dataset3 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-001-5.2.json")
|
105 |
+
dataset4 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-001-2.1.json")
|
106 |
+
dataset5 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-001-5.1.json")
|
107 |
+
dataset6 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-002-1.json")
|
108 |
+
dataset7 = load_dataset("json", data_files="./Distribution20241221_all/ichikara-instruction-003-003-1.json")
|
109 |
+
|
110 |
+
datasets_to_concatenate = [
|
111 |
+
dataset0["train"],
|
112 |
+
dataset1["train"],
|
113 |
+
dataset2["train"],
|
114 |
+
dataset3["train"],
|
115 |
+
dataset4["train"],
|
116 |
+
dataset5["train"],
|
117 |
+
dataset6["train"],
|
118 |
+
dataset7["train"]
|
119 |
+
]
|
120 |
+
|
121 |
+
concatenated_train_dataset = concatenate_datasets(datasets_to_concatenate)
|
122 |
+
|
123 |
+
dataset_all = DatasetDict({
|
124 |
+
"train": concatenated_train_dataset
|
125 |
+
})
|
126 |
+
|
127 |
+
# 学習時のプロンプトフォーマットの定義
|
128 |
+
prompt = """### 指示
|
129 |
+
{}
|
130 |
+
### 回答
|
131 |
+
{}"""
|
132 |
+
|
133 |
+
|
134 |
+
"""
|
135 |
+
formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
|
136 |
+
"""
|
137 |
+
EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
|
138 |
+
def formatting_prompts_func(examples):
|
139 |
+
input = examples["text"] # 入力データ
|
140 |
+
output = examples["output"] # 出力データ
|
141 |
+
text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
|
142 |
+
return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
|
143 |
+
pass
|
144 |
+
|
145 |
+
# # 各データにフォーマットを適用
|
146 |
+
dataset = dataset.map(
|
147 |
+
formatting_prompts_func,
|
148 |
+
num_proc= 4, # 並列処理数を指��
|
149 |
+
)
|
150 |
+
|
151 |
+
# データをtrainデータとtestデータに分割 (test_sizeの比率に)
|
152 |
+
dataset = dataset["train"].train_test_split(test_size=0.1, seed=SEED_VALUE)
|
153 |
+
|
154 |
+
|
155 |
+
training_arguments = TrainingArguments(
|
156 |
+
output_dir=new_model_id,
|
157 |
+
per_device_train_batch_size=1, #
|
158 |
+
gradient_accumulation_steps=4, # def: 2
|
159 |
+
optim="paged_adamw_32bit",
|
160 |
+
num_train_epochs=1, # def: 1
|
161 |
+
logging_strategy="steps",
|
162 |
+
logging_steps=10,
|
163 |
+
warmup_steps=10,
|
164 |
+
save_steps=100,
|
165 |
+
save_total_limit = 2,
|
166 |
+
max_steps = -1, # def:-1
|
167 |
+
learning_rate=2e-5, # def:5e-5,
|
168 |
+
fp16= False,
|
169 |
+
bf16= False,
|
170 |
+
seed = SEED_VALUE,
|
171 |
+
group_by_length=True,
|
172 |
+
report_to="wandb"
|
173 |
+
)
|
174 |
+
|
175 |
+
trainer = SFTTrainer(
|
176 |
+
model=model,
|
177 |
+
train_dataset=dataset["train"],
|
178 |
+
peft_config=peft_config,
|
179 |
+
max_seq_length= 512,
|
180 |
+
dataset_text_field="formatted_text",
|
181 |
+
tokenizer=tokenizer,
|
182 |
+
args=training_arguments,
|
183 |
+
packing= False,
|
184 |
+
)
|
185 |
+
|
186 |
+
model.config.use_cache = False # キャッシュ機能を無効化
|
187 |
+
trainer.train() # トレーニングを実行
|
188 |
+
|
189 |
+
from datetime import datetime
|
190 |
+
|
191 |
+
# 現在の日時を取得
|
192 |
+
now = datetime.now()
|
193 |
+
|
194 |
+
# フォーマットを指定して日時を文字列に変換
|
195 |
+
formatted_date = now.strftime("%Y%m%d_%H%M%S") # 例: "20241214_153045"
|
196 |
+
|
197 |
+
print(formatted_date)
|
198 |
+
|
199 |
+
# タスクとなるデータの読み込み。
|
200 |
+
# omnicampusの開発環境では、左にタスクのjsonlをドラッグアンドドロップしてから実行。
|
201 |
+
import json
|
202 |
+
datasets = []
|
203 |
+
with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
|
204 |
+
item = ""
|
205 |
+
for line in f:
|
206 |
+
line = line.strip()
|
207 |
+
item += line
|
208 |
+
if item.endswith("}"):
|
209 |
+
datasets.append(json.loads(item))
|
210 |
+
item = ""
|
211 |
+
|
212 |
+
|
213 |
+
# モデルによるタスクの推論。
|
214 |
+
from tqdm import tqdm
|
215 |
+
|
216 |
+
results = []
|
217 |
+
for data in tqdm(datasets):
|
218 |
+
|
219 |
+
input = data["input"]
|
220 |
+
|
221 |
+
prompt = f"""### 指示
|
222 |
+
{input}
|
223 |
+
### 回答
|
224 |
+
"""
|
225 |
+
|
226 |
+
tokenized_input = tokenizer.encode(prompt, add_special_tokens=False, return_tensors="pt").to(model.device)
|
227 |
+
attention_mask = torch.ones_like(tokenized_input)
|
228 |
+
|
229 |
+
with torch.no_grad():
|
230 |
+
outputs = model.generate(
|
231 |
+
tokenized_input,
|
232 |
+
attention_mask=attention_mask,
|
233 |
+
max_new_tokens=100,
|
234 |
+
do_sample=False,
|
235 |
+
repetition_penalty=1.2,
|
236 |
+
pad_token_id=tokenizer.eos_token_id
|
237 |
+
)[0]
|
238 |
+
output = tokenizer.decode(outputs[tokenized_input.size(1):], skip_special_tokens=True)
|
239 |
+
|
240 |
+
results.append({"task_id": data["task_id"], "input": input, "output": output})
|
241 |
+
|
242 |
+
# こちらで生成されたjsolを提出してください。
|
243 |
+
# 本コードではinputとeval_aspectも含んでいますが、なくても問題ありません。
|
244 |
+
# 必須なのはtask_idとoutputとなります。
|
245 |
+
import re
|
246 |
+
jsonl_id = re.sub(".*/", "", new_model_id)
|
247 |
+
with open(f"./{jsonl_id}-outputs-{formatted_date}.jsonl", 'w', encoding='utf-8') as f:
|
248 |
+
for result in results:
|
249 |
+
json.dump(result, f, ensure_ascii=False) # ensure_ascii=False for handling non-ASCII characters
|
250 |
+
f.write('\n')
|
251 |
+
|
252 |
+
# モデルとトークナイザーをHugging Faceにアップロード
|
253 |
+
model.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving
|
254 |
+
tokenizer.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving
|
255 |
+
|
256 |
+
|
257 |
+
|
258 |
+
```
|
259 |
+
|
260 |
+
|
261 |
+
|
262 |
---
|
263 |
library_name: transformers
|
|
|
264 |
---
|
265 |
|
266 |
# Model Card for Model ID
|
267 |
|
268 |
<!-- Provide a quick summary of what the model is/does. -->
|
269 |
|
|
|
|
|
270 |
## Model Details
|
271 |
|
272 |
### Model Description
|