| 401 | self.lora_layer = lora_layer |
| 402 | |
| 403 | def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False): |
| 404 | if self.lora_layer is None: |
| 405 | return |
| 406 | |
| 407 | dtype, device = self.weight.data.dtype, self.weight.data.device |
| 408 | |
| 409 | w_orig = self.weight.data.float() |
| 410 | w_up = self.lora_layer.up.weight.data.float() |
| 411 | w_down = self.lora_layer.down.weight.data.float() |
| 412 | |
| 413 | if self.lora_layer.network_alpha is not None: |
| 414 | w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank |
| 415 | |
| 416 | fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0]) |
| 417 | |
| 418 | if safe_fusing and torch.isnan(fused_weight).any().item(): |
| 419 | raise ValueError( |
| 420 | "This LoRA weight seems to be broken. " |
| 421 | f"Encountered NaN values when trying to fuse LoRA weights for {self}." |
| 422 | "LoRA weights will not be fused." |
| 423 | ) |
| 424 | |
| 425 | self.weight.data = fused_weight.to(device=device, dtype=dtype) |
| 426 | |
| 427 | # we can drop the lora layer now |
| 428 | self.lora_layer = None |
| 429 | |
| 430 | # offload the up and down matrices to CPU to not blow the memory |
| 431 | self.w_up = w_up.cpu() |
| 432 | self.w_down = w_down.cpu() |
| 433 | self._lora_scale = lora_scale |
| 434 | |
| 435 | def _unfuse_lora(self): |
| 436 | if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None): |