File size: 77,736 Bytes
dfbf500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Model Evaluation: Fine-tuned vs Base Model Comparison\n",
        "\n",
        "This notebook compares the fine-tuned model against the original `unsloth/Llama-3.2-3B-Instruct` using:\n",
        "1. **ROUGE scores** comparing generated responses to ground truth\n",
        "2. **Qualitative examples** - side-by-side comparisons\n",
        "3. **Response length analysis**"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "%%capture\n",
        "# Install dependencies\n",
        "%uv pip install unsloth\n",
        "%uv pip install rouge-score evaluate datasets tqdm"
      ],
      "execution_count": 1,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "from unsloth import FastLanguageModel\n",
        "from unsloth.chat_templates import get_chat_template, standardize_sharegpt\n",
        "import torch\n",
        "import numpy as np\n",
        "from tqdm import tqdm\n",
        "from datasets import load_dataset\n",
        "\n",
        "# Configuration\n",
        "max_seq_length = 2048\n",
        "dtype = \"float16\"\n",
        "load_in_4bit = True\n",
        "\n",
        "BASE_MODEL_NAME = \"unsloth/Llama-3.2-3B-Instruct\"\n",
        "LORA_ADAPTER_PATH = \"/vol/checkpoint-10688\"  # your local folder in Modal\n"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\ud83e\udda5 Unsloth: Will patch your computer to enable 2x faster free finetuning.\n",
            "\ud83e\udda5 Unsloth Zoo will now patch everything to make training faster!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. Prepare the Test Dataset\n",
        "\n",
        "Using the same splits as during training (10% test set)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "# Load and prepare dataset (same as training)\n",
        "dataset = load_dataset(\"mlabonne/FineTome-100k\", split=\"train\")\n",
        "dataset = standardize_sharegpt(dataset)\n",
        "\n",
        "# Same splits as training: train+val (90%), test (10%)\n",
        "train_val_split = dataset.train_test_split(test_size=0.15, seed=42)\n",
        "test_dataset = train_val_split[\"test\"]\n",
        "\n",
        "print(f\"Test set size: {len(test_dataset)} samples\")"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "e56d65e8c6ec4db0b7c61258c77a9bd2",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "README.md:   0%|          | 0.00/982 [00:00<?, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "b3e8721d30df4d33a06e31865c6bb0fc",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "data/train-00000-of-00001.parquet:   0%|          | 0.00/117M [00:00<?, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "a6e0b28225b94469adcb2e6a58ae000d",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "Generating train split:   0%|          | 0/100000 [00:00<?, ? examples/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "7312c3a59534419993d6458816a64416",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "Unsloth: Standardizing formats (num_proc=14):   0%|          | 0/100000 [00:00<?, ? examples/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Test set size: 15000 samples\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. Load Base Model"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "# Load the BASE model (not fine-tuned)\n",
        "base_model, base_tokenizer = FastLanguageModel.from_pretrained(\n",
        "    model_name     = BASE_MODEL_NAME,\n",
        "    max_seq_length = max_seq_length,\n",
        "    dtype          = dtype,\n",
        "    load_in_4bit   = load_in_4bit,\n",
        ")\n",
        "base_tokenizer = get_chat_template(base_tokenizer, chat_template=\"llama-3.1\")\n",
        "FastLanguageModel.for_inference(base_model)\n",
        "print(\"Base model loaded!\")"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==((====))==  Unsloth 2025.11.6: Fast Llama patching. Transformers: 4.56.0.\n",
            "   \\\\   /|    Tesla T4. Num GPUs = 3. Max memory: 14.563 GB. Platform: Linux.\n",
            "O^O/ \\_/ \\    Torch: 2.9.0+cu128. CUDA: 7.5. CUDA Toolkit: 12.8. Triton: 3.5.0\n",
            "\\        /    Bfloat16 = FALSE. FA [Xformers = 0.0.33.post1. FA2 = False]\n",
            " \"-____-\"     Free license: http://github.com/unslothai/unsloth\n",
            "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "d388e30418ae4375ac5730e0c10c036d",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "model.safetensors:   0%|          | 0.00/2.35G [00:00<?, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "feb44d05734b494a8d7e793831499231",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "generation_config.json:   0%|          | 0.00/234 [00:00<?, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "bd4febb360a143f5b7bca061da96e65e",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "tokenizer_config.json: 0.00B [00:00, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "ce6dddafbc5042cba3be648d738725c5",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "special_tokens_map.json:   0%|          | 0.00/454 [00:00<?, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "bcd13ed2a83d49e98d4742a94975fd70",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "tokenizer.json:   0%|          | 0.00/17.2M [00:00<?, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "893171e0722e44acbf568ad057a7b1c9",
              "version_minor": 0.0,
              "version_major": 2.0
            },
            "text/plain": "chat_template.jinja: 0.00B [00:00, ?B/s]"
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Base model loaded!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. Load Fine-tuned Model (with LoRA adapters)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "# Load the FINE-TUNED model from LoRA checkpoint folder\n",
        "finetuned_model, finetuned_tokenizer = FastLanguageModel.from_pretrained(\n",
        "    model_name     = LORA_ADAPTER_PATH,    # <-- peka direkt p\u00e5 /vol/checkpoint-10688\n",
        "    max_seq_length = max_seq_length,\n",
        "    dtype          = dtype,\n",
        "    load_in_4bit   = load_in_4bit,\n",
        ")\n",
        "finetuned_tokenizer = get_chat_template(finetuned_tokenizer, chat_template=\"llama-3.1\")\n",
        "FastLanguageModel.for_inference(finetuned_model)\n",
        "print(\"Fine-tuned model loaded!\")\n"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==((====))==  Unsloth 2025.11.6: Fast Llama patching. Transformers: 4.56.0.\n",
            "   \\\\   /|    Tesla T4. Num GPUs = 3. Max memory: 14.563 GB. Platform: Linux.\n",
            "O^O/ \\_/ \\    Torch: 2.9.0+cu128. CUDA: 7.5. CUDA Toolkit: 12.8. Triton: 3.5.0\n",
            "\\        /    Bfloat16 = FALSE. FA [Xformers = 0.0.33.post1. FA2 = False]\n",
            " \"-____-\"     Free license: http://github.com/unslothai/unsloth\n",
            "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "Unsloth 2025.11.6 patched 28 layers with 28 QKV layers, 28 O layers and 28 MLP layers.\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Fine-tuned model loaded!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "prompt = [\n",
        "    {\"role\": \"user\", \"content\": \"Explain photosynthesis in one short paragraph.\"}\n",
        "]\n",
        "\n",
        "b = generate_response(base_model, base_tokenizer, prompt, deterministic=True)\n",
        "f = generate_response(finetuned_model, finetuned_tokenizer, prompt, deterministic=True)\n",
        "\n",
        "print(\"BASE:\\n\", b)\n",
        "print(\"\\nFINETUNED:\\n\", f)\n"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "BASE:\n",
            " Photosynthesis is the process by which plants, algae, and some bacteria convert light energy from the sun into chemical energy in the form of glucose. This process occurs in specialized organelles called chloroplasts, which contain the pigment chlorophyll. Water and carbon dioxide are absorbed by the plant, and with the energy from sunlight, they are converted into glucose and oxygen, releasing oxygen into the atmosphere as a byproduct.\n",
            "\n",
            "FINETUNED:\n",
            " Photosynthesis is the process by which plants, algae, and some bacteria convert sunlight, water, and carbon dioxide into glucose and oxygen. During photosynthesis, chlorophyll in the plant's cells absorbs sunlight, which is then used to convert carbon dioxide and water into glucose and oxygen. This process is essential for life on Earth, as it provides the energy and organic compounds needed for growth and sustenance.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. Evaluation Functions"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "from rouge_score import rouge_scorer\n",
        "\n",
        "def format_conversation_for_eval(example):\n",
        "    convos = example[\"conversations\"]\n",
        "\n",
        "    # referens = sista assistant-svaret\n",
        "    reference = None\n",
        "    for msg in reversed(convos):\n",
        "        if msg[\"role\"] == \"assistant\":\n",
        "            reference = msg[\"content\"]\n",
        "            break\n",
        "\n",
        "    if reference is None:\n",
        "        return [], None\n",
        "\n",
        "    # prompt = alla meddelanden f\u00f6re detta\n",
        "    cutoff_index = convos.index(next(m for m in convos if m[\"content\"] == reference))\n",
        "    prompt_messages = convos[:cutoff_index]\n",
        "\n",
        "    return prompt_messages, reference\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "def generate_response(model, tokenizer, messages, max_new_tokens=256, deterministic=True):\n",
        "    inputs = tokenizer.apply_chat_template(\n",
        "        messages,\n",
        "        tokenize=True,\n",
        "        add_generation_prompt=True,\n",
        "        return_tensors=\"pt\",\n",
        "    ).to(\"cuda\")\n",
        "\n",
        "    attention_mask = torch.ones_like(inputs)\n",
        "\n",
        "    gen_kwargs = {\n",
        "        \"input_ids\": inputs,\n",
        "        \"attention_mask\": attention_mask,\n",
        "        \"max_new_tokens\": max_new_tokens,\n",
        "        \"use_cache\": True,\n",
        "        \"pad_token_id\": tokenizer.eos_token_id,\n",
        "    }\n",
        "\n",
        "    if deterministic:\n",
        "        gen_kwargs.update(\n",
        "            dict(\n",
        "                do_sample=False,\n",
        "                temperature=None,\n",
        "            )\n",
        "        )\n",
        "    else:\n",
        "        gen_kwargs.update(\n",
        "            dict(\n",
        "                do_sample=True,\n",
        "                temperature=0.7,\n",
        "            )\n",
        "        )\n",
        "\n",
        "    with torch.no_grad():\n",
        "        outputs = model.generate(**gen_kwargs)\n",
        "\n",
        "    generated = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)\n",
        "    return generated.strip()\n",
        "\n",
        "\n",
        "\n",
        "def compute_rouge_scores(predictions, references):\n",
        "    \"\"\"Compute ROUGE scores\"\"\"\n",
        "    scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)\n",
        "    \n",
        "    scores = {'rouge1': [], 'rouge2': [], 'rougeL': []}\n",
        "    \n",
        "    for pred, ref in zip(predictions, references):\n",
        "        if ref and pred:\n",
        "            score = scorer.score(ref, pred)\n",
        "            scores['rouge1'].append(score['rouge1'].fmeasure)\n",
        "            scores['rouge2'].append(score['rouge2'].fmeasure)\n",
        "            scores['rougeL'].append(score['rougeL'].fmeasure)\n",
        "    \n",
        "    return {\n",
        "        'rouge1': np.mean(scores['rouge1']),\n",
        "        'rouge2': np.mean(scores['rouge2']),\n",
        "        'rougeL': np.mean(scores['rougeL']),\n",
        "    }\n",
        "\n",
        "print(\"Evaluation functions defined!\")"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Evaluation functions defined!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. Run Evaluation on Test Set\n",
        "\n",
        "We'll evaluate on a subset of the test set for speed (adjust `num_samples` as needed)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "# Number of samples to evaluate (more = better statistics, but slower)\n",
        "num_samples = 100  # Increase for more reliable results\n",
        "\n",
        "# Sample from test set\n",
        "eval_indices = np.random.RandomState(42).choice(len(test_dataset), min(num_samples, len(test_dataset)), replace=False)\n",
        "eval_samples = test_dataset.select(eval_indices)\n",
        "\n",
        "print(f\"Evaluating on {len(eval_samples)} samples...\")"
      ],
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Evaluating on 100 samples...\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "# Generate responses from both models\n",
        "base_predictions = []\n",
        "finetuned_predictions = []\n",
        "references = []\n",
        "prompts_used = []\n",
        "\n",
        "for i, example in enumerate(tqdm(eval_samples, desc=\"Generating responses\")):\n",
        "    prompt_messages, reference = format_conversation_for_eval(example)\n",
        "    \n",
        "    if reference is None or len(prompt_messages) == 0:\n",
        "        continue\n",
        "    \n",
        "    try:\n",
        "        base_response = generate_response(base_model, base_tokenizer, prompt_messages, deterministic=True)\n",
        "        finetuned_response = generate_response(finetuned_model, finetuned_tokenizer, prompt_messages, deterministic=True)\n",
        "\n",
        "        \n",
        "        base_predictions.append(base_response)\n",
        "        finetuned_predictions.append(finetuned_response)\n",
        "        references.append(reference)\n",
        "        prompts_used.append(prompt_messages)\n",
        "        \n",
        "    except Exception as e:\n",
        "        print(f\"Error on sample {i}: {e}\")\n",
        "        continue\n",
        "\n",
        "print(f\"Successfully evaluated {len(references)} samples\")"
      ],
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "\rGenerating responses:   0%|                                                            | 0/100 [00:00<?, ?it/s]\rGenerating responses:   1%|\u258c                                                   | 1/100 [00:16<26:46, 16.22s/it]\rGenerating responses:   2%|\u2588                                                   | 2/100 [00:42<36:10, 22.15s/it]\rGenerating responses:   3%|\u2588\u258c                                                  | 3/100 [01:08<38:59, 24.11s/it]\rGenerating responses:   4%|\u2588\u2588                                                  | 4/100 [01:35<40:10, 25.10s/it]\rGenerating responses:   5%|\u2588\u2588\u258c                                                 | 5/100 [01:56<37:17, 23.56s/it]\rGenerating responses:   6%|\u2588\u2588\u2588                                                 | 6/100 [02:22<38:28, 24.56s/it]\rGenerating responses:   7%|\u2588\u2588\u2588\u258b                                                | 7/100 [02:49<38:55, 25.12s/it]\rGenerating responses:   8%|\u2588\u2588\u2588\u2588\u258f                                               | 8/100 [03:15<39:08, 25.52s/it]\rGenerating responses:   9%|\u2588\u2588\u2588\u2588\u258b                                               | 9/100 [03:40<38:23, 25.31s/it]\rGenerating responses:  10%|\u2588\u2588\u2588\u2588\u2588                                              | 10/100 [04:05<37:39, 25.11s/it]\rGenerating responses:  11%|\u2588\u2588\u2588\u2588\u2588\u258c                                             | 11/100 [04:29<36:52, 24.86s/it]\rGenerating responses:  12%|\u2588\u2588\u2588\u2588\u2588\u2588                                             | 12/100 [04:43<31:32, 21.51s/it]\rGenerating responses:  13%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b                                            | 13/100 [05:09<33:29, 23.09s/it]\rGenerating responses:  14%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                                           | 14/100 [05:36<34:27, 24.04s/it]\rGenerating responses:  15%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                                           | 15/100 [06:02<35:04, 24.75s/it]\rGenerating responses:  16%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                                          | 16/100 [06:22<32:29, 23.21s/it]\rGenerating responses:  17%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                                          | 17/100 [06:48<33:31, 24.23s/it]\rGenerating responses:  18%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                                         | 18/100 [07:15<34:10, 25.00s/it]\rGenerating responses:  19%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                                         | 19/100 [07:42<34:27, 25.52s/it]\rGenerating responses:  20%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                                        | 20/100 [08:08<34:28, 25.85s/it]\rGenerating responses:  21%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                                        | 21/100 [08:21<28:50, 21.90s/it]\rGenerating responses:  22%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                                       | 22/100 [08:48<30:13, 23.25s/it]\rGenerating responses:  23%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                                       | 23/100 [09:14<31:05, 24.23s/it]\rGenerating responses:  24%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                                      | 24/100 [09:41<31:38, 24.99s/it]\rGenerating responses:  25%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                      | 25/100 [10:04<30:24, 24.32s/it]\rGenerating responses:  26%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e                                     | 26/100 [10:30<30:50, 25.00s/it]\rGenerating responses:  27%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                     | 27/100 [10:46<26:59, 22.18s/it]\rGenerating responses:  28%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e                                    | 28/100 [11:12<28:09, 23.47s/it]\rGenerating responses:  29%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                    | 29/100 [11:39<28:47, 24.34s/it]\rGenerating responses:  30%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e                                   | 30/100 [12:01<27:45, 23.79s/it]\rGenerating responses:  31%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                   | 31/100 [12:28<28:16, 24.58s/it]\rGenerating responses:  32%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e                                  | 32/100 [12:55<28:41, 25.31s/it]\rGenerating responses:  33%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                  | 33/100 [13:17<27:25, 24.56s/it]\rGenerating responses:  34%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e                                 | 34/100 [13:44<27:40, 25.16s/it]\rGenerating responses:  35%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                 | 35/100 [14:10<27:40, 25.55s/it]\rGenerating responses:  36%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e                                | 36/100 [14:37<27:36, 25.88s/it]\rGenerating responses:  37%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                                | 37/100 [15:04<27:35, 26.27s/it]\rGenerating responses:  38%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                               | 38/100 [15:30<27:08, 26.27s/it]\rGenerating responses:  39%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                               | 39/100 [15:48<24:05, 23.69s/it]\rGenerating responses:  40%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                              | 40/100 [16:14<24:18, 24.30s/it]\rGenerating responses:  41%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                              | 41/100 [16:38<23:46, 24.18s/it]\rGenerating responses:  42%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                             | 42/100 [16:58<22:11, 22.96s/it]\rGenerating responses:  43%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                             | 43/100 [17:19<21:23, 22.51s/it]\rGenerating responses:  44%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                            | 44/100 [17:34<18:48, 20.15s/it]\rGenerating responses:  45%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                            | 45/100 [18:00<19:59, 21.81s/it]\rGenerating responses:  46%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                           | 46/100 [18:25<20:39, 22.95s/it]\rGenerating responses:  47%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                           | 47/100 [18:44<19:01, 21.54s/it]\rGenerating responses:  48%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                          | 48/100 [18:46<13:38, 15.74s/it]\rGenerating responses:  49%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                          | 49/100 [19:11<15:55, 18.73s/it]\rGenerating responses:  50%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                         | 50/100 [19:32<15:58, 19.17s/it]\rGenerating responses:  51%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                         | 51/100 [19:58<17:20, 21.24s/it]\rGenerating responses:  52%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                        | 52/100 [20:16<16:15, 20.33s/it]\rGenerating responses:  53%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                        | 53/100 [20:36<15:46, 20.15s/it]\rGenerating responses:  54%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                       | 54/100 [21:01<16:41, 21.77s/it]\rGenerating responses:  55%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                       | 55/100 [21:17<14:58, 19.96s/it]\rGenerating responses:  56%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                      | 56/100 [21:35<14:14, 19.43s/it]\rGenerating responses:  57%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                      | 57/100 [22:00<15:01, 20.97s/it]\rGenerating responses:  58%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                     | 58/100 [22:19<14:25, 20.60s/it]\rGenerating responses:  59%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                     | 59/100 [22:45<15:10, 22.21s/it]\rGenerating responses:  60%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                    | 60/100 [23:12<15:45, 23.63s/it]\rGenerating responses:  61%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                    | 61/100 [23:29<13:59, 21.54s/it]\rGenerating responses:  62%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                   | 62/100 [23:56<14:40, 23.17s/it]\rGenerating responses:  63%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                  | 63/100 [24:22<14:48, 24.03s/it]\rGenerating responses:  64%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                  | 64/100 [24:40<13:21, 22.26s/it]\rGenerating responses:  65%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                 | 65/100 [25:06<13:34, 23.26s/it]\rGenerating responses:  66%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                 | 66/100 [25:29<13:15, 23.40s/it]\rGenerating responses:  67%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                | 67/100 [25:54<13:00, 23.64s/it]\rGenerating responses:  68%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b                | 68/100 [26:18<12:46, 23.95s/it]\rGenerating responses:  69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f               | 69/100 [26:38<11:46, 22.79s/it]\rGenerating responses:  70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b               | 70/100 [26:54<10:17, 20.57s/it]\rGenerating responses:  71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f              | 71/100 [27:17<10:17, 21.28s/it]\rGenerating responses:  72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b              | 72/100 [27:44<10:44, 23.00s/it]\rGenerating responses:  73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f             | 73/100 [28:13<11:07, 24.73s/it]\rGenerating responses:  74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b             | 74/100 [28:33<10:12, 23.55s/it]\rGenerating responses:  75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e            | 75/100 [28:51<09:02, 21.72s/it]\rGenerating responses:  76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a            | 76/100 [29:10<08:24, 21.01s/it]\rGenerating responses:  77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e           | 77/100 [29:26<07:27, 19.44s/it]\rGenerating responses:  78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a           | 78/100 [29:44<06:55, 18.90s/it]\rGenerating responses:  79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e          | 79/100 [29:56<05:55, 16.92s/it]\rGenerating responses:  80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a          | 80/100 [30:18<06:12, 18.63s/it]\rGenerating responses:  81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e         | 81/100 [30:33<05:32, 17.49s/it]\rGenerating responses:  82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a         | 82/100 [30:59<05:59, 19.95s/it]\rGenerating responses:  83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e        | 83/100 [31:25<06:08, 21.66s/it]\rGenerating responses:  84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a        | 84/100 [31:51<06:11, 23.22s/it]\rGenerating responses:  85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e       | 85/100 [32:18<06:02, 24.20s/it]\rGenerating responses:  86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a       | 86/100 [32:37<05:18, 22.72s/it]\rGenerating responses:  87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e      | 87/100 [33:02<05:03, 23.33s/it]\rGenerating responses:  88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589      | 88/100 [33:28<04:47, 23.99s/it]\rGenerating responses:  89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d     | 89/100 [33:50<04:18, 23.52s/it]\rGenerating responses:  90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589     | 90/100 [34:13<03:55, 23.51s/it]\rGenerating responses:  91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d    | 91/100 [34:32<03:17, 21.96s/it]\rGenerating responses:  92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589    | 92/100 [34:59<03:07, 23.41s/it]\rGenerating responses:  93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 93/100 [35:21<02:41, 23.09s/it]\rGenerating responses:  94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 94/100 [35:47<02:23, 23.85s/it]\rGenerating responses:  95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 95/100 [36:12<02:01, 24.27s/it]\rGenerating responses:  96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 96/100 [36:38<01:39, 24.75s/it]\rGenerating responses:  97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 97/100 [37:02<01:13, 24.58s/it]\rGenerating responses:  98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 98/100 [37:17<00:43, 21.64s/it]\rGenerating responses:  99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 99/100 [37:33<00:20, 20.18s/it]\rGenerating responses: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [37:54<00:00, 20.24s/it]\rGenerating responses: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [37:54<00:00, 22.74s/it]"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Successfully evaluated 100 samples\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6. Compute Metrics"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "# Calculate ROUGE scores\n",
        "base_rouge = compute_rouge_scores(base_predictions, references)\n",
        "finetuned_rouge = compute_rouge_scores(finetuned_predictions, references)\n",
        "\n",
        "print(\"=\" * 60)\n",
        "print(\"EVALUATION RESULTS\")\n",
        "print(\"=\" * 60)\n",
        "print(f\"Number of samples evaluated: {len(references)}\")\n",
        "print()\n",
        "print(\"-\" * 60)\n",
        "print(\"ROUGE Scores (higher is better)\")\n",
        "print(\"-\" * 60)\n",
        "print(f\"{'Metric':<15} {'Base Model':<20} {'Fine-tuned':<20} {'Change':<15}\")\n",
        "print(\"-\" * 60)\n",
        "\n",
        "for metric in ['rouge1', 'rouge2', 'rougeL']:\n",
        "    base_score = base_rouge[metric]\n",
        "    ft_score = finetuned_rouge[metric]\n",
        "    improvement = ((ft_score - base_score) / base_score) * 100 if base_score > 0 else 0\n",
        "    print(f\"{metric:<15} {base_score:<20.4f} {ft_score:<20.4f} {improvement:+.2f}%\")\n",
        "\n",
        "print(\"=\" * 60)"
      ],
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "============================================================\n",
            "EVALUATION RESULTS\n",
            "============================================================\n",
            "Number of samples evaluated: 100\n",
            "\n",
            "------------------------------------------------------------\n",
            "ROUGE Scores (higher is better)\n",
            "------------------------------------------------------------\n",
            "Metric          Base Model           Fine-tuned           Change         \n",
            "------------------------------------------------------------\n",
            "rouge1          0.4732               0.5323               +12.49%\n",
            "rouge2          0.2255               0.2849               +26.35%\n",
            "rougeL          0.2856               0.3521               +23.30%\n",
            "============================================================\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 7. Qualitative Comparison - Side by Side Examples"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "num_examples = 10\n",
        "\n",
        "for i in range(min(num_examples, len(references))):\n",
        "    print(\"=\" * 80)\n",
        "    print(f\"EXAMPLE {i+1}\")\n",
        "    print(\"=\" * 80)\n",
        "    \n",
        "    last_user_msg = None\n",
        "    for msg in prompts_used[i]:\n",
        "        if msg[\"role\"] == \"user\":\n",
        "            last_user_msg = msg[\"content\"]\n",
        "    \n",
        "    print(f\"USER PROMPT:\\n{last_user_msg[:500]}{'...' if len(str(last_user_msg)) > 500 else ''}\")\n",
        "    print(f\"\\nREFERENCE:\\n{references[i][:500]}{'...' if len(references[i]) > 500 else ''}\")\n",
        "    print(f\"\\nBASE MODEL:\\n{base_predictions[i][:500]}{'...' if len(base_predictions[i]) > 500 else ''}\")\n",
        "    print(f\"\\nFINE-TUNED MODEL:\\n{finetuned_predictions[i][:500]}{'...' if len(finetuned_predictions[i]) > 500 else ''}\")\n",
        "    print()"
      ],
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "================================================================================\n",
            "EXAMPLE 1\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "Explain the process of photosynthesis in simple terms and describe its importance for the ecosystem.\n",
            "\n",
            "REFERENCE:\n",
            "Photosynthesis is a process by which plants, algae, and some bacteria convert sunlight, water, and carbon dioxide into sugar and oxygen. This process occurs in the chloroplasts of these organisms. In simple terms, sunlight is absorbed, and its energy is used to break down water and carbon dioxide molecules, which are then reassembled into sugars and oxygen. The sugar provides energy for growth, while oxygen is released into the atmosphere. Photosynthesis is essential for the ecosystem because it...\n",
            "\n",
            "BASE MODEL:\n",
            "**What is Photosynthesis?**\n",
            "\n",
            "Photosynthesis is a process by which plants, algae, and some bacteria convert light energy from the sun into chemical energy in the form of glucose (a type of sugar). This process is essential for life on Earth, as it provides energy and organic compounds for plants to grow and thrive.\n",
            "\n",
            "**The Process of Photosynthesis:**\n",
            "\n",
            "1. **Light absorption**: Plants absorb light energy from the sun through specialized pigments such as chlorophyll.\n",
            "2. **Water absorption**: Plants ...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "Photosynthesis is a process used by plants, algae, and some bacteria to convert sunlight, water, and carbon dioxide into glucose and oxygen. In simple terms, plants use sunlight to make food (glucose) and release oxygen as a byproduct. This process is crucial for the ecosystem as it provides energy and organic compounds for plants to grow, which in turn supports the food chain and maintains the balance of the environment.\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 2\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "What is the mathematical foundation for adding or multiplying the same value to both sides of an equation, and why does it maintain the validity of the equation?\n",
            "\n",
            "REFERENCE:\n",
            "The principle of adding or multiplying the same value to both sides of an equation is a fundamental property of equality, known as the \"reflexive property of equality.\" This property states that if a number is equal to another number, then any operation performed on both sides of the equality will preserve that equality. \n",
            "\n",
            "For instance, consider the equation $x = 2$, where $x$ represents an unknown value. If we add 3 to both sides, we get $x + 3 = 2 + 3$, which simplifies to $x = 5$. The equalit...\n",
            "\n",
            "BASE MODEL:\n",
            "The mathematical foundation for adding or multiplying the same value to both sides of an equation lies in the properties of equality and the distributive property.\n",
            "\n",
            "**Equality Property:**\n",
            "\n",
            "The equality property states that if two expressions are equal, then any operation performed on both expressions will result in the same outcome. Mathematically, this can be expressed as:\n",
            "\n",
            "a = b \u21d4 (a + c) = (b + c)\n",
            "\n",
            "where a and b are the original expressions, and c is any value.\n",
            "\n",
            "**Distributive Property:**\n",
            "\n",
            "Th...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "The mathematical foundation for this operation lies in the properties of equality and the concept of equivalence classes. When you add or multiply the same value to both sides of an equation, you are essentially creating a new equation that is equivalent to the original one. This is because the operations you perform do not change the relationship between the variables in the equation.\n",
            "\n",
            "For example, consider the equation $x + 2 = 5$. If you add 3 to both sides of the equation, you get $x + 5 = 8...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 3\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "A pyramid has a rhombus-shaped base with sides of length 9 units and an angle of 120 degrees at one of its corners. The pyramid's height is 7 units. What is the surface area of the pyramid?\n",
            "\n",
            "REFERENCE:\n",
            "The base of the pyramid is a rhombus with sides of length 9 units and an angle of 120 degrees at one of its corners. The height of the pyramid is 7 units.\n",
            "\n",
            "To find the surface area of the pyramid, we need to find the area of the base and the area of each of the four triangular faces.\n",
            "\n",
            "The area of the base is given by the formula:\n",
            "\n",
            "Area of base = (1/2) * d1 * d2 * sin(theta)\n",
            "\n",
            "where d1 and d2 are the lengths of the diagonals of the rhombus and theta is the angle between the diagonals.\n",
            "\n",
            "Since the d...\n",
            "\n",
            "BASE MODEL:\n",
            "To find the surface area of the pyramid, we need to calculate the area of the base and the area of the four triangular faces, then add them together.\n",
            "\n",
            "The base of the pyramid is a rhombus with sides of length 9 units. Since the angle at one of its corners is 120 degrees, we can use trigonometry to find the length of the diagonals.\n",
            "\n",
            "The diagonals of a rhombus bisect each other at right angles, so we can use the Pythagorean theorem to find the length of the diagonals:\n",
            "\n",
            "Diagonal 1 = 2 * sin(60) * 9...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "The surface area of the pyramid is 173.5 square units.\n",
            "\n",
            "Explanation:\n",
            "To find the surface area of the pyramid, we need to calculate the area of the base (which is a rhombus) and the area of the four triangular faces.\n",
            "\n",
            "1. Area of the base (rhombus):\n",
            "The area of a rhombus can be found using the formula: Area = (1/2) * d1 * d2 * sin(\u03b8), where d1 and d2 are the lengths of the diagonals, and \u03b8 is the angle between them.\n",
            "\n",
            "Given that the sides of the rhombus are 9 units and the angle at one corner is 12...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 4\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "How do gravitational waves affect the curvature of spacetime and what is the mathematical expression that describes it?\n",
            "\n",
            "REFERENCE:\n",
            "Gravitational waves are ripples in the fabric of spacetime caused by the acceleration of massive objects, such as merging black holes or neutron stars. These waves propagate through spacetime at the speed of light, carrying energy and information about the events that generated them. They affect the curvature of spacetime by causing it to stretch and compress as the waves pass through.\n",
            "\n",
            "The mathematical expression that describes the effect of gravitational waves on the curvature of spacetime is ...\n",
            "\n",
            "BASE MODEL:\n",
            "Gravitational waves are ripples in the fabric of spacetime that are produced by the acceleration of massive objects, such as black holes or neutron stars. These waves cause a disturbance in the curvature of spacetime, which can be described using the Einstein field equations.\n",
            "\n",
            "The Einstein field equations describe the relationship between the curvature of spacetime (represented by the Ricci tensor, R\u03bc\u03bd) and the mass-energy density of the objects causing the curvature. The equations are:\n",
            "\n",
            "R\u03bc\u03bd - 1...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "Gravitational waves are ripples in the fabric of spacetime caused by the acceleration of massive objects, such as merging black holes or neutron stars. These waves propagate through spacetime at the speed of light and carry energy away from the source. The curvature of spacetime is affected by the presence of these waves, which causes a disturbance in the geometry of spacetime.\n",
            "\n",
            "The mathematical expression that describes the curvature of spacetime due to gravitational waves is given by the Einst...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 5\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "Write Python code to solve the task:\n",
            "We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.\n",
            "\n",
            "For example, `greenbin` is an anagram of `beginner`. As seen here, when the same character occurs multiple times, that character must be used that number of times.\n",
            "\n",
            "Given are N strings s_1, s_2, \\ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Fin...\n",
            "\n",
            "REFERENCE:\n",
            "Step 1:  We need to find the number of pairs of strings that are anagrams of each other.\n",
            "Step 2:  We can start by creating a function to check if two strings are anagrams.\n",
            "Step 3:  Then we can create a loop to compare each string with every other string in the list.\n",
            "Step 4:  We should also consider the number of pairs we need to check and how we can reduce this number by half since the problem is symmetrical.\n",
            "Step 5:  We should also utilize a dictionary to count the frequency of each character a...\n",
            "\n",
            "BASE MODEL:\n",
            "def count_anagrams(N, strings):\n",
            "    anagrams = {}\n",
            "    for s in strings:\n",
            "        sorted_s = ''.join(sorted(s))\n",
            "        if sorted_s in anagrams:\n",
            "            anagrams[sorted_s].append(s)\n",
            "        else:\n",
            "            anagrams[sorted_s] = [s]\n",
            "    count = 0\n",
            "    for v in anagrams.values():\n",
            "        count += len(v) * (len(v) - 1) // 2\n",
            "    return count\n",
            "\n",
            "N = int(input())\n",
            "strings = [input() for _ in range(N)]\n",
            "print(count_anagrams(N, strings))\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "Step 1:  The problem requires us to find the number of pairs of integers i, j (1 \u2264 i < j \u2264 N) such that s_i is an anagram of s_j.\n",
            "Step 2:  We can start by creating a function to check if two strings are anagrams of each other.\n",
            "Step 3:  Then, we can iterate through the input strings and count the number of pairs that satisfy the condition.\n",
            "Step 4:  We also need to consider the constraints and the input format.\n",
            "Step 5:  We can use a dictionary to store the count of each string and then calculate t...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 6\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "Write a short story about a computer that can predict the future.\n",
            "\n",
            "REFERENCE:\n",
            "Once upon a time, there was a computer named Oracle. Oracle was no ordinary computer \u2013 it had the unique ability to predict the future. It was the invention of a brilliant computer scientist, who had spent years creating and perfecting its software. The scientist had a vision to make the world a better place by preventing misfortunes and tragedies before they occurred.\n",
            "\n",
            "At first, people were skeptical of Oracle's abilities. But soon, the computer proved its worth. It predicted natural disasters ...\n",
            "\n",
            "BASE MODEL:\n",
            "**The Oracle of Code**\n",
            "\n",
            "In a small, cluttered laboratory, a team of brilliant engineers had been working on a top-secret project for years. Their goal was to create a computer that could predict the future. The team had tried countless approaches, from complex algorithms to advanced machine learning techniques, but nothing seemed to yield the desired results.\n",
            "\n",
            "That was until they stumbled upon an unusual approach. Instead of focusing on predicting specific events, they decided to create a comput...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "Once upon a time, in a small town nestled in the heart of a dense forest, there was a computer that possessed a unique gift. It could predict the future.\n",
            "\n",
            "The computer, named \"Chrono,\" was created by a brilliant scientist who had spent years studying the mysteries of time. He had designed Chrono to be able to analyze vast amounts of data and make predictions based on that analysis.\n",
            "\n",
            "At first, Chrono's predictions were nothing more than guesses. But as time went on, the computer's accuracy began ...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 7\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "What measures can we implement to reduce the negative impact of frequent air travel on the environment, particularly in relation to carbon emissions, atmospheric pollution, and depletion of natural resources? How can we maintain the benefits and convenience of air travel while also ensuring its sustainability in the long term? Additionally, how can we consider the impact of air travel on global temperature, biodiversity loss, and social equity when developing sustainable air travel practices?\n",
            "\n",
            "REFERENCE:\n",
            "There are several measures that can be implemented to reduce the negative impact of frequent air travel on the environment:\n",
            "1. Promote the use of alternative modes of transportation, such as trains and buses, for shorter distances.\n",
            "2. Encourage the use of more fuel-efficient aircraft and engines, as well as the use of alternative fuels like biofuels.\n",
            "3. Implement carbon offsetting programs, where airlines invest in projects that reduce carbon emissions, such as renewable energy or reforestation....\n",
            "\n",
            "BASE MODEL:\n",
            "To reduce the negative impact of frequent air travel on the environment, several measures can be implemented:\n",
            "\n",
            "1. **Carbon offsetting**: Calculate and offset carbon emissions from flights by investing in projects that reduce greenhouse gas emissions, such as reforestation or renewable energy projects.\n",
            "2. **Fuel efficiency**: Improve aircraft fuel efficiency through more efficient engines, aerodynamic designs, and alternative fuels, such as biofuels or electric propulsion.\n",
            "3. **Sustainable aviati...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "There are several measures that can be implemented to reduce the negative impact of frequent air travel on the environment. Here are some of them:\n",
            "1. Carbon offsetting: This involves investing in projects that reduce greenhouse gas emissions, such as reforestation or renewable energy projects. Airlines can offer carbon offsetting options to passengers, and passengers can choose to offset their carbon emissions from flights.\n",
            "2. Fuel efficiency: Airlines can improve fuel efficiency by using more e...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 8\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "How does the Earth's structure impact our lives and the environment?\n",
            "\n",
            "REFERENCE:\n",
            "The Earth's structure plays a vital role in supporting life and influencing various natural phenomena. Here are three key ways in which the Earth's interior affects us:\n",
            "\n",
            "1) The Earth's large metallic core generates a strong magnetic field, which serves as a shield against harmful solar radiation and high-energy particles. This protection is crucial for the survival of living organisms on the planet.\n",
            "\n",
            "2) The core's heat, resulting from radioactive decay, drives convection currents in the mantle. ...\n",
            "\n",
            "BASE MODEL:\n",
            "The Earth's structure has a profound impact on our lives and the environment. Here are some ways in which the Earth's structure affects us:\n",
            "\n",
            "1. **Climate and Weather Patterns**: The Earth's structure, including its rotation, orbit, and atmospheric circulation, influences the climate and weather patterns. This, in turn, affects the distribution of heat, moisture, and precipitation around the globe, impacting agriculture, water resources, and human settlements.\n",
            "2. **Geological Activity**: The Eart...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "The Earth's structure plays a significant role in shaping our lives and the environment. Here are some ways in which it impacts us:\n",
            "\n",
            "1. Climate: The Earth's structure, including its atmosphere, oceans, and landmasses, determines the climate we experience. The atmosphere traps heat, which in turn affects the temperature of the Earth's surface. The oceans and landmasses also play a role in regulating the climate.\n",
            "\n",
            "2. Natural Resources: The Earth's structure is responsible for the availability of n...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 9\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "There are 20 hands in Peter\u2019s class, not including his. Assume every student in the class has 2 arms and x hands. There are 11 students in Peter's class including him. What is the value of unknown variable x? What is the value of unknown variable x?\n",
            "\n",
            "REFERENCE:\n",
            "To solve this problem, we need to determine the value of x, which represents the number of hands each student in Peter's class has.\n",
            "We know that there are 11 students in Peter's class, including him. Therefore, there are 11 - 1 = 10 other students in the class.\n",
            "We also know that each student has 2 arms, which means they have 2 hands each.\n",
            "So, the total number of hands in the class, not including Peter's, is 10 students * 2 hands per student = 20 hands.\n",
            "Since each student has x hands, we can set ...\n",
            "\n",
            "BASE MODEL:\n",
            "To find the value of x, we need to know the total number of hands in the class. Since there are 20 hands not including Peter's, and Peter also has hands, we need to add Peter's hands to the total.\n",
            "\n",
            "There are 11 students in the class, including Peter. Since every student has 2 arms and x hands, the total number of hands in the class is:\n",
            "\n",
            "11 students * 2 arms/student * x hands/arm = 22x hands\n",
            "\n",
            "However, we know that there are 20 hands not including Peter's. Since Peter also has hands, we can set up...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "1. The problem states that there are 20 hands in Peter's class, not including his. This means that the total number of hands in the class, including Peter's, is 20 + 1 = 21.\n",
            "2. The problem also states that every student in the class has 2 arms and x hands. This means that the total number of hands in the class, including Peter's, is 2 * (number of students) + x * (number of students).\n",
            "3. We know that there are 11 students in Peter's class, including him. This means that the total number of hands...\n",
            "\n",
            "================================================================================\n",
            "EXAMPLE 10\n",
            "================================================================================\n",
            "USER PROMPT:\n",
            "Solve the following math problem step-by-step.\n",
            "Simplify your answer as much as possible. Present your final answer as \\boxed{Your Answer}.\n",
            "A coin is flipped eight times, and the sequence of heads and tails occurring is recorded. How many distinct sequences are possible?\n",
            "\n",
            "REFERENCE:\n",
            "Step 1: To calculate the number of distinct sequences possible, we need to determine the number of options for each flip of the coin and multiply them together.\n",
            "Step 2: Since there are two possible outcomes for each flip (heads or tails), there are 2 options for each flip.\n",
            "Step 3: Since there are 8 flips in total, we need to multiply the number of options for each flip together to find the total number of distinct sequences.\n",
            "Step 4: So, the solution is 2^8 = 256 distinct sequences.\n",
            "\n",
            "Answer:\n",
            "\\box...\n",
            "\n",
            "BASE MODEL:\n",
            "To solve this problem, we need to consider the number of possible outcomes for each coin flip. Since a coin can land either heads or tails, there are 2 possible outcomes for each flip.\n",
            "\n",
            "Since the coin is flipped 8 times, we need to multiply the number of possible outcomes for each flip together to get the total number of distinct sequences.\n",
            "\n",
            "Here's the step-by-step calculation:\n",
            "\n",
            "1. Number of possible outcomes for the first flip: 2\n",
            "2. Number of possible outcomes for the second flip: 2\n",
            "3. Number o...\n",
            "\n",
            "FINE-TUNED MODEL:\n",
            "Step 1:  To solve this problem, we need to understand the concept of permutations and how it applies to the given scenario.\n",
            "Step 2:  The coin is flipped eight times, and the sequence of heads and tails occurring is recorded. This means that for each flip, there are two possible outcomes - heads or tails.\n",
            "Step 3:  Since the coin is flipped eight times, we have a total of 8 flips, and each flip has 2 possible outcomes. This leads us to the total number of distinct sequences possible.\n",
            "Step 4:  The ...\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 8. Response Length Analysis"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "base_lengths = [len(p.split()) for p in base_predictions]\n",
        "ft_lengths = [len(p.split()) for p in finetuned_predictions]\n",
        "ref_lengths = [len(r.split()) for r in references]\n",
        "\n",
        "print(\"Response Length Analysis (words)\")\n",
        "print(\"-\" * 50)\n",
        "print(f\"{'Metric':<25} {'Base':<12} {'Fine-tuned':<12} {'Reference':<12}\")\n",
        "print(\"-\" * 50)\n",
        "print(f\"{'Mean length':<25} {np.mean(base_lengths):<12.1f} {np.mean(ft_lengths):<12.1f} {np.mean(ref_lengths):<12.1f}\")\n",
        "print(f\"{'Median length':<25} {np.median(base_lengths):<12.1f} {np.median(ft_lengths):<12.1f} {np.median(ref_lengths):<12.1f}\")\n",
        "print(f\"{'Std deviation':<25} {np.std(base_lengths):<12.1f} {np.std(ft_lengths):<12.1f} {np.std(ref_lengths):<12.1f}\")"
      ],
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Response Length Analysis (words)\n",
            "--------------------------------------------------\n",
            "Metric                    Base         Fine-tuned   Reference   \n",
            "--------------------------------------------------\n",
            "Mean length               165.0        155.7        216.3       \n",
            "Median length             176.0        165.5        199.0       \n",
            "Std deviation             42.5         53.6         109.4       \n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 9. Save Results"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "collapsed": false,
        "scrolled": true
      },
      "source": [
        "import json\n",
        "from datetime import datetime\n",
        "\n",
        "results = {\n",
        "    \"timestamp\": datetime.now().isoformat(),\n",
        "    \"base_model\": BASE_MODEL_NAME,\n",
        "    \"finetuned_model\": LORA_ADAPTER_PATH,\n",
        "    \"num_samples\": len(references),\n",
        "    \"metrics\": {\n",
        "        \"base_model\": base_rouge,\n",
        "        \"finetuned_model\": finetuned_rouge,\n",
        "    },\n",
        "    \"response_lengths\": {\n",
        "        \"base_mean\": float(np.mean(base_lengths)),\n",
        "        \"finetuned_mean\": float(np.mean(ft_lengths)),\n",
        "        \"reference_mean\": float(np.mean(ref_lengths)),\n",
        "    }\n",
        "}\n",
        "\n",
        "with open(\"evaluation_results.json\", \"w\") as f:\n",
        "    json.dump(results, f, indent=2)\n",
        "\n",
        "print(\"Results saved to evaluation_results.json\")\n",
        "print(json.dumps(results, indent=2))"
      ],
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Results saved to evaluation_results.json\n",
            "{\n",
            "  \"timestamp\": \"2025-12-02T10:09:18.235153\",\n",
            "  \"base_model\": \"unsloth/Llama-3.2-3B-Instruct\",\n",
            "  \"finetuned_model\": \"/vol/checkpoint-10688\",\n",
            "  \"num_samples\": 100,\n",
            "  \"metrics\": {\n",
            "    \"base_model\": {\n",
            "      \"rouge1\": 0.4732268736349978,\n",
            "      \"rouge2\": 0.22545052802537063,\n",
            "      \"rougeL\": 0.2855963588727634\n",
            "    },\n",
            "    \"finetuned_model\": {\n",
            "      \"rouge1\": 0.5323317587648463,\n",
            "      \"rouge2\": 0.28485583536195763,\n",
            "      \"rougeL\": 0.35213159677059536\n",
            "    }\n",
            "  },\n",
            "  \"response_lengths\": {\n",
            "    \"base_mean\": 165.0,\n",
            "    \"finetuned_mean\": 155.68,\n",
            "    \"reference_mean\": 216.27\n",
            "  }\n",
            "}\n"
          ]
        }
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python",
      "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"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}