File size: 11,244 Bytes
768d3d4
 
 
 
 
 
 
 
1bc814c
768d3d4
1bc814c
e5a3930
 
768d3d4
 
 
 
 
1bc814c
768d3d4
 
 
 
772dd33
 
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
 
 
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
 
 
772dd33
 
 
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
 
772dd33
b8c1d8b
772dd33
b8c1d8b
 
 
772dd33
 
 
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
 
 
772dd33
b8c1d8b
 
 
772dd33
b8c1d8b
772dd33
 
 
 
 
 
 
 
 
 
b8c1d8b
 
 
 
 
 
 
 
 
 
772dd33
6d177b0
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
 
 
f4b0c9b
 
b8c1d8b
772dd33
 
 
 
 
b8c1d8b
772dd33
 
 
b8c1d8b
772dd33
 
 
 
b8c1d8b
772dd33
b8c1d8b
772dd33
 
 
b8c1d8b
 
 
772dd33
b8c1d8b
772dd33
b8c1d8b
772dd33
b8c1d8b
 
 
772dd33
b8c1d8b
772dd33
b8c1d8b
 
 
772dd33
b8c1d8b
772dd33
 
 
 
b8c1d8b
772dd33
 
b8c1d8b
 
 
 
 
772dd33
 
 
 
 
 
 
 
 
 
 
 
b8c1d8b
 
 
 
 
 
 
 
 
 
 
 
 
772dd33
 
 
b8c1d8b
772dd33
b8c1d8b
 
 
 
 
 
 
 
fbfe906
b8c1d8b
fbfe906
 
 
b8c1d8b
 
 
fbfe906
 
 
 
b8c1d8b
 
fbfe906
b8c1d8b
 
 
fbfe906
b8c1d8b
fbfe906
 
 
 
 
6acdb89
b8c1d8b
 
 
 
 
 
 
 
 
 
 
b81eee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8c1d8b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
---
base_model: llm-jp/llm-jp-3-13b
tags:
- text-generation-inference
- transformers
- unsloth
- llama
- trl
license: cc-by-nc-4.0
language:
- ja
datasets:
- DeL-TaiseiOzaki/Tengentoppa-sft-v1.0
---

# Uploaded  model

- **Developed by:** daichira
- **License:** cc-by-nc-4.0
- **Finetuned from model :** llm-jp/llm-jp-3-13b

This llama model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.

[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)

### README.md

# llm-jp-3-13b-itnew9

## 概要

このプロジェクトは、Hugging Face上で提供される言語モデル`llm-jp/llm-jp-3-13b`を基盤とし、さらなる指示応答タスク向けに微調整(SFT: Supervised Fine-Tuning)を施した'daichira/llm-jp-3-13b-finetune2'から、さらに後述のコードによりSFTを施したモデル`llm-jp-3-13b-itnew9`を公開するものです。このREADMEは、モデルのセットアップ、トレーニング、推論の再現性を確保するための手順を示します。

---

## 前提条件

このプロジェクトを実行するには、以下の環境とツールが必要です:

- Python 3.8以上
- Google Colabまたはローカル環境 (GPU推奨)
- Hugging Faceアクセストークン (HF\_TOKEN)

---

## セットアップ手順

### 1. ライブラリのインストール

Google Colabの場合、以下のコマンドを使用して必要なライブラリをインストールします:

```bash
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
!pip install --upgrade torch
!pip install --upgrade xformers
!pip install ipywidgets --upgrade
```

Flash Attention 2をサポートするために、以下をインストールします:

```python
import torch
if torch.cuda.get_device_capability()[0] >= 8:
    !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
```

### 2. モデルとトークナイザーのロード

以下のコードを使用して、Hugging Faceからベースモデルをロードし、LoRAの設定を適用します:

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
from unsloth import FastLanguageModel

max_seq_length = 1024
dtype = None
load_in_4bit = True
model_id = "daichira/llm-jp-3-13b-finetune2"
new_model_id = "llm-jp-3-13b-itnew9"

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=model_id,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
    trust_remote_code=True,
)

model = FastLanguageModel.get_peft_model(
    model,
    r=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_alpha=32,
    lora_dropout=0.05,
    bias="none",
    use_gradient_checkpointing="unsloth",
    random_state=3407,
    use_rslora=False,
    loftq_config=None,
    max_seq_length=max_seq_length,
)

```

---

## データセットの準備

### データの分割と保存

以下のコードでデータセットをHugging Faceからロードし、分割して保存します:

```python
HF_TOKEN = "Your_token" # Write権限

!pip install datasets
import os
from datasets import load_dataset

dataset = load_dataset("DeL-TaiseiOzaki/Tengentoppa-sft-v1.0", split="train")
chunk_size = 30000
output_dir = "/content/tengentoppa_chunks"
os.makedirs(output_dir, exist_ok=True)

total_rows = len(dataset)
num_chunks = (total_rows + chunk_size - 1) // chunk_size

for i in range(num_chunks):
    start_idx = i * chunk_size
    end_idx = min(start_idx + chunk_size, total_rows)
    chunk = dataset.select(range(start_idx, end_idx))
    chunk_file = f"{output_dir}/tengentoppa_chunk_{i+1}.json"
    chunk.to_json(chunk_file)
    print(f"Saved chunk {i+1}/{num_chunks} to {chunk_file}")

print("All chunks have been saved!")
```

### JSON形式でのデータセット読み込み

以下のコードでJSONデータセットをロードします:

```python
json_path = "/content/tengentoppa_chunks/tengentoppa_chunk_3.json"
dataset = load_dataset("json", data_files=json_path)
print(dataset)
```

---

## トレーニングの設定

以下の手順でトレーニングを設定します:

```python
prompt = """### 指示
{}
### 回答
{}"""
EOS_TOKEN = tokenizer.eos_token

def formatting_prompts_func(examples):
    input_text = examples["instruction"]
    output_text = examples["output"]
    return {"formatted_text": prompt.format(input_text, output_text) + EOS_TOKEN}

dataset = dataset.map(formatting_prompts_func, num_proc=4)

from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset["train"],
    max_seq_length=max_seq_length,
    dataset_text_field="formatted_text",
    args=TrainingArguments(
        per_device_train_batch_size=6,
        gradient_accumulation_steps=4,
        num_train_epochs=1,
        logging_steps=50,
        warmup_steps=500,
        save_steps=500,
        save_total_limit=2,
        learning_rate=3e-4,
        fp16=not is_bfloat16_supported(),
        bf16=is_bfloat16_supported(),
        group_by_length=True,
        seed=3407,
        output_dir="outputs",
    ),
)

# 学習実行
torch.cuda.empty_cache()
trainer.train()
```

---

## 推論

以下のコードでトレーニング済みモデルを使用して推論を行います:

```python
import json
from tqdm import tqdm

with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
    datasets = [json.loads(line) for line in f if line.strip().endswith("}")]

FastLanguageModel.for_inference(model)

results = []
for dt in tqdm(datasets):
    input_text = dt["input"]
    prompt = f"### 指示\n{input_text}\n### 回答\n"

    inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
    outputs = model.generate(**inputs, max_new_tokens=512, use_cache=True, do_sample=False, repetition_penalty=1.2)
    prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]

    results.append({"task_id": dt["task_id"], "input": input_text, "output": prediction})

with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
    for result in results:
        json.dump(result, f, ensure_ascii=False)
        f.write('\n')
```

---

## 注意事項

- 本モデルは日本語専用で設計されています。
- 再現性を確保するため、ランダムシードを固定しています (`seed=3407`)。
- モデルのパラメータ量が大きいため、十分なGPUメモリを確保してください (推奨: 16GB以上)。

---

## 実行コード全体
```python
# 必要なライブラリのインストール
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
!pip install --upgrade torch
!pip install --upgrade xformers
!pip install ipywidgets --upgrade

# Flash Attention 2のインストール
import torch
if torch.cuda.get_device_capability()[0] >= 8:
    !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"

# モデルとトークナイザーのロード
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from unsloth import FastLanguageModel

# モデル設定
max_seq_length = 1024
dtype = None
load_in_4bit = True
model_id = "daichira/llm-jp-3-13b-finetune2"
new_model_id = "llm-jp-3-13b-itnew9"

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=model_id,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
    trust_remote_code=True,
)

# SFT用のモデル設定
model = FastLanguageModel.get_peft_model(
    model,
    r=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_alpha=32,
    lora_dropout=0.05,
    bias="none",
    use_gradient_checkpointing="unsloth",
    random_state=3407,
    use_rslora=False,
    loftq_config=None,
    max_seq_length=max_seq_length,
)

# Hugging Faceのトークン設定
HF_TOKEN = "your_token"

# データセットの準備
!pip install datasets
import os
from datasets import load_dataset

dataset = load_dataset("DeL-TaiseiOzaki/Tengentoppa-sft-v1.0", split="train")
chunk_size = 30000
output_dir = "/content/tengentoppa_chunks"
os.makedirs(output_dir, exist_ok=True)

total_rows = len(dataset)
num_chunks = (total_rows + chunk_size - 1) // chunk_size

for i in range(num_chunks):
    start_idx = i * chunk_size
    end_idx = min(start_idx + chunk_size, total_rows)
    chunk = dataset.select(range(start_idx, end_idx))
    chunk_file = f"{output_dir}/tengentoppa_chunk_{i+1}.json"
    chunk.to_json(chunk_file)
    print(f"Saved chunk {i+1}/{num_chunks} to {chunk_file}")

print("All chunks have been saved!")

# JSON形式のデータセットをロード
json_path = "/content/tengentoppa_chunks/tengentoppa_chunk_3.json"
dataset = load_dataset("json", data_files=json_path)
print(dataset)

# プロンプトフォーマットの適用
prompt = """### 指示
{}
### 回答
{}"""
EOS_TOKEN = tokenizer.eos_token

def formatting_prompts_func(examples):
    input_text = examples["instruction"]
    output_text = examples["output"]
    return {"formatted_text": prompt.format(input_text, output_text) + EOS_TOKEN}

dataset = dataset.map(formatting_prompts_func, num_proc=4)

# トレーニングの設定
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset["train"],
    max_seq_length=max_seq_length,
    dataset_text_field="formatted_text",
    args=TrainingArguments(
        per_device_train_batch_size=6,
        gradient_accumulation_steps=4,
        num_train_epochs=1,
        logging_steps=50,
        warmup_steps=500,
        save_steps=500,
        save_total_limit=2,
        learning_rate=3e-4,
        fp16=not is_bfloat16_supported(),
        bf16=is_bfloat16_supported(),
        group_by_length=True,
        seed=3407,
        output_dir="outputs",
    ),
)

# 学習実行
torch.cuda.empty_cache()
trainer.train()

# 推論の準備
import json
from tqdm import tqdm

with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
    datasets = [json.loads(line) for line in f if line.strip().endswith("}")]

FastLanguageModel.for_inference(model)

results = []
for dt in tqdm(datasets):
    input_text = dt["input"]
    prompt = f"""### 指示\n{input_text}\n### 回答\n"""

    inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
    outputs = model.generate(**inputs, max_new_tokens=512, use_cache=True, do_sample=False, repetition_penalty=1.2)
    prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]

    results.append({"task_id": dt["task_id"], "input": input_text, "output": prediction})

# 推論結果の保存
with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
    for result in results:
        json.dump(result, f, ensure_ascii=False)
        f.write('\n')
```


```