nishijimat commited on
Commit
1bd7941
·
verified ·
1 Parent(s): 8bce475

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +209 -1
README.md CHANGED
@@ -21,4 +21,212 @@ This llama model was trained 2x faster with [Unsloth](https://github.com/unsloth
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
- 以下は、
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
25
+
26
+ 以下は、elyza-tasks-100-TV_0.jsonlの回答のためのコードです。
27
+
28
+ #nishijimat/llm-jp-3-13b-it
29
+
30
+ !pip uninstall unsloth -y
31
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
32
+
33
+ # Google Colab のデフォルトで入っているパッケージをアップグレード(Moriyasu さんありがとうございます)
34
+ !pip install --upgrade torch
35
+ !pip install --upgrade xformers
36
+
37
+ # notebookでインタラクティブな表示を可能とする(ただし、うまく動かない場合あり)
38
+ !pip install ipywidgets --upgrade
39
+
40
+ # Install Flash Attention 2 for softcapping support
41
+ import torch
42
+ if torch.cuda.get_device_capability()[0] >= 8:
43
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
44
+
45
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
46
+
47
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
48
+ from unsloth import FastLanguageModel
49
+ import torch
50
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
51
+ dtype = None # Noneにしておけば自動で設定
52
+ load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
53
+
54
+ model_id = "llm-jp-3-13b"
55
+ new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
56
+ # FastLanguageModel インスタンスを作成
57
+ model, tokenizer = FastLanguageModel.from_pretrained(
58
+ model_name=model_id,
59
+ dtype=dtype,
60
+ load_in_4bit=load_in_4bit,
61
+ trust_remote_code=True,
62
+ )
63
+
64
+ # SFT用のモデルを用意
65
+ model = FastLanguageModel.get_peft_model(
66
+ model,
67
+ r = 32,
68
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
69
+ "gate_proj", "up_proj", "down_proj",],
70
+ lora_alpha = 32,
71
+ lora_dropout = 0.05,
72
+ bias = "none",
73
+ use_gradient_checkpointing = "unsloth",
74
+ random_state = 3407,
75
+ use_rslora = False,
76
+ loftq_config = None,
77
+ max_seq_length = max_seq_length,
78
+ )
79
+
80
+ from google.colab import output
81
+ output.disable_custom_widget_manager()
82
+
83
+ # Hugging Face Token を指定
84
+ HF_TOKEN = "" #@param {type:"string"}
85
+
86
+ !pip install datasets
87
+
88
+ zip_file_path = '/content/drive/MyDrive/Distribution20241221_all.zip'
89
+ # 解凍先のディレクトリを指定(任意)
90
+ extract_dir = 'extracted_files'
91
+
92
+ # zip ファイルを解凍
93
+ !unzip -q {zip_file_path} -d {extract_dir}
94
+
95
+ # 学習に用いるデータセットの指定
96
+ # https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
97
+
98
+ from datasets import load_dataset
99
+
100
+ dataset = load_dataset("json", data_files="/content/extracted_files/Distribution20241221_all/ichikara-instruction-003-001-1.json")
101
+
102
+ # 学習時のプロンプトフォーマットの定義
103
+ prompt = """### 指示
104
+ {}
105
+ ### 回答
106
+ {}"""
107
+
108
+
109
+
110
+ """
111
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
112
+ """
113
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
114
+ def formatting_prompts_func(examples):
115
+ input = examples["text"] # 入力データ
116
+ output = examples["output"] # 出力データ
117
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
118
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
119
+ pass
120
+
121
+ # # 各データにフォーマットを適用
122
+ dataset = dataset.map(
123
+ formatting_prompts_func,
124
+ num_proc= 4, # 並列処理数を指定
125
+ )
126
+
127
+ dataset
128
+
129
+ # データを確認
130
+ print(dataset["train"]["formatted_text"][3])
131
+
132
+
133
+ from trl import SFTTrainer
134
+ from transformers import TrainingArguments
135
+ from unsloth import is_bfloat16_supported
136
+
137
+ trainer = SFTTrainer(
138
+ model = model,
139
+ tokenizer = tokenizer,
140
+ train_dataset=dataset["train"],
141
+ max_seq_length = max_seq_length,
142
+ dataset_text_field="formatted_text",
143
+ packing = False,
144
+ args = TrainingArguments(
145
+ per_device_train_batch_size = 2,
146
+ gradient_accumulation_steps = 4,
147
+ num_train_epochs = 1,
148
+ logging_steps = 10,
149
+ warmup_steps = 10,
150
+ save_steps=100,
151
+ save_total_limit=2,
152
+ max_steps=-1,
153
+ learning_rate = 2e-4,
154
+ fp16 = not is_bfloat16_supported(),
155
+ bf16 = is_bfloat16_supported(),
156
+ group_by_length=True,
157
+ seed = 3407,
158
+ output_dir = "outputs",
159
+ report_to = "none",
160
+ ),
161
+ )
162
+
163
+
164
+ #@title 現在のメモリ使用量を表示
165
+ gpu_stats = torch.cuda.get_device_properties(0)
166
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
167
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
168
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
169
+ print(f"{start_gpu_memory} GB of memory reserved.")
170
+
171
+ #@title 学習実行
172
+ trainer_stats = trainer.train()
173
+ # データセットの読み込み。
174
+ import json
175
+ datasets = []
176
+ with open("/content/drive/MyDrive/elyza-tasks-100-TV_0.jsonl", "r") as f:
177
+ item = ""
178
+ for line in f:
179
+ line = line.strip()
180
+ item += line
181
+ if item.endswith("}"):
182
+ datasets.append(json.loads(item))
183
+ item = ""
184
+
185
+ # 学習したモデルを用いてタスクを実行
186
+ from tqdm import tqdm
187
+
188
+ # 推論するためにモデルのモードを変更
189
+ FastLanguageModel.for_inference(model)
190
+
191
+ results = []
192
+ for dt in tqdm(datasets):
193
+ input = dt["input"]
194
+
195
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
196
+
197
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
198
+
199
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
200
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
201
+
202
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
203
+
204
+ import os
205
+
206
+ with open(f"/content/drive/MyDrive/{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
207
+ for result in results:
208
+ json.dump(result, f, ensure_ascii=False)
209
+ f.write('\n')
210
+ # jsonlで保存
211
+ with open(f"/content/drive/MyDrive/{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
212
+ for result in results:
213
+ json.dump(result, f, ensure_ascii=False)
214
+ f.write('\n')
215
+
216
+ # モデルとトークナイザーをHugging Faceにアップロード。
217
+ model.push_to_hub_merged(
218
+ new_model_id,
219
+ tokenizer=tokenizer,
220
+ save_method="lora",
221
+ token=HF_TOKEN,
222
+ private=True
223
+ )
224
+
225
+
226
+ 本コードは、unslothで学習したqLoRAのアダプタを用いてelyza-tasks-100-TVの出力を得るためのコードです。
227
+ Hugging Faceにアダプタをアップロードしていることが前提となります。
228
+ このコードはunslothを用いてモデルを読み込み、推論するためのコードをなります。
229
+ このコードで生成されたjsonlファイルは課題の成果物です。
230
+
231
+ ※本コードはGoogle Colabでの動作を想定しており、omunicampusでの動作を想定していません。
232
+