Views
No views yet
1# 必要なライブラリをインストール
2!pip install unsloth
3!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
4!pip install -U torch
5!pip install -U peft
6
7# Google Colabの場合、デフォルトで入っているパッケージをアップグレード
8!pip install --upgrade torch
9!pip install --upgrade xformers
10
11# 必要なライブラリを読み込み
12from unsloth import FastLanguageModel
13from peft import PeftModel
14import torch
15import json
16from tqdm import tqdm
17import re
18
19# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
20model_id = "llm-jp/llm-jp-3-13b"
21adapter_id = "kimurakmkm123/llm-jp-3-13b-LoRA_new_unsloth_3times_2nd"
22
23from google.colab import userdata
24HF_TOKEN=userdata.get('HF_TOKEN') #HF_TOKENにはトークンを指定してください
25
26'''
27#googlecolabの場合
28!huggingface-cli login
29#上のコードを実行してトークンを指定する
30'''
31
32# unslothのFastLanguageModelで元のモデルをロード。
33dtype = None # Noneにしておけば自動で設定
34load_in_4bit = True # 今回は13Bモデルを扱うためTrue
35
36model, tokenizer = FastLanguageModel.from_pretrained(
37 model_name=model_id,
38 dtype=dtype,
39 load_in_4bit=load_in_4bit,
40 trust_remote_code=True,
41)
42
43# 元のモデルにLoRAのアダプタを統合。
44model = PeftModel.from_pretrained(model, adapter_id, token = HF_TOKEN)
45
46# 学習したモデルを用いてタスクを実行
47from tqdm import tqdm
48
49推論に使うデータセットをdatasetsに格納する elyza-task-100-TV_0.jsonlのパスについては適宜変更の必要
50datasets = []
51with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
52 item = ""
53 for line in f:
54 line = line.strip()
55 item += line
56 if item.endswith("}"):
57 datasets.append(json.loads(item))
58 item = ""
59
60# 推論するためにモデルのモードを変更
61FastLanguageModel.for_inference(model)
62
63# modelにこのモデルを指定して、datasetに対して推論を行う
64results = []
65for dt in tqdm(datasets): #dataset中のデータを入力、出力をresultsに保存する処理
66 input = dt["input"] #データセットによるが、問を表すカラム名をinputに入れるとよい 上のデータセットではこのままでだいじょうぶ
67
68 prompt = f"""### 指示\n{input}\n### 回答\n"""
69
70 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
71
72 outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
73 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
74
75 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
76
77# 推論結果をjsonlで保存 上の推論でのresultsの内容をファイルに書き込んでる
78with open(f"new_lora_output.jsonl", 'w', encoding='utf-8') as f:
79 for result in results:
80 json.dump(result, f, ensure_ascii=False)
81 f.write('\n')
82
83#new_lora_output_jsonlに出力結果が保存される。
84
85
86[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)