| 117 | return super().state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars) |
| 118 | |
| 119 | def _fuse_lora(self, lora_scale=1.0, safe_fusing=False): |
| 120 | if self.lora_linear_layer is None: |
| 121 | return |
| 122 | |
| 123 | dtype, device = self.regular_linear_layer.weight.data.dtype, self.regular_linear_layer.weight.data.device |
| 124 | |
| 125 | w_orig = self.regular_linear_layer.weight.data.float() |
| 126 | w_up = self.lora_linear_layer.up.weight.data.float() |
| 127 | w_down = self.lora_linear_layer.down.weight.data.float() |
| 128 | |
| 129 | if self.lora_linear_layer.network_alpha is not None: |
| 130 | w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank |
| 131 | |
| 132 | fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0]) |
| 133 | |
| 134 | if safe_fusing and torch.isnan(fused_weight).any().item(): |
| 135 | raise ValueError( |
| 136 | "This LoRA weight seems to be broken. " |
| 137 | f"Encountered NaN values when trying to fuse LoRA weights for {self}." |
| 138 | "LoRA weights will not be fused." |
| 139 | ) |
| 140 | |
| 141 | self.regular_linear_layer.weight.data = fused_weight.to(device=device, dtype=dtype) |
| 142 | |
| 143 | # we can drop the lora layer now |
| 144 | self.lora_linear_layer = None |
| 145 | |
| 146 | # offload the up and down matrices to CPU to not blow the memory |
| 147 | self.w_up = w_up.cpu() |
| 148 | self.w_down = w_down.cpu() |
| 149 | self.lora_scale = lora_scale |
| 150 | |
| 151 | def _unfuse_lora(self): |
| 152 | if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None): |