wan_runner.py 12.5 KB
Newer Older
helloyongyang's avatar
helloyongyang committed
1
import os
2
import gc
helloyongyang's avatar
helloyongyang committed
3
4
5
6
7
8
9
import numpy as np
import torch
import torchvision.transforms.functional as TF
from PIL import Image
from lightx2v.utils.registry_factory import RUNNER_REGISTER
from lightx2v.models.runners.default_runner import DefaultRunner
from lightx2v.models.schedulers.wan.scheduler import WanScheduler
gushiqiao's avatar
gushiqiao committed
10
11
12
from lightx2v.models.schedulers.wan.changing_resolution.scheduler import (
    WanScheduler4ChangingResolution,
)
13
14
from lightx2v.models.schedulers.wan.feature_caching.scheduler import (
    WanSchedulerTeaCaching,
15
16
17
    WanSchedulerTaylorCaching,
    WanSchedulerAdaCaching,
    WanSchedulerCustomCaching,
18
)
helloyongyang's avatar
helloyongyang committed
19
20
21
22
23
24
from lightx2v.utils.profiler import ProfilingContext
from lightx2v.models.input_encoders.hf.t5.model import T5EncoderModel
from lightx2v.models.input_encoders.hf.xlm_roberta.model import CLIPModel
from lightx2v.models.networks.wan.model import WanModel
from lightx2v.models.networks.wan.lora_adapter import WanLoraWrapper
from lightx2v.models.video_encoders.hf.wan.vae import WanVAE
25
from lightx2v.models.video_encoders.hf.wan.vae_tiny import WanVAE_tiny
26
from lightx2v.utils.utils import cache_video
root's avatar
root committed
27
from loguru import logger
helloyongyang's avatar
helloyongyang committed
28
29
30
31
32
33
34


@RUNNER_REGISTER("wan2.1")
class WanRunner(DefaultRunner):
    def __init__(self, config):
        super().__init__(config)

35
36
37
38
39
40
    def load_transformer(self):
        model = WanModel(
            self.config.model_path,
            self.config,
            self.init_device,
        )
41
        if self.config.get("lora_configs") and self.config.lora_configs:
42
            assert not self.config.get("dit_quantized", False) or self.config.mm_config.get("weight_auto_quant", False)
43
            lora_wrapper = WanLoraWrapper(model)
44
45
46
            for lora_config in self.config.lora_configs:
                lora_path = lora_config["path"]
                strength = lora_config.get("strength", 1.0)
GoatWu's avatar
GoatWu committed
47
                lora_name = lora_wrapper.load_lora(lora_path)
48
49
                lora_wrapper.apply_lora(lora_name, strength)
                logger.info(f"Loaded LoRA: {lora_name} with strength: {strength}")
50
51
        return model

52
    def load_image_encoder(self):
helloyongyang's avatar
helloyongyang committed
53
        image_encoder = None
54
        if self.config.task == "i2v":
gushiqiao's avatar
gushiqiao committed
55
56
57
58
59
            # quant_config
            clip_quantized = self.config.get("clip_quantized", False)
            if clip_quantized:
                clip_quant_scheme = self.config.get("clip_quant_scheme", None)
                assert clip_quant_scheme is not None
gushiqiao's avatar
gushiqiao committed
60
                tmp_clip_quant_scheme = clip_quant_scheme.split("-")[0]
gushiqiao's avatar
gushiqiao committed
61
62
63
                clip_quantized_ckpt = self.config.get(
                    "clip_quantized_ckpt",
                    os.path.join(
gushiqiao's avatar
gushiqiao committed
64
65
                        os.path.join(self.config.model_path, tmp_clip_quant_scheme),
                        f"clip-{tmp_clip_quant_scheme}.pth",
gushiqiao's avatar
gushiqiao committed
66
67
68
69
70
71
                    ),
                )
            else:
                clip_quantized_ckpt = None
                clip_quant_scheme = None

72
73
            image_encoder = CLIPModel(
                dtype=torch.float16,
74
                device=self.init_device,
75
76
77
78
                checkpoint_path=os.path.join(
                    self.config.model_path,
                    "models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth",
                ),
gushiqiao's avatar
gushiqiao committed
79
80
81
                clip_quantized=clip_quantized,
                clip_quantized_ckpt=clip_quantized_ckpt,
                quant_scheme=clip_quant_scheme,
82
83
            )
        return image_encoder
helloyongyang's avatar
helloyongyang committed
84

85
    def load_text_encoder(self):
gushiqiao's avatar
gushiqiao committed
86
        # offload config
gushiqiao's avatar
gushiqiao committed
87
88
89
90
91
        t5_offload = self.config.get("t5_cpu_offload", False)
        if t5_offload:
            t5_device = torch.device("cpu")
        else:
            t5_device = torch.device("cuda")
gushiqiao's avatar
gushiqiao committed
92
93
94
95
96

        # quant_config
        t5_quantized = self.config.get("t5_quantized", False)
        if t5_quantized:
            t5_quant_scheme = self.config.get("t5_quant_scheme", None)
gushiqiao's avatar
gushiqiao committed
97
            tmp_t5_quant_scheme = t5_quant_scheme.split("-")[0]
gushiqiao's avatar
gushiqiao committed
98
99
100
101
            assert t5_quant_scheme is not None
            t5_quantized_ckpt = self.config.get(
                "t5_quantized_ckpt",
                os.path.join(
gushiqiao's avatar
gushiqiao committed
102
103
                    os.path.join(self.config.model_path, tmp_t5_quant_scheme),
                    f"models_t5_umt5-xxl-enc-{tmp_t5_quant_scheme}.pth",
gushiqiao's avatar
gushiqiao committed
104
105
106
107
108
                ),
            )
        else:
            t5_quant_scheme = None
            t5_quantized_ckpt = None
gushiqiao's avatar
Fix  
gushiqiao committed
109

helloyongyang's avatar
helloyongyang committed
110
111
112
        text_encoder = T5EncoderModel(
            text_len=self.config["text_len"],
            dtype=torch.bfloat16,
gushiqiao's avatar
gushiqiao committed
113
            device=t5_device,
helloyongyang's avatar
helloyongyang committed
114
115
116
            checkpoint_path=os.path.join(self.config.model_path, "models_t5_umt5-xxl-enc-bf16.pth"),
            tokenizer_path=os.path.join(self.config.model_path, "google/umt5-xxl"),
            shard_fn=None,
gushiqiao's avatar
gushiqiao committed
117
            cpu_offload=t5_offload,
118
            offload_granularity=self.config.get("t5_offload_granularity", "model"),
gushiqiao's avatar
gushiqiao committed
119
120
121
            t5_quantized=t5_quantized,
            t5_quantized_ckpt=t5_quantized_ckpt,
            quant_scheme=t5_quant_scheme,
helloyongyang's avatar
helloyongyang committed
122
123
        )
        text_encoders = [text_encoder]
124
        return text_encoders
helloyongyang's avatar
helloyongyang committed
125

126
    def load_vae_encoder(self):
127
128
        vae_config = {
            "vae_pth": os.path.join(self.config.model_path, "Wan2.1_VAE.pth"),
129
            "device": self.init_device,
130
131
132
            "parallel": self.config.parallel_vae,
            "use_tiling": self.config.get("use_tiling_vae", False),
        }
133
134
135
136
137
138
139
140
141
142
143
144
145
        if self.config.task != "i2v":
            return None
        else:
            return WanVAE(**vae_config)

    def load_vae_decoder(self):
        vae_config = {
            "vae_pth": os.path.join(self.config.model_path, "Wan2.1_VAE.pth"),
            "device": self.init_device,
            "parallel": self.config.parallel_vae,
            "use_tiling": self.config.get("use_tiling_vae", False),
        }
        if self.config.get("tiny_vae", False):
146
            vae_decoder = WanVAE_tiny(
147
                vae_pth=self.config.tiny_vae_path,
148
                device=self.init_device,
149
            ).to("cuda")
150
        else:
151
            vae_decoder = WanVAE(**vae_config)
152
        return vae_decoder
helloyongyang's avatar
helloyongyang committed
153

154
    def load_vae(self):
gushiqiao's avatar
gushiqiao committed
155
156
157
158
159
160
        vae_encoder = self.load_vae_encoder()
        if vae_encoder is None or self.config.get("tiny_vae", False):
            vae_decoder = self.load_vae_decoder()
        else:
            vae_decoder = vae_encoder
        return vae_encoder, vae_decoder
helloyongyang's avatar
helloyongyang committed
161
162

    def init_scheduler(self):
163
164
        if self.config.get("changing_resolution", False):
            scheduler = WanScheduler4ChangingResolution(self.config)
helloyongyang's avatar
helloyongyang committed
165
        else:
166
167
168
169
170
171
172
173
174
175
176
177
            if self.config.feature_caching == "NoCaching":
                scheduler = WanScheduler(self.config)
            elif self.config.feature_caching == "Tea":
                scheduler = WanSchedulerTeaCaching(self.config)
            elif self.config.feature_caching == "TaylorSeer":
                scheduler = WanSchedulerTaylorCaching(self.config)
            elif self.config.feature_caching == "Ada":
                scheduler = WanSchedulerAdaCaching(self.config)
            elif self.config.feature_caching == "Custom":
                scheduler = WanSchedulerCustomCaching(self.config)
            else:
                raise NotImplementedError(f"Unsupported feature_caching type: {self.config.feature_caching}")
helloyongyang's avatar
helloyongyang committed
178
179
        self.model.set_scheduler(scheduler)

180
    def run_text_encoder(self, text, img):
gushiqiao's avatar
gushiqiao committed
181
        if self.config.get("lazy_load", False) or self.config.get("unload_modules", False):
182
            self.text_encoders = self.load_text_encoder()
helloyongyang's avatar
helloyongyang committed
183
        text_encoder_output = {}
184
185
186
        n_prompt = self.config.get("negative_prompt", "")
        context = self.text_encoders[0].infer([text])
        context_null = self.text_encoders[0].infer([n_prompt if n_prompt else ""])
gushiqiao's avatar
gushiqiao committed
187
        if self.config.get("lazy_load", False) or self.config.get("unload_modules", False):
188
189
190
            del self.text_encoders[0]
            torch.cuda.empty_cache()
            gc.collect()
helloyongyang's avatar
helloyongyang committed
191
192
193
194
        text_encoder_output["context"] = context
        text_encoder_output["context_null"] = context_null
        return text_encoder_output

195
    def run_image_encoder(self, img):
gushiqiao's avatar
gushiqiao committed
196
        if self.config.get("lazy_load", False) or self.config.get("unload_modules", False):
197
            self.image_encoder = self.load_image_encoder()
198
199
        img = TF.to_tensor(img).sub_(0.5).div_(0.5).cuda()
        clip_encoder_out = self.image_encoder.visual([img[:, None, :, :]], self.config).squeeze(0).to(torch.bfloat16)
gushiqiao's avatar
gushiqiao committed
200
        if self.config.get("lazy_load", False) or self.config.get("unload_modules", False):
201
202
203
            del self.image_encoder
            torch.cuda.empty_cache()
            gc.collect()
204
205
206
        return clip_encoder_out

    def run_vae_encoder(self, img):
helloyongyang's avatar
helloyongyang committed
207
208
209
        img = TF.to_tensor(img).sub_(0.5).div_(0.5).cuda()
        h, w = img.shape[1:]
        aspect_ratio = h / w
210
211
212
        max_area = self.config.target_height * self.config.target_width
        lat_h = round(np.sqrt(max_area * aspect_ratio) // self.config.vae_stride[1] // self.config.patch_size[1] * self.config.patch_size[1])
        lat_w = round(np.sqrt(max_area / aspect_ratio) // self.config.vae_stride[2] // self.config.patch_size[2] * self.config.patch_size[2])
213
214
215

        if self.config.get("changing_resolution", False):
            self.config.lat_h, self.config.lat_w = lat_h, lat_w
216
217
218
219
220
221
            vae_encode_out_list = []
            for i in range(len(self.config["resolution_rate"])):
                lat_h, lat_w = int(self.config.lat_h * self.config.resolution_rate[i]) // 2 * 2, int(self.config.lat_w * self.config.resolution_rate[i]) // 2 * 2
                vae_encode_out_list.append(self.get_vae_encoder_output(img, lat_h, lat_w))
            vae_encode_out_list.append(self.get_vae_encoder_output(img, self.config.lat_h, self.config.lat_w))
            return vae_encode_out_list
222
223
224
225
226
227
        else:
            self.config.lat_h, self.config.lat_w = lat_h, lat_w
            vae_encode_out = self.get_vae_encoder_output(img, lat_h, lat_w)
            return vae_encode_out

    def get_vae_encoder_output(self, img, lat_h, lat_w):
228
229
        h = lat_h * self.config.vae_stride[1]
        w = lat_w * self.config.vae_stride[2]
helloyongyang's avatar
helloyongyang committed
230

231
232
233
234
235
236
237
        msk = torch.ones(
            1,
            self.config.target_video_length,
            lat_h,
            lat_w,
            device=torch.device("cuda"),
        )
helloyongyang's avatar
helloyongyang committed
238
239
240
241
        msk[:, 1:] = 0
        msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1)
        msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w)
        msk = msk.transpose(1, 2)[0]
gushiqiao's avatar
gushiqiao committed
242
        if self.config.get("lazy_load", False) or self.config.get("unload_modules", False):
243
            self.vae_encoder = self.load_vae_encoder()
244
        vae_encode_out = self.vae_encoder.encode(
245
246
247
248
            [
                torch.concat(
                    [
                        torch.nn.functional.interpolate(img[None].cpu(), size=(h, w), mode="bicubic").transpose(0, 1),
249
                        torch.zeros(3, self.config.target_video_length - 1, h, w),
250
251
252
253
                    ],
                    dim=1,
                ).cuda()
            ],
254
            self.config,
helloyongyang's avatar
helloyongyang committed
255
        )[0]
gushiqiao's avatar
gushiqiao committed
256
        if self.config.get("lazy_load", False) or self.config.get("unload_modules", False):
257
258
259
            del self.vae_encoder
            torch.cuda.empty_cache()
            gc.collect()
helloyongyang's avatar
helloyongyang committed
260
        vae_encode_out = torch.concat([msk, vae_encode_out]).to(torch.bfloat16)
helloyongyang's avatar
helloyongyang committed
261
        return vae_encode_out
262
263

    def get_encoder_output_i2v(self, clip_encoder_out, vae_encode_out, text_encoder_output, img):
264
265
266
267
        image_encoder_output = {
            "clip_encoder_out": clip_encoder_out,
            "vae_encode_out": vae_encode_out,
        }
268
269
270
271
        return {
            "text_encoder_output": text_encoder_output,
            "image_encoder_output": image_encoder_output,
        }
helloyongyang's avatar
helloyongyang committed
272
273

    def set_target_shape(self):
274
        num_channels_latents = self.config.get("num_channels_latents", 16)
helloyongyang's avatar
helloyongyang committed
275
        if self.config.task == "i2v":
276
277
            self.config.target_shape = (
                num_channels_latents,
278
                (self.config.target_video_length - 1) // self.config.vae_stride[0] + 1,
279
280
281
                self.config.lat_h,
                self.config.lat_w,
            )
helloyongyang's avatar
helloyongyang committed
282
283
        elif self.config.task == "t2v":
            self.config.target_shape = (
284
                num_channels_latents,
285
                (self.config.target_video_length - 1) // self.config.vae_stride[0] + 1,
helloyongyang's avatar
helloyongyang committed
286
287
288
                int(self.config.target_height) // self.config.vae_stride[1],
                int(self.config.target_width) // self.config.vae_stride[2],
            )
289
290

    def save_video_func(self, images):
291
292
293
294
295
296
297
298
        cache_video(
            tensor=images,
            save_file=self.config.save_video_path,
            fps=self.config.get("fps", 16),
            nrow=1,
            normalize=True,
            value_range=(-1, 1),
        )