콘텐츠로 이동

Cosmos-Transfer2.5(제어 기반 비디오 생성)

개요

Cosmos-Transfer2.5는 Cosmos-Predict2.5를 기반으로 구축된 multi-controlnet 모델로, edge, depth, segmentation, blur 등 다양한 공간적 제어 입력(spatial control inputs)을 조건으로 고품질의 비디오를 생성합니다. Cosmos-Transfer2.5를 사용하면 시뮬레이션 비디오를 실사 비디오로 변환(Sim2Real)하거나 실사 비디오의 배경을 변형(Real2Real)하여 Physical AI 학습 데이터를 증강할 수 있습니다. 이 튜토리얼에서는 RBLN Optimum(optimum-rbln)을 사용하여 Cosmos-Transfer2.5 파이프라인과 edge ControlNet을 여러 개의 RBLN NPU용으로 컴파일하고, 컨트롤 비디오와 텍스트 프롬프트를 이용하여 새로운 비디오를 생성하는 방법을 보여줍니다.

Info

리벨리온 확장형 설계(Rebellions Scalable Design, RSD)는 ATOM™+ (RBLN-CA22)와 ATOM™-Max(RBLN-CA25)에서 사용 가능합니다. 현재 사용 중인 RBLN NPU 종류는 rbln-stat 명령어로 확인할 수 있습니다.

환경 설정 및 설치 확인

시작하기 전에 시스템 환경이 올바르게 구성되어 있고 필요한 패키지가 모두 설치되어 있는지 확인합니다. 필요한 항목은 다음과 같습니다:

Note

  • RBLN Compiler를 사용하려면 RBLN 포털 계정이 필요합니다.
  • 위 명령은 Debian 계열 Linux(예: Ubuntu)에서 pip로 패키지를 설치하는 일반적인 절차를 전제로 합니다. OS나 환경이 다른 경우에는 설치 가이드에서 지원되는 설치 조합과 적용 가능한 명령을 확인할 수 있습니다.

Note

nvidia/Cosmos-Transfer2.5-2B 모델은 접근이 제한되어 있습니다(gated model). HuggingFace에서 NVIDIA Open Model License에 동의하여 접근 권한을 부여받은 후, 아래와 같이 hf auth(huggingface-cli) 명령어를 사용하여 로그인할 수 있습니다.

$ hf auth login

    _|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|
    _|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|
    _|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|
    _|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|
    _|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|

    To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens.
Enter your token (input will not be visible):

RBLN Optimum(optimum-rbln) 라이브러리를 사용하여 실행하기

이 단계에서는 여러 개의 RBLN NPU에서 실행되도록 Cosmos-Transfer2.5 모델을 컴파일합니다.

다중 NPU 대상 모델 컴파일

Cosmos-Transfer2.5는 Cosmos-Predict2.5 기반 파이프라인에 제어 모달리티별 ControlNet이 추가된 구조입니다. HuggingFace 허브의 공식 저장소에서는 ControlNet 가중치를 별도의 revision으로 제공하므로, 먼저 diffusers의 AutoModel 클래스로 원하는 ControlNet(edge, depth, seg, blur 중 하나)을 불러온 뒤 파이프라인에 전달합니다.

이후 optimum-rbln 라이브러리에서 제공하는 RBLNCosmos2_5_TransferPipeline 클래스를 사용하여 Cosmos-Transfer2.5 파이프라인의 모델을 컴파일합니다. 모델을 컴파일하려면 export 인수를 True로 설정합니다. 이 클래스의 from_pretrained() 메서드는 HuggingFace 허브에서 Cosmos-Transfer2.5 모델을 다운로드하고 RBLN Compiler를 사용하여 컴파일합니다. 컴파일 후에는 save_pretrained() 메서드를 사용하여 모델 아티팩트(artifacts)를 디스크에 저장합니다. 이 과정은 컴파일된 모델을 포함하는 디렉터리(예: rbln-cosmos-transfer2.5)를 생성합니다.

모델을 컴파일하기 전, 출력 비디오의 크기를 명시해야 합니다. 긴 비디오는 num_frames 크기의 청크(chunk) 단위로 자기회귀적으로(auto-regressively) 생성되므로, 컴파일 시 지정하는 크기(704x1280 픽셀, 93 프레임)는 청크 하나에 대한 것이며, 전체 출력 길이는 입력 컨트롤 비디오의 길이를 따릅니다.

또한 파이프라인의 일부 모듈은 추론 시 여러 개의 NPU가 필요하므로, 컴파일 시에 NPU 수를 명시해야 합니다. 컴파일 예제 코드는 다음과 같습니다.

import torch
from diffusers import AutoModel
from optimum.rbln import RBLNCosmos2_5_TransferPipeline

# Define the HuggingFace model ID
model_id = "nvidia/Cosmos-Transfer2.5-2B"

# Load the edge ControlNet from its own revision
controlnet = AutoModel.from_pretrained(
    model_id,
    revision="diffusers/controlnet/general/edge",
    torch_dtype=torch.bfloat16,
)

# Compile Cosmos core models (transformer, controlnet, text_encoder, vae, safety_checker)
pipe = RBLNCosmos2_5_TransferPipeline.from_pretrained(
    model_id,
    revision="diffusers/general",
    controlnet=controlnet,
    torch_dtype=torch.bfloat16,
    export=True,
    rbln_config={
        "height": 704,
        "width": 1280,
        "num_frames": 93,
        "max_seq_len": 512,
        "create_runtimes": False,
        "text_encoder": {
            "num_devices": 8,
        },
        "transformer": {
            "num_devices": 8,
        },
        "controlnet": {
            "num_devices": 2,
        },
    },
)

pipe.save_pretrained("rbln-cosmos-transfer2.5")

컴파일된 RBLN 모델 불러오기

비디오를 생성하려면, 먼저 이전 단계에서 저장한 컴파일된 모델을 불러와야 합니다. RBLNCosmos2_5_TransferPipeline 클래스의 from_pretrained() 메서드로 모델을 불러옵니다. 이번에는 export 인수를 False로 설정하여 로컬 경로에서 사전 컴파일된 모델을 불러오도록 지정합니다.

Cosmos-Transfer2.5 파이프라인은 여러 개의 모듈로 구성되어 있고, 이 중 일부는 디바이스 메모리를 많이 차지합니다. 따라서 이러한 모델을 동일한 디바이스에 모두 불러오면 디바이스 메모리 부족(out of memory) 오류가 발생합니다. 같은 수의 NPU를 사용하더라도 어떤 모듈을 어느 디바이스에 배치하는지에 따라 로드의 성공 여부가 달라지므로, rbln_config에서 device id를 유의해서 설정해야 합니다. 아래 예제 코드에서는 모든 서브모듈이 transformer가 사용하는 8개의 NPU 위에 함께 올라갑니다. text_encoder는 8개를 모두 공유하고, controlnet, VAE encoder/decoder(컨트롤 비디오 인코딩에도 사용), safety_checker는 앞쪽 4개를 나누어 사용하므로 전체 파이프라인이 8개의 NPU 풀에 들어갑니다.

from optimum.rbln import RBLNCosmos2_5_TransferPipeline

pipe = RBLNCosmos2_5_TransferPipeline.from_pretrained(
    model_id="rbln-cosmos-transfer2.5",
    export=False,
    rbln_config={
        "text_encoder": {
            "device": [0, 1, 2, 3, 4, 5, 6, 7],
        },
        "transformer": {
            "device": [0, 1, 2, 3, 4, 5, 6, 7],
        },
        "controlnet": {
            "device": [0, 1],
        },
        "vae": {
            "device_map": {"encoder": 2, "decoder": 3},
        },
        "safety_checker": {
            "qwen3guard": {"device": 0},
            "face_blur_filter": {"device": 0},
        },
    },
)

비디오 생성

컴파일된 파이프라인을 불러온 뒤 다음과 같이 비디오를 생성합니다. 컨트롤 비디오 및 프롬프트와 함께 파이프라인을 호출하면, 컨트롤 비디오(edge map)의 구조를 따르는 새로운 비디오가 생성됩니다. 네거티브 프롬프트는 파이프라인 내부에 정의된 기본값을 사용하며, negative_prompt 인수로 원하는 프롬프트를 직접 전달할 수도 있습니다. 출력 비디오의 전체 길이는 기본적으로 컨트롤 비디오의 길이(아래 예제에서는 121 프레임)를 따르며, 컴파일 시 지정한 93 프레임 청크 단위로 비디오를 생성합니다.

Note

원본 cosmos-transfer2.5 구현은 여러 제어 모달리티를 동시에 조합하는 multi-control을 지원하지만, 현재 diffusers 구현(0.38.0 버전 기준)은 하나의 ControlNet과 하나의 컨트롤 비디오만 입력할 수 있습니다. 다른 제어 모달리티를 사용하려면 해당 ControlNet(depth, seg, blur)으로 파이프라인을 다시 컴파일해야 합니다.

NVIDIA Open Model License

NVIDIA Open Model License 정책에 따라 safety_checker 서브모듈이 입력 프롬프트와 생성된 비디오에 대한 가드레일 검사를 파이프라인 내부에서 자동으로 적용합니다. safety_checker를 제거하거나 비활성화해서는 안 됩니다. 용도에 맞는 동등한 수준의 가드레일로 대체하지 않는 한, 가드레일을 우회하거나 그 효력을 떨어뜨리면 라이선스에 따른 권리가 자동으로 종료됩니다.

import torch
from diffusers.utils import export_to_video, load_video

# Control video: the pre-computed Canny edge maps for the car driving scene from the
# official cosmos-transfer2.5 assets.
controls = [
    load_video(
        "https://github.com/nvidia-cosmos/cosmos-transfer2.5/raw/refs/heads/main/assets/car_example/edge/car_edge.mp4"
    )
]
prompt = "The video is a driving scene through a modern urban environment, likely captured from a dashcam or a similar fixed camera setup inside a vehicle. The scene unfolds on a wide, multi-lane road flanked by tall, modern buildings with glass facades. The road is relatively empty, with only a few cars visible, including a black car directly ahead of the camera, maintaining a steady pace. The camera remains static, providing a consistent view of the road and surroundings as the vehicle moves forward.On the left side of the road, there are several trees lining the sidewalk, providing a touch of greenery amidst the urban setting. Pedestrians are visible on the sidewalks, some walking leisurely, while others stand near the buildings. The buildings are a mix of architectural styles, with some featuring large glass windows and others having more traditional concrete exteriors. A few commercial signs and logos are visible on the buildings, indicating the presence of businesses and offices.Traffic cones are placed on the road ahead, suggesting some form of roadwork or lane closure, guiding the vehicles to merge or change lanes. The road markings are clear, with white arrows indicating the direction of travel. The sky is clear, suggesting a sunny day, which enhances the visibility of the scene. Throughout the video, the vehicle maintains a steady speed, and the camera captures the gradual approach towards the intersection, where the road splits into different directions. The overall atmosphere is calm and orderly, typical of a city during non-peak hours."

# Transfer inference with controls: the output video follows the edge maps.
video = pipe(
    controls=controls,
    controls_conditioning_scale=1.0,
    prompt=prompt,
    height=704,
    width=1280,
    generator=torch.Generator().manual_seed(1),
).frames[0]
export_to_video(video, "generated_video.mp4", fps=16)

예시 출력:

전체 예제 코드는 RBLN Model Zoo GitHub 저장소에서 확인할 수 있습니다.

참고