File size: 27,830 Bytes
e685da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7145796
 
769d8b8
7145796
 
 
 
 
 
 
 
769d8b8
7145796
 
 
 
 
42c11d3
 
769d8b8
7145796
769d8b8
 
 
7145796
 
42c11d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e685da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'conversations': [{'content': 'How do astronomers determine the original wavelength of light emitted by a celestial body at rest, which is necessary for measuring its speed using the Doppler effect?',\n",
       "   'role': 'user'},\n",
       "  {'content': 'Astronomers make use of the unique spectral fingerprints of elements found in stars. These elements emit and absorb light at specific, known wavelengths, forming an absorption spectrum. By analyzing the light received from distant stars and comparing it to the laboratory-measured spectra of these elements, astronomers can identify the shifts in these wavelengths due to the Doppler effect. The observed shift tells them the extent to which the light has been redshifted or blueshifted, thereby allowing them to calculate the speed of the star along the line of sight relative to Earth.',\n",
       "   'role': 'assistant'}]}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "d = json.loads(\"{'conversations': [{'content': 'How do astronomers determine the original wavelength of light emitted by a celestial body at rest, which is necessary for measuring its speed using the Doppler effect?', 'role': 'user'}, {'content': 'Astronomers make use of the unique spectral fingerprints of elements found in stars. These elements emit and absorb light at specific, known wavelengths, forming an absorption spectrum. By analyzing the light received from distant stars and comparing it to the laboratory-measured spectra of these elements, astronomers can identify the shifts in these wavelengths due to the Doppler effect. The observed shift tells them the extent to which the light has been redshifted or blueshifted, thereby allowing them to calculate the speed of the star along the line of sight relative to Earth.', 'role': 'assistant'}]}\".replace(\"'\", '\"'))\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "ImportError",
     "evalue": "Please install Unsloth via `pip install unsloth`!",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mImportError\u001b[39m                               Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[1]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m      1\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mos\u001b[39;00m\n\u001b[32m      2\u001b[39m \u001b[38;5;66;03m# os.environ[\"UNSLOTH_IS_PRESENT\"] = \"1\"\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01munsloth_zoo\u001b[39;00m\u001b[34;01m.\u001b[39;00m\u001b[34;01mdataset_utils\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m train_on_responses_only\n",
      "\u001b[36mFile \u001b[39m\u001b[32m/opt/anaconda3/envs/unsloth_torch260/lib/python3.12/site-packages/unsloth_zoo/__init__.py:27\u001b[39m\n\u001b[32m     25\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mos\u001b[39;00m\n\u001b[32m     26\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[33m\"\u001b[39m\u001b[33mUNSLOTH_IS_PRESENT\u001b[39m\u001b[33m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m os.environ):\n\u001b[32m---> \u001b[39m\u001b[32m27\u001b[39m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mPlease install Unsloth via `pip install unsloth`!\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m     28\u001b[39m \u001b[38;5;28;01mpass\u001b[39;00m\n\u001b[32m     30\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n",
      "\u001b[31mImportError\u001b[39m: Please install Unsloth via `pip install unsloth`!"
     ]
    }
   ],
   "source": [
    "import os\n",
    "# os.environ[\"UNSLOTH_IS_PRESENT\"] = \"1\"\n",
    "\n",
    "from unsloth_zoo.dataset_utils import train_on_responses_only"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoProcessor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.48, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.\n"
     ]
    }
   ],
   "source": [
    "processor = AutoProcessor.from_pretrained(\"Qwen/Qwen2-VL-7B-Instruct\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input_ids': [9707, 11, 1879, 0], 'attention_mask': [1, 1, 1, 1]}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "processor.tokenizer(\"Hello, world!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<|im_start|>system\n",
      "You are a helpful assistant.<|im_end|>\n",
      "<|im_start|>user\n",
      "Hello, world!<|im_end|>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n",
    "formatted_text = processor.apply_chat_template(messages, processor.chat_template)\n",
    "print(formatted_text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "response = requests.get(\"https://raw.githubusercontent.com/unslothai/unsloth-zoo/refs/heads/main/unsloth_zoo/dataset_utils.py\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "abc() got an unexpected keyword argument 'r'",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mTypeError\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[10]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m      1\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mabc\u001b[39m(a, *args):\n\u001b[32m      2\u001b[39m     \u001b[38;5;28;01mpass\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m \u001b[43mabc\u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m2\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m4\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m5\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mr\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m4\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "\u001b[31mTypeError\u001b[39m: abc() got an unexpected keyword argument 'r'"
     ]
    }
   ],
   "source": [
    "def abc(a, *args):\n",
    "    pass\n",
    "\n",
    "abc(1, 2, 3, 4, 5, r=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "OSError",
     "evalue": "could not get source code",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mOSError\u001b[39m                                   Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43minspect\u001b[49m\u001b[43m.\u001b[49m\u001b[43mgetsource\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtrain_on_responses_only\u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[36mFile \u001b[39m\u001b[32m/opt/anaconda3/envs/unsloth_torch260/lib/python3.12/inspect.py:1285\u001b[39m, in \u001b[36mgetsource\u001b[39m\u001b[34m(object)\u001b[39m\n\u001b[32m   1279\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mgetsource\u001b[39m(\u001b[38;5;28mobject\u001b[39m):\n\u001b[32m   1280\u001b[39m \u001b[38;5;250m    \u001b[39m\u001b[33;03m\"\"\"Return the text of the source code for an object.\u001b[39;00m\n\u001b[32m   1281\u001b[39m \n\u001b[32m   1282\u001b[39m \u001b[33;03m    The argument may be a module, class, method, function, traceback, frame,\u001b[39;00m\n\u001b[32m   1283\u001b[39m \u001b[33;03m    or code object.  The source code is returned as a single string.  An\u001b[39;00m\n\u001b[32m   1284\u001b[39m \u001b[33;03m    OSError is raised if the source code cannot be retrieved.\"\"\"\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m1285\u001b[39m     lines, lnum = \u001b[43mgetsourcelines\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mobject\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[32m   1286\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[33m'\u001b[39m\u001b[33m'\u001b[39m.join(lines)\n",
      "\u001b[36mFile \u001b[39m\u001b[32m/opt/anaconda3/envs/unsloth_torch260/lib/python3.12/inspect.py:1267\u001b[39m, in \u001b[36mgetsourcelines\u001b[39m\u001b[34m(object)\u001b[39m\n\u001b[32m   1259\u001b[39m \u001b[38;5;250m\u001b[39m\u001b[33;03m\"\"\"Return a list of source lines and starting line number for an object.\u001b[39;00m\n\u001b[32m   1260\u001b[39m \n\u001b[32m   1261\u001b[39m \u001b[33;03mThe argument may be a module, class, method, function, traceback, frame,\u001b[39;00m\n\u001b[32m   (...)\u001b[39m\u001b[32m   1264\u001b[39m \u001b[33;03moriginal source file the first line of code was found.  An OSError is\u001b[39;00m\n\u001b[32m   1265\u001b[39m \u001b[33;03mraised if the source code cannot be retrieved.\"\"\"\u001b[39;00m\n\u001b[32m   1266\u001b[39m \u001b[38;5;28mobject\u001b[39m = unwrap(\u001b[38;5;28mobject\u001b[39m)\n\u001b[32m-> \u001b[39m\u001b[32m1267\u001b[39m lines, lnum = \u001b[43mfindsource\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mobject\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[32m   1269\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m istraceback(\u001b[38;5;28mobject\u001b[39m):\n\u001b[32m   1270\u001b[39m     \u001b[38;5;28mobject\u001b[39m = \u001b[38;5;28mobject\u001b[39m.tb_frame\n",
      "\u001b[36mFile \u001b[39m\u001b[32m/opt/anaconda3/envs/unsloth_torch260/lib/python3.12/inspect.py:1096\u001b[39m, in \u001b[36mfindsource\u001b[39m\u001b[34m(object)\u001b[39m\n\u001b[32m   1094\u001b[39m     lines = linecache.getlines(file)\n\u001b[32m   1095\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m lines:\n\u001b[32m-> \u001b[39m\u001b[32m1096\u001b[39m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mOSError\u001b[39;00m(\u001b[33m'\u001b[39m\u001b[33mcould not get source code\u001b[39m\u001b[33m'\u001b[39m)\n\u001b[32m   1098\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m ismodule(\u001b[38;5;28mobject\u001b[39m):\n\u001b[32m   1099\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m lines, \u001b[32m0\u001b[39m\n",
      "\u001b[31mOSError\u001b[39m: could not get source code"
     ]
    }
   ],
   "source": [
    "inspect.getsource(train_on_responses_only)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['abc']"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = \"['abc']\"\n",
    "eval(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Unsloth: Will map <end_of_turn> to EOS = <|im_end|>.\n"
     ]
    }
   ],
   "source": [
    "from unsloth.chat_templates import get_chat_template\n",
    "\n",
    "text_tokenizer = get_chat_template(\n",
    "    text_tokenizer,\n",
    "    chat_template = \"gemma\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['unsloth', 'zephyr', 'chatml', 'mistral', 'llama', 'vicuna', 'vicuna_old', 'vicuna old', 'alpaca', 'gemma', 'gemma_chatml', 'gemma2', 'gemma2_chatml', 'llama-3', 'llama3', 'phi-3', 'phi-35', 'phi-3.5', 'llama-3.1', 'llama-31', 'llama-3.2', 'llama-3.3', 'llama-32', 'llama-33', 'qwen-2.5', 'qwen-25', 'qwen25', 'qwen2.5', 'phi-4'])"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from unsloth.chat_templates import CHAT_TEMPLATES\n",
    "CHAT_TEMPLATES.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n",
    "# import unsloth\n",
    "import torch\n",
    "import torch.utils._triton\n",
    "import sys\n",
    "sys.modules[\"torch.utils._triton\"].has_triton()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# torch.cuda.get_device_capability = lambda: (8, 0)\n",
    "torch.cuda.is_bf16_supported()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'<start_of_turn>user\\nYou are<end_of_turn>\\n'"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text_tokenizer.apply_chat_template([{\"role\": \"user\", \"content\": \"You are\"}], tokenize=False, add_generation_prompt=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n{% endif %}<|im_start|>{{ message['role'] }}\\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\\n{% endif %}\""
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text_tokenizer.chat_template"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-03-11 22:38:13.841 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.842 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.843 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.844 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.844 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.844 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.845 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:13.846 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.585 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.587 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.587 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.588 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.589 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.589 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.590 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.590 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.591 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.591 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.592 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.592 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.594 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.595 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.595 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.595 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.596 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.596 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.597 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.597 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.598 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.598 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.599 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.599 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.600 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.601 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.601 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n",
      "2025-03-11 22:38:16.602 Thread 'MainThread': missing ScriptRunContext! This warning can be ignored when running in bare mode.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "os.environ[\"UNSLOTH_IS_PRESENT\"] = \"1\"\n",
    "\n",
    "import json\n",
    "import streamlit as st\n",
    "from transformers import AutoProcessor\n",
    "from unsloth_zoo.dataset_utils import train_on_responses_only\n",
    "\n",
    "class DummyArgs:\n",
    "    pass\n",
    "\n",
    "class DummyDataset:\n",
    "    def __init__(self, example):\n",
    "        self.example = [example]\n",
    "\n",
    "    def map(self, function, *args, **kwargs):\n",
    "        self.example[0].update(function(self.example[0]))\n",
    "        return self\n",
    "    \n",
    "    def __len__(self):\n",
    "        return 1\n",
    "    \n",
    "    def __getitem__(self, idx):\n",
    "        return self.example[idx]\n",
    "\n",
    "class DummyTrainer:\n",
    "    pass\n",
    "\n",
    "st.title('Train With Response Only Analyzer')\n",
    "\n",
    "model = st.text_input(\"Model Name on HuggingFace\", \"Qwen/Qwen2-VL-7B-Instruct\")\n",
    "processor = AutoProcessor.from_pretrained(model)\n",
    "text_tokenizer = processor if not hasattr(processor, \"tokenizer\") else processor.tokenizer\n",
    "\n",
    "sample = \"\"\n",
    "if \"Qwen2-VL\" in model:\n",
    "    sample = {\"conversations\": [{'content': 'How do astronomers determine the original wavelength of light emitted by a celestial body at rest, which is necessary for measuring its speed using the Doppler effect?', 'role': 'user'}, {'content': 'Astronomers make use of the unique spectral fingerprints of elements found in stars. These elements emit and absorb light at specific, known wavelengths, forming an absorption spectrum. By analyzing the light received from distant stars and comparing it to the laboratory-measured spectra of these elements, astronomers can identify the shifts in these wavelengths due to the Doppler effect. The observed shift tells them the extent to which the light has been redshifted or blueshifted, thereby allowing them to calculate the speed of the star along the line of sight relative to Earth.', 'role': 'assistant'}], \"instruction_part\": \"<|im_start|>system\", \"response_part\": \"<|im_start|>assistant\"}\n",
    "\n",
    "chat_template = processor.chat_template\n",
    "user_chat_template = st.text_area(\"User Chat Template\", chat_template)\n",
    "message_sample = sample[\"conversations\"]\n",
    "message = st.text_area(\"Message\", str(message_sample))\n",
    "\n",
    "try:\n",
    "    message = eval(message)\n",
    "except:\n",
    "    pass\n",
    "\n",
    "instruction_part = st.text_input(\"Instruction Part\", sample[\"instruction_part\"])\n",
    "response_part = st.text_input(\"Response Part\", sample[\"response_part\"])\n",
    "\n",
    "converted_message = processor.apply_chat_template(message, user_chat_template)\n",
    "\n",
    "st.header(\"Original Prompt\")\n",
    "st.code(converted_message, language=\"html\")\n",
    "\n",
    "trainer = DummyTrainer()\n",
    "trainer.train_dataset = DummyDataset({\"input_ids\": [text_tokenizer.encode(converted_message)]})\n",
    "trainer.tokenizer = text_tokenizer\n",
    "trainer.args = DummyArgs()\n",
    "trainer.args.dataset_kwargs = {\"skip_prepare_dataset\": False}\n",
    "\n",
    "trainer = train_on_responses_only(trainer, instruction_part, response_part)\n",
    "ids = trainer.train_dataset[0][\"labels\"][0]\n",
    "space = text_tokenizer.encode(\" \", add_special_tokens = False)[0]\n",
    "print(text_tokenizer.decode([space if x == -100 else x for x in ids]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                                \n",
      "Astronomers make use of the unique spectral fingerprints of elements found in stars. These elements emit and absorb light at specific, known wavelengths, forming an absorption spectrum. By analyzing the light received from distant stars and comparing it to the laboratory-measured spectra of these elements, astronomers can identify the shifts in these wavelengths due to the Doppler effect. The observed shift tells them the extent to which the light has been redshifted or blueshifted, thereby allowing them to calculate the speed of the star along the line of sight relative to Earth.<|im_end|>\n",
      "\n"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<|im_start|>system\n",
      "You are a helpful assistant.<|im_end|>\n",
      "<|im_start|>user\n",
      "How do astronomers determine the original wavelength of light emitted by a celestial body at rest, which is necessary for measuring its speed using the Doppler effect?<|im_end|>\n",
      "<|im_start|>assistant\n",
      "Astronomers make use of the unique spectral fingerprints of elements found in stars. These elements emit and absorb light at specific, known wavelengths, forming an absorption spectrum. By analyzing the light received from distant stars and comparing it to the laboratory-measured spectra of these elements, astronomers can identify the shifts in these wavelengths due to the Doppler effect. The observed shift tells them the extent to which the light has been redshifted or blueshifted, thereby allowing them to calculate the speed of the star along the line of sight relative to Earth.<|im_end|>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(converted_message)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "unsloth_torch260",
   "language": "python",
   "name": "python3"
  },
  "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.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}