Views
No views yet
1# Googleドライブに接続
2from google.colab import drive
3drive.mount('/content/drive')
4# 接続しているGPUの種類の表示
5!nvidia-smi
6
7# 必要なライブラリのインストール
8!pip uninstall unsloth -y
9!pip install xformers -q
10!pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git" -q
11!pip install -U torch -q
12!pip install -U peft -q
13
14# 必要なライブラリの読み込み
15from unsloth import FastLanguageModel
16from peft import PeftModel
17import torch
18import json
19from tqdm import tqdm
20import re1# ベースとなるモデルと学習したLoRAのアダプタ(本モデル)のIDやHugging face tokenを指定。
2model_id = "llm-jp/llm-jp-3-13b"
3adapter_id = "kazuHF/llm-jp-3-13b-it2_lora"
4HF_TOKEN = "huggingface_token"
5# unslothのFastLanguageModelで元のモデルとトークナイザーをロード。
6model, tokenizer = FastLanguageModel.from_pretrained(
7 model_name=model_id,
8 dtype=None,
9 load_in_4bit=True,
10 trust_remote_code=True,
11)
12
13# 元のモデルにLoRAのアダプタを統合。
14model = PeftModel.from_pretrained(model, adapter_id, token = HF_TOKEN)1# 単一の入力文に基づいて推論する関数の定義。
2def Decoder(input):
3 # 推論するためにモデルのモードを変更
4 FastLanguageModel.for_inference(model)
5 # 入力文による推論
6 prompt = f"""### 指示\n\n{str(input)}\n\n### 回答"""
7 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
8 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
9 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
10 print(prompt)
11 print(prediction)Decoder('犬と猫の見分け方は何か。')1# jsonlで作製されたタスクを一括処理する場合。
2datasets = []
3with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
4 for line in f:
5 if line.strip():
6 datasets.append(json.loads(line))
7
8# モデルで入力を一括処理。
9results = []
10for dt in tqdm(datasets):
11 # 推論するためにモデルのモードを変更
12 FastLanguageModel.for_inference(model)
13 # 入力文による推論
14 input = dt["input"]
15 prompt = f"""### 指示\n{input}\n### 回答\n"""
16 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
17 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
18 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
19 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
20
21# 結果をjsonlで保存。
22json_file_id = re.sub(".*/", "", adapter_id)
23with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
24 for result in results:
25 json.dump(result, f, ensure_ascii=False)
26 f.write('\n')