AIGC笔记--SVD中UNet加载预训练权重

1--加载方式

  1. 加载全参数(.ckpt)

  2. 加载LoRA(.safetensors)

2--简单实例

python 复制代码
import sys
sys.path.append("/mnt/dolphinfs/hdd_pool/docker/user/hadoop-waimai-aigc/liujinfu/Codes/v3d-vgen-motion")

import torch
from peft import LoraConfig
from safetensors import safe_open

from svd.models.i2v_svd_unet import UNetSpatioTemporalConditionModel
from svd.utils.util import zero_rank_print

if __name__ == "__main__":

    pretrained_model_path = "/mnt/dolphinfs/hdd_pool/docker/user/hadoop-waimai-aigc/liujinfu/Codes/svd_models/models/stable-video-diffusion-img2vid-xt"
    unet = UNetSpatioTemporalConditionModel.from_pretrained(pretrained_model_path, subfolder = "unet")

    # resume_checkpoint_path = "/mnt/dolphinfs/hdd_pool/docker/user/hadoop-waimai-aigc/liujinfu/Codes/v3d-vgen-motion/results/outputs_motionlora_realRota_0603_1024_stride5/test-0-2024-06-03T14-31-30/checkpoints/checkpoint-500.safetensors"
    resume_checkpoint_path = "/mnt/dolphinfs/hdd_pool/docker/user/hadoop-waimai-aigc/liujinfu/Codes/v3d-vgen-motion/results/outputs_motionFull_realRota_0529_stride5/test-0-2024-05-29T10-04-34/checkpoints/checkpoint-step-5000.ckpt"

    # Load pretrained unet weights
    if resume_checkpoint_path.endswith(".ckpt"):
        zero_rank_print(f"resume from checkpoint: {resume_checkpoint_path}")
        resume_checkpoint = torch.load(resume_checkpoint_path, map_location="cpu")
        # resume dit parameters
        print(f'resume_checkpoint keys: {resume_checkpoint.keys()}')
        state_dict = resume_checkpoint["state_dict"]
        m, u = unet.load_state_dict(state_dict, strict=False)
        zero_rank_print(f"dit missing keys: {len(m)}, unexpected keys: {len(u)}")
        assert len(u) == 0
        # resume global step
        resume_global_step = False
        if "global_step" in resume_checkpoint and resume_global_step:
            zero_rank_print(f"resume global_step: {resume_checkpoint['global_step']}")
            global_step = resume_checkpoint['global_step']    
            
    elif resume_checkpoint_path.endswith(".safetensors"):

        unet_lora_config = LoraConfig(
            r = 64, 
            lora_alpha = 64, # scaling = lora_alpha / r
            init_lora_weights = "gaussian", 
            target_modules = ["to_q","to_k","to_v","to_out.0"],
            lora_dropout = 0.1
        )
        unet.add_adapter(unet_lora_config)

        zero_rank_print(f"resume from safetensors: {resume_checkpoint_path}")
        
        state_dict = {}
        with safe_open(resume_checkpoint_path, framework="pt", device="cpu") as f:
            for key in f.keys():
                key_ = key.replace('unet.', '').replace('.weight', '')
                state_dict[key_] = f.get_tensor(key)

                u = 0
                try:
                    unet.get_submodule(key_+'.default').state_dict()['weight'].data.copy_(state_dict[key_])
                except:
                    u += 1
        assert u == 0, "resume unet params failed"

    print("All Done!")
相关推荐
hqyjzsb6 小时前
AI证书和传统证书有什么区别?
人工智能·金融·数据挖掘·数据分析·aigc·创业创新·学习方法
洞窝技术8 小时前
QwenPaw 官方详解:部署在你本地的专属数字员工,懂你所需,伴你左右
aigc
后端小肥肠10 小时前
做个人 IP 不用真人出镜,我做了个一键生成 IP 动画视频的 Skill
人工智能·aigc·agent
wu85877345712 小时前
从 Prompt 到 Loop:拆解 AI 工程化四范式的演进逻辑与落地边界
人工智能·ai·prompt·aigc·ai编程
爱查宝小二12 小时前
爱查宝 AIGC 检测与改写实效评测
人工智能·aigc
库拉大叔14 小时前
写小说谁家强?GPT-5.6、Claude 4.8 Opus、Gemini 3.5文学素养硬核横评
人工智能·gpt·aigc
李剑一15 小时前
Kimi K3太牛了!但老板说API太贵,让我本地化部署,我算完成本,他涨红脸沉默不语了!其实成本不高,三千万足矣。
aigc·ai编程
leeyi15 小时前
ToolsNode 源码拆解:工具并行执行、中间件洋葱与 HITL Rerun(第65篇-E51)
aigc·agent·ai编程
三声三视15 小时前
我弃了“全自主 Agent“:一次误退款,让我给所有危险工具加了道人工闸
人工智能·ai·aigc
倔强的石头_15 小时前
我把 22 篇 RAG 论文喂给了 RAG,让 AI 自己给我讲明白什么是 RAG
aigc