Apply LoRA weights to model weights. Args: weight_dict: The model weights dictionary (will be modified in place) lora_weights: The LoRA weights dictionary alpha: Global alpha scaling factor strength: Additional strength factor for LoR
(
self,
weight_dict: Dict[str, torch.Tensor],
lora_weights: Dict[str, torch.Tensor],
alpha: float = None,
strength: float = 1.0,
)
| 339 | return lora_diffs |
| 340 | |
| 341 | def apply_lora( |
| 342 | self, |
| 343 | weight_dict: Dict[str, torch.Tensor], |
| 344 | lora_weights: Dict[str, torch.Tensor], |
| 345 | alpha: float = None, |
| 346 | strength: float = 1.0, |
| 347 | ) -> int: |
| 348 | """ |
| 349 | Apply LoRA weights to model weights. |
| 350 | |
| 351 | Args: |
| 352 | weight_dict: The model weights dictionary (will be modified in place) |
| 353 | lora_weights: The LoRA weights dictionary |
| 354 | alpha: Global alpha scaling factor |
| 355 | strength: Additional strength factor for LoRA deltas |
| 356 | |
| 357 | Returns: |
| 358 | Number of LoRA weights successfully applied |
| 359 | """ |
| 360 | # Extract LoRA pairs, diffs, and alphas |
| 361 | lora_pairs = self.extract_lora_pairs(lora_weights) |
| 362 | lora_diffs = self.extract_lora_diffs(lora_weights) |
| 363 | |
| 364 | applied_count = 0 |
| 365 | used_lora_keys = set() |
| 366 | |
| 367 | # Apply LoRA pairs (matrix multiplication) |
| 368 | for model_key, pair_info in lora_pairs.items(): |
| 369 | if model_key not in weight_dict: |
| 370 | logger.debug(f"Model key not found: {model_key}") |
| 371 | continue |
| 372 | |
| 373 | param = weight_dict[model_key] |
| 374 | up_key = pair_info["up_key"] |
| 375 | down_key = pair_info["down_key"] |
| 376 | |
| 377 | # Track used keys |
| 378 | used_lora_keys.add(up_key) |
| 379 | used_lora_keys.add(down_key) |
| 380 | if pair_info["mid_key"]: |
| 381 | used_lora_keys.add(pair_info["mid_key"]) |
| 382 | |
| 383 | try: |
| 384 | lora_up = lora_weights[up_key].to(param.device, param.dtype) |
| 385 | lora_down = lora_weights[down_key].to(param.device, param.dtype) |
| 386 | |
| 387 | # Get LoRA-specific alpha if available, otherwise use global alpha |
| 388 | # Apply LoRA: W' = W + (alpha/rank) * B @ A |
| 389 | # where B = up (out_features, rank), A = down (rank, in_features) |
| 390 | if pair_info["alpha"]: |
| 391 | lora_scale = pair_info["alpha"] / lora_down.shape[0] |
| 392 | elif alpha is not None: |
| 393 | lora_scale = alpha / lora_down.shape[0] |
| 394 | else: |
| 395 | lora_scale = 1 |
| 396 | |
| 397 | if len(lora_down.shape) == 2 and len(lora_up.shape) == 2: |
| 398 | lora_delta = torch.mm(lora_up, lora_down) * lora_scale |
no test coverage detected