Views
No views yet
1# python 3.10.12
2!pip install -U pip
3!pip install -U transformers
4!pip install -U bitsandbytes
5!pip install -U accelerate
6!pip install -U datasets
7!pip install -U peft
8!pip install -U trl
9!pip install -U wandb
10!pip install ipywidgets --upgrade1!pip install huggingface_hub
2!huggingface-cli login
3
4# Hugging Face Token
5HF_TOKEN = "my_token"1from transformers import (
2 AutoModelForCausalLM,
3 AutoTokenizer,
4 BitsAndBytesConfig,
5 TrainingArguments,
6 logging,
7)
8from peft import (
9 LoraConfig,
10 PeftModel,
11 get_peft_model,
12)
13import os, torch, gc
14from datasets import load_dataset
15import bitsandbytes as bnb
16from trl import SFTTrainer1# モデルを読み込み。
2base_model_id = "llm-jp/llm-jp-3-13b"
3new_model_id = "llm-jp-3-13b-finetune" #Fine-Tuningしたモデルにつけたい名前
4
5# 量子化の設定
6bnb_config = BitsAndBytesConfig(
7 load_in_4bit=True,
8 bnb_4bit_quant_type="nf4", # nf4は通常のINT4より精度が高く、ニューラルネットワークの分布に最適です
9 bnb_4bit_compute_dtype=torch.bfloat16,
10)
11
12# モデル
13model = AutoModelForCausalLM.from_pretrained(
14 base_model_id,
15 quantization_config=bnb_config,
16 device_map="auto"
17)
18# トークナイザ
19tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)1# モデル内の4bit量子化線形層を探します。
2def find_all_linear_names(model):
3 cls = bnb.nn.Linear4bit # 4bit量子化線形層クラスを指定
4 lora_module_names = set() # ここに取得した線形層を保持します。
5
6 # モデル内の全てのモジュールを探索します
7 for name, module in model.named_modules():
8 if isinstance(module, cls): # モジュールが4bit量子化線形層の場合
9 names = name.split('.') # モジュールの名前を分割 (ネストされてる際などに対処)
10 lora_module_names.add(names[0] if len(names) == 1 else names[-1]) # 最下層の名前をlora_module_namesに追加
11
12 # 'lm_head' は16ビット演算の際に除外する必要があるため、lora_module_namesから削除
13 if 'lm_head' in lora_module_names:
14 lora_module_names.remove('lm_head')
15
16 return list(lora_module_names) # lora_module_namesをリストに変換して返します。
17
18modules = find_all_linear_names(model)1# PEFTの構成設定
2peft_config = LoraConfig(
3 r=16,
4 lora_alpha=32,
5 lora_dropout=0.05,
6 bias="none",
7 task_type="CAUSAL_LM",
8 target_modules=modules,
9)
10
11model = get_peft_model(model, peft_config)1# 学習に用いるデータセットの指定(LLM-jp の公開している Ichikara Instruction)
2# あらかじめ,使用申請を後にダウンロード + google driveをマウントした上で,本コードで使用できる環境にしました.
3
4dataset = load_dataset("json", data_files="/content/Distribution20241221_all/ichikara-instruction-003-001-1.json")
5dataset1# 学習時のプロンプトフォーマットの定義
2prompt = """### 指示
3{}
4### 回答
5{}"""
6
7
8# 各データをプロンプトに合わせた形式に合わせる
9EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
10def formatting_prompts_func(examples):
11 input = examples["text"] # 入力データ
12 output = examples["output"] # 出力データ
13 text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
14 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
15pass
16
17# 各データにフォーマットを適用
18dataset = dataset.map(
19 formatting_prompts_func,
20 num_proc= 4, # 並列処理数を指定
21)
22
23dataset1# 学習の設定
2training_arguments = TrainingArguments(
3 output_dir=new_model_id,
4 per_device_train_batch_size=1,
5 gradient_accumulation_steps=2,
6 optim="paged_adamw_32bit",
7 num_train_epochs=1,
8 logging_strategy="steps",
9 logging_steps=10,
10 warmup_steps=10,
11 save_steps=100,
12 save_total_limit = 2,
13 max_steps = -1,
14 learning_rate=5e-5,
15 fp16=False,
16 bf16=False,
17 seed = 3407,
18 group_by_length=True,
19 report_to="none"
20)
21
22
23# Supervised Fine-Tuningに関する設定
24trainer = SFTTrainer(
25 model=model,
26 train_dataset=dataset["train"],
27 peft_config=peft_config,
28 max_seq_length= 512,
29 dataset_text_field="formatted_text",
30 tokenizer=tokenizer,
31 args=training_arguments,
32 packing= False,
33)
34
35model.config.use_cache = False # キャッシュ機能を無効化
36trainer.train() # トレーニングを実行1# jsonlデータの読み込み
2import json
3datasets = []
4with open("/content/drive/MyDrive/LLM講座/最終課題/elyza-tasks-100-TV_0.jsonl", "r") as f:
5 item = ""
6 for line in f:
7 line = line.strip()
8 item += line
9 if item.endswith("}"):
10 datasets.append(json.loads(item))
11 item = ""1# モデルによる推論
2from tqdm import tqdm
3
4results = []
5for data in tqdm(datasets):
6
7 input = data["input"]
8
9 prompt = f"""### 指示
10 {input}
11 ### 回答
12 """
13
14 tokenized_input = tokenizer.encode(prompt, add_special_tokens=False, return_tensors="pt").to(model.device)
15 attention_mask = torch.ones_like(tokenized_input)
16
17 with torch.no_grad():
18 outputs = model.generate(
19 tokenized_input,
20 attention_mask=attention_mask,
21 max_new_tokens=100,
22 do_sample=False,
23 repetition_penalty=1.2,
24 pad_token_id=tokenizer.eos_token_id
25 )[0]
26 output = tokenizer.decode(outputs[tokenized_input.size(1):], skip_special_tokens=True)
27
28 results.append({"task_id": data["task_id"], "input": input, "output": output})1# 回答jsolファイルの生成
2import re
3jsonl_id = re.sub(".*/", "", new_model_id)
4with open(f"./{jsonl_id}-outputs.jsonl", 'w', encoding='utf-8') as f:
5 for result in results:
6 json.dump(result, f, ensure_ascii=False) # ensure_ascii=False for handling non-ASCII characters
7 f.write('\n')
8
9
10# モデルとトークナイザーをHugging Faceにアップロード
11model.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving
12tokenizer.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving