Views
No views yet
1!pip uninstall unsloth -y
2!pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
3!pip install --upgrade torch
4!pip install --upgrade xformers
5import torch
6if torch.cuda.get_device_capability()[0] >= 8:
7 !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
8
9HF_TOKEN = "your-token"
10
11## llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
12from unsloth import FastLanguageModel
13import torch
14max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
15dtype = None # Noneにしておけば自動で設定
16load_in_4bit = True # 今回は13Bモデルを扱うためTrue
17
18model_id = "llm-jp/llm-jp-3-13b"
19new_model_id = "llm-jp-3-13b-it-v1" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
20
21## FastLanguageModel インスタンスを作成
22model, tokenizer = FastLanguageModel.from_pretrained(
23 model_name=model_id,
24 dtype=dtype,
25 load_in_4bit=load_in_4bit,
26 trust_remote_code=True,
27)
28
29## SFT用のモデルを用意
30model = FastLanguageModel.get_peft_model(
31 model,
32 r = 8 # 32, # LoRAのランク
33 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
34 "gate_proj", "up_proj", "down_proj",],
35 lora_alpha = 32,
36 lora_dropout = 0.05,
37 bias = "none",
38 use_gradient_checkpointing = "unsloth",
39 random_state = 3407,
40 use_rslora = False,
41 loftq_config = None,
42 max_seq_length = max_seq_length,
43)
44
45## 学習に用いるデータセットの指定
46from datasets import load_dataset
47dataset = load_dataset("json", data_files="your-source/ichikara-instruction-003-001-1.json")
48
49
50## 学習時のプロンプトフォーマットの定義
51prompt = """・ 指示
52{}
53・ 回答
54{}"""
55
56EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
57def formatting_prompts_func(examples):
58 input = examples["text"] # 入力データ
59 output = examples["output"] # 出力データ
60 text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
61 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
62pass
63
64## 各データにフォーマットを適用
65dataset = dataset.map(
66 formatting_prompts_func,
67 num_proc= 4, # 並列処理数を指定
68)
69
70## 学習の設定
71from trl import SFTTrainer
72from transformers import TrainingArguments
73from unsloth import is_bfloat16_supported
74
75trainer = SFTTrainer(
76 model = model,
77 tokenizer = tokenizer,
78 train_dataset=dataset["train"],
79 max_seq_length = max_seq_length,
80 dataset_text_field="formatted_text",
81 packing = False,
82 args = TrainingArguments(
83 per_device_train_batch_size = 2,
84 gradient_accumulation_steps = 4,
85 num_train_epochs = 1,
86 logging_steps = 10,
87 warmup_steps = 10,
88 save_steps=100,
89 save_total_limit=2,
90 max_steps=-1,
91 learning_rate = 2e-4,
92 fp16 = not is_bfloat16_supported(),
93 bf16 = is_bfloat16_supported(),
94 group_by_length=True,
95 # optim="adamw_8bit",
96 # weight_decay=0.01,
97 # lr_scheduler_type = "linear",
98 seed = 3407,
99 output_dir = "outputs",
100 report_to = "wandb",
101 ),
102)
103
104## 学習実行
105trainer_stats = trainer.train()
106
107## ELYZA-tasks-100-TVの読み込み。事前にファイルをアップロードしてください
108import json
109datasets = []
110with open("your-source/elyza-tasks-100-TV_0.jsonl", "r") as f:
111 item = ""
112 for line in f:
113 line = line.strip()
114 item += line
115 if item.endswith("}"):
116 datasets.append(json.loads(item))
117 item = ""
118
119## 学習したモデルを用いてタスクを実行
120from tqdm import tqdm
121FastLanguageModel.for_inference(model)
122
123results = []
124for dt in tqdm(datasets):
125 input = dt["input"]
126
127 prompt = f"""### 指示\n{input}\n### 回答\n"""
128
129 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
130
131 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
132 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
133
134 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
135
136## jsonlで保存
137file_path = f"your-source/{new_model_id}_output.jsonl"
138with open(file_path, 'w', encoding='utf-8') as f:
139 for result in results:
140 json.dump(result, f, ensure_ascii=False)
141 f.write('\n')
142
143## LoRAアダプタだけ保存
144model.push_to_hub_merged(
145 new_model_id + "_lora",
146 tokenizer=tokenizer,
147 save_method="lora",
148 token=HF_TOKEN,
149 private=True
150)