Diffusers documentation
Cosmos
Cosmos
Nền tảng Mô hình Nền tảng Thế giới Cosmos cho AI Vật lý của NVIDIA.
Physical AI cần được huấn luyện kỹ thuật số trước. Nó cần một bản sao kỹ thuật số của chính nó, mô hình chính sách, và một bản sao kỹ thuật số của thế giới, mô hình thế giới. Trong bài báo này, chúng tôi giới thiệu Nền tảng Mô hình Nền tảng Thế giới Cosmos để hỗ trợ các nhà phát triển xây dựng các mô hình thế giới tùy chỉnh cho các hệ thống Physical AI của họ. Chúng tôi định vị một mô hình nền tảng thế giới như một mô hình thế giới đa năng, có thể được tinh chỉnh thành các mô hình thế giới tùy chỉnh cho các ứng dụng hạ nguồn. Nền tảng của chúng tôi bao gồm một quy trình tuyển chọn video, các mô hình nền tảng thế giới đã được huấn luyện trước, các ví dụ về huấn luyện sau của các mô hình nền tảng thế giới đã được huấn luyện trước, và các bộ mã hóa video. Để hỗ trợ các nhà xây dựng Physical AI giải quyết những vấn đề quan trọng nhất của xã hội, chúng tôi mã nguồn mở nền tảng của mình và cung cấp các mô hình với trọng số mở theo giấy phép cho phép, có sẵn tại https://github.com/NVIDIA/Cosmos.
Hãy chắc chắn xem qua hướng dẫn về Schedulers để tìm hiểu cách khám phá sự đánh đổi giữa tốc độ và chất lượng của scheduler, và xem phần tái sử dụng các thành phần giữa các pipeline để tìm hiểu cách nạp các thành phần giống nhau vào nhiều pipeline một cách hiệu quả.
Cách sử dụng cơ bản
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, revision="diffusers/base/post-trained", dtype=torch.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(
image=None,
video=None,
prompt=prompt,
negative_prompt=negative_prompt,
num_frames=93,
generator=torch.Generator().manual_seed(1),
).frames[0]
export_to_video(output, "text2world.mp4", fps=16)Cosmos2_5_TransferPipeline
lớp diffusers.Cosmos2_5_TransferPipeline
< source >( text_encoder: Qwen2_5_VLForConditionalGenerationtokenizer: AutoTokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: UniPCMultistepSchedulercontrolnet: CosmosControlNetModelsafety_checker: typing.Optional[diffusers.pipelines.cosmos.pipeline_cosmos2_5_transfer.CosmosSafetyChecker] = None )
Tham số
- text_encoder (
Qwen2_5_VLForConditionalGeneration) — Bộ mã hóa văn bản đóng băng. Cosmos Transfer2.5 sử dụng bộ mã hóa Qwen2.5 VL. - tokenizer (
AutoTokenizer) — Tokenizer liên quan đến bộ mã hóa Qwen2.5 VL. - transformer (CosmosTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (UniPCMultistepScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
- controlnet (
CosmosControlNetModel) — ControlNet được sử dụng để điều kiện hóa quá trình tạo dựa trên các đầu vào điều khiển.
Pipeline cho Cosmos Transfer2.5, hỗ trợ suy luận tự hồi quy.
Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( controls: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]]controls_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0prompt: typing.Union[str, typing.List[str], NoneType] = Nonenegative_prompt: typing.Union[str, typing.List[str]] = '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.'height: int = 704width: typing.Optional[int] = Nonenum_frames: typing.Optional[int] = Nonenum_frames_per_chunk: int = 93num_inference_steps: int = 36guidance_scale: float = 3.0num_videos_per_prompt: int = 1generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: typing.Optional[str] = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']max_sequence_length: int = 512conditional_frame_timestep: float = 0.1num_ar_conditional_frames: typing.Optional[int] = 1num_ar_latent_conditional_frames: typing.Optional[int] = None ) → ~CosmosPipelineOutput or tuple
Tham số
- controls (
PipelineImageInput,List[PipelineImageInput]) — Ảnh hoặc video đầu vào điều khiển được sử dụng bởi ControlNet. - controls_conditioning_scale (
floathoặcList[float], tùy chọn, mặc định là1.0) — Hệ số tỷ lệ cho các đầu ra của ControlNet. Một giá trị float đơn lẻ sẽ được phát sóng (broadcast) đến tất cả các khối điều khiển. - prompt (
strhoặcList[str], tùy chọn) — Prompt hoặc các prompt để định hướng quá trình tạo. Bắt buộc trừ khiprompt_embedsđược cung cấp. - negative_prompt (
strhoặcList[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalekhông lớn hơn1). - height (
int, mặc định là704) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, tùy chọn) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. Nếu không được cung cấp, giá trị này sẽ được xác định dựa trên tỷ lệ khung hình của đầu vào và chiều cao được cung cấp. - num_frames (
int, tùy chọn) — Số lượng khung hình đầu ra. Mặc định làNoneđể xuất ra cùng số lượng khung hình với đầu vàocontrols. - num_frames_per_chunk (
int, tuỳ chọn, mặc định là93) — Số lượng khung hình được tạo ra cho mỗi khối tự hồi quy. Khi tổng số khung hình vượt quá giá trị này, quá trình tạo sẽ được chia thành nhiều khối bằng cách tiếp cận cửa sổ trượt. - num_inference_steps (
int, mặc định là36) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - guidance_scale (
float, mặc định là3.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.GeneratorhoặcList[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào. Có thể dùng để tinh chỉnh cùng một quá trình sinh với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtCosmosPipelineOutputthay vì một tuple thông thường hay không. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, tùy chọn) — Một hàm hoặc một lớp con củaPipelineCallbackhoặcMultiPipelineCallbacksđược gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
List, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
int, mặc định là512) — Số lượng token tối đa trong prompt. Nếu prompt vượt quá độ dài này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn độ dài này, nó sẽ được đệm. - conditional_frame_timestep (
float, tùy chọn, mặc định là 0.1) — Giá trị bước thời gian (timestep) được sử dụng cho các khung hình điều kiện trong quá trình khử nhiễu. Phải nằm trong khoảng[0, 1]. - num_ar_conditional_frames (
int, tuỳ chọn, mặc định là1) — Số lượng khung hình để điều kiện cho các vòng lặp suy luận tiếp theo trong suy luận tự hồi quy, tức là cho chunk thứ hai trở đi. Chỉ được sử dụng nếunum_ar_latent_conditional_frameslàNone.Điều này chỉ được sử dụng khi suy luận tự hồi quy được thực hiện, tức là khi số lượng khung hình trong controls > num_frames_per_chunk
- num_ar_latent_conditional_frames (
int, tuỳ chọn) — Số lượng khung latent để điều kiện cho các vòng lặp suy luận tiếp theo trong suy luận tự hồi quy, tức là cho chunk thứ hai trở đi. Chỉ được sử dụng nếunum_ar_conditional_frameslàNone.Điều này chỉ được sử dụng khi suy luận tự hồi quy được thực hiện, tức là khi số lượng khung hình trong controls > num_frames_per_chunk
Trả về
~CosmosPipelineOutput hoặc tuple
Nếu return_dict là True, CosmosPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó
phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các bool
cho biết hình ảnh được tạo ra tương ứng có chứa nội dung “not-safe-for-work” (nsfw) hay không.
controls điều khiển quá trình điều kiện thông qua ControlNet. Các controls được giả định là đã được tiền xử lý, ví dụ như các bản đồ cạnh đã được tính toán trước.
Việc đặt num_frames sẽ giới hạn tổng số khung hình đầu ra, nếu không được cung cấp hoặc được gán là None (mặc định) thì số khung hình đầu ra sẽ khớp với controls đầu vào.
Suy luận tự hồi quy được hỗ trợ, do đó một cửa sổ trượt gồm num_frames_per_chunk khung hình được sử dụng cho mỗi vòng lặp khử nhiễu. Ngoài ra, khi thực hiện suy luận tự hồi quy, num_ar_latent_conditional_frames hoặc num_ar_conditional_frames khung hình trước đó được dùng để điều kiện cho các vòng lặp suy luận khử nhiễu tiếp theo.
Ví dụ:
>>> 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"
>>> # Load a Transfer2.5 controlnet variant (edge, depth, seg, or blur)
>>> controlnet = AutoModel.from_pretrained(
... model_id, revision="diffusers/controlnet/general/edge", torch_dtype=torch.bfloat16
... )
>>> pipe = Cosmos2_5_TransferPipeline.from_pretrained(
... model_id, controlnet=controlnet, revision="diffusers/general", torch_dtype=torch.bfloat16
... )
>>> pipe = pipe.to("cuda")
>>> # Video2World with edge control: Generate video guided by edge maps extracted from input video.
>>> prompt = (
... "The video is a demonstration of robotic manipulation, likely in a laboratory or testing environment. It"
... "features two robotic arms interacting with a piece of blue fabric. The setting is a room with a beige"
... "couch in the background, providing a neutral backdrop for the robotic activity. The robotic arms are"
... "positioned on either side of the fabric, which is placed on a yellow cushion. The left robotic arm is"
... "white with a black gripper, while the right arm is black with a more complex, articulated gripper. At the"
... "beginning, the fabric is laid out on the cushion. The left robotic arm approaches the fabric, its gripper"
... "opening and closing as it positions itself. The right arm remains stationary initially, poised to assist."
... "As the video progresses, the left arm grips the fabric, lifting it slightly off the cushion. The right arm"
... "then moves in, its gripper adjusting to grasp the opposite side of the fabric. Both arms work in"
... "coordination, lifting and holding the fabric between them. The fabric is manipulated with precision,"
... "showcasing the dexterity and control of the robotic arms. The camera remains static throughout, focusing"
... "on the interaction between the robotic arms and the fabric, allowing viewers to observe the detailed"
... "movements and coordination involved in the task."
... )
>>> 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."
... )
>>> input_video = load_video(
... "https://github.com/nvidia-cosmos/cosmos-transfer2.5/raw/refs/heads/main/assets/robot_example/robot_input.mp4"
... )
>>> num_frames = 93
>>> # Extract edge maps from the input video using Canny edge detection
>>> 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", fps=30)
>>> # Transfer inference with controls.
>>> video = pipe(
... controls=controls,
... controls_conditioning_scale=1.0,
... prompt=prompt,
... negative_prompt=negative_prompt,
... num_frames=num_frames,
... ).frames[0]
>>> export_to_video(video, "edge_controlled_video.mp4", fps=30)encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]]negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặcList[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặcList[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
Cosmos2_5_PredictBasePipeline
lớp diffusers.Cosmos2_5_PredictBasePipeline
< source >( text_encoder: Qwen2_5_VLForConditionalGenerationtokenizer: AutoTokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: UniPCMultistepSchedulersafety_checker: CosmosSafetyChecker = None )
Tham số
- text_encoder (
Qwen2_5_VLForConditionalGeneration) — Bộ mã hóa văn bản đóng băng. Cosmos Predict2.5 sử dụng bộ mã hóa Qwen2.5 VL. - tokenizer (
AutoTokenizer) — Tokenizer liên quan đến bộ mã hóa Qwen2.5 VL. - transformer (CosmosTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (UniPCMultistepScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
Pipeline cho mô hình cơ sở Cosmos Predict2.5.
Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneprompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 93num_inference_steps: int = 36guidance_scale: float = 7.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512conditional_frame_timestep: float = 0.0001num_latent_conditional_frames: int = 2 ) → ~CosmosPipelineOutput or tuple
Tham số
- image (
PIL.Image.Image,np.ndarray,torch.Tensor, tùy chọn) — Ảnh đơn tùy chọn để điều kiện cho Image2World. Phải làNonekhivideođược cung cấp. - video (
list[PIL.Image.Image],np.ndarray,torch.Tensor, tuỳ chọn) — Video đầu vào tuỳ chọn để điều kiện cho Video2World. Phải làNonekhiimageđược cung cấp. - prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng quá trình tạo. Bắt buộc trừ khiprompt_embedsđược cung cấp. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalekhông lớn hơn1). - height (
int, mặc định là704) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là1280) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - num_frames (
int, mặc định là93) — Số lượng khung hình đầu ra. Sử dụng93để tạo thế giới (video); đặt thành1để trả về một khung hình duy nhất. - num_inference_steps (
int, mặc định là35) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - guidance_scale (
float, mặc định là7.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtCosmosPipelineOutputthay vì một tuple thông thường hay không. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, tùy chọn) — Một hàm hoặc một lớp con củaPipelineCallbackhoặcMultiPipelineCallbacksđược gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
List, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
int, mặc định là512) — Số lượng token tối đa trong prompt. Nếu prompt vượt quá độ dài này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn độ dài này, nó sẽ được đệm. - num_latent_conditional_frames (
int, mặc định là2) — Số lượng khung hình điều kiện ẩn (latent conditional frames) được sử dụng cho điều kiện Video2World. Số lượng khung hình pixel được trích xuất từ video đầu vào được tính bằng4 * (num_latent_conditional_frames - 1) + 1. Đặt thành 1 để có hành vi tương tự Image2World (điều kiện bằng một khung hình duy nhất). - conditional_frame_timestep (
float, tùy chọn, mặc định là 0.0001) — Giá trị bước thời gian (timestep) được sử dụng cho các khung hình có điều kiện trong quá trình khử nhiễu (denoising).
Trả về
~CosmosPipelineOutput hoặc tuple
Nếu return_dict là True, CosmosPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó
phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các bool
cho biết hình ảnh được tạo ra tương ứng có chứa nội dung “not-safe-for-work” (nsfw) hay không.
Hàm gọi cho pipeline để tạo nội dung. Hỗ trợ ba chế độ:
- Text2World:
image=None,video=None, cóprompt. Tạo một đoạn clip thế giới. - Image2World: cung cấp
image,video=None, cung cấpprompt. Điều kiện trên một khung hình duy nhất. - Video2World: cung cấp
video,image=None, cung cấpprompt. Điều kiện trên một đoạn clip đầu vào.
Đặt num_frames=93 (mặc định) để tạo video thế giới, hoặc num_frames=1 để tạo một khung hình ảnh đơn (như ở trên trong “*2Image mode”).
Outputs tuân theo output_type (ví dụ, "pil" trả về một danh sách gồm num_frames hình ảnh PIL cho mỗi prompt).
Ví dụ:
>>> import torch
>>> from diffusers import Cosmos2_5_PredictBasePipeline
>>> from diffusers.utils import export_to_video, load_image, load_video
>>> model_id = "nvidia/Cosmos-Predict2.5-2B"
>>> pipe = Cosmos2_5_PredictBasePipeline.from_pretrained(
... model_id, revision="diffusers/base/post-trained", torch_dtype=torch.bfloat16
... )
>>> pipe = pipe.to("cuda")
>>> # Common negative prompt reused across modes.
>>> 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."
... )
>>> # Text2World: generate a 93-frame world video from text only.
>>> 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."
... )
>>> video = pipe(
... image=None,
... video=None,
... prompt=prompt,
... negative_prompt=negative_prompt,
... num_frames=93,
... generator=torch.Generator().manual_seed(1),
... ).frames[0]
>>> export_to_video(video, "text2world.mp4", fps=16)
>>> # Image2World: condition on a single image and generate a 93-frame world video.
>>> 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. "
... "The welding process is in full swing, with bright sparks and intense light illuminating the scene, creating a vivid "
... "display of blue and white hues. A significant amount of smoke billows around the welding area, partially obscuring "
... "the view but emphasizing the heat and activity. The background reveals parts of the workshop environment, including a "
... "ventilation system and various pieces of machinery, indicating a busy and functional industrial workspace. As the video "
... "progresses, the robotic arm maintains its steady position, continuing the welding process and moving to its left. "
... "The welding torch consistently emits sparks and light, and the smoke continues to rise, diffusing slightly as it moves upward. "
... "The metal surface beneath the torch shows ongoing signs of heating and melting. The scene retains its industrial ambiance, with "
... "the welding sparks and smoke dominating the visual field, underscoring the ongoing nature of the welding operation."
... )
>>> image = load_image(
... "https://media.githubusercontent.com/media/nvidia-cosmos/cosmos-predict2.5/refs/heads/main/assets/base/robot_welding.jpg"
... )
>>> video = pipe(
... image=image,
... video=None,
... prompt=prompt,
... negative_prompt=negative_prompt,
... num_frames=93,
... generator=torch.Generator().manual_seed(1),
... ).frames[0]
>>> export_to_video(video, "image2world.mp4", fps=16)
>>> # Video2World: condition on an input clip and predict a 93-frame world video.
>>> prompt = (
... "The video opens with an aerial view of a large-scale sand mining construction operation, showcasing extensive piles "
... "of brown sand meticulously arranged in parallel rows. A central water channel, fed by a water pipe, flows through the "
... "middle of these sand heaps, creating ripples and movement as it cascades down. The surrounding area features dense green "
... "vegetation on the left, contrasting with the sandy terrain, while a body of water is visible in the background on the right. "
... "As the video progresses, a piece of heavy machinery, likely a bulldozer, enters the frame from the right, moving slowly along "
... "the edge of the sand piles. This machinery's presence indicates ongoing construction work in the operation. The final frame "
... "captures the same scene, with the water continuing its flow and the bulldozer still in motion, maintaining the dynamic yet "
... "steady pace of the construction activity."
... )
>>> input_video = load_video(
... "https://github.com/nvidia-cosmos/cosmos-predict2.5/raw/refs/heads/main/assets/base/sand_mining.mp4"
... )
>>> video = pipe(
... image=None,
... video=input_video,
... prompt=prompt,
... negative_prompt=negative_prompt,
... num_frames=93,
... generator=torch.Generator().manual_seed(1),
... ).frames[0]
>>> export_to_video(video, "video2world.mp4", fps=16)
>>> # To produce an image instead of a world (video) clip, set num_frames=1 and
>>> # save the first frame: pipe(..., num_frames=1).frames[0][0].encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
CosmosTextToWorldPipeline
lớp diffusers.CosmosTextToWorldPipeline
< source >( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLCosmosscheduler: EDMEulerSchedulersafety_checker: CosmosSafetyChecker = None )
Tham số
- text_encoder (
T5EncoderModel) — Bộ mã hóa văn bản đóng băng. Cosmos sử dụng T5; cụ thể là biến thể t5-11b. - tokenizer (
T5TokenizerFast) — Tokenizer của lớp T5Tokenizer. - transformer (CosmosTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLCosmos) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn.
Pipeline để tạo thế giới từ văn bản sử dụng Cosmos Predict1.
Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 121num_inference_steps: int = 36guidance_scale: float = 7.0fps: int = 30num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~CosmosPipelineOutput or tuple
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalekhông lớn hơn1). - height (
int, mặc định là720) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là1280) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - num_frames (
int, mặc định là121) — Số lượng khung hình trong video được tạo ra. - num_inference_steps (
int, mặc định là36) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - guidance_scale (
float, mặc định là7.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. - fps (
int, mặc định là30) — Số khung hình mỗi giây của video được tạo ra. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtCosmosPipelineOutputthay vì một tuple thông thường hay không. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, tùy chọn) — Một hàm hoặc một lớp con củaPipelineCallbackhoặcMultiPipelineCallbacksđược gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
int, mặc định là512) — Số lượng token tối đa trong prompt. Nếu prompt vượt quá độ dài này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn độ dài này, nó sẽ được đệm.
Trả về
~CosmosPipelineOutput hoặc tuple
Nếu return_dict là True, CosmosPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó
phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các bool
cho biết hình ảnh được tạo ra tương ứng có chứa nội dung “not-safe-for-work” (nsfw) hay không.
Hàm gọi call của pipeline để tạo nội dung.
Ví dụ:
>>> 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_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A sleek, humanoid robot stands in a vast warehouse filled with neatly stacked cardboard boxes on industrial shelves. The robot's metallic body gleams under the bright, even lighting, highlighting its futuristic design and intricate joints. A glowing blue light emanates from its chest, adding a touch of advanced technology. The background is dominated by rows of boxes, suggesting a highly organized storage system. The floor is lined with wooden pallets, enhancing the industrial setting. The camera remains static, capturing the robot's poised stance amidst the orderly environment, with a shallow depth of field that keeps the focus on the robot while subtly blurring the background for a cinematic effect."
>>> output = pipe(prompt=prompt).frames[0]
>>> export_to_video(output, "output.mp4", fps=30)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
CosmosVideoToWorldPipeline
lớp diffusers.CosmosVideoToWorldPipeline
< source >( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLCosmosscheduler: EDMEulerSchedulersafety_checker: CosmosSafetyChecker = None )
Tham số
- text_encoder (
T5EncoderModel) — Bộ mã hóa văn bản đóng băng. Cosmos sử dụng T5; cụ thể là biến thể t5-11b. - tokenizer (
T5TokenizerFast) — Tokenizer của lớp T5Tokenizer. - transformer (CosmosTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLCosmos) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn.
Pipeline cho việc tạo thế giới từ ảnh và từ video sử dụng Cosmos Predict-1.
Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 121num_inference_steps: int = 36guidance_scale: float = 7.0input_frames_guidance: bool = Falseaugment_sigma: float = 0.001fps: int = 30num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~CosmosPipelineOutput or tuple
Tham số
- image (
PIL.Image.Image,np.ndarray,torch.Tensor, tùy chọn) — Hình ảnh được sử dụng làm đầu vào điều kiện cho việc tạo video. - video (
list[PIL.Image.Image],np.ndarray,torch.Tensor, tùy chọn) — Video được sử dụng làm đầu vào điều kiện cho việc tạo video. - prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalekhông lớn hơn1). - height (
int, mặc định là720) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là1280) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - num_frames (
int, mặc định là121) — Số lượng khung hình trong video được tạo ra. - num_inference_steps (
int, mặc định là36) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - guidance_scale (
float, mặc định là7.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. - input_frames_guidance (
bool, tùy chọn, mặc định làFalse) — Có áp dụng guidance cho các khung đầu vào có điều kiện hay không. - augment_sigma (
float, tùy chọn, mặc định là 0.001) — Giá trị Sigma được sử dụng để tăng cường các latents có điều kiện trong quá trình khử nhiễu. - fps (
int, mặc định là30) — Số khung hình mỗi giây của video được tạo ra. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtCosmosPipelineOutputthay vì một tuple thông thường hay không. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, tùy chọn) — Một hàm hoặc một lớp con củaPipelineCallbackhoặcMultiPipelineCallbacksđược gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
int, mặc định là512) — Số lượng token tối đa trong prompt. Nếu prompt vượt quá độ dài này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn độ dài này, nó sẽ được đệm.
Trả về
~CosmosPipelineOutput hoặc tuple
Nếu return_dict là True, CosmosPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó
phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các bool
cho biết hình ảnh được tạo ra tương ứng có chứa nội dung “not-safe-for-work” (nsfw) hay không.
Hàm gọi call của pipeline để tạo nội dung.
Ví dụ:
Điều kiện hình ảnh:
>>> import torch
>>> from diffusers import CosmosVideoToWorldPipeline
>>> from diffusers.utils import export_to_video, load_image
>>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
>>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "The video depicts a long, straight highway stretching into the distance, flanked by metal guardrails. The road is divided into multiple lanes, with a few vehicles visible in the far distance. The surrounding landscape features dry, grassy fields on one side and rolling hills on the other. The sky is mostly clear with a few scattered clouds, suggesting a bright, sunny day."
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
... )
>>> video = pipe(image=image, prompt=prompt).frames[0]
>>> export_to_video(video, "output.mp4", fps=30)Điều kiện hóa video:
>>> import torch
>>> from diffusers import CosmosVideoToWorldPipeline
>>> from diffusers.utils import export_to_video, load_video
>>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
>>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.transformer = torch.compile(pipe.transformer)
>>> pipe.to("cuda")
>>> prompt = "The video depicts a winding mountain road covered in snow, with a single vehicle traveling along it. The road is flanked by steep, rocky cliffs and sparse vegetation. The landscape is characterized by rugged terrain and a river visible in the distance. The scene captures the solitude and beauty of a winter drive through a mountainous region."
>>> video = load_video(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
... )[:21] # This example uses only the first 21 frames
>>> video = pipe(video=video, prompt=prompt).frames[0]
>>> export_to_video(video, "output.mp4", fps=30)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
Cosmos2TextToImagePipeline
lớp diffusers.Cosmos2TextToImagePipeline
< source >( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulersafety_checker: CosmosSafetyChecker = None )
Tham số
- text_encoder (
T5EncoderModel) — Bộ mã hóa văn bản đóng băng. Cosmos sử dụng T5; cụ thể là biến thể t5-11b. - tokenizer (
T5TokenizerFast) — Tokenizer của lớp T5Tokenizer. - transformer (CosmosTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
Pipeline để tạo ảnh từ văn bản sử dụng Cosmos Predict2.
Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 768width: int = 1360num_inference_steps: int = 35guidance_scale: float = 7.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~CosmosImagePipelineOutput or tuple
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalekhông lớn hơn1). - height (
int, mặc định là768) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là1360) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - num_inference_steps (
int, mặc định là35) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - guidance_scale (
float, mặc định là7.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtCosmosImagePipelineOutputthay vì một tuple thông thường hay không. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, tùy chọn) — Một hàm hoặc một lớp con củaPipelineCallbackhoặcMultiPipelineCallbacksđược gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
int, mặc định là512) — Số lượng token tối đa trong prompt. Nếu prompt vượt quá độ dài này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn độ dài này, nó sẽ được đệm.
Trả về
~CosmosImagePipelineOutput hoặc tuple
Nếu return_dict là True, CosmosImagePipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về
trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các bool
cho biết hình ảnh được tạo ra tương ứng có chứa nội dung “not-safe-for-work” (nsfw) hay không.
Hàm gọi call của pipeline để tạo nội dung.
Ví dụ:
>>> import torch
>>> from diffusers import Cosmos2TextToImagePipeline
>>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Text2Image, nvidia/Cosmos-Predict2-14B-Text2Image
>>> model_id = "nvidia/Cosmos-Predict2-2B-Text2Image"
>>> pipe = Cosmos2TextToImagePipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess."
>>> 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(
... prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1)
... ).images[0]
>>> output.save("output.png")encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
Cosmos2VideoToWorldPipeline
lớp diffusers.Cosmos2VideoToWorldPipeline
< source >( text_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: CosmosTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulersafety_checker: CosmosSafetyChecker = None )
Tham số
- text_encoder (
T5EncoderModel) — Bộ mã hóa văn bản đóng băng. Cosmos sử dụng T5; cụ thể là biến thể t5-11b. - tokenizer (
T5TokenizerFast) — Tokenizer của lớp T5Tokenizer. - transformer (CosmosTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
Pipeline để tạo thế giới từ video sử dụng Cosmos Predict2.
Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 704width: int = 1280num_frames: int = 93num_inference_steps: int = 35guidance_scale: float = 7.0fps: int = 16num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512sigma_conditioning: float = 0.0001 ) → ~CosmosPipelineOutput or tuple
Tham số
- image (
PIL.Image.Image,np.ndarray,torch.Tensor, tùy chọn) — Hình ảnh được sử dụng làm đầu vào điều kiện cho việc tạo video. - video (
list[PIL.Image.Image],np.ndarray,torch.Tensor, tùy chọn) — Video được sử dụng làm đầu vào điều kiện cho việc tạo video. - prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalekhông lớn hơn1). - height (
int, mặc định là704) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là1280) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - num_frames (
int, mặc định là93) — Số lượng khung hình trong video được tạo ra. - num_inference_steps (
int, mặc định là35) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - guidance_scale (
float, mặc định là7.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. - fps (
int, mặc định là16) — Số khung hình mỗi giây của video được tạo ra. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtCosmosPipelineOutputthay vì một tuple thông thường hay không. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, tùy chọn) — Một hàm hoặc một lớp con củaPipelineCallbackhoặcMultiPipelineCallbacksđược gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
int, mặc định là512) — Số lượng token tối đa trong prompt. Nếu prompt vượt quá độ dài này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn độ dài này, nó sẽ được đệm. - sigma_conditioning (
float, mặc định là0.0001) — Giá trị sigma được sử dụng để chuẩn hóa các latent điều kiện. Về lý tưởng, giá trị này không nên được thay đổi hoặc nên được đặt thành một giá trị nhỏ gần bằng không.
Trả về
~CosmosPipelineOutput hoặc tuple
Nếu return_dict là True, CosmosPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó
phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các bool
cho biết hình ảnh được tạo ra tương ứng có chứa nội dung “not-safe-for-work” (nsfw) hay không.
Hàm gọi call của pipeline để tạo nội dung.
Ví dụ:
>>> import torch
>>> from diffusers import Cosmos2VideoToWorldPipeline
>>> from diffusers.utils import export_to_video, load_image
>>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Video2World, nvidia/Cosmos-Predict2-14B-Video2World
>>> model_id = "nvidia/Cosmos-Predict2-2B-Video2World"
>>> pipe = Cosmos2VideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess."
>>> 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."
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yellow-scrubber.png"
... )
>>> video = pipe(
... image=image, prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1)
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
CosmosPipelineOutput
lớp diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput
< source >( frames: Tensor )
Tham số
- frames (
torch.Tensor,np.ndarray, hoặc list[list[PIL.Image.Image]]) — danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dàibatch_size,trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dàinum_frames.Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng(batch_size, num_frames, channels, height, width).
Lớp đầu ra cho các pipeline any-to-world/video của Cosmos.
CosmosImagePipelineOutput
lớp diffusers.pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Lớp đầu ra cho các pipeline any-to-image của Cosmos.