"megatron/legacy/model/transformer.py" did not exist on "cdd2afdf22a8d3490b5c9091c957449765519fdc"
post_infer.py 1.48 KB
Newer Older
helloyongyang's avatar
helloyongyang committed
1
2
3
import math
import torch
import torch.cuda.amp as amp
gushiqiao's avatar
gushiqiao committed
4
from lightx2v.utils.envs import *
helloyongyang's avatar
helloyongyang committed
5
6
7
8
9
10
11


class WanPostInfer:
    def __init__(self, config):
        self.out_dim = config["out_dim"]
        self.patch_size = (1, 2, 2)

12
13
14
    def set_scheduler(self, scheduler):
        self.scheduler = scheduler

helloyongyang's avatar
helloyongyang committed
15
    def infer(self, weights, x, e, grid_sizes):
16
        if e.dim() == 2:
17
            modulation = weights.head_modulation.tensor  # 1, 2, dim
18
19
            e = (modulation + e.unsqueeze(1)).chunk(2, dim=1)
        elif e.dim() == 3:  # For Diffustion forcing
20
            modulation = weights.head_modulation.tensor.unsqueeze(2)  # 1, 2, seq, dim
21
22
23
            e = (modulation + e.unsqueeze(1)).chunk(2, dim=1)
            e = [ei.squeeze(1) for ei in e]

gushiqiao's avatar
gushiqiao committed
24
25
26
27
        norm_out = weights.norm.apply(x)

        if GET_DTYPE() != "BF16":
            norm_out = norm_out.float()
helloyongyang's avatar
helloyongyang committed
28
        out = norm_out * (1 + e[1].squeeze(0)) + e[0].squeeze(0)
gushiqiao's avatar
gushiqiao committed
29
30
31
        if GET_DTYPE() != "BF16":
            out = out.to(torch.bfloat16)

TorynCurtis's avatar
TorynCurtis committed
32
        x = weights.head.apply(out)
helloyongyang's avatar
helloyongyang committed
33
34
35
36
37
38
39
40
41
42
43
44
45
        x = self.unpatchify(x, grid_sizes)
        return [u.float() for u in x]

    def unpatchify(self, x, grid_sizes):
        x = x.unsqueeze(0)
        c = self.out_dim
        out = []
        for u, v in zip(x, grid_sizes.tolist()):
            u = u[: math.prod(v)].view(*v, *self.patch_size, c)
            u = torch.einsum("fhwpqrc->cfphqwr", u)
            u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)])
            out.append(u)
        return out