natmin322 commited on
Commit
60ae8d5
·
1 Parent(s): d6f2636
improve_gainlora/src/cl_trainer_specroute.py CHANGED
@@ -117,14 +117,14 @@ class TransInputGPMCallback(TrainerCallback):
117
  new_trans_input_1 = self.trainer.model.encoder.trans_input[2].weight.detach() - torch.mm(self.trainer.model.encoder.trans_input[2].weight.detach()-old_trans_input_1, self.trainer.feature_trans_mat[1])
118
 
119
  new_trans_input_0 = torch.nan_to_num(
120
- new_trans_input_0 * new_trans_input_0norm / new_trans_input_0.norm(dim=1, keepdim=True).clamp(min=1e-12),
121
- nan=0.0, posinf=0.0, neginf=0.0)
122
  new_trans_input_1 = torch.nan_to_num(
123
- new_trans_input_1 * new_trans_input_1norm / new_trans_input_1.norm(dim=1, keepdim=True).clamp(min=1e-12),
124
- nan=0.0, posinf=0.0, neginf=0.0)
125
  new_prompt_key = torch.nan_to_num(
126
- new_prompt_key * new_prompt_key_norm / new_prompt_key.norm(dim=1, keepdim=True).clamp(min=1e-12),
127
- nan=0.0, posinf=0.0, neginf=0.0)
128
 
129
  self.trainer.model.encoder.trans_input[0].weight.data.copy_(new_trans_input_0)
130
  self.trainer.model.encoder.trans_input[2].weight.data.copy_(new_trans_input_1)
 
117
  new_trans_input_1 = self.trainer.model.encoder.trans_input[2].weight.detach() - torch.mm(self.trainer.model.encoder.trans_input[2].weight.detach()-old_trans_input_1, self.trainer.feature_trans_mat[1])
118
 
119
  new_trans_input_0 = torch.nan_to_num(
120
+ new_trans_input_0.float() * new_trans_input_0norm.float() / new_trans_input_0.float().norm(dim=1, keepdim=True).clamp_min(1e-12),
121
+ nan=0.0, posinf=0.0, neginf=0.0).to(new_trans_input_0.dtype)
122
  new_trans_input_1 = torch.nan_to_num(
123
+ new_trans_input_1.float() * new_trans_input_1norm.float() / new_trans_input_1.float().norm(dim=1, keepdim=True).clamp_min(1e-12),
124
+ nan=0.0, posinf=0.0, neginf=0.0).to(new_trans_input_1.dtype)
125
  new_prompt_key = torch.nan_to_num(
126
+ new_prompt_key.float() * new_prompt_key_norm.float() / new_prompt_key.float().norm(dim=1, keepdim=True).clamp_min(1e-12),
127
+ nan=0.0, posinf=0.0, neginf=0.0).to(new_prompt_key.dtype)
128
 
129
  self.trainer.model.encoder.trans_input[0].weight.data.copy_(new_trans_input_0)
130
  self.trainer.model.encoder.trans_input[2].weight.data.copy_(new_trans_input_1)
improve_gainlora/src/t5_specroute.py CHANGED
@@ -235,10 +235,21 @@ class T5Stack(T5PreTrainedModel):
235
 
236
  def cal_attention(self, prompt_key, x, return_logits=False):
237
  # ROOT-style routing similarity
238
- x = x/(x.norm(dim=-1,keepdim=True) + 1e-12)
239
- prompt_key = prompt_key/(prompt_key.norm(dim=-1,keepdim=True) + 1e-12)
240
- attn_scores = (x*prompt_key).sum(dim=-1, keepdim=True)
241
- weights = torch.abs(torch.nn.functional.sigmoid(attn_scores*4)*2-1)
 
 
 
 
 
 
 
 
 
 
 
242
  if not return_logits:
243
  return weights
244
  else:
 
235
 
236
  def cal_attention(self, prompt_key, x, return_logits=False):
237
  # ROOT-style routing similarity
238
+ # Force float32 to prevent underflow/overflow in fp16/bf16 on H100
239
+ x_fp32 = x.float()
240
+ prompt_key_fp32 = prompt_key.float()
241
+
242
+ # Add epsilon to prevent div-by-zero, clamp to prevent extreme values
243
+ x_norm = x_fp32 / (x_fp32.norm(dim=-1, keepdim=True).clamp_min(1e-12))
244
+ prompt_key_norm = prompt_key_fp32 / (prompt_key_fp32.norm(dim=-1, keepdim=True).clamp_min(1e-12))
245
+
246
+ attn_scores = (x_norm * prompt_key_norm).sum(dim=-1, keepdim=True)
247
+ # Scaled sigmoid gating exact to ROOT GainLoRA
248
+ weights_fp32 = torch.abs(torch.nn.functional.sigmoid(attn_scores * 4.0) * 2.0 - 1.0)
249
+
250
+ weights = weights_fp32.to(x.dtype)
251
+ attn_scores = attn_scores.to(x.dtype)
252
+
253
  if not return_logits:
254
  return weights
255
  else:
improve_gainlora/test_v10a_loss.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import torch
4
+
5
+ sys.path.append('src')
6
+
7
+ from t5_specroute import T5ForConditionalGeneration
8
+ from transformers import AutoConfig, AutoTokenizer
9
+
10
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
11
+
12
+ config = AutoConfig.from_pretrained('google/flan-t5-small')
13
+ tokenizer = AutoTokenizer.from_pretrained('google/flan-t5-small')
14
+
15
+ prompt_config = {
16
+ 'seq_len': 512,
17
+ 'mlp_hidden_dim': 100,
18
+ 'attn_temperature': 1.0,
19
+ 'routing_mode': 'learned',
20
+ 'previous_lora_path': None,
21
+ 'previous_prompt_key_path': None,
22
+ 'task_id': 0,
23
+ 'run_single': False,
24
+ 'lora_r': 8,
25
+ 'lora_alpha': 16,
26
+ 'lora_dropout': 0.1,
27
+ 'training_bias': 'none',
28
+ 'target_routing_alpha': 0.8,
29
+ }
30
+
31
+ print("Loading model...")
32
+ model = T5ForConditionalGeneration.from_pretrained(
33
+ 'google/flan-t5-small',
34
+ prompt_config,
35
+ config=config
36
+ ).to(device)
37
+
38
+ print("Reinitializing Lora A...")
39
+ import math
40
+ import torch.nn as nn
41
+ for module in model.modules():
42
+ if hasattr(module, 'lora_A') and hasattr(module, 'lora_B') and hasattr(module, 'reset_parameters'):
43
+ nn.init.kaiming_uniform_(module.lora_A, a=math.sqrt(5))
44
+
45
+ model.train()
46
+ # Freeze all except lora_B, trans_input, prompt_key
47
+ for name, param in model.named_parameters():
48
+ param.requires_grad = False
49
+ if "lora_B" in name or "trans_input" in name or "prompt_key" in name:
50
+ param.requires_grad = True
51
+
52
+ input_text = ["This is a test sentence.", "Another test."]
53
+ inputs = tokenizer(input_text, return_tensors='pt', padding=True).to(device)
54
+ labels = tokenizer(["Positive", "Negative"], return_tensors='pt', padding=True).to(device)
55
+
56
+ print("Forward pass...")
57
+ outputs = model(
58
+ input_ids=inputs.input_ids,
59
+ attention_mask=inputs.attention_mask,
60
+ labels=labels.input_ids
61
+ )
62
+
63
+ loss = outputs.loss
64
+ print(f"Loss: {loss.item()}")
65
+
66
+ print("Backward pass...")
67
+ loss.backward()
68
+
69
+ n_grad = 0
70
+ n_zero = 0
71
+ n_nan = 0
72
+ n_none = 0
73
+ for name, param in model.named_parameters():
74
+ if param.requires_grad:
75
+ if param.grad is not None:
76
+ norm = param.grad.norm().item()
77
+ if torch.isnan(param.grad).any():
78
+ n_nan += 1
79
+ elif norm > 0:
80
+ n_grad += 1
81
+ else:
82
+ n_zero += 1
83
+ else:
84
+ n_none += 1
85
+
86
+ print(f"Gradients -> >0: {n_grad}, ==0: {n_zero}, NaN: {n_nan}, None: {n_none}")