Views
No views yet
https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)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# 必要なライブラリを読み込み
8from unsloth import FastLanguageModel
9from peft import PeftModel
10import torch
11import json
12from tqdm import tqdm
13import re
14# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
15model_id = "llm-jp/llm-jp-3-13b"
16adapter_id = "katataku-dev/llm-jp-3-13b-it_lora"
17# Hugging Face Token を指定。
18# 下記の URL から Hugging Face Token を取得できますので下記の HF_TOKEN に入れてください。
19# https://huggingface.co/settings/tokens
20HF_TOKEN = "" #@param {type:"string"}
21# unslothのFastLanguageModelで元のモデルをロード。
22dtype = None # Noneにしておけば自動で設定
23load_in_4bit = True # 今回は13Bモデルを扱うためTrue
24
25model, tokenizer = FastLanguageModel.from_pretrained(
26 model_name=model_id,
27 dtype=dtype,
28 load_in_4bit=load_in_4bit,
29 trust_remote_code=True,
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
47# 推論するためにモデルのモードを変更
48FastLanguageModel.for_inference(model)
49
50results = []
51for dt in tqdm(datasets):
52 input = dt["input"]
53
54 prompt = f"""## 指示\n{input}\n## 回答\n"""
55
56 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
57
58 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
59 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n## 回答')[-1]
60
61 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
62
63# 結果をjsonlで保存。
64# ここではadapter_idを元にファイル名を決定しているが、ファイル名は任意で問題なし。
65json_file_id = re.sub(".*/", "", adapter_id)
66with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
67 for result in results:
68 json.dump(result, f, ensure_ascii=False)
69 f.write('\n')