File size: 35,640 Bytes
204d8d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setting Up"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture\n",
    "%pip install -U transformers\n",
    "%pip install -U datasets \n",
    "%pip install -U accelerate \n",
    "%pip install -U peft \n",
    "%pip install -U trl \n",
    "%pip install -U bitsandbytes\n",
    "%pip install huggingface_hub[hf_xet]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
     ]
    }
   ],
   "source": [
    "from huggingface_hub import login\n",
    "import os\n",
    "\n",
    "hf_token = os.environ.get(\"HF_TOKEN\")\n",
    "login(hf_token)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading the model and tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "_cell_guid": "82e08da0-4ee2-4235-a54f-c2bed3609a2b",
    "_uuid": "059b3da3-4a60-40ed-8a3c-2c395b2c3a8d",
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
    "import torch\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "bnb_config = BitsAndBytesConfig(\n",
    "    load_in_4bit=True,\n",
    "    bnb_4bit_use_double_quant=False,\n",
    "    bnb_4bit_quant_type=\"nf4\",\n",
    "    bnb_4bit_compute_dtype=torch.bfloat16,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6784ce596124486cb42f8dbb5680a038",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/17 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load tokenizer & model\n",
    "\n",
    "model_dir = \"Qwen/Qwen3-32B\"\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True)\n",
    "\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    model_dir,\n",
    "    quantization_config=bnb_config,   \n",
    "    device_map=\"auto\",  \n",
    "    torch_dtype=torch.bfloat16,\n",
    "    trust_remote_code=True             \n",
    ")\n",
    "\n",
    "model.config.use_cache = False\n",
    "model.config.pretraining_tp = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tue Apr 29 13:19:53 2025       \n",
      "+-----------------------------------------------------------------------------------------+\n",
      "| NVIDIA-SMI 565.57.01              Driver Version: 565.57.01      CUDA Version: 12.8     |\n",
      "|-----------------------------------------+------------------------+----------------------+\n",
      "| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |\n",
      "| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |\n",
      "|                                         |                        |               MIG M. |\n",
      "|=========================================+========================+======================|\n",
      "|   0  NVIDIA A100-SXM4-80GB          On  |   00000000:9B:00.0 Off |                    0 |\n",
      "| N/A   29C    P0             84W /  400W |   31789MiB /  81920MiB |      0%      Default |\n",
      "|                                         |                        |             Disabled |\n",
      "+-----------------------------------------+------------------------+----------------------+\n",
      "                                                                                         \n",
      "+-----------------------------------------------------------------------------------------+\n",
      "| Processes:                                                                              |\n",
      "|  GPU   GI   CI        PID   Type   Process name                              GPU Memory |\n",
      "|        ID   ID                                                               Usage      |\n",
      "|=========================================================================================|\n",
      "+-----------------------------------------------------------------------------------------+\n"
     ]
    }
   ],
   "source": [
    "!nvidia-smi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading and processing the dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_prompt_style = \"\"\"Below is an instruction that describes a task, paired with an input that provides further context. \n",
    "Write a response that appropriately completes the request. \n",
    "Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.\n",
    "\n",
    "### Instruction:\n",
    "You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. \n",
    "Please answer the following medical question. \n",
    "\n",
    "### Question:\n",
    "{}\n",
    "\n",
    "### Response:\n",
    "<think>\n",
    "{}\n",
    "</think>\n",
    "{}\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS_TOKEN = tokenizer.eos_token  # Must add EOS_TOKEN\n",
    "\n",
    "def formatting_prompts_func(examples):\n",
    "    inputs = examples[\"Question\"]\n",
    "    complex_cots = examples[\"Complex_CoT\"]\n",
    "    outputs = examples[\"Response\"]\n",
    "    texts = []\n",
    "    for question, cot, response in zip(inputs, complex_cots, outputs):\n",
    "        # Append the EOS token to the response if it's not already there\n",
    "        if not response.endswith(tokenizer.eos_token):\n",
    "            response += tokenizer.eos_token\n",
    "        text = train_prompt_style.format(question, cot, response)\n",
    "        texts.append(text)\n",
    "    return {\"text\": texts}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6bbb17fe1316445cb5c849258d94aea6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "README.md:   0%|          | 0.00/1.97k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "efe760c819454343a4212a5d401af10f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "medical_o1_sft.json:   0%|          | 0.00/58.2M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e84278d969714666b536448b6f1dd663",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Generating train split:   0%|          | 0/19704 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "22320917d4f0468e97c0364c3d2b10e0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/2000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\"Below is an instruction that describes a task, paired with an input that provides further context. \\nWrite a response that appropriately completes the request. \\nBefore answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.\\n\\n### Instruction:\\nYou are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. \\nPlease answer the following medical question. \\n\\n### Question:\\nIn a patient with dermatomyositis as indicated by fatigue, muscle weakness, a scaly rash, elevated creatine kinase-MB, anti-Jo-1 antibodies, and perimysial inflammation, which type of cancer is most often associated with this condition?\\n\\n### Response:\\n<think>\\nAlright, so when I'm thinking about dermatomyositis, I know it's an inflammatory condition with muscle weakness and a telltale skin rash. It's sometimes linked to certain cancers. \\n\\nNow, I remember reading somewhere that when you have dermatomyositis, there's a higher chance of getting some types of cancer. But which one pops up the most? Let's think about that. \\n\\nFrom what I recall, ovarian cancer often gets mentioned in this context. That's especially true for women with dermatomyositis. So, it seems like a big contender. \\n\\nHowever, just pointing out ovarian cancer seems a bit simplistic. With diseases like this, there might be more frequently encountered cancers, especially if you consider both men and women. \\n\\nLung and stomach cancers are quite common and could potentially have strong links too. They seem like they'd show up in some statistics regarding dermatomyositis. \\n\\nBut there was that thought about ovarian cancer having a notable association. Maybe I need to dive into some literature and research findings. Hmm. \\n\\nIn some studies, what I often find is ovarian cancer being highlighted for women with dermatomyositis, maybe more consistently than others like stomach or colorectal cancer. \\n\\nGastric cancer seemed an initial possibility for both genders—could it overshadow ovarian cancer just because it's more common overall? \\n\\nLet's switch lanes and think about the most common cancers overall. For women, breast cancer is always high in any list. Maybe it's the same with dermatomyositis? Is breast cancer actually more common here too?\\n\\nIt might even show more prevalence than ovarian cancer across different studies, especially since breast cancer is so frequent in the general female population. \\n\\nAfter digging deeper into research, I start to see breast cancer's name popping up quite a bit with dermatomyositis. I guess considering all demographics, breast cancer may outpace ovarian cancer. \\n\\nSo, upon deeper reflection and pulling all this together, it sounds logical that breast cancer might just be the top association after all with dermatomyositis. At least, that's where my thinking leads me.\\n</think>\\nIn patients with dermatomyositis, ovarian cancer is the most often associated malignancy, particularly in women. While other types of cancer such as breast, lung, and gastric can also be associated with dermatomyositis, ovarian cancer has a relatively strong and specific link, especially in the context of developing this autoimmune condition. It’s important for individuals with dermatomyositis to undergo appropriate cancer screening for early detection and management, particularly for ovarian cancer.<|im_end|>\""
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "dataset = load_dataset(\n",
    "    \"FreedomIntelligence/medical-o1-reasoning-SFT\",\n",
    "    \"en\",\n",
    "    split=\"train[0:2000]\",\n",
    "    trust_remote_code=True,\n",
    ")\n",
    "dataset = dataset.map(\n",
    "    formatting_prompts_func,\n",
    "    batched=True,\n",
    ")\n",
    "dataset[\"text\"][10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import DataCollatorForLanguageModeling\n",
    "\n",
    "data_collator = DataCollatorForLanguageModeling(\n",
    "    tokenizer=tokenizer,\n",
    "    mlm=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model inference before fine-tuning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "inference_prompt_style = \"\"\"Below is an instruction that describes a task, paired with an input that provides further context. \n",
    "Write a response that appropriately completes the request. \n",
    "Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.\n",
    "\n",
    "### Instruction:\n",
    "You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. \n",
    "Please answer the following medical question. \n",
    "\n",
    "### Question:\n",
    "{}\n",
    "\n",
    "### Response:\n",
    "<think>{}\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "<think>\n",
      "\n",
      "Okay, let's tackle this question. So, the user is asking about the type of cancer most often associated with dermatomyositis based on the given symptoms and lab results.\n",
      "\n",
      "First, I need to recall what dermatomyositis is. It's an autoimmune inflammatory myopathy characterized by muscle weakness, skin rash, and specific lab findings like elevated creatine kinase. The presence of anti-Jo-1 antibodies points towards a specific subset, maybe the polymyositis/dermatomyositis overlap with interstitial lung disease. But the main question is about the associated cancer.\n",
      "\n",
      "I remember that dermatomyositis is linked to an increased risk of malignancy, especially in adults. The classic teaching is that certain cancers are more commonly associated with it. Which ones come to mind? Ovarian cancer? Lung cancer? Maybe breast or lymphomas?\n",
      "\n",
      "Wait, I think the most commonly associated cancers in dermatomyositis include ovarian cancer, lung cancer (especially non-small cell), and sometimes lymphomas. But which one is the most frequent? I recall that ovarian cancer is often cited as a common association. However, I should verify if there are more recent studies or guidelines that emphasize different cancers.\n",
      "\n",
      "Also, considering the patient's presentation with perimysial inflammation, which is a histopathological finding in dermatomyositis. The presence of anti-Jo-1 antibodies is part of the antisynthetase syndrome, which might be associated with interstitial lung disease rather than malignancy. But does that affect the cancer association? Maybe not directly. So the question is about dermatomyositis in general, not specifically the antisynthetase subset.\n",
      "\n",
      "Another angle: the age of the patient. Dermatomyositis in adults is more commonly associated with cancer than in children. So if this is an adult patient, malignancy risk is higher. The most commonly associated cancers are ovarian, lung, breast, and sometimes lymphomas. But which one is the most prevalent?\n",
      "\n",
      "I think that in the literature, ovarian cancer is frequently mentioned. However, lung cancer is also a significant one. Wait, maybe lung cancer is more common? Or is there a specific type? For example, non-small cell lung cancer.\n",
      "\n",
      "Alternatively, I've heard that in some studies, the most common malignancies associated with dermatomyositis are lung cancer (especially squamous cell carcinoma), ovarian cancer, and lymphomas. But which is the most often associated? \n",
      "\n",
      "I need to recall the statistics. From what I remember, the most commonly reported malignancy is lung cancer, but others might have conflicting data. Wait, some sources say that ovarian cancer is the most frequent, while others say lung. Maybe it's better to check recent guidelines or studies.\n",
      "\n",
      "Wait, a quick search in my memory: according to the American College of Rheumatology guidelines or UpToDate, the most commonly associated cancers with dermatomyositis are ovarian, lung, and breast cancers. But which is the most frequent? Another thought: in some sources, the most common is lung cancer, especially squamous cell carcinoma. However, other sources suggest that the risk varies by gender and age. For example, women might be more prone to ovarian cancer, while men might have higher rates of lung cancer.\n",
      "\n",
      "But the question asks for the most often associated type of cancer. Considering overall incidence, perhaps lung cancer is the most common. Alternatively, maybe it's ovarian cancer. Hmm.\n",
      "\n",
      "Wait, I think that in dermatomyositis, the most commonly associated malignancy is ovarian cancer. Wait, but I'm not entirely sure. Maybe I should think of specific numbers. For example, in some studies, about 20% of adult patients with dermatomyositis have an associated malignancy, and the most common ones are ovarian cancer, lung cancer, breast cancer, and lymphomas. However, the exact ranking might differ. \n",
      "\n",
      "Alternatively, some sources state that the most frequently reported malignancies in dermatomyositis are lung cancer (especially non-small cell), ovarian cancer, and lymphomas. However, if I have to pick one as the most often associated, perhaps lung cancer is the answer? Or maybe ovarian cancer?\n",
      "\n",
      "Wait, I think that in some references, lung cancer is cited as the most common malignancy associated with dermatomyositis. For example, a study might show that lung cancer is the most frequently associated malignancy in dermatomyositis patients. Alternatively, maybe breast cancer.\n",
      "\n",
      "Alternatively, perhaps the correct answer is ovarian cancer. Wait, I'm getting confused. Let me try to recall specific associations. \n",
      "\n",
      "Another angle: certain autoantibodies might be associated with specific cancers. For example, anti-Mi-2 antibodies are associated with a lower risk of malignancy, whereas anti-Jo-1 is more associated with interstitial lung disease rather than cancer. Since this patient has anti-Jo-1 antibodies, maybe that's a clue. But does anti-Jo-1 affect the cancer association? Maybe not directly. \n",
      "\n",
      "So the question is about dermatomyositis in general. I think that the most commonly associated cancer is ovarian cancer, but I'm not certain. Alternatively, lung cancer. \n",
      "\n",
      "Wait, I think I remember that in dermatomyositis, the most common cancers are lung cancer (especially squamous cell), ovarian cancer, breast cancer, and lymphomas. But if I have to choose one, maybe ovarian cancer is the most frequently cited. \n",
      "\n",
      "Alternatively, perhaps lung cancer is the most common. Wait, some sources say that lung cancer is the most common malignancy associated with dermatomyositis. For example, a study published in Arthritis & Rheumatism found that lung cancer was the most common malignancy in dermatomyositis patients. \n",
      "\n",
      "But I'm not sure. Another approach: think of the classic associations. For example, in dermatomyositis, the presence of a heliotrope rash and Got\n"
     ]
    }
   ],
   "source": [
    "question = dataset[10]['Question']\n",
    "inputs = tokenizer(\n",
    "    [inference_prompt_style.format(question, \"\") + tokenizer.eos_token],\n",
    "    return_tensors=\"pt\"\n",
    ").to(\"cuda\")\n",
    "\n",
    "outputs = model.generate(\n",
    "    input_ids=inputs.input_ids,\n",
    "    attention_mask=inputs.attention_mask,\n",
    "    max_new_tokens=1200,\n",
    "    eos_token_id=tokenizer.eos_token_id,\n",
    "    use_cache=True,\n",
    ")\n",
    "response = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
    "print(response[0].split(\"### Response:\")[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setting up the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from peft import LoraConfig, get_peft_model\n",
    "\n",
    "# LoRA config\n",
    "peft_config = LoraConfig(\n",
    "    lora_alpha=16,                           # Scaling factor for LoRA\n",
    "    lora_dropout=0.05,                       # Add slight dropout for regularization\n",
    "    r=64,                                    # Rank of the LoRA update matrices\n",
    "    bias=\"none\",                             # No bias reparameterization\n",
    "    task_type=\"CAUSAL_LM\",                   # Task type: Causal Language Modeling\n",
    "    target_modules=[\n",
    "        \"q_proj\",\n",
    "        \"k_proj\",\n",
    "        \"v_proj\",\n",
    "        \"o_proj\",\n",
    "        \"gate_proj\",\n",
    "        \"up_proj\",\n",
    "        \"down_proj\",\n",
    "    ],  # Target modules for LoRA\n",
    ")\n",
    "\n",
    "model = get_peft_model(model, peft_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "493a98d757814d53b7d49d0a010bb467",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Converting train dataset to ChatML:   0%|          | 0/2000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "cec6ce8ff8e7445abc24630d836327e4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Adding EOS to train dataset:   0%|          | 0/2000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b2863e9e45db496dbf60563b4d265961",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Tokenizing train dataset:   0%|          | 0/2000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d45bd6835aa643c59e771b89ef10230b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Truncating train dataset:   0%|          | 0/2000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No label_names provided for model class `PeftModelForCausalLM`. Since `PeftModel` hides base models input arguments, if label_names is not given, label_names can't be set automatically within `Trainer`. Note that empty label_names list will be used instead.\n"
     ]
    }
   ],
   "source": [
    "from trl import SFTTrainer\n",
    "from transformers import TrainingArguments\n",
    "\n",
    "\n",
    "# Training Arguments\n",
    "training_arguments = TrainingArguments(\n",
    "    output_dir=\"output\",\n",
    "    per_device_train_batch_size=1,\n",
    "    per_device_eval_batch_size=1,\n",
    "    gradient_accumulation_steps=2,\n",
    "    optim=\"paged_adamw_32bit\",\n",
    "    num_train_epochs=1,\n",
    "    logging_steps=0.2,\n",
    "    warmup_steps=10,\n",
    "    logging_strategy=\"steps\",\n",
    "    learning_rate=2e-4,\n",
    "    fp16=False,\n",
    "    bf16=False,\n",
    "    group_by_length=True,\n",
    "    report_to=\"none\"\n",
    ")\n",
    "\n",
    "# Initialize the Trainer\n",
    "trainer = SFTTrainer(\n",
    "    model=model,\n",
    "    args=training_arguments,\n",
    "    train_dataset=dataset,\n",
    "    peft_config=peft_config,\n",
    "    data_collator=data_collator,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model Training"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='1000' max='1000' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [1000/1000 41:49, Epoch 1/1]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Step</th>\n",
       "      <th>Training Loss</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>200</td>\n",
       "      <td>1.186100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>400</td>\n",
       "      <td>1.125300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>600</td>\n",
       "      <td>1.119600</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>800</td>\n",
       "      <td>1.120100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1000</td>\n",
       "      <td>1.095900</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "TrainOutput(global_step=1000, training_loss=1.1294009857177734, metrics={'train_runtime': 2515.0296, 'train_samples_per_second': 0.795, 'train_steps_per_second': 0.398, 'total_flos': 2.7579217282460467e+17, 'train_loss': 1.1294009857177734})"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc, torch\n",
    "gc.collect()\n",
    "torch.cuda.empty_cache()\n",
    "model.config.use_cache = False\n",
    "trainer.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model inference after fine-tuning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "<think>\n",
      "In dermatomyositis, there's a known link between the condition and certain cancers. The connection is especially significant in adult patients. So, which type of cancer is most commonly associated with dermatomyositis?\n",
      "\n",
      "First, I know that dermatomyositis can be an indicator of underlying cancer. It's like a sign that something else might be going on in the body. When we talk about the cancers linked to dermatomyositis, several come to mind, like lung cancer, breast cancer, ovarian cancer, and sometimes even pancreatic cancer. But there's one that really stands out.\n",
      "\n",
      "Let's think about it: lung cancer is often mentioned as being closely tied to dermatomyositis. It seems that lung cancer, especially non-small cell lung cancer, is the most frequently associated with this condition. It's not just a coincidence; it's been observed in many studies that when dermatomyositis is diagnosed in adults, there's a higher likelihood of lung cancer being present.\n",
      "\n",
      "Now, why is lung cancer so closely linked with dermatomyositis? One theory is that the presence of dermatomyositis might be a sign of the immune system responding to cancer. It's like the body's way of saying, \"Hey, there's something wrong here.\" This immune response might be what leads to the symptoms we see in dermatomyositis.\n",
      "\n",
      "So, putting it all together, when we look at the data, lung cancer, particularly non-small cell lung cancer, is the type most often associated with dermatomyositis. It's a well-documented connection, and it's important for doctors to consider this possibility when diagnosing dermatomyositis, especially in adult patients.\n",
      "\n",
      "In conclusion, given the symptoms and the known associations, lung cancer, especially non-small cell lung cancer, is the type most commonly linked with dermatomyositis. This is a key point that doctors keep in mind when treating patients with this condition.\n",
      "</think>\n",
      "In patients with dermatomyositis, lung cancer, particularly non-small cell lung cancer, is the type most commonly associated with the condition. This connection is well-documented, and it's important for healthcare providers to consider the possibility of underlying cancer when diagnosing dermatomyositis, especially in adult patients.\n"
     ]
    }
   ],
   "source": [
    "question = dataset[10]['Question']\n",
    "inputs = tokenizer(\n",
    "    [inference_prompt_style.format(question, \"\") + tokenizer.eos_token],\n",
    "    return_tensors=\"pt\"\n",
    ").to(\"cuda\")\n",
    "\n",
    "outputs = model.generate(\n",
    "    input_ids=inputs.input_ids,\n",
    "    attention_mask=inputs.attention_mask,\n",
    "    max_new_tokens=1200,\n",
    "    eos_token_id=tokenizer.eos_token_id,\n",
    "    use_cache=True,\n",
    ")\n",
    "response = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
    "print(response[0].split(\"### Response:\")[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "<think>\n",
      "Toxic shock syndrome, or TSS, is usually associated with bacterial toxins, especially those produced by Staphylococcus aureus. These toxins can cause a massive release of cytokines, leading to symptoms like fever, rash, and systemic issues. The toxins involved are known as superantigens.\n",
      "\n",
      "Superantigens are special because they don't need to be processed by antigen-presenting cells to activate T cells. Instead, they bind directly to the outside of MHC class II molecules on antigen-presenting cells. This binding allows the toxin to interact with a large number of T cells, not just specific ones. This interaction is a key factor in the massive immune response seen in TSS.\n",
      "\n",
      "So, these superantigens bind to T cell receptors, but in a different way than typical antigens. They don't bind to the antigen-binding site of the T cell receptor but rather to the variable region, specifically the β-chain. This unique binding causes the activation of many T cells, which leads to the release of a lot of cytokines.\n",
      "\n",
      "In the case of TSS, the toxins produced by Staphylococcus aureus, like TSS toxin-1, bind to the β-chain of the T cell receptor. This binding leads to the massive immune response that causes the symptoms of TSS.\n",
      "\n",
      "So, the specific molecule on T cells that the toxin most likely binds to is the β-chain of the T cell receptor.\n",
      "</think>\n",
      "The toxin most likely binds to the β-chain of the T cell receptor. In toxic shock syndrome, superantigens produced by bacteria such as Staphylococcus aureus bind to the β-chain of the T cell receptor, triggering a massive immune response and the characteristic symptoms of TSS.\n"
     ]
    }
   ],
   "source": [
    "question = dataset[100]['Question']\n",
    "inputs = tokenizer(\n",
    "    [inference_prompt_style.format(question, \"\") + tokenizer.eos_token],\n",
    "    return_tensors=\"pt\"\n",
    ").to(\"cuda\")\n",
    "\n",
    "outputs = model.generate(\n",
    "    input_ids=inputs.input_ids,\n",
    "    attention_mask=inputs.attention_mask,\n",
    "    max_new_tokens=1200,\n",
    "    eos_token_id=tokenizer.eos_token_id,\n",
    "    use_cache=True,\n",
    ")\n",
    "response = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
    "print(response[0].split(\"### Response:\")[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Saving the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1f3228aa7aa742c5bc5e010354d69bd8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Uploading...:   0%|          | 0.00/2.15G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No files have been modified since last commit. Skipping to prevent empty commit.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "08675e6ccc2c40f3ac34e6dba442036a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Uploading...:   0%|          | 0.00/11.4M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No files have been modified since last commit. Skipping to prevent empty commit.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/kingabzpro/Qwen-3-32B-Medical-Reasoning/commit/028c43854a330c79b2dc214feda3ebfe6b4b85a0', commit_message='Upload tokenizer', commit_description='', oid='028c43854a330c79b2dc214feda3ebfe6b4b85a0', pr_url=None, repo_url=RepoUrl('https://huggingface.co/kingabzpro/Qwen-3-32B-Medical-Reasoning', endpoint='https://huggingface.co', repo_type='model', repo_id='kingabzpro/Qwen-3-32B-Medical-Reasoning'), pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_model_name = \"Qwen-3-32B-Medical-Reasoning\"\n",
    "model.push_to_hub(new_model_name)\n",
    "tokenizer.push_to_hub(new_model_name)"
   ]
  }
 ],
 "metadata": {
  "kaggle": {
   "accelerator": "nvidiaTeslaT4",
   "dataSources": [
    {
     "modelId": 322000,
     "modelInstanceId": 301517,
     "sourceId": 363139,
     "sourceType": "modelInstanceVersion"
    }
   ],
   "dockerImageVersionId": 31011,
   "isGpuEnabled": true,
   "isInternetEnabled": true,
   "language": "python",
   "sourceType": "notebook"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}