BiliSakura commited on
Commit
3859610
·
verified ·
1 Parent(s): a9c9521

Delete jit_diffusers

Browse files
jit_diffusers/__init__.py DELETED
@@ -1,11 +0,0 @@
1
- from .modeling_jit_transformer_2d import JiTTransformer2DModel, JiTDiffusersModel
2
- from .pipeline_jit import JiTPipeline, JiTPipelineOutput
3
- from .scheduling_jit import JiTScheduler
4
-
5
- __all__ = [
6
- "JiTTransformer2DModel",
7
- "JiTDiffusersModel",
8
- "JiTPipeline",
9
- "JiTPipelineOutput",
10
- "JiTScheduler",
11
- ]
 
 
 
 
 
 
 
 
 
 
 
 
jit_diffusers/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (448 Bytes)
 
jit_diffusers/__pycache__/modeling_jit_backbone.cpython-312.pyc DELETED
Binary file (22.9 kB)
 
jit_diffusers/__pycache__/modeling_jit_transformer_2d.cpython-312.pyc DELETED
Binary file (9.74 kB)
 
jit_diffusers/__pycache__/modeling_jit_utils.cpython-312.pyc DELETED
Binary file (10 kB)
 
jit_diffusers/__pycache__/pipeline_jit.cpython-312.pyc DELETED
Binary file (9.6 kB)
 
jit_diffusers/__pycache__/scheduling_jit.cpython-312.pyc DELETED
Binary file (3.33 kB)
 
jit_diffusers/modeling_jit_backbone.py DELETED
@@ -1,321 +0,0 @@
1
- import math
2
-
3
- import torch
4
- import torch.nn as nn
5
- import torch.nn.functional as F
6
-
7
- from .modeling_jit_utils import VisionRotaryEmbeddingFast, get_2d_sincos_pos_embed, RMSNorm
8
-
9
-
10
- def modulate(x, shift, scale):
11
- return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
12
-
13
-
14
- class BottleneckPatchEmbed(nn.Module):
15
- def __init__(self, img_size=224, patch_size=16, in_chans=3, pca_dim=768, embed_dim=768, bias=True):
16
- super().__init__()
17
- img_size = (img_size, img_size)
18
- patch_size = (patch_size, patch_size)
19
- num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
20
- self.img_size = img_size
21
- self.patch_size = patch_size
22
- self.num_patches = num_patches
23
-
24
- self.proj1 = nn.Conv2d(in_chans, pca_dim, kernel_size=patch_size, stride=patch_size, bias=False)
25
- self.proj2 = nn.Conv2d(pca_dim, embed_dim, kernel_size=1, stride=1, bias=bias)
26
-
27
- def forward(self, x):
28
- _, _, height, width = x.shape
29
- assert height == self.img_size[0] and width == self.img_size[1], (
30
- f"Input image size ({height}*{width}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
31
- )
32
- x = self.proj2(self.proj1(x)).flatten(2).transpose(1, 2)
33
- return x
34
-
35
-
36
- class TimestepEmbedder(nn.Module):
37
- def __init__(self, hidden_size, frequency_embedding_size=256):
38
- super().__init__()
39
- self.mlp = nn.Sequential(
40
- nn.Linear(frequency_embedding_size, hidden_size, bias=True),
41
- nn.SiLU(),
42
- nn.Linear(hidden_size, hidden_size, bias=True),
43
- )
44
- self.frequency_embedding_size = frequency_embedding_size
45
-
46
- @staticmethod
47
- def timestep_embedding(t, dim, max_period=10000):
48
- half = dim // 2
49
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
50
- device=t.device
51
- )
52
- args = t[:, None].float() * freqs[None]
53
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
54
- if dim % 2:
55
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
56
- return embedding
57
-
58
- def forward(self, t):
59
- t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
60
- t_freq = t_freq.to(dtype=self.mlp[0].weight.dtype)
61
- t_emb = self.mlp(t_freq)
62
- return t_emb
63
-
64
-
65
- class LabelEmbedder(nn.Module):
66
- def __init__(self, num_classes, hidden_size):
67
- super().__init__()
68
- self.embedding_table = nn.Embedding(num_classes + 1, hidden_size)
69
- self.num_classes = num_classes
70
-
71
- def forward(self, labels):
72
- embeddings = self.embedding_table(labels)
73
- return embeddings
74
-
75
-
76
- def scaled_dot_product_attention(query, key, value, dropout_p=0.0) -> torch.Tensor:
77
- query_len, key_len = query.size(-2), key.size(-2)
78
- scale_factor = 1 / math.sqrt(query.size(-1))
79
- attn_bias = torch.zeros(query.size(0), 1, query_len, key_len, dtype=query.dtype, device=query.device)
80
-
81
- with torch.amp.autocast("cuda", enabled=False):
82
- attn_weight = query.float() @ key.float().transpose(-2, -1) * scale_factor
83
- attn_weight += attn_bias
84
- attn_weight = torch.softmax(attn_weight, dim=-1)
85
- attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
86
- out = attn_weight @ value.float()
87
- return out.to(query.dtype)
88
-
89
-
90
- class Attention(nn.Module):
91
- def __init__(self, dim, num_heads=8, qkv_bias=True, qk_norm=True, attn_drop=0.0, proj_drop=0.0):
92
- super().__init__()
93
- self.num_heads = num_heads
94
- head_dim = dim // num_heads
95
-
96
- self.q_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()
97
- self.k_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()
98
-
99
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
100
- self.attn_drop = nn.Dropout(attn_drop)
101
- self.proj = nn.Linear(dim, dim)
102
- self.proj_drop = nn.Dropout(proj_drop)
103
-
104
- def forward(self, x, rope):
105
- batch_size, num_tokens, channels = x.shape
106
- qkv = self.qkv(x).reshape(batch_size, num_tokens, 3, self.num_heads, channels // self.num_heads).permute(2, 0, 3, 1, 4)
107
- q, k, v = qkv[0], qkv[1], qkv[2]
108
-
109
- q = self.q_norm(q)
110
- k = self.k_norm(k)
111
- q = rope(q)
112
- k = rope(k)
113
-
114
- x = scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0)
115
- x = x.transpose(1, 2).reshape(batch_size, num_tokens, channels)
116
- x = x.to(self.proj.weight.dtype)
117
- x = self.proj(x)
118
- x = self.proj_drop(x)
119
- return x
120
-
121
-
122
- class SwiGLUFFN(nn.Module):
123
- def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
124
- super().__init__()
125
- hidden_dim = int(hidden_dim * 2 / 3)
126
- self.w12 = nn.Linear(dim, 2 * hidden_dim, bias=bias)
127
- self.w3 = nn.Linear(hidden_dim, dim, bias=bias)
128
- self.ffn_dropout = nn.Dropout(drop)
129
-
130
- def forward(self, x):
131
- x12 = self.w12(x)
132
- x1, x2 = x12.chunk(2, dim=-1)
133
- hidden = F.silu(x1) * x2
134
- return self.w3(self.ffn_dropout(hidden))
135
-
136
-
137
- class FinalLayer(nn.Module):
138
- def __init__(self, hidden_size, patch_size, out_channels):
139
- super().__init__()
140
- self.norm_final = RMSNorm(hidden_size)
141
- self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
142
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
143
-
144
- def forward(self, x, c):
145
- shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
146
- x = modulate(self.norm_final(x), shift, scale)
147
- x = self.linear(x)
148
- return x
149
-
150
-
151
- class JiTBlock(nn.Module):
152
- def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0):
153
- super().__init__()
154
- self.norm1 = RMSNorm(hidden_size, eps=1e-6)
155
- self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=True, attn_drop=attn_drop, proj_drop=proj_drop)
156
- self.norm2 = RMSNorm(hidden_size, eps=1e-6)
157
- mlp_hidden_dim = int(hidden_size * mlp_ratio)
158
- self.mlp = SwiGLUFFN(hidden_size, mlp_hidden_dim, drop=proj_drop)
159
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
160
-
161
- def forward(self, x, c, feat_rope=None):
162
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1)
163
- x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
164
- x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
165
- return x
166
-
167
-
168
- class JiT(nn.Module):
169
- def __init__(
170
- self,
171
- input_size=256,
172
- patch_size=16,
173
- in_channels=3,
174
- hidden_size=1024,
175
- depth=24,
176
- num_heads=16,
177
- mlp_ratio=4.0,
178
- attn_drop=0.0,
179
- proj_drop=0.0,
180
- num_classes=1000,
181
- bottleneck_dim=128,
182
- in_context_len=32,
183
- in_context_start=8,
184
- ):
185
- super().__init__()
186
- self.in_channels = in_channels
187
- self.out_channels = in_channels
188
- self.patch_size = patch_size
189
- self.num_heads = num_heads
190
- self.hidden_size = hidden_size
191
- self.input_size = input_size
192
- self.in_context_len = in_context_len
193
- self.in_context_start = in_context_start
194
- self.num_classes = num_classes
195
-
196
- self.t_embedder = TimestepEmbedder(hidden_size)
197
- self.y_embedder = LabelEmbedder(num_classes, hidden_size)
198
- self.x_embedder = BottleneckPatchEmbed(input_size, patch_size, in_channels, bottleneck_dim, hidden_size, bias=True)
199
-
200
- num_patches = self.x_embedder.num_patches
201
- self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
202
-
203
- if self.in_context_len > 0:
204
- self.in_context_posemb = nn.Parameter(torch.zeros(1, self.in_context_len, hidden_size), requires_grad=True)
205
- torch.nn.init.normal_(self.in_context_posemb, std=0.02)
206
-
207
- half_head_dim = hidden_size // num_heads // 2
208
- hw_seq_len = input_size // patch_size
209
- self.feat_rope = VisionRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len, num_cls_token=0)
210
- self.feat_rope_incontext = VisionRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len, num_cls_token=self.in_context_len)
211
-
212
- self.blocks = nn.ModuleList(
213
- [
214
- JiTBlock(
215
- hidden_size,
216
- num_heads,
217
- mlp_ratio=mlp_ratio,
218
- attn_drop=attn_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,
219
- proj_drop=proj_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,
220
- )
221
- for i in range(depth)
222
- ]
223
- )
224
-
225
- self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)
226
- self.initialize_weights()
227
-
228
- def initialize_weights(self):
229
- def _basic_init(module):
230
- if isinstance(module, nn.Linear):
231
- torch.nn.init.xavier_uniform_(module.weight)
232
- if module.bias is not None:
233
- nn.init.constant_(module.bias, 0)
234
-
235
- self.apply(_basic_init)
236
-
237
- pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5))
238
- self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
239
-
240
- w1 = self.x_embedder.proj1.weight.data
241
- nn.init.xavier_uniform_(w1.view([w1.shape[0], -1]))
242
- w2 = self.x_embedder.proj2.weight.data
243
- nn.init.xavier_uniform_(w2.view([w2.shape[0], -1]))
244
- nn.init.constant_(self.x_embedder.proj2.bias, 0)
245
-
246
- nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
247
- nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
248
- nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
249
-
250
- for block in self.blocks:
251
- nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
252
- nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
253
-
254
- nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
255
- nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
256
- nn.init.constant_(self.final_layer.linear.weight, 0)
257
- nn.init.constant_(self.final_layer.linear.bias, 0)
258
-
259
- def unpatchify(self, x, patch_size):
260
- channels = self.out_channels
261
- height = width = int(x.shape[1] ** 0.5)
262
- assert height * width == x.shape[1]
263
-
264
- x = x.reshape(shape=(x.shape[0], height, width, patch_size, patch_size, channels))
265
- x = torch.einsum("nhwpqc->nchpwq", x)
266
- images = x.reshape(shape=(x.shape[0], channels, height * patch_size, height * patch_size))
267
- return images
268
-
269
- def forward(self, x, t, y):
270
- t_emb = self.t_embedder(t)
271
- y_emb = self.y_embedder(y)
272
- c = t_emb + y_emb
273
-
274
- x = self.x_embedder(x)
275
- x += self.pos_embed
276
-
277
- for i, block in enumerate(self.blocks):
278
- if self.in_context_len > 0 and i == self.in_context_start:
279
- in_context_tokens = y_emb.unsqueeze(1).repeat(1, self.in_context_len, 1)
280
- in_context_tokens += self.in_context_posemb
281
- x = torch.cat([in_context_tokens, x], dim=1)
282
- x = block(x, c, self.feat_rope if i < self.in_context_start else self.feat_rope_incontext)
283
-
284
- x = x[:, self.in_context_len :]
285
- x = self.final_layer(x, c)
286
- output = self.unpatchify(x, self.patch_size)
287
- return output
288
-
289
-
290
- def JiT_B_16(**kwargs):
291
- return JiT(depth=12, hidden_size=768, num_heads=12, bottleneck_dim=128, in_context_len=32, in_context_start=4, patch_size=16, **kwargs)
292
-
293
-
294
- def JiT_B_32(**kwargs):
295
- return JiT(depth=12, hidden_size=768, num_heads=12, bottleneck_dim=128, in_context_len=32, in_context_start=4, patch_size=32, **kwargs)
296
-
297
-
298
- def JiT_L_16(**kwargs):
299
- return JiT(depth=24, hidden_size=1024, num_heads=16, bottleneck_dim=128, in_context_len=32, in_context_start=8, patch_size=16, **kwargs)
300
-
301
-
302
- def JiT_L_32(**kwargs):
303
- return JiT(depth=24, hidden_size=1024, num_heads=16, bottleneck_dim=128, in_context_len=32, in_context_start=8, patch_size=32, **kwargs)
304
-
305
-
306
- def JiT_H_16(**kwargs):
307
- return JiT(depth=32, hidden_size=1280, num_heads=16, bottleneck_dim=256, in_context_len=32, in_context_start=10, patch_size=16, **kwargs)
308
-
309
-
310
- def JiT_H_32(**kwargs):
311
- return JiT(depth=32, hidden_size=1280, num_heads=16, bottleneck_dim=256, in_context_len=32, in_context_start=10, patch_size=32, **kwargs)
312
-
313
-
314
- JiT_models = {
315
- "JiT-B/16": JiT_B_16,
316
- "JiT-B/32": JiT_B_32,
317
- "JiT-L/16": JiT_L_16,
318
- "JiT-L/32": JiT_L_32,
319
- "JiT-H/16": JiT_H_16,
320
- "JiT-H/32": JiT_H_32,
321
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
jit_diffusers/modeling_jit_transformer_2d.py DELETED
@@ -1,200 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import argparse
4
- from collections.abc import Mapping
5
- from dataclasses import dataclass
6
- from typing import Any, Dict, Literal, Tuple
7
-
8
- import torch
9
- from diffusers import ConfigMixin, ModelMixin
10
- from diffusers.configuration_utils import register_to_config
11
- from diffusers.models.modeling_outputs import Transformer2DModelOutput
12
-
13
- from .modeling_jit_backbone import JiT_models
14
-
15
-
16
- def _extract_module_state_dict(
17
- state_dict: Dict[str, torch.Tensor], prefixes: Tuple[str, ...] = ("transformer.", "net.")
18
- ) -> Dict[str, torch.Tensor]:
19
- """Extract module state by stripping the first fully-matching prefix.
20
-
21
- Prefix precedence is left-to-right; `"transformer."` is preferred over legacy `"net."`.
22
- """
23
- for prefix in prefixes:
24
- if all(key.startswith(prefix) for key in state_dict.keys()):
25
- return {k[len(prefix):]: v for k, v in state_dict.items()}
26
- return state_dict
27
-
28
-
29
- def _build_jit_kwargs(
30
- image_size: int,
31
- num_classes: int,
32
- attn_dropout: float,
33
- proj_dropout: float,
34
- model_name: str | None = None,
35
- ) -> Dict[str, object]:
36
- # Keep model_name for backward-compatible internal call signatures.
37
- _ = model_name
38
- return {
39
- "input_size": image_size,
40
- "in_channels": 3,
41
- "num_classes": num_classes,
42
- "attn_drop": attn_dropout,
43
- "proj_drop": proj_dropout,
44
- }
45
-
46
-
47
- @dataclass
48
- class JiTCheckpointConfig:
49
- model_name: str
50
- image_size: int
51
- num_classes: int
52
- attn_dropout: float
53
- proj_dropout: float
54
-
55
-
56
- def _config_from_checkpoint(ckpt_args: argparse.Namespace | Mapping[str, Any]) -> JiTCheckpointConfig:
57
- if isinstance(ckpt_args, argparse.Namespace):
58
- args_dict = vars(ckpt_args)
59
- elif isinstance(ckpt_args, Mapping):
60
- args_dict = ckpt_args
61
- else:
62
- raise TypeError(f"Unsupported checkpoint args type: {type(ckpt_args)}")
63
-
64
- def _get_first_available(*keys: str, default=None):
65
- for key in keys:
66
- if key in args_dict and args_dict[key] is not None:
67
- return args_dict[key]
68
- return default
69
-
70
- model_name = _get_first_available("model", "model_name", "model_type")
71
- image_size = _get_first_available("img_size", "image_size", "sample_size")
72
- num_classes = _get_first_available("class_num", "num_classes", "num_class_embeds")
73
- if model_name is None or image_size is None or num_classes is None:
74
- raise ValueError("Checkpoint args are missing model/image_size/num_classes information.")
75
-
76
- return JiTCheckpointConfig(
77
- model_name=str(model_name),
78
- image_size=int(image_size),
79
- num_classes=int(num_classes),
80
- attn_dropout=float(_get_first_available("attn_dropout", "attention_dropout", default=0.0)),
81
- proj_dropout=float(_get_first_available("proj_dropout", "dropout", default=0.0)),
82
- )
83
-
84
-
85
- class JiTTransformer2DModel(ModelMixin, ConfigMixin):
86
- @register_to_config
87
- def __init__(
88
- self,
89
- model_type: str = "JiT-B/16",
90
- sample_size: int = 256,
91
- num_class_embeds: int = 1000,
92
- attention_dropout: float = 0.0,
93
- dropout: float = 0.0,
94
- model_name: str | None = None,
95
- image_size: int | None = None,
96
- num_classes: int | None = None,
97
- attn_dropout: float | None = None,
98
- proj_dropout: float | None = None,
99
- ):
100
- super().__init__()
101
- resolved_model_type = model_type if model_name is None else model_name
102
- resolved_sample_size = sample_size if image_size is None else image_size
103
- resolved_num_class_embeds = num_class_embeds if num_classes is None else num_classes
104
- resolved_attention_dropout = attention_dropout if attn_dropout is None else attn_dropout
105
- resolved_dropout = dropout if proj_dropout is None else proj_dropout
106
-
107
- if resolved_model_type not in JiT_models:
108
- raise ValueError(f"Unknown model '{resolved_model_type}'. Available: {list(JiT_models.keys())}")
109
-
110
- self.transformer = JiT_models[resolved_model_type](
111
- **_build_jit_kwargs(
112
- image_size=resolved_sample_size,
113
- num_classes=resolved_num_class_embeds,
114
- attn_dropout=resolved_attention_dropout,
115
- proj_dropout=resolved_dropout,
116
- model_name=resolved_model_type,
117
- )
118
- )
119
-
120
- def forward(
121
- self,
122
- sample: torch.Tensor,
123
- timestep: torch.Tensor,
124
- class_labels: torch.Tensor,
125
- return_dict: bool = True,
126
- ):
127
- timestep = torch.as_tensor(timestep, device=sample.device)
128
- if timestep.ndim == 0:
129
- timestep = timestep.repeat(sample.shape[0])
130
- else:
131
- timestep = timestep.reshape(-1)
132
- if timestep.shape[0] == 1 and sample.shape[0] > 1:
133
- timestep = timestep.repeat(sample.shape[0])
134
-
135
- denoised = self.transformer(sample, timestep, class_labels)
136
- if not return_dict:
137
- return (denoised,)
138
- return Transformer2DModelOutput(sample=denoised)
139
-
140
- @classmethod
141
- def from_jit_checkpoint(
142
- cls,
143
- checkpoint_path: str,
144
- weights: Literal["model", "ema1", "ema2"] = "ema1",
145
- map_location: str = "cpu",
146
- strict: bool = True,
147
- ) -> Tuple["JiTTransformer2DModel", Dict[str, object]]:
148
- checkpoint = torch.load(checkpoint_path, map_location=map_location)
149
- if "args" not in checkpoint:
150
- raise ValueError("Checkpoint is missing 'args', cannot infer JiT architecture config.")
151
-
152
- config = _config_from_checkpoint(checkpoint["args"])
153
- model = cls(
154
- model_type=config.model_name,
155
- sample_size=config.image_size,
156
- num_class_embeds=config.num_classes,
157
- attention_dropout=config.attn_dropout,
158
- dropout=config.proj_dropout,
159
- )
160
-
161
- key = "model" if weights == "model" else f"model_{weights}"
162
- if key not in checkpoint:
163
- raise ValueError(f"Checkpoint key '{key}' not found. Available keys: {list(checkpoint.keys())}")
164
-
165
- model_state = _extract_module_state_dict(checkpoint[key])
166
- model.transformer.load_state_dict(model_state, strict=strict)
167
-
168
- metadata = {
169
- "checkpoint_path": checkpoint_path,
170
- "weights": weights,
171
- "epoch": checkpoint.get("epoch"),
172
- "source_args": checkpoint.get("args"),
173
- }
174
- return model, metadata
175
-
176
- def to_jit_checkpoint(
177
- self,
178
- ema_mode: Literal["none", "copy_to_both"] = "copy_to_both",
179
- prefix: str = "net.",
180
- ) -> Dict[str, object]:
181
- base_state = {f"{prefix}{k}": v.detach().cpu() for k, v in self.transformer.state_dict().items()}
182
- checkpoint = {"model": base_state}
183
- if ema_mode == "copy_to_both":
184
- checkpoint["model_ema1"] = {k: v.clone() for k, v in base_state.items()}
185
- checkpoint["model_ema2"] = {k: v.clone() for k, v in base_state.items()}
186
- elif ema_mode != "none":
187
- raise ValueError(f"Unsupported ema_mode='{ema_mode}'.")
188
- return checkpoint
189
-
190
- @property
191
- def net(self):
192
- return self.transformer
193
-
194
- @net.setter
195
- def net(self, module):
196
- self.transformer = module
197
-
198
-
199
- # Backward-compatible alias.
200
- JiTDiffusersModel = JiTTransformer2DModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
jit_diffusers/modeling_jit_utils.py DELETED
@@ -1,129 +0,0 @@
1
- from math import pi
2
-
3
- import numpy as np
4
- import torch
5
- from einops import rearrange, repeat
6
- from torch import nn
7
-
8
-
9
- def broadcat(tensors, dim=-1):
10
- num_tensors = len(tensors)
11
- shape_lens = set(list(map(lambda tensor: len(tensor.shape), tensors)))
12
- assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
13
- shape_len = list(shape_lens)[0]
14
- dim = (dim + shape_len) if dim < 0 else dim
15
- dims = list(zip(*map(lambda tensor: list(tensor.shape), tensors)))
16
- expandable_dims = [(index, val) for index, val in enumerate(dims) if index != dim]
17
- assert all([*map(lambda tensor: len(set(tensor[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatenation"
18
- max_dims = list(map(lambda tensor: (tensor[0], max(tensor[1])), expandable_dims))
19
- expanded_dims = list(map(lambda tensor: (tensor[0], (tensor[1],) * num_tensors), max_dims))
20
- expanded_dims.insert(dim, (dim, dims[dim]))
21
- expandable_shapes = list(zip(*map(lambda tensor: tensor[1], expanded_dims)))
22
- tensors = list(map(lambda tensor: tensor[0].expand(*tensor[1]), zip(tensors, expandable_shapes)))
23
- return torch.cat(tensors, dim=dim)
24
-
25
-
26
- def rotate_half(x):
27
- x = rearrange(x, "... (d r) -> ... d r", r=2)
28
- x1, x2 = x.unbind(dim=-1)
29
- x = torch.stack((-x2, x1), dim=-1)
30
- return rearrange(x, "... d r -> ... (d r)")
31
-
32
-
33
- class VisionRotaryEmbeddingFast(nn.Module):
34
- def __init__(
35
- self,
36
- dim,
37
- pt_seq_len=16,
38
- ft_seq_len=None,
39
- custom_freqs=None,
40
- freqs_for="lang",
41
- theta=10000,
42
- max_freq=10,
43
- num_freqs=1,
44
- num_cls_token=0,
45
- ):
46
- super().__init__()
47
- if custom_freqs:
48
- freqs = custom_freqs
49
- elif freqs_for == "lang":
50
- freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
51
- elif freqs_for == "pixel":
52
- freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
53
- elif freqs_for == "constant":
54
- freqs = torch.ones(num_freqs).float()
55
- else:
56
- raise ValueError(f"unknown modality {freqs_for}")
57
-
58
- if ft_seq_len is None:
59
- ft_seq_len = pt_seq_len
60
- t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
61
-
62
- freqs = torch.einsum("..., f -> ... f", t, freqs)
63
- freqs = repeat(freqs, "... n -> ... (n r)", r=2)
64
- freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
65
-
66
- if num_cls_token > 0:
67
- freqs_flat = freqs.view(-1, freqs.shape[-1])
68
- cos_img = freqs_flat.cos()
69
- sin_img = freqs_flat.sin()
70
- _, dim_freq = cos_img.shape
71
- cos_pad = torch.ones(num_cls_token, dim_freq, dtype=cos_img.dtype, device=cos_img.device)
72
- sin_pad = torch.zeros(num_cls_token, dim_freq, dtype=sin_img.dtype, device=sin_img.device)
73
- self.register_buffer("freqs_cos", torch.cat([cos_pad, cos_img], dim=0), persistent=False)
74
- self.register_buffer("freqs_sin", torch.cat([sin_pad, sin_img], dim=0), persistent=False)
75
- else:
76
- self.register_buffer("freqs_cos", freqs.cos().view(-1, freqs.shape[-1]), persistent=False)
77
- self.register_buffer("freqs_sin", freqs.sin().view(-1, freqs.shape[-1]), persistent=False)
78
-
79
- def forward(self, tensor):
80
- freqs_cos = self.freqs_cos.to(device=tensor.device, dtype=tensor.dtype)
81
- freqs_sin = self.freqs_sin.to(device=tensor.device, dtype=tensor.dtype)
82
- return tensor * freqs_cos + rotate_half(tensor) * freqs_sin
83
-
84
-
85
- class RMSNorm(nn.Module):
86
- def __init__(self, hidden_size, eps=1e-6):
87
- super().__init__()
88
- self.weight = nn.Parameter(torch.ones(hidden_size))
89
- self.variance_epsilon = eps
90
-
91
- def forward(self, hidden_states):
92
- input_dtype = hidden_states.dtype
93
- hidden_states = hidden_states.to(torch.float32)
94
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
95
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
96
- return (self.weight * hidden_states).to(input_dtype)
97
-
98
-
99
- def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
100
- grid_h = np.arange(grid_size, dtype=np.float32)
101
- grid_w = np.arange(grid_size, dtype=np.float32)
102
- grid = np.meshgrid(grid_w, grid_h)
103
- grid = np.stack(grid, axis=0)
104
- grid = grid.reshape([2, 1, grid_size, grid_size])
105
- pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
106
- if cls_token and extra_tokens > 0:
107
- pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
108
- return pos_embed
109
-
110
-
111
- def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
112
- assert embed_dim % 2 == 0
113
- emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])
114
- emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])
115
- emb = np.concatenate([emb_h, emb_w], axis=1)
116
- return emb
117
-
118
-
119
- def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
120
- assert embed_dim % 2 == 0
121
- omega = np.arange(embed_dim // 2, dtype=np.float64)
122
- omega /= embed_dim / 2.0
123
- omega = 1.0 / 10000**omega
124
- pos = pos.reshape(-1)
125
- out = np.einsum("m,d->md", pos, omega)
126
- emb_sin = np.sin(out)
127
- emb_cos = np.cos(out)
128
- emb = np.concatenate([emb_sin, emb_cos], axis=1)
129
- return emb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
jit_diffusers/pipeline_jit.py DELETED
@@ -1,179 +0,0 @@
1
- from dataclasses import dataclass
2
- from pathlib import Path
3
- from typing import List, Tuple
4
-
5
- import numpy as np
6
- import torch
7
- from diffusers import DiffusionPipeline
8
- from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
9
- from diffusers.utils import BaseOutput
10
- from diffusers.utils.torch_utils import randn_tensor
11
-
12
- from .modeling_jit_transformer_2d import JiTTransformer2DModel
13
- from .scheduling_jit import JiTScheduler
14
-
15
-
16
- RECOMMENDED_CFG_BY_MODEL = {
17
- "JiT-B/16": 3.0,
18
- "JiT-L/16": 2.4,
19
- "JiT-H/16": 2.2,
20
- "JiT-B/32": 3.0,
21
- "JiT-L/32": 2.5,
22
- "JiT-H/32": 2.3,
23
- }
24
-
25
- RECOMMENDED_NOISE_BY_RESOLUTION = {
26
- 256: 1.0,
27
- 512: 2.0,
28
- }
29
-
30
-
31
- @dataclass
32
- class JiTPipelineOutput(BaseOutput):
33
- images: List["PIL.Image.Image"] | np.ndarray | torch.Tensor
34
-
35
-
36
- class JiTPipeline(DiffusionPipeline):
37
- model_cpu_offload_seq = "transformer"
38
-
39
- def __init__(self, transformer: JiTTransformer2DModel, scheduler: JiTScheduler | None = None):
40
- super().__init__()
41
- self.register_modules(transformer=transformer, scheduler=scheduler or JiTScheduler())
42
-
43
- @classmethod
44
- def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
45
- model_kwargs = dict(kwargs)
46
- transformer_subfolder = model_kwargs.pop("transformer_subfolder", None)
47
- scheduler_subfolder = model_kwargs.pop("scheduler_subfolder", None)
48
- scheduler_kwargs = model_kwargs.pop("scheduler_kwargs", {})
49
- if transformer_subfolder is not None:
50
- transformer_path = str(Path(pretrained_model_name_or_path) / transformer_subfolder)
51
- else:
52
- transformer_path = pretrained_model_name_or_path
53
- transformer = JiTTransformer2DModel.from_pretrained(transformer_path, **model_kwargs)
54
- try:
55
- scheduler = JiTScheduler.from_pretrained(
56
- pretrained_model_name_or_path,
57
- subfolder=scheduler_subfolder,
58
- **scheduler_kwargs,
59
- )
60
- except Exception:
61
- scheduler = JiTScheduler(**scheduler_kwargs)
62
- return cls(transformer=transformer, scheduler=scheduler)
63
-
64
- @torch.no_grad()
65
- def __call__(
66
- self,
67
- class_labels: int | List[int] | torch.Tensor,
68
- num_inference_steps: int = 50,
69
- guidance_scale: float | None = None,
70
- guidance_interval_min: float = 0.1,
71
- guidance_interval_max: float = 1.0,
72
- noise_scale: float | None = None,
73
- t_eps: float = 5e-2,
74
- sampling_method: str | None = None,
75
- generator: torch.Generator | List[torch.Generator] | None = None,
76
- output_type: str = "pil",
77
- return_dict: bool = True,
78
- ) -> JiTPipelineOutput | ImagePipelineOutput | Tuple:
79
- if output_type not in {"pil", "np", "pt"}:
80
- raise ValueError("output_type must be one of: 'pil', 'np', 'pt'.")
81
- if sampling_method is not None and sampling_method not in {"heun", "euler"}:
82
- raise ValueError("sampling_method must be one of: 'heun', 'euler'.")
83
- if num_inference_steps < 2:
84
- raise ValueError("num_inference_steps must be >= 2.")
85
- if sampling_method is not None and sampling_method != self.scheduler.config.solver:
86
- self.scheduler = JiTScheduler.from_config(self.scheduler.config, solver=sampling_method)
87
-
88
- if isinstance(class_labels, int):
89
- class_labels = [class_labels]
90
- if isinstance(class_labels, list):
91
- class_labels = torch.tensor(class_labels, device=self._execution_device, dtype=torch.long)
92
- else:
93
- class_labels = class_labels.to(self._execution_device, dtype=torch.long).reshape(-1)
94
-
95
- batch_size = class_labels.shape[0]
96
- latent_size = int(self.transformer.config.sample_size)
97
- latent_channels = int(getattr(self.transformer.config, "in_channels", 3))
98
- num_classes = int(self.transformer.config.num_class_embeds)
99
- model_type = str(getattr(self.transformer.config, "model_type", ""))
100
-
101
- if guidance_scale is None:
102
- guidance_scale = RECOMMENDED_CFG_BY_MODEL.get(model_type, 2.9)
103
- if noise_scale is None:
104
- noise_scale = RECOMMENDED_NOISE_BY_RESOLUTION.get(latent_size, 1.0)
105
-
106
- class_labels = class_labels.clamp(0, num_classes - 1)
107
- class_null = torch.full_like(class_labels, num_classes)
108
-
109
- latents = randn_tensor(
110
- shape=(batch_size, latent_channels, latent_size, latent_size),
111
- generator=generator,
112
- device=self._execution_device,
113
- dtype=self.transformer.dtype,
114
- ) * noise_scale
115
- self.scheduler.set_timesteps(num_inference_steps=num_inference_steps, device=self._execution_device)
116
- timesteps = self.scheduler.timesteps.to(device=self._execution_device, dtype=latents.dtype)
117
-
118
- def forward_cfg(z_value: torch.Tensor, t: torch.Tensor | float) -> torch.Tensor:
119
- t = torch.as_tensor(t, device=self._execution_device, dtype=latents.dtype)
120
- x_cond = self.transformer(sample=z_value, timestep=t.flatten(), class_labels=class_labels).sample
121
- v_cond = (x_cond - z_value) / (1.0 - t).clamp_min(t_eps)
122
-
123
- x_uncond = self.transformer(sample=z_value, timestep=t.flatten(), class_labels=class_null).sample
124
- v_uncond = (x_uncond - z_value) / (1.0 - t).clamp_min(t_eps)
125
-
126
- interval_mask = t < guidance_interval_max
127
- if guidance_interval_min != 0.0:
128
- interval_mask = interval_mask & (t > guidance_interval_min)
129
- scale = torch.where(
130
- interval_mask,
131
- torch.tensor(guidance_scale, device=self._execution_device, dtype=latents.dtype),
132
- torch.tensor(1.0, device=self._execution_device, dtype=latents.dtype),
133
- )
134
- return v_uncond + scale * (v_cond - v_uncond)
135
-
136
- for i in self.progress_bar(range(num_inference_steps - 1)):
137
- t, t_next = timesteps[i], timesteps[i + 1]
138
- model_output = forward_cfg(latents, t)
139
- if self.scheduler.config.solver == "heun":
140
- latents = self.scheduler.step(
141
- model_output=model_output,
142
- timestep=t,
143
- next_timestep=t_next,
144
- sample=latents,
145
- model_fn=forward_cfg,
146
- ).prev_sample
147
- else:
148
- latents = self.scheduler.step(
149
- model_output=model_output,
150
- timestep=t,
151
- next_timestep=t_next,
152
- sample=latents,
153
- ).prev_sample
154
-
155
- # Match the original JiT implementation: always use Euler for the final step.
156
- t, t_next = timesteps[-2], timesteps[-1]
157
- model_output = forward_cfg(latents, t)
158
- latents = self.scheduler.euler_step(
159
- model_output=model_output,
160
- timestep=t,
161
- next_timestep=t_next,
162
- sample=latents,
163
- ).prev_sample
164
-
165
- images_pt = ((latents.float().clamp(-1, 1) + 1.0) / 2.0).cpu()
166
- if output_type == "pt":
167
- images = images_pt
168
- else:
169
- images_np = images_pt.permute(0, 2, 3, 1).numpy()
170
- if output_type == "np":
171
- images = images_np
172
- else:
173
- images = self.numpy_to_pil(images_np)
174
-
175
- self.maybe_free_model_hooks()
176
-
177
- if not return_dict:
178
- return (images,)
179
- return JiTPipelineOutput(images=images)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
jit_diffusers/scheduling_jit.py DELETED
@@ -1,71 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Callable
4
-
5
- import torch
6
- from diffusers.configuration_utils import ConfigMixin, register_to_config
7
- from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
8
-
9
-
10
- class JiTScheduler(SchedulerMixin, ConfigMixin):
11
- order = 1
12
-
13
- @register_to_config
14
- def __init__(
15
- self,
16
- solver: str = "heun",
17
- timestep_start: float = 0.0,
18
- timestep_end: float = 1.0,
19
- ):
20
- if solver not in {"heun", "euler"}:
21
- raise ValueError("solver must be one of: 'heun', 'euler'.")
22
- if timestep_end <= timestep_start:
23
- raise ValueError("timestep_end must be greater than timestep_start.")
24
- self.timesteps = torch.tensor([])
25
-
26
- def set_timesteps(self, num_inference_steps: int, device: str | torch.device | None = None):
27
- if num_inference_steps < 2:
28
- raise ValueError("num_inference_steps must be >= 2.")
29
- self.timesteps = torch.linspace(
30
- self.config.timestep_start,
31
- self.config.timestep_end,
32
- num_inference_steps + 1,
33
- device=device,
34
- dtype=torch.float32,
35
- )
36
-
37
- def euler_step(
38
- self,
39
- model_output: torch.Tensor,
40
- timestep: torch.Tensor,
41
- next_timestep: torch.Tensor,
42
- sample: torch.Tensor,
43
- return_dict: bool = True,
44
- ) -> SchedulerOutput | tuple[torch.Tensor]:
45
- prev_sample = sample + (next_timestep - timestep) * model_output
46
- if not return_dict:
47
- return (prev_sample,)
48
- return SchedulerOutput(prev_sample=prev_sample)
49
-
50
- def step(
51
- self,
52
- model_output: torch.Tensor,
53
- timestep: torch.Tensor,
54
- next_timestep: torch.Tensor,
55
- sample: torch.Tensor,
56
- model_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
57
- return_dict: bool = True,
58
- ) -> SchedulerOutput | tuple[torch.Tensor]:
59
- if self.config.solver == "euler":
60
- return self.euler_step(model_output, timestep, next_timestep, sample, return_dict=return_dict)
61
-
62
- if model_fn is None:
63
- raise ValueError("model_fn is required when solver='heun'.")
64
-
65
- sample_euler = sample + (next_timestep - timestep) * model_output
66
- model_output_next = model_fn(sample_euler, next_timestep)
67
- prev_sample = sample + (next_timestep - timestep) * 0.5 * (model_output + model_output_next)
68
-
69
- if not return_dict:
70
- return (prev_sample,)
71
- return SchedulerOutput(prev_sample=prev_sample)