Views
No views yet
1
2# 必要なライブラリをインストール
3%%capture
4!pip install unsloth
5!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
6!pip install -U torch
7!pip install -U peft
8
9# 必要なライブラリを読み込み
10from unsloth import FastLanguageModel
11from peft import PeftModel
12import torch
13import json
14from tqdm import tqdm
15import re
16
17# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
18model_id = "llm-jp/llm-jp-3-13b"
19adapter_id = "fumikawa/llm-jp-3-13b-it_lora_20241206"
20
21# Hugging Face Token を指定。Colab secret key使用。
22from google.colab import userdata
23HF_TOKEN=userdata.get('HF_TOKEN')
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# タスクとなるデータの読み込み。
40datasets = []
41with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
42 item = ""
43 for line in f:
44 line = line.strip()
45 item += line
46 if item.endswith("}"):
47 datasets.append(json.loads(item))
48 item = ""
49
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')