kenakayama commited on
Commit
e99faf1
·
verified ·
1 Parent(s): fdbc050

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +162 -0
README.md CHANGED
@@ -20,3 +20,165 @@ language:
20
  This llama model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
21
 
22
  [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  This llama model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
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
+ # Usage
25
+ The below code is the procedure from model import to inference. (Environment: Google Colaboratory, T4 GPU)
26
+
27
+ ~~~
28
+ !pip uninstall unsloth -y
29
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
30
+
31
+ !pip install --upgrade torch
32
+ !pip install --upgrade xformers
33
+
34
+ import torch
35
+ if torch.cuda.get_device_capability()[0] >= 8:
36
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
37
+
38
+ HF_TOKEN = [YOURTOKEN]
39
+
40
+ from unsloth import FastLanguageModel
41
+ import torch
42
+ max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
43
+ dtype = None # Noneにしておけば自動で設定
44
+ load_in_4bit = True # 今回は13Bモデルを扱うためTrue
45
+
46
+ model_id = "llm-jp/llm-jp-3-13b"
47
+ new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
48
+ # FastLanguageModel インスタンスを作成
49
+ model, tokenizer = FastLanguageModel.from_pretrained(
50
+ model_name=model_id,
51
+ dtype=dtype,
52
+ load_in_4bit=load_in_4bit,
53
+ trust_remote_code=True,
54
+ )
55
+
56
+ # SFT用のモデルを用意
57
+ model = FastLanguageModel.get_peft_model(
58
+ model,
59
+ r = 32,
60
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
61
+ "gate_proj", "up_proj", "down_proj",],
62
+ lora_alpha = 32,
63
+ lora_dropout = 0.05,
64
+ bias = "none",
65
+ use_gradient_checkpointing = "unsloth",
66
+ random_state = 3407,
67
+ use_rslora = False,
68
+ loftq_config = None,
69
+ max_seq_length = max_seq_length,
70
+ )
71
+
72
+ from google.colab import drive
73
+ drive.mount('/content/drive')
74
+
75
+ from datasets import load_dataset
76
+
77
+ dataset = load_dataset("json", data_files="/content/drive/MyDrive/Colab Notebooks/LLM/final/traindata/Distribution20241221_all/ichikara-instruction-003-001-1.json")
78
+
79
+ # 学習時のプロンプトフォーマットの定義
80
+ prompt = """### 指示
81
+ {}
82
+ ### 回答
83
+ {}"""
84
+
85
+
86
+ """
87
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
88
+ """
89
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
90
+ def formatting_prompts_func(examples):
91
+ input = examples["text"] # 入力データ
92
+ output = examples["output"] # 出力データ
93
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
94
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
95
+ pass
96
+
97
+ # # 各データにフォーマットを適用
98
+ dataset = dataset.map(
99
+ formatting_prompts_func,
100
+ num_proc= 4, # 並列処理数を指定
101
+ )
102
+
103
+ from trl import SFTTrainer
104
+ from transformers import TrainingArguments
105
+ from unsloth import is_bfloat16_supported
106
+
107
+ trainer = SFTTrainer(
108
+ model = model,
109
+ tokenizer = tokenizer,
110
+ train_dataset=dataset["train"],
111
+ max_seq_length = max_seq_length,
112
+ dataset_text_field="formatted_text",
113
+ packing = False,
114
+ args = TrainingArguments(
115
+ per_device_train_batch_size = 2,
116
+ gradient_accumulation_steps = 4,
117
+ num_train_epochs = 1,
118
+ logging_steps = 10,
119
+ warmup_steps = 10,
120
+ save_steps=100,
121
+ save_total_limit=2,
122
+ max_steps=-1,
123
+ learning_rate = 2e-4,
124
+ fp16 = not is_bfloat16_supported(),
125
+ bf16 = is_bfloat16_supported(),
126
+ group_by_length=True,
127
+ seed = 3407,
128
+ output_dir = "outputs",
129
+ report_to = "none",
130
+ ),
131
+ )
132
+
133
+ gpu_stats = torch.cuda.get_device_properties(0)
134
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
135
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
136
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
137
+ print(f"{start_gpu_memory} GB of memory reserved.")
138
+
139
+ trainer_stats = trainer.train()
140
+
141
+ import json
142
+ datasets = []
143
+ with open("/content/drive/MyDrive/Colab Notebooks/LLM/final/testdata/elyza-tasks-100-TV_0.jsonl", "r") as f:
144
+ item = ""
145
+ for line in f:
146
+ line = line.strip()
147
+ item += line
148
+ if item.endswith("}"):
149
+ datasets.append(json.loads(item))
150
+ item = ""
151
+
152
+ from tqdm import tqdm
153
+
154
+ # 推論するためにモデルのモードを変更
155
+ FastLanguageModel.for_inference(model)
156
+
157
+ results = []
158
+ for dt in tqdm(datasets):
159
+ input = dt["input"]
160
+
161
+ prompt = f"""### 指示\n{input}\n### 回答\n"""
162
+
163
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
164
+
165
+ outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
166
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
167
+
168
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
169
+
170
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
171
+ for result in results:
172
+ json.dump(result, f, ensure_ascii=False)
173
+ f.write('\n')
174
+
175
+
176
+ model.push_to_hub_merged(
177
+ new_model_id+"_lora",
178
+ tokenizer=tokenizer,
179
+ save_method="lora",
180
+ token=HF_TOKEN,
181
+ private=True
182
+ )
183
+
184
+ ~~~