model.py 5.83 KB
Newer Older
helloyongyang's avatar
helloyongyang committed
1
2
3
4
import os
import torch
import time
import glob
5
6
7
from lightx2v.models.networks.wan.weights.pre_weights import WanPreWeights
from lightx2v.models.networks.wan.weights.post_weights import WanPostWeights
from lightx2v.models.networks.wan.weights.transformer_weights import (
helloyongyang's avatar
helloyongyang committed
8
9
    WanTransformerWeights,
)
10
11
12
from lightx2v.models.networks.wan.infer.pre_infer import WanPreInfer
from lightx2v.models.networks.wan.infer.post_infer import WanPostInfer
from lightx2v.models.networks.wan.infer.transformer_infer import (
helloyongyang's avatar
helloyongyang committed
13
14
    WanTransformerInfer,
)
15
from lightx2v.models.networks.wan.infer.feature_caching.transformer_infer import WanTransformerInferTeaCaching
helloyongyang's avatar
helloyongyang committed
16
from safetensors import safe_open
Xinchi Huang's avatar
Xinchi Huang committed
17
18
import lightx2v.attentions.distributed.ulysses.wrap as ulysses_dist_wrap
import lightx2v.attentions.distributed.ring.wrap as ring_dist_wrap
helloyongyang's avatar
helloyongyang committed
19
20
21
22
23
24
25


class WanModel:
    pre_weight_class = WanPreWeights
    post_weight_class = WanPostWeights
    transformer_weight_class = WanTransformerWeights

gushiqiao's avatar
gushiqiao committed
26
    def __init__(self, model_path, config, device):
helloyongyang's avatar
helloyongyang committed
27
28
        self.model_path = model_path
        self.config = config
gushiqiao's avatar
gushiqiao committed
29
        self.device = device
helloyongyang's avatar
helloyongyang committed
30
31
32
        self._init_infer_class()
        self._init_weights()
        self._init_infer()
lijiaqi2's avatar
lijiaqi2 committed
33
        self.current_lora = None
helloyongyang's avatar
helloyongyang committed
34

Xinchi Huang's avatar
Xinchi Huang committed
35
36
37
38
39
40
41
        if config["parallel_attn_type"]:
            if config["parallel_attn_type"] == "ulysses":
                ulysses_dist_wrap.parallelize_wan(self)
            elif config["parallel_attn_type"] == "ring":
                ring_dist_wrap.parallelize_wan(self)
            else:
                raise Exception(f"Unsuppotred parallel_attn_type")
Xinchi Huang's avatar
Xinchi Huang committed
42

Dongz's avatar
Dongz committed
43
        if self.config["cpu_offload"]:
TorynCurtis's avatar
TorynCurtis committed
44
45
            self.to_cpu()

helloyongyang's avatar
helloyongyang committed
46
47
48
49
50
51
    def _init_infer_class(self):
        self.pre_infer_class = WanPreInfer
        self.post_infer_class = WanPostInfer
        if self.config["feature_caching"] == "NoCaching":
            self.transformer_infer_class = WanTransformerInfer
        elif self.config["feature_caching"] == "Tea":
52
            self.transformer_infer_class = WanTransformerInferTeaCaching
helloyongyang's avatar
helloyongyang committed
53
        else:
Dongz's avatar
Dongz committed
54
            raise NotImplementedError(f"Unsupported feature_caching type: {self.config['feature_caching']}")
helloyongyang's avatar
helloyongyang committed
55
56

    def _load_safetensor_to_dict(self, file_path):
lijiaqi2's avatar
lijiaqi2 committed
57
        use_bfloat16 = self.config.get("use_bfloat16", True)
helloyongyang's avatar
helloyongyang committed
58
        with safe_open(file_path, framework="pt") as f:
lijiaqi2's avatar
lijiaqi2 committed
59
60
61
62
            if use_bfloat16:
                tensor_dict = {key: f.get_tensor(key).to(torch.bfloat16).to(self.device) for key in f.keys()}
            else:
                tensor_dict = {key: f.get_tensor(key).to(self.device) for key in f.keys()}
helloyongyang's avatar
helloyongyang committed
63
64
65
66
67
68
69
        return tensor_dict

    def _load_ckpt(self):
        safetensors_pattern = os.path.join(self.model_path, "*.safetensors")
        safetensors_files = glob.glob(safetensors_pattern)

        if not safetensors_files:
Dongz's avatar
Dongz committed
70
            raise FileNotFoundError(f"No .safetensors files found in directory: {self.model_path}")
helloyongyang's avatar
helloyongyang committed
71
72
73
74
75
76
        weight_dict = {}
        for file_path in safetensors_files:
            file_weights = self._load_safetensor_to_dict(file_path)
            weight_dict.update(file_weights)
        return weight_dict

lijiaqi2's avatar
lijiaqi2 committed
77
78
79
80
81
    def _init_weights(self, weight_dict=None):
        if weight_dict is None:
            self.original_weight_dict = self._load_ckpt()
        else:
            self.original_weight_dict = weight_dict
helloyongyang's avatar
helloyongyang committed
82
83
        # init weights
        self.pre_weight = self.pre_weight_class(self.config)
TorynCurtis's avatar
TorynCurtis committed
84
        self.post_weight = self.post_weight_class(self.config)
helloyongyang's avatar
helloyongyang committed
85
86
        self.transformer_weights = self.transformer_weight_class(self.config)
        # load weights
87
88
89
        self.pre_weight.load(self.original_weight_dict)
        self.post_weight.load(self.original_weight_dict)
        self.transformer_weights.load(self.original_weight_dict)
helloyongyang's avatar
helloyongyang committed
90
91
92
93
94
95
96
97

    def _init_infer(self):
        self.pre_infer = self.pre_infer_class(self.config)
        self.post_infer = self.post_infer_class(self.config)
        self.transformer_infer = self.transformer_infer_class(self.config)

    def set_scheduler(self, scheduler):
        self.scheduler = scheduler
98
99
        self.pre_infer.set_scheduler(scheduler)
        self.post_infer.set_scheduler(scheduler)
helloyongyang's avatar
helloyongyang committed
100
101
        self.transformer_infer.set_scheduler(scheduler)

TorynCurtis's avatar
TorynCurtis committed
102
103
104
105
106
107
108
109
110
111
    def to_cpu(self):
        self.pre_weight.to_cpu()
        self.post_weight.to_cpu()
        self.transformer_weights.to_cpu()

    def to_cuda(self):
        self.pre_weight.to_cuda()
        self.post_weight.to_cuda()
        self.transformer_weights.to_cuda()

helloyongyang's avatar
helloyongyang committed
112
    @torch.no_grad()
113
    def infer(self, inputs):
gushiqiao's avatar
gushiqiao committed
114
115
116
117
        if self.config["cpu_offload"]:
            self.pre_weight.to_cuda()
            self.post_weight.to_cuda()

118
        embed, grid_sizes, pre_infer_out = self.pre_infer.infer(self.pre_weight, inputs, positive=True)
Dongz's avatar
Dongz committed
119
120
        x = self.transformer_infer.infer(self.transformer_weights, grid_sizes, embed, *pre_infer_out)
        noise_pred_cond = self.post_infer.infer(self.post_weight, x, embed, grid_sizes)[0]
helloyongyang's avatar
helloyongyang committed
121
122
123
124
125

        if self.config["feature_caching"] == "Tea":
            self.scheduler.cnt += 1
            if self.scheduler.cnt >= self.scheduler.num_steps:
                self.scheduler.cnt = 0
root's avatar
root committed
126
        self.scheduler.noise_pred = noise_pred_cond
helloyongyang's avatar
helloyongyang committed
127

128
        if self.config["enable_cfg"]:
root's avatar
root committed
129
130
131
            embed, grid_sizes, pre_infer_out = self.pre_infer.infer(self.pre_weight, inputs, positive=False)
            x = self.transformer_infer.infer(self.transformer_weights, grid_sizes, embed, *pre_infer_out)
            noise_pred_uncond = self.post_infer.infer(self.post_weight, x, embed, grid_sizes)[0]
helloyongyang's avatar
helloyongyang committed
132

root's avatar
root committed
133
134
135
136
            if self.config["feature_caching"] == "Tea":
                self.scheduler.cnt += 1
                if self.scheduler.cnt >= self.scheduler.num_steps:
                    self.scheduler.cnt = 0
helloyongyang's avatar
helloyongyang committed
137

root's avatar
root committed
138
            self.scheduler.noise_pred = noise_pred_uncond + self.config.sample_guide_scale * (noise_pred_cond - noise_pred_uncond)
gushiqiao's avatar
gushiqiao committed
139

root's avatar
root committed
140
141
142
            if self.config["cpu_offload"]:
                self.pre_weight.to_cpu()
                self.post_weight.to_cpu()