Views
No views yet
1
2!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
3!pip install -U xformers --index-url https://download.pytorch.org/whl/cu124
4!pip install --no-deps "trl<0.9.0" peft accelerate bitsandbytes
5
6import torch
7if torch.cuda.get_device_capability()[0] >= 8:
8 !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
9
10from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
11from unsloth import FastLanguageModel
12import torch
13max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
14dtype = None # Noneにしておけば自動で設定
15load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
16
17model_id = "llm-jp/llm-jp-3-13b"
18new_model_id = "llm-jp-3-13b-finetune-2" #Fine-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
43HF_TOKEN = "mytoken"
44
45"""
46dataset: 学習に用いるデータセット
47
48 ベースコードでは以下のリンクからデータをダウンロードして使います。zipを展開(!unzip)してデータのパスを指定してください。
49 (https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/)
50 関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎.
51 ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)
52
53omnicampusの開発環境では取得したデータを左側にドラッグアンドドロップしてお使いください。
54"""
55from datasets import load_dataset
56
57dataset = load_dataset("json", data_files="./ichikara-instruction-003-001-1.json")
58dataset
59
60# 学習時のプロンプトフォーマットの定義
61prompt = """### 指示
62{}
63### 回答
64{}"""
65
66
67
68"""
69formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
70"""
71EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
72def formatting_prompts_func(examples):
73 input = examples["text"] # 入力データ
74 output = examples["output"] # 出力データ
75 text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
76 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
77pass
78
79# # 各データにフォーマットを適用
80dataset = dataset.map(
81 formatting_prompts_func,
82 num_proc= 4, # 並列処理数を指定
83)
84
85dataset
86print(dataset["train"]["formatted_text"][3])
87
88from trl import SFTTrainer
89from transformers import TrainingArguments
90from unsloth import is_bfloat16_supported
91
92trainer = SFTTrainer(
93 model = model,
94 tokenizer = tokenizer,
95 train_dataset=dataset["train"],
96 max_seq_length = max_seq_length,
97 dataset_text_field="formatted_text",
98 packing = False,
99 args = TrainingArguments(
100 per_device_train_batch_size = 2,
101 gradient_accumulation_steps = 4,
102 num_train_epochs = 1,
103 eval_steps=0.2,
104 logging_steps = 10,
105 warmup_steps = 10,
106 save_steps=100,
107 save_total_limit=2,
108 max_steps=-1,
109 learning_rate = 2e-4,
110 fp16 = not is_bfloat16_supported(),
111 bf16 = is_bfloat16_supported(),
112 group_by_length=True,
113 seed = 3407,
114 output_dir = "outputs",
115 ),
116)
117trainer_stats = trainer.train()
118gpu_stats = torch.cuda.get_device_properties(0)
119start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
120max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
121print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
122print(f"{start_gpu_memory} GB of memory reserved.")
123
124trainer_stats = trainer.train()
125
126model.push_to_hub_merged(
127 new_model_id,
128 tokenizer=tokenizer,
129 # save_method="lora",
130 token=HF_TOKEN,
131 private=True
132)
133