daima / __init__.py
kazuyi1222's picture
Upload __init__.py
50bfe77 verified
Raw
History Blame Contribute Delete
10.2 kB
import os
import math
import torch
import folder_paths
import comfy.utils
import comfy.lora
class GLoKRLoaderNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"clip": ("CLIP",),
"lora_name": (folder_paths.get_filename_list("loras"),),
"strength_model": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"strength_clip": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"rs_lora": ("BOOLEAN", {"default": False}),
"wd_on_out": ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("MODEL", "CLIP")
FUNCTION = "load_glokr"
CATEGORY = "loaders"
def load_glokr(self, model, clip, lora_name, strength_model, strength_clip, rs_lora, wd_on_out):
if strength_model == 0.0 and strength_clip == 0.0:
return (model, clip)
lora_path = folder_paths.get_full_path("loras", lora_name)
if lora_path is None:
raise FileNotFoundError(f"GLoKR LoRA '{lora_name}' not found.")
lora_sd = comfy.utils.load_torch_file(lora_path)
key_map_unet = {}
if model is not None:
key_map_unet = comfy.lora.model_lora_keys_unet(model.model, key_map_unet)
key_map_clip = {}
if clip is not None:
key_map_clip = comfy.lora.model_lora_keys_clip(clip.cond_stage_model, key_map_clip)
groups = {}
for key, tensor in lora_sd.items():
if "." in key:
base, suffix = key.rsplit(".", 1)
if base not in groups:
groups[base] = {}
groups[base][suffix] = tensor
unet_patches = {}
clip_patches = {}
def rebuild_tucker(t, a, b):
return torch.einsum("i j ..., i u, j v -> u v ...", t, a, b)
def make_kron_local(w1, w2):
if len(w2.shape) == 4:
w1 = w1.unsqueeze(2).unsqueeze(2)
w2 = w2.contiguous()
return torch.kron(w1, w2)
def apply_weight_decompose(weight, dora_scale, wd_on_out=True, multiplier=1.0):
target_dtype = weight.dtype
weight = weight.to(dora_scale.dtype)
dora_norm_dims = weight.dim() - 1
if wd_on_out:
weight_norm = (
weight.reshape(weight.shape[0], -1)
.norm(dim=1)
.reshape(weight.shape[0], *[1] * dora_norm_dims)
) + torch.finfo(weight.dtype).eps
else:
weight_norm = (
weight.transpose(0, 1)
.reshape(weight.shape[1], -1)
.norm(dim=1, keepdim=True)
.reshape(weight.shape[1], *[1] * dora_norm_dims)
.transpose(0, 1)
) + torch.finfo(weight.dtype).eps
scale = dora_scale.to(weight.device) / weight_norm
if multiplier != 1.0:
scale = multiplier * (scale - 1.0) + 1.0
return (weight * scale).to(target_dtype)
for base_key, group in groups.items():
target_key = None
is_unet = False
current_strength = 1.0
if base_key in key_map_unet:
target_key = key_map_unet[base_key]
is_unet = True
current_strength = strength_model
elif base_key in key_map_clip:
target_key = key_map_clip[base_key]
is_unet = False
current_strength = strength_clip
else:
normalized_base = base_key.replace("lora_unet_", "").replace("lora_te_", "").replace("lora_te1_", "").replace("lora_te2_", "")
matched = False
for k_map, v_map in key_map_unet.items():
norm_map = k_map.replace("lora_unet_", "")
if normalized_base == norm_map:
target_key = v_map
is_unet = True
current_strength = strength_model
matched = True
break
if not matched:
for k_map, v_map in key_map_clip.items():
norm_map = k_map.replace("lora_te_", "").replace("lora_te1_", "").replace("lora_te2_", "")
if normalized_base == norm_map:
target_key = v_map
is_unet = False
current_strength = strength_clip
matched = True
break
if target_key is None or current_strength == 0.0:
continue
if is_unet:
base_sd = model.model.state_dict()
else:
base_sd = clip.cond_stage_model.state_dict()
if target_key not in base_sd:
continue
orig_weight = base_sd[target_key]
orig_shape = orig_weight.shape
out_dim = orig_shape[0]
in_dim = orig_shape[1]
group_cpu = {k: v.cpu().float() for k, v in group.items()}
lora_dim = 1
for k in ["b_w1_a", "b_w2_a", "a_w1_a", "a_w2_a"]:
if k in group_cpu:
lora_dim = group_cpu[k].shape[1]
break
alpha = group_cpu.get("alpha", torch.tensor(lora_dim)).item()
if alpha == 0:
alpha = lora_dim
scalar = group_cpu.get("scalar", torch.tensor(1.0)).item()
use_b_w1 = "b_w1" in group_cpu
use_b_w2 = "b_w2" in group_cpu
use_a_w1 = "a_w1" in group_cpu
use_a_w2 = "a_w2" in group_cpu
r_factor = math.sqrt(lora_dim) if rs_lora else lora_dim
scale_b = 1.0 if (use_b_w2 and use_b_w1) else (alpha / r_factor)
scale_a = 1.0 if (use_a_w2 and use_a_w1) else (alpha / r_factor)
b_w1_prod = None
if "b_w1" in group_cpu:
b_w1_prod = group_cpu["b_w1"]
elif "b_w1_a" in group_cpu and "b_w1_b" in group_cpu:
b_w1_prod = group_cpu["b_w1_a"] @ group_cpu["b_w1_b"]
b_w2_prod = None
if "b_w2" in group_cpu:
b_w2_prod = group_cpu["b_w2"]
elif "b_w2_a" in group_cpu and "b_w2_b" in group_cpu:
if "b_t2" in group_cpu:
b_w2_prod = rebuild_tucker(group_cpu["b_t2"], group_cpu["b_w2_a"], group_cpu["b_w2_b"])
else:
b_w2_prod = group_cpu["b_w2_a"] @ group_cpu["b_w2_b"]
if b_w1_prod is not None and b_w2_prod is not None:
wb = make_kron_local(b_w1_prod, b_w2_prod)
else:
wb = b_w1_prod if b_w1_prod is not None else b_w2_prod
if wb is not None:
wb = wb.reshape(orig_shape)
a_w1_prod = None
if "a_w1" in group_cpu:
a_w1_prod = group_cpu["a_w1"]
elif "a_w1_a" in group_cpu and "a_w1_b" in group_cpu:
a_w1_prod = group_cpu["a_w1_a"] @ group_cpu["a_w1_b"]
a_w2_prod = None
if "a_w2" in group_cpu:
a_w2_prod = group_cpu["a_w2"]
elif "a_w2_a" in group_cpu and "a_w2_b" in group_cpu:
a_w2_prod = group_cpu["a_w2_a"] @ group_cpu["a_w2_b"]
if a_w1_prod is not None and a_w2_prod is not None:
wa = make_kron_local(a_w1_prod, a_w2_prod)
else:
wa = a_w1_prod if a_w1_prod is not None else a_w2_prod
if wa is not None:
if len(orig_shape) > 2:
wa = wa.reshape(in_dim, in_dim, *(1,) * len(orig_shape[2:]))
else:
wa = wa.reshape(in_dim, in_dim)
orig_cpu = orig_weight.detach().cpu().float()
if wa is not None:
wa_flat = wa.view(wa.size(0), -1)
if orig_cpu.dim() > 2:
w_wa = torch.einsum("o i ..., i j -> o j ...", orig_cpu, wa_flat)
else:
w_wa = orig_cpu @ wa_flat
else:
w_wa = torch.zeros_like(orig_cpu)
scaled_update = torch.zeros_like(orig_cpu)
if wb is not None:
scaled_update += wb * scale_b
if wa is not None:
scaled_update += w_wa * scale_a
diff_weight = scaled_update * scalar
if "dora_scale" in group_cpu:
dora_scale = group_cpu["dora_scale"]
new_weight = apply_weight_decompose(
orig_cpu + diff_weight * current_strength,
dora_scale,
wd_on_out,
multiplier=current_strength
)
patch = new_weight - orig_cpu
else:
patch = diff_weight * current_strength
patch_tensor = patch.to(device=orig_weight.device, dtype=orig_weight.dtype)
if is_unet:
unet_patches[target_key] = (patch_tensor,)
else:
clip_patches[target_key] = (patch_tensor,)
new_model = model.clone() if model is not None else None
if new_model is not None and len(unet_patches) > 0:
new_model.add_patches(unet_patches, strength_patch=1.0)
new_clip = clip.clone() if clip is not None else None
if new_clip is not None and len(clip_patches) > 0:
new_clip.add_patches(clip_patches, strength_patch=1.0)
return (new_model, new_clip)
NODE_CLASS_MAPPINGS = {
"GLoKRLoader": GLoKRLoaderNode
}
NODE_DISPLAY_NAME_MAPPINGS = {
"GLoKRLoader": "GLoKR LoRA Loader"
}