Views
No views yet
1# 必要なライブラリをインストール
2%%capture
3!pip install unsloth
4!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
5!pip install -U torch
6!pip install -U peft
7
8# 必要なライブラリを読み込み
9from unsloth import FastLanguageModel
10from peft import PeftModel
11import torch
12import json
13from tqdm import tqdm
14import re
15from pathlib import Path
16
17# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
18model_id = "llm-jp/llm-jp-3-13b"
19adapter_id = "morikazu/llm-jp-3-13b-finetuned_ten_1"
20
21test_dataset_path = "/content/elyza-tasks-100-TV_0.jsonl" # テストデータセットのパス
22print(test_dataset_path)
23
24# Hugging Face Token を指定。
25# 下記の URL から Hugging Face Token を取得できますので下記の HF_TOKEN に入れてください。
26# https://huggingface.co/settings/tokens
27HF_TOKEN = "{Token}" #@param {type:"string"}
28
29# unslothのFastLanguageModelで元のモデルをロード。
30dtype = None # Noneにしておけば自動で設定
31load_in_4bit = True # 今回は13Bモデルを扱うためTrue
32
33model, tokenizer = FastLanguageModel.from_pretrained(
34 model_name=model_id,
35 dtype=dtype,
36 load_in_4bit=load_in_4bit,
37 trust_remote_code=True,
38)
39
40# 元のモデルにLoRAのアダプタを統合。
41model = PeftModel.from_pretrained(model, adapter_id, token = HF_TOKEN)
42
43# タスクとなるデータの読み込み。
44# 事前にデータをアップロードしてください。
45datasets = []
46with open(test_dataset_path, "r") as f:
47 item = ""
48 for line in f:
49 line = line.strip()
50 item += line
51 if item.endswith("}"):
52 datasets.append(json.loads(item))
53 item = ""
54
55# モデルを用いてタスクの推論。
56
57# 推論するためにモデルのモードを変更
58FastLanguageModel.for_inference(model)
59
60results = []
61for dt in tqdm(datasets):
62 input = dt["input"]
63
64 prompt = f"""### 指示\n{input}\n### 回答\n"""
65
66 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
67
68 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
69 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
70
71 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
72
73# 結果をjsonlで保存。
74
75# ここではadapter_idを元にファイル名を決定しているが、ファイル名は任意で問題なし。
76json_file_id = re.sub(".*/", "", adapter_id)
77with open("output.jsonl", 'w', encoding='utf-8') as f:
78 for result in results:
79 json.dump(result, f, ensure_ascii=False)
80 f.write('\n')
81