kingabzpro commited on
Commit
204d8d8
·
verified ·
1 Parent(s): 196cacf

Upload fine-tuning-qwen-3.ipynb

Browse files
Files changed (1) hide show
  1. fine-tuning-qwen-3.ipynb +834 -0
fine-tuning-qwen-3.ipynb ADDED
@@ -0,0 +1,834 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## Setting Up"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": 1,
13
+ "metadata": {},
14
+ "outputs": [],
15
+ "source": [
16
+ "%%capture\n",
17
+ "%pip install -U transformers\n",
18
+ "%pip install -U datasets \n",
19
+ "%pip install -U accelerate \n",
20
+ "%pip install -U peft \n",
21
+ "%pip install -U trl \n",
22
+ "%pip install -U bitsandbytes\n",
23
+ "%pip install huggingface_hub[hf_xet]"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": 2,
29
+ "metadata": {},
30
+ "outputs": [
31
+ {
32
+ "name": "stderr",
33
+ "output_type": "stream",
34
+ "text": [
35
+ "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
36
+ ]
37
+ }
38
+ ],
39
+ "source": [
40
+ "from huggingface_hub import login\n",
41
+ "import os\n",
42
+ "\n",
43
+ "hf_token = os.environ.get(\"HF_TOKEN\")\n",
44
+ "login(hf_token)"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "markdown",
49
+ "metadata": {},
50
+ "source": [
51
+ "## Loading the model and tokenizer"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": 3,
57
+ "metadata": {
58
+ "_cell_guid": "82e08da0-4ee2-4235-a54f-c2bed3609a2b",
59
+ "_uuid": "059b3da3-4a60-40ed-8a3c-2c395b2c3a8d",
60
+ "collapsed": false,
61
+ "jupyter": {
62
+ "outputs_hidden": false
63
+ }
64
+ },
65
+ "outputs": [],
66
+ "source": [
67
+ "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
68
+ "import torch\n"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": 4,
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "bnb_config = BitsAndBytesConfig(\n",
78
+ " load_in_4bit=True,\n",
79
+ " bnb_4bit_use_double_quant=False,\n",
80
+ " bnb_4bit_quant_type=\"nf4\",\n",
81
+ " bnb_4bit_compute_dtype=torch.bfloat16,\n",
82
+ ")"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": 5,
88
+ "metadata": {},
89
+ "outputs": [
90
+ {
91
+ "data": {
92
+ "application/vnd.jupyter.widget-view+json": {
93
+ "model_id": "6784ce596124486cb42f8dbb5680a038",
94
+ "version_major": 2,
95
+ "version_minor": 0
96
+ },
97
+ "text/plain": [
98
+ "Loading checkpoint shards: 0%| | 0/17 [00:00<?, ?it/s]"
99
+ ]
100
+ },
101
+ "metadata": {},
102
+ "output_type": "display_data"
103
+ }
104
+ ],
105
+ "source": [
106
+ "# Load tokenizer & model\n",
107
+ "\n",
108
+ "model_dir = \"Qwen/Qwen3-32B\"\n",
109
+ "\n",
110
+ "tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True)\n",
111
+ "\n",
112
+ "model = AutoModelForCausalLM.from_pretrained(\n",
113
+ " model_dir,\n",
114
+ " quantization_config=bnb_config, \n",
115
+ " device_map=\"auto\", \n",
116
+ " torch_dtype=torch.bfloat16,\n",
117
+ " trust_remote_code=True \n",
118
+ ")\n",
119
+ "\n",
120
+ "model.config.use_cache = False\n",
121
+ "model.config.pretraining_tp = 1"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": 6,
127
+ "metadata": {},
128
+ "outputs": [
129
+ {
130
+ "name": "stdout",
131
+ "output_type": "stream",
132
+ "text": [
133
+ "Tue Apr 29 13:19:53 2025 \n",
134
+ "+-----------------------------------------------------------------------------------------+\n",
135
+ "| NVIDIA-SMI 565.57.01 Driver Version: 565.57.01 CUDA Version: 12.8 |\n",
136
+ "|-----------------------------------------+------------------------+----------------------+\n",
137
+ "| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n",
138
+ "| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n",
139
+ "| | | MIG M. |\n",
140
+ "|=========================================+========================+======================|\n",
141
+ "| 0 NVIDIA A100-SXM4-80GB On | 00000000:9B:00.0 Off | 0 |\n",
142
+ "| N/A 29C P0 84W / 400W | 31789MiB / 81920MiB | 0% Default |\n",
143
+ "| | | Disabled |\n",
144
+ "+-----------------------------------------+------------------------+----------------------+\n",
145
+ " \n",
146
+ "+-----------------------------------------------------------------------------------------+\n",
147
+ "| Processes: |\n",
148
+ "| GPU GI CI PID Type Process name GPU Memory |\n",
149
+ "| ID ID Usage |\n",
150
+ "|=========================================================================================|\n",
151
+ "+-----------------------------------------------------------------------------------------+\n"
152
+ ]
153
+ }
154
+ ],
155
+ "source": [
156
+ "!nvidia-smi"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "## Loading and processing the dataset"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": 7,
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "train_prompt_style = \"\"\"Below is an instruction that describes a task, paired with an input that provides further context. \n",
173
+ "Write a response that appropriately completes the request. \n",
174
+ "Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.\n",
175
+ "\n",
176
+ "### Instruction:\n",
177
+ "You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. \n",
178
+ "Please answer the following medical question. \n",
179
+ "\n",
180
+ "### Question:\n",
181
+ "{}\n",
182
+ "\n",
183
+ "### Response:\n",
184
+ "<think>\n",
185
+ "{}\n",
186
+ "</think>\n",
187
+ "{}\"\"\""
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": 8,
193
+ "metadata": {},
194
+ "outputs": [],
195
+ "source": [
196
+ "EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN\n",
197
+ "\n",
198
+ "def formatting_prompts_func(examples):\n",
199
+ " inputs = examples[\"Question\"]\n",
200
+ " complex_cots = examples[\"Complex_CoT\"]\n",
201
+ " outputs = examples[\"Response\"]\n",
202
+ " texts = []\n",
203
+ " for question, cot, response in zip(inputs, complex_cots, outputs):\n",
204
+ " # Append the EOS token to the response if it's not already there\n",
205
+ " if not response.endswith(tokenizer.eos_token):\n",
206
+ " response += tokenizer.eos_token\n",
207
+ " text = train_prompt_style.format(question, cot, response)\n",
208
+ " texts.append(text)\n",
209
+ " return {\"text\": texts}"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "execution_count": 9,
215
+ "metadata": {},
216
+ "outputs": [
217
+ {
218
+ "data": {
219
+ "application/vnd.jupyter.widget-view+json": {
220
+ "model_id": "6bbb17fe1316445cb5c849258d94aea6",
221
+ "version_major": 2,
222
+ "version_minor": 0
223
+ },
224
+ "text/plain": [
225
+ "README.md: 0%| | 0.00/1.97k [00:00<?, ?B/s]"
226
+ ]
227
+ },
228
+ "metadata": {},
229
+ "output_type": "display_data"
230
+ },
231
+ {
232
+ "data": {
233
+ "application/vnd.jupyter.widget-view+json": {
234
+ "model_id": "efe760c819454343a4212a5d401af10f",
235
+ "version_major": 2,
236
+ "version_minor": 0
237
+ },
238
+ "text/plain": [
239
+ "medical_o1_sft.json: 0%| | 0.00/58.2M [00:00<?, ?B/s]"
240
+ ]
241
+ },
242
+ "metadata": {},
243
+ "output_type": "display_data"
244
+ },
245
+ {
246
+ "data": {
247
+ "application/vnd.jupyter.widget-view+json": {
248
+ "model_id": "e84278d969714666b536448b6f1dd663",
249
+ "version_major": 2,
250
+ "version_minor": 0
251
+ },
252
+ "text/plain": [
253
+ "Generating train split: 0%| | 0/19704 [00:00<?, ? examples/s]"
254
+ ]
255
+ },
256
+ "metadata": {},
257
+ "output_type": "display_data"
258
+ },
259
+ {
260
+ "data": {
261
+ "application/vnd.jupyter.widget-view+json": {
262
+ "model_id": "22320917d4f0468e97c0364c3d2b10e0",
263
+ "version_major": 2,
264
+ "version_minor": 0
265
+ },
266
+ "text/plain": [
267
+ "Map: 0%| | 0/2000 [00:00<?, ? examples/s]"
268
+ ]
269
+ },
270
+ "metadata": {},
271
+ "output_type": "display_data"
272
+ },
273
+ {
274
+ "data": {
275
+ "text/plain": [
276
+ "\"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|>\""
277
+ ]
278
+ },
279
+ "execution_count": 9,
280
+ "metadata": {},
281
+ "output_type": "execute_result"
282
+ }
283
+ ],
284
+ "source": [
285
+ "from datasets import load_dataset\n",
286
+ "\n",
287
+ "dataset = load_dataset(\n",
288
+ " \"FreedomIntelligence/medical-o1-reasoning-SFT\",\n",
289
+ " \"en\",\n",
290
+ " split=\"train[0:2000]\",\n",
291
+ " trust_remote_code=True,\n",
292
+ ")\n",
293
+ "dataset = dataset.map(\n",
294
+ " formatting_prompts_func,\n",
295
+ " batched=True,\n",
296
+ ")\n",
297
+ "dataset[\"text\"][10]"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": 10,
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "from transformers import DataCollatorForLanguageModeling\n",
307
+ "\n",
308
+ "data_collator = DataCollatorForLanguageModeling(\n",
309
+ " tokenizer=tokenizer,\n",
310
+ " mlm=False\n",
311
+ ")"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "markdown",
316
+ "metadata": {},
317
+ "source": [
318
+ "## Model inference before fine-tuning"
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "execution_count": 11,
324
+ "metadata": {},
325
+ "outputs": [],
326
+ "source": [
327
+ "inference_prompt_style = \"\"\"Below is an instruction that describes a task, paired with an input that provides further context. \n",
328
+ "Write a response that appropriately completes the request. \n",
329
+ "Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.\n",
330
+ "\n",
331
+ "### Instruction:\n",
332
+ "You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. \n",
333
+ "Please answer the following medical question. \n",
334
+ "\n",
335
+ "### Question:\n",
336
+ "{}\n",
337
+ "\n",
338
+ "### Response:\n",
339
+ "<think>{}\"\"\""
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "execution_count": 13,
345
+ "metadata": {},
346
+ "outputs": [
347
+ {
348
+ "name": "stdout",
349
+ "output_type": "stream",
350
+ "text": [
351
+ "\n",
352
+ "<think>\n",
353
+ "\n",
354
+ "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",
355
+ "\n",
356
+ "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",
357
+ "\n",
358
+ "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",
359
+ "\n",
360
+ "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",
361
+ "\n",
362
+ "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",
363
+ "\n",
364
+ "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",
365
+ "\n",
366
+ "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",
367
+ "\n",
368
+ "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",
369
+ "\n",
370
+ "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",
371
+ "\n",
372
+ "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",
373
+ "\n",
374
+ "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",
375
+ "\n",
376
+ "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",
377
+ "\n",
378
+ "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",
379
+ "\n",
380
+ "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",
381
+ "\n",
382
+ "Alternatively, perhaps the correct answer is ovarian cancer. Wait, I'm getting confused. Let me try to recall specific associations. \n",
383
+ "\n",
384
+ "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",
385
+ "\n",
386
+ "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",
387
+ "\n",
388
+ "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",
389
+ "\n",
390
+ "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",
391
+ "\n",
392
+ "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"
393
+ ]
394
+ }
395
+ ],
396
+ "source": [
397
+ "question = dataset[10]['Question']\n",
398
+ "inputs = tokenizer(\n",
399
+ " [inference_prompt_style.format(question, \"\") + tokenizer.eos_token],\n",
400
+ " return_tensors=\"pt\"\n",
401
+ ").to(\"cuda\")\n",
402
+ "\n",
403
+ "outputs = model.generate(\n",
404
+ " input_ids=inputs.input_ids,\n",
405
+ " attention_mask=inputs.attention_mask,\n",
406
+ " max_new_tokens=1200,\n",
407
+ " eos_token_id=tokenizer.eos_token_id,\n",
408
+ " use_cache=True,\n",
409
+ ")\n",
410
+ "response = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
411
+ "print(response[0].split(\"### Response:\")[1])"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "markdown",
416
+ "metadata": {},
417
+ "source": [
418
+ "## Setting up the model"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "code",
423
+ "execution_count": 14,
424
+ "metadata": {},
425
+ "outputs": [],
426
+ "source": [
427
+ "from peft import LoraConfig, get_peft_model\n",
428
+ "\n",
429
+ "# LoRA config\n",
430
+ "peft_config = LoraConfig(\n",
431
+ " lora_alpha=16, # Scaling factor for LoRA\n",
432
+ " lora_dropout=0.05, # Add slight dropout for regularization\n",
433
+ " r=64, # Rank of the LoRA update matrices\n",
434
+ " bias=\"none\", # No bias reparameterization\n",
435
+ " task_type=\"CAUSAL_LM\", # Task type: Causal Language Modeling\n",
436
+ " target_modules=[\n",
437
+ " \"q_proj\",\n",
438
+ " \"k_proj\",\n",
439
+ " \"v_proj\",\n",
440
+ " \"o_proj\",\n",
441
+ " \"gate_proj\",\n",
442
+ " \"up_proj\",\n",
443
+ " \"down_proj\",\n",
444
+ " ], # Target modules for LoRA\n",
445
+ ")\n",
446
+ "\n",
447
+ "model = get_peft_model(model, peft_config)"
448
+ ]
449
+ },
450
+ {
451
+ "cell_type": "code",
452
+ "execution_count": 15,
453
+ "metadata": {},
454
+ "outputs": [
455
+ {
456
+ "data": {
457
+ "application/vnd.jupyter.widget-view+json": {
458
+ "model_id": "493a98d757814d53b7d49d0a010bb467",
459
+ "version_major": 2,
460
+ "version_minor": 0
461
+ },
462
+ "text/plain": [
463
+ "Converting train dataset to ChatML: 0%| | 0/2000 [00:00<?, ? examples/s]"
464
+ ]
465
+ },
466
+ "metadata": {},
467
+ "output_type": "display_data"
468
+ },
469
+ {
470
+ "data": {
471
+ "application/vnd.jupyter.widget-view+json": {
472
+ "model_id": "cec6ce8ff8e7445abc24630d836327e4",
473
+ "version_major": 2,
474
+ "version_minor": 0
475
+ },
476
+ "text/plain": [
477
+ "Adding EOS to train dataset: 0%| | 0/2000 [00:00<?, ? examples/s]"
478
+ ]
479
+ },
480
+ "metadata": {},
481
+ "output_type": "display_data"
482
+ },
483
+ {
484
+ "data": {
485
+ "application/vnd.jupyter.widget-view+json": {
486
+ "model_id": "b2863e9e45db496dbf60563b4d265961",
487
+ "version_major": 2,
488
+ "version_minor": 0
489
+ },
490
+ "text/plain": [
491
+ "Tokenizing train dataset: 0%| | 0/2000 [00:00<?, ? examples/s]"
492
+ ]
493
+ },
494
+ "metadata": {},
495
+ "output_type": "display_data"
496
+ },
497
+ {
498
+ "data": {
499
+ "application/vnd.jupyter.widget-view+json": {
500
+ "model_id": "d45bd6835aa643c59e771b89ef10230b",
501
+ "version_major": 2,
502
+ "version_minor": 0
503
+ },
504
+ "text/plain": [
505
+ "Truncating train dataset: 0%| | 0/2000 [00:00<?, ? examples/s]"
506
+ ]
507
+ },
508
+ "metadata": {},
509
+ "output_type": "display_data"
510
+ },
511
+ {
512
+ "name": "stderr",
513
+ "output_type": "stream",
514
+ "text": [
515
+ "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"
516
+ ]
517
+ }
518
+ ],
519
+ "source": [
520
+ "from trl import SFTTrainer\n",
521
+ "from transformers import TrainingArguments\n",
522
+ "\n",
523
+ "\n",
524
+ "# Training Arguments\n",
525
+ "training_arguments = TrainingArguments(\n",
526
+ " output_dir=\"output\",\n",
527
+ " per_device_train_batch_size=1,\n",
528
+ " per_device_eval_batch_size=1,\n",
529
+ " gradient_accumulation_steps=2,\n",
530
+ " optim=\"paged_adamw_32bit\",\n",
531
+ " num_train_epochs=1,\n",
532
+ " logging_steps=0.2,\n",
533
+ " warmup_steps=10,\n",
534
+ " logging_strategy=\"steps\",\n",
535
+ " learning_rate=2e-4,\n",
536
+ " fp16=False,\n",
537
+ " bf16=False,\n",
538
+ " group_by_length=True,\n",
539
+ " report_to=\"none\"\n",
540
+ ")\n",
541
+ "\n",
542
+ "# Initialize the Trainer\n",
543
+ "trainer = SFTTrainer(\n",
544
+ " model=model,\n",
545
+ " args=training_arguments,\n",
546
+ " train_dataset=dataset,\n",
547
+ " peft_config=peft_config,\n",
548
+ " data_collator=data_collator,\n",
549
+ ")"
550
+ ]
551
+ },
552
+ {
553
+ "cell_type": "markdown",
554
+ "metadata": {},
555
+ "source": [
556
+ "## Model Training"
557
+ ]
558
+ },
559
+ {
560
+ "cell_type": "code",
561
+ "execution_count": 16,
562
+ "metadata": {},
563
+ "outputs": [
564
+ {
565
+ "data": {
566
+ "text/html": [
567
+ "\n",
568
+ " <div>\n",
569
+ " \n",
570
+ " <progress value='1000' max='1000' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
571
+ " [1000/1000 41:49, Epoch 1/1]\n",
572
+ " </div>\n",
573
+ " <table border=\"1\" class=\"dataframe\">\n",
574
+ " <thead>\n",
575
+ " <tr style=\"text-align: left;\">\n",
576
+ " <th>Step</th>\n",
577
+ " <th>Training Loss</th>\n",
578
+ " </tr>\n",
579
+ " </thead>\n",
580
+ " <tbody>\n",
581
+ " <tr>\n",
582
+ " <td>200</td>\n",
583
+ " <td>1.186100</td>\n",
584
+ " </tr>\n",
585
+ " <tr>\n",
586
+ " <td>400</td>\n",
587
+ " <td>1.125300</td>\n",
588
+ " </tr>\n",
589
+ " <tr>\n",
590
+ " <td>600</td>\n",
591
+ " <td>1.119600</td>\n",
592
+ " </tr>\n",
593
+ " <tr>\n",
594
+ " <td>800</td>\n",
595
+ " <td>1.120100</td>\n",
596
+ " </tr>\n",
597
+ " <tr>\n",
598
+ " <td>1000</td>\n",
599
+ " <td>1.095900</td>\n",
600
+ " </tr>\n",
601
+ " </tbody>\n",
602
+ "</table><p>"
603
+ ],
604
+ "text/plain": [
605
+ "<IPython.core.display.HTML object>"
606
+ ]
607
+ },
608
+ "metadata": {},
609
+ "output_type": "display_data"
610
+ },
611
+ {
612
+ "data": {
613
+ "text/plain": [
614
+ "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})"
615
+ ]
616
+ },
617
+ "execution_count": 16,
618
+ "metadata": {},
619
+ "output_type": "execute_result"
620
+ }
621
+ ],
622
+ "source": [
623
+ "import gc, torch\n",
624
+ "gc.collect()\n",
625
+ "torch.cuda.empty_cache()\n",
626
+ "model.config.use_cache = False\n",
627
+ "trainer.train()"
628
+ ]
629
+ },
630
+ {
631
+ "cell_type": "markdown",
632
+ "metadata": {},
633
+ "source": [
634
+ "## Model inference after fine-tuning"
635
+ ]
636
+ },
637
+ {
638
+ "cell_type": "code",
639
+ "execution_count": 18,
640
+ "metadata": {},
641
+ "outputs": [
642
+ {
643
+ "name": "stdout",
644
+ "output_type": "stream",
645
+ "text": [
646
+ "\n",
647
+ "<think>\n",
648
+ "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",
649
+ "\n",
650
+ "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",
651
+ "\n",
652
+ "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",
653
+ "\n",
654
+ "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",
655
+ "\n",
656
+ "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",
657
+ "\n",
658
+ "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",
659
+ "</think>\n",
660
+ "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"
661
+ ]
662
+ }
663
+ ],
664
+ "source": [
665
+ "question = dataset[10]['Question']\n",
666
+ "inputs = tokenizer(\n",
667
+ " [inference_prompt_style.format(question, \"\") + tokenizer.eos_token],\n",
668
+ " return_tensors=\"pt\"\n",
669
+ ").to(\"cuda\")\n",
670
+ "\n",
671
+ "outputs = model.generate(\n",
672
+ " input_ids=inputs.input_ids,\n",
673
+ " attention_mask=inputs.attention_mask,\n",
674
+ " max_new_tokens=1200,\n",
675
+ " eos_token_id=tokenizer.eos_token_id,\n",
676
+ " use_cache=True,\n",
677
+ ")\n",
678
+ "response = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
679
+ "print(response[0].split(\"### Response:\")[1])"
680
+ ]
681
+ },
682
+ {
683
+ "cell_type": "code",
684
+ "execution_count": 19,
685
+ "metadata": {},
686
+ "outputs": [
687
+ {
688
+ "name": "stdout",
689
+ "output_type": "stream",
690
+ "text": [
691
+ "\n",
692
+ "<think>\n",
693
+ "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",
694
+ "\n",
695
+ "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",
696
+ "\n",
697
+ "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",
698
+ "\n",
699
+ "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",
700
+ "\n",
701
+ "So, the specific molecule on T cells that the toxin most likely binds to is the β-chain of the T cell receptor.\n",
702
+ "</think>\n",
703
+ "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"
704
+ ]
705
+ }
706
+ ],
707
+ "source": [
708
+ "question = dataset[100]['Question']\n",
709
+ "inputs = tokenizer(\n",
710
+ " [inference_prompt_style.format(question, \"\") + tokenizer.eos_token],\n",
711
+ " return_tensors=\"pt\"\n",
712
+ ").to(\"cuda\")\n",
713
+ "\n",
714
+ "outputs = model.generate(\n",
715
+ " input_ids=inputs.input_ids,\n",
716
+ " attention_mask=inputs.attention_mask,\n",
717
+ " max_new_tokens=1200,\n",
718
+ " eos_token_id=tokenizer.eos_token_id,\n",
719
+ " use_cache=True,\n",
720
+ ")\n",
721
+ "response = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
722
+ "print(response[0].split(\"### Response:\")[1])"
723
+ ]
724
+ },
725
+ {
726
+ "cell_type": "markdown",
727
+ "metadata": {},
728
+ "source": [
729
+ "## Saving the model"
730
+ ]
731
+ },
732
+ {
733
+ "cell_type": "code",
734
+ "execution_count": 21,
735
+ "metadata": {},
736
+ "outputs": [
737
+ {
738
+ "data": {
739
+ "application/vnd.jupyter.widget-view+json": {
740
+ "model_id": "1f3228aa7aa742c5bc5e010354d69bd8",
741
+ "version_major": 2,
742
+ "version_minor": 0
743
+ },
744
+ "text/plain": [
745
+ "Uploading...: 0%| | 0.00/2.15G [00:00<?, ?B/s]"
746
+ ]
747
+ },
748
+ "metadata": {},
749
+ "output_type": "display_data"
750
+ },
751
+ {
752
+ "name": "stderr",
753
+ "output_type": "stream",
754
+ "text": [
755
+ "No files have been modified since last commit. Skipping to prevent empty commit.\n"
756
+ ]
757
+ },
758
+ {
759
+ "data": {
760
+ "application/vnd.jupyter.widget-view+json": {
761
+ "model_id": "08675e6ccc2c40f3ac34e6dba442036a",
762
+ "version_major": 2,
763
+ "version_minor": 0
764
+ },
765
+ "text/plain": [
766
+ "Uploading...: 0%| | 0.00/11.4M [00:00<?, ?B/s]"
767
+ ]
768
+ },
769
+ "metadata": {},
770
+ "output_type": "display_data"
771
+ },
772
+ {
773
+ "name": "stderr",
774
+ "output_type": "stream",
775
+ "text": [
776
+ "No files have been modified since last commit. Skipping to prevent empty commit.\n"
777
+ ]
778
+ },
779
+ {
780
+ "data": {
781
+ "text/plain": [
782
+ "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)"
783
+ ]
784
+ },
785
+ "execution_count": 21,
786
+ "metadata": {},
787
+ "output_type": "execute_result"
788
+ }
789
+ ],
790
+ "source": [
791
+ "new_model_name = \"Qwen-3-32B-Medical-Reasoning\"\n",
792
+ "model.push_to_hub(new_model_name)\n",
793
+ "tokenizer.push_to_hub(new_model_name)"
794
+ ]
795
+ }
796
+ ],
797
+ "metadata": {
798
+ "kaggle": {
799
+ "accelerator": "nvidiaTeslaT4",
800
+ "dataSources": [
801
+ {
802
+ "modelId": 322000,
803
+ "modelInstanceId": 301517,
804
+ "sourceId": 363139,
805
+ "sourceType": "modelInstanceVersion"
806
+ }
807
+ ],
808
+ "dockerImageVersionId": 31011,
809
+ "isGpuEnabled": true,
810
+ "isInternetEnabled": true,
811
+ "language": "python",
812
+ "sourceType": "notebook"
813
+ },
814
+ "kernelspec": {
815
+ "display_name": "Python 3 (ipykernel)",
816
+ "language": "python",
817
+ "name": "python3"
818
+ },
819
+ "language_info": {
820
+ "codemirror_mode": {
821
+ "name": "ipython",
822
+ "version": 3
823
+ },
824
+ "file_extension": ".py",
825
+ "mimetype": "text/x-python",
826
+ "name": "python",
827
+ "nbconvert_exporter": "python",
828
+ "pygments_lexer": "ipython3",
829
+ "version": "3.11.11"
830
+ }
831
+ },
832
+ "nbformat": 4,
833
+ "nbformat_minor": 4
834
+ }