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