Views
No views yet
# conda環境の構築
wget "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
# このコマンドではいくつか質問があるので答えて下さい。おそらくインストール先のデフォルトは/root/miniforge3かと思います
bash Miniforge3-$(uname)-$(uname -m).sh
# 以下、インストール先が/root/miniforge3であることを前提とします
export PATH=/root/miniforge3/bin:$PATH
conda init
# ここで一度、terminalを立ち上げ直す必要があります。
# 以下のリンク先に従い環境を作ります。
# https://docs.unsloth.ai/get-started/installation/conda-install
conda create --name unsloth_env python=3.10 pytorch-cuda=12.1 pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers -y
conda activate unsloth_env
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps "trl<0.9.0" peft accelerate bitsandbytes
# jupyter notebook用のセットアップ。
conda install -c conda-forge ipykernel
python -m ipykernel install --user --name=unsloth_env --display-name "Python (unsloth_env)"%%capture
!pip uninstall unsloth -y
!pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
!pip install --upgrade torch
!pip install --upgrade xformers
!pip install ipywidgets --upgrade1# 必要なライブラリを読み込み
2from unsloth import FastLanguageModel
3from peft import PeftModel
4import torch
5import json
6from tqdm import tqdm
7import re
8
9# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
10model_id = "llm-jp/llm-jp-3-13b"
11adapter_id = "HayatoF-1015/magpie_lora_elyza_12-15-v2"
12
13# unslothのFastLanguageModelで元のモデルをロード。
14dtype = None # Noneにしておけば自動で設定
15load_in_4bit = True # 今回は13Bモデルを扱うためTrue
16
17model, tokenizer = FastLanguageModel.from_pretrained(
18 model_name=model_id,
19 dtype=dtype,
20 load_in_4bit=load_in_4bit,
21 trust_remote_code=True,
22)
23
24# 元のモデルにLoRAのアダプタを統合。
25model = PeftModel.from_pretrained(model, adapter_id)
26
27
28# タスクとなるデータの読み込み。
29# 事前にデータをアップロードしてください。
30datasets = []
31with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
32 item = ""
33 for line in f:
34 line = line.strip()
35 item += line
36 if item.endswith("}"):
37 datasets.append(json.loads(item))
38 item = ""
39
40# モデルを用いてタスクの推論。
41
42# 推論するためにモデルのモードを変更
43FastLanguageModel.for_inference(model)
44
45results = []
46for dt in tqdm(datasets):
47 input = dt["input"]
48
49 prompt = f"""### 指示\n{input}\n### 回答\n"""
50
51 inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
52
53 outputs = model.generate(**inputs, max_new_tokens = 2048, use_cache = True, do_sample=False, repetition_penalty=1.2)
54 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
55
56 results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
57
58# ここではadapter_idを元にファイル名を決定している.
59json_file_id = re.sub(".*/", "", adapter_id)
60with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
61 for result in results:
62 json.dump(result, f, ensure_ascii=False)
63 f.write('\n')
64