-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmonitor.py
More file actions
1789 lines (1506 loc) · 79.9 KB
/
monitor.py
File metadata and controls
1789 lines (1506 loc) · 79.9 KB
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
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import collections
import math
import matplotlib.pyplot as plt
import random
import json
import os
from datetime import datetime
import time
# --- Set Random Seeds for Reproducibility ---
SEED = 43
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# --- Configuration Parameters ---
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
INPUT_DIM = 64
OUTPUT_DIM = 64
HIDDEN_DIM = 64 # Hidden dimension for base model
# Method specific parameters (manually set for each method)
LORA_RANK = 2
VERA_RANK = 64
BLOCK_DIAG_RANK = 4
PISSA_RANK = 2
DORA_RANK = 1
PROLORA_RANK = 2
ADALORA_RANK = 2
MOS_RANK = 2
# Training parameters
BASE_LR = 0.001 # Learning rate for base model
ADAPT_LR = 0.001 # Learning rate for adaptation methods
BASE_EPOCHS = 250 # Epochs for base model training
ADAPT_EPOCHS = 100 # Epochs for adaptation methods
EVAL_INTERVAL = 10 # Evaluation interval
N_TRAIN = 50 # Number of training data points
N_VALID = 100 # Number of validation data points
NOISE_STD = 0.05 # Noise standard deviation for training data
# --- Data Generation Functions ---
def base_function(x):
"""Original function to fit with the base model"""
return torch.sin(2 * torch.pi * x)
def modified_function(x):
"""Modified function for adaptation (slightly different)"""
return torch.sin(2 * torch.pi * x) + 0.3 * torch.cos(3 * torch.pi * x)
def generate_data(n_samples, func, noise_std, device):
"""Generate synthetic data from the given function"""
x = torch.rand(n_samples, INPUT_DIM) * 2 - 1 # X in range [-1, 1]
y = func(x) + torch.randn(n_samples, OUTPUT_DIM) * noise_std
return x.to(device), y.to(device)
# Generate datasets
x_train_base, y_train_base = generate_data(N_TRAIN, base_function, NOISE_STD, DEVICE)
x_valid_base, y_valid_base = generate_data(N_VALID, base_function, 0.0, DEVICE) # No noise for validation
x_train_adapt, y_train_adapt = generate_data(N_TRAIN, modified_function, NOISE_STD, DEVICE)
x_valid_adapt, y_valid_adapt = generate_data(N_VALID, modified_function, 0.0, DEVICE) # No noise for validation
# --- Base MLP Model ---
class BaseModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super().__init__()
self.layer1 = nn.Linear(input_dim, hidden_dim)
self.relu = nn.ReLU()
self.layer2 = nn.Linear(hidden_dim, output_dim)
self.adapter_name = "BaseModel"
def forward(self, x):
x = self.layer1(x)
x = self.relu(x)
x = self.layer2(x)
return x
# --- Common: Freeze Original Layer ---
def freeze_original_layer(original_layer):
for param in original_layer.parameters():
param.requires_grad = False
# --- LoRA Adapter ---
class LoRAAdapter(nn.Module):
def __init__(self, original_layer, rank, scale=1.0):
super().__init__()
self.original_layer = original_layer
# Freeze the original layer
freeze_original_layer(original_layer)
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.rank = rank
self.scale = scale
# LoRA parameters
self.lora_A = nn.Parameter(torch.empty(rank, self.in_features))
self.lora_B = nn.Parameter(torch.empty(self.out_features, rank))
# Initialize parameters
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
nn.init.zeros_(self.lora_B) # B initialized to zero
def forward(self, x):
# Original output
original_output = self.original_layer(x)
# LoRA adaptation: W = W0 + BA
delta = self.lora_B @ self.lora_A @ x.T
return original_output + self.scale * delta.T
def num_adapter_parameters(self):
return self.lora_A.numel() + self.lora_B.numel()
# --- VeRA Adapter ---
class VeRAAdapter(nn.Module):
def __init__(self, original_layer, rank, d_init_val=0.1):
super().__init__()
self.original_layer = original_layer
# Freeze the original layer
freeze_original_layer(original_layer)
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.rank = rank
# Frozen pseudo-shared matrices
self.A_frozen = torch.empty(rank, self.in_features)
self.B_frozen = torch.empty(self.out_features, rank)
nn.init.kaiming_uniform_(self.A_frozen, a=math.sqrt(5))
nn.init.kaiming_uniform_(self.B_frozen, a=math.sqrt(5))
self.A_frozen = self.A_frozen.to(DEVICE)
self.B_frozen = self.B_frozen.to(DEVICE)
self.A_frozen.requires_grad = False
self.B_frozen.requires_grad = False
# Trainable scaling vectors
self.b_vec = nn.Parameter(torch.zeros(self.out_features)) # Output dimension
self.d_vec = nn.Parameter(torch.full((rank,), d_init_val)) # Rank dimension
def forward(self, x):
# Original output
original_output = self.original_layer(x)
# VeRA adaptation: W = W0 + diag(b) * B * diag(d) * A
Lambda_b = torch.diag(self.b_vec)
Lambda_d = torch.diag(self.d_vec)
delta = Lambda_b @ self.B_frozen @ Lambda_d @ self.A_frozen @ x.T
return original_output + delta.T
def num_adapter_parameters(self):
return self.b_vec.numel() + self.d_vec.numel()
# --- Our Method: Block Diagonal Adapter ---
class BlockDiagonalAdapter(nn.Module):
def __init__(self, original_layer, rank): # rank 参数现在代表 ShardLoRA 的秩 r
super().__init__()
self.original_layer = original_layer
freeze_original_layer(original_layer) # 假设此函数存在或在外部调用
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.r = rank # 这是论文 [cite: 110, 111] 中的 'r' 或 Algorithm 1 中的 self.r
if self.in_features % self.r != 0:
raise ValueError(f"Input dimension ({self.in_features}) "
f"must be divisible by shard_lora_rank ({self.r}) "
f"for this ShardLoRA-style adapter.")
# 可训练矩阵 D (论文中表示为 D in R^(r x d)[cite: 109, 111], 或 Algorithm 1 中的 self.disha)
# 大小为 (shard_lora_rank, out_features)
self.disha_D = nn.Parameter(torch.empty(self.r, self.out_features))
# 论文 [cite: 42] 中提到 ShardLoRA (Ours) 的 D 初始化为0
nn.init.zeros_(self.disha_D)
def forward(self, x): # x: (batch_size, ..., in_features)
original_output = self.original_layer(x)
# 输入聚合 S,参考论文 Section 4.2 [cite: 112, 119] 和 Algorithm 1 [cite: 110]
# x 原始 shape: (batch_size, seq_len, in_features) 或 (batch_size, in_features)
# 需要重塑为 (batch_size, ..., in_features // self.r, self.r)
# 然后在倒数第二个维度上求和 (即 in_features // self.r 这个维度)
leading_dims = x.shape[:-1] # (batch_size, seq_len) 或 (batch_size,)
in_features_dim = x.shape[-1]
if in_features_dim != self.in_features:
raise ValueError(f"Input feature dimension {in_features_dim} does not match layer's in_features {self.in_features}")
# Reshape for summation
# x_reshaped: (batch_size, ..., self.in_features // self.r, self.r)
x_reshaped_for_sum = x.view(*leading_dims, self.in_features // self.r, self.r)
# Sum along the (self.in_features // self.r) dimension
# S: (batch_size, ..., self.r)
S = torch.sum(x_reshaped_for_sum, dim=-2)
# 计算 delta_y = S @ D
# S shape: (batch_size, ..., self.r)
# self.disha_D shape: (self.r, self.out_features)
# delta_y shape: (batch_size, ..., self.out_features)
delta_y = torch.matmul(S, self.disha_D)
return original_output + delta_y
def num_adapter_parameters(self):
# 参数量为 r * out_features [cite: 117, 124]
return self.disha_D.numel()
# --- 1. PiSSA Adapter ---
class PiSSAAdapter(nn.Module):
def __init__(self, original_layer, rank):
super().__init__()
self.original_layer_weights_only = original_layer # Keep a reference if needed for W_res
freeze_original_layer(original_layer) # The original layer object itself might not be used if W_res is handled separately
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.rank = rank
self.adapter_name = f"PiSSA (Rank {rank})"
# Perform SVD on original_layer.weight (W)
# W = U S V^T
# This is conceptual. In practice, you'd load W and decompose.
W = original_layer.weight.data.clone() # Shape: (out_features, in_features)
try:
U, S_diag, Vh = torch.linalg.svd(W, full_matrices=False)
except torch.linalg.LinAlgError: # Handle cases where SVD might fail for zero matrices etc.
# Fallback or error handling
print(f"SVD failed for layer, initializing PiSSA with LoRA-like approach as fallback.")
# Fallback to LoRA-like initialization for A and B if SVD fails
self.lora_A = nn.Parameter(torch.empty(rank, self.in_features))
self.lora_B = nn.Parameter(torch.empty(self.out_features, rank))
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
nn.init.zeros_(self.lora_B)
self.W_res = nn.Parameter(W, requires_grad=False) # Freeze original weights
self.bias = nn.Parameter(original_layer.bias.data.clone() if original_layer.bias is not None else None, requires_grad=False)
self.svd_initialized = False
return
# Principal components for A and B
U_r = U[:, :rank]
S_r_diag = S_diag[:rank]
Vh_r = Vh[:rank, :] # Vh is V.T, so Vh_r is (V_r)^T
S_r_sqrt = torch.sqrt(S_r_diag)
self.lora_A = nn.Parameter(torch.diag(S_r_sqrt) @ Vh_r) # S_r^(1/2) @ V_r^T
self.lora_B = nn.Parameter(U_r @ torch.diag(S_r_sqrt)) # U_r @ S_r^(1/2)
# Residual weights (frozen)
if rank < S_diag.size(0) and rank < U.size(1) and rank < Vh.size(0):
U_res = U[:, rank:]
S_res_diag = S_diag[rank:]
Vh_res = Vh[rank:, :]
self.W_res = nn.Parameter(U_res @ torch.diag(S_res_diag) @ Vh_res, requires_grad=False)
else: # If rank is too large, residual might be zero or very small
self.W_res = nn.Parameter(torch.zeros_like(W), requires_grad=False)
# Freeze original bias if it exists
if original_layer.bias is not None:
self.bias = nn.Parameter(original_layer.bias.data.clone(), requires_grad=False)
else:
self.bias = None
self.svd_initialized = True
def forward(self, x):
# For PiSSA, we need to be careful with dimensions
# The error occurs because we're trying to add tensors of incompatible shapes
if not self.svd_initialized: # Fallback case
original_output = torch.functional.F.linear(x, self.W_res, self.bias)
delta = self.lora_B @ self.lora_A
return original_output + torch.functional.F.linear(x, delta, None)
# Residual part
output_res = torch.functional.F.linear(x, self.W_res, self.bias)
# Adaptable part - simplified approach using F.linear
# Instead of manually handling matrix multiplications, use F.linear
delta_W = self.lora_B @ self.lora_A
adapt_output = torch.functional.F.linear(x, delta_W, None)
return output_res + adapt_output
def num_adapter_parameters(self):
return self.lora_A.numel() + self.lora_B.numel()
# --- 2. DoRA Adapter ---
class DoRAAdapter(nn.Module):
def __init__(self, original_layer, rank, lora_alpha=1.0): # lora_alpha is often rank
super().__init__()
self.original_layer = original_layer # Keep for W0 and bias
freeze_original_layer(original_layer)
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.rank = rank
self.lora_alpha = lora_alpha # LoRA scaling factor
self.adapter_name = f"DoRA (Rank {rank})"
# Pre-trained weight W0 (direction component initially)
self.W0 = original_layer.weight.data.clone()
self.W0.requires_grad = False # Direction component of W0 is frozen
# Magnitude vector m, initialized from ||W0||_c
# Shape: (out_features, 1) to allow broadcasting for column norms
# Or (1, in_features) if norms are taken row-wise (paper says column-wise for W in R^dxk)
# Assuming W0 is (out_features, in_features), ||W0||_c means norm of each column vector
# So m should correspond to columns of W0.
# If W' = m * (V / ||V||_c), and W' is (out_features, in_features)
# V is (out_features, in_features), ||V||_c is (1, in_features)
# m should be (1, in_features) to scale columns
# The paper Figure 1 shows m as (1 x k) for W (d x k) -> k = in_features
self.m = nn.Parameter(torch.linalg.norm(self.W0, dim=0, keepdim=True)) # Norm along columns (dim=0)
# LoRA matrices for directional update (delta_V = BA)
self.lora_A = nn.Parameter(torch.empty(rank, self.in_features)) # r x k
self.lora_B = nn.Parameter(torch.empty(self.out_features, rank)) # d x r
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
nn.init.zeros_(self.lora_B)
self.scaling = self.lora_alpha / self.rank
self.bias = None
if original_layer.bias is not None:
self.bias = original_layer.bias.data.clone()
self.bias.requires_grad = False
def forward(self, x):
# W_adapted = m * normalize(W0 + BA)
# y = x @ W_adapted.T + bias_orig
# or y = m * ( (x @ (W0+BA).T) / ||W0+BA||_c_row_wise ) + bias if m scales output
# From paper eq (5): W' = m * (W0 + BA) / ||W0 + BA||_c
# So, y = x @ W'.T + bias = x @ (m * (W0 + BA) / ||W0 + BA||_c).T + bias
# This means m needs to be applied after normalization, or W' precomputed.
delta_W = self.lora_B @ self.lora_A # d x k
adapted_V = self.W0 + self.scaling * delta_W # Directional part update
# Column-wise norm of adapted_V
norm_adapted_V = torch.linalg.norm(adapted_V, dim=0, keepdim=True) + 1e-5 # Avoid division by zero
# Normalized direction
V_normalized = adapted_V / norm_adapted_V
# Final adapted weight
W_prime = self.m * V_normalized # Element-wise multiplication due to m being (1, k) and V_norm (d, k)
return torch.functional.F.linear(x, W_prime, self.bias)
def num_adapter_parameters(self):
return self.m.numel() + self.lora_A.numel() + self.lora_B.numel()
# --- ProLoRA Adapter ---
class ProLoRAAdapter(nn.Module):
def __init__(self, original_layer, rank, unshared_rank_u=1, sharing_ratio_m_A=None, sharing_ratio_n_B=None, base_stride_sA=1, base_stride_sB=1):
super().__init__()
self.original_layer = original_layer
freeze_original_layer(original_layer)
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.r = rank
self.u = unshared_rank_u # unshared rank
# Auto-adjust sharing ratios based on input dimensions if not provided
# Choose sharing ratios that divide the dimensions evenly
if sharing_ratio_m_A is None:
# Default to 1 if in_features < 2, otherwise use 2 if divisible, else 1
self.m_A = 1 if self.in_features < 2 else (2 if self.in_features % 2 == 0 else 1)
else:
self.m_A = sharing_ratio_m_A
if sharing_ratio_n_B is None:
# Default to 1 if out_features < 2, otherwise use 2 if divisible, else 1
self.n_B = 1 if self.out_features < 2 else (2 if self.out_features % 2 == 0 else 1)
else:
self.n_B = sharing_ratio_n_B
self.sA = base_stride_sA
self.sB = base_stride_sB
self.adapter_name = f"ProLoRA (Rank {rank})"
# Verify dimensions are compatible with sharing ratios
if self.in_features % self.m_A != 0:
print(f"Warning: in_features {self.in_features} not divisible by m_A {self.m_A}. Adjusting m_A to 1.")
self.m_A = 1
if self.out_features % self.n_B != 0:
print(f"Warning: out_features {self.out_features} not divisible by n_B {self.n_B}. Adjusting n_B to 1.")
self.n_B = 1
if (self.r - self.u) <= 0 :
print("Warning: No shared ranks in ProLoRA, behaves like LoRA with rank u.")
self.is_lora_equivalent = True
self.lora_A_eq = nn.Parameter(torch.empty(self.u, self.in_features))
self.lora_B_eq = nn.Parameter(torch.empty(self.out_features, self.u))
nn.init.kaiming_uniform_(self.lora_A_eq, a=math.sqrt(5))
nn.init.zeros_(self.lora_B_eq)
self.shared_rank = 0
else:
self.is_lora_equivalent = False
self.shared_rank = self.r - self.u
# Unshared parts
self.A_u = nn.Parameter(torch.empty(self.u, self.in_features))
self.B_u = nn.Parameter(torch.empty(self.out_features, self.u))
nn.init.kaiming_uniform_(self.A_u, a=math.sqrt(5))
nn.init.zeros_(self.B_u)
# Shared base chunks (A0, B0)
# Dimensions of A0: (shared_rank, in_features / m_A)
# Dimensions of B0: (out_features / n_B, shared_rank)
self.A0_chunk_in_dim = self.in_features // self.m_A
self.B0_chunk_out_dim = self.out_features // self.n_B
self.A0_shared = nn.Parameter(torch.empty(self.shared_rank, self.A0_chunk_in_dim))
self.B0_shared = nn.Parameter(torch.empty(self.B0_chunk_out_dim, self.shared_rank))
# Rectified Kaiming for A0, Zeros for B0
# For A0, fan_in is the full in_features for the equivalent non-sharded matrix part
gain = nn.init.calculate_gain('leaky_relu', math.sqrt(5)) # kaiming_uniform default uses leaky_relu
std_A0 = gain / math.sqrt(self.in_features) # Use full in_features for bound calculation
bound_A0 = math.sqrt(3.0) * std_A0
nn.init.uniform_(self.A0_shared, -bound_A0, bound_A0)
nn.init.zeros_(self.B0_shared)
def _get_rotated_chunks(self):
# Construct full A_shared and B_shared from A0, B0 with rotation
A_s_chunks = []
for i in range(self.m_A):
stride = i * self.sA
# Roll along rank dimension (dim=0 for A0_shared)
Ai_chunk = torch.roll(self.A0_shared, shifts=stride, dims=0)
A_s_chunks.append(Ai_chunk)
A_s = torch.cat(A_s_chunks, dim=1) # Concatenate along hidden_dim for A
B_s_chunks = []
for i in range(self.n_B):
stride = i * self.sB
# Roll along rank dimension (dim=1 for B0_shared)
Bi_chunk = torch.roll(self.B0_shared, shifts=stride, dims=1)
B_s_chunks.append(Bi_chunk)
B_s = torch.cat(B_s_chunks, dim=0) # Concatenate along out_dim for B
return A_s, B_s
def forward(self, x):
original_output = self.original_layer(x)
if self.is_lora_equivalent:
delta_W = self.lora_B_eq @ self.lora_A_eq
else:
A_s, B_s = self._get_rotated_chunks() # A_s: (shared_r, in_feat), B_s: (out_feat, shared_r)
# Combine unshared and shared parts for delta_W calculation
delta_W_unshared = self.B_u @ self.A_u
delta_W_shared = B_s @ A_s
delta_W = delta_W_unshared + delta_W_shared # Assuming this additive composition
# Need to handle x dimensions for matmul correctly
if x.ndim == 2: # (batch, features)
adapt_output = torch.functional.F.linear(x, delta_W, None)
elif x.ndim == 3: # (batch, seq_len, features)
original_shape = x.shape
x_reshaped = x.reshape(-1, x.shape[-1])
adapt_output_reshaped = torch.functional.F.linear(x_reshaped, delta_W, None)
adapt_output = adapt_output_reshaped.reshape(original_shape[0], original_shape[1], -1)
else:
raise ValueError("Input x must be 2D or 3D")
return original_output + adapt_output
def num_adapter_parameters(self):
if self.is_lora_equivalent:
return self.lora_A_eq.numel() + self.lora_B_eq.numel()
params = self.A_u.numel() + self.B_u.numel()
if self.shared_rank > 0 :
params += self.A0_shared.numel() + self.B0_shared.numel()
return params
# --- AdaLoRA Adapter ---
class AdaLoRAAdapter(nn.Module):
def __init__(self, original_layer, initial_rank):
super().__init__()
self.original_layer = original_layer
freeze_original_layer(original_layer)
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.r = initial_rank # Rank can change during training
self.adapter_name = f"AdaLoRA (Rank {initial_rank})"
# P Lambda Q parameterization
# P: (out_features, r), Q: (r, in_features), Lambda: (r, r) diagonal
self.lora_P = nn.Parameter(torch.empty(self.out_features, self.r))
self.lora_Q = nn.Parameter(torch.empty(self.r, self.in_features))
self.lora_Lambda_diag = nn.Parameter(torch.empty(self.r)) # Store diagonal of Lambda
nn.init.normal_(self.lora_P, 0, 0.02) # Example: Gaussian init
nn.init.normal_(self.lora_Q, 0, 0.02) # Example: Gaussian init
nn.init.zeros_(self.lora_Lambda_diag) # Lambda initialized to zero
self.bias = None
if original_layer.bias is not None:
self.bias = original_layer.bias.data.clone()
self.bias.requires_grad = False
def forward(self, x):
original_output = self.original_layer(x)
# Delta W = P @ diag(Lambda_diag) @ Q
Lambda_matrix = torch.diag(self.lora_Lambda_diag)
delta_W = self.lora_P @ Lambda_matrix @ self.lora_Q
if x.ndim == 2:
adapt_output = torch.functional.F.linear(x, delta_W, None)
elif x.ndim == 3:
original_shape = x.shape
x_reshaped = x.reshape(-1, x.shape[-1])
adapt_output_reshaped = torch.functional.F.linear(x_reshaped, delta_W, None)
adapt_output = adapt_output_reshaped.reshape(original_shape[0], original_shape[1], -1)
else:
raise ValueError("Input x must be 2D or 3D")
return original_output + adapt_output
def num_adapter_parameters(self):
# This is complex as r changes. This is for current r.
return self.lora_P.numel() + self.lora_Q.numel() + self.lora_Lambda_diag.numel()
# --- 5. MoS (Mixture of Shards) Adapter ---
class MoSAdapter(nn.Module):
def __init__(self, original_layer, rank_per_layer, shard_dim_ratio=2):
super().__init__()
self.original_layer = original_layer
freeze_original_layer(original_layer)
self.in_features = original_layer.in_features
self.out_features = original_layer.out_features
self.rank_per_layer = rank_per_layer # Effective rank for this layer
# For simplicity, use a configuration that works with our 1-dim inputs
# Assuming rank is 4, shard_dim_ratio is 4, we'd have 4 shards
num_shards_A = shard_dim_ratio
num_shards_B = shard_dim_ratio
num_selected_shards_A = shard_dim_ratio
num_selected_shards_B = shard_dim_ratio
# Dimensions for our shards - simplified for this implementation
shard_dim_A_rank = rank_per_layer // num_selected_shards_A
shard_dim_A_in = self.in_features
shard_dim_B_out = self.out_features
shard_dim_B_rank = rank_per_layer // num_selected_shards_B
self.num_selected_shards_A = num_selected_shards_A
self.num_selected_shards_B = num_selected_shards_B
# Simulate global shard pools (simplified for this implementation)
self.A_shard_pool = nn.ParameterList(
[nn.Parameter(torch.empty(shard_dim_A_rank, shard_dim_A_in)) for _ in range(num_shards_A)]
)
self.B_shard_pool = nn.ParameterList(
[nn.Parameter(torch.empty(shard_dim_B_out, shard_dim_B_rank)) for _ in range(num_shards_B)]
)
# Initialization
for shard_A in self.A_shard_pool:
nn.init.kaiming_uniform_(shard_A, a=math.sqrt(5))
for shard_B in self.B_shard_pool:
nn.init.zeros_(shard_B)
# Fixed selection for demonstration - use all shards
self.selected_A_indices = list(range(num_selected_shards_A))
self.selected_B_indices = list(range(num_selected_shards_B))
self.bias = None
if original_layer.bias is not None:
self.bias = original_layer.bias.data.clone()
self.bias.requires_grad = False
def _construct_lora_matrices(self):
# Get selected shards
selected_A_shards = [self.A_shard_pool[i] for i in self.selected_A_indices]
lora_A_eff = torch.cat(selected_A_shards, dim=0) # Cat along rank dimension
selected_B_shards = [self.B_shard_pool[i] for i in self.selected_B_indices]
lora_B_eff = torch.cat(selected_B_shards, dim=1) # Cat along rank dimension
return lora_A_eff, lora_B_eff
def forward(self, x):
original_output = self.original_layer(x)
lora_A, lora_B = self._construct_lora_matrices()
delta_W = lora_B @ lora_A
if x.ndim == 2:
adapt_output = torch.functional.F.linear(x, delta_W, None)
elif x.ndim == 3:
original_shape = x.shape
x_reshaped = x.reshape(-1, x.shape[-1])
adapt_output_reshaped = torch.functional.F.linear(x_reshaped, delta_W, None)
adapt_output = adapt_output_reshaped.reshape(original_shape[0], original_shape[1], -1)
else:
raise ValueError("Input x must be 2D or 3D")
return original_output + adapt_output
def num_adapter_parameters(self):
# Parameters are in the shard pools
total_params = 0
for p in self.A_shard_pool:
total_params += p.numel()
for p in self.B_shard_pool:
total_params += p.numel()
return total_params
# --- Training Functions ---
def train_base_model(model, x_train, y_train, x_valid, y_valid, epochs, lr, eval_interval):
"""Train the base model from scratch"""
optimizer = optim.Adam(model.parameters(), lr=lr)
criterion = nn.MSELoss()
history = {'train_loss': [], 'valid_loss': [], 'epochs': []}
print(f"\nTraining Base Model...")
for epoch in range(epochs):
model.train()
optimizer.zero_grad()
y_pred = model(x_train)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
if (epoch + 1) % eval_interval == 0 or epoch == 0:
model.eval()
with torch.no_grad():
valid_pred = model(x_valid)
valid_loss = criterion(valid_pred, y_valid)
history['train_loss'].append(loss.item())
history['valid_loss'].append(valid_loss.item())
history['epochs'].append(epoch + 1)
print(f"Epoch [{epoch+1}/{epochs}], Train Loss: {loss.item():.6f}, Valid Loss: {valid_loss.item():.6f}")
total_params = sum(p.numel() for p in model.parameters())
final_train_loss = loss.item()
model.eval()
with torch.no_grad():
final_valid_loss = criterion(model(x_valid), y_valid).item()
print(f"Base Model - Total Parameters: {total_params}, Final Train Loss: {final_train_loss:.6f}, Final Valid Loss: {final_valid_loss:.6f}")
return model, history, total_params
def train_adapter(model, x_train, y_train, x_valid, y_valid, epochs, lr, eval_interval):
"""Train only the adapter parameters while keeping base model frozen"""
# Only optimize trainable parameters (adapter parameters)
optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)
criterion = nn.MSELoss()
history = {'train_loss': [], 'valid_loss': [], 'epochs': []}
# For detailed step-by-step logging
detailed_history = {'step': [], 'epoch': [], 'train_loss': [], 'valid_loss': []}
adapter_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"\nTraining {model.adapter_name} - Trainable Parameters: {adapter_params}")
for epoch in range(epochs):
model.train()
optimizer.zero_grad()
y_pred = model(x_train)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
# Log every step
model.eval()
with torch.no_grad():
valid_pred = model(x_valid)
valid_loss = criterion(valid_pred, y_valid).item()
train_loss = loss.item()
detailed_history['step'].append(epoch)
detailed_history['epoch'].append(epoch + 1)
detailed_history['train_loss'].append(train_loss)
detailed_history['valid_loss'].append(valid_loss)
if (epoch + 1) % eval_interval == 0 or epoch == 0:
model.eval()
with torch.no_grad():
valid_pred = model(x_valid)
valid_loss = criterion(valid_pred, y_valid)
history['train_loss'].append(loss.item())
history['valid_loss'].append(valid_loss.item())
history['epochs'].append(epoch + 1)
print(f"Epoch [{epoch+1}/{epochs}], Train Loss: {loss.item():.6f}, Valid Loss: {valid_loss.item():.6f}")
final_train_loss = loss.item()
model.eval()
with torch.no_grad():
final_valid_loss = criterion(model(x_valid), y_valid).item()
print(f"{model.adapter_name} - Trainable Parameters: {adapter_params}, Final Train Loss: {final_train_loss:.6f}, Final Valid Loss: {final_valid_loss:.6f}")
return history, adapter_params, final_train_loss, final_valid_loss, detailed_history
def calculate_parameter_counts(input_dim, hidden_dim, output_dim, lora_rank, vera_rank, block_diag_rank, pissa_rank, dora_rank, prolora_rank, adalora_rank, mos_rank):
"""Calculate parameter counts for different adaptation methods"""
param_counts = {}
# Base model total parameters
base_model = BaseModel(input_dim, hidden_dim, output_dim)
param_counts['base_model'] = sum(p.numel() for p in base_model.parameters())
# Linear layer parameters (focus on first layer for adaptation)
linear_layer = nn.Linear(input_dim, hidden_dim)
param_counts['layer_weights'] = linear_layer.weight.numel() # weights only
param_counts['layer_total'] = sum(p.numel() for p in linear_layer.parameters()) # weights + bias
# LoRA parameters
param_counts['lora'] = lora_rank * input_dim + hidden_dim * lora_rank
# VeRA parameters
param_counts['vera'] = hidden_dim + vera_rank # b_vec and d_vec
# Block Diagonal parameters
if block_diag_rank == 0: # Avoid division by zero if rank is 0 (though unlikely for this adapter)
param_counts['block_diagonal'] = 0
else:
param_counts['block_diagonal'] = (hidden_dim * input_dim) // block_diag_rank
# PiSSA parameters
param_counts['pissa'] = pissa_rank * input_dim + hidden_dim * pissa_rank
# DoRA parameters
param_counts['dora'] = input_dim + dora_rank * input_dim + hidden_dim * dora_rank
# ProLoRA parameters (simplified, assumes 1 shared dimension)
unshared_rank = 1 # 1/4 of rank is unshared for this example
shared_rank = prolora_rank - unshared_rank
sharing_ratio = 2 # m_A and n_B are both 2
param_counts['prolora'] = (unshared_rank * input_dim + hidden_dim * unshared_rank) + \
(shared_rank * (input_dim // sharing_ratio) + (hidden_dim // sharing_ratio) * shared_rank)
# AdaLoRA parameters
param_counts['adalora'] = hidden_dim * adalora_rank + adalora_rank * input_dim + adalora_rank # P, Q, Lambda_diag
# MoS parameters
shard_ratio = 2 # Number of shards
param_counts['mos'] = (mos_rank // shard_ratio) * input_dim * shard_ratio + hidden_dim * (mos_rank // shard_ratio) * shard_ratio
return param_counts
def run_experiment():
"""Run the complete experiment with base model training and adaptation methods"""
print(f"Running experiments on device: {DEVICE}")
# Create directory for results if it doesn't exist
results_dir = "experiment_results"
os.makedirs(results_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
result_json_path = os.path.join(results_dir, f"adaptation_results_{timestamp}.json")
# Dictionary to store all experiment data
experiment_data = {
"config": {
"device": str(DEVICE),
"input_dim": INPUT_DIM,
"hidden_dim": HIDDEN_DIM,
"output_dim": OUTPUT_DIM,
"seed": SEED,
"base_epochs": BASE_EPOCHS,
"adapt_epochs": ADAPT_EPOCHS,
"base_lr": BASE_LR,
"adapt_lr": ADAPT_LR,
"noise_std": NOISE_STD,
"n_train": N_TRAIN,
"n_valid": N_VALID
},
"method_configs": {
"lora_rank": LORA_RANK,
"vera_rank": VERA_RANK,
"block_diag_rank": BLOCK_DIAG_RANK,
"pissa_rank": PISSA_RANK,
"dora_rank": DORA_RANK,
"prolora_rank": PROLORA_RANK,
"adalora_rank": ADALORA_RANK,
"mos_rank": MOS_RANK
},
"results": {}
}
# Calculate and display parameter counts
param_counts = calculate_parameter_counts(
INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM,
LORA_RANK, VERA_RANK, BLOCK_DIAG_RANK, PISSA_RANK, DORA_RANK, PROLORA_RANK, ADALORA_RANK, MOS_RANK
)
experiment_data["parameter_counts"] = param_counts
print(param_counts)
print("\n===== Parameter Counts =====")
print(f"Base Model Total: {param_counts['base_model']}")
print(f"First Layer Weights: {param_counts['layer_weights']}")
print(f"First Layer Total: {param_counts['layer_total']}")
print(f"LoRA (Rank {LORA_RANK}): {param_counts['lora']}")
print(f"VeRA (Rank {VERA_RANK}): {param_counts['vera']}")
print(f"Block Diagonal (Rank {BLOCK_DIAG_RANK}): {param_counts['block_diagonal']}")
print(f"PiSSA (Rank {PISSA_RANK}): {param_counts['pissa']}")
print(f"DoRA (Rank {DORA_RANK}): {param_counts['dora']}")
print(f"ProLoRA (Rank {PROLORA_RANK}): {param_counts['prolora']}")
print(f"AdaLoRA (Rank {ADALORA_RANK}): {param_counts['adalora']}")
print(f"MoS (Rank {MOS_RANK}): {param_counts['mos']}")
# Train base model on original function
print("\n===== Phase 1: Training Base Model on Original Function =====")
base_model = BaseModel(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM).to(DEVICE)
trained_base_model, base_history, base_params = train_base_model(
base_model, x_train_base, y_train_base, x_valid_base, y_valid_base,
BASE_EPOCHS, BASE_LR, EVAL_INTERVAL
)
experiment_data["base_model_training"] = {
"total_params": base_params,
"history": {
"epochs": base_history["epochs"],
"train_loss": [float(loss) for loss in base_history["train_loss"]],
"valid_loss": [float(loss) for loss in base_history["valid_loss"]]
}
}
# Phase 2: Adaptation to the modified function
print("\n===== Phase 2: Adapting to Modified Function =====")
results = collections.defaultdict(list)
experiment_data["results"] = {}
# 1. Full Fine-tuning (all parameters)
print("\n----- Full Fine-tuning -----")
full_finetune_model = BaseModel(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM).to(DEVICE)
# Load the base model weights
full_finetune_model.load_state_dict(trained_base_model.state_dict())
full_finetune_model.adapter_name = "FullFineTune"
# Train all parameters
full_finetune_history, full_ft_params, full_ft_train_loss, full_ft_valid_loss, full_ft_detailed = train_adapter(
full_finetune_model, x_train_adapt, y_train_adapt, x_valid_adapt, y_valid_adapt,
ADAPT_EPOCHS, ADAPT_LR, EVAL_INTERVAL
)
results['full_finetune'].append({
'params': full_ft_params,
'train_loss': full_ft_train_loss,
'valid_loss': full_ft_valid_loss,
'history': full_finetune_history,
'detailed_history': full_ft_detailed
})
experiment_data["results"]["full_finetune"] = {
"params": full_ft_params,
"final_train_loss": float(full_ft_train_loss),
"final_valid_loss": float(full_ft_valid_loss),
"detailed_history": {
"step": full_ft_detailed["step"],
"epoch": full_ft_detailed["epoch"],
"train_loss": [float(loss) for loss in full_ft_detailed["train_loss"]],
"valid_loss": [float(loss) for loss in full_ft_detailed["valid_loss"]]
}
}
# 2. LoRA Adaptation
print("----- LoRA Adaptation -----")
lora_model = BaseModel(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM).to(DEVICE)
lora_model.load_state_dict(trained_base_model.state_dict())
lora_model.layer1 = LoRAAdapter(lora_model.layer1, LORA_RANK, scale=1.0).to(DEVICE)
lora_model.adapter_name = f"LoRA (Rank {LORA_RANK})"
lora_history, lora_params, lora_train_loss, lora_valid_loss, lora_detailed = train_adapter(
lora_model, x_train_adapt, y_train_adapt, x_valid_adapt, y_valid_adapt,
ADAPT_EPOCHS, ADAPT_LR, EVAL_INTERVAL
)
results['lora'].append({
'rank': LORA_RANK,
'params': lora_params,
'train_loss': lora_train_loss,
'valid_loss': lora_valid_loss,
'history': lora_history,
'detailed_history': lora_detailed
})
experiment_data["results"]["lora"] = {
"rank": LORA_RANK,
"params": lora_params,
"final_train_loss": float(lora_train_loss),
"final_valid_loss": float(lora_valid_loss),
"detailed_history": {
"step": lora_detailed["step"],
"epoch": lora_detailed["epoch"],
"train_loss": [float(loss) for loss in lora_detailed["train_loss"]],
"valid_loss": [float(loss) for loss in lora_detailed["valid_loss"]]
}
}
# 3. VeRA Adaptation
print("----- VeRA Adaptation -----")
vera_model = BaseModel(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM).to(DEVICE)
vera_model.load_state_dict(trained_base_model.state_dict())
vera_model.layer1 = VeRAAdapter(vera_model.layer1, VERA_RANK, d_init_val=0.1).to(DEVICE)
vera_model.adapter_name = f"VeRA (Rank {VERA_RANK})"
vera_history, vera_params, vera_train_loss, vera_valid_loss, vera_detailed = train_adapter(
vera_model, x_train_adapt, y_train_adapt, x_valid_adapt, y_valid_adapt,
ADAPT_EPOCHS, ADAPT_LR, EVAL_INTERVAL
)
results['vera'].append({
'rank': VERA_RANK,
'params': vera_params,
'train_loss': vera_train_loss,
'valid_loss': vera_valid_loss,
'history': vera_history,
'detailed_history': vera_detailed
})
experiment_data["results"]["vera"] = {
"rank": VERA_RANK,
"params": vera_params,
"final_train_loss": float(vera_train_loss),
"final_valid_loss": float(vera_valid_loss),
"detailed_history": {
"step": vera_detailed["step"],
"epoch": vera_detailed["epoch"],
"train_loss": [float(loss) for loss in vera_detailed["train_loss"]],
"valid_loss": [float(loss) for loss in vera_detailed["valid_loss"]]
}
}
# 4. Block Diagonal Method
print("----- Block Diagonal Adaptation -----")
our_model = BaseModel(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM).to(DEVICE)
our_model.load_state_dict(trained_base_model.state_dict())
our_model.layer1 = BlockDiagonalAdapter(our_model.layer1, BLOCK_DIAG_RANK).to(DEVICE)
our_model.adapter_name = f"BlockDiagonal (Rank {BLOCK_DIAG_RANK})"
our_history, our_params, our_train_loss, our_valid_loss, our_detailed = train_adapter(
our_model, x_train_adapt, y_train_adapt, x_valid_adapt, y_valid_adapt,
ADAPT_EPOCHS, ADAPT_LR, EVAL_INTERVAL
)
results['block_diagonal'].append({
'rank': BLOCK_DIAG_RANK,
'params': our_params,
'train_loss': our_train_loss,
'valid_loss': our_valid_loss,
'history': our_history,
'detailed_history': our_detailed
})
experiment_data["results"]["block_diagonal"] = {
"rank": BLOCK_DIAG_RANK,
"params": our_params,
"final_train_loss": float(our_train_loss),
"final_valid_loss": float(our_valid_loss),
"detailed_history": {
"step": our_detailed["step"],
"epoch": our_detailed["epoch"],
"train_loss": [float(loss) for loss in our_detailed["train_loss"]],
"valid_loss": [float(loss) for loss in our_detailed["valid_loss"]]
}
}
# 5. PiSSA Adaptation
print("----- PiSSA Adaptation -----")
pissa_model = BaseModel(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM).to(DEVICE)
pissa_model.load_state_dict(trained_base_model.state_dict())
pissa_model.layer1 = PiSSAAdapter(pissa_model.layer1, PISSA_RANK).to(DEVICE)
pissa_history, pissa_params, pissa_train_loss, pissa_valid_loss, pissa_detailed = train_adapter(
pissa_model, x_train_adapt, y_train_adapt, x_valid_adapt, y_valid_adapt,
ADAPT_EPOCHS, ADAPT_LR, EVAL_INTERVAL
)
results['pissa'].append({
'rank': PISSA_RANK,
'params': pissa_params,