mondk commited on
Commit
e8c61dd
·
verified ·
1 Parent(s): fee1aa2

Update You_can_still_run_it_directly_on_your_own_machine_if_it's_too_small.ipynb

Browse files
You_can_still_run_it_directly_on_your_own_machine_if_it's_too_small.ipynb CHANGED
@@ -193,6 +193,49 @@
193
  ],
194
  "id": "PP6KcuhQXeQ1"
195
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  {
197
  "cell_type": "code",
198
  "execution_count": null,
@@ -229,4 +272,4 @@
229
  },
230
  "nbformat": 4,
231
  "nbformat_minor": 5
232
- }
 
193
  ],
194
  "id": "PP6KcuhQXeQ1"
195
  },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": null,
199
+ "metadata": {
200
+ "id": "fix1chatFn"
201
+ },
202
+ "outputs": [],
203
+ "source": [
204
+ "# --- FIX: ham chat() bi thieu, day la ham duoc them lai ---\n",
205
+ "# Encode/decode qua tokenizers backend, va tu sinh token cho den khi\n",
206
+ "# gap END_ID (thay vi dung model.generate() goc, vi ham do khong biet\n",
207
+ "# dung lai o END_TOK va se tra ve ca prompt lan phan sinh ra).\n",
208
+ "\n",
209
+ "@torch.no_grad()\n",
210
+ "def chat(user_input, max_new_tokens=200, temperature=0.8, top_k=40):\n",
211
+ " prompt = f\"{USER_TOK}{user_input}{ASSISTANT_TOK}\"\n",
212
+ " prompt_ids = tokenizer_backend.encode(prompt).ids\n",
213
+ " # cat bot neu prompt dai hon block_size\n",
214
+ " prompt_ids = prompt_ids[-model.block_size:]\n",
215
+ " idx = torch.tensor([prompt_ids], dtype=torch.long, device=device)\n",
216
+ "\n",
217
+ " generated_ids = []\n",
218
+ " for _ in range(max_new_tokens):\n",
219
+ " idx_cond = idx[:, -model.block_size:]\n",
220
+ " logits, _ = model(idx_cond)\n",
221
+ " logits = logits[:, -1, :] / temperature\n",
222
+ " if top_k is not None:\n",
223
+ " v, _ = torch.topk(logits, top_k)\n",
224
+ " logits[logits < v[:, [-1]]] = float(\"-inf\")\n",
225
+ " probs = F.softmax(logits, dim=-1)\n",
226
+ " next_id = torch.multinomial(probs, num_samples=1)\n",
227
+ "\n",
228
+ " if next_id.item() == END_ID:\n",
229
+ " break\n",
230
+ "\n",
231
+ " generated_ids.append(next_id.item())\n",
232
+ " idx = torch.cat([idx, next_id], dim=1)\n",
233
+ "\n",
234
+ " reply = tokenizer_backend.decode(generated_ids)\n",
235
+ " return reply.strip()\n"
236
+ ],
237
+ "id": "fix1chatFn"
238
+ },
239
  {
240
  "cell_type": "code",
241
  "execution_count": null,
 
272
  },
273
  "nbformat": 4,
274
  "nbformat_minor": 5
275
+ }