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