Views
No views yet
1# install some modules
2!pip uninstall unsloth -y
3!pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
4!pip install --upgrade torch
5!pip install --upgrade xformers
6!pip install ipywidgets --upgrade
7
8# Install Flash Attention 2 for softcapping support
9import torch
10if torch.cuda.get_device_capability()[0] >= 8:
11!pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
121# Load Pretrained model
2from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3from unsloth import FastLanguageModel
4import torch
5max_seq_length = 512
6dtype = None
7model_id = "llm-jp/llm-jp-3-13b"
8
9# Model name for SFT
10new_model_id = "llm-jp-3-13b-finetune-2"
11load_in_4bit = True
12# Make FastLanguageModel
13model, tokenizer = FastLanguageModel.from_pretrained(
14 model_name=model_id,
15 dtype=dtype,
16 load_in_4bit=load_in_4bit,
17 trust_remote_code=True,
18 )
19# Make model of SFT
20model = FastLanguageModel.get_peft_model(
21 model,
22 r = 32,
23 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",],
24 lora_alpha = 32,
25 lora_dropout = 0.05,
26 bias = "none",
27 use_gradient_checkpointing = "unsloth",
28 random_state = 3407,
29 use_rslora = False,
30 loftq_config = None,
31 max_seq_length = max_seq_length,)1# Load Hugging Face Token
2HF_TOKEN = "" #@param {type:"string"}
31# Load dataset
2# ref: https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
3# 関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)
4
5from datasets import load_dataset
6dataset = load_dataset("json", data_files="/content/ichikara-instruction-003-001-1.json")1# Define prompt format
2prompt = """### 指示
3 {}
4 ### 回答
5 {}"""
6
7 EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン)
8 def formatting_prompts_func(examples):
9 input = examples["text"] # 入力データ
10 output = examples["output"] # 出力データ
11 text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成
12 # print(text)
13 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す
14 pass
15
16# Apply defined prompt format
17 dataset = dataset.map(
18 formatting_prompts_func,
19 num_proc= 4, # 並列処理数を指定
20 )1# Prepare traininig
2from trl import SFTTrainer
3from transformers import TrainingArguments
4from unsloth import is_bfloat16_supported
5
6# llm-jp-13b
7trainer = SFTTrainer(
8 model = model,
9 tokenizer = tokenizer,
10 train_dataset=dataset["train"],
11 max_seq_length = max_seq_length,
12 dataset_text_field="formatted_text",
13 packing = False,
14 args = TrainingArguments(
15 per_device_train_batch_size = 2,
16 gradient_accumulation_steps = 4,
17 num_train_epochs = 1,
18 logging_steps = 10,
19 warmup_steps = 10,
20 save_steps=100,
21 save_total_limit=2,
22 max_steps=-1,
23 learning_rate = 2e-4,
24 fp16 = not is_bfloat16_supported(),
25 bf16 = is_bfloat16_supported(),
26 group_by_length=True,
27 seed = 3407,
28 output_dir = "outputs",
29 report_to = "none"
30 ),
31)
32 # Train
33 trainer_stats = trainer.train()1 # load ELYZA-tasks-100-TV
2 import json
3 datasets = []
4 with open("./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 # Test
2 from tqdm import tqdm
3 FastLanguageModel.for_inference(model)
4
5 results = []
6 for dt in tqdm(datasets):
7 input = dt["input"]
8
9 prompt = f"""### 指示\n{input}\n### 回答\n"""
10
11 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
12
13 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
14 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
15
16 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})1# Save result to jsonl and Hugging face
2with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
3 for result in results:
4 json.dump(result, f, ensure_ascii=False)
5 f.write('\n')
6
7model.push_to_hub_merged(
8 new_model_id,
9 tokenizer=tokenizer,
10 save_method="lora",
11 token=HF_TOKEN,
12 private=True
13)