MCPcopy Create free account
hub / github.com/YesianRohn/TextSSR / _fuse_lora

Method _fuse_lora

diffusers/src/diffusers/models/lora.py:317–349  ·  view source on GitHub ↗
(self, lora_scale: float = 1.0, safe_fusing: bool = False)

Source from the content-addressed store, hash-verified

315 self.lora_layer = lora_layer
316
317 def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
318 if self.lora_layer is None:
319 return
320
321 dtype, device = self.weight.data.dtype, self.weight.data.device
322
323 w_orig = self.weight.data.float()
324 w_up = self.lora_layer.up.weight.data.float()
325 w_down = self.lora_layer.down.weight.data.float()
326
327 if self.lora_layer.network_alpha is not None:
328 w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
329
330 fusion = torch.mm(w_up.flatten(start_dim=1), w_down.flatten(start_dim=1))
331 fusion = fusion.reshape((w_orig.shape))
332 fused_weight = w_orig + (lora_scale * fusion)
333
334 if safe_fusing and torch.isnan(fused_weight).any().item():
335 raise ValueError(
336 "This LoRA weight seems to be broken. "
337 f"Encountered NaN values when trying to fuse LoRA weights for {self}."
338 "LoRA weights will not be fused."
339 )
340
341 self.weight.data = fused_weight.to(device=device, dtype=dtype)
342
343 # we can drop the lora layer now
344 self.lora_layer = None
345
346 # offload the up and down matrices to CPU to not blow the memory
347 self.w_up = w_up.cpu()
348 self.w_down = w_down.cpu()
349 self._lora_scale = lora_scale
350
351 def _unfuse_lora(self):
352 if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):

Callers

nothing calls this directly

Calls 1

toMethod · 0.45

Tested by

no test coverage detected