Pipeline 实战指南)
在 Diffusers 中使用 NVIDIA Cosmos 生成世界模型视频Cosmos2.5 与任意到世界Any-to-WorldPipeline 实战指南【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusersNVIDIA Cosmos 是一套面向 Physical AI 的世界基础模型World Foundation Model平台本指南以 diffusers 官方 API 文档 为骨架系统讲解如何在 Diffusers 中加载并运行 Cosmos 系列 Pipeline实现从文本、单张图片或输入视频片段生成世界模型视频World Video并深入解析Cosmos2_5_PredictBasePipeline、Cosmos2_5_TransferPipeline、CosmosTextToWorldPipeline、CosmosVideoToWorldPipeline、Cosmos2TextToImagePipeline、Cosmos2VideoToWorldPipeline等 Pipeline 的源码实现与关键参数。读完本文你将能够独立完成文生世界Text2World图生世界Image2World视频生世界Video2World三类任务的推理掌握 ControlNet 条件下的结构可控生成并理解其底层文本编码、条件掩码与 VAE 时序压缩机制。Cosmos 平台与 Diffusers 集成概览Cosmos论文标题为Cosmos World Foundation Model Platform for Physical AIarXiv 编号 2501.03575由 NVIDIA 提出核心理念是物理 AI 需要先在数字世界中训练平台提供视频整理curation流程、预训练世界基础模型、后训练示例以及视频分词器video tokenizer帮助开发者构建定制化世界模型。在 Diffusers 中Cosmos 系列模型以一组完整的 Diffusion Pipeline 形式落地全部位于 src/diffusers/pipelines/cosmos 目录下并在 src/diffusers/init.py 中统一导出Pipeline 类源码文件定位Cosmos2_5_PredictBasePipelinepipeline_cosmos2_5_predict.pyCosmos Predict2.5 基础模型支持 Text2World / Image2World / Video2World 三种模式Cosmos2_5_TransferPipelinepipeline_cosmos2_5_transfer.pyCosmos Transfer2.5支持 edge / depth / seg / blur 等 ControlNet 结构条件CosmosTextToWorldPipelinepipeline_cosmos_text2world.pyCosmos 1.0 文生世界模型CosmosVideoToWorldPipelinepipeline_cosmos_video2world.pyCosmos 1.0 视频生世界模型Cosmos2TextToImagePipelinepipeline_cosmos2_text2image.pyCosmos Predict2 文生图模型Cosmos2VideoToWorldPipelinepipeline_cosmos2_video2world.pyCosmos Predict2 视频生世界模型此外仓库还包含Cosmos3OmniPipeline等较新变体以及配套的CosmosTransformer3DModel、AutoencoderKLWan、AutoencoderKLCosmos、CosmosControlNetModel等模型组件与CosmosLoraLoaderMixin加载器相关注册同样可在 src/diffusers/init.py 中查到。运行环境与依赖Cosmos Pipeline 依赖 PyTorch 与 Transformers 生态使用前请确认环境满足主框架本仓库 diffusers 本体从源码安装或通过 pip 安装最新版本Transformers用于加载Qwen2_5_VLForConditionalGenerationPredict2.5 文本编码器或T5EncoderModel/T5TokenizerFastCosmos 1.0 / Predict2 文本编码器见 pipeline_cosmos2_5_predict.py 的导入语句torchvision视频帧预处理依赖源码通过is_torchvision_available()条件导入cosmos_guardrail可选但推荐安全审查组件。若未安装Pipeline 实例化时会抛出提示安装的 ImportError需执行pip install cosmos_guardrail参见 pipeline_cosmos2_5_predict.py设备支持示例代码注释标明可在cuda、mps、xpu、cpu上运行源码还检测torch_xla环境以支持 TPU 推理见文件开头的is_torch_xla_available()分支。需要注意的是世界模型推理显存开销较大实际部署请结合自身 GPU 显存选择 2B 或 14B 规模检查点。基础用法Cosmos2.5 文生世界Text2World官方文档给出的最小可用示例是使用Cosmos2_5_PredictBasePipeline加载 NVIDIA 的 Predict2.5 基础模型并做文生世界推理。以下为完整继承自 cosmos.md 的原始示例import torch from diffusers import Cosmos2_5_PredictBasePipeline from diffusers.utils import export_to_video model_id nvidia/Cosmos-Predict2.5-2B pipe Cosmos2_5_PredictBasePipeline.from_pretrained( model_id, revisiondiffusers/base/post-trained, dtypetorch.bfloat16 ) pipe.to(cuda) # or mps, xpu, cpu prompt As the red light shifts to green, the red bus at the intersection begins to move forward, its headlights cutting through the falling snow. The snowy tire tracks deepen as the vehicle inches ahead, casting fresh lines onto the slushy road. Around it, streetlights glow warmer, illuminating the drifting flakes and wet reflections on the asphalt. Other cars behind start to edge forward, their beams joining the scene. The stillness of the urban street transitions into motion as the quiet snowfall is punctuated by the slow advance of traffic through the frosty city corridor. negative_prompt The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality. output pipe( imageNone, videoNone, promptprompt, negative_promptnegative_prompt, num_frames93, generatortorch.Generator().manual_seed(1), ).frames[0] export_to_video(output, text2world.mp4, fps16)代码要点说明revisiondiffusers/base/post-trained指定从 Hugging Face Hub 拉取经过后训练post-trained的 diffusers 格式权重分支源码 docstring 中也有等价写法torch_dtypetorch.bfloat16建议以torch_dtype关键字传递 dtype 以保证跨版本兼容imageNone, videoNone明确声明纯文本条件模式即 Text2Worldnum_frames93表示输出 93 帧世界视频文档与源码默认值均为 93generator固定随机种子保证结果可复现export_to_video(output, ..., fps16)来自diffusers.utils将帧序列编码为视频文件。三种生成模式与__call__关键参数Cosmos2_5_PredictBasePipeline.__call__的完整签名定义在 pipeline_cosmos2_5_predict.py它通过image与video参数的组合支持三种模式模式条件组合说明Text2WorldimageNone, videoNone提供prompt纯文本生成世界视频Image2World提供imagevideoNone以单帧图片为条件生成后续世界视频Video2World提供videoimageNone以输入视频片段为条件预测后续帧若将num_frames设为1三种模式退化为对应的*2Image单帧图像生成此时输出为单张图源码注释中的*2Image mode。下表整理了__call__的核心参数及其默认值来源同上源码 docstring供实战参考参数默认值作用height/width704/1280输出视频的空间分辨率像素num_frames93输出帧数93生成世界视频1返回单帧num_inference_steps36去噪步数越多质量越高但推理越慢guidance_scale7.0无分类器引导强度CFG大于 1 时启用num_videos_per_prompt1每个 prompt 生成的视频数量generatorNone随机数生成器可传入列表实现按 batch 复现latentsNone预先生成的噪声潜变量可用于复用同一生成prompt_embeds/negative_prompt_embedsNone预计算文本嵌入便于 prompt 加权等高级操作output_typepil输出格式pil返回 PIL 帧列表return_dictTrue为True返回CosmosPipelineOutput否则返回元组max_sequence_length512prompt 最大 token 数超长截断、不足填充num_latent_conditional_frames2Video2World 条件帧数量潜变量维度像素帧数按4 * (n-1) 1换算conditional_frame_timestep0.0001条件帧在去噪过程中使用的 timestep 值callback_on_step_endNone每步去噪结束回调支持PipelineCallback/MultiPipelineCallbacksImage2World 实战在源码 pipeline_cosmos2_5_predict.py 的 docstring 中给出了 Image2World 示例使用diffusers.utils.load_image加载一张机器人焊接场景的静态图片作为条件配以一段描述焊接过程的 prompt同样生成 93 帧世界视频from diffusers.utils import load_image prompt ( A high-definition video captures the precision of robotic welding in an industrial setting. The first frame showcases a robotic arm, equipped with a welding torch, positioned over a large metal structure. ... ) image load_image(.../robot_welding.jpg) # 示例素材由 NVIDIA Cosmos 官方仓库提供 video pipe( imageimage, videoNone, promptprompt, negative_promptnegative_prompt, num_frames93, generatortorch.Generator().manual_seed(1), ).frames[0] export_to_video(video, image2world.mp4, fps16)Video2World 实战Video2World 则将一段输入视频作为条件。源码 pipeline_cosmos2_5_predict.py 的示例使用load_video读取一段沙矿施工航拍视频预测其后续 93 帧from diffusers.utils import load_video prompt ( The video opens with an aerial view of a large-scale sand mining construction operation, ... ) input_video load_video(.../sand_mining.mp4) # 示例素材由 NVIDIA Cosmos 官方仓库提供 video pipe( imageNone, videoinput_video, promptprompt, negative_promptnegative_prompt, num_frames93, generatortorch.Generator().manual_seed(1), ).frames[0] export_to_video(video, video2world.mp4, fps16)源码原理Predict2.5 的内部结构组件装配与卸载策略从 pipeline_cosmos2_5_predict.py 的类定义可以看出Cosmos2_5_PredictBasePipeline由五个核心组件构成text_encoderQwen2_5_VLForConditionalGenerationQwen2.5-VL-7B-Instruct冻结使用tokenizer与 Qwen2.5 VL 编码器配套的AutoTokenizertransformerCosmosTransformer3DModel负责对视频潜变量去噪vaeAutoencoderKLWan在视频像素与潜变量之间编解码schedulerUniPCMultistepScheduler规划去噪时间步safety_checkerCosmosSafetyChecker来自cosmos_guardrail标注为可选组件但仍强烈建议启用。类属性model_cpu_offload_seq text_encoder-transformer-vae定义了顺序 CPU 卸载序列_exclude_from_cpu_offload [safety_checker]则让安全检查器始终驻留显存_callback_tensor_inputs [latents, prompt_embeds, negative_prompt_embeds]限定了每步回调可获取的张量。VAE 时序压缩与潜变量形状构造方法中通过 VAE 配置计算两类压缩比pipeline_cosmos2_5_predict.py时间维压缩比vae_scale_factor_temporal 2 ** sum(vae.temperal_downsample)空间维压缩比vae_scale_factor_spatial 2 ** len(vae.temperal_downsample)。prepare_latents依据这两个比例推导潜变量形状(B, C16, T, H, W)其中T (num_frames_out - 1) // temporal_scale 1、H height // spatial_scale、W width // spatial_scale。同时从 VAE 配置读取latents_mean与latents_std对噪声做归一化这是保持与官方权重数值分布一致的关键。条件掩码机制create_condition_maskpipeline_cosmos2_5_predict.py为 Video2World 生成条件指示掩码潜变量时间维的前num_cond_latent_frames帧被标记为 1条件帧保持输入内容其余帧为 0待生成帧。num_latent_conditional_frames默认2按4 * (2-1) 1 5换算为 5 个像素级条件帧设为1时退化为单帧条件行为接近 Image2World。Prompt 编码多层隐藏状态拼接_get_prompt_embedspipeline_cosmos2_5_predict.py的编码流程较具特色按 Qwen2.5-VL 的对话模板system user 角色构造对话并 tokenizemax_sequence_length512截断、paddingmax_length填充前向得到所有层的hidden_states从第 1 层起对每一层隐藏状态做均值/标准差归一化再沿特征维拼接得到最终prompt_embeds。这种归一化后逐层拼接的做法使文本条件蕴含更丰富的语义层级信息也是该模型文本理解能力强的原因之一。CFG 分支encode_prompt会复用同一编码器处理负向 prompt未显式传入负向 prompt 时自动使用源码中定义的DEFAULT_NEGATIVE_PROMPT即示例中那一段关于画面质量缺陷的通用描述定义于文件顶部 pipeline_cosmos2_5_predict.py。结构可控生成Cosmos2_5_TransferPipelineCosmos2_5_TransferPipeline在 Predict2.5 基础上引入CosmosControlNetModel支持用边缘edge、深度depth、分割seg、模糊blur等结构控制信号约束世界生成。其完整示例位于 pipeline_cosmos2_5_transfer.py核心步骤如下用AutoModel.from_pretrained按分支加载 ControlNet 变体例如revisiondiffusers/controlnet/general/edge对应边缘控制将 ControlNet 作为controlnet参数注入主 Pipeline主模型分支为revisiondiffusers/general用 OpenCV 的 Canny 算法从输入视频帧提取边缘图堆叠为控制序列推理时传入controls与controls_conditioning_scale1.0控制引导强度。import cv2 import numpy as np from PIL import Image import torch from diffusers import Cosmos2_5_TransferPipeline, AutoModel from diffusers.utils import export_to_video, load_video model_id nvidia/Cosmos-Transfer2.5-2B # 加载 edge边缘变体的 ControlNet controlnet AutoModel.from_pretrained( model_id, revisiondiffusers/controlnet/general/edge, torch_dtypetorch.bfloat16 ) pipe Cosmos2_5_TransferPipeline.from_pretrained( model_id, controlnetcontrolnet, revisiondiffusers/general, torch_dtypetorch.bfloat16 ) pipe pipe.to(cuda) input_video load_video(.../robot_input.mp4) # 示例素材由 NVIDIA Cosmos 官方仓库提供 num_frames 93 # 使用 Canny 算子从输入视频提取边缘图作为控制信号 edge_maps [ cv2.Canny(cv2.cvtColor(np.array(frame.convert(RGB)), cv2.COLOR_RGB2BGR), 100, 200) for frame in input_video[:num_frames] ] edge_maps np.stack(edge_maps)[None] # (T, H, W) - (1, T, H, W) controls torch.from_numpy(edge_maps).expand(3, -1, -1, -1) # (1, T, H, W) - (3, T, H, W) controls [Image.fromarray(x.numpy()) for x in controls.permute(1, 2, 3, 0)] export_to_video(controls, edge_controlled_video_edge.mp4, fps30) video pipe( controlscontrols, controls_conditioning_scale1.0, promptprompt, negative_promptnegative_prompt, num_framesnum_frames, ).frames[0] export_to_video(video, edge_controlled_video.mp4, fps30)这种结构控制对 Physical AI 场景尤其重要在机器人操控、自动驾驶仿真等任务中开发者往往需要先锁定几何/语义结构再让世界模型填充纹理、光照与动态controls_conditioning_scale即可调节结构约束与生成自由度之间的平衡。Cosmos 1.0 与 Predict2 系列 PipelineCosmosTextToWorldPipeline1.0 文生世界针对nvidia/Cosmos-1.0-Diffusion-7B-Text2World检查点pipeline_cosmos_text2world.py 采用与 Predict2.5 不同的组件组合T5EncoderModelT5TokenizerFast作为文本编码器、AutoencoderKLCosmos作为 VAE、EDMEulerScheduler作为采样器且其DEFAULT_NEGATIVE_PROMPT与 Predict2.5 完全一致。使用方式import torch from diffusers import CosmosTextToWorldPipeline from diffusers.utils import export_to_video model_id nvidia/Cosmos-1.0-Diffusion-7B-Text2World pipe CosmosTextToWorldPipeline.from_pretrained(model_id, torch_dtypetorch.bfloat16) pipe.to(cuda) prompt A sleek, humanoid robot stands in a vast warehouse filled with neatly stacked cardboard boxes on industrial shelves. ... output pipe(promptprompt).frames[0] export_to_video(output, output.mp4, fps30)该 Pipeline 的__call__同样复用retrieve_timesteps工具从 stable diffusion 复制而来支持传入自定义timesteps或sigmas覆盖调度器的默认时间步策略但二者不可同时传入参见 pipeline_cosmos_text2world.py。CosmosVideoToWorldPipeline与 1.0 文生世界配套的视频条件变体pipeline_cosmos_video2world.py将输入视频片段编码为潜变量作为条件预测后续世界帧。Cosmos2TextToImagePipelinePredict2 文生图面向nvidia/Cosmos-Predict2-2B-Text2Image与nvidia/Cosmos-Predict2-14B-Text2Image检查点pipeline_cosmos2_text2image.py 的组合为T5EncoderModelT5TokenizerFastAutoencoderKLWanFlowMatchEulerDiscreteScheduler返回的是单张图像而非视频输出类型为CosmosImagePipelineOutputimport torch from diffusers import Cosmos2TextToImagePipeline model_id nvidia/Cosmos-Predict2-2B-Text2Image pipe Cosmos2TextToImagePipeline.from_pretrained(model_id, torch_dtypetorch.bfloat16) pipe.to(cuda) prompt A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, ... negative_prompt The video captures a series of frames showing ugly scenes, static with no motion, ... output pipe( promptprompt, negative_promptnegative_prompt, generatortorch.Generator().manual_seed(1) ).images[0] output.save(output.png)Cosmos2VideoToWorldPipelinePredict2 时代的视频生世界管线pipeline_cosmos2_video2world.pyCosmos2_5_PredictBasePipeline.prepare_latents的实现即标注为从该 Pipeline 与Cosmos2TextToImagePipeline改造而来可见两代模型在潜变量准备逻辑上的继承关系。输出对象CosmosPipelineOutput 与 CosmosImagePipelineOutput两类输出 dataclass 定义在 pipeline_output.pyCosmosPipelineOutput视频/世界类 Pipeline 的输出唯一字段frames可以是torch.Tensor、np.ndarray或长度为batch_size的嵌套 PIL 帧序列每个子列表长度为num_frames若为张量/数组则形状为(batch_size, num_frames, channels, height, width)CosmosImagePipelineOutput图像类 Pipeline如Cosmos2TextToImagePipeline的输出字段images为长度为batch_size的 PIL 图像列表或形状(batch_size, height, width, num_channels)的 NumPy 数组。两者均继承diffusers.utils.BaseOutput因此支持属性访问与 dict 式解包例如示例中的pipe(...).frames[0]与pipe(...).images[0]。从推理走向训练与生态工具仓库为 Cosmos 提供了从推理到训练、转换的完整配套可作为后续深入实践的入口LoRA 训练examples/cosmos/train_cosmos_predict25_lora.py 提供 Predict2.5 的 LoRA 微调脚本配套数据集下载与预处理脚本 examples/cosmos/download_and_preprocess_datasets.sh 以及评估脚本 examples/cosmos/eval_cosmos_predict25_lora.py内含基于 LLM 的评测 prompt见 examples/cosmos/llm_judge_prompts训练说明详见 examples/cosmos/README.mdCosmos3 推理examples/cosmos3/inference_cosmos3.py 演示最新一代Cosmos3OmniPipeline的用法权重转换scripts/convert_cosmos_to_diffusers.py 用于将 NVIDIA 原始权重转换为 diffusers 格式测试覆盖tests/pipelines/cosmos 下包含各 Pipeline 的单元测试可作为参数用法的权威参考。使用建议与注意事项安全检查器不可随意关闭源码中明确禁止在未显式处理的情况下禁用safety_checker否则抛出 ValueError生产环境请安装cosmos_guardrail并保留默认安全审查负向提示词可直接复用默认值各 Pipeline 的DEFAULT_NEGATIVE_PROMPT已针对画面伪影、抖动、过曝等常见退化精心设计不传negative_prompt时即自动启用帧数换算关系Video2World 的条件帧数遵循4 * (num_latent_conditional_frames - 1) 1的换算调整该参数即可在单帧条件与多帧条件间切换资源管理2B 模型适合单卡快速验证14B 或 7B 模型建议开启enable_model_cpu_offload或使用顺序卸载序列控制显存峰值可复现性固定torch.Generator().manual_seed(...)并使用同一latents可稳定复现结果适合做消融对比。Cosmos 系列 Pipeline 把世界模型从研究概念落到了 diffusers 的标准接口上无论你是在构建自动驾驶仿真数据、机器人操作预测还是探索物理世界视频生成都可以用本指南中的模式快速上手若需进一步探究调度器质量与速度的权衡可参考官方 Schedulers 指南并在多 Pipeline 场景中利用 跨 Pipeline 复用组件 节省显存与加载时间。【免费下载链接】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),仅供参考