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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
from typing import Dict, List, Optional, Any
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from torch.utils.data import DataLoader
|
| 8 |
+
|
| 9 |
+
from dytr.core.model import DynamicTransformer
|
| 10 |
+
from dytr.core.config import ModelConfig, TaskConfig, TrainingStrategy
|
| 11 |
+
from dytr.training.data import MultiTaskDataset, TaskAwareBatchSampler, collate_fn
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LoRALayer(nn.Module):
|
| 15 |
+
def __init__(self, linear_layer: nn.Linear, rank: int = 8, alpha: float = 16.0, dropout: float = 0.1):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.linear = linear_layer
|
| 18 |
+
self.rank = rank
|
| 19 |
+
self.alpha = alpha
|
| 20 |
+
self.scaling = alpha / rank
|
| 21 |
+
in_features = linear_layer.in_features
|
| 22 |
+
out_features = linear_layer.out_features
|
| 23 |
+
self.lora_A = nn.Parameter(torch.zeros(rank, in_features))
|
| 24 |
+
self.lora_B = nn.Parameter(torch.zeros(out_features, rank))
|
| 25 |
+
self.dropout = nn.Dropout(dropout)
|
| 26 |
+
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
|
| 27 |
+
nn.init.zeros_(self.lora_B)
|
| 28 |
+
self.enabled = True
|
| 29 |
+
|
| 30 |
+
def forward(self, x: torch.Tensor):
|
| 31 |
+
result = self.linear(x)
|
| 32 |
+
if not self.enabled:
|
| 33 |
+
return result
|
| 34 |
+
lora_out = (x @ self.lora_A.T) @ self.lora_B.T * self.scaling
|
| 35 |
+
return result + self.dropout(lora_out)
|
| 36 |
+
|
| 37 |
+
def disable(self):
|
| 38 |
+
self.enabled = False
|
| 39 |
+
|
| 40 |
+
def enable(self):
|
| 41 |
+
self.enabled = True
|
| 42 |
+
|
| 43 |
+
def merge(self):
|
| 44 |
+
merged_weight = self.linear.weight.data + (self.lora_B @ self.lora_A) * self.scaling
|
| 45 |
+
new_linear = nn.Linear(self.linear.in_features, self.linear.out_features, bias=self.linear.bias is not None)
|
| 46 |
+
new_linear.weight.data = merged_weight
|
| 47 |
+
if self.linear.bias is not None:
|
| 48 |
+
new_linear.bias.data = self.linear.bias.data
|
| 49 |
+
return new_linear
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TaskSpecificLoRALayer(nn.Module):
|
| 53 |
+
def __init__(self, linear_layer: nn.Linear, task_name: str, rank: int = 8, alpha: float = 16.0, dropout: float = 0.1):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.linear = linear_layer
|
| 56 |
+
self.task_name = task_name
|
| 57 |
+
self.rank = rank
|
| 58 |
+
self.alpha = alpha
|
| 59 |
+
self.scaling = alpha / rank
|
| 60 |
+
in_features = linear_layer.in_features
|
| 61 |
+
out_features = linear_layer.out_features
|
| 62 |
+
self.lora_A = nn.Parameter(torch.zeros(rank, in_features))
|
| 63 |
+
self.lora_B = nn.Parameter(torch.zeros(out_features, rank))
|
| 64 |
+
self.dropout = nn.Dropout(dropout)
|
| 65 |
+
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
|
| 66 |
+
nn.init.zeros_(self.lora_B)
|
| 67 |
+
self.enabled = True
|
| 68 |
+
|
| 69 |
+
def forward(self, x: torch.Tensor):
|
| 70 |
+
result = self.linear(x)
|
| 71 |
+
if not self.enabled:
|
| 72 |
+
return result
|
| 73 |
+
lora_out = (x @ self.lora_A.T) @ self.lora_B.T * self.scaling
|
| 74 |
+
return result + self.dropout(lora_out)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class LoRAWrapper:
|
| 78 |
+
def __init__(self, model: DynamicTransformer, rank: int = 8, alpha: float = 16.0, dropout: float = 0.1, target_modules: List[str] = None):
|
| 79 |
+
self.model = model
|
| 80 |
+
self.rank = rank
|
| 81 |
+
self.alpha = alpha
|
| 82 |
+
self.dropout = dropout
|
| 83 |
+
self.target_modules = target_modules or ["q_proj", "k_proj", "v_proj", "out_proj", "gate_proj", "up_proj", "down_proj"]
|
| 84 |
+
self.lora_layers = []
|
| 85 |
+
self._apply_lora_to_model()
|
| 86 |
+
self._freeze_base_model()
|
| 87 |
+
|
| 88 |
+
def _apply_lora_to_model(self):
|
| 89 |
+
for module_name, module in self.model.named_modules():
|
| 90 |
+
if any(target in module_name for target in self.target_modules):
|
| 91 |
+
if isinstance(module, nn.Linear):
|
| 92 |
+
lora = LoRALayer(module, self.rank, self.alpha, self.dropout)
|
| 93 |
+
self.lora_layers.append((module_name, lora))
|
| 94 |
+
self._replace_module(module_name, module, lora)
|
| 95 |
+
|
| 96 |
+
def _replace_module(self, module_name: str, original_module: nn.Linear, lora_module: LoRALayer):
|
| 97 |
+
parent_name, child_name = self._get_parent_and_child(module_name)
|
| 98 |
+
parent = self._get_module_by_path(parent_name)
|
| 99 |
+
setattr(parent, child_name, lora_module)
|
| 100 |
+
|
| 101 |
+
def _get_parent_and_child(self, module_name: str):
|
| 102 |
+
parts = module_name.split('.')
|
| 103 |
+
child_name = parts[-1]
|
| 104 |
+
parent_name = '.'.join(parts[:-1]) if len(parts) > 1 else ''
|
| 105 |
+
return parent_name, child_name
|
| 106 |
+
|
| 107 |
+
def _get_module_by_path(self, path: str):
|
| 108 |
+
if not path:
|
| 109 |
+
return self.model
|
| 110 |
+
module = self.model
|
| 111 |
+
for part in path.split('.'):
|
| 112 |
+
module = getattr(module, part)
|
| 113 |
+
return module
|
| 114 |
+
|
| 115 |
+
def _freeze_base_model(self):
|
| 116 |
+
for param in self.model.parameters():
|
| 117 |
+
param.requires_grad = False
|
| 118 |
+
for _, lora in self.lora_layers:
|
| 119 |
+
lora.lora_A.requires_grad = True
|
| 120 |
+
lora.lora_B.requires_grad = True
|
| 121 |
+
|
| 122 |
+
def get_trainable_parameters(self):
|
| 123 |
+
params = []
|
| 124 |
+
for _, lora in self.lora_layers:
|
| 125 |
+
params.append(lora.lora_A)
|
| 126 |
+
params.append(lora.lora_B)
|
| 127 |
+
return params
|
| 128 |
+
|
| 129 |
+
def merge_all_lora_weights(self):
|
| 130 |
+
for module_name, lora in self.lora_layers:
|
| 131 |
+
parent_name, child_name = self._get_parent_and_child(module_name)
|
| 132 |
+
parent = self._get_module_by_path(parent_name)
|
| 133 |
+
merged_linear = lora.merge()
|
| 134 |
+
setattr(parent, child_name, merged_linear)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class MultiTaskLoRAWrapper:
|
| 138 |
+
def __init__(self, model: DynamicTransformer, rank: int = 8, alpha: float = 16.0, dropout: float = 0.1,target_modules: List[str] = None):
|
| 139 |
+
self.model = model
|
| 140 |
+
self.rank = rank
|
| 141 |
+
self.alpha = alpha
|
| 142 |
+
self.dropout = dropout
|
| 143 |
+
self.target_modules = target_modules or ["q_proj", "k_proj", "v_proj", "out_proj", "gate_proj", "up_proj", "down_proj"]
|
| 144 |
+
self.task_lora_layers = {}
|
| 145 |
+
self._analyze_model_architecture()
|
| 146 |
+
self._apply_lora_to_trainable_components()
|
| 147 |
+
|
| 148 |
+
def _analyze_model_architecture(self):
|
| 149 |
+
self.trainable_status = {}
|
| 150 |
+
for name, param in self.model.named_parameters():
|
| 151 |
+
self.trainable_status[name] = param.requires_grad
|
| 152 |
+
self.task_heads = list(self.model.task_heads.keys())
|
| 153 |
+
self.decoders = list(self.model.decoders.keys())
|
| 154 |
+
self.encoder_trainable = any('encoder' in n and p.requires_grad for n, p in self.model.named_parameters())
|
| 155 |
+
self.shared_embedding_trainable = any('shared_embedding' in n and p.requires_grad for n, p in self.model.named_parameters())
|
| 156 |
+
|
| 157 |
+
def _apply_lora_to_trainable_components(self):
|
| 158 |
+
#target_modules = ["q_proj", "k_proj", "v_proj", "out_proj", "gate_proj", "up_proj", "down_proj"]
|
| 159 |
+
for module_name, module in self.model.named_modules():
|
| 160 |
+
if not isinstance(module, nn.Linear):
|
| 161 |
+
continue
|
| 162 |
+
if not any(target in module_name for target in self.target_modules):
|
| 163 |
+
continue
|
| 164 |
+
should_apply = self._should_apply_lora(module_name)
|
| 165 |
+
if not should_apply:
|
| 166 |
+
continue
|
| 167 |
+
self.task_lora_layers[module_name] = {}
|
| 168 |
+
for task_name in self.model.current_tasks.keys():
|
| 169 |
+
if not self._is_task_relevant(module_name, task_name):
|
| 170 |
+
continue
|
| 171 |
+
lora = TaskSpecificLoRALayer(module, task_name, self.rank, self.alpha, self.dropout)
|
| 172 |
+
self.task_lora_layers[module_name][task_name] = lora
|
| 173 |
+
if self.task_lora_layers[module_name]:
|
| 174 |
+
self._replace_module_with_lora(module_name, module)
|
| 175 |
+
|
| 176 |
+
def _should_apply_lora(self, module_name: str) -> bool:
|
| 177 |
+
if 'encoder' in module_name:
|
| 178 |
+
return self.encoder_trainable
|
| 179 |
+
if 'shared_embedding' in module_name:
|
| 180 |
+
return self.shared_embedding_trainable
|
| 181 |
+
if 'decoders' in module_name:
|
| 182 |
+
parts = module_name.split('.')
|
| 183 |
+
decoder_name = parts[1] if len(parts) > 1 else None
|
| 184 |
+
if decoder_name and decoder_name in self.decoders:
|
| 185 |
+
return True
|
| 186 |
+
if 'task_heads' in module_name:
|
| 187 |
+
parts = module_name.split('.')
|
| 188 |
+
head_name = parts[1] if len(parts) > 1 else None
|
| 189 |
+
if head_name and head_name in self.task_heads:
|
| 190 |
+
return True
|
| 191 |
+
return False
|
| 192 |
+
|
| 193 |
+
def _is_task_relevant(self, module_name: str, task_name: str) -> bool:
|
| 194 |
+
if 'decoders' in module_name:
|
| 195 |
+
parts = module_name.split('.')
|
| 196 |
+
decoder_name = parts[1] if len(parts) > 1 else None
|
| 197 |
+
return decoder_name == task_name
|
| 198 |
+
if 'task_heads' in module_name:
|
| 199 |
+
parts = module_name.split('.')
|
| 200 |
+
head_name = parts[1] if len(parts) > 1 else None
|
| 201 |
+
return head_name == task_name
|
| 202 |
+
return True
|
| 203 |
+
|
| 204 |
+
def _replace_module_with_lora(self, module_name: str, original_module: nn.Linear):
|
| 205 |
+
parent_name, child_name = self._get_parent_and_child(module_name)
|
| 206 |
+
parent = self._get_module_by_path(parent_name)
|
| 207 |
+
|
| 208 |
+
class MultiTaskLinear(nn.Module):
|
| 209 |
+
def __init__(self, original, lora_dict):
|
| 210 |
+
super().__init__()
|
| 211 |
+
self.original = original
|
| 212 |
+
self.lora_dict = lora_dict
|
| 213 |
+
self.current_task = None
|
| 214 |
+
|
| 215 |
+
def forward(self, x):
|
| 216 |
+
result = self.original(x)
|
| 217 |
+
if self.current_task and self.current_task in self.lora_dict:
|
| 218 |
+
lora = self.lora_dict[self.current_task]
|
| 219 |
+
lora_out = (x @ lora.lora_A.T) @ lora.lora_B.T * lora.scaling
|
| 220 |
+
result = result + lora_out
|
| 221 |
+
return result
|
| 222 |
+
|
| 223 |
+
multi_linear = MultiTaskLinear(original_module, self.task_lora_layers[module_name])
|
| 224 |
+
setattr(parent, child_name, multi_linear)
|
| 225 |
+
|
| 226 |
+
def _get_parent_and_child(self, module_name: str):
|
| 227 |
+
parts = module_name.split('.')
|
| 228 |
+
child_name = parts[-1]
|
| 229 |
+
parent_name = '.'.join(parts[:-1]) if len(parts) > 1 else ''
|
| 230 |
+
return parent_name, child_name
|
| 231 |
+
|
| 232 |
+
def _get_module_by_path(self, path: str):
|
| 233 |
+
if not path:
|
| 234 |
+
return self.model
|
| 235 |
+
module = self.model
|
| 236 |
+
for part in path.split('.'):
|
| 237 |
+
module = getattr(module, part)
|
| 238 |
+
return module
|
| 239 |
+
|
| 240 |
+
def set_current_task(self, task_name: str):
|
| 241 |
+
for module_name, task_loras in self.task_lora_layers.items():
|
| 242 |
+
parent_name, child_name = self._get_parent_and_child(module_name)
|
| 243 |
+
parent = self._get_module_by_path(parent_name)
|
| 244 |
+
if hasattr(parent, child_name):
|
| 245 |
+
multi_linear = getattr(parent, child_name)
|
| 246 |
+
multi_linear.current_task = task_name
|
| 247 |
+
|
| 248 |
+
def get_trainable_parameters(self):
|
| 249 |
+
params = []
|
| 250 |
+
for module_name, task_loras in self.task_lora_layers.items():
|
| 251 |
+
parent_name, child_name = self._get_parent_and_child(module_name)
|
| 252 |
+
parent = self._get_module_by_path(parent_name)
|
| 253 |
+
if not hasattr(parent, child_name):
|
| 254 |
+
continue
|
| 255 |
+
multi_linear = getattr(parent, child_name)
|
| 256 |
+
for task_name, lora in task_loras.items():
|
| 257 |
+
if task_name in multi_linear.lora_dict:
|
| 258 |
+
params.append(multi_linear.lora_dict[task_name].lora_A)
|
| 259 |
+
params.append(multi_linear.lora_dict[task_name].lora_B)
|
| 260 |
+
return params
|
| 261 |
+
|
| 262 |
+
def merge_task_weights(self, task_name: str):
|
| 263 |
+
for module_name, task_loras in self.task_lora_layers.items():
|
| 264 |
+
parent_name, child_name = self._get_parent_and_child(module_name)
|
| 265 |
+
parent = self._get_module_by_path(parent_name)
|
| 266 |
+
if not hasattr(parent, child_name):
|
| 267 |
+
continue
|
| 268 |
+
multi_linear = getattr(parent, child_name)
|
| 269 |
+
if task_name in multi_linear.lora_dict:
|
| 270 |
+
lora = multi_linear.lora_dict[task_name]
|
| 271 |
+
merged_weight = multi_linear.original.weight.data + (lora.lora_B @ lora.lora_A) * lora.scaling
|
| 272 |
+
multi_linear.original.weight.data = merged_weight
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class ProgressiveLoRATrainer:
|
| 276 |
+
def __init__(self, model: DynamicTransformer, config: ModelConfig, exp_dir: str, initial_rank: int = 4, final_rank: int = 16):
|
| 277 |
+
self.model = model
|
| 278 |
+
self.config = config
|
| 279 |
+
self.exp_dir = exp_dir
|
| 280 |
+
os.makedirs(self.exp_dir, exist_ok=True)
|
| 281 |
+
self.initial_rank = initial_rank
|
| 282 |
+
self.final_rank = final_rank
|
| 283 |
+
self.current_rank = initial_rank
|
| 284 |
+
self.lora_wrapper = None
|
| 285 |
+
self.val_loader=None
|
| 286 |
+
self.best_val_loss = float('inf')
|
| 287 |
+
|
| 288 |
+
def train(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict):
|
| 289 |
+
for task_config in task_configs:
|
| 290 |
+
if task_config.task_name not in self.model.current_tasks:
|
| 291 |
+
self.model.add_task(task_config)
|
| 292 |
+
|
| 293 |
+
self._phase_1_warmup(task_configs, train_datasets, val_datasets)
|
| 294 |
+
self._phase_2_expansion(task_configs, train_datasets, val_datasets)
|
| 295 |
+
self._phase_3_hybrid(task_configs, train_datasets, val_datasets)
|
| 296 |
+
self._phase_4_native(task_configs, train_datasets, val_datasets)
|
| 297 |
+
|
| 298 |
+
return self.model
|
| 299 |
+
|
| 300 |
+
def _phase_1_warmup(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict):
|
| 301 |
+
print("\n" + "="*60)
|
| 302 |
+
print("Phase 1: Warmup with Low-Rank LoRA")
|
| 303 |
+
print("="*60)
|
| 304 |
+
|
| 305 |
+
self.current_rank = self.initial_rank
|
| 306 |
+
self.lora_wrapper = LoRAWrapper(self.model, rank=self.current_rank, alpha=self.current_rank * 2)
|
| 307 |
+
|
| 308 |
+
train_dataset = MultiTaskDataset(train_datasets, self.model.tokenizer, task_configs)
|
| 309 |
+
train_sampler = TaskAwareBatchSampler(train_dataset, self.config.per_device_train_batch_size, shuffle=True)
|
| 310 |
+
train_loader = DataLoader(train_dataset, batch_sampler=train_sampler, collate_fn=collate_fn, num_workers=0)
|
| 311 |
+
|
| 312 |
+
trainable_params = self.lora_wrapper.get_trainable_parameters()
|
| 313 |
+
optimizer = torch.optim.AdamW(trainable_params, lr=self.config.learning_rate, weight_decay=self.config.weight_decay)
|
| 314 |
+
|
| 315 |
+
original_epochs = self.config.num_train_epochs
|
| 316 |
+
self.config.num_train_epochs = 2
|
| 317 |
+
|
| 318 |
+
self._run_training_phase(task_configs, train_datasets, val_datasets, train_loader, optimizer, "Warmup")
|
| 319 |
+
|
| 320 |
+
self.config.num_train_epochs = original_epochs
|
| 321 |
+
|
| 322 |
+
def _phase_2_expansion(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict):
|
| 323 |
+
print("\n" + "="*60)
|
| 324 |
+
print("Phase 2: Expansion with Increased LoRA Rank")
|
| 325 |
+
print("="*60)
|
| 326 |
+
|
| 327 |
+
self.lora_wrapper.merge_all_lora_weights()
|
| 328 |
+
|
| 329 |
+
self.current_rank = self.final_rank
|
| 330 |
+
self.lora_wrapper = LoRAWrapper(self.model, rank=self.current_rank, alpha=self.current_rank * 2)
|
| 331 |
+
|
| 332 |
+
train_dataset = MultiTaskDataset(train_datasets, self.model.tokenizer, task_configs)
|
| 333 |
+
train_sampler = TaskAwareBatchSampler(train_dataset, self.config.per_device_train_batch_size, shuffle=True)
|
| 334 |
+
train_loader = DataLoader(train_dataset, batch_sampler=train_sampler, collate_fn=collate_fn, num_workers=0)
|
| 335 |
+
|
| 336 |
+
trainable_params = self.lora_wrapper.get_trainable_parameters()
|
| 337 |
+
optimizer = torch.optim.AdamW(trainable_params, lr=self.config.learning_rate * 0.5, weight_decay=self.config.weight_decay)
|
| 338 |
+
|
| 339 |
+
original_epochs = self.config.num_train_epochs
|
| 340 |
+
self.config.num_train_epochs = 3
|
| 341 |
+
|
| 342 |
+
self._run_training_phase(task_configs, train_datasets, val_datasets, train_loader, optimizer, "Expansion")
|
| 343 |
+
|
| 344 |
+
self.config.num_train_epochs = original_epochs
|
| 345 |
+
|
| 346 |
+
def _phase_3_hybrid(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict):
|
| 347 |
+
print("\n" + "="*60)
|
| 348 |
+
print("Phase 3: Hybrid (LoRA on Encoder Only)")
|
| 349 |
+
print("="*60)
|
| 350 |
+
|
| 351 |
+
self.lora_wrapper.merge_all_lora_weights()
|
| 352 |
+
|
| 353 |
+
for name, param in self.model.named_parameters():
|
| 354 |
+
if 'encoder' in name:
|
| 355 |
+
param.requires_grad = True
|
| 356 |
+
else:
|
| 357 |
+
param.requires_grad = True
|
| 358 |
+
|
| 359 |
+
train_dataset = MultiTaskDataset(train_datasets, self.model.tokenizer, task_configs)
|
| 360 |
+
train_sampler = TaskAwareBatchSampler(train_dataset, self.config.per_device_train_batch_size, shuffle=True)
|
| 361 |
+
train_loader = DataLoader(train_dataset, batch_sampler=train_sampler, collate_fn=collate_fn, num_workers=0)
|
| 362 |
+
|
| 363 |
+
encoder_params = []
|
| 364 |
+
other_params = []
|
| 365 |
+
for name, param in self.model.named_parameters():
|
| 366 |
+
if param.requires_grad:
|
| 367 |
+
if 'encoder' in name:
|
| 368 |
+
encoder_params.append(param)
|
| 369 |
+
else:
|
| 370 |
+
other_params.append(param)
|
| 371 |
+
|
| 372 |
+
optimizer = torch.optim.AdamW([
|
| 373 |
+
{'params': encoder_params, 'lr': self.config.learning_rate * 0.1},
|
| 374 |
+
{'params': other_params, 'lr': self.config.learning_rate}
|
| 375 |
+
], weight_decay=self.config.weight_decay)
|
| 376 |
+
|
| 377 |
+
original_epochs = self.config.num_train_epochs
|
| 378 |
+
self.config.num_train_epochs = 5
|
| 379 |
+
|
| 380 |
+
self._run_training_phase(task_configs, train_datasets, val_datasets, train_loader, optimizer, "Hybrid")
|
| 381 |
+
|
| 382 |
+
self.config.num_train_epochs = original_epochs
|
| 383 |
+
|
| 384 |
+
def _phase_4_native(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict):
|
| 385 |
+
print("\n" + "="*60)
|
| 386 |
+
print("Phase 4: Full Native Training")
|
| 387 |
+
print("="*60)
|
| 388 |
+
|
| 389 |
+
for name, param in self.model.named_parameters():
|
| 390 |
+
param.requires_grad = True
|
| 391 |
+
|
| 392 |
+
train_dataset = MultiTaskDataset(train_datasets, self.model.tokenizer, task_configs)
|
| 393 |
+
train_sampler = TaskAwareBatchSampler(train_dataset, self.config.per_device_train_batch_size, shuffle=True)
|
| 394 |
+
train_loader = DataLoader(train_dataset, batch_sampler=train_sampler, collate_fn=collate_fn, num_workers=0)
|
| 395 |
+
|
| 396 |
+
optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.config.learning_rate * 0.1, weight_decay=self.config.weight_decay)
|
| 397 |
+
|
| 398 |
+
self._run_training_phase(task_configs, train_datasets, val_datasets, train_loader, optimizer, "Native")
|
| 399 |
+
|
| 400 |
+
def _run_training_phase(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict, train_loader, optimizer, phase_name):
|
| 401 |
+
if val_datasets:
|
| 402 |
+
val_dataset = MultiTaskDataset(val_datasets, self.model.tokenizer, task_configs)
|
| 403 |
+
val_sampler = TaskAwareBatchSampler(val_dataset, self.config.per_device_eval_batch_size, shuffle=False)
|
| 404 |
+
self.val_loader = DataLoader(val_dataset, batch_sampler=val_sampler, collate_fn=collate_fn, num_workers=0)
|
| 405 |
+
|
| 406 |
+
for epoch in range(self.config.num_train_epochs):
|
| 407 |
+
self.model.train()
|
| 408 |
+
total_loss = 0
|
| 409 |
+
num_batches = 0
|
| 410 |
+
|
| 411 |
+
pbar = tqdm(train_loader, desc=f"{phase_name} Epoch {epoch+1}/{self.config.num_train_epochs}")
|
| 412 |
+
|
| 413 |
+
for batch in pbar:
|
| 414 |
+
batch = {k: v.to(self.config.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
|
| 415 |
+
|
| 416 |
+
outputs = self.model(
|
| 417 |
+
input_ids=batch["input_ids"],
|
| 418 |
+
attention_mask=batch.get("attention_mask"),
|
| 419 |
+
task_name=batch["task_name"][0],
|
| 420 |
+
labels=batch.get("labels")
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
if outputs is not None and "loss" in outputs and outputs["loss"] is not None:
|
| 424 |
+
loss = outputs["loss"]
|
| 425 |
+
if torch.isfinite(loss):
|
| 426 |
+
loss.backward()
|
| 427 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.config.max_grad_norm)
|
| 428 |
+
optimizer.step()
|
| 429 |
+
optimizer.zero_grad()
|
| 430 |
+
total_loss += loss.item()
|
| 431 |
+
num_batches += 1
|
| 432 |
+
pbar.set_postfix({'loss': f'{total_loss/num_batches:.4f}'})
|
| 433 |
+
|
| 434 |
+
if num_batches > 0:
|
| 435 |
+
print(f"\n{phase_name} Epoch {epoch+1} average loss: {total_loss/num_batches:.4f}")
|
| 436 |
+
if self.val_loader is not None:
|
| 437 |
+
val_loss = self._validate()
|
| 438 |
+
print(f"validation loss:{val_loss}")
|
| 439 |
+
|
| 440 |
+
if val_loss is not None and val_loss < self.best_val_loss:
|
| 441 |
+
print("best val loss --->",val_loss)
|
| 442 |
+
self.best_val_loss = val_loss
|
| 443 |
+
|
| 444 |
+
final_path = os.path.join(self.exp_dir, f"{phase_name.lower()}_model.pt")
|
| 445 |
+
self.model.save_model(final_path)
|
| 446 |
+
def _validate(self):
|
| 447 |
+
self.model.eval()
|
| 448 |
+
total_loss = 0
|
| 449 |
+
val_batches = 0
|
| 450 |
+
|
| 451 |
+
with torch.no_grad():
|
| 452 |
+
for batch in self.val_loader:
|
| 453 |
+
task_name = batch["task_name"][0]
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
batch = {k: v.to(self.config.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
|
| 458 |
+
|
| 459 |
+
outputs = self.model(
|
| 460 |
+
input_ids=batch["input_ids"],
|
| 461 |
+
attention_mask=batch.get("attention_mask"),
|
| 462 |
+
task_name=task_name,
|
| 463 |
+
labels=batch.get("labels")
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
if outputs is not None and "loss" in outputs and outputs["loss"] is not None:
|
| 467 |
+
if torch.isfinite(outputs["loss"]):
|
| 468 |
+
total_loss += outputs["loss"].item()
|
| 469 |
+
val_batches += 1
|
| 470 |
+
|
| 471 |
+
if val_batches > 0:
|
| 472 |
+
return total_loss / val_batches
|
| 473 |
+
return None
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
class LoRATrainer:
|
| 477 |
+
def __init__(self, model: DynamicTransformer, config: ModelConfig, exp_dir: str, rank: int = 8, alpha: float = 16.0, dropout: float = 0.1, mode: str = "single"):
|
| 478 |
+
self.model = model
|
| 479 |
+
self.config = model.config
|
| 480 |
+
self.exp_dir = exp_dir
|
| 481 |
+
os.makedirs(self.exp_dir, exist_ok=True)
|
| 482 |
+
self.rank = rank
|
| 483 |
+
self.alpha = alpha
|
| 484 |
+
self.dropout = dropout
|
| 485 |
+
self.mode = mode
|
| 486 |
+
self.lora_wrapper = None
|
| 487 |
+
self.best_val_loss = float('inf')
|
| 488 |
+
|
| 489 |
+
def train(self, task_configs: List[TaskConfig], train_datasets: Dict, val_datasets: Dict):
|
| 490 |
+
for task_config in task_configs:
|
| 491 |
+
if task_config.task_name not in self.model.current_tasks:
|
| 492 |
+
self.model.add_task(task_config)
|
| 493 |
+
|
| 494 |
+
if self.mode == "single":
|
| 495 |
+
self.lora_wrapper = LoRAWrapper(self.model, self.rank, self.alpha, self.dropout)
|
| 496 |
+
elif self.mode == "multi":
|
| 497 |
+
self.lora_wrapper = MultiTaskLoRAWrapper(self.model, self.rank, self.alpha, self.dropout)
|
| 498 |
+
elif self.mode == "progressive":
|
| 499 |
+
progressive_trainer = ProgressiveLoRATrainer(self.model, self.config, self.exp_dir, self.rank, self.rank * 2)
|
| 500 |
+
return progressive_trainer.train(task_configs, train_datasets, val_datasets)
|
| 501 |
+
else:
|
| 502 |
+
self.lora_wrapper = LoRAWrapper(self.model, self.rank, self.alpha, self.dropout)
|
| 503 |
+
|
| 504 |
+
train_dataset = MultiTaskDataset(train_datasets, self.model.tokenizer, task_configs)
|
| 505 |
+
val_dataset = None
|
| 506 |
+
val_loader = None
|
| 507 |
+
print(len(val_datasets))
|
| 508 |
+
if val_datasets:
|
| 509 |
+
val_dataset = MultiTaskDataset(val_datasets, self.model.tokenizer, task_configs)
|
| 510 |
+
val_sampler = TaskAwareBatchSampler(val_dataset, self.config.per_device_eval_batch_size, shuffle=False)
|
| 511 |
+
val_loader = DataLoader(val_dataset, batch_sampler=val_sampler, collate_fn=collate_fn, num_workers=0)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
train_sampler = TaskAwareBatchSampler(train_dataset, self.config.per_device_train_batch_size, shuffle=True)
|
| 515 |
+
train_loader = DataLoader(train_dataset, batch_sampler=train_sampler, collate_fn=collate_fn, num_workers=0)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
trainable_params = self.lora_wrapper.get_trainable_parameters()
|
| 520 |
+
|
| 521 |
+
print(f"\nLoRA Training Mode: {self.mode}")
|
| 522 |
+
print(f"Trainable parameters: {sum(p.numel() for p in trainable_params):,}")
|
| 523 |
+
print(f"Total model parameters: {sum(p.numel() for p in self.model.parameters()):,}")
|
| 524 |
+
print(f"Reduction: {(1 - sum(p.numel() for p in trainable_params) / sum(p.numel() for p in self.model.parameters())) * 100:.2f}%")
|
| 525 |
+
|
| 526 |
+
optimizer = torch.optim.AdamW(trainable_params, lr=self.config.learning_rate, weight_decay=self.config.weight_decay)
|
| 527 |
+
|
| 528 |
+
for epoch in range(self.config.num_train_epochs):
|
| 529 |
+
self.model.train()
|
| 530 |
+
total_loss = 0
|
| 531 |
+
num_batches = 0
|
| 532 |
+
|
| 533 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{self.config.num_train_epochs}")
|
| 534 |
+
|
| 535 |
+
for batch in pbar:
|
| 536 |
+
task_name = batch["task_name"][0]
|
| 537 |
+
|
| 538 |
+
if self.mode == "multi" and hasattr(self.lora_wrapper, 'set_current_task'):
|
| 539 |
+
self.lora_wrapper.set_current_task(task_name)
|
| 540 |
+
|
| 541 |
+
batch = {k: v.to(self.config.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
|
| 542 |
+
|
| 543 |
+
outputs = self.model(
|
| 544 |
+
input_ids=batch["input_ids"],
|
| 545 |
+
attention_mask=batch.get("attention_mask"),
|
| 546 |
+
task_name=task_name,
|
| 547 |
+
labels=batch.get("labels")
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
if outputs is not None and "loss" in outputs and outputs["loss"] is not None:
|
| 551 |
+
loss = outputs["loss"]
|
| 552 |
+
if torch.isfinite(loss):
|
| 553 |
+
loss.backward()
|
| 554 |
+
torch.nn.utils.clip_grad_norm_(trainable_params, self.config.max_grad_norm)
|
| 555 |
+
optimizer.step()
|
| 556 |
+
optimizer.zero_grad()
|
| 557 |
+
total_loss += loss.item()
|
| 558 |
+
num_batches += 1
|
| 559 |
+
pbar.set_postfix({'loss': f'{total_loss/num_batches:.4f}'})
|
| 560 |
+
|
| 561 |
+
if num_batches > 0:
|
| 562 |
+
print(f"\nEpoch {epoch+1} average loss: {total_loss/num_batches:.4f}")
|
| 563 |
+
#print("@"*100)
|
| 564 |
+
#print(len(val_loader))
|
| 565 |
+
if val_loader is not None:
|
| 566 |
+
val_loss = self._validate(val_loader)
|
| 567 |
+
print(f"validation loss:{val_loss}")
|
| 568 |
+
|
| 569 |
+
if val_loss is not None and val_loss < self.best_val_loss:
|
| 570 |
+
self.best_val_loss = val_loss
|
| 571 |
+
self._save_model()
|
| 572 |
+
|
| 573 |
+
if self.mode == "single":
|
| 574 |
+
self.lora_wrapper.merge_all_lora_weights()
|
| 575 |
+
|
| 576 |
+
final_path = os.path.join(self.exp_dir, "final_model.pt")
|
| 577 |
+
self.model.save_model(final_path)
|
| 578 |
+
|
| 579 |
+
return self.model
|
| 580 |
+
|
| 581 |
+
def _validate(self, val_loader):
|
| 582 |
+
self.model.eval()
|
| 583 |
+
total_loss = 0
|
| 584 |
+
val_batches = 0
|
| 585 |
+
|
| 586 |
+
with torch.no_grad():
|
| 587 |
+
for batch in val_loader:
|
| 588 |
+
task_name = batch["task_name"][0]
|
| 589 |
+
|
| 590 |
+
if self.mode == "multi" and hasattr(self.lora_wrapper, 'set_current_task'):
|
| 591 |
+
self.lora_wrapper.set_current_task(task_name)
|
| 592 |
+
|
| 593 |
+
batch = {k: v.to(self.config.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
|
| 594 |
+
|
| 595 |
+
outputs = self.model(
|
| 596 |
+
input_ids=batch["input_ids"],
|
| 597 |
+
attention_mask=batch.get("attention_mask"),
|
| 598 |
+
task_name=task_name,
|
| 599 |
+
labels=batch.get("labels")
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
if outputs is not None and "loss" in outputs and outputs["loss"] is not None:
|
| 603 |
+
if torch.isfinite(outputs["loss"]):
|
| 604 |
+
total_loss += outputs["loss"].item()
|
| 605 |
+
val_batches += 1
|
| 606 |
+
|
| 607 |
+
if val_batches > 0:
|
| 608 |
+
return total_loss / val_batches
|
| 609 |
+
return None
|
| 610 |
+
|
| 611 |
+
def _save_model(self):
|
| 612 |
+
save_path = os.path.join(self.exp_dir, "best_model.pt")
|
| 613 |
+
os.makedirs(self.exp_dir, exist_ok=True)
|
| 614 |
+
self.model.save_model(save_path)
|
| 615 |
+
print(f"Best model saved to {save_path}")
|