Buckets:

mishig's picture
|
download
raw
19.8 kB
# 비디오 생성
Video generation models은 이미지 생성(1프레임의 비디오로 간주할 수 있음)을 확장하여 공간 및 시간과 관련된 데이터도 처리합니다. 텍스트, 공간, 시간 등 모든 데이터가 프레임 간에 일관되고 정렬되도록 유지하는 것은 길고 고해상도의 비디오를 생성하는 데 있어 큰 과제입니다.
Modern video models은 이 문제를 diffusion transformer (DiT) 아키텍처로 해결합니다. 이를 통해 계산 비용을 줄이고, 더 크고 고품질의 이미지 및 비디오 데이터로 더 효율적으로 확장할 수 있습니다.
아래에서 이러한 비디오 모델 중 일부가 어떤 기능을 하는지 확인해 보세요.
```py
# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import UMT5EncoderModel
text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", dtype=torch.bfloat16)
vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32)
transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", dtype=torch.bfloat16)
# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
apply_group_offloading(text_encoder,
onload_device=onload_device,
offload_device=offload_device,
offload_type="block_level",
num_blocks_per_group=4
)
transformer.enable_group_offload(
onload_device=onload_device,
offload_device=offload_device,
offload_type="leaf_level",
use_stream=True
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
vae=vae,
transformer=transformer,
text_encoder=text_encoder,
dtype=torch.bfloat16
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
prompt = """
The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""
output = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
```py
import torch
from diffusers importAutoModel, HunyuanVideoPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.utils import export_to_video
# quantize weights to int4 with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
quant_backend="bitsandbytes_4bit",
quant_kwargs={
"load_in_4bit": True,
"bnb_4bit_quant_type": "nf4",
"bnb_4bit_compute_dtype": torch.bfloat16
},
components_to_quantize="transformer"
)
pipeline = HunyuanVideoPipeline.from_pretrained(
"hunyuanvideo-community/HunyuanVideo",
quantization_config=pipeline_quant_config,
dtype=torch.bfloat16,
)
# model-offloading and tiling
pipeline.enable_model_cpu_offload()
pipeline.vae.enable_tiling()
prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
export_to_video(video, "output.mp4", fps=15)
```
```py
import torch
from diffusers import LTXPipeline, AutoModel
from diffusers.hooks import apply_group_offloading
from diffusers.utils import export_to_video
# fp8 layerwise weight-casting
transformer = AutoModel.from_pretrained(
"Lightricks/LTX-Video",
subfolder="transformer",
dtype=torch.bfloat16
)
transformer.enable_layerwise_casting(
storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16
)
pipeline = LTXPipeline.from_pretrained("Lightricks/LTX-Video", transformer=transformer, dtype=torch.bfloat16)
# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True)
apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2)
apply_group_offloading(pipeline.vae, onload_device=onload_device, offload_type="leaf_level")
prompt = """
A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage
"""
negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
video = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
width=768,
height=512,
num_frames=161,
decode_timestep=0.03,
decode_noise_scale=0.025,
num_inference_steps=50,
).frames[0]
export_to_video(video, "output.mp4", fps=24)
```
이 가이드에서는 어떤 매개변수를 설정해야 하는지, 메모리 사용량을 어떻게 줄일 수 있는지와 같은 비디오 생성의 기본 사항을 다룹니다.
> [!TIP]
> 특정 모델 사용법에 대해 더 자세히 알고 싶으시다면 해당 모델의 pipeline API 모델 카드를 참고하세요.
## Pipeline 매개변수
pipeline에서 비디오 생성의 품질이나 속도에 영향을 미치는 여러 매개변수를 설정할 수 있습니다. 적절한 품질과 속도 간 트레이드오프를 발견하려면 다양한 매개변수 값으로 실험하는 것이 중요합니다.
### num_frames
프레임은 다른 프레임들과 연속적으로 재생되어 움직임이나 영상을 만드는 정지 이미지입니다. `num_frames`로 초당 생성되는 프레임 수를 제어합니다. `num_frames`을 늘리면 움직임의 부드러움과 시각적 일관성이 향상되어, 동적인 콘텐츠를 포함하는 영상에서 특히 중요합니다. `num_frames` 값이 높을수록 영상 길이도 길어집니다.
일부 비디오 모델은 추론을 위해 더 구체적인 `num_frames` 값을 요구합니다. 예를 들어, [HunyuanVideoPipeline](/docs/diffusers/main/ko/api/pipelines/hunyuan_video#diffusers.HunyuanVideoPipeline)은 `num_frames`를 `(4 * num_frames) +1`로 계산하는 것을 권장합니다. 권장 값이 있는지 항상 해당 파이프라인의 API 모델 카드를 확인하세요.
```py
import torch
from diffusers import LTXPipeline
from diffusers.utils import export_to_video
pipeline = LTXPipeline.from_pretrained(
"Lightricks/LTX-Video", dtype=torch.bfloat16
).to("cuda") # or "mps", "xpu", "cpu"
prompt = """
A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman
with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The
camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and
natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be
real-life footage
"""
video = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
width=768,
height=512,
num_frames=161,
decode_timestep=0.03,
decode_noise_scale=0.025,
num_inference_steps=50,
).frames[0]
export_to_video(video, "output.mp4", fps=24)
```
### guidance_scale
Guidance scale 또는 "cfg"는 생성된 프레임이 입력 조건(텍스트, 이미지 또는 둘 다)에 얼마나 밀접하게 따르는지를 제어합니다. `guidance_scale`을 높이면 입력 조건과 더 유사하고 세부 사항이 더 정교한 프레임이 생성되지만, 아티팩트가 도입되고 출력 다양성이 감소할 위험이 있습니다. `guidance_scale` 값을 낮추면 프롬프트에 대한 준수도가 느슨해지고 출력 다양성이 증가하지만, 세부 사항이 덜 정교할 수 있습니다. 값이 너무 낮으면 프롬프트를 완전히 무시하고 무작위 노이즈를 생성할 수 있습니다.
```py
import torch
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
from diffusers.utils import export_to_video
pipeline = CogVideoXPipeline.from_pretrained(
"THUDM/CogVideoX-2b",
dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
prompt = """
A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over
a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown,
with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an
oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at
a playful environment. The scene captures the innocence and imagination of childhood,
with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
"""
video = pipeline(
prompt=prompt,
guidance_scale=6,
num_inference_steps=50
).frames[0]
export_to_video(video, "output.mp4", fps=8)
```
### negative_prompt
네거티브 프롬프트는 생성된 비디오에서 보고 싶지 않은 요소를 제외하는 데 유용합니다. "blurry, distorted, ugly"와 같은 바람직하지 않은 요소로부터 모델을 멀어지게 하여 생성된 비디오의 품질과 정합성을 개선하는 데 일반적으로 사용됩니다. 이를 통해 더 깔끔하고 초점이 명확한 비디오를 만들 수 있습니다.
```py
# pip install ftfy
import torch
from diffusers import WanPipeline
from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
from diffusers.utils import export_to_video
vae = AutoencoderKLWan.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, dtype=torch.bfloat16
)
pipeline.scheduler = UniPCMultistepScheduler.from_config(
pipeline.scheduler.config, flow_shift=5.0
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie")
pipeline.set_adapters("steamboat-willie")
pipeline.enable_model_cpu_offload()
# use "steamboat willie style" to trigger the LoRA
prompt = """
steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts
dynamic shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
output = pipeline(
prompt=prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
## 메모리 사용량 줄이기
10B 이상의 매개변수를 가진 [HunyuanVideoPipeline](/docs/diffusers/main/ko/api/pipelines/hunyuan_video#diffusers.HunyuanVideoPipeline)와 [WanPipeline](/docs/diffusers/main/ko/api/pipelines/wan#diffusers.WanPipeline)과 같은 최신 비디오 모델은 많은 메모리가 필요하며, 소비자 하드웨어에서 사용할 수 있는 메모리를 초과하는 경우가 많습니다. Diffusers는 이러한 대규모 모델의 메모리 요구 사항을 줄이는 여러 기법을 제공합니다.
> [!TIP]
> 기타 메모리 절약 기법에 대한 자세한 내용은 [메모리 사용량 줄이기](../optimization/memory) 가이드를 참조하세요.
이러한 기법 중 하나는 [group-offloading](../optimization/memory#group-offloading)으로, 사용되지 않을 때 모델의 내부 레이어 그룹(예: `torch.nn.Sequential`)을 CPU로 오프로드합니다. 이러한 레이어는 계산에 필요할 때만 로드되므로, 모델의 **모든** 구성 요소를 GPU에 저장할 필요가 없습니다. [WanPipeline](/docs/diffusers/main/ko/api/pipelines/wan#diffusers.WanPipeline)과 같은 14B 파라미터 모델의 경우, group-offloading을 사용하면 필요한 메모리를 약 13GB의 VRAM으로 줄일 수 있습니다.
```py
# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import UMT5EncoderModel
text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", dtype=torch.bfloat16)
vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32)
transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", dtype=torch.bfloat16)
# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
apply_group_offloading(text_encoder,
onload_device=onload_device,
offload_device=offload_device,
offload_type="block_level",
num_blocks_per_group=4
)
transformer.enable_group_offload(
onload_device=onload_device,
offload_device=offload_device,
offload_type="leaf_level",
use_stream=True
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
vae=vae,
transformer=transformer,
text_encoder=text_encoder,
dtype=torch.bfloat16
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
prompt = """
The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""
output = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
메모리를 줄이는 또 다른 옵션은 모델을 양자화하는 것입니다. 양자화는 모델 가중치를 더 낮은 정밀도의 데이터 유형으로 저장합니다. 그러나 양자화는 특정 비디오 모델에 따라 비디오 품질에 영향을 미칠 수 있습니다. 지원되는 다양한 양자화 백엔드에 대해 자세히 알아보려면 양자화 [개요](../quantization/overview)를 참조하세요.
아래 예제는 [bitsandbytes](../quantization/bitsandbytes)를 사용하여 모델을 양자화합니다.
```py
# pip install ftfy
import torch
from diffusers import WanPipeline
from diffusers import AutoModel, WanPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
from transformers import UMT5EncoderModel
from diffusers.utils import export_to_video
# quantize transformer and text encoder weights with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
quant_backend="bitsandbytes_4bit",
quant_kwargs={"load_in_4bit": True},
components_to_quantize=["transformer", "text_encoder"]
)
vae = AutoModel.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, quantization_config=pipeline_quant_config, dtype=torch.bfloat16
)
pipeline.scheduler = UniPCMultistepScheduler.from_config(
pipeline.scheduler.config, flow_shift=5.0
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie")
pipeline.set_adapters("steamboat-willie")
pipeline.enable_model_cpu_offload()
# use "steamboat willie style" to trigger the LoRA
prompt = """
steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts
dynamic shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
output = pipeline(
prompt=prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
## 추론 속도
[torch.compile](https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)은 최적화된 커널을 사용하여 추론 속도를 높일 수 있습니다. 컴파일은 첫 번째 실행 시 시간이 더 오래 걸리지만, 한 번 컴파일된 후에는 훨씬 빠릅니다. 파이프라인을 한 번만 컴파일한 후, 아무것도 변경하지 않고 파이프라인을 여러 번 사용하는 것이 가장 좋습니다. 이미지 크기 변경과 같은 변경 사항은 재컴파일을 트리거합니다.
아래 예시에서는 파이프라인의 transformer를 컴파일하고 `"max-autotune"` 모드를 사용하여 성능을 극대화합니다.
```py
import torch
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
from diffusers.utils import export_to_video
pipeline = CogVideoXPipeline.from_pretrained(
"THUDM/CogVideoX-2b",
dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
pipeline.transformer, mode="max-autotune", fullgraph=True
)
prompt = """
A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea.
The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse.
Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood,
with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
"""
video = pipeline(
prompt=prompt,
guidance_scale=6,
num_inference_steps=50
).frames[0]
export_to_video(video, "output.mp4", fps=8)
```

Xet Storage Details

Size:
19.8 kB
·
Xet hash:
c2bab831edcec4565d85f471a868ad9340d63024e99dc6d5a41cde68b6381fbf

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.