Transformers
Safetensors
Japanese
text-generation-inference
unsloth
llama
trl
Inference Endpoints
File size: 7,742 Bytes
6530c70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2a3eb6d8",
   "metadata": {},
   "source": [
    "# 推論テストコード\n",
    "\n",
    "運営様より提供されているテストコードをベースにした推論用コードです。unslothを使用しますが、conda環境を作らなければ動作しませんので、ご注意ください。\n",
    "12-16 (2024)\n",
    "\n",
    "## 環境構築例\n",
    "\n",
    "```bash\n",
    "# install conda\n",
    "curl -L -O \"https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh\"\n",
    "bash Miniforge3-$(uname)-$(uname -m).sh\n",
    "\n",
    "\n",
    "source ~/miniforge3/etc/profile.d/mamba.sh\n",
    "\n",
    "mamba create --name unsloth_env \\\n",
    "    python=3.10 \\\n",
    "    pytorch-cuda=12.1 \\\n",
    "    pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers \\\n",
    "    -y\n",
    "    \n",
    "mamba activate unsloth_env\n",
    "\n",
    "pip install \"unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git\"\n",
    "\n",
    "pip install --no-deps \"trl<0.9.0\" peft accelerate bitsandbytes\n",
    "\n",
    "pip install ipykernel\n",
    "\n",
    "ipython kernel install --name=unsloth --display-name=unsloth\n",
    "```\n",
    "\n",
    "上記環境構築後、`unsloth`カーネルで本jupyter notebookを動作させてください。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1ed5ea31",
   "metadata": {},
   "outputs": [],
   "source": [
    "from unsloth import FastLanguageModel\n",
    "from peft import PeftModel\n",
    "import torch\n",
    "import json\n",
    "from tqdm import tqdm\n",
    "import re\n",
    "import datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e07b721",
   "metadata": {},
   "source": [
    "## モデル読み込み"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "50a5cebd",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_id = \"llm-jp/llm-jp-3-13b\"\n",
    "adapter_id = \"poprap/llm-jp-3-13b-it-2-3\"\n",
    "adapter_dpo_id = \"poprap/llm-jp-3-13b-dpo\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e800c15b",
   "metadata": {},
   "outputs": [],
   "source": [
    "HF_TOKEN = \"\" "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a1240544",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Unsloth: WARNING `trust_remote_code` is True.\n",
      "Are you certain you want to do remote code execution?\n",
      "==((====))==  Unsloth 2024.12.4: Fast Llama patching. Transformers:4.46.3.\n",
      "   \\\\   /|    GPU: NVIDIA L4. Max memory: 21.964 GB. Platform: Linux.\n",
      "O^O/ \\_/ \\    Torch: 2.5.1. CUDA: 8.9. CUDA Toolkit: 12.1. Triton: 3.1.0\n",
      "\\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.28.post3. FA2 = False]\n",
      " \"-____-\"     Free Apache license: http://github.com/unslothai/unsloth\n",
      "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading shards: 100%|██████████| 6/6 [01:38<00:00, 16.49s/it]\n",
      "Loading checkpoint shards: 100%|██████████| 6/6 [00:09<00:00,  1.61s/it]\n"
     ]
    }
   ],
   "source": [
    "# unslothのFastLanguageModelで元のモデルをロード。\n",
    "dtype = None # Noneにしておけば自動で設定\n",
    "load_in_4bit = True # 今回は13Bモデルを扱うためTrue\n",
    "\n",
    "model, tokenizer = FastLanguageModel.from_pretrained(\n",
    "    model_name=model_id,\n",
    "    dtype=dtype,\n",
    "    load_in_4bit=load_in_4bit,\n",
    "    trust_remote_code=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e0599d87",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 元のモデルにLoRAのアダプタを統合。\n",
    "model = PeftModel.from_pretrained(model, adapter_id, token = HF_TOKEN)\n",
    "model = PeftModel.from_pretrained(model, adapter_dpo_id, token = HF_TOKEN)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a2830ce",
   "metadata": {},
   "source": [
    "## タスクjsonlの読み込み"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3547c974",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds = []\n",
    "\n",
    "with open(\"elyza-tasks-100-TV_0.jsonl\", \"r\") as f:\n",
    "    item = \"\"\n",
    "    for line in f:\n",
    "      line = line.strip()\n",
    "      item += line\n",
    "      if item.endswith(\"}\"):\n",
    "        ds.append(json.loads(item))\n",
    "        item = \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0c1a580f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'task_id': 0, 'input': '野球選手が今シーズン活躍するために取り組むべき5つのことを教えてください。'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a18d3ccd",
   "metadata": {},
   "source": [
    "## 推論 \n",
    "\n",
    "何度か試したところ推論に要する時間はまちまちです。サーバーのリソースの問題でしょうか。\n",
    "一時間はかかりません。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "db654962",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 100/100 [14:17<00:00,  8.58s/it]\n"
     ]
    }
   ],
   "source": [
    "# 推論するためにモデルのモードを変更\n",
    "FastLanguageModel.for_inference(model)\n",
    "\n",
    "results = []\n",
    "for dt in tqdm(ds):\n",
    "    input = dt[\"input\"]\n",
    "\n",
    "    prompt = f\"\"\"### 指示\\n{input}\\n### 回答\\n\"\"\"\n",
    "\n",
    "    inputs = tokenizer([prompt], return_tensors = \"pt\").to(model.device)\n",
    "\n",
    "    outputs = model.generate(\n",
    "        **inputs,\n",
    "        max_new_tokens=1024,\n",
    "        use_cache = True, \n",
    "        do_sample=False, \n",
    "        repetition_penalty=1.2\n",
    "      )\n",
    "    prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\\n### 回答')[-1]\n",
    "    \n",
    "    results.append({\"task_id\": dt['task_id'], \"input\": input, \"output\": prediction})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "9a18a4f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "json_file_id = re.sub(\".*/\", \"\", adapter_id)\n",
    "with open(f\"{json_file_id}_output.jsonl\", 'w', encoding='utf-8') as f:\n",
    "    for result in results:\n",
    "        json.dump(result, f, ensure_ascii=False)\n",
    "        f.write('\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2ebf493",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "unsloth",
   "language": "python",
   "name": "unsloth"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}