解除diffusers库的prompt长度限制(SDXL版)

2025-5-21 注:本文只提供思路,没有解决"权重识别"、"BREAK"问题。

要想实现与webui一样的绘图效果与无限prompt,可参考diffusers/examples/community/lpw_stable_diffusion_xl.py

1、上代码

python 复制代码
from diffusers import StableDiffusionXLPipeline,EulerAncestralDiscreteScheduler

# 1. 加载模型
config_path = "anime_illust_diffusion_xl"
model_id="anime_illust_diffusion_xl/animeIllustDiffusion_v08.safetensors"
pipe = StableDiffusionXLPipeline.from_single_file(
    model_id, 
    dtype=torch.bfloat16,
    config=config_path,
    local_files_only=True)

pipe = pipe.to("cuda") 

# 2. 准备输入图像和提示词
#======================================
clip_skip = 1

prompt = 40 * "1girl, solo, black background,(best quality:1.5)" # 超出77长度限制
negative_prompt = "worst quality, low quality, multi views"

max_length = pipe.tokenizer.model_max_length
tokenizers = [pipe.tokenizer,pipe.tokenizer_2]
text_encoders = [pipe.text_encoder,pipe.text_encoder_2]
prompts = [prompt,prompt]
negative_prompts = [negative_prompt,negative_prompt]

prompt_embeds_list = []
negative_prompt_embeds_list= []

for prompt,negative_prompt, tokenizer, text_encoder in zip(prompts,negative_prompts, tokenizers, text_encoders):
    input_ids = tokenizer(prompt, return_tensors="pt").input_ids
    input_ids = input_ids.to("cuda")
    negative_ids =tokenizer(negative_prompt, truncation=False, padding="max_length", max_length=input_ids.shape[-1], return_tensors="pt").input_ids                                                                                                     
    negative_ids = negative_ids.to("cuda")
    
    # 分段处理prompt
    concat_embeds = [] 
    neg_embeds = []
    for i in range(0, input_ids.shape[-1], max_length):
        embeds_1 = text_encoder(input_ids[:, i: i + max_length], output_hidden_states=True)
        pooled_prompt_embeds = embeds_1[0]
        concat_embeds.append(embeds_1.hidden_states[-(clip_skip+2)])
        
        embeds_2 = text_encoder(negative_ids[:, i: i + max_length],output_hidden_states=True)
        negative_pooled_prompt_embeds = embeds_2[0]
        neg_embeds.append(embeds_2.hidden_states[-2])
        

    # 拼接text_encoder结果
    # 例:(1,77,768)+(1,22,768) = (1,99,768)
    prompt_embeds = torch.cat(concat_embeds, dim=1)
    negative_prompt_embeds = torch.cat(neg_embeds, dim=1)
    
    prompt_embeds_list.append(prompt_embeds)
    negative_prompt_embeds_list.append(negative_prompt_embeds)

# 拼接两个text_encoder的特征
# 例:(1,99,768)+(1,99,1280) = (1,99,2048)
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)

#=====================================

# 3. 设置生成参数
num_inference_steps = 28  # 推理步数,可根据需要调整
guidance_scale = 7     # 引导比例,控制生成图像与提示的匹配程度
generator = torch.Generator("cuda").manual_seed(31)
 


# 4. 执行生成
with torch.no_grad():
    images = pipe(
        #prompt=prompt,
        #negative_prompt=negative_prompt,
        prompt_embeds = prompt_embeds, 
        pooled_prompt_embeds = pooled_prompt_embeds,
        negative_prompt_embeds = negative_prompt_embeds, 
        negative_pooled_prompt_embeds = negative_pooled_prompt_embeds,
        height = 1216,
        width= 832,
        num_inference_steps=num_inference_steps,
        guidance_scale=guidance_scale,
        clip_skip=clip_skip,
        num_images_per_prompt=2,
        generator = generator
    ).images

print(type(images))
# 5. 保存结果
for id in range(len(images)):
    images[id].save(f"output_image_{id}.png")

2、分析

需要准备下面四样东西:

prompt_embeds # 正向提示词编码

pooled_prompt_embeds # 正向提示词编码的全局池化

negative_prompt_embeds # 负向提示词编码

negative_pooled_prompt_embeds # 负向提示词的全局池化

前置知识:

  1. sdxl有两个text_encoder,不妨设为t1,t2:

将prompt输入t1,得到768维的数据;输入t2,得到1280维的数据

最后送入Unet进行cross_attention的,是拼接后2048维的数据

t1、t2的输入限制了大小,最大为77

2. pooled_prompt_embeds,这玩意的原理我不懂,不过生成方式在上面代码里有写

解决方案

把长度为99的prompt,拆分为77+22,分别输入text_encoder,然后将结果拼接

相关推荐
昨日之日20061 小时前
Wan2.2-S2V - 音频驱动图像生成电影级质量的数字人视频 ComfyUI工作流 支持50系显卡 一键整合包下载
人工智能·音视频
SEO_juper4 小时前
大型语言模型SEO(LLM SEO)完全手册:驾驭搜索新范式
人工智能·语言模型·自然语言处理·chatgpt·llm·seo·数字营销
攻城狮7号5 小时前
腾讯混元翻译模型Hunyuan-MT-7B开源,先前拿了30个冠军
人工智能·hunyuan-mt-7b·腾讯混元翻译模型·30个冠军
zezexihaha5 小时前
从“帮写文案”到“管生活”:个人AI工具的边界在哪?
人工智能
算家云5 小时前
nano banana官方最强Prompt模板来了!六大场景模板详解
人工智能·谷歌·ai大模型·算家云·ai生图·租算力,到算家云·nano banana 提示词
暴躁的大熊5 小时前
AI助力决策:告别生活与工作中的纠结,明析抉择引领明智选择
人工智能
Gyoku Mint5 小时前
提示词工程(Prompt Engineering)的崛起——为什么“会写Prompt”成了新技能?
人工智能·pytorch·深度学习·神经网络·语言模型·自然语言处理·nlp
梁小憨憨5 小时前
zotero扩容
人工智能·笔记
大数据张老师5 小时前
AI架构师的思维方式与架构设计原则
人工智能·架构师·ai架构·后端架构
AKAMAI5 小时前
Entity Digital Sports 降低成本并快速扩展
人工智能·云计算