{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "546b6c6d-f949-4387-9c41-6989223911f8",
   "metadata": {},
   "source": [
    "# Initializing weights with LoftQ by replacing LoRA weights in-place"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d041ecb4-6957-467e-8f3e-d4a12c674e9f",
   "metadata": {},
   "source": [
    "This notebook shows how to apply [LoftQ](https://arxiv.org/abs/2310.08659) initialization on our QLoRA model.\n",
    "\n",
    "In short, the idea behind LoftQ is the following. When we use QLoRA, i.e. we quantize the base model with bitsandbytes to save memory, and then train LoRA weights on top of this base model, we expect a certain performance gap. This is partly due to the fact that quantization is onyl an approximation of the \"real\" weights and thus introduces a quantization error. By default, LoRA weights are initialized such that they are a no-op at the start of the training. However, we can instead initialize them so that they minimize the quantization error. This is the idea behind LoftQ.\n",
    "\n",
    "Note that this only influences the initialization of the model. Everything that follows stays the same as always."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90d5420f-de32-42fa-8792-247f60e3647d",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a2c69b7c-c922-405f-aae1-ccc4f6911155",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "22be0432-8798-44a2-9014-d929525e3059",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f087ce0f-71b4-45ec-b2f9-197677bbc1ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "from peft import get_peft_model, LoraConfig, replace_lora_weights_loftq"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63fdf18e-4ac4-409e-8475-88147cf85067",
   "metadata": {},
   "source": [
    "## Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "af14bd0a-597e-446c-800b-619fc0599ee0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_mae(x, y):\n",
    "    return (x - y).abs().mean()\n",
    "\n",
    "\n",
    "def get_mse(x, y):\n",
    "    return torch.pow(x - y, 2).mean()\n",
    "\n",
    "\n",
    "def error_report(x, y):\n",
    "    mae = get_mae(x, y)\n",
    "    mse = get_mse(x, y)\n",
    "    print(\n",
    "        f\"Mean absolute error: {mae:>8.5f}\\n\"\n",
    "        f\"Mean squared error:  {mse:>8.5f}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bc01a5f-7ee8-400f-8e80-3f2b7df29882",
   "metadata": {},
   "source": [
    "## Base model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdc447d9-2f4f-4d0f-afdb-1cf5c4237321",
   "metadata": {},
   "source": [
    "First, let's load a base model and calculate some logits. These logits are the baseline, i.e. we try to match their values as best as possible. We only need these logits for demonstration purposes. In practice, it is not necessary to load the non-quantized weights to apply LoftQ initialization.\n",
    "\n",
    "**Note**: We have to choose a model with a `model.safetensors` file. As PyTorch checkpoints (pickle) cannot be loaded lazily, we have to use [safetensors](https://huggingface.co/docs/safetensors/index). If those don't exist for your model, save the pretrained model as a safetensors file using `safe_pretrained` and pass the model path to `replace_lora_weights_loftq`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0cb29074-d180-4fdc-8a47-27d2b9857264",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_id = \"bigscience/bloomz-560m\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e7ddd6a2-04dd-42ec-9f48-100a3946ae04",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(model_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1f5b27db-51cc-41da-a21d-049ff747a149",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(model_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "51548b6a-945c-4797-b02a-0e3fc77d1242",
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"\"\"Beautiful is better than ugly.\n",
    "Explicit is better than implicit.\n",
    "Simple is better than complex.\n",
    "Complex is better than complicated.\n",
    "Flat is better than nested.\n",
    "Sparse is better than dense.\n",
    "Readability counts.\n",
    "Special cases aren't special enough to break the rules.\n",
    "Although practicality beats purity.\n",
    "Errors should never pass silently.\n",
    "Unless explicitly silenced.\n",
    "In the face of ambiguity, refuse the temptation to guess.\n",
    "There should be one-- and preferably only one --obvious way to do it.\n",
    "Although that way may not be obvious at first unless you're Dutch.\n",
    "Now is better than never.\n",
    "Although never is often better than *right* now.\n",
    "If the implementation is hard to explain, it's a bad idea.\n",
    "If the implementation is easy to explain, it may be a good idea.\n",
    "Namespaces are one honking great idea -- let's do more of those!\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "ce72d923-5283-48ba-96ef-7f859309ad84",
   "metadata": {},
   "outputs": [],
   "source": [
    "inputs = tokenizer(s.splitlines(), return_tensors=\"pt\", padding=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bfe54cb-76ef-4981-ba25-3e544d264c62",
   "metadata": {},
   "source": [
    "Our baseline logits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "04bebcaa-3a05-4621-9a03-e25de72fa27c",
   "metadata": {},
   "outputs": [],
   "source": [
    "logits_base = model(**inputs).logits"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa9c9001-8ade-422d-92f8-bcafa50917c7",
   "metadata": {},
   "source": [
    "## Normal LoRA model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8024390b-736a-4b21-848b-aa4f30951d51",
   "metadata": {},
   "source": [
    "Now we load the model quantized with bitsandbytes. For now, only 4bit is supported."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "01d1912a-646e-42d2-8292-6702b77d1948",
   "metadata": {},
   "outputs": [],
   "source": [
    "bnb_config = BitsAndBytesConfig(\n",
    "    load_in_4bit=True,\n",
    "    bnb_4bit_use_double_quant=True,\n",
    "    bnb_4bit_compute_dtype=torch.float16,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b1218717-4db4-48ce-978d-c05dc190fa91",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "`low_cpu_mem_usage` was None, now set to True since model is quantized.\n"
     ]
    }
   ],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0b4e4c5-3932-4d9a-9457-41a05f24d556",
   "metadata": {},
   "source": [
    "Next we create a LoRA model using PEFT and compute the logits of that model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4741bce0-cd2b-4f05-a50c-4f9e56b43e72",
   "metadata": {},
   "outputs": [],
   "source": [
    "lora_config = LoraConfig(task_type=\"CAUSAL_LM\", target_modules=\"all-linear\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "cf55cc48-b55d-4806-b6ab-e9b8035ed526",
   "metadata": {},
   "outputs": [],
   "source": [
    "peft_model = get_peft_model(model, lora_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f2f11e25-4a1e-485b-be4c-65aec62ac207",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      ".../bitsandbytes/nn/modules.py:391: UserWarning: Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference or training speed.\n",
      "  warnings.warn('Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference or training speed.')\n"
     ]
    }
   ],
   "source": [
    "logits_lora = peft_model(**inputs).logits"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bc0cde7-0b9f-4305-ac0e-e3a6d2cfa401",
   "metadata": {},
   "source": [
    "Let's check the influence of the quantization error on our logits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "6f404c0d-f428-4923-9122-7b830410f089",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mean absolute error:  3.61113\n",
      "Mean squared error:  36.53259\n"
     ]
    }
   ],
   "source": [
    "error_report(logits_base, logits_lora)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58c437e1-4fae-4a2f-9c42-ada6bedb9a4d",
   "metadata": {},
   "source": [
    "## LoftQ"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1af05376-c8b0-48ec-8d80-7d7f4d32bbd7",
   "metadata": {},
   "source": [
    "Next, let's use LoftQ initialization and see if it helps reduce the error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "890e6108-3f02-469c-9e7d-f2144448227c",
   "metadata": {},
   "outputs": [],
   "source": [
    "replace_lora_weights_loftq(peft_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b452db0e-a510-42d3-bef5-f567186e26c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "logits_loftq = peft_model(**inputs).logits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "456dc564-f268-4cf3-9d59-a6942d3733ad",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mean absolute error:  3.24111\n",
      "Mean squared error:  31.13725\n"
     ]
    }
   ],
   "source": [
    "error_report(logits_base, logits_loftq)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ddf9e0f-3f78-426c-be59-77c6481674ec",
   "metadata": {},
   "source": [
    "We can see that LoftQ initialization helped a little bit, but the difference is not huge."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0dd344f2-249c-4fe9-8357-7fe3bcd1e82f",
   "metadata": {},
   "source": [
    "## LoftQ with callback"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2fd7dd5-88b3-40b8-95c2-3f3895d8093d",
   "metadata": {},
   "source": [
    "To help with this, let's write a small callback function and pass it to `replace_lora_weights_loftq`. What this function does is that each time one weight is being replaced with LoftQ-initialized weights, we perform a test if the quantization error is actually reduced. If it it is not, we roll back the replacement. This way, we keep only those replacements that improve the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "1f882802-22b7-4969-919e-120b1f2893d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "`low_cpu_mem_usage` was None, now set to True since model is quantized.\n"
     ]
    }
   ],
   "source": [
    "# Since PEFT has modified the base model, we should reload it\n",
    "model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c6438363-b66e-4507-8667-5a6df379a03f",
   "metadata": {},
   "outputs": [],
   "source": [
    "peft_model = get_peft_model(model, lora_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "7b93d082-0fcb-4b20-982e-c1aaf0c71d13",
   "metadata": {},
   "outputs": [],
   "source": [
    "current_mse = float(\"inf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "e22eb18d-b06e-47fe-91ba-ff34cbf62f60",
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_callback(model, module_name):\n",
    "    \"\"\"Callable to replace weights with LoFTQ if the mse is lower than the current best one.\"\"\"\n",
    "    global current_mse\n",
    "\n",
    "    logits = model(**inputs).logits\n",
    "    mse = get_mse(logits_base, logits)\n",
    "    if mse < current_mse:\n",
    "        current_mse = mse\n",
    "        print(f\"MSE improved for module {module_name}\")\n",
    "        return True\n",
    "    print(f\"MSE did not improve for module {module_name}\")\n",
    "    return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "44ee90d1-e15a-4740-a39d-ebf9e7adb79c",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MSE improved for module transformer.h.0.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.0.self_attention.dense\n",
      "MSE improved for module transformer.h.0.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.0.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.1.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.1.self_attention.dense\n",
      "MSE did not improve for module transformer.h.1.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.1.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.2.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.2.self_attention.dense\n",
      "MSE improved for module transformer.h.2.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.2.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.3.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.3.self_attention.dense\n",
      "MSE improved for module transformer.h.3.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.3.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.4.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.4.self_attention.dense\n",
      "MSE improved for module transformer.h.4.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.4.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.5.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.5.self_attention.dense\n",
      "MSE improved for module transformer.h.5.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.5.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.6.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.6.self_attention.dense\n",
      "MSE improved for module transformer.h.6.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.6.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.7.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.7.self_attention.dense\n",
      "MSE did not improve for module transformer.h.7.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.7.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.8.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.8.self_attention.dense\n",
      "MSE improved for module transformer.h.8.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.8.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.9.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.9.self_attention.dense\n",
      "MSE did not improve for module transformer.h.9.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.9.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.10.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.10.self_attention.dense\n",
      "MSE did not improve for module transformer.h.10.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.10.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.11.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.11.self_attention.dense\n",
      "MSE did not improve for module transformer.h.11.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.11.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.12.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.12.self_attention.dense\n",
      "MSE improved for module transformer.h.12.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.12.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.13.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.13.self_attention.dense\n",
      "MSE did not improve for module transformer.h.13.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.13.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.14.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.14.self_attention.dense\n",
      "MSE did not improve for module transformer.h.14.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.14.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.15.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.15.self_attention.dense\n",
      "MSE did not improve for module transformer.h.15.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.15.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.16.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.16.self_attention.dense\n",
      "MSE improved for module transformer.h.16.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.16.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.17.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.17.self_attention.dense\n",
      "MSE improved for module transformer.h.17.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.17.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.18.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.18.self_attention.dense\n",
      "MSE did not improve for module transformer.h.18.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.18.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.19.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.19.self_attention.dense\n",
      "MSE improved for module transformer.h.19.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.19.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.20.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.20.self_attention.dense\n",
      "MSE did not improve for module transformer.h.20.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.20.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.21.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.21.self_attention.dense\n",
      "MSE did not improve for module transformer.h.21.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.21.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.22.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.22.self_attention.dense\n",
      "MSE improved for module transformer.h.22.mlp.dense_h_to_4h\n",
      "MSE improved for module transformer.h.22.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.23.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.23.self_attention.dense\n",
      "MSE improved for module transformer.h.23.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.23.mlp.dense_4h_to_h\n"
     ]
    }
   ],
   "source": [
    "replace_lora_weights_loftq(peft_model, callback=my_callback)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "e31adc81-a090-49b2-90f6-9906743c76ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "logits_loftq_callback = peft_model(**inputs).logits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "7c640092-1f26-48be-bea4-487511205440",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mean absolute error:  1.79576\n",
      "Mean squared error:   8.47075\n"
     ]
    }
   ],
   "source": [
    "error_report(logits_base, logits_loftq_callback)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1896857e-3d87-44a9-887f-90c765bc8d91",
   "metadata": {},
   "source": [
    "We can see that applying LoftQ with the help of the callback reduced the error quite significantly."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8eaf86cf-4fb4-455d-ab07-892591564303",
   "metadata": {},
   "source": [
    "## Applying LoftQ multiple times"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70836a75-5c6d-4b7b-9175-f395aef8383b",
   "metadata": {},
   "source": [
    "It is possible to run `replace_lora_weights_loftq` multiple times on the same model when using the callback."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "8e5ee38c-007c-4c75-9248-005d94b19445",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MSE did not improve for module transformer.h.0.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.0.self_attention.dense\n",
      "MSE did not improve for module transformer.h.0.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.0.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.1.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.1.self_attention.dense\n",
      "MSE did not improve for module transformer.h.1.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.1.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.2.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.2.self_attention.dense\n",
      "MSE did not improve for module transformer.h.2.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.2.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.3.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.3.self_attention.dense\n",
      "MSE did not improve for module transformer.h.3.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.3.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.4.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.4.self_attention.dense\n",
      "MSE did not improve for module transformer.h.4.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.4.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.5.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.5.self_attention.dense\n",
      "MSE did not improve for module transformer.h.5.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.5.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.6.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.6.self_attention.dense\n",
      "MSE did not improve for module transformer.h.6.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.6.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.7.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.7.self_attention.dense\n",
      "MSE did not improve for module transformer.h.7.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.7.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.8.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.8.self_attention.dense\n",
      "MSE did not improve for module transformer.h.8.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.8.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.9.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.9.self_attention.dense\n",
      "MSE did not improve for module transformer.h.9.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.9.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.10.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.10.self_attention.dense\n",
      "MSE improved for module transformer.h.10.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.10.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.11.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.11.self_attention.dense\n",
      "MSE did not improve for module transformer.h.11.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.11.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.12.self_attention.query_key_value\n",
      "MSE improved for module transformer.h.12.self_attention.dense\n",
      "MSE did not improve for module transformer.h.12.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.12.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.13.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.13.self_attention.dense\n",
      "MSE did not improve for module transformer.h.13.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.13.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.14.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.14.self_attention.dense\n",
      "MSE did not improve for module transformer.h.14.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.14.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.15.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.15.self_attention.dense\n",
      "MSE did not improve for module transformer.h.15.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.15.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.16.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.16.self_attention.dense\n",
      "MSE did not improve for module transformer.h.16.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.16.mlp.dense_4h_to_h\n",
      "MSE improved for module transformer.h.17.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.17.self_attention.dense\n",
      "MSE did not improve for module transformer.h.17.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.17.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.18.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.18.self_attention.dense\n",
      "MSE did not improve for module transformer.h.18.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.18.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.19.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.19.self_attention.dense\n",
      "MSE did not improve for module transformer.h.19.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.19.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.20.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.20.self_attention.dense\n",
      "MSE did not improve for module transformer.h.20.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.20.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.21.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.21.self_attention.dense\n",
      "MSE did not improve for module transformer.h.21.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.21.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.22.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.22.self_attention.dense\n",
      "MSE did not improve for module transformer.h.22.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.22.mlp.dense_4h_to_h\n",
      "MSE did not improve for module transformer.h.23.self_attention.query_key_value\n",
      "MSE did not improve for module transformer.h.23.self_attention.dense\n",
      "MSE did not improve for module transformer.h.23.mlp.dense_h_to_4h\n",
      "MSE did not improve for module transformer.h.23.mlp.dense_4h_to_h\n"
     ]
    }
   ],
   "source": [
    "replace_lora_weights_loftq(peft_model, callback=my_callback)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "2abe2702-9510-4814-b5f2-63140a102c17",
   "metadata": {},
   "outputs": [],
   "source": [
    "logits_loftq_callback_twice = peft_model(**inputs).logits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "e908de14-01f9-4fdc-91b5-61118a3ce6cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mean absolute error:  1.76357\n",
      "Mean squared error:   8.33938\n"
     ]
    }
   ],
   "source": [
    "error_report(logits_base, logits_loftq_callback_twice)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b8b09fe-d369-4444-b6e2-cd514e775637",
   "metadata": {},
   "source": [
    "There are further gains, but they are not very big."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
