File size: 33,717 Bytes
b51146f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "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": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "72f4f1bf4d4b4a6f8c4f7ec258efe012",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/6 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
    "import torch\n",
    "\n",
    "# Load tokenizer & model\n",
    "model_dir = \"microsoft/Phi-4-reasoning-plus\"\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True)\n",
    "\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    model_dir, \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": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tue May 13 18:05:17 2025       \n",
      "+-----------------------------------------------------------------------------------------+\n",
      "| NVIDIA-SMI 565.57.01              Driver Version: 565.57.01      CUDA Version: 12.7     |\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:4E:00.0 Off |                    0 |\n",
      "| N/A   25C    P0             65W /  400W |   28387MiB /  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": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_prompt_style=\"\"\"\n",
    "<|im_start|>system<|im_sep|>\n",
    "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",
    "<|im_end|>\n",
    "<|im_start|>user<|im_sep|>\n",
    "{}<|im_end|>\n",
    "<|im_start|>assistant<|im_sep|>\n",
    "<think>\n",
    "{}\n",
    "</think>\n",
    "{}\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS_TOKEN = tokenizer.eos_token  # Must add EOS_TOKEN\n",
    "\n",
    "def formatting_prompts_func(examples):\n",
    "    inputs = examples[\"Open-ended Verifiable Question\"]\n",
    "    complex_cots = examples[\"Complex_CoT\"]\n",
    "    outputs = examples[\"Response\"]\n",
    "    texts = []\n",
    "    for input, cot, output in zip(inputs,complex_cots,outputs):\n",
    "        text = train_prompt_style.format(input,cot,output) + EOS_TOKEN\n",
    "        texts.append(text)\n",
    "    return {\n",
    "        \"text\": texts,\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4b7732d8b4e343adaff55dcdb610a8a4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/1000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\"\\n<|im_start|>system<|im_sep|>\\nBelow 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<|im_end|>\\n<|im_start|>user<|im_sep|>\\nPlease answer the given financial question based on the context.\\nContext: american tower corporation and subsidiaries notes to consolidated financial statements 2014 ( continued ) stock-based compensation 2014the company complies with the provisions of sfas no . 148 , 201caccounting for stock-based compensation 2014transition and disclosure 2014an amendment of sfas no . 123 , 201d which provides optional transition guidance for those companies electing to voluntarily adopt the accounting provisions of sfas no . 123 . the company continues to use accounting principles board opinion no . 25 ( apb no . 25 ) , 201caccounting for stock issued to employees , 201d to account for equity grants and awards to employees , officers and directors and has adopted the disclosure-only provisions of sfas no . 148 . in accordance with apb no . 25 , the company recognizes compensation expense based on the excess , if any , of the quoted stock price at the grant date of the award or other measurement date over the amount an employee must pay to acquire the stock . the company 2019s stock option plans are more fully described in note 13 . in december 2004 , the fasb issued sfas no . 123r , 201cshare-based payment 201d ( sfas no . 123r ) , described below . the following table illustrates the effect on net loss and net loss per share if the company had applied the fair value recognition provisions of sfas no . 123 ( as amended ) to stock-based compensation . the estimated fair value of each option is calculated using the black-scholes option-pricing model ( in thousands , except per share amounts ) : .\\n||2004|2003|2002|\\n|net loss as reported|$ -247587 ( 247587 )|$ -325321 ( 325321 )|$ -1163540 ( 1163540 )|\\n|add : stock-based employee compensation expense associated with modifications net of related tax effect included in net loss asreported|2297|2077||\\n|less : total stock-based employee compensation expense determined under fair value based method for all awards net of related taxeffect|-23906 ( 23906 )|-31156 ( 31156 )|-38126 ( 38126 )|\\n|pro-forma net loss|$ -269196 ( 269196 )|$ -354400 ( 354400 )|$ -1201666 ( 1201666 )|\\n|basic and diluted net loss per share 2014as reported|$ -1.10 ( 1.10 )|$ -1.56 ( 1.56 )|$ -5.95 ( 5.95 )|\\n|basic and diluted net loss per share pro-forma|$ -1.20 ( 1.20 )|$ -1.70 ( 1.70 )|$ -6.15 ( 6.15 )|\\nduring the year ended december 31 , 2004 and 2003 , the company modified certain option awards to accelerate vesting and recorded charges of $ 3.0 million and $ 2.3 million , respectively , and corresponding increases to additional paid in capital in the accompanying consolidated financial statements . fair value of financial instruments 2014the carrying values of the company 2019s financial instruments , with the exception of long-term obligations , including current portion , reasonably approximate the related fair values as of december 31 , 2004 and 2003 . as of december 31 , 2004 , the carrying amount and fair value of long-term obligations , including current portion , were $ 3.3 billion and $ 3.6 billion , respectively . as of december 31 , 2003 , the carrying amount and fair value of long-term obligations , including current portion , were $ 3.4 billion and $ 3.6 billion , respectively . fair values are based primarily on quoted market prices for those or similar instruments . retirement plan 2014the company has a 401 ( k ) plan covering substantially all employees who meet certain age and employment requirements . under the plan , the company matching contribution for periods prior to june 30 , 2004 was 35% ( 35 % ) up to a maximum 5% ( 5 % ) of a participant 2019s contributions . effective july 1 , 2004 , the plan was amended to increase the company match to 50% ( 50 % ) up to a maximum 6% ( 6 % ) of a participant 2019s contributions . the company contributed approximately $ 533000 , $ 825000 and $ 979000 to the plan for the years ended december 31 , 2004 , 2003 and 2002 , respectively . recent accounting pronouncements 2014in december 2004 , the fasb issued sfas no . 123r , which is a revision of sfas no . 123 , 201caccounting for stock-based compensation , 201d and supersedes apb no . 25 , accounting for .\\nQuestion: what was the percentage increase in the employee contribution from 2002 to 2003\\nAnswer:<|im_end|>\\n<|im_start|>assistant<|im_sep|>\\n<think>\\nOkay, let's break this down. I need to figure out the percentage increase in employee contributions between 2002 and 2003 for the 401(k) plan. \\n\\nFirst off, the company's matching rates were consistent during this period. They matched 35% of employee contributions up to 5% of what the employees contributed in both 2002 and 2003. \\n\\nWhat I have is the company's contributions. In 2002, the company contributed $979,000, and in 2003, it was $825,000. \\n\\nSince the match rate was the same both years, I can say that $979,000 in 2002 and $825,000 in 2003 represented 35% of the employee contributions. But how do I get the total employee contributions from this?\\n\\nOh, right! To find the total employee contributions, I just need to reverse the percentage. So, for 2002, I divide $979,000 by 0.35. Hmm, doing the math, that gives $2,797,143 for total employee contributions in 2002.\\n\\nNow, for 2003, I do the same thing: divide $825,000 by 0.35. Alright, that works out to $2,357,143 for 2003.\\n\\nNext, I need to find out how the contributions changed from 2002 to 2003. This means calculating the percentage change. I take the difference between the contributions in 2003 and 2002, which is $2,357,143 minus $2,797,143.\\n\\nWait, the result looks like a decrease because it's negative. The difference is -$440,000, so there's actually a decrease. \\n\\nNow for the percentage: I divide this difference by the 2002 amount ($2,797,143) and then multiply by 100 to get the percentage. Let's see, this equals a change of about -15.725%.\\n\\nHmm, it makes sense now, the contributions actually decreased from 2002 to 2003 by roughly 15.725%.\\n</think>\\nThere was actually a percentage decrease in employee contributions from 2002 to 2003. The employee contributions decreased by approximately 15.725%.\\n<|im_end|>\""
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "dataset = load_dataset(\n",
    "    \"TheFinAI/Fino1_Reasoning_Path_FinQA\", split=\"train[0:1000]\", trust_remote_code=True\n",
    ")\n",
    "dataset = dataset.map(\n",
    "    formatting_prompts_func,\n",
    "    batched=True,\n",
    ")\n",
    "dataset[\"text\"][20]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "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": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "inference_prompt_style = \"\"\"\n",
    "<|im_start|>system<|im_sep|>\n",
    "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",
    "<|im_end|>\n",
    "<|im_start|>user<|im_sep|>\n",
    "{}<|im_end|>\n",
    "<|im_start|>assistant<|im_sep|>\n",
    "<think>\n",
    "{}\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<think><|im_end|>We are asked: \"what was the percentage increase in the employee contribution from 2002 to 2003?\" Let's check the provided context carefully. The context is a snippet from a financial statement notes. It says: \"retirement plan 2014the company has a 401 (k) plan covering substantially all employees who meet certain age and employment requirements . under the plan , the company matching contribution for periods prior to june 30, 2004 was 35% (35%) up to a maximum 5% (5%) of a participant's contributions. effective july 1, 2004, the plan was amended to increase the company match to 50% (50%) up to a maximum 6% (6%) of a participant's contributions. the company contributed approximately $533,000, $825,000 and $979,000 to the plan for the years ended December 31, 2004, 2003 and 2002, respectively.\"\n",
      "\n",
      "We must compute: \"what was the percentage increase in the employee contribution from 2002 to 2003?\" Wait, caution: The question says: \"what was the percentage increase in the employee contribution from 2002 to 2003?\" However, careful reading: \"the company contributed approximately $533,000, $825,000 and $979,000 to the plan for the years ended December 31, 2004, 2003, and 2002, respectively.\" The question: \"percentage increase in the employee contribution\" But these numbers are the company's contributions to the plan? Wait, not exactly, they are the company's contributions to the 401(k) plan. However, the question says \"employee contribution.\" But the text says \"the company contributed\" amounts. Actually, check: The text says \"the company contributed approximately $533,000, $825,000 and $979,000 to the plan for the years ended December 31, 2004, 2003, and 2002, respectively.\" That indicates the amounts that the company contributed. But the question says \"employee contribution.\" Possibly a misprint? Wait, maybe \"employee contribution\" means the employees' contributions? But no, the amounts are clearly stated as \"company contributed\" amounts.\n",
      "\n",
      "Let's re-read the retirement plan note carefully:\n",
      "\n",
      "\"retirement plan 2014the company has a 401 (k) plan covering substantially all employees who meet certain age and employment requirements . under the plan , the company matching contribution for periods prior to june 30, 2004 was 35% (35%) up to a maximum 5% (5%) of a participant's contributions. effective july 1, 2004, the plan was amended to increase the company match to 50% (50%) up to a maximum 6% (6%) of a participant's contributions. the company contributed approximately $533,000, $825,000 and $979,000 to the plan for the years ended December 31, 2004, 2003 and 2002, respectively.\"\n",
      "\n",
      "So the amounts are \"company contributions\" to the plan. But then the question asks: \"what was the percentage increase in the employee contribution from 2002 to 2003?\" Possibly the percentages refer to the company match percentages? Possibly the question means \"what was the percentage increase in the company match percentage from 2002 to 2003?\" But wait, the text: \"the company matching contribution for periods prior to june 30, 2004 was 35% up to a maximum 5% of a participant's contributions. effective july 1, 2004, the plan was amended to increase the company match to 50% up to a maximum 6% of a participant's contributions.\" But then the question: \"what was the percentage increase in the employee contribution from 2002 to 2003\" I see: The given numbers: For 2002: $979,000, for 2003: $825,000, for 2004: $533,000. The question asks: \"employee contribution\" but those amounts are company contributions. Possibly there is a misinterpretation: Actually the question may be asking: \"what was the percentage increase in the employee contribution\" but the text says \"the company contributed approximately $533,000, $825,000 and $979,000 to the plan for the years ended December 31, 2004, 2003 and 2002, respectively.\" So which one is the employee's contribution? Alternatively, the note says \"employee\" may refer to the company's matching contribution? Actually, re-read: \"under the plan, the company matching contribution for periods prior to june 30, 2004 was 35% (35%) up to a maximum 5% (5%) of a participant's contributions.\" That is the company match. Then: \"effective july 1, 2004, the plan was amended to increase the company match to 50% (50%) up to a maximum 6% (6%) of a participant's contributions.\" So these are percentages of the employee's contributions. But then later the note says \"the company contributed approximately $533,000, $825,000 and $979,000 to the plan for the years ended December 31, 2004, 2003 and 2002, respectively.\" So maybe the question \"what was the percentage increase in the employee contribution\" actually might refer to the company's matching contribution as a percentage of the employee contributions, i.e. from 5% to 6%? But then the question \"from 2002 to 2003\" doesn't match because the plan change effective date is july 1, 2004, and that's not relevant to the\n"
     ]
    }
   ],
   "source": [
    "question = dataset[20]['Open-ended Verifiable 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)\n",
    "print(response[0].split(\"<|im_start|>assistant<|im_sep|>\")[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setting up the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "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": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "50fed52d9fce44e5a7f7586b13700d83",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Converting train dataset to ChatML:   0%|          | 0/1000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bbe465aef9164fda938c16123563e185",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Adding EOS to train dataset:   0%|          | 0/1000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a302c537fdab496aad69b7f42915cacc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Tokenizing train dataset:   0%|          | 0/1000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3735f907a3a84669b38856d8e8e62a71",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Truncating train dataset:   0%|          | 0/1000 [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": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='500' max='500' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [500/500 07:20, 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>100</td>\n",
       "      <td>1.452900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>200</td>\n",
       "      <td>1.366900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>300</td>\n",
       "      <td>1.285200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>400</td>\n",
       "      <td>1.324600</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>500</td>\n",
       "      <td>1.345900</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=500, training_loss=1.3550911560058594, metrics={'train_runtime': 442.2688, 'train_samples_per_second': 2.261, 'train_steps_per_second': 1.131, 'total_flos': 8.592683944836096e+16, 'train_loss': 1.3550911560058594})"
      ]
     },
     "execution_count": 19,
     "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": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<think><|im_end|>First, I need to figure out what the employee contributions were for the years 2002 and 2003. Okay, looking at the numbers, I see that the company contributed $979,000 in 2002 and $825,000 in 2003. So, those are my two key figures. \n",
      "\n",
      "Next, I'll calculate the change in the contribution amount. To find this, I subtract the 2003 contribution from the 2002 contribution. Let me do that: $979,000 minus $825,000 equals $154,000. So, there's a decrease of $154,000 from 2002 to 2003.\n",
      "\n",
      "Now, I need to understand what this decrease means in terms of percentage. Percentage change is usually calculated by taking the change, dividing it by the original number, and then multiplying by 100. So, I'll take that $154,000 change and divide it by the 2002 amount, $979,000. \n",
      "\n",
      "Let me do that math: $154,000 divided by $979,000... Hmm, this gives me a value of approximately 0.1573. \n",
      "\n",
      "Finally, I multiply that by 100 to convert it to a percentage. That gives me about 15.73%. \n",
      "\n",
      "Oh, wait, let me make sure everything makes sense. I calculated the change in contributions correctly by subtracting the 2003 amount from the 2002 amount. Then I used the original amount from 2002 as the base for the percentage calculation. \n",
      "\n",
      "Yes, that all seems right. So, the employee contribution decreased by approximately 15.73% from 2002 to 2003.</think>The percentage decrease in the employee contribution from 2002 to 2003 was approximately 15.73%.<|im_end|>\n"
     ]
    }
   ],
   "source": [
    "question = dataset[20]['Open-ended Verifiable 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)\n",
    "print(response[0].split(\"<|im_start|>assistant<|im_sep|>\")[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<think><|im_end|>Okay, let's figure out how much of the long-term debt should be considered current liabilities. So, the total long-term debt at the end of 2011 was $1859 million. Now, I remember that there's some information about the timing of cash payments related to this debt. In particular, there's a chunk of $29 million that is due in 2012. Hmm, that's the part that's likely to become a current liability. \n",
      "\n",
      "Let’s check the table again to make sure. It says total long-term debt is $1859 million, and the breakdown of estimated cash payments includes $29 million for 2012. Yep, that seems to align. So, this $29 million should be classified as a current liability because it's due within the next year. \n",
      "\n",
      "But wait, let me double-check. The table is pretty straightforward: long-term debt is $1859 million and the breakdown clearly shows $29 million due in 2012. So, that $29 million is the part that should be on the current liabilities section of the balance sheet. \n",
      "\n",
      "Alright, so I'm confident that the portion of the long-term debt that's included in current liabilities as of December 31, 2011, is $29 million. That's it!</think>The portion of the long-term debt included in the current liabilities on the balance sheet as of December 31, 2011, is $29 million. This $29 million represents the amount of debt due within the next year, making it a current liability.<|im_end|>\n"
     ]
    }
   ],
   "source": [
    "question = dataset[200]['Open-ended Verifiable 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)\n",
    "print(response[0].split(\"<|im_start|>assistant<|im_sep|>\")[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Saving the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "353b85ce8ef84ff1980867ff5547abc0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Uploading...:   0%|          | 0.00/341M [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/Phi-4-Reasoning-Plus-FinQA-COT/commit/a18b837a05dc0a83729c7f0bab1a8e39a91b7774', commit_message='Upload tokenizer', commit_description='', oid='a18b837a05dc0a83729c7f0bab1a8e39a91b7774', pr_url=None, repo_url=RepoUrl('https://huggingface.co/kingabzpro/Phi-4-Reasoning-Plus-FinQA-COT', endpoint='https://huggingface.co', repo_type='model', repo_id='kingabzpro/Phi-4-Reasoning-Plus-FinQA-COT'), pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_model_name = \"Phi-4-Reasoning-Plus-FinQA-COT\"\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
}