Views
No views yet
1# 必要なライブラリをインストール
2!pip uninstall unsloth -y
3!pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
4!pip install --upgrade torch
5!pip install --upgrade xformers
6
7
8# 必要なライブラリを読み込み
9from unsloth import FastLanguageModel
10import json
11from tqdm import tqdm
12import re
13
14
15# モデルをロード
16model, tokenizer = FastLanguageModel.from_pretrained(
17 model_name = "mnm373/gemma-2-9b-it-v3_lora",
18 load_in_4bit = True,
19 trust_remote_code=True,
20)
21FastLanguageModel.for_inference(model) # Enable native 2x faster inference
22
23# データセットの読み込み
24# 事前にデータをアップロードしてください
25datasets = []
26with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
27 item = ""
28 for line in f:
29 line = line.strip()
30 item += line
31 if item.endswith("}"):
32 datasets.append(json.loads(item))
33 item = ""
34
35# 推論の実行
36results = []
37for dt in tqdm(datasets):
38 input_text = dt["input"]
39
40 prompt = f"""### 指示\n{input_text}\n### 回答\n"""
41
42 inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
43
44 outputs = model.generate(**inputs, max_new_tokens=1024, use_cache=True, do_sample=False, repetition_penalty=1.2)
45 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答\n')[-1]
46
47 # 不要なフレーズを削除
48 if prediction.startswith("こんにちは!"):
49 prediction = prediction.lstrip("こんにちは!")
50 if prediction.startswith("もちろんです!"):
51 prediction = prediction.lstrip("もちろんです!")
52
53 phrases_to_remove = [
54 "ユーモアを交えてお答えしますね。",
55 "ユーモアを交えつつお答えしますね。"
56 ]
57 for phrase in phrases_to_remove:
58 prediction = prediction.replace(phrase, "")
59
60 # 不要な空白や改行をトリミング
61 prediction = prediction.strip()
62
63 results.append({"task_id": dt["task_id"], "input": input_text, "output": prediction})
64
65
66# 結果をjsonlで保存。
67json_file_id = re.sub(".*/", "", adapter_id)
68with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
69 for result in results:
70 json.dump(result, f, ensure_ascii=False)
71 f.write('\n')