Update api/ltx_server_refactored.py
Browse files- api/ltx_server_refactored.py +54 -49
api/ltx_server_refactored.py
CHANGED
|
@@ -1,17 +1,7 @@
|
|
| 1 |
# ltx_server_refactored.py — VideoService (Modular Version with Simple Overlap Chunking)
|
| 2 |
|
| 3 |
-
# --- 0. WARNINGS E AMBIENTE ---
|
| 4 |
import warnings
|
| 5 |
-
warnings.filterwarnings("ignore", category=UserWarning)
|
| 6 |
-
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 7 |
-
warnings.filterwarnings("ignore", message=".*")
|
| 8 |
from huggingface_hub import logging
|
| 9 |
-
logging.set_verbosity_error()
|
| 10 |
-
logging.set_verbosity_warning()
|
| 11 |
-
logging.set_verbosity_info()
|
| 12 |
-
logging.set_verbosity_debug()
|
| 13 |
-
LTXV_DEBUG=1
|
| 14 |
-
LTXV_FRAME_LOG_EVERY=8
|
| 15 |
import os, subprocess, shlex, tempfile
|
| 16 |
import torch
|
| 17 |
import json
|
|
@@ -38,8 +28,18 @@ from einops import rearrange
|
|
| 38 |
import torch.nn.functional as F
|
| 39 |
from managers.vae_manager import vae_manager_singleton
|
| 40 |
from tools.video_encode_tool import video_encode_tool_singleton
|
|
|
|
| 41 |
DEPS_DIR = Path("/data")
|
| 42 |
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
# (Todas as funções de setup, helpers e inicialização da classe permanecem inalteradas)
|
| 45 |
# ... (run_setup, add_deps_to_path, _query_gpu_processes_via_nvml, etc.)
|
|
@@ -99,27 +99,6 @@ from api.ltx.inference import (
|
|
| 99 |
)
|
| 100 |
|
| 101 |
class VideoService:
|
| 102 |
-
def __init__(self):
|
| 103 |
-
t0 = time.perf_counter()
|
| 104 |
-
print("[DEBUG] Inicializando VideoService...")
|
| 105 |
-
self.device = gpu_manager.get_ltx_device()
|
| 106 |
-
print(f"[DEBUG] LTX foi alocado para o dispositivo: {self.device}")
|
| 107 |
-
|
| 108 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 109 |
-
self.config = self._load_config()
|
| 110 |
-
self.pipeline, self.latent_upsampler = self._load_models()
|
| 111 |
-
self.pipeline.to(self.device)
|
| 112 |
-
if self.latent_upsampler:
|
| 113 |
-
self.latent_upsampler.to(self.device)
|
| 114 |
-
self._apply_precision_policy()
|
| 115 |
-
vae_manager_singleton.attach_pipeline(
|
| 116 |
-
self.pipeline,
|
| 117 |
-
device=self.device,
|
| 118 |
-
autocast_dtype=self.runtime_autocast_dtype
|
| 119 |
-
)
|
| 120 |
-
self._tmp_dirs = set()
|
| 121 |
-
print(f"[DEBUG] VideoService pronto. boot_time={time.perf_counter()-t0:.3f}s")
|
| 122 |
-
|
| 123 |
def _load_config(self):
|
| 124 |
base = LTX_VIDEO_REPO_DIR / "configs"
|
| 125 |
config_path = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
|
|
@@ -143,20 +122,6 @@ class VideoService:
|
|
| 143 |
self._log_gpu_memory("Após finalize")
|
| 144 |
except Exception as e:
|
| 145 |
print(f"[DEBUG] Log GPU pós-finalize falhou: {e}")
|
| 146 |
-
|
| 147 |
-
def move_to_device(self, device):
|
| 148 |
-
"""Move os modelos do pipeline para o dispositivo especificado."""
|
| 149 |
-
print(f"[LTX] Movendo modelos para {device}...")
|
| 150 |
-
self.pipeline.to(device)
|
| 151 |
-
if self.latent_upsampler:
|
| 152 |
-
self.latent_upsampler.to(device)
|
| 153 |
-
self.device = device
|
| 154 |
-
|
| 155 |
-
def move_to_cpu(self):
|
| 156 |
-
"""Move os modelos para a CPU para liberar VRAM."""
|
| 157 |
-
self.move_to_device(torch.device("cpu"))
|
| 158 |
-
if torch.cuda.is_available():
|
| 159 |
-
torch.cuda.empty_cache()
|
| 160 |
|
| 161 |
def _load_models(self):
|
| 162 |
t0 = time.perf_counter()
|
|
@@ -559,11 +524,51 @@ class VideoService:
|
|
| 559 |
final_pixel_tensor = torch.cat(pixel_chunks_to_concat, dim=2)
|
| 560 |
final_video_path = self._save_and_log_video(final_pixel_tensor, f"final_concatenated_{seed}", fps, temp_dir, results_dir, seed)
|
| 561 |
return final_video_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
-
|
|
|
|
| 565 |
print("Criando instância do VideoService...")
|
| 566 |
video_generation_service = VideoService()
|
| 567 |
-
print("Instância do VideoService pronta.")
|
| 568 |
-
self.device = gpu_manager.get_ltx_device()
|
| 569 |
-
print(f"[DEBUG] LTX foi alocado para o dispositivo: {self.device}")
|
|
|
|
| 1 |
# ltx_server_refactored.py — VideoService (Modular Version with Simple Overlap Chunking)
|
| 2 |
|
|
|
|
| 3 |
import warnings
|
|
|
|
|
|
|
|
|
|
| 4 |
from huggingface_hub import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import os, subprocess, shlex, tempfile
|
| 6 |
import torch
|
| 7 |
import json
|
|
|
|
| 28 |
import torch.nn.functional as F
|
| 29 |
from managers.vae_manager import vae_manager_singleton
|
| 30 |
from tools.video_encode_tool import video_encode_tool_singleton
|
| 31 |
+
|
| 32 |
DEPS_DIR = Path("/data")
|
| 33 |
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
|
| 34 |
+
logging.set_verbosity_error()
|
| 35 |
+
logging.set_verbosity_warning()
|
| 36 |
+
logging.set_verbosity_info()
|
| 37 |
+
logging.set_verbosity_debug()
|
| 38 |
+
LTXV_DEBUG=1
|
| 39 |
+
LTXV_FRAME_LOG_EVERY=8
|
| 40 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 41 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 42 |
+
warnings.filterwarnings("ignore", message=".*")
|
| 43 |
|
| 44 |
# (Todas as funções de setup, helpers e inicialização da classe permanecem inalteradas)
|
| 45 |
# ... (run_setup, add_deps_to_path, _query_gpu_processes_via_nvml, etc.)
|
|
|
|
| 99 |
)
|
| 100 |
|
| 101 |
class VideoService:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
def _load_config(self):
|
| 103 |
base = LTX_VIDEO_REPO_DIR / "configs"
|
| 104 |
config_path = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
|
|
|
|
| 122 |
self._log_gpu_memory("Após finalize")
|
| 123 |
except Exception as e:
|
| 124 |
print(f"[DEBUG] Log GPU pós-finalize falhou: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
def _load_models(self):
|
| 127 |
t0 = time.perf_counter()
|
|
|
|
| 524 |
final_pixel_tensor = torch.cat(pixel_chunks_to_concat, dim=2)
|
| 525 |
final_video_path = self._save_and_log_video(final_pixel_tensor, f"final_concatenated_{seed}", fps, temp_dir, results_dir, seed)
|
| 526 |
return final_video_path
|
| 527 |
+
|
| 528 |
+
def __init__(self):
|
| 529 |
+
t0 = time.perf_counter()
|
| 530 |
+
print("[DEBUG] Inicializando VideoService...")
|
| 531 |
+
|
| 532 |
+
# 1. Obter o dispositivo alvo a partir do gerenciador
|
| 533 |
+
# Não definimos `self.device` ainda, apenas guardamos o alvo.
|
| 534 |
+
target_device = gpu_manager.get_ltx_device()
|
| 535 |
+
print(f"[DEBUG] LTX foi alocado para o dispositivo: {target_device}")
|
| 536 |
+
|
| 537 |
+
# 2. Carregar a configuração e os modelos (na CPU, como a função _load_models faz)
|
| 538 |
+
self.config = self._load_config()
|
| 539 |
+
self.pipeline, self.latent_upsampler = self._load_models()
|
| 540 |
+
|
| 541 |
+
# 3. Mover os modelos para o dispositivo alvo e definir `self.device`
|
| 542 |
+
self.move_to_device(target_device) # Usando a função que já criamos!
|
| 543 |
+
|
| 544 |
+
# 4. Configurar o resto dos componentes com o dispositivo correto
|
| 545 |
+
self._apply_precision_policy()
|
| 546 |
+
vae_manager_singleton.attach_pipeline(
|
| 547 |
+
self.pipeline,
|
| 548 |
+
device=self.device, # Agora `self.device` está correto
|
| 549 |
+
autocast_dtype=self.runtime_autocast_dtype
|
| 550 |
+
)
|
| 551 |
+
self._tmp_dirs = set()
|
| 552 |
+
print(f"[DEBUG] VideoService pronto. boot_time={time.perf_counter()-t0:.3f}s")
|
| 553 |
+
|
| 554 |
+
# A função move_to_device que criamos antes é essencial aqui
|
| 555 |
+
def move_to_device(self, device):
|
| 556 |
+
"""Move os modelos do pipeline para o dispositivo especificado."""
|
| 557 |
+
print(f"[LTX] Movendo modelos para {device}...")
|
| 558 |
+
self.device = torch.device(device) # Garante que é um objeto torch.device
|
| 559 |
+
self.pipeline.to(self.device)
|
| 560 |
+
if self.latent_upsampler:
|
| 561 |
+
self.latent_upsampler.to(self.device)
|
| 562 |
+
print(f"[LTX] Modelos agora estão em {self.device}.")
|
| 563 |
|
| 564 |
+
def move_to_cpu(self):
|
| 565 |
+
"""Move os modelos para a CPU para liberar VRAM."""
|
| 566 |
+
self.move_to_device(torch.device("cpu"))
|
| 567 |
+
if torch.cuda.is_available():
|
| 568 |
+
torch.cuda.empty_cache()
|
| 569 |
|
| 570 |
+
|
| 571 |
+
# Instanciação limpa, sem usar `self` fora da classe.
|
| 572 |
print("Criando instância do VideoService...")
|
| 573 |
video_generation_service = VideoService()
|
| 574 |
+
print("Instância do VideoService pronta.")
|
|
|
|
|
|