eeuuia commited on
Commit
2869224
·
verified ·
1 Parent(s): 8906472

Update api/ltx/ltx_aduc_manager.py

Browse files
Files changed (1) hide show
  1. api/ltx/ltx_aduc_manager.py +49 -65
api/ltx/ltx_aduc_manager.py CHANGED
@@ -5,7 +5,6 @@
5
  import logging
6
  import torch
7
  import sys
8
- import os
9
  from pathlib import Path
10
  import threading
11
  import queue
@@ -14,10 +13,9 @@ import yaml
14
  from huggingface_hub import hf_hub_download
15
  from typing import List, Optional, Callable, Any, Tuple, Dict
16
 
17
- # --- Importa o gerenciador de GPUs e os builders de baixo nível ---
18
  from managers.gpu_manager import gpu_manager
19
- # Importa os builders que foram movidos para ltx_utils
20
- from api.ltx.ltx_utils import _build_ltx_transformer_pipeline, _build_vae, _build_latent_upscaler
21
 
22
  # --- Adiciona o path do LTX-Video para importação de tipos ---
23
  LTX_VIDEO_REPO_DIR = Path("/data/LTX-Video")
@@ -29,76 +27,56 @@ add_deps_to_path()
29
 
30
  from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
31
  from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
32
- from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
33
-
34
- # ==============================================================================
35
- # --- FUNÇÕES DE ORQUESTRAÇÃO DA CONSTRUÇÃO (Internas ao Manager) ---
36
- # ==============================================================================
37
-
38
- def _load_config() -> Dict:
39
- """Helper centralizado para carregar o arquivo de configuração YAML."""
40
- config_path = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
41
- with open(config_path, "r") as file:
42
- return yaml.safe_load(file)
43
-
44
- def get_main_ltx_pipeline() -> LTXVideoPipeline:
45
- """Orquestra a construção do Pipeline Transformer principal (sem o VAE)."""
46
- config = _load_config()
47
- precision = config.get("precision", "bfloat16")
48
- ckpt_path_str = hf_hub_download(repo_id="Lightricks/LTX-Video", filename=config["checkpoint_path"], cache_dir=os.environ.get("HF_HOME"))
49
- return _build_ltx_transformer_pipeline(ckpt_path_str, config, precision)
50
-
51
- def get_main_vae() -> CausalVideoAutoencoder:
52
- """Orquestra a construção do VAE principal."""
53
- config = _load_config()
54
- precision = config.get("precision", "bfloat16")
55
- ckpt_path_str = hf_hub_download(repo_id="Lightricks/LTX-Video", filename=config["checkpoint_path"], cache_dir=os.environ.get("HF_HOME"))
56
- return _build_vae(ckpt_path_str, precision)
57
 
58
  # ==============================================================================
59
  # --- CLASSES DE WORKER (Especialistas em Tarefas) ---
60
  # ==============================================================================
61
 
62
  class BaseWorker(threading.Thread):
63
- def __init__(self, worker_id: int, device: torch.device):
 
64
  super().__init__()
65
  self.worker_id = worker_id
66
  self.device = device
 
67
  self.is_healthy = False
68
  self.is_busy = False
69
  self.daemon = True
70
 
71
  def run(self):
 
72
  try:
73
- self._load_models()
 
 
74
  self.is_healthy = True
75
  logging.info(f"✅ Worker {self.worker_id} ({self.__class__.__name__}) on {self.device} is healthy and ready.")
76
  except Exception:
77
  self.is_healthy = False
78
  logging.error(f"❌ Worker {self.worker_id} on {self.device} FAILED to initialize!", exc_info=True)
79
 
80
- def _load_models(self):
81
- raise NotImplementedError
 
82
 
83
  def get_status(self) -> Tuple[bool, bool]:
84
  return self.is_healthy, self.is_busy
85
 
86
  class LTXMainWorker(BaseWorker):
87
- def __init__(self, worker_id: int, device: torch.device):
88
- super().__init__(worker_id, device)
89
- self.pipeline: Optional[LTXVideoPipeline] = None
 
90
  self.autocast_dtype: torch.dtype = torch.float32
91
 
92
- def _load_models(self):
93
- logging.info(f"[LTXWorker-{self.worker_id}] Loading models to CPU...")
94
- self.pipeline = get_main_ltx_pipeline()
95
  self._set_precision_policy()
96
- logging.info(f"[LTXWorker-{self.worker_id}] Moving pipeline to {self.device}...")
97
- self.pipeline.to(self.device)
98
 
99
  def _set_precision_policy(self):
100
  try:
101
- config = _load_config()
 
 
102
  precision = str(config.get("precision", "bfloat16")).lower()
103
  if precision in ["float8_e4m3fn", "bfloat16"]: self.autocast_dtype = torch.bfloat16
104
  elif precision == "mixed_precision": self.autocast_dtype = torch.float16
@@ -118,15 +96,12 @@ class LTXMainWorker(BaseWorker):
118
  self.is_busy = False
119
 
120
  class VAEWorker(BaseWorker):
121
- def __init__(self, worker_id: int, device: torch.device):
122
- super().__init__(worker_id, device)
123
- self.vae: Optional[CausalVideoAutoencoder] = None
124
-
125
- def _load_models(self):
126
- logging.info(f"[VAEWorker-{self.worker_id}] Loading VAE model to CPU...")
127
- self.vae = get_main_vae()
128
- logging.info(f"[VAEWorker-{self.worker_id}] Moving VAE to {self.device}...")
129
- self.vae.to(self.device)
130
  self.vae.eval()
131
 
132
  def execute(self, job_func: Callable, args: tuple, kwargs: dict) -> Any:
@@ -163,8 +138,12 @@ class LTXAducManager:
163
  self.vae_job_queue = queue.Queue()
164
  self.pool_lock = threading.Lock()
165
 
 
 
 
166
  self._initialize_workers()
167
 
 
168
  self.ltx_dispatcher = threading.Thread(target=self._dispatch_jobs, args=(self.ltx_job_queue, self.ltx_workers), daemon=True)
169
  self.vae_dispatcher = threading.Thread(target=self._dispatch_jobs, args=(self.vae_job_queue, self.vae_workers), daemon=True)
170
  self.health_monitor = threading.Thread(target=self._health_check_loop, daemon=True)
@@ -176,18 +155,29 @@ class LTXAducManager:
176
  self._initialized = True
177
  logging.info("✅ Advanced Pool Manager is running with all threads started.")
178
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  def _initialize_workers(self):
 
180
  ltx_device = gpu_manager.get_ltx_device()
181
  vae_device = gpu_manager.get_ltx_vae_device()
182
 
183
  with self.pool_lock:
184
- # Para esta fase, criamos um worker de cada tipo.
185
- # No futuro, pode-se iterar sobre listas de GPUs de gpu_manager.
186
- ltx_worker = LTXMainWorker(worker_id=0, device=ltx_device)
187
  self.ltx_workers.append(ltx_worker)
188
  ltx_worker.start()
189
 
190
- vae_worker = VAEWorker(worker_id=0, device=vae_device)
191
  self.vae_workers.append(vae_worker)
192
  vae_worker.start()
193
 
@@ -195,8 +185,7 @@ class LTXAducManager:
195
  with self.pool_lock:
196
  for worker in worker_pool:
197
  healthy, busy = worker.get_status()
198
- if healthy and not busy:
199
- return worker
200
  return None
201
 
202
  def _dispatch_jobs(self, job_queue: queue.Queue, worker_pool: List[BaseWorker]):
@@ -206,7 +195,6 @@ class LTXAducManager:
206
  while worker is None:
207
  worker = self._get_available_worker(worker_pool)
208
  if worker is None: time.sleep(0.1)
209
-
210
  try:
211
  result = worker.execute(job_func, args, kwargs)
212
  future.put(result)
@@ -220,14 +208,14 @@ class LTXAducManager:
220
  for i, worker in enumerate(self.ltx_workers):
221
  if not worker.is_alive() or not worker.is_healthy:
222
  logging.warning(f"LTX Worker {worker.worker_id} on {worker.device} is UNHEALTHY. Restarting...")
223
- new_worker = LTXMainWorker(worker.worker_id, worker.device)
224
  self.ltx_workers[i] = new_worker
225
  new_worker.start()
226
 
227
  for i, worker in enumerate(self.vae_workers):
228
  if not worker.is_alive() or not worker.is_healthy:
229
  logging.warning(f"VAE Worker {worker.worker_id} on {worker.device} is UNHEALTHY. Restarting...")
230
- new_worker = VAEWorker(worker.worker_id, worker.device)
231
  self.vae_workers[i] = new_worker
232
  new_worker.start()
233
 
@@ -237,9 +225,7 @@ class LTXAducManager:
237
 
238
  job_queue = self.ltx_job_queue if job_type == 'ltx' else self.vae_job_queue
239
  future = queue.Queue(1)
240
-
241
  job_queue.put((job_func, args, kwargs, future))
242
-
243
  result = future.get()
244
 
245
  if isinstance(result, Exception):
@@ -247,11 +233,9 @@ class LTXAducManager:
247
 
248
  return result
249
 
250
- # ==============================================================================
251
  # --- INSTANCIAÇÃO GLOBAL ---
252
- # ==============================================================================
253
  try:
254
  ltx_aduc_manager = LTXAducManager()
255
- except Exception as e:
256
  logging.critical("CRITICAL ERROR: Failed to initialize the LTXAducManager pool.", exc_info=True)
257
  ltx_aduc_manager = None
 
5
  import logging
6
  import torch
7
  import sys
 
8
  from pathlib import Path
9
  import threading
10
  import queue
 
13
  from huggingface_hub import hf_hub_download
14
  from typing import List, Optional, Callable, Any, Tuple, Dict
15
 
16
+ # --- Importa o gerenciador de GPUs e o builder de baixo nível ---
17
  from managers.gpu_manager import gpu_manager
18
+ from api.ltx.ltx_utils import build_components_on_cpu
 
19
 
20
  # --- Adiciona o path do LTX-Video para importação de tipos ---
21
  LTX_VIDEO_REPO_DIR = Path("/data/LTX-Video")
 
27
 
28
  from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
29
  from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  # ==============================================================================
32
  # --- CLASSES DE WORKER (Especialistas em Tarefas) ---
33
  # ==============================================================================
34
 
35
  class BaseWorker(threading.Thread):
36
+ """Classe base para nossos workers com gerenciamento de estado e saúde."""
37
+ def __init__(self, worker_id: int, device: torch.device, model: torch.nn.Module):
38
  super().__init__()
39
  self.worker_id = worker_id
40
  self.device = device
41
+ self.model = model
42
  self.is_healthy = False
43
  self.is_busy = False
44
  self.daemon = True
45
 
46
  def run(self):
47
+ """O loop de vida do worker, responsável por mover o modelo para a GPU."""
48
  try:
49
+ logging.info(f"Worker {self.worker_id} ({self.__class__.__name__}) moving model to {self.device}...")
50
+ self.model.to(self.device)
51
+ self._post_load_hook()
52
  self.is_healthy = True
53
  logging.info(f"✅ Worker {self.worker_id} ({self.__class__.__name__}) on {self.device} is healthy and ready.")
54
  except Exception:
55
  self.is_healthy = False
56
  logging.error(f"❌ Worker {self.worker_id} on {self.device} FAILED to initialize!", exc_info=True)
57
 
58
+ def _post_load_hook(self):
59
+ """Gancho para ações pós-carregamento, como chamar .eval()."""
60
+ pass
61
 
62
  def get_status(self) -> Tuple[bool, bool]:
63
  return self.is_healthy, self.is_busy
64
 
65
  class LTXMainWorker(BaseWorker):
66
+ """Worker especialista para o pipeline principal do LTX."""
67
+ def __init__(self, worker_id: int, device: torch.device, pipeline: LTXVideoPipeline):
68
+ super().__init__(worker_id, device, pipeline)
69
+ self.pipeline = self.model # Alias para clareza
70
  self.autocast_dtype: torch.dtype = torch.float32
71
 
72
+ def _post_load_hook(self):
 
 
73
  self._set_precision_policy()
 
 
74
 
75
  def _set_precision_policy(self):
76
  try:
77
+ config_path = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
78
+ with open(config_path, "r") as file:
79
+ config = yaml.safe_load(file)
80
  precision = str(config.get("precision", "bfloat16")).lower()
81
  if precision in ["float8_e4m3fn", "bfloat16"]: self.autocast_dtype = torch.bfloat16
82
  elif precision == "mixed_precision": self.autocast_dtype = torch.float16
 
96
  self.is_busy = False
97
 
98
  class VAEWorker(BaseWorker):
99
+ """Worker especialista para o modelo VAE."""
100
+ def __init__(self, worker_id: int, device: torch.device, vae: CausalVideoAutoencoder):
101
+ super().__init__(worker_id, device, vae)
102
+ self.vae = self.model # Alias
103
+
104
+ def _post_load_hook(self):
 
 
 
105
  self.vae.eval()
106
 
107
  def execute(self, job_func: Callable, args: tuple, kwargs: dict) -> Any:
 
138
  self.vae_job_queue = queue.Queue()
139
  self.pool_lock = threading.Lock()
140
 
141
+ # Carrega os modelos na CPU antes de criar os workers
142
+ self.main_pipeline, self.main_vae = self._load_components_once()
143
+
144
  self._initialize_workers()
145
 
146
+ # Inicia threads consumidores para processar as filas
147
  self.ltx_dispatcher = threading.Thread(target=self._dispatch_jobs, args=(self.ltx_job_queue, self.ltx_workers), daemon=True)
148
  self.vae_dispatcher = threading.Thread(target=self._dispatch_jobs, args=(self.vae_job_queue, self.vae_workers), daemon=True)
149
  self.health_monitor = threading.Thread(target=self._health_check_loop, daemon=True)
 
155
  self._initialized = True
156
  logging.info("✅ Advanced Pool Manager is running with all threads started.")
157
 
158
+ def _load_components_once(self) -> Tuple[LTXVideoPipeline, CausalVideoAutoencoder]:
159
+ """Orquestra a construção de TODOS os componentes na CPU uma única vez."""
160
+ logging.info("Manager loading all components onto CPU...")
161
+ config_path = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
162
+ with open(config_path, "r") as file:
163
+ config = yaml.safe_load(file)
164
+
165
+ ckpt_path = hf_hub_download(repo_id="Lightricks/LTX-Video", filename=config["checkpoint_path"], cache_dir=os.environ.get("HF_HOME"))
166
+ pipeline, vae = build_components_on_cpu(ckpt_path, config)
167
+ logging.info("✅ All components loaded to CPU successfully.")
168
+ return pipeline, vae
169
+
170
  def _initialize_workers(self):
171
+ """Cria e inicia os workers, injetando os modelos já carregados."""
172
  ltx_device = gpu_manager.get_ltx_device()
173
  vae_device = gpu_manager.get_ltx_vae_device()
174
 
175
  with self.pool_lock:
176
+ ltx_worker = LTXMainWorker(worker_id=0, device=ltx_device, pipeline=self.main_pipeline)
 
 
177
  self.ltx_workers.append(ltx_worker)
178
  ltx_worker.start()
179
 
180
+ vae_worker = VAEWorker(worker_id=0, device=vae_device, vae=self.main_vae)
181
  self.vae_workers.append(vae_worker)
182
  vae_worker.start()
183
 
 
185
  with self.pool_lock:
186
  for worker in worker_pool:
187
  healthy, busy = worker.get_status()
188
+ if healthy and not busy: return worker
 
189
  return None
190
 
191
  def _dispatch_jobs(self, job_queue: queue.Queue, worker_pool: List[BaseWorker]):
 
195
  while worker is None:
196
  worker = self._get_available_worker(worker_pool)
197
  if worker is None: time.sleep(0.1)
 
198
  try:
199
  result = worker.execute(job_func, args, kwargs)
200
  future.put(result)
 
208
  for i, worker in enumerate(self.ltx_workers):
209
  if not worker.is_alive() or not worker.is_healthy:
210
  logging.warning(f"LTX Worker {worker.worker_id} on {worker.device} is UNHEALTHY. Restarting...")
211
+ new_worker = LTXMainWorker(worker.worker_id, worker.device, self.main_pipeline)
212
  self.ltx_workers[i] = new_worker
213
  new_worker.start()
214
 
215
  for i, worker in enumerate(self.vae_workers):
216
  if not worker.is_alive() or not worker.is_healthy:
217
  logging.warning(f"VAE Worker {worker.worker_id} on {worker.device} is UNHEALTHY. Restarting...")
218
+ new_worker = VAEWorker(worker.worker_id, worker.device, self.main_vae)
219
  self.vae_workers[i] = new_worker
220
  new_worker.start()
221
 
 
225
 
226
  job_queue = self.ltx_job_queue if job_type == 'ltx' else self.vae_job_queue
227
  future = queue.Queue(1)
 
228
  job_queue.put((job_func, args, kwargs, future))
 
229
  result = future.get()
230
 
231
  if isinstance(result, Exception):
 
233
 
234
  return result
235
 
 
236
  # --- INSTANCIAÇÃO GLOBAL ---
 
237
  try:
238
  ltx_aduc_manager = LTXAducManager()
239
+ except Exception:
240
  logging.critical("CRITICAL ERROR: Failed to initialize the LTXAducManager pool.", exc_info=True)
241
  ltx_aduc_manager = None