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