Jeppcode commited on
Commit
dfbf500
·
verified ·
1 Parent(s): 39883de

Upload 4 files

Browse files
Files changed (4) hide show
  1. ModelToGGUFCleaned.ipynb +0 -0
  2. ReadMe.md +133 -0
  3. evaluatemodels.ipynb +1097 -0
  4. lab2-scalable.ipynb +919 -0
ModelToGGUFCleaned.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
ReadMe.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 2 - Fine-Tuning a Large Language Model
2
+
3
+ ## Overview
4
+
5
+ In this lab we fine-tuned the open-source base model `unsloth/Llama-3.2-3B-Instruct` on Maxime Labonne's FineTome-100k instruction dataset using LoRA (Low-Rank Adaptation) with QLoRA quantization via Unsloth and `trl.SFTTrainer`. The training used the following hyperparameters:
6
+
7
+ | Hyperparameter | Value |
8
+ |----------------|-------|
9
+ | `per_device_train_batch_size` | 2 |
10
+ | `gradient_accumulation_steps` | 4 |
11
+ | `num_train_epochs` | 1 |
12
+ | `learning_rate` | 2e-4 |
13
+ | `warmup_steps` | 5 |
14
+ | `weight_decay` | 0.01 |
15
+ | `optimizer` | adamw_8bit |
16
+
17
+ ---
18
+
19
+ ## Evaluation Methodology
20
+
21
+ We evaluated both the base model and the fine-tuned model on **100 held-out examples** from a 15% test split of FineTome-100k. For each example we used the conversation history as input and treated the last assistant turn as the reference answer.
22
+
23
+ ### Metrics Used
24
+
25
+ We used **ROUGE scores** (Recall-Oriented Understudy for Gisting Evaluation) to measure the overlap between model-generated responses and reference answers:
26
+
27
+ - **ROUGE-1**: Measures unigram (single word) overlap between the generated text and reference. Higher scores indicate better word-level similarity.
28
+ - **ROUGE-2**: Measures bigram (two consecutive words) overlap. This captures phrase-level similarity and is more sensitive to word order.
29
+ - **ROUGE-L**: Measures the longest common subsequence between generated and reference text. This captures sentence-level structure and fluency.
30
+
31
+ All scores use the F-measure (harmonic mean of precision and recall) and range from 0 to 1, where higher is better.
32
+
33
+ ### Generation Settings
34
+
35
+ We used **deterministic generation** (greedy decoding with `do_sample=False`) for both models to ensure reproducible and comparable results. Each response was limited to 256 new tokens.
36
+
37
+ ---
38
+
39
+ ## Results
40
+
41
+ The fine-tuned model clearly outperformed the base model across all ROUGE metrics:
42
+
43
+ | Metric | Base Model | Fine-Tuned Model | Improvement |
44
+ |--------|------------|------------------|-------------|
45
+ | ROUGE-1 | 0.4732 | 0.5323 | **+12.5%** |
46
+ | ROUGE-2 | 0.2255 | 0.2849 | **+26.4%** |
47
+ | ROUGE-L | 0.2856 | 0.3521 | **+23.3%** |
48
+
49
+ These results demonstrate that even a single epoch of LoRA fine-tuning on FineTome-100k produces substantial improvements in response quality. The largest gain was in ROUGE-2 (+26.4%), indicating that the fine-tuned model better captures phrase-level patterns from the training data.
50
+
51
+ ### Response Length Analysis
52
+
53
+ | Metric | Base Model | Fine-Tuned Model | Reference |
54
+ |--------|------------|------------------|-----------|
55
+ | Mean length (words) | 165.0 | 155.7 | 216.3 |
56
+ | Median length (words) | 176.0 | 165.5 | 199.0 |
57
+
58
+ The fine-tuned model produces slightly more concise responses while achieving higher ROUGE scores, suggesting improved information density.
59
+
60
+ ---
61
+
62
+ ## Improving Model Performance
63
+
64
+ ### (a) Model-Centric Approach
65
+
66
+ A model-centric approach keeps the data fixed and focuses on changing the model architecture, training configuration, or optimization procedure. Below are concrete strategies for further improvement:
67
+
68
+ #### Hyperparameter Tuning
69
+
70
+ - **Learning rate**: Sweep over values such as `1e-4`, `2e-4`, `5e-4` to find the optimal learning rate. Our current setting of `2e-4` is a reasonable default but may not be optimal.
71
+ - **Learning rate schedule**: Experiment with cosine decay or cosine with warm restarts instead of constant learning rate.
72
+ - **Training epochs**: Train for 2–3 epochs with early stopping based on validation loss to potentially improve convergence.
73
+ - **Batch size**: Increase effective batch size (via `gradient_accumulation_steps`) within memory constraints for more stable gradients.
74
+ - **Warmup steps**: Adjust warmup duration (e.g., 10–100 steps) to improve training stability.
75
+ - **Weight decay**: Test different regularization strengths (e.g., `0.001`, `0.01`, `0.1`) to control overfitting.
76
+
77
+ #### LoRA Configuration
78
+
79
+ - **Rank (r)**: Increase LoRA rank (e.g., from 16 to 32 or 64) to allow more expressive adapter updates, at the cost of increased memory.
80
+ - **Alpha scaling**: Adjust the LoRA alpha parameter to control the magnitude of adapter contributions.
81
+ - **Target modules**: Experiment with applying LoRA to different layer types (attention only, MLP layers, or both) and different layer ranges.
82
+
83
+ #### Model Architecture
84
+
85
+ - **Base model selection**: Compare different foundation models such as `Llama-3.2-1B-Instruct` (faster inference) or `Llama-3.1-8B-Instruct` (potentially higher quality but slower).
86
+ - **Quantization**: Compare 4-bit (QLoRA) vs 8-bit quantization to understand the quality-speed tradeoff.
87
+
88
+ #### Training Procedure
89
+
90
+ - **Gradient clipping**: Add gradient clipping to prevent exploding gradients and improve training stability.
91
+ - **Mixed precision**: Ensure optimal use of mixed precision training for faster iteration.
92
+
93
+ ### (b) Data-Centric Approach
94
+
95
+ A data-centric approach keeps the model and training loop mostly fixed and focuses on improving or extending the training data. Below are concrete strategies:
96
+
97
+ #### Data Quality Improvements
98
+
99
+ - **Filter low-quality examples**: Remove very short, unclear, or noisy instruction-response pairs from FineTome-100k to increase average signal per batch.
100
+ - **Deduplicate**: Remove near-duplicate examples that may cause the model to overfit to specific patterns.
101
+ - **Balance task types**: If the target application focuses on specific capabilities (e.g., reasoning, coding, explanation), up-sample those categories and down-sample less relevant ones.
102
+
103
+ #### Additional Data Sources
104
+
105
+ Augment FineTome-100k with other high-quality open-source instruction datasets:
106
+
107
+ | Dataset | Focus Area | Potential Benefit |
108
+ |---------|------------|-------------------|
109
+ | OpenAssistant Conversations | Multi-turn dialogue | Improved conversational ability |
110
+ | GSM8K / MetaMath | Math reasoning | Better mathematical problem-solving |
111
+ | CodeAlpaca / Code-Feedback | Programming tasks | Improved code generation |
112
+ | FLAN Collection | Diverse NLP tasks | Broader task coverage |
113
+ | UltraChat | Long-form dialogue | Better handling of extended conversations |
114
+
115
+ #### Domain-Specific Fine-Tuning
116
+
117
+ - **Curriculum learning**: Start training on general instructions, then gradually shift to more specialized or difficult examples.
118
+ - **Task-specific adapters**: Train separate LoRA adapters for different domains (math, code, creative writing) and select the appropriate adapter at inference time.
119
+
120
+ #### Data Alignment
121
+
122
+ - **Match UI format**: If the final application expects specific output formats (e.g., step-by-step reasoning, JSON responses), construct or filter training examples that demonstrate these formats.
123
+ - **User feedback loop**: In production, log anonymized user interactions (if permitted) to create a fine-tuning set that reflects real usage patterns.
124
+
125
+ ---
126
+
127
+ ## Conclusion
128
+
129
+ Our fine-tuning pipeline demonstrates measurable improvements over the base model, with ROUGE scores increasing by 12–26% on a held-out test set. The model-centric and data-centric strategies outlined above provide clear directions for further performance gains. The most promising next steps would be:
130
+
131
+ 1. **Hyperparameter sweep** on learning rate and number of epochs
132
+ 2. **Increase LoRA rank** to allow more expressive updates
133
+ 3. **Mix in domain-specific datasets** (e.g., math reasoning or code) to improve performance on specialized tasks
evaluatemodels.ipynb ADDED
@@ -0,0 +1,1097 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Model Evaluation: Fine-tuned vs Base Model Comparison\n",
8
+ "\n",
9
+ "This notebook compares the fine-tuned model against the original `unsloth/Llama-3.2-3B-Instruct` using:\n",
10
+ "1. **ROUGE scores** comparing generated responses to ground truth\n",
11
+ "2. **Qualitative examples** - side-by-side comparisons\n",
12
+ "3. **Response length analysis**"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "metadata": {
18
+ "collapsed": false,
19
+ "scrolled": true
20
+ },
21
+ "source": [
22
+ "%%capture\n",
23
+ "# Install dependencies\n",
24
+ "%uv pip install unsloth\n",
25
+ "%uv pip install rouge-score evaluate datasets tqdm"
26
+ ],
27
+ "execution_count": 1,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {
33
+ "collapsed": false,
34
+ "scrolled": true
35
+ },
36
+ "source": [
37
+ "from unsloth import FastLanguageModel\n",
38
+ "from unsloth.chat_templates import get_chat_template, standardize_sharegpt\n",
39
+ "import torch\n",
40
+ "import numpy as np\n",
41
+ "from tqdm import tqdm\n",
42
+ "from datasets import load_dataset\n",
43
+ "\n",
44
+ "# Configuration\n",
45
+ "max_seq_length = 2048\n",
46
+ "dtype = \"float16\"\n",
47
+ "load_in_4bit = True\n",
48
+ "\n",
49
+ "BASE_MODEL_NAME = \"unsloth/Llama-3.2-3B-Instruct\"\n",
50
+ "LORA_ADAPTER_PATH = \"/vol/checkpoint-10688\" # your local folder in Modal\n"
51
+ ],
52
+ "execution_count": 2,
53
+ "outputs": [
54
+ {
55
+ "output_type": "stream",
56
+ "name": "stdout",
57
+ "text": [
58
+ "\ud83e\udda5 Unsloth: Will patch your computer to enable 2x faster free finetuning.\n",
59
+ "\ud83e\udda5 Unsloth Zoo will now patch everything to make training faster!\n"
60
+ ]
61
+ }
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "markdown",
66
+ "metadata": {},
67
+ "source": [
68
+ "## 1. Prepare the Test Dataset\n",
69
+ "\n",
70
+ "Using the same splits as during training (10% test set)"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {
76
+ "collapsed": false,
77
+ "scrolled": true
78
+ },
79
+ "source": [
80
+ "# Load and prepare dataset (same as training)\n",
81
+ "dataset = load_dataset(\"mlabonne/FineTome-100k\", split=\"train\")\n",
82
+ "dataset = standardize_sharegpt(dataset)\n",
83
+ "\n",
84
+ "# Same splits as training: train+val (90%), test (10%)\n",
85
+ "train_val_split = dataset.train_test_split(test_size=0.15, seed=42)\n",
86
+ "test_dataset = train_val_split[\"test\"]\n",
87
+ "\n",
88
+ "print(f\"Test set size: {len(test_dataset)} samples\")"
89
+ ],
90
+ "execution_count": 3,
91
+ "outputs": [
92
+ {
93
+ "output_type": "display_data",
94
+ "data": {
95
+ "application/vnd.jupyter.widget-view+json": {
96
+ "model_id": "e56d65e8c6ec4db0b7c61258c77a9bd2",
97
+ "version_minor": 0.0,
98
+ "version_major": 2.0
99
+ },
100
+ "text/plain": "README.md: 0%| | 0.00/982 [00:00<?, ?B/s]"
101
+ },
102
+ "metadata": {}
103
+ },
104
+ {
105
+ "output_type": "display_data",
106
+ "data": {
107
+ "application/vnd.jupyter.widget-view+json": {
108
+ "model_id": "b3e8721d30df4d33a06e31865c6bb0fc",
109
+ "version_minor": 0.0,
110
+ "version_major": 2.0
111
+ },
112
+ "text/plain": "data/train-00000-of-00001.parquet: 0%| | 0.00/117M [00:00<?, ?B/s]"
113
+ },
114
+ "metadata": {}
115
+ },
116
+ {
117
+ "output_type": "display_data",
118
+ "data": {
119
+ "application/vnd.jupyter.widget-view+json": {
120
+ "model_id": "a6e0b28225b94469adcb2e6a58ae000d",
121
+ "version_minor": 0.0,
122
+ "version_major": 2.0
123
+ },
124
+ "text/plain": "Generating train split: 0%| | 0/100000 [00:00<?, ? examples/s]"
125
+ },
126
+ "metadata": {}
127
+ },
128
+ {
129
+ "output_type": "display_data",
130
+ "data": {
131
+ "application/vnd.jupyter.widget-view+json": {
132
+ "model_id": "7312c3a59534419993d6458816a64416",
133
+ "version_minor": 0.0,
134
+ "version_major": 2.0
135
+ },
136
+ "text/plain": "Unsloth: Standardizing formats (num_proc=14): 0%| | 0/100000 [00:00<?, ? examples/s]"
137
+ },
138
+ "metadata": {}
139
+ },
140
+ {
141
+ "output_type": "stream",
142
+ "name": "stdout",
143
+ "text": [
144
+ "Test set size: 15000 samples\n"
145
+ ]
146
+ }
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "markdown",
151
+ "metadata": {},
152
+ "source": [
153
+ "## 2. Load Base Model"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {
159
+ "collapsed": false,
160
+ "scrolled": true
161
+ },
162
+ "source": [
163
+ "# Load the BASE model (not fine-tuned)\n",
164
+ "base_model, base_tokenizer = FastLanguageModel.from_pretrained(\n",
165
+ " model_name = BASE_MODEL_NAME,\n",
166
+ " max_seq_length = max_seq_length,\n",
167
+ " dtype = dtype,\n",
168
+ " load_in_4bit = load_in_4bit,\n",
169
+ ")\n",
170
+ "base_tokenizer = get_chat_template(base_tokenizer, chat_template=\"llama-3.1\")\n",
171
+ "FastLanguageModel.for_inference(base_model)\n",
172
+ "print(\"Base model loaded!\")"
173
+ ],
174
+ "execution_count": 4,
175
+ "outputs": [
176
+ {
177
+ "output_type": "stream",
178
+ "name": "stdout",
179
+ "text": [
180
+ "==((====))== Unsloth 2025.11.6: Fast Llama patching. Transformers: 4.56.0.\n",
181
+ " \\\\ /| Tesla T4. Num GPUs = 3. Max memory: 14.563 GB. Platform: Linux.\n",
182
+ "O^O/ \\_/ \\ Torch: 2.9.0+cu128. CUDA: 7.5. CUDA Toolkit: 12.8. Triton: 3.5.0\n",
183
+ "\\ / Bfloat16 = FALSE. FA [Xformers = 0.0.33.post1. FA2 = False]\n",
184
+ " \"-____-\" Free license: http://github.com/unslothai/unsloth\n",
185
+ "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n"
186
+ ]
187
+ },
188
+ {
189
+ "output_type": "display_data",
190
+ "data": {
191
+ "application/vnd.jupyter.widget-view+json": {
192
+ "model_id": "d388e30418ae4375ac5730e0c10c036d",
193
+ "version_minor": 0.0,
194
+ "version_major": 2.0
195
+ },
196
+ "text/plain": "model.safetensors: 0%| | 0.00/2.35G [00:00<?, ?B/s]"
197
+ },
198
+ "metadata": {}
199
+ },
200
+ {
201
+ "output_type": "display_data",
202
+ "data": {
203
+ "application/vnd.jupyter.widget-view+json": {
204
+ "model_id": "feb44d05734b494a8d7e793831499231",
205
+ "version_minor": 0.0,
206
+ "version_major": 2.0
207
+ },
208
+ "text/plain": "generation_config.json: 0%| | 0.00/234 [00:00<?, ?B/s]"
209
+ },
210
+ "metadata": {}
211
+ },
212
+ {
213
+ "output_type": "display_data",
214
+ "data": {
215
+ "application/vnd.jupyter.widget-view+json": {
216
+ "model_id": "bd4febb360a143f5b7bca061da96e65e",
217
+ "version_minor": 0.0,
218
+ "version_major": 2.0
219
+ },
220
+ "text/plain": "tokenizer_config.json: 0.00B [00:00, ?B/s]"
221
+ },
222
+ "metadata": {}
223
+ },
224
+ {
225
+ "output_type": "display_data",
226
+ "data": {
227
+ "application/vnd.jupyter.widget-view+json": {
228
+ "model_id": "ce6dddafbc5042cba3be648d738725c5",
229
+ "version_minor": 0.0,
230
+ "version_major": 2.0
231
+ },
232
+ "text/plain": "special_tokens_map.json: 0%| | 0.00/454 [00:00<?, ?B/s]"
233
+ },
234
+ "metadata": {}
235
+ },
236
+ {
237
+ "output_type": "display_data",
238
+ "data": {
239
+ "application/vnd.jupyter.widget-view+json": {
240
+ "model_id": "bcd13ed2a83d49e98d4742a94975fd70",
241
+ "version_minor": 0.0,
242
+ "version_major": 2.0
243
+ },
244
+ "text/plain": "tokenizer.json: 0%| | 0.00/17.2M [00:00<?, ?B/s]"
245
+ },
246
+ "metadata": {}
247
+ },
248
+ {
249
+ "output_type": "display_data",
250
+ "data": {
251
+ "application/vnd.jupyter.widget-view+json": {
252
+ "model_id": "893171e0722e44acbf568ad057a7b1c9",
253
+ "version_minor": 0.0,
254
+ "version_major": 2.0
255
+ },
256
+ "text/plain": "chat_template.jinja: 0.00B [00:00, ?B/s]"
257
+ },
258
+ "metadata": {}
259
+ },
260
+ {
261
+ "output_type": "stream",
262
+ "name": "stdout",
263
+ "text": [
264
+ "Base model loaded!\n"
265
+ ]
266
+ }
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "markdown",
271
+ "metadata": {},
272
+ "source": [
273
+ "## 3. Load Fine-tuned Model (with LoRA adapters)"
274
+ ]
275
+ },
276
+ {
277
+ "cell_type": "code",
278
+ "metadata": {
279
+ "collapsed": false,
280
+ "scrolled": true
281
+ },
282
+ "source": [
283
+ "# Load the FINE-TUNED model from LoRA checkpoint folder\n",
284
+ "finetuned_model, finetuned_tokenizer = FastLanguageModel.from_pretrained(\n",
285
+ " model_name = LORA_ADAPTER_PATH, # <-- peka direkt p\u00e5 /vol/checkpoint-10688\n",
286
+ " max_seq_length = max_seq_length,\n",
287
+ " dtype = dtype,\n",
288
+ " load_in_4bit = load_in_4bit,\n",
289
+ ")\n",
290
+ "finetuned_tokenizer = get_chat_template(finetuned_tokenizer, chat_template=\"llama-3.1\")\n",
291
+ "FastLanguageModel.for_inference(finetuned_model)\n",
292
+ "print(\"Fine-tuned model loaded!\")\n"
293
+ ],
294
+ "execution_count": 16,
295
+ "outputs": [
296
+ {
297
+ "output_type": "stream",
298
+ "name": "stdout",
299
+ "text": [
300
+ "==((====))== Unsloth 2025.11.6: Fast Llama patching. Transformers: 4.56.0.\n",
301
+ " \\\\ /| Tesla T4. Num GPUs = 3. Max memory: 14.563 GB. Platform: Linux.\n",
302
+ "O^O/ \\_/ \\ Torch: 2.9.0+cu128. CUDA: 7.5. CUDA Toolkit: 12.8. Triton: 3.5.0\n",
303
+ "\\ / Bfloat16 = FALSE. FA [Xformers = 0.0.33.post1. FA2 = False]\n",
304
+ " \"-____-\" Free license: http://github.com/unslothai/unsloth\n",
305
+ "Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!\n"
306
+ ]
307
+ },
308
+ {
309
+ "output_type": "stream",
310
+ "name": "stderr",
311
+ "text": [
312
+ "Unsloth 2025.11.6 patched 28 layers with 28 QKV layers, 28 O layers and 28 MLP layers.\n"
313
+ ]
314
+ },
315
+ {
316
+ "output_type": "stream",
317
+ "name": "stdout",
318
+ "text": [
319
+ "Fine-tuned model loaded!\n"
320
+ ]
321
+ }
322
+ ]
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "metadata": {
327
+ "collapsed": false,
328
+ "scrolled": true
329
+ },
330
+ "source": [
331
+ "prompt = [\n",
332
+ " {\"role\": \"user\", \"content\": \"Explain photosynthesis in one short paragraph.\"}\n",
333
+ "]\n",
334
+ "\n",
335
+ "b = generate_response(base_model, base_tokenizer, prompt, deterministic=True)\n",
336
+ "f = generate_response(finetuned_model, finetuned_tokenizer, prompt, deterministic=True)\n",
337
+ "\n",
338
+ "print(\"BASE:\\n\", b)\n",
339
+ "print(\"\\nFINETUNED:\\n\", f)\n"
340
+ ],
341
+ "execution_count": 17,
342
+ "outputs": [
343
+ {
344
+ "output_type": "stream",
345
+ "name": "stdout",
346
+ "text": [
347
+ "BASE:\n",
348
+ " 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",
349
+ "\n",
350
+ "FINETUNED:\n",
351
+ " 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"
352
+ ]
353
+ }
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "markdown",
358
+ "metadata": {},
359
+ "source": [
360
+ "## 4. Evaluation Functions"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {
366
+ "collapsed": false,
367
+ "scrolled": true
368
+ },
369
+ "source": [
370
+ "from rouge_score import rouge_scorer\n",
371
+ "\n",
372
+ "def format_conversation_for_eval(example):\n",
373
+ " convos = example[\"conversations\"]\n",
374
+ "\n",
375
+ " # referens = sista assistant-svaret\n",
376
+ " reference = None\n",
377
+ " for msg in reversed(convos):\n",
378
+ " if msg[\"role\"] == \"assistant\":\n",
379
+ " reference = msg[\"content\"]\n",
380
+ " break\n",
381
+ "\n",
382
+ " if reference is None:\n",
383
+ " return [], None\n",
384
+ "\n",
385
+ " # prompt = alla meddelanden f\u00f6re detta\n",
386
+ " cutoff_index = convos.index(next(m for m in convos if m[\"content\"] == reference))\n",
387
+ " prompt_messages = convos[:cutoff_index]\n",
388
+ "\n",
389
+ " return prompt_messages, reference\n",
390
+ "\n",
391
+ "\n",
392
+ "\n",
393
+ "\n",
394
+ "def generate_response(model, tokenizer, messages, max_new_tokens=256, deterministic=True):\n",
395
+ " inputs = tokenizer.apply_chat_template(\n",
396
+ " messages,\n",
397
+ " tokenize=True,\n",
398
+ " add_generation_prompt=True,\n",
399
+ " return_tensors=\"pt\",\n",
400
+ " ).to(\"cuda\")\n",
401
+ "\n",
402
+ " attention_mask = torch.ones_like(inputs)\n",
403
+ "\n",
404
+ " gen_kwargs = {\n",
405
+ " \"input_ids\": inputs,\n",
406
+ " \"attention_mask\": attention_mask,\n",
407
+ " \"max_new_tokens\": max_new_tokens,\n",
408
+ " \"use_cache\": True,\n",
409
+ " \"pad_token_id\": tokenizer.eos_token_id,\n",
410
+ " }\n",
411
+ "\n",
412
+ " if deterministic:\n",
413
+ " gen_kwargs.update(\n",
414
+ " dict(\n",
415
+ " do_sample=False,\n",
416
+ " temperature=None,\n",
417
+ " )\n",
418
+ " )\n",
419
+ " else:\n",
420
+ " gen_kwargs.update(\n",
421
+ " dict(\n",
422
+ " do_sample=True,\n",
423
+ " temperature=0.7,\n",
424
+ " )\n",
425
+ " )\n",
426
+ "\n",
427
+ " with torch.no_grad():\n",
428
+ " outputs = model.generate(**gen_kwargs)\n",
429
+ "\n",
430
+ " generated = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)\n",
431
+ " return generated.strip()\n",
432
+ "\n",
433
+ "\n",
434
+ "\n",
435
+ "def compute_rouge_scores(predictions, references):\n",
436
+ " \"\"\"Compute ROUGE scores\"\"\"\n",
437
+ " scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)\n",
438
+ " \n",
439
+ " scores = {'rouge1': [], 'rouge2': [], 'rougeL': []}\n",
440
+ " \n",
441
+ " for pred, ref in zip(predictions, references):\n",
442
+ " if ref and pred:\n",
443
+ " score = scorer.score(ref, pred)\n",
444
+ " scores['rouge1'].append(score['rouge1'].fmeasure)\n",
445
+ " scores['rouge2'].append(score['rouge2'].fmeasure)\n",
446
+ " scores['rougeL'].append(score['rougeL'].fmeasure)\n",
447
+ " \n",
448
+ " return {\n",
449
+ " 'rouge1': np.mean(scores['rouge1']),\n",
450
+ " 'rouge2': np.mean(scores['rouge2']),\n",
451
+ " 'rougeL': np.mean(scores['rougeL']),\n",
452
+ " }\n",
453
+ "\n",
454
+ "print(\"Evaluation functions defined!\")"
455
+ ],
456
+ "execution_count": 6,
457
+ "outputs": [
458
+ {
459
+ "output_type": "stream",
460
+ "name": "stdout",
461
+ "text": [
462
+ "Evaluation functions defined!\n"
463
+ ]
464
+ }
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "markdown",
469
+ "metadata": {},
470
+ "source": [
471
+ "## 5. Run Evaluation on Test Set\n",
472
+ "\n",
473
+ "We'll evaluate on a subset of the test set for speed (adjust `num_samples` as needed)"
474
+ ]
475
+ },
476
+ {
477
+ "cell_type": "code",
478
+ "metadata": {
479
+ "collapsed": false,
480
+ "scrolled": true
481
+ },
482
+ "source": [
483
+ "# Number of samples to evaluate (more = better statistics, but slower)\n",
484
+ "num_samples = 100 # Increase for more reliable results\n",
485
+ "\n",
486
+ "# Sample from test set\n",
487
+ "eval_indices = np.random.RandomState(42).choice(len(test_dataset), min(num_samples, len(test_dataset)), replace=False)\n",
488
+ "eval_samples = test_dataset.select(eval_indices)\n",
489
+ "\n",
490
+ "print(f\"Evaluating on {len(eval_samples)} samples...\")"
491
+ ],
492
+ "execution_count": 19,
493
+ "outputs": [
494
+ {
495
+ "output_type": "stream",
496
+ "name": "stdout",
497
+ "text": [
498
+ "Evaluating on 100 samples...\n"
499
+ ]
500
+ }
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "code",
505
+ "metadata": {
506
+ "collapsed": false,
507
+ "scrolled": true
508
+ },
509
+ "source": [
510
+ "# Generate responses from both models\n",
511
+ "base_predictions = []\n",
512
+ "finetuned_predictions = []\n",
513
+ "references = []\n",
514
+ "prompts_used = []\n",
515
+ "\n",
516
+ "for i, example in enumerate(tqdm(eval_samples, desc=\"Generating responses\")):\n",
517
+ " prompt_messages, reference = format_conversation_for_eval(example)\n",
518
+ " \n",
519
+ " if reference is None or len(prompt_messages) == 0:\n",
520
+ " continue\n",
521
+ " \n",
522
+ " try:\n",
523
+ " base_response = generate_response(base_model, base_tokenizer, prompt_messages, deterministic=True)\n",
524
+ " finetuned_response = generate_response(finetuned_model, finetuned_tokenizer, prompt_messages, deterministic=True)\n",
525
+ "\n",
526
+ " \n",
527
+ " base_predictions.append(base_response)\n",
528
+ " finetuned_predictions.append(finetuned_response)\n",
529
+ " references.append(reference)\n",
530
+ " prompts_used.append(prompt_messages)\n",
531
+ " \n",
532
+ " except Exception as e:\n",
533
+ " print(f\"Error on sample {i}: {e}\")\n",
534
+ " continue\n",
535
+ "\n",
536
+ "print(f\"Successfully evaluated {len(references)} samples\")"
537
+ ],
538
+ "execution_count": 20,
539
+ "outputs": [
540
+ {
541
+ "output_type": "stream",
542
+ "name": "stderr",
543
+ "text": [
544
+ "\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]"
545
+ ]
546
+ },
547
+ {
548
+ "output_type": "stream",
549
+ "name": "stdout",
550
+ "text": [
551
+ "Successfully evaluated 100 samples\n"
552
+ ]
553
+ },
554
+ {
555
+ "output_type": "stream",
556
+ "name": "stderr",
557
+ "text": [
558
+ "\n"
559
+ ]
560
+ }
561
+ ]
562
+ },
563
+ {
564
+ "cell_type": "markdown",
565
+ "metadata": {},
566
+ "source": [
567
+ "## 6. Compute Metrics"
568
+ ]
569
+ },
570
+ {
571
+ "cell_type": "code",
572
+ "metadata": {
573
+ "collapsed": false,
574
+ "scrolled": true
575
+ },
576
+ "source": [
577
+ "# Calculate ROUGE scores\n",
578
+ "base_rouge = compute_rouge_scores(base_predictions, references)\n",
579
+ "finetuned_rouge = compute_rouge_scores(finetuned_predictions, references)\n",
580
+ "\n",
581
+ "print(\"=\" * 60)\n",
582
+ "print(\"EVALUATION RESULTS\")\n",
583
+ "print(\"=\" * 60)\n",
584
+ "print(f\"Number of samples evaluated: {len(references)}\")\n",
585
+ "print()\n",
586
+ "print(\"-\" * 60)\n",
587
+ "print(\"ROUGE Scores (higher is better)\")\n",
588
+ "print(\"-\" * 60)\n",
589
+ "print(f\"{'Metric':<15} {'Base Model':<20} {'Fine-tuned':<20} {'Change':<15}\")\n",
590
+ "print(\"-\" * 60)\n",
591
+ "\n",
592
+ "for metric in ['rouge1', 'rouge2', 'rougeL']:\n",
593
+ " base_score = base_rouge[metric]\n",
594
+ " ft_score = finetuned_rouge[metric]\n",
595
+ " improvement = ((ft_score - base_score) / base_score) * 100 if base_score > 0 else 0\n",
596
+ " print(f\"{metric:<15} {base_score:<20.4f} {ft_score:<20.4f} {improvement:+.2f}%\")\n",
597
+ "\n",
598
+ "print(\"=\" * 60)"
599
+ ],
600
+ "execution_count": 21,
601
+ "outputs": [
602
+ {
603
+ "output_type": "stream",
604
+ "name": "stdout",
605
+ "text": [
606
+ "============================================================\n",
607
+ "EVALUATION RESULTS\n",
608
+ "============================================================\n",
609
+ "Number of samples evaluated: 100\n",
610
+ "\n",
611
+ "------------------------------------------------------------\n",
612
+ "ROUGE Scores (higher is better)\n",
613
+ "------------------------------------------------------------\n",
614
+ "Metric Base Model Fine-tuned Change \n",
615
+ "------------------------------------------------------------\n",
616
+ "rouge1 0.4732 0.5323 +12.49%\n",
617
+ "rouge2 0.2255 0.2849 +26.35%\n",
618
+ "rougeL 0.2856 0.3521 +23.30%\n",
619
+ "============================================================\n"
620
+ ]
621
+ }
622
+ ]
623
+ },
624
+ {
625
+ "cell_type": "markdown",
626
+ "metadata": {},
627
+ "source": [
628
+ "## 7. Qualitative Comparison - Side by Side Examples"
629
+ ]
630
+ },
631
+ {
632
+ "cell_type": "code",
633
+ "metadata": {
634
+ "collapsed": false,
635
+ "scrolled": true
636
+ },
637
+ "source": [
638
+ "num_examples = 10\n",
639
+ "\n",
640
+ "for i in range(min(num_examples, len(references))):\n",
641
+ " print(\"=\" * 80)\n",
642
+ " print(f\"EXAMPLE {i+1}\")\n",
643
+ " print(\"=\" * 80)\n",
644
+ " \n",
645
+ " last_user_msg = None\n",
646
+ " for msg in prompts_used[i]:\n",
647
+ " if msg[\"role\"] == \"user\":\n",
648
+ " last_user_msg = msg[\"content\"]\n",
649
+ " \n",
650
+ " print(f\"USER PROMPT:\\n{last_user_msg[:500]}{'...' if len(str(last_user_msg)) > 500 else ''}\")\n",
651
+ " print(f\"\\nREFERENCE:\\n{references[i][:500]}{'...' if len(references[i]) > 500 else ''}\")\n",
652
+ " print(f\"\\nBASE MODEL:\\n{base_predictions[i][:500]}{'...' if len(base_predictions[i]) > 500 else ''}\")\n",
653
+ " print(f\"\\nFINE-TUNED MODEL:\\n{finetuned_predictions[i][:500]}{'...' if len(finetuned_predictions[i]) > 500 else ''}\")\n",
654
+ " print()"
655
+ ],
656
+ "execution_count": 22,
657
+ "outputs": [
658
+ {
659
+ "output_type": "stream",
660
+ "name": "stdout",
661
+ "text": [
662
+ "================================================================================\n",
663
+ "EXAMPLE 1\n",
664
+ "================================================================================\n",
665
+ "USER PROMPT:\n",
666
+ "Explain the process of photosynthesis in simple terms and describe its importance for the ecosystem.\n",
667
+ "\n",
668
+ "REFERENCE:\n",
669
+ "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",
670
+ "\n",
671
+ "BASE MODEL:\n",
672
+ "**What is Photosynthesis?**\n",
673
+ "\n",
674
+ "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",
675
+ "\n",
676
+ "**The Process of Photosynthesis:**\n",
677
+ "\n",
678
+ "1. **Light absorption**: Plants absorb light energy from the sun through specialized pigments such as chlorophyll.\n",
679
+ "2. **Water absorption**: Plants ...\n",
680
+ "\n",
681
+ "FINE-TUNED MODEL:\n",
682
+ "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",
683
+ "\n",
684
+ "================================================================================\n",
685
+ "EXAMPLE 2\n",
686
+ "================================================================================\n",
687
+ "USER PROMPT:\n",
688
+ "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",
689
+ "\n",
690
+ "REFERENCE:\n",
691
+ "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",
692
+ "\n",
693
+ "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",
694
+ "\n",
695
+ "BASE MODEL:\n",
696
+ "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",
697
+ "\n",
698
+ "**Equality Property:**\n",
699
+ "\n",
700
+ "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",
701
+ "\n",
702
+ "a = b \u21d4 (a + c) = (b + c)\n",
703
+ "\n",
704
+ "where a and b are the original expressions, and c is any value.\n",
705
+ "\n",
706
+ "**Distributive Property:**\n",
707
+ "\n",
708
+ "Th...\n",
709
+ "\n",
710
+ "FINE-TUNED MODEL:\n",
711
+ "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",
712
+ "\n",
713
+ "For example, consider the equation $x + 2 = 5$. If you add 3 to both sides of the equation, you get $x + 5 = 8...\n",
714
+ "\n",
715
+ "================================================================================\n",
716
+ "EXAMPLE 3\n",
717
+ "================================================================================\n",
718
+ "USER PROMPT:\n",
719
+ "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",
720
+ "\n",
721
+ "REFERENCE:\n",
722
+ "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",
723
+ "\n",
724
+ "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",
725
+ "\n",
726
+ "The area of the base is given by the formula:\n",
727
+ "\n",
728
+ "Area of base = (1/2) * d1 * d2 * sin(theta)\n",
729
+ "\n",
730
+ "where d1 and d2 are the lengths of the diagonals of the rhombus and theta is the angle between the diagonals.\n",
731
+ "\n",
732
+ "Since the d...\n",
733
+ "\n",
734
+ "BASE MODEL:\n",
735
+ "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",
736
+ "\n",
737
+ "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",
738
+ "\n",
739
+ "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",
740
+ "\n",
741
+ "Diagonal 1 = 2 * sin(60) * 9...\n",
742
+ "\n",
743
+ "FINE-TUNED MODEL:\n",
744
+ "The surface area of the pyramid is 173.5 square units.\n",
745
+ "\n",
746
+ "Explanation:\n",
747
+ "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",
748
+ "\n",
749
+ "1. Area of the base (rhombus):\n",
750
+ "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",
751
+ "\n",
752
+ "Given that the sides of the rhombus are 9 units and the angle at one corner is 12...\n",
753
+ "\n",
754
+ "================================================================================\n",
755
+ "EXAMPLE 4\n",
756
+ "================================================================================\n",
757
+ "USER PROMPT:\n",
758
+ "How do gravitational waves affect the curvature of spacetime and what is the mathematical expression that describes it?\n",
759
+ "\n",
760
+ "REFERENCE:\n",
761
+ "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",
762
+ "\n",
763
+ "The mathematical expression that describes the effect of gravitational waves on the curvature of spacetime is ...\n",
764
+ "\n",
765
+ "BASE MODEL:\n",
766
+ "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",
767
+ "\n",
768
+ "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",
769
+ "\n",
770
+ "R\u03bc\u03bd - 1...\n",
771
+ "\n",
772
+ "FINE-TUNED MODEL:\n",
773
+ "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",
774
+ "\n",
775
+ "The mathematical expression that describes the curvature of spacetime due to gravitational waves is given by the Einst...\n",
776
+ "\n",
777
+ "================================================================================\n",
778
+ "EXAMPLE 5\n",
779
+ "================================================================================\n",
780
+ "USER PROMPT:\n",
781
+ "Write Python code to solve the task:\n",
782
+ "We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.\n",
783
+ "\n",
784
+ "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",
785
+ "\n",
786
+ "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",
787
+ "\n",
788
+ "REFERENCE:\n",
789
+ "Step 1: We need to find the number of pairs of strings that are anagrams of each other.\n",
790
+ "Step 2: We can start by creating a function to check if two strings are anagrams.\n",
791
+ "Step 3: Then we can create a loop to compare each string with every other string in the list.\n",
792
+ "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",
793
+ "Step 5: We should also utilize a dictionary to count the frequency of each character a...\n",
794
+ "\n",
795
+ "BASE MODEL:\n",
796
+ "def count_anagrams(N, strings):\n",
797
+ " anagrams = {}\n",
798
+ " for s in strings:\n",
799
+ " sorted_s = ''.join(sorted(s))\n",
800
+ " if sorted_s in anagrams:\n",
801
+ " anagrams[sorted_s].append(s)\n",
802
+ " else:\n",
803
+ " anagrams[sorted_s] = [s]\n",
804
+ " count = 0\n",
805
+ " for v in anagrams.values():\n",
806
+ " count += len(v) * (len(v) - 1) // 2\n",
807
+ " return count\n",
808
+ "\n",
809
+ "N = int(input())\n",
810
+ "strings = [input() for _ in range(N)]\n",
811
+ "print(count_anagrams(N, strings))\n",
812
+ "\n",
813
+ "FINE-TUNED MODEL:\n",
814
+ "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",
815
+ "Step 2: We can start by creating a function to check if two strings are anagrams of each other.\n",
816
+ "Step 3: Then, we can iterate through the input strings and count the number of pairs that satisfy the condition.\n",
817
+ "Step 4: We also need to consider the constraints and the input format.\n",
818
+ "Step 5: We can use a dictionary to store the count of each string and then calculate t...\n",
819
+ "\n",
820
+ "================================================================================\n",
821
+ "EXAMPLE 6\n",
822
+ "================================================================================\n",
823
+ "USER PROMPT:\n",
824
+ "Write a short story about a computer that can predict the future.\n",
825
+ "\n",
826
+ "REFERENCE:\n",
827
+ "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",
828
+ "\n",
829
+ "At first, people were skeptical of Oracle's abilities. But soon, the computer proved its worth. It predicted natural disasters ...\n",
830
+ "\n",
831
+ "BASE MODEL:\n",
832
+ "**The Oracle of Code**\n",
833
+ "\n",
834
+ "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",
835
+ "\n",
836
+ "That was until they stumbled upon an unusual approach. Instead of focusing on predicting specific events, they decided to create a comput...\n",
837
+ "\n",
838
+ "FINE-TUNED MODEL:\n",
839
+ "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",
840
+ "\n",
841
+ "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",
842
+ "\n",
843
+ "At first, Chrono's predictions were nothing more than guesses. But as time went on, the computer's accuracy began ...\n",
844
+ "\n",
845
+ "================================================================================\n",
846
+ "EXAMPLE 7\n",
847
+ "================================================================================\n",
848
+ "USER PROMPT:\n",
849
+ "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",
850
+ "\n",
851
+ "REFERENCE:\n",
852
+ "There are several measures that can be implemented to reduce the negative impact of frequent air travel on the environment:\n",
853
+ "1. Promote the use of alternative modes of transportation, such as trains and buses, for shorter distances.\n",
854
+ "2. Encourage the use of more fuel-efficient aircraft and engines, as well as the use of alternative fuels like biofuels.\n",
855
+ "3. Implement carbon offsetting programs, where airlines invest in projects that reduce carbon emissions, such as renewable energy or reforestation....\n",
856
+ "\n",
857
+ "BASE MODEL:\n",
858
+ "To reduce the negative impact of frequent air travel on the environment, several measures can be implemented:\n",
859
+ "\n",
860
+ "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",
861
+ "2. **Fuel efficiency**: Improve aircraft fuel efficiency through more efficient engines, aerodynamic designs, and alternative fuels, such as biofuels or electric propulsion.\n",
862
+ "3. **Sustainable aviati...\n",
863
+ "\n",
864
+ "FINE-TUNED MODEL:\n",
865
+ "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",
866
+ "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",
867
+ "2. Fuel efficiency: Airlines can improve fuel efficiency by using more e...\n",
868
+ "\n",
869
+ "================================================================================\n",
870
+ "EXAMPLE 8\n",
871
+ "================================================================================\n",
872
+ "USER PROMPT:\n",
873
+ "How does the Earth's structure impact our lives and the environment?\n",
874
+ "\n",
875
+ "REFERENCE:\n",
876
+ "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",
877
+ "\n",
878
+ "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",
879
+ "\n",
880
+ "2) The core's heat, resulting from radioactive decay, drives convection currents in the mantle. ...\n",
881
+ "\n",
882
+ "BASE MODEL:\n",
883
+ "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",
884
+ "\n",
885
+ "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",
886
+ "2. **Geological Activity**: The Eart...\n",
887
+ "\n",
888
+ "FINE-TUNED MODEL:\n",
889
+ "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",
890
+ "\n",
891
+ "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",
892
+ "\n",
893
+ "2. Natural Resources: The Earth's structure is responsible for the availability of n...\n",
894
+ "\n",
895
+ "================================================================================\n",
896
+ "EXAMPLE 9\n",
897
+ "================================================================================\n",
898
+ "USER PROMPT:\n",
899
+ "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",
900
+ "\n",
901
+ "REFERENCE:\n",
902
+ "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",
903
+ "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",
904
+ "We also know that each student has 2 arms, which means they have 2 hands each.\n",
905
+ "So, the total number of hands in the class, not including Peter's, is 10 students * 2 hands per student = 20 hands.\n",
906
+ "Since each student has x hands, we can set ...\n",
907
+ "\n",
908
+ "BASE MODEL:\n",
909
+ "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",
910
+ "\n",
911
+ "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",
912
+ "\n",
913
+ "11 students * 2 arms/student * x hands/arm = 22x hands\n",
914
+ "\n",
915
+ "However, we know that there are 20 hands not including Peter's. Since Peter also has hands, we can set up...\n",
916
+ "\n",
917
+ "FINE-TUNED MODEL:\n",
918
+ "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",
919
+ "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",
920
+ "3. We know that there are 11 students in Peter's class, including him. This means that the total number of hands...\n",
921
+ "\n",
922
+ "================================================================================\n",
923
+ "EXAMPLE 10\n",
924
+ "================================================================================\n",
925
+ "USER PROMPT:\n",
926
+ "Solve the following math problem step-by-step.\n",
927
+ "Simplify your answer as much as possible. Present your final answer as \\boxed{Your Answer}.\n",
928
+ "A coin is flipped eight times, and the sequence of heads and tails occurring is recorded. How many distinct sequences are possible?\n",
929
+ "\n",
930
+ "REFERENCE:\n",
931
+ "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",
932
+ "Step 2: Since there are two possible outcomes for each flip (heads or tails), there are 2 options for each flip.\n",
933
+ "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",
934
+ "Step 4: So, the solution is 2^8 = 256 distinct sequences.\n",
935
+ "\n",
936
+ "Answer:\n",
937
+ "\\box...\n",
938
+ "\n",
939
+ "BASE MODEL:\n",
940
+ "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",
941
+ "\n",
942
+ "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",
943
+ "\n",
944
+ "Here's the step-by-step calculation:\n",
945
+ "\n",
946
+ "1. Number of possible outcomes for the first flip: 2\n",
947
+ "2. Number of possible outcomes for the second flip: 2\n",
948
+ "3. Number o...\n",
949
+ "\n",
950
+ "FINE-TUNED MODEL:\n",
951
+ "Step 1: To solve this problem, we need to understand the concept of permutations and how it applies to the given scenario.\n",
952
+ "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",
953
+ "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",
954
+ "Step 4: The ...\n",
955
+ "\n"
956
+ ]
957
+ }
958
+ ]
959
+ },
960
+ {
961
+ "cell_type": "markdown",
962
+ "metadata": {},
963
+ "source": [
964
+ "## 8. Response Length Analysis"
965
+ ]
966
+ },
967
+ {
968
+ "cell_type": "code",
969
+ "metadata": {
970
+ "collapsed": false,
971
+ "scrolled": true
972
+ },
973
+ "source": [
974
+ "base_lengths = [len(p.split()) for p in base_predictions]\n",
975
+ "ft_lengths = [len(p.split()) for p in finetuned_predictions]\n",
976
+ "ref_lengths = [len(r.split()) for r in references]\n",
977
+ "\n",
978
+ "print(\"Response Length Analysis (words)\")\n",
979
+ "print(\"-\" * 50)\n",
980
+ "print(f\"{'Metric':<25} {'Base':<12} {'Fine-tuned':<12} {'Reference':<12}\")\n",
981
+ "print(\"-\" * 50)\n",
982
+ "print(f\"{'Mean length':<25} {np.mean(base_lengths):<12.1f} {np.mean(ft_lengths):<12.1f} {np.mean(ref_lengths):<12.1f}\")\n",
983
+ "print(f\"{'Median length':<25} {np.median(base_lengths):<12.1f} {np.median(ft_lengths):<12.1f} {np.median(ref_lengths):<12.1f}\")\n",
984
+ "print(f\"{'Std deviation':<25} {np.std(base_lengths):<12.1f} {np.std(ft_lengths):<12.1f} {np.std(ref_lengths):<12.1f}\")"
985
+ ],
986
+ "execution_count": 24,
987
+ "outputs": [
988
+ {
989
+ "output_type": "stream",
990
+ "name": "stdout",
991
+ "text": [
992
+ "Response Length Analysis (words)\n",
993
+ "--------------------------------------------------\n",
994
+ "Metric Base Fine-tuned Reference \n",
995
+ "--------------------------------------------------\n",
996
+ "Mean length 165.0 155.7 216.3 \n",
997
+ "Median length 176.0 165.5 199.0 \n",
998
+ "Std deviation 42.5 53.6 109.4 \n"
999
+ ]
1000
+ }
1001
+ ]
1002
+ },
1003
+ {
1004
+ "cell_type": "markdown",
1005
+ "metadata": {},
1006
+ "source": [
1007
+ "## 9. Save Results"
1008
+ ]
1009
+ },
1010
+ {
1011
+ "cell_type": "code",
1012
+ "metadata": {
1013
+ "collapsed": false,
1014
+ "scrolled": true
1015
+ },
1016
+ "source": [
1017
+ "import json\n",
1018
+ "from datetime import datetime\n",
1019
+ "\n",
1020
+ "results = {\n",
1021
+ " \"timestamp\": datetime.now().isoformat(),\n",
1022
+ " \"base_model\": BASE_MODEL_NAME,\n",
1023
+ " \"finetuned_model\": LORA_ADAPTER_PATH,\n",
1024
+ " \"num_samples\": len(references),\n",
1025
+ " \"metrics\": {\n",
1026
+ " \"base_model\": base_rouge,\n",
1027
+ " \"finetuned_model\": finetuned_rouge,\n",
1028
+ " },\n",
1029
+ " \"response_lengths\": {\n",
1030
+ " \"base_mean\": float(np.mean(base_lengths)),\n",
1031
+ " \"finetuned_mean\": float(np.mean(ft_lengths)),\n",
1032
+ " \"reference_mean\": float(np.mean(ref_lengths)),\n",
1033
+ " }\n",
1034
+ "}\n",
1035
+ "\n",
1036
+ "with open(\"evaluation_results.json\", \"w\") as f:\n",
1037
+ " json.dump(results, f, indent=2)\n",
1038
+ "\n",
1039
+ "print(\"Results saved to evaluation_results.json\")\n",
1040
+ "print(json.dumps(results, indent=2))"
1041
+ ],
1042
+ "execution_count": 25,
1043
+ "outputs": [
1044
+ {
1045
+ "output_type": "stream",
1046
+ "name": "stdout",
1047
+ "text": [
1048
+ "Results saved to evaluation_results.json\n",
1049
+ "{\n",
1050
+ " \"timestamp\": \"2025-12-02T10:09:18.235153\",\n",
1051
+ " \"base_model\": \"unsloth/Llama-3.2-3B-Instruct\",\n",
1052
+ " \"finetuned_model\": \"/vol/checkpoint-10688\",\n",
1053
+ " \"num_samples\": 100,\n",
1054
+ " \"metrics\": {\n",
1055
+ " \"base_model\": {\n",
1056
+ " \"rouge1\": 0.4732268736349978,\n",
1057
+ " \"rouge2\": 0.22545052802537063,\n",
1058
+ " \"rougeL\": 0.2855963588727634\n",
1059
+ " },\n",
1060
+ " \"finetuned_model\": {\n",
1061
+ " \"rouge1\": 0.5323317587648463,\n",
1062
+ " \"rouge2\": 0.28485583536195763,\n",
1063
+ " \"rougeL\": 0.35213159677059536\n",
1064
+ " }\n",
1065
+ " },\n",
1066
+ " \"response_lengths\": {\n",
1067
+ " \"base_mean\": 165.0,\n",
1068
+ " \"finetuned_mean\": 155.68,\n",
1069
+ " \"reference_mean\": 216.27\n",
1070
+ " }\n",
1071
+ "}\n"
1072
+ ]
1073
+ }
1074
+ ]
1075
+ }
1076
+ ],
1077
+ "metadata": {
1078
+ "kernelspec": {
1079
+ "display_name": "Python",
1080
+ "language": "python",
1081
+ "name": "python3"
1082
+ },
1083
+ "language_info": {
1084
+ "codemirror_mode": {
1085
+ "name": "ipython",
1086
+ "version": 3
1087
+ },
1088
+ "file_extension": ".py",
1089
+ "mimetype": "text/x-python",
1090
+ "name": "python",
1091
+ "nbconvert_exporter": "python",
1092
+ "pygments_lexer": "ipython3"
1093
+ }
1094
+ },
1095
+ "nbformat": 4,
1096
+ "nbformat_minor": 5
1097
+ }
lab2-scalable.ipynb ADDED
@@ -0,0 +1,919 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Lab 2: Fine-Tuning LLM with LoRA (ID2223)\n",
8
+ "\n",
9
+ "This notebook is structured into separate sections:\n",
10
+ "\n",
11
+ "**PART 1: Installation and Configuration** - Always run this first\n",
12
+ "\n",
13
+ "**PART 2: Training Pipeline** - Run this section to fine-tune a new model from scratch\n",
14
+ "\n",
15
+ "**PART 3: Load Existing LoRA and Export** - Run this section to load previously trained LoRA weights and export to HuggingFace/GGUF\n",
16
+ "\n",
17
+ "**PART 4: Inference and Testing** - Test your model\n",
18
+ "\n",
19
+ "---\n",
20
+ "\n",
21
+ "Base model: `unsloth/Llama-3.2-3B-Instruct`\n",
22
+ "\n",
23
+ "Dataset: [FineTome-100k](https://huggingface.co/datasets/mlabonne/FineTome-100k)\n",
24
+ "\n",
25
+ "---\n",
26
+ "\n",
27
+ "Features:\n",
28
+ "1. Uses Maxime Labonne's FineTome 100K dataset\n",
29
+ "2. Convert ShareGPT to HuggingFace format via `standardize_sharegpt`\n",
30
+ "3. Train on Completions / Assistant only via `train_on_responses_only`\n",
31
+ "4. Checkpoint saving every 500 steps for resumable training\n",
32
+ "5. Export to FP16 and GGUF formats for deployment"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "markdown",
37
+ "metadata": {},
38
+ "source": [
39
+ "---\n",
40
+ "# PART 1: Installation and Configuration\n",
41
+ "---\n",
42
+ "\n",
43
+ "Run this section first regardless of whether you are training or loading an existing model."
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "metadata": {},
49
+ "source": [
50
+ "## 1.1 Install Dependencies"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": null,
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "%%capture\n",
60
+ "%uv pip install unsloth\n",
61
+ "# Also get the latest nightly Unsloth!\n",
62
+ "%uv pip uninstall unsloth -y && pip install --upgrade --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git@nightly git+https://github.com/unslothai/unsloth-zoo.git"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "markdown",
67
+ "metadata": {},
68
+ "source": [
69
+ "## 1.2 Configuration\n",
70
+ "\n",
71
+ "Set your model parameters and paths here. These are used throughout the notebook."
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "import torch\n",
81
+ "\n",
82
+ "# Model configuration\n",
83
+ "BASE_MODEL_NAME = \"unsloth/Llama-3.2-3B-Instruct\"\n",
84
+ "max_seq_length = 2048\n",
85
+ "dtype = \"float16\" # Float16 for Tesla T4, V100. Use None for auto detection.\n",
86
+ "load_in_4bit = True\n",
87
+ "\n",
88
+ "# LoRA configuration\n",
89
+ "LORA_R = 16\n",
90
+ "LORA_ALPHA = 16\n",
91
+ "LORA_DROPOUT = 0\n",
92
+ "LORA_TARGET_MODULES = [\n",
93
+ " \"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n",
94
+ " \"gate_proj\", \"up_proj\", \"down_proj\",\n",
95
+ "]\n",
96
+ "\n",
97
+ "# Paths for saving/loading\n",
98
+ "OUTPUT_DIR = \"/vol\" # Training checkpoints directory\n",
99
+ "LORA_ADAPTER_PATH = \"/vol/checkpoint-10688\" # Path to saved LoRA adapter (for loading)\n",
100
+ "MERGED_MODEL_DIR = \"/vol/merged-model\" # Path for merged FP16 model\n",
101
+ "GGUF_MODEL_DIR = \"/vol/gguf-model\" # Path for GGUF model\n",
102
+ "\n",
103
+ "# HuggingFace configuration\n",
104
+ "HF_REPO_ID = \"Jeppcode/ScalableLab2\" # Your HuggingFace repo"
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "markdown",
109
+ "metadata": {},
110
+ "source": [
111
+ "## 1.3 Supported Models\n",
112
+ "\n",
113
+ "We support Llama, Mistral, Phi-3, Gemma, Yi, DeepSeek, Qwen, TinyLlama, Vicuna, Open Hermes etc.\n",
114
+ "We support 16bit LoRA or 4bit QLoRA. Both 2x faster.\n",
115
+ "`max_seq_length` can be set to anything, since we do automatic RoPE Scaling."
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "metadata": {},
122
+ "outputs": [],
123
+ "source": [
124
+ "# 4bit pre quantized models we support for 4x faster downloading + no OOMs.\n",
125
+ "fourbit_models = [\n",
126
+ " \"unsloth/Meta-Llama-3.1-8B-bnb-4bit\",\n",
127
+ " \"unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit\",\n",
128
+ " \"unsloth/Meta-Llama-3.1-70B-bnb-4bit\",\n",
129
+ " \"unsloth/Meta-Llama-3.1-405B-bnb-4bit\",\n",
130
+ " \"unsloth/Mistral-Small-Instruct-2409\",\n",
131
+ " \"unsloth/mistral-7b-instruct-v0.3-bnb-4bit\",\n",
132
+ " \"unsloth/Phi-3.5-mini-instruct\",\n",
133
+ " \"unsloth/Phi-3-medium-4k-instruct\",\n",
134
+ " \"unsloth/gemma-2-9b-bnb-4bit\",\n",
135
+ " \"unsloth/gemma-2-27b-bnb-4bit\",\n",
136
+ " \"unsloth/Llama-3.2-1B-bnb-4bit\",\n",
137
+ " \"unsloth/Llama-3.2-1B-Instruct-bnb-4bit\",\n",
138
+ " \"unsloth/Llama-3.2-3B-bnb-4bit\",\n",
139
+ " \"unsloth/Llama-3.2-3B-Instruct-bnb-4bit\",\n",
140
+ " \"unsloth/Llama-3.3-70B-Instruct-bnb-4bit\"\n",
141
+ "]"
142
+ ]
143
+ },
144
+ {
145
+ "cell_type": "markdown",
146
+ "metadata": {},
147
+ "source": [
148
+ "---\n",
149
+ "# PART 2: Training Pipeline\n",
150
+ "---\n",
151
+ "\n",
152
+ "**Run this section to fine-tune a new model from scratch.**\n",
153
+ "\n",
154
+ "Skip this section if you already have trained LoRA weights and want to load/export them (go to PART 3)."
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "markdown",
159
+ "metadata": {},
160
+ "source": [
161
+ "## 2.1 Load Base Model for Training"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": null,
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "from unsloth import FastLanguageModel\n",
171
+ "\n",
172
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
173
+ " model_name = BASE_MODEL_NAME,\n",
174
+ " max_seq_length = max_seq_length,\n",
175
+ " dtype = dtype,\n",
176
+ " load_in_4bit = load_in_4bit,\n",
177
+ " # token = \"hf_...\", # Use if accessing gated models\n",
178
+ ")"
179
+ ]
180
+ },
181
+ {
182
+ "cell_type": "markdown",
183
+ "metadata": {},
184
+ "source": [
185
+ "## 2.2 Add LoRA Adapters\n",
186
+ "\n",
187
+ "We add LoRA adapters so we only need to update 1-10% of all parameters."
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "metadata": {},
194
+ "outputs": [],
195
+ "source": [
196
+ "model = FastLanguageModel.get_peft_model(\n",
197
+ " model,\n",
198
+ " r = LORA_R,\n",
199
+ " target_modules = LORA_TARGET_MODULES,\n",
200
+ " lora_alpha = LORA_ALPHA,\n",
201
+ " lora_dropout = LORA_DROPOUT,\n",
202
+ " bias = \"none\",\n",
203
+ " use_gradient_checkpointing = \"unsloth\",\n",
204
+ " random_state = 3407,\n",
205
+ " use_rslora = False,\n",
206
+ " loftq_config = None,\n",
207
+ ")"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "markdown",
212
+ "metadata": {},
213
+ "source": [
214
+ "## 2.3 Data Preparation\n",
215
+ "\n",
216
+ "We use the Llama-3.1 format for conversation style finetunes. We use Maxime Labonne's FineTome-100k dataset in ShareGPT style and convert it to HuggingFace's normal multiturn format."
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": null,
222
+ "metadata": {},
223
+ "outputs": [],
224
+ "source": [
225
+ "from unsloth.chat_templates import get_chat_template\n",
226
+ "\n",
227
+ "tokenizer = get_chat_template(\n",
228
+ " tokenizer,\n",
229
+ " chat_template = \"llama-3.1\",\n",
230
+ ")\n",
231
+ "\n",
232
+ "def formatting_prompts_func(examples):\n",
233
+ " convos = examples[\"conversations\"]\n",
234
+ " texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]\n",
235
+ " return { \"text\" : texts, }\n",
236
+ "\n",
237
+ "from datasets import load_dataset\n",
238
+ "dataset = load_dataset(\"mlabonne/FineTome-100k\", split = \"train\")"
239
+ ]
240
+ },
241
+ {
242
+ "cell_type": "markdown",
243
+ "metadata": {},
244
+ "source": [
245
+ "### Standardize ShareGPT Format\n",
246
+ "\n",
247
+ "Convert ShareGPT style datasets into HuggingFace's generic format."
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": null,
253
+ "metadata": {},
254
+ "outputs": [],
255
+ "source": [
256
+ "from unsloth.chat_templates import standardize_sharegpt\n",
257
+ "dataset = standardize_sharegpt(dataset)"
258
+ ]
259
+ },
260
+ {
261
+ "cell_type": "markdown",
262
+ "metadata": {},
263
+ "source": [
264
+ "### Split Dataset\n",
265
+ "\n",
266
+ "Split into train (85%), validation (5%), and test (10%) sets."
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": null,
272
+ "metadata": {},
273
+ "outputs": [],
274
+ "source": [
275
+ "# First split: train+val (90%), test (10%)\n",
276
+ "train_val_split = dataset.train_test_split(test_size=0.10, seed=42)\n",
277
+ "test_dataset = train_val_split[\"test\"]\n",
278
+ "train_val_dataset = train_val_split[\"train\"]\n",
279
+ "\n",
280
+ "# Second split: train (95%), val (5%) of the remaining 90%\n",
281
+ "train_valid = train_val_dataset.train_test_split(test_size=0.05, seed=42)\n",
282
+ "train_dataset = train_valid[\"train\"]\n",
283
+ "valid_dataset = train_valid[\"test\"]\n",
284
+ "\n",
285
+ "# Apply formatting\n",
286
+ "train_dataset = train_dataset.map(formatting_prompts_func, batched=True)\n",
287
+ "valid_dataset = valid_dataset.map(formatting_prompts_func, batched=True)\n",
288
+ "test_dataset = test_dataset.map(formatting_prompts_func, batched=True)\n",
289
+ "\n",
290
+ "print(f\"Train: {len(train_dataset)}, Valid: {len(valid_dataset)}, Test: {len(test_dataset)}\")"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "markdown",
295
+ "metadata": {},
296
+ "source": [
297
+ "### Inspect Dataset (Optional)"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": null,
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "# View conversation structure\n",
307
+ "print(\"Conversation structure:\")\n",
308
+ "print(train_dataset[5][\"conversations\"])\n",
309
+ "print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
310
+ "print(\"Formatted text:\")\n",
311
+ "print(train_dataset[5][\"text\"])"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "markdown",
316
+ "metadata": {},
317
+ "source": [
318
+ "## 2.4 Setup Trainer\n",
319
+ "\n",
320
+ "Using HuggingFace TRL's SFTTrainer with checkpointing enabled."
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "execution_count": null,
326
+ "metadata": {},
327
+ "outputs": [],
328
+ "source": [
329
+ "from trl import SFTTrainer\n",
330
+ "from transformers import TrainingArguments, DataCollatorForSeq2Seq\n",
331
+ "from unsloth import is_bfloat16_supported\n",
332
+ "\n",
333
+ "trainer = SFTTrainer(\n",
334
+ " model = model,\n",
335
+ " tokenizer = tokenizer,\n",
336
+ " train_dataset = train_dataset,\n",
337
+ " eval_dataset = valid_dataset,\n",
338
+ " dataset_text_field = \"text\",\n",
339
+ " max_seq_length = max_seq_length,\n",
340
+ " data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer),\n",
341
+ " dataset_num_proc = 2,\n",
342
+ " packing = False,\n",
343
+ " args = TrainingArguments(\n",
344
+ " per_device_train_batch_size = 2,\n",
345
+ " gradient_accumulation_steps = 4,\n",
346
+ " warmup_steps = 5,\n",
347
+ " num_train_epochs = 1,\n",
348
+ " # max_steps = 60, # Uncomment for quick test runs\n",
349
+ " learning_rate = 2e-4,\n",
350
+ " fp16 = not is_bfloat16_supported(),\n",
351
+ " bf16 = is_bfloat16_supported(),\n",
352
+ " logging_steps = 50,\n",
353
+ " optim = \"adamw_8bit\",\n",
354
+ " weight_decay = 0.01,\n",
355
+ " lr_scheduler_type = \"linear\",\n",
356
+ " seed = 3407,\n",
357
+ " output_dir = OUTPUT_DIR,\n",
358
+ " report_to = \"none\",\n",
359
+ " \n",
360
+ " # Checkpointing - saves every 500 steps\n",
361
+ " save_strategy = \"steps\",\n",
362
+ " save_steps = 500,\n",
363
+ " save_total_limit = 5,\n",
364
+ " \n",
365
+ " # Evaluation\n",
366
+ " eval_steps = 500,\n",
367
+ " ),\n",
368
+ ")"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "markdown",
373
+ "metadata": {},
374
+ "source": [
375
+ "### Train on Responses Only\n",
376
+ "\n",
377
+ "Only train on the assistant outputs, ignore the loss on user inputs."
378
+ ]
379
+ },
380
+ {
381
+ "cell_type": "code",
382
+ "execution_count": null,
383
+ "metadata": {},
384
+ "outputs": [],
385
+ "source": [
386
+ "from unsloth.chat_templates import train_on_responses_only\n",
387
+ "trainer = train_on_responses_only(\n",
388
+ " trainer,\n",
389
+ " instruction_part = \"<|start_header_id|>user<|end_header_id|>\\n\\n\",\n",
390
+ " response_part = \"<|start_header_id|>assistant<|end_header_id|>\\n\\n\",\n",
391
+ " num_proc = 1,\n",
392
+ ")"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "metadata": {},
398
+ "source": [
399
+ "### Verify Masking (Optional)"
400
+ ]
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "execution_count": null,
405
+ "metadata": {},
406
+ "outputs": [],
407
+ "source": [
408
+ "# Check that system and instruction prompts are masked\n",
409
+ "space = tokenizer(\" \", add_special_tokens = False).input_ids[0]\n",
410
+ "print(\"Original:\")\n",
411
+ "print(tokenizer.decode(trainer.train_dataset[5][\"input_ids\"]))\n",
412
+ "print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
413
+ "print(\"Masked (spaces show masked tokens):\")\n",
414
+ "print(tokenizer.decode([space if x == -100 else x for x in trainer.train_dataset[5][\"labels\"]]))"
415
+ ]
416
+ },
417
+ {
418
+ "cell_type": "markdown",
419
+ "metadata": {},
420
+ "source": [
421
+ "## 2.5 Train the Model"
422
+ ]
423
+ },
424
+ {
425
+ "cell_type": "code",
426
+ "execution_count": null,
427
+ "metadata": {},
428
+ "outputs": [],
429
+ "source": [
430
+ "# Show current memory stats\n",
431
+ "gpu_stats = torch.cuda.get_device_properties(0)\n",
432
+ "start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)\n",
433
+ "max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)\n",
434
+ "print(f\"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.\")\n",
435
+ "print(f\"{start_gpu_memory} GB of memory reserved.\")"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "execution_count": null,
441
+ "metadata": {},
442
+ "outputs": [],
443
+ "source": [
444
+ "trainer_stats = trainer.train()"
445
+ ]
446
+ },
447
+ {
448
+ "cell_type": "code",
449
+ "execution_count": null,
450
+ "metadata": {},
451
+ "outputs": [],
452
+ "source": [
453
+ "# Show final memory and time stats\n",
454
+ "used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)\n",
455
+ "used_memory_for_lora = round(used_memory - start_gpu_memory, 3)\n",
456
+ "used_percentage = round(used_memory / max_memory * 100, 3)\n",
457
+ "lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)\n",
458
+ "print(f\"{trainer_stats.metrics['train_runtime']} seconds used for training.\")\n",
459
+ "print(f\"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.\")\n",
460
+ "print(f\"Peak reserved memory = {used_memory} GB.\")\n",
461
+ "print(f\"Peak reserved memory for training = {used_memory_for_lora} GB.\")\n",
462
+ "print(f\"Peak reserved memory % of max memory = {used_percentage} %.\")\n",
463
+ "print(f\"Peak reserved memory for training % of max memory = {lora_percentage} %.\")"
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "markdown",
468
+ "metadata": {},
469
+ "source": [
470
+ "## 2.6 Save LoRA Adapters\n",
471
+ "\n",
472
+ "Save the trained LoRA adapters locally."
473
+ ]
474
+ },
475
+ {
476
+ "cell_type": "code",
477
+ "execution_count": null,
478
+ "metadata": {},
479
+ "outputs": [],
480
+ "source": [
481
+ "model.save_pretrained(f\"{OUTPUT_DIR}/lora-final\")\n",
482
+ "tokenizer.save_pretrained(f\"{OUTPUT_DIR}/lora-final\")\n",
483
+ "print(f\"LoRA adapters saved to {OUTPUT_DIR}/lora-final\")"
484
+ ]
485
+ },
486
+ {
487
+ "cell_type": "markdown",
488
+ "metadata": {},
489
+ "source": [
490
+ "### Upload LoRA Adapters to HuggingFace (Optional)"
491
+ ]
492
+ },
493
+ {
494
+ "cell_type": "code",
495
+ "execution_count": null,
496
+ "metadata": {},
497
+ "outputs": [],
498
+ "source": [
499
+ "from huggingface_hub import login, HfApi\n",
500
+ "login()"
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "code",
505
+ "execution_count": null,
506
+ "metadata": {},
507
+ "outputs": [],
508
+ "source": [
509
+ "api = HfApi()\n",
510
+ "api.upload_folder(\n",
511
+ " folder_path=f\"{OUTPUT_DIR}/lora-final\",\n",
512
+ " repo_id=HF_REPO_ID,\n",
513
+ " path_in_repo=\"lora_adapters\",\n",
514
+ ")\n",
515
+ "print(f\"Uploaded to {HF_REPO_ID}/lora_adapters\")"
516
+ ]
517
+ },
518
+ {
519
+ "cell_type": "markdown",
520
+ "metadata": {},
521
+ "source": [
522
+ "---\n",
523
+ "# PART 3: Load Existing LoRA and Export\n",
524
+ "---\n",
525
+ "\n",
526
+ "**Run this section if you already have trained LoRA weights and want to:**\n",
527
+ "- Load the base model + LoRA adapters\n",
528
+ "- Merge into a full FP16 model\n",
529
+ "- Export to GGUF format for CPU inference\n",
530
+ "- Upload to HuggingFace\n",
531
+ "\n",
532
+ "**Skip this section if you just trained a model in PART 2 and it is still in memory - go directly to PART 4 for inference.**"
533
+ ]
534
+ },
535
+ {
536
+ "cell_type": "markdown",
537
+ "metadata": {},
538
+ "source": [
539
+ "## 3.1 Load Base Model"
540
+ ]
541
+ },
542
+ {
543
+ "cell_type": "code",
544
+ "execution_count": null,
545
+ "metadata": {},
546
+ "outputs": [],
547
+ "source": [
548
+ "from unsloth import FastLanguageModel\n",
549
+ "\n",
550
+ "base_model, tokenizer = FastLanguageModel.from_pretrained(\n",
551
+ " model_name = BASE_MODEL_NAME,\n",
552
+ " max_seq_length = max_seq_length,\n",
553
+ " dtype = dtype,\n",
554
+ " load_in_4bit = load_in_4bit,\n",
555
+ ")"
556
+ ]
557
+ },
558
+ {
559
+ "cell_type": "markdown",
560
+ "metadata": {},
561
+ "source": [
562
+ "## 3.2 Recreate LoRA Structure and Load Weights\n",
563
+ "\n",
564
+ "We need to recreate the same LoRA structure that was used during training, then load the saved weights."
565
+ ]
566
+ },
567
+ {
568
+ "cell_type": "code",
569
+ "execution_count": null,
570
+ "metadata": {},
571
+ "outputs": [],
572
+ "source": [
573
+ "# Recreate LoRA layers with the same configuration used during training\n",
574
+ "model = FastLanguageModel.get_peft_model(\n",
575
+ " base_model,\n",
576
+ " r = LORA_R,\n",
577
+ " target_modules = LORA_TARGET_MODULES,\n",
578
+ " lora_alpha = LORA_ALPHA,\n",
579
+ " lora_dropout = LORA_DROPOUT,\n",
580
+ " bias = \"none\",\n",
581
+ " use_gradient_checkpointing = \"unsloth\",\n",
582
+ " random_state = 3407,\n",
583
+ ")\n",
584
+ "\n",
585
+ "print(\"Empty LoRA structure recreated.\")"
586
+ ]
587
+ },
588
+ {
589
+ "cell_type": "code",
590
+ "execution_count": null,
591
+ "metadata": {},
592
+ "outputs": [],
593
+ "source": [
594
+ "# Load the saved LoRA adapter weights\n",
595
+ "model.load_adapter(LORA_ADAPTER_PATH, adapter_name=\"default\")\n",
596
+ "model.set_adapter(\"default\")\n",
597
+ "\n",
598
+ "print(f\"LoRA adapter loaded from: {LORA_ADAPTER_PATH}\")"
599
+ ]
600
+ },
601
+ {
602
+ "cell_type": "markdown",
603
+ "metadata": {},
604
+ "source": [
605
+ "## 3.3 Merge LoRA into Full Model (FP16)\n",
606
+ "\n",
607
+ "Merge the LoRA adapters into the base model to create a standalone FP16 model."
608
+ ]
609
+ },
610
+ {
611
+ "cell_type": "code",
612
+ "execution_count": null,
613
+ "metadata": {},
614
+ "outputs": [],
615
+ "source": [
616
+ "model.save_pretrained_merged(\n",
617
+ " MERGED_MODEL_DIR,\n",
618
+ " tokenizer,\n",
619
+ " save_method=\"merged_16bit\",\n",
620
+ ")\n",
621
+ "\n",
622
+ "print(f\"Merged FP16 model saved at: {MERGED_MODEL_DIR}\")"
623
+ ]
624
+ },
625
+ {
626
+ "cell_type": "markdown",
627
+ "metadata": {},
628
+ "source": [
629
+ "## 3.4 Export to GGUF Format\n",
630
+ "\n",
631
+ "Export to GGUF format for CPU inference (e.g., with llama.cpp, Ollama, GPT4All).\n",
632
+ "\n",
633
+ "Quantization options:\n",
634
+ "- `q8_0` - Fast conversion, high quality\n",
635
+ "- `q4_k_m` - Recommended balance of size and quality\n",
636
+ "- `q5_k_m` - Better quality than q4_k_m"
637
+ ]
638
+ },
639
+ {
640
+ "cell_type": "code",
641
+ "execution_count": null,
642
+ "metadata": {},
643
+ "outputs": [],
644
+ "source": [
645
+ "model.save_pretrained_gguf(\n",
646
+ " GGUF_MODEL_DIR,\n",
647
+ " tokenizer,\n",
648
+ " quantization_method=\"q4_k_m\",\n",
649
+ ")\n",
650
+ "\n",
651
+ "print(f\"GGUF model saved at: {GGUF_MODEL_DIR}\")"
652
+ ]
653
+ },
654
+ {
655
+ "cell_type": "markdown",
656
+ "metadata": {},
657
+ "source": [
658
+ "## 3.5 Upload to HuggingFace"
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "code",
663
+ "execution_count": null,
664
+ "metadata": {},
665
+ "outputs": [],
666
+ "source": [
667
+ "from huggingface_hub import login, HfApi\n",
668
+ "login()"
669
+ ]
670
+ },
671
+ {
672
+ "cell_type": "markdown",
673
+ "metadata": {},
674
+ "source": [
675
+ "### Upload Merged FP16 Model"
676
+ ]
677
+ },
678
+ {
679
+ "cell_type": "code",
680
+ "execution_count": null,
681
+ "metadata": {},
682
+ "outputs": [],
683
+ "source": [
684
+ "api = HfApi()\n",
685
+ "api.upload_folder(\n",
686
+ " folder_path=MERGED_MODEL_DIR,\n",
687
+ " repo_id=HF_REPO_ID,\n",
688
+ " path_in_repo=\"merged-model-fp16\",\n",
689
+ ")\n",
690
+ "print(f\"Merged model uploaded to {HF_REPO_ID}/merged-model-fp16\")"
691
+ ]
692
+ },
693
+ {
694
+ "cell_type": "markdown",
695
+ "metadata": {},
696
+ "source": [
697
+ "### Upload GGUF Model"
698
+ ]
699
+ },
700
+ {
701
+ "cell_type": "code",
702
+ "execution_count": null,
703
+ "metadata": {},
704
+ "outputs": [],
705
+ "source": [
706
+ "api = HfApi()\n",
707
+ "api.upload_folder(\n",
708
+ " folder_path=GGUF_MODEL_DIR,\n",
709
+ " repo_id=HF_REPO_ID,\n",
710
+ " path_in_repo=\"gguf-model\",\n",
711
+ ")\n",
712
+ "print(f\"GGUF model uploaded to {HF_REPO_ID}/gguf-model\")"
713
+ ]
714
+ },
715
+ {
716
+ "cell_type": "markdown",
717
+ "metadata": {},
718
+ "source": [
719
+ "---\n",
720
+ "# PART 4: Inference and Testing\n",
721
+ "---\n",
722
+ "\n",
723
+ "Test your fine-tuned model. This works with the model in memory from either PART 2 or PART 3."
724
+ ]
725
+ },
726
+ {
727
+ "cell_type": "markdown",
728
+ "metadata": {},
729
+ "source": [
730
+ "## 4.1 Basic Inference"
731
+ ]
732
+ },
733
+ {
734
+ "cell_type": "code",
735
+ "execution_count": null,
736
+ "metadata": {},
737
+ "outputs": [],
738
+ "source": [
739
+ "from unsloth.chat_templates import get_chat_template\n",
740
+ "\n",
741
+ "tokenizer = get_chat_template(\n",
742
+ " tokenizer,\n",
743
+ " chat_template = \"llama-3.1\",\n",
744
+ ")\n",
745
+ "FastLanguageModel.for_inference(model)\n",
746
+ "\n",
747
+ "messages = [\n",
748
+ " {\"role\": \"user\", \"content\": \"Continue the fibonacci sequence: 1, 1, 2, 3, 5, 8,\"},\n",
749
+ "]\n",
750
+ "inputs = tokenizer.apply_chat_template(\n",
751
+ " messages,\n",
752
+ " tokenize = True,\n",
753
+ " add_generation_prompt = True,\n",
754
+ " return_tensors = \"pt\",\n",
755
+ ").to(\"cuda\")\n",
756
+ "\n",
757
+ "outputs = model.generate(input_ids = inputs, max_new_tokens = 64, use_cache = True,\n",
758
+ " temperature = 1.5, min_p = 0.1)\n",
759
+ "tokenizer.batch_decode(outputs)"
760
+ ]
761
+ },
762
+ {
763
+ "cell_type": "markdown",
764
+ "metadata": {},
765
+ "source": [
766
+ "## 4.2 Streaming Inference\n",
767
+ "\n",
768
+ "Use TextStreamer to see generation token by token."
769
+ ]
770
+ },
771
+ {
772
+ "cell_type": "code",
773
+ "execution_count": null,
774
+ "metadata": {},
775
+ "outputs": [],
776
+ "source": [
777
+ "FastLanguageModel.for_inference(model)\n",
778
+ "\n",
779
+ "messages = [\n",
780
+ " {\"role\": \"user\", \"content\": \"Explain what machine learning is in simple terms.\"},\n",
781
+ "]\n",
782
+ "inputs = tokenizer.apply_chat_template(\n",
783
+ " messages,\n",
784
+ " tokenize = True,\n",
785
+ " add_generation_prompt = True,\n",
786
+ " return_tensors = \"pt\",\n",
787
+ ").to(\"cuda\")\n",
788
+ "\n",
789
+ "from transformers import TextStreamer\n",
790
+ "text_streamer = TextStreamer(tokenizer, skip_prompt = True)\n",
791
+ "_ = model.generate(input_ids = inputs, streamer = text_streamer, max_new_tokens = 128,\n",
792
+ " use_cache = True, temperature = 1.5, min_p = 0.1)"
793
+ ]
794
+ },
795
+ {
796
+ "cell_type": "markdown",
797
+ "metadata": {},
798
+ "source": [
799
+ "---\n",
800
+ "# Additional Options\n",
801
+ "---"
802
+ ]
803
+ },
804
+ {
805
+ "cell_type": "markdown",
806
+ "metadata": {},
807
+ "source": [
808
+ "## Alternative: Load LoRA from Local Directory for Inference\n",
809
+ "\n",
810
+ "If you saved LoRA adapters and want to load them directly for inference."
811
+ ]
812
+ },
813
+ {
814
+ "cell_type": "code",
815
+ "execution_count": null,
816
+ "metadata": {},
817
+ "outputs": [],
818
+ "source": [
819
+ "if False: # Set to True to run\n",
820
+ " from unsloth import FastLanguageModel\n",
821
+ " model, tokenizer = FastLanguageModel.from_pretrained(\n",
822
+ " model_name = \"lora_model\", # Path to saved LoRA model\n",
823
+ " max_seq_length = max_seq_length,\n",
824
+ " dtype = dtype,\n",
825
+ " load_in_4bit = load_in_4bit,\n",
826
+ " )\n",
827
+ " FastLanguageModel.for_inference(model)"
828
+ ]
829
+ },
830
+ {
831
+ "cell_type": "markdown",
832
+ "metadata": {},
833
+ "source": [
834
+ "## Alternative: Save/Upload with Different Methods"
835
+ ]
836
+ },
837
+ {
838
+ "cell_type": "code",
839
+ "execution_count": null,
840
+ "metadata": {},
841
+ "outputs": [],
842
+ "source": [
843
+ "# Merge to 16bit\n",
844
+ "if False: model.save_pretrained_merged(\"model\", tokenizer, save_method = \"merged_16bit\",)\n",
845
+ "if False: model.push_to_hub_merged(\"hf/model\", tokenizer, save_method = \"merged_16bit\", token = \"\")\n",
846
+ "\n",
847
+ "# Merge to 4bit\n",
848
+ "if False: model.save_pretrained_merged(\"model\", tokenizer, save_method = \"merged_4bit\",)\n",
849
+ "if False: model.push_to_hub_merged(\"hf/model\", tokenizer, save_method = \"merged_4bit\", token = \"\")\n",
850
+ "\n",
851
+ "# Just LoRA adapters\n",
852
+ "if False: model.save_pretrained_merged(\"model\", tokenizer, save_method = \"lora\",)\n",
853
+ "if False: model.push_to_hub_merged(\"hf/model\", tokenizer, save_method = \"lora\", token = \"\")"
854
+ ]
855
+ },
856
+ {
857
+ "cell_type": "markdown",
858
+ "metadata": {},
859
+ "source": [
860
+ "## Alternative: GGUF Export Options"
861
+ ]
862
+ },
863
+ {
864
+ "cell_type": "code",
865
+ "execution_count": null,
866
+ "metadata": {},
867
+ "outputs": [],
868
+ "source": [
869
+ "# Save to 8bit Q8_0\n",
870
+ "if False: model.save_pretrained_gguf(\"model\", tokenizer,)\n",
871
+ "if False: model.push_to_hub_gguf(\"hf/model\", tokenizer, token = \"\")\n",
872
+ "\n",
873
+ "# Save to 16bit GGUF\n",
874
+ "if False: model.save_pretrained_gguf(\"model\", tokenizer, quantization_method = \"f16\")\n",
875
+ "if False: model.push_to_hub_gguf(\"hf/model\", tokenizer, quantization_method = \"f16\", token = \"\")\n",
876
+ "\n",
877
+ "# Save to q4_k_m GGUF\n",
878
+ "if False: model.save_pretrained_gguf(\"model\", tokenizer, quantization_method = \"q4_k_m\")\n",
879
+ "if False: model.push_to_hub_gguf(\"hf/model\", tokenizer, quantization_method = \"q4_k_m\", token = \"\")\n",
880
+ "\n",
881
+ "# Save to multiple GGUF options\n",
882
+ "if False:\n",
883
+ " model.push_to_hub_gguf(\n",
884
+ " \"hf/model\",\n",
885
+ " tokenizer,\n",
886
+ " quantization_method = [\"q4_k_m\", \"q8_0\", \"q5_k_m\",],\n",
887
+ " token = \"\",\n",
888
+ " )"
889
+ ]
890
+ },
891
+ {
892
+ "cell_type": "markdown",
893
+ "metadata": {},
894
+ "source": [
895
+ "---\n",
896
+ "\n",
897
+ "## Resources\n",
898
+ "\n",
899
+ "- [Unsloth GitHub](https://github.com/unslothai/unsloth)\n",
900
+ "- [TRL SFT docs](https://huggingface.co/docs/trl/sft_trainer)\n",
901
+ "- [FineTome-100k Dataset](https://huggingface.co/datasets/mlabonne/FineTome-100k)\n",
902
+ "- [GGUF Quantization Options](https://github.com/unslothai/unsloth/wiki#gguf-quantization-options)"
903
+ ]
904
+ }
905
+ ],
906
+ "metadata": {
907
+ "kernelspec": {
908
+ "display_name": "Python 3",
909
+ "language": "python",
910
+ "name": "python3"
911
+ },
912
+ "language_info": {
913
+ "name": "python",
914
+ "version": "3.10.0"
915
+ }
916
+ },
917
+ "nbformat": 4,
918
+ "nbformat_minor": 4
919
+ }