Views
No views yet
1!pip install unsloth
2!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
3!pip install -U torch
4!pip install -U peft
5
6from unsloth import FastLanguageModel
7from peft import PeftModel
8import torch
9import json
10from tqdm import tqdm
11import re
12
13# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
14model_id = "llm-jp/llm-jp-3-13b"
15adapter_id = "idakazoo/llm-jp-3-13b-it-idk_lora"
16
17# Hugging Face Token を指定。
18HF_TOKEN = "YOUR_TOKEN"
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, token = HF_TOKEN)
33
34# タスクとなるデータの読み込み。
35datasets = []
36with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
37 item = ""
38 for line in f:
39 line = line.strip()
40 item += line
41 if item.endswith("}"):
42 datasets.append(json.loads(item))
43 item = ""
44
45# モデルを用いてタスクの推論。
46# 推論するためにモデルのモードを変更
47FastLanguageModel.for_inference(model)
48
49results = []
50for dt in tqdm(datasets):
51 input = dt["input"]
52 prompt = f"""### 指示\n{input}\n### 回答\n"""
53 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
54 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
55 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
56 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
57
58# 結果をjsonlで保存。
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')