hzhn commited on
Commit
c969d2d
·
verified ·
1 Parent(s): a1c4819

Update README.md

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
+ # Instruction Tuning
25
+
26
+ The models have been fine-tuned on the following datasets.
27
+
28
+ | Language | Dataset | description |
29
+ |:---|:---|:---|
30
+ |Japanese|[ichikara-instruction-003-001-1.json](https://liat-aip.sakura.ne.jp/wp/llm%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E6%97%A5%E6%9C%AC%E8%AA%9E%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%A9%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%83%87%E3%83%BC%E3%82%BF%E4%BD%9C%E6%88%90/llm%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E6%97%A5%E6%9C%AC%E8%AA%9E%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%A9%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%83%87%E3%83%BC%E3%82%BF-%E5%85%AC%E9%96%8B/)| A manually constructed instruction dataset |
31
+
32
+ データセット作成チーム:
33
+ 関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)
34
+
35
+
36
+ # Usage
37
+
38
+ 以下はElyza-tasks-100-TV_0.jsonlの回答のためのコードです。
39
+
40
+ ```python
41
+ from transformers import (
42
+ AutoModelForCausalLM,
43
+ AutoTokenizer,
44
+ BitsAndBytesConfig,
45
+ TrainingArguments,
46
+ logging,
47
+ )
48
+ from peft import (
49
+ LoraConfig,
50
+ PeftModel,
51
+ get_peft_model,
52
+ )
53
+ import os, torch, gc
54
+ from datasets import load_dataset
55
+ import bitsandbytes as bnb
56
+ from trl import SFTTrainer
57
+ ```
58
+
59
+ ```python
60
+ # Hugging Face Token
61
+ HF_TOKEN = "your_token"
62
+ ```
63
+
64
+ ```python
65
+ base_model_id = "llm-jp/llm-jp-3-13b"
66
+ new_model_id = "llm-jp-3-13b-it_lora"
67
+ ```
68
+
69
+ ```python
70
+ bnb_config = BitsAndBytesConfig(
71
+ load_in_4bit=True,
72
+ bnb_4bit_quant_type="nf4",
73
+ bnb_4bit_compute_dtype=torch.bfloat16,
74
+ )
75
+
76
+ model = AutoModelForCausalLM.from_pretrained(
77
+ base_model_id,
78
+ quantization_config=bnb_config,
79
+ device_map="auto"
80
+ )
81
+
82
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
83
+ ```
84
+
85
+ ```python
86
+ def find_all_linear_names(model):
87
+ cls = bnb.nn.Linear4bit # 4bit量子化線形層クラスを指定
88
+ lora_module_names = set() # ここに取得した線形層を保持します。
89
+
90
+ # モデル内の全てのモジュールを探索します
91
+ for name, module in model.named_modules():
92
+ if isinstance(module, cls): # モジュールが4bit量子化線形層の場合
93
+ names = name.split('.') # モジュールの名前を分割 (ネストされてる際などに対処)
94
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1]) # 最下層の名前をlora_module_namesに追加
95
+
96
+ # 'lm_head' は16ビット演算の際に除外する必要があるため、lora_module_namesから削除
97
+ if 'lm_head' in lora_module_names:
98
+ lora_module_names.remove('lm_head')
99
+
100
+ return list(lora_module_names) # lora_module_namesをリストに変換して返します。
101
+
102
+ modules = find_all_linear_names(model)
103
+ ```
104
+
105
+ ```python
106
+ peft_config = LoraConfig(
107
+ r=16,
108
+ lora_alpha=32,
109
+ lora_dropout=0.05,
110
+ bias="none",
111
+ task_type="CAUSAL_LM",
112
+ target_modules=modules,
113
+ )
114
+
115
+ model = get_peft_model(model, peft_config)
116
+ ```
117
+
118
+ ```python
119
+ dataset = load_dataset("json", data_files="./ichikara-instruction-003-001-1.json")
120
+ ```
121
+
122
+ ```python
123
+ # 学習時のプロンプトフォーマットの定義
124
+ prompt = """### 指示
125
+ {}
126
+ ### 回答
127
+ {}"""
128
+
129
+
130
+ """
131
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
132
+ """
133
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
134
+ def formatting_prompts_func(examples):
135
+ input = examples["text"] # 入力データ
136
+ output = examples["output"] # 出力データ
137
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
138
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
139
+ pass
140
+
141
+ # # 各データにフォーマットを適用
142
+ dataset = dataset.map(
143
+ formatting_prompts_func,
144
+ num_proc= 4, # 並列処理数を指定
145
+ )
146
+ ```
147
+
148
+ ```python
149
+ training_arguments = TrainingArguments(
150
+ output_dir=new_model_id,
151
+ per_device_train_batch_size=1,
152
+ gradient_accumulation_steps=2,
153
+ optim="paged_adamw_32bit",
154
+ num_train_epochs=1,
155
+ logging_strategy="steps",
156
+ logging_steps=10,
157
+ warmup_steps=10,
158
+ save_steps=100,
159
+ save_total_limit = 2,
160
+ max_steps = -1,
161
+ learning_rate=5e-5,
162
+ fp16=False,
163
+ bf16=False,
164
+ seed = 3407,
165
+ group_by_length=True,
166
+ report_to="none"
167
+ )
168
+ ```
169
+
170
+ ```python
171
+ trainer = SFTTrainer(
172
+ model=model,
173
+ train_dataset=dataset["train"],
174
+ peft_config=peft_config,
175
+ max_seq_length= 512,
176
+ dataset_text_field="formatted_text",
177
+ tokenizer=tokenizer,
178
+ args=training_arguments,
179
+ packing= False,
180
+ )
181
+
182
+ model.config.use_cache = False # キャッシュ機能を無効化
183
+ trainer.train() # トレーニングを実行
184
+ ```
185
+
186
+ ```python
187
+ import json
188
+ datasets = []
189
+ with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
190
+ item = ""
191
+ for line in f:
192
+ line = line.strip()
193
+ item += line
194
+ if item.endswith("}"):
195
+ datasets.append(json.loads(item))
196
+ item = ""
197
+ ```
198
+
199
+ ```python
200
+ from tqdm import tqdm
201
+
202
+ results = []
203
+ for data in tqdm(datasets):
204
+
205
+ input = data["input"]
206
+
207
+ prompt = f"""### 指示
208
+ {input}
209
+ ### 回答
210
+ """
211
+
212
+ tokenized_input = tokenizer.encode(prompt, add_special_tokens=False, return_tensors="pt").to(model.device)
213
+ attention_mask = torch.ones_like(tokenized_input)
214
+
215
+ with torch.no_grad():
216
+ outputs = model.generate(
217
+ tokenized_input,
218
+ attention_mask=attention_mask,
219
+ max_new_tokens=100,
220
+ do_sample=False,
221
+ repetition_penalty=1.2,
222
+ pad_token_id=tokenizer.eos_token_id
223
+ )[0]
224
+ output = tokenizer.decode(outputs[tokenized_input.size(1):], skip_special_tokens=True)
225
+
226
+ results.append({"task_id": data["task_id"], "input": input, "output": output})
227
+ ```
228
+
229
+ ```python
230
+ import re
231
+ jsonl_id = re.sub(".*/", "", new_model_id)
232
+ with open(f"./{jsonl_id}-outputs.jsonl", 'w', encoding='utf-8') as f:
233
+ for result in results:
234
+ json.dump(result, f, ensure_ascii=False) # ensure_ascii=False for handling non-ASCII characters
235
+ f.write('\n')
236
+ ```