Load LoRA XXX.safetensors to diffusers (StableDiffusionPipeline/StableDiffusionControlNetPipeline)

该函数从安全张量中加载LoRA权重,然后更新Diffusers模型中的text_encoder和unet层。它遍历state_dict,根据键的结构找到对应模型层,并应用权重更新。权重更新涉及到weight_up、weight_down和alpha,最后将这些权重适当地加到当前层的权重数据上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

def load_lora_weights(pipeline, checkpoint_path, multiplier, device, dtype):
    LORA_PREFIX_UNET = "lora_unet"
    LORA_PREFIX_TEXT_ENCODER = "lora_te"
    # load LoRA weight from .safetensors
    state_dict = load_file(checkpoint_path, device=device)

    updates = defaultdict(dict)
    for key, value in state_dict.items():
        # it is suggested to print out the key, it usually will be something like below
        # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight"

        layer, elem = key.split('.', 1)
        updates[layer][elem] = value

    # directly update weight in diffusers model
    for layer, elems in updates.items():

        if "text" in layer:
            layer_infos = layer.split(LORA_PREFIX_TEXT_ENCODER + "_")[-1].split("_")
            curr_layer = pipeline.text_encoder
        else:
            layer_infos = layer.split(LORA_PREFIX_UNET + "_")[-1].split("_")
            curr_layer = pipeline.unet

        # find the target layer
        temp_name = layer_infos.pop(0)
        while len(layer_infos) > -1:
            try:
                curr_layer = curr_layer.__getattr__(temp_name)
                if len(layer_infos) > 0:
                    temp_name = layer_infos.pop(0)
                elif len(layer_infos) == 0:
                    break
            except Exception:
                if len(temp_name) > 0:
                    temp_name += "_" + layer_infos.pop(0)
                else:
                    temp_name = layer_infos.pop(0)

        # get elements for this layer
        weight_up = elems['lora_up.weight'].to(dtype)
        weight_down = elems['lora_down.weight'].to(dtype)
        alpha = elems['alpha']
        if alpha:
            alpha = alpha.item() / weight_up.shape[1]
        else:
            alpha = 1.0

        curr_layer.weight.data = curr_layer.weight.data.to(device) 
        # update weight
        if len(weight_up.shape) == 4:
            curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up.squeeze(3).squeeze(2), weight_down.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)
        else:
            curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up, weight_down)

    return pipeline

Example usage:

pipe = load_lora_weights(pipe, lora_path, 1.0, 'cuda', torch.float16)

### 如何获取 `thibaud_x1_openpose_256lora.safetensors` 文件 要找到并下载名为 `thibaud_x1_openpose_256lora.safetensors` 的文件,可以按照以下方法操作: #### 1. **确认文件用途** 该 `.safetensors` 文件通常是一个 LoRA(Low-Rank Adaptation)权重文件,用于增强 Stable Diffusion 或其他 AI 绘画模型的表现力。这类文件主要用于微调特定风格或功能,例如 OpenPose 骨骼检测效果。 #### 2. **查找资源网站** 许多用户会分享自定义训练的 LoRA 权重到公开平台。以下是可能存储此类文件的地方: - **CivitAI**: CivitAI 是一个专注于 AI 艺术工具和模型的社区,提供了大量由用户上传的 LoRA 和插件文件[^4]。 - **Hugging Face Hub**: Hugging Face 提供了一个广泛的机器学习模型库,其中也包括一些开源的 LoRA 权重文件[^5]。 可以通过搜索引擎输入关键词如 `"thibaud_x1_openpose_256lora civitai"` 或 `"thibaud_x1_openpose_256lora huggingface"` 进行定位。 #### 3. **手动制作或请求作者提供** 如果无法在线找到现成的文件,则可以选择联系原作者 Thibaud (假设此名称来源于其命名方式)。部分开发者会在 GitHub、Discord 社区或其他社交媒体平台上活跃。通过这些渠道询问具体发布位置或者寻求帮助是一种有效途径。 另外还可以尝试自己训练类似的LoRA模块来满足需求,不过这需要一定技术基础以及相应硬件支持. #### 下载命令示例 (适用于已知URL情况) 当成功定位目标链接之后可利用wget等工具完成自动化抓取过程: ```bash wget https://example.com/path/to/thibaud_x1_openpose_256lora.safetensors -O ./models/Lora/thibaud_x1_openpose_256lora.safetensors ``` --- ### 注意事项 确保所使用的模型符合版权规定,并仅限于个人研究与合法范围内应用。此外,在加载新LORA之前建议备份原有配置以免造成不可逆更改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值