Views
No views yet
1
2# Install Flash Attention 2 for softcapping support
3import torch
4if torch.cuda.get_device_capability()[0] >= 8:
5 !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
6
7HF_TOKEN = "your-token"
8
9# llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
10
11from unsloth import FastLanguageModel
12import torch
13max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
14dtype = None # Noneにしておけば自動で設定
15load_in_4bit = True # 今回は13Bモデルを扱うためTrue
16
17model_id = "llm-jp/llm-jp-3-13b"
18new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
19# FastLanguageModel インスタンスを作成
20model, tokenizer = FastLanguageModel.from_pretrained(
21 model_name=model_id,
22 dtype=dtype,
23 load_in_4bit=load_in_4bit,
24 trust_remote_code=True,
25)
26
27# SFT用のモデルを用意
28model = FastLanguageModel.get_peft_model(
29 model,
30 r = 32,
31 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
32 "gate_proj", "up_proj", "down_proj",],
33 lora_alpha = 32,
34 lora_dropout = 0.05,
35 bias = "none",
36 use_gradient_checkpointing = "unsloth",
37 random_state = 3407,
38 use_rslora = False,
39 loftq_config = None,
40 max_seq_length = max_seq_length,
41)
42
43# 学習に用いるデータセットの指定
44# 今回はLLM-jp の公開している Ichikara Instruction を使います。
45
46from datasets import load_dataset
47
48dataset = load_dataset("json", data_files="")
49
50# 学習時のプロンプトフォーマットの定義
51prompt = """### 指示
52{}
53### 回答
54{}"""
55
56
57"""
58formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
59"""
60EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
61def formatting_prompts_func(examples):
62 input = examples["text"] # 入力データ
63 output = examples["output"] # 出力データ
64 text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
65 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
66pass
67
68# # 各データにフォーマットを適用
69dataset = dataset.map(
70 formatting_prompts_func,
71 num_proc= 4, # 並列処理数を指定
72)
73
74dataset
75
76# データを確認
77print(dataset["train"]["formatted_text"][3])
78
79"""
80training_arguments: 学習の設定
81
82 - output_dir:
83 -トレーニング後のモデルを保存するディレクトリ
84
85 - per_device_train_batch_size:
86 - デバイスごとのトレーニングバッチサイズ
87
88 - per_device_eval_batch_size:
89 - デバイスごとの評価バッチサイズ
90
91 - gradient_accumulation_steps:
92 - 勾配を更新する前にステップを積み重ねる回数
93
94 - optim:
95 - オプティマイザの設定
96
97 - num_train_epochs:
98 - エポック数
99
100 - eval_strategy:
101 - 評価の戦略 ("no"/"steps"/"epoch")
102
103 - eval_steps:
104 - eval_strategyが"steps"のとき、評価を行うstep間隔
105
106 - logging_strategy:
107 - ログ記録の戦略
108
109 - logging_steps:
110 - ログを出力するステップ間隔
111
112 - warmup_steps:
113 - 学習率のウォームアップステップ数
114
115 - save_steps:
116 - モデルを保存するステップ間隔
117
118 - save_total_limit:
119 - 保存しておくcheckpointの数
120
121 - max_steps:
122 - トレーニングの最大ステップ数
123
124 - learning_rate:
125 - 学習率
126
127 - fp16:
128 - 16bit浮動小数点の使用設定(第8回演習を参考にすると良いです)
129
130 - bf16:
131 - BFloat16の使用設定
132
133 - group_by_length:
134 - 入力シーケンスの長さによりバッチをグループ化 (トレーニングの効率化)
135
136 - report_to:
137 - ログの送信先 ("wandb"/"tensorboard"など)
138"""
139from trl import SFTTrainer
140from transformers import TrainingArguments
141from unsloth import is_bfloat16_supported
142
143trainer = SFTTrainer(
144 model = model,
145 tokenizer = tokenizer,
146 train_dataset=dataset["train"],
147 max_seq_length = max_seq_length,
148 dataset_text_field="formatted_text",
149 packing = False,
150 args = TrainingArguments(
151 per_device_train_batch_size = 2,
152 gradient_accumulation_steps = 4,
153 num_train_epochs = 1,
154 logging_steps = 10,
155 warmup_steps = 10,
156 save_steps=100,
157 save_total_limit=2,
158 max_steps=-1,
159 learning_rate = 2e-4,
160 fp16 = not is_bfloat16_supported(),
161 bf16 = is_bfloat16_supported(),
162 group_by_length=True,
163 seed = 3407,
164 output_dir = "outputs",
165 report_to = "none",
166 ),
167)
168
169#@title 学習実行
170trainer_stats = trainer.train()
171
172import json
173datasets = []
174with open("/content//elyza-tasks-100-TV_0.jsonl", "r") as f:
175 item = ""
176 for line in f:
177 line = line.strip()
178 item += line
179 if item.endswith("}"):
180 datasets.append(json.loads(item))
181 item = ""
182
183# 学習したモデルを用いてタスクを実行
184from tqdm import tqdm
185
186# 推論するためにモデルのモードを変更
187FastLanguageModel.for_inference(model)
188
189results = []
190for dt in tqdm(datasets):
191 input = dt["input"]
192
193 prompt = f"""### 指示\n{input}\n### 回答\n"""
194
195 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
196
197 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
198 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
199
200 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
201
202# jsonlで保存
203with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
204 for result in results:
205 json.dump(result, f, ensure_ascii=False)
206 f.write('\n')