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
15
16# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
17model_id = "llm-jp/llm-jp-3-13b"
18adapter_id = "hiroHugging/llm-jp-3-13b-it_lora"
19
20# unslothのFastLanguageModelで元のモデルをロード。
21dtype = None # Noneにしておけば自動で設定
22load_in_4bit = True # 今回は13Bモデルを扱うためTrue
23
24model, tokenizer = FastLanguageModel.from_pretrained(
25 model_name=model_id,
26 dtype=dtype,
27 load_in_4bit=load_in_4bit,
28 trust_remote_code=True,
29)
30
31# 元のモデルにLoRAのアダプタを統合。
32model = PeftModel.from_pretrained(model, adapter_id)
33
34# タスクとなるデータの読み込み。
35# 事前にデータをアップロードしてください。
36datasets = []
37with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
38 item = ""
39 for line in f:
40 line = line.strip()
41 item += line
42 if item.endswith("}"):
43 datasets.append(json.loads(item))
44 item = ""
45
46# モデルを用いてタスクの推論。
47# 推論するためにモデルのモードを変更
48FastLanguageModel.for_inference(model)
49
50results = []
51for dt in tqdm(datasets):
52 input = dt["input"]
53
54 prompt = f"""### 指示\n{input}\n### 回答\n"""
55 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
56 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
57 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
58
59 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
60
61# 結果をjsonlで保存。
62# ここではadapter_idを元にファイル名を決定しているが、ファイル名は任意で問題なし。
63json_file_id = re.sub(".*/", "", adapter_id)
64with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
65 for result in results:
66 json.dump(result, f, ensure_ascii=False)
67 f.write('\n')