Views
No views yet
1# 必要なライブラリをインポート
2import json
3from datetime import datetime
4from pathlib import Path
5
6import jsonlines
7import torch
8from huggingface_hub import get_token
9from peft import PeftModel
10from tqdm.notebook import tqdm
11from transformers import pipeline
12from transformers.pipelines.text_generation import TextGenerationPipeline
13from unsloth import FastLanguageModel
14
15# 定数の定義
16HF_TOKEN = get_token()
17PROMPT_TEMPLATE = "\n".join(
18 [
19 "### 指示",
20 "{}",
21 "### 回答",
22 "{}",
23 ]
24)
25
26# 変数の設定
27base_model_id = "llm-jp/llm-jp-3-13b" # 使用するベースモデル
28adapter_id = "HBD007/llm-jp-3-13b-LLM2024-lora" # LoRAアダプタ
29input_data_path = Path("data/elyza-tasks-100-TV_0.jsonl") # 入力データのパス
30output_file_path = Path(
31 f"inference_results-{datetime.now().strftime('%Y%m%d-%H%M%S')}.jsonl"
32)
33
34# データの読み込み
35datasets_list = [obj for obj in jsonlines.open(input_data_path)]
36
37# モデルとトークナイザーの読み込み
38model, tokenizer = FastLanguageModel.from_pretrained(
39 model_name=base_model_id,
40 trust_remote_code=True,
41 token=HF_TOKEN,
42)
43
44# LoRAアダプタのロード
45model = PeftModel.from_pretrained(
46 model,
47 adapter_id,
48 token=HF_TOKEN,
49)
50
51# 推論モードに設定
52model = FastLanguageModel.for_inference(model)
53
54# テキスト生成パイプラインの作成
55generator: TextGenerationPipeline = pipeline(
56 task="text-generation",
57 model=model,
58 tokenizer=tokenizer,
59 use_cache=True,
60 do_sample=False,
61 repetition_penalty=1.2,
62)
63
64# GPUの状態を表示
65if torch.cuda.is_available():
66 gpu_stats = torch.cuda.get_device_properties(0)
67 start_gpu_memory = round(torch.cuda.max_memory_reserved() / (1024**3), 3)
68 max_memory = round(gpu_stats.total_memory / (1024**3), 3)
69 print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
70 print(f"{start_gpu_memory} GB of memory reserved.")
71
72# 結果を生成
73results = []
74for dt in tqdm(datasets_list):
75 input_text = dt["input"]
76 task_id = dt["task_id"]
77 generated = generator(
78 text_inputs=PROMPT_TEMPLATE.format(input_text, ""),
79 return_full_text=False,
80 )
81 results.append({
82 "task_id": task_id,
83 "input": input_text,
84 "output": generated[0]["generated_text"],
85 })
86
87# 結果を保存
88with output_file_path.open("w", encoding="utf-8") as f:
89 for result in results:
90 json.dump(result, f, ensure_ascii=False)
91 f.write("\n")
92
93print(f"Inference results saved to {output_file_path}")
94