File size: 103,431 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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
#!/usr/bin/env python3

# coding=utf-8
# Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import re
import unittest
from copy import deepcopy

import pytest
import torch
from diffusers import StableDiffusionPipeline
from parameterized import parameterized
from torch import nn
from transformers import (
    AutoModel,
    AutoModelForCausalLM,
    AutoModelForSeq2SeqLM,
    AutoModelForSequenceClassification,
    BitsAndBytesConfig,
)
from transformers.pytorch_utils import Conv1D

from peft import (
    AdaptionPromptConfig,
    IA3Config,
    LoHaConfig,
    LoraConfig,
    PeftModel,
    PromptTuningConfig,
    VeraConfig,
    get_layer_status,
    get_model_status,
    get_peft_model,
)
from peft.tuners.lora.layer import LoraLayer
from peft.tuners.tuners_utils import (
    BaseTuner,
    BaseTunerLayer,
    _maybe_include_all_linear_layers,
    check_target_module_exists,
    inspect_matched_modules,
)
from peft.tuners.tuners_utils import (
    _find_minimal_target_modules as find_minimal_target_modules,
)
from peft.utils import INCLUDE_LINEAR_LAYERS_SHORTHAND, ModulesToSaveWrapper, infer_device
from peft.utils.constants import DUMMY_MODEL_CONFIG, MIN_TARGET_MODULES_FOR_OPTIMIZATION

from .testing_utils import hub_online_once, require_bitsandbytes, require_non_cpu


# Implements tests for regex matching logic common for all BaseTuner subclasses, and
# tests for correct behaviour with different config kwargs for BaseTuners (Ex: feedforward for IA3, etc) and
# tests for utility function to include all linear layers

REGEX_TEST_CASES = [
    # tuple of
    # 1. key
    # 2. target_modules
    # 3. layers_to_transform
    # 4. layers_pattern
    # 5. expected result
    # some basic examples
    ("", [], None, None, False),
    ("", ["foo"], None, None, False),
    ("foo", [], None, None, False),
    ("foo", ["foo"], None, None, True),
    ("foo", ["bar"], None, None, False),
    ("foo", ["foo", "bar"], None, None, True),
    # with regex
    ("foo", "foo", None, None, True),
    ("foo", ".*oo", None, None, True),
    ("foo", "fo.*", None, None, True),
    ("foo", ".*bar.*", None, None, False),
    ("foobar", ".*oba.*", None, None, True),
    # with layers_to_transform
    ("foo.bar.1.baz", ["baz"], [1], ["bar"], True),
    ("foo.bar.1.baz", ["baz"], [0], ["bar"], False),
    ("foo.bar.1.baz", ["baz"], [2], ["bar"], False),
    ("foo.bar.10.baz", ["baz"], [0], ["bar"], False),
    ("foo.bar.10.baz", ["baz"], [1], ["bar"], False),
    ("foo.bar.1.baz", ["baz"], [0, 1, 2], ["bar"], True),
    ("foo.bar.1.baz", ["baz", "spam"], [1], ["bar"], True),
    ("foo.bar.1.baz", ["baz", "spam"], [0, 1, 2], ["bar"], True),
    # empty layers_pattern
    ("foo.whatever.1.baz", ["baz"], [1], [], True),
    ("foo.whatever.1.baz", ["baz"], [0], [], False),
    ("foo.whatever.1.baz", ["baz"], [1], "", True),
    ("foo.whatever.1.baz", ["baz"], [0], "", False),
    ("foo.whatever.1.baz", ["baz"], [1], None, True),
    ("foo.whatever.1.baz", ["baz"], [0], None, False),
    # some realistic examples: transformers model
    ("transformer.h.1.attn.attention.q_proj.foo", ["q_proj"], None, [], False),
    ("transformer.h.1.attn.attention.q_proj", [], None, [], False),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj"], None, [], True),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj", "v_proj"], None, [], True),
    ("transformer.h.1.attn.attention.resid_dropout", ["q_proj", "v_proj"], None, [], False),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj"], [1], ["h"], True),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj"], [0], ["h"], False),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj"], [2], ["h"], False),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj"], [0, 1, 2], ["h"], True),
    ("transformer.h.1.attn.attention.q_proj", ["q_proj", "v_proj"], [0, 1, 2], ["h"], True),
    ("foo.bar.q_proj", ["q_proj"], None, [], True),
    ("foo.bar.1.baz", ["baz"], [1], ["foo"], False),
    # other corner cases. For ex, below is a case where layers_pattern
    # is one of the target nn.modules
    ("foo.bar.1.baz", ["baz"], [1], ["baz"], False),
    # here, layers_pattern is 'bar', but only keys that contain '.bar' are valid.
    ("bar.1.baz", ["baz"], [1], ["bar"], False),
    ("foo.bar.001.baz", ["baz"], [1], ["bar"], True),
    ("foo.bar.1.spam.2.baz", ["baz"], [1], ["bar"], True),
    ("foo.bar.2.spam.1.baz", ["baz"], [1], ["bar"], False),
    # some realistic examples: module using nn.Sequential
    # for the below test case, key should contain '.blocks' to be valid, because of how layers_pattern is matched
    ("blocks.1.weight", ["weight"], [1], ["blocks"], False),
    ("blocks.1.bias", ["weight"], [1], ["blocks"], False),
    ("mlp.blocks.1.weight", ["weight"], [1], ["blocks"], True),
    ("mlp.blocks.1.bias", ["weight"], [1], ["blocks"], False),
]

MAYBE_INCLUDE_ALL_LINEAR_LAYERS_TEST_CASES = [
    # model_name, model_type, initial_target_modules, expected_target_modules
    # test for a causal Llama model
    (
        "HuggingFaceH4/tiny-random-LlamaForCausalLM",
        "causal",
        INCLUDE_LINEAR_LAYERS_SHORTHAND,
        ["k_proj", "v_proj", "q_proj", "o_proj", "down_proj", "up_proj", "gate_proj"],
    ),
    # test for a Llama model without the LM head
    (
        "HuggingFaceH4/tiny-random-LlamaForCausalLM",
        "base",
        INCLUDE_LINEAR_LAYERS_SHORTHAND,
        ["k_proj", "v_proj", "q_proj", "o_proj", "down_proj", "up_proj", "gate_proj"],
    ),
    # test for gpt2 with Conv1D layers
    ("hf-internal-testing/tiny-random-gpt2", "causal", INCLUDE_LINEAR_LAYERS_SHORTHAND, ["c_attn", "c_proj", "c_fc"]),
    # test for T5 model
    (
        "hf-internal-testing/tiny-random-t5",
        "seq2seq",
        INCLUDE_LINEAR_LAYERS_SHORTHAND,
        ["k", "q", "v", "o", "wi", "wo"],
    ),
    # test for GPTNeoX. output module list should exclude classification head - which is named as "embed_out" instead of the usual "lm_head" for GPTNeoX
    (
        "hf-internal-testing/tiny-random-GPTNeoXForCausalLM",
        "causal",
        INCLUDE_LINEAR_LAYERS_SHORTHAND,
        ["query_key_value", "dense", "dense_h_to_4h", "dense_4h_to_h"],
    ),
]

# tests for a few args that should remain unchanged
MAYBE_INCLUDE_ALL_LINEAR_LAYERS_TEST_INTERNALS = [
    # initial_target_modules, expected_target_modules
    (["k_proj"], ["k_proj"]),
    # test with target_modules as None
    (None, None),
    # test with target_modules as a regex expression
    (".*(q_proj|v_proj)$", ".*(q_proj|v_proj)$"),
]

BNB_QUANTIZATIONS = [("4bit",), ("8bit",)]
BNB_TEST_CASES = [(x + y) for x in MAYBE_INCLUDE_ALL_LINEAR_LAYERS_TEST_CASES for y in BNB_QUANTIZATIONS]


class PeftCustomKwargsTester(unittest.TestCase):
    r"""
    Test if the PeftModel is instantiated with correct behaviour for custom kwargs. This includes:
    - test if regex matching works correctly
    - test if adapters handle custom kwargs the right way e.g. IA3 for `feedforward_modules`

    """

    transformers_class_map = {"causal": AutoModelForCausalLM, "seq2seq": AutoModelForSeq2SeqLM, "base": AutoModel}

    @parameterized.expand(REGEX_TEST_CASES)
    def test_regex_matching_valid(self, key, target_modules, layers_to_transform, layers_pattern, expected_result):
        # We use a LoRA Config for testing, but the regex matching function is common for all BaseTuner subclasses.
        # example model_id for config initialization. key is matched only against the target_modules given, so this can be any model
        model_id = "peft-internal-testing/tiny-OPTForCausalLM-lora"
        config = LoraConfig(
            base_model_name_or_path=model_id,
            target_modules=target_modules,
            layers_pattern=layers_pattern,
            layers_to_transform=layers_to_transform,
        )
        actual_result = bool(check_target_module_exists(config, key))
        assert actual_result == expected_result

    def test_module_matching_lora(self):
        # peft models that have a module matching method to inspect the matching modules to allow
        # users to easily debug their configuration. Here we only test a single case, not all possible combinations of
        # configs that could exist. This is okay as the method calls `check_target_module_exists` internally, which
        # has been extensively tested above.
        model_id = "hf-internal-testing/tiny-random-BloomForCausalLM"
        with hub_online_once(model_id):
            model = AutoModel.from_pretrained(model_id)
        # by default, this model matches query_key_value
        config = LoraConfig()
        peft_model = get_peft_model(model, config)

        output = inspect_matched_modules(peft_model)  # inspects default adapter for peft_model
        matched = output["matched"]
        expected = [
            "h.0.self_attention.query_key_value",
            "h.1.self_attention.query_key_value",
            "h.2.self_attention.query_key_value",
            "h.3.self_attention.query_key_value",
            "h.4.self_attention.query_key_value",
        ]
        assert matched == expected  # module lists should match exactly

        # no overlap with matched modules
        unmatched = output["unmatched"]
        for key in expected:
            assert key not in unmatched

    def test_feedforward_matching_ia3(self):
        model_id = "hf-internal-testing/tiny-random-T5ForConditionalGeneration"
        with hub_online_once(model_id):
            model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
        # simple example for just one t5 block for testing
        config_kwargs = {
            "target_modules": ".*encoder.*block.0.*(SelfAttention|EncDecAttention|DenseReluDense).(k|q|v|wo|wi)$",
            "feedforward_modules": ["wo", "wi"],
        }
        config = IA3Config(base_model_name_or_path=model_id, **config_kwargs)
        peft_model = get_peft_model(model, config)
        output = inspect_matched_modules(peft_model)  # inspects default adapter for peft_model
        matched = output["matched"]
        expected = [
            "encoder.block.0.layer.0.SelfAttention.q",
            "encoder.block.0.layer.0.SelfAttention.k",
            "encoder.block.0.layer.0.SelfAttention.v",
            "encoder.block.0.layer.1.DenseReluDense.wi",
            "encoder.block.0.layer.1.DenseReluDense.wo",
        ]
        expected_feedforward = [
            "encoder.block.0.layer.1.DenseReluDense.wi",
            "encoder.block.0.layer.1.DenseReluDense.wo",
        ]
        assert matched == expected  # not required since we do similar checks above, but just to be sure
        module_dict = dict(model.named_modules())
        for key in matched:
            module = module_dict[key]
            if key in expected_feedforward:
                assert module.is_feedforward
            else:  # other IA3 modules should not be marked as feedforward
                assert not module.is_feedforward

    @parameterized.expand(MAYBE_INCLUDE_ALL_LINEAR_LAYERS_TEST_CASES)
    def test_maybe_include_all_linear_layers_lora(
        self, model_id, model_type, initial_target_modules, expected_target_modules
    ):
        with hub_online_once(model_id):
            model = self.transformers_class_map[model_type].from_pretrained(model_id)
        config_cls = LoraConfig
        self._check_match_with_expected_target_modules(
            model_id, model, config_cls, initial_target_modules, expected_target_modules
        )

    @parameterized.expand(BNB_TEST_CASES)
    @require_non_cpu
    @require_bitsandbytes
    def test_maybe_include_all_linear_layers_lora_bnb(
        self, model_id, model_type, initial_target_modules, expected_target_modules, quantization
    ):
        if quantization == "4bit":
            config_kwargs = {"quantization_config": BitsAndBytesConfig(load_in_4bit=True)}
        elif quantization == "8bit":
            config_kwargs = {"quantization_config": BitsAndBytesConfig(load_in_8bit=True)}

        with hub_online_once(model_id):
            model = self.transformers_class_map[model_type].from_pretrained(
                model_id, device_map="auto", **config_kwargs
            )
        config_cls = LoraConfig
        self._check_match_with_expected_target_modules(
            model_id, model, config_cls, initial_target_modules, expected_target_modules
        )

    def _check_match_with_expected_target_modules(
        self, model_id, model, config_cls, initial_target_modules, expected_target_modules
    ):
        """
        Helper function for the test for `_maybe_include_all_linear_layers`
        """
        actual_config = config_cls(base_model_name_or_path=model_id, target_modules=initial_target_modules)
        expected_config = config_cls(base_model_name_or_path=model_id, target_modules=expected_target_modules)
        model_copy = deepcopy(model)
        actual_model = get_peft_model(model, peft_config=actual_config)
        expected_model = get_peft_model(model_copy, peft_config=expected_config)
        expected_model_module_dict = dict(expected_model.named_modules())
        # compare the two models and assert that all layers are of the same type
        for name, actual_module in actual_model.named_modules():
            expected_module = expected_model_module_dict[name]
            assert type(actual_module) is type(expected_module)

    def test_maybe_include_all_linear_layers_ia3_loha(self):
        model_id, initial_target_modules, expected_target_modules = (
            "HuggingFaceH4/tiny-random-LlamaForCausalLM",
            INCLUDE_LINEAR_LAYERS_SHORTHAND,
            ["k_proj", "v_proj", "q_proj", "o_proj", "down_proj", "up_proj", "gate_proj"],
        )
        with hub_online_once(model_id):
            model_ia3 = AutoModelForCausalLM.from_pretrained(model_id)
        model_loha = deepcopy(model_ia3)
        config_classes = [IA3Config, LoHaConfig]
        models = [model_ia3, model_loha]
        for config_cls, model in zip(config_classes, models):
            self._check_match_with_expected_target_modules(
                model_id, model, config_cls, initial_target_modules, expected_target_modules
            )

    @parameterized.expand(MAYBE_INCLUDE_ALL_LINEAR_LAYERS_TEST_INTERNALS)
    def test_maybe_include_all_linear_layers_internals(self, initial_target_modules, expected_target_modules):
        model_id = "HuggingFaceH4/tiny-random-LlamaForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        config = LoraConfig(base_model_name_or_path=model_id, target_modules=initial_target_modules)
        new_config = _maybe_include_all_linear_layers(config, model)
        if isinstance(expected_target_modules, list):
            # assert that expected and actual target_modules have the same items
            assert set(new_config.target_modules) == set(expected_target_modules)
        else:
            assert new_config.target_modules == expected_target_modules

    def test_maybe_include_all_linear_layers_diffusion(self):
        model_id = "hf-internal-testing/tiny-sd-pipe"
        with hub_online_once(model_id):
            model = StableDiffusionPipeline.from_pretrained(model_id)
        config = LoraConfig(base_model_name_or_path=model_id, target_modules="all-linear")

        # all linear layers should be converted
        num_linear = sum(isinstance(module, (nn.Linear, Conv1D)) for module in model.unet.modules())
        model.unet = get_peft_model(model.unet, config)
        num_lora = sum(isinstance(module, LoraLayer) for module in model.unet.modules())
        assert num_lora == num_linear

    def test_maybe_include_all_linear_does_not_target_classifier_head(self):
        # See issue 2027
        # Ensure that if a SEQ_CLS model is being used with target_modules="all-linear", the classification head is not
        # targeted by the adapter layer.
        model_id = "HuggingFaceH4/tiny-random-LlamaForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForSequenceClassification.from_pretrained(model_id, num_labels=10)
        # sanity check
        assert isinstance(model.score, nn.Linear)

        num_linear = sum(isinstance(module, (nn.Linear, Conv1D)) for module in model.modules())

        config = LoraConfig(task_type="SEQ_CLS", target_modules="all-linear")
        model = get_peft_model(model, config)
        assert isinstance(model.base_model.score, ModulesToSaveWrapper)

        # the bug was that these were lora.Linear instances
        assert isinstance(model.base_model.score.original_module, nn.Linear)
        assert isinstance(model.base_model.score.modules_to_save["default"], nn.Linear)

        # ensure that all but one linear layer was targeted by LoRA
        num_lora = sum(isinstance(module, LoraLayer) for module in model.modules())
        assert num_lora == num_linear - 1

    @parameterized.expand(MAYBE_INCLUDE_ALL_LINEAR_LAYERS_TEST_CASES)
    def test_all_linear_nested_targets_correct_layers(
        self, model_id, model_type, initial_target_modules, expected_target_modules
    ):
        # See 2390
        # Ensure that if adapter layers are already applied, we don't get nested adapter layers (e.g. LoRA targeting the
        # lora_A, lora_B layers)
        with hub_online_once(model_id):
            model = self.transformers_class_map[model_type].from_pretrained(model_id)
        config_cls = LoraConfig
        self._check_match_with_expected_target_modules(
            model_id, model, config_cls, initial_target_modules, expected_target_modules
        )
        # re-use the same model, i.e. the adapter is already applied
        self._check_match_with_expected_target_modules(
            model_id, model, config_cls, initial_target_modules, expected_target_modules
        )

    def test_add_second_adapter_with_all_linear_works(self):
        # See 2390 Similar test to test_all_linear_nested_targets_correct_layers above, but using add_adapter instead of
        # calling get_peft_model in an already adapted model
        model_id = "HuggingFaceH4/tiny-random-LlamaForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)

        # important: don't reuse the first config, since config.target_modules will be overwritten, which would make the
        # test pass trivially.
        config0 = LoraConfig(target_modules=INCLUDE_LINEAR_LAYERS_SHORTHAND)
        config1 = LoraConfig(target_modules=INCLUDE_LINEAR_LAYERS_SHORTHAND)

        model = get_peft_model(model, config0)
        model.add_adapter(adapter_name="other", peft_config=config1)

        # both configs should result in the same target modules being chosen (remember that config.target_modules will
        # be replaced by the actual set of target_modules)
        assert config0.target_modules == config1.target_modules

        for layer in model.base_model.model.model.layers:
            projs = (
                layer.self_attn.q_proj,
                layer.self_attn.v_proj,
                layer.self_attn.k_proj,
                layer.mlp.gate_proj,
                layer.mlp.up_proj,
                layer.mlp.down_proj,
            )
            for proj in projs:
                # the targted layer itself, which in the base model was the nn.Linear layer, is now a LoraLayer
                assert isinstance(proj, LoraLayer)
                # all children of that layer are still normal nn.Linear layers
                assert isinstance(proj.base_layer, nn.Linear)
                assert isinstance(proj.lora_A["default"], nn.Linear)
                assert isinstance(proj.lora_B["default"], nn.Linear)
                assert isinstance(proj.lora_A["other"], nn.Linear)
                assert isinstance(proj.lora_B["other"], nn.Linear)


class MLP(nn.Module):
    def __init__(self, bias=True):
        super().__init__()
        self.lin0 = nn.Linear(10, 20, bias=bias)
        self.relu = nn.ReLU()
        self.drop = nn.Dropout(0.5)
        self.lin1 = nn.Linear(20, 2, bias=bias)
        self.sm = nn.LogSoftmax(dim=-1)


class TestTargetedModuleNames(unittest.TestCase):
    """Check that the attribute targeted_module_names is correctly set.

    This checks LoRA and IA³, but this should be sufficient, testing all other tuners is not necessary.
    """

    def test_one_targeted_module_regex(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules="lin0"))
        assert model.targeted_module_names == ["lin0"]

    def test_two_targeted_module_regex(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules="lin.*"))
        assert model.targeted_module_names == ["lin0", "lin1"]

    def test_one_targeted_module_list(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules=["lin0"]))
        assert model.targeted_module_names == ["lin0"]

    def test_two_targeted_module_list(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules=["lin0", "lin1"]))
        assert model.targeted_module_names == ["lin0", "lin1"]

    def test_ia3_targeted_module_regex(self):
        model = MLP()
        model = get_peft_model(model, IA3Config(target_modules=".*lin.*", feedforward_modules=".*lin.*"))
        assert model.targeted_module_names == ["lin0", "lin1"]

    def test_ia3_targeted_module_list(self):
        model = MLP()
        model = get_peft_model(model, IA3Config(target_modules=["lin0", "lin1"], feedforward_modules=["lin0", "lin1"]))
        assert model.targeted_module_names == ["lin0", "lin1"]

    def test_realistic_example(self):
        model_id = "hf-internal-testing/tiny-random-BloomForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        config = LoraConfig(task_type="CAUSAL_LM")
        model = get_peft_model(model, config)
        expected = [
            f"transformer.h.{i}.self_attention.query_key_value" for i in range(len(model.base_model.transformer.h))
        ]
        assert model.targeted_module_names == expected


class TestTargetedParameterNames(unittest.TestCase):
    """Check that the attribute targeted_parameter_names (via target_parameters) is correctly set.

    This is only implemented for LoRA. Regex matching is currently not implemented.
    """

    def test_one_targeted_parameters_list(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_parameters=["lin0.weight"]))
        assert model.targeted_parameter_names == ["lin0.weight"]

    def test_two_targeted_parameters_list(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_parameters=["lin0.weight", "lin1.weight"]))
        assert model.targeted_parameter_names == ["lin0.weight", "lin1.weight"]

    def test_realistic_example(self):
        model_id = "trl-internal-testing/tiny-random-LlamaForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        config = LoraConfig(target_modules=[], task_type="CAUSAL_LM", target_parameters=["v_proj.weight"])
        model = get_peft_model(model, config)
        expected = [
            f"model.layers.{i}.self_attn.v_proj.weight" for i in range(len(model.base_model.model.model.layers))
        ]
        assert model.targeted_parameter_names == expected


class TestExcludedModuleNames(unittest.TestCase):
    """Check that the attribute exclude_module is correctly set.

    This checks LoRA and IA³, but this should be sufficient, testing all other tuners is not necessary.
    """

    def test_two_excluded_module_regex(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules=("lin.*"), exclude_modules="lin0"))
        assert model.targeted_module_names == ["lin1"]

    def test_two_excluded_module_list(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules=["lin0", "lin1"], exclude_modules="lin0"))
        assert model.targeted_module_names == ["lin1"]

    def test_multiple_excluded_modules_list(self):
        model = MLP()
        model = get_peft_model(model, LoraConfig(target_modules=["lin0", "lin1"], exclude_modules=["lin0"]))
        assert model.targeted_module_names == ["lin1"]

    def test_ia3_two_excluded_module_regex(self):
        model = MLP()
        model = get_peft_model(
            model, IA3Config(target_modules=".*lin.*", feedforward_modules=".*lin.*", exclude_modules="lin0")
        )
        assert model.targeted_module_names == ["lin1"]

    def test_ia3_multiple_excluded_modules_list(self):
        model = MLP()
        model = get_peft_model(
            model, IA3Config(target_modules=["lin0", "lin1"], feedforward_modules=".*lin.*", exclude_modules=["lin1"])
        )
        assert model.targeted_module_names == ["lin0"]

    def test_all_modules_excluded(self):
        model = MLP()
        with pytest.raises(ValueError, match="All modules were excluded"):
            get_peft_model(
                model,
                LoraConfig(
                    target_modules=["lin0", "lin1", "relu", "drop", "sm"],
                    exclude_modules=["lin0", "lin1", "relu", "drop", "sm"],
                ),
            )

    def test_no_modules_matched(self):
        model = MLP()
        with pytest.raises(ValueError, match="Target modules .* not found in the base model"):
            get_peft_model(model, LoraConfig(target_modules=["non_existent_module"]))

    def test_some_modules_excluded_some_unmatched(self):
        model = MLP()
        with pytest.raises(ValueError, match="No modules were targeted for adaptation"):
            get_peft_model(model, LoraConfig(target_modules=["lin0", "non_existent_module"], exclude_modules=["lin0"]))

    def test_exclude_modules_not_used(self):
        model = MLP()
        with pytest.warns(UserWarning, match="You have passed exclude_modules=.* but no modules were excluded"):
            get_peft_model(model, LoraConfig(target_modules=["lin1"], exclude_modules=["non_existent_module"]))

    def test_realistic_example(self):
        model_id = "hf-internal-testing/tiny-random-BloomForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        config = LoraConfig(task_type="CAUSAL_LM", exclude_modules="transformer.h.2.self_attention.query_key_value")
        model = get_peft_model(model, config)
        expected = [
            f"transformer.h.{i}.self_attention.query_key_value"
            for i in range(len(model.base_model.transformer.h))
            if i != 2
        ]
        assert model.targeted_module_names == expected


class TestModelAndLayerStatus:
    """Check the methods `get_layer_status` and `get_model_status`.`

    Note that we only test LoRA here but the same logic should work for other tuner types (if they support the
    corresponding features like merging).

    """

    torch_device = infer_device()

    @pytest.fixture
    def small_base_model_cls(self):
        class SmallModel(nn.Module):
            def __init__(self):
                super().__init__()
                self.lin0 = nn.Linear(10, 10)
                self.lin1 = nn.Linear(10, 10)

        return SmallModel

    @pytest.fixture
    def small_base_emb_model_cls(self):
        class SmallEmbModel(nn.Module):
            def __init__(self):
                super().__init__()
                self.lin0 = nn.Linear(10, 10)
                self.emb = nn.Embedding(10, 10)

        return SmallEmbModel

    @pytest.fixture
    def small_model(self, small_base_model_cls):
        config = LoraConfig(target_modules="lin0")
        return get_peft_model(small_base_model_cls(), config)

    @pytest.fixture
    def large_model(self):
        class LargeModel(nn.Module):
            def __init__(self):
                super().__init__()
                self.lin0 = nn.Linear(10, 10)
                self.conv0 = nn.Conv2d(3, 10, 3)
                self.emb0 = nn.Embedding(10, 10)
                self.lin1 = nn.Linear(10, 10)
                self.conv1 = nn.Conv2d(3, 10, 3)
                self.emb1 = nn.Embedding(10, 10)

        config0 = LoraConfig(target_modules=["lin0", "conv1", "emb0"])
        config1 = LoraConfig(target_modules=["lin0", "lin1"], r=16)
        model = get_peft_model(LargeModel(), config0)
        model.add_adapter("other", config1)
        return model

    ################
    # layer status #
    ################

    def test_layer_names_small(self, small_model):
        layer_status = small_model.get_layer_status()
        expected = ["model.lin0"]
        assert [status.name for status in layer_status] == expected

    def test_layer_names_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = sorted([status.name for status in layer_status])
        expected = ["model.conv1", "model.emb0", "model.lin0", "model.lin1"]
        assert result == expected

    def test_module_type_small(self, small_model):
        layer_status = small_model.get_layer_status()
        assert [status.module_type for status in layer_status] == ["lora.Linear"]

    def test_module_type_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = sorted([status.module_type for status in layer_status])
        expected = ["lora.Conv2d", "lora.Embedding", "lora.Linear", "lora.Linear"]
        assert result == expected

    def test_enabled_small(self, small_model):
        layer_status = small_model.get_layer_status()
        assert [status.enabled for status in layer_status] == [True]

    def test_enabled_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = [status.enabled for status in layer_status]
        expected = [True, True, True, True]
        assert result == expected

    def test_enabled_irregular(self, large_model):
        # this is an invalid state, but we should still test it
        # disable a single layer
        for module in large_model.modules():
            if isinstance(module, BaseTunerLayer):
                module.enable_adapters(False)
                break

        layer_status = large_model.get_layer_status()
        result = [status.enabled for status in layer_status]
        expected = [False, True, True, True]
        assert result == expected

    def test_active_adapters_small(self, small_model):
        layer_status = small_model.get_layer_status()
        assert [status.active_adapters for status in layer_status] == [["default"]]

    def test_active_adapters_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = [status.active_adapters for status in layer_status]
        # note: as currently implemented, the active adapter can be an adapter that does not exist on this specific
        # layer, for instance, layer 3 (i.e. index 2) only has the "other" adapter but "default" is still shown as the
        # active adapter
        expected = [["default"], ["default"], ["default"], ["default"]]
        assert result == expected

        # switch to "other"
        large_model.set_adapter("other")
        layer_status = large_model.get_layer_status()
        result = [status.active_adapters for status in layer_status]
        expected = [["other"], ["other"], ["other"], ["other"]]

    def test_merge_adapters_small(self, small_model):
        layer_status = small_model.get_layer_status()
        assert [status.merged_adapters for status in layer_status] == [[]]
        assert [status.available_adapters for status in layer_status] == [["default"]]

        # now merge "default"
        small_model.merge_adapter(["default"])
        layer_status = small_model.get_layer_status()
        assert [status.merged_adapters for status in layer_status] == [["default"]]
        assert [status.available_adapters for status in layer_status] == [["default"]]

    def test_merge_adapters_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = [status.merged_adapters for status in layer_status]
        assert result == [[], [], [], []]

        # now merge "default"
        large_model.merge_adapter(["default"])
        layer_status = large_model.get_layer_status()
        result = [status.merged_adapters for status in layer_status]
        # default is on layer 0, 1, and 3
        assert result == [["default"], ["default"], [], ["default"]]

        # now merge "other"
        large_model.unmerge_adapter()
        large_model.merge_adapter(["other"])
        layer_status = large_model.get_layer_status()
        result = [status.merged_adapters for status in layer_status]
        # other is on layer 0 and 2
        assert result == [["other"], [], ["other"], []]

        # now merge both
        large_model.merge_adapter(["default", "other"])
        layer_status = large_model.get_layer_status()
        result = [status.merged_adapters for status in layer_status]
        # default is on layer 0, 1, and 3, other is on layer 0 and 2
        assert result == [["other", "default"], ["default"], ["other"], ["default"]]

    def test_requires_grad_small(self, small_model):
        layer_status = small_model.get_layer_status()
        assert [status.requires_grad for status in layer_status] == [{"default": True}]

    def test_requires_grad_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = [status.requires_grad for status in layer_status]
        # default is on layer 0, 1, and 3, other is on layer 0 and 2
        expected = [{"default": True, "other": False}, {"default": True}, {"other": False}, {"default": True}]
        assert result == expected

        # now activate "other"
        large_model.set_adapter("other")
        layer_status = large_model.get_layer_status()
        result = [status.requires_grad for status in layer_status]
        expected = [{"default": False, "other": True}, {"default": False}, {"other": True}, {"default": False}]
        assert result == expected

        # change requires grad, is now inconsistent with active/inactive adapter
        large_model.set_requires_grad("default", requires_grad=True)
        large_model.set_requires_grad("other", requires_grad=False)
        layer_status = large_model.get_layer_status()
        result = [status.requires_grad for status in layer_status]
        expected = [{"default": True, "other": False}, {"default": True}, {"other": False}, {"default": True}]
        assert result == expected

    def test_requires_grad_irregular(self, large_model):
        # inject an embedding layer with requires_grad=False
        # this is an invalid state, but we should still test it
        lora_embedding_A = nn.Parameter(torch.zeros(10, 10))
        lora_embedding_B = nn.Parameter(torch.zeros(10, 10))
        lora_embedding_A.requires_grad = False
        lora_embedding_B.requires_grad = False
        large_model.base_model.model.lin0.lora_embedding_A["default"] = lora_embedding_A
        large_model.base_model.model.lin0.lora_embedding_B["default"] = lora_embedding_B

        layer_status = large_model.get_layer_status()
        result = [status.requires_grad for status in layer_status]
        expected = [{"default": "irregular", "other": False}, {"default": True}, {"other": False}, {"default": True}]
        assert result == expected

    def test_available_adapters_small(self, small_model):
        layer_status = small_model.get_layer_status()
        result = [status.available_adapters for status in layer_status]
        expected = [["default"]]
        assert result == expected

    def test_available_adapters_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = [status.available_adapters for status in layer_status]
        expected = [["default", "other"], ["default"], ["other"], ["default"]]
        assert result == expected

    def test_devices_all_cpu_small(self, small_model):
        layer_status = small_model.get_layer_status()
        result = [status.devices for status in layer_status]
        expected = [{"default": ["cpu"]}]
        assert result == expected

    def test_devices_all_cpu_large(self, large_model):
        layer_status = large_model.get_layer_status()
        result = [status.devices for status in layer_status]
        expected = [
            {"default": ["cpu"], "other": ["cpu"]},
            {"default": ["cpu"]},
            {"other": ["cpu"]},
            {"default": ["cpu"]},
        ]
        assert result == expected

    def test_with_modules_to_save(self, small_base_model_cls):
        # check that modules_to_save are correctly reported in layer status
        model = small_base_model_cls()
        config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
        model = get_peft_model(model, config)
        layer_status = model.get_layer_status()

        assert len(layer_status) == 2
        status = layer_status[1]  # for modules_to_save

        assert status.name == "model.lin1"
        assert status.module_type == "ModulesToSaveWrapper"
        assert status.enabled is True
        assert status.active_adapters == ["default"]
        assert status.merged_adapters == []
        assert status.available_adapters == ["default"]
        assert status.requires_grad == {"default": True}
        assert status.devices == {"default": ["cpu"]}

    def test_with_trainable_tokens(self, small_base_emb_model_cls):
        # check that trainable_token_indices are correctly reported in layer status
        model = small_base_emb_model_cls()
        config = LoraConfig(target_modules=["lin0"], trainable_token_indices={"emb": [0, 1, 2]})
        model = get_peft_model(model, config)
        layer_status = model.get_layer_status()

        assert len(layer_status) == 2
        status = layer_status[1]  # for trainable tokens

        assert status.name == "model.emb.token_adapter"
        assert status.module_type == "TrainableTokensLayer"
        assert status.enabled is True
        assert status.active_adapters == ["default"]
        assert status.merged_adapters == []
        assert status.available_adapters == ["default"]
        assert status.requires_grad == {"default": True}
        assert status.devices == {"default": ["cpu"]}

    @require_non_cpu
    def test_devices_all_gpu_large(self, large_model):
        large_model.to(self.torch_device)
        layer_status = large_model.get_layer_status()
        result = [status.devices for status in layer_status]
        expected = [
            {"default": [self.torch_device], "other": [self.torch_device]},
            {"default": [self.torch_device]},
            {"other": [self.torch_device]},
            {"default": [self.torch_device]},
        ]
        assert result == expected

    @require_non_cpu
    def test_devices_cpu_and_gpu_large(self, large_model):
        # move the embedding layer to GPU
        large_model.model.lin0.lora_A["default"] = large_model.model.lin0.lora_A["default"].to(self.torch_device)
        layer_status = large_model.get_layer_status()
        result = [status.devices for status in layer_status]
        expected = [
            {"default": ["cpu", self.torch_device], "other": ["cpu"]},
            {"default": ["cpu"]},
            {"other": ["cpu"]},
            {"default": ["cpu"]},
        ]
        assert result == expected

    def test_target_parameters(self, large_model):
        # don't check each attribute, just the relevant ones
        # first remove the normal LoRA layers
        large_model = large_model.merge_and_unload()
        config = LoraConfig(target_parameters=["lin0.weight", "lin1.weight"])
        large_model = get_peft_model(large_model, config)
        layer_status = large_model.get_layer_status()
        assert [status.name for status in layer_status] == ["model.lin0", "model.lin1"]
        assert [status.module_type for status in layer_status] == ["lora.ParamWrapper"] * 2

    def test_target_parameters_and_target_modules(self, large_model):
        # don't check each attribute, just the relevant ones
        # first remove the normal LoRA layers
        large_model = large_model.merge_and_unload()
        config = LoraConfig(target_parameters=["lin0.weight"], target_modules=["lin1"])
        large_model = get_peft_model(large_model, config)
        layer_status = large_model.get_layer_status()
        assert [status.name for status in layer_status] == ["model.lin0", "model.lin1"]
        assert [status.module_type for status in layer_status] == ["lora.ParamWrapper", "lora.Linear"]

    ################
    # model status #
    ################

    def test_base_model_type_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.base_model_type == "SmallModel"

    def test_base_model_type_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.base_model_type == "LargeModel"

    def test_base_model_type_transformers_automodel(self):
        # ensure that this also works with transformers AutoModels
        model_id = "google/flan-t5-small"
        with hub_online_once(model_id):
            model = AutoModel.from_pretrained(model_id)
        model = get_peft_model(model, LoraConfig())
        model_status = model.get_model_status()
        assert model_status.base_model_type == "T5Model"

    def test_adapter_model_type_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.adapter_model_type == "LoraModel"

    def test_adapter_model_type_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.adapter_model_type == "LoraModel"

    def test_peft_types_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.peft_types == {"default": "LORA"}

    def test_peft_types_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.peft_types == {"default": "LORA", "other": "LORA"}

    def test_nb_params_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.trainable_params == 160
        assert model_status.total_params == 380

    def test_nb_params_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.trainable_params == 616
        assert model_status.total_params == 2236

    def test_num_adapter_layers_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.num_adapter_layers == 1

    def test_num_adapter_layers_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.num_adapter_layers == 4

    def test_model_enabled_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.enabled is True

    def test_model_enabled_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.enabled is True

    def test_model_disabled_small(self, small_model):
        small_model.disable_adapter_layers()
        model_status = small_model.get_model_status()
        assert model_status.enabled is False

    def test_model_disabled_large(self, large_model):
        large_model.disable_adapter_layers()
        model_status = large_model.get_model_status()
        assert model_status.enabled is False

    def test_model_enabled_irregular(self, large_model):
        # this is an invalid state, but we should still test it
        # disable a single layer
        for module in large_model.modules():
            if isinstance(module, BaseTunerLayer):
                module.enable_adapters(False)
                break

        model_status = large_model.get_model_status()
        assert model_status.enabled == "irregular"

    def test_model_enabled_irregular_with_modules_to_save(self, small_base_model_cls):
        # check that modules_to_save are correctly reported in layer status
        model = small_base_model_cls()
        config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
        model = get_peft_model(model, config)

        # disable only lin0
        model.lin0.enable_adapters(False)

        model_status = model.get_model_status()
        # since lin1 is still enabled, the overall model status is "irregular"
        assert model_status.enabled == "irregular"

    def test_model_enabled_irregular_with_trainable_tokens(self, small_base_emb_model_cls):
        # check that trainable_token_indices are correctly reported in layer status
        model = small_base_emb_model_cls()
        config = LoraConfig(target_modules=["lin0"], trainable_token_indices={"emb": [0, 1, 2]})
        model = get_peft_model(model, config)

        # disable only lin0
        model.lin0.enable_adapters(False)

        model_status = model.get_model_status()
        # since emb is still enabled, the overall model status is "irregular"
        assert model_status.enabled == "irregular"

    def test_model_active_adapters_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.active_adapters == ["default"]

    def test_model_active_adapters_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.active_adapters == ["default"]

        large_model.set_adapter("other")
        model_status = large_model.get_model_status()
        assert model_status.active_adapters == ["other"]

    def test_model_active_adapters_irregular(self, large_model):
        # this is an invalid state, but we should still test it
        # disable a single layer
        for module in large_model.modules():
            if isinstance(module, BaseTunerLayer):
                # switch a single layer's active adapter from default to other
                if module.active_adapters == ["default"]:
                    module._active_adapter = "other"
                    assert module.active_adapters == ["other"]
                    break

        model_status = large_model.get_model_status()
        assert model_status.active_adapters == "irregular"

    def test_model_active_adapters_with_modules_to_save_irregular(self, small_base_model_cls):
        # check that modules_to_save are correctly reported in layer status
        model = small_base_model_cls()
        config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
        model = get_peft_model(model, config)
        model.add_adapter("other", config)

        # switch modules_to_save to "other"
        model.lin1.set_adapter("other")

        model_status = model.get_model_status()
        # since lin0 is still on "default", the overall model status is "irregular"
        assert model_status.active_adapters == "irregular"

    def test_model_active_adapters_with_trainable_tokens_irregular(self, small_base_emb_model_cls):
        # check that trainable_token_indices are correctly reported in layer status
        model = small_base_emb_model_cls()
        config = LoraConfig(target_modules=["lin0"], trainable_token_indices={"emb": [0, 1, 2]})
        model = get_peft_model(model, config)
        model.add_adapter("other", config)

        # switch trainable tokens to "other"
        model.emb.set_adapter("other")

        model_status = model.get_model_status()
        # since lin0 is still on "default", the overall model status is "irregular"
        assert model_status.active_adapters == "irregular"

    def test_model_merged_adapters_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.merged_adapters == []

        small_model.merge_adapter()
        model_status = small_model.get_model_status()
        assert model_status.merged_adapters == ["default"]

        small_model.unmerge_adapter()
        model_status = small_model.get_model_status()
        assert model_status.merged_adapters == []

    def test_model_merged_adapters_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.merged_adapters == []

        large_model.merge_adapter(["default"])
        model_status = large_model.get_model_status()
        assert model_status.merged_adapters == ["default"]

        large_model.unmerge_adapter()
        large_model.merge_adapter(["other"])
        model_status = large_model.get_model_status()
        assert model_status.merged_adapters == ["other"]

        large_model.unmerge_adapter()
        large_model.merge_adapter(["default", "other"])
        model_status = large_model.get_model_status()
        assert model_status.merged_adapters == ["default", "other"]

    def test_model_merged_adapters_irregular(self, large_model):
        # this is an invalid state, but we should still test it
        # by merging only lin0 of "default", we end up in a irregular state, because not all "default" layers are merged
        large_model.base_model.lin0.merge(["default"])

        model_status = large_model.get_model_status()
        assert model_status.merged_adapters == "irregular"

    def test_model_requires_grad_model_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.requires_grad == {"default": True}

    def test_model_requires_grad_model_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.requires_grad == {"default": True, "other": False}

        large_model.set_adapter("other")
        model_status = large_model.get_model_status()
        assert model_status.requires_grad == {"default": False, "other": True}

        # change requires grad, is now inconsistent with active/inactive adapter
        large_model.set_requires_grad("default", requires_grad=True)
        large_model.set_requires_grad("other", requires_grad=False)
        model_status = large_model.get_model_status()
        assert model_status.requires_grad == {"default": True, "other": False}

    def test_model_requires_grad_model_irregular(self, large_model):
        # inject an embedding layer with requires_grad=False
        # this is an invalid state, but we should still test it
        lora_embedding_A = nn.Parameter(torch.zeros(10, 10))
        lora_embedding_B = nn.Parameter(torch.zeros(10, 10))
        lora_embedding_A.requires_grad = False
        lora_embedding_B.requires_grad = False
        large_model.base_model.model.lin0.lora_embedding_A["default"] = lora_embedding_A
        large_model.base_model.model.lin0.lora_embedding_B["default"] = lora_embedding_B

        model_status = large_model.get_model_status()
        assert model_status.requires_grad == {"default": "irregular", "other": False}

    def test_model_requires_irregular_with_modules_to_save(self, small_base_model_cls):
        # check that modules_to_save are correctly reported in layer status
        model = small_base_model_cls()
        config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
        model = get_peft_model(model, config)

        # set modules_to_save to requires_grad=False
        model.lin1.modules_to_save.default.weight.requires_grad = False

        model_status = model.get_model_status()
        # since lin1 is still requires_grad=True, the overall model status is "irregular"
        assert model_status.requires_grad == {"default": "irregular"}

    def test_model_requires_irregular_with_trainable_tokens(self, small_base_emb_model_cls):
        # check that trainable_token_indices are correctly reported in layer status
        model = small_base_emb_model_cls()
        config = LoraConfig(target_modules=["lin0"], trainable_token_indices={"emb": [0, 1, 2]})
        model = get_peft_model(model, config)

        # set trainable tokens to requires_grad=False
        model.emb.token_adapter.trainable_tokens_delta.default.requires_grad = False

        model_status = model.get_model_status()
        # since emb is still requires_grad=True, the overall model status is "irregular"
        assert model_status.requires_grad == {"default": "irregular"}

    def test_model_available_adapters_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.available_adapters == ["default"]

    def test_model_available_adapters_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.available_adapters == ["default", "other"]

    def test_model_devices_all_cpu_small(self, small_model):
        model_status = small_model.get_model_status()
        assert model_status.devices == {"default": ["cpu"]}

    def test_model_devices_all_cpu_large(self, large_model):
        model_status = large_model.get_model_status()
        assert model_status.devices == {"default": ["cpu"], "other": ["cpu"]}

    @require_non_cpu
    def test_model_devices_all_gpu_large(self, large_model):
        large_model.to(self.torch_device)
        model_status = large_model.get_model_status()
        assert model_status.devices == {"default": [self.torch_device], "other": [self.torch_device]}

    @require_non_cpu
    def test_model_devices_cpu_and_gpu_large(self, large_model):
        # move the embedding layer to GPU
        large_model.model.lin0.lora_A["default"] = large_model.model.lin0.lora_A["default"].to(self.torch_device)
        model_status = large_model.get_model_status()
        assert model_status.devices == {"default": ["cpu", self.torch_device], "other": ["cpu"]}

    def test_model_target_parameters(self, large_model):
        # don't check each attribute, just the relevant ones
        # first remove the normal LoRA layers
        large_model = large_model.merge_and_unload()
        config = LoraConfig(target_parameters=["lin0.weight", "lin1.weight"])
        large_model = get_peft_model(large_model, config)
        model_status = large_model.get_model_status()
        model_status = large_model.get_model_status()
        assert model_status.adapter_model_type == "LoraModel"
        assert model_status.peft_types == {"default": "LORA", "other": "LORA"}
        assert model_status.num_adapter_layers == 2
        assert model_status.trainable_params == 2 * (8 * 10 + 10 * 8)

    def test_model_target_parameters_and_target_modules(self, large_model):
        # don't check each attribute, just the relevant ones
        # first remove the normal LoRA layers
        large_model = large_model.merge_and_unload()
        config = LoraConfig(target_parameters=["lin0.weight"], target_modules=["lin1"])
        large_model = get_peft_model(large_model, config)
        model_status = large_model.get_model_status()
        assert model_status.adapter_model_type == "LoraModel"
        assert model_status.peft_types == {"default": "LORA", "other": "LORA"}
        assert model_status.num_adapter_layers == 2
        assert model_status.trainable_params == 2 * (8 * 10 + 10 * 8)

    def test_model_status_with_modules_to_save(self, small_base_model_cls):
        # check that modules_to_save are correctly reported in layer status
        model = small_base_model_cls()
        num_base_params = sum(p.numel() for p in small_base_model_cls().parameters())
        config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
        model = get_peft_model(model, config)
        model_status = model.get_model_status()

        assert model_status.base_model_type == "SmallModel"
        assert model_status.adapter_model_type == "LoraModel"
        assert model_status.peft_types == {"default": "LORA"}
        # 2 x 80 for LoRA, 100 for modules_to_save.weight, 10 for modules_to_save.bias
        assert model_status.trainable_params == 2 * 80 + 100 + 10
        assert model_status.total_params == 2 * 80 + 100 + 10 + num_base_params
        assert model_status.num_adapter_layers == 2  # lin0 + lin1
        assert model_status.enabled is True
        assert model_status.active_adapters == ["default"]
        assert model_status.merged_adapters == []
        assert model_status.requires_grad == {"default": True}
        assert model_status.available_adapters == ["default"]
        assert model_status.devices == {"default": ["cpu"]}  # all on CPU

    def test_model_status_with_trainable_tokens(self, small_base_emb_model_cls):
        # check that trainable_token_indices are correctly reported in layer status
        model = small_base_emb_model_cls()
        num_base_params = sum(p.numel() for p in small_base_emb_model_cls().parameters())
        config = LoraConfig(target_modules=["lin0"], trainable_token_indices={"emb": [0, 1, 2]})
        model = get_peft_model(model, config)
        model_status = model.get_model_status()

        assert model_status.base_model_type == "SmallEmbModel"
        assert model_status.adapter_model_type == "LoraModel"
        assert model_status.peft_types == {"default": "LORA"}
        # 2 x 80 for LoRA, 3 x 10 for trainable tokens
        assert model_status.trainable_params == 2 * 80 + 3 * 10
        assert model_status.total_params == 2 * 80 + 3 * 10 + num_base_params
        assert model_status.num_adapter_layers == 2
        assert model_status.enabled is True
        assert model_status.active_adapters == ["default"]
        assert model_status.merged_adapters == []
        assert model_status.requires_grad == {"default": True}
        assert model_status.available_adapters == ["default"]
        assert model_status.devices == {"default": ["cpu"]}  # all on CPU

    def test_loha_model(self):
        # ensure that this also works with non-LoRA, it's not necessary to test all tuners
        class SmallModel(nn.Module):
            def __init__(self):
                super().__init__()
                self.lin0 = nn.Linear(10, 10)
                self.lin1 = nn.Linear(10, 10)

        base_model = SmallModel()
        config = LoHaConfig(target_modules=["lin0", "lin1"], init_weights=False)
        model = get_peft_model(base_model, config)

        model_status = model.get_model_status()
        layer_status = model.get_layer_status()

        assert model_status.base_model_type == "SmallModel"
        assert model_status.adapter_model_type == "LoHaModel"
        assert model_status.peft_types == {"default": "LOHA"}
        assert model_status.trainable_params == 640
        assert model_status.total_params == 860
        assert model_status.num_adapter_layers == 2
        assert model_status.enabled is True
        assert model_status.active_adapters == ["default"]
        assert model_status.merged_adapters == []
        assert model_status.requires_grad == {"default": True}
        assert model_status.available_adapters == ["default"]
        assert model_status.devices == {"default": ["cpu"]}

        layer_status0 = layer_status[0]
        assert len(layer_status) == 2
        assert layer_status0.name == "model.lin0"
        assert layer_status0.module_type == "loha.Linear"
        assert layer_status0.enabled is True
        assert layer_status0.active_adapters == ["default"]
        assert layer_status0.merged_adapters == []
        assert layer_status0.requires_grad == {"default": True}
        assert layer_status0.available_adapters == ["default"]
        assert layer_status0.devices == {"default": ["cpu"]}

    @require_non_cpu
    def test_vera_model(self):
        # let's also test VeRA because it uses BufferDict
        class SmallModel(nn.Module):
            def __init__(self):
                super().__init__()
                self.lin0 = nn.Linear(10, 10)
                self.lin1 = nn.Linear(10, 10)

        base_model = SmallModel()
        config = VeraConfig(target_modules=["lin0", "lin1"], init_weights=False)
        model = get_peft_model(base_model, config)

        # move the buffer dict to GPU
        model.lin0.vera_A["default"] = model.lin0.vera_A["default"].to(self.torch_device)

        model_status = model.get_model_status()
        layer_status = model.get_layer_status()

        assert model_status.base_model_type == "SmallModel"
        assert model_status.adapter_model_type == "VeraModel"
        assert model_status.peft_types == {"default": "VERA"}
        assert model_status.trainable_params == 532
        assert model_status.total_params == 752
        assert model_status.num_adapter_layers == 2
        assert model_status.enabled is True
        assert model_status.active_adapters == ["default"]
        assert model_status.merged_adapters == []
        assert model_status.requires_grad == {"default": True}
        assert model_status.available_adapters == ["default"]
        assert model_status.devices == {"default": ["cpu", self.torch_device]}

        layer_status0 = layer_status[0]
        assert len(layer_status) == 2
        assert layer_status0.name == "model.lin0"
        assert layer_status0.module_type == "vera.Linear"
        assert layer_status0.enabled is True
        assert layer_status0.active_adapters == ["default"]
        assert layer_status0.merged_adapters == []
        assert layer_status0.requires_grad == {"default": True}
        assert layer_status0.available_adapters == ["default"]
        assert layer_status0.devices == {"default": ["cpu", self.torch_device]}

    ###################
    # non-PEFT models #
    ###################

    def test_transformers_model(self):
        model_id = "peft-internal-testing/gpt2-lora-random"
        # note that loading through AutoModelForCausalLM.from_pretrained does not enable training mode, hence
        # requires_grad=False
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        model_status = get_model_status(model)
        layer_status = get_layer_status(model)

        assert model_status.base_model_type == "GPT2LMHeadModel"
        assert model_status.adapter_model_type == "None"
        assert model_status.peft_types == {}
        assert model_status.trainable_params == 0
        assert model_status.total_params == 124734720
        assert model_status.num_adapter_layers == 12
        assert model_status.enabled is True
        assert model_status.active_adapters == ["default"]
        assert model_status.merged_adapters == []
        assert model_status.requires_grad == {"default": False}
        assert model_status.available_adapters == ["default"]
        assert model_status.devices == {"default": ["cpu"]}

        layer_status0 = layer_status[0]
        assert len(layer_status) == 12
        assert layer_status0.name == "transformer.h.0.attn.c_attn"
        assert layer_status0.module_type == "lora.Linear"
        assert layer_status0.enabled is True
        assert layer_status0.active_adapters == ["default"]
        assert layer_status0.merged_adapters == []
        assert layer_status0.requires_grad == {"default": False}
        assert layer_status0.available_adapters == ["default"]
        assert layer_status0.devices == {"default": ["cpu"]}

    def test_model_with_injected_layers(self, large_model):
        model = large_model.base_model.model
        model_status = get_model_status(model)
        layer_status = get_layer_status(model)

        assert model_status.base_model_type == "other"
        assert model_status.adapter_model_type == "None"
        assert model_status.peft_types == {}
        assert model_status.trainable_params == 616
        assert model_status.total_params == 2236
        assert model_status.num_adapter_layers == 4
        assert model_status.enabled is True
        assert model_status.active_adapters == ["default"]
        assert model_status.merged_adapters == []
        assert model_status.requires_grad == {"default": True, "other": False}
        assert model_status.available_adapters == ["default", "other"]
        assert model_status.devices == {"default": ["cpu"], "other": ["cpu"]}

        layer_status1 = layer_status[1]
        assert len(layer_status) == 4
        assert layer_status1.name == "emb0"
        assert layer_status1.module_type == "lora.Embedding"
        assert layer_status1.enabled is True
        assert layer_status1.active_adapters == ["default"]
        assert layer_status1.merged_adapters == []
        assert layer_status1.requires_grad == {"default": True}
        assert layer_status1.available_adapters == ["default"]
        assert layer_status1.devices == {"default": ["cpu"]}

    ###############
    # error cases #
    ###############

    def test_vanilla_model_raises(self):
        model = nn.Linear(10, 10)
        # note: full error message is longer
        with pytest.raises(ValueError, match="No adapter layers found in the model"):
            get_layer_status(model)

        with pytest.raises(ValueError, match="No adapter layers found in the model"):
            get_model_status(model)

    def test_transformer_model_without_adapter_raises(self):
        model_id = "gpt2"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        # note: full error message is longer
        with pytest.raises(ValueError, match="No adapter layers found in the model"):
            get_layer_status(model)

        with pytest.raises(ValueError, match="No adapter layers found in the model"):
            get_model_status(model)

    def test_prefix_tuning(self):
        model_id = "hf-internal-testing/tiny-random-BartForConditionalGeneration"
        with hub_online_once(model_id):
            model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
        config = PromptTuningConfig(task_type="SEQ_2_SEQ_LM", num_virtual_tokens=10)
        model = get_peft_model(model, config)

        # note: full error message is longer
        with pytest.raises(TypeError, match=re.escape("get_layer_status() got an invalid PeftModel instance")):
            model.get_layer_status()

        with pytest.raises(TypeError, match=re.escape("get_model_status() got an invalid PeftModel instance")):
            model.get_model_status()

    def test_adaption_prompt(self):
        model_id = "HuggingFaceH4/tiny-random-LlamaForCausalLM"
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        config = AdaptionPromptConfig(adapter_layers=1, adapter_len=4)
        model = get_peft_model(model, config)

        # note: full error message is longer
        with pytest.raises(TypeError, match=re.escape("get_layer_status() got an invalid PeftModel instance")):
            model.get_layer_status()

        with pytest.raises(TypeError, match=re.escape("get_model_status() got an invalid PeftModel instance")):
            model.get_model_status()

    def test_mixed_model_raises(self):
        class SimpleNet(nn.Module):
            def __init__(self, bias=True):
                super().__init__()
                # note: out_features must be > rank or else OFT will be an identity transform
                self.lin0 = nn.Linear(10, 20, bias=bias)
                self.relu = nn.ReLU()
                self.lin1 = nn.Linear(20, 16, bias=bias)

            def forward(self, X):
                X = X.float()
                X = self.lin0(X)
                X = self.relu(X)
                X = self.lin1(X)
                return X

        base_model = SimpleNet()
        config0 = LoraConfig(target_modules=["lin0"], init_lora_weights=False)
        config1 = LoHaConfig(target_modules=["lin0", "lin1"], init_weights=False)
        model = get_peft_model(base_model, config0, adapter_name="adapter0", mixed="mixed")
        model.add_adapter("adapter1", config1)

        # note: full error message is longer
        with pytest.raises(TypeError, match="get_layer_status is not supported for PeftMixedModel"):
            model.get_layer_status()

        with pytest.raises(TypeError, match="get_model_status is not supported for PeftMixedModel"):
            model.get_model_status()


# Tests for BaseTuner
class MockModelConfig:
    config = {"mock_key": "mock_value"}

    def to_dict(self):
        return self.config


@dataclasses.dataclass
class MockModelDataclassConfig:
    mock_key: str


class ModelWithConfig(nn.Module):
    def __init__(self):
        self.config = MockModelConfig()


class ModelWithDictConfig(nn.Module):
    def __init__(self):
        self.config = MockModelConfig.config


class ModelWithDataclassConfig(nn.Module):
    def __init__(self):
        self.config = MockModelDataclassConfig(**MockModelConfig().to_dict())


class ModelWithNoConfig(nn.Module):
    pass


class TestBaseTunerGetModelConfig(unittest.TestCase):
    def test_get_model_config_use_to_dict(self):
        config = BaseTuner.get_model_config(ModelWithConfig())
        assert config == MockModelConfig.config

    def test_get_model_config_as_dict(self):
        config = BaseTuner.get_model_config(ModelWithDictConfig())
        assert config == MockModelConfig.config

    def test_get_model_config_with_no_config(self):
        config = BaseTuner.get_model_config(ModelWithNoConfig())
        assert config == DUMMY_MODEL_CONFIG

    def test_get_model_config_with_dataclass(self):
        config = BaseTuner.get_model_config(ModelWithDataclassConfig())
        assert config == MockModelConfig.config


class TestBaseTunerWarnForTiedEmbeddings:
    model_id = "HuggingFaceH4/tiny-random-LlamaForCausalLM"
    warn_end_inject = "huggingface/peft/issues/2018."
    warn_end_merge = (
        "# Now use the original model but in untied format\n"
        "model = AutoModelForCausalLM.from_pretrained(untied_model_dir)\n```\n"
    )

    def _get_peft_model(self, tie_word_embeddings, target_module):
        with hub_online_once(self.model_id):
            base_model = AutoModelForCausalLM.from_pretrained(self.model_id, tie_word_embeddings=tie_word_embeddings)
        model = get_peft_model(
            base_model,
            LoraConfig(target_modules=[target_module]),
        )
        return model

    def _is_warn_triggered(self, warning_list, endswith):
        return any(str(warning.message).endswith(endswith) for warning in warning_list)

    def test_warn_for_tied_embeddings_inject(self, recwarn):
        self._get_peft_model(tie_word_embeddings=True, target_module="lm_head")
        assert self._is_warn_triggered(recwarn.list, self.warn_end_inject)

    def test_warn_for_tied_embeddings_merge(self, recwarn):
        model = self._get_peft_model(tie_word_embeddings=True, target_module="lm_head")
        model.merge_and_unload()
        assert self._is_warn_triggered(recwarn.list, self.warn_end_merge)

    def test_no_warn_for_untied_embeddings_inject(self, recwarn):
        self._get_peft_model(tie_word_embeddings=False, target_module="lm_head")
        assert not self._is_warn_triggered(recwarn.list, self.warn_end_inject)

    def test_no_warn_for_untied_embeddings_merge(self, recwarn):
        model_not_tied = self._get_peft_model(tie_word_embeddings=False, target_module="lm_head")
        model_not_tied.merge_and_unload()
        assert not self._is_warn_triggered(recwarn.list, self.warn_end_merge)

    def test_no_warn_for_no_target_module_inject(self, recwarn):
        self._get_peft_model(tie_word_embeddings=True, target_module="q_proj")
        assert not self._is_warn_triggered(recwarn.list, self.warn_end_inject)

    def test_no_warn_for_no_target_module_merge(self, recwarn):
        model_no_target_module = self._get_peft_model(tie_word_embeddings=True, target_module="q_proj")
        model_no_target_module.merge_and_unload()
        assert not self._is_warn_triggered(recwarn.list, self.warn_end_merge)


class TestFindMinimalTargetModules:
    @pytest.mark.parametrize(
        "target_modules, other_module_names, expected",
        [
            (["bar"], [], {"bar"}),
            (["foo"], ["bar"], {"foo"}),
            (["1.foo", "2.foo"], ["3.foo", "4.foo"], {"1.foo", "2.foo"}),
            # Could also return "bar.baz" but we want the shorter one
            (["bar.baz"], ["foo.bar"], {"baz"}),
            (["1.foo", "2.foo", "bar.baz"], ["3.foo", "bar.bla"], {"1.foo", "2.foo", "baz"}),
            # Case with longer suffix chains and nested suffixes
            (["a.b.c", "d.e.f", "g.h.i"], ["j.k.l", "m.n.o"], {"c", "f", "i"}),
            (["a.b.c", "d.e.f", "g.h.i"], ["a.b.x", "d.x.f", "x.h.i"], {"c", "e.f", "g.h.i"}),
            # Case with multiple items that can be covered by a single suffix
            (["foo.bar.baz", "qux.bar.baz"], ["baz.bar.foo"], {"baz"}),
            # Realistic examples
            # Only match k_proj
            (
                ["model.decoder.layers.{i}.self_attn.k_proj" for i in range(12)],
                (
                    ["model.decoder.layers.{i}.self_attn" for i in range(12)]
                    + ["model.decoder.layers.{i}.self_attn.v_proj" for i in range(12)]
                    + ["model.decoder.layers.{i}.self_attn.q_proj" for i in range(12)]
                ),
                {"k_proj"},
            ),
            # Match all k_proj except the one in layer 5 => no common suffix
            (
                ["model.decoder.layers.{i}.self_attn.k_proj" for i in range(12) if i != 5],
                (
                    ["model.decoder.layers.5.self_attn.k_proj"]
                    + ["model.decoder.layers.{i}.self_attn" for i in range(12)]
                    + ["model.decoder.layers.{i}.self_attn.v_proj" for i in range(12)]
                    + ["model.decoder.layers.{i}.self_attn.q_proj" for i in range(12)]
                ),
                {"{i}.self_attn.k_proj" for i in range(12) if i != 5},
            ),
        ],
    )
    def test_find_minimal_target_modules(self, target_modules, other_module_names, expected):
        # check all possible combinations of list and set
        result = find_minimal_target_modules(target_modules, other_module_names)
        assert result == expected

        result = find_minimal_target_modules(set(target_modules), other_module_names)
        assert result == expected

        result = find_minimal_target_modules(target_modules, set(other_module_names))
        assert result == expected

        result = find_minimal_target_modules(set(target_modules), set(other_module_names))
        assert result == expected

    def test_find_minimal_target_modules_empty_raises(self):
        with pytest.raises(ValueError, match="target_modules should be a list or set of strings"):
            find_minimal_target_modules([], ["foo"])

        with pytest.raises(ValueError, match="target_modules should be a list or set of strings"):
            find_minimal_target_modules(set(), ["foo"])

    def test_find_minimal_target_modules_contains_empty_string_raises(self):
        target_modules = ["", "foo", "bar.baz"]
        other_module_names = ["bar"]
        with pytest.raises(ValueError, match="target_modules should not contain an empty string"):
            find_minimal_target_modules(target_modules, other_module_names)

    def test_find_minimal_target_modules_string_raises(self):
        target_modules = "foo"
        other_module_names = ["bar"]
        with pytest.raises(ValueError, match="target_modules should be a list or set of strings"):
            find_minimal_target_modules(target_modules, other_module_names)

    @pytest.mark.parametrize(
        "target_modules, other_module_names",
        [
            (["foo"], ["foo"]),
            (["foo.bar"], ["foo.bar"]),
            (["foo.bar", "spam", "eggs"], ["foo.bar"]),
            (["foo.bar", "spam"], ["foo.bar", "eggs"]),
            (["foo.bar"], ["foo.bar", "spam", "eggs"]),
        ],
    )
    def test_find_minimal_target_modules_not_disjoint_raises(self, target_modules, other_module_names):
        msg = (
            "target_modules and other_module_names contain common elements, this should not happen, please "
            "open a GitHub issue at https://github.com/huggingface/peft/issues with the code to reproduce this issue"
        )
        with pytest.raises(ValueError, match=msg):
            find_minimal_target_modules(target_modules, other_module_names)

    def test_get_peft_model_applies_find_target_modules(self):
        # Check that when calling get_peft_model, the target_module optimization is indeed applied if the length of
        # target_modules is big enough. The resulting model itself should be unaffected.
        torch.manual_seed(0)
        model_id = "facebook/opt-125m"  # must be big enough for optimization to trigger
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)

        # base case: specify target_modules in a minimal fashion
        config = LoraConfig(init_lora_weights=False, target_modules=["q_proj", "v_proj"])
        model = get_peft_model(model, config)

        # this list contains all targeted modules listed separately
        big_target_modules = [name for name, module in model.named_modules() if isinstance(module, LoraLayer)]
        # sanity check
        assert len(big_target_modules) > MIN_TARGET_MODULES_FOR_OPTIMIZATION

        # make a "checksum" of the model for comparison
        model_check_sum_before = sum(p.sum() for p in model.parameters())

        # strip prefix so that the names they can be used as new target_modules
        prefix_to_strip = "base_model.model.model."
        big_target_modules = [name[len(prefix_to_strip) :] for name in big_target_modules]

        del model

        torch.manual_seed(0)
        with hub_online_once(model_id):
            model = AutoModelForCausalLM.from_pretrained(model_id)
        # pass the big target_modules to config
        config = LoraConfig(init_lora_weights=False, target_modules=big_target_modules)
        model = get_peft_model(model, config)

        # check that target modules have been condensed
        assert model.peft_config["default"].target_modules == {"q_proj", "v_proj"}

        # check that the resulting model is still the same
        model_check_after = sum(p.sum() for p in model.parameters())
        assert model_check_sum_before == model_check_after

    def test_suffix_is_substring_of_other_suffix(self):
        # This test is based on a real world bug found in diffusers. The issue was that we needed the suffix
        # 'time_emb_proj' in the minimal target modules. However, if there already was the suffix 'proj' in the
        # required_suffixes, 'time_emb_proj' would not be added because the test was `endswith(suffix)` and
        # 'time_emb_proj' ends with 'proj'. The correct logic is to test if `endswith("." + suffix")`. The module names
        # chosen here are only a subset of the hundreds of actual module names but this subset is sufficient to
        # replicate the bug.
        target_modules = [
            "down_blocks.1.attentions.0.transformer_blocks.0.ff.net.0.proj",
            "mid_block.attentions.0.transformer_blocks.0.ff.net.0.proj",
            "up_blocks.0.attentions.0.transformer_blocks.0.ff.net.0.proj",
            "mid_block.attentions.0.proj_out",
            "up_blocks.0.attentions.0.proj_out",
            "down_blocks.1.attentions.0.proj_out",
            "up_blocks.0.resnets.0.time_emb_proj",
            "down_blocks.0.resnets.0.time_emb_proj",
            "mid_block.resnets.0.time_emb_proj",
        ]
        other_module_names = [
            "conv_in",
            "time_proj",
            "time_embedding",
            "time_embedding.linear_1",
            "add_time_proj",
            "add_embedding",
            "add_embedding.linear_1",
            "add_embedding.linear_2",
            "down_blocks",
            "down_blocks.0",
            "down_blocks.0.resnets",
            "down_blocks.0.resnets.0",
            "up_blocks",
            "up_blocks.0",
            "up_blocks.0.attentions",
            "up_blocks.0.attentions.0",
            "up_blocks.0.attentions.0.norm",
            "up_blocks.0.attentions.0.transformer_blocks",
            "up_blocks.0.attentions.0.transformer_blocks.0",
            "up_blocks.0.attentions.0.transformer_blocks.0.norm1",
            "up_blocks.0.attentions.0.transformer_blocks.0.attn1",
        ]
        expected = {"time_emb_proj", "proj", "proj_out"}
        result = find_minimal_target_modules(target_modules, other_module_names)
        assert result == expected

    def test_get_peft_modules_module_name_is_suffix_of_another_module(self):
        # Solves the following bug:
        # https://github.com/huggingface/diffusers/pull/9622#issuecomment-2404789721

        # The cause for the bug is as follows: When we have, say, a module called "bar.0.query" that we want to target
        # and another module called "foo_bar.0.query" that we don't want to target, there was potential for an error.
        # This is not caused by _find_minimal_target_modules directly, but rather the bug was inside of
        # BaseTuner.inject_adapter and how the names_no_target were chosen. Those used to be chosen based on suffix. In
        # our example, however, "bar.0.query" is a suffix of "foo_bar.0.query", therefore "foo_bar.0.query" was *not*
        # added to names_no_target when it should have. As a consequence, during the optimization, it looks like "query"
        # is safe to use as target_modules because we don't see that it wrongly matches "foo_bar.0.query".

        # ensure that we have sufficiently many modules to trigger the optimization
        n_layers = MIN_TARGET_MODULES_FOR_OPTIMIZATION + 1

        class InnerModule(nn.Module):
            def __init__(self):
                super().__init__()
                self.query = nn.Linear(10, 10)

        class OuterModule(nn.Module):
            def __init__(self):
                super().__init__()
                # note that "transformer_blocks" is a suffix of "single_transformer_blocks"
                self.transformer_blocks = nn.ModuleList([InnerModule() for _ in range(n_layers)])
                self.single_transformer_blocks = nn.ModuleList([InnerModule() for _ in range(n_layers)])

        # we want to match all "transformer_blocks" layers but not "single_transformer_blocks"
        target_modules = [f"transformer_blocks.{i}.query" for i in range(n_layers)]
        model = get_peft_model(OuterModule(), LoraConfig(target_modules=target_modules))

        # sanity check: we should have n_layers PEFT layers in model.transformer_blocks
        transformer_blocks = model.base_model.model.transformer_blocks
        assert sum(isinstance(module, BaseTunerLayer) for module in transformer_blocks.modules()) == n_layers

        # we should not have any PEFT layers in model.single_transformer_blocks
        single_transformer_blocks = model.base_model.model.single_transformer_blocks
        assert not any(isinstance(module, BaseTunerLayer) for module in single_transformer_blocks.modules())

        # target modules should *not* be simplified to "query" as that would match "single_transformers_blocks" too
        assert model.peft_config["default"].target_modules != {"query"}

    def test_find_minimal_target_modules_does_not_error_with_ia3(self, tmp_path):
        # See #2429
        # There is an issue with the compression of the target_modules attribute when using IA³. There, we additionally
        # have the feedforward_modules attribute, which must be subset of target_modules. When target_modules is shrunk,
        # the subset check will fail. This test ensures that this doesn't happen.
        n_layers = MIN_TARGET_MODULES_FOR_OPTIMIZATION + 1

        class InnerModule(nn.Module):
            def __init__(self):
                super().__init__()
                self.query = nn.Linear(10, 10)

        class OuterModule(nn.Module):
            def __init__(self):
                super().__init__()
                self.blocks = nn.ModuleList([InnerModule() for _ in range(n_layers)])

        target_modules = [f"blocks.{i}.query" for i in range(n_layers)]
        feedforward_modules = [f"blocks.{i}.query" for i in range(n_layers)]
        # the subset check happens here
        config = IA3Config(target_modules=target_modules, feedforward_modules=feedforward_modules)
        # the optimization step happens here, after the subset check, so at first we're fine, but we will run into an
        # issue after a save/load roundtrip
        model = get_peft_model(OuterModule(), config)
        model.save_pretrained(tmp_path)
        del model

        # does not raise
        PeftModel.from_pretrained(OuterModule(), tmp_path)


class TestRankAndAlphaPattern:
    @pytest.fixture
    def model(self):
        # we always target the foo layers, the *bar* layers are used as a control group to ensure that they are not
        # accidentally targeted
        class Inner(nn.Module):
            def __init__(self):
                super().__init__()
                self.foo = nn.Linear(1, 1)
                self.barfoo = nn.Linear(1, 1)

        class Middle(nn.Module):
            def __init__(self):
                super().__init__()
                self.foo = nn.Linear(1, 1)
                self.foobar = nn.Linear(1, 1)
                self.module = Inner()

        class Outer(nn.Module):
            def __init__(self):
                super().__init__()
                self.foo = nn.Linear(1, 1)
                self.bar = nn.Linear(1, 1)
                self.module = Middle()

        # resulting model for overview:
        # Outer(
        #   (foo): Linear(...)
        #   (bar): Linear(...)
        #   (module): Middle(
        #     (foo): Linear(...)
        #     (foobar): Linear(...)
        #     (module): Inner(
        #       (foo): Linear(...)
        #       (barfoo): Linear(...)
        #     )
        #   )
        # )

        return Outer()

    def test_no_rank_nor_alpha_pattern(self, model):
        # sanity check the default case, no rank or alpha pattern
        config = LoraConfig(target_modules="all-linear")
        model = get_peft_model(model, config).base_model.model
        # r is the default rank and alpha, thus scaling is 1.0
        assert model.foo.r["default"] == 8
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.r["default"] == 8
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.r["default"] == 8
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.r["default"] == 8
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.r["default"] == 8
        assert model.module.module.foo.scaling["default"] == 1.0
        assert model.module.module.barfoo.r["default"] == 8
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_rank_and_alpha_pattern_no_matching_keys(self, model):
        # sanity check for non-matching keys, no rank or alpha pattern
        config = LoraConfig(target_modules="all-linear", rank_pattern={"bla": 4, "oof": 6}, alpha_pattern={"baz": 3})
        model = get_peft_model(model, config).base_model.model
        # r is the default rank and alpha, thus scaling is 1.0
        assert model.foo.r["default"] == 8
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.r["default"] == 8
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.r["default"] == 8
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.r["default"] == 8
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.r["default"] == 8
        assert model.module.module.foo.scaling["default"] == 1.0
        assert model.module.module.barfoo.r["default"] == 8
        assert model.module.module.barfoo.scaling["default"] == 1.0

    # below, we test all permutations for rank_pattern of targeting outer, middle, and inner foo layers:

    def test_rank_pattern_target_all(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"foo": 16})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 16
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 16
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_outer(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^foo": 16})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 8
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 8
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_middle(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^module.foo": 16})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 8
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 16
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 8
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_inner(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"module.module.foo": 16})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 8
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 8
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 16
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_inner_with_caret(self, model):
        # same as before, but using the caret in the regex should also work
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^module.module.foo": 16})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 8
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 8
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 16
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_middle_inner(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"module.foo": 16})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 8
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 16
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 16
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_middle_inner_different_ranks(self, model):
        # same layers targeted as in previous test, but with different ranks
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^module.foo": 16, "^module.module.foo": 24})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 8
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 16
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 24
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_outer_middle(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^foo": 16, "^module.foo": 24})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 24
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 8
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_outer_inner(self, model):
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^foo": 16, "module.module.foo": 24})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 8
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 24
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_outer_inner_with_caret(self, model):
        # same as before, but using the caret in the regex should also work
        config = LoraConfig(target_modules="all-linear", rank_pattern={"^foo": 16, "^module.module.foo": 24})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 8
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 24
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_outer_middle_inner_with_caret(self, model):
        # indicate each layer with a different rank and use the caret in the regex
        config = LoraConfig(
            target_modules="all-linear", rank_pattern={"^foo": 16, "^module.foo": 24, "^module.module.foo": 32}
        )
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 24
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 32
        assert model.module.module.barfoo.r["default"] == 8

    def test_rank_pattern_target_outer_middle_inner_with_caret_dict_order(self, model):
        # same as before, but change the order of the rank_pattern dict
        config = LoraConfig(
            target_modules="all-linear", rank_pattern={"^module.module.foo": 32, "^module.foo": 24, "^foo": 16}
        )
        model = get_peft_model(model, config).base_model.model
        assert model.foo.r["default"] == 16
        assert model.bar.r["default"] == 8
        assert model.module.foo.r["default"] == 24
        assert model.module.foobar.r["default"] == 8
        assert model.module.module.foo.r["default"] == 32
        assert model.module.module.barfoo.r["default"] == 8

    # below, we test all permutations for alpha_pattern of targeting outer, middle, and inner foo layers:
    # these tests are analogous to the rank_pattern tests above

    def test_alpha_pattern_target_all(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"foo": 4})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.5
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.5
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_outer(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^foo": 4})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 1.0
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_middle(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^module.foo": 4})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.5
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 1.0
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_inner(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"module.module.foo": 4})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.5
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_inner_with_caret(self, model):
        # same as before, but using the caret in the regex should also work
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^module.module.foo": 4})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.5
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_middle_inner(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"module.foo": 4})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.5
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.5
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_middle_inner_different_alphas(self, model):
        # same layers targeted as in previous test, but with different alphas
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^module.foo": 4, "^module.module.foo": 2})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 1.0
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.5
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.25
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_outer_middle(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^foo": 4, "^module.foo": 2})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.25
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 1.0
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_outer_inner(self, model):
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^foo": 4, "module.module.foo": 2})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.25
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_outer_inner_with_caret(self, model):
        # same as before, but using the caret in the regex should also work
        config = LoraConfig(target_modules="all-linear", alpha_pattern={"^foo": 4, "^module.module.foo": 2})
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 1.0
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.25
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_outer_middle_inner_with_caret(self, model):
        # indicate each layer with a different alpha and use the caret in the regex
        config = LoraConfig(
            target_modules="all-linear", alpha_pattern={"^foo": 4, "^module.foo": 2, "^module.module.foo": 1}
        )
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.25
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.125
        assert model.module.module.barfoo.scaling["default"] == 1.0

    def test_alpha_pattern_target_outer_middle_inner_with_caret_dict_order(self, model):
        # same as before, but change the order of the alpha_pattern dict
        config = LoraConfig(
            target_modules="all-linear", alpha_pattern={"^module.module.foo": 1, "^module.foo": 2, "^foo": 4}
        )
        model = get_peft_model(model, config).base_model.model
        assert model.foo.scaling["default"] == 0.5
        assert model.bar.scaling["default"] == 1.0
        assert model.module.foo.scaling["default"] == 0.25
        assert model.module.foobar.scaling["default"] == 1.0
        assert model.module.module.foo.scaling["default"] == 0.125
        assert model.module.module.barfoo.scaling["default"] == 1.0