Toki-AI commited on
Commit
b110378
·
verified ·
1 Parent(s): 5ed964b

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +93 -113
README.md CHANGED
@@ -11,150 +11,130 @@ language:
11
  - en
12
  ---
13
 
14
- # Uploaded model
15
 
16
- - **Developed by:** Toki-AI
17
- - **License:** apache-2.0
18
- - **Finetuned from model :** llm-jp/llm-jp-3-13b
19
 
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
  !pip list
 
 
25
 
26
- from unsloth import PatchDPOTrainer
27
- PatchDPOTrainer()
28
 
 
 
 
29
  from unsloth import FastLanguageModel
30
  import torch
31
- max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
32
- dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
33
- load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
34
- HF_TOKEN = "your_token"#ご自身のToken
 
 
35
  model, tokenizer = FastLanguageModel.from_pretrained(
36
- model_name = "Toki-AI/llm-jp-3-13b-finetune-241202", # 自分がUnslothを使ってFTして、loraだけアップロードしているモデル
37
  max_seq_length = max_seq_length,
38
  dtype = dtype,
39
  load_in_4bit = load_in_4bit,
40
- token = HF_TOKEN,
41
  )
 
42
 
43
- from huggingface_hub import login
44
-
45
-
46
- # 生成したトークンをペースト
47
- login(HF_TOKEN)
48
 
49
- from datasets import load_dataset
 
 
 
50
 
51
- # データセットをロード
52
- ds = load_dataset("weblab-GENIAC/aya-ja-nemotron-dpo-masked")
53
 
54
- # フィルタリング関数を定義
55
- def filter_short_examples(example):
56
- return (
57
- len(example['prompt']) <= 2000 and
58
- len(example['chosen']) <= 2000 and
59
- len(example['rejected']) <= 2000
60
- )
61
 
62
- # トレーニングデータをフィルタリング
63
- filtered_train = ds['train'].filter(filter_short_examples)
64
-
65
- # データセットをトレーニング用と評価用に分割 (80%をトレーニング用、20%を評価用)
66
- train_size = int(0.8 * len(filtered_train)) # トレーニングデータのサイズ
67
- eval_size = len(filtered_train) - train_size # 評価データのサイズ
68
-
69
- # インデックスを順序通りに生成 (ランダム性なし)
70
- train_indices = list(range(train_size)) # トレーニング用インデックス
71
- eval_indices = list(range(train_size, len(filtered_train))) # 評価用インデックス
72
-
73
- # トレーニングデータと評価データを選択
74
- train_dataset = filtered_train.select(train_indices)
75
- eval_dataset = filtered_train.select(eval_indices)
76
-
77
- # データセットのサイズを出力
78
- print(f"トレーニングデータセットのサイズ: {len(train_dataset)}")
79
- print(f"評価データセットのサイズ: {len(eval_dataset)}")
80
-
81
- use_dataset = train_dataset.select(range(100))
82
- use_dataset
83
-
84
- # One must patch the DPO Trainer first!
85
- from unsloth import PatchDPOTrainer
86
- PatchDPOTrainer()
87
-
88
- from transformers import TrainingArguments
89
- from trl import DPOTrainer, DPOConfig
90
- from unsloth import is_bfloat16_supported
91
-
92
- dpo_trainer = DPOTrainer(
93
- model = model,
94
- ref_model = None,
95
- args = DPOConfig(
96
- per_device_train_batch_size = 2,
97
- gradient_accumulation_steps = 4,
98
- warmup_ratio = 0.1,
99
- num_train_epochs = 1,
100
- learning_rate = 5e-6,
101
- fp16 = not is_bfloat16_supported(),
102
- bf16 = is_bfloat16_supported(),
103
- logging_steps = 1,
104
- optim = "adamw_8bit",
105
- weight_decay = 0.0,
106
- lr_scheduler_type = "linear",
107
- seed = 42,
108
- output_dir = "outputs",
109
- report_to = "none", # Use this for WandB etc
110
- ),
111
- beta = 0.1,
112
- train_dataset = use_dataset, #raw_datasets["train"],
113
- # eval_dataset = raw_datasets["test"],
114
- tokenizer = tokenizer,
115
- max_length = 2048,
116
- max_prompt_length = 1024,
117
- )
118
 
119
- dpo_trainer.train()
 
120
 
121
- # ELYZA-tasks-100-TVの読み込み。
122
- import json
123
  datasets = []
124
  with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
125
  item = ""
126
  for line in f:
127
- line = line.strip()
128
- item += line
129
- if item.endswith("}"):
130
- datasets.append(json.loads(item))
131
- item = ""
132
-
133
- # 学習したモデルを用いてタスクを実行
134
- from tqdm import tqdm
135
-
136
- # 推論するためにモデルのモードを変更
137
- FastLanguageModel.for_inference(model)
138
 
139
  results = []
140
  for dt in tqdm(datasets):
141
- input = dt["input"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- prompt = f"""### 指示\n{input}\n### 回答\n"""
144
 
145
- inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
146
 
147
- outputs = model.generate(**inputs, max_new_tokens = 2048, use_cache = True, do_sample=False, repetition_penalty=1.2)
148
- prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
149
 
150
- results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
151
 
152
- #modelをhugging faceにアップロード
153
- # LoRAアダプタだけ保存
154
- model.push_to_hub_merged(
155
- "llm-jp-3-13b-finetune-241202_lora-DPO-12-17",#保存するモデルの名前
156
- tokenizer=tokenizer,
157
- save_method="lora",#loraだけ保存
158
- token=HF_TOKEN,
159
- private=True
160
- )
 
11
  - en
12
  ---
13
 
 
14
 
15
+ ## 概要
 
 
16
 
17
+ [llm-jp/llm-jp-3-13b](https://huggingface.co/llm-jp/llm-jp-3-13b) をベースに、LoRA(Low-Rank Adaptation)を用いたモデルである[Toki-AI/llm-jp-3-13b-finetune-241202](https://huggingface.co/Toki-AI/llm-jp-3-13b-finetune-241202)に対して、DPOを適用したモデルである。
18
+
19
+ - **Developed by:** Toki-AI
20
+ - **License:** apache-2.0
21
+ - **Finetuned from model:** [llm-jp/llm-jp-3-13b](https://huggingface.co/llm-jp/llm-jp-3-13b)
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
+ - [weblab-GENIAC/aya-ja-nemotron-dpo-masked](https://huggingface.co/datasets/weblab-GENIAC/aya-ja-nemotron-dpo-masked)
28
+
29
+ ## 推論環境の準備
30
+
31
+ 以下のようにライブラリをインストールしてください(環境によっては適宜調整)。
32
+
33
+ ```bash
34
+ pip install transformers
35
+ pip install datasets
36
+ pip install accelerate
37
+ pip install trl
38
+ pip install peft
39
+ pip install bitsandbytes # 4bit量子化利用時など、GPUに応じて追加でインストール
40
+ ```
41
+
42
+ `!pip list` などで依存パッケージが正しくインストールされているかを確認しておきます。
43
+
44
+ ```bash
45
  !pip list
46
+ ```
47
+
48
 
49
+ ## 推論方法
 
50
 
51
+ ### 1. モデルのロード
52
+
53
+ ```python
54
  from unsloth import FastLanguageModel
55
  import torch
56
+
57
+ max_seq_length = 2048 # 推論時に使用する最大シーケンス長
58
+ dtype = None # Noneで自動検出 (Tesla T4, V100ならfp16、Ampere+ならbfloat16)
59
+ load_in_4bit = True # メモリ削減のため4bit量子化を使用
60
+ HF_TOKEN = "your_token"
61
+
62
  model, tokenizer = FastLanguageModel.from_pretrained(
63
+ model_name = "Toki-AI/llm-jp-3-13b-finetune-241202",
64
  max_seq_length = max_seq_length,
65
  dtype = dtype,
66
  load_in_4bit = load_in_4bit,
67
+ token = HF_TOKEN
68
  )
69
+ ```
70
 
71
+ ### 2. Hugging Face Hubへのログイン
 
 
 
 
72
 
73
+ ```python
74
+ from huggingface_hub import login
75
+ login(HF_TOKEN) # Hugging Faceのアクセストークンを入力
76
+ ```
77
 
78
+ ### 3. 推論実行例 (ELYZA-tasks-100-TV)
 
79
 
80
+ 以下は `elyza-tasks-100-TV_0.jsonl` のタスクに対して推論を行い、回答を取得する例です。
 
 
 
 
 
 
81
 
82
+ ```python
83
+ import json
84
+ from tqdm import tqdm
85
+ from unsloth import FastLanguageModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ # 推論のためにモデルのモードを切り替え
88
+ FastLanguageModel.for_inference(model)
89
 
90
+ # JSONLファイルの読み込み
 
91
  datasets = []
92
  with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
93
  item = ""
94
  for line in f:
95
+ line = line.strip()
96
+ item += line
97
+ if item.endswith("}"):
98
+ datasets.append(json.loads(item))
99
+ item = ""
 
 
 
 
 
 
100
 
101
  results = []
102
  for dt in tqdm(datasets):
103
+ input_text = dt["input"]
104
+ prompt = f"""### 指示\n{input_text}\n### 回答\n"""
105
+
106
+ # トークナイズ & 推論
107
+ inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
108
+ outputs = model.generate(
109
+ **inputs,
110
+ max_new_tokens=2048,
111
+ use_cache=True,
112
+ do_sample=False,
113
+ repetition_penalty=1.2
114
+ )
115
+ prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
116
+
117
+ results.append({
118
+ "task_id": dt["task_id"],
119
+ "input": input_text,
120
+ "output": prediction
121
+ })
122
+
123
+ # 結果を確認
124
+ for r in results[:3]:
125
+ print(r)
126
+ ```
127
 
128
+ 本サンプルコードでは `repetition_penalty=1.2` を指定していますが、各種パラメータは用途に応じて変更してください (例: `temperature`, `top_p`, `max_new_tokens` など)。
129
 
 
130
 
 
 
131
 
132
+ ## ライセンス
133
 
134
+ 本モデルは [Apache License 2.0](./LICENSE) のもとで配布されています。
135
+ ベースモデルである [llm-jp/llm-jp-3-13b](https://huggingface.co/llm-jp/llm-jp-3-13b) のライセンスおよび利用規約もあわせてご確認ください。
136
+
137
+
138
+ 本モデルの利用にあたっては、各種規約を遵守してください。
139
+
140
+ ---