Diffusion 기반 생성형 AI 활용기/Text2Video 비디오 생성 AI

[Diffusers] AnimateDiff 이용한 영상 생성 AI 만들기

누군가의 이야기 2024. 4. 24. 19:23
728x90

 

 

https://huggingface.co/docs/diffusers/api/pipelines/animatediff

 

Text-to-Video Generation with AnimateDiff

With the advance of text-to-image models (e.g., Stable Diffusion) and corresponding personalization techniques such as DreamBooth and LoRA, everyone can manifest their imagination into high-quality images at an affordable cost. Subsequently, there is a gre

huggingface.co

본문은 위 포스팅을 바탕으로 정리한 글입니다.


 

1. 개요

Text2Image 기술(스테이블 디퓨전 등)과 이를 특정 도메인에 파인 튜닝하는 기술의 발전(드림부스, LoRA) 등으로 이미지 생성 기술의 접근성이 좋아지고, 결과 이미지의 품질도 매우 향상되었다.

 

이후, 생성된 정적인 이미지들에 움직임(모션)을 결합하여 영상 애니메이션을 생성하는 것에 대한 수요도 함께 증가하고 있다.

 

AnimateDiff는 기존 파인튜닝 된 Text2Image 모델을 한 번에 애니메이션화하여 모델별 튜닝에 드는 비용을 절약할 수 있는 프레임워크를 제안한다.

 

AnimateDiff의 핵심은, 동결된 Text2Image 모델에 모션 모델링 모듈(motion modeling module)을 적용하는 것이다.

 

보다 구체적인 내용은 아래 링크 참조

https://animatediff.github.io/

 

AnimateDiff

AnimateDiff: Animate Your Personalized Text-to-Image Diffusion Models without Specific Tuning  (ICLR'24 spotlight) Yuwei Guo1 Ceyuan Yang2✝ Anyi Rao3 Zhengyang Liang2 Yaohui Wang2 Yu Qiao2 Maneesh Agrawala3 Dahua Lin1,2 Bo Dai2 ✝Corresponding Author.

animatediff.github.io

 

 

AnimateDiff 체크포인트 모델은 아래 링크에서 다운로드 가능

https://huggingface.co/guoyww

 

guoyww (Yuwei Guo)

Running on A10G

huggingface.co

 

이 체크포인트 모델들은 스테이블 디퓨전 1.4/1.5 버전 모델이면 모두 적용 가능하다.


2. 파이프라인

import torch
from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

# Load the motion adapter
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2", torch_dtype=torch.float16)
# load SD 1.5 based finetuned model
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
pipe = AnimateDiffPipeline.from_pretrained(model_id, motion_adapter=adapter, torch_dtype=torch.float16)
scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    clip_sample=False,
    timestep_spacing="linspace",
    beta_schedule="linear",
    steps_offset=1,
)
pipe.scheduler = scheduler

# enable memory savings
pipe.enable_vae_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt=(
        "masterpiece, bestquality, highlydetailed, ultradetailed, sunset, "
        "orange sky, warm lighting, fishing boats, ocean waves seagulls, "
        "rippling water, wharf, silhouette, serene atmosphere, dusk, evening glow, "
        "golden hour, coastal landscape, seaside scenery"
    ),
    negative_prompt="bad quality, worse quality",
    num_frames=16,
    guidance_scale=7.5,
    num_inference_steps=25,
    generator=torch.Generator("cpu").manual_seed(42),
)
frames = output.frames[0]
export_to_gif(frames, "animation.gif")

 

Diffusers 라이브러리로 AnmateDiff기본적인 영상 생성 파이프라인

 

베이스가 되는 스테이블 디퓨전 기반 체크포인트 모델: "SG161222/Realistic_Vision_V5.1_noVAE"

모션 어답터: "guoyww/animatediff-motion-adapter-v1-5-2"

스케쥴러: DDIMScheduler

 

이들을 각각 Diffusers 고유의 객체인 AnimateDiffPipeline에 설정해준다

 

영상 추론/생성 하이퍼파라미터를 조정해서 출력한 결과는 아래와 같다.

    num_frames=16,
    guidance_scale=7.5,
    num_inference_steps=25,

더불어 위 하이퍼파라미터는 영상 품질과 직결되는 것들.

 

 


3. Motion LoRAs

여기에 다음과 같이 Motion LoRAs를 추가적으로 적용해줄 수 있다. 

pipe.load_lora_weights(
    "diffusers/animatediff-motion-lora-zoom-out", adapter_name="zoom-out",
)
pipe.load_lora_weights(
    "diffusers/animatediff-motion-lora-pan-left", adapter_name="pan-left",
)
pipe.set_adapters(["zoom-out", "pan-left"], adapter_weights=[1.0, 1.0])

 

 


4. FreeInit

FreeInit은 추가적인 학습 없이 영상 생성 인공지능의 시간적 일관성과 전반적인 품질을 향상할 수 있는 기술이다.

자세한 내용은 아래 논문에서 참고 가능하고,

FreeInit: Bridging Initialization Gap in Video Diffusion Models

 

FreeInit: Bridging Initialization Gap in Video Diffusion Models

Though diffusion-based video generation has witnessed rapid progress, the inference results of existing models still exhibit unsatisfactory temporal consistency and unnatural dynamics. In this paper, we delve deep into the noise initialization of video dif

arxiv.org

아래 코드를 통해 파이프라인에 적용 가능하다.

 

728x90
# enable FreeInit
# Refer to the enable_free_init documentation for a full list of configurable parameters
pipe.enable_free_init(method="butterworth", use_fast_sampling=True)

 

FreeInit을 활용하면 성능은 향상되지만 추론 시간이 길어진다는 단점이 있다고 한다.

 

스케줄러 가이드에서 스케줄러 속도와 품질 사이의 균형을 탐색하는 방법을 확인하여 개선하면 좋다.

https://huggingface.co/docs/diffusers/using-diffusers/schedulers

 


5. AnimateLCM

AnimateLCMmotion module checkpoint이고,  LCM LoRA using a consistency learning strategy that decouples the distillation of the image generation priors and the motion generation priors.

 

내용이 어렵다. 조만간 논문 정독해볼 예정

 

import torch
from diffusers import AnimateDiffPipeline, LCMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

adapter = MotionAdapter.from_pretrained("wangfuyun/AnimateLCM")
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=adapter)
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, beta_schedule="linear")

pipe.load_lora_weights("wangfuyun/AnimateLCM", weight_name="sd15_lora_beta.safetensors", adapter_name="lcm-lora")

pipe.enable_vae_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt="A space rocket with trails of smoke behind it launching into space from the desert, 4k, high resolution",
    negative_prompt="bad quality, worse quality, low resolution",
    num_frames=16,
    guidance_scale=1.5,
    num_inference_steps=6,
    generator=torch.Generator("cpu").manual_seed(0),
)
frames = output.frames[0]
export_to_gif(frames, "animatelcm.gif")

 

모션 어답터 "wangfuyun/AnimateLCM" 를 적용한 생성 결과는 다음과 같다.

 

 

여기에 다른 Motion LoRA를 함께 적용하면 아래와 같은 결과를 얻을 수 있다.

불러올 수 있는 AnimateDiff Motion LoRA 목록:

https://huggingface.co/collections/dn6/animatediff-motion-loras-654cb8ad732b9e3cf4d3c17e

pipe.load_lora_weights("guoyww/animatediff-motion-lora-tilt-up", adapter_name="tilt-up")

pipe.set_adapters(["lcm-lora", "tilt-up"], [1.0, 0.8])

 

 

 

 

 

 

 

728x90