natmin322 commited on
Commit
dbf9735
·
1 Parent(s): 3c81e8e
improve_gainlora/src/cl_trainer_specroute.py CHANGED
@@ -133,7 +133,8 @@ class SpecRoute_Trainer(Seq2SeqTrainer):
133
  compute_metrics=None, callbacks=None,
134
  lambda_entropy=0.0, use_preconditioning=False,
135
  precond_eps=1e-6, entropy_warmup_ratio=0.1,
136
- n_batches_c5=100):
 
137
  if callbacks is None:
138
  callbacks = []
139
  callbacks.append(TransInputGPMCallback(self))
@@ -308,13 +309,42 @@ class SpecRoute_Trainer(Seq2SeqTrainer):
308
 
309
  def load_previous_reg_matrix(self):
310
  """Load LoRA GPM bases from previous task. Also load trans_input GPM if learned routing."""
 
 
311
  log_path = os.path.dirname(self.args.output_dir)
312
  local_dir = os.path.basename(self.args.output_dir)
313
- print(log_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
  all_dirs = os.listdir(log_path)
316
- reg_matrix = []
317
- reg_trans_matrix = []
318
  for all_dir in all_dirs:
319
  if not os.path.isdir(os.path.join(log_path, all_dir)):
320
  continue
@@ -322,14 +352,22 @@ class SpecRoute_Trainer(Seq2SeqTrainer):
322
  i = 0
323
  for module in self.model.modules():
324
  if hasattr(module, 'get_feature'):
325
- reg_matrix.append(torch.load(
326
- os.path.join(os.path.join(log_path, all_dir), "reg_{}.pt".format(i))
327
- ))
 
 
 
328
  i += 1
329
  if getattr(self.model.encoder, "routing_mode", "") == "learned":
330
- reg_trans_matrix.append(torch.load(os.path.join(os.path.join(log_path, all_dir, 'trans_input'), "reg_0.pt"), weights_only=True))
331
- reg_trans_matrix.append(torch.load(os.path.join(os.path.join(log_path, all_dir, 'trans_input'), "reg_1.pt"), weights_only=True))
332
- reg_trans_matrix.append(torch.load(os.path.join(os.path.join(log_path, all_dir, 'trans_input'), "reg_2.pt"), weights_only=True))
 
 
 
 
 
333
 
334
  print(os.path.join(log_path, all_dir))
335
  print(len(reg_matrix))
@@ -380,10 +418,25 @@ class SpecRoute_Trainer(Seq2SeqTrainer):
380
  P_old = feature_mat[index] # [step, step]
381
  Q = torch.eye(module.step, device=P_old.device) - P_old
382
  C_tilde = Q @ C_t.to(P_old.device) @ Q
383
- # Enforce symmetry for numerical stability
384
  C_tilde = (C_tilde + C_tilde.T) * 0.5
385
- # eigh returns ascending eigenvalues; take last r (largest)
386
- eigvals, eigvecs = torch.linalg.eigh(C_tilde.float())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  # Fallback: if null-space signal is degenerate, keep Kaiming init
388
  if eigvals[-1].item() < 1e-6:
389
  print(f'[C5] Layer {i+1} index {index}: max_eigval={eigvals[-1].item():.2e} < 1e-6, fallback to Kaiming+InfLoRA')
 
133
  compute_metrics=None, callbacks=None,
134
  lambda_entropy=0.0, use_preconditioning=False,
135
  precond_eps=1e-6, entropy_warmup_ratio=0.1,
136
+ n_batches_c5=100, previous_lora_path=None):
137
+ self.previous_lora_path = previous_lora_path
138
  if callbacks is None:
139
  callbacks = []
140
  callbacks.append(TransInputGPMCallback(self))
 
309
 
310
  def load_previous_reg_matrix(self):
311
  """Load LoRA GPM bases from previous task. Also load trans_input GPM if learned routing."""
312
+ reg_matrix = []
313
+ reg_trans_matrix = []
314
  log_path = os.path.dirname(self.args.output_dir)
315
  local_dir = os.path.basename(self.args.output_dir)
316
+
317
+ # If explicit path provided, use it (comma separated for multiple past tasks)
318
+ if hasattr(self, "previous_lora_path") and self.previous_lora_path:
319
+ previous_lora_list = self.previous_lora_path.split(',')
320
+ # InfLoRA GPM bases are cumulative; we only need the bases from the immediately preceding task
321
+ # because InfLoRA's loading logic in ROOT/GainLoRA builds upon them.
322
+ # Actually, the specroute implementation loads reg_{i}.pt from the PREVIOUS task only.
323
+ last_task_path = previous_lora_list[-1]
324
+
325
+ i = 0
326
+ for module in self.model.modules():
327
+ if hasattr(module, 'get_feature'):
328
+ path = os.path.join(last_task_path, "reg_{}.pt".format(i))
329
+ if os.path.exists(path):
330
+ mat = torch.load(path, map_location='cpu')
331
+ if torch.isnan(mat).any() or torch.isinf(mat).any():
332
+ mat = torch.nan_to_num(mat, nan=0.0)
333
+ reg_matrix.append(mat)
334
+ i += 1
335
+ if getattr(self.model.encoder, "routing_mode", "") == "learned":
336
+ for name in ['reg_0.pt', 'reg_1.pt', 'reg_2.pt']:
337
+ path = os.path.join(last_task_path, 'trans_input', name)
338
+ if os.path.exists(path):
339
+ mat = torch.load(path, map_location='cpu', weights_only=True)
340
+ if torch.isnan(mat).any() or torch.isinf(mat).any():
341
+ mat = torch.nan_to_num(mat, nan=0.0)
342
+ reg_trans_matrix.append(mat)
343
+
344
+ print(f"[GPM] Loaded bases from {last_task_path}")
345
+ return reg_matrix, reg_trans_matrix, len(previous_lora_list) - 1
346
 
347
  all_dirs = os.listdir(log_path)
 
 
348
  for all_dir in all_dirs:
349
  if not os.path.isdir(os.path.join(log_path, all_dir)):
350
  continue
 
352
  i = 0
353
  for module in self.model.modules():
354
  if hasattr(module, 'get_feature'):
355
+ path = os.path.join(os.path.join(log_path, all_dir), "reg_{}.pt".format(i))
356
+ mat = torch.load(path, map_location='cpu')
357
+ if torch.isnan(mat).any() or torch.isinf(mat).any():
358
+ print(f'[GPM] WARNING: {path} contains NaN/Inf. Cleaning to 0.')
359
+ mat = torch.nan_to_num(mat, nan=0.0, posinf=0.0, neginf=0.0)
360
+ reg_matrix.append(mat)
361
  i += 1
362
  if getattr(self.model.encoder, "routing_mode", "") == "learned":
363
+ for name in ['reg_0.pt', 'reg_1.pt', 'reg_2.pt']:
364
+ path = os.path.join(log_path, all_dir, 'trans_input', name)
365
+ if os.path.exists(path):
366
+ mat = torch.load(path, map_location='cpu', weights_only=True)
367
+ if torch.isnan(mat).any() or torch.isinf(mat).any():
368
+ print(f'[GPM] WARNING: {path} contains NaN/Inf. Cleaning.')
369
+ mat = torch.nan_to_num(mat, nan=0.0)
370
+ reg_trans_matrix.append(mat)
371
 
372
  print(os.path.join(log_path, all_dir))
373
  print(len(reg_matrix))
 
418
  P_old = feature_mat[index] # [step, step]
419
  Q = torch.eye(module.step, device=P_old.device) - P_old
420
  C_tilde = Q @ C_t.to(P_old.device) @ Q
421
+ # Enforce symmetry and add tiny jitter for numerical stability
422
  C_tilde = (C_tilde + C_tilde.T) * 0.5
423
+ # Guard against NaNs or Infs that might cause linalg.eigh to fail
424
+ if torch.isnan(C_tilde).any() or torch.isinf(C_tilde).any():
425
+ print(f'[C5] WARNING: Layer {i+1} index {index} contains NaN/Inf in C_tilde. Cleaning.')
426
+ C_tilde = torch.nan_to_num(C_tilde, nan=0.0, posinf=0.0, neginf=0.0)
427
+
428
+ # Add tiny diagonal jitter to prevent ill-conditioned matrix errors (error code 641)
429
+ # Scaling jitter to mean magnitude of C_tilde
430
+ jitter_scale = 1e-10 * (C_tilde.abs().mean() + 1e-12)
431
+ C_tilde += jitter_scale * torch.eye(C_tilde.shape[0], device=C_tilde.device)
432
+
433
+ try:
434
+ # eigh returns ascending eigenvalues; take last r (largest)
435
+ eigvals, eigvecs = torch.linalg.eigh(C_tilde.float())
436
+ except torch._C._LinAlgError as e:
437
+ print(f'[C5] WARNING: Layer {i+1} index {index} - linalg.eigh failed: {e}. Falling back.')
438
+ continue
439
+
440
  # Fallback: if null-space signal is degenerate, keep Kaiming init
441
  if eigvals[-1].item() < 1e-6:
442
  print(f'[C5] Layer {i+1} index {index}: max_eigval={eigvals[-1].item():.2e} < 1e-6, fallback to Kaiming+InfLoRA')
improve_gainlora/src/run_t5.py CHANGED
@@ -959,6 +959,7 @@ def main():
959
  precond_eps=model_args.precond_eps,
960
  entropy_warmup_ratio=model_args.entropy_warmup_ratio,
961
  n_batches_c5=model_args.n_batches_c5,
 
962
  )
963
  if training_args.do_train:
964
  if not model_args.run_single: # C5 is only useful for tasks t>=2
 
959
  precond_eps=model_args.precond_eps,
960
  entropy_warmup_ratio=model_args.entropy_warmup_ratio,
961
  n_batches_c5=model_args.n_batches_c5,
962
+ previous_lora_path=model_args.previous_lora_path
963
  )
964
  if training_args.do_train:
965
  if not model_args.run_single: # C5 is only useful for tasks t>=2