当前位置: 首页 > news >正文

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

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

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

1、上代码

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 = 1prompt = 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_idsinput_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")# 分段处理promptconcat_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).imagesprint(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,然后将结果拼接

http://www.xdnf.cn/news/567037.html

相关文章:

  • ArcGIS Pro 3.4 二次开发 - 核心主机
  • Linux yq 命令使用详解
  • 【Qt】QImage实战
  • 一文读懂迁移学习:从理论到实践
  • Git Clone 原理详解:为什么它比本地文件复制更快? -优雅草卓伊凡
  • word格式相关问题
  • C语言——函数递归与迭代
  • 微调后的模型保存与加载
  • Android13 wifi设置国家码详解
  • 结课作业01. 用户空间 MPU6050 体感鼠标驱动程序
  • SuperVINS:应对挑战性成像条件的实时视觉-惯性SLAM框架【全流程配置与测试!!!】【2025最新版!!!!】
  • flink 提交流程
  • 基于Flink的数据中台管理平台
  • CNN手写数字识别/全套源码+注释可直接运行
  • 基于moonshot模型的Dify大语言模型应用开发核心场景
  • 如何成为更好的自己?
  • AI智能分析网关V4玩手机检测算法精准管控人员手机行为,搭建智慧化安防监管体系
  • iOS 15.4.1 TrollStore(巨魔商店)安装教程详解:第二篇
  • Ubuntu学习记录
  • vscode打开vue + element项目
  • ADB常用语句
  • springboot 1.x2.x依赖spring版本
  • 初识Linux · 五种IO模型和非阻塞IO
  • Flink基本理解
  • 初识Linux · NAT 内网穿透 内网打洞 代理
  • 【题解-洛谷】B4240 [海淀区小学组 2025] 最短字符串
  • buunctf Crypto-[NCTF2019]Keyboard1
  • 腾讯游戏安全与高通合作构建PC端游安全新格局
  • 改写视频生产流程!快手SketchVideo开源:通过线稿精准控制动态分镜的AI视频生成方案
  • Java开发-如何将一个字符串转换成一个数组,又如何把他转换成一个集合