natmin322 commited on
Commit
bc95dae
·
1 Parent(s): 060b67d
improve_gainlora/_add_c5_flags.py DELETED
@@ -1,54 +0,0 @@
1
- """Add --run_single False and --n_batches_c5 100 to task 2+ in gen_scripts."""
2
- import re, os
3
-
4
- BASE = '/Users/nnminh322/Desktop/personal/Continual/improve_gainlora'
5
-
6
- T5_SCRIPTS = [
7
- os.path.join(BASE, 'gen_script_superni_order1_t5_specroute.sh'),
8
- os.path.join(BASE, 'gen_script_superni_order2_t5_specroute.sh'),
9
- os.path.join(BASE, 'gen_script_long_order3_t5_specroute.sh'),
10
- os.path.join(BASE, 'gen_script_long_order4_t5_specroute.sh'),
11
- ]
12
-
13
- for name in T5_SCRIPTS:
14
- if not os.path.exists(name):
15
- print(f'SKIP (not found): {name}')
16
- continue
17
-
18
- with open(name) as f:
19
- lines = f.readlines()
20
-
21
- # Process line by line to find and modify task 2+ blocks
22
- # Task 2+ blocks have "--per_device_train_batch_size $BSZ" but NOT "--run_single True"
23
- # We need to add --run_single False and --n_batches_c5 100 before --data_replay_freq
24
-
25
- result = []
26
- in_task_ge_2 = False
27
- for i, line in enumerate(lines):
28
- # Detect task 1: has "--run_single True"
29
- if '--run_single True' in line:
30
- in_task_ge_2 = False
31
- result.append(line)
32
- # Detect task 2+: previous task block ended, and this block has "--output_dir" with task number > 1
33
- elif 'outputs/' in line and re.search(r'/(\d+)-', line):
34
- task_num = int(re.search(r'/(\d+)-', line).group(1))
35
- in_task_ge_2 = task_num > 1
36
- result.append(line)
37
- # Add flags before --data_replay_freq for task 2+
38
- elif in_task_ge_2 and line.strip() == '--data_replay_freq -1 \\':
39
- # Check if we need to add the flags
40
- # Look back to see if --run_single or --n_batches_c5 already present in recent lines
41
- recent = ''.join(lines[max(0, i-20):i])
42
- if '--run_single' not in recent and '--n_batches_c5' not in recent:
43
- result.append(' --run_single False \\\n')
44
- result.append(' --n_batches_c5 100 \\\n')
45
- result.append(line)
46
- else:
47
- result.append(line)
48
-
49
- with open(name, 'w') as f:
50
- f.writelines(result)
51
-
52
- print(f'{os.path.basename(name)}: added C5 flags')
53
-
54
- print('Done.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
improve_gainlora/gen_script_long_order3_t5_specroute.sh CHANGED
@@ -42,7 +42,7 @@ elif [ "$IS_T4" -eq 1 ]; then
42
  GPU_IDS="${1:-0}"
43
  FP16_FLAG="--gradient_checkpointing"
44
  echo "[GPU] Strategy: 1x T4 + fp32 + gradient_checkpointing"
45
- elif [ "$GPU_MEM" -gt 16000 ]; then
46
  GPU_MODE="p100"
47
  GPU_IDS="${1:-0}"
48
  FP16_FLAG="--gradient_checkpointing"
@@ -63,7 +63,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
63
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
64
  BSZ=4; GA=8; EVAL_BSZ=16
65
  elif [ "$GPU_MODE" = "p100" ]; then
66
- BSZ=8; GA=4; EVAL_BSZ=4
67
  else
68
  BSZ=8; GA=4; EVAL_BSZ=128
69
  fi
@@ -118,7 +118,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
118
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
119
  BSZ=4; GA=8; EVAL_BSZ=16
120
  elif [ "$GPU_MODE" = "p100" ]; then
121
- BSZ=8; GA=4; EVAL_BSZ=4
122
  else
123
  BSZ=16; GA=2; EVAL_BSZ=128
124
  fi
@@ -175,7 +175,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
175
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
176
  BSZ=4; GA=8; EVAL_BSZ=16
177
  elif [ "$GPU_MODE" = "p100" ]; then
178
- BSZ=8; GA=4; EVAL_BSZ=4
179
  else
180
  BSZ=16; GA=2; EVAL_BSZ=128
181
  fi
@@ -232,7 +232,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
232
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
233
  BSZ=4; GA=8; EVAL_BSZ=16
234
  elif [ "$GPU_MODE" = "p100" ]; then
235
- BSZ=8; GA=4; EVAL_BSZ=4
236
  else
237
  BSZ=16; GA=2; EVAL_BSZ=128
238
  fi
@@ -289,7 +289,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
289
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
290
  BSZ=4; GA=8; EVAL_BSZ=16
291
  elif [ "$GPU_MODE" = "p100" ]; then
292
- BSZ=8; GA=4; EVAL_BSZ=4
293
  else
294
  BSZ=16; GA=2; EVAL_BSZ=128
295
  fi
@@ -346,7 +346,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
346
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
347
  BSZ=4; GA=8; EVAL_BSZ=16
348
  elif [ "$GPU_MODE" = "p100" ]; then
349
- BSZ=8; GA=4; EVAL_BSZ=4
350
  else
351
  BSZ=16; GA=2; EVAL_BSZ=128
352
  fi
@@ -403,7 +403,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
403
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
404
  BSZ=4; GA=8; EVAL_BSZ=16
405
  elif [ "$GPU_MODE" = "p100" ]; then
406
- BSZ=8; GA=4; EVAL_BSZ=4
407
  else
408
  BSZ=16; GA=2; EVAL_BSZ=128
409
  fi
@@ -460,7 +460,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
460
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
461
  BSZ=4; GA=8; EVAL_BSZ=16
462
  elif [ "$GPU_MODE" = "p100" ]; then
463
- BSZ=8; GA=4; EVAL_BSZ=4
464
  else
465
  BSZ=16; GA=2; EVAL_BSZ=128
466
  fi
@@ -517,7 +517,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
517
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
518
  BSZ=4; GA=8; EVAL_BSZ=16
519
  elif [ "$GPU_MODE" = "p100" ]; then
520
- BSZ=8; GA=4; EVAL_BSZ=4
521
  else
522
  BSZ=16; GA=2; EVAL_BSZ=128
523
  fi
@@ -574,7 +574,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
574
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
575
  BSZ=4; GA=8; EVAL_BSZ=16
576
  elif [ "$GPU_MODE" = "p100" ]; then
577
- BSZ=8; GA=4; EVAL_BSZ=4
578
  else
579
  BSZ=16; GA=2; EVAL_BSZ=128
580
  fi
@@ -631,7 +631,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
631
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
632
  BSZ=4; GA=8; EVAL_BSZ=16
633
  elif [ "$GPU_MODE" = "p100" ]; then
634
- BSZ=8; GA=4; EVAL_BSZ=4
635
  else
636
  BSZ=16; GA=2; EVAL_BSZ=128
637
  fi
@@ -688,7 +688,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
688
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
689
  BSZ=4; GA=8; EVAL_BSZ=16
690
  elif [ "$GPU_MODE" = "p100" ]; then
691
- BSZ=8; GA=4; EVAL_BSZ=4
692
  else
693
  BSZ=16; GA=2; EVAL_BSZ=128
694
  fi
@@ -745,7 +745,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
745
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
746
  BSZ=4; GA=8; EVAL_BSZ=16
747
  elif [ "$GPU_MODE" = "p100" ]; then
748
- BSZ=8; GA=4; EVAL_BSZ=4
749
  else
750
  BSZ=16; GA=2; EVAL_BSZ=128
751
  fi
@@ -802,7 +802,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
802
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
803
  BSZ=4; GA=8; EVAL_BSZ=16
804
  elif [ "$GPU_MODE" = "p100" ]; then
805
- BSZ=8; GA=4; EVAL_BSZ=4
806
  else
807
  BSZ=16; GA=2; EVAL_BSZ=128
808
  fi
@@ -859,7 +859,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
859
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
860
  BSZ=4; GA=8; EVAL_BSZ=16
861
  elif [ "$GPU_MODE" = "p100" ]; then
862
- BSZ=8; GA=4; EVAL_BSZ=4
863
  else
864
  BSZ=16; GA=2; EVAL_BSZ=128
865
  fi
 
42
  GPU_IDS="${1:-0}"
43
  FP16_FLAG="--gradient_checkpointing"
44
  echo "[GPU] Strategy: 1x T4 + fp32 + gradient_checkpointing"
45
+ elif [ "$GPU_MEM" -le 17000 ]; then
46
  GPU_MODE="p100"
47
  GPU_IDS="${1:-0}"
48
  FP16_FLAG="--gradient_checkpointing"
 
63
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
64
  BSZ=4; GA=8; EVAL_BSZ=16
65
  elif [ "$GPU_MODE" = "p100" ]; then
66
+ BSZ=16; GA=2; EVAL_BSZ=32
67
  else
68
  BSZ=8; GA=4; EVAL_BSZ=128
69
  fi
 
118
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
119
  BSZ=4; GA=8; EVAL_BSZ=16
120
  elif [ "$GPU_MODE" = "p100" ]; then
121
+ BSZ=16; GA=2; EVAL_BSZ=32
122
  else
123
  BSZ=16; GA=2; EVAL_BSZ=128
124
  fi
 
175
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
176
  BSZ=4; GA=8; EVAL_BSZ=16
177
  elif [ "$GPU_MODE" = "p100" ]; then
178
+ BSZ=16; GA=2; EVAL_BSZ=32
179
  else
180
  BSZ=16; GA=2; EVAL_BSZ=128
181
  fi
 
232
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
233
  BSZ=4; GA=8; EVAL_BSZ=16
234
  elif [ "$GPU_MODE" = "p100" ]; then
235
+ BSZ=16; GA=2; EVAL_BSZ=32
236
  else
237
  BSZ=16; GA=2; EVAL_BSZ=128
238
  fi
 
289
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
290
  BSZ=4; GA=8; EVAL_BSZ=16
291
  elif [ "$GPU_MODE" = "p100" ]; then
292
+ BSZ=16; GA=2; EVAL_BSZ=32
293
  else
294
  BSZ=16; GA=2; EVAL_BSZ=128
295
  fi
 
346
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
347
  BSZ=4; GA=8; EVAL_BSZ=16
348
  elif [ "$GPU_MODE" = "p100" ]; then
349
+ BSZ=16; GA=2; EVAL_BSZ=32
350
  else
351
  BSZ=16; GA=2; EVAL_BSZ=128
352
  fi
 
403
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
404
  BSZ=4; GA=8; EVAL_BSZ=16
405
  elif [ "$GPU_MODE" = "p100" ]; then
406
+ BSZ=16; GA=2; EVAL_BSZ=32
407
  else
408
  BSZ=16; GA=2; EVAL_BSZ=128
409
  fi
 
460
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
461
  BSZ=4; GA=8; EVAL_BSZ=16
462
  elif [ "$GPU_MODE" = "p100" ]; then
463
+ BSZ=16; GA=2; EVAL_BSZ=32
464
  else
465
  BSZ=16; GA=2; EVAL_BSZ=128
466
  fi
 
517
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
518
  BSZ=4; GA=8; EVAL_BSZ=16
519
  elif [ "$GPU_MODE" = "p100" ]; then
520
+ BSZ=16; GA=2; EVAL_BSZ=32
521
  else
522
  BSZ=16; GA=2; EVAL_BSZ=128
523
  fi
 
574
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
575
  BSZ=4; GA=8; EVAL_BSZ=16
576
  elif [ "$GPU_MODE" = "p100" ]; then
577
+ BSZ=16; GA=2; EVAL_BSZ=32
578
  else
579
  BSZ=16; GA=2; EVAL_BSZ=128
580
  fi
 
631
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
632
  BSZ=4; GA=8; EVAL_BSZ=16
633
  elif [ "$GPU_MODE" = "p100" ]; then
634
+ BSZ=16; GA=2; EVAL_BSZ=32
635
  else
636
  BSZ=16; GA=2; EVAL_BSZ=128
637
  fi
 
688
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
689
  BSZ=4; GA=8; EVAL_BSZ=16
690
  elif [ "$GPU_MODE" = "p100" ]; then
691
+ BSZ=16; GA=2; EVAL_BSZ=32
692
  else
693
  BSZ=16; GA=2; EVAL_BSZ=128
694
  fi
 
745
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
746
  BSZ=4; GA=8; EVAL_BSZ=16
747
  elif [ "$GPU_MODE" = "p100" ]; then
748
+ BSZ=16; GA=2; EVAL_BSZ=32
749
  else
750
  BSZ=16; GA=2; EVAL_BSZ=128
751
  fi
 
802
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
803
  BSZ=4; GA=8; EVAL_BSZ=16
804
  elif [ "$GPU_MODE" = "p100" ]; then
805
+ BSZ=16; GA=2; EVAL_BSZ=32
806
  else
807
  BSZ=16; GA=2; EVAL_BSZ=128
808
  fi
 
859
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
860
  BSZ=4; GA=8; EVAL_BSZ=16
861
  elif [ "$GPU_MODE" = "p100" ]; then
862
+ BSZ=16; GA=2; EVAL_BSZ=32
863
  else
864
  BSZ=16; GA=2; EVAL_BSZ=128
865
  fi
improve_gainlora/gen_script_long_order4_t5_specroute.sh CHANGED
@@ -42,7 +42,7 @@ elif [ "$IS_T4" -eq 1 ]; then
42
  GPU_IDS="${1:-0}"
43
  FP16_FLAG="--gradient_checkpointing"
44
  echo "[GPU] Strategy: 1x T4 + fp32 + gradient_checkpointing"
45
- elif [ "$GPU_MEM" -gt 16000 ]; then
46
  GPU_MODE="p100"
47
  GPU_IDS="${1:-0}"
48
  FP16_FLAG="--gradient_checkpointing"
@@ -63,7 +63,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
63
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
64
  BSZ=4; GA=8; EVAL_BSZ=16
65
  elif [ "$GPU_MODE" = "p100" ]; then
66
- BSZ=8; GA=4; EVAL_BSZ=4
67
  else
68
  BSZ=8; GA=4; EVAL_BSZ=128
69
  fi
@@ -118,7 +118,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
118
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
119
  BSZ=4; GA=8; EVAL_BSZ=16
120
  elif [ "$GPU_MODE" = "p100" ]; then
121
- BSZ=8; GA=4; EVAL_BSZ=4
122
  else
123
  BSZ=16; GA=2; EVAL_BSZ=128
124
  fi
@@ -175,7 +175,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
175
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
176
  BSZ=4; GA=8; EVAL_BSZ=16
177
  elif [ "$GPU_MODE" = "p100" ]; then
178
- BSZ=8; GA=4; EVAL_BSZ=4
179
  else
180
  BSZ=16; GA=2; EVAL_BSZ=128
181
  fi
@@ -232,7 +232,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
232
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
233
  BSZ=4; GA=8; EVAL_BSZ=16
234
  elif [ "$GPU_MODE" = "p100" ]; then
235
- BSZ=8; GA=4; EVAL_BSZ=4
236
  else
237
  BSZ=16; GA=2; EVAL_BSZ=128
238
  fi
@@ -289,7 +289,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
289
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
290
  BSZ=4; GA=8; EVAL_BSZ=16
291
  elif [ "$GPU_MODE" = "p100" ]; then
292
- BSZ=8; GA=4; EVAL_BSZ=4
293
  else
294
  BSZ=16; GA=2; EVAL_BSZ=128
295
  fi
@@ -346,7 +346,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
346
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
347
  BSZ=4; GA=8; EVAL_BSZ=16
348
  elif [ "$GPU_MODE" = "p100" ]; then
349
- BSZ=8; GA=4; EVAL_BSZ=4
350
  else
351
  BSZ=16; GA=2; EVAL_BSZ=128
352
  fi
@@ -403,7 +403,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
403
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
404
  BSZ=4; GA=8; EVAL_BSZ=16
405
  elif [ "$GPU_MODE" = "p100" ]; then
406
- BSZ=8; GA=4; EVAL_BSZ=4
407
  else
408
  BSZ=16; GA=2; EVAL_BSZ=128
409
  fi
@@ -460,7 +460,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
460
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
461
  BSZ=4; GA=8; EVAL_BSZ=16
462
  elif [ "$GPU_MODE" = "p100" ]; then
463
- BSZ=8; GA=4; EVAL_BSZ=4
464
  else
465
  BSZ=16; GA=2; EVAL_BSZ=128
466
  fi
@@ -517,7 +517,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
517
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
518
  BSZ=4; GA=8; EVAL_BSZ=16
519
  elif [ "$GPU_MODE" = "p100" ]; then
520
- BSZ=8; GA=4; EVAL_BSZ=4
521
  else
522
  BSZ=16; GA=2; EVAL_BSZ=128
523
  fi
@@ -574,7 +574,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
574
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
575
  BSZ=4; GA=8; EVAL_BSZ=16
576
  elif [ "$GPU_MODE" = "p100" ]; then
577
- BSZ=8; GA=4; EVAL_BSZ=4
578
  else
579
  BSZ=16; GA=2; EVAL_BSZ=128
580
  fi
@@ -631,7 +631,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
631
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
632
  BSZ=4; GA=8; EVAL_BSZ=16
633
  elif [ "$GPU_MODE" = "p100" ]; then
634
- BSZ=8; GA=4; EVAL_BSZ=4
635
  else
636
  BSZ=16; GA=2; EVAL_BSZ=128
637
  fi
@@ -688,7 +688,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
688
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
689
  BSZ=4; GA=8; EVAL_BSZ=16
690
  elif [ "$GPU_MODE" = "p100" ]; then
691
- BSZ=8; GA=4; EVAL_BSZ=4
692
  else
693
  BSZ=16; GA=2; EVAL_BSZ=128
694
  fi
@@ -745,7 +745,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
745
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
746
  BSZ=4; GA=8; EVAL_BSZ=16
747
  elif [ "$GPU_MODE" = "p100" ]; then
748
- BSZ=8; GA=4; EVAL_BSZ=4
749
  else
750
  BSZ=16; GA=2; EVAL_BSZ=128
751
  fi
@@ -802,7 +802,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
802
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
803
  BSZ=4; GA=8; EVAL_BSZ=16
804
  elif [ "$GPU_MODE" = "p100" ]; then
805
- BSZ=8; GA=4; EVAL_BSZ=4
806
  else
807
  BSZ=16; GA=2; EVAL_BSZ=128
808
  fi
@@ -859,7 +859,7 @@ if [ "$GPU_MODE" = "t4_2gpu" ]; then
859
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
860
  BSZ=4; GA=8; EVAL_BSZ=16
861
  elif [ "$GPU_MODE" = "p100" ]; then
862
- BSZ=8; GA=4; EVAL_BSZ=4
863
  else
864
  BSZ=16; GA=2; EVAL_BSZ=128
865
  fi
 
42
  GPU_IDS="${1:-0}"
43
  FP16_FLAG="--gradient_checkpointing"
44
  echo "[GPU] Strategy: 1x T4 + fp32 + gradient_checkpointing"
45
+ elif [ "$GPU_MEM" -le 17000 ]; then
46
  GPU_MODE="p100"
47
  GPU_IDS="${1:-0}"
48
  FP16_FLAG="--gradient_checkpointing"
 
63
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
64
  BSZ=4; GA=8; EVAL_BSZ=16
65
  elif [ "$GPU_MODE" = "p100" ]; then
66
+ BSZ=16; GA=2; EVAL_BSZ=32
67
  else
68
  BSZ=8; GA=4; EVAL_BSZ=128
69
  fi
 
118
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
119
  BSZ=4; GA=8; EVAL_BSZ=16
120
  elif [ "$GPU_MODE" = "p100" ]; then
121
+ BSZ=16; GA=2; EVAL_BSZ=32
122
  else
123
  BSZ=16; GA=2; EVAL_BSZ=128
124
  fi
 
175
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
176
  BSZ=4; GA=8; EVAL_BSZ=16
177
  elif [ "$GPU_MODE" = "p100" ]; then
178
+ BSZ=16; GA=2; EVAL_BSZ=32
179
  else
180
  BSZ=16; GA=2; EVAL_BSZ=128
181
  fi
 
232
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
233
  BSZ=4; GA=8; EVAL_BSZ=16
234
  elif [ "$GPU_MODE" = "p100" ]; then
235
+ BSZ=16; GA=2; EVAL_BSZ=32
236
  else
237
  BSZ=16; GA=2; EVAL_BSZ=128
238
  fi
 
289
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
290
  BSZ=4; GA=8; EVAL_BSZ=16
291
  elif [ "$GPU_MODE" = "p100" ]; then
292
+ BSZ=16; GA=2; EVAL_BSZ=32
293
  else
294
  BSZ=16; GA=2; EVAL_BSZ=128
295
  fi
 
346
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
347
  BSZ=4; GA=8; EVAL_BSZ=16
348
  elif [ "$GPU_MODE" = "p100" ]; then
349
+ BSZ=16; GA=2; EVAL_BSZ=32
350
  else
351
  BSZ=16; GA=2; EVAL_BSZ=128
352
  fi
 
403
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
404
  BSZ=4; GA=8; EVAL_BSZ=16
405
  elif [ "$GPU_MODE" = "p100" ]; then
406
+ BSZ=16; GA=2; EVAL_BSZ=32
407
  else
408
  BSZ=16; GA=2; EVAL_BSZ=128
409
  fi
 
460
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
461
  BSZ=4; GA=8; EVAL_BSZ=16
462
  elif [ "$GPU_MODE" = "p100" ]; then
463
+ BSZ=16; GA=2; EVAL_BSZ=32
464
  else
465
  BSZ=16; GA=2; EVAL_BSZ=128
466
  fi
 
517
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
518
  BSZ=4; GA=8; EVAL_BSZ=16
519
  elif [ "$GPU_MODE" = "p100" ]; then
520
+ BSZ=16; GA=2; EVAL_BSZ=32
521
  else
522
  BSZ=16; GA=2; EVAL_BSZ=128
523
  fi
 
574
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
575
  BSZ=4; GA=8; EVAL_BSZ=16
576
  elif [ "$GPU_MODE" = "p100" ]; then
577
+ BSZ=16; GA=2; EVAL_BSZ=32
578
  else
579
  BSZ=16; GA=2; EVAL_BSZ=128
580
  fi
 
631
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
632
  BSZ=4; GA=8; EVAL_BSZ=16
633
  elif [ "$GPU_MODE" = "p100" ]; then
634
+ BSZ=16; GA=2; EVAL_BSZ=32
635
  else
636
  BSZ=16; GA=2; EVAL_BSZ=128
637
  fi
 
688
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
689
  BSZ=4; GA=8; EVAL_BSZ=16
690
  elif [ "$GPU_MODE" = "p100" ]; then
691
+ BSZ=16; GA=2; EVAL_BSZ=32
692
  else
693
  BSZ=16; GA=2; EVAL_BSZ=128
694
  fi
 
745
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
746
  BSZ=4; GA=8; EVAL_BSZ=16
747
  elif [ "$GPU_MODE" = "p100" ]; then
748
+ BSZ=16; GA=2; EVAL_BSZ=32
749
  else
750
  BSZ=16; GA=2; EVAL_BSZ=128
751
  fi
 
802
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
803
  BSZ=4; GA=8; EVAL_BSZ=16
804
  elif [ "$GPU_MODE" = "p100" ]; then
805
+ BSZ=16; GA=2; EVAL_BSZ=32
806
  else
807
  BSZ=16; GA=2; EVAL_BSZ=128
808
  fi
 
859
  elif [ "$GPU_MODE" = "t4_1gpu" ]; then
860
  BSZ=4; GA=8; EVAL_BSZ=16
861
  elif [ "$GPU_MODE" = "p100" ]; then
862
+ BSZ=16; GA=2; EVAL_BSZ=32
863
  else
864
  BSZ=16; GA=2; EVAL_BSZ=128
865
  fi
improve_gainlora/src/cl_trainer_specroute.py CHANGED
@@ -12,7 +12,6 @@ Key differences from GainLoRA_InfLoRA_Trainer:
12
 
13
  import gc
14
  import torch
15
- import math as _math
16
  from torch.utils.data import DataLoader
17
  from torch.utils.data.distributed import DistributedSampler
18
  from transformers import GenerationConfig
@@ -141,30 +140,9 @@ class SpecRoute_Trainer(Seq2SeqTrainer):
141
  self._precond_matrices[id(lora.lora_B)] = inv_sqrt.to(lora.lora_B.data.device)
142
  print(f"[C4] Precomputed {len(self._precond_matrices)} preconditioner matrices")
143
 
144
- def _compute_spectral_entropy_loss(self):
145
- """Compute spectral entropy regularization via efficient QR trick.
146
- For each LoRA layer: QR(B) and QR(A^T) -> SVD of r×r matrix -> entropy."""
147
- ent_loss = torch.tensor(0.0, device=self.args.device)
148
- count = 0
149
- for module in self.model.modules():
150
- if not (hasattr(module, 'lora_q') and hasattr(module, 'lora_v')):
151
- continue
152
- for lora in [module.lora_q, module.lora_v]:
153
- B = lora.lora_B.float() # [d_out, r]
154
- A = lora.lora_A.float() # [r, d_in]
155
- if B.norm() < 1e-8:
156
- continue
157
- _, R_B = torch.linalg.qr(B) # B: [d_out, r] -> R_B: [r, r]
158
- _, R_A = torch.linalg.qr(A.T) # A.T: [d_in, r] -> R_A: [r, r]
159
- sigma_hat = torch.linalg.svdvals(R_B @ R_A.T) # [r, r] @ [r, r] -> [r, r] -> [r]
160
- sigma_hat = sigma_hat / (sigma_hat.sum() + 1e-12)
161
- ent = -(sigma_hat * torch.log(sigma_hat + 1e-12)).sum()
162
- max_ent = _math.log(sigma_hat.size(0))
163
- ent_loss = ent_loss + (max_ent - ent)
164
- count += 1
165
- if count > 0:
166
- ent_loss = ent_loss / count
167
- return ent_loss
168
 
169
  def _apply_preconditioning(self):
170
  """Apply (AA^T + eps*I)^{-1/2} preconditioner to lora_B gradients after backward."""
@@ -412,7 +390,7 @@ class SpecRoute_Trainer(Seq2SeqTrainer):
412
  else:
413
  labels = None
414
  outputs = self.model(**inputs)
415
- if step > 200: # 200 batches sufficient for stable SVD (reduced from 1000 for speed)
416
  break
417
  print('end get representation')
418
 
 
12
 
13
  import gc
14
  import torch
 
15
  from torch.utils.data import DataLoader
16
  from torch.utils.data.distributed import DistributedSampler
17
  from transformers import GenerationConfig
 
140
  self._precond_matrices[id(lora.lora_B)] = inv_sqrt.to(lora.lora_B.data.device)
141
  print(f"[C4] Precomputed {len(self._precond_matrices)} preconditioner matrices")
142
 
143
+ # NOTE: _compute_spectral_entropy_loss() removed in V7.
144
+ # Entropy regularization conflicts with C5 data-informed init philosophy.
145
+ # lambda_entropy is hardcoded to 0.0 and this method was dead code.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  def _apply_preconditioning(self):
148
  """Apply (AA^T + eps*I)^{-1/2} preconditioner to lora_B gradients after backward."""
 
390
  else:
391
  labels = None
392
  outputs = self.model(**inputs)
393
+ if step > 100: # 100 batches sufficient for stable SVD
394
  break
395
  print('end get representation')
396
 
improve_gainlora/src/run_t5.py CHANGED
@@ -638,21 +638,15 @@ def main():
638
  previous_lora_list_sig = model_args.previous_lora_path.split(',')
639
  previous_lora_list_sig.reverse()
640
  spectral_sigs = []
641
- task_protos = []
642
  for path in previous_lora_list_sig:
643
  sig_path = os.path.join(path, "spectral_signatures.pt")
644
  if os.path.exists(sig_path):
645
  sig = torch.load(sig_path, map_location=device)
646
  spectral_sigs.append(sig)
647
- proto_path = os.path.join(path, "task_prototype.pt")
648
- if os.path.exists(proto_path):
649
- task_protos.append(torch.load(proto_path, map_location='cpu'))
650
  model.encoder.spectral_signatures = spectral_sigs
651
- model.encoder.task_prototypes = task_protos
652
  del previous_lora_list_sig
653
  gc.collect()
654
- print(f"----------Loaded {len(spectral_sigs)} spectral signatures, "
655
- f"{len(task_protos)} task prototypes----------")
656
 
657
  for name, param in model.named_parameters():
658
  if training_args.model_name in ['gainlora_olora', 'olora']:
@@ -1034,12 +1028,6 @@ def main():
1034
  from t5_specroute import compute_spectral_signatures
1035
  signatures = compute_spectral_signatures(trainer.model, config)
1036
  torch.save(signatures, os.path.join(save_path, 'spectral_signatures.pt'))
1037
- # Finalize and save task prototype (V5)
1038
- trainer.model.encoder.finalize_prototype()
1039
- if trainer.model.encoder._current_task_prototype is not None:
1040
- torch.save(trainer.model.encoder._current_task_prototype,
1041
- os.path.join(save_path, 'task_prototype.pt'))
1042
- print("----------Saved task prototype----------")
1043
  print("----------Saved spectral signatures----------")
1044
  # Only save tokenizer for non-specroute (specroute never reloads it)
1045
  if training_args.model_name != 'specroute':
 
638
  previous_lora_list_sig = model_args.previous_lora_path.split(',')
639
  previous_lora_list_sig.reverse()
640
  spectral_sigs = []
 
641
  for path in previous_lora_list_sig:
642
  sig_path = os.path.join(path, "spectral_signatures.pt")
643
  if os.path.exists(sig_path):
644
  sig = torch.load(sig_path, map_location=device)
645
  spectral_sigs.append(sig)
 
 
 
646
  model.encoder.spectral_signatures = spectral_sigs
 
647
  del previous_lora_list_sig
648
  gc.collect()
649
+ print(f"----------Loaded {len(spectral_sigs)} spectral signatures----------")
 
650
 
651
  for name, param in model.named_parameters():
652
  if training_args.model_name in ['gainlora_olora', 'olora']:
 
1028
  from t5_specroute import compute_spectral_signatures
1029
  signatures = compute_spectral_signatures(trainer.model, config)
1030
  torch.save(signatures, os.path.join(save_path, 'spectral_signatures.pt'))
 
 
 
 
 
 
1031
  print("----------Saved spectral signatures----------")
1032
  # Only save tokenizer for non-specroute (specroute never reloads it)
1033
  if training_args.model_name != 'specroute':
improve_gainlora/src/t5_specroute.py CHANGED
@@ -178,28 +178,12 @@ class T5Stack(T5PreTrainedModel):
178
 
179
  self.prompt_config = prompt_config
180
 
181
- if not self.is_decoder:
182
- # Prototype-based inference routing (V5)
183
- # Task centroids in input embedding space — immune to GPM constraints.
184
- # Must be initialized for ALL tasks (including first/run_single) since
185
- # _update_prototype() is called during every training forward pass.
186
- self.task_prototypes = [] # List[Tensor(d,)] — normalized μ_k, old tasks
187
- self._current_prototype_sum = None # Running sum for current task (CPU float)
188
- self._current_prototype_count = 0
189
- self._current_task_prototype = None # Finalized normalized prototype
190
-
191
  if not self.is_decoder and not prompt_config["run_single"]:
192
  # ===== Spectral routing: NO learned parameters for routing =====
193
  # Spectral signatures loaded from previous tasks' saved weights
194
  self.spectral_signatures = [] # List[dict] — one dict per old task
195
  self.routing_temperature = prompt_config.get('attn_temperature', 1.0)
196
 
197
- # Prototype routing temperature (V5): cosine similarities are in a much
198
- # narrower range (~0.85-0.95) than spectral fits (~0-0.5). A separate,
199
- # lower temperature ensures discriminative softmax for prototype routing.
200
- # τ_proto = 0.01 → for gap=0.05, ratio = e^5 ≈ 148 (semi-hard routing).
201
- self._prototype_temperature = 0.01
202
-
203
  # Adaptive training bias: β = T·ln(α·n_old/(1−α))
204
  # Ensures current task gets consistent routing weight ~α regardless
205
  # of total number of tasks (fixes softmax dilution with constant bias).
@@ -251,8 +235,6 @@ class T5Stack(T5PreTrainedModel):
251
 
252
  fits = []
253
 
254
- _use_proto = False
255
-
256
  if self.training:
257
  # === TRAINING MODE: A-row fit + adaptive bias for current task ===
258
  # A rows give stable non-zero signal even when B=0 (cold-start).
@@ -276,83 +258,40 @@ class T5Stack(T5PreTrainedModel):
276
  current_fit = current_fit + beta
277
  fits.append(current_fit)
278
  else:
279
- # === INFERENCE MODE ===
280
- # Try prototype routing (V5): cosine similarity in embedding space.
281
- # Immune to GPM constraints — handles same-domain tasks correctly.
282
- _n_expected = 1 + len(self.spectral_signatures)
283
- _protos = []
284
- if self._current_task_prototype is not None:
285
- _protos.append(self._current_task_prototype)
286
- elif self._current_prototype_sum is not None and self._current_prototype_count > 0:
287
- # During training eval: use running mean as approximate prototype
288
- _tmp = self._current_prototype_sum / self._current_prototype_count
289
- _protos.append(_tmp / (_tmp.norm() + 1e-8))
290
- _protos.extend(self.task_prototypes)
291
-
292
- if len(_protos) == _n_expected:
293
- # Prototype routing for ALL tasks
294
- _use_proto = True
295
- h_flat = h.squeeze(1) # (B, d_model)
296
- h_norm = h_flat.norm(dim=-1, keepdim=True).clamp(min=1e-8) # (B, 1)
297
-
298
- # One-time diagnostic: pairwise cosine similarity between prototypes
299
- if self.is_inference and not getattr(self, '_proto_diag_done', False):
300
- self._proto_diag_done = True
301
- _pstack = torch.stack([p.to(h_flat.device, dtype=h_flat.dtype) for p in _protos])
302
- _pair = torch.matmul(_pstack, _pstack.T) # already unit-norm → cosine sim
303
- _mask = ~torch.eye(_pair.size(0), dtype=torch.bool, device=_pair.device)
304
- _offdiag = _pair[_mask]
305
- print(f"[SpecRoute] Prototype cosine matrix (n={_pair.size(0)}): "
306
- f"off-diag min={_offdiag.min():.4f}, max={_offdiag.max():.4f}, "
307
- f"mean={_offdiag.mean():.4f}, std={_offdiag.std():.4f}")
308
- if _offdiag.max() > 0.99:
309
- print(f"[SpecRoute] WARNING: some prototypes are near-identical "
310
- f"(max cos={_offdiag.max():.4f}). Consider mean-centering.")
311
-
312
- for proto in _protos:
313
- p = proto.to(h_flat.device, dtype=h_flat.dtype) # (d,) normalized
314
- cos_sim = torch.matmul(h_flat, p.unsqueeze(-1)) / h_norm # (B, 1)
315
- fits.append(cos_sim)
316
- else:
317
- # Fallback: SVD-based spectral routing (V3)
318
- if self._current_task_svd is not None:
319
- cur_fits = []
320
- for key, sig_data in self._current_task_svd.items():
321
- if not key.startswith('enc.'):
322
- continue
323
- V = sig_data['V'].to(h.device, dtype=h.dtype)
324
- sigma = sig_data['sigma'].to(h.device, dtype=h.dtype)
325
- proj = torch.matmul(h, V.T)
326
- sigma_sq = sigma ** 2
327
- sigma_sq_sum = sigma_sq.sum() + 1e-8
328
- weighted_proj = (proj ** 2 * sigma_sq.unsqueeze(0).unsqueeze(0)).sum(dim=-1)
329
- fit = weighted_proj / (sigma_sq_sum * h_norm_sq)
330
- cur_fits.append(fit)
331
- if cur_fits:
332
- current_fit = torch.stack(cur_fits).mean(dim=0)
333
- else:
334
- current_fit = torch.zeros(h.shape[0], 1, device=h.device, dtype=h.dtype)
335
  else:
336
- current_fits_layers = []
337
- for block in self.block:
338
- attn = block.layer[0].SelfAttention
339
- for lora in [attn.lora_q, attn.lora_v]:
340
- A = lora.lora_A.data.float()
341
- r = lora.r
342
- A_h = A.to(h.device, dtype=h.dtype)
343
- proj = torch.matmul(h, A_h.T)
344
- fit = (proj ** 2).sum(dim=-1) / (r * h_norm_sq)
345
- current_fits_layers.append(fit)
346
- current_fit = torch.stack(current_fits_layers).mean(dim=0)
347
- fits.append(current_fit)
348
-
349
- # Early return for prototype routing (uses separate temperature)
350
- if _use_proto:
351
- fit_scores = torch.cat(fits, dim=1) # (B, n_tasks)
352
- weights = torch.softmax(fit_scores / self._prototype_temperature, dim=1)
353
- return weights.unsqueeze(2) # (B, n_tasks, 1)
354
-
355
- # Old tasks: spectral signatures (training or fallback inference)
356
  for sig_dict in self.spectral_signatures:
357
  task_fits = []
358
  for key, sig_data in sig_dict.items():
@@ -398,40 +337,13 @@ class T5Stack(T5PreTrainedModel):
398
  B = lora.lora_B.data.float()
399
  r = lora.r
400
  S, Vt = _thin_svd_low_rank(B, A)
401
- sigs[f'enc.{j}.self.{name}'] = {
402
  'V': Vt[:r].cpu(),
403
  'sigma': S[:r].cpu()
404
  }
405
  self._current_task_svd = sigs
406
  print(f"[SpecRoute] Prepared inference routing: {len(sigs)} encoder SVD signatures for current task")
407
 
408
- def _update_prototype(self, h_batch):
409
- """Accumulate running mean for current task prototype.
410
- Called during training forward passes.
411
- Args:
412
- h_batch: (B, d_model) — attention-masked mean of input embeddings
413
- """
414
- with torch.no_grad():
415
- batch_sum = h_batch.detach().float().sum(dim=0).cpu()
416
- count = h_batch.size(0)
417
- if self._current_prototype_sum is None:
418
- self._current_prototype_sum = batch_sum
419
- self._current_prototype_count = count
420
- else:
421
- self._current_prototype_sum = self._current_prototype_sum + batch_sum
422
- self._current_prototype_count += count
423
-
424
- def finalize_prototype(self):
425
- """Finalize current task prototype from accumulated running mean."""
426
- if self._current_prototype_sum is not None and self._current_prototype_count > 0:
427
- proto = self._current_prototype_sum / self._current_prototype_count
428
- proto = proto / (proto.norm() + 1e-8)
429
- self._current_task_prototype = proto
430
- print(f"[SpecRoute] Finalized task prototype "
431
- f"({self._current_prototype_count} samples, d={proto.shape[0]})")
432
- self._current_prototype_sum = None
433
- self._current_prototype_count = 0
434
-
435
  def parallelize(self, device_map=None):
436
  self.device_map = (
437
  get_device_map(len(self.block), range(torch.cuda.device_count()))
@@ -512,19 +424,15 @@ class T5Stack(T5PreTrainedModel):
512
 
513
  batch_size, seq_length = input_shape
514
 
515
- # ============ SPECTRAL ROUTING + PROTOTYPE (V5) ============
516
  self.key_attention_weights = None
517
  if not self.is_decoder:
518
- # Properly masked mean of input embeddings (V5 fix)
519
  _mask_count = attention_mask.sum(dim=1, keepdim=True).clamp(min=1).unsqueeze(-1) # (B,1,1)
520
  avg_inputs_embeds = (attention_mask.unsqueeze(-1) * inputs_embeds).sum(dim=1, keepdim=True) / _mask_count
521
 
522
- # Accumulate prototype during training (all tasks including first)
523
- if self.training:
524
- self._update_prototype(avg_inputs_embeds.squeeze(1))
525
-
526
  if not self.is_decoder and not self.prompt_config["run_single"]:
527
- if len(self.spectral_signatures) > 0 or len(self.task_prototypes) > 0:
528
  # Multi-task: compute routing
529
  key_attention_weights = self.compute_spectral_routing(avg_inputs_embeds)
530
  # Detach: routing weights are shared across all gradient-checkpointed
 
178
 
179
  self.prompt_config = prompt_config
180
 
 
 
 
 
 
 
 
 
 
 
181
  if not self.is_decoder and not prompt_config["run_single"]:
182
  # ===== Spectral routing: NO learned parameters for routing =====
183
  # Spectral signatures loaded from previous tasks' saved weights
184
  self.spectral_signatures = [] # List[dict] — one dict per old task
185
  self.routing_temperature = prompt_config.get('attn_temperature', 1.0)
186
 
 
 
 
 
 
 
187
  # Adaptive training bias: β = T·ln(α·n_old/(1−α))
188
  # Ensures current task gets consistent routing weight ~α regardless
189
  # of total number of tasks (fixes softmax dilution with constant bias).
 
235
 
236
  fits = []
237
 
 
 
238
  if self.training:
239
  # === TRAINING MODE: A-row fit + adaptive bias for current task ===
240
  # A rows give stable non-zero signal even when B=0 (cold-start).
 
258
  current_fit = current_fit + beta
259
  fits.append(current_fit)
260
  else:
261
+ # === INFERENCE MODE: SVD-based spectral routing (symmetric) ===
262
+ if self._current_task_svd is not None:
263
+ cur_fits = []
264
+ for key, sig_data in self._current_task_svd.items():
265
+ if not key.startswith('enc.'):
266
+ continue
267
+ V = sig_data['V'].to(h.device, dtype=h.dtype)
268
+ sigma = sig_data['sigma'].to(h.device, dtype=h.dtype)
269
+ proj = torch.matmul(h, V.T)
270
+ sigma_sq = sigma ** 2
271
+ sigma_sq_sum = sigma_sq.sum() + 1e-8
272
+ weighted_proj = (proj ** 2 * sigma_sq.unsqueeze(0).unsqueeze(0)).sum(dim=-1)
273
+ fit = weighted_proj / (sigma_sq_sum * h_norm_sq)
274
+ cur_fits.append(fit)
275
+ if cur_fits:
276
+ current_fit = torch.stack(cur_fits).mean(dim=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  else:
278
+ current_fit = torch.zeros(h.shape[0], 1, device=h.device, dtype=h.dtype)
279
+ else:
280
+ # Fallback: A-row fit (before prepare_inference_routing() is called)
281
+ current_fits_layers = []
282
+ for block in self.block:
283
+ attn = block.layer[0].SelfAttention
284
+ for lora in [attn.lora_q, attn.lora_v]:
285
+ A = lora.lora_A.data.float()
286
+ r = lora.r
287
+ A_h = A.to(h.device, dtype=h.dtype)
288
+ proj = torch.matmul(h, A_h.T)
289
+ fit = (proj ** 2).sum(dim=-1) / (r * h_norm_sq)
290
+ current_fits_layers.append(fit)
291
+ current_fit = torch.stack(current_fits_layers).mean(dim=0)
292
+ fits.append(current_fit)
293
+
294
+ # Old tasks: σ²-weighted spectral affinity (Rayleigh quotient)
 
 
 
295
  for sig_dict in self.spectral_signatures:
296
  task_fits = []
297
  for key, sig_data in sig_dict.items():
 
337
  B = lora.lora_B.data.float()
338
  r = lora.r
339
  S, Vt = _thin_svd_low_rank(B, A)
340
+ sigs[f'enc.{j}.{name}'] = {
341
  'V': Vt[:r].cpu(),
342
  'sigma': S[:r].cpu()
343
  }
344
  self._current_task_svd = sigs
345
  print(f"[SpecRoute] Prepared inference routing: {len(sigs)} encoder SVD signatures for current task")
346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  def parallelize(self, device_map=None):
348
  self.device_map = (
349
  get_device_map(len(self.block), range(torch.cuda.device_count()))
 
424
 
425
  batch_size, seq_length = input_shape
426
 
427
+ # ============ SPECTRAL ROUTING ============
428
  self.key_attention_weights = None
429
  if not self.is_decoder:
430
+ # Properly masked mean of input embeddings
431
  _mask_count = attention_mask.sum(dim=1, keepdim=True).clamp(min=1).unsqueeze(-1) # (B,1,1)
432
  avg_inputs_embeds = (attention_mask.unsqueeze(-1) * inputs_embeds).sum(dim=1, keepdim=True) / _mask_count
433
 
 
 
 
 
434
  if not self.is_decoder and not self.prompt_config["run_single"]:
435
+ if len(self.spectral_signatures) > 0:
436
  # Multi-task: compute routing
437
  key_attention_weights = self.compute_spectral_routing(avg_inputs_embeds)
438
  # Detach: routing weights are shared across all gradient-checkpointed