File size: 4,348 Bytes
138fdcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import torch
from torch import nn
from torch.nn import functional as F
from functools import partial
import typing as tp

from einops import rearrange
from diffusers import (
    AutoencoderKL,
    FlowMatchEulerDiscreteScheduler,
    SD3Transformer2DModel,
    StableDiffusion3Pipeline,
)
import math

class SinePositionalEmbedding(nn.Module):
    def __init__(
            self,
            embedding_dim: int,
            dropout: float=0.0,
            scale: bool=False,
            alpha: bool=False, ):
        super().__init__()
        self.embedding_dim = embedding_dim
        self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
        self.alpha = nn.Parameter(torch.ones(1), requires_grad=alpha)
        self.dropout = torch.nn.Dropout(p=dropout)

        self.reverse = False
        self.pe = None
        self.extend_pe(torch.tensor(0.0).expand(1, 4000))

    def extend_pe(self, x):
        """Reset the positional encodings."""
        if self.pe is not None:
            if self.pe.size(1) >= x.size(1):
                if self.pe.dtype != x.dtype or self.pe.device != x.device:
                    self.pe = self.pe.to(dtype=x.dtype, device=x.device)
                return
        pe = torch.zeros(x.size(1), self.embedding_dim)
        if self.reverse:
            position = torch.arange(
                x.size(1) - 1, -1, -1.0, dtype=torch.float32).unsqueeze(1)
        else:
            position = torch.arange(
                0, x.size(1), dtype=torch.float32).unsqueeze(1)
        div_term = torch.exp(
            torch.arange(0, self.embedding_dim, 2, dtype=torch.float32) *
            -(math.log(10000.0) / self.embedding_dim))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0)
        self.pe = pe.to(device=x.device, dtype=x.dtype).detach()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        self.extend_pe(x)
        output = x.unsqueeze(-1) if x.ndim == 2 else x
        output = output * self.x_scale + self.alpha * self.pe[:, :x.size(1)]
        return self.dropout(output)



class SD3DiffusionModelWrapper(nn.Module):
    def __init__(
                self,
    ):
        super().__init__()
        self.model = SD3Transformer2DModel(
            attention_head_dim=64,
            caption_projection_dim=1024,
            in_channels=16,
            joint_attention_dim=384,
            num_attention_heads=16,
            num_layers=6,
            out_channels=16,
            patch_size=1,
            pooled_projection_dim=2048,
            pos_embed_max_size=512,
            sample_size=512
        )
        context_dim = 1024
        self.cond_map_disc = nn.Embedding(32768, 192)
        self.cond_map_cont = nn.Conv1d(context_dim, 192, 3, padding=1)
        self.ssl_position = SinePositionalEmbedding(192*2, dropout=0.1, scale=False, alpha=True)



    def forward(self, x, t, cond=None, cfg=False, **kwargs):
        """
        Forward pass of DiT.
        x:    (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
        t:    (N,) tensor of diffusion timesteps
        cond: [(N, L, D) tensor of SSL embeddings, (N, L) tensor of SSL tokens]
        """        
        ssl_q, toks = cond
        cond_disc = self.cond_map_disc(toks).transpose(1, 2)
        cond_cont = self.cond_map_cont(ssl_q.to(x.dtype).transpose(1, 2))
        cond = torch.cat([cond_disc, cond_cont], dim=1)
        cond = self.ssl_position(cond.transpose(1, 2)) 

        if cfg:
            cond = cond*0

        # cond [b. 1189, 384]
        # t [b]
        # x [b, 16, 512, 16]
        pooled_projections = torch.randn(x.shape[0], 2048).to(x.device)
        noise_pred = self.model(
                hidden_states=x,
            timestep=t,
            encoder_hidden_states=cond,
            pooled_projections=pooled_projections,
            return_dict=False,
        )[0]
        return noise_pred

if __name__ == "__main__":
    model = SD3DiffusionModelWrapper().cuda()
    print('n params', sum(param.numel() for param in model.parameters())/1e6,"m")
    x = torch.randn(2, 16, 512, 32).cuda()
    t = torch.tensor([0.5, 0.5]).cuda()
    cond = [torch.randn(2, 1189, 1024).cuda(), torch.randint(0, 32768, (2, 1189)).cuda()]
    out = model(x, t, cond)
    print(out.shape)