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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ltx_manager_helpers.py
|
| 2 |
+
# Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
|
| 3 |
+
# (Licenciamento e cabeçalhos permanecem os mesmos)
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import gc
|
| 7 |
+
import os
|
| 8 |
+
import yaml
|
| 9 |
+
import logging
|
| 10 |
+
import huggingface_hub
|
| 11 |
+
import time
|
| 12 |
+
import threading
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
from optimization import optimize_ltx_worker, can_optimize_fp8
|
| 16 |
+
from hardware_manager import hardware_manager
|
| 17 |
+
from inference import create_ltx_video_pipeline, calculate_padding
|
| 18 |
+
from ltx_video.pipelines.pipeline_ltx_video import LatentConditioningItem
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
class LtxWorker:
|
| 23 |
+
"""
|
| 24 |
+
Representa uma única instância da pipeline LTX-Video em um dispositivo específico.
|
| 25 |
+
Gerencia o carregamento do modelo para a CPU e a movimentação de/para a GPU.
|
| 26 |
+
"""
|
| 27 |
+
def __init__(self, device_id, ltx_config_file):
|
| 28 |
+
# ... (código do LtxWorker __init__ permanece o mesmo) ...
|
| 29 |
+
self.cpu_device = torch.device('cpu')
|
| 30 |
+
self.device = torch.device(device_id if torch.cuda.is_available() else 'cpu')
|
| 31 |
+
logger.info(f"LTX Worker ({self.device}): Inicializando com config '{ltx_config_file}'...")
|
| 32 |
+
|
| 33 |
+
with open(ltx_config_file, "r") as file:
|
| 34 |
+
self.config = yaml.safe_load(file)
|
| 35 |
+
|
| 36 |
+
self.is_distilled = "distilled" in self.config.get("checkpoint_path", "")
|
| 37 |
+
|
| 38 |
+
models_dir = "downloaded_models_gradio"
|
| 39 |
+
|
| 40 |
+
logger.info(f"LTX Worker ({self.device}): Carregando modelo para a CPU...")
|
| 41 |
+
model_path = os.path.join(models_dir, self.config["checkpoint_path"])
|
| 42 |
+
if not os.path.exists(model_path):
|
| 43 |
+
model_path = huggingface_hub.hf_hub_download(
|
| 44 |
+
repo_id="Lightricks/LTX-Video", filename=self.config["checkpoint_path"],
|
| 45 |
+
local_dir=models_dir, local_dir_use_symlinks=False
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
self.pipeline = create_ltx_video_pipeline(
|
| 49 |
+
ckpt_path=model_path, precision=self.config["precision"],
|
| 50 |
+
text_encoder_model_name_or_path=self.config["text_encoder_model_name_or_path"],
|
| 51 |
+
sampler=self.config["sampler"], device='cpu'
|
| 52 |
+
)
|
| 53 |
+
logger.info(f"LTX Worker ({self.device}): Modelo pronto na CPU. É um modelo destilado? {self.is_distilled}")
|
| 54 |
+
|
| 55 |
+
def to_gpu(self):
|
| 56 |
+
"""Move o pipeline para a GPU designada E OTIMIZA SE POSSÍVEL."""
|
| 57 |
+
if self.device.type == 'cpu': return
|
| 58 |
+
logger.info(f"LTX Worker: Movendo pipeline para a GPU {self.device}...")
|
| 59 |
+
self.pipeline.to(self.device)
|
| 60 |
+
|
| 61 |
+
# A otimização agora ocorre aqui, uma única vez, quando o modelo vai para a GPU.
|
| 62 |
+
if self.device.type == 'cuda' and can_optimize_fp8():
|
| 63 |
+
logger.info(f"LTX Worker ({self.device}): GPU com suporte a FP8 detectada. Iniciando otimização...")
|
| 64 |
+
optimize_ltx_worker(self)
|
| 65 |
+
logger.info(f"LTX Worker ({self.device}): Otimização concluída.")
|
| 66 |
+
elif self.device.type == 'cuda':
|
| 67 |
+
logger.info(f"LTX Worker ({self.device}): Otimização FP8 não suportada ou desativada.")
|
| 68 |
+
|
| 69 |
+
def to_cpu(self):
|
| 70 |
+
"""Move o pipeline de volta para a CPU e libera a memória da GPU."""
|
| 71 |
+
if self.device.type == 'cpu': return
|
| 72 |
+
logger.info(f"LTX Worker: Descarregando pipeline da GPU {self.device}...")
|
| 73 |
+
self.pipeline.to('cpu')
|
| 74 |
+
gc.collect()
|
| 75 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 76 |
+
|
| 77 |
+
def generate_video_fragment_internal(self, **kwargs):
|
| 78 |
+
"""Invoca a pipeline de geração."""
|
| 79 |
+
return self.pipeline(**kwargs).images
|
| 80 |
+
|
| 81 |
+
class LtxPoolManager:
|
| 82 |
+
"""
|
| 83 |
+
Gerencia um pool de LtxWorkers para otimizar o uso de múltiplas GPUs.
|
| 84 |
+
NOVO MODO "HOT START": Mantém todos os modelos carregados na VRAM para latência mínima.
|
| 85 |
+
"""
|
| 86 |
+
def __init__(self, device_ids, ltx_config_file):
|
| 87 |
+
logger.info(f"LTX POOL MANAGER: Criando workers para os dispositivos: {device_ids}")
|
| 88 |
+
self.workers = [LtxWorker(dev_id, ltx_config_file) for dev_id in device_ids]
|
| 89 |
+
self.current_worker_index = 0
|
| 90 |
+
self.lock = threading.Lock()
|
| 91 |
+
|
| 92 |
+
# ######################################################################
|
| 93 |
+
# ## MUDANÇA 1: PRÉ-AQUECIMENTO DAS GPUs ##
|
| 94 |
+
# ######################################################################
|
| 95 |
+
if all(w.device.type == 'cuda' for w in self.workers):
|
| 96 |
+
logger.info("LTX POOL MANAGER: MODO HOT START ATIVADO. Pré-aquecendo todas as GPUs...")
|
| 97 |
+
for worker in self.workers:
|
| 98 |
+
worker.to_gpu()
|
| 99 |
+
logger.info("LTX POOL MANAGER: Todas as GPUs estão quentes e prontas.")
|
| 100 |
+
else:
|
| 101 |
+
logger.info("LTX POOL MANAGER: Operando em modo CPU ou misto. O pré-aquecimento de GPU foi ignorado.")
|
| 102 |
+
# ######################################################################
|
| 103 |
+
|
| 104 |
+
def _prepare_and_log_params(self, worker_to_use, **kwargs):
|
| 105 |
+
# ... (Esta função permanece exatamente a mesma) ...
|
| 106 |
+
target_device = worker_to_use.device
|
| 107 |
+
height, width = kwargs['height'], kwargs['width']
|
| 108 |
+
|
| 109 |
+
conditioning_data = kwargs.get('conditioning_items_data', [])
|
| 110 |
+
final_conditioning_items = []
|
| 111 |
+
conditioning_log_details = []
|
| 112 |
+
for i, item in enumerate(conditioning_data):
|
| 113 |
+
if hasattr(item, 'latent_tensor'):
|
| 114 |
+
item.latent_tensor = item.latent_tensor.to(target_device)
|
| 115 |
+
final_conditioning_items.append(item)
|
| 116 |
+
conditioning_log_details.append(
|
| 117 |
+
f" - Item {i}: frame={item.media_frame_number}, strength={item.conditioning_strength:.2f}, shape={list(item.latent_tensor.shape)}"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
first_pass_config = worker_to_use.config.get("first_pass", {})
|
| 121 |
+
padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
|
| 122 |
+
padding_vals = calculate_padding(height, width, padded_h, padded_w)
|
| 123 |
+
|
| 124 |
+
pipeline_params = {
|
| 125 |
+
"height": padded_h, "width": padded_w,
|
| 126 |
+
"num_frames": kwargs['video_total_frames'], "frame_rate": kwargs['video_fps'],
|
| 127 |
+
"generator": torch.Generator(device=target_device).manual_seed(int(kwargs.get('seed', time.time())) + kwargs['current_fragment_index']),
|
| 128 |
+
"conditioning_items": final_conditioning_items,
|
| 129 |
+
"is_video": True, "vae_per_channel_normalize": True,
|
| 130 |
+
"decode_timestep": float(kwargs.get('decode_timestep', worker_to_use.config.get("decode_timestep", 0.05))),
|
| 131 |
+
"image_cond_noise_scale": float(kwargs.get('image_cond_noise_scale', 0.0)),
|
| 132 |
+
"prompt": kwargs['motion_prompt'],
|
| 133 |
+
"negative_prompt": kwargs.get('negative_prompt', "blurry, distorted, static, bad quality, artifacts"),
|
| 134 |
+
"guidance_scale": float(kwargs.get('guidance_scale', 2.0)),
|
| 135 |
+
"stg_scale": float(kwargs.get('stg_scale', 0.025)),
|
| 136 |
+
"rescaling_scale": float(kwargs.get('rescaling_scale', 0.15)),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if worker_to_use.is_distilled:
|
| 140 |
+
pipeline_params["timesteps"] = first_pass_config.get("timesteps")
|
| 141 |
+
pipeline_params["num_inference_steps"] = len(pipeline_params["timesteps"]) if "timesteps" in first_pass_config else 20
|
| 142 |
+
else:
|
| 143 |
+
pipeline_params["num_inference_steps"] = int(kwargs.get('num_inference_steps', 20))
|
| 144 |
+
|
| 145 |
+
log_friendly_params = pipeline_params.copy()
|
| 146 |
+
log_friendly_params.pop('generator', None)
|
| 147 |
+
log_friendly_params.pop('conditioning_items', None)
|
| 148 |
+
|
| 149 |
+
logger.info("="*60)
|
| 150 |
+
logger.info(f"CHAMADA AO PIPELINE LTX NO DISPOSITIVO: {worker_to_use.device}")
|
| 151 |
+
logger.info(f"Modelo: {'Distilled' if worker_to_use.is_distilled else 'Base'}")
|
| 152 |
+
logger.info("-" * 20 + " PARÂMETROS DA PIPELINE " + "-" * 20)
|
| 153 |
+
logger.info(json.dumps(log_friendly_params, indent=2))
|
| 154 |
+
logger.info("-" * 20 + " ITENS DE CONDICIONAMENTO " + "-" * 19)
|
| 155 |
+
logger.info("\n".join(conditioning_log_details) if conditioning_log_details else " - Nenhum")
|
| 156 |
+
logger.info("="*60)
|
| 157 |
+
|
| 158 |
+
return pipeline_params, padding_vals
|
| 159 |
+
|
| 160 |
+
def _execute_on_worker(self, execution_fn, **kwargs):
|
| 161 |
+
"""
|
| 162 |
+
Função unificada para selecionar um worker e executar uma tarefa,
|
| 163 |
+
sem a lógica de carregar/descarregar.
|
| 164 |
+
"""
|
| 165 |
+
worker_to_use = None
|
| 166 |
+
try:
|
| 167 |
+
with self.lock:
|
| 168 |
+
worker_to_use = self.workers[self.current_worker_index]
|
| 169 |
+
self.current_worker_index = (self.current_worker_index + 1) % len(self.workers)
|
| 170 |
+
|
| 171 |
+
pipeline_params, padding_vals = self._prepare_and_log_params(worker_to_use, **kwargs)
|
| 172 |
+
|
| 173 |
+
result = execution_fn(worker_to_use, pipeline_params, **kwargs)
|
| 174 |
+
|
| 175 |
+
return result, padding_vals
|
| 176 |
+
|
| 177 |
+
except Exception as e:
|
| 178 |
+
logger.error(f"LTX POOL MANAGER: Erro durante a execução em {worker_to_use.device if worker_to_use else 'N/A'}: {e}", exc_info=True)
|
| 179 |
+
raise e
|
| 180 |
+
finally:
|
| 181 |
+
# Apenas limpa o cache da GPU, não descarrega o modelo.
|
| 182 |
+
if worker_to_use and worker_to_use.device.type == 'cuda':
|
| 183 |
+
with torch.cuda.device(worker_to_use.device):
|
| 184 |
+
gc.collect()
|
| 185 |
+
torch.cuda.empty_cache()
|
| 186 |
+
|
| 187 |
+
def generate_latent_fragment(self, **kwargs) -> (torch.Tensor, tuple):
|
| 188 |
+
"""
|
| 189 |
+
Orquestra a geração de um novo fragmento de vídeo a partir do ruído.
|
| 190 |
+
"""
|
| 191 |
+
def execution_logic(worker, params, **inner_kwargs):
|
| 192 |
+
params['output_type'] = "latent"
|
| 193 |
+
with torch.no_grad():
|
| 194 |
+
return worker.generate_video_fragment_internal(**params)
|
| 195 |
+
|
| 196 |
+
return self._execute_on_worker(execution_logic, **kwargs)
|
| 197 |
+
|
| 198 |
+
def refine_latents(self, upscaled_latents: torch.Tensor, **kwargs) -> (torch.Tensor, tuple):
|
| 199 |
+
"""
|
| 200 |
+
Orquestra um passe de difusão curto em latentes já existentes para refinamento.
|
| 201 |
+
"""
|
| 202 |
+
def execution_logic(worker, params, **inner_kwargs):
|
| 203 |
+
params['latents'] = upscaled_latents.to(worker.device, dtype=worker.pipeline.transformer.dtype)
|
| 204 |
+
params['strength'] = inner_kwargs.get('denoise_strength', 0.4)
|
| 205 |
+
params['num_inference_steps'] = int(inner_kwargs.get('refine_steps', 10))
|
| 206 |
+
params['output_type'] = "latent"
|
| 207 |
+
|
| 208 |
+
logger.info("LTX POOL MANAGER: Iniciando passe de refinamento (denoise) em latentes de alta resolução.")
|
| 209 |
+
|
| 210 |
+
with torch.no_grad():
|
| 211 |
+
return worker.generate_video_fragment_internal(**params)
|
| 212 |
+
|
| 213 |
+
return self._execute_on_worker(execution_logic, upscaled_latents=upscaled_latents, **kwargs)
|
| 214 |
+
|
| 215 |
+
# --- Instanciação Singleton ---
|
| 216 |
+
logger.info("Lendo config.yaml para inicializar o LTX Pool Manager...")
|
| 217 |
+
with open("config.yaml", 'r') as f:
|
| 218 |
+
config = yaml.safe_load(f)
|
| 219 |
+
ltx_gpus_required = config['specialists']['ltx']['gpus_required']
|
| 220 |
+
ltx_device_ids = hardware_manager.allocate_gpus('LTX', ltx_gpus_required)
|
| 221 |
+
ltx_config_path = config['specialists']['ltx']['config_file']
|
| 222 |
+
ltx_manager_singleton = LtxPoolManager(device_ids=ltx_device_ids, ltx_config_file=ltx_config_path)
|
| 223 |
+
logger.info("Especialista de Vídeo (LTX) pronto.")
|