File size: 31,233 Bytes
302920f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
{
 "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://huggingface.co/papers/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
}