Views
No views yet
1# llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
2from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3from unsloth import FastLanguageModel
4import torch
5max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
6dtype = None # Noneにしておけば自動で設定
7load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
8
9model_id = "llm-jp/llm-jp-3-13b"
10new_model_id = "llm-jp-3-13b-finetune-2" #Fine-Tuningしたモデルにつけたい名前
11# FastLanguageModel インスタンスを作成
12model, tokenizer = FastLanguageModel.from_pretrained(
13 model_name=model_id,
14 dtype=dtype,
15 load_in_4bit=load_in_4bit,
16 trust_remote_code=True,
17)
18# SFT用のモデルを用意
19model = FastLanguageModel.get_peft_model(
20 model,
21 r = 32,
22 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
23 "gate_proj", "up_proj", "down_proj",],
24 lora_alpha = 32,
25 lora_dropout = 0.05,
26 bias = "none",
27 use_gradient_checkpointing = "unsloth",
28 random_state = 3407,
29 use_rslora = False,
30 loftq_config = None,
31 max_seq_length = max_seq_length,
32)
33# 学習時のプロンプトフォーマットの定義
34prompt = """### 指示
35{}
36### 回答
37{}"""
38
39
40
41"""
42formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
43"""
44EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
45def formatting_prompts_func(examples):
46 input = examples["text"] # 入力データ
47 output = examples["output"] # 出力データ
48 text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
49 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
50pass
51# # 各データにフォーマットを適用
52dataset = dataset.map(
53 formatting_prompts_func,
54 num_proc= 4, # 並列処理数を指定
55)
56dataset
57from trl import SFTTrainer
58from transformers import TrainingArguments
59from unsloth import is_bfloat16_supported
60
61trainer = SFTTrainer(
62 model = model,
63 tokenizer = tokenizer,
64 train_dataset=dataset["train"],
65 max_seq_length = max_seq_length,
66 dataset_text_field="formatted_text",
67 packing = False,
68 args = TrainingArguments(
69 per_device_train_batch_size = 2,
70 gradient_accumulation_steps = 4,
71 num_train_epochs = 1,
72 logging_steps = 10,
73 warmup_steps = 10,
74 save_steps=100,
75 save_total_limit=2,
76 max_steps=-1,
77 learning_rate = 2e-4,
78 fp16 = not is_bfloat16_supported(),
79 bf16 = is_bfloat16_supported(),
80 group_by_length=True,
81 seed = 3407,
82 output_dir = "outputs",
83 report_to = "none",
84 ),
85)
86#@title 学習実行
87trainer_stats = trainer.train()
88# 学習したモデルを用いてタスクを実行
89from tqdm import tqdm
90# 推論するためにモデルのモードを変更
91FastLanguageModel.for_inference(model)
92results = []
93for dt in tqdm(datasets):
94 input = dt["input"]
95 prompt = f"""### 指示\n{input}\n### 回答\n"""
96 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
97 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
98 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
99 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})