如何为diffusers.StableDiffusionInpaintPipeline定义提示词权重?
调整Diffusers Inpainting Pipeline提示词权重的实现示例
diffusers的StableDiffusionInpaintPipeline不支持(word:1.5)这类括号权重语法,要实现特定词汇的权重调整,得手动生成加权的prompt_embeds参数,以下是完整实现示例:
步骤1:加载依赖与模型
from diffusers import StableDiffusionInpaintPipeline import torch # 加载inpainting管道,可根据需求替换模型 pipe = StableDiffusionInpaintPipeline.from_pretrained( "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16 ).to("cuda")
步骤2:实现加权嵌入生成函数
这个函数接收“提示词片段-权重”的配对列表,分别编码每个片段后按权重缩放,最后合并成最终的嵌入向量:
def generate_weighted_embeds(prompt_weight_pairs, tokenizer, text_encoder, device): embed_list = [] for segment, weight in prompt_weight_pairs: # 编码单段提示词 tokenized = tokenizer( segment, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt" ).to(device) with torch.no_grad(): segment_embed = text_encoder(tokenized.input_ids)[0] # 按权重缩放嵌入 embed_list.append(segment_embed * weight) # 对所有加权嵌入取平均,得到最终的prompt_embeds return torch.mean(torch.stack(embed_list), dim=0)
步骤3:定义加权提示词并生成嵌入
比如我们要让“red cat”的权重是2.0(比普通词影响力强一倍),“blue couch”权重是0.5(比普通词影响力弱一半):
# 定义提示词片段与对应权重 prompt_pairs = [ ("a photo of a", 1.0), ("red cat", 2.0), ("sitting on a", 1.0), ("blue couch", 0.5) ] # 生成加权prompt_embeds prompt_embeds = generate_weighted_embeds( prompt_pairs, pipe.tokenizer, pipe.text_encoder, "cuda" ) # 生成negative prompt的嵌入(按需调整内容) negative_prompt = "ugly, blurry, low resolution, distorted" negative_tokenized = pipe.tokenizer( negative_prompt, padding="max_length", max_length=pipe.tokenizer.model_max_length, truncation=True, return_tensors="pt" ).to("cuda") with torch.no_grad(): negative_prompt_embeds = pipe.text_encoder(negative_tokenized.input_ids)[0]
步骤4:执行inpainting推理
传入生成好的prompt_embeds和negative_prompt_embeds,替换原来的prompt参数:
# 假设你已经准备好原图image和遮罩图mask_image result = pipe( image=image, mask_image=mask_image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds ).images[0] # 保存结果 result.save("weighted_inpaint_result.png")
额外说明
- 权重是相对值:1.0为基准,大于1增强对应词汇的影响力,小于1削弱
- 若需要给单个子词加权(拆分到token级别),可以解析tokenizer的输出,单独调整每个token的嵌入值后再重组
- 确保
prompt_embeds和negative_prompt_embeds的维度一致,否则会报错
内容的提问来源于stack exchange,提问作者Bálint Komjáti
相关产品推荐
相关产品推荐

