Views
No views yet
1# 必要なライブラリをインストール
2!pip install unsloth
3!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
4!pip install -U torch
5!pip install -U peft
6
7# 必要なライブラリを読み込み
8from unsloth import FastLanguageModel
9from peft import PeftModel
10import torch
11import json
12from tqdm import tqdm
13import re
14
15# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
16model_id = "sue124/llm-jp-3-13b-ft-uns-exp018_dpo_lora"
17
18from google.colab import userdata
19HF_TOKEN=userdata.get('HF_TOKEN')
20
21# unslothのFastLanguageModelで元のモデルをロード。
22dtype = None # Noneにしておけば自動で設定
23load_in_4bit = True # 今回は13Bモデルを扱うためTrue
24
25model, tokenizer = FastLanguageModel.from_pretrained(
26 model_name=model_id,
27 dtype=dtype,
28 load_in_4bit=load_in_4bit,
29 trust_remote_code=True,
30)
31
32# タスクとなるデータの読み込み。
33# 事前にデータをアップロードしてください。
34datasets = []
35with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
36 item = ""
37 for line in f:
38 line = line.strip()
39 item += line
40 if item.endswith("}"):
41 datasets.append(json.loads(item))
42 item = ""
43
44# モデルを用いてタスクの推論。
45
46# 推論するためにモデルのモードを変更
47FastLanguageModel.for_inference(model)
48
49results = []
50for dt in tqdm(datasets):
51 input = dt["input"]
52
53 prompt = f"""必ず指示に従うこと。簡潔に200文字までで回答してください。### 指示\n{input}\n### 回答\n"""
54
55 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
56
57 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
58 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1].lstrip("\n")
59 prediction = re.sub(r"[*#]", "", prediction)
60
61 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
62
63# 結果をjsonlで保存。
64json_file_id = model_id.split("/")[-1]
65with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
66 for result in results:
67 json.dump(result, f, ensure_ascii=False)
68 f.write('\n')