如何在Python中为HuggingFace模型加载多个LoRa safetensors
加载多个LoRA safetensors文件的解决方案
一、正确加载多个LoRA权重的两种方式
方式1:一次性加载多个LoRA
通过字典传入多个LoRA的路径,每个键为自定义的适配器名称,值为对应LoRA文件的路径:
import torch from diffusers import StableDiffusionPipeline text2img_pipe = StableDiffusionPipeline.from_pretrained( "stablediffusionapi/deliberate-v2", torch_dtype=torch.float16, safety_checker=None ).to("cuda:0") # 定义多个LoRA的路径映射 lora_config = { "character_lora": "<path/to/character_lora.safetensors>", "style_lora": "<path/to/style_lora.safetensors>" } # 一次性加载所有LoRA text2img_pipe.load_lora_weights(lora_config) # 可选:将所有LoRA权重合并到主模型,后续无需指定适配器即可使用 text2img_pipe.merge_lora_weights()
方式2:逐个加载并指定适配器名称
每次加载时通过adapter_name参数指定唯一名称,避免覆盖之前加载的LoRA:
# 加载第一个LoRA,指定适配器名称 text2img_pipe.load_lora_weights("<path/to/lora1.safetensors>", adapter_name="lora1") # 加载第二个LoRA,指定不同的适配器名称 text2img_pipe.load_lora_weights("<path/to/lora2.safetensors>", adapter_name="lora2") # 合并所有适配器的权重到主模型 text2img_pipe.merge_lora_weights()
二、解决"逐个加载权重未保留"的问题
之前逐个加载时权重被覆盖,是因为load_lora_weights默认使用名为default的适配器,每次加载都会覆盖这个适配器的权重。只要给每个LoRA指定不同的adapter_name,就能保留多个LoRA的权重,之后还可以通过text2img_pipe.set_adapters(["lora1", "lora2"], adapter_weights=[0.5, 0.5])调整不同LoRA的权重占比。
三、解决use_safetensors参数的报错问题
use_safetensors参数是用于加载基础StableDiffusion模型的safetensors格式权重,而非加载LoRA。报错原因是你的基础模型目录中混合了.bin和.safetensors格式的权重文件,或者缺少部分组件的safetensors文件。解决方法:
- 无需手动设置
use_safetensors=True,diffusers会自动检测目录中可用的权重格式并加载; - 若必须使用safetensors格式,确保基础模型的所有组件(unet、text_encoder、vae等)都有对应的
.safetensors文件,且目录中没有混合.bin文件。
内容的提问来源于stack exchange,提问作者D.Giunchi
相关产品推荐
相关产品推荐

