cuio
/

cuio dummy9996 commited on
Commit
f33cb1d
·
0 Parent(s):

Duplicate from dummy9996/MiniT2I_bf16

Browse files

Co-authored-by: bebop <dummy9996@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ base_model:
3
+ - MiniT2I/MiniT2I
4
+ base_model_relation: quantized
5
+ ---
minit2i-b-16/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MiniT2IFlowMatchScheduler",
3
+ "_diffusers_version": "0.35.2",
4
+ "num_inference_steps": 100,
5
+ "t_lognorm_mu": -0.8,
6
+ "t_lognorm_sigma": 0.8,
7
+ "train_t_schedule": "lognorm"
8
+ }
minit2i-b-16/transformer/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MiniT2IMMJiTModel",
3
+ "_diffusers_version": "0.35.2",
4
+ "cfg_channels": 3,
5
+ "cfg_interval": [
6
+ 0.0,
7
+ 1.0
8
+ ],
9
+ "cond_vec_size": 768,
10
+ "depth_double": 17,
11
+ "head_dim": 64,
12
+ "hidden_size": 768,
13
+ "image_size": 512,
14
+ "in_channels": 3,
15
+ "llm": "google/flan-t5-large",
16
+ "mlp_ratio": 2.6666666666666665,
17
+ "n_T": 100,
18
+ "num_heads": 12,
19
+ "patch_size": 16,
20
+ "pca_channels": 128,
21
+ "prediction": "x",
22
+ "prompt_length": 256,
23
+ "sampler": "euler",
24
+ "txt_hidden_size": 768,
25
+ "txt_input_size": 1024,
26
+ "txt_preamble_depth": 2
27
+ }
minit2i-b-16/transformer/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c65380a0f632de06ddf4b6ae38c61126cddb041d6a916ad0bf7d7af6da36b19
3
+ size 516288952
minit2i-l-16/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MiniT2IFlowMatchScheduler",
3
+ "_diffusers_version": "0.35.2",
4
+ "num_inference_steps": 100,
5
+ "t_lognorm_mu": -0.8,
6
+ "t_lognorm_sigma": 0.8,
7
+ "train_t_schedule": "lognorm"
8
+ }
minit2i-l-16/transformer/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MiniT2IMMJiTModel",
3
+ "_diffusers_version": "0.35.2",
4
+ "cfg_channels": 3,
5
+ "cfg_interval": [
6
+ 0.0,
7
+ 1.0
8
+ ],
9
+ "cond_vec_size": 1248,
10
+ "depth_double": 23,
11
+ "head_dim": 52,
12
+ "hidden_size": 1248,
13
+ "image_size": 512,
14
+ "in_channels": 3,
15
+ "llm": "google/flan-t5-large",
16
+ "mlp_ratio": 2.7051282051282053,
17
+ "n_T": 100,
18
+ "num_heads": 24,
19
+ "patch_size": 16,
20
+ "pca_channels": 128,
21
+ "prediction": "x",
22
+ "prompt_length": 256,
23
+ "sampler": "euler",
24
+ "txt_hidden_size": 1248,
25
+ "txt_input_size": 1024,
26
+ "txt_preamble_depth": 2
27
+ }
minit2i-l-16/transformer/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edef2e54784fe04135afe298fff29c0555980d98ee39608731fe51755227edfc
3
+ size 1823591560
mmdit.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+
9
+
10
+ def modulate(x, shift, scale):
11
+ return x * (1 + scale[:, None, :]) + shift[:, None, :]
12
+
13
+
14
+ def rotate_half(x):
15
+ x1, x2 = x.reshape(*x.shape[:-1], 2, -1).unbind(dim=-2)
16
+ return torch.cat((-x2, x1), dim=-1)
17
+
18
+
19
+ class RMSNorm(nn.Module):
20
+ def __init__(self, dim: int, eps: float = 1e-6):
21
+ super().__init__()
22
+ self.weight = nn.Parameter(torch.ones(dim))
23
+ self.eps = eps
24
+
25
+ def forward(self, x):
26
+ y = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
27
+ return y * self.weight
28
+
29
+
30
+ class TimestepEmbedder(nn.Module):
31
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
32
+ super().__init__()
33
+ self.frequency_embedding_size = frequency_embedding_size
34
+ self.mlp = nn.Sequential(
35
+ nn.Linear(frequency_embedding_size, hidden_size),
36
+ nn.SiLU(),
37
+ nn.Linear(hidden_size, hidden_size),
38
+ )
39
+
40
+ def forward(self, t):
41
+ half = self.frequency_embedding_size // 2
42
+ freqs = torch.exp(
43
+ -math.log(10000.0)
44
+ * torch.arange(half, device=t.device, dtype=torch.float32)
45
+ / half
46
+ )
47
+ args = t.float()[:, None] * freqs[None]
48
+ emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
49
+ return self.mlp(emb.to(dtype=self.mlp[0].weight.dtype))
50
+
51
+
52
+ class BottleneckPatchEmbed(nn.Module):
53
+ def __init__(self, img_size=512, patch_size=16, in_channels=3, pca_channels=128, hidden_size=1248):
54
+ super().__init__()
55
+ self.img_size = img_size
56
+ self.patch_size = patch_size
57
+ self.proj1 = nn.Conv2d(in_channels, pca_channels, kernel_size=patch_size, stride=patch_size, bias=False)
58
+ self.proj2 = nn.Conv2d(pca_channels, hidden_size, kernel_size=1, stride=1, bias=True)
59
+
60
+ def forward(self, x):
61
+ x = self.proj2(self.proj1(x))
62
+ return x.flatten(2).transpose(1, 2)
63
+
64
+
65
+ class SwiGLUMlp(nn.Module):
66
+ def __init__(self, in_features: int, hidden_features: int):
67
+ super().__init__()
68
+ hidden_dim = (hidden_features + 7) // 8 * 8
69
+ self.w1 = nn.Linear(in_features, hidden_dim, bias=False)
70
+ self.w3 = nn.Linear(in_features, hidden_dim, bias=False)
71
+ self.w2 = nn.Linear(hidden_dim, in_features, bias=False)
72
+
73
+ def forward(self, x):
74
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
75
+
76
+
77
+ class TextRotaryEmbedding1D(nn.Module):
78
+ def __init__(self, head_dim: int, theta: float = 10000.0):
79
+ super().__init__()
80
+ self.head_dim = head_dim
81
+ self.theta = theta
82
+
83
+ def forward(self, x):
84
+ b, length, h, d = x.shape
85
+ inv = 1.0 / (self.theta ** (torch.arange(0, d, 2, device=x.device, dtype=torch.float32) / d))
86
+ pos = torch.arange(length, device=x.device, dtype=torch.float32)
87
+ angles = torch.einsum("l,f->lf", pos, inv)
88
+ angles = torch.cat([angles, angles], dim=-1)
89
+ cos = angles.cos().to(dtype=x.dtype)
90
+ sin = angles.sin().to(dtype=x.dtype)
91
+ return x * cos[None, :, None, :] + rotate_half(x) * sin[None, :, None, :]
92
+
93
+
94
+ class VisionRotaryEmbeddingFast(nn.Module):
95
+ def __init__(self, head_dim: int, theta: float = 10000.0):
96
+ super().__init__()
97
+ self.dim = head_dim // 2
98
+ self.theta = theta
99
+
100
+ def forward(self, x):
101
+ length = x.shape[1]
102
+ side = int(math.sqrt(length))
103
+ if side * side != length:
104
+ raise ValueError(f"image token length must be square, got {length}")
105
+ freqs = 1.0 / (
106
+ self.theta
107
+ ** (torch.arange(0, self.dim, 2, device=x.device, dtype=torch.float32)[: self.dim // 2] / self.dim)
108
+ )
109
+ t = torch.arange(side, device=x.device, dtype=torch.float32)
110
+ base = torch.einsum("l,f->lf", t, freqs)
111
+ f_h, f_w = torch.broadcast_tensors(base[:, None, :], base[None, :, :])
112
+ angles = torch.cat([f_h, f_w], dim=-1)
113
+ angles = torch.cat([angles, angles], dim=-1).reshape(length, -1)
114
+ cos = angles.cos().to(dtype=x.dtype)
115
+ sin = angles.sin().to(dtype=x.dtype)
116
+ return x * cos[None, :, None, :] + rotate_half(x) * sin[None, :, None, :]
117
+
118
+
119
+ class MultiModalRotaryEmbeddingFast(nn.Module):
120
+ def __init__(self, head_dim: int):
121
+ super().__init__()
122
+ self.text_rope = TextRotaryEmbedding1D(head_dim)
123
+ self.vision_rope = VisionRotaryEmbeddingFast(head_dim)
124
+
125
+ def forward(self, x, txt_len: int):
126
+ txt = self.text_rope(x[:, :txt_len])
127
+ img = self.vision_rope(x[:, txt_len:])
128
+ return torch.cat([txt, img], dim=1)
129
+
130
+
131
+ class PlainTextTransformerBlock(nn.Module):
132
+ def __init__(self, hidden_size=1248, num_heads=24, head_dim=52, mlp_ratio=2.7):
133
+ super().__init__()
134
+ self.num_heads = num_heads
135
+ self.head_dim = head_dim
136
+ inner_dim = num_heads * head_dim
137
+ self.norm1 = RMSNorm(hidden_size)
138
+ self.norm2 = RMSNorm(hidden_size)
139
+ self.qkv = nn.Linear(hidden_size, inner_dim * 3)
140
+ self.attn_proj = nn.Linear(inner_dim, hidden_size)
141
+ self.mlp = SwiGLUMlp(hidden_size, int(hidden_size * mlp_ratio))
142
+ self.q_norm = RMSNorm(head_dim)
143
+ self.k_norm = RMSNorm(head_dim)
144
+ self.rope = TextRotaryEmbedding1D(head_dim)
145
+
146
+ def forward(self, txt):
147
+ b, length, _ = txt.shape
148
+ qkv = self.qkv(self.norm1(txt)).reshape(b, length, 3, self.num_heads, self.head_dim)
149
+ q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
150
+ q = self.rope(self.q_norm(q))
151
+ k = self.rope(self.k_norm(k))
152
+ attn = torch.einsum("bqhd,bkhd->bhqk", q, k) * (self.head_dim ** -0.5)
153
+ out = torch.einsum("bhqk,bkhd->bqhd", attn.softmax(dim=-1), v).reshape(b, length, -1)
154
+ txt = txt + self.attn_proj(out)
155
+ txt = txt + self.mlp(self.norm2(txt))
156
+ return txt
157
+
158
+
159
+ class DoubleStreamDiTBlock(nn.Module):
160
+ def __init__(self, hidden_size=1248, txt_hidden_size=1248, num_heads=24, head_dim=52, mlp_ratio=2.7):
161
+ super().__init__()
162
+ self.hidden_size = hidden_size
163
+ self.txt_hidden_size = txt_hidden_size
164
+ self.num_heads = num_heads
165
+ self.head_dim = head_dim
166
+ inner_dim = num_heads * head_dim
167
+ self.img_norm1 = RMSNorm(hidden_size)
168
+ self.img_norm2 = RMSNorm(hidden_size)
169
+ self.txt_norm1 = RMSNorm(txt_hidden_size)
170
+ self.txt_norm2 = RMSNorm(txt_hidden_size)
171
+ self.img_qkv = nn.Linear(hidden_size, inner_dim * 3)
172
+ self.txt_qkv = nn.Linear(txt_hidden_size, inner_dim * 3)
173
+ self.q_norm = RMSNorm(head_dim)
174
+ self.k_norm = RMSNorm(head_dim)
175
+ self.rope = MultiModalRotaryEmbeddingFast(head_dim)
176
+ self.img_attn_proj = nn.Linear(inner_dim, hidden_size)
177
+ self.txt_attn_proj = nn.Linear(inner_dim, txt_hidden_size)
178
+ self.img_mlp = SwiGLUMlp(hidden_size, int(hidden_size * mlp_ratio))
179
+ self.txt_mlp = SwiGLUMlp(txt_hidden_size, int(txt_hidden_size * mlp_ratio))
180
+
181
+ def forward(self, x, txt, vec):
182
+ b, li, _ = x.shape
183
+ lt = txt.shape[1]
184
+ x_norm = self.img_norm1(x)
185
+ txt_norm = self.txt_norm1(txt)
186
+ qkv_i = self.img_qkv(x_norm).reshape(b, li, 3, self.num_heads, self.head_dim)
187
+ qkv_t = self.txt_qkv(txt_norm).reshape(b, lt, 3, self.num_heads, self.head_dim)
188
+ q_i, k_i, v_i = qkv_i[:, :, 0], qkv_i[:, :, 1], qkv_i[:, :, 2]
189
+ q_t, k_t, v_t = qkv_t[:, :, 0], qkv_t[:, :, 1], qkv_t[:, :, 2]
190
+ q_i, k_i = self.q_norm(q_i), self.k_norm(k_i)
191
+ q_t, k_t = self.q_norm(q_t), self.k_norm(k_t)
192
+ q = self.rope(torch.cat([q_t, q_i], dim=1), txt_len=lt)
193
+ k = self.rope(torch.cat([k_t, k_i], dim=1), txt_len=lt)
194
+ v = torch.cat([v_t, v_i], dim=1)
195
+ attn = torch.einsum("bqhd,bkhd->bhqk", q, k) * (self.head_dim ** -0.5)
196
+ out = torch.einsum("bhqk,bkhd->bqhd", attn.softmax(dim=-1), v)
197
+ x = x + self.img_attn_proj(out[:, lt:].reshape(b, li, -1))
198
+ txt = txt + self.txt_attn_proj(out[:, :lt].reshape(b, lt, -1))
199
+ x = x + self.img_mlp(self.img_norm2(x))
200
+ txt = txt + self.txt_mlp(self.txt_norm2(txt))
201
+ return x, txt
202
+
203
+
204
+ class FinalLayer(nn.Module):
205
+ def __init__(self, hidden_size=1248, patch_size=16, out_channels=3):
206
+ super().__init__()
207
+ self.patch_size = patch_size
208
+ self.out_channels = out_channels
209
+ self.norm_final = RMSNorm(hidden_size)
210
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels)
211
+
212
+ def forward(self, x, vec=None):
213
+ return self.linear(self.norm_final(x))
214
+
215
+
216
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, device, dtype):
217
+ grid_h = torch.arange(grid_size, device=device, dtype=torch.float32)
218
+ grid_w = torch.arange(grid_size, device=device, dtype=torch.float32)
219
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy")
220
+ grid = torch.stack(grid, dim=0).reshape(2, 1, grid_size, grid_size)
221
+ emb_h = get_1d_sincos_pos_embed(embed_dim // 2, grid[0])
222
+ emb_w = get_1d_sincos_pos_embed(embed_dim // 2, grid[1])
223
+ return torch.cat([emb_h, emb_w], dim=1).to(dtype=dtype)
224
+
225
+
226
+ def get_1d_sincos_pos_embed(embed_dim, pos):
227
+ omega = torch.arange(embed_dim // 2, device=pos.device, dtype=torch.float32)
228
+ omega = 1.0 / (10000 ** (omega / (embed_dim / 2.0)))
229
+ out = torch.einsum("m,d->md", pos.reshape(-1), omega)
230
+ return torch.cat([out.sin(), out.cos()], dim=1)
231
+
232
+
233
+ @dataclass
234
+ class MMJiTConfig:
235
+ image_size: int = 512
236
+ patch_size: int = 16
237
+ in_channels: int = 3
238
+ txt_input_size: int = 1024
239
+ hidden_size: int = 768
240
+ txt_hidden_size: int = 768
241
+ cond_vec_size: int = 768
242
+ depth_double: int = 17
243
+ txt_preamble_depth: int = 2
244
+ num_heads: int = 12
245
+ head_dim: int = 64
246
+ mlp_ratio: float = 2.6667
247
+ pca_channels: int = 128
248
+ prompt_length: int = 256
249
+ n_T: int = 100
250
+ prediction: str = "x"
251
+ sampler: str = "euler"
252
+ cfg_channels: int = 3
253
+ cfg_interval: tuple = (0.0, 1.0)
254
+ llm: str = "google/flan-t5-large"
255
+
256
+
257
+ class MMJiT(nn.Module):
258
+ def __init__(self, cfg: MMJiTConfig):
259
+ super().__init__()
260
+ self.cfg = cfg
261
+ self.latent_img_size = cfg.image_size // cfg.patch_size
262
+ self.img_embedder = BottleneckPatchEmbed(
263
+ cfg.image_size, cfg.patch_size, cfg.in_channels, cfg.pca_channels, cfg.hidden_size
264
+ )
265
+ self.txt_embedder = nn.Linear(cfg.txt_input_size, cfg.txt_hidden_size, bias=False)
266
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, cfg.txt_input_size))
267
+ self.t_embedder = TimestepEmbedder(cfg.cond_vec_size)
268
+ self.pooled_embedder = nn.Linear(cfg.txt_input_size, cfg.cond_vec_size, bias=False)
269
+ self.txt_preamble_blocks = nn.ModuleList(
270
+ [PlainTextTransformerBlock(cfg.txt_hidden_size, cfg.num_heads, cfg.head_dim, cfg.mlp_ratio) for _ in range(cfg.txt_preamble_depth)]
271
+ )
272
+ self.double_blocks = nn.ModuleList(
273
+ [
274
+ DoubleStreamDiTBlock(
275
+ cfg.hidden_size, cfg.txt_hidden_size, cfg.num_heads, cfg.head_dim, cfg.mlp_ratio
276
+ )
277
+ for _ in range(cfg.depth_double)
278
+ ]
279
+ )
280
+ self.final_layer = FinalLayer(cfg.hidden_size, cfg.patch_size, cfg.in_channels)
281
+
282
+ def unpatchify(self, x):
283
+ b = x.shape[0]
284
+ p = self.cfg.patch_size
285
+ c = self.cfg.in_channels
286
+ h = w = int(math.sqrt(x.shape[1]))
287
+ x = x.reshape(b, h, w, p, p, c)
288
+ x = torch.einsum("nhwpqc->nchpwq", x)
289
+ return x.reshape(b, c, h * p, w * p)
290
+
291
+ def forward(self, img, t, context, attn_mask):
292
+ if img.ndim == 4 and img.shape[1] != self.cfg.in_channels:
293
+ img = img.permute(0, 3, 1, 2)
294
+ attn_mask = attn_mask.to(device=context.device)
295
+ context = torch.where(attn_mask[:, :, None] > 0.5, context, self.mask_token.to(dtype=context.dtype))
296
+ x = self.img_embedder(img)
297
+ pos = get_2d_sincos_pos_embed(self.cfg.hidden_size, self.latent_img_size, x.device, x.dtype)
298
+ x = x + pos[None]
299
+ t_vec = self.t_embedder(t)
300
+ txt = self.txt_embedder(context.to(dtype=self.txt_embedder.weight.dtype))
301
+ pooled_text = context.mean(dim=1)
302
+ vec = t_vec + self.pooled_embedder(pooled_text.to(dtype=self.pooled_embedder.weight.dtype))
303
+ for block in self.txt_preamble_blocks:
304
+ txt = block(txt)
305
+ for block in self.double_blocks:
306
+ x, txt = block(x, txt, vec)
307
+ combined = torch.cat([txt, x], dim=1)
308
+ out = self.final_layer(combined, vec)
309
+ img_out = out[:, txt.shape[1] :, :]
310
+ return self.unpatchify(img_out)
311
+
312
+
313
+ class DiffusionModel(nn.Module):
314
+ def __init__(self, cfg: Optional[MMJiTConfig] = None):
315
+ super().__init__()
316
+ self.cfg = cfg or MMJiTConfig()
317
+ self.net = MMJiT(self.cfg)
318
+
319
+ def real_t_to_embed_t(self, t):
320
+ return t
321
+
322
+ def pred_velocity(self, x, t, text, mask):
323
+ x0 = self.net(x, self.real_t_to_embed_t(t), text, mask)
324
+ return (x0 - x) / torch.clamp(1 - t[:, None, None, None], min=0.001)
325
+
326
+ def cfg_velocity(self, x, t, text, mask, cfg_scale: float):
327
+ b = x.shape[0]
328
+ xx = torch.cat([x, x], dim=0)
329
+ tt = torch.cat([t, t], dim=0)
330
+ yy = torch.cat([text, text], dim=0)
331
+ mm = torch.cat([mask, torch.zeros_like(mask)], dim=0)
332
+ out = self.pred_velocity(xx, tt, yy, mm)
333
+ cond, uncond = out[:b], out[b:]
334
+ use_cfg = ((t >= self.cfg.cfg_interval[0]) & (t <= self.cfg.cfg_interval[1])).to(out.dtype)
335
+ scale = torch.where(use_cfg[:, None, None, None] > 0, torch.tensor(cfg_scale, device=x.device, dtype=out.dtype), torch.tensor(1.0, device=x.device, dtype=out.dtype))
336
+ return uncond + (cond - uncond) * scale
337
+
338
+ @torch.no_grad()
339
+ def sample(self, text, mask, cfg_scale=6.0, generator=None, progress=False):
340
+ b = text.shape[0]
341
+ device = text.device
342
+ dtype = next(self.parameters()).dtype
343
+ x = torch.randn(
344
+ b, self.cfg.in_channels, self.cfg.image_size, self.cfg.image_size,
345
+ generator=generator, device=device, dtype=dtype,
346
+ ) * 2
347
+ timesteps = torch.linspace(0.0, 1.0, self.cfg.n_T + 1, device=device, dtype=dtype)
348
+ iterator = range(self.cfg.n_T)
349
+ if progress:
350
+ from tqdm.auto import tqdm
351
+ iterator = tqdm(iterator)
352
+ for i in iterator:
353
+ t_cur = timesteps[i].expand(b)
354
+ t_next = timesteps[i + 1].expand(b)
355
+ v = self.cfg_velocity(x, t_cur, text.to(dtype), mask.to(dtype), cfg_scale)
356
+ x = x + (t_next - t_cur)[:, None, None, None] * v
357
+ return x
model_index.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_class_name": "MiniT2IPipeline",
3
+ "_diffusers_version": "0.35.2"
4
+ }
pipeline.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+
9
+
10
+ def modulate(x, shift, scale):
11
+ return x * (1 + scale[:, None, :]) + shift[:, None, :]
12
+
13
+
14
+ def rotate_half(x):
15
+ x1, x2 = x.reshape(*x.shape[:-1], 2, -1).unbind(dim=-2)
16
+ return torch.cat((-x2, x1), dim=-1)
17
+
18
+
19
+ class RMSNorm(nn.Module):
20
+ def __init__(self, dim: int, eps: float = 1e-6):
21
+ super().__init__()
22
+ self.weight = nn.Parameter(torch.ones(dim))
23
+ self.eps = eps
24
+
25
+ def forward(self, x):
26
+ y = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
27
+ return y * self.weight
28
+
29
+
30
+ class TimestepEmbedder(nn.Module):
31
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
32
+ super().__init__()
33
+ self.frequency_embedding_size = frequency_embedding_size
34
+ self.mlp = nn.Sequential(
35
+ nn.Linear(frequency_embedding_size, hidden_size),
36
+ nn.SiLU(),
37
+ nn.Linear(hidden_size, hidden_size),
38
+ )
39
+
40
+ def forward(self, t):
41
+ half = self.frequency_embedding_size // 2
42
+ freqs = torch.exp(
43
+ -math.log(10000.0)
44
+ * torch.arange(half, device=t.device, dtype=torch.float32)
45
+ / half
46
+ )
47
+ args = t.float()[:, None] * freqs[None]
48
+ emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
49
+ return self.mlp(emb.to(dtype=self.mlp[0].weight.dtype))
50
+
51
+
52
+ class BottleneckPatchEmbed(nn.Module):
53
+ def __init__(self, img_size=512, patch_size=16, in_channels=3, pca_channels=128, hidden_size=1248):
54
+ super().__init__()
55
+ self.img_size = img_size
56
+ self.patch_size = patch_size
57
+ self.proj1 = nn.Conv2d(in_channels, pca_channels, kernel_size=patch_size, stride=patch_size, bias=False)
58
+ self.proj2 = nn.Conv2d(pca_channels, hidden_size, kernel_size=1, stride=1, bias=True)
59
+
60
+ def forward(self, x):
61
+ x = self.proj2(self.proj1(x))
62
+ return x.flatten(2).transpose(1, 2)
63
+
64
+
65
+ class SwiGLUMlp(nn.Module):
66
+ def __init__(self, in_features: int, hidden_features: int):
67
+ super().__init__()
68
+ hidden_dim = (hidden_features + 7) // 8 * 8
69
+ self.w1 = nn.Linear(in_features, hidden_dim, bias=False)
70
+ self.w3 = nn.Linear(in_features, hidden_dim, bias=False)
71
+ self.w2 = nn.Linear(hidden_dim, in_features, bias=False)
72
+
73
+ def forward(self, x):
74
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
75
+
76
+
77
+ class TextRotaryEmbedding1D(nn.Module):
78
+ def __init__(self, head_dim: int, theta: float = 10000.0):
79
+ super().__init__()
80
+ self.head_dim = head_dim
81
+ self.theta = theta
82
+
83
+ def forward(self, x):
84
+ b, length, h, d = x.shape
85
+ inv = 1.0 / (self.theta ** (torch.arange(0, d, 2, device=x.device, dtype=torch.float32) / d))
86
+ pos = torch.arange(length, device=x.device, dtype=torch.float32)
87
+ angles = torch.einsum("l,f->lf", pos, inv)
88
+ angles = torch.cat([angles, angles], dim=-1)
89
+ cos = angles.cos().to(dtype=x.dtype)
90
+ sin = angles.sin().to(dtype=x.dtype)
91
+ return x * cos[None, :, None, :] + rotate_half(x) * sin[None, :, None, :]
92
+
93
+
94
+ class VisionRotaryEmbeddingFast(nn.Module):
95
+ def __init__(self, head_dim: int, theta: float = 10000.0):
96
+ super().__init__()
97
+ self.dim = head_dim // 2
98
+ self.theta = theta
99
+
100
+ def forward(self, x):
101
+ length = x.shape[1]
102
+ side = int(math.sqrt(length))
103
+ if side * side != length:
104
+ raise ValueError(f"image token length must be square, got {length}")
105
+ freqs = 1.0 / (
106
+ self.theta
107
+ ** (torch.arange(0, self.dim, 2, device=x.device, dtype=torch.float32)[: self.dim // 2] / self.dim)
108
+ )
109
+ t = torch.arange(side, device=x.device, dtype=torch.float32)
110
+ base = torch.einsum("l,f->lf", t, freqs)
111
+ f_h, f_w = torch.broadcast_tensors(base[:, None, :], base[None, :, :])
112
+ angles = torch.cat([f_h, f_w], dim=-1)
113
+ angles = torch.cat([angles, angles], dim=-1).reshape(length, -1)
114
+ cos = angles.cos().to(dtype=x.dtype)
115
+ sin = angles.sin().to(dtype=x.dtype)
116
+ return x * cos[None, :, None, :] + rotate_half(x) * sin[None, :, None, :]
117
+
118
+
119
+ class MultiModalRotaryEmbeddingFast(nn.Module):
120
+ def __init__(self, head_dim: int):
121
+ super().__init__()
122
+ self.text_rope = TextRotaryEmbedding1D(head_dim)
123
+ self.vision_rope = VisionRotaryEmbeddingFast(head_dim)
124
+
125
+ def forward(self, x, txt_len: int):
126
+ txt = self.text_rope(x[:, :txt_len])
127
+ img = self.vision_rope(x[:, txt_len:])
128
+ return torch.cat([txt, img], dim=1)
129
+
130
+
131
+ class PlainTextTransformerBlock(nn.Module):
132
+ def __init__(self, hidden_size=1248, num_heads=24, head_dim=52, mlp_ratio=2.7):
133
+ super().__init__()
134
+ self.num_heads = num_heads
135
+ self.head_dim = head_dim
136
+ inner_dim = num_heads * head_dim
137
+ self.norm1 = RMSNorm(hidden_size)
138
+ self.norm2 = RMSNorm(hidden_size)
139
+ self.qkv = nn.Linear(hidden_size, inner_dim * 3)
140
+ self.attn_proj = nn.Linear(inner_dim, hidden_size)
141
+ self.mlp = SwiGLUMlp(hidden_size, int(hidden_size * mlp_ratio))
142
+ self.q_norm = RMSNorm(head_dim)
143
+ self.k_norm = RMSNorm(head_dim)
144
+ self.rope = TextRotaryEmbedding1D(head_dim)
145
+
146
+ def forward(self, txt):
147
+ b, length, _ = txt.shape
148
+ qkv = self.qkv(self.norm1(txt)).reshape(b, length, 3, self.num_heads, self.head_dim)
149
+ q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
150
+ q = self.rope(self.q_norm(q))
151
+ k = self.rope(self.k_norm(k))
152
+ attn = torch.einsum("bqhd,bkhd->bhqk", q, k) * (self.head_dim ** -0.5)
153
+ out = torch.einsum("bhqk,bkhd->bqhd", attn.softmax(dim=-1), v).reshape(b, length, -1)
154
+ txt = txt + self.attn_proj(out)
155
+ txt = txt + self.mlp(self.norm2(txt))
156
+ return txt
157
+
158
+
159
+ class DoubleStreamDiTBlock(nn.Module):
160
+ def __init__(self, hidden_size=1248, txt_hidden_size=1248, num_heads=24, head_dim=52, mlp_ratio=2.7):
161
+ super().__init__()
162
+ self.hidden_size = hidden_size
163
+ self.txt_hidden_size = txt_hidden_size
164
+ self.num_heads = num_heads
165
+ self.head_dim = head_dim
166
+ inner_dim = num_heads * head_dim
167
+ self.img_norm1 = RMSNorm(hidden_size)
168
+ self.img_norm2 = RMSNorm(hidden_size)
169
+ self.txt_norm1 = RMSNorm(txt_hidden_size)
170
+ self.txt_norm2 = RMSNorm(txt_hidden_size)
171
+ self.img_qkv = nn.Linear(hidden_size, inner_dim * 3)
172
+ self.txt_qkv = nn.Linear(txt_hidden_size, inner_dim * 3)
173
+ self.q_norm = RMSNorm(head_dim)
174
+ self.k_norm = RMSNorm(head_dim)
175
+ self.rope = MultiModalRotaryEmbeddingFast(head_dim)
176
+ self.img_attn_proj = nn.Linear(inner_dim, hidden_size)
177
+ self.txt_attn_proj = nn.Linear(inner_dim, txt_hidden_size)
178
+ self.img_mlp = SwiGLUMlp(hidden_size, int(hidden_size * mlp_ratio))
179
+ self.txt_mlp = SwiGLUMlp(txt_hidden_size, int(txt_hidden_size * mlp_ratio))
180
+
181
+ def forward(self, x, txt, vec):
182
+ b, li, _ = x.shape
183
+ lt = txt.shape[1]
184
+ x_norm = self.img_norm1(x)
185
+ txt_norm = self.txt_norm1(txt)
186
+ qkv_i = self.img_qkv(x_norm).reshape(b, li, 3, self.num_heads, self.head_dim)
187
+ qkv_t = self.txt_qkv(txt_norm).reshape(b, lt, 3, self.num_heads, self.head_dim)
188
+ q_i, k_i, v_i = qkv_i[:, :, 0], qkv_i[:, :, 1], qkv_i[:, :, 2]
189
+ q_t, k_t, v_t = qkv_t[:, :, 0], qkv_t[:, :, 1], qkv_t[:, :, 2]
190
+ q_i, k_i = self.q_norm(q_i), self.k_norm(k_i)
191
+ q_t, k_t = self.q_norm(q_t), self.k_norm(k_t)
192
+ q = self.rope(torch.cat([q_t, q_i], dim=1), txt_len=lt)
193
+ k = self.rope(torch.cat([k_t, k_i], dim=1), txt_len=lt)
194
+ v = torch.cat([v_t, v_i], dim=1)
195
+ attn = torch.einsum("bqhd,bkhd->bhqk", q, k) * (self.head_dim ** -0.5)
196
+ out = torch.einsum("bhqk,bkhd->bqhd", attn.softmax(dim=-1), v)
197
+ x = x + self.img_attn_proj(out[:, lt:].reshape(b, li, -1))
198
+ txt = txt + self.txt_attn_proj(out[:, :lt].reshape(b, lt, -1))
199
+ x = x + self.img_mlp(self.img_norm2(x))
200
+ txt = txt + self.txt_mlp(self.txt_norm2(txt))
201
+ return x, txt
202
+
203
+
204
+ class FinalLayer(nn.Module):
205
+ def __init__(self, hidden_size=1248, patch_size=16, out_channels=3):
206
+ super().__init__()
207
+ self.patch_size = patch_size
208
+ self.out_channels = out_channels
209
+ self.norm_final = RMSNorm(hidden_size)
210
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels)
211
+
212
+ def forward(self, x, vec=None):
213
+ return self.linear(self.norm_final(x))
214
+
215
+
216
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, device, dtype):
217
+ grid_h = torch.arange(grid_size, device=device, dtype=torch.float32)
218
+ grid_w = torch.arange(grid_size, device=device, dtype=torch.float32)
219
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy")
220
+ grid = torch.stack(grid, dim=0).reshape(2, 1, grid_size, grid_size)
221
+ emb_h = get_1d_sincos_pos_embed(embed_dim // 2, grid[0])
222
+ emb_w = get_1d_sincos_pos_embed(embed_dim // 2, grid[1])
223
+ return torch.cat([emb_h, emb_w], dim=1).to(dtype=dtype)
224
+
225
+
226
+ def get_1d_sincos_pos_embed(embed_dim, pos):
227
+ omega = torch.arange(embed_dim // 2, device=pos.device, dtype=torch.float32)
228
+ omega = 1.0 / (10000 ** (omega / (embed_dim / 2.0)))
229
+ out = torch.einsum("m,d->md", pos.reshape(-1), omega)
230
+ return torch.cat([out.sin(), out.cos()], dim=1)
231
+
232
+
233
+ @dataclass
234
+ class MMJiTConfig:
235
+ image_size: int = 512
236
+ patch_size: int = 16
237
+ in_channels: int = 3
238
+ txt_input_size: int = 1024
239
+ hidden_size: int = 768
240
+ txt_hidden_size: int = 768
241
+ cond_vec_size: int = 768
242
+ depth_double: int = 17
243
+ txt_preamble_depth: int = 2
244
+ num_heads: int = 12
245
+ head_dim: int = 64
246
+ mlp_ratio: float = 2.6667
247
+ pca_channels: int = 128
248
+ prompt_length: int = 256
249
+ n_T: int = 100
250
+ prediction: str = "x"
251
+ sampler: str = "euler"
252
+ cfg_channels: int = 3
253
+ cfg_interval: tuple = (0.0, 1.0)
254
+ llm: str = "google/flan-t5-large"
255
+
256
+
257
+ class MMJiT(nn.Module):
258
+ def __init__(self, cfg: MMJiTConfig):
259
+ super().__init__()
260
+ self.cfg = cfg
261
+ self.latent_img_size = cfg.image_size // cfg.patch_size
262
+ self.img_embedder = BottleneckPatchEmbed(
263
+ cfg.image_size, cfg.patch_size, cfg.in_channels, cfg.pca_channels, cfg.hidden_size
264
+ )
265
+ self.txt_embedder = nn.Linear(cfg.txt_input_size, cfg.txt_hidden_size, bias=False)
266
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, cfg.txt_input_size))
267
+ self.t_embedder = TimestepEmbedder(cfg.cond_vec_size)
268
+ self.pooled_embedder = nn.Linear(cfg.txt_input_size, cfg.cond_vec_size, bias=False)
269
+ self.txt_preamble_blocks = nn.ModuleList(
270
+ [PlainTextTransformerBlock(cfg.txt_hidden_size, cfg.num_heads, cfg.head_dim, cfg.mlp_ratio) for _ in range(cfg.txt_preamble_depth)]
271
+ )
272
+ self.double_blocks = nn.ModuleList(
273
+ [
274
+ DoubleStreamDiTBlock(
275
+ cfg.hidden_size, cfg.txt_hidden_size, cfg.num_heads, cfg.head_dim, cfg.mlp_ratio
276
+ )
277
+ for _ in range(cfg.depth_double)
278
+ ]
279
+ )
280
+ self.final_layer = FinalLayer(cfg.hidden_size, cfg.patch_size, cfg.in_channels)
281
+
282
+ def unpatchify(self, x):
283
+ b = x.shape[0]
284
+ p = self.cfg.patch_size
285
+ c = self.cfg.in_channels
286
+ h = w = int(math.sqrt(x.shape[1]))
287
+ x = x.reshape(b, h, w, p, p, c)
288
+ x = torch.einsum("nhwpqc->nchpwq", x)
289
+ return x.reshape(b, c, h * p, w * p)
290
+
291
+ def forward(self, img, t, context, attn_mask):
292
+ if img.ndim == 4 and img.shape[1] != self.cfg.in_channels:
293
+ img = img.permute(0, 3, 1, 2)
294
+ attn_mask = attn_mask.to(device=context.device)
295
+ context = torch.where(attn_mask[:, :, None] > 0.5, context, self.mask_token.to(dtype=context.dtype))
296
+ x = self.img_embedder(img)
297
+ pos = get_2d_sincos_pos_embed(self.cfg.hidden_size, self.latent_img_size, x.device, x.dtype)
298
+ x = x + pos[None]
299
+ t_vec = self.t_embedder(t)
300
+ txt = self.txt_embedder(context.to(dtype=self.txt_embedder.weight.dtype))
301
+ pooled_text = context.mean(dim=1)
302
+ vec = t_vec + self.pooled_embedder(pooled_text.to(dtype=self.pooled_embedder.weight.dtype))
303
+ for block in self.txt_preamble_blocks:
304
+ txt = block(txt)
305
+ for block in self.double_blocks:
306
+ x, txt = block(x, txt, vec)
307
+ combined = torch.cat([txt, x], dim=1)
308
+ out = self.final_layer(combined, vec)
309
+ img_out = out[:, txt.shape[1] :, :]
310
+ return self.unpatchify(img_out)
311
+
312
+
313
+ class DiffusionModel(nn.Module):
314
+ def __init__(self, cfg: Optional[MMJiTConfig] = None):
315
+ super().__init__()
316
+ self.cfg = cfg or MMJiTConfig()
317
+ self.net = MMJiT(self.cfg)
318
+
319
+ def real_t_to_embed_t(self, t):
320
+ return t
321
+
322
+ def pred_velocity(self, x, t, text, mask):
323
+ x0 = self.net(x, self.real_t_to_embed_t(t), text, mask)
324
+ return (x0 - x) / torch.clamp(1 - t[:, None, None, None], min=0.001)
325
+
326
+ def cfg_velocity(self, x, t, text, mask, cfg_scale: float):
327
+ b = x.shape[0]
328
+ xx = torch.cat([x, x], dim=0)
329
+ tt = torch.cat([t, t], dim=0)
330
+ yy = torch.cat([text, text], dim=0)
331
+ mm = torch.cat([mask, torch.zeros_like(mask)], dim=0)
332
+ out = self.pred_velocity(xx, tt, yy, mm)
333
+ cond, uncond = out[:b], out[b:]
334
+ use_cfg = ((t >= self.cfg.cfg_interval[0]) & (t <= self.cfg.cfg_interval[1])).to(out.dtype)
335
+ scale = torch.where(use_cfg[:, None, None, None] > 0, torch.tensor(cfg_scale, device=x.device, dtype=out.dtype), torch.tensor(1.0, device=x.device, dtype=out.dtype))
336
+ return uncond + (cond - uncond) * scale
337
+
338
+ @torch.no_grad()
339
+ def sample(self, text, mask, cfg_scale=6.0, generator=None, progress=False):
340
+ b = text.shape[0]
341
+ device = text.device
342
+ dtype = next(self.parameters()).dtype
343
+ x = torch.randn(
344
+ b, self.cfg.in_channels, self.cfg.image_size, self.cfg.image_size,
345
+ generator=generator, device=device, dtype=dtype,
346
+ ) * 2
347
+ timesteps = torch.linspace(0.0, 1.0, self.cfg.n_T + 1, device=device, dtype=dtype)
348
+ iterator = range(self.cfg.n_T)
349
+ if progress:
350
+ from tqdm.auto import tqdm
351
+ iterator = tqdm(iterator)
352
+ for i in iterator:
353
+ t_cur = timesteps[i].expand(b)
354
+ t_next = timesteps[i + 1].expand(b)
355
+ v = self.cfg_velocity(x, t_cur, text.to(dtype), mask.to(dtype), cfg_scale)
356
+ x = x + (t_next - t_cur)[:, None, None, None] * v
357
+ return x
358
+
359
+
360
+ import os
361
+ from dataclasses import asdict
362
+ from pathlib import Path
363
+ from types import SimpleNamespace
364
+ from typing import List, Optional, Union
365
+
366
+ os.environ.setdefault("USE_FLAX", "0")
367
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
368
+
369
+ import torch
370
+ from PIL import Image
371
+ from huggingface_hub import snapshot_download
372
+ from transformers import AutoTokenizer, T5EncoderModel
373
+ from transformers import logging as transformers_logging
374
+
375
+ from diffusers import DiffusionPipeline, ModelMixin
376
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
377
+ from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
378
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
379
+
380
+
381
+ transformers_logging.set_verbosity_error()
382
+
383
+
384
+ class MiniT2IFlowMatchScheduler(SchedulerMixin, ConfigMixin):
385
+ config_name = "scheduler_config.json"
386
+
387
+ @register_to_config
388
+ def __init__(
389
+ self,
390
+ train_t_schedule: str = "lognorm",
391
+ t_lognorm_mu: float = -0.8,
392
+ t_lognorm_sigma: float = 0.8,
393
+ num_inference_steps: int = 100,
394
+ ):
395
+ if train_t_schedule not in {"uniform", "lognorm"}:
396
+ raise ValueError(f"Unsupported train_t_schedule: {train_t_schedule}")
397
+
398
+ def sample_train_timesteps(self, batch_size, device, dtype=torch.float32, generator=None):
399
+ if self.config.train_t_schedule == "uniform":
400
+ return torch.rand(batch_size, device=device, dtype=dtype, generator=generator)
401
+ normal = torch.randn(batch_size, device=device, dtype=torch.float32, generator=generator)
402
+ normal = normal * self.config.t_lognorm_sigma + self.config.t_lognorm_mu
403
+ return torch.sigmoid(normal).to(dtype=dtype)
404
+
405
+ def get_inference_timesteps(self, num_inference_steps=None, device=None, dtype=torch.float32):
406
+ steps = int(num_inference_steps or self.config.num_inference_steps)
407
+ return torch.linspace(0.0, 1.0, steps + 1, device=device, dtype=dtype)
408
+
409
+
410
+ class MiniT2IMMJiTModel(ModelMixin, ConfigMixin):
411
+ config_name = "config.json"
412
+
413
+ @register_to_config
414
+ def __init__(
415
+ self,
416
+ image_size: int = 512,
417
+ patch_size: int = 16,
418
+ in_channels: int = 3,
419
+ txt_input_size: int = 1024,
420
+ hidden_size: int = 768,
421
+ txt_hidden_size: int = 768,
422
+ cond_vec_size: int = 768,
423
+ depth_double: int = 17,
424
+ txt_preamble_depth: int = 2,
425
+ num_heads: int = 12,
426
+ head_dim: int = 64,
427
+ mlp_ratio: float = 2.6666666666666665,
428
+ pca_channels: int = 128,
429
+ prompt_length: int = 256,
430
+ n_T: int = 100,
431
+ prediction: str = "x",
432
+ sampler: str = "euler",
433
+ cfg_channels: int = 3,
434
+ cfg_interval: tuple = (0.0, 1.0),
435
+ llm: str = "google/flan-t5-large",
436
+ ):
437
+ super().__init__()
438
+ cfg = MMJiTConfig(
439
+ image_size=image_size,
440
+ patch_size=patch_size,
441
+ in_channels=in_channels,
442
+ txt_input_size=txt_input_size,
443
+ hidden_size=hidden_size,
444
+ txt_hidden_size=txt_hidden_size,
445
+ cond_vec_size=cond_vec_size,
446
+ depth_double=depth_double,
447
+ txt_preamble_depth=txt_preamble_depth,
448
+ num_heads=num_heads,
449
+ head_dim=head_dim,
450
+ mlp_ratio=mlp_ratio,
451
+ pca_channels=pca_channels,
452
+ prompt_length=prompt_length,
453
+ n_T=n_T,
454
+ prediction=prediction,
455
+ sampler=sampler,
456
+ cfg_channels=cfg_channels,
457
+ cfg_interval=tuple(cfg_interval),
458
+ llm=llm,
459
+ )
460
+ self.model = DiffusionModel(cfg)
461
+
462
+ @property
463
+ def mmjit_config(self) -> MMJiTConfig:
464
+ return self.model.cfg
465
+
466
+ def forward(self, img, t, context, attn_mask):
467
+ return self.model.net(img, t, context, attn_mask)
468
+
469
+ def pred_velocity(self, x, t, text, mask):
470
+ return self.model.pred_velocity(x, t, text, mask)
471
+
472
+ def sample(self, text, mask, cfg_scale=6.0, generator=None, progress=False):
473
+ return self.model.sample(text, mask, cfg_scale=cfg_scale, generator=generator, progress=progress)
474
+
475
+
476
+ class MiniT2ITextToImagePipeline(nn.Module):
477
+ def __init__(
478
+ self,
479
+ transformer: MiniT2IMMJiTModel,
480
+ scheduler: Optional[MiniT2IFlowMatchScheduler] = None,
481
+ tokenizer=None,
482
+ text_encoder=None,
483
+ text_encoder_name: str = "google/flan-t5-large",
484
+ train_t_schedule: str = "lognorm",
485
+ t_lognorm_mu: float = -0.8,
486
+ t_lognorm_sigma: float = 0.8,
487
+ num_inference_steps: int = 100,
488
+ ):
489
+ super().__init__()
490
+ if not isinstance(scheduler, MiniT2IFlowMatchScheduler):
491
+ scheduler = MiniT2IFlowMatchScheduler(
492
+ train_t_schedule=train_t_schedule,
493
+ t_lognorm_mu=t_lognorm_mu,
494
+ t_lognorm_sigma=t_lognorm_sigma,
495
+ num_inference_steps=num_inference_steps,
496
+ )
497
+ self.transformer = transformer
498
+ self.scheduler = scheduler
499
+ self.tokenizer = tokenizer
500
+ self.text_encoder = text_encoder
501
+ self.config = SimpleNamespace(
502
+ text_encoder_name=text_encoder_name,
503
+ train_t_schedule=scheduler.config.train_t_schedule,
504
+ t_lognorm_mu=scheduler.config.t_lognorm_mu,
505
+ t_lognorm_sigma=scheduler.config.t_lognorm_sigma,
506
+ num_inference_steps=scheduler.config.num_inference_steps,
507
+ )
508
+
509
+ @classmethod
510
+ def from_pretrained(
511
+ cls,
512
+ pretrained_model_name_or_path: Union[str, os.PathLike],
513
+ torch_dtype: Optional[torch.dtype] = None,
514
+ text_encoder_dtype: torch.dtype = torch.float32,
515
+ local_files_only: bool = False,
516
+ revision: Optional[str] = None,
517
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
518
+ **kwargs,
519
+ ):
520
+ root = Path(pretrained_model_name_or_path)
521
+ if not root.exists():
522
+ root = Path(
523
+ snapshot_download(
524
+ repo_id=str(pretrained_model_name_or_path),
525
+ revision=revision,
526
+ cache_dir=cache_dir,
527
+ local_files_only=local_files_only,
528
+ )
529
+ )
530
+ transformer = MiniT2IMMJiTModel.from_pretrained(root / "transformer", torch_dtype=torch_dtype, **kwargs)
531
+ scheduler_dir = root / "scheduler"
532
+ if scheduler_dir.exists():
533
+ scheduler = MiniT2IFlowMatchScheduler.from_pretrained(scheduler_dir)
534
+ else:
535
+ scheduler = MiniT2IFlowMatchScheduler()
536
+ text_encoder_name = transformer.mmjit_config.llm
537
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_name, local_files_only=local_files_only)
538
+ text_encoder = T5EncoderModel.from_pretrained(
539
+ text_encoder_name,
540
+ torch_dtype=text_encoder_dtype,
541
+ local_files_only=local_files_only,
542
+ )
543
+ return cls(
544
+ transformer=transformer,
545
+ scheduler=scheduler,
546
+ tokenizer=tokenizer,
547
+ text_encoder=text_encoder,
548
+ text_encoder_name=text_encoder_name,
549
+ )
550
+
551
+ def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs):
552
+ save_directory = Path(save_directory)
553
+ save_directory.mkdir(parents=True, exist_ok=True)
554
+ self.transformer.save_pretrained(save_directory / "transformer", **kwargs)
555
+ self.scheduler.save_pretrained(save_directory / "scheduler")
556
+
557
+ def _encode_prompt(self, prompt: Union[str, List[str]], device):
558
+ if isinstance(prompt, str):
559
+ prompt = [prompt]
560
+ if self.tokenizer is None:
561
+ self.tokenizer = AutoTokenizer.from_pretrained(self.config.text_encoder_name)
562
+ if self.text_encoder is None:
563
+ self.text_encoder = T5EncoderModel.from_pretrained(self.config.text_encoder_name)
564
+ if next(self.text_encoder.parameters()).device != device:
565
+ self.text_encoder.to(device)
566
+ cfg = self.transformer.mmjit_config
567
+ tokens = self.tokenizer(
568
+ prompt,
569
+ return_tensors="pt",
570
+ padding="max_length",
571
+ truncation=True,
572
+ max_length=cfg.prompt_length,
573
+ )
574
+ input_ids = tokens.input_ids.to(device)
575
+ attn = tokens.attention_mask.to(device)
576
+ text = self.text_encoder(input_ids=input_ids, attention_mask=attn).last_hidden_state
577
+ return text, attn
578
+
579
+ @torch.no_grad()
580
+ def __call__(
581
+ self,
582
+ prompt: Union[str, List[str]],
583
+ num_images_per_prompt: int = 1,
584
+ guidance_scale: float = 6.0,
585
+ num_inference_steps: Optional[int] = None,
586
+ generator: Optional[torch.Generator] = None,
587
+ output_type: str = "pil",
588
+ return_dict: bool = True,
589
+ progress: bool = True,
590
+ ):
591
+ device = next(self.transformer.parameters()).device
592
+ if isinstance(prompt, str):
593
+ prompt_batch = [prompt] * num_images_per_prompt
594
+ else:
595
+ prompt_batch = []
596
+ for p in prompt:
597
+ prompt_batch.extend([p] * num_images_per_prompt)
598
+
599
+ old_steps = self.transformer.mmjit_config.n_T
600
+ self.transformer.model.cfg.n_T = int(num_inference_steps or self.scheduler.config.num_inference_steps)
601
+ try:
602
+ text, attn = self._encode_prompt(prompt_batch, device)
603
+ model_dtype = next(self.transformer.parameters()).dtype
604
+ images = self.transformer.sample(
605
+ text.to(dtype=model_dtype),
606
+ attn.to(dtype=model_dtype),
607
+ cfg_scale=guidance_scale,
608
+ generator=generator,
609
+ progress=progress,
610
+ )
611
+ finally:
612
+ self.transformer.model.cfg.n_T = old_steps
613
+
614
+ images = (images.clamp(-1, 1) * 127.5 + 128.0).clamp(0, 255).to(torch.uint8)
615
+ images = images.permute(0, 2, 3, 1).cpu().numpy()
616
+ if output_type == "pil":
617
+ images = [Image.fromarray(image) for image in images]
618
+ if not return_dict:
619
+ return (images,)
620
+ return ImagePipelineOutput(images=images)
621
+
622
+
623
+ class MiniT2IPipeline(DiffusionPipeline):
624
+ MODEL_ALIASES = {
625
+ "b": "minit2i-b-16",
626
+ "b16": "minit2i-b-16",
627
+ "b-16": "minit2i-b-16",
628
+ "base": "minit2i-b-16",
629
+ "minit2i-b16": "minit2i-b-16",
630
+ "minit2i-b-16": "minit2i-b-16",
631
+ "minit2i-b/16": "minit2i-b-16",
632
+ "l": "minit2i-l-16",
633
+ "l16": "minit2i-l-16",
634
+ "l-16": "minit2i-l-16",
635
+ "large": "minit2i-l-16",
636
+ "minit2i-l16": "minit2i-l-16",
637
+ "minit2i-l-16": "minit2i-l-16",
638
+ "minit2i-l/16": "minit2i-l-16",
639
+ }
640
+
641
+ def __init__(self):
642
+ super().__init__()
643
+
644
+ @classmethod
645
+ def _resolve_model_type(cls, model_type: str) -> str:
646
+ key = model_type.lower().replace("_", "-")
647
+ if key not in cls.MODEL_ALIASES:
648
+ choices = ", ".join(sorted(set(cls.MODEL_ALIASES)))
649
+ raise ValueError(f"Unknown model_type={model_type!r}. Expected one of: {choices}")
650
+ return cls.MODEL_ALIASES[key]
651
+
652
+ @staticmethod
653
+ def _resolve_root(
654
+ repo_id_or_path: Union[str, os.PathLike],
655
+ model_dir: str,
656
+ revision: Optional[str],
657
+ cache_dir: Optional[Union[str, os.PathLike]],
658
+ local_files_only: bool,
659
+ ) -> Path:
660
+ root = Path(repo_id_or_path)
661
+ if root.exists():
662
+ return root
663
+ return Path(
664
+ snapshot_download(
665
+ repo_id=str(repo_id_or_path),
666
+ revision=revision,
667
+ cache_dir=cache_dir,
668
+ local_files_only=local_files_only,
669
+ allow_patterns=[
670
+ f"{model_dir}/transformer/*",
671
+ f"{model_dir}/scheduler/*",
672
+ ],
673
+ )
674
+ )
675
+
676
+ @torch.no_grad()
677
+ def __call__(
678
+ self,
679
+ prompt: Union[str, List[str]],
680
+ model_type: str = "b16",
681
+ repo_id_or_path: Union[str, os.PathLike] = "dummy9996/MiniT2I_bf16",
682
+ torch_dtype: Optional[torch.dtype] = torch.bfloat16,
683
+ text_encoder_dtype: torch.dtype = torch.float32,
684
+ device: Optional[Union[str, torch.device]] = None,
685
+ local_files_only: bool = False,
686
+ revision: Optional[str] = None,
687
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
688
+ **kwargs,
689
+ ):
690
+ model_dir = self._resolve_model_type(model_type)
691
+ root = self._resolve_root(repo_id_or_path, model_dir, revision, cache_dir, local_files_only)
692
+ model_root = root / model_dir
693
+ transformer = MiniT2IMMJiTModel.from_pretrained(model_root / "transformer", torch_dtype=torch_dtype)
694
+ scheduler = MiniT2IFlowMatchScheduler.from_pretrained(model_root / "scheduler")
695
+ text_encoder_name = transformer.mmjit_config.llm
696
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_name, local_files_only=local_files_only)
697
+ text_encoder = T5EncoderModel.from_pretrained(
698
+ text_encoder_name,
699
+ torch_dtype=text_encoder_dtype,
700
+ local_files_only=local_files_only,
701
+ )
702
+ pipe = MiniT2ITextToImagePipeline(
703
+ transformer=transformer,
704
+ scheduler=scheduler,
705
+ tokenizer=tokenizer,
706
+ text_encoder=text_encoder,
707
+ text_encoder_name=text_encoder_name,
708
+ )
709
+ if device is None:
710
+ device = "cuda" if torch.cuda.is_available() else "cpu"
711
+ pipe.to(device)
712
+ return pipe(prompt=prompt, **kwargs)
713
+
714
+
715
+ def build_transformer_from_checkpoint(ckpt_path: Union[str, os.PathLike]) -> MiniT2IMMJiTModel:
716
+ payload = torch.load(ckpt_path, map_location="cpu")
717
+ cfg = MMJiTConfig(**payload["config"])
718
+ transformer = MiniT2IMMJiTModel(**asdict(cfg))
719
+ prefixed = payload["state_dict"]
720
+ state_dict = {}
721
+ for key, value in prefixed.items():
722
+ if key.startswith("net."):
723
+ state_dict[f"model.{key}"] = value
724
+ else:
725
+ state_dict[f"model.{key}"] = value
726
+ transformer.load_state_dict(state_dict, strict=True)
727
+ return transformer