
Diffusers 中的 Kolors Pipeline中英双语照片级文生图模型的完整使用指南【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusersKolors 是由快手 Kolors 团队开发、基于潜在扩散latent diffusion的大规模文生图模型本指南讲解如何在 Diffusers 中通过KolorsPipeline与KolorsImg2ImgPipeline加载并运行该模型。你将掌握文生图、图生图、IP-Adapter 风格迁移的完整调用方法以及从模型组件、文本编码到去噪循环的源码级原理能够在 CUDA、MPS、XPU 与 CPU 等不同设备上快速落地中文与英文提示词的图像生成任务。模型背景为什么 Kolors 擅长中英双语与复杂语义Kolors 是快手 Kolors 团队在数十亿图文对上训练的大规模文生图模型。与多数仅针对英文优化的扩散模型不同Kolors 同时支持中文与英文输入在视觉质量、复杂语义理解以及中英文字渲染text rendering方面表现突出尤其擅长理解和生成中文特有的内容。根据官方技术报告的摘要其核心设计包含三个关键点以 GLM 作为文本编码器不同于 Imagen 和 Stable Diffusion 3 使用的 T5Kolors 构建在通用语言模型 GLM 之上增强了中英双语的语义理解能力同时使用多模态大语言模型对大规模训练数据重新标注recaption实现细粒度文本理解显著提升了多实体等复杂语义的理解与文字渲染能力。两阶段训练策略先进行面向广泛知识的概念学习阶段再用精心筛选的高美学质量数据进行质量提升阶段并研究了噪声调度noise schedule在高分辨率生成中的关键作用。类别均衡的 KolorsPrompts 基准用于指导训练与评估在人类评估中即便是常用的 U-Net 主干Kolors 也展现出优异的视觉吸引力表现。在 Diffusers 仓库中Kolors 的实现集中在 src/diffusers/pipelines/kolors 目录由 pipeline_kolors.py文生图与 pipeline_kolors_img2img.py图生图两个 Pipeline 构成并配套实现了 ChatGLM 文本编码器与分词器text_encoder.py、tokenizer.py。快速开始文本生成图像Text-to-Image安装与加载首先确保环境中已安装 Diffusers当前仓库源码位于 src/diffusers并从 Hugging Face 加载官方Kwai-Kolors/Kolors-diffusers权重import torch from diffusers import DPMSolverMultistepScheduler, KolorsPipeline pipe KolorsPipeline.from_pretrained(Kwai-Kolors/Kolors-diffusers, dtypetorch.float16, variantfp16) pipe.to(cuda) # 或 mps、xpu、cpu加载后官方示例推荐将调度器切换为带 Karras sigma 曲线的DPMSolverMultistepScheduler在较少步数下获得更好的采样质量pipe.scheduler DPMSolverMultistepScheduler.from_config(pipe.scheduler.config, use_karras_sigmasTrue)生成图像image pipe( prompt一张瓢虫的照片微距变焦高质量电影拿着一个牌子写着可图, negative_prompt, guidance_scale6.5, num_inference_steps25, ).images[0] image.save(kolors_sample.png)注意上例同时展示了 Kolors 的两项核心能力中文提示词理解以及中文文字渲染——提示词中可图二字会被准确绘制在瓢虫举着的牌子上。核心调用参数详解基于源码KolorsPipeline.__call__的完整签名定义在 pipeline_kolors.py 中关键参数及其默认值如下参数默认值说明promptNone提示词str或list[str]若不传则必须传prompt_embedsheight/width1024输出图像尺寸默认取unet.config.sample_size * vae_scale_factor低于 512 像素时效果不佳num_inference_steps50去噪步数步数越多质量越高但推理越慢guidance_scale5.0无分类器引导CFG强度1 时启用引导越大图像越贴合提示词但可能损失质量negative_promptNone负面提示词str或list[str]与negative_prompt_embeds二选一num_images_per_prompt1每个提示词生成的图像数量eta0.0DDIM 的随机性参数 η仅对DDIMScheduler生效generatorNonetorch.Generator用于可复现生成latentsNone预生成的初始噪声 latent可复用同一噪声配合不同提示词prompt_embeds/pooled_prompt_embedsNone预生成的文本嵌入便于做 prompt weighting 等微调ip_adapter_image/ip_adapter_image_embedsNoneIP-Adapter 的参考图像或预计算图像嵌入output_typepil输出格式可选pil、np或latentreturn_dictTrue是否返回KolorsPipelineOutput否则返回普通元组max_sequence_length256提示词最大序列长度源码check_inputs限制其不能大于 256与 SDXL 相似的微条件参数源码为 Kolors 引入了与 SDXL 同源的微条件micro-conditioning机制相关参数包括original_size、crops_coords_top_left、target_size及其对应的 negative 版本negative_original_size等。它们的默认逻辑是original_size与target_size缺省时均取(height, width)crops_coords_top_left取(0, 0)。这些时间步附加条件通过 pipeline_kolors.py 中的_get_add_time_ids方法编码并连同池化文本嵌入一起经added_cond_kwargs传入 U-Net。可复现性与自定义时间步传入generator可固定随机种子latents也可直接传入以复用同一起始噪声。timesteps与sigmas允许自定义去噪调度两者互斥源码中retrieve_timesteps会校验需要调度器在set_timesteps中支持对应参数。callback_on_step_end支持在每个去噪步结束后注入回调可访问的中间张量由callback_on_step_end_tensor_inputs指定默认[latents]全部可选张量定义在类的_callback_tensor_inputs属性中含latents、prompt_embeds、add_text_embeds、add_time_ids等。源码级原理Pipeline 内部是如何工作的模型组件构成KolorsPipeline继承自DiffusionPipeline、StableDiffusionMixin、StableDiffusionLoraLoaderMixin与IPAdapterMixin共注册六个模块vaeAutoencoderKL负责图像与 latent 空间之间的编解码text_encoderChatGLMModel即 ChatGLM3-6BKolors 的双语文本理解核心tokenizerChatGLMTokenizerunetUNet2DConditionModel条件去噪网络scheduler去噪调度器如 DDIM、DPMSolverMultistep 等image_encoder/feature_extractor可选组件用于 IP-Adapter 的图像编码CLIP。此外KolorsPipeline还支持通过StableDiffusionLoraLoaderMixin加载/保存 LoRA 权重load_lora_weights/save_lora_weights通过IPAdapterMixin的load_ip_adapter加载 IP-Adapter通过model_cpu_offload_seq text_encoder-image_encoder-unet-vae实现模型的顺序 CPU 卸载。文本编码从 ChatGLM 到 U-Net 条件encode_prompt方法负责将提示词转为嵌入。核心逻辑是使用ChatGLMTokenizer以max_lengthmax_sequence_length默认 256填充并截断提示词送入 ChatGLM 后取output_hidden_statesTrue其中序列嵌入取自倒数第二层隐藏状态hidden_states[-2]转置为[batch, seq_len, hidden]池化嵌入取自最后一层hidden_states[-1]的最后一行即[batch, hidden]作为add_text_embeds附加条件。针对无分类器引导CFG源码支持两种负向条件策略若negative_prompt为None且配置force_zeros_for_empty_promptTrue则负向嵌入直接置零torch.zeros_like否则按negative_prompt或空串[]重新编码出负向嵌入。当guidance_scale 1时源码属性do_classifier_free_guidance的定义条件正向与负向嵌入会在dim0上拼接后一起送入 U-Net。去噪循环与图像解码在__call__主流程中按序执行输入校验check_inputs其中要求height/width能被 8 整除→ 文本编码 → 时间步准备retrieve_timesteps→ latent 初始化prepare_latents按scheduler.init_noise_sigma缩放初始噪声→ 附加时间条件编码 → 逐时间步去噪每个时间步将 latent 复制为两份用于 CFG经scheduler.scale_model_input缩放后预测噪声残差再做noise_pred_uncond guidance_scale * (noise_pred_text - noise_pred_uncond)的 CFG 组合最后scheduler.step推进→ VAE 解码。在解码阶段有一个值得注意的细节当 VAE 为 float16 且配置要求force_upcast时源码会把 VAE 提升到 float32 再解码避免 float16 溢出随后再切回 float16。输出通过VaeImageProcessor.postprocess得到 PIL 图像封装在KolorsPipelineOutput定义于 pipeline_output.py中其中images为list[PIL.Image.Image]或np.ndarray。图生图KolorsImg2ImgPipelineKolorsImg2ImgPipeline在文生图基础上增加了输入图像官方示例import torch from diffusers import KolorsImg2ImgPipeline from diffusers.utils import load_image pipe KolorsImg2ImgPipeline.from_pretrained( Kwai-Kolors/Kolors-diffusers, variantfp16, torch_dtypetorch.float16 ) pipe pipe.to(cuda) init_image load_image(https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/kolors/bunny_source.png) prompt high quality image of a capybara wearing sunglasses. In the background of the image there are trees, poles, grass and other objects. At the bottom of the object there is the road., 8k, highly detailed. image pipe(prompt, imageinit_image).images[0]图生图的关键参数是strength默认 0.3其取值范围被源码限制在[0.0, 1.0]。它的工作原理见get_timesteps方法init_timestep min(int(num_inference_steps * strength), num_inference_steps)即用strength决定实际执行的去噪步数——strength越大保留的原始图像结构越少、改动幅度越大。此外也可直接用denoising_start指定从哪个时间步开始此时strength失效。该 Pipeline 同样支持 LoRA继承StableDiffusionXLLoraLoaderMixin与 IP-Adapter继承IPAdapterMixin。使用 IP-Adapter 做风格迁移Kolors 使用的 IP-Adapter 与 Stable Diffusion 版本不同它采用OpenAI-CLIP-336clip-vit-large-patch14-336作为图像编码器。使用前需注意两点官方文档明确提示显存要求较高Kolors 配合 IP-Adapter 需要超过 24GB 显存消费级 GPU 上建议配合enable_model_cpu_offload使用需要指定 revision在 Diffusers 中集成时需从特定 revision 加载 safetensor 格式的图像编码器若接受 pickle 权重也可使用原仓库主分支。完整示例import torch from transformers import CLIPVisionModelWithProjection from diffusers import DPMSolverMultistepScheduler, KolorsPipeline from diffusers.utils import load_image image_encoder CLIPVisionModelWithProjection.from_pretrained( Kwai-Kolors/Kolors-IP-Adapter-Plus, subfolderimage_encoder, low_cpu_mem_usageTrue, dtypetorch.float16, revisionrefs/pr/4, ) pipe KolorsPipeline.from_pretrained( Kwai-Kolors/Kolors-diffusers, image_encoderimage_encoder, dtypetorch.float16, variantfp16 ) pipe.scheduler DPMSolverMultistepScheduler.from_config(pipe.scheduler.config, use_karras_sigmasTrue) pipe.load_ip_adapter( Kwai-Kolors/Kolors-IP-Adapter-Plus, subfolder, weight_nameip_adapter_plus_general.safetensors, revisionrefs/pr/4, image_encoder_folderNone, ) pipe.enable_model_cpu_offload() ipa_image load_image(https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/kolors/cat_square.png) image pipe( promptbest quality, high quality, negative_prompt, guidance_scale6.5, num_inference_steps25, ip_adapter_imageipa_image, ).images[0] image.save(kolors_ipa_sample.png)在源码层面IP-Adapter 的图像嵌入由encode_image与prepare_ip_adapter_image_embeds处理参考图像经feature_extractorCLIPImageProcessor预处理后送入 CLIP 视觉编码器若对应的图像投影层不是ImageProjection类型则取倒数第二层隐藏状态hidden_states[-2]否则取image_embeds负向图像嵌入默认用零张量。最终嵌入作为added_cond_kwargs[image_embeds]在去噪循环中传入 U-Net。内存优化与多设备运行设备迁移pipe.to(cuda)之外源码支持mpsApple Silicon、xpuIntel与cpu并针对 MPS 在 VAE 解码与 latent 精度上有专门的兼容处理。CPU 卸载enable_model_cpu_offload()按model_cpu_offload_seq text_encoder-image_encoder-unet-vae的顺序逐模块在 GPU/CPU 间搬运显著降低显存占用是消费级 GPU 上运行 IP-Adapter 的推荐方案。低精度推理官方权重提供variantfp16的 float16 版本配合dtypetorch.float16加载可减少显存占用并加速推理。从测试与社区脚本看更多玩法仓库中的测试用例 tests/pipelines/kolors/test_kolors.py 与 test_kolors_img2img.py 使用小型 dummy 组件UNet2DConditionModel、EulerDiscreteScheduler等验证两个 Pipeline 的完整调用链并覆盖了批次参数、回调张量add_text_embeds、add_time_ids与输出形状可作为理解 API 约定与自行扩展的参考。社区还基于 Kolors 提供了多种扩展脚本全部位于 examples/communitypipeline_kolors_inpainting.pyKolors 图像修复pipeline_kolors_differential_img2img.py差分图生图pipeline_controlnet_xl_kolors.py 及其 img2img / inpaint 版本Kolors 与 ControlNet 结合实现精确结构控制。此外pipeline_pag_kolors.py 展示了将 Perturbed-Attention GuidancePAG与 Kolors 结合的官方实现。注意事项分辨率下限官方权重默认在 1024×1024 附近表现最佳源码文档明确提示低于 512 像素的效果不佳除非使用针对低分辨率微调过的权重。max_sequence_length上限源码在check_inputs中强制max_sequence_length不能大于 256。中文支持Kolors 的 ChatGLM 文本编码器使其在中英文提示词、中英文文字渲染上具备原生优势这也是与其他英文为主的开源模型最显著的区别。通过本文你已了解 Kolors 在 Diffusers 中的完整接入方式从模型背景、文生图与图生图的直接调用到 IP-Adapter 风格迁移、显存优化策略再到文本编码与去噪循环的底层实现。结合仓库中的 pipeline_kolors.py 源码与 tests/pipelines/kolors 测试你可以进一步深入自定义采样流程或将 Kolors 集成到自己的中文图像生成应用中。【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考