WatariNAKANO commited on
Commit
cfb61df
·
verified ·
1 Parent(s): 6302250

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +176 -0
README.md CHANGED
@@ -9,6 +9,7 @@ tags:
9
  license: apache-2.0
10
  language:
11
  - en
 
12
  ---
13
 
14
  # Uploaded model
@@ -20,3 +21,178 @@ 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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  license: apache-2.0
10
  language:
11
  - en
12
+ - ja
13
  ---
14
 
15
  # Uploaded model
 
21
  This llama model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
22
 
23
  [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
24
+
25
+
26
+ # 推論用コード
27
+
28
+ ```python
29
+ !pip uninstall unsloth -y
30
+ !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
31
+ !pip install --upgrade torch
32
+ !pip install --upgrade xformers
33
+
34
+ # Install Flash Attention 2 for softcapping support
35
+ import torch
36
+ if torch.cuda.get_device_capability()[0] >= 8:
37
+ !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
38
+
39
+ # Hugging Face Token を指定
40
+ HF_TOKEN = "your-token" #@param {type:"string"}
41
+
42
+ # llm-jp/llm-jp-3-13bを4bit量子化のqLoRA設定でロード。
43
+
44
+ from unsloth import FastLanguageModel
45
+ import torch
46
+ max_seq_length = 1024 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能
47
+ dtype = None # Noneにしておけば自動で設定
48
+ load_in_4bit = True # 今回は13Bモデルを扱うためTrue
49
+
50
+ model_id = "llm-jp/llm-jp-3-13b"
51
+ new_model_id = "llm-jp-3-13b-it" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
52
+ # FastLanguageModel インスタンスを作成
53
+ model, tokenizer = FastLanguageModel.from_pretrained(
54
+ model_name=model_id,
55
+ dtype=dtype,
56
+ load_in_4bit=load_in_4bit,
57
+ trust_remote_code=True,
58
+ )
59
+
60
+ # SFT用のモデルを用意
61
+ model = FastLanguageModel.get_peft_model(
62
+ model,
63
+ r = 32,
64
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
65
+ "gate_proj", "up_proj", "down_proj",],
66
+ lora_alpha = 32,
67
+ lora_dropout = 0.05,
68
+ bias = "none",
69
+ use_gradient_checkpointing = "unsloth",
70
+ random_state = 3407,
71
+ use_rslora = False,
72
+ loftq_config = None,
73
+ max_seq_length = max_seq_length,
74
+ )
75
+
76
+ # 学習に用いるデータセットの指定
77
+ # CC-BY-NC-SAですのでモデルはライセンスを継承する前提でお使いください。
78
+ # https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
79
+ # 関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)
80
+
81
+ from datasets import load_dataset
82
+
83
+ dataset = load_dataset("json", data_files="/content/ichikara-instruction-003-001-1.json")
84
+
85
+ # 学習時のプロンプトフォーマットの定義
86
+ prompt = """### 指示
87
+ {}
88
+ ### 回答
89
+ {}"""
90
+
91
+
92
+ """
93
+ formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
94
+ """
95
+ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
96
+ def formatting_prompts_func(examples):
97
+ input = examples["text"] # 入力データ
98
+ output = examples["output"] # 出力データ
99
+ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
100
+ return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
101
+ pass
102
+
103
+ # # 各データにフォーマットを適用
104
+ dataset = dataset.map(
105
+ formatting_prompts_func,
106
+ num_proc= 4, # 並列処理数を指定
107
+ )
108
+
109
+ dataset
110
+
111
+
112
+ # training_arguments: 学習の設定
113
+ from trl import SFTTrainer
114
+ from transformers import TrainingArguments
115
+ from unsloth import is_bfloat16_supported
116
+
117
+ trainer = SFTTrainer(
118
+ model = model,
119
+ tokenizer = tokenizer,
120
+ train_dataset=dataset["train"],
121
+ max_seq_length = max_seq_length,
122
+ dataset_text_field="formatted_text",
123
+ packing = False,
124
+ args = TrainingArguments(
125
+ per_device_train_batch_size = 2,
126
+ gradient_accumulation_steps = 4,
127
+ num_train_epochs = 1,
128
+ logging_steps = 10,
129
+ warmup_steps = 10,
130
+ save_steps=100,
131
+ save_total_limit=2,
132
+ max_steps=-1,
133
+ learning_rate = 2e-4,
134
+ fp16 = not is_bfloat16_supported(),
135
+ bf16 = is_bfloat16_supported(),
136
+ group_by_length=True,
137
+ seed = 3407,
138
+ output_dir = "outputs",
139
+ report_to = "none",
140
+ ),
141
+ )
142
+
143
+
144
+ #@title 学習実行
145
+ trainer_stats = trainer.train()
146
+
147
+
148
+ # データセットの読み込み。
149
+ import json
150
+ datasets = []
151
+ with open("/content//elyza-tasks-100-TV_0.jsonl", "r") as f:
152
+ item = ""
153
+ for line in f:
154
+ line = line.strip()
155
+ item += line
156
+ if item.endswith("}"):
157
+ datasets.append(json.loads(item))
158
+ item = ""
159
+
160
+
161
+ # 学習したモデルを用いてタスクを実行
162
+ from tqdm import tqdm
163
+
164
+ # 推論するためにモデルのモードを変更
165
+ FastLanguageModel.for_inference(model)
166
+
167
+ results = []
168
+ for dt in tqdm(datasets):
169
+ input = dt["input"]
170
+
171
+ prompt = f"""### 指���\n{input}\n### 回答\n"""
172
+
173
+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
174
+
175
+ outputs = model.generate(**inputs, max_new_tokens = 1024, use_cache = True, do_sample=False, repetition_penalty=1.2)
176
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
177
+
178
+ results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
179
+
180
+
181
+ # jsonlで保存
182
+ with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
183
+ for result in results:
184
+ json.dump(result, f, ensure_ascii=False)
185
+ f.write('\n')
186
+
187
+
188
+ # LoRAアダプタだけ保存
189
+ new_model_id = "WatariNAKANO/llm-jp-3-13b-it-2" #Fine-Tuningしたモデルにつけたい名前
190
+ model.push_to_hub_merged(
191
+ new_model_id+"_lora",
192
+ tokenizer=tokenizer,
193
+ save_method="lora",
194
+ token=HF_TOKEN,
195
+ private=True
196
+ )
197
+
198
+ ```