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