Upload 16 files
Browse files- Dockerfile +76 -75
- app.py +148 -261
- compose.yaml +31 -18
- entrypoint.sh +36 -13
- pipeline_ltx_video (3).py +1895 -0
- requirements.txt +1 -1
- setup.py +114 -120
- start.sh +73 -34
Dockerfile
CHANGED
|
@@ -1,126 +1,127 @@
|
|
| 1 |
# =============================================================================
|
| 2 |
-
# ADUC-SDR Video Suite —
|
|
|
|
| 3 |
# CUDA 12.8 | PyTorch 2.8.0+cu128 | Ubuntu 22.04
|
| 4 |
# =============================================================================
|
| 5 |
FROM nvidia/cuda:12.8.0-devel-ubuntu22.04
|
| 6 |
|
| 7 |
-
LABEL maintainer="Carlos Rodrigues dos Santos
|
| 8 |
-
LABEL description="High-performance Diffusers stack with
|
| 9 |
-
LABEL version="
|
| 10 |
LABEL cuda_version="12.8.0"
|
| 11 |
LABEL python_version="3.10"
|
| 12 |
LABEL pytorch_version="2.8.0+cu128"
|
| 13 |
LABEL gpu_optimized_for="8x_NVIDIA_L40S"
|
| 14 |
|
| 15 |
-
#
|
|
|
|
|
|
|
| 16 |
ENV DEBIAN_FRONTEND=noninteractive TZ=UTC LANG=C.UTF-8 LC_ALL=C.UTF-8 \
|
| 17 |
PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
|
| 18 |
-
PIP_NO_CACHE_DIR=
|
| 19 |
|
| 20 |
-
# GPU
|
| 21 |
-
ENV NVIDIA_VISIBLE_DEVICES=all
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
|
| 26 |
-
# Threads
|
| 27 |
ENV OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 MAX_JOBS=160
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
ENV PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512,garbage_collection_threshold:0.8
|
| 31 |
-
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
ENV APP_HOME=/app
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
ENV HF_HOME=/data/.cache/huggingface
|
| 39 |
-
ENV TORCH_HOME=/data/.cache/torch
|
| 40 |
-
ENV HF_DATASETS_CACHE=/data/.cache/datasets
|
| 41 |
-
ENV TRANSFORMERS_CACHE=/data/.cache/transformers
|
| 42 |
-
ENV DIFFUSERS_CACHE=/data/.cache/diffusers
|
| 43 |
-
ENV HF_HUB_ENABLE_HF_TRANSFER=1
|
| 44 |
-
ENV TOKENIZERS_PARALLELISM=false
|
| 45 |
|
| 46 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
RUN useradd -m -u 1000 -s /bin/bash appuser && \
|
| 48 |
-
mkdir -p /data /
|
| 49 |
-
/data/.cache/huggingface /data/.cache/torch \
|
| 50 |
-
/data/.cache/datasets /data/.cache/transformers /data/.cache/diffusers && \
|
| 51 |
-
chown -R appuser:appuser /data
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
ENV MODELS_DIR=/data/models
|
| 55 |
-
RUN ln -sf /data/models /app/models
|
| 56 |
-
|
| 57 |
-
# ---------------- System & Python ----------------
|
| 58 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 59 |
build-essential gosu tree cmake git git-lfs curl wget ffmpeg ninja-build \
|
| 60 |
python3.10 python3.10-dev python3.10-distutils python3-pip \
|
| 61 |
ca-certificates libglib2.0-0 libgl1 \
|
| 62 |
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 63 |
|
| 64 |
-
RUN ln -sf /usr/bin/python3.10 /usr/bin/
|
| 65 |
-
ln -sf /usr/bin/python3.10 /usr/bin/python && \
|
| 66 |
python3 -m pip install --upgrade pip
|
| 67 |
|
| 68 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
RUN pip install --index-url https://download.pytorch.org/whl/cu128 \
|
| 70 |
torch>=2.8.0+cu128 torchvision>=0.23.0+cu128 torchaudio>=2.8.0+cu128
|
| 71 |
|
| 72 |
-
#
|
| 73 |
RUN pip install packaging ninja cmake pybind11 scikit-build cython hf_transfer "numpy>=1.24.4"
|
| 74 |
|
| 75 |
-
# Triton 3.x
|
| 76 |
RUN pip uninstall -y triton || true && \
|
| 77 |
pip install -v --no-build-isolation triton==3.4.0
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# ---------------- App dependencies ----------------
|
| 87 |
-
COPY requirements.txt ./requirements.txt
|
| 88 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 89 |
|
| 90 |
-
#
|
| 91 |
RUN pip install --upgrade bitsandbytes
|
| 92 |
|
| 93 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
RUN echo "Installing custom wheels..." && \
|
| 95 |
pip install --no-cache-dir \
|
| 96 |
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl" \
|
| 97 |
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/dropout_layer_norm-0.1-cp310-cp310-linux_x86_64.whl"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
#
|
| 101 |
-
RUN
|
| 102 |
-
|
| 103 |
-
# RUN git clone https://github.com/Lightricks/LTX-Video.git /data/LTX-Video && \
|
| 104 |
-
# cd /data/LTX-Video && python -m pip install -e .[inference]
|
| 105 |
-
# ====================================================================
|
| 106 |
-
|
| 107 |
-
# Scripts and app
|
| 108 |
-
COPY info.sh ./app/info.sh
|
| 109 |
-
COPY builder.sh ./app/builder.sh
|
| 110 |
-
COPY start.sh ./app/start.sh
|
| 111 |
-
COPY entrypoint.sh ./app/entrypoint.sh
|
| 112 |
-
|
| 113 |
-
# Copy the rest of the source last for better caching
|
| 114 |
-
COPY . .
|
| 115 |
-
|
| 116 |
-
# Permissions on app tree
|
| 117 |
-
RUN chown -R appuser:appuser /app /data && \
|
| 118 |
-
chmod 0755 /app/entrypoint.sh /app/start.sh /app/info.sh /app/builder.sh
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
VOLUME /data
|
| 121 |
|
| 122 |
-
|
| 123 |
USER appuser
|
| 124 |
|
| 125 |
-
#
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# =============================================================================
|
| 2 |
+
# ADUC-SDR Video Suite — Dockerfile Otimizado
|
| 3 |
+
# Preserva a estrutura de instalação original para alta performance.
|
| 4 |
# CUDA 12.8 | PyTorch 2.8.0+cu128 | Ubuntu 22.04
|
| 5 |
# =============================================================================
|
| 6 |
FROM nvidia/cuda:12.8.0-devel-ubuntu22.04
|
| 7 |
|
| 8 |
+
LABEL maintainer="Carlos Rodrigues dos Santos"
|
| 9 |
+
LABEL description="ADUC-SDR: High-performance Diffusers stack for 8x NVIDIA L40S with LTX-Video and SeedVR"
|
| 10 |
+
LABEL version="5.0.0"
|
| 11 |
LABEL cuda_version="12.8.0"
|
| 12 |
LABEL python_version="3.10"
|
| 13 |
LABEL pytorch_version="2.8.0+cu128"
|
| 14 |
LABEL gpu_optimized_for="8x_NVIDIA_L40S"
|
| 15 |
|
| 16 |
+
# =============================================================================
|
| 17 |
+
# 1. Variáveis de Ambiente e Configuração de Paths
|
| 18 |
+
# =============================================================================
|
| 19 |
ENV DEBIAN_FRONTEND=noninteractive TZ=UTC LANG=C.UTF-8 LC_ALL=C.UTF-8 \
|
| 20 |
PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
|
| 21 |
+
PIP_NO_CACHE_DIR=0 PIP_DISABLE_PIP_VERSION_CHECK=1
|
| 22 |
|
| 23 |
+
# --- Configurações de GPU e Computação ---
|
| 24 |
+
ENV NVIDIA_VISIBLE_DEVICES=all \
|
| 25 |
+
TORCH_CUDA_ARCH_LIST="8.9" \
|
| 26 |
+
CUDA_DEVICE_ORDER=PCI_BUS_ID \
|
| 27 |
+
CUDA_DEVICE_MAX_CONNECTIONS=32
|
| 28 |
|
| 29 |
+
# --- Configurações de Threads ---
|
| 30 |
ENV OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 MAX_JOBS=160
|
| 31 |
|
| 32 |
+
# --- Configurações de Alocador de Memória e Caches de GPU ---
|
| 33 |
+
ENV PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512,garbage_collection_threshold:0.8 \
|
| 34 |
+
CUDA_LAUNCH_BLOCKING=0 CUDA_CACHE_MAXSIZE=2147483648 CUDA_CACHE_DISABLE=0
|
| 35 |
|
| 36 |
+
# --- Paths da Aplicação e Dados Persistentes ---
|
| 37 |
+
ENV APP_HOME=/app \
|
| 38 |
+
HF_HOME=/data/.cache/huggingface \
|
| 39 |
+
TORCH_HOME=/data/.cache/torch \
|
| 40 |
+
HF_DATASETS_CACHE=/data/.cache/datasets \
|
| 41 |
+
TRANSFORMERS_CACHE=/data/.cache/transformers \
|
| 42 |
+
DIFFUSERS_CACHE=/data/.cache/diffusers \
|
| 43 |
+
HF_HUB_ENABLE_HF_TRANSFER=1 \
|
| 44 |
+
TOKENIZERS_PARALLELISM=false
|
| 45 |
|
| 46 |
+
WORKDIR $APP_HOME
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
# =============================================================================
|
| 49 |
+
# 2. Setup de Usuário e Sistema
|
| 50 |
+
# =============================================================================
|
| 51 |
+
# Cria usuário não-root e diretórios de dados/app.
|
| 52 |
+
# As permissões finais serão aplicadas no final.
|
| 53 |
RUN useradd -m -u 1000 -s /bin/bash appuser && \
|
| 54 |
+
mkdir -p /data $APP_HOME /app/output
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# --- Instalação de Pacotes de Sistema e Python ---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 58 |
build-essential gosu tree cmake git git-lfs curl wget ffmpeg ninja-build \
|
| 59 |
python3.10 python3.10-dev python3.10-distutils python3-pip \
|
| 60 |
ca-certificates libglib2.0-0 libgl1 \
|
| 61 |
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 62 |
|
| 63 |
+
RUN ln -sf /usr/bin/python3.10 /usr/bin/python && \
|
|
|
|
| 64 |
python3 -m pip install --upgrade pip
|
| 65 |
|
| 66 |
+
# =============================================================================
|
| 67 |
+
# 3. Instalação da Toolchain de Machine Learning (Mantida 100% Original)
|
| 68 |
+
# =============================================================================
|
| 69 |
+
|
| 70 |
+
# --- PyTorch para CUDA 12.8 ---
|
| 71 |
RUN pip install --index-url https://download.pytorch.org/whl/cu128 \
|
| 72 |
torch>=2.8.0+cu128 torchvision>=0.23.0+cu128 torchaudio>=2.8.0+cu128
|
| 73 |
|
| 74 |
+
# --- Ferramentas de Compilação, Triton e FlashAttention ---
|
| 75 |
RUN pip install packaging ninja cmake pybind11 scikit-build cython hf_transfer "numpy>=1.24.4"
|
| 76 |
|
| 77 |
+
# --- Triton 3.x ---
|
| 78 |
RUN pip uninstall -y triton || true && \
|
| 79 |
pip install -v --no-build-isolation triton==3.4.0
|
| 80 |
|
| 81 |
+
# --- FlashAttention 2.8.x ---
|
| 82 |
+
|
| 83 |
+
# =============================================================================
|
| 84 |
+
# 4. Instalação das Dependências da Aplicação
|
| 85 |
+
# =============================================================================
|
| 86 |
+
# Copia e instala requirements.txt primeiro para otimizar o cache de camadas do Docker.
|
| 87 |
+
COPY --chown=appuser:appuser requirements.txt ./requirements.txt
|
|
|
|
|
|
|
| 88 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 89 |
|
| 90 |
+
# --- Instalação de bitsandbytes e Wheels Customizados (Mantido 100% Original) ---
|
| 91 |
RUN pip install --upgrade bitsandbytes
|
| 92 |
|
| 93 |
+
# Instala wheels customizados (Apex, etc.)
|
| 94 |
+
# Instala q8_kernels
|
| 95 |
+
RUN pip install --no-cache-dir \
|
| 96 |
+
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/q8_kernels-0.0.5-cp310-cp310-linux_x86_64.whl"
|
| 97 |
+
|
| 98 |
RUN echo "Installing custom wheels..." && \
|
| 99 |
pip install --no-cache-dir \
|
| 100 |
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl" \
|
| 101 |
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/dropout_layer_norm-0.1-cp310-cp310-linux_x86_64.whl"
|
| 102 |
+
|
| 103 |
+
# =============================================================================
|
| 104 |
+
# 5. Cópia do Código-Fonte e Configuração Final
|
| 105 |
+
# =============================================================================
|
| 106 |
+
# Copia o restante do código-fonte da aplicação por último.
|
| 107 |
+
COPY --chown=appuser:appuser . .
|
| 108 |
|
| 109 |
+
# Garante que todos os scripts de inicialização sejam executáveis
|
| 110 |
+
# e que o usuário 'appuser' seja o dono de todos os arquivos.
|
| 111 |
+
RUN chown -R appuser:appuser $APP_HOME /data && \
|
| 112 |
+
chmod +x /app/entrypoint.sh /app/start.sh /app/info.sh /app/builder.sh
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
# =============================================================================
|
| 115 |
+
# 6. Ponto de Entrada
|
| 116 |
+
# =============================================================================
|
| 117 |
+
# Expõe o diretório /data para ser montado como um volume persistente.
|
| 118 |
VOLUME /data
|
| 119 |
|
| 120 |
+
# Define o usuário padrão para a execução do contêiner.
|
| 121 |
USER appuser
|
| 122 |
|
| 123 |
+
# Define o script que será executado na inicialização do contêiner.
|
| 124 |
+
ENTRYPOINT ["/app/entrypoint.sh"]
|
| 125 |
+
|
| 126 |
+
# Define o comando padrão a ser executado pelo entrypoint.
|
| 127 |
+
CMD ["/app/start.sh"]
|
app.py
CHANGED
|
@@ -1,307 +1,194 @@
|
|
| 1 |
-
|
| 2 |
-
#
|
| 3 |
-
# Provides a user-friendly, step-by-step workflow for creating videos.
|
| 4 |
|
| 5 |
import gradio as gr
|
| 6 |
-
import
|
| 7 |
import sys
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
#
|
| 36 |
-
|
| 37 |
-
def
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
progress=gr.Progress(track_tqdm=True)
|
| 42 |
-
) -> tuple:
|
| 43 |
-
"""
|
| 44 |
-
Wrapper to call the backend for generating the initial low-resolution video.
|
| 45 |
-
It decides whether to use the 'narrative' or 'single' generation mode.
|
| 46 |
-
"""
|
| 47 |
-
try:
|
| 48 |
-
print(f"[UI] Request received for base video generation. Mode: {generation_mode}")
|
| 49 |
|
| 50 |
-
|
| 51 |
if start_img:
|
| 52 |
-
# Estimate total frames for conditioning context
|
| 53 |
num_frames_estimate = int(duration * 24)
|
| 54 |
-
items_list = [[start_img, 0, 1.0]]
|
| 55 |
-
|
| 56 |
-
items_list, height, width, num_frames_estimate
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
# Package advanced LTX settings for the backend
|
| 60 |
-
ltx_configs = {
|
| 61 |
-
"guidance_preset": fp_guidance_preset,
|
| 62 |
-
"guidance_scale_list": fp_guidance_scale_list,
|
| 63 |
-
"stg_scale_list": fp_stg_scale_list,
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
# Select the appropriate backend function based on UI mode
|
| 67 |
-
if generation_mode == "Narrativa (Múltiplos Prompts)":
|
| 68 |
-
func_to_call = video_generation_service.generate_narrative_low
|
| 69 |
-
else:
|
| 70 |
-
func_to_call = video_generation_service.generate_single_low
|
| 71 |
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
| 73 |
prompt=prompt, negative_prompt=neg_prompt,
|
| 74 |
-
height=height, width=width,
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
ltx_configs_override=ltx_configs
|
| 78 |
)
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
print(f"[UI] Base video generation successful. Path: {video_path}")
|
| 87 |
return video_path, new_state, gr.update(visible=True)
|
| 88 |
-
|
| 89 |
-
except Exception as e:
|
| 90 |
-
error_message = f"❌ An error occurred during base generation:\n{e}"
|
| 91 |
-
print(f"{error_message}\nDetails: {traceback.format_exc()}")
|
| 92 |
-
raise gr.Error(error_message)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def run_ltx_refinement(
|
| 96 |
-
state: dict, prompt: str, neg_prompt: str,
|
| 97 |
-
progress=gr.Progress(track_tqdm=True)
|
| 98 |
-
) -> tuple:
|
| 99 |
-
"""Wrapper to call the LTX texture refinement and upscaling backend function."""
|
| 100 |
-
if not state or not state.get("low_res_latents"):
|
| 101 |
-
raise gr.Error("Error: Please generate a base video in Step 1 before refining.")
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
| 105 |
video_path, tensor_path = video_generation_service.generate_upscale_denoise(
|
| 106 |
latents_path=state["low_res_latents"],
|
| 107 |
prompt=prompt,
|
| 108 |
negative_prompt=neg_prompt,
|
|
|
|
| 109 |
seed=state["used_seed"]
|
| 110 |
)
|
| 111 |
-
|
|
|
|
| 112 |
state["refined_video_ltx"] = video_path
|
| 113 |
state["refined_latents_ltx"] = tensor_path
|
| 114 |
-
|
| 115 |
return video_path, state
|
| 116 |
-
except Exception as e:
|
| 117 |
-
error_message = f"❌ An error occurred during LTX Refinement:\n{e}"
|
| 118 |
-
print(f"{error_message}\nDetails: {traceback.format_exc()}")
|
| 119 |
-
raise gr.Error(error_message)
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
def run_seedvr_upscaling(
|
| 123 |
-
state: dict, seed: int, resolution: int, batch_size: int, fps: int,
|
| 124 |
-
progress=gr.Progress(track_tqdm=True)
|
| 125 |
-
) -> tuple:
|
| 126 |
-
"""Wrapper to call the SeedVR upscaling backend service."""
|
| 127 |
-
if not state or not state.get("low_res_video"):
|
| 128 |
-
raise gr.Error("Error: Please generate a base video in Step 1 before upscaling.")
|
| 129 |
-
if not seedvr_inference_server:
|
| 130 |
-
raise gr.Error("Error: The SeedVR upscaling server is not available.")
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
output_filepath = seedvr_inference_server.run_inference(
|
| 137 |
-
file_path=
|
| 138 |
batch_size=batch_size, fps=fps, progress=progress_wrapper
|
| 139 |
)
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
print(f"[UI] SeedVR upscaling successful. Path: {output_filepath}")
|
| 143 |
-
return gr.update(value=output_filepath), gr.update(value=status_message)
|
| 144 |
-
except Exception as e:
|
| 145 |
-
error_message = f"❌ An error occurred during SeedVR Upscaling:\n{e}"
|
| 146 |
-
print(f"{error_message}\nDetails: {traceback.format_exc()}")
|
| 147 |
-
return None, gr.update(value=error_message)
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
# ==============================================================================
|
| 151 |
-
# --- UI BUILDER ---
|
| 152 |
-
# Functions dedicated to creating parts of the Gradio interface.
|
| 153 |
-
# ==============================================================================
|
| 154 |
-
|
| 155 |
-
def build_ui():
|
| 156 |
-
"""Constructs the entire Gradio application UI."""
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
with gr.
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
| 170 |
|
| 171 |
-
with gr.
|
| 172 |
-
gr.
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
# Connect all UI events to their corresponding functions
|
| 181 |
-
_register_event_handlers(app_state, ui_components)
|
| 182 |
-
|
| 183 |
-
return demo
|
| 184 |
-
|
| 185 |
-
def _build_generation_controls(ui: dict):
|
| 186 |
-
"""Builds the UI components for Step 1: Base Video Generation."""
|
| 187 |
-
gr.Markdown("### Etapa 1: Configurações de Geração")
|
| 188 |
-
|
| 189 |
-
ui['generation_mode'] = gr.Radio(
|
| 190 |
-
label="Modo de Geração",
|
| 191 |
-
choices=["Simples (Prompt Único)", "Narrativa (Múltiplos Prompts)"],
|
| 192 |
-
value="Narrativa (Múltiplos Prompts)",
|
| 193 |
-
info="Simples para uma ação contínua, Narrativa para uma sequência de cenas (uma por linha)."
|
| 194 |
-
)
|
| 195 |
-
ui['prompt'] = gr.Textbox(label="Prompt(s)", value="Um leão majestoso caminha pela savana\nEle sobe em uma grande pedra e olha o horizonte", lines=4)
|
| 196 |
-
ui['neg_prompt'] = gr.Textbox(label="Negative Prompt", value="blurry, low quality, bad anatomy, deformed", lines=2)
|
| 197 |
-
ui['start_image'] = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload"])
|
| 198 |
-
|
| 199 |
-
with gr.Accordion("Parâmetros Principais", open=True):
|
| 200 |
-
ui['duration'] = gr.Slider(label="Duração Total (s)", value=4, step=1, minimum=1, maximum=30)
|
| 201 |
-
with gr.Row():
|
| 202 |
-
ui['height'] = gr.Slider(label="Height", value=432, step=16, minimum=256, maximum=1024)
|
| 203 |
-
ui['width'] = gr.Slider(label="Width", value=768, step=16, minimum=256, maximum=1024)
|
| 204 |
-
with gr.Row():
|
| 205 |
-
ui['seed'] = gr.Number(label="Seed", value=42, precision=0)
|
| 206 |
-
ui['randomize_seed'] = gr.Checkbox(label="Randomize Seed", value=True)
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
info="Controla como a guiagem de texto se comporta ao longo da difusão."
|
| 214 |
-
)
|
| 215 |
-
with gr.Group(visible=False) as ui['custom_guidance_group']:
|
| 216 |
-
gr.Markdown("⚠️ Edite as listas em formato JSON. Ex: `[1.0, 2.5, 3.0]`")
|
| 217 |
-
ui['fp_guidance_scale_list'] = gr.Textbox(label="Lista de Guidance Scale", value="[1, 1, 6, 8, 6, 1, 1]")
|
| 218 |
-
ui['fp_stg_scale_list'] = gr.Textbox(label="Lista de STG Scale (Movimento)", value="[0, 0, 4, 4, 4, 2, 1]")
|
| 219 |
-
|
| 220 |
-
ui['generate_low_btn'] = gr.Button("1. Gerar Vídeo Base", variant="primary")
|
| 221 |
|
| 222 |
-
def _build_postprod_controls(ui: dict):
|
| 223 |
-
"""Builds the UI components for Step 2: Post-Production."""
|
| 224 |
-
with gr.Group(visible=False) as ui['post_prod_group']:
|
| 225 |
-
gr.Markdown("--- \n## Etapa 2: Pós-Produção", elem_id="postprod-title")
|
| 226 |
-
|
| 227 |
with gr.Tabs():
|
| 228 |
-
|
|
|
|
| 229 |
with gr.Row():
|
| 230 |
with gr.Column(scale=1):
|
| 231 |
-
gr.Markdown("
|
| 232 |
-
|
|
|
|
| 233 |
with gr.Column(scale=1):
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
gr.Markdown("🔴 *O serviço SeedVR não está disponível nesta instância.*")
|
| 240 |
-
|
| 241 |
with gr.Row():
|
| 242 |
with gr.Column(scale=1):
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
| 248 |
with gr.Column(scale=1):
|
| 249 |
-
|
| 250 |
-
|
|
|
|
| 251 |
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
-
#
|
| 254 |
-
# --- EVENT HANDLERS ---
|
| 255 |
-
# Connects UI component events (like clicks) to the wrapper functions.
|
| 256 |
-
# ==============================================================================
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
return gr.update(visible=(preset_choice == "Customizado"))
|
| 264 |
-
|
| 265 |
-
ui['fp_guidance_preset'].change(
|
| 266 |
-
fn=toggle_custom_guidance,
|
| 267 |
-
inputs=ui['fp_guidance_preset'],
|
| 268 |
-
outputs=ui['custom_guidance_group']
|
| 269 |
)
|
| 270 |
|
| 271 |
-
#
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
gen_outputs = [
|
| 278 |
-
ui['low_res_video_output'], app_state, ui['post_prod_group']
|
| 279 |
-
]
|
| 280 |
-
ui['generate_low_btn'].click(fn=run_generate_base_video, inputs=gen_inputs, outputs=gen_outputs)
|
| 281 |
-
|
| 282 |
-
# --- Handler for the LTX Refine button ---
|
| 283 |
-
refine_inputs = [app_state, ui['prompt'], ui['neg_prompt']]
|
| 284 |
-
refine_outputs = [ui['ltx_refined_video_output'], app_state]
|
| 285 |
-
ui['ltx_refine_btn'].click(fn=run_ltx_refinement, inputs=refine_inputs, outputs=refine_outputs)
|
| 286 |
-
|
| 287 |
-
# --- Handler for the SeedVR Upscale button ---
|
| 288 |
-
if 'run_seedvr_btn' in ui:
|
| 289 |
-
seedvr_inputs = [app_state, ui['seedvr_seed'], ui['seedvr_resolution'], ui['seedvr_batch_size'], ui['seedvr_fps']]
|
| 290 |
-
seedvr_outputs = [ui['seedvr_video_output'], ui['seedvr_status_box']]
|
| 291 |
-
ui['run_seedvr_btn'].click(fn=run_seedvr_upscaling, inputs=seedvr_inputs, outputs=seedvr_outputs)
|
| 292 |
-
|
| 293 |
|
| 294 |
-
#
|
| 295 |
-
|
| 296 |
-
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
if __name__ == "__main__":
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
print("Launching Gradio app...")
|
| 302 |
-
gradio_app.queue().launch(
|
| 303 |
-
server_name="0.0.0.0",
|
| 304 |
-
server_port=7860,
|
| 305 |
-
debug=True,
|
| 306 |
-
show_error=True
|
| 307 |
-
)
|
|
|
|
| 1 |
+
|
| 2 |
+
# app_refactored_with_postprod.py (FINAL VERSION with LTX Refinement)
|
|
|
|
| 3 |
|
| 4 |
import gradio as gr
|
| 5 |
+
import os
|
| 6 |
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import torch
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
# --- Import dos Serviços de Backend ---
|
| 14 |
+
|
| 15 |
+
# Serviço LTX para geração de vídeo base e refinamento de textura
|
| 16 |
+
from api.ltx_server_refactored import video_generation_service
|
| 17 |
+
|
| 18 |
+
# Serviço SeedVR para upscaling de alta qualidade
|
| 19 |
+
from api.seedvr_server import SeedVRServer
|
| 20 |
+
|
| 21 |
+
# Inicializa o servidor SeedVR uma vez, se disponível
|
| 22 |
+
seedvr_inference_server = SeedVRServer() if SeedVRServer else None
|
| 23 |
+
|
| 24 |
+
# --- ESTADO DA SESSÃO ---
|
| 25 |
+
def create_initial_state():
|
| 26 |
+
return {
|
| 27 |
+
"low_res_video": None,
|
| 28 |
+
"low_res_latents": None,
|
| 29 |
+
"refined_video_ltx": None,
|
| 30 |
+
"refined_latents_ltx": None,
|
| 31 |
+
"used_seed": None
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# --- FUNÇÕES WRAPPER PARA A UI ---
|
| 35 |
+
|
| 36 |
+
def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
|
| 37 |
+
"""Executa a primeira etapa: geração de um vídeo base em baixa resolução."""
|
| 38 |
+
print("UI: Chamando generate_low")
|
| 39 |
+
if True:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
conditioning_items = []
|
| 42 |
if start_img:
|
|
|
|
| 43 |
num_frames_estimate = int(duration * 24)
|
| 44 |
+
items_list = [[start_img, 0, 1.0]]
|
| 45 |
+
conditioning_items = video_generation_service._prepare_condition_items(items_list, height, width, num_frames_estimate)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
|
| 48 |
+
used_seed = None if randomize_seed else seed
|
| 49 |
+
|
| 50 |
+
video_path, tensor_path, final_seed = video_generation_service.generate_low_resolution(
|
| 51 |
prompt=prompt, negative_prompt=neg_prompt,
|
| 52 |
+
height=height, width=width, duration_secs=duration,
|
| 53 |
+
guidance_scale=cfg, seed=used_seed,
|
| 54 |
+
conditioning_items=conditioning_items
|
|
|
|
| 55 |
)
|
| 56 |
|
| 57 |
+
new_state = {
|
| 58 |
+
"low_res_video": video_path,
|
| 59 |
+
"low_res_latents": tensor_path,
|
| 60 |
+
"refined_video_ltx": None,
|
| 61 |
+
"refined_latents_ltx": None,
|
| 62 |
+
"used_seed": final_seed
|
| 63 |
+
}
|
| 64 |
|
|
|
|
| 65 |
return video_path, new_state, gr.update(visible=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
def run_ltx_refinement(state, prompt, neg_prompt, cfg, progress=gr.Progress(track_tqdm=True)):
|
| 68 |
+
"""Executa o processo de refinamento e upscaling de textura com o pipeline LTX."""
|
| 69 |
+
print("UI: Chamando run_ltx_refinement (generate_upscale_denoise)")
|
| 70 |
+
|
| 71 |
+
if True:
|
| 72 |
video_path, tensor_path = video_generation_service.generate_upscale_denoise(
|
| 73 |
latents_path=state["low_res_latents"],
|
| 74 |
prompt=prompt,
|
| 75 |
negative_prompt=neg_prompt,
|
| 76 |
+
guidance_scale=cfg,
|
| 77 |
seed=state["used_seed"]
|
| 78 |
)
|
| 79 |
+
|
| 80 |
+
# Atualiza o estado com os novos artefatos refinados
|
| 81 |
state["refined_video_ltx"] = video_path
|
| 82 |
state["refined_latents_ltx"] = tensor_path
|
| 83 |
+
|
| 84 |
return video_path, state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
|
| 87 |
+
"""Executa o processo de upscaling com SeedVR."""
|
| 88 |
+
|
| 89 |
+
video_path = state["low_res_video"]
|
| 90 |
+
print(f"▶️ Iniciando processo de upscaling SeedVR para o vídeo: {video_path}")
|
| 91 |
+
|
| 92 |
+
if True:
|
| 93 |
+
def progress_wrapper(p, desc=""):
|
| 94 |
+
progress(p, desc=desc)
|
| 95 |
output_filepath = seedvr_inference_server.run_inference(
|
| 96 |
+
file_path=video_path, seed=seed, resolution=resolution,
|
| 97 |
batch_size=batch_size, fps=fps, progress=progress_wrapper
|
| 98 |
)
|
| 99 |
+
final_message = f"✅ Processo SeedVR concluído!\nVídeo salvo em: {output_filepath}"
|
| 100 |
+
return gr.update(value=output_filepath, interactive=True), gr.update(value=final_message, interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# --- DEFINIÇÃO DA INTERFACE GRADIO ---
|
| 103 |
+
with gr.Blocks() as demo:
|
| 104 |
+
gr.Markdown("# LTX Video - Geração e Pós-Produção por Etapas")
|
| 105 |
+
|
| 106 |
+
app_state = gr.State(value=create_initial_state())
|
| 107 |
+
|
| 108 |
+
# --- ETAPA 1: Geração Base ---
|
| 109 |
+
with gr.Row():
|
| 110 |
+
with gr.Column(scale=1):
|
| 111 |
+
gr.Markdown("### Etapa 1: Configurações de Geração")
|
| 112 |
+
prompt_input = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3)
|
| 113 |
+
neg_prompt_input = gr.Textbox(visible=False, label="Negative Prompt", value="worst quality, blurry, low quality, jittery", lines=2)
|
| 114 |
+
start_image = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload", "clipboard"])
|
| 115 |
|
| 116 |
+
with gr.Accordion("Parâmetros Avançados", open=False):
|
| 117 |
+
height_input = gr.Slider(label="Height", value=512, step=64, minimum=256, maximum=1024)
|
| 118 |
+
width_input = gr.Slider(label="Width", value=512, step=64, minimum=256, maximum=1024)
|
| 119 |
+
duration_input = gr.Slider(label="Duração (s)", value=8, step=0.5, minimum=1, maximum=16)
|
| 120 |
+
cfg_input = gr.Slider(label="Guidance Scale (CFG)", value=5.0, step=1, minimum=1, maximum=10.0)
|
| 121 |
+
seed_input = gr.Number(label="Seed", value=42, precision=0)
|
| 122 |
+
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 123 |
+
|
| 124 |
+
generate_low_btn = gr.Button("1. Gerar Vídeo Base (Low-Res)", variant="primary")
|
| 125 |
|
| 126 |
+
with gr.Column(scale=1):
|
| 127 |
+
gr.Markdown("### Vídeo Base Gerado")
|
| 128 |
+
low_res_video_output = gr.Video(label="O resultado da Etapa 1 aparecerá aqui", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
# --- ETAPA 2: Pós-Produção (no rodapé, em abas) ---
|
| 131 |
+
with gr.Group(visible=False) as post_prod_group:
|
| 132 |
+
gr.Markdown("<hr style='margin-top: 20px; margin-bottom: 20px;'>")
|
| 133 |
+
gr.Markdown("## Etapa 2: Pós-Produção")
|
| 134 |
+
gr.Markdown("Use o vídeo gerado acima como entrada para as ferramentas abaixo. **O prompt e a CFG da Etapa 1 serão reutilizados.**")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
with gr.Tabs():
|
| 137 |
+
# --- ABA LTX REFINEMENT (AGORA FUNCIONAL) ---
|
| 138 |
+
with gr.TabItem("🚀 Upscaler Textura (LTX)"):
|
| 139 |
with gr.Row():
|
| 140 |
with gr.Column(scale=1):
|
| 141 |
+
gr.Markdown("### Parâmetros de Refinamento")
|
| 142 |
+
gr.Markdown("Esta etapa reutiliza o prompt, o prompt negativo e a CFG da Etapa 1 para manter a consistência.")
|
| 143 |
+
ltx_refine_btn = gr.Button("Aplicar Refinamento de Textura LTX", variant="primary")
|
| 144 |
with gr.Column(scale=1):
|
| 145 |
+
gr.Markdown("### Resultado do Refinamento")
|
| 146 |
+
ltx_refined_video_output = gr.Video(label="Vídeo com Textura Refinada (LTX)", interactive=False)
|
| 147 |
+
|
| 148 |
+
# --- ABA SEEDVR UPSCALER ---
|
| 149 |
+
with gr.TabItem("✨ Upscaler SeedVR"):
|
|
|
|
|
|
|
| 150 |
with gr.Row():
|
| 151 |
with gr.Column(scale=1):
|
| 152 |
+
gr.Markdown("### Parâmetros do SeedVR")
|
| 153 |
+
seedvr_seed = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
|
| 154 |
+
seedvr_resolution = gr.Slider(minimum=720, maximum=1440, value=1072, step=8, label="Resolução Vertical (Altura)")
|
| 155 |
+
seedvr_batch_size = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
|
| 156 |
+
seedvr_fps_output = gr.Number(label="FPS de Saída (0 = original)", value=0)
|
| 157 |
+
run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
|
| 158 |
+
if not seedvr_inference_server:
|
| 159 |
+
gr.Markdown("<p style='color: red;'>Serviço SeedVR não disponível.</p>")
|
| 160 |
with gr.Column(scale=1):
|
| 161 |
+
gr.Markdown("### Resultado do Upscaling")
|
| 162 |
+
seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
|
| 163 |
+
seedvr_status_box = gr.Textbox(label="Status do Processamento", value="Aguardando...", lines=3, interactive=False)
|
| 164 |
|
| 165 |
+
# --- ABA MM-AUDIO ---
|
| 166 |
+
with gr.TabItem("🔊 Áudio (MM-Audio)"):
|
| 167 |
+
gr.Markdown("*(Funcionalidade futura para adicionar som aos vídeos)*")
|
| 168 |
|
| 169 |
+
# --- LÓGICA DE EVENTOS DA UI ---
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
# Botão da Etapa 1
|
| 172 |
+
generate_low_btn.click(
|
| 173 |
+
fn=run_generate_low,
|
| 174 |
+
inputs=[prompt_input, neg_prompt_input, start_image, height_input, width_input, duration_input, cfg_input, seed_input, randomize_seed],
|
| 175 |
+
outputs=[low_res_video_output, app_state, post_prod_group]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
)
|
| 177 |
|
| 178 |
+
# Botão da Aba LTX Refinement
|
| 179 |
+
ltx_refine_btn.click(
|
| 180 |
+
fn=run_ltx_refinement,
|
| 181 |
+
inputs=[app_state, prompt_input, neg_prompt_input, cfg_input],
|
| 182 |
+
outputs=[ltx_refined_video_output, app_state]
|
| 183 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
# Botão da Aba SeedVR
|
| 186 |
+
run_seedvr_button.click(
|
| 187 |
+
fn=run_seedvr_upscaling,
|
| 188 |
+
inputs=[app_state, seedvr_seed, seedvr_resolution, seedvr_batch_size, seedvr_fps_output],
|
| 189 |
+
outputs=[seedvr_video_output, seedvr_status_box]
|
| 190 |
+
)
|
| 191 |
|
| 192 |
if __name__ == "__main__":
|
| 193 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=True)
|
| 194 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
compose.yaml
CHANGED
|
@@ -1,26 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
services:
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
deploy:
|
| 5 |
resources:
|
| 6 |
reservations:
|
| 7 |
devices:
|
| 8 |
-
-
|
|
|
|
|
|
|
| 9 |
ports:
|
| 10 |
-
- "
|
| 11 |
-
environment:
|
| 12 |
-
GRADIO_SERVER_PORT: "7860"
|
| 13 |
-
HF_HUB_CACHE: "/data/.cache/huggingface/hub"
|
| 14 |
-
CKPT_ROOT: "/data/ckpt/VINCIE-3B"
|
| 15 |
-
VINCIE_ROOT: "/data/VINCIE"
|
| 16 |
volumes:
|
| 17 |
-
-
|
| 18 |
-
-
|
| 19 |
-
|
| 20 |
-
- vincie_repo:/data/VINCIE
|
| 21 |
volumes:
|
| 22 |
-
|
| 23 |
-
vincie_ckpt: {}
|
| 24 |
-
vincie_out: {}
|
| 25 |
-
vincie_repo: {}
|
| 26 |
-
|
|
|
|
| 1 |
+
# compose.yaml (Versão com VINCIE)
|
| 2 |
+
version: '3.8'
|
| 3 |
+
|
| 4 |
services:
|
| 5 |
+
aduc-sdr-app:
|
| 6 |
+
build: .
|
| 7 |
+
environment:
|
| 8 |
+
ADUC_LOG_LEVEL: "DEBUG"
|
| 9 |
+
image: aduc-sdr-videosuite:latest
|
| 10 |
+
# (deploy, resources... mantidos como antes)
|
| 11 |
+
ports:
|
| 12 |
+
- "7860:7860" # Porta para a UI principal (LTX + SeedVR)
|
| 13 |
+
- "7861:7861" # Porta para a nova UI do VINCIE
|
| 14 |
+
volumes:
|
| 15 |
+
# O volume 'aduc_data' agora armazena tudo: cache, modelos e repos.
|
| 16 |
+
- aduc_data:/data
|
| 17 |
+
- ./output:/app/output
|
| 18 |
+
# O entrypoint cuidará do setup na inicialização.
|
| 19 |
+
# O CMD padrão iniciará a UI principal. Para VINCIE, usaremos um comando diferente.
|
| 20 |
+
|
| 21 |
+
# Novo serviço para a interface do VINCIE
|
| 22 |
+
vince-ui:
|
| 23 |
+
image: aduc-sdr-videosuite:latest # Usa a mesma imagem já construída
|
| 24 |
+
command: python3 /app/app_vince.py # Sobrescreve o CMD padrão para iniciar a UI do VINCIE
|
| 25 |
deploy:
|
| 26 |
resources:
|
| 27 |
reservations:
|
| 28 |
devices:
|
| 29 |
+
- driver: nvidia
|
| 30 |
+
count: all
|
| 31 |
+
capabilities: [gpu]
|
| 32 |
ports:
|
| 33 |
+
- "7861:7861"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
volumes:
|
| 35 |
+
- aduc_data:/data
|
| 36 |
+
- ./output:/app/output
|
| 37 |
+
|
|
|
|
| 38 |
volumes:
|
| 39 |
+
aduc_data:
|
|
|
|
|
|
|
|
|
|
|
|
entrypoint.sh
CHANGED
|
@@ -1,21 +1,44 @@
|
|
| 1 |
-
#!/bin/
|
| 2 |
-
# entrypoint.sh - Executado como root para corrigir permissões.
|
| 3 |
set -e
|
| 4 |
|
| 5 |
-
echo "
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
|
| 20 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
exec "$@"
|
|
|
|
| 1 |
+
#!/bin/bash
|
|
|
|
| 2 |
set -e
|
| 3 |
|
| 4 |
+
echo "🚀 ADUC-SDR Entrypoint: Configurando o ambiente de execução..."
|
| 5 |
|
| 6 |
+
# --- Configuração de Performance (CPU & GPU) ---
|
| 7 |
+
NUM_VCPUS=$(nproc)
|
| 8 |
+
NUM_GPUS=$(nvidia-smi --query-gpu=count --format=csv,noheader | head -n 1 || echo 0)
|
| 9 |
+
echo " > Hardware: ${NUM_VCPUS} vCPUs, ${NUM_GPUS} GPUs"
|
| 10 |
+
if [[ ${NUM_GPUS} -gt 0 ]]; then
|
| 11 |
+
VCPUS_PER_GPU=$((NUM_VCPUS / NUM_GPUS))
|
| 12 |
+
THREADS_PER_PROCESS=$((VCPUS_PER_GPU / 2))
|
| 13 |
+
else
|
| 14 |
+
THREADS_PER_PROCESS=$((NUM_VCPUS / 2))
|
| 15 |
+
fi
|
| 16 |
+
MIN_THREADS=4; MAX_THREADS=16
|
| 17 |
+
if [[ ${THREADS_PER_PROCESS} -lt ${MIN_THREADS} ]]; then THREADS_PER_PROCESS=${MIN_THREADS}; fi
|
| 18 |
+
if [[ ${THREADS_PER_PROCESS} -gt ${MAX_THREADS} ]]; then THREADS_PER_PROCESS=${MAX_THREADS}; fi
|
| 19 |
+
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-${THREADS_PER_PROCESS}}
|
| 20 |
+
export MKL_NUM_THREADS=${MKL_NUM_THREADS:-${THREADS_PER_PROCESS}}
|
| 21 |
+
export MAX_JOBS=${MAX_JOBS:-${NUM_VCPUS}}
|
| 22 |
+
export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-"max_split_size_mb:512"}
|
| 23 |
+
export NVIDIA_TF32_OVERRIDE=${NVIDIA_TF32_OVERRIDE:-1}
|
| 24 |
|
| 25 |
+
# --- Configuração de Depuração e Logging ---
|
| 26 |
+
export ADUC_LOG_LEVEL=${ADUC_LOG_LEVEL:-"INFO"}
|
| 27 |
+
export CUDA_LAUNCH_BLOCKING=${CUDA_LAUNCH_BLOCKING:-0}
|
| 28 |
+
export PYTHONFAULTHANDLER=1
|
| 29 |
+
export GRADIO_DEBUG=${GRADIO_DEBUG:-"False"}
|
| 30 |
|
| 31 |
+
echo " > Performance: OMP_NUM_THREADS=${OMP_NUM_THREADS}, MKL_NUM_THREADS=${MKL_NUM_THREADS}"
|
| 32 |
+
echo " > Depuração: ADUC_LOG_LEVEL=${ADUC_LOG_LEVEL}, CUDA_LAUNCH_BLOCKING=${CUDA_LAUNCH_BLOCKING}"
|
| 33 |
+
echo ""
|
| 34 |
+
echo ""
|
| 35 |
|
| 36 |
+
#/bin/bash /app/info.sh
|
| 37 |
|
| 38 |
+
# --- Setup de Dependências ---
|
| 39 |
+
echo " > Verificando dependências com setup.py..."
|
| 40 |
+
python3 /app/setup.py
|
| 41 |
+
|
| 42 |
+
echo "---------------------------------------------------------"
|
| 43 |
+
echo "🔥 Ambiente configurado. Iniciando o comando principal: $@"
|
| 44 |
exec "$@"
|
pipeline_ltx_video (3).py
ADDED
|
@@ -0,0 +1,1895 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py
|
| 2 |
+
import copy
|
| 3 |
+
import inspect
|
| 4 |
+
import math
|
| 5 |
+
import re
|
| 6 |
+
from contextlib import nullcontext
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 13 |
+
from diffusers.models import AutoencoderKL
|
| 14 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 15 |
+
from diffusers.schedulers import DPMSolverMultistepScheduler
|
| 16 |
+
from diffusers.utils import deprecate, logging
|
| 17 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 18 |
+
from einops import rearrange
|
| 19 |
+
from transformers import (
|
| 20 |
+
T5EncoderModel,
|
| 21 |
+
T5Tokenizer,
|
| 22 |
+
AutoModelForCausalLM,
|
| 23 |
+
AutoProcessor,
|
| 24 |
+
AutoTokenizer,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from ltx_video.models.autoencoders.causal_video_autoencoder import (
|
| 28 |
+
CausalVideoAutoencoder,
|
| 29 |
+
)
|
| 30 |
+
from ltx_video.models.autoencoders.vae_encode import (
|
| 31 |
+
get_vae_size_scale_factor,
|
| 32 |
+
latent_to_pixel_coords,
|
| 33 |
+
vae_decode,
|
| 34 |
+
vae_encode,
|
| 35 |
+
)
|
| 36 |
+
from ltx_video.models.transformers.symmetric_patchifier import Patchifier
|
| 37 |
+
from ltx_video.models.transformers.transformer3d import Transformer3DModel
|
| 38 |
+
from ltx_video.schedulers.rf import TimestepShifter
|
| 39 |
+
from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
|
| 40 |
+
from ltx_video.utils.prompt_enhance_utils import generate_cinematic_prompt
|
| 41 |
+
from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
|
| 42 |
+
from ltx_video.models.autoencoders.vae_encode import (
|
| 43 |
+
un_normalize_latents,
|
| 44 |
+
normalize_latents,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
ASPECT_RATIO_1024_BIN = {
|
| 52 |
+
"0.25": [512.0, 2048.0],
|
| 53 |
+
"0.28": [512.0, 1856.0],
|
| 54 |
+
"0.32": [576.0, 1792.0],
|
| 55 |
+
"0.33": [576.0, 1728.0],
|
| 56 |
+
"0.35": [576.0, 1664.0],
|
| 57 |
+
"0.4": [640.0, 1600.0],
|
| 58 |
+
"0.42": [640.0, 1536.0],
|
| 59 |
+
"0.48": [704.0, 1472.0],
|
| 60 |
+
"0.5": [704.0, 1408.0],
|
| 61 |
+
"0.52": [704.0, 1344.0],
|
| 62 |
+
"0.57": [768.0, 1344.0],
|
| 63 |
+
"0.6": [768.0, 1280.0],
|
| 64 |
+
"0.68": [832.0, 1216.0],
|
| 65 |
+
"0.72": [832.0, 1152.0],
|
| 66 |
+
"0.78": [896.0, 1152.0],
|
| 67 |
+
"0.82": [896.0, 1088.0],
|
| 68 |
+
"0.88": [960.0, 1088.0],
|
| 69 |
+
"0.94": [960.0, 1024.0],
|
| 70 |
+
"1.0": [1024.0, 1024.0],
|
| 71 |
+
"1.07": [1024.0, 960.0],
|
| 72 |
+
"1.13": [1088.0, 960.0],
|
| 73 |
+
"1.21": [1088.0, 896.0],
|
| 74 |
+
"1.29": [1152.0, 896.0],
|
| 75 |
+
"1.38": [1152.0, 832.0],
|
| 76 |
+
"1.46": [1216.0, 832.0],
|
| 77 |
+
"1.67": [1280.0, 768.0],
|
| 78 |
+
"1.75": [1344.0, 768.0],
|
| 79 |
+
"2.0": [1408.0, 704.0],
|
| 80 |
+
"2.09": [1472.0, 704.0],
|
| 81 |
+
"2.4": [1536.0, 640.0],
|
| 82 |
+
"2.5": [1600.0, 640.0],
|
| 83 |
+
"3.0": [1728.0, 576.0],
|
| 84 |
+
"4.0": [2048.0, 512.0],
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
ASPECT_RATIO_512_BIN = {
|
| 88 |
+
"0.25": [256.0, 1024.0],
|
| 89 |
+
"0.28": [256.0, 928.0],
|
| 90 |
+
"0.32": [288.0, 896.0],
|
| 91 |
+
"0.33": [288.0, 864.0],
|
| 92 |
+
"0.35": [288.0, 832.0],
|
| 93 |
+
"0.4": [320.0, 800.0],
|
| 94 |
+
"0.42": [320.0, 768.0],
|
| 95 |
+
"0.48": [352.0, 736.0],
|
| 96 |
+
"0.5": [352.0, 704.0],
|
| 97 |
+
"0.52": [352.0, 672.0],
|
| 98 |
+
"0.57": [384.0, 672.0],
|
| 99 |
+
"0.6": [384.0, 640.0],
|
| 100 |
+
"0.68": [416.0, 608.0],
|
| 101 |
+
"0.72": [416.0, 576.0],
|
| 102 |
+
"0.78": [448.0, 576.0],
|
| 103 |
+
"0.82": [448.0, 544.0],
|
| 104 |
+
"0.88": [480.0, 544.0],
|
| 105 |
+
"0.94": [480.0, 512.0],
|
| 106 |
+
"1.0": [512.0, 512.0],
|
| 107 |
+
"1.07": [512.0, 480.0],
|
| 108 |
+
"1.13": [544.0, 480.0],
|
| 109 |
+
"1.21": [544.0, 448.0],
|
| 110 |
+
"1.29": [576.0, 448.0],
|
| 111 |
+
"1.38": [576.0, 416.0],
|
| 112 |
+
"1.46": [608.0, 416.0],
|
| 113 |
+
"1.67": [640.0, 384.0],
|
| 114 |
+
"1.75": [672.0, 384.0],
|
| 115 |
+
"2.0": [704.0, 352.0],
|
| 116 |
+
"2.09": [736.0, 352.0],
|
| 117 |
+
"2.4": [768.0, 320.0],
|
| 118 |
+
"2.5": [800.0, 320.0],
|
| 119 |
+
"3.0": [864.0, 288.0],
|
| 120 |
+
"4.0": [1024.0, 256.0],
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
| 125 |
+
def retrieve_timesteps(
|
| 126 |
+
scheduler,
|
| 127 |
+
num_inference_steps: Optional[int] = None,
|
| 128 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 129 |
+
timesteps: Optional[List[int]] = None,
|
| 130 |
+
skip_initial_inference_steps: int = 0,
|
| 131 |
+
skip_final_inference_steps: int = 0,
|
| 132 |
+
**kwargs,
|
| 133 |
+
):
|
| 134 |
+
"""
|
| 135 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 136 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
scheduler (`SchedulerMixin`):
|
| 140 |
+
The scheduler to get timesteps from.
|
| 141 |
+
num_inference_steps (`int`):
|
| 142 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
| 143 |
+
`timesteps` must be `None`.
|
| 144 |
+
device (`str` or `torch.device`, *optional*):
|
| 145 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 146 |
+
timesteps (`List[int]`, *optional*):
|
| 147 |
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
| 148 |
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
| 149 |
+
must be `None`.
|
| 150 |
+
max_timestep ('float', *optional*, defaults to 1.0):
|
| 151 |
+
The initial noising level for image-to-image/video-to-video. The list if timestamps will be
|
| 152 |
+
truncated to start with a timestamp greater or equal to this.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 156 |
+
second element is the number of inference steps.
|
| 157 |
+
"""
|
| 158 |
+
if timesteps is not None:
|
| 159 |
+
accepts_timesteps = "timesteps" in set(
|
| 160 |
+
inspect.signature(scheduler.set_timesteps).parameters.keys()
|
| 161 |
+
)
|
| 162 |
+
if not accepts_timesteps:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 165 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 166 |
+
)
|
| 167 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 168 |
+
timesteps = scheduler.timesteps
|
| 169 |
+
num_inference_steps = len(timesteps)
|
| 170 |
+
else:
|
| 171 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 172 |
+
timesteps = scheduler.timesteps
|
| 173 |
+
|
| 174 |
+
if (
|
| 175 |
+
skip_initial_inference_steps < 0
|
| 176 |
+
or skip_final_inference_steps < 0
|
| 177 |
+
or skip_initial_inference_steps + skip_final_inference_steps
|
| 178 |
+
>= num_inference_steps
|
| 179 |
+
):
|
| 180 |
+
raise ValueError(
|
| 181 |
+
"invalid skip inference step values: must be non-negative and the sum of skip_initial_inference_steps and skip_final_inference_steps must be less than the number of inference steps"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
timesteps = timesteps[
|
| 185 |
+
skip_initial_inference_steps : len(timesteps) - skip_final_inference_steps
|
| 186 |
+
]
|
| 187 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 188 |
+
num_inference_steps = len(timesteps)
|
| 189 |
+
|
| 190 |
+
return timesteps, num_inference_steps
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@dataclass
|
| 194 |
+
class ConditioningItem:
|
| 195 |
+
"""
|
| 196 |
+
Defines a single frame-conditioning item - a single frame or a sequence of frames.
|
| 197 |
+
|
| 198 |
+
Attributes:
|
| 199 |
+
media_item (torch.Tensor): shape=(b, 3, f, h, w). The media item to condition on.
|
| 200 |
+
media_frame_number (int): The start-frame number of the media item in the generated video.
|
| 201 |
+
conditioning_strength (float): The strength of the conditioning (1.0 = full conditioning).
|
| 202 |
+
media_x (Optional[int]): Optional left x coordinate of the media item in the generated frame.
|
| 203 |
+
media_y (Optional[int]): Optional top y coordinate of the media item in the generated frame.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
media_item: torch.Tensor
|
| 207 |
+
media_frame_number: int
|
| 208 |
+
conditioning_strength: float
|
| 209 |
+
media_x: Optional[int] = None
|
| 210 |
+
media_y: Optional[int] = None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class LTXVideoPipeline(DiffusionPipeline):
|
| 214 |
+
r"""
|
| 215 |
+
Pipeline for text-to-image generation using LTX-Video.
|
| 216 |
+
|
| 217 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
| 218 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
vae ([`AutoencoderKL`]):
|
| 222 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 223 |
+
text_encoder ([`T5EncoderModel`]):
|
| 224 |
+
Frozen text-encoder. This uses
|
| 225 |
+
[T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
|
| 226 |
+
[t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
|
| 227 |
+
tokenizer (`T5Tokenizer`):
|
| 228 |
+
Tokenizer of class
|
| 229 |
+
[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
|
| 230 |
+
transformer ([`Transformer2DModel`]):
|
| 231 |
+
A text conditioned `Transformer2DModel` to denoise the encoded image latents.
|
| 232 |
+
scheduler ([`SchedulerMixin`]):
|
| 233 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
bad_punct_regex = re.compile(
|
| 237 |
+
r"["
|
| 238 |
+
+ "#®•©™&@·º½¾¿¡§~"
|
| 239 |
+
+ r"\)"
|
| 240 |
+
+ r"\("
|
| 241 |
+
+ r"\]"
|
| 242 |
+
+ r"\["
|
| 243 |
+
+ r"\}"
|
| 244 |
+
+ r"\{"
|
| 245 |
+
+ r"\|"
|
| 246 |
+
+ "\\"
|
| 247 |
+
+ r"\/"
|
| 248 |
+
+ r"\*"
|
| 249 |
+
+ r"]{1,}"
|
| 250 |
+
) # noqa
|
| 251 |
+
|
| 252 |
+
_optional_components = [
|
| 253 |
+
"tokenizer",
|
| 254 |
+
"text_encoder",
|
| 255 |
+
"prompt_enhancer_image_caption_model",
|
| 256 |
+
"prompt_enhancer_image_caption_processor",
|
| 257 |
+
"prompt_enhancer_llm_model",
|
| 258 |
+
"prompt_enhancer_llm_tokenizer",
|
| 259 |
+
]
|
| 260 |
+
model_cpu_offload_seq = "prompt_enhancer_image_caption_model->prompt_enhancer_llm_model->text_encoder->transformer->vae"
|
| 261 |
+
|
| 262 |
+
def __init__(
|
| 263 |
+
self,
|
| 264 |
+
tokenizer: T5Tokenizer,
|
| 265 |
+
text_encoder: T5EncoderModel,
|
| 266 |
+
vae: AutoencoderKL,
|
| 267 |
+
transformer: Transformer3DModel,
|
| 268 |
+
scheduler: DPMSolverMultistepScheduler,
|
| 269 |
+
patchifier: Patchifier,
|
| 270 |
+
prompt_enhancer_image_caption_model: AutoModelForCausalLM,
|
| 271 |
+
prompt_enhancer_image_caption_processor: AutoProcessor,
|
| 272 |
+
prompt_enhancer_llm_model: AutoModelForCausalLM,
|
| 273 |
+
prompt_enhancer_llm_tokenizer: AutoTokenizer,
|
| 274 |
+
allowed_inference_steps: Optional[List[float]] = None,
|
| 275 |
+
):
|
| 276 |
+
super().__init__()
|
| 277 |
+
|
| 278 |
+
self.register_modules(
|
| 279 |
+
tokenizer=tokenizer,
|
| 280 |
+
text_encoder=text_encoder,
|
| 281 |
+
vae=vae,
|
| 282 |
+
transformer=transformer,
|
| 283 |
+
scheduler=scheduler,
|
| 284 |
+
patchifier=patchifier,
|
| 285 |
+
prompt_enhancer_image_caption_model=prompt_enhancer_image_caption_model,
|
| 286 |
+
prompt_enhancer_image_caption_processor=prompt_enhancer_image_caption_processor,
|
| 287 |
+
prompt_enhancer_llm_model=prompt_enhancer_llm_model,
|
| 288 |
+
prompt_enhancer_llm_tokenizer=prompt_enhancer_llm_tokenizer,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
self.video_scale_factor, self.vae_scale_factor, _ = get_vae_size_scale_factor(
|
| 292 |
+
self.vae
|
| 293 |
+
)
|
| 294 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 295 |
+
|
| 296 |
+
self.allowed_inference_steps = allowed_inference_steps
|
| 297 |
+
|
| 298 |
+
def mask_text_embeddings(self, emb, mask):
|
| 299 |
+
if emb.shape[0] == 1:
|
| 300 |
+
keep_index = mask.sum().item()
|
| 301 |
+
return emb[:, :, :keep_index, :], keep_index
|
| 302 |
+
else:
|
| 303 |
+
masked_feature = emb * mask[:, None, :, None]
|
| 304 |
+
return masked_feature, emb.shape[2]
|
| 305 |
+
|
| 306 |
+
# Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_prompt
|
| 307 |
+
def encode_prompt(
|
| 308 |
+
self,
|
| 309 |
+
prompt: Union[str, List[str]],
|
| 310 |
+
do_classifier_free_guidance: bool = True,
|
| 311 |
+
negative_prompt: str = "",
|
| 312 |
+
num_images_per_prompt: int = 1,
|
| 313 |
+
device: Optional[torch.device] = None,
|
| 314 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 315 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 316 |
+
prompt_attention_mask: Optional[torch.FloatTensor] = None,
|
| 317 |
+
negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
|
| 318 |
+
text_encoder_max_tokens: int = 256,
|
| 319 |
+
**kwargs,
|
| 320 |
+
):
|
| 321 |
+
r"""
|
| 322 |
+
Encodes the prompt into text encoder hidden states.
|
| 323 |
+
|
| 324 |
+
Args:
|
| 325 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 326 |
+
prompt to be encoded
|
| 327 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 328 |
+
The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
|
| 329 |
+
instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
|
| 330 |
+
This should be "".
|
| 331 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 332 |
+
whether to use classifier free guidance or not
|
| 333 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 334 |
+
number of images that should be generated per prompt
|
| 335 |
+
device: (`torch.device`, *optional*):
|
| 336 |
+
torch device to place the resulting embeddings on
|
| 337 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 338 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 339 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 340 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 341 |
+
Pre-generated negative text embeddings.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
if "mask_feature" in kwargs:
|
| 345 |
+
deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
|
| 346 |
+
deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
|
| 347 |
+
|
| 348 |
+
if device is None:
|
| 349 |
+
device = self._execution_device
|
| 350 |
+
|
| 351 |
+
if prompt is not None and isinstance(prompt, str):
|
| 352 |
+
batch_size = 1
|
| 353 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 354 |
+
batch_size = len(prompt)
|
| 355 |
+
else:
|
| 356 |
+
batch_size = prompt_embeds.shape[0]
|
| 357 |
+
|
| 358 |
+
# See Section 3.1. of the paper.
|
| 359 |
+
max_length = (
|
| 360 |
+
text_encoder_max_tokens # TPU supports only lengths multiple of 128
|
| 361 |
+
)
|
| 362 |
+
if prompt_embeds is None:
|
| 363 |
+
assert (
|
| 364 |
+
self.text_encoder is not None
|
| 365 |
+
), "You should provide either prompt_embeds or self.text_encoder should not be None,"
|
| 366 |
+
text_enc_device = next(self.text_encoder.parameters()).device
|
| 367 |
+
prompt = self._text_preprocessing(prompt)
|
| 368 |
+
text_inputs = self.tokenizer(
|
| 369 |
+
prompt,
|
| 370 |
+
padding="max_length",
|
| 371 |
+
max_length=max_length,
|
| 372 |
+
truncation=True,
|
| 373 |
+
add_special_tokens=True,
|
| 374 |
+
return_tensors="pt",
|
| 375 |
+
)
|
| 376 |
+
text_input_ids = text_inputs.input_ids
|
| 377 |
+
untruncated_ids = self.tokenizer(
|
| 378 |
+
prompt, padding="longest", return_tensors="pt"
|
| 379 |
+
).input_ids
|
| 380 |
+
|
| 381 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[
|
| 382 |
+
-1
|
| 383 |
+
] and not torch.equal(text_input_ids, untruncated_ids):
|
| 384 |
+
removed_text = self.tokenizer.batch_decode(
|
| 385 |
+
untruncated_ids[:, max_length - 1 : -1]
|
| 386 |
+
)
|
| 387 |
+
logger.warning(
|
| 388 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 389 |
+
f" {max_length} tokens: {removed_text}"
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
prompt_attention_mask = text_inputs.attention_mask
|
| 393 |
+
prompt_attention_mask = prompt_attention_mask.to(text_enc_device)
|
| 394 |
+
prompt_attention_mask = prompt_attention_mask.to(device)
|
| 395 |
+
|
| 396 |
+
prompt_embeds = self.text_encoder(
|
| 397 |
+
text_input_ids.to(text_enc_device), attention_mask=prompt_attention_mask
|
| 398 |
+
)
|
| 399 |
+
prompt_embeds = prompt_embeds[0]
|
| 400 |
+
|
| 401 |
+
if self.text_encoder is not None:
|
| 402 |
+
dtype = self.text_encoder.dtype
|
| 403 |
+
elif self.transformer is not None:
|
| 404 |
+
dtype = self.transformer.dtype
|
| 405 |
+
else:
|
| 406 |
+
dtype = None
|
| 407 |
+
|
| 408 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 409 |
+
|
| 410 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 411 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
| 412 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 413 |
+
prompt_embeds = prompt_embeds.view(
|
| 414 |
+
bs_embed * num_images_per_prompt, seq_len, -1
|
| 415 |
+
)
|
| 416 |
+
prompt_attention_mask = prompt_attention_mask.repeat(1, num_images_per_prompt)
|
| 417 |
+
prompt_attention_mask = prompt_attention_mask.view(
|
| 418 |
+
bs_embed * num_images_per_prompt, -1
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# get unconditional embeddings for classifier free guidance
|
| 422 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 423 |
+
uncond_tokens = self._text_preprocessing(negative_prompt)
|
| 424 |
+
uncond_tokens = uncond_tokens * batch_size
|
| 425 |
+
max_length = prompt_embeds.shape[1]
|
| 426 |
+
uncond_input = self.tokenizer(
|
| 427 |
+
uncond_tokens,
|
| 428 |
+
padding="max_length",
|
| 429 |
+
max_length=max_length,
|
| 430 |
+
truncation=True,
|
| 431 |
+
return_attention_mask=True,
|
| 432 |
+
add_special_tokens=True,
|
| 433 |
+
return_tensors="pt",
|
| 434 |
+
)
|
| 435 |
+
negative_prompt_attention_mask = uncond_input.attention_mask
|
| 436 |
+
negative_prompt_attention_mask = negative_prompt_attention_mask.to(
|
| 437 |
+
text_enc_device
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
negative_prompt_embeds = self.text_encoder(
|
| 441 |
+
uncond_input.input_ids.to(text_enc_device),
|
| 442 |
+
attention_mask=negative_prompt_attention_mask,
|
| 443 |
+
)
|
| 444 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 445 |
+
|
| 446 |
+
if do_classifier_free_guidance:
|
| 447 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 448 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 449 |
+
|
| 450 |
+
negative_prompt_embeds = negative_prompt_embeds.to(
|
| 451 |
+
dtype=dtype, device=device
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(
|
| 455 |
+
1, num_images_per_prompt, 1
|
| 456 |
+
)
|
| 457 |
+
negative_prompt_embeds = negative_prompt_embeds.view(
|
| 458 |
+
batch_size * num_images_per_prompt, seq_len, -1
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(
|
| 462 |
+
1, num_images_per_prompt
|
| 463 |
+
)
|
| 464 |
+
negative_prompt_attention_mask = negative_prompt_attention_mask.view(
|
| 465 |
+
bs_embed * num_images_per_prompt, -1
|
| 466 |
+
)
|
| 467 |
+
else:
|
| 468 |
+
negative_prompt_embeds = None
|
| 469 |
+
negative_prompt_attention_mask = None
|
| 470 |
+
|
| 471 |
+
return (
|
| 472 |
+
prompt_embeds,
|
| 473 |
+
prompt_attention_mask,
|
| 474 |
+
negative_prompt_embeds,
|
| 475 |
+
negative_prompt_attention_mask,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 479 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 480 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 481 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 482 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 483 |
+
# and should be between [0, 1]
|
| 484 |
+
|
| 485 |
+
accepts_eta = "eta" in set(
|
| 486 |
+
inspect.signature(self.scheduler.step).parameters.keys()
|
| 487 |
+
)
|
| 488 |
+
extra_step_kwargs = {}
|
| 489 |
+
if accepts_eta:
|
| 490 |
+
extra_step_kwargs["eta"] = eta
|
| 491 |
+
|
| 492 |
+
# check if the scheduler accepts generator
|
| 493 |
+
accepts_generator = "generator" in set(
|
| 494 |
+
inspect.signature(self.scheduler.step).parameters.keys()
|
| 495 |
+
)
|
| 496 |
+
if accepts_generator:
|
| 497 |
+
extra_step_kwargs["generator"] = generator
|
| 498 |
+
return extra_step_kwargs
|
| 499 |
+
|
| 500 |
+
def check_inputs(
|
| 501 |
+
self,
|
| 502 |
+
prompt,
|
| 503 |
+
height,
|
| 504 |
+
width,
|
| 505 |
+
negative_prompt,
|
| 506 |
+
prompt_embeds=None,
|
| 507 |
+
negative_prompt_embeds=None,
|
| 508 |
+
prompt_attention_mask=None,
|
| 509 |
+
negative_prompt_attention_mask=None,
|
| 510 |
+
enhance_prompt=False,
|
| 511 |
+
):
|
| 512 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 513 |
+
raise ValueError(
|
| 514 |
+
f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
if prompt is not None and prompt_embeds is not None:
|
| 518 |
+
raise ValueError(
|
| 519 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 520 |
+
" only forward one of the two."
|
| 521 |
+
)
|
| 522 |
+
elif prompt is None and prompt_embeds is None:
|
| 523 |
+
raise ValueError(
|
| 524 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 525 |
+
)
|
| 526 |
+
elif prompt is not None and (
|
| 527 |
+
not isinstance(prompt, str) and not isinstance(prompt, list)
|
| 528 |
+
):
|
| 529 |
+
raise ValueError(
|
| 530 |
+
f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
if prompt is not None and negative_prompt_embeds is not None:
|
| 534 |
+
raise ValueError(
|
| 535 |
+
f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
|
| 536 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 540 |
+
raise ValueError(
|
| 541 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 542 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
if prompt_embeds is not None and prompt_attention_mask is None:
|
| 546 |
+
raise ValueError(
|
| 547 |
+
"Must provide `prompt_attention_mask` when specifying `prompt_embeds`."
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
if (
|
| 551 |
+
negative_prompt_embeds is not None
|
| 552 |
+
and negative_prompt_attention_mask is None
|
| 553 |
+
):
|
| 554 |
+
raise ValueError(
|
| 555 |
+
"Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`."
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 559 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 560 |
+
raise ValueError(
|
| 561 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 562 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 563 |
+
f" {negative_prompt_embeds.shape}."
|
| 564 |
+
)
|
| 565 |
+
if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
|
| 566 |
+
raise ValueError(
|
| 567 |
+
"`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
|
| 568 |
+
f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
|
| 569 |
+
f" {negative_prompt_attention_mask.shape}."
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
if enhance_prompt:
|
| 573 |
+
assert (
|
| 574 |
+
self.prompt_enhancer_image_caption_model is not None
|
| 575 |
+
), "Image caption model must be initialized if enhance_prompt is True"
|
| 576 |
+
assert (
|
| 577 |
+
self.prompt_enhancer_image_caption_processor is not None
|
| 578 |
+
), "Image caption processor must be initialized if enhance_prompt is True"
|
| 579 |
+
assert (
|
| 580 |
+
self.prompt_enhancer_llm_model is not None
|
| 581 |
+
), "Text prompt enhancer model must be initialized if enhance_prompt is True"
|
| 582 |
+
assert (
|
| 583 |
+
self.prompt_enhancer_llm_tokenizer is not None
|
| 584 |
+
), "Text prompt enhancer tokenizer must be initialized if enhance_prompt is True"
|
| 585 |
+
|
| 586 |
+
def _text_preprocessing(self, text):
|
| 587 |
+
if not isinstance(text, (tuple, list)):
|
| 588 |
+
text = [text]
|
| 589 |
+
|
| 590 |
+
def process(text: str):
|
| 591 |
+
text = text.strip()
|
| 592 |
+
return text
|
| 593 |
+
|
| 594 |
+
return [process(t) for t in text]
|
| 595 |
+
|
| 596 |
+
@staticmethod
|
| 597 |
+
def add_noise_to_image_conditioning_latents(
|
| 598 |
+
t: float,
|
| 599 |
+
init_latents: torch.Tensor,
|
| 600 |
+
latents: torch.Tensor,
|
| 601 |
+
noise_scale: float,
|
| 602 |
+
conditioning_mask: torch.Tensor,
|
| 603 |
+
generator,
|
| 604 |
+
eps=1e-6,
|
| 605 |
+
):
|
| 606 |
+
"""
|
| 607 |
+
Add timestep-dependent noise to the hard-conditioning latents.
|
| 608 |
+
This helps with motion continuity, especially when conditioned on a single frame.
|
| 609 |
+
"""
|
| 610 |
+
noise = randn_tensor(
|
| 611 |
+
latents.shape,
|
| 612 |
+
generator=generator,
|
| 613 |
+
device=latents.device,
|
| 614 |
+
dtype=latents.dtype,
|
| 615 |
+
)
|
| 616 |
+
# Add noise only to hard-conditioning latents (conditioning_mask = 1.0)
|
| 617 |
+
need_to_noise = (conditioning_mask > 1.0 - eps).unsqueeze(-1)
|
| 618 |
+
noised_latents = init_latents + noise_scale * noise * (t**2)
|
| 619 |
+
latents = torch.where(need_to_noise, noised_latents, latents)
|
| 620 |
+
return latents
|
| 621 |
+
|
| 622 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 623 |
+
def prepare_latents(
|
| 624 |
+
self,
|
| 625 |
+
latents: torch.Tensor | None,
|
| 626 |
+
media_items: torch.Tensor | None,
|
| 627 |
+
timestep: float,
|
| 628 |
+
latent_shape: torch.Size | Tuple[Any, ...],
|
| 629 |
+
dtype: torch.dtype,
|
| 630 |
+
device: torch.device,
|
| 631 |
+
generator: torch.Generator | List[torch.Generator],
|
| 632 |
+
vae_per_channel_normalize: bool = True,
|
| 633 |
+
):
|
| 634 |
+
"""
|
| 635 |
+
Prepare the initial latent tensor to be denoised.
|
| 636 |
+
The latents are either pure noise or a noised version of the encoded media items.
|
| 637 |
+
Args:
|
| 638 |
+
latents (`torch.FloatTensor` or `None`):
|
| 639 |
+
The latents to use (provided by the user) or `None` to create new latents.
|
| 640 |
+
media_items (`torch.FloatTensor` or `None`):
|
| 641 |
+
An image or video to be updated using img2img or vid2vid. The media item is encoded and noised.
|
| 642 |
+
timestep (`float`):
|
| 643 |
+
The timestep to noise the encoded media_items to.
|
| 644 |
+
latent_shape (`torch.Size`):
|
| 645 |
+
The target latent shape.
|
| 646 |
+
dtype (`torch.dtype`):
|
| 647 |
+
The target dtype.
|
| 648 |
+
device (`torch.device`):
|
| 649 |
+
The target device.
|
| 650 |
+
generator (`torch.Generator` or `List[torch.Generator]`):
|
| 651 |
+
Generator(s) to be used for the noising process.
|
| 652 |
+
vae_per_channel_normalize ('bool'):
|
| 653 |
+
When encoding the media_items, whether to normalize the latents per-channel.
|
| 654 |
+
Returns:
|
| 655 |
+
`torch.FloatTensor`: The latents to be used for the denoising process. This is a tensor of shape
|
| 656 |
+
(batch_size, num_channels, height, width).
|
| 657 |
+
"""
|
| 658 |
+
if isinstance(generator, list) and len(generator) != latent_shape[0]:
|
| 659 |
+
raise ValueError(
|
| 660 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 661 |
+
f" size of {latent_shape[0]}. Make sure the batch size matches the length of the generators."
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
# Initialize the latents with the given latents or encoded media item, if provided
|
| 665 |
+
assert (
|
| 666 |
+
latents is None or media_items is None
|
| 667 |
+
), "Cannot provide both latents and media_items. Please provide only one of the two."
|
| 668 |
+
|
| 669 |
+
assert (
|
| 670 |
+
latents is None and media_items is None or timestep < 1.0
|
| 671 |
+
), "Input media_item or latents are provided, but they will be replaced with noise."
|
| 672 |
+
|
| 673 |
+
if media_items is not None:
|
| 674 |
+
latents = vae_encode(
|
| 675 |
+
media_items.to(dtype=self.vae.dtype, device=self.vae.device),
|
| 676 |
+
self.vae,
|
| 677 |
+
vae_per_channel_normalize=vae_per_channel_normalize,
|
| 678 |
+
)
|
| 679 |
+
if latents is not None:
|
| 680 |
+
assert (
|
| 681 |
+
latents.shape == latent_shape
|
| 682 |
+
), f"Latents have to be of shape {latent_shape} but are {latents.shape}."
|
| 683 |
+
latents = latents.to(device=device, dtype=dtype)
|
| 684 |
+
|
| 685 |
+
# For backward compatibility, generate in the "patchified" shape and rearrange
|
| 686 |
+
b, c, f, h, w = latent_shape
|
| 687 |
+
noise = randn_tensor(
|
| 688 |
+
(b, f * h * w, c), generator=generator, device=device, dtype=dtype
|
| 689 |
+
)
|
| 690 |
+
noise = rearrange(noise, "b (f h w) c -> b c f h w", f=f, h=h, w=w)
|
| 691 |
+
|
| 692 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 693 |
+
noise = noise * self.scheduler.init_noise_sigma
|
| 694 |
+
|
| 695 |
+
if latents is None:
|
| 696 |
+
latents = noise
|
| 697 |
+
else:
|
| 698 |
+
# Noise the latents to the required (first) timestep
|
| 699 |
+
latents = timestep * noise + (1 - timestep) * latents
|
| 700 |
+
|
| 701 |
+
return latents
|
| 702 |
+
|
| 703 |
+
@staticmethod
|
| 704 |
+
def classify_height_width_bin(
|
| 705 |
+
height: int, width: int, ratios: dict
|
| 706 |
+
) -> Tuple[int, int]:
|
| 707 |
+
"""Returns binned height and width."""
|
| 708 |
+
ar = float(height / width)
|
| 709 |
+
closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
|
| 710 |
+
default_hw = ratios[closest_ratio]
|
| 711 |
+
return int(default_hw[0]), int(default_hw[1])
|
| 712 |
+
|
| 713 |
+
@staticmethod
|
| 714 |
+
def resize_and_crop_tensor(
|
| 715 |
+
samples: torch.Tensor, new_width: int, new_height: int
|
| 716 |
+
) -> torch.Tensor:
|
| 717 |
+
n_frames, orig_height, orig_width = samples.shape[-3:]
|
| 718 |
+
|
| 719 |
+
# Check if resizing is needed
|
| 720 |
+
if orig_height != new_height or orig_width != new_width:
|
| 721 |
+
ratio = max(new_height / orig_height, new_width / orig_width)
|
| 722 |
+
resized_width = int(orig_width * ratio)
|
| 723 |
+
resized_height = int(orig_height * ratio)
|
| 724 |
+
|
| 725 |
+
# Resize
|
| 726 |
+
samples = LTXVideoPipeline.resize_tensor(
|
| 727 |
+
samples, resized_height, resized_width
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
# Center Crop
|
| 731 |
+
start_x = (resized_width - new_width) // 2
|
| 732 |
+
end_x = start_x + new_width
|
| 733 |
+
start_y = (resized_height - new_height) // 2
|
| 734 |
+
end_y = start_y + new_height
|
| 735 |
+
samples = samples[..., start_y:end_y, start_x:end_x]
|
| 736 |
+
|
| 737 |
+
return samples
|
| 738 |
+
|
| 739 |
+
@staticmethod
|
| 740 |
+
def resize_tensor(media_items, height, width):
|
| 741 |
+
n_frames = media_items.shape[2]
|
| 742 |
+
if media_items.shape[-2:] != (height, width):
|
| 743 |
+
media_items = rearrange(media_items, "b c n h w -> (b n) c h w")
|
| 744 |
+
media_items = F.interpolate(
|
| 745 |
+
media_items,
|
| 746 |
+
size=(height, width),
|
| 747 |
+
mode="bilinear",
|
| 748 |
+
align_corners=False,
|
| 749 |
+
)
|
| 750 |
+
media_items = rearrange(media_items, "(b n) c h w -> b c n h w", n=n_frames)
|
| 751 |
+
return media_items
|
| 752 |
+
|
| 753 |
+
@torch.no_grad()
|
| 754 |
+
def __call__(
|
| 755 |
+
self,
|
| 756 |
+
height: int,
|
| 757 |
+
width: int,
|
| 758 |
+
num_frames: int,
|
| 759 |
+
frame_rate: float,
|
| 760 |
+
prompt: Union[str, List[str]] = None,
|
| 761 |
+
negative_prompt: str = "",
|
| 762 |
+
num_inference_steps: int = 20,
|
| 763 |
+
skip_initial_inference_steps: int = 0,
|
| 764 |
+
skip_final_inference_steps: int = 0,
|
| 765 |
+
timesteps: List[int] = None,
|
| 766 |
+
guidance_scale: Union[float, List[float]] = 4.5,
|
| 767 |
+
cfg_star_rescale: bool = False,
|
| 768 |
+
skip_layer_strategy: Optional[SkipLayerStrategy] = None,
|
| 769 |
+
skip_block_list: Optional[Union[List[List[int]], List[int]]] = None,
|
| 770 |
+
stg_scale: Union[float, List[float]] = 1.0,
|
| 771 |
+
rescaling_scale: Union[float, List[float]] = 0.7,
|
| 772 |
+
guidance_timesteps: Optional[List[int]] = None,
|
| 773 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 774 |
+
eta: float = 0.0,
|
| 775 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 776 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 777 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 778 |
+
prompt_attention_mask: Optional[torch.FloatTensor] = None,
|
| 779 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 780 |
+
negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
|
| 781 |
+
output_type: Optional[str] = "pil",
|
| 782 |
+
return_dict: bool = True,
|
| 783 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 784 |
+
conditioning_items: Optional[List[ConditioningItem]] = None,
|
| 785 |
+
decode_timestep: Union[List[float], float] = 0.0,
|
| 786 |
+
decode_noise_scale: Optional[List[float]] = None,
|
| 787 |
+
mixed_precision: bool = False,
|
| 788 |
+
offload_to_cpu: bool = False,
|
| 789 |
+
enhance_prompt: bool = False,
|
| 790 |
+
text_encoder_max_tokens: int = 256,
|
| 791 |
+
stochastic_sampling: bool = False,
|
| 792 |
+
media_items: Optional[torch.Tensor] = None,
|
| 793 |
+
tone_map_compression_ratio: float = 0.0,
|
| 794 |
+
**kwargs,
|
| 795 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 796 |
+
"""
|
| 797 |
+
Function invoked when calling the pipeline for generation.
|
| 798 |
+
|
| 799 |
+
Args:
|
| 800 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 801 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 802 |
+
instead.
|
| 803 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 804 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 805 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 806 |
+
less than `1`).
|
| 807 |
+
num_inference_steps (`int`, *optional*, defaults to 100):
|
| 808 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 809 |
+
expense of slower inference. If `timesteps` is provided, this parameter is ignored.
|
| 810 |
+
skip_initial_inference_steps (`int`, *optional*, defaults to 0):
|
| 811 |
+
The number of initial timesteps to skip. After calculating the timesteps, this number of timesteps will
|
| 812 |
+
be removed from the beginning of the timesteps list. Meaning the highest-timesteps values will not run.
|
| 813 |
+
skip_final_inference_steps (`int`, *optional*, defaults to 0):
|
| 814 |
+
The number of final timesteps to skip. After calculating the timesteps, this number of timesteps will
|
| 815 |
+
be removed from the end of the timesteps list. Meaning the lowest-timesteps values will not run.
|
| 816 |
+
timesteps (`List[int]`, *optional*):
|
| 817 |
+
Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
|
| 818 |
+
timesteps are used. Must be in descending order.
|
| 819 |
+
guidance_scale (`float`, *optional*, defaults to 4.5):
|
| 820 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 821 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 822 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 823 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 824 |
+
usually at the expense of lower image quality.
|
| 825 |
+
cfg_star_rescale (`bool`, *optional*, defaults to `False`):
|
| 826 |
+
If set to `True`, applies the CFG star rescale. Scales the negative prediction according to dot
|
| 827 |
+
product between positive and negative.
|
| 828 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 829 |
+
The number of images to generate per prompt.
|
| 830 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size):
|
| 831 |
+
The height in pixels of the generated image.
|
| 832 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size):
|
| 833 |
+
The width in pixels of the generated image.
|
| 834 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 835 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 836 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 837 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 838 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 839 |
+
to make generation deterministic.
|
| 840 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 841 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 842 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 843 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 844 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 845 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 846 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 847 |
+
prompt_attention_mask (`torch.FloatTensor`, *optional*): Pre-generated attention mask for text embeddings.
|
| 848 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 849 |
+
Pre-generated negative text embeddings. This negative prompt should be "". If not
|
| 850 |
+
provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
|
| 851 |
+
negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
|
| 852 |
+
Pre-generated attention mask for negative text embeddings.
|
| 853 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 854 |
+
The output format of the generate image. Choose between
|
| 855 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 856 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 857 |
+
Whether to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
|
| 858 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 859 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 860 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 861 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 862 |
+
`callback_on_step_end_tensor_inputs`.
|
| 863 |
+
use_resolution_binning (`bool` defaults to `True`):
|
| 864 |
+
If set to `True`, the requested height and width are first mapped to the closest resolutions using
|
| 865 |
+
`ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
|
| 866 |
+
the requested resolution. Useful for generating non-square images.
|
| 867 |
+
enhance_prompt (`bool`, *optional*, defaults to `False`):
|
| 868 |
+
If set to `True`, the prompt is enhanced using a LLM model.
|
| 869 |
+
text_encoder_max_tokens (`int`, *optional*, defaults to `256`):
|
| 870 |
+
The maximum number of tokens to use for the text encoder.
|
| 871 |
+
stochastic_sampling (`bool`, *optional*, defaults to `False`):
|
| 872 |
+
If set to `True`, the sampling is stochastic. If set to `False`, the sampling is deterministic.
|
| 873 |
+
media_items ('torch.Tensor', *optional*):
|
| 874 |
+
The input media item used for image-to-image / video-to-video.
|
| 875 |
+
tone_map_compression_ratio: compression ratio for tone mapping, defaults to 0.0.
|
| 876 |
+
If set to 0.0, no tone mapping is applied. If set to 1.0 - full compression is applied.
|
| 877 |
+
Examples:
|
| 878 |
+
|
| 879 |
+
Returns:
|
| 880 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`:
|
| 881 |
+
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
|
| 882 |
+
returned where the first element is a list with the generated images
|
| 883 |
+
"""
|
| 884 |
+
if "mask_feature" in kwargs:
|
| 885 |
+
deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
|
| 886 |
+
deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
|
| 887 |
+
|
| 888 |
+
is_video = kwargs.get("is_video", False)
|
| 889 |
+
self.check_inputs(
|
| 890 |
+
prompt,
|
| 891 |
+
height,
|
| 892 |
+
width,
|
| 893 |
+
negative_prompt,
|
| 894 |
+
prompt_embeds,
|
| 895 |
+
negative_prompt_embeds,
|
| 896 |
+
prompt_attention_mask,
|
| 897 |
+
negative_prompt_attention_mask,
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
# 2. Default height and width to transformer
|
| 901 |
+
if prompt is not None and isinstance(prompt, str):
|
| 902 |
+
batch_size = 1
|
| 903 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 904 |
+
batch_size = len(prompt)
|
| 905 |
+
else:
|
| 906 |
+
batch_size = prompt_embeds.shape[0]
|
| 907 |
+
|
| 908 |
+
device = self._execution_device
|
| 909 |
+
|
| 910 |
+
self.video_scale_factor = self.video_scale_factor if is_video else 1
|
| 911 |
+
vae_per_channel_normalize = kwargs.get("vae_per_channel_normalize", True)
|
| 912 |
+
image_cond_noise_scale = kwargs.get("image_cond_noise_scale", 0.0)
|
| 913 |
+
|
| 914 |
+
latent_height = height // self.vae_scale_factor
|
| 915 |
+
latent_width = width // self.vae_scale_factor
|
| 916 |
+
latent_num_frames = num_frames // self.video_scale_factor
|
| 917 |
+
if isinstance(self.vae, CausalVideoAutoencoder) and is_video:
|
| 918 |
+
latent_num_frames += 1
|
| 919 |
+
latent_shape = (
|
| 920 |
+
batch_size * num_images_per_prompt,
|
| 921 |
+
self.transformer.config.in_channels,
|
| 922 |
+
latent_num_frames,
|
| 923 |
+
latent_height,
|
| 924 |
+
latent_width,
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
# Prepare the list of denoising time-steps
|
| 928 |
+
|
| 929 |
+
retrieve_timesteps_kwargs = {}
|
| 930 |
+
if isinstance(self.scheduler, TimestepShifter):
|
| 931 |
+
retrieve_timesteps_kwargs["samples_shape"] = latent_shape
|
| 932 |
+
|
| 933 |
+
assert (
|
| 934 |
+
skip_initial_inference_steps == 0
|
| 935 |
+
or latents is not None
|
| 936 |
+
or media_items is not None
|
| 937 |
+
), (
|
| 938 |
+
f"skip_initial_inference_steps ({skip_initial_inference_steps}) is used for image-to-image/video-to-video - "
|
| 939 |
+
"media_item or latents should be provided."
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 943 |
+
self.scheduler,
|
| 944 |
+
num_inference_steps,
|
| 945 |
+
device,
|
| 946 |
+
timesteps,
|
| 947 |
+
skip_initial_inference_steps=skip_initial_inference_steps,
|
| 948 |
+
skip_final_inference_steps=skip_final_inference_steps,
|
| 949 |
+
**retrieve_timesteps_kwargs,
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
if self.allowed_inference_steps is not None:
|
| 953 |
+
for timestep in [round(x, 4) for x in timesteps.tolist()]:
|
| 954 |
+
assert (
|
| 955 |
+
timestep in self.allowed_inference_steps
|
| 956 |
+
), f"Invalid inference timestep {timestep}. Allowed timesteps are {self.allowed_inference_steps}."
|
| 957 |
+
|
| 958 |
+
if guidance_timesteps:
|
| 959 |
+
guidance_mapping = []
|
| 960 |
+
for timestep in timesteps:
|
| 961 |
+
indices = [
|
| 962 |
+
i for i, val in enumerate(guidance_timesteps) if val <= timestep
|
| 963 |
+
]
|
| 964 |
+
# assert len(indices) > 0, f"No guidance timestep found for {timestep}"
|
| 965 |
+
guidance_mapping.append(
|
| 966 |
+
indices[0] if len(indices) > 0 else (len(guidance_timesteps) - 1)
|
| 967 |
+
)
|
| 968 |
+
|
| 969 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 970 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 971 |
+
# corresponds to doing no classifier free guidance.
|
| 972 |
+
if not isinstance(guidance_scale, List):
|
| 973 |
+
guidance_scale = [guidance_scale] * len(timesteps)
|
| 974 |
+
else:
|
| 975 |
+
guidance_scale = [
|
| 976 |
+
guidance_scale[guidance_mapping[i]] for i in range(len(timesteps))
|
| 977 |
+
]
|
| 978 |
+
|
| 979 |
+
if not isinstance(stg_scale, List):
|
| 980 |
+
stg_scale = [stg_scale] * len(timesteps)
|
| 981 |
+
else:
|
| 982 |
+
stg_scale = [stg_scale[guidance_mapping[i]] for i in range(len(timesteps))]
|
| 983 |
+
|
| 984 |
+
if not isinstance(rescaling_scale, List):
|
| 985 |
+
rescaling_scale = [rescaling_scale] * len(timesteps)
|
| 986 |
+
else:
|
| 987 |
+
rescaling_scale = [
|
| 988 |
+
rescaling_scale[guidance_mapping[i]] for i in range(len(timesteps))
|
| 989 |
+
]
|
| 990 |
+
|
| 991 |
+
# Normalize skip_block_list to always be None or a list of lists matching timesteps
|
| 992 |
+
if skip_block_list is not None:
|
| 993 |
+
# Convert single list to list of lists if needed
|
| 994 |
+
if len(skip_block_list) == 0 or not isinstance(skip_block_list[0], list):
|
| 995 |
+
skip_block_list = [skip_block_list] * len(timesteps)
|
| 996 |
+
else:
|
| 997 |
+
new_skip_block_list = []
|
| 998 |
+
for i, timestep in enumerate(timesteps):
|
| 999 |
+
new_skip_block_list.append(skip_block_list[guidance_mapping[i]])
|
| 1000 |
+
skip_block_list = new_skip_block_list
|
| 1001 |
+
|
| 1002 |
+
if enhance_prompt:
|
| 1003 |
+
self.prompt_enhancer_image_caption_model = (
|
| 1004 |
+
self.prompt_enhancer_image_caption_model.to(self._execution_device)
|
| 1005 |
+
)
|
| 1006 |
+
self.prompt_enhancer_llm_model = self.prompt_enhancer_llm_model.to(
|
| 1007 |
+
self._execution_device
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
prompt = generate_cinematic_prompt(
|
| 1011 |
+
self.prompt_enhancer_image_caption_model,
|
| 1012 |
+
self.prompt_enhancer_image_caption_processor,
|
| 1013 |
+
self.prompt_enhancer_llm_model,
|
| 1014 |
+
self.prompt_enhancer_llm_tokenizer,
|
| 1015 |
+
prompt,
|
| 1016 |
+
conditioning_items,
|
| 1017 |
+
max_new_tokens=text_encoder_max_tokens,
|
| 1018 |
+
)
|
| 1019 |
+
|
| 1020 |
+
# 3. Encode input prompt
|
| 1021 |
+
if self.text_encoder is not None:
|
| 1022 |
+
self.text_encoder = self.text_encoder.to(self._execution_device)
|
| 1023 |
+
|
| 1024 |
+
(
|
| 1025 |
+
prompt_embeds,
|
| 1026 |
+
prompt_attention_mask,
|
| 1027 |
+
negative_prompt_embeds,
|
| 1028 |
+
negative_prompt_attention_mask,
|
| 1029 |
+
) = self.encode_prompt(
|
| 1030 |
+
prompt,
|
| 1031 |
+
True,
|
| 1032 |
+
negative_prompt=negative_prompt,
|
| 1033 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1034 |
+
device=device,
|
| 1035 |
+
prompt_embeds=prompt_embeds,
|
| 1036 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1037 |
+
prompt_attention_mask=prompt_attention_mask,
|
| 1038 |
+
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
| 1039 |
+
text_encoder_max_tokens=text_encoder_max_tokens,
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
if offload_to_cpu and self.text_encoder is not None:
|
| 1043 |
+
self.text_encoder = self.text_encoder.cpu()
|
| 1044 |
+
|
| 1045 |
+
self.transformer = self.transformer.to(self._execution_device)
|
| 1046 |
+
|
| 1047 |
+
prompt_embeds_batch = prompt_embeds
|
| 1048 |
+
prompt_attention_mask_batch = prompt_attention_mask
|
| 1049 |
+
negative_prompt_embeds = (
|
| 1050 |
+
torch.zeros_like(prompt_embeds)
|
| 1051 |
+
if negative_prompt_embeds is None
|
| 1052 |
+
else negative_prompt_embeds
|
| 1053 |
+
)
|
| 1054 |
+
negative_prompt_attention_mask = (
|
| 1055 |
+
torch.zeros_like(prompt_attention_mask)
|
| 1056 |
+
if negative_prompt_attention_mask is None
|
| 1057 |
+
else negative_prompt_attention_mask
|
| 1058 |
+
)
|
| 1059 |
+
|
| 1060 |
+
prompt_embeds_batch = torch.cat(
|
| 1061 |
+
[negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0
|
| 1062 |
+
)
|
| 1063 |
+
prompt_attention_mask_batch = torch.cat(
|
| 1064 |
+
[
|
| 1065 |
+
negative_prompt_attention_mask,
|
| 1066 |
+
prompt_attention_mask,
|
| 1067 |
+
prompt_attention_mask,
|
| 1068 |
+
],
|
| 1069 |
+
dim=0,
|
| 1070 |
+
)
|
| 1071 |
+
# 4. Prepare the initial latents using the provided media and conditioning items
|
| 1072 |
+
|
| 1073 |
+
# Prepare the initial latents tensor, shape = (b, c, f, h, w)
|
| 1074 |
+
latents = self.prepare_latents(
|
| 1075 |
+
latents=latents,
|
| 1076 |
+
media_items=media_items,
|
| 1077 |
+
timestep=timesteps[0],
|
| 1078 |
+
latent_shape=latent_shape,
|
| 1079 |
+
dtype=prompt_embeds.dtype,
|
| 1080 |
+
device=device,
|
| 1081 |
+
generator=generator,
|
| 1082 |
+
vae_per_channel_normalize=vae_per_channel_normalize,
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
# Update the latents with the conditioning items and patchify them into (b, n, c)
|
| 1086 |
+
latents, pixel_coords, conditioning_mask, num_cond_latents = (
|
| 1087 |
+
self.prepare_conditioning(
|
| 1088 |
+
conditioning_items=conditioning_items,
|
| 1089 |
+
init_latents=latents,
|
| 1090 |
+
num_frames=num_frames,
|
| 1091 |
+
height=height,
|
| 1092 |
+
width=width,
|
| 1093 |
+
vae_per_channel_normalize=vae_per_channel_normalize,
|
| 1094 |
+
generator=generator,
|
| 1095 |
+
)
|
| 1096 |
+
)
|
| 1097 |
+
init_latents = latents.clone() # Used for image_cond_noise_update
|
| 1098 |
+
|
| 1099 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 1100 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 1101 |
+
|
| 1102 |
+
# 7. Denoising loop
|
| 1103 |
+
num_warmup_steps = max(
|
| 1104 |
+
len(timesteps) - num_inference_steps * self.scheduler.order, 0
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
orig_conditioning_mask = conditioning_mask
|
| 1108 |
+
|
| 1109 |
+
# Befor compiling this code please be aware:
|
| 1110 |
+
# This code might generate different input shapes if some timesteps have no STG or CFG.
|
| 1111 |
+
# This means that the codes might need to be compiled mutliple times.
|
| 1112 |
+
# To avoid that, use the same STG and CFG values for all timesteps.
|
| 1113 |
+
|
| 1114 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1115 |
+
for i, t in enumerate(timesteps):
|
| 1116 |
+
do_classifier_free_guidance = guidance_scale[i] > 1.0
|
| 1117 |
+
do_spatio_temporal_guidance = stg_scale[i] > 0
|
| 1118 |
+
do_rescaling = rescaling_scale[i] != 1.0
|
| 1119 |
+
|
| 1120 |
+
num_conds = 1
|
| 1121 |
+
if do_classifier_free_guidance:
|
| 1122 |
+
num_conds += 1
|
| 1123 |
+
if do_spatio_temporal_guidance:
|
| 1124 |
+
num_conds += 1
|
| 1125 |
+
|
| 1126 |
+
if do_classifier_free_guidance and do_spatio_temporal_guidance:
|
| 1127 |
+
indices = slice(batch_size * 0, batch_size * 3)
|
| 1128 |
+
elif do_classifier_free_guidance:
|
| 1129 |
+
indices = slice(batch_size * 0, batch_size * 2)
|
| 1130 |
+
elif do_spatio_temporal_guidance:
|
| 1131 |
+
indices = slice(batch_size * 1, batch_size * 3)
|
| 1132 |
+
else:
|
| 1133 |
+
indices = slice(batch_size * 1, batch_size * 2)
|
| 1134 |
+
|
| 1135 |
+
# Prepare skip layer masks
|
| 1136 |
+
skip_layer_mask: Optional[torch.Tensor] = None
|
| 1137 |
+
if do_spatio_temporal_guidance:
|
| 1138 |
+
if skip_block_list is not None:
|
| 1139 |
+
skip_layer_mask = self.transformer.create_skip_layer_mask(
|
| 1140 |
+
batch_size, num_conds, num_conds - 1, skip_block_list[i]
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
batch_pixel_coords = torch.cat([pixel_coords] * num_conds)
|
| 1144 |
+
conditioning_mask = orig_conditioning_mask
|
| 1145 |
+
if conditioning_mask is not None and is_video:
|
| 1146 |
+
assert num_images_per_prompt == 1
|
| 1147 |
+
conditioning_mask = torch.cat([conditioning_mask] * num_conds)
|
| 1148 |
+
fractional_coords = batch_pixel_coords.to(torch.float32)
|
| 1149 |
+
fractional_coords[:, 0] = fractional_coords[:, 0] * (1.0 / frame_rate)
|
| 1150 |
+
|
| 1151 |
+
if conditioning_mask is not None and image_cond_noise_scale > 0.0:
|
| 1152 |
+
latents = self.add_noise_to_image_conditioning_latents(
|
| 1153 |
+
t,
|
| 1154 |
+
init_latents,
|
| 1155 |
+
latents,
|
| 1156 |
+
image_cond_noise_scale,
|
| 1157 |
+
orig_conditioning_mask,
|
| 1158 |
+
generator,
|
| 1159 |
+
)
|
| 1160 |
+
|
| 1161 |
+
latent_model_input = (
|
| 1162 |
+
torch.cat([latents] * num_conds) if num_conds > 1 else latents
|
| 1163 |
+
)
|
| 1164 |
+
latent_model_input = self.scheduler.scale_model_input(
|
| 1165 |
+
latent_model_input, t
|
| 1166 |
+
)
|
| 1167 |
+
|
| 1168 |
+
current_timestep = t
|
| 1169 |
+
if not torch.is_tensor(current_timestep):
|
| 1170 |
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
| 1171 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
| 1172 |
+
is_mps = latent_model_input.device.type == "mps"
|
| 1173 |
+
if isinstance(current_timestep, float):
|
| 1174 |
+
dtype = torch.float32 if is_mps else torch.float64
|
| 1175 |
+
else:
|
| 1176 |
+
dtype = torch.int32 if is_mps else torch.int64
|
| 1177 |
+
current_timestep = torch.tensor(
|
| 1178 |
+
[current_timestep],
|
| 1179 |
+
dtype=dtype,
|
| 1180 |
+
device=latent_model_input.device,
|
| 1181 |
+
)
|
| 1182 |
+
elif len(current_timestep.shape) == 0:
|
| 1183 |
+
current_timestep = current_timestep[None].to(
|
| 1184 |
+
latent_model_input.device
|
| 1185 |
+
)
|
| 1186 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 1187 |
+
current_timestep = current_timestep.expand(
|
| 1188 |
+
latent_model_input.shape[0]
|
| 1189 |
+
).unsqueeze(-1)
|
| 1190 |
+
|
| 1191 |
+
if conditioning_mask is not None:
|
| 1192 |
+
# Conditioning latents have an initial timestep and noising level of (1.0 - conditioning_mask)
|
| 1193 |
+
# and will start to be denoised when the current timestep is lower than their conditioning timestep.
|
| 1194 |
+
current_timestep = torch.min(
|
| 1195 |
+
current_timestep, 1.0 - conditioning_mask
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
# Choose the appropriate context manager based on `mixed_precision`
|
| 1199 |
+
if mixed_precision:
|
| 1200 |
+
context_manager = torch.autocast(device.type, dtype=torch.bfloat16)
|
| 1201 |
+
else:
|
| 1202 |
+
context_manager = nullcontext() # Dummy context manager
|
| 1203 |
+
|
| 1204 |
+
# predict noise model_output
|
| 1205 |
+
with context_manager:
|
| 1206 |
+
noise_pred = self.transformer(
|
| 1207 |
+
latent_model_input.to(self.transformer.dtype),
|
| 1208 |
+
indices_grid=fractional_coords,
|
| 1209 |
+
encoder_hidden_states=prompt_embeds_batch[indices].to(
|
| 1210 |
+
self.transformer.dtype
|
| 1211 |
+
),
|
| 1212 |
+
encoder_attention_mask=prompt_attention_mask_batch[indices],
|
| 1213 |
+
timestep=current_timestep,
|
| 1214 |
+
skip_layer_mask=skip_layer_mask,
|
| 1215 |
+
skip_layer_strategy=skip_layer_strategy,
|
| 1216 |
+
return_dict=False,
|
| 1217 |
+
)[0]
|
| 1218 |
+
|
| 1219 |
+
# perform guidance
|
| 1220 |
+
if do_spatio_temporal_guidance:
|
| 1221 |
+
noise_pred_text, noise_pred_text_perturb = noise_pred.chunk(
|
| 1222 |
+
num_conds
|
| 1223 |
+
)[-2:]
|
| 1224 |
+
if do_classifier_free_guidance:
|
| 1225 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(num_conds)[:2]
|
| 1226 |
+
|
| 1227 |
+
if cfg_star_rescale:
|
| 1228 |
+
# Rescales the unconditional noise prediction using the projection of the conditional prediction onto it:
|
| 1229 |
+
# α = (⟨ε_text, ε_uncond⟩ / ||ε_uncond||²), then ε_uncond ← α * ε_uncond
|
| 1230 |
+
# where ε_text is the conditional noise prediction and ε_uncond is the unconditional one.
|
| 1231 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 1232 |
+
negative_flat = noise_pred_uncond.view(batch_size, -1)
|
| 1233 |
+
dot_product = torch.sum(
|
| 1234 |
+
positive_flat * negative_flat, dim=1, keepdim=True
|
| 1235 |
+
)
|
| 1236 |
+
squared_norm = (
|
| 1237 |
+
torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
|
| 1238 |
+
)
|
| 1239 |
+
alpha = dot_product / squared_norm
|
| 1240 |
+
noise_pred_uncond = alpha * noise_pred_uncond
|
| 1241 |
+
|
| 1242 |
+
noise_pred = noise_pred_uncond + guidance_scale[i] * (
|
| 1243 |
+
noise_pred_text - noise_pred_uncond
|
| 1244 |
+
)
|
| 1245 |
+
elif do_spatio_temporal_guidance:
|
| 1246 |
+
noise_pred = noise_pred_text
|
| 1247 |
+
if do_spatio_temporal_guidance:
|
| 1248 |
+
noise_pred = noise_pred + stg_scale[i] * (
|
| 1249 |
+
noise_pred_text - noise_pred_text_perturb
|
| 1250 |
+
)
|
| 1251 |
+
if do_rescaling and stg_scale[i] > 0.0:
|
| 1252 |
+
noise_pred_text_std = noise_pred_text.view(batch_size, -1).std(
|
| 1253 |
+
dim=1, keepdim=True
|
| 1254 |
+
)
|
| 1255 |
+
noise_pred_std = noise_pred.view(batch_size, -1).std(
|
| 1256 |
+
dim=1, keepdim=True
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
factor = noise_pred_text_std / noise_pred_std
|
| 1260 |
+
factor = rescaling_scale[i] * factor + (1 - rescaling_scale[i])
|
| 1261 |
+
|
| 1262 |
+
noise_pred = noise_pred * factor.view(batch_size, 1, 1)
|
| 1263 |
+
|
| 1264 |
+
current_timestep = current_timestep[:1]
|
| 1265 |
+
# learned sigma
|
| 1266 |
+
if (
|
| 1267 |
+
self.transformer.config.out_channels // 2
|
| 1268 |
+
== self.transformer.config.in_channels
|
| 1269 |
+
):
|
| 1270 |
+
noise_pred = noise_pred.chunk(2, dim=1)[0]
|
| 1271 |
+
|
| 1272 |
+
# compute previous image: x_t -> x_t-1
|
| 1273 |
+
latents = self.denoising_step(
|
| 1274 |
+
latents,
|
| 1275 |
+
noise_pred,
|
| 1276 |
+
current_timestep,
|
| 1277 |
+
orig_conditioning_mask,
|
| 1278 |
+
t,
|
| 1279 |
+
extra_step_kwargs,
|
| 1280 |
+
stochastic_sampling=stochastic_sampling,
|
| 1281 |
+
)
|
| 1282 |
+
|
| 1283 |
+
# call the callback, if provided
|
| 1284 |
+
if i == len(timesteps) - 1 or (
|
| 1285 |
+
(i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
|
| 1286 |
+
):
|
| 1287 |
+
progress_bar.update()
|
| 1288 |
+
|
| 1289 |
+
if callback_on_step_end is not None:
|
| 1290 |
+
callback_on_step_end(self, i, t, {})
|
| 1291 |
+
|
| 1292 |
+
if offload_to_cpu:
|
| 1293 |
+
self.transformer = self.transformer.cpu()
|
| 1294 |
+
if self._execution_device == "cuda":
|
| 1295 |
+
torch.cuda.empty_cache()
|
| 1296 |
+
|
| 1297 |
+
# Remove the added conditioning latents
|
| 1298 |
+
latents = latents[:, num_cond_latents:]
|
| 1299 |
+
|
| 1300 |
+
latents = self.patchifier.unpatchify(
|
| 1301 |
+
latents=latents,
|
| 1302 |
+
output_height=latent_height,
|
| 1303 |
+
output_width=latent_width,
|
| 1304 |
+
out_channels=self.transformer.in_channels
|
| 1305 |
+
// math.prod(self.patchifier.patch_size),
|
| 1306 |
+
)
|
| 1307 |
+
if output_type != "latent":
|
| 1308 |
+
if self.vae.decoder.timestep_conditioning:
|
| 1309 |
+
noise = torch.randn_like(latents)
|
| 1310 |
+
if not isinstance(decode_timestep, list):
|
| 1311 |
+
decode_timestep = [decode_timestep] * latents.shape[0]
|
| 1312 |
+
if decode_noise_scale is None:
|
| 1313 |
+
decode_noise_scale = decode_timestep
|
| 1314 |
+
elif not isinstance(decode_noise_scale, list):
|
| 1315 |
+
decode_noise_scale = [decode_noise_scale] * latents.shape[0]
|
| 1316 |
+
|
| 1317 |
+
decode_timestep = torch.tensor(decode_timestep).to(latents.device)
|
| 1318 |
+
decode_noise_scale = torch.tensor(decode_noise_scale).to(
|
| 1319 |
+
latents.device
|
| 1320 |
+
)[:, None, None, None, None]
|
| 1321 |
+
latents = (
|
| 1322 |
+
latents * (1 - decode_noise_scale) + noise * decode_noise_scale
|
| 1323 |
+
)
|
| 1324 |
+
else:
|
| 1325 |
+
decode_timestep = None
|
| 1326 |
+
latents = self.tone_map_latents(latents, tone_map_compression_ratio)
|
| 1327 |
+
image = vae_decode(
|
| 1328 |
+
latents,
|
| 1329 |
+
self.vae,
|
| 1330 |
+
is_video,
|
| 1331 |
+
vae_per_channel_normalize=kwargs["vae_per_channel_normalize"],
|
| 1332 |
+
timestep=decode_timestep,
|
| 1333 |
+
)
|
| 1334 |
+
|
| 1335 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 1336 |
+
|
| 1337 |
+
else:
|
| 1338 |
+
image = latents
|
| 1339 |
+
|
| 1340 |
+
# Offload all models
|
| 1341 |
+
self.maybe_free_model_hooks()
|
| 1342 |
+
|
| 1343 |
+
if not return_dict:
|
| 1344 |
+
return (image,)
|
| 1345 |
+
|
| 1346 |
+
return ImagePipelineOutput(images=image)
|
| 1347 |
+
|
| 1348 |
+
def denoising_step(
|
| 1349 |
+
self,
|
| 1350 |
+
latents: torch.Tensor,
|
| 1351 |
+
noise_pred: torch.Tensor,
|
| 1352 |
+
current_timestep: torch.Tensor,
|
| 1353 |
+
conditioning_mask: torch.Tensor,
|
| 1354 |
+
t: float,
|
| 1355 |
+
extra_step_kwargs,
|
| 1356 |
+
t_eps=1e-6,
|
| 1357 |
+
stochastic_sampling=False,
|
| 1358 |
+
):
|
| 1359 |
+
"""
|
| 1360 |
+
Perform the denoising step for the required tokens, based on the current timestep and
|
| 1361 |
+
conditioning mask:
|
| 1362 |
+
Conditioning latents have an initial timestep and noising level of (1.0 - conditioning_mask)
|
| 1363 |
+
and will start to be denoised when the current timestep is equal or lower than their
|
| 1364 |
+
conditioning timestep.
|
| 1365 |
+
(hard-conditioning latents with conditioning_mask = 1.0 are never denoised)
|
| 1366 |
+
"""
|
| 1367 |
+
# Denoise the latents using the scheduler
|
| 1368 |
+
denoised_latents = self.scheduler.step(
|
| 1369 |
+
noise_pred,
|
| 1370 |
+
t if current_timestep is None else current_timestep,
|
| 1371 |
+
latents,
|
| 1372 |
+
**extra_step_kwargs,
|
| 1373 |
+
return_dict=False,
|
| 1374 |
+
stochastic_sampling=stochastic_sampling,
|
| 1375 |
+
)[0]
|
| 1376 |
+
|
| 1377 |
+
if conditioning_mask is None:
|
| 1378 |
+
return denoised_latents
|
| 1379 |
+
|
| 1380 |
+
tokens_to_denoise_mask = (t - t_eps < (1.0 - conditioning_mask)).unsqueeze(-1)
|
| 1381 |
+
return torch.where(tokens_to_denoise_mask, denoised_latents, latents)
|
| 1382 |
+
|
| 1383 |
+
def prepare_conditioning(
|
| 1384 |
+
self,
|
| 1385 |
+
conditioning_items: Optional[List[ConditioningItem]],
|
| 1386 |
+
init_latents: torch.Tensor,
|
| 1387 |
+
num_frames: int,
|
| 1388 |
+
height: int,
|
| 1389 |
+
width: int,
|
| 1390 |
+
vae_per_channel_normalize: bool = False,
|
| 1391 |
+
generator=None,
|
| 1392 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
|
| 1393 |
+
"""
|
| 1394 |
+
Prepare conditioning tokens based on the provided conditioning items.
|
| 1395 |
+
|
| 1396 |
+
This method encodes provided conditioning items (video frames or single frames) into latents
|
| 1397 |
+
and integrates them with the initial latent tensor. It also calculates corresponding pixel
|
| 1398 |
+
coordinates, a mask indicating the influence of conditioning latents, and the total number of
|
| 1399 |
+
conditioning latents.
|
| 1400 |
+
|
| 1401 |
+
Args:
|
| 1402 |
+
conditioning_items (Optional[List[ConditioningItem]]): A list of ConditioningItem objects.
|
| 1403 |
+
init_latents (torch.Tensor): The initial latent tensor of shape (b, c, f_l, h_l, w_l), where
|
| 1404 |
+
`f_l` is the number of latent frames, and `h_l` and `w_l` are latent spatial dimensions.
|
| 1405 |
+
num_frames, height, width: The dimensions of the generated video.
|
| 1406 |
+
vae_per_channel_normalize (bool, optional): Whether to normalize channels during VAE encoding.
|
| 1407 |
+
Defaults to `False`.
|
| 1408 |
+
generator: The random generator
|
| 1409 |
+
|
| 1410 |
+
Returns:
|
| 1411 |
+
Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
|
| 1412 |
+
- `init_latents` (torch.Tensor): The updated latent tensor including conditioning latents,
|
| 1413 |
+
patchified into (b, n, c) shape.
|
| 1414 |
+
- `init_pixel_coords` (torch.Tensor): The pixel coordinates corresponding to the updated
|
| 1415 |
+
latent tensor.
|
| 1416 |
+
- `conditioning_mask` (torch.Tensor): A mask indicating the conditioning-strength of each
|
| 1417 |
+
latent token.
|
| 1418 |
+
- `num_cond_latents` (int): The total number of latent tokens added from conditioning items.
|
| 1419 |
+
|
| 1420 |
+
Raises:
|
| 1421 |
+
AssertionError: If input shapes, dimensions, or conditions for applying conditioning are invalid.
|
| 1422 |
+
"""
|
| 1423 |
+
assert isinstance(self.vae, CausalVideoAutoencoder)
|
| 1424 |
+
|
| 1425 |
+
if conditioning_items:
|
| 1426 |
+
batch_size, _, num_latent_frames = init_latents.shape[:3]
|
| 1427 |
+
|
| 1428 |
+
init_conditioning_mask = torch.zeros(
|
| 1429 |
+
init_latents[:, 0, :, :, :].shape,
|
| 1430 |
+
dtype=torch.float32,
|
| 1431 |
+
device=init_latents.device,
|
| 1432 |
+
)
|
| 1433 |
+
|
| 1434 |
+
extra_conditioning_latents = []
|
| 1435 |
+
extra_conditioning_pixel_coords = []
|
| 1436 |
+
extra_conditioning_mask = []
|
| 1437 |
+
extra_conditioning_num_latents = 0 # Number of extra conditioning latents added (should be removed before decoding)
|
| 1438 |
+
|
| 1439 |
+
# Process each conditioning item
|
| 1440 |
+
for conditioning_item in conditioning_items:
|
| 1441 |
+
conditioning_item = self._resize_conditioning_item(
|
| 1442 |
+
conditioning_item, height, width
|
| 1443 |
+
)
|
| 1444 |
+
media_item = conditioning_item.media_item
|
| 1445 |
+
media_frame_number = conditioning_item.media_frame_number
|
| 1446 |
+
strength = conditioning_item.conditioning_strength
|
| 1447 |
+
assert media_item.ndim == 5 # (b, c, f, h, w)
|
| 1448 |
+
b, c, n_frames, h, w = media_item.shape
|
| 1449 |
+
assert (
|
| 1450 |
+
height == h and width == w
|
| 1451 |
+
) or media_frame_number == 0, f"Dimensions do not match: {height}x{width} != {h}x{w} - allowed only when media_frame_number == 0"
|
| 1452 |
+
assert n_frames % 8 == 1
|
| 1453 |
+
assert (
|
| 1454 |
+
media_frame_number >= 0
|
| 1455 |
+
and media_frame_number + n_frames <= num_frames
|
| 1456 |
+
)
|
| 1457 |
+
|
| 1458 |
+
# Encode the provided conditioning media item
|
| 1459 |
+
media_item_latents = vae_encode(
|
| 1460 |
+
media_item.to(dtype=self.vae.dtype, device=self.vae.device),
|
| 1461 |
+
self.vae,
|
| 1462 |
+
vae_per_channel_normalize=vae_per_channel_normalize,
|
| 1463 |
+
).to(dtype=init_latents.dtype)
|
| 1464 |
+
|
| 1465 |
+
# Handle the different conditioning cases
|
| 1466 |
+
if media_frame_number == 0:
|
| 1467 |
+
# Get the target spatial position of the latent conditioning item
|
| 1468 |
+
media_item_latents, l_x, l_y = self._get_latent_spatial_position(
|
| 1469 |
+
media_item_latents,
|
| 1470 |
+
conditioning_item,
|
| 1471 |
+
height,
|
| 1472 |
+
width,
|
| 1473 |
+
strip_latent_border=True,
|
| 1474 |
+
)
|
| 1475 |
+
b, c_l, f_l, h_l, w_l = media_item_latents.shape
|
| 1476 |
+
|
| 1477 |
+
# First frame or sequence - just update the initial noise latents and the mask
|
| 1478 |
+
init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l] = (
|
| 1479 |
+
torch.lerp(
|
| 1480 |
+
init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l],
|
| 1481 |
+
media_item_latents,
|
| 1482 |
+
strength,
|
| 1483 |
+
)
|
| 1484 |
+
)
|
| 1485 |
+
init_conditioning_mask[
|
| 1486 |
+
:, :f_l, l_y : l_y + h_l, l_x : l_x + w_l
|
| 1487 |
+
] = strength
|
| 1488 |
+
else:
|
| 1489 |
+
# Non-first frame or sequence
|
| 1490 |
+
if n_frames > 1:
|
| 1491 |
+
# Handle non-first sequence.
|
| 1492 |
+
# Encoded latents are either fully consumed, or the prefix is handled separately below.
|
| 1493 |
+
(
|
| 1494 |
+
init_latents,
|
| 1495 |
+
init_conditioning_mask,
|
| 1496 |
+
media_item_latents,
|
| 1497 |
+
) = self._handle_non_first_conditioning_sequence(
|
| 1498 |
+
init_latents,
|
| 1499 |
+
init_conditioning_mask,
|
| 1500 |
+
media_item_latents,
|
| 1501 |
+
media_frame_number,
|
| 1502 |
+
strength,
|
| 1503 |
+
)
|
| 1504 |
+
|
| 1505 |
+
# Single frame or sequence-prefix latents
|
| 1506 |
+
if media_item_latents is not None:
|
| 1507 |
+
noise = randn_tensor(
|
| 1508 |
+
media_item_latents.shape,
|
| 1509 |
+
generator=generator,
|
| 1510 |
+
device=media_item_latents.device,
|
| 1511 |
+
dtype=media_item_latents.dtype,
|
| 1512 |
+
)
|
| 1513 |
+
|
| 1514 |
+
media_item_latents = torch.lerp(
|
| 1515 |
+
noise, media_item_latents, strength
|
| 1516 |
+
)
|
| 1517 |
+
|
| 1518 |
+
# Patchify the extra conditioning latents and calculate their pixel coordinates
|
| 1519 |
+
media_item_latents, latent_coords = self.patchifier.patchify(
|
| 1520 |
+
latents=media_item_latents
|
| 1521 |
+
)
|
| 1522 |
+
pixel_coords = latent_to_pixel_coords(
|
| 1523 |
+
latent_coords,
|
| 1524 |
+
self.vae,
|
| 1525 |
+
causal_fix=self.transformer.config.causal_temporal_positioning,
|
| 1526 |
+
)
|
| 1527 |
+
|
| 1528 |
+
# Update the frame numbers to match the target frame number
|
| 1529 |
+
pixel_coords[:, 0] += media_frame_number
|
| 1530 |
+
extra_conditioning_num_latents += media_item_latents.shape[1]
|
| 1531 |
+
|
| 1532 |
+
conditioning_mask = torch.full(
|
| 1533 |
+
media_item_latents.shape[:2],
|
| 1534 |
+
strength,
|
| 1535 |
+
dtype=torch.float32,
|
| 1536 |
+
device=init_latents.device,
|
| 1537 |
+
)
|
| 1538 |
+
|
| 1539 |
+
extra_conditioning_latents.append(media_item_latents)
|
| 1540 |
+
extra_conditioning_pixel_coords.append(pixel_coords)
|
| 1541 |
+
extra_conditioning_mask.append(conditioning_mask)
|
| 1542 |
+
|
| 1543 |
+
# Patchify the updated latents and calculate their pixel coordinates
|
| 1544 |
+
init_latents, init_latent_coords = self.patchifier.patchify(
|
| 1545 |
+
latents=init_latents
|
| 1546 |
+
)
|
| 1547 |
+
init_pixel_coords = latent_to_pixel_coords(
|
| 1548 |
+
init_latent_coords,
|
| 1549 |
+
self.vae,
|
| 1550 |
+
causal_fix=self.transformer.config.causal_temporal_positioning,
|
| 1551 |
+
)
|
| 1552 |
+
|
| 1553 |
+
if not conditioning_items:
|
| 1554 |
+
return init_latents, init_pixel_coords, None, 0
|
| 1555 |
+
|
| 1556 |
+
init_conditioning_mask, _ = self.patchifier.patchify(
|
| 1557 |
+
latents=init_conditioning_mask.unsqueeze(1)
|
| 1558 |
+
)
|
| 1559 |
+
init_conditioning_mask = init_conditioning_mask.squeeze(-1)
|
| 1560 |
+
|
| 1561 |
+
if extra_conditioning_latents:
|
| 1562 |
+
# Stack the extra conditioning latents, pixel coordinates and mask
|
| 1563 |
+
init_latents = torch.cat([*extra_conditioning_latents, init_latents], dim=1)
|
| 1564 |
+
init_pixel_coords = torch.cat(
|
| 1565 |
+
[*extra_conditioning_pixel_coords, init_pixel_coords], dim=2
|
| 1566 |
+
)
|
| 1567 |
+
init_conditioning_mask = torch.cat(
|
| 1568 |
+
[*extra_conditioning_mask, init_conditioning_mask], dim=1
|
| 1569 |
+
)
|
| 1570 |
+
|
| 1571 |
+
if self.transformer.use_tpu_flash_attention:
|
| 1572 |
+
# When flash attention is used, keep the original number of tokens by removing
|
| 1573 |
+
# tokens from the end.
|
| 1574 |
+
init_latents = init_latents[:, :-extra_conditioning_num_latents]
|
| 1575 |
+
init_pixel_coords = init_pixel_coords[
|
| 1576 |
+
:, :, :-extra_conditioning_num_latents
|
| 1577 |
+
]
|
| 1578 |
+
init_conditioning_mask = init_conditioning_mask[
|
| 1579 |
+
:, :-extra_conditioning_num_latents
|
| 1580 |
+
]
|
| 1581 |
+
|
| 1582 |
+
return (
|
| 1583 |
+
init_latents,
|
| 1584 |
+
init_pixel_coords,
|
| 1585 |
+
init_conditioning_mask,
|
| 1586 |
+
extra_conditioning_num_latents,
|
| 1587 |
+
)
|
| 1588 |
+
|
| 1589 |
+
@staticmethod
|
| 1590 |
+
def _resize_conditioning_item(
|
| 1591 |
+
conditioning_item: ConditioningItem,
|
| 1592 |
+
height: int,
|
| 1593 |
+
width: int,
|
| 1594 |
+
):
|
| 1595 |
+
if conditioning_item.media_x or conditioning_item.media_y:
|
| 1596 |
+
raise ValueError(
|
| 1597 |
+
"Provide media_item in the target size for spatial conditioning."
|
| 1598 |
+
)
|
| 1599 |
+
new_conditioning_item = copy.copy(conditioning_item)
|
| 1600 |
+
new_conditioning_item.media_item = LTXVideoPipeline.resize_tensor(
|
| 1601 |
+
conditioning_item.media_item, height, width
|
| 1602 |
+
)
|
| 1603 |
+
return new_conditioning_item
|
| 1604 |
+
|
| 1605 |
+
def _get_latent_spatial_position(
|
| 1606 |
+
self,
|
| 1607 |
+
latents: torch.Tensor,
|
| 1608 |
+
conditioning_item: ConditioningItem,
|
| 1609 |
+
height: int,
|
| 1610 |
+
width: int,
|
| 1611 |
+
strip_latent_border,
|
| 1612 |
+
):
|
| 1613 |
+
"""
|
| 1614 |
+
Get the spatial position of the conditioning item in the latent space.
|
| 1615 |
+
If requested, strip the conditioning latent borders that do not align with target borders.
|
| 1616 |
+
(border latents look different then other latents and might confuse the model)
|
| 1617 |
+
"""
|
| 1618 |
+
scale = self.vae_scale_factor
|
| 1619 |
+
h, w = conditioning_item.media_item.shape[-2:]
|
| 1620 |
+
assert (
|
| 1621 |
+
h <= height and w <= width
|
| 1622 |
+
), f"Conditioning item size {h}x{w} is larger than target size {height}x{width}"
|
| 1623 |
+
assert h % scale == 0 and w % scale == 0
|
| 1624 |
+
|
| 1625 |
+
# Compute the start and end spatial positions of the media item
|
| 1626 |
+
x_start, y_start = conditioning_item.media_x, conditioning_item.media_y
|
| 1627 |
+
x_start = (width - w) // 2 if x_start is None else x_start
|
| 1628 |
+
y_start = (height - h) // 2 if y_start is None else y_start
|
| 1629 |
+
x_end, y_end = x_start + w, y_start + h
|
| 1630 |
+
assert (
|
| 1631 |
+
x_end <= width and y_end <= height
|
| 1632 |
+
), f"Conditioning item {x_start}:{x_end}x{y_start}:{y_end} is out of bounds for target size {width}x{height}"
|
| 1633 |
+
|
| 1634 |
+
if strip_latent_border:
|
| 1635 |
+
# Strip one latent from left/right and/or top/bottom, update x, y accordingly
|
| 1636 |
+
if x_start > 0:
|
| 1637 |
+
x_start += scale
|
| 1638 |
+
latents = latents[:, :, :, :, 1:]
|
| 1639 |
+
|
| 1640 |
+
if y_start > 0:
|
| 1641 |
+
y_start += scale
|
| 1642 |
+
latents = latents[:, :, :, 1:, :]
|
| 1643 |
+
|
| 1644 |
+
if x_end < width:
|
| 1645 |
+
latents = latents[:, :, :, :, :-1]
|
| 1646 |
+
|
| 1647 |
+
if y_end < height:
|
| 1648 |
+
latents = latents[:, :, :, :-1, :]
|
| 1649 |
+
|
| 1650 |
+
return latents, x_start // scale, y_start // scale
|
| 1651 |
+
|
| 1652 |
+
@staticmethod
|
| 1653 |
+
def _handle_non_first_conditioning_sequence(
|
| 1654 |
+
init_latents: torch.Tensor,
|
| 1655 |
+
init_conditioning_mask: torch.Tensor,
|
| 1656 |
+
latents: torch.Tensor,
|
| 1657 |
+
media_frame_number: int,
|
| 1658 |
+
strength: float,
|
| 1659 |
+
num_prefix_latent_frames: int = 2,
|
| 1660 |
+
prefix_latents_mode: str = "concat",
|
| 1661 |
+
prefix_soft_conditioning_strength: float = 0.15,
|
| 1662 |
+
):
|
| 1663 |
+
"""
|
| 1664 |
+
Special handling for a conditioning sequence that does not start on the first frame.
|
| 1665 |
+
The special handling is required to allow a short encoded video to be used as middle
|
| 1666 |
+
(or last) sequence in a longer video.
|
| 1667 |
+
Args:
|
| 1668 |
+
init_latents (torch.Tensor): The initial noise latents to be updated.
|
| 1669 |
+
init_conditioning_mask (torch.Tensor): The initial conditioning mask to be updated.
|
| 1670 |
+
latents (torch.Tensor): The encoded conditioning item.
|
| 1671 |
+
media_frame_number (int): The target frame number of the first frame in the conditioning sequence.
|
| 1672 |
+
strength (float): The conditioning strength for the conditioning latents.
|
| 1673 |
+
num_prefix_latent_frames (int, optional): The length of the sequence prefix, to be handled
|
| 1674 |
+
separately. Defaults to 2.
|
| 1675 |
+
prefix_latents_mode (str, optional): Special treatment for prefix (boundary) latents.
|
| 1676 |
+
- "drop": Drop the prefix latents.
|
| 1677 |
+
- "soft": Use the prefix latents, but with soft-conditioning
|
| 1678 |
+
- "concat": Add the prefix latents as extra tokens (like single frames)
|
| 1679 |
+
prefix_soft_conditioning_strength (float, optional): The strength of the soft-conditioning for
|
| 1680 |
+
the prefix latents, relevant if `prefix_latents_mode` is "soft". Defaults to 0.1.
|
| 1681 |
+
|
| 1682 |
+
"""
|
| 1683 |
+
f_l = latents.shape[2]
|
| 1684 |
+
f_l_p = num_prefix_latent_frames
|
| 1685 |
+
assert f_l >= f_l_p
|
| 1686 |
+
assert media_frame_number % 8 == 0
|
| 1687 |
+
if f_l > f_l_p:
|
| 1688 |
+
# Insert the conditioning latents **excluding the prefix** into the sequence
|
| 1689 |
+
f_l_start = media_frame_number // 8 + f_l_p
|
| 1690 |
+
f_l_end = f_l_start + f_l - f_l_p
|
| 1691 |
+
init_latents[:, :, f_l_start:f_l_end] = torch.lerp(
|
| 1692 |
+
init_latents[:, :, f_l_start:f_l_end],
|
| 1693 |
+
latents[:, :, f_l_p:],
|
| 1694 |
+
strength,
|
| 1695 |
+
)
|
| 1696 |
+
# Mark these latent frames as conditioning latents
|
| 1697 |
+
init_conditioning_mask[:, f_l_start:f_l_end] = strength
|
| 1698 |
+
|
| 1699 |
+
# Handle the prefix-latents
|
| 1700 |
+
if prefix_latents_mode == "soft":
|
| 1701 |
+
if f_l_p > 1:
|
| 1702 |
+
# Drop the first (single-frame) latent and soft-condition the remaining prefix
|
| 1703 |
+
f_l_start = media_frame_number // 8 + 1
|
| 1704 |
+
f_l_end = f_l_start + f_l_p - 1
|
| 1705 |
+
strength = min(prefix_soft_conditioning_strength, strength)
|
| 1706 |
+
init_latents[:, :, f_l_start:f_l_end] = torch.lerp(
|
| 1707 |
+
init_latents[:, :, f_l_start:f_l_end],
|
| 1708 |
+
latents[:, :, 1:f_l_p],
|
| 1709 |
+
strength,
|
| 1710 |
+
)
|
| 1711 |
+
# Mark these latent frames as conditioning latents
|
| 1712 |
+
init_conditioning_mask[:, f_l_start:f_l_end] = strength
|
| 1713 |
+
latents = None # No more latents to handle
|
| 1714 |
+
elif prefix_latents_mode == "drop":
|
| 1715 |
+
# Drop the prefix latents
|
| 1716 |
+
latents = None
|
| 1717 |
+
elif prefix_latents_mode == "concat":
|
| 1718 |
+
# Pass-on the prefix latents to be handled as extra conditioning frames
|
| 1719 |
+
latents = latents[:, :, :f_l_p]
|
| 1720 |
+
else:
|
| 1721 |
+
raise ValueError(f"Invalid prefix_latents_mode: {prefix_latents_mode}")
|
| 1722 |
+
return (
|
| 1723 |
+
init_latents,
|
| 1724 |
+
init_conditioning_mask,
|
| 1725 |
+
latents,
|
| 1726 |
+
)
|
| 1727 |
+
|
| 1728 |
+
def trim_conditioning_sequence(
|
| 1729 |
+
self, start_frame: int, sequence_num_frames: int, target_num_frames: int
|
| 1730 |
+
):
|
| 1731 |
+
"""
|
| 1732 |
+
Trim a conditioning sequence to the allowed number of frames.
|
| 1733 |
+
|
| 1734 |
+
Args:
|
| 1735 |
+
start_frame (int): The target frame number of the first frame in the sequence.
|
| 1736 |
+
sequence_num_frames (int): The number of frames in the sequence.
|
| 1737 |
+
target_num_frames (int): The target number of frames in the generated video.
|
| 1738 |
+
|
| 1739 |
+
Returns:
|
| 1740 |
+
int: updated sequence length
|
| 1741 |
+
"""
|
| 1742 |
+
scale_factor = self.video_scale_factor
|
| 1743 |
+
num_frames = min(sequence_num_frames, target_num_frames - start_frame)
|
| 1744 |
+
# Trim down to a multiple of temporal_scale_factor frames plus 1
|
| 1745 |
+
num_frames = (num_frames - 1) // scale_factor * scale_factor + 1
|
| 1746 |
+
return num_frames
|
| 1747 |
+
|
| 1748 |
+
@staticmethod
|
| 1749 |
+
def tone_map_latents(
|
| 1750 |
+
latents: torch.Tensor,
|
| 1751 |
+
compression: float,
|
| 1752 |
+
) -> torch.Tensor:
|
| 1753 |
+
"""
|
| 1754 |
+
Applies a non-linear tone-mapping function to latent values to reduce their dynamic range
|
| 1755 |
+
in a perceptually smooth way using a sigmoid-based compression.
|
| 1756 |
+
|
| 1757 |
+
This is useful for regularizing high-variance latents or for conditioning outputs
|
| 1758 |
+
during generation, especially when controlling dynamic behavior with a `compression` factor.
|
| 1759 |
+
|
| 1760 |
+
Parameters:
|
| 1761 |
+
----------
|
| 1762 |
+
latents : torch.Tensor
|
| 1763 |
+
Input latent tensor with arbitrary shape. Expected to be roughly in [-1, 1] or [0, 1] range.
|
| 1764 |
+
compression : float
|
| 1765 |
+
Compression strength in the range [0, 1].
|
| 1766 |
+
- 0.0: No tone-mapping (identity transform)
|
| 1767 |
+
- 1.0: Full compression effect
|
| 1768 |
+
|
| 1769 |
+
Returns:
|
| 1770 |
+
-------
|
| 1771 |
+
torch.Tensor
|
| 1772 |
+
The tone-mapped latent tensor of the same shape as input.
|
| 1773 |
+
"""
|
| 1774 |
+
if not (0 <= compression <= 1):
|
| 1775 |
+
raise ValueError("Compression must be in the range [0, 1]")
|
| 1776 |
+
|
| 1777 |
+
# Remap [0-1] to [0-0.75] and apply sigmoid compression in one shot
|
| 1778 |
+
scale_factor = compression * 0.75
|
| 1779 |
+
abs_latents = torch.abs(latents)
|
| 1780 |
+
|
| 1781 |
+
# Sigmoid compression: sigmoid shifts large values toward 0.2, small values stay ~1.0
|
| 1782 |
+
# When scale_factor=0, sigmoid term vanishes, when scale_factor=0.75, full effect
|
| 1783 |
+
sigmoid_term = torch.sigmoid(4.0 * scale_factor * (abs_latents - 1.0))
|
| 1784 |
+
scales = 1.0 - 0.8 * scale_factor * sigmoid_term
|
| 1785 |
+
|
| 1786 |
+
filtered = latents * scales
|
| 1787 |
+
return filtered
|
| 1788 |
+
|
| 1789 |
+
|
| 1790 |
+
def adain_filter_latent(
|
| 1791 |
+
latents: torch.Tensor, reference_latents: torch.Tensor, factor=1.0
|
| 1792 |
+
):
|
| 1793 |
+
"""
|
| 1794 |
+
Applies Adaptive Instance Normalization (AdaIN) to a latent tensor based on
|
| 1795 |
+
statistics from a reference latent tensor.
|
| 1796 |
+
|
| 1797 |
+
Args:
|
| 1798 |
+
latent (torch.Tensor): Input latents to normalize
|
| 1799 |
+
reference_latent (torch.Tensor): The reference latents providing style statistics.
|
| 1800 |
+
factor (float): Blending factor between original and transformed latent.
|
| 1801 |
+
Range: -10.0 to 10.0, Default: 1.0
|
| 1802 |
+
|
| 1803 |
+
Returns:
|
| 1804 |
+
torch.Tensor: The transformed latent tensor
|
| 1805 |
+
"""
|
| 1806 |
+
result = latents.clone()
|
| 1807 |
+
|
| 1808 |
+
for i in range(latents.size(0)):
|
| 1809 |
+
for c in range(latents.size(1)):
|
| 1810 |
+
r_sd, r_mean = torch.std_mean(
|
| 1811 |
+
reference_latents[i, c], dim=None
|
| 1812 |
+
) # index by original dim order
|
| 1813 |
+
i_sd, i_mean = torch.std_mean(result[i, c], dim=None)
|
| 1814 |
+
|
| 1815 |
+
result[i, c] = ((result[i, c] - i_mean) / i_sd) * r_sd + r_mean
|
| 1816 |
+
|
| 1817 |
+
result = torch.lerp(latents, result, factor)
|
| 1818 |
+
return result
|
| 1819 |
+
|
| 1820 |
+
|
| 1821 |
+
class LTXMultiScalePipeline:
|
| 1822 |
+
def _upsample_latents(
|
| 1823 |
+
self, latest_upsampler: LatentUpsampler, latents: torch.Tensor
|
| 1824 |
+
):
|
| 1825 |
+
assert latents.device == latest_upsampler.device
|
| 1826 |
+
|
| 1827 |
+
latents = un_normalize_latents(
|
| 1828 |
+
latents, self.vae, vae_per_channel_normalize=True
|
| 1829 |
+
)
|
| 1830 |
+
upsampled_latents = latest_upsampler(latents)
|
| 1831 |
+
upsampled_latents = normalize_latents(
|
| 1832 |
+
upsampled_latents, self.vae, vae_per_channel_normalize=True
|
| 1833 |
+
)
|
| 1834 |
+
return upsampled_latents
|
| 1835 |
+
|
| 1836 |
+
def __init__(
|
| 1837 |
+
self, video_pipeline: LTXVideoPipeline, latent_upsampler: LatentUpsampler
|
| 1838 |
+
):
|
| 1839 |
+
self.video_pipeline = video_pipeline
|
| 1840 |
+
self.vae = video_pipeline.vae
|
| 1841 |
+
self.latent_upsampler = latent_upsampler
|
| 1842 |
+
|
| 1843 |
+
def __call__(
|
| 1844 |
+
self,
|
| 1845 |
+
downscale_factor: float,
|
| 1846 |
+
first_pass: dict,
|
| 1847 |
+
second_pass: dict,
|
| 1848 |
+
*args: Any,
|
| 1849 |
+
**kwargs: Any,
|
| 1850 |
+
) -> Any:
|
| 1851 |
+
original_kwargs = kwargs.copy()
|
| 1852 |
+
original_output_type = kwargs["output_type"]
|
| 1853 |
+
original_width = kwargs["width"]
|
| 1854 |
+
original_height = kwargs["height"]
|
| 1855 |
+
|
| 1856 |
+
x_width = int(kwargs["width"] * downscale_factor)
|
| 1857 |
+
downscaled_width = x_width - (x_width % self.video_pipeline.vae_scale_factor)
|
| 1858 |
+
x_height = int(kwargs["height"] * downscale_factor)
|
| 1859 |
+
downscaled_height = x_height - (x_height % self.video_pipeline.vae_scale_factor)
|
| 1860 |
+
|
| 1861 |
+
kwargs["output_type"] = "latent"
|
| 1862 |
+
kwargs["width"] = downscaled_width
|
| 1863 |
+
kwargs["height"] = downscaled_height
|
| 1864 |
+
kwargs.update(**first_pass)
|
| 1865 |
+
result = self.video_pipeline(*args, **kwargs)
|
| 1866 |
+
latents = result.images
|
| 1867 |
+
|
| 1868 |
+
upsampled_latents = self._upsample_latents(self.latent_upsampler, latents)
|
| 1869 |
+
upsampled_latents = adain_filter_latent(
|
| 1870 |
+
latents=upsampled_latents, reference_latents=latents
|
| 1871 |
+
)
|
| 1872 |
+
|
| 1873 |
+
kwargs = original_kwargs
|
| 1874 |
+
|
| 1875 |
+
kwargs["latents"] = upsampled_latents
|
| 1876 |
+
kwargs["output_type"] = original_output_type
|
| 1877 |
+
kwargs["width"] = downscaled_width * 2
|
| 1878 |
+
kwargs["height"] = downscaled_height * 2
|
| 1879 |
+
kwargs.update(**second_pass)
|
| 1880 |
+
|
| 1881 |
+
result = self.video_pipeline(*args, **kwargs)
|
| 1882 |
+
if original_output_type != "latent":
|
| 1883 |
+
num_frames = result.images.shape[2]
|
| 1884 |
+
videos = rearrange(result.images, "b c f h w -> (b f) c h w")
|
| 1885 |
+
|
| 1886 |
+
videos = F.interpolate(
|
| 1887 |
+
videos,
|
| 1888 |
+
size=(original_height, original_width),
|
| 1889 |
+
mode="bilinear",
|
| 1890 |
+
align_corners=False,
|
| 1891 |
+
)
|
| 1892 |
+
videos = rearrange(videos, "(b f) c h w -> b c f h w", f=num_frames)
|
| 1893 |
+
result.images = videos
|
| 1894 |
+
|
| 1895 |
+
return result
|
requirements.txt
CHANGED
|
@@ -12,7 +12,7 @@ imageio-ffmpeg
|
|
| 12 |
einops
|
| 13 |
timm
|
| 14 |
av
|
| 15 |
-
flash-attn-3@https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
|
| 16 |
git+https://github.com/huggingface/diffusers.git@main
|
| 17 |
|
| 18 |
|
|
|
|
| 12 |
einops
|
| 13 |
timm
|
| 14 |
av
|
| 15 |
+
#flash-attn-3@https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
|
| 16 |
git+https://github.com/huggingface/diffusers.git@main
|
| 17 |
|
| 18 |
|
setup.py
CHANGED
|
@@ -2,179 +2,173 @@
|
|
| 2 |
#
|
| 3 |
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
#
|
| 5 |
-
# Versão
|
| 6 |
-
# -
|
| 7 |
-
# -
|
| 8 |
-
# - Unifica o download de todas as dependências (Git, LTX Models, SeedVR Models).
|
| 9 |
|
| 10 |
import os
|
| 11 |
import subprocess
|
| 12 |
import sys
|
| 13 |
from pathlib import Path
|
| 14 |
import yaml
|
| 15 |
-
from huggingface_hub import hf_hub_download
|
| 16 |
|
| 17 |
-
#
|
|
|
|
|
|
|
|
|
|
| 18 |
DEPS_DIR = Path("/data")
|
|
|
|
| 19 |
|
| 20 |
-
# ---
|
| 21 |
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
# ---
|
| 24 |
-
SEEDVR_MODELS_DIR = DEPS_DIR / "SeedVR"
|
| 25 |
-
|
| 26 |
-
# --- Repositórios para Clonar ---
|
| 27 |
REPOS_TO_CLONE = {
|
| 28 |
"LTX-Video": "https://huggingface.co/spaces/Lightricks/ltx-video-distilled",
|
| 29 |
"SeedVR": "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler",
|
| 30 |
-
"
|
| 31 |
}
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
def run_command(command, cwd=None):
|
| 34 |
-
"""Executa um comando no terminal e
|
| 35 |
print(f"Executando: {' '.join(command)}")
|
| 36 |
try:
|
| 37 |
subprocess.run(
|
| 38 |
-
command,
|
| 39 |
-
|
| 40 |
-
cwd=cwd,
|
| 41 |
-
stdin=subprocess.DEVNULL,
|
| 42 |
)
|
| 43 |
except subprocess.CalledProcessError as e:
|
| 44 |
-
print(f"ERRO: O comando falhou com o código
|
| 45 |
sys.exit(1)
|
| 46 |
except FileNotFoundError:
|
| 47 |
-
print(f"ERRO:
|
| 48 |
sys.exit(1)
|
| 49 |
|
| 50 |
-
# --- Funções de Download (LTX-Video) ---
|
| 51 |
-
|
| 52 |
def _load_ltx_config():
|
| 53 |
"""Carrega o arquivo de configuração YAML do LTX-Video."""
|
| 54 |
print("--- Carregando Configuração do LTX-Video ---")
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
base / "ltxv-13b-0.9.8-distilled-fp8.yaml",
|
| 59 |
-
base / "ltxv-13b-0.9.8-distilled.yaml",
|
| 60 |
-
]
|
| 61 |
-
for cfg_path in candidates:
|
| 62 |
-
if cfg_path.exists():
|
| 63 |
-
print(f"Configuração encontrada: {cfg_path}")
|
| 64 |
-
with open(cfg_path, "r") as file:
|
| 65 |
-
return yaml.safe_load(file)
|
| 66 |
-
|
| 67 |
-
fallback_path = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
|
| 68 |
-
print(f"AVISO: Nenhuma configuração preferencial encontrada. Usando fallback: {fallback_path}")
|
| 69 |
-
if not fallback_path.exists():
|
| 70 |
-
print(f"ERRO: Arquivo de configuração fallback '{fallback_path}' não encontrado.")
|
| 71 |
return None
|
| 72 |
-
|
| 73 |
-
with open(
|
| 74 |
return yaml.safe_load(file)
|
| 75 |
|
| 76 |
-
def
|
| 77 |
-
"""
|
| 78 |
-
|
| 79 |
-
LTX_REPO = "Lightricks/LTX-Video"
|
| 80 |
-
|
| 81 |
-
if "checkpoint_path" not in config or "spatial_upscaler_model_path" not in config:
|
| 82 |
-
print("ERRO: Chaves de modelo não encontradas no arquivo de configuração do LTX.")
|
| 83 |
-
sys.exit(1)
|
| 84 |
-
|
| 85 |
-
models_to_download = {
|
| 86 |
-
config["checkpoint_path"]: "checkpoint principal",
|
| 87 |
-
config["spatial_upscaler_model_path"]: "upscaler espacial"
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
# O hf_hub_download já verifica o cache, mas vamos verificar o diretório final para clareza
|
| 91 |
-
# e para garantir que a lógica seja explícita.
|
| 92 |
-
for filename, description in models_to_download.items():
|
| 93 |
-
# A biblioteca huggingface_hub gerencia o local exato, então confiamos nela.
|
| 94 |
-
# A verificação aqui é para garantir que o download seja tentado.
|
| 95 |
-
print(f"Garantindo a existência do {description}: {filename}...")
|
| 96 |
-
try:
|
| 97 |
-
hf_hub_download(
|
| 98 |
-
repo_id=LTX_REPO, filename=filename,
|
| 99 |
-
local_dir=os.getenv("HF_HOME"), cache_dir=os.getenv("HF_HOME_CACHE"), token=os.getenv("HF_TOKEN")
|
| 100 |
-
)
|
| 101 |
-
print(f"{description.capitalize()} está disponível.")
|
| 102 |
-
except Exception as e:
|
| 103 |
-
print(f"ERRO ao baixar o {description}: {e}")
|
| 104 |
-
sys.exit(1)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def _download_seedvr_models():
|
| 108 |
-
"""Baixa os modelos do SeedVR, pulando os que já existem."""
|
| 109 |
-
print(f"\n--- Verificando Checkpoints do SeedVR em {SEEDVR_MODELS_DIR} ---")
|
| 110 |
-
SEEDVR_MODELS_DIR.mkdir(exist_ok=True)
|
| 111 |
-
|
| 112 |
-
model_files = {
|
| 113 |
-
"seedvr2_ema_7b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 114 |
-
"seedvr2_ema_7b_sharp_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 115 |
-
"seedvr2_ema_3b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 116 |
-
"ema_vae_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 117 |
-
"pos_emb.pt": "ByteDance-Seed/SeedVR2-3B",
|
| 118 |
-
"neg_emb.pt": "ByteDance-Seed/SeedVR2-3B"
|
| 119 |
-
}
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
if
|
| 124 |
-
|
| 125 |
-
|
| 126 |
hf_hub_download(
|
| 127 |
-
repo_id=repo_id,
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
cache_dir=os.getenv("HF_HOME_CACHE"),
|
| 131 |
token=os.getenv("HF_TOKEN"),
|
| 132 |
)
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
#
|
|
|
|
|
|
|
| 142 |
|
| 143 |
def main():
|
| 144 |
-
|
|
|
|
| 145 |
DEPS_DIR.mkdir(exist_ok=True)
|
|
|
|
| 146 |
|
| 147 |
# --- ETAPA 1: Clonar Repositórios ---
|
| 148 |
-
print("\n--- ETAPA 1:
|
| 149 |
for repo_name, repo_url in REPOS_TO_CLONE.items():
|
| 150 |
repo_path = DEPS_DIR / repo_name
|
| 151 |
-
if repo_path.is_dir():
|
| 152 |
-
print(f"Repositório '{repo_name}' já existe. Pulando.")
|
| 153 |
else:
|
| 154 |
print(f"Clonando '{repo_name}' de {repo_url}...")
|
| 155 |
run_command(["git", "clone", "--depth", "1", repo_url, str(repo_path)])
|
| 156 |
-
print(f"'{repo_name}' clonado com sucesso.")
|
| 157 |
|
| 158 |
-
# --- ETAPA 2: Baixar Modelos
|
| 159 |
-
print("\n--- ETAPA 2:
|
| 160 |
-
if not LTX_VIDEO_REPO_DIR.is_dir():
|
| 161 |
-
print(f"ERRO: Diretório '{LTX_VIDEO_REPO_DIR}' não encontrado. Execute a clonagem primeiro.")
|
| 162 |
-
sys.exit(1)
|
| 163 |
-
|
| 164 |
ltx_config = _load_ltx_config()
|
| 165 |
-
if ltx_config:
|
| 166 |
-
_download_ltx_models(ltx_config)
|
| 167 |
-
else:
|
| 168 |
print("ERRO: Não foi possível carregar a configuração do LTX-Video. Abortando.")
|
| 169 |
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
# --- ETAPA 3: Baixar Modelos
|
| 172 |
-
print("\n--- ETAPA 3:
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
print("\n\n--- Setup do Ambiente Concluído com Sucesso! ---")
|
| 176 |
-
print("Todos os repositórios e modelos
|
| 177 |
-
print("Você agora pode iniciar a aplicação principal.")
|
| 178 |
|
| 179 |
if __name__ == "__main__":
|
| 180 |
main()
|
|
|
|
| 2 |
#
|
| 3 |
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
#
|
| 5 |
+
# Versão 3.1.0 (Setup Unificado com LTX, SeedVR e VINCIE com Cache Robusto)
|
| 6 |
+
# - Orquestra a instalação de todos os repositórios e modelos para a suíte ADUC-SDR.
|
| 7 |
+
# - Usa snapshot_download para baixar dependências de forma eficiente e correta.
|
|
|
|
| 8 |
|
| 9 |
import os
|
| 10 |
import subprocess
|
| 11 |
import sys
|
| 12 |
from pathlib import Path
|
| 13 |
import yaml
|
| 14 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 15 |
|
| 16 |
+
# ==============================================================================
|
| 17 |
+
# --- CONFIGURAÇÃO DE PATHS E CACHE ---
|
| 18 |
+
# ==============================================================================
|
| 19 |
+
# Assume que /data é um volume persistente montado no contêiner.
|
| 20 |
DEPS_DIR = Path("/data")
|
| 21 |
+
CACHE_DIR = DEPS_DIR / ".cache" / "huggingface"
|
| 22 |
|
| 23 |
+
# --- Paths dos Módulos da Aplicação ---
|
| 24 |
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
|
| 25 |
+
SEEDVR_MODELS_DIR = DEPS_DIR / "models" / "SeedVR"
|
| 26 |
+
VINCIE_REPO_DIR = DEPS_DIR / "VINCIE"
|
| 27 |
+
VINCIE_CKPT_DIR = DEPS_DIR / "ckpt" / "VINCIE-3B"
|
| 28 |
|
| 29 |
+
# --- Repositórios Git para Clonar ---
|
|
|
|
|
|
|
|
|
|
| 30 |
REPOS_TO_CLONE = {
|
| 31 |
"LTX-Video": "https://huggingface.co/spaces/Lightricks/ltx-video-distilled",
|
| 32 |
"SeedVR": "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler",
|
| 33 |
+
"VINCIE": "https://github.com/ByteDance-Seed/VINCIE",
|
| 34 |
}
|
| 35 |
|
| 36 |
+
# ==============================================================================
|
| 37 |
+
# --- FUNÇÕES AUXILIARES ---
|
| 38 |
+
# ==============================================================================
|
| 39 |
+
|
| 40 |
def run_command(command, cwd=None):
|
| 41 |
+
"""Executa um comando no terminal de forma segura e com logs claros."""
|
| 42 |
print(f"Executando: {' '.join(command)}")
|
| 43 |
try:
|
| 44 |
subprocess.run(
|
| 45 |
+
command, check=True, cwd=cwd,
|
| 46 |
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
|
|
|
|
|
|
| 47 |
)
|
| 48 |
except subprocess.CalledProcessError as e:
|
| 49 |
+
print(f"ERRO: O comando falhou com o código {e.returncode}\nStderr:\n{e.stderr.strip()}")
|
| 50 |
sys.exit(1)
|
| 51 |
except FileNotFoundError:
|
| 52 |
+
print(f"ERRO: Comando '{command[0]}' não encontrado. Verifique se o git está instalado.")
|
| 53 |
sys.exit(1)
|
| 54 |
|
|
|
|
|
|
|
| 55 |
def _load_ltx_config():
|
| 56 |
"""Carrega o arquivo de configuração YAML do LTX-Video."""
|
| 57 |
print("--- Carregando Configuração do LTX-Video ---")
|
| 58 |
+
config_file = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
|
| 59 |
+
if not config_file.exists():
|
| 60 |
+
print(f"ERRO: Arquivo de configuração do LTX não encontrado em '{config_file}'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return None
|
| 62 |
+
print(f"Configuração LTX encontrada: {config_file}")
|
| 63 |
+
with open(config_file, "r") as file:
|
| 64 |
return yaml.safe_load(file)
|
| 65 |
|
| 66 |
+
def _ensure_hf_model(repo_id, filenames=None, allow_patterns=None, local_dir=None):
|
| 67 |
+
"""Função genérica para baixar um ou mais arquivos (hf_hub_download) ou um snapshot (snapshot_download)."""
|
| 68 |
+
if not repo_id: return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
print(f"Verificando/Baixando modelo do repositório: '{repo_id}'...")
|
| 71 |
+
try:
|
| 72 |
+
if filenames: # Baixa arquivos específicos
|
| 73 |
+
for filename in filenames:
|
| 74 |
+
if not filename: continue
|
| 75 |
hf_hub_download(
|
| 76 |
+
repo_id=repo_id, filename=filename, cache_dir=str(CACHE_DIR),
|
| 77 |
+
local_dir=str(local_dir) if local_dir else None,
|
| 78 |
+
#local_dir_use_symlinks=False,
|
|
|
|
| 79 |
token=os.getenv("HF_TOKEN"),
|
| 80 |
)
|
| 81 |
+
else: # Baixa um snapshot (partes de um repositório)
|
| 82 |
+
snapshot_download(
|
| 83 |
+
repo_id=repo_id, cache_dir=str(CACHE_DIR),
|
| 84 |
+
local_dir=str(local_dir) if local_dir else None,
|
| 85 |
+
allow_patterns=allow_patterns,
|
| 86 |
+
token=os.getenv("HF_TOKEN"),
|
| 87 |
+
)
|
| 88 |
+
print(f"-> Modelo '{repo_id}' está disponível.")
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"ERRO CRÍTICO ao baixar o modelo '{repo_id}': {e}")
|
| 91 |
+
sys.exit(1)
|
| 92 |
|
| 93 |
+
# ==============================================================================
|
| 94 |
+
# --- FUNÇÃO PRINCIPAL DE SETUP ---
|
| 95 |
+
# ==============================================================================
|
| 96 |
|
| 97 |
def main():
|
| 98 |
+
"""Orquestra todo o processo de setup do ambiente."""
|
| 99 |
+
print("--- Iniciando Setup do Ambiente ADUC-SDR (LTX + SeedVR + VINCIE) ---")
|
| 100 |
DEPS_DIR.mkdir(exist_ok=True)
|
| 101 |
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 102 |
|
| 103 |
# --- ETAPA 1: Clonar Repositórios ---
|
| 104 |
+
print("\n--- ETAPA 1: Verificando Repositórios Git ---")
|
| 105 |
for repo_name, repo_url in REPOS_TO_CLONE.items():
|
| 106 |
repo_path = DEPS_DIR / repo_name
|
| 107 |
+
if repo_path.is_dir():
|
| 108 |
+
print(f"Repositório '{repo_name}' já existe em '{repo_path}'. Pulando.")
|
| 109 |
else:
|
| 110 |
print(f"Clonando '{repo_name}' de {repo_url}...")
|
| 111 |
run_command(["git", "clone", "--depth", "1", repo_url, str(repo_path)])
|
| 112 |
+
print(f"-> '{repo_name}' clonado com sucesso.")
|
| 113 |
|
| 114 |
+
# --- ETAPA 2: Baixar Modelos LTX-Video e Dependências ---
|
| 115 |
+
print("\n--- ETAPA 2: Verificando Modelos LTX-Video e Dependências ---")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
ltx_config = _load_ltx_config()
|
| 117 |
+
if not ltx_config:
|
|
|
|
|
|
|
| 118 |
print("ERRO: Não foi possível carregar a configuração do LTX-Video. Abortando.")
|
| 119 |
sys.exit(1)
|
| 120 |
+
|
| 121 |
+
_ensure_hf_model(
|
| 122 |
+
repo_id="Lightricks/LTX-Video",
|
| 123 |
+
filenames=[
|
| 124 |
+
ltx_config.get("checkpoint_path"),
|
| 125 |
+
ltx_config.get("spatial_upscaler_model_path") # <-- Adicione esta linha
|
| 126 |
+
]
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
_ensure_hf_model(
|
| 130 |
+
repo_id=ltx_config.get("text_encoder_model_name_or_path"),
|
| 131 |
+
allow_patterns=["*.json", "*.safetensors"]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
enhancer_repos = [
|
| 135 |
+
ltx_config.get("prompt_enhancer_image_caption_model_name_or_path"),
|
| 136 |
+
ltx_config.get("prompt_enhancer_llm_model_name_or_path"),
|
| 137 |
+
]
|
| 138 |
+
for repo_id in filter(None, enhancer_repos):
|
| 139 |
+
_ensure_hf_model(repo_id=repo_id, allow_patterns=["*.json", "*.safetensors", "*.bin"])
|
| 140 |
|
| 141 |
+
# --- ETAPA 3: Baixar Modelos SeedVR ---
|
| 142 |
+
print("\n--- ETAPA 3: Verificando Modelos SeedVR ---")
|
| 143 |
+
SEEDVR_MODELS_DIR.mkdir(parents=True, exist_ok=True)
|
| 144 |
+
seedvr_files = {
|
| 145 |
+
"seedvr2_ema_7b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 146 |
+
"seedvr2_ema_7b_sharp_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 147 |
+
"ema_vae_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 148 |
+
}
|
| 149 |
+
for filename, repo_id in seedvr_files.items():
|
| 150 |
+
if not (SEEDVR_MODELS_DIR / filename).is_file():
|
| 151 |
+
_ensure_hf_model(repo_id=repo_id, filenames=[filename], local_dir=SEEDVR_MODELS_DIR)
|
| 152 |
+
else:
|
| 153 |
+
print(f"Arquivo SeedVR '{filename}' já existe. Pulando.")
|
| 154 |
+
|
| 155 |
+
# --- ETAPA 4: Baixar Modelos VINCIE ---
|
| 156 |
+
print("\n--- ETAPA 4: Verificando Modelos VINCIE ---")
|
| 157 |
+
VINCIE_CKPT_DIR.mkdir(parents=True, exist_ok=True)
|
| 158 |
+
_ensure_hf_model(repo_id="ByteDance-Seed/VINCIE-3B", local_dir=VINCIE_CKPT_DIR)
|
| 159 |
+
|
| 160 |
+
# Cria o symlink de compatibilidade, se necessário
|
| 161 |
+
repo_ckpt_dir = VINCIE_REPO_DIR / "ckpt"
|
| 162 |
+
repo_ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
link = repo_ckpt_dir / "VINCIE-3B"
|
| 164 |
+
if not link.exists():
|
| 165 |
+
link.symlink_to(VINCIE_CKPT_DIR.resolve(), target_is_directory=True)
|
| 166 |
+
print(f"-> Symlink de compatibilidade VINCIE criado: '{link}' -> '{VINCIE_CKPT_DIR.resolve()}'")
|
| 167 |
+
else:
|
| 168 |
+
print(f"-> Symlink de compatibilidade VINCIE já existe.")
|
| 169 |
|
| 170 |
+
print("\n\n--- ✅ Setup Completo do Ambiente ADUC-SDR Concluído com Sucesso! ---")
|
| 171 |
+
print("Todos os repositórios e modelos foram verificados e estão prontos para uso.")
|
|
|
|
| 172 |
|
| 173 |
if __name__ == "__main__":
|
| 174 |
main()
|
start.sh
CHANGED
|
@@ -1,49 +1,88 @@
|
|
| 1 |
-
#!/
|
| 2 |
-
set -euo pipefail
|
| 3 |
|
| 4 |
|
|
|
|
| 5 |
|
| 6 |
-
tree -L
|
| 7 |
-
tree -L 4 /data
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
export LTXV_FRAME_LOG_EVERY=8
|
| 16 |
-
export LTXV_DEBUG=1
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
#if [ -f "/app/builder.sh" ]; then
|
| 26 |
-
# /bin/bash /app/builder.sh
|
| 27 |
-
# echo "✅ Builder finalizado."
|
| 28 |
-
#else
|
| 29 |
-
# echo "⚠️ Aviso: builder.sh não encontrado. Pulando etapa de compilação de dependências."
|
| 30 |
-
#fi
|
| 31 |
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
|
|
|
| 2 |
|
| 3 |
|
| 4 |
+
cp /app/LTX-Video/. /data/LTX-Video -rdfv
|
| 5 |
|
| 6 |
+
tree -L 6 /data
|
|
|
|
| 7 |
|
| 8 |
+
# ==============================================================================
|
| 9 |
+
# GERENCIAMENTO DE LOGS NA INICIALIZAÇÃO
|
| 10 |
+
# ==============================================================================
|
| 11 |
+
mkdir /data/logs
|
| 12 |
+
LOG_FILE="/data/logs/session.log"
|
| 13 |
|
| 14 |
+
# Verifica se o arquivo de log da sessão anterior existe e não está vazio
|
| 15 |
+
if [ -f "$LOG_FILE" ] && [ -s "$LOG_FILE" ]; then
|
| 16 |
+
echo "[STARTUP] Log da sessão anterior encontrado. Preparando para upload."
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# Cria um nome de arquivo com timestamp para o upload
|
| 19 |
+
TODAY=$(date +%Y-%m-%d)
|
| 20 |
+
TIMESTAMP=$(date +%H-%M-%S)
|
| 21 |
+
UPLOAD_FILENAME="log-${TIMESTAMP}.txt"
|
| 22 |
+
export REPO_PATH="logs/${TODAY}/${UPLOAD_FILENAME}"
|
| 23 |
|
| 24 |
+
# Move o log antigo para um local temporário para evitar que a aplicação comece a escrever nele
|
| 25 |
+
TEMP_LOG_PATH="/data/previous_session.log"
|
| 26 |
+
mv "$LOG_FILE" "$TEMP_LOG_PATH"
|
| 27 |
+
|
| 28 |
+
echo "[STARTUP] Fazendo upload de '$TEMP_LOG_PATH' para o repositório em '$REPO_PATH'..."
|
| 29 |
|
| 30 |
+
# Executa o script de upload do Python em segundo plano para não bloquear a inicialização
|
| 31 |
+
# O token HF_TOKEN deve estar definido como uma variável de ambiente no seu contêiner
|
| 32 |
+
python - <<'PY' &
|
| 33 |
+
import os
|
| 34 |
+
import time
|
| 35 |
+
from huggingface_hub import HfApi, HfFolder
|
| 36 |
|
| 37 |
+
# Adiciona uma pequena espera para garantir que a rede esteja pronta
|
| 38 |
+
time.sleep(5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
repo = os.environ.get("SELF_HF_REPO_ID", "eeuuia/Tmp")
|
| 41 |
+
token = os.getenv("HF_TOKEN")
|
| 42 |
+
log_to_upload = "/data/previous_session.log"
|
| 43 |
+
repo_path = os.getenv("REPO_PATH",'logs/log.log')
|
| 44 |
|
| 45 |
+
if not token:
|
| 46 |
+
print("[UPLOAD_SCRIPT] AVISO: HF_TOKEN ausente; upload do log desabilitado.")
|
| 47 |
+
# Limpa o arquivo temporário mesmo assim
|
| 48 |
+
if os.path.exists(log_to_upload):
|
| 49 |
+
os.remove(log_to_upload)
|
| 50 |
+
exit()
|
| 51 |
|
| 52 |
+
if not repo_path:
|
| 53 |
+
print("[UPLOAD_SCRIPT] ERRO: REPO_PATH não definido.")
|
| 54 |
+
exit()
|
| 55 |
|
| 56 |
+
try:
|
| 57 |
+
print(f"[UPLOAD_SCRIPT] Iniciando upload para {repo}...")
|
| 58 |
+
api = HfApi(token=token)
|
| 59 |
+
api.upload_file(
|
| 60 |
+
path_or_fileobj=log_to_upload,
|
| 61 |
+
path_in_repo=repo_path,
|
| 62 |
+
repo_id=repo,
|
| 63 |
+
repo_type="model",
|
| 64 |
+
)
|
| 65 |
+
print(f"[UPLOAD_SCRIPT] Upload de log concluído com sucesso para: {repo_path}")
|
| 66 |
+
finally:
|
| 67 |
+
# Garante que o arquivo de log temporário seja sempre removido após a tentativa de upload
|
| 68 |
+
if os.path.exists(log_to_upload):
|
| 69 |
+
os.remove(log_to_upload)
|
| 70 |
+
print("[UPLOAD_SCRIPT] Arquivo de log temporário limpo.")
|
| 71 |
+
PY
|
| 72 |
+
|
| 73 |
+
else
|
| 74 |
+
echo "[STARTUP] Nenhum log da sessão anterior encontrado. Iniciando com um log limpo."
|
| 75 |
+
fi
|
| 76 |
|
| 77 |
+
# ==============================================================================
|
| 78 |
+
# INICIALIZAÇÃO DA APLICAÇÃO PRINCIPAL
|
| 79 |
+
# ==============================================================================
|
| 80 |
+
echo "[STARTUP] Iniciando a aplicação principal Gradio (app.py)..."
|
| 81 |
|
| 82 |
+
# Executa o setup.py primeiro para garantir que as dependências estão prontas
|
| 83 |
+
python /app/setup.py
|
| 84 |
+
|
| 85 |
+
# Inicia a aplicação Gradio
|
| 86 |
+
# O `exec` substitui o processo do shell pelo processo do python,
|
| 87 |
+
# o que é uma boa prática para scripts de inicialização de contêineres.
|
| 88 |
+
exec python /app/app.py
|