euiia commited on
Commit
c7e0b21
·
verified ·
1 Parent(s): 8894134

Delete ltx_manager_helpers.py

Browse files
Files changed (1) hide show
  1. ltx_manager_helpers.py +0 -240
ltx_manager_helpers.py DELETED
@@ -1,240 +0,0 @@
1
- # ltx_manager_helpers.py
2
- # Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
3
- #
4
- # ORIGINAL SOURCE: LTX-Video by Lightricks Ltd. & other open-source projects.
5
- # Licensed under the Apache License, Version 2.0
6
- # https://github.com/Lightricks/LTX-Video
7
- #
8
- # MODIFICATIONS FOR ADUC-SDR_Video:
9
- # This file is part of ADUC-SDR_Video, a derivative work based on LTX-Video.
10
- # It has been modified to manage pools of LTX workers, handle GPU memory,
11
- # and prepare parameters for the ADUC-SDR orchestration framework.
12
- # All modifications are also licensed under the Apache License, Version 2.0.
13
-
14
- import torch
15
- import gc
16
- import os
17
- import yaml
18
- import logging
19
- import huggingface_hub
20
- import time
21
- import threading
22
- import json
23
-
24
- from optimization import optimize_ltx_worker, can_optimize_fp8
25
- from hardware_manager import hardware_manager
26
- from inference import create_ltx_video_pipeline, calculate_padding
27
- from ltx_video.pipelines.pipeline_ltx_video import LatentConditioningItem
28
-
29
- logger = logging.getLogger(__name__)
30
-
31
- class LtxWorker:
32
- """
33
- Representa uma única instância da pipeline LTX-Video em um dispositivo específico.
34
- Gerencia o carregamento do modelo para a CPU e a movimentação de/para a GPU.
35
- """
36
- def __init__(self, device_id, ltx_config_file):
37
- self.cpu_device = torch.device('cpu')
38
- self.device = torch.device(device_id if torch.cuda.is_available() else 'cpu')
39
- logger.info(f"LTX Worker ({self.device}): Inicializando com config '{ltx_config_file}'...")
40
-
41
- with open(ltx_config_file, "r") as file:
42
- self.config = yaml.safe_load(file)
43
-
44
- self.is_distilled = "distilled" in self.config.get("checkpoint_path", "")
45
-
46
- models_dir = "downloaded_models_gradio"
47
-
48
- logger.info(f"LTX Worker ({self.device}): Carregando modelo para a CPU...")
49
- model_path = os.path.join(models_dir, self.config["checkpoint_path"])
50
- if not os.path.exists(model_path):
51
- model_path = huggingface_hub.hf_hub_download(
52
- repo_id="Lightricks/LTX-Video", filename=self.config["checkpoint_path"],
53
- local_dir=models_dir, local_dir_use_symlinks=False
54
- )
55
-
56
- self.pipeline = create_ltx_video_pipeline(
57
- ckpt_path=model_path, precision=self.config["precision"],
58
- text_encoder_model_name_or_path=self.config["text_encoder_model_name_or_path"],
59
- sampler=self.config["sampler"], device='cpu'
60
- )
61
- logger.info(f"LTX Worker ({self.device}): Modelo pronto na CPU. É um modelo destilado? {self.is_distilled}")
62
-
63
- def to_gpu(self):
64
- """Move o pipeline para a GPU designada E OTIMIZA SE POSSÍVEL."""
65
- if self.device.type == 'cpu': return
66
- logger.info(f"LTX Worker: Movendo pipeline para a GPU {self.device}...")
67
- self.pipeline.to(self.device)
68
-
69
- if self.device.type == 'cuda' and can_optimize_fp8():
70
- logger.info(f"LTX Worker ({self.device}): GPU com suporte a FP8 detectada. Iniciando otimização...")
71
- optimize_ltx_worker(self)
72
- logger.info(f"LTX Worker ({self.device}): Otimização concluída.")
73
- elif self.device.type == 'cuda':
74
- logger.info(f"LTX Worker ({self.device}): Otimização FP8 não suportada ou desativada.")
75
-
76
- def to_cpu(self):
77
- """Move o pipeline de volta para a CPU e libera a memória da GPU."""
78
- if self.device.type == 'cpu': return
79
- logger.info(f"LTX Worker: Descarregando pipeline da GPU {self.device}...")
80
- self.pipeline.to('cpu')
81
- gc.collect()
82
- if torch.cuda.is_available(): torch.cuda.empty_cache()
83
-
84
- def generate_video_fragment_internal(self, **kwargs):
85
- """Invoca a pipeline de geração."""
86
- return self.pipeline(**kwargs).images
87
-
88
- class LtxPoolManager:
89
- """
90
- Gerencia um pool de LtxWorkers. MODO "HOT START": Mantém todos os modelos carregados na VRAM.
91
- """
92
- def __init__(self, device_ids, ltx_config_file):
93
- logger.info(f"LTX POOL MANAGER: Criando workers para os dispositivos: {device_ids}")
94
- self.workers = [LtxWorker(dev_id, ltx_config_file) for dev_id in device_ids]
95
- self.current_worker_index = 0
96
- self.lock = threading.Lock()
97
-
98
- if all(w.device.type == 'cuda' for w in self.workers):
99
- logger.info("LTX POOL MANAGER: MODO HOT START ATIVADO. Pré-aquecendo todas as GPUs...")
100
- for worker in self.workers:
101
- worker.to_gpu()
102
- logger.info("LTX POOL MANAGER: Todas as GPUs estão quentes e prontas.")
103
- else:
104
- logger.info("LTX POOL MANAGER: Operando em modo CPU ou misto. O pré-aquecimento de GPU foi ignorado.")
105
-
106
- def _prepare_and_log_params(self, worker_to_use, **kwargs):
107
- target_device = worker_to_use.device
108
- height, width = kwargs['height'], kwargs['width']
109
-
110
- conditioning_data = kwargs.get('conditioning_items_data', [])
111
- final_conditioning_items = []
112
- conditioning_log_details = []
113
- for i, item in enumerate(conditioning_data):
114
- if hasattr(item, 'latent_tensor'):
115
- item.latent_tensor = item.latent_tensor.to(target_device)
116
- final_conditioning_items.append(item)
117
- conditioning_log_details.append(
118
- f" - Item {i}: frame={item.media_frame_number}, strength={item.conditioning_strength:.2f}, shape={list(item.latent_tensor.shape)}"
119
- )
120
-
121
- first_pass_config = worker_to_use.config.get("first_pass", {})
122
-
123
- if 'latents' in kwargs and kwargs['latents'] is not None:
124
- padded_h, padded_w = height, width
125
- padding_vals = (0, 0, 0, 0)
126
- else:
127
- padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
128
- padding_vals = calculate_padding(height, width, padded_h, padded_w)
129
-
130
- pipeline_params = {
131
- "height": padded_h, "width": padded_w,
132
- "num_frames": kwargs['video_total_frames'], "frame_rate": kwargs['video_fps'],
133
- "generator": torch.Generator(device=target_device).manual_seed(int(kwargs.get('seed', time.time())) + kwargs['current_fragment_index']),
134
- "conditioning_items": final_conditioning_items,
135
- "is_video": True, "vae_per_channel_normalize": True,
136
- "decode_timestep": float(kwargs.get('decode_timestep', worker_to_use.config.get("decode_timestep", 0.05))),
137
- "image_cond_noise_scale": float(kwargs.get('image_cond_noise_scale', 0.0)),
138
- "prompt": kwargs['motion_prompt'],
139
- "negative_prompt": kwargs.get('negative_prompt', "blurry, distorted, static, bad quality, artifacts"),
140
- "guidance_scale": float(kwargs.get('guidance_scale', 2.0)),
141
- "stg_scale": float(kwargs.get('stg_scale', 0.025)),
142
- "rescaling_scale": float(kwargs.get('rescaling_scale', 0.15)),
143
- }
144
-
145
- if worker_to_use.is_distilled:
146
- pipeline_params["timesteps"] = first_pass_config.get("timesteps")
147
- pipeline_params["num_inference_steps"] = len(pipeline_params["timesteps"]) if "timesteps" in first_pass_config else 20
148
- else:
149
- pipeline_params["num_inference_steps"] = int(kwargs.get('num_inference_steps', 20))
150
-
151
- log_friendly_params = pipeline_params.copy()
152
- log_friendly_params.pop('generator', None)
153
- log_friendly_params.pop('conditioning_items', None)
154
-
155
- logger.info("="*60)
156
- logger.info(f"CHAMADA AO PIPELINE LTX NO DISPOSITIVO: {worker_to_use.device}")
157
-
158
- return pipeline_params, padding_vals
159
-
160
- def _execute_on_worker(self, execution_fn, **kwargs):
161
- worker_to_use = None
162
- try:
163
- with self.lock:
164
- worker_to_use = self.workers[self.current_worker_index]
165
- self.current_worker_index = (self.current_worker_index + 1) % len(self.workers)
166
-
167
- result, padding_vals = execution_fn(worker_to_use, **kwargs)
168
-
169
- return result, padding_vals
170
-
171
- except Exception as e:
172
- 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)
173
- raise e
174
- finally:
175
- if worker_to_use and worker_to_use.device.type == 'cuda':
176
- with torch.cuda.device(worker_to_use.device):
177
- gc.collect()
178
- torch.cuda.empty_cache()
179
-
180
- def generate_latent_fragment(self, **kwargs) -> (torch.Tensor, tuple):
181
- def execution_logic(worker, **inner_kwargs):
182
- pipeline_params, padding_vals = self._prepare_and_log_params(worker, **inner_kwargs)
183
- pipeline_params['output_type'] = "latent"
184
- with torch.no_grad():
185
- result_tensor = worker.generate_video_fragment_internal(**pipeline_params)
186
- return result_tensor, padding_vals
187
-
188
- return self._execute_on_worker(execution_logic, **kwargs)
189
-
190
- def refine_latents(self, upscaled_latents: torch.Tensor, **kwargs) -> (torch.Tensor, tuple):
191
- def execution_logic(worker, **inner_kwargs):
192
- pipeline_params, padding_vals = self._prepare_and_log_params(worker, **inner_kwargs)
193
-
194
- strength = inner_kwargs.get('denoise_strength', 0.4)
195
- num_refine_steps_requested = int(inner_kwargs.get('refine_steps', 10))
196
-
197
- allowed_timesteps = worker.config.get("first_pass", {}).get("timesteps")
198
-
199
- if allowed_timesteps is None:
200
- scheduler = worker.pipeline.scheduler
201
- scheduler.set_timesteps(num_refine_steps_requested, device=worker.device)
202
- timesteps = scheduler.timesteps
203
- else:
204
- timesteps = torch.tensor(allowed_timesteps, device=worker.device)
205
-
206
- num_total_timesteps = len(timesteps)
207
- start_timestep_idx = int(num_total_timesteps * strength)
208
- if start_timestep_idx >= num_total_timesteps:
209
- start_timestep_idx = num_total_timesteps - 1
210
-
211
- start_timestep = timesteps[start_timestep_idx]
212
-
213
- noise = torch.randn_like(upscaled_latents, device=worker.device)
214
- noisy_latents = worker.pipeline.scheduler.add_noise(upscaled_latents.to(worker.device), noise, start_timestep)
215
-
216
- final_timesteps = timesteps[start_timestep_idx:]
217
- pipeline_params['latents'] = noisy_latents.to(worker.device, dtype=worker.pipeline.transformer.dtype)
218
- pipeline_params['timesteps'] = final_timesteps
219
- pipeline_params['num_inference_steps'] = len(final_timesteps)
220
- pipeline_params.pop('strength', None)
221
- pipeline_params['output_type'] = "latent"
222
-
223
- logger.info(f"LTX POOL MANAGER: Iniciando refinamento com {len(final_timesteps)} passos a partir do timestep {start_timestep.item():.4f}.")
224
-
225
- with torch.no_grad():
226
- refined_tensor = worker.generate_video_fragment_internal(**pipeline_params)
227
-
228
- return refined_tensor, padding_vals
229
-
230
- return self._execute_on_worker(execution_logic, upscaled_latents=upscaled_latents, **kwargs)
231
-
232
- # --- Instanciação Singleton ---
233
- logger.info("Lendo config.yaml para inicializar o LTX Pool Manager...")
234
- with open("config.yaml", 'r') as f:
235
- config = yaml.safe_load(f)
236
- ltx_gpus_required = config['specialists']['ltx']['gpus_required']
237
- ltx_device_ids = hardware_manager.allocate_gpus('LTX', ltx_gpus_required)
238
- ltx_config_path = config['specialists']['ltx']['config_file']
239
- ltx_manager_singleton = LtxPoolManager(device_ids=ltx_device_ids, ltx_config_file=ltx_config_path)
240
- logger.info("Especialista de Vídeo (LTX) pronto.")