x2XcarleX2x commited on
Commit
6945ae4
·
verified ·
1 Parent(s): d51ffb7

Create pipeline_patches.py

Browse files
aduc_framework/tools/pipeline_patches.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # aduc_framework/tools/pipeline_patches.py (Central de Modificações ADUC)
2
+ import torch
3
+ import logging
4
+ from typing import List, Optional, Union
5
+
6
+ # --- Importa os tipos da nossa arquitetura ---
7
+ from ..types import LatentConditioningItem
8
+
9
+ # --- Importa as classes originais que vamos modificar ---
10
+ # Usamos try-except para permitir que o linter analise o arquivo mesmo sem as dependências.
11
+ try:
12
+ from diffusers.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
13
+ from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline, ConditioningItem
14
+ from ltx_video.models.autoencoders.vae_encode import latent_to_pixel_coords
15
+ from diffusers.utils.torch_utils import randn_tensor
16
+ except ImportError:
17
+ WanImageToVideoPipeline = None
18
+ LTXVideoPipeline = None
19
+ ConditioningItem = None
20
+ latent_to_pixel_coords = None
21
+ randn_tensor = None
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # ==============================================================================
26
+ # PATCH #1: Pipeline WanImageToVideo (Wan2.2)
27
+ # Objetivo: Ensinar a pipeline a usar `LatentConditioningItem` para controle ADUC.
28
+ # ==============================================================================
29
+ def prepare_latents_patch_for_wan_i2v(
30
+ self: WanImageToVideoPipeline,
31
+ conditioning_items: List[LatentConditioningItem],
32
+ batch_size: int,
33
+ num_channels_latents: int,
34
+ height: int,
35
+ width: int,
36
+ num_frames: int,
37
+ dtype: torch.dtype,
38
+ device: torch.device,
39
+ generator,
40
+ latents: Optional[torch.Tensor] = None,
41
+ **kwargs # Aceita e ignora outros argumentos como 'image', 'last_image'
42
+ ) -> tuple[torch.Tensor, torch.Tensor]:
43
+ """Monkey patch para a pipeline WanImageToVideo, permitindo o uso de LatentConditioningItem."""
44
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
45
+ latent_height = height // self.vae_scale_factor_spatial
46
+ latent_width = width // self.vae_scale_factor_spatial
47
+ shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
48
+
49
+ init_latents = latents if latents is not None else torch.randn(shape, generator=generator, device=device, dtype=dtype)
50
+ init_latents = init_latents.to(device=device, dtype=dtype)
51
+
52
+ mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height, latent_width, device=device, dtype=dtype)
53
+ mask_lat_size[:, :, 1:] = 0
54
+
55
+ first_frame_mask = mask_lat_size[:, :, 0:1]
56
+ first_frame_mask = torch.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
57
+ mask_lat_size = torch.concat([first_frame_mask, mask_lat_size[:, :, 1:]], dim=2)
58
+ mask_lat_size = mask_lat_size.view(batch_size, -1, self.vae_scale_factor_temporal, latent_height, latent_width)
59
+ mask_lat_size = mask_lat_size.transpose(1, 2).to(init_latents.device)
60
+
61
+ logger.info(f"WAN_PATCH: Aplicando {len(conditioning_items)} itens de condicionamento.")
62
+ for item in conditioning_items:
63
+ media_item_latents = item.latent_tensor.to(dtype=init_latents.dtype, device=init_latents.device)
64
+ frame_idx, strength = item.media_frame_number, item.conditioning_strength
65
+
66
+ if frame_idx >= num_latent_frames:
67
+ logger.warning(f"WAN_PATCH: frame_idx {frame_idx} fora dos limites. Pulando.")
68
+ continue
69
+
70
+ f_l, h_l, w_l = media_item_latents.shape[-3:]
71
+ init_latents[:, :, frame_idx:frame_idx+f_l, :h_l, :w_l] = torch.lerp(
72
+ init_latents[:, :, frame_idx:frame_idx+f_l, :h_l, :w_l], media_item_latents, strength
73
+ )
74
+ mask_lat_size[:, :, frame_idx, :h_l, :w_l] = strength
75
+
76
+ condition = torch.concat([mask_lat_size, init_latents], dim=1)
77
+ return init_latents, condition
78
+
79
+ # ==============================================================================
80
+ # PATCH #2: Pipeline LTXVideo (LTX)
81
+ # Objetivo: Ensinar a pipeline a usar `LatentConditioningItem` para controle ADUC.
82
+ # ==============================================================================
83
+ def prepare_conditioning_patch_for_ltx(
84
+ self: "LTXVideoPipeline",
85
+ conditioning_items: Optional[List[Union["ConditioningItem", "LatentConditioningItem"]]],
86
+ init_latents: torch.Tensor,
87
+ num_frames: int,
88
+ height: int,
89
+ width: int,
90
+ vae_per_channel_normalize: bool = False,
91
+ generator=None,
92
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
93
+ """Monkey patch para a pipeline LTX-Video, focando no uso de LatentConditioningItem."""
94
+ if not conditioning_items:
95
+ init_latents, init_latent_coords = self.patchifier.patchify(latents=init_latents)
96
+ init_pixel_coords = latent_to_pixel_coords(init_latent_coords, self.vae, causal_fix=self.transformer.config.causal_temporal_positioning)
97
+ return init_latents, init_pixel_coords, None, 0
98
+
99
+ init_conditioning_mask = torch.zeros_like(init_latents[:, 0, ...], dtype=torch.float32, device=init_latents.device)
100
+ extra_conditioning_latents, extra_conditioning_pixel_coords, extra_conditioning_mask = [], [], []
101
+ extra_conditioning_num_latents = 0
102
+
103
+ logger.info(f"LTX_PATCH: Aplicando {len(conditioning_items)} itens de condicionamento.")
104
+ for item in conditioning_items:
105
+ if not isinstance(item, LatentConditioningItem):
106
+ logger.warning("LTX_PATCH: Item de condicionamento não é um LatentConditioningItem e será ignorado.")
107
+ continue
108
+
109
+ media_item_latents = item.latent_tensor.to(dtype=init_latents.dtype, device=init_latents.device)
110
+ media_frame_number, strength = item.media_frame_number, item.conditioning_strength
111
+
112
+ if media_frame_number == 0:
113
+ f_l, h_l, w_l = media_item_latents.shape[-3:]
114
+ init_latents[..., :f_l, :h_l, :w_l] = torch.lerp(init_latents[..., :f_l, :h_l, :w_l], media_item_latents, strength)
115
+ init_conditioning_mask[..., :f_l, :h_l, :w_l] = strength
116
+ else:
117
+ noise = randn_tensor(media_item_latents.shape, generator=generator, device=media_item_latents.device, dtype=media_item_latents.dtype)
118
+ media_item_latents = torch.lerp(noise, media_item_latents, strength)
119
+ patched_latents, latent_coords = self.patchifier.patchify(latents=media_item_latents)
120
+ pixel_coords = latent_to_pixel_coords(latent_coords, self.vae, causal_fix=self.transformer.config.causal_temporal_positioning)
121
+ pixel_coords[:, 0] += media_frame_number
122
+ extra_conditioning_num_latents += patched_latents.shape[1]
123
+ new_mask = torch.full(patched_latents.shape[:2], strength, dtype=torch.float32, device=init_latents.device)
124
+ extra_conditioning_latents.append(patched_latents)
125
+ extra_conditioning_pixel_coords.append(pixel_coords)
126
+ extra_conditioning_mask.append(new_mask)
127
+
128
+ init_latents, init_latent_coords = self.patchifier.patchify(latents=init_latents)
129
+ init_pixel_coords = latent_to_pixel_coords(init_latent_coords, self.vae, causal_fix=self.transformer.config.causal_temporal_positioning)
130
+ init_conditioning_mask, _ = self.patchifier.patchify(latents=init_conditioning_mask.unsqueeze(1))
131
+ init_conditioning_mask = init_conditioning_mask.squeeze(-1)
132
+
133
+ if extra_conditioning_latents:
134
+ init_latents = torch.cat([*extra_conditioning_latents, init_latents], dim=1)
135
+ init_pixel_coords = torch.cat([*extra_conditioning_pixel_coords, init_pixel_coords], dim=2)
136
+ init_conditioning_mask = torch.cat([*extra_conditioning_mask, init_conditioning_mask], dim=1)
137
+
138
+ return init_latents, init_pixel_coords, init_conditioning_mask, extra_conditioning_num_latents
139
+
140
+ # ==============================================================================
141
+ # FUNÇÃO DE APLICAÇÃO CENTRAL
142
+ # ==============================================================================
143
+ def apply_aduc_patches():
144
+ """Função central para aplicar todos os nossos patches ADUC-SDR."""
145
+ logger.info("--- Central de Patches ADUC-SDR: Aplicando modificações ---")
146
+
147
+ # Aplica o patch na pipeline do Wan2.2
148
+ if WanImageToVideoPipeline:
149
+ logger.info("-> Modificando 'WanImageToVideoPipeline.prepare_latents'...")
150
+ WanImageToVideoPipeline.prepare_latents = prepare_latents_patch_for_wan_i2v
151
+ else:
152
+ logger.warning("-> WanImageToVideoPipeline não encontrada. Patch pulado.")
153
+
154
+ # Aplica o patch na pipeline do LTX
155
+ if LTXVideoPipeline:
156
+ logger.info("-> Modificando 'LTXVideoPipeline.prepare_conditioning'...")
157
+ LTXVideoPipeline.prepare_conditioning = prepare_conditioning_patch_for_ltx
158
+ else:
159
+ logger.warning("-> LTXVideoPipeline não encontrada. Patch pulado.")
160
+
161
+ logger.info("--- Modificações de pipeline concluídas ---")