{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Model Evaluation: Fine-tuned vs Base Model Comparison\n", "\n", "This notebook compares the fine-tuned model against the original `unsloth/Llama-3.2-3B-Instruct` using:\n", "1. **ROUGE scores** comparing generated responses to ground truth\n", "2. **Qualitative examples** - side-by-side comparisons\n", "3. **Response length analysis**" ] }, { "cell_type": "code", "metadata": { "collapsed": false, "scrolled": true }, "source": [ "%%capture\n", "# Install dependencies\n", "%uv pip install unsloth\n", "%uv pip install rouge-score evaluate datasets tqdm" ], "execution_count": 1, "outputs": [] }, { "cell_type": "code", "metadata": { "collapsed": false, "scrolled": true }, "source": [ "from unsloth import FastLanguageModel\n", "from unsloth.chat_templates import get_chat_template, standardize_sharegpt\n", "import torch\n", "import numpy as np\n", "from tqdm import tqdm\n", "from datasets import load_dataset\n", "\n", "# Configuration\n", "max_seq_length = 2048\n", "dtype = \"float16\"\n", "load_in_4bit = True\n", "\n", "BASE_MODEL_NAME = \"unsloth/Llama-3.2-3B-Instruct\"\n", "LORA_ADAPTER_PATH = \"/vol/checkpoint-10688\" # your local folder in Modal\n" ], "execution_count": 2, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\ud83e\udda5 Unsloth: Will patch your computer to enable 2x faster free finetuning.\n", "\ud83e\udda5 Unsloth Zoo will now patch everything to make training faster!\n" ] } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Prepare the Test Dataset\n", "\n", "Using the same splits as during training (10% test set)" ] }, { "cell_type": "code", "metadata": { "collapsed": false, "scrolled": true }, "source": [ "# Load and prepare dataset (same as training)\n", "dataset = load_dataset(\"mlabonne/FineTome-100k\", split=\"train\")\n", "dataset = standardize_sharegpt(dataset)\n", "\n", "# Same splits as training: train+val (90%), test (10%)\n", "train_val_split = dataset.train_test_split(test_size=0.15, seed=42)\n", "test_dataset = train_val_split[\"test\"]\n", "\n", "print(f\"Test set size: {len(test_dataset)} samples\")" ], "execution_count": 3, "outputs": [ { "output_type": "display_data", "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e56d65e8c6ec4db0b7c61258c77a9bd2", "version_minor": 0.0, "version_major": 2.0 }, "text/plain": "README.md: 0%| | 0.00/982 [00:00 0 else 0\n", " print(f\"{metric:<15} {base_score:<20.4f} {ft_score:<20.4f} {improvement:+.2f}%\")\n", "\n", "print(\"=\" * 60)" ], "execution_count": 21, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "============================================================\n", "EVALUATION RESULTS\n", "============================================================\n", "Number of samples evaluated: 100\n", "\n", "------------------------------------------------------------\n", "ROUGE Scores (higher is better)\n", "------------------------------------------------------------\n", "Metric Base Model Fine-tuned Change \n", "------------------------------------------------------------\n", "rouge1 0.4732 0.5323 +12.49%\n", "rouge2 0.2255 0.2849 +26.35%\n", "rougeL 0.2856 0.3521 +23.30%\n", "============================================================\n" ] } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Qualitative Comparison - Side by Side Examples" ] }, { "cell_type": "code", "metadata": { "collapsed": false, "scrolled": true }, "source": [ "num_examples = 10\n", "\n", "for i in range(min(num_examples, len(references))):\n", " print(\"=\" * 80)\n", " print(f\"EXAMPLE {i+1}\")\n", " print(\"=\" * 80)\n", " \n", " last_user_msg = None\n", " for msg in prompts_used[i]:\n", " if msg[\"role\"] == \"user\":\n", " last_user_msg = msg[\"content\"]\n", " \n", " print(f\"USER PROMPT:\\n{last_user_msg[:500]}{'...' if len(str(last_user_msg)) > 500 else ''}\")\n", " print(f\"\\nREFERENCE:\\n{references[i][:500]}{'...' if len(references[i]) > 500 else ''}\")\n", " print(f\"\\nBASE MODEL:\\n{base_predictions[i][:500]}{'...' if len(base_predictions[i]) > 500 else ''}\")\n", " print(f\"\\nFINE-TUNED MODEL:\\n{finetuned_predictions[i][:500]}{'...' if len(finetuned_predictions[i]) > 500 else ''}\")\n", " print()" ], "execution_count": 22, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "================================================================================\n", "EXAMPLE 1\n", "================================================================================\n", "USER PROMPT:\n", "Explain the process of photosynthesis in simple terms and describe its importance for the ecosystem.\n", "\n", "REFERENCE:\n", "Photosynthesis is a process by which plants, algae, and some bacteria convert sunlight, water, and carbon dioxide into sugar and oxygen. This process occurs in the chloroplasts of these organisms. In simple terms, sunlight is absorbed, and its energy is used to break down water and carbon dioxide molecules, which are then reassembled into sugars and oxygen. The sugar provides energy for growth, while oxygen is released into the atmosphere. Photosynthesis is essential for the ecosystem because it...\n", "\n", "BASE MODEL:\n", "**What is Photosynthesis?**\n", "\n", "Photosynthesis is a process by which plants, algae, and some bacteria convert light energy from the sun into chemical energy in the form of glucose (a type of sugar). This process is essential for life on Earth, as it provides energy and organic compounds for plants to grow and thrive.\n", "\n", "**The Process of Photosynthesis:**\n", "\n", "1. **Light absorption**: Plants absorb light energy from the sun through specialized pigments such as chlorophyll.\n", "2. **Water absorption**: Plants ...\n", "\n", "FINE-TUNED MODEL:\n", "Photosynthesis is a process used by plants, algae, and some bacteria to convert sunlight, water, and carbon dioxide into glucose and oxygen. In simple terms, plants use sunlight to make food (glucose) and release oxygen as a byproduct. This process is crucial for the ecosystem as it provides energy and organic compounds for plants to grow, which in turn supports the food chain and maintains the balance of the environment.\n", "\n", "================================================================================\n", "EXAMPLE 2\n", "================================================================================\n", "USER PROMPT:\n", "What is the mathematical foundation for adding or multiplying the same value to both sides of an equation, and why does it maintain the validity of the equation?\n", "\n", "REFERENCE:\n", "The principle of adding or multiplying the same value to both sides of an equation is a fundamental property of equality, known as the \"reflexive property of equality.\" This property states that if a number is equal to another number, then any operation performed on both sides of the equality will preserve that equality. \n", "\n", "For instance, consider the equation $x = 2$, where $x$ represents an unknown value. If we add 3 to both sides, we get $x + 3 = 2 + 3$, which simplifies to $x = 5$. The equalit...\n", "\n", "BASE MODEL:\n", "The mathematical foundation for adding or multiplying the same value to both sides of an equation lies in the properties of equality and the distributive property.\n", "\n", "**Equality Property:**\n", "\n", "The equality property states that if two expressions are equal, then any operation performed on both expressions will result in the same outcome. Mathematically, this can be expressed as:\n", "\n", "a = b \u21d4 (a + c) = (b + c)\n", "\n", "where a and b are the original expressions, and c is any value.\n", "\n", "**Distributive Property:**\n", "\n", "Th...\n", "\n", "FINE-TUNED MODEL:\n", "The mathematical foundation for this operation lies in the properties of equality and the concept of equivalence classes. When you add or multiply the same value to both sides of an equation, you are essentially creating a new equation that is equivalent to the original one. This is because the operations you perform do not change the relationship between the variables in the equation.\n", "\n", "For example, consider the equation $x + 2 = 5$. If you add 3 to both sides of the equation, you get $x + 5 = 8...\n", "\n", "================================================================================\n", "EXAMPLE 3\n", "================================================================================\n", "USER PROMPT:\n", "A pyramid has a rhombus-shaped base with sides of length 9 units and an angle of 120 degrees at one of its corners. The pyramid's height is 7 units. What is the surface area of the pyramid?\n", "\n", "REFERENCE:\n", "The base of the pyramid is a rhombus with sides of length 9 units and an angle of 120 degrees at one of its corners. The height of the pyramid is 7 units.\n", "\n", "To find the surface area of the pyramid, we need to find the area of the base and the area of each of the four triangular faces.\n", "\n", "The area of the base is given by the formula:\n", "\n", "Area of base = (1/2) * d1 * d2 * sin(theta)\n", "\n", "where d1 and d2 are the lengths of the diagonals of the rhombus and theta is the angle between the diagonals.\n", "\n", "Since the d...\n", "\n", "BASE MODEL:\n", "To find the surface area of the pyramid, we need to calculate the area of the base and the area of the four triangular faces, then add them together.\n", "\n", "The base of the pyramid is a rhombus with sides of length 9 units. Since the angle at one of its corners is 120 degrees, we can use trigonometry to find the length of the diagonals.\n", "\n", "The diagonals of a rhombus bisect each other at right angles, so we can use the Pythagorean theorem to find the length of the diagonals:\n", "\n", "Diagonal 1 = 2 * sin(60) * 9...\n", "\n", "FINE-TUNED MODEL:\n", "The surface area of the pyramid is 173.5 square units.\n", "\n", "Explanation:\n", "To find the surface area of the pyramid, we need to calculate the area of the base (which is a rhombus) and the area of the four triangular faces.\n", "\n", "1. Area of the base (rhombus):\n", "The area of a rhombus can be found using the formula: Area = (1/2) * d1 * d2 * sin(\u03b8), where d1 and d2 are the lengths of the diagonals, and \u03b8 is the angle between them.\n", "\n", "Given that the sides of the rhombus are 9 units and the angle at one corner is 12...\n", "\n", "================================================================================\n", "EXAMPLE 4\n", "================================================================================\n", "USER PROMPT:\n", "How do gravitational waves affect the curvature of spacetime and what is the mathematical expression that describes it?\n", "\n", "REFERENCE:\n", "Gravitational waves are ripples in the fabric of spacetime caused by the acceleration of massive objects, such as merging black holes or neutron stars. These waves propagate through spacetime at the speed of light, carrying energy and information about the events that generated them. They affect the curvature of spacetime by causing it to stretch and compress as the waves pass through.\n", "\n", "The mathematical expression that describes the effect of gravitational waves on the curvature of spacetime is ...\n", "\n", "BASE MODEL:\n", "Gravitational waves are ripples in the fabric of spacetime that are produced by the acceleration of massive objects, such as black holes or neutron stars. These waves cause a disturbance in the curvature of spacetime, which can be described using the Einstein field equations.\n", "\n", "The Einstein field equations describe the relationship between the curvature of spacetime (represented by the Ricci tensor, R\u03bc\u03bd) and the mass-energy density of the objects causing the curvature. The equations are:\n", "\n", "R\u03bc\u03bd - 1...\n", "\n", "FINE-TUNED MODEL:\n", "Gravitational waves are ripples in the fabric of spacetime caused by the acceleration of massive objects, such as merging black holes or neutron stars. These waves propagate through spacetime at the speed of light and carry energy away from the source. The curvature of spacetime is affected by the presence of these waves, which causes a disturbance in the geometry of spacetime.\n", "\n", "The mathematical expression that describes the curvature of spacetime due to gravitational waves is given by the Einst...\n", "\n", "================================================================================\n", "EXAMPLE 5\n", "================================================================================\n", "USER PROMPT:\n", "Write Python code to solve the task:\n", "We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.\n", "\n", "For example, `greenbin` is an anagram of `beginner`. As seen here, when the same character occurs multiple times, that character must be used that number of times.\n", "\n", "Given are N strings s_1, s_2, \\ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Fin...\n", "\n", "REFERENCE:\n", "Step 1: We need to find the number of pairs of strings that are anagrams of each other.\n", "Step 2: We can start by creating a function to check if two strings are anagrams.\n", "Step 3: Then we can create a loop to compare each string with every other string in the list.\n", "Step 4: We should also consider the number of pairs we need to check and how we can reduce this number by half since the problem is symmetrical.\n", "Step 5: We should also utilize a dictionary to count the frequency of each character a...\n", "\n", "BASE MODEL:\n", "def count_anagrams(N, strings):\n", " anagrams = {}\n", " for s in strings:\n", " sorted_s = ''.join(sorted(s))\n", " if sorted_s in anagrams:\n", " anagrams[sorted_s].append(s)\n", " else:\n", " anagrams[sorted_s] = [s]\n", " count = 0\n", " for v in anagrams.values():\n", " count += len(v) * (len(v) - 1) // 2\n", " return count\n", "\n", "N = int(input())\n", "strings = [input() for _ in range(N)]\n", "print(count_anagrams(N, strings))\n", "\n", "FINE-TUNED MODEL:\n", "Step 1: The problem requires us to find the number of pairs of integers i, j (1 \u2264 i < j \u2264 N) such that s_i is an anagram of s_j.\n", "Step 2: We can start by creating a function to check if two strings are anagrams of each other.\n", "Step 3: Then, we can iterate through the input strings and count the number of pairs that satisfy the condition.\n", "Step 4: We also need to consider the constraints and the input format.\n", "Step 5: We can use a dictionary to store the count of each string and then calculate t...\n", "\n", "================================================================================\n", "EXAMPLE 6\n", "================================================================================\n", "USER PROMPT:\n", "Write a short story about a computer that can predict the future.\n", "\n", "REFERENCE:\n", "Once upon a time, there was a computer named Oracle. Oracle was no ordinary computer \u2013 it had the unique ability to predict the future. It was the invention of a brilliant computer scientist, who had spent years creating and perfecting its software. The scientist had a vision to make the world a better place by preventing misfortunes and tragedies before they occurred.\n", "\n", "At first, people were skeptical of Oracle's abilities. But soon, the computer proved its worth. It predicted natural disasters ...\n", "\n", "BASE MODEL:\n", "**The Oracle of Code**\n", "\n", "In a small, cluttered laboratory, a team of brilliant engineers had been working on a top-secret project for years. Their goal was to create a computer that could predict the future. The team had tried countless approaches, from complex algorithms to advanced machine learning techniques, but nothing seemed to yield the desired results.\n", "\n", "That was until they stumbled upon an unusual approach. Instead of focusing on predicting specific events, they decided to create a comput...\n", "\n", "FINE-TUNED MODEL:\n", "Once upon a time, in a small town nestled in the heart of a dense forest, there was a computer that possessed a unique gift. It could predict the future.\n", "\n", "The computer, named \"Chrono,\" was created by a brilliant scientist who had spent years studying the mysteries of time. He had designed Chrono to be able to analyze vast amounts of data and make predictions based on that analysis.\n", "\n", "At first, Chrono's predictions were nothing more than guesses. But as time went on, the computer's accuracy began ...\n", "\n", "================================================================================\n", "EXAMPLE 7\n", "================================================================================\n", "USER PROMPT:\n", "What measures can we implement to reduce the negative impact of frequent air travel on the environment, particularly in relation to carbon emissions, atmospheric pollution, and depletion of natural resources? How can we maintain the benefits and convenience of air travel while also ensuring its sustainability in the long term? Additionally, how can we consider the impact of air travel on global temperature, biodiversity loss, and social equity when developing sustainable air travel practices?\n", "\n", "REFERENCE:\n", "There are several measures that can be implemented to reduce the negative impact of frequent air travel on the environment:\n", "1. Promote the use of alternative modes of transportation, such as trains and buses, for shorter distances.\n", "2. Encourage the use of more fuel-efficient aircraft and engines, as well as the use of alternative fuels like biofuels.\n", "3. Implement carbon offsetting programs, where airlines invest in projects that reduce carbon emissions, such as renewable energy or reforestation....\n", "\n", "BASE MODEL:\n", "To reduce the negative impact of frequent air travel on the environment, several measures can be implemented:\n", "\n", "1. **Carbon offsetting**: Calculate and offset carbon emissions from flights by investing in projects that reduce greenhouse gas emissions, such as reforestation or renewable energy projects.\n", "2. **Fuel efficiency**: Improve aircraft fuel efficiency through more efficient engines, aerodynamic designs, and alternative fuels, such as biofuels or electric propulsion.\n", "3. **Sustainable aviati...\n", "\n", "FINE-TUNED MODEL:\n", "There are several measures that can be implemented to reduce the negative impact of frequent air travel on the environment. Here are some of them:\n", "1. Carbon offsetting: This involves investing in projects that reduce greenhouse gas emissions, such as reforestation or renewable energy projects. Airlines can offer carbon offsetting options to passengers, and passengers can choose to offset their carbon emissions from flights.\n", "2. Fuel efficiency: Airlines can improve fuel efficiency by using more e...\n", "\n", "================================================================================\n", "EXAMPLE 8\n", "================================================================================\n", "USER PROMPT:\n", "How does the Earth's structure impact our lives and the environment?\n", "\n", "REFERENCE:\n", "The Earth's structure plays a vital role in supporting life and influencing various natural phenomena. Here are three key ways in which the Earth's interior affects us:\n", "\n", "1) The Earth's large metallic core generates a strong magnetic field, which serves as a shield against harmful solar radiation and high-energy particles. This protection is crucial for the survival of living organisms on the planet.\n", "\n", "2) The core's heat, resulting from radioactive decay, drives convection currents in the mantle. ...\n", "\n", "BASE MODEL:\n", "The Earth's structure has a profound impact on our lives and the environment. Here are some ways in which the Earth's structure affects us:\n", "\n", "1. **Climate and Weather Patterns**: The Earth's structure, including its rotation, orbit, and atmospheric circulation, influences the climate and weather patterns. This, in turn, affects the distribution of heat, moisture, and precipitation around the globe, impacting agriculture, water resources, and human settlements.\n", "2. **Geological Activity**: The Eart...\n", "\n", "FINE-TUNED MODEL:\n", "The Earth's structure plays a significant role in shaping our lives and the environment. Here are some ways in which it impacts us:\n", "\n", "1. Climate: The Earth's structure, including its atmosphere, oceans, and landmasses, determines the climate we experience. The atmosphere traps heat, which in turn affects the temperature of the Earth's surface. The oceans and landmasses also play a role in regulating the climate.\n", "\n", "2. Natural Resources: The Earth's structure is responsible for the availability of n...\n", "\n", "================================================================================\n", "EXAMPLE 9\n", "================================================================================\n", "USER PROMPT:\n", "There are 20 hands in Peter\u2019s class, not including his. Assume every student in the class has 2 arms and x hands. There are 11 students in Peter's class including him. What is the value of unknown variable x? What is the value of unknown variable x?\n", "\n", "REFERENCE:\n", "To solve this problem, we need to determine the value of x, which represents the number of hands each student in Peter's class has.\n", "We know that there are 11 students in Peter's class, including him. Therefore, there are 11 - 1 = 10 other students in the class.\n", "We also know that each student has 2 arms, which means they have 2 hands each.\n", "So, the total number of hands in the class, not including Peter's, is 10 students * 2 hands per student = 20 hands.\n", "Since each student has x hands, we can set ...\n", "\n", "BASE MODEL:\n", "To find the value of x, we need to know the total number of hands in the class. Since there are 20 hands not including Peter's, and Peter also has hands, we need to add Peter's hands to the total.\n", "\n", "There are 11 students in the class, including Peter. Since every student has 2 arms and x hands, the total number of hands in the class is:\n", "\n", "11 students * 2 arms/student * x hands/arm = 22x hands\n", "\n", "However, we know that there are 20 hands not including Peter's. Since Peter also has hands, we can set up...\n", "\n", "FINE-TUNED MODEL:\n", "1. The problem states that there are 20 hands in Peter's class, not including his. This means that the total number of hands in the class, including Peter's, is 20 + 1 = 21.\n", "2. The problem also states that every student in the class has 2 arms and x hands. This means that the total number of hands in the class, including Peter's, is 2 * (number of students) + x * (number of students).\n", "3. We know that there are 11 students in Peter's class, including him. This means that the total number of hands...\n", "\n", "================================================================================\n", "EXAMPLE 10\n", "================================================================================\n", "USER PROMPT:\n", "Solve the following math problem step-by-step.\n", "Simplify your answer as much as possible. Present your final answer as \\boxed{Your Answer}.\n", "A coin is flipped eight times, and the sequence of heads and tails occurring is recorded. How many distinct sequences are possible?\n", "\n", "REFERENCE:\n", "Step 1: To calculate the number of distinct sequences possible, we need to determine the number of options for each flip of the coin and multiply them together.\n", "Step 2: Since there are two possible outcomes for each flip (heads or tails), there are 2 options for each flip.\n", "Step 3: Since there are 8 flips in total, we need to multiply the number of options for each flip together to find the total number of distinct sequences.\n", "Step 4: So, the solution is 2^8 = 256 distinct sequences.\n", "\n", "Answer:\n", "\\box...\n", "\n", "BASE MODEL:\n", "To solve this problem, we need to consider the number of possible outcomes for each coin flip. Since a coin can land either heads or tails, there are 2 possible outcomes for each flip.\n", "\n", "Since the coin is flipped 8 times, we need to multiply the number of possible outcomes for each flip together to get the total number of distinct sequences.\n", "\n", "Here's the step-by-step calculation:\n", "\n", "1. Number of possible outcomes for the first flip: 2\n", "2. Number of possible outcomes for the second flip: 2\n", "3. Number o...\n", "\n", "FINE-TUNED MODEL:\n", "Step 1: To solve this problem, we need to understand the concept of permutations and how it applies to the given scenario.\n", "Step 2: The coin is flipped eight times, and the sequence of heads and tails occurring is recorded. This means that for each flip, there are two possible outcomes - heads or tails.\n", "Step 3: Since the coin is flipped eight times, we have a total of 8 flips, and each flip has 2 possible outcomes. This leads us to the total number of distinct sequences possible.\n", "Step 4: The ...\n", "\n" ] } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Response Length Analysis" ] }, { "cell_type": "code", "metadata": { "collapsed": false, "scrolled": true }, "source": [ "base_lengths = [len(p.split()) for p in base_predictions]\n", "ft_lengths = [len(p.split()) for p in finetuned_predictions]\n", "ref_lengths = [len(r.split()) for r in references]\n", "\n", "print(\"Response Length Analysis (words)\")\n", "print(\"-\" * 50)\n", "print(f\"{'Metric':<25} {'Base':<12} {'Fine-tuned':<12} {'Reference':<12}\")\n", "print(\"-\" * 50)\n", "print(f\"{'Mean length':<25} {np.mean(base_lengths):<12.1f} {np.mean(ft_lengths):<12.1f} {np.mean(ref_lengths):<12.1f}\")\n", "print(f\"{'Median length':<25} {np.median(base_lengths):<12.1f} {np.median(ft_lengths):<12.1f} {np.median(ref_lengths):<12.1f}\")\n", "print(f\"{'Std deviation':<25} {np.std(base_lengths):<12.1f} {np.std(ft_lengths):<12.1f} {np.std(ref_lengths):<12.1f}\")" ], "execution_count": 24, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Response Length Analysis (words)\n", "--------------------------------------------------\n", "Metric Base Fine-tuned Reference \n", "--------------------------------------------------\n", "Mean length 165.0 155.7 216.3 \n", "Median length 176.0 165.5 199.0 \n", "Std deviation 42.5 53.6 109.4 \n" ] } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9. Save Results" ] }, { "cell_type": "code", "metadata": { "collapsed": false, "scrolled": true }, "source": [ "import json\n", "from datetime import datetime\n", "\n", "results = {\n", " \"timestamp\": datetime.now().isoformat(),\n", " \"base_model\": BASE_MODEL_NAME,\n", " \"finetuned_model\": LORA_ADAPTER_PATH,\n", " \"num_samples\": len(references),\n", " \"metrics\": {\n", " \"base_model\": base_rouge,\n", " \"finetuned_model\": finetuned_rouge,\n", " },\n", " \"response_lengths\": {\n", " \"base_mean\": float(np.mean(base_lengths)),\n", " \"finetuned_mean\": float(np.mean(ft_lengths)),\n", " \"reference_mean\": float(np.mean(ref_lengths)),\n", " }\n", "}\n", "\n", "with open(\"evaluation_results.json\", \"w\") as f:\n", " json.dump(results, f, indent=2)\n", "\n", "print(\"Results saved to evaluation_results.json\")\n", "print(json.dumps(results, indent=2))" ], "execution_count": 25, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Results saved to evaluation_results.json\n", "{\n", " \"timestamp\": \"2025-12-02T10:09:18.235153\",\n", " \"base_model\": \"unsloth/Llama-3.2-3B-Instruct\",\n", " \"finetuned_model\": \"/vol/checkpoint-10688\",\n", " \"num_samples\": 100,\n", " \"metrics\": {\n", " \"base_model\": {\n", " \"rouge1\": 0.4732268736349978,\n", " \"rouge2\": 0.22545052802537063,\n", " \"rougeL\": 0.2855963588727634\n", " },\n", " \"finetuned_model\": {\n", " \"rouge1\": 0.5323317587648463,\n", " \"rouge2\": 0.28485583536195763,\n", " \"rougeL\": 0.35213159677059536\n", " }\n", " },\n", " \"response_lengths\": {\n", " \"base_mean\": 165.0,\n", " \"finetuned_mean\": 155.68,\n", " \"reference_mean\": 216.27\n", " }\n", "}\n" ] } ] } ], "metadata": { "kernelspec": { "display_name": "Python", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 5 }