BiliSakura commited on
Commit
e505e1f
·
verified ·
1 Parent(s): 7ebed14

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +12 -0
  2. AFM-B-2-1NFE-guided/demo.png +3 -0
  3. AFM-B-2-1NFE-guided/generator/__pycache__/modeling_afm.cpython-312.pyc +0 -0
  4. AFM-B-2-1NFE-guided/generator/config.json +20 -0
  5. AFM-B-2-1NFE-guided/generator/diffusion_pytorch_model.safetensors +3 -0
  6. AFM-B-2-1NFE-guided/generator/modeling_afm.py +511 -0
  7. AFM-B-2-1NFE-guided/model_index.json +1022 -0
  8. AFM-B-2-1NFE-guided/pipeline.py +276 -0
  9. AFM-B-2-1NFE-guided/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc +0 -0
  10. AFM-B-2-1NFE-guided/scheduler/scheduler_config.json +5 -0
  11. AFM-B-2-1NFE-guided/scheduler/scheduling_continuous_flow.py +98 -0
  12. AFM-B-2-1NFE-guided/vae/config.json +38 -0
  13. AFM-B-2-1NFE-guided/vae/diffusion_pytorch_model.safetensors +3 -0
  14. AFM-B-2-1NFE-noguide/demo.png +3 -0
  15. AFM-B-2-1NFE-noguide/generator/config.json +20 -0
  16. AFM-B-2-1NFE-noguide/generator/diffusion_pytorch_model.safetensors +3 -0
  17. AFM-B-2-1NFE-noguide/generator/modeling_afm.py +511 -0
  18. AFM-B-2-1NFE-noguide/model_index.json +1022 -0
  19. AFM-B-2-1NFE-noguide/pipeline.py +276 -0
  20. AFM-B-2-1NFE-noguide/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc +0 -0
  21. AFM-B-2-1NFE-noguide/scheduler/scheduler_config.json +5 -0
  22. AFM-B-2-1NFE-noguide/scheduler/scheduling_continuous_flow.py +98 -0
  23. AFM-B-2-1NFE-noguide/vae/config.json +38 -0
  24. AFM-B-2-1NFE-noguide/vae/diffusion_pytorch_model.safetensors +3 -0
  25. AFM-L-2-1NFE-guided/demo.png +3 -0
  26. AFM-L-2-1NFE-guided/generator/config.json +20 -0
  27. AFM-L-2-1NFE-guided/generator/diffusion_pytorch_model.safetensors +3 -0
  28. AFM-L-2-1NFE-guided/generator/modeling_afm.py +511 -0
  29. AFM-L-2-1NFE-guided/model_index.json +1022 -0
  30. AFM-L-2-1NFE-guided/pipeline.py +276 -0
  31. AFM-L-2-1NFE-guided/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc +0 -0
  32. AFM-L-2-1NFE-guided/scheduler/scheduler_config.json +5 -0
  33. AFM-L-2-1NFE-guided/scheduler/scheduling_continuous_flow.py +98 -0
  34. AFM-L-2-1NFE-guided/vae/config.json +38 -0
  35. AFM-L-2-1NFE-guided/vae/diffusion_pytorch_model.safetensors +3 -0
  36. AFM-L-2-1NFE-noguide/demo.png +3 -0
  37. AFM-L-2-1NFE-noguide/generator/config.json +20 -0
  38. AFM-L-2-1NFE-noguide/generator/diffusion_pytorch_model.safetensors +3 -0
  39. AFM-L-2-1NFE-noguide/generator/modeling_afm.py +511 -0
  40. AFM-L-2-1NFE-noguide/model_index.json +1022 -0
  41. AFM-L-2-1NFE-noguide/pipeline.py +276 -0
  42. AFM-L-2-1NFE-noguide/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc +0 -0
  43. AFM-L-2-1NFE-noguide/scheduler/scheduler_config.json +5 -0
  44. AFM-L-2-1NFE-noguide/scheduler/scheduling_continuous_flow.py +98 -0
  45. AFM-L-2-1NFE-noguide/vae/config.json +38 -0
  46. AFM-L-2-1NFE-noguide/vae/diffusion_pytorch_model.safetensors +3 -0
  47. AFM-M-2-1NFE-guided/demo.png +3 -0
  48. AFM-M-2-1NFE-guided/generator/config.json +20 -0
  49. AFM-M-2-1NFE-guided/generator/diffusion_pytorch_model.safetensors +3 -0
  50. AFM-M-2-1NFE-guided/generator/modeling_afm.py +511 -0
.gitattributes CHANGED
@@ -33,3 +33,15 @@ saved_model/**/* 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
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ AFM-B-2-1NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
37
+ AFM-B-2-1NFE-noguide/demo.png filter=lfs diff=lfs merge=lfs -text
38
+ AFM-L-2-1NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
39
+ AFM-L-2-1NFE-noguide/demo.png filter=lfs diff=lfs merge=lfs -text
40
+ AFM-M-2-1NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
41
+ AFM-M-2-1NFE-noguide/demo.png filter=lfs diff=lfs merge=lfs -text
42
+ AFM-XL-2-112layer-1NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
43
+ AFM-XL-2-1NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
44
+ AFM-XL-2-1NFE-noguide/demo.png filter=lfs diff=lfs merge=lfs -text
45
+ AFM-XL-2-2NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
46
+ AFM-XL-2-2NFE-noguide/demo.png filter=lfs diff=lfs merge=lfs -text
47
+ AFM-XL-2-56layer-1NFE-guided/demo.png filter=lfs diff=lfs merge=lfs -text
AFM-B-2-1NFE-guided/demo.png ADDED

Git LFS Details

  • SHA256: a9b31babbcfbd6fe28ae301f4cdb6c193fd5621b4348e7a30432d41d8e962808
  • Pointer size: 131 Bytes
  • Size of remote file: 130 kB
AFM-B-2-1NFE-guided/generator/__pycache__/modeling_afm.cpython-312.pyc ADDED
Binary file (23.8 kB). View file
 
AFM-B-2-1NFE-guided/generator/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AFMGenerator2DModel",
3
+ "_diffusers_version": "0.36.0",
4
+ "model_type": "AFM-B/2",
5
+ "architecture": "standard",
6
+ "repeat": 1,
7
+ "use_t_src": false,
8
+ "use_t_tgt": false,
9
+ "pred_type": "x",
10
+ "num_inference_steps": 1,
11
+ "learn_sigma": false,
12
+ "class_dropout_prob": 0.0,
13
+ "input_size": 32,
14
+ "num_classes": 1000,
15
+ "in_channels": 4,
16
+ "depth": 12,
17
+ "hidden_size": 768,
18
+ "patch_size": 2,
19
+ "num_heads": 12
20
+ }
AFM-B-2-1NFE-guided/generator/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8288ea86cfca336987ea264c9ec315c683a39fdd7ec9740efb32bbcd463a4875
3
+ size 589740400
AFM-B-2-1NFE-guided/generator/modeling_afm.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained AFM generator for Hugging Face diffusers checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Dict, Optional
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from torch import nn
14
+
15
+
16
+ def get_dit_transformer_class():
17
+ from diffusers.models.transformers.dit_transformer_2d import DiTTransformer2DModel
18
+
19
+ return DiTTransformer2DModel
20
+
21
+
22
+ def build_dit_config(
23
+ *,
24
+ depth: int = 28,
25
+ hidden_size: int = 1152,
26
+ patch_size: int = 2,
27
+ num_heads: int = 16,
28
+ learn_sigma: bool = False,
29
+ class_dropout_prob: float = 0.0,
30
+ input_size: int = 32,
31
+ num_classes: int = 1000,
32
+ in_channels: int = 4,
33
+ ) -> Dict[str, Any]:
34
+ attention_head_dim = hidden_size // num_heads
35
+ num_embeds_ada_norm = num_classes + (1 if class_dropout_prob > 0 else 0)
36
+ out_channels = in_channels * 2 if learn_sigma else in_channels
37
+ return {
38
+ "sample_size": input_size,
39
+ "num_layers": depth,
40
+ "num_attention_heads": num_heads,
41
+ "attention_head_dim": attention_head_dim,
42
+ "in_channels": in_channels,
43
+ "out_channels": out_channels,
44
+ "patch_size": patch_size,
45
+ "attention_bias": True,
46
+ "activation_fn": "gelu-approximate",
47
+ "num_embeds_ada_norm": num_embeds_ada_norm,
48
+ "norm_type": "ada_norm_zero",
49
+ "norm_elementwise_affine": False,
50
+ "dropout": 0.0,
51
+ "norm_num_groups": 32,
52
+ "norm_eps": 1e-5,
53
+ "upcast_attention": False,
54
+ }
55
+
56
+
57
+ def _convert_legacy_dit_state_dict(state_dict: Dict[str, torch.Tensor], depth: int) -> Dict[str, torch.Tensor]:
58
+ converted = copy.deepcopy(state_dict)
59
+
60
+ converted["pos_embed.proj.weight"] = converted.pop("x_embedder.proj.weight").clone().contiguous()
61
+ converted["pos_embed.proj.bias"] = converted.pop("x_embedder.proj.bias").clone().contiguous()
62
+
63
+ if "t_embedder.mlp.0.weight" in converted:
64
+ timestep_weights = {
65
+ "linear_1.weight": converted.pop("t_embedder.mlp.0.weight"),
66
+ "linear_1.bias": converted.pop("t_embedder.mlp.0.bias"),
67
+ "linear_2.weight": converted.pop("t_embedder.mlp.2.weight"),
68
+ "linear_2.bias": converted.pop("t_embedder.mlp.2.bias"),
69
+ }
70
+ else:
71
+ timestep_weights = None
72
+ class_embedding = converted.pop("y_embedder.embedding_table.weight")
73
+ if class_embedding.shape[0] == 1000:
74
+ null_class = torch.zeros(1, class_embedding.shape[1], dtype=class_embedding.dtype)
75
+ class_embedding = torch.cat([class_embedding, null_class], dim=0)
76
+
77
+ for block_idx in range(depth):
78
+ if timestep_weights is not None:
79
+ for key, tensor in timestep_weights.items():
80
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.timestep_embedder.{key}"] = tensor.clone()
81
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.class_embedder.embedding_table.weight"] = (
82
+ class_embedding.clone()
83
+ )
84
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.weight"] = converted[
85
+ f"blocks.{block_idx}.adaLN_modulation.1.weight"
86
+ ]
87
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.bias"] = converted[
88
+ f"blocks.{block_idx}.adaLN_modulation.1.bias"
89
+ ]
90
+
91
+ q, k, v = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.weight"], 3, dim=0)
92
+ q_bias, k_bias, v_bias = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.bias"], 3, dim=0)
93
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.weight"] = q
94
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.bias"] = q_bias
95
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.weight"] = k
96
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.bias"] = k_bias
97
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.weight"] = v
98
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.bias"] = v_bias
99
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.weight"] = converted[
100
+ f"blocks.{block_idx}.attn.proj.weight"
101
+ ]
102
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.bias"] = converted[
103
+ f"blocks.{block_idx}.attn.proj.bias"
104
+ ]
105
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.weight"] = converted[
106
+ f"blocks.{block_idx}.mlp.fc1.weight"
107
+ ]
108
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.bias"] = converted[
109
+ f"blocks.{block_idx}.mlp.fc1.bias"
110
+ ]
111
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.weight"] = converted[
112
+ f"blocks.{block_idx}.mlp.fc2.weight"
113
+ ]
114
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.bias"] = converted[
115
+ f"blocks.{block_idx}.mlp.fc2.bias"
116
+ ]
117
+
118
+ for suffix in (
119
+ "attn.qkv.weight",
120
+ "attn.qkv.bias",
121
+ "attn.proj.weight",
122
+ "attn.proj.bias",
123
+ "mlp.fc1.weight",
124
+ "mlp.fc1.bias",
125
+ "mlp.fc2.weight",
126
+ "mlp.fc2.bias",
127
+ "adaLN_modulation.1.weight",
128
+ "adaLN_modulation.1.bias",
129
+ ):
130
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
131
+
132
+ converted["proj_out_1.weight"] = converted.pop("final_layer.adaLN_modulation.1.weight")
133
+ converted["proj_out_1.bias"] = converted.pop("final_layer.adaLN_modulation.1.bias")
134
+ converted["proj_out_2.weight"] = converted.pop("final_layer.linear.weight")
135
+ converted["proj_out_2.bias"] = converted.pop("final_layer.linear.bias")
136
+
137
+ converted.pop("pos_embed", None)
138
+ for block_idx in range(depth):
139
+ for suffix in ("norm1.weight", "norm1.bias", "norm2.weight", "norm2.bias"):
140
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
141
+
142
+ return {key: tensor.detach().clone().contiguous() for key, tensor in converted.items()}
143
+
144
+
145
+ def load_legacy_dit_state_dict(
146
+ state_dict: Dict[str, torch.Tensor],
147
+ depth: int,
148
+ patch_size: int,
149
+ hidden_size: int,
150
+ num_heads: int,
151
+ ) -> Dict[str, torch.Tensor]:
152
+ if "transformer_blocks.0.attn1.to_q.weight" in state_dict:
153
+ return state_dict
154
+ if any(key.startswith("blocks.") for key in state_dict):
155
+ return _convert_legacy_dit_state_dict(state_dict, depth)
156
+ return state_dict
157
+
158
+
159
+ def forward_dit_output(
160
+ transformer,
161
+ hidden_states: torch.Tensor,
162
+ timestep: Optional[torch.Tensor],
163
+ class_labels: torch.Tensor,
164
+ extra_cond: Optional[torch.Tensor] = None,
165
+ ) -> torch.Tensor:
166
+ hidden_states = transformer.pos_embed(hidden_states)
167
+
168
+ for block in transformer.transformer_blocks:
169
+ if torch.is_grad_enabled() and transformer.gradient_checkpointing:
170
+ hidden_states = transformer._gradient_checkpointing_func(
171
+ block,
172
+ hidden_states,
173
+ None,
174
+ None,
175
+ None,
176
+ timestep,
177
+ None,
178
+ class_labels,
179
+ )
180
+ else:
181
+ hidden_states = block(
182
+ hidden_states,
183
+ attention_mask=None,
184
+ encoder_hidden_states=None,
185
+ encoder_attention_mask=None,
186
+ timestep=timestep,
187
+ cross_attention_kwargs=None,
188
+ class_labels=class_labels,
189
+ )
190
+
191
+ conditioning = transformer.transformer_blocks[0].norm1.emb(
192
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
193
+ )
194
+ if extra_cond is not None:
195
+ conditioning = conditioning + extra_cond
196
+ shift, scale = transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
197
+ hidden_states = transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
198
+ hidden_states = transformer.proj_out_2(hidden_states)
199
+
200
+ height = width = int(hidden_states.shape[1] ** 0.5)
201
+ hidden_states = hidden_states.reshape(
202
+ shape=(-1, height, width, transformer.patch_size, transformer.patch_size, transformer.out_channels)
203
+ )
204
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
205
+ return hidden_states.reshape(
206
+ shape=(-1, transformer.out_channels, height * transformer.patch_size, width * transformer.patch_size)
207
+ )
208
+
209
+
210
+ def remap_transformer_state_dict(
211
+ state_dict: Dict[str, torch.Tensor],
212
+ legacy_kwargs: Dict[str, int],
213
+ extra_prefixes: tuple[str, ...] = (),
214
+ ) -> Dict[str, torch.Tensor]:
215
+ state_dict = load_legacy_dit_state_dict(state_dict, **legacy_kwargs)
216
+ remapped: Dict[str, torch.Tensor] = {}
217
+ for key, value in state_dict.items():
218
+ if any(key.startswith(prefix) for prefix in extra_prefixes):
219
+ remapped[key] = value
220
+ elif key.startswith("transformer."):
221
+ remapped[key] = value
222
+ else:
223
+ remapped[f"transformer.{key}"] = value
224
+ return remapped
225
+
226
+
227
+ def split_output_channels(output: torch.Tensor, in_channels: int) -> torch.Tensor:
228
+ if output.shape[1] == in_channels:
229
+ return output
230
+ output, _ = output.chunk(2, dim=1)
231
+ return output
232
+
233
+
234
+ class TimestepEmbedder(nn.Module):
235
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
236
+ super().__init__()
237
+ self.mlp = nn.Sequential(
238
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
239
+ nn.SiLU(),
240
+ nn.Linear(hidden_size, hidden_size, bias=True),
241
+ )
242
+ self.frequency_embedding_size = frequency_embedding_size
243
+
244
+ @staticmethod
245
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
246
+ half = dim // 2
247
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
248
+ device=t.device
249
+ )
250
+ args = t[:, None].float() * freqs[None]
251
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
252
+ if dim % 2:
253
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
254
+ return embedding
255
+
256
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
257
+ emb = self.timestep_embedding(t.float(), self.frequency_embedding_size)
258
+ weight_dtype = self.mlp[0].weight.dtype
259
+ return self.mlp(emb.to(dtype=weight_dtype))
260
+
261
+
262
+ class Generator(nn.Module):
263
+ def __init__(
264
+ self,
265
+ *,
266
+ use_t_src: bool = False,
267
+ use_t_tgt: bool = False,
268
+ depth: int = 28,
269
+ hidden_size: int = 1152,
270
+ patch_size: int = 2,
271
+ num_heads: int = 16,
272
+ learn_sigma: bool = False,
273
+ class_dropout_prob: float = 0.0,
274
+ input_size: int = 32,
275
+ num_classes: int = 1000,
276
+ in_channels: int = 4,
277
+ **_,
278
+ ):
279
+ super().__init__()
280
+ self.use_t_src = use_t_src
281
+ self.use_t_tgt = use_t_tgt
282
+ self._legacy_kwargs = {
283
+ "depth": depth,
284
+ "hidden_size": hidden_size,
285
+ "patch_size": patch_size,
286
+ "num_heads": num_heads,
287
+ }
288
+ dit_cls = get_dit_transformer_class()
289
+ self.transformer = dit_cls(
290
+ **build_dit_config(
291
+ depth=depth,
292
+ hidden_size=hidden_size,
293
+ patch_size=patch_size,
294
+ num_heads=num_heads,
295
+ learn_sigma=learn_sigma,
296
+ class_dropout_prob=class_dropout_prob,
297
+ input_size=input_size,
298
+ num_classes=num_classes,
299
+ in_channels=in_channels,
300
+ )
301
+ )
302
+ self.in_channels = in_channels
303
+ if use_t_tgt:
304
+ self.t_tgt_embedder = TimestepEmbedder(hidden_size)
305
+ nn.init.normal_(self.t_tgt_embedder.mlp[0].weight, std=0.02)
306
+ nn.init.normal_(self.t_tgt_embedder.mlp[2].weight, std=0.02)
307
+
308
+ def load_state_dict(self, state_dict, strict: bool = True):
309
+ extra = ("t_tgt_embedder.",)
310
+ has_extra = any(key.startswith(extra) for key in state_dict)
311
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
312
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs, extra_prefixes=extra)
313
+ if self.use_t_tgt and not has_extra:
314
+ strict = False
315
+ if not has_t_embedder:
316
+ strict = False
317
+ out = super().load_state_dict(remapped, strict=strict)
318
+ if not has_t_embedder:
319
+ for name, param in self.named_parameters():
320
+ if "timestep_embedder" in name:
321
+ param.data.zero_()
322
+ return out
323
+
324
+ def forward(self, x, y, t_src=None, t_tgt=None):
325
+ if self.use_t_src and t_src is not None:
326
+ timestep = (t_src * 1000).long()
327
+ else:
328
+ timestep = torch.zeros(x.shape[0], device=x.device, dtype=torch.long)
329
+
330
+ extra_cond = None
331
+ if self.use_t_tgt and t_tgt is not None:
332
+ extra_cond = self.t_tgt_embedder(t_tgt * 1000)
333
+
334
+ output = forward_dit_output(self.transformer, x, timestep, y, extra_cond=extra_cond)
335
+ return split_output_channels(output, self.in_channels)
336
+
337
+
338
+ class GeneratorDeep(nn.Module):
339
+ def __init__(
340
+ self,
341
+ *,
342
+ repeat: int,
343
+ depth: int = 28,
344
+ hidden_size: int = 1152,
345
+ patch_size: int = 2,
346
+ num_heads: int = 16,
347
+ learn_sigma: bool = False,
348
+ class_dropout_prob: float = 0.0,
349
+ input_size: int = 32,
350
+ num_classes: int = 1000,
351
+ in_channels: int = 4,
352
+ **_,
353
+ ):
354
+ super().__init__()
355
+ self.repeat = repeat
356
+ self._legacy_kwargs = {
357
+ "depth": depth,
358
+ "hidden_size": hidden_size,
359
+ "patch_size": patch_size,
360
+ "num_heads": num_heads,
361
+ }
362
+ dit_cls = get_dit_transformer_class()
363
+ self.transformer = dit_cls(
364
+ **build_dit_config(
365
+ depth=depth,
366
+ hidden_size=hidden_size,
367
+ patch_size=patch_size,
368
+ num_heads=num_heads,
369
+ learn_sigma=learn_sigma,
370
+ class_dropout_prob=class_dropout_prob,
371
+ input_size=input_size,
372
+ num_classes=num_classes,
373
+ in_channels=in_channels,
374
+ )
375
+ )
376
+ self.in_channels = in_channels
377
+
378
+ def load_state_dict(self, state_dict, strict: bool = True):
379
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs)
380
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
381
+ if not has_t_embedder:
382
+ strict = False
383
+ out = super().load_state_dict(remapped, strict=strict)
384
+ if not has_t_embedder:
385
+ for name, param in self.named_parameters():
386
+ if "timestep_embedder" in name:
387
+ param.data.zero_()
388
+ return out
389
+
390
+ def forward(self, x, y, *args, **kwargs):
391
+ hidden_states = self.transformer.pos_embed(x)
392
+ for t in torch.arange(1, 0, -1 / self.repeat).tolist():
393
+ timestep = torch.full([x.shape[0]], int(t * 1000), device=x.device, dtype=torch.long)
394
+ for block in self.transformer.transformer_blocks:
395
+ hidden_states = block(
396
+ hidden_states,
397
+ attention_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ timestep=timestep,
401
+ cross_attention_kwargs=None,
402
+ class_labels=y,
403
+ )
404
+
405
+ conditioning = self.transformer.transformer_blocks[0].norm1.emb(
406
+ torch.zeros(x.shape[0], device=x.device, dtype=torch.long),
407
+ y,
408
+ hidden_dtype=hidden_states.dtype,
409
+ )
410
+ shift, scale = self.transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
411
+ hidden_states = self.transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
412
+ hidden_states = self.transformer.proj_out_2(hidden_states)
413
+
414
+ height = width = int(hidden_states.shape[1] ** 0.5)
415
+ hidden_states = hidden_states.reshape(
416
+ shape=(
417
+ -1,
418
+ height,
419
+ width,
420
+ self.transformer.patch_size,
421
+ self.transformer.patch_size,
422
+ self.transformer.out_channels,
423
+ )
424
+ )
425
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
426
+ output = hidden_states.reshape(
427
+ shape=(-1, self.transformer.out_channels, height * self.transformer.patch_size, width * self.transformer.patch_size)
428
+ )
429
+ return split_output_channels(output, self.in_channels)
430
+
431
+
432
+ class AFMGenerator2DModel(Generator, ModelMixin, ConfigMixin):
433
+ config_name = "config.json"
434
+
435
+ @register_to_config
436
+ def __init__(
437
+ self,
438
+ model_type: str = "AFM-XL/2",
439
+ architecture: str = "standard",
440
+ repeat: int = 1,
441
+ use_t_src: bool = False,
442
+ use_t_tgt: bool = False,
443
+ depth: int = 28,
444
+ hidden_size: int = 1152,
445
+ patch_size: int = 2,
446
+ num_heads: int = 16,
447
+ learn_sigma: bool = False,
448
+ class_dropout_prob: float = 0.0,
449
+ input_size: int = 32,
450
+ num_classes: int = 1000,
451
+ in_channels: int = 4,
452
+ pred_type: str = "x",
453
+ num_inference_steps: int = 1,
454
+ ) -> None:
455
+ if architecture == "deep":
456
+ raise ValueError("Use AFMGeneratorDeep2DModel for deep AFM checkpoints.")
457
+ Generator.__init__(
458
+ self,
459
+ use_t_src=use_t_src,
460
+ use_t_tgt=use_t_tgt,
461
+ depth=depth,
462
+ hidden_size=hidden_size,
463
+ patch_size=patch_size,
464
+ num_heads=num_heads,
465
+ learn_sigma=learn_sigma,
466
+ class_dropout_prob=class_dropout_prob,
467
+ input_size=input_size,
468
+ num_classes=num_classes,
469
+ in_channels=in_channels,
470
+ )
471
+
472
+
473
+ class AFMGeneratorDeep2DModel(GeneratorDeep, ModelMixin, ConfigMixin):
474
+ config_name = "config.json"
475
+
476
+ @register_to_config
477
+ def __init__(
478
+ self,
479
+ model_type: str = "AFM-XL/2",
480
+ architecture: str = "deep",
481
+ repeat: int = 2,
482
+ use_t_src: bool = False,
483
+ use_t_tgt: bool = False,
484
+ depth: int = 28,
485
+ hidden_size: int = 1152,
486
+ patch_size: int = 2,
487
+ num_heads: int = 16,
488
+ learn_sigma: bool = False,
489
+ class_dropout_prob: float = 0.0,
490
+ input_size: int = 32,
491
+ num_classes: int = 1000,
492
+ in_channels: int = 4,
493
+ pred_type: str = "x",
494
+ num_inference_steps: int = 1,
495
+ ) -> None:
496
+ GeneratorDeep.__init__(
497
+ self,
498
+ repeat=repeat,
499
+ depth=depth,
500
+ hidden_size=hidden_size,
501
+ patch_size=patch_size,
502
+ num_heads=num_heads,
503
+ learn_sigma=learn_sigma,
504
+ class_dropout_prob=class_dropout_prob,
505
+ input_size=input_size,
506
+ num_classes=num_classes,
507
+ in_channels=in_channels,
508
+ )
509
+
510
+
511
+ __all__ = ["AFMGenerator2DModel", "AFMGeneratorDeep2DModel"]
AFM-B-2-1NFE-guided/model_index.json ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "AFMPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "generator": [
8
+ "modeling_afm",
9
+ "AFMGenerator2DModel"
10
+ ],
11
+ "vae": [
12
+ "diffusers",
13
+ "AutoencoderKL"
14
+ ],
15
+ "scheduler": [
16
+ "scheduling_continuous_flow",
17
+ "ContinuousFlowMatchScheduler"
18
+ ],
19
+ "pred_type": "x",
20
+ "id2label": {
21
+ "0": "tench, Tinca tinca",
22
+ "1": "goldfish, Carassius auratus",
23
+ "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
24
+ "3": "tiger shark, Galeocerdo cuvieri",
25
+ "4": "hammerhead, hammerhead shark",
26
+ "5": "electric ray, crampfish, numbfish, torpedo",
27
+ "6": "stingray",
28
+ "7": "cock",
29
+ "8": "hen",
30
+ "9": "ostrich, Struthio camelus",
31
+ "10": "brambling, Fringilla montifringilla",
32
+ "11": "goldfinch, Carduelis carduelis",
33
+ "12": "house finch, linnet, Carpodacus mexicanus",
34
+ "13": "junco, snowbird",
35
+ "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
36
+ "15": "robin, American robin, Turdus migratorius",
37
+ "16": "bulbul",
38
+ "17": "jay",
39
+ "18": "magpie",
40
+ "19": "chickadee",
41
+ "20": "water ouzel, dipper",
42
+ "21": "kite",
43
+ "22": "bald eagle, American eagle, Haliaeetus leucocephalus",
44
+ "23": "vulture",
45
+ "24": "great grey owl, great gray owl, Strix nebulosa",
46
+ "25": "European fire salamander, Salamandra salamandra",
47
+ "26": "common newt, Triturus vulgaris",
48
+ "27": "eft",
49
+ "28": "spotted salamander, Ambystoma maculatum",
50
+ "29": "axolotl, mud puppy, Ambystoma mexicanum",
51
+ "30": "bullfrog, Rana catesbeiana",
52
+ "31": "tree frog, tree-frog",
53
+ "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
54
+ "33": "loggerhead, loggerhead turtle, Caretta caretta",
55
+ "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
56
+ "35": "mud turtle",
57
+ "36": "terrapin",
58
+ "37": "box turtle, box tortoise",
59
+ "38": "banded gecko",
60
+ "39": "common iguana, iguana, Iguana iguana",
61
+ "40": "American chameleon, anole, Anolis carolinensis",
62
+ "41": "whiptail, whiptail lizard",
63
+ "42": "agama",
64
+ "43": "frilled lizard, Chlamydosaurus kingi",
65
+ "44": "alligator lizard",
66
+ "45": "Gila monster, Heloderma suspectum",
67
+ "46": "green lizard, Lacerta viridis",
68
+ "47": "African chameleon, Chamaeleo chamaeleon",
69
+ "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
70
+ "49": "African crocodile, Nile crocodile, Crocodylus niloticus",
71
+ "50": "American alligator, Alligator mississipiensis",
72
+ "51": "triceratops",
73
+ "52": "thunder snake, worm snake, Carphophis amoenus",
74
+ "53": "ringneck snake, ring-necked snake, ring snake",
75
+ "54": "hognose snake, puff adder, sand viper",
76
+ "55": "green snake, grass snake",
77
+ "56": "king snake, kingsnake",
78
+ "57": "garter snake, grass snake",
79
+ "58": "water snake",
80
+ "59": "vine snake",
81
+ "60": "night snake, Hypsiglena torquata",
82
+ "61": "boa constrictor, Constrictor constrictor",
83
+ "62": "rock python, rock snake, Python sebae",
84
+ "63": "Indian cobra, Naja naja",
85
+ "64": "green mamba",
86
+ "65": "sea snake",
87
+ "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
88
+ "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
89
+ "68": "sidewinder, horned rattlesnake, Crotalus cerastes",
90
+ "69": "trilobite",
91
+ "70": "harvestman, daddy longlegs, Phalangium opilio",
92
+ "71": "scorpion",
93
+ "72": "black and gold garden spider, Argiope aurantia",
94
+ "73": "barn spider, Araneus cavaticus",
95
+ "74": "garden spider, Aranea diademata",
96
+ "75": "black widow, Latrodectus mactans",
97
+ "76": "tarantula",
98
+ "77": "wolf spider, hunting spider",
99
+ "78": "tick",
100
+ "79": "centipede",
101
+ "80": "black grouse",
102
+ "81": "ptarmigan",
103
+ "82": "ruffed grouse, partridge, Bonasa umbellus",
104
+ "83": "prairie chicken, prairie grouse, prairie fowl",
105
+ "84": "peacock",
106
+ "85": "quail",
107
+ "86": "partridge",
108
+ "87": "African grey, African gray, Psittacus erithacus",
109
+ "88": "macaw",
110
+ "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
111
+ "90": "lorikeet",
112
+ "91": "coucal",
113
+ "92": "bee eater",
114
+ "93": "hornbill",
115
+ "94": "hummingbird",
116
+ "95": "jacamar",
117
+ "96": "toucan",
118
+ "97": "drake",
119
+ "98": "red-breasted merganser, Mergus serrator",
120
+ "99": "goose",
121
+ "100": "black swan, Cygnus atratus",
122
+ "101": "tusker",
123
+ "102": "echidna, spiny anteater, anteater",
124
+ "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
125
+ "104": "wallaby, brush kangaroo",
126
+ "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
127
+ "106": "wombat",
128
+ "107": "jellyfish",
129
+ "108": "sea anemone, anemone",
130
+ "109": "brain coral",
131
+ "110": "flatworm, platyhelminth",
132
+ "111": "nematode, nematode worm, roundworm",
133
+ "112": "conch",
134
+ "113": "snail",
135
+ "114": "slug",
136
+ "115": "sea slug, nudibranch",
137
+ "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
138
+ "117": "chambered nautilus, pearly nautilus, nautilus",
139
+ "118": "Dungeness crab, Cancer magister",
140
+ "119": "rock crab, Cancer irroratus",
141
+ "120": "fiddler crab",
142
+ "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
143
+ "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
144
+ "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
145
+ "124": "crayfish, crawfish, crawdad, crawdaddy",
146
+ "125": "hermit crab",
147
+ "126": "isopod",
148
+ "127": "white stork, Ciconia ciconia",
149
+ "128": "black stork, Ciconia nigra",
150
+ "129": "spoonbill",
151
+ "130": "flamingo",
152
+ "131": "little blue heron, Egretta caerulea",
153
+ "132": "American egret, great white heron, Egretta albus",
154
+ "133": "bittern",
155
+ "134": "crane",
156
+ "135": "limpkin, Aramus pictus",
157
+ "136": "European gallinule, Porphyrio porphyrio",
158
+ "137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
159
+ "138": "bustard",
160
+ "139": "ruddy turnstone, Arenaria interpres",
161
+ "140": "red-backed sandpiper, dunlin, Erolia alpina",
162
+ "141": "redshank, Tringa totanus",
163
+ "142": "dowitcher",
164
+ "143": "oystercatcher, oyster catcher",
165
+ "144": "pelican",
166
+ "145": "king penguin, Aptenodytes patagonica",
167
+ "146": "albatross, mollymawk",
168
+ "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
169
+ "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
170
+ "149": "dugong, Dugong dugon",
171
+ "150": "sea lion",
172
+ "151": "Chihuahua",
173
+ "152": "Japanese spaniel",
174
+ "153": "Maltese dog, Maltese terrier, Maltese",
175
+ "154": "Pekinese, Pekingese, Peke",
176
+ "155": "Shih-Tzu",
177
+ "156": "Blenheim spaniel",
178
+ "157": "papillon",
179
+ "158": "toy terrier",
180
+ "159": "Rhodesian ridgeback",
181
+ "160": "Afghan hound, Afghan",
182
+ "161": "basset, basset hound",
183
+ "162": "beagle",
184
+ "163": "bloodhound, sleuthhound",
185
+ "164": "bluetick",
186
+ "165": "black-and-tan coonhound",
187
+ "166": "Walker hound, Walker foxhound",
188
+ "167": "English foxhound",
189
+ "168": "redbone",
190
+ "169": "borzoi, Russian wolfhound",
191
+ "170": "Irish wolfhound",
192
+ "171": "Italian greyhound",
193
+ "172": "whippet",
194
+ "173": "Ibizan hound, Ibizan Podenco",
195
+ "174": "Norwegian elkhound, elkhound",
196
+ "175": "otterhound, otter hound",
197
+ "176": "Saluki, gazelle hound",
198
+ "177": "Scottish deerhound, deerhound",
199
+ "178": "Weimaraner",
200
+ "179": "Staffordshire bullterrier, Staffordshire bull terrier",
201
+ "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
202
+ "181": "Bedlington terrier",
203
+ "182": "Border terrier",
204
+ "183": "Kerry blue terrier",
205
+ "184": "Irish terrier",
206
+ "185": "Norfolk terrier",
207
+ "186": "Norwich terrier",
208
+ "187": "Yorkshire terrier",
209
+ "188": "wire-haired fox terrier",
210
+ "189": "Lakeland terrier",
211
+ "190": "Sealyham terrier, Sealyham",
212
+ "191": "Airedale, Airedale terrier",
213
+ "192": "cairn, cairn terrier",
214
+ "193": "Australian terrier",
215
+ "194": "Dandie Dinmont, Dandie Dinmont terrier",
216
+ "195": "Boston bull, Boston terrier",
217
+ "196": "miniature schnauzer",
218
+ "197": "giant schnauzer",
219
+ "198": "standard schnauzer",
220
+ "199": "Scotch terrier, Scottish terrier, Scottie",
221
+ "200": "Tibetan terrier, chrysanthemum dog",
222
+ "201": "silky terrier, Sydney silky",
223
+ "202": "soft-coated wheaten terrier",
224
+ "203": "West Highland white terrier",
225
+ "204": "Lhasa, Lhasa apso",
226
+ "205": "flat-coated retriever",
227
+ "206": "curly-coated retriever",
228
+ "207": "golden retriever",
229
+ "208": "Labrador retriever",
230
+ "209": "Chesapeake Bay retriever",
231
+ "210": "German short-haired pointer",
232
+ "211": "vizsla, Hungarian pointer",
233
+ "212": "English setter",
234
+ "213": "Irish setter, red setter",
235
+ "214": "Gordon setter",
236
+ "215": "Brittany spaniel",
237
+ "216": "clumber, clumber spaniel",
238
+ "217": "English springer, English springer spaniel",
239
+ "218": "Welsh springer spaniel",
240
+ "219": "cocker spaniel, English cocker spaniel, cocker",
241
+ "220": "Sussex spaniel",
242
+ "221": "Irish water spaniel",
243
+ "222": "kuvasz",
244
+ "223": "schipperke",
245
+ "224": "groenendael",
246
+ "225": "malinois",
247
+ "226": "briard",
248
+ "227": "kelpie",
249
+ "228": "komondor",
250
+ "229": "Old English sheepdog, bobtail",
251
+ "230": "Shetland sheepdog, Shetland sheep dog, Shetland",
252
+ "231": "collie",
253
+ "232": "Border collie",
254
+ "233": "Bouvier des Flandres, Bouviers des Flandres",
255
+ "234": "Rottweiler",
256
+ "235": "German shepherd, German shepherd dog, German police dog, alsatian",
257
+ "236": "Doberman, Doberman pinscher",
258
+ "237": "miniature pinscher",
259
+ "238": "Greater Swiss Mountain dog",
260
+ "239": "Bernese mountain dog",
261
+ "240": "Appenzeller",
262
+ "241": "EntleBucher",
263
+ "242": "boxer",
264
+ "243": "bull mastiff",
265
+ "244": "Tibetan mastiff",
266
+ "245": "French bulldog",
267
+ "246": "Great Dane",
268
+ "247": "Saint Bernard, St Bernard",
269
+ "248": "Eskimo dog, husky",
270
+ "249": "malamute, malemute, Alaskan malamute",
271
+ "250": "Siberian husky",
272
+ "251": "dalmatian, coach dog, carriage dog",
273
+ "252": "affenpinscher, monkey pinscher, monkey dog",
274
+ "253": "basenji",
275
+ "254": "pug, pug-dog",
276
+ "255": "Leonberg",
277
+ "256": "Newfoundland, Newfoundland dog",
278
+ "257": "Great Pyrenees",
279
+ "258": "Samoyed, Samoyede",
280
+ "259": "Pomeranian",
281
+ "260": "chow, chow chow",
282
+ "261": "keeshond",
283
+ "262": "Brabancon griffon",
284
+ "263": "Pembroke, Pembroke Welsh corgi",
285
+ "264": "Cardigan, Cardigan Welsh corgi",
286
+ "265": "toy poodle",
287
+ "266": "miniature poodle",
288
+ "267": "standard poodle",
289
+ "268": "Mexican hairless",
290
+ "269": "timber wolf, grey wolf, gray wolf, Canis lupus",
291
+ "270": "white wolf, Arctic wolf, Canis lupus tundrarum",
292
+ "271": "red wolf, maned wolf, Canis rufus, Canis niger",
293
+ "272": "coyote, prairie wolf, brush wolf, Canis latrans",
294
+ "273": "dingo, warrigal, warragal, Canis dingo",
295
+ "274": "dhole, Cuon alpinus",
296
+ "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
297
+ "276": "hyena, hyaena",
298
+ "277": "red fox, Vulpes vulpes",
299
+ "278": "kit fox, Vulpes macrotis",
300
+ "279": "Arctic fox, white fox, Alopex lagopus",
301
+ "280": "grey fox, gray fox, Urocyon cinereoargenteus",
302
+ "281": "tabby, tabby cat",
303
+ "282": "tiger cat",
304
+ "283": "Persian cat",
305
+ "284": "Siamese cat, Siamese",
306
+ "285": "Egyptian cat",
307
+ "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
308
+ "287": "lynx, catamount",
309
+ "288": "leopard, Panthera pardus",
310
+ "289": "snow leopard, ounce, Panthera uncia",
311
+ "290": "jaguar, panther, Panthera onca, Felis onca",
312
+ "291": "lion, king of beasts, Panthera leo",
313
+ "292": "tiger, Panthera tigris",
314
+ "293": "cheetah, chetah, Acinonyx jubatus",
315
+ "294": "brown bear, bruin, Ursus arctos",
316
+ "295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
317
+ "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
318
+ "297": "sloth bear, Melursus ursinus, Ursus ursinus",
319
+ "298": "mongoose",
320
+ "299": "meerkat, mierkat",
321
+ "300": "tiger beetle",
322
+ "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
323
+ "302": "ground beetle, carabid beetle",
324
+ "303": "long-horned beetle, longicorn, longicorn beetle",
325
+ "304": "leaf beetle, chrysomelid",
326
+ "305": "dung beetle",
327
+ "306": "rhinoceros beetle",
328
+ "307": "weevil",
329
+ "308": "fly",
330
+ "309": "bee",
331
+ "310": "ant, emmet, pismire",
332
+ "311": "grasshopper, hopper",
333
+ "312": "cricket",
334
+ "313": "walking stick, walkingstick, stick insect",
335
+ "314": "cockroach, roach",
336
+ "315": "mantis, mantid",
337
+ "316": "cicada, cicala",
338
+ "317": "leafhopper",
339
+ "318": "lacewing, lacewing fly",
340
+ "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
341
+ "320": "damselfly",
342
+ "321": "admiral",
343
+ "322": "ringlet, ringlet butterfly",
344
+ "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
345
+ "324": "cabbage butterfly",
346
+ "325": "sulphur butterfly, sulfur butterfly",
347
+ "326": "lycaenid, lycaenid butterfly",
348
+ "327": "starfish, sea star",
349
+ "328": "sea urchin",
350
+ "329": "sea cucumber, holothurian",
351
+ "330": "wood rabbit, cottontail, cottontail rabbit",
352
+ "331": "hare",
353
+ "332": "Angora, Angora rabbit",
354
+ "333": "hamster",
355
+ "334": "porcupine, hedgehog",
356
+ "335": "fox squirrel, eastern fox squirrel, Sciurus niger",
357
+ "336": "marmot",
358
+ "337": "beaver",
359
+ "338": "guinea pig, Cavia cobaya",
360
+ "339": "sorrel",
361
+ "340": "zebra",
362
+ "341": "hog, pig, grunter, squealer, Sus scrofa",
363
+ "342": "wild boar, boar, Sus scrofa",
364
+ "343": "warthog",
365
+ "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
366
+ "345": "ox",
367
+ "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
368
+ "347": "bison",
369
+ "348": "ram, tup",
370
+ "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
371
+ "350": "ibex, Capra ibex",
372
+ "351": "hartebeest",
373
+ "352": "impala, Aepyceros melampus",
374
+ "353": "gazelle",
375
+ "354": "Arabian camel, dromedary, Camelus dromedarius",
376
+ "355": "llama",
377
+ "356": "weasel",
378
+ "357": "mink",
379
+ "358": "polecat, fitch, foulmart, foumart, Mustela putorius",
380
+ "359": "black-footed ferret, ferret, Mustela nigripes",
381
+ "360": "otter",
382
+ "361": "skunk, polecat, wood pussy",
383
+ "362": "badger",
384
+ "363": "armadillo",
385
+ "364": "three-toed sloth, ai, Bradypus tridactylus",
386
+ "365": "orangutan, orang, orangutang, Pongo pygmaeus",
387
+ "366": "gorilla, Gorilla gorilla",
388
+ "367": "chimpanzee, chimp, Pan troglodytes",
389
+ "368": "gibbon, Hylobates lar",
390
+ "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
391
+ "370": "guenon, guenon monkey",
392
+ "371": "patas, hussar monkey, Erythrocebus patas",
393
+ "372": "baboon",
394
+ "373": "macaque",
395
+ "374": "langur",
396
+ "375": "colobus, colobus monkey",
397
+ "376": "proboscis monkey, Nasalis larvatus",
398
+ "377": "marmoset",
399
+ "378": "capuchin, ringtail, Cebus capucinus",
400
+ "379": "howler monkey, howler",
401
+ "380": "titi, titi monkey",
402
+ "381": "spider monkey, Ateles geoffroyi",
403
+ "382": "squirrel monkey, Saimiri sciureus",
404
+ "383": "Madagascar cat, ring-tailed lemur, Lemur catta",
405
+ "384": "indri, indris, Indri indri, Indri brevicaudatus",
406
+ "385": "Indian elephant, Elephas maximus",
407
+ "386": "African elephant, Loxodonta africana",
408
+ "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
409
+ "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
410
+ "389": "barracouta, snoek",
411
+ "390": "eel",
412
+ "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
413
+ "392": "rock beauty, Holocanthus tricolor",
414
+ "393": "anemone fish",
415
+ "394": "sturgeon",
416
+ "395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
417
+ "396": "lionfish",
418
+ "397": "puffer, pufferfish, blowfish, globefish",
419
+ "398": "abacus",
420
+ "399": "abaya",
421
+ "400": "academic gown, academic robe, judge robe",
422
+ "401": "accordion, piano accordion, squeeze box",
423
+ "402": "acoustic guitar",
424
+ "403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
425
+ "404": "airliner",
426
+ "405": "airship, dirigible",
427
+ "406": "altar",
428
+ "407": "ambulance",
429
+ "408": "amphibian, amphibious vehicle",
430
+ "409": "analog clock",
431
+ "410": "apiary, bee house",
432
+ "411": "apron",
433
+ "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
434
+ "413": "assault rifle, assault gun",
435
+ "414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
436
+ "415": "bakery, bakeshop, bakehouse",
437
+ "416": "balance beam, beam",
438
+ "417": "balloon",
439
+ "418": "ballpoint, ballpoint pen, ballpen, Biro",
440
+ "419": "Band Aid",
441
+ "420": "banjo",
442
+ "421": "bannister, banister, balustrade, balusters, handrail",
443
+ "422": "barbell",
444
+ "423": "barber chair",
445
+ "424": "barbershop",
446
+ "425": "barn",
447
+ "426": "barometer",
448
+ "427": "barrel, cask",
449
+ "428": "barrow, garden cart, lawn cart, wheelbarrow",
450
+ "429": "baseball",
451
+ "430": "basketball",
452
+ "431": "bassinet",
453
+ "432": "bassoon",
454
+ "433": "bathing cap, swimming cap",
455
+ "434": "bath towel",
456
+ "435": "bathtub, bathing tub, bath, tub",
457
+ "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
458
+ "437": "beacon, lighthouse, beacon light, pharos",
459
+ "438": "beaker",
460
+ "439": "bearskin, busby, shako",
461
+ "440": "beer bottle",
462
+ "441": "beer glass",
463
+ "442": "bell cote, bell cot",
464
+ "443": "bib",
465
+ "444": "bicycle-built-for-two, tandem bicycle, tandem",
466
+ "445": "bikini, two-piece",
467
+ "446": "binder, ring-binder",
468
+ "447": "binoculars, field glasses, opera glasses",
469
+ "448": "birdhouse",
470
+ "449": "boathouse",
471
+ "450": "bobsled, bobsleigh, bob",
472
+ "451": "bolo tie, bolo, bola tie, bola",
473
+ "452": "bonnet, poke bonnet",
474
+ "453": "bookcase",
475
+ "454": "bookshop, bookstore, bookstall",
476
+ "455": "bottlecap",
477
+ "456": "bow",
478
+ "457": "bow tie, bow-tie, bowtie",
479
+ "458": "brass, memorial tablet, plaque",
480
+ "459": "brassiere, bra, bandeau",
481
+ "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
482
+ "461": "breastplate, aegis, egis",
483
+ "462": "broom",
484
+ "463": "bucket, pail",
485
+ "464": "buckle",
486
+ "465": "bulletproof vest",
487
+ "466": "bullet train, bullet",
488
+ "467": "butcher shop, meat market",
489
+ "468": "cab, hack, taxi, taxicab",
490
+ "469": "caldron, cauldron",
491
+ "470": "candle, taper, wax light",
492
+ "471": "cannon",
493
+ "472": "canoe",
494
+ "473": "can opener, tin opener",
495
+ "474": "cardigan",
496
+ "475": "car mirror",
497
+ "476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
498
+ "477": "carpenters kit, tool kit",
499
+ "478": "carton",
500
+ "479": "car wheel",
501
+ "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
502
+ "481": "cassette",
503
+ "482": "cassette player",
504
+ "483": "castle",
505
+ "484": "catamaran",
506
+ "485": "CD player",
507
+ "486": "cello, violoncello",
508
+ "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
509
+ "488": "chain",
510
+ "489": "chainlink fence",
511
+ "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
512
+ "491": "chain saw, chainsaw",
513
+ "492": "chest",
514
+ "493": "chiffonier, commode",
515
+ "494": "chime, bell, gong",
516
+ "495": "china cabinet, china closet",
517
+ "496": "Christmas stocking",
518
+ "497": "church, church building",
519
+ "498": "cinema, movie theater, movie theatre, movie house, picture palace",
520
+ "499": "cleaver, meat cleaver, chopper",
521
+ "500": "cliff dwelling",
522
+ "501": "cloak",
523
+ "502": "clog, geta, patten, sabot",
524
+ "503": "cocktail shaker",
525
+ "504": "coffee mug",
526
+ "505": "coffeepot",
527
+ "506": "coil, spiral, volute, whorl, helix",
528
+ "507": "combination lock",
529
+ "508": "computer keyboard, keypad",
530
+ "509": "confectionery, confectionary, candy store",
531
+ "510": "container ship, containership, container vessel",
532
+ "511": "convertible",
533
+ "512": "corkscrew, bottle screw",
534
+ "513": "cornet, horn, trumpet, trump",
535
+ "514": "cowboy boot",
536
+ "515": "cowboy hat, ten-gallon hat",
537
+ "516": "cradle",
538
+ "517": "crane",
539
+ "518": "crash helmet",
540
+ "519": "crate",
541
+ "520": "crib, cot",
542
+ "521": "Crock Pot",
543
+ "522": "croquet ball",
544
+ "523": "crutch",
545
+ "524": "cuirass",
546
+ "525": "dam, dike, dyke",
547
+ "526": "desk",
548
+ "527": "desktop computer",
549
+ "528": "dial telephone, dial phone",
550
+ "529": "diaper, nappy, napkin",
551
+ "530": "digital clock",
552
+ "531": "digital watch",
553
+ "532": "dining table, board",
554
+ "533": "dishrag, dishcloth",
555
+ "534": "dishwasher, dish washer, dishwashing machine",
556
+ "535": "disk brake, disc brake",
557
+ "536": "dock, dockage, docking facility",
558
+ "537": "dogsled, dog sled, dog sleigh",
559
+ "538": "dome",
560
+ "539": "doormat, welcome mat",
561
+ "540": "drilling platform, offshore rig",
562
+ "541": "drum, membranophone, tympan",
563
+ "542": "drumstick",
564
+ "543": "dumbbell",
565
+ "544": "Dutch oven",
566
+ "545": "electric fan, blower",
567
+ "546": "electric guitar",
568
+ "547": "electric locomotive",
569
+ "548": "entertainment center",
570
+ "549": "envelope",
571
+ "550": "espresso maker",
572
+ "551": "face powder",
573
+ "552": "feather boa, boa",
574
+ "553": "file, file cabinet, filing cabinet",
575
+ "554": "fireboat",
576
+ "555": "fire engine, fire truck",
577
+ "556": "fire screen, fireguard",
578
+ "557": "flagpole, flagstaff",
579
+ "558": "flute, transverse flute",
580
+ "559": "folding chair",
581
+ "560": "football helmet",
582
+ "561": "forklift",
583
+ "562": "fountain",
584
+ "563": "fountain pen",
585
+ "564": "four-poster",
586
+ "565": "freight car",
587
+ "566": "French horn, horn",
588
+ "567": "frying pan, frypan, skillet",
589
+ "568": "fur coat",
590
+ "569": "garbage truck, dustcart",
591
+ "570": "gasmask, respirator, gas helmet",
592
+ "571": "gas pump, gasoline pump, petrol pump, island dispenser",
593
+ "572": "goblet",
594
+ "573": "go-kart",
595
+ "574": "golf ball",
596
+ "575": "golfcart, golf cart",
597
+ "576": "gondola",
598
+ "577": "gong, tam-tam",
599
+ "578": "gown",
600
+ "579": "grand piano, grand",
601
+ "580": "greenhouse, nursery, glasshouse",
602
+ "581": "grille, radiator grille",
603
+ "582": "grocery store, grocery, food market, market",
604
+ "583": "guillotine",
605
+ "584": "hair slide",
606
+ "585": "hair spray",
607
+ "586": "half track",
608
+ "587": "hammer",
609
+ "588": "hamper",
610
+ "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
611
+ "590": "hand-held computer, hand-held microcomputer",
612
+ "591": "handkerchief, hankie, hanky, hankey",
613
+ "592": "hard disc, hard disk, fixed disk",
614
+ "593": "harmonica, mouth organ, harp, mouth harp",
615
+ "594": "harp",
616
+ "595": "harvester, reaper",
617
+ "596": "hatchet",
618
+ "597": "holster",
619
+ "598": "home theater, home theatre",
620
+ "599": "honeycomb",
621
+ "600": "hook, claw",
622
+ "601": "hoopskirt, crinoline",
623
+ "602": "horizontal bar, high bar",
624
+ "603": "horse cart, horse-cart",
625
+ "604": "hourglass",
626
+ "605": "iPod",
627
+ "606": "iron, smoothing iron",
628
+ "607": "jack-o-lantern",
629
+ "608": "jean, blue jean, denim",
630
+ "609": "jeep, landrover",
631
+ "610": "jersey, T-shirt, tee shirt",
632
+ "611": "jigsaw puzzle",
633
+ "612": "jinrikisha, ricksha, rickshaw",
634
+ "613": "joystick",
635
+ "614": "kimono",
636
+ "615": "knee pad",
637
+ "616": "knot",
638
+ "617": "lab coat, laboratory coat",
639
+ "618": "ladle",
640
+ "619": "lampshade, lamp shade",
641
+ "620": "laptop, laptop computer",
642
+ "621": "lawn mower, mower",
643
+ "622": "lens cap, lens cover",
644
+ "623": "letter opener, paper knife, paperknife",
645
+ "624": "library",
646
+ "625": "lifeboat",
647
+ "626": "lighter, light, igniter, ignitor",
648
+ "627": "limousine, limo",
649
+ "628": "liner, ocean liner",
650
+ "629": "lipstick, lip rouge",
651
+ "630": "Loafer",
652
+ "631": "lotion",
653
+ "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
654
+ "633": "loupe, jewelers loupe",
655
+ "634": "lumbermill, sawmill",
656
+ "635": "magnetic compass",
657
+ "636": "mailbag, postbag",
658
+ "637": "mailbox, letter box",
659
+ "638": "maillot",
660
+ "639": "maillot, tank suit",
661
+ "640": "manhole cover",
662
+ "641": "maraca",
663
+ "642": "marimba, xylophone",
664
+ "643": "mask",
665
+ "644": "matchstick",
666
+ "645": "maypole",
667
+ "646": "maze, labyrinth",
668
+ "647": "measuring cup",
669
+ "648": "medicine chest, medicine cabinet",
670
+ "649": "megalith, megalithic structure",
671
+ "650": "microphone, mike",
672
+ "651": "microwave, microwave oven",
673
+ "652": "military uniform",
674
+ "653": "milk can",
675
+ "654": "minibus",
676
+ "655": "miniskirt, mini",
677
+ "656": "minivan",
678
+ "657": "missile",
679
+ "658": "mitten",
680
+ "659": "mixing bowl",
681
+ "660": "mobile home, manufactured home",
682
+ "661": "Model T",
683
+ "662": "modem",
684
+ "663": "monastery",
685
+ "664": "monitor",
686
+ "665": "moped",
687
+ "666": "mortar",
688
+ "667": "mortarboard",
689
+ "668": "mosque",
690
+ "669": "mosquito net",
691
+ "670": "motor scooter, scooter",
692
+ "671": "mountain bike, all-terrain bike, off-roader",
693
+ "672": "mountain tent",
694
+ "673": "mouse, computer mouse",
695
+ "674": "mousetrap",
696
+ "675": "moving van",
697
+ "676": "muzzle",
698
+ "677": "nail",
699
+ "678": "neck brace",
700
+ "679": "necklace",
701
+ "680": "nipple",
702
+ "681": "notebook, notebook computer",
703
+ "682": "obelisk",
704
+ "683": "oboe, hautboy, hautbois",
705
+ "684": "ocarina, sweet potato",
706
+ "685": "odometer, hodometer, mileometer, milometer",
707
+ "686": "oil filter",
708
+ "687": "organ, pipe organ",
709
+ "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
710
+ "689": "overskirt",
711
+ "690": "oxcart",
712
+ "691": "oxygen mask",
713
+ "692": "packet",
714
+ "693": "paddle, boat paddle",
715
+ "694": "paddlewheel, paddle wheel",
716
+ "695": "padlock",
717
+ "696": "paintbrush",
718
+ "697": "pajama, pyjama, pjs, jammies",
719
+ "698": "palace",
720
+ "699": "panpipe, pandean pipe, syrinx",
721
+ "700": "paper towel",
722
+ "701": "parachute, chute",
723
+ "702": "parallel bars, bars",
724
+ "703": "park bench",
725
+ "704": "parking meter",
726
+ "705": "passenger car, coach, carriage",
727
+ "706": "patio, terrace",
728
+ "707": "pay-phone, pay-station",
729
+ "708": "pedestal, plinth, footstall",
730
+ "709": "pencil box, pencil case",
731
+ "710": "pencil sharpener",
732
+ "711": "perfume, essence",
733
+ "712": "Petri dish",
734
+ "713": "photocopier",
735
+ "714": "pick, plectrum, plectron",
736
+ "715": "pickelhaube",
737
+ "716": "picket fence, paling",
738
+ "717": "pickup, pickup truck",
739
+ "718": "pier",
740
+ "719": "piggy bank, penny bank",
741
+ "720": "pill bottle",
742
+ "721": "pillow",
743
+ "722": "ping-pong ball",
744
+ "723": "pinwheel",
745
+ "724": "pirate, pirate ship",
746
+ "725": "pitcher, ewer",
747
+ "726": "plane, carpenters plane, woodworking plane",
748
+ "727": "planetarium",
749
+ "728": "plastic bag",
750
+ "729": "plate rack",
751
+ "730": "plow, plough",
752
+ "731": "plunger, plumbers helper",
753
+ "732": "Polaroid camera, Polaroid Land camera",
754
+ "733": "pole",
755
+ "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
756
+ "735": "poncho",
757
+ "736": "pool table, billiard table, snooker table",
758
+ "737": "pop bottle, soda bottle",
759
+ "738": "pot, flowerpot",
760
+ "739": "potters wheel",
761
+ "740": "power drill",
762
+ "741": "prayer rug, prayer mat",
763
+ "742": "printer",
764
+ "743": "prison, prison house",
765
+ "744": "projectile, missile",
766
+ "745": "projector",
767
+ "746": "puck, hockey puck",
768
+ "747": "punching bag, punch bag, punching ball, punchball",
769
+ "748": "purse",
770
+ "749": "quill, quill pen",
771
+ "750": "quilt, comforter, comfort, puff",
772
+ "751": "racer, race car, racing car",
773
+ "752": "racket, racquet",
774
+ "753": "radiator",
775
+ "754": "radio, wireless",
776
+ "755": "radio telescope, radio reflector",
777
+ "756": "rain barrel",
778
+ "757": "recreational vehicle, RV, R.V.",
779
+ "758": "reel",
780
+ "759": "reflex camera",
781
+ "760": "refrigerator, icebox",
782
+ "761": "remote control, remote",
783
+ "762": "restaurant, eating house, eating place, eatery",
784
+ "763": "revolver, six-gun, six-shooter",
785
+ "764": "rifle",
786
+ "765": "rocking chair, rocker",
787
+ "766": "rotisserie",
788
+ "767": "rubber eraser, rubber, pencil eraser",
789
+ "768": "rugby ball",
790
+ "769": "rule, ruler",
791
+ "770": "running shoe",
792
+ "771": "safe",
793
+ "772": "safety pin",
794
+ "773": "saltshaker, salt shaker",
795
+ "774": "sandal",
796
+ "775": "sarong",
797
+ "776": "sax, saxophone",
798
+ "777": "scabbard",
799
+ "778": "scale, weighing machine",
800
+ "779": "school bus",
801
+ "780": "schooner",
802
+ "781": "scoreboard",
803
+ "782": "screen, CRT screen",
804
+ "783": "screw",
805
+ "784": "screwdriver",
806
+ "785": "seat belt, seatbelt",
807
+ "786": "sewing machine",
808
+ "787": "shield, buckler",
809
+ "788": "shoe shop, shoe-shop, shoe store",
810
+ "789": "shoji",
811
+ "790": "shopping basket",
812
+ "791": "shopping cart",
813
+ "792": "shovel",
814
+ "793": "shower cap",
815
+ "794": "shower curtain",
816
+ "795": "ski",
817
+ "796": "ski mask",
818
+ "797": "sleeping bag",
819
+ "798": "slide rule, slipstick",
820
+ "799": "sliding door",
821
+ "800": "slot, one-armed bandit",
822
+ "801": "snorkel",
823
+ "802": "snowmobile",
824
+ "803": "snowplow, snowplough",
825
+ "804": "soap dispenser",
826
+ "805": "soccer ball",
827
+ "806": "sock",
828
+ "807": "solar dish, solar collector, solar furnace",
829
+ "808": "sombrero",
830
+ "809": "soup bowl",
831
+ "810": "space bar",
832
+ "811": "space heater",
833
+ "812": "space shuttle",
834
+ "813": "spatula",
835
+ "814": "speedboat",
836
+ "815": "spider web, spiders web",
837
+ "816": "spindle",
838
+ "817": "sports car, sport car",
839
+ "818": "spotlight, spot",
840
+ "819": "stage",
841
+ "820": "steam locomotive",
842
+ "821": "steel arch bridge",
843
+ "822": "steel drum",
844
+ "823": "stethoscope",
845
+ "824": "stole",
846
+ "825": "stone wall",
847
+ "826": "stopwatch, stop watch",
848
+ "827": "stove",
849
+ "828": "strainer",
850
+ "829": "streetcar, tram, tramcar, trolley, trolley car",
851
+ "830": "stretcher",
852
+ "831": "studio couch, day bed",
853
+ "832": "stupa, tope",
854
+ "833": "submarine, pigboat, sub, U-boat",
855
+ "834": "suit, suit of clothes",
856
+ "835": "sundial",
857
+ "836": "sunglass",
858
+ "837": "sunglasses, dark glasses, shades",
859
+ "838": "sunscreen, sunblock, sun blocker",
860
+ "839": "suspension bridge",
861
+ "840": "swab, swob, mop",
862
+ "841": "sweatshirt",
863
+ "842": "swimming trunks, bathing trunks",
864
+ "843": "swing",
865
+ "844": "switch, electric switch, electrical switch",
866
+ "845": "syringe",
867
+ "846": "table lamp",
868
+ "847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
869
+ "848": "tape player",
870
+ "849": "teapot",
871
+ "850": "teddy, teddy bear",
872
+ "851": "television, television system",
873
+ "852": "tennis ball",
874
+ "853": "thatch, thatched roof",
875
+ "854": "theater curtain, theatre curtain",
876
+ "855": "thimble",
877
+ "856": "thresher, thrasher, threshing machine",
878
+ "857": "throne",
879
+ "858": "tile roof",
880
+ "859": "toaster",
881
+ "860": "tobacco shop, tobacconist shop, tobacconist",
882
+ "861": "toilet seat",
883
+ "862": "torch",
884
+ "863": "totem pole",
885
+ "864": "tow truck, tow car, wrecker",
886
+ "865": "toyshop",
887
+ "866": "tractor",
888
+ "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
889
+ "868": "tray",
890
+ "869": "trench coat",
891
+ "870": "tricycle, trike, velocipede",
892
+ "871": "trimaran",
893
+ "872": "tripod",
894
+ "873": "triumphal arch",
895
+ "874": "trolleybus, trolley coach, trackless trolley",
896
+ "875": "trombone",
897
+ "876": "tub, vat",
898
+ "877": "turnstile",
899
+ "878": "typewriter keyboard",
900
+ "879": "umbrella",
901
+ "880": "unicycle, monocycle",
902
+ "881": "upright, upright piano",
903
+ "882": "vacuum, vacuum cleaner",
904
+ "883": "vase",
905
+ "884": "vault",
906
+ "885": "velvet",
907
+ "886": "vending machine",
908
+ "887": "vestment",
909
+ "888": "viaduct",
910
+ "889": "violin, fiddle",
911
+ "890": "volleyball",
912
+ "891": "waffle iron",
913
+ "892": "wall clock",
914
+ "893": "wallet, billfold, notecase, pocketbook",
915
+ "894": "wardrobe, closet, press",
916
+ "895": "warplane, military plane",
917
+ "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
918
+ "897": "washer, automatic washer, washing machine",
919
+ "898": "water bottle",
920
+ "899": "water jug",
921
+ "900": "water tower",
922
+ "901": "whiskey jug",
923
+ "902": "whistle",
924
+ "903": "wig",
925
+ "904": "window screen",
926
+ "905": "window shade",
927
+ "906": "Windsor tie",
928
+ "907": "wine bottle",
929
+ "908": "wing",
930
+ "909": "wok",
931
+ "910": "wooden spoon",
932
+ "911": "wool, woolen, woollen",
933
+ "912": "worm fence, snake fence, snake-rail fence, Virginia fence",
934
+ "913": "wreck",
935
+ "914": "yawl",
936
+ "915": "yurt",
937
+ "916": "web site, website, internet site, site",
938
+ "917": "comic book",
939
+ "918": "crossword puzzle, crossword",
940
+ "919": "street sign",
941
+ "920": "traffic light, traffic signal, stoplight",
942
+ "921": "book jacket, dust cover, dust jacket, dust wrapper",
943
+ "922": "menu",
944
+ "923": "plate",
945
+ "924": "guacamole",
946
+ "925": "consomme",
947
+ "926": "hot pot, hotpot",
948
+ "927": "trifle",
949
+ "928": "ice cream, icecream",
950
+ "929": "ice lolly, lolly, lollipop, popsicle",
951
+ "930": "French loaf",
952
+ "931": "bagel, beigel",
953
+ "932": "pretzel",
954
+ "933": "cheeseburger",
955
+ "934": "hotdog, hot dog, red hot",
956
+ "935": "mashed potato",
957
+ "936": "head cabbage",
958
+ "937": "broccoli",
959
+ "938": "cauliflower",
960
+ "939": "zucchini, courgette",
961
+ "940": "spaghetti squash",
962
+ "941": "acorn squash",
963
+ "942": "butternut squash",
964
+ "943": "cucumber, cuke",
965
+ "944": "artichoke, globe artichoke",
966
+ "945": "bell pepper",
967
+ "946": "cardoon",
968
+ "947": "mushroom",
969
+ "948": "Granny Smith",
970
+ "949": "strawberry",
971
+ "950": "orange",
972
+ "951": "lemon",
973
+ "952": "fig",
974
+ "953": "pineapple, ananas",
975
+ "954": "banana",
976
+ "955": "jackfruit, jak, jack",
977
+ "956": "custard apple",
978
+ "957": "pomegranate",
979
+ "958": "hay",
980
+ "959": "carbonara",
981
+ "960": "chocolate sauce, chocolate syrup",
982
+ "961": "dough",
983
+ "962": "meat loaf, meatloaf",
984
+ "963": "pizza, pizza pie",
985
+ "964": "potpie",
986
+ "965": "burrito",
987
+ "966": "red wine",
988
+ "967": "espresso",
989
+ "968": "cup",
990
+ "969": "eggnog",
991
+ "970": "alp",
992
+ "971": "bubble",
993
+ "972": "cliff, drop, drop-off",
994
+ "973": "coral reef",
995
+ "974": "geyser",
996
+ "975": "lakeside, lakeshore",
997
+ "976": "promontory, headland, head, foreland",
998
+ "977": "sandbar, sand bar",
999
+ "978": "seashore, coast, seacoast, sea-coast",
1000
+ "979": "valley, vale",
1001
+ "980": "volcano",
1002
+ "981": "ballplayer, baseball player",
1003
+ "982": "groom, bridegroom",
1004
+ "983": "scuba diver",
1005
+ "984": "rapeseed",
1006
+ "985": "daisy",
1007
+ "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
1008
+ "987": "corn",
1009
+ "988": "acorn",
1010
+ "989": "hip, rose hip, rosehip",
1011
+ "990": "buckeye, horse chestnut, conker",
1012
+ "991": "coral fungus",
1013
+ "992": "agaric",
1014
+ "993": "gyromitra",
1015
+ "994": "stinkhorn, carrion fungus",
1016
+ "995": "earthstar",
1017
+ "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
1018
+ "997": "bolete",
1019
+ "998": "ear, spike, capitulum",
1020
+ "999": "toilet tissue, toilet paper, bathroom tissue"
1021
+ }
1022
+ }
AFM-B-2-1NFE-guided/pipeline.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: AFMPipeline.
2
+
3
+ Load with native Hugging Face diffusers and trust_remote_code=True.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ from diffusers.image_processor import VaeImageProcessor
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
16
+ from diffusers.utils.torch_utils import randn_tensor
17
+
18
+
19
+ class AFMPipeline(DiffusionPipeline):
20
+ model_cpu_offload_seq = "generator->vae"
21
+
22
+ @staticmethod
23
+ def _coerce_scheduler(scheduler, generator):
24
+ if scheduler is not None and not isinstance(scheduler, (list, tuple)):
25
+ return scheduler
26
+ variant_path = getattr(generator.config, "_name_or_path", None)
27
+ if variant_path:
28
+ scheduler_dir = Path(variant_path).resolve().parent / "scheduler"
29
+ module_path = scheduler_dir / "scheduling_continuous_flow.py"
30
+ config_path = scheduler_dir / "scheduler_config.json"
31
+ if module_path.is_file() and config_path.is_file():
32
+ spec = importlib.util.spec_from_file_location("scheduling_continuous_flow", module_path)
33
+ if spec is not None and spec.loader is not None:
34
+ module = importlib.util.module_from_spec(spec)
35
+ spec.loader.exec_module(module)
36
+ return module.ContinuousFlowMatchScheduler.from_pretrained(str(scheduler_dir))
37
+ raise ValueError("AFMPipeline could not load ContinuousFlowMatchScheduler from the variant folder.")
38
+
39
+ def __init__(
40
+ self,
41
+ generator,
42
+ vae,
43
+ scheduler=None,
44
+ pred_type: str = "x",
45
+ id2label: Optional[Dict[Union[int, str], str]] = None,
46
+ ) -> None:
47
+ super().__init__()
48
+ scheduler = self._coerce_scheduler(scheduler, generator)
49
+ self.register_modules(generator=generator, vae=vae, scheduler=scheduler)
50
+ self.register_to_config(pred_type=pred_type)
51
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
52
+ self._id2label = self._normalize_id2label(id2label)
53
+ self.labels = self._build_label2id(self._id2label)
54
+ self._labels_loaded_from_model_index = bool(self._id2label)
55
+
56
+ @staticmethod
57
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
58
+ if not id2label:
59
+ return {}
60
+ return {int(key): value for key, value in id2label.items()}
61
+
62
+ @staticmethod
63
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
64
+ if not variant_path:
65
+ return {}
66
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
67
+ if not model_index_path.exists():
68
+ return {}
69
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
70
+ id2label = raw.get("id2label")
71
+ if not isinstance(id2label, dict):
72
+ return {}
73
+ return {int(key): value for key, value in id2label.items()}
74
+
75
+ @staticmethod
76
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
77
+ label2id: Dict[str, int] = {}
78
+ for class_id, value in id2label.items():
79
+ for synonym in value.split(","):
80
+ synonym = synonym.strip()
81
+ if synonym:
82
+ label2id[synonym] = int(class_id)
83
+ return dict(sorted(label2id.items()))
84
+
85
+ @property
86
+ def vae_scale_factor(self) -> int:
87
+ block_out_channels = getattr(self.vae.config, "block_out_channels", None)
88
+ if block_out_channels:
89
+ return int(2 ** (len(block_out_channels) - 1))
90
+ return 8
91
+
92
+ @property
93
+ def id2label(self) -> Dict[int, str]:
94
+ self._ensure_labels_loaded()
95
+ return self._id2label
96
+
97
+ def _ensure_labels_loaded(self) -> None:
98
+ if self._labels_loaded_from_model_index:
99
+ return
100
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
101
+ if loaded:
102
+ self._id2label = loaded
103
+ self.labels = self._build_label2id(self._id2label)
104
+ self._labels_loaded_from_model_index = True
105
+
106
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
107
+ self._ensure_labels_loaded()
108
+ labels = [label] if isinstance(label, str) else label
109
+ if not self.labels:
110
+ raise ValueError("No id2label mapping is available in this checkpoint.")
111
+ missing = [item for item in labels if item not in self.labels]
112
+ if missing:
113
+ preview = ", ".join(list(self.labels.keys())[:8])
114
+ raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
115
+ return [self.labels[item] for item in labels]
116
+
117
+ def _normalize_class_labels(
118
+ self,
119
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
120
+ device: torch.device,
121
+ ) -> torch.LongTensor:
122
+ if torch.is_tensor(class_labels):
123
+ return class_labels.to(device=device, dtype=torch.long).reshape(-1)
124
+ if isinstance(class_labels, int):
125
+ class_label_ids = [class_labels]
126
+ elif isinstance(class_labels, str):
127
+ class_label_ids = self.get_label_ids(class_labels)
128
+ elif class_labels and isinstance(class_labels[0], str):
129
+ class_label_ids = self.get_label_ids(class_labels)
130
+ else:
131
+ class_label_ids = list(class_labels)
132
+ return torch.tensor(class_label_ids, device=device, dtype=torch.long).reshape(-1)
133
+
134
+ def _default_image_size(self) -> int:
135
+ transformer = getattr(self.generator, "transformer", None)
136
+ if transformer is not None:
137
+ return int(transformer.config.sample_size) * self.vae_scale_factor
138
+ return 256
139
+
140
+ def check_inputs(
141
+ self,
142
+ height: int,
143
+ width: int,
144
+ num_inference_steps: int,
145
+ output_type: str,
146
+ sampler: str,
147
+ ) -> None:
148
+ if num_inference_steps < 1:
149
+ raise ValueError("`num_inference_steps` must be >= 1.")
150
+ if output_type not in {"pil", "np", "pt", "latent"}:
151
+ raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
152
+ if sampler not in {"euler", "heun"}:
153
+ raise ValueError("sampler must be one of: 'euler', 'heun'.")
154
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
155
+ raise ValueError(
156
+ f"`height` and `width` must be divisible by {self.vae_scale_factor}, got ({height}, {width})."
157
+ )
158
+
159
+ def prepare_latents(
160
+ self,
161
+ batch_size: int,
162
+ height: int,
163
+ width: int,
164
+ dtype: torch.dtype,
165
+ device: torch.device,
166
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
167
+ latents: Optional[torch.Tensor] = None,
168
+ ) -> torch.Tensor:
169
+ if latents is not None:
170
+ return latents.to(device=device, dtype=dtype)
171
+ latent_height = height // self.vae_scale_factor
172
+ latent_width = width // self.vae_scale_factor
173
+ in_channels = int(getattr(self.generator, "in_channels", 4))
174
+ return randn_tensor(
175
+ (batch_size, in_channels, latent_height, latent_width),
176
+ generator=generator,
177
+ device=device,
178
+ dtype=dtype,
179
+ )
180
+
181
+ def decode_latents(self, latents: torch.Tensor, output_type: str = "pil"):
182
+ if output_type == "latent":
183
+ return latents
184
+ scaling_factor = getattr(self.vae.config, "scaling_factor", 0.18215)
185
+ image = self.vae.decode(latents / scaling_factor).sample
186
+ if output_type == "pt":
187
+ return image
188
+ return self.image_processor.postprocess(image, output_type=output_type)
189
+
190
+ def _run_denoising_loop(
191
+ self,
192
+ latents: torch.Tensor,
193
+ class_labels_tensor: torch.Tensor,
194
+ batch_size: int,
195
+ device: torch.device,
196
+ num_inference_steps: int,
197
+ sampler: str,
198
+ pred_type: str,
199
+ ) -> torch.Tensor:
200
+ self.scheduler.set_timesteps(num_inference_steps, device=device, solver=sampler)
201
+ timesteps = self.scheduler.timesteps
202
+ self.generator.eval()
203
+ for t_src, t_tgt in self.progress_bar(list(zip(timesteps[:-1], timesteps[1:]))):
204
+ t_src_batch = t_src.expand(batch_size)
205
+ t_tgt_batch = t_tgt.expand(batch_size)
206
+ outputs = self.generator(latents, class_labels_tensor, t_src_batch, t_tgt_batch)
207
+ if pred_type == "v":
208
+ if sampler == "heun":
209
+ latents_next = self.scheduler.step(
210
+ outputs, t_src, t_tgt, latents, prediction_type="v"
211
+ ).prev_sample
212
+ outputs_next = self.generator(latents_next, class_labels_tensor, t_tgt_batch, t_tgt_batch)
213
+ latents = self.scheduler.step(
214
+ outputs,
215
+ t_src,
216
+ t_tgt,
217
+ latents,
218
+ model_output_next=outputs_next,
219
+ prediction_type="v",
220
+ ).prev_sample
221
+ else:
222
+ latents = self.scheduler.step(
223
+ outputs, t_src, t_tgt, latents, prediction_type="v"
224
+ ).prev_sample
225
+ else:
226
+ latents = outputs
227
+ return latents
228
+
229
+ @torch.inference_mode()
230
+ def __call__(
231
+ self,
232
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
233
+ height: Optional[int] = None,
234
+ width: Optional[int] = None,
235
+ num_inference_steps: Optional[int] = None,
236
+ sampler: str = "euler",
237
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
238
+ latents: Optional[torch.Tensor] = None,
239
+ output_type: str = "pil",
240
+ return_dict: bool = True,
241
+ ):
242
+ default_size = self._default_image_size()
243
+ height = int(height or default_size)
244
+ width = int(width or default_size)
245
+ if num_inference_steps is None:
246
+ num_inference_steps = int(getattr(self.generator.config, "num_inference_steps", 1))
247
+ self.check_inputs(height, width, num_inference_steps, output_type, sampler)
248
+
249
+ device = getattr(self, "_execution_device", None) or next(self.generator.parameters()).device
250
+ dtype = next(self.generator.parameters()).dtype
251
+ pred_type = self.config.pred_type
252
+ class_labels_tensor = self._normalize_class_labels(class_labels, device=device)
253
+ batch_size = class_labels_tensor.shape[0]
254
+ latents = self.prepare_latents(
255
+ batch_size=batch_size,
256
+ height=height,
257
+ width=width,
258
+ dtype=dtype,
259
+ device=device,
260
+ generator=generator,
261
+ latents=latents,
262
+ )
263
+ latents = self._run_denoising_loop(
264
+ latents,
265
+ class_labels_tensor,
266
+ batch_size,
267
+ device,
268
+ num_inference_steps,
269
+ sampler,
270
+ pred_type,
271
+ )
272
+ image = self.decode_latents(latents, output_type=output_type)
273
+ self.maybe_free_model_hooks()
274
+ if not return_dict:
275
+ return (image,)
276
+ return ImagePipelineOutput(images=image)
AFM-B-2-1NFE-guided/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc ADDED
Binary file (5.38 kB). View file
 
AFM-B-2-1NFE-guided/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ContinuousFlowMatchScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "solver": "euler"
5
+ }
AFM-B-2-1NFE-guided/scheduler/scheduling_continuous_flow.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+ from diffusers.utils import BaseOutput
10
+
11
+
12
+ @dataclass
13
+ class ContinuousFlowMatchSchedulerOutput(BaseOutput):
14
+ prev_sample: torch.Tensor
15
+
16
+
17
+ class ContinuousFlowMatchScheduler(SchedulerMixin, ConfigMixin):
18
+ """Flow-matching scheduler for AFM with time in [1, 0]."""
19
+
20
+ order = 2
21
+
22
+ @register_to_config
23
+ def __init__(self, solver: str = "euler"):
24
+ if solver not in {"euler", "heun"}:
25
+ raise ValueError("solver must be one of: 'euler', 'heun'.")
26
+ self.timesteps: Optional[torch.Tensor] = None
27
+ self.num_inference_steps: Optional[int] = None
28
+ self._step_index: Optional[int] = None
29
+
30
+ @property
31
+ def init_noise_sigma(self) -> float:
32
+ return 1.0
33
+
34
+ def set_timesteps(
35
+ self,
36
+ num_inference_steps: int,
37
+ device: Union[str, torch.device, None] = None,
38
+ solver: Optional[str] = None,
39
+ ) -> None:
40
+ if num_inference_steps < 1:
41
+ raise ValueError("num_inference_steps must be >= 1.")
42
+ self.num_inference_steps = num_inference_steps
43
+ if solver == "heun":
44
+ grid_size = (num_inference_steps // 2) + 1
45
+ else:
46
+ grid_size = num_inference_steps + 1
47
+ self.timesteps = torch.linspace(1.0, 0.0, grid_size, device=device, dtype=torch.float32)
48
+ self._step_index = 0
49
+ if solver is not None:
50
+ self.register_to_config(solver=solver)
51
+
52
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
53
+ del timestep
54
+ return sample
55
+
56
+ def _resolve_step_index(self, timestep: Union[float, torch.Tensor, None]) -> int:
57
+ if self._step_index is not None:
58
+ return self._step_index
59
+ if self.timesteps is None:
60
+ raise ValueError("Call `set_timesteps` before `step`.")
61
+ if timestep is None:
62
+ return 0
63
+ t_value = float(timestep) if not isinstance(timestep, torch.Tensor) else float(timestep.flatten()[0])
64
+ matches = (self.timesteps - t_value).abs() < 1e-6
65
+ if matches.any():
66
+ return int(matches.nonzero(as_tuple=False)[0].item())
67
+ return 0
68
+
69
+ def step(
70
+ self,
71
+ model_output: torch.Tensor,
72
+ timestep_src: Union[float, torch.Tensor],
73
+ timestep_tgt: Union[float, torch.Tensor],
74
+ sample: torch.Tensor,
75
+ model_output_next: Optional[torch.Tensor] = None,
76
+ prediction_type: str = "v",
77
+ return_dict: bool = True,
78
+ ) -> Union[ContinuousFlowMatchSchedulerOutput, Tuple[torch.Tensor]]:
79
+ if prediction_type == "x":
80
+ prev_sample = model_output
81
+ else:
82
+ t_src = torch.as_tensor(timestep_src, device=sample.device, dtype=sample.dtype)
83
+ t_tgt = torch.as_tensor(timestep_tgt, device=sample.device, dtype=sample.dtype)
84
+ while t_src.ndim < sample.ndim:
85
+ t_src = t_src.unsqueeze(-1)
86
+ t_tgt = t_tgt.unsqueeze(-1)
87
+ dt = t_src - t_tgt
88
+ if self.config.solver == "heun" and model_output_next is not None:
89
+ prev_sample = sample - dt * 0.5 * (model_output + model_output_next)
90
+ else:
91
+ prev_sample = sample - dt * model_output
92
+
93
+ step_index = self._resolve_step_index(timestep_src)
94
+ self._step_index = step_index + 1
95
+
96
+ if not return_dict:
97
+ return (prev_sample,)
98
+ return ContinuousFlowMatchSchedulerOutput(prev_sample=prev_sample)
AFM-B-2-1NFE-guided/vae/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.36.0",
4
+ "_name_or_path": "stabilityai/sd-vae-ft-mse",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "latents_mean": null,
22
+ "latents_std": null,
23
+ "layers_per_block": 2,
24
+ "mid_block_add_attention": true,
25
+ "norm_num_groups": 32,
26
+ "out_channels": 3,
27
+ "sample_size": 256,
28
+ "scaling_factor": 0.18215,
29
+ "shift_factor": null,
30
+ "up_block_types": [
31
+ "UpDecoderBlock2D",
32
+ "UpDecoderBlock2D",
33
+ "UpDecoderBlock2D",
34
+ "UpDecoderBlock2D"
35
+ ],
36
+ "use_post_quant_conv": true,
37
+ "use_quant_conv": true
38
+ }
AFM-B-2-1NFE-guided/vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d993488569e928462932c8c38a0760b874d166399b14414135bd9c42df5815
3
+ size 334643276
AFM-B-2-1NFE-noguide/demo.png ADDED

Git LFS Details

  • SHA256: 0bfabcede55121fac1b540e5ef9807e29fd9e74572799c361313ed373cde8f25
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
AFM-B-2-1NFE-noguide/generator/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AFMGenerator2DModel",
3
+ "_diffusers_version": "0.36.0",
4
+ "model_type": "AFM-B/2",
5
+ "architecture": "standard",
6
+ "repeat": 1,
7
+ "use_t_src": false,
8
+ "use_t_tgt": false,
9
+ "pred_type": "x",
10
+ "num_inference_steps": 1,
11
+ "learn_sigma": false,
12
+ "class_dropout_prob": 0.0,
13
+ "input_size": 32,
14
+ "num_classes": 1000,
15
+ "in_channels": 4,
16
+ "depth": 12,
17
+ "hidden_size": 768,
18
+ "patch_size": 2,
19
+ "num_heads": 12
20
+ }
AFM-B-2-1NFE-noguide/generator/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb5297181aebfeb15fd7bf69781c80a2ae15aef5c24a2479991cba2fd17ba14d
3
+ size 589740400
AFM-B-2-1NFE-noguide/generator/modeling_afm.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained AFM generator for Hugging Face diffusers checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Dict, Optional
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from torch import nn
14
+
15
+
16
+ def get_dit_transformer_class():
17
+ from diffusers.models.transformers.dit_transformer_2d import DiTTransformer2DModel
18
+
19
+ return DiTTransformer2DModel
20
+
21
+
22
+ def build_dit_config(
23
+ *,
24
+ depth: int = 28,
25
+ hidden_size: int = 1152,
26
+ patch_size: int = 2,
27
+ num_heads: int = 16,
28
+ learn_sigma: bool = False,
29
+ class_dropout_prob: float = 0.0,
30
+ input_size: int = 32,
31
+ num_classes: int = 1000,
32
+ in_channels: int = 4,
33
+ ) -> Dict[str, Any]:
34
+ attention_head_dim = hidden_size // num_heads
35
+ num_embeds_ada_norm = num_classes + (1 if class_dropout_prob > 0 else 0)
36
+ out_channels = in_channels * 2 if learn_sigma else in_channels
37
+ return {
38
+ "sample_size": input_size,
39
+ "num_layers": depth,
40
+ "num_attention_heads": num_heads,
41
+ "attention_head_dim": attention_head_dim,
42
+ "in_channels": in_channels,
43
+ "out_channels": out_channels,
44
+ "patch_size": patch_size,
45
+ "attention_bias": True,
46
+ "activation_fn": "gelu-approximate",
47
+ "num_embeds_ada_norm": num_embeds_ada_norm,
48
+ "norm_type": "ada_norm_zero",
49
+ "norm_elementwise_affine": False,
50
+ "dropout": 0.0,
51
+ "norm_num_groups": 32,
52
+ "norm_eps": 1e-5,
53
+ "upcast_attention": False,
54
+ }
55
+
56
+
57
+ def _convert_legacy_dit_state_dict(state_dict: Dict[str, torch.Tensor], depth: int) -> Dict[str, torch.Tensor]:
58
+ converted = copy.deepcopy(state_dict)
59
+
60
+ converted["pos_embed.proj.weight"] = converted.pop("x_embedder.proj.weight").clone().contiguous()
61
+ converted["pos_embed.proj.bias"] = converted.pop("x_embedder.proj.bias").clone().contiguous()
62
+
63
+ if "t_embedder.mlp.0.weight" in converted:
64
+ timestep_weights = {
65
+ "linear_1.weight": converted.pop("t_embedder.mlp.0.weight"),
66
+ "linear_1.bias": converted.pop("t_embedder.mlp.0.bias"),
67
+ "linear_2.weight": converted.pop("t_embedder.mlp.2.weight"),
68
+ "linear_2.bias": converted.pop("t_embedder.mlp.2.bias"),
69
+ }
70
+ else:
71
+ timestep_weights = None
72
+ class_embedding = converted.pop("y_embedder.embedding_table.weight")
73
+ if class_embedding.shape[0] == 1000:
74
+ null_class = torch.zeros(1, class_embedding.shape[1], dtype=class_embedding.dtype)
75
+ class_embedding = torch.cat([class_embedding, null_class], dim=0)
76
+
77
+ for block_idx in range(depth):
78
+ if timestep_weights is not None:
79
+ for key, tensor in timestep_weights.items():
80
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.timestep_embedder.{key}"] = tensor.clone()
81
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.class_embedder.embedding_table.weight"] = (
82
+ class_embedding.clone()
83
+ )
84
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.weight"] = converted[
85
+ f"blocks.{block_idx}.adaLN_modulation.1.weight"
86
+ ]
87
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.bias"] = converted[
88
+ f"blocks.{block_idx}.adaLN_modulation.1.bias"
89
+ ]
90
+
91
+ q, k, v = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.weight"], 3, dim=0)
92
+ q_bias, k_bias, v_bias = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.bias"], 3, dim=0)
93
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.weight"] = q
94
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.bias"] = q_bias
95
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.weight"] = k
96
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.bias"] = k_bias
97
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.weight"] = v
98
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.bias"] = v_bias
99
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.weight"] = converted[
100
+ f"blocks.{block_idx}.attn.proj.weight"
101
+ ]
102
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.bias"] = converted[
103
+ f"blocks.{block_idx}.attn.proj.bias"
104
+ ]
105
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.weight"] = converted[
106
+ f"blocks.{block_idx}.mlp.fc1.weight"
107
+ ]
108
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.bias"] = converted[
109
+ f"blocks.{block_idx}.mlp.fc1.bias"
110
+ ]
111
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.weight"] = converted[
112
+ f"blocks.{block_idx}.mlp.fc2.weight"
113
+ ]
114
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.bias"] = converted[
115
+ f"blocks.{block_idx}.mlp.fc2.bias"
116
+ ]
117
+
118
+ for suffix in (
119
+ "attn.qkv.weight",
120
+ "attn.qkv.bias",
121
+ "attn.proj.weight",
122
+ "attn.proj.bias",
123
+ "mlp.fc1.weight",
124
+ "mlp.fc1.bias",
125
+ "mlp.fc2.weight",
126
+ "mlp.fc2.bias",
127
+ "adaLN_modulation.1.weight",
128
+ "adaLN_modulation.1.bias",
129
+ ):
130
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
131
+
132
+ converted["proj_out_1.weight"] = converted.pop("final_layer.adaLN_modulation.1.weight")
133
+ converted["proj_out_1.bias"] = converted.pop("final_layer.adaLN_modulation.1.bias")
134
+ converted["proj_out_2.weight"] = converted.pop("final_layer.linear.weight")
135
+ converted["proj_out_2.bias"] = converted.pop("final_layer.linear.bias")
136
+
137
+ converted.pop("pos_embed", None)
138
+ for block_idx in range(depth):
139
+ for suffix in ("norm1.weight", "norm1.bias", "norm2.weight", "norm2.bias"):
140
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
141
+
142
+ return {key: tensor.detach().clone().contiguous() for key, tensor in converted.items()}
143
+
144
+
145
+ def load_legacy_dit_state_dict(
146
+ state_dict: Dict[str, torch.Tensor],
147
+ depth: int,
148
+ patch_size: int,
149
+ hidden_size: int,
150
+ num_heads: int,
151
+ ) -> Dict[str, torch.Tensor]:
152
+ if "transformer_blocks.0.attn1.to_q.weight" in state_dict:
153
+ return state_dict
154
+ if any(key.startswith("blocks.") for key in state_dict):
155
+ return _convert_legacy_dit_state_dict(state_dict, depth)
156
+ return state_dict
157
+
158
+
159
+ def forward_dit_output(
160
+ transformer,
161
+ hidden_states: torch.Tensor,
162
+ timestep: Optional[torch.Tensor],
163
+ class_labels: torch.Tensor,
164
+ extra_cond: Optional[torch.Tensor] = None,
165
+ ) -> torch.Tensor:
166
+ hidden_states = transformer.pos_embed(hidden_states)
167
+
168
+ for block in transformer.transformer_blocks:
169
+ if torch.is_grad_enabled() and transformer.gradient_checkpointing:
170
+ hidden_states = transformer._gradient_checkpointing_func(
171
+ block,
172
+ hidden_states,
173
+ None,
174
+ None,
175
+ None,
176
+ timestep,
177
+ None,
178
+ class_labels,
179
+ )
180
+ else:
181
+ hidden_states = block(
182
+ hidden_states,
183
+ attention_mask=None,
184
+ encoder_hidden_states=None,
185
+ encoder_attention_mask=None,
186
+ timestep=timestep,
187
+ cross_attention_kwargs=None,
188
+ class_labels=class_labels,
189
+ )
190
+
191
+ conditioning = transformer.transformer_blocks[0].norm1.emb(
192
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
193
+ )
194
+ if extra_cond is not None:
195
+ conditioning = conditioning + extra_cond
196
+ shift, scale = transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
197
+ hidden_states = transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
198
+ hidden_states = transformer.proj_out_2(hidden_states)
199
+
200
+ height = width = int(hidden_states.shape[1] ** 0.5)
201
+ hidden_states = hidden_states.reshape(
202
+ shape=(-1, height, width, transformer.patch_size, transformer.patch_size, transformer.out_channels)
203
+ )
204
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
205
+ return hidden_states.reshape(
206
+ shape=(-1, transformer.out_channels, height * transformer.patch_size, width * transformer.patch_size)
207
+ )
208
+
209
+
210
+ def remap_transformer_state_dict(
211
+ state_dict: Dict[str, torch.Tensor],
212
+ legacy_kwargs: Dict[str, int],
213
+ extra_prefixes: tuple[str, ...] = (),
214
+ ) -> Dict[str, torch.Tensor]:
215
+ state_dict = load_legacy_dit_state_dict(state_dict, **legacy_kwargs)
216
+ remapped: Dict[str, torch.Tensor] = {}
217
+ for key, value in state_dict.items():
218
+ if any(key.startswith(prefix) for prefix in extra_prefixes):
219
+ remapped[key] = value
220
+ elif key.startswith("transformer."):
221
+ remapped[key] = value
222
+ else:
223
+ remapped[f"transformer.{key}"] = value
224
+ return remapped
225
+
226
+
227
+ def split_output_channels(output: torch.Tensor, in_channels: int) -> torch.Tensor:
228
+ if output.shape[1] == in_channels:
229
+ return output
230
+ output, _ = output.chunk(2, dim=1)
231
+ return output
232
+
233
+
234
+ class TimestepEmbedder(nn.Module):
235
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
236
+ super().__init__()
237
+ self.mlp = nn.Sequential(
238
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
239
+ nn.SiLU(),
240
+ nn.Linear(hidden_size, hidden_size, bias=True),
241
+ )
242
+ self.frequency_embedding_size = frequency_embedding_size
243
+
244
+ @staticmethod
245
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
246
+ half = dim // 2
247
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
248
+ device=t.device
249
+ )
250
+ args = t[:, None].float() * freqs[None]
251
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
252
+ if dim % 2:
253
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
254
+ return embedding
255
+
256
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
257
+ emb = self.timestep_embedding(t.float(), self.frequency_embedding_size)
258
+ weight_dtype = self.mlp[0].weight.dtype
259
+ return self.mlp(emb.to(dtype=weight_dtype))
260
+
261
+
262
+ class Generator(nn.Module):
263
+ def __init__(
264
+ self,
265
+ *,
266
+ use_t_src: bool = False,
267
+ use_t_tgt: bool = False,
268
+ depth: int = 28,
269
+ hidden_size: int = 1152,
270
+ patch_size: int = 2,
271
+ num_heads: int = 16,
272
+ learn_sigma: bool = False,
273
+ class_dropout_prob: float = 0.0,
274
+ input_size: int = 32,
275
+ num_classes: int = 1000,
276
+ in_channels: int = 4,
277
+ **_,
278
+ ):
279
+ super().__init__()
280
+ self.use_t_src = use_t_src
281
+ self.use_t_tgt = use_t_tgt
282
+ self._legacy_kwargs = {
283
+ "depth": depth,
284
+ "hidden_size": hidden_size,
285
+ "patch_size": patch_size,
286
+ "num_heads": num_heads,
287
+ }
288
+ dit_cls = get_dit_transformer_class()
289
+ self.transformer = dit_cls(
290
+ **build_dit_config(
291
+ depth=depth,
292
+ hidden_size=hidden_size,
293
+ patch_size=patch_size,
294
+ num_heads=num_heads,
295
+ learn_sigma=learn_sigma,
296
+ class_dropout_prob=class_dropout_prob,
297
+ input_size=input_size,
298
+ num_classes=num_classes,
299
+ in_channels=in_channels,
300
+ )
301
+ )
302
+ self.in_channels = in_channels
303
+ if use_t_tgt:
304
+ self.t_tgt_embedder = TimestepEmbedder(hidden_size)
305
+ nn.init.normal_(self.t_tgt_embedder.mlp[0].weight, std=0.02)
306
+ nn.init.normal_(self.t_tgt_embedder.mlp[2].weight, std=0.02)
307
+
308
+ def load_state_dict(self, state_dict, strict: bool = True):
309
+ extra = ("t_tgt_embedder.",)
310
+ has_extra = any(key.startswith(extra) for key in state_dict)
311
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
312
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs, extra_prefixes=extra)
313
+ if self.use_t_tgt and not has_extra:
314
+ strict = False
315
+ if not has_t_embedder:
316
+ strict = False
317
+ out = super().load_state_dict(remapped, strict=strict)
318
+ if not has_t_embedder:
319
+ for name, param in self.named_parameters():
320
+ if "timestep_embedder" in name:
321
+ param.data.zero_()
322
+ return out
323
+
324
+ def forward(self, x, y, t_src=None, t_tgt=None):
325
+ if self.use_t_src and t_src is not None:
326
+ timestep = (t_src * 1000).long()
327
+ else:
328
+ timestep = torch.zeros(x.shape[0], device=x.device, dtype=torch.long)
329
+
330
+ extra_cond = None
331
+ if self.use_t_tgt and t_tgt is not None:
332
+ extra_cond = self.t_tgt_embedder(t_tgt * 1000)
333
+
334
+ output = forward_dit_output(self.transformer, x, timestep, y, extra_cond=extra_cond)
335
+ return split_output_channels(output, self.in_channels)
336
+
337
+
338
+ class GeneratorDeep(nn.Module):
339
+ def __init__(
340
+ self,
341
+ *,
342
+ repeat: int,
343
+ depth: int = 28,
344
+ hidden_size: int = 1152,
345
+ patch_size: int = 2,
346
+ num_heads: int = 16,
347
+ learn_sigma: bool = False,
348
+ class_dropout_prob: float = 0.0,
349
+ input_size: int = 32,
350
+ num_classes: int = 1000,
351
+ in_channels: int = 4,
352
+ **_,
353
+ ):
354
+ super().__init__()
355
+ self.repeat = repeat
356
+ self._legacy_kwargs = {
357
+ "depth": depth,
358
+ "hidden_size": hidden_size,
359
+ "patch_size": patch_size,
360
+ "num_heads": num_heads,
361
+ }
362
+ dit_cls = get_dit_transformer_class()
363
+ self.transformer = dit_cls(
364
+ **build_dit_config(
365
+ depth=depth,
366
+ hidden_size=hidden_size,
367
+ patch_size=patch_size,
368
+ num_heads=num_heads,
369
+ learn_sigma=learn_sigma,
370
+ class_dropout_prob=class_dropout_prob,
371
+ input_size=input_size,
372
+ num_classes=num_classes,
373
+ in_channels=in_channels,
374
+ )
375
+ )
376
+ self.in_channels = in_channels
377
+
378
+ def load_state_dict(self, state_dict, strict: bool = True):
379
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs)
380
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
381
+ if not has_t_embedder:
382
+ strict = False
383
+ out = super().load_state_dict(remapped, strict=strict)
384
+ if not has_t_embedder:
385
+ for name, param in self.named_parameters():
386
+ if "timestep_embedder" in name:
387
+ param.data.zero_()
388
+ return out
389
+
390
+ def forward(self, x, y, *args, **kwargs):
391
+ hidden_states = self.transformer.pos_embed(x)
392
+ for t in torch.arange(1, 0, -1 / self.repeat).tolist():
393
+ timestep = torch.full([x.shape[0]], int(t * 1000), device=x.device, dtype=torch.long)
394
+ for block in self.transformer.transformer_blocks:
395
+ hidden_states = block(
396
+ hidden_states,
397
+ attention_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ timestep=timestep,
401
+ cross_attention_kwargs=None,
402
+ class_labels=y,
403
+ )
404
+
405
+ conditioning = self.transformer.transformer_blocks[0].norm1.emb(
406
+ torch.zeros(x.shape[0], device=x.device, dtype=torch.long),
407
+ y,
408
+ hidden_dtype=hidden_states.dtype,
409
+ )
410
+ shift, scale = self.transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
411
+ hidden_states = self.transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
412
+ hidden_states = self.transformer.proj_out_2(hidden_states)
413
+
414
+ height = width = int(hidden_states.shape[1] ** 0.5)
415
+ hidden_states = hidden_states.reshape(
416
+ shape=(
417
+ -1,
418
+ height,
419
+ width,
420
+ self.transformer.patch_size,
421
+ self.transformer.patch_size,
422
+ self.transformer.out_channels,
423
+ )
424
+ )
425
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
426
+ output = hidden_states.reshape(
427
+ shape=(-1, self.transformer.out_channels, height * self.transformer.patch_size, width * self.transformer.patch_size)
428
+ )
429
+ return split_output_channels(output, self.in_channels)
430
+
431
+
432
+ class AFMGenerator2DModel(Generator, ModelMixin, ConfigMixin):
433
+ config_name = "config.json"
434
+
435
+ @register_to_config
436
+ def __init__(
437
+ self,
438
+ model_type: str = "AFM-XL/2",
439
+ architecture: str = "standard",
440
+ repeat: int = 1,
441
+ use_t_src: bool = False,
442
+ use_t_tgt: bool = False,
443
+ depth: int = 28,
444
+ hidden_size: int = 1152,
445
+ patch_size: int = 2,
446
+ num_heads: int = 16,
447
+ learn_sigma: bool = False,
448
+ class_dropout_prob: float = 0.0,
449
+ input_size: int = 32,
450
+ num_classes: int = 1000,
451
+ in_channels: int = 4,
452
+ pred_type: str = "x",
453
+ num_inference_steps: int = 1,
454
+ ) -> None:
455
+ if architecture == "deep":
456
+ raise ValueError("Use AFMGeneratorDeep2DModel for deep AFM checkpoints.")
457
+ Generator.__init__(
458
+ self,
459
+ use_t_src=use_t_src,
460
+ use_t_tgt=use_t_tgt,
461
+ depth=depth,
462
+ hidden_size=hidden_size,
463
+ patch_size=patch_size,
464
+ num_heads=num_heads,
465
+ learn_sigma=learn_sigma,
466
+ class_dropout_prob=class_dropout_prob,
467
+ input_size=input_size,
468
+ num_classes=num_classes,
469
+ in_channels=in_channels,
470
+ )
471
+
472
+
473
+ class AFMGeneratorDeep2DModel(GeneratorDeep, ModelMixin, ConfigMixin):
474
+ config_name = "config.json"
475
+
476
+ @register_to_config
477
+ def __init__(
478
+ self,
479
+ model_type: str = "AFM-XL/2",
480
+ architecture: str = "deep",
481
+ repeat: int = 2,
482
+ use_t_src: bool = False,
483
+ use_t_tgt: bool = False,
484
+ depth: int = 28,
485
+ hidden_size: int = 1152,
486
+ patch_size: int = 2,
487
+ num_heads: int = 16,
488
+ learn_sigma: bool = False,
489
+ class_dropout_prob: float = 0.0,
490
+ input_size: int = 32,
491
+ num_classes: int = 1000,
492
+ in_channels: int = 4,
493
+ pred_type: str = "x",
494
+ num_inference_steps: int = 1,
495
+ ) -> None:
496
+ GeneratorDeep.__init__(
497
+ self,
498
+ repeat=repeat,
499
+ depth=depth,
500
+ hidden_size=hidden_size,
501
+ patch_size=patch_size,
502
+ num_heads=num_heads,
503
+ learn_sigma=learn_sigma,
504
+ class_dropout_prob=class_dropout_prob,
505
+ input_size=input_size,
506
+ num_classes=num_classes,
507
+ in_channels=in_channels,
508
+ )
509
+
510
+
511
+ __all__ = ["AFMGenerator2DModel", "AFMGeneratorDeep2DModel"]
AFM-B-2-1NFE-noguide/model_index.json ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "AFMPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "generator": [
8
+ "modeling_afm",
9
+ "AFMGenerator2DModel"
10
+ ],
11
+ "vae": [
12
+ "diffusers",
13
+ "AutoencoderKL"
14
+ ],
15
+ "scheduler": [
16
+ "scheduling_continuous_flow",
17
+ "ContinuousFlowMatchScheduler"
18
+ ],
19
+ "pred_type": "x",
20
+ "id2label": {
21
+ "0": "tench, Tinca tinca",
22
+ "1": "goldfish, Carassius auratus",
23
+ "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
24
+ "3": "tiger shark, Galeocerdo cuvieri",
25
+ "4": "hammerhead, hammerhead shark",
26
+ "5": "electric ray, crampfish, numbfish, torpedo",
27
+ "6": "stingray",
28
+ "7": "cock",
29
+ "8": "hen",
30
+ "9": "ostrich, Struthio camelus",
31
+ "10": "brambling, Fringilla montifringilla",
32
+ "11": "goldfinch, Carduelis carduelis",
33
+ "12": "house finch, linnet, Carpodacus mexicanus",
34
+ "13": "junco, snowbird",
35
+ "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
36
+ "15": "robin, American robin, Turdus migratorius",
37
+ "16": "bulbul",
38
+ "17": "jay",
39
+ "18": "magpie",
40
+ "19": "chickadee",
41
+ "20": "water ouzel, dipper",
42
+ "21": "kite",
43
+ "22": "bald eagle, American eagle, Haliaeetus leucocephalus",
44
+ "23": "vulture",
45
+ "24": "great grey owl, great gray owl, Strix nebulosa",
46
+ "25": "European fire salamander, Salamandra salamandra",
47
+ "26": "common newt, Triturus vulgaris",
48
+ "27": "eft",
49
+ "28": "spotted salamander, Ambystoma maculatum",
50
+ "29": "axolotl, mud puppy, Ambystoma mexicanum",
51
+ "30": "bullfrog, Rana catesbeiana",
52
+ "31": "tree frog, tree-frog",
53
+ "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
54
+ "33": "loggerhead, loggerhead turtle, Caretta caretta",
55
+ "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
56
+ "35": "mud turtle",
57
+ "36": "terrapin",
58
+ "37": "box turtle, box tortoise",
59
+ "38": "banded gecko",
60
+ "39": "common iguana, iguana, Iguana iguana",
61
+ "40": "American chameleon, anole, Anolis carolinensis",
62
+ "41": "whiptail, whiptail lizard",
63
+ "42": "agama",
64
+ "43": "frilled lizard, Chlamydosaurus kingi",
65
+ "44": "alligator lizard",
66
+ "45": "Gila monster, Heloderma suspectum",
67
+ "46": "green lizard, Lacerta viridis",
68
+ "47": "African chameleon, Chamaeleo chamaeleon",
69
+ "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
70
+ "49": "African crocodile, Nile crocodile, Crocodylus niloticus",
71
+ "50": "American alligator, Alligator mississipiensis",
72
+ "51": "triceratops",
73
+ "52": "thunder snake, worm snake, Carphophis amoenus",
74
+ "53": "ringneck snake, ring-necked snake, ring snake",
75
+ "54": "hognose snake, puff adder, sand viper",
76
+ "55": "green snake, grass snake",
77
+ "56": "king snake, kingsnake",
78
+ "57": "garter snake, grass snake",
79
+ "58": "water snake",
80
+ "59": "vine snake",
81
+ "60": "night snake, Hypsiglena torquata",
82
+ "61": "boa constrictor, Constrictor constrictor",
83
+ "62": "rock python, rock snake, Python sebae",
84
+ "63": "Indian cobra, Naja naja",
85
+ "64": "green mamba",
86
+ "65": "sea snake",
87
+ "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
88
+ "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
89
+ "68": "sidewinder, horned rattlesnake, Crotalus cerastes",
90
+ "69": "trilobite",
91
+ "70": "harvestman, daddy longlegs, Phalangium opilio",
92
+ "71": "scorpion",
93
+ "72": "black and gold garden spider, Argiope aurantia",
94
+ "73": "barn spider, Araneus cavaticus",
95
+ "74": "garden spider, Aranea diademata",
96
+ "75": "black widow, Latrodectus mactans",
97
+ "76": "tarantula",
98
+ "77": "wolf spider, hunting spider",
99
+ "78": "tick",
100
+ "79": "centipede",
101
+ "80": "black grouse",
102
+ "81": "ptarmigan",
103
+ "82": "ruffed grouse, partridge, Bonasa umbellus",
104
+ "83": "prairie chicken, prairie grouse, prairie fowl",
105
+ "84": "peacock",
106
+ "85": "quail",
107
+ "86": "partridge",
108
+ "87": "African grey, African gray, Psittacus erithacus",
109
+ "88": "macaw",
110
+ "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
111
+ "90": "lorikeet",
112
+ "91": "coucal",
113
+ "92": "bee eater",
114
+ "93": "hornbill",
115
+ "94": "hummingbird",
116
+ "95": "jacamar",
117
+ "96": "toucan",
118
+ "97": "drake",
119
+ "98": "red-breasted merganser, Mergus serrator",
120
+ "99": "goose",
121
+ "100": "black swan, Cygnus atratus",
122
+ "101": "tusker",
123
+ "102": "echidna, spiny anteater, anteater",
124
+ "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
125
+ "104": "wallaby, brush kangaroo",
126
+ "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
127
+ "106": "wombat",
128
+ "107": "jellyfish",
129
+ "108": "sea anemone, anemone",
130
+ "109": "brain coral",
131
+ "110": "flatworm, platyhelminth",
132
+ "111": "nematode, nematode worm, roundworm",
133
+ "112": "conch",
134
+ "113": "snail",
135
+ "114": "slug",
136
+ "115": "sea slug, nudibranch",
137
+ "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
138
+ "117": "chambered nautilus, pearly nautilus, nautilus",
139
+ "118": "Dungeness crab, Cancer magister",
140
+ "119": "rock crab, Cancer irroratus",
141
+ "120": "fiddler crab",
142
+ "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
143
+ "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
144
+ "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
145
+ "124": "crayfish, crawfish, crawdad, crawdaddy",
146
+ "125": "hermit crab",
147
+ "126": "isopod",
148
+ "127": "white stork, Ciconia ciconia",
149
+ "128": "black stork, Ciconia nigra",
150
+ "129": "spoonbill",
151
+ "130": "flamingo",
152
+ "131": "little blue heron, Egretta caerulea",
153
+ "132": "American egret, great white heron, Egretta albus",
154
+ "133": "bittern",
155
+ "134": "crane",
156
+ "135": "limpkin, Aramus pictus",
157
+ "136": "European gallinule, Porphyrio porphyrio",
158
+ "137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
159
+ "138": "bustard",
160
+ "139": "ruddy turnstone, Arenaria interpres",
161
+ "140": "red-backed sandpiper, dunlin, Erolia alpina",
162
+ "141": "redshank, Tringa totanus",
163
+ "142": "dowitcher",
164
+ "143": "oystercatcher, oyster catcher",
165
+ "144": "pelican",
166
+ "145": "king penguin, Aptenodytes patagonica",
167
+ "146": "albatross, mollymawk",
168
+ "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
169
+ "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
170
+ "149": "dugong, Dugong dugon",
171
+ "150": "sea lion",
172
+ "151": "Chihuahua",
173
+ "152": "Japanese spaniel",
174
+ "153": "Maltese dog, Maltese terrier, Maltese",
175
+ "154": "Pekinese, Pekingese, Peke",
176
+ "155": "Shih-Tzu",
177
+ "156": "Blenheim spaniel",
178
+ "157": "papillon",
179
+ "158": "toy terrier",
180
+ "159": "Rhodesian ridgeback",
181
+ "160": "Afghan hound, Afghan",
182
+ "161": "basset, basset hound",
183
+ "162": "beagle",
184
+ "163": "bloodhound, sleuthhound",
185
+ "164": "bluetick",
186
+ "165": "black-and-tan coonhound",
187
+ "166": "Walker hound, Walker foxhound",
188
+ "167": "English foxhound",
189
+ "168": "redbone",
190
+ "169": "borzoi, Russian wolfhound",
191
+ "170": "Irish wolfhound",
192
+ "171": "Italian greyhound",
193
+ "172": "whippet",
194
+ "173": "Ibizan hound, Ibizan Podenco",
195
+ "174": "Norwegian elkhound, elkhound",
196
+ "175": "otterhound, otter hound",
197
+ "176": "Saluki, gazelle hound",
198
+ "177": "Scottish deerhound, deerhound",
199
+ "178": "Weimaraner",
200
+ "179": "Staffordshire bullterrier, Staffordshire bull terrier",
201
+ "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
202
+ "181": "Bedlington terrier",
203
+ "182": "Border terrier",
204
+ "183": "Kerry blue terrier",
205
+ "184": "Irish terrier",
206
+ "185": "Norfolk terrier",
207
+ "186": "Norwich terrier",
208
+ "187": "Yorkshire terrier",
209
+ "188": "wire-haired fox terrier",
210
+ "189": "Lakeland terrier",
211
+ "190": "Sealyham terrier, Sealyham",
212
+ "191": "Airedale, Airedale terrier",
213
+ "192": "cairn, cairn terrier",
214
+ "193": "Australian terrier",
215
+ "194": "Dandie Dinmont, Dandie Dinmont terrier",
216
+ "195": "Boston bull, Boston terrier",
217
+ "196": "miniature schnauzer",
218
+ "197": "giant schnauzer",
219
+ "198": "standard schnauzer",
220
+ "199": "Scotch terrier, Scottish terrier, Scottie",
221
+ "200": "Tibetan terrier, chrysanthemum dog",
222
+ "201": "silky terrier, Sydney silky",
223
+ "202": "soft-coated wheaten terrier",
224
+ "203": "West Highland white terrier",
225
+ "204": "Lhasa, Lhasa apso",
226
+ "205": "flat-coated retriever",
227
+ "206": "curly-coated retriever",
228
+ "207": "golden retriever",
229
+ "208": "Labrador retriever",
230
+ "209": "Chesapeake Bay retriever",
231
+ "210": "German short-haired pointer",
232
+ "211": "vizsla, Hungarian pointer",
233
+ "212": "English setter",
234
+ "213": "Irish setter, red setter",
235
+ "214": "Gordon setter",
236
+ "215": "Brittany spaniel",
237
+ "216": "clumber, clumber spaniel",
238
+ "217": "English springer, English springer spaniel",
239
+ "218": "Welsh springer spaniel",
240
+ "219": "cocker spaniel, English cocker spaniel, cocker",
241
+ "220": "Sussex spaniel",
242
+ "221": "Irish water spaniel",
243
+ "222": "kuvasz",
244
+ "223": "schipperke",
245
+ "224": "groenendael",
246
+ "225": "malinois",
247
+ "226": "briard",
248
+ "227": "kelpie",
249
+ "228": "komondor",
250
+ "229": "Old English sheepdog, bobtail",
251
+ "230": "Shetland sheepdog, Shetland sheep dog, Shetland",
252
+ "231": "collie",
253
+ "232": "Border collie",
254
+ "233": "Bouvier des Flandres, Bouviers des Flandres",
255
+ "234": "Rottweiler",
256
+ "235": "German shepherd, German shepherd dog, German police dog, alsatian",
257
+ "236": "Doberman, Doberman pinscher",
258
+ "237": "miniature pinscher",
259
+ "238": "Greater Swiss Mountain dog",
260
+ "239": "Bernese mountain dog",
261
+ "240": "Appenzeller",
262
+ "241": "EntleBucher",
263
+ "242": "boxer",
264
+ "243": "bull mastiff",
265
+ "244": "Tibetan mastiff",
266
+ "245": "French bulldog",
267
+ "246": "Great Dane",
268
+ "247": "Saint Bernard, St Bernard",
269
+ "248": "Eskimo dog, husky",
270
+ "249": "malamute, malemute, Alaskan malamute",
271
+ "250": "Siberian husky",
272
+ "251": "dalmatian, coach dog, carriage dog",
273
+ "252": "affenpinscher, monkey pinscher, monkey dog",
274
+ "253": "basenji",
275
+ "254": "pug, pug-dog",
276
+ "255": "Leonberg",
277
+ "256": "Newfoundland, Newfoundland dog",
278
+ "257": "Great Pyrenees",
279
+ "258": "Samoyed, Samoyede",
280
+ "259": "Pomeranian",
281
+ "260": "chow, chow chow",
282
+ "261": "keeshond",
283
+ "262": "Brabancon griffon",
284
+ "263": "Pembroke, Pembroke Welsh corgi",
285
+ "264": "Cardigan, Cardigan Welsh corgi",
286
+ "265": "toy poodle",
287
+ "266": "miniature poodle",
288
+ "267": "standard poodle",
289
+ "268": "Mexican hairless",
290
+ "269": "timber wolf, grey wolf, gray wolf, Canis lupus",
291
+ "270": "white wolf, Arctic wolf, Canis lupus tundrarum",
292
+ "271": "red wolf, maned wolf, Canis rufus, Canis niger",
293
+ "272": "coyote, prairie wolf, brush wolf, Canis latrans",
294
+ "273": "dingo, warrigal, warragal, Canis dingo",
295
+ "274": "dhole, Cuon alpinus",
296
+ "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
297
+ "276": "hyena, hyaena",
298
+ "277": "red fox, Vulpes vulpes",
299
+ "278": "kit fox, Vulpes macrotis",
300
+ "279": "Arctic fox, white fox, Alopex lagopus",
301
+ "280": "grey fox, gray fox, Urocyon cinereoargenteus",
302
+ "281": "tabby, tabby cat",
303
+ "282": "tiger cat",
304
+ "283": "Persian cat",
305
+ "284": "Siamese cat, Siamese",
306
+ "285": "Egyptian cat",
307
+ "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
308
+ "287": "lynx, catamount",
309
+ "288": "leopard, Panthera pardus",
310
+ "289": "snow leopard, ounce, Panthera uncia",
311
+ "290": "jaguar, panther, Panthera onca, Felis onca",
312
+ "291": "lion, king of beasts, Panthera leo",
313
+ "292": "tiger, Panthera tigris",
314
+ "293": "cheetah, chetah, Acinonyx jubatus",
315
+ "294": "brown bear, bruin, Ursus arctos",
316
+ "295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
317
+ "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
318
+ "297": "sloth bear, Melursus ursinus, Ursus ursinus",
319
+ "298": "mongoose",
320
+ "299": "meerkat, mierkat",
321
+ "300": "tiger beetle",
322
+ "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
323
+ "302": "ground beetle, carabid beetle",
324
+ "303": "long-horned beetle, longicorn, longicorn beetle",
325
+ "304": "leaf beetle, chrysomelid",
326
+ "305": "dung beetle",
327
+ "306": "rhinoceros beetle",
328
+ "307": "weevil",
329
+ "308": "fly",
330
+ "309": "bee",
331
+ "310": "ant, emmet, pismire",
332
+ "311": "grasshopper, hopper",
333
+ "312": "cricket",
334
+ "313": "walking stick, walkingstick, stick insect",
335
+ "314": "cockroach, roach",
336
+ "315": "mantis, mantid",
337
+ "316": "cicada, cicala",
338
+ "317": "leafhopper",
339
+ "318": "lacewing, lacewing fly",
340
+ "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
341
+ "320": "damselfly",
342
+ "321": "admiral",
343
+ "322": "ringlet, ringlet butterfly",
344
+ "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
345
+ "324": "cabbage butterfly",
346
+ "325": "sulphur butterfly, sulfur butterfly",
347
+ "326": "lycaenid, lycaenid butterfly",
348
+ "327": "starfish, sea star",
349
+ "328": "sea urchin",
350
+ "329": "sea cucumber, holothurian",
351
+ "330": "wood rabbit, cottontail, cottontail rabbit",
352
+ "331": "hare",
353
+ "332": "Angora, Angora rabbit",
354
+ "333": "hamster",
355
+ "334": "porcupine, hedgehog",
356
+ "335": "fox squirrel, eastern fox squirrel, Sciurus niger",
357
+ "336": "marmot",
358
+ "337": "beaver",
359
+ "338": "guinea pig, Cavia cobaya",
360
+ "339": "sorrel",
361
+ "340": "zebra",
362
+ "341": "hog, pig, grunter, squealer, Sus scrofa",
363
+ "342": "wild boar, boar, Sus scrofa",
364
+ "343": "warthog",
365
+ "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
366
+ "345": "ox",
367
+ "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
368
+ "347": "bison",
369
+ "348": "ram, tup",
370
+ "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
371
+ "350": "ibex, Capra ibex",
372
+ "351": "hartebeest",
373
+ "352": "impala, Aepyceros melampus",
374
+ "353": "gazelle",
375
+ "354": "Arabian camel, dromedary, Camelus dromedarius",
376
+ "355": "llama",
377
+ "356": "weasel",
378
+ "357": "mink",
379
+ "358": "polecat, fitch, foulmart, foumart, Mustela putorius",
380
+ "359": "black-footed ferret, ferret, Mustela nigripes",
381
+ "360": "otter",
382
+ "361": "skunk, polecat, wood pussy",
383
+ "362": "badger",
384
+ "363": "armadillo",
385
+ "364": "three-toed sloth, ai, Bradypus tridactylus",
386
+ "365": "orangutan, orang, orangutang, Pongo pygmaeus",
387
+ "366": "gorilla, Gorilla gorilla",
388
+ "367": "chimpanzee, chimp, Pan troglodytes",
389
+ "368": "gibbon, Hylobates lar",
390
+ "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
391
+ "370": "guenon, guenon monkey",
392
+ "371": "patas, hussar monkey, Erythrocebus patas",
393
+ "372": "baboon",
394
+ "373": "macaque",
395
+ "374": "langur",
396
+ "375": "colobus, colobus monkey",
397
+ "376": "proboscis monkey, Nasalis larvatus",
398
+ "377": "marmoset",
399
+ "378": "capuchin, ringtail, Cebus capucinus",
400
+ "379": "howler monkey, howler",
401
+ "380": "titi, titi monkey",
402
+ "381": "spider monkey, Ateles geoffroyi",
403
+ "382": "squirrel monkey, Saimiri sciureus",
404
+ "383": "Madagascar cat, ring-tailed lemur, Lemur catta",
405
+ "384": "indri, indris, Indri indri, Indri brevicaudatus",
406
+ "385": "Indian elephant, Elephas maximus",
407
+ "386": "African elephant, Loxodonta africana",
408
+ "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
409
+ "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
410
+ "389": "barracouta, snoek",
411
+ "390": "eel",
412
+ "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
413
+ "392": "rock beauty, Holocanthus tricolor",
414
+ "393": "anemone fish",
415
+ "394": "sturgeon",
416
+ "395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
417
+ "396": "lionfish",
418
+ "397": "puffer, pufferfish, blowfish, globefish",
419
+ "398": "abacus",
420
+ "399": "abaya",
421
+ "400": "academic gown, academic robe, judge robe",
422
+ "401": "accordion, piano accordion, squeeze box",
423
+ "402": "acoustic guitar",
424
+ "403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
425
+ "404": "airliner",
426
+ "405": "airship, dirigible",
427
+ "406": "altar",
428
+ "407": "ambulance",
429
+ "408": "amphibian, amphibious vehicle",
430
+ "409": "analog clock",
431
+ "410": "apiary, bee house",
432
+ "411": "apron",
433
+ "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
434
+ "413": "assault rifle, assault gun",
435
+ "414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
436
+ "415": "bakery, bakeshop, bakehouse",
437
+ "416": "balance beam, beam",
438
+ "417": "balloon",
439
+ "418": "ballpoint, ballpoint pen, ballpen, Biro",
440
+ "419": "Band Aid",
441
+ "420": "banjo",
442
+ "421": "bannister, banister, balustrade, balusters, handrail",
443
+ "422": "barbell",
444
+ "423": "barber chair",
445
+ "424": "barbershop",
446
+ "425": "barn",
447
+ "426": "barometer",
448
+ "427": "barrel, cask",
449
+ "428": "barrow, garden cart, lawn cart, wheelbarrow",
450
+ "429": "baseball",
451
+ "430": "basketball",
452
+ "431": "bassinet",
453
+ "432": "bassoon",
454
+ "433": "bathing cap, swimming cap",
455
+ "434": "bath towel",
456
+ "435": "bathtub, bathing tub, bath, tub",
457
+ "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
458
+ "437": "beacon, lighthouse, beacon light, pharos",
459
+ "438": "beaker",
460
+ "439": "bearskin, busby, shako",
461
+ "440": "beer bottle",
462
+ "441": "beer glass",
463
+ "442": "bell cote, bell cot",
464
+ "443": "bib",
465
+ "444": "bicycle-built-for-two, tandem bicycle, tandem",
466
+ "445": "bikini, two-piece",
467
+ "446": "binder, ring-binder",
468
+ "447": "binoculars, field glasses, opera glasses",
469
+ "448": "birdhouse",
470
+ "449": "boathouse",
471
+ "450": "bobsled, bobsleigh, bob",
472
+ "451": "bolo tie, bolo, bola tie, bola",
473
+ "452": "bonnet, poke bonnet",
474
+ "453": "bookcase",
475
+ "454": "bookshop, bookstore, bookstall",
476
+ "455": "bottlecap",
477
+ "456": "bow",
478
+ "457": "bow tie, bow-tie, bowtie",
479
+ "458": "brass, memorial tablet, plaque",
480
+ "459": "brassiere, bra, bandeau",
481
+ "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
482
+ "461": "breastplate, aegis, egis",
483
+ "462": "broom",
484
+ "463": "bucket, pail",
485
+ "464": "buckle",
486
+ "465": "bulletproof vest",
487
+ "466": "bullet train, bullet",
488
+ "467": "butcher shop, meat market",
489
+ "468": "cab, hack, taxi, taxicab",
490
+ "469": "caldron, cauldron",
491
+ "470": "candle, taper, wax light",
492
+ "471": "cannon",
493
+ "472": "canoe",
494
+ "473": "can opener, tin opener",
495
+ "474": "cardigan",
496
+ "475": "car mirror",
497
+ "476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
498
+ "477": "carpenters kit, tool kit",
499
+ "478": "carton",
500
+ "479": "car wheel",
501
+ "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
502
+ "481": "cassette",
503
+ "482": "cassette player",
504
+ "483": "castle",
505
+ "484": "catamaran",
506
+ "485": "CD player",
507
+ "486": "cello, violoncello",
508
+ "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
509
+ "488": "chain",
510
+ "489": "chainlink fence",
511
+ "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
512
+ "491": "chain saw, chainsaw",
513
+ "492": "chest",
514
+ "493": "chiffonier, commode",
515
+ "494": "chime, bell, gong",
516
+ "495": "china cabinet, china closet",
517
+ "496": "Christmas stocking",
518
+ "497": "church, church building",
519
+ "498": "cinema, movie theater, movie theatre, movie house, picture palace",
520
+ "499": "cleaver, meat cleaver, chopper",
521
+ "500": "cliff dwelling",
522
+ "501": "cloak",
523
+ "502": "clog, geta, patten, sabot",
524
+ "503": "cocktail shaker",
525
+ "504": "coffee mug",
526
+ "505": "coffeepot",
527
+ "506": "coil, spiral, volute, whorl, helix",
528
+ "507": "combination lock",
529
+ "508": "computer keyboard, keypad",
530
+ "509": "confectionery, confectionary, candy store",
531
+ "510": "container ship, containership, container vessel",
532
+ "511": "convertible",
533
+ "512": "corkscrew, bottle screw",
534
+ "513": "cornet, horn, trumpet, trump",
535
+ "514": "cowboy boot",
536
+ "515": "cowboy hat, ten-gallon hat",
537
+ "516": "cradle",
538
+ "517": "crane",
539
+ "518": "crash helmet",
540
+ "519": "crate",
541
+ "520": "crib, cot",
542
+ "521": "Crock Pot",
543
+ "522": "croquet ball",
544
+ "523": "crutch",
545
+ "524": "cuirass",
546
+ "525": "dam, dike, dyke",
547
+ "526": "desk",
548
+ "527": "desktop computer",
549
+ "528": "dial telephone, dial phone",
550
+ "529": "diaper, nappy, napkin",
551
+ "530": "digital clock",
552
+ "531": "digital watch",
553
+ "532": "dining table, board",
554
+ "533": "dishrag, dishcloth",
555
+ "534": "dishwasher, dish washer, dishwashing machine",
556
+ "535": "disk brake, disc brake",
557
+ "536": "dock, dockage, docking facility",
558
+ "537": "dogsled, dog sled, dog sleigh",
559
+ "538": "dome",
560
+ "539": "doormat, welcome mat",
561
+ "540": "drilling platform, offshore rig",
562
+ "541": "drum, membranophone, tympan",
563
+ "542": "drumstick",
564
+ "543": "dumbbell",
565
+ "544": "Dutch oven",
566
+ "545": "electric fan, blower",
567
+ "546": "electric guitar",
568
+ "547": "electric locomotive",
569
+ "548": "entertainment center",
570
+ "549": "envelope",
571
+ "550": "espresso maker",
572
+ "551": "face powder",
573
+ "552": "feather boa, boa",
574
+ "553": "file, file cabinet, filing cabinet",
575
+ "554": "fireboat",
576
+ "555": "fire engine, fire truck",
577
+ "556": "fire screen, fireguard",
578
+ "557": "flagpole, flagstaff",
579
+ "558": "flute, transverse flute",
580
+ "559": "folding chair",
581
+ "560": "football helmet",
582
+ "561": "forklift",
583
+ "562": "fountain",
584
+ "563": "fountain pen",
585
+ "564": "four-poster",
586
+ "565": "freight car",
587
+ "566": "French horn, horn",
588
+ "567": "frying pan, frypan, skillet",
589
+ "568": "fur coat",
590
+ "569": "garbage truck, dustcart",
591
+ "570": "gasmask, respirator, gas helmet",
592
+ "571": "gas pump, gasoline pump, petrol pump, island dispenser",
593
+ "572": "goblet",
594
+ "573": "go-kart",
595
+ "574": "golf ball",
596
+ "575": "golfcart, golf cart",
597
+ "576": "gondola",
598
+ "577": "gong, tam-tam",
599
+ "578": "gown",
600
+ "579": "grand piano, grand",
601
+ "580": "greenhouse, nursery, glasshouse",
602
+ "581": "grille, radiator grille",
603
+ "582": "grocery store, grocery, food market, market",
604
+ "583": "guillotine",
605
+ "584": "hair slide",
606
+ "585": "hair spray",
607
+ "586": "half track",
608
+ "587": "hammer",
609
+ "588": "hamper",
610
+ "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
611
+ "590": "hand-held computer, hand-held microcomputer",
612
+ "591": "handkerchief, hankie, hanky, hankey",
613
+ "592": "hard disc, hard disk, fixed disk",
614
+ "593": "harmonica, mouth organ, harp, mouth harp",
615
+ "594": "harp",
616
+ "595": "harvester, reaper",
617
+ "596": "hatchet",
618
+ "597": "holster",
619
+ "598": "home theater, home theatre",
620
+ "599": "honeycomb",
621
+ "600": "hook, claw",
622
+ "601": "hoopskirt, crinoline",
623
+ "602": "horizontal bar, high bar",
624
+ "603": "horse cart, horse-cart",
625
+ "604": "hourglass",
626
+ "605": "iPod",
627
+ "606": "iron, smoothing iron",
628
+ "607": "jack-o-lantern",
629
+ "608": "jean, blue jean, denim",
630
+ "609": "jeep, landrover",
631
+ "610": "jersey, T-shirt, tee shirt",
632
+ "611": "jigsaw puzzle",
633
+ "612": "jinrikisha, ricksha, rickshaw",
634
+ "613": "joystick",
635
+ "614": "kimono",
636
+ "615": "knee pad",
637
+ "616": "knot",
638
+ "617": "lab coat, laboratory coat",
639
+ "618": "ladle",
640
+ "619": "lampshade, lamp shade",
641
+ "620": "laptop, laptop computer",
642
+ "621": "lawn mower, mower",
643
+ "622": "lens cap, lens cover",
644
+ "623": "letter opener, paper knife, paperknife",
645
+ "624": "library",
646
+ "625": "lifeboat",
647
+ "626": "lighter, light, igniter, ignitor",
648
+ "627": "limousine, limo",
649
+ "628": "liner, ocean liner",
650
+ "629": "lipstick, lip rouge",
651
+ "630": "Loafer",
652
+ "631": "lotion",
653
+ "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
654
+ "633": "loupe, jewelers loupe",
655
+ "634": "lumbermill, sawmill",
656
+ "635": "magnetic compass",
657
+ "636": "mailbag, postbag",
658
+ "637": "mailbox, letter box",
659
+ "638": "maillot",
660
+ "639": "maillot, tank suit",
661
+ "640": "manhole cover",
662
+ "641": "maraca",
663
+ "642": "marimba, xylophone",
664
+ "643": "mask",
665
+ "644": "matchstick",
666
+ "645": "maypole",
667
+ "646": "maze, labyrinth",
668
+ "647": "measuring cup",
669
+ "648": "medicine chest, medicine cabinet",
670
+ "649": "megalith, megalithic structure",
671
+ "650": "microphone, mike",
672
+ "651": "microwave, microwave oven",
673
+ "652": "military uniform",
674
+ "653": "milk can",
675
+ "654": "minibus",
676
+ "655": "miniskirt, mini",
677
+ "656": "minivan",
678
+ "657": "missile",
679
+ "658": "mitten",
680
+ "659": "mixing bowl",
681
+ "660": "mobile home, manufactured home",
682
+ "661": "Model T",
683
+ "662": "modem",
684
+ "663": "monastery",
685
+ "664": "monitor",
686
+ "665": "moped",
687
+ "666": "mortar",
688
+ "667": "mortarboard",
689
+ "668": "mosque",
690
+ "669": "mosquito net",
691
+ "670": "motor scooter, scooter",
692
+ "671": "mountain bike, all-terrain bike, off-roader",
693
+ "672": "mountain tent",
694
+ "673": "mouse, computer mouse",
695
+ "674": "mousetrap",
696
+ "675": "moving van",
697
+ "676": "muzzle",
698
+ "677": "nail",
699
+ "678": "neck brace",
700
+ "679": "necklace",
701
+ "680": "nipple",
702
+ "681": "notebook, notebook computer",
703
+ "682": "obelisk",
704
+ "683": "oboe, hautboy, hautbois",
705
+ "684": "ocarina, sweet potato",
706
+ "685": "odometer, hodometer, mileometer, milometer",
707
+ "686": "oil filter",
708
+ "687": "organ, pipe organ",
709
+ "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
710
+ "689": "overskirt",
711
+ "690": "oxcart",
712
+ "691": "oxygen mask",
713
+ "692": "packet",
714
+ "693": "paddle, boat paddle",
715
+ "694": "paddlewheel, paddle wheel",
716
+ "695": "padlock",
717
+ "696": "paintbrush",
718
+ "697": "pajama, pyjama, pjs, jammies",
719
+ "698": "palace",
720
+ "699": "panpipe, pandean pipe, syrinx",
721
+ "700": "paper towel",
722
+ "701": "parachute, chute",
723
+ "702": "parallel bars, bars",
724
+ "703": "park bench",
725
+ "704": "parking meter",
726
+ "705": "passenger car, coach, carriage",
727
+ "706": "patio, terrace",
728
+ "707": "pay-phone, pay-station",
729
+ "708": "pedestal, plinth, footstall",
730
+ "709": "pencil box, pencil case",
731
+ "710": "pencil sharpener",
732
+ "711": "perfume, essence",
733
+ "712": "Petri dish",
734
+ "713": "photocopier",
735
+ "714": "pick, plectrum, plectron",
736
+ "715": "pickelhaube",
737
+ "716": "picket fence, paling",
738
+ "717": "pickup, pickup truck",
739
+ "718": "pier",
740
+ "719": "piggy bank, penny bank",
741
+ "720": "pill bottle",
742
+ "721": "pillow",
743
+ "722": "ping-pong ball",
744
+ "723": "pinwheel",
745
+ "724": "pirate, pirate ship",
746
+ "725": "pitcher, ewer",
747
+ "726": "plane, carpenters plane, woodworking plane",
748
+ "727": "planetarium",
749
+ "728": "plastic bag",
750
+ "729": "plate rack",
751
+ "730": "plow, plough",
752
+ "731": "plunger, plumbers helper",
753
+ "732": "Polaroid camera, Polaroid Land camera",
754
+ "733": "pole",
755
+ "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
756
+ "735": "poncho",
757
+ "736": "pool table, billiard table, snooker table",
758
+ "737": "pop bottle, soda bottle",
759
+ "738": "pot, flowerpot",
760
+ "739": "potters wheel",
761
+ "740": "power drill",
762
+ "741": "prayer rug, prayer mat",
763
+ "742": "printer",
764
+ "743": "prison, prison house",
765
+ "744": "projectile, missile",
766
+ "745": "projector",
767
+ "746": "puck, hockey puck",
768
+ "747": "punching bag, punch bag, punching ball, punchball",
769
+ "748": "purse",
770
+ "749": "quill, quill pen",
771
+ "750": "quilt, comforter, comfort, puff",
772
+ "751": "racer, race car, racing car",
773
+ "752": "racket, racquet",
774
+ "753": "radiator",
775
+ "754": "radio, wireless",
776
+ "755": "radio telescope, radio reflector",
777
+ "756": "rain barrel",
778
+ "757": "recreational vehicle, RV, R.V.",
779
+ "758": "reel",
780
+ "759": "reflex camera",
781
+ "760": "refrigerator, icebox",
782
+ "761": "remote control, remote",
783
+ "762": "restaurant, eating house, eating place, eatery",
784
+ "763": "revolver, six-gun, six-shooter",
785
+ "764": "rifle",
786
+ "765": "rocking chair, rocker",
787
+ "766": "rotisserie",
788
+ "767": "rubber eraser, rubber, pencil eraser",
789
+ "768": "rugby ball",
790
+ "769": "rule, ruler",
791
+ "770": "running shoe",
792
+ "771": "safe",
793
+ "772": "safety pin",
794
+ "773": "saltshaker, salt shaker",
795
+ "774": "sandal",
796
+ "775": "sarong",
797
+ "776": "sax, saxophone",
798
+ "777": "scabbard",
799
+ "778": "scale, weighing machine",
800
+ "779": "school bus",
801
+ "780": "schooner",
802
+ "781": "scoreboard",
803
+ "782": "screen, CRT screen",
804
+ "783": "screw",
805
+ "784": "screwdriver",
806
+ "785": "seat belt, seatbelt",
807
+ "786": "sewing machine",
808
+ "787": "shield, buckler",
809
+ "788": "shoe shop, shoe-shop, shoe store",
810
+ "789": "shoji",
811
+ "790": "shopping basket",
812
+ "791": "shopping cart",
813
+ "792": "shovel",
814
+ "793": "shower cap",
815
+ "794": "shower curtain",
816
+ "795": "ski",
817
+ "796": "ski mask",
818
+ "797": "sleeping bag",
819
+ "798": "slide rule, slipstick",
820
+ "799": "sliding door",
821
+ "800": "slot, one-armed bandit",
822
+ "801": "snorkel",
823
+ "802": "snowmobile",
824
+ "803": "snowplow, snowplough",
825
+ "804": "soap dispenser",
826
+ "805": "soccer ball",
827
+ "806": "sock",
828
+ "807": "solar dish, solar collector, solar furnace",
829
+ "808": "sombrero",
830
+ "809": "soup bowl",
831
+ "810": "space bar",
832
+ "811": "space heater",
833
+ "812": "space shuttle",
834
+ "813": "spatula",
835
+ "814": "speedboat",
836
+ "815": "spider web, spiders web",
837
+ "816": "spindle",
838
+ "817": "sports car, sport car",
839
+ "818": "spotlight, spot",
840
+ "819": "stage",
841
+ "820": "steam locomotive",
842
+ "821": "steel arch bridge",
843
+ "822": "steel drum",
844
+ "823": "stethoscope",
845
+ "824": "stole",
846
+ "825": "stone wall",
847
+ "826": "stopwatch, stop watch",
848
+ "827": "stove",
849
+ "828": "strainer",
850
+ "829": "streetcar, tram, tramcar, trolley, trolley car",
851
+ "830": "stretcher",
852
+ "831": "studio couch, day bed",
853
+ "832": "stupa, tope",
854
+ "833": "submarine, pigboat, sub, U-boat",
855
+ "834": "suit, suit of clothes",
856
+ "835": "sundial",
857
+ "836": "sunglass",
858
+ "837": "sunglasses, dark glasses, shades",
859
+ "838": "sunscreen, sunblock, sun blocker",
860
+ "839": "suspension bridge",
861
+ "840": "swab, swob, mop",
862
+ "841": "sweatshirt",
863
+ "842": "swimming trunks, bathing trunks",
864
+ "843": "swing",
865
+ "844": "switch, electric switch, electrical switch",
866
+ "845": "syringe",
867
+ "846": "table lamp",
868
+ "847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
869
+ "848": "tape player",
870
+ "849": "teapot",
871
+ "850": "teddy, teddy bear",
872
+ "851": "television, television system",
873
+ "852": "tennis ball",
874
+ "853": "thatch, thatched roof",
875
+ "854": "theater curtain, theatre curtain",
876
+ "855": "thimble",
877
+ "856": "thresher, thrasher, threshing machine",
878
+ "857": "throne",
879
+ "858": "tile roof",
880
+ "859": "toaster",
881
+ "860": "tobacco shop, tobacconist shop, tobacconist",
882
+ "861": "toilet seat",
883
+ "862": "torch",
884
+ "863": "totem pole",
885
+ "864": "tow truck, tow car, wrecker",
886
+ "865": "toyshop",
887
+ "866": "tractor",
888
+ "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
889
+ "868": "tray",
890
+ "869": "trench coat",
891
+ "870": "tricycle, trike, velocipede",
892
+ "871": "trimaran",
893
+ "872": "tripod",
894
+ "873": "triumphal arch",
895
+ "874": "trolleybus, trolley coach, trackless trolley",
896
+ "875": "trombone",
897
+ "876": "tub, vat",
898
+ "877": "turnstile",
899
+ "878": "typewriter keyboard",
900
+ "879": "umbrella",
901
+ "880": "unicycle, monocycle",
902
+ "881": "upright, upright piano",
903
+ "882": "vacuum, vacuum cleaner",
904
+ "883": "vase",
905
+ "884": "vault",
906
+ "885": "velvet",
907
+ "886": "vending machine",
908
+ "887": "vestment",
909
+ "888": "viaduct",
910
+ "889": "violin, fiddle",
911
+ "890": "volleyball",
912
+ "891": "waffle iron",
913
+ "892": "wall clock",
914
+ "893": "wallet, billfold, notecase, pocketbook",
915
+ "894": "wardrobe, closet, press",
916
+ "895": "warplane, military plane",
917
+ "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
918
+ "897": "washer, automatic washer, washing machine",
919
+ "898": "water bottle",
920
+ "899": "water jug",
921
+ "900": "water tower",
922
+ "901": "whiskey jug",
923
+ "902": "whistle",
924
+ "903": "wig",
925
+ "904": "window screen",
926
+ "905": "window shade",
927
+ "906": "Windsor tie",
928
+ "907": "wine bottle",
929
+ "908": "wing",
930
+ "909": "wok",
931
+ "910": "wooden spoon",
932
+ "911": "wool, woolen, woollen",
933
+ "912": "worm fence, snake fence, snake-rail fence, Virginia fence",
934
+ "913": "wreck",
935
+ "914": "yawl",
936
+ "915": "yurt",
937
+ "916": "web site, website, internet site, site",
938
+ "917": "comic book",
939
+ "918": "crossword puzzle, crossword",
940
+ "919": "street sign",
941
+ "920": "traffic light, traffic signal, stoplight",
942
+ "921": "book jacket, dust cover, dust jacket, dust wrapper",
943
+ "922": "menu",
944
+ "923": "plate",
945
+ "924": "guacamole",
946
+ "925": "consomme",
947
+ "926": "hot pot, hotpot",
948
+ "927": "trifle",
949
+ "928": "ice cream, icecream",
950
+ "929": "ice lolly, lolly, lollipop, popsicle",
951
+ "930": "French loaf",
952
+ "931": "bagel, beigel",
953
+ "932": "pretzel",
954
+ "933": "cheeseburger",
955
+ "934": "hotdog, hot dog, red hot",
956
+ "935": "mashed potato",
957
+ "936": "head cabbage",
958
+ "937": "broccoli",
959
+ "938": "cauliflower",
960
+ "939": "zucchini, courgette",
961
+ "940": "spaghetti squash",
962
+ "941": "acorn squash",
963
+ "942": "butternut squash",
964
+ "943": "cucumber, cuke",
965
+ "944": "artichoke, globe artichoke",
966
+ "945": "bell pepper",
967
+ "946": "cardoon",
968
+ "947": "mushroom",
969
+ "948": "Granny Smith",
970
+ "949": "strawberry",
971
+ "950": "orange",
972
+ "951": "lemon",
973
+ "952": "fig",
974
+ "953": "pineapple, ananas",
975
+ "954": "banana",
976
+ "955": "jackfruit, jak, jack",
977
+ "956": "custard apple",
978
+ "957": "pomegranate",
979
+ "958": "hay",
980
+ "959": "carbonara",
981
+ "960": "chocolate sauce, chocolate syrup",
982
+ "961": "dough",
983
+ "962": "meat loaf, meatloaf",
984
+ "963": "pizza, pizza pie",
985
+ "964": "potpie",
986
+ "965": "burrito",
987
+ "966": "red wine",
988
+ "967": "espresso",
989
+ "968": "cup",
990
+ "969": "eggnog",
991
+ "970": "alp",
992
+ "971": "bubble",
993
+ "972": "cliff, drop, drop-off",
994
+ "973": "coral reef",
995
+ "974": "geyser",
996
+ "975": "lakeside, lakeshore",
997
+ "976": "promontory, headland, head, foreland",
998
+ "977": "sandbar, sand bar",
999
+ "978": "seashore, coast, seacoast, sea-coast",
1000
+ "979": "valley, vale",
1001
+ "980": "volcano",
1002
+ "981": "ballplayer, baseball player",
1003
+ "982": "groom, bridegroom",
1004
+ "983": "scuba diver",
1005
+ "984": "rapeseed",
1006
+ "985": "daisy",
1007
+ "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
1008
+ "987": "corn",
1009
+ "988": "acorn",
1010
+ "989": "hip, rose hip, rosehip",
1011
+ "990": "buckeye, horse chestnut, conker",
1012
+ "991": "coral fungus",
1013
+ "992": "agaric",
1014
+ "993": "gyromitra",
1015
+ "994": "stinkhorn, carrion fungus",
1016
+ "995": "earthstar",
1017
+ "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
1018
+ "997": "bolete",
1019
+ "998": "ear, spike, capitulum",
1020
+ "999": "toilet tissue, toilet paper, bathroom tissue"
1021
+ }
1022
+ }
AFM-B-2-1NFE-noguide/pipeline.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: AFMPipeline.
2
+
3
+ Load with native Hugging Face diffusers and trust_remote_code=True.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ from diffusers.image_processor import VaeImageProcessor
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
16
+ from diffusers.utils.torch_utils import randn_tensor
17
+
18
+
19
+ class AFMPipeline(DiffusionPipeline):
20
+ model_cpu_offload_seq = "generator->vae"
21
+
22
+ @staticmethod
23
+ def _coerce_scheduler(scheduler, generator):
24
+ if scheduler is not None and not isinstance(scheduler, (list, tuple)):
25
+ return scheduler
26
+ variant_path = getattr(generator.config, "_name_or_path", None)
27
+ if variant_path:
28
+ scheduler_dir = Path(variant_path).resolve().parent / "scheduler"
29
+ module_path = scheduler_dir / "scheduling_continuous_flow.py"
30
+ config_path = scheduler_dir / "scheduler_config.json"
31
+ if module_path.is_file() and config_path.is_file():
32
+ spec = importlib.util.spec_from_file_location("scheduling_continuous_flow", module_path)
33
+ if spec is not None and spec.loader is not None:
34
+ module = importlib.util.module_from_spec(spec)
35
+ spec.loader.exec_module(module)
36
+ return module.ContinuousFlowMatchScheduler.from_pretrained(str(scheduler_dir))
37
+ raise ValueError("AFMPipeline could not load ContinuousFlowMatchScheduler from the variant folder.")
38
+
39
+ def __init__(
40
+ self,
41
+ generator,
42
+ vae,
43
+ scheduler=None,
44
+ pred_type: str = "x",
45
+ id2label: Optional[Dict[Union[int, str], str]] = None,
46
+ ) -> None:
47
+ super().__init__()
48
+ scheduler = self._coerce_scheduler(scheduler, generator)
49
+ self.register_modules(generator=generator, vae=vae, scheduler=scheduler)
50
+ self.register_to_config(pred_type=pred_type)
51
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
52
+ self._id2label = self._normalize_id2label(id2label)
53
+ self.labels = self._build_label2id(self._id2label)
54
+ self._labels_loaded_from_model_index = bool(self._id2label)
55
+
56
+ @staticmethod
57
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
58
+ if not id2label:
59
+ return {}
60
+ return {int(key): value for key, value in id2label.items()}
61
+
62
+ @staticmethod
63
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
64
+ if not variant_path:
65
+ return {}
66
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
67
+ if not model_index_path.exists():
68
+ return {}
69
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
70
+ id2label = raw.get("id2label")
71
+ if not isinstance(id2label, dict):
72
+ return {}
73
+ return {int(key): value for key, value in id2label.items()}
74
+
75
+ @staticmethod
76
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
77
+ label2id: Dict[str, int] = {}
78
+ for class_id, value in id2label.items():
79
+ for synonym in value.split(","):
80
+ synonym = synonym.strip()
81
+ if synonym:
82
+ label2id[synonym] = int(class_id)
83
+ return dict(sorted(label2id.items()))
84
+
85
+ @property
86
+ def vae_scale_factor(self) -> int:
87
+ block_out_channels = getattr(self.vae.config, "block_out_channels", None)
88
+ if block_out_channels:
89
+ return int(2 ** (len(block_out_channels) - 1))
90
+ return 8
91
+
92
+ @property
93
+ def id2label(self) -> Dict[int, str]:
94
+ self._ensure_labels_loaded()
95
+ return self._id2label
96
+
97
+ def _ensure_labels_loaded(self) -> None:
98
+ if self._labels_loaded_from_model_index:
99
+ return
100
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
101
+ if loaded:
102
+ self._id2label = loaded
103
+ self.labels = self._build_label2id(self._id2label)
104
+ self._labels_loaded_from_model_index = True
105
+
106
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
107
+ self._ensure_labels_loaded()
108
+ labels = [label] if isinstance(label, str) else label
109
+ if not self.labels:
110
+ raise ValueError("No id2label mapping is available in this checkpoint.")
111
+ missing = [item for item in labels if item not in self.labels]
112
+ if missing:
113
+ preview = ", ".join(list(self.labels.keys())[:8])
114
+ raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
115
+ return [self.labels[item] for item in labels]
116
+
117
+ def _normalize_class_labels(
118
+ self,
119
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
120
+ device: torch.device,
121
+ ) -> torch.LongTensor:
122
+ if torch.is_tensor(class_labels):
123
+ return class_labels.to(device=device, dtype=torch.long).reshape(-1)
124
+ if isinstance(class_labels, int):
125
+ class_label_ids = [class_labels]
126
+ elif isinstance(class_labels, str):
127
+ class_label_ids = self.get_label_ids(class_labels)
128
+ elif class_labels and isinstance(class_labels[0], str):
129
+ class_label_ids = self.get_label_ids(class_labels)
130
+ else:
131
+ class_label_ids = list(class_labels)
132
+ return torch.tensor(class_label_ids, device=device, dtype=torch.long).reshape(-1)
133
+
134
+ def _default_image_size(self) -> int:
135
+ transformer = getattr(self.generator, "transformer", None)
136
+ if transformer is not None:
137
+ return int(transformer.config.sample_size) * self.vae_scale_factor
138
+ return 256
139
+
140
+ def check_inputs(
141
+ self,
142
+ height: int,
143
+ width: int,
144
+ num_inference_steps: int,
145
+ output_type: str,
146
+ sampler: str,
147
+ ) -> None:
148
+ if num_inference_steps < 1:
149
+ raise ValueError("`num_inference_steps` must be >= 1.")
150
+ if output_type not in {"pil", "np", "pt", "latent"}:
151
+ raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
152
+ if sampler not in {"euler", "heun"}:
153
+ raise ValueError("sampler must be one of: 'euler', 'heun'.")
154
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
155
+ raise ValueError(
156
+ f"`height` and `width` must be divisible by {self.vae_scale_factor}, got ({height}, {width})."
157
+ )
158
+
159
+ def prepare_latents(
160
+ self,
161
+ batch_size: int,
162
+ height: int,
163
+ width: int,
164
+ dtype: torch.dtype,
165
+ device: torch.device,
166
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
167
+ latents: Optional[torch.Tensor] = None,
168
+ ) -> torch.Tensor:
169
+ if latents is not None:
170
+ return latents.to(device=device, dtype=dtype)
171
+ latent_height = height // self.vae_scale_factor
172
+ latent_width = width // self.vae_scale_factor
173
+ in_channels = int(getattr(self.generator, "in_channels", 4))
174
+ return randn_tensor(
175
+ (batch_size, in_channels, latent_height, latent_width),
176
+ generator=generator,
177
+ device=device,
178
+ dtype=dtype,
179
+ )
180
+
181
+ def decode_latents(self, latents: torch.Tensor, output_type: str = "pil"):
182
+ if output_type == "latent":
183
+ return latents
184
+ scaling_factor = getattr(self.vae.config, "scaling_factor", 0.18215)
185
+ image = self.vae.decode(latents / scaling_factor).sample
186
+ if output_type == "pt":
187
+ return image
188
+ return self.image_processor.postprocess(image, output_type=output_type)
189
+
190
+ def _run_denoising_loop(
191
+ self,
192
+ latents: torch.Tensor,
193
+ class_labels_tensor: torch.Tensor,
194
+ batch_size: int,
195
+ device: torch.device,
196
+ num_inference_steps: int,
197
+ sampler: str,
198
+ pred_type: str,
199
+ ) -> torch.Tensor:
200
+ self.scheduler.set_timesteps(num_inference_steps, device=device, solver=sampler)
201
+ timesteps = self.scheduler.timesteps
202
+ self.generator.eval()
203
+ for t_src, t_tgt in self.progress_bar(list(zip(timesteps[:-1], timesteps[1:]))):
204
+ t_src_batch = t_src.expand(batch_size)
205
+ t_tgt_batch = t_tgt.expand(batch_size)
206
+ outputs = self.generator(latents, class_labels_tensor, t_src_batch, t_tgt_batch)
207
+ if pred_type == "v":
208
+ if sampler == "heun":
209
+ latents_next = self.scheduler.step(
210
+ outputs, t_src, t_tgt, latents, prediction_type="v"
211
+ ).prev_sample
212
+ outputs_next = self.generator(latents_next, class_labels_tensor, t_tgt_batch, t_tgt_batch)
213
+ latents = self.scheduler.step(
214
+ outputs,
215
+ t_src,
216
+ t_tgt,
217
+ latents,
218
+ model_output_next=outputs_next,
219
+ prediction_type="v",
220
+ ).prev_sample
221
+ else:
222
+ latents = self.scheduler.step(
223
+ outputs, t_src, t_tgt, latents, prediction_type="v"
224
+ ).prev_sample
225
+ else:
226
+ latents = outputs
227
+ return latents
228
+
229
+ @torch.inference_mode()
230
+ def __call__(
231
+ self,
232
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
233
+ height: Optional[int] = None,
234
+ width: Optional[int] = None,
235
+ num_inference_steps: Optional[int] = None,
236
+ sampler: str = "euler",
237
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
238
+ latents: Optional[torch.Tensor] = None,
239
+ output_type: str = "pil",
240
+ return_dict: bool = True,
241
+ ):
242
+ default_size = self._default_image_size()
243
+ height = int(height or default_size)
244
+ width = int(width or default_size)
245
+ if num_inference_steps is None:
246
+ num_inference_steps = int(getattr(self.generator.config, "num_inference_steps", 1))
247
+ self.check_inputs(height, width, num_inference_steps, output_type, sampler)
248
+
249
+ device = getattr(self, "_execution_device", None) or next(self.generator.parameters()).device
250
+ dtype = next(self.generator.parameters()).dtype
251
+ pred_type = self.config.pred_type
252
+ class_labels_tensor = self._normalize_class_labels(class_labels, device=device)
253
+ batch_size = class_labels_tensor.shape[0]
254
+ latents = self.prepare_latents(
255
+ batch_size=batch_size,
256
+ height=height,
257
+ width=width,
258
+ dtype=dtype,
259
+ device=device,
260
+ generator=generator,
261
+ latents=latents,
262
+ )
263
+ latents = self._run_denoising_loop(
264
+ latents,
265
+ class_labels_tensor,
266
+ batch_size,
267
+ device,
268
+ num_inference_steps,
269
+ sampler,
270
+ pred_type,
271
+ )
272
+ image = self.decode_latents(latents, output_type=output_type)
273
+ self.maybe_free_model_hooks()
274
+ if not return_dict:
275
+ return (image,)
276
+ return ImagePipelineOutput(images=image)
AFM-B-2-1NFE-noguide/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc ADDED
Binary file (5.38 kB). View file
 
AFM-B-2-1NFE-noguide/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ContinuousFlowMatchScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "solver": "euler"
5
+ }
AFM-B-2-1NFE-noguide/scheduler/scheduling_continuous_flow.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+ from diffusers.utils import BaseOutput
10
+
11
+
12
+ @dataclass
13
+ class ContinuousFlowMatchSchedulerOutput(BaseOutput):
14
+ prev_sample: torch.Tensor
15
+
16
+
17
+ class ContinuousFlowMatchScheduler(SchedulerMixin, ConfigMixin):
18
+ """Flow-matching scheduler for AFM with time in [1, 0]."""
19
+
20
+ order = 2
21
+
22
+ @register_to_config
23
+ def __init__(self, solver: str = "euler"):
24
+ if solver not in {"euler", "heun"}:
25
+ raise ValueError("solver must be one of: 'euler', 'heun'.")
26
+ self.timesteps: Optional[torch.Tensor] = None
27
+ self.num_inference_steps: Optional[int] = None
28
+ self._step_index: Optional[int] = None
29
+
30
+ @property
31
+ def init_noise_sigma(self) -> float:
32
+ return 1.0
33
+
34
+ def set_timesteps(
35
+ self,
36
+ num_inference_steps: int,
37
+ device: Union[str, torch.device, None] = None,
38
+ solver: Optional[str] = None,
39
+ ) -> None:
40
+ if num_inference_steps < 1:
41
+ raise ValueError("num_inference_steps must be >= 1.")
42
+ self.num_inference_steps = num_inference_steps
43
+ if solver == "heun":
44
+ grid_size = (num_inference_steps // 2) + 1
45
+ else:
46
+ grid_size = num_inference_steps + 1
47
+ self.timesteps = torch.linspace(1.0, 0.0, grid_size, device=device, dtype=torch.float32)
48
+ self._step_index = 0
49
+ if solver is not None:
50
+ self.register_to_config(solver=solver)
51
+
52
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
53
+ del timestep
54
+ return sample
55
+
56
+ def _resolve_step_index(self, timestep: Union[float, torch.Tensor, None]) -> int:
57
+ if self._step_index is not None:
58
+ return self._step_index
59
+ if self.timesteps is None:
60
+ raise ValueError("Call `set_timesteps` before `step`.")
61
+ if timestep is None:
62
+ return 0
63
+ t_value = float(timestep) if not isinstance(timestep, torch.Tensor) else float(timestep.flatten()[0])
64
+ matches = (self.timesteps - t_value).abs() < 1e-6
65
+ if matches.any():
66
+ return int(matches.nonzero(as_tuple=False)[0].item())
67
+ return 0
68
+
69
+ def step(
70
+ self,
71
+ model_output: torch.Tensor,
72
+ timestep_src: Union[float, torch.Tensor],
73
+ timestep_tgt: Union[float, torch.Tensor],
74
+ sample: torch.Tensor,
75
+ model_output_next: Optional[torch.Tensor] = None,
76
+ prediction_type: str = "v",
77
+ return_dict: bool = True,
78
+ ) -> Union[ContinuousFlowMatchSchedulerOutput, Tuple[torch.Tensor]]:
79
+ if prediction_type == "x":
80
+ prev_sample = model_output
81
+ else:
82
+ t_src = torch.as_tensor(timestep_src, device=sample.device, dtype=sample.dtype)
83
+ t_tgt = torch.as_tensor(timestep_tgt, device=sample.device, dtype=sample.dtype)
84
+ while t_src.ndim < sample.ndim:
85
+ t_src = t_src.unsqueeze(-1)
86
+ t_tgt = t_tgt.unsqueeze(-1)
87
+ dt = t_src - t_tgt
88
+ if self.config.solver == "heun" and model_output_next is not None:
89
+ prev_sample = sample - dt * 0.5 * (model_output + model_output_next)
90
+ else:
91
+ prev_sample = sample - dt * model_output
92
+
93
+ step_index = self._resolve_step_index(timestep_src)
94
+ self._step_index = step_index + 1
95
+
96
+ if not return_dict:
97
+ return (prev_sample,)
98
+ return ContinuousFlowMatchSchedulerOutput(prev_sample=prev_sample)
AFM-B-2-1NFE-noguide/vae/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.36.0",
4
+ "_name_or_path": "stabilityai/sd-vae-ft-mse",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "latents_mean": null,
22
+ "latents_std": null,
23
+ "layers_per_block": 2,
24
+ "mid_block_add_attention": true,
25
+ "norm_num_groups": 32,
26
+ "out_channels": 3,
27
+ "sample_size": 256,
28
+ "scaling_factor": 0.18215,
29
+ "shift_factor": null,
30
+ "up_block_types": [
31
+ "UpDecoderBlock2D",
32
+ "UpDecoderBlock2D",
33
+ "UpDecoderBlock2D",
34
+ "UpDecoderBlock2D"
35
+ ],
36
+ "use_post_quant_conv": true,
37
+ "use_quant_conv": true
38
+ }
AFM-B-2-1NFE-noguide/vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d993488569e928462932c8c38a0760b874d166399b14414135bd9c42df5815
3
+ size 334643276
AFM-L-2-1NFE-guided/demo.png ADDED

Git LFS Details

  • SHA256: b4a722696e47cfab9a967c46526d4740eafdb6c29beb605b3d140a2fc3caa885
  • Pointer size: 131 Bytes
  • Size of remote file: 113 kB
AFM-L-2-1NFE-guided/generator/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AFMGenerator2DModel",
3
+ "_diffusers_version": "0.36.0",
4
+ "model_type": "AFM-L/2",
5
+ "architecture": "standard",
6
+ "repeat": 1,
7
+ "use_t_src": false,
8
+ "use_t_tgt": false,
9
+ "pred_type": "x",
10
+ "num_inference_steps": 1,
11
+ "learn_sigma": false,
12
+ "class_dropout_prob": 0.0,
13
+ "input_size": 32,
14
+ "num_classes": 1000,
15
+ "in_channels": 4,
16
+ "depth": 24,
17
+ "hidden_size": 1024,
18
+ "patch_size": 2,
19
+ "num_heads": 16
20
+ }
AFM-L-2-1NFE-guided/generator/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f95d199f5759ef66f561d7d9f08f31489b1794272f450713a844551c2c816682
3
+ size 2046434688
AFM-L-2-1NFE-guided/generator/modeling_afm.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained AFM generator for Hugging Face diffusers checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Dict, Optional
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from torch import nn
14
+
15
+
16
+ def get_dit_transformer_class():
17
+ from diffusers.models.transformers.dit_transformer_2d import DiTTransformer2DModel
18
+
19
+ return DiTTransformer2DModel
20
+
21
+
22
+ def build_dit_config(
23
+ *,
24
+ depth: int = 28,
25
+ hidden_size: int = 1152,
26
+ patch_size: int = 2,
27
+ num_heads: int = 16,
28
+ learn_sigma: bool = False,
29
+ class_dropout_prob: float = 0.0,
30
+ input_size: int = 32,
31
+ num_classes: int = 1000,
32
+ in_channels: int = 4,
33
+ ) -> Dict[str, Any]:
34
+ attention_head_dim = hidden_size // num_heads
35
+ num_embeds_ada_norm = num_classes + (1 if class_dropout_prob > 0 else 0)
36
+ out_channels = in_channels * 2 if learn_sigma else in_channels
37
+ return {
38
+ "sample_size": input_size,
39
+ "num_layers": depth,
40
+ "num_attention_heads": num_heads,
41
+ "attention_head_dim": attention_head_dim,
42
+ "in_channels": in_channels,
43
+ "out_channels": out_channels,
44
+ "patch_size": patch_size,
45
+ "attention_bias": True,
46
+ "activation_fn": "gelu-approximate",
47
+ "num_embeds_ada_norm": num_embeds_ada_norm,
48
+ "norm_type": "ada_norm_zero",
49
+ "norm_elementwise_affine": False,
50
+ "dropout": 0.0,
51
+ "norm_num_groups": 32,
52
+ "norm_eps": 1e-5,
53
+ "upcast_attention": False,
54
+ }
55
+
56
+
57
+ def _convert_legacy_dit_state_dict(state_dict: Dict[str, torch.Tensor], depth: int) -> Dict[str, torch.Tensor]:
58
+ converted = copy.deepcopy(state_dict)
59
+
60
+ converted["pos_embed.proj.weight"] = converted.pop("x_embedder.proj.weight").clone().contiguous()
61
+ converted["pos_embed.proj.bias"] = converted.pop("x_embedder.proj.bias").clone().contiguous()
62
+
63
+ if "t_embedder.mlp.0.weight" in converted:
64
+ timestep_weights = {
65
+ "linear_1.weight": converted.pop("t_embedder.mlp.0.weight"),
66
+ "linear_1.bias": converted.pop("t_embedder.mlp.0.bias"),
67
+ "linear_2.weight": converted.pop("t_embedder.mlp.2.weight"),
68
+ "linear_2.bias": converted.pop("t_embedder.mlp.2.bias"),
69
+ }
70
+ else:
71
+ timestep_weights = None
72
+ class_embedding = converted.pop("y_embedder.embedding_table.weight")
73
+ if class_embedding.shape[0] == 1000:
74
+ null_class = torch.zeros(1, class_embedding.shape[1], dtype=class_embedding.dtype)
75
+ class_embedding = torch.cat([class_embedding, null_class], dim=0)
76
+
77
+ for block_idx in range(depth):
78
+ if timestep_weights is not None:
79
+ for key, tensor in timestep_weights.items():
80
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.timestep_embedder.{key}"] = tensor.clone()
81
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.class_embedder.embedding_table.weight"] = (
82
+ class_embedding.clone()
83
+ )
84
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.weight"] = converted[
85
+ f"blocks.{block_idx}.adaLN_modulation.1.weight"
86
+ ]
87
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.bias"] = converted[
88
+ f"blocks.{block_idx}.adaLN_modulation.1.bias"
89
+ ]
90
+
91
+ q, k, v = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.weight"], 3, dim=0)
92
+ q_bias, k_bias, v_bias = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.bias"], 3, dim=0)
93
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.weight"] = q
94
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.bias"] = q_bias
95
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.weight"] = k
96
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.bias"] = k_bias
97
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.weight"] = v
98
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.bias"] = v_bias
99
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.weight"] = converted[
100
+ f"blocks.{block_idx}.attn.proj.weight"
101
+ ]
102
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.bias"] = converted[
103
+ f"blocks.{block_idx}.attn.proj.bias"
104
+ ]
105
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.weight"] = converted[
106
+ f"blocks.{block_idx}.mlp.fc1.weight"
107
+ ]
108
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.bias"] = converted[
109
+ f"blocks.{block_idx}.mlp.fc1.bias"
110
+ ]
111
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.weight"] = converted[
112
+ f"blocks.{block_idx}.mlp.fc2.weight"
113
+ ]
114
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.bias"] = converted[
115
+ f"blocks.{block_idx}.mlp.fc2.bias"
116
+ ]
117
+
118
+ for suffix in (
119
+ "attn.qkv.weight",
120
+ "attn.qkv.bias",
121
+ "attn.proj.weight",
122
+ "attn.proj.bias",
123
+ "mlp.fc1.weight",
124
+ "mlp.fc1.bias",
125
+ "mlp.fc2.weight",
126
+ "mlp.fc2.bias",
127
+ "adaLN_modulation.1.weight",
128
+ "adaLN_modulation.1.bias",
129
+ ):
130
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
131
+
132
+ converted["proj_out_1.weight"] = converted.pop("final_layer.adaLN_modulation.1.weight")
133
+ converted["proj_out_1.bias"] = converted.pop("final_layer.adaLN_modulation.1.bias")
134
+ converted["proj_out_2.weight"] = converted.pop("final_layer.linear.weight")
135
+ converted["proj_out_2.bias"] = converted.pop("final_layer.linear.bias")
136
+
137
+ converted.pop("pos_embed", None)
138
+ for block_idx in range(depth):
139
+ for suffix in ("norm1.weight", "norm1.bias", "norm2.weight", "norm2.bias"):
140
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
141
+
142
+ return {key: tensor.detach().clone().contiguous() for key, tensor in converted.items()}
143
+
144
+
145
+ def load_legacy_dit_state_dict(
146
+ state_dict: Dict[str, torch.Tensor],
147
+ depth: int,
148
+ patch_size: int,
149
+ hidden_size: int,
150
+ num_heads: int,
151
+ ) -> Dict[str, torch.Tensor]:
152
+ if "transformer_blocks.0.attn1.to_q.weight" in state_dict:
153
+ return state_dict
154
+ if any(key.startswith("blocks.") for key in state_dict):
155
+ return _convert_legacy_dit_state_dict(state_dict, depth)
156
+ return state_dict
157
+
158
+
159
+ def forward_dit_output(
160
+ transformer,
161
+ hidden_states: torch.Tensor,
162
+ timestep: Optional[torch.Tensor],
163
+ class_labels: torch.Tensor,
164
+ extra_cond: Optional[torch.Tensor] = None,
165
+ ) -> torch.Tensor:
166
+ hidden_states = transformer.pos_embed(hidden_states)
167
+
168
+ for block in transformer.transformer_blocks:
169
+ if torch.is_grad_enabled() and transformer.gradient_checkpointing:
170
+ hidden_states = transformer._gradient_checkpointing_func(
171
+ block,
172
+ hidden_states,
173
+ None,
174
+ None,
175
+ None,
176
+ timestep,
177
+ None,
178
+ class_labels,
179
+ )
180
+ else:
181
+ hidden_states = block(
182
+ hidden_states,
183
+ attention_mask=None,
184
+ encoder_hidden_states=None,
185
+ encoder_attention_mask=None,
186
+ timestep=timestep,
187
+ cross_attention_kwargs=None,
188
+ class_labels=class_labels,
189
+ )
190
+
191
+ conditioning = transformer.transformer_blocks[0].norm1.emb(
192
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
193
+ )
194
+ if extra_cond is not None:
195
+ conditioning = conditioning + extra_cond
196
+ shift, scale = transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
197
+ hidden_states = transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
198
+ hidden_states = transformer.proj_out_2(hidden_states)
199
+
200
+ height = width = int(hidden_states.shape[1] ** 0.5)
201
+ hidden_states = hidden_states.reshape(
202
+ shape=(-1, height, width, transformer.patch_size, transformer.patch_size, transformer.out_channels)
203
+ )
204
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
205
+ return hidden_states.reshape(
206
+ shape=(-1, transformer.out_channels, height * transformer.patch_size, width * transformer.patch_size)
207
+ )
208
+
209
+
210
+ def remap_transformer_state_dict(
211
+ state_dict: Dict[str, torch.Tensor],
212
+ legacy_kwargs: Dict[str, int],
213
+ extra_prefixes: tuple[str, ...] = (),
214
+ ) -> Dict[str, torch.Tensor]:
215
+ state_dict = load_legacy_dit_state_dict(state_dict, **legacy_kwargs)
216
+ remapped: Dict[str, torch.Tensor] = {}
217
+ for key, value in state_dict.items():
218
+ if any(key.startswith(prefix) for prefix in extra_prefixes):
219
+ remapped[key] = value
220
+ elif key.startswith("transformer."):
221
+ remapped[key] = value
222
+ else:
223
+ remapped[f"transformer.{key}"] = value
224
+ return remapped
225
+
226
+
227
+ def split_output_channels(output: torch.Tensor, in_channels: int) -> torch.Tensor:
228
+ if output.shape[1] == in_channels:
229
+ return output
230
+ output, _ = output.chunk(2, dim=1)
231
+ return output
232
+
233
+
234
+ class TimestepEmbedder(nn.Module):
235
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
236
+ super().__init__()
237
+ self.mlp = nn.Sequential(
238
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
239
+ nn.SiLU(),
240
+ nn.Linear(hidden_size, hidden_size, bias=True),
241
+ )
242
+ self.frequency_embedding_size = frequency_embedding_size
243
+
244
+ @staticmethod
245
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
246
+ half = dim // 2
247
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
248
+ device=t.device
249
+ )
250
+ args = t[:, None].float() * freqs[None]
251
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
252
+ if dim % 2:
253
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
254
+ return embedding
255
+
256
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
257
+ emb = self.timestep_embedding(t.float(), self.frequency_embedding_size)
258
+ weight_dtype = self.mlp[0].weight.dtype
259
+ return self.mlp(emb.to(dtype=weight_dtype))
260
+
261
+
262
+ class Generator(nn.Module):
263
+ def __init__(
264
+ self,
265
+ *,
266
+ use_t_src: bool = False,
267
+ use_t_tgt: bool = False,
268
+ depth: int = 28,
269
+ hidden_size: int = 1152,
270
+ patch_size: int = 2,
271
+ num_heads: int = 16,
272
+ learn_sigma: bool = False,
273
+ class_dropout_prob: float = 0.0,
274
+ input_size: int = 32,
275
+ num_classes: int = 1000,
276
+ in_channels: int = 4,
277
+ **_,
278
+ ):
279
+ super().__init__()
280
+ self.use_t_src = use_t_src
281
+ self.use_t_tgt = use_t_tgt
282
+ self._legacy_kwargs = {
283
+ "depth": depth,
284
+ "hidden_size": hidden_size,
285
+ "patch_size": patch_size,
286
+ "num_heads": num_heads,
287
+ }
288
+ dit_cls = get_dit_transformer_class()
289
+ self.transformer = dit_cls(
290
+ **build_dit_config(
291
+ depth=depth,
292
+ hidden_size=hidden_size,
293
+ patch_size=patch_size,
294
+ num_heads=num_heads,
295
+ learn_sigma=learn_sigma,
296
+ class_dropout_prob=class_dropout_prob,
297
+ input_size=input_size,
298
+ num_classes=num_classes,
299
+ in_channels=in_channels,
300
+ )
301
+ )
302
+ self.in_channels = in_channels
303
+ if use_t_tgt:
304
+ self.t_tgt_embedder = TimestepEmbedder(hidden_size)
305
+ nn.init.normal_(self.t_tgt_embedder.mlp[0].weight, std=0.02)
306
+ nn.init.normal_(self.t_tgt_embedder.mlp[2].weight, std=0.02)
307
+
308
+ def load_state_dict(self, state_dict, strict: bool = True):
309
+ extra = ("t_tgt_embedder.",)
310
+ has_extra = any(key.startswith(extra) for key in state_dict)
311
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
312
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs, extra_prefixes=extra)
313
+ if self.use_t_tgt and not has_extra:
314
+ strict = False
315
+ if not has_t_embedder:
316
+ strict = False
317
+ out = super().load_state_dict(remapped, strict=strict)
318
+ if not has_t_embedder:
319
+ for name, param in self.named_parameters():
320
+ if "timestep_embedder" in name:
321
+ param.data.zero_()
322
+ return out
323
+
324
+ def forward(self, x, y, t_src=None, t_tgt=None):
325
+ if self.use_t_src and t_src is not None:
326
+ timestep = (t_src * 1000).long()
327
+ else:
328
+ timestep = torch.zeros(x.shape[0], device=x.device, dtype=torch.long)
329
+
330
+ extra_cond = None
331
+ if self.use_t_tgt and t_tgt is not None:
332
+ extra_cond = self.t_tgt_embedder(t_tgt * 1000)
333
+
334
+ output = forward_dit_output(self.transformer, x, timestep, y, extra_cond=extra_cond)
335
+ return split_output_channels(output, self.in_channels)
336
+
337
+
338
+ class GeneratorDeep(nn.Module):
339
+ def __init__(
340
+ self,
341
+ *,
342
+ repeat: int,
343
+ depth: int = 28,
344
+ hidden_size: int = 1152,
345
+ patch_size: int = 2,
346
+ num_heads: int = 16,
347
+ learn_sigma: bool = False,
348
+ class_dropout_prob: float = 0.0,
349
+ input_size: int = 32,
350
+ num_classes: int = 1000,
351
+ in_channels: int = 4,
352
+ **_,
353
+ ):
354
+ super().__init__()
355
+ self.repeat = repeat
356
+ self._legacy_kwargs = {
357
+ "depth": depth,
358
+ "hidden_size": hidden_size,
359
+ "patch_size": patch_size,
360
+ "num_heads": num_heads,
361
+ }
362
+ dit_cls = get_dit_transformer_class()
363
+ self.transformer = dit_cls(
364
+ **build_dit_config(
365
+ depth=depth,
366
+ hidden_size=hidden_size,
367
+ patch_size=patch_size,
368
+ num_heads=num_heads,
369
+ learn_sigma=learn_sigma,
370
+ class_dropout_prob=class_dropout_prob,
371
+ input_size=input_size,
372
+ num_classes=num_classes,
373
+ in_channels=in_channels,
374
+ )
375
+ )
376
+ self.in_channels = in_channels
377
+
378
+ def load_state_dict(self, state_dict, strict: bool = True):
379
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs)
380
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
381
+ if not has_t_embedder:
382
+ strict = False
383
+ out = super().load_state_dict(remapped, strict=strict)
384
+ if not has_t_embedder:
385
+ for name, param in self.named_parameters():
386
+ if "timestep_embedder" in name:
387
+ param.data.zero_()
388
+ return out
389
+
390
+ def forward(self, x, y, *args, **kwargs):
391
+ hidden_states = self.transformer.pos_embed(x)
392
+ for t in torch.arange(1, 0, -1 / self.repeat).tolist():
393
+ timestep = torch.full([x.shape[0]], int(t * 1000), device=x.device, dtype=torch.long)
394
+ for block in self.transformer.transformer_blocks:
395
+ hidden_states = block(
396
+ hidden_states,
397
+ attention_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ timestep=timestep,
401
+ cross_attention_kwargs=None,
402
+ class_labels=y,
403
+ )
404
+
405
+ conditioning = self.transformer.transformer_blocks[0].norm1.emb(
406
+ torch.zeros(x.shape[0], device=x.device, dtype=torch.long),
407
+ y,
408
+ hidden_dtype=hidden_states.dtype,
409
+ )
410
+ shift, scale = self.transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
411
+ hidden_states = self.transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
412
+ hidden_states = self.transformer.proj_out_2(hidden_states)
413
+
414
+ height = width = int(hidden_states.shape[1] ** 0.5)
415
+ hidden_states = hidden_states.reshape(
416
+ shape=(
417
+ -1,
418
+ height,
419
+ width,
420
+ self.transformer.patch_size,
421
+ self.transformer.patch_size,
422
+ self.transformer.out_channels,
423
+ )
424
+ )
425
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
426
+ output = hidden_states.reshape(
427
+ shape=(-1, self.transformer.out_channels, height * self.transformer.patch_size, width * self.transformer.patch_size)
428
+ )
429
+ return split_output_channels(output, self.in_channels)
430
+
431
+
432
+ class AFMGenerator2DModel(Generator, ModelMixin, ConfigMixin):
433
+ config_name = "config.json"
434
+
435
+ @register_to_config
436
+ def __init__(
437
+ self,
438
+ model_type: str = "AFM-XL/2",
439
+ architecture: str = "standard",
440
+ repeat: int = 1,
441
+ use_t_src: bool = False,
442
+ use_t_tgt: bool = False,
443
+ depth: int = 28,
444
+ hidden_size: int = 1152,
445
+ patch_size: int = 2,
446
+ num_heads: int = 16,
447
+ learn_sigma: bool = False,
448
+ class_dropout_prob: float = 0.0,
449
+ input_size: int = 32,
450
+ num_classes: int = 1000,
451
+ in_channels: int = 4,
452
+ pred_type: str = "x",
453
+ num_inference_steps: int = 1,
454
+ ) -> None:
455
+ if architecture == "deep":
456
+ raise ValueError("Use AFMGeneratorDeep2DModel for deep AFM checkpoints.")
457
+ Generator.__init__(
458
+ self,
459
+ use_t_src=use_t_src,
460
+ use_t_tgt=use_t_tgt,
461
+ depth=depth,
462
+ hidden_size=hidden_size,
463
+ patch_size=patch_size,
464
+ num_heads=num_heads,
465
+ learn_sigma=learn_sigma,
466
+ class_dropout_prob=class_dropout_prob,
467
+ input_size=input_size,
468
+ num_classes=num_classes,
469
+ in_channels=in_channels,
470
+ )
471
+
472
+
473
+ class AFMGeneratorDeep2DModel(GeneratorDeep, ModelMixin, ConfigMixin):
474
+ config_name = "config.json"
475
+
476
+ @register_to_config
477
+ def __init__(
478
+ self,
479
+ model_type: str = "AFM-XL/2",
480
+ architecture: str = "deep",
481
+ repeat: int = 2,
482
+ use_t_src: bool = False,
483
+ use_t_tgt: bool = False,
484
+ depth: int = 28,
485
+ hidden_size: int = 1152,
486
+ patch_size: int = 2,
487
+ num_heads: int = 16,
488
+ learn_sigma: bool = False,
489
+ class_dropout_prob: float = 0.0,
490
+ input_size: int = 32,
491
+ num_classes: int = 1000,
492
+ in_channels: int = 4,
493
+ pred_type: str = "x",
494
+ num_inference_steps: int = 1,
495
+ ) -> None:
496
+ GeneratorDeep.__init__(
497
+ self,
498
+ repeat=repeat,
499
+ depth=depth,
500
+ hidden_size=hidden_size,
501
+ patch_size=patch_size,
502
+ num_heads=num_heads,
503
+ learn_sigma=learn_sigma,
504
+ class_dropout_prob=class_dropout_prob,
505
+ input_size=input_size,
506
+ num_classes=num_classes,
507
+ in_channels=in_channels,
508
+ )
509
+
510
+
511
+ __all__ = ["AFMGenerator2DModel", "AFMGeneratorDeep2DModel"]
AFM-L-2-1NFE-guided/model_index.json ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "AFMPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "generator": [
8
+ "modeling_afm",
9
+ "AFMGenerator2DModel"
10
+ ],
11
+ "vae": [
12
+ "diffusers",
13
+ "AutoencoderKL"
14
+ ],
15
+ "scheduler": [
16
+ "scheduling_continuous_flow",
17
+ "ContinuousFlowMatchScheduler"
18
+ ],
19
+ "pred_type": "x",
20
+ "id2label": {
21
+ "0": "tench, Tinca tinca",
22
+ "1": "goldfish, Carassius auratus",
23
+ "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
24
+ "3": "tiger shark, Galeocerdo cuvieri",
25
+ "4": "hammerhead, hammerhead shark",
26
+ "5": "electric ray, crampfish, numbfish, torpedo",
27
+ "6": "stingray",
28
+ "7": "cock",
29
+ "8": "hen",
30
+ "9": "ostrich, Struthio camelus",
31
+ "10": "brambling, Fringilla montifringilla",
32
+ "11": "goldfinch, Carduelis carduelis",
33
+ "12": "house finch, linnet, Carpodacus mexicanus",
34
+ "13": "junco, snowbird",
35
+ "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
36
+ "15": "robin, American robin, Turdus migratorius",
37
+ "16": "bulbul",
38
+ "17": "jay",
39
+ "18": "magpie",
40
+ "19": "chickadee",
41
+ "20": "water ouzel, dipper",
42
+ "21": "kite",
43
+ "22": "bald eagle, American eagle, Haliaeetus leucocephalus",
44
+ "23": "vulture",
45
+ "24": "great grey owl, great gray owl, Strix nebulosa",
46
+ "25": "European fire salamander, Salamandra salamandra",
47
+ "26": "common newt, Triturus vulgaris",
48
+ "27": "eft",
49
+ "28": "spotted salamander, Ambystoma maculatum",
50
+ "29": "axolotl, mud puppy, Ambystoma mexicanum",
51
+ "30": "bullfrog, Rana catesbeiana",
52
+ "31": "tree frog, tree-frog",
53
+ "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
54
+ "33": "loggerhead, loggerhead turtle, Caretta caretta",
55
+ "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
56
+ "35": "mud turtle",
57
+ "36": "terrapin",
58
+ "37": "box turtle, box tortoise",
59
+ "38": "banded gecko",
60
+ "39": "common iguana, iguana, Iguana iguana",
61
+ "40": "American chameleon, anole, Anolis carolinensis",
62
+ "41": "whiptail, whiptail lizard",
63
+ "42": "agama",
64
+ "43": "frilled lizard, Chlamydosaurus kingi",
65
+ "44": "alligator lizard",
66
+ "45": "Gila monster, Heloderma suspectum",
67
+ "46": "green lizard, Lacerta viridis",
68
+ "47": "African chameleon, Chamaeleo chamaeleon",
69
+ "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
70
+ "49": "African crocodile, Nile crocodile, Crocodylus niloticus",
71
+ "50": "American alligator, Alligator mississipiensis",
72
+ "51": "triceratops",
73
+ "52": "thunder snake, worm snake, Carphophis amoenus",
74
+ "53": "ringneck snake, ring-necked snake, ring snake",
75
+ "54": "hognose snake, puff adder, sand viper",
76
+ "55": "green snake, grass snake",
77
+ "56": "king snake, kingsnake",
78
+ "57": "garter snake, grass snake",
79
+ "58": "water snake",
80
+ "59": "vine snake",
81
+ "60": "night snake, Hypsiglena torquata",
82
+ "61": "boa constrictor, Constrictor constrictor",
83
+ "62": "rock python, rock snake, Python sebae",
84
+ "63": "Indian cobra, Naja naja",
85
+ "64": "green mamba",
86
+ "65": "sea snake",
87
+ "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
88
+ "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
89
+ "68": "sidewinder, horned rattlesnake, Crotalus cerastes",
90
+ "69": "trilobite",
91
+ "70": "harvestman, daddy longlegs, Phalangium opilio",
92
+ "71": "scorpion",
93
+ "72": "black and gold garden spider, Argiope aurantia",
94
+ "73": "barn spider, Araneus cavaticus",
95
+ "74": "garden spider, Aranea diademata",
96
+ "75": "black widow, Latrodectus mactans",
97
+ "76": "tarantula",
98
+ "77": "wolf spider, hunting spider",
99
+ "78": "tick",
100
+ "79": "centipede",
101
+ "80": "black grouse",
102
+ "81": "ptarmigan",
103
+ "82": "ruffed grouse, partridge, Bonasa umbellus",
104
+ "83": "prairie chicken, prairie grouse, prairie fowl",
105
+ "84": "peacock",
106
+ "85": "quail",
107
+ "86": "partridge",
108
+ "87": "African grey, African gray, Psittacus erithacus",
109
+ "88": "macaw",
110
+ "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
111
+ "90": "lorikeet",
112
+ "91": "coucal",
113
+ "92": "bee eater",
114
+ "93": "hornbill",
115
+ "94": "hummingbird",
116
+ "95": "jacamar",
117
+ "96": "toucan",
118
+ "97": "drake",
119
+ "98": "red-breasted merganser, Mergus serrator",
120
+ "99": "goose",
121
+ "100": "black swan, Cygnus atratus",
122
+ "101": "tusker",
123
+ "102": "echidna, spiny anteater, anteater",
124
+ "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
125
+ "104": "wallaby, brush kangaroo",
126
+ "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
127
+ "106": "wombat",
128
+ "107": "jellyfish",
129
+ "108": "sea anemone, anemone",
130
+ "109": "brain coral",
131
+ "110": "flatworm, platyhelminth",
132
+ "111": "nematode, nematode worm, roundworm",
133
+ "112": "conch",
134
+ "113": "snail",
135
+ "114": "slug",
136
+ "115": "sea slug, nudibranch",
137
+ "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
138
+ "117": "chambered nautilus, pearly nautilus, nautilus",
139
+ "118": "Dungeness crab, Cancer magister",
140
+ "119": "rock crab, Cancer irroratus",
141
+ "120": "fiddler crab",
142
+ "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
143
+ "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
144
+ "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
145
+ "124": "crayfish, crawfish, crawdad, crawdaddy",
146
+ "125": "hermit crab",
147
+ "126": "isopod",
148
+ "127": "white stork, Ciconia ciconia",
149
+ "128": "black stork, Ciconia nigra",
150
+ "129": "spoonbill",
151
+ "130": "flamingo",
152
+ "131": "little blue heron, Egretta caerulea",
153
+ "132": "American egret, great white heron, Egretta albus",
154
+ "133": "bittern",
155
+ "134": "crane",
156
+ "135": "limpkin, Aramus pictus",
157
+ "136": "European gallinule, Porphyrio porphyrio",
158
+ "137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
159
+ "138": "bustard",
160
+ "139": "ruddy turnstone, Arenaria interpres",
161
+ "140": "red-backed sandpiper, dunlin, Erolia alpina",
162
+ "141": "redshank, Tringa totanus",
163
+ "142": "dowitcher",
164
+ "143": "oystercatcher, oyster catcher",
165
+ "144": "pelican",
166
+ "145": "king penguin, Aptenodytes patagonica",
167
+ "146": "albatross, mollymawk",
168
+ "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
169
+ "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
170
+ "149": "dugong, Dugong dugon",
171
+ "150": "sea lion",
172
+ "151": "Chihuahua",
173
+ "152": "Japanese spaniel",
174
+ "153": "Maltese dog, Maltese terrier, Maltese",
175
+ "154": "Pekinese, Pekingese, Peke",
176
+ "155": "Shih-Tzu",
177
+ "156": "Blenheim spaniel",
178
+ "157": "papillon",
179
+ "158": "toy terrier",
180
+ "159": "Rhodesian ridgeback",
181
+ "160": "Afghan hound, Afghan",
182
+ "161": "basset, basset hound",
183
+ "162": "beagle",
184
+ "163": "bloodhound, sleuthhound",
185
+ "164": "bluetick",
186
+ "165": "black-and-tan coonhound",
187
+ "166": "Walker hound, Walker foxhound",
188
+ "167": "English foxhound",
189
+ "168": "redbone",
190
+ "169": "borzoi, Russian wolfhound",
191
+ "170": "Irish wolfhound",
192
+ "171": "Italian greyhound",
193
+ "172": "whippet",
194
+ "173": "Ibizan hound, Ibizan Podenco",
195
+ "174": "Norwegian elkhound, elkhound",
196
+ "175": "otterhound, otter hound",
197
+ "176": "Saluki, gazelle hound",
198
+ "177": "Scottish deerhound, deerhound",
199
+ "178": "Weimaraner",
200
+ "179": "Staffordshire bullterrier, Staffordshire bull terrier",
201
+ "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
202
+ "181": "Bedlington terrier",
203
+ "182": "Border terrier",
204
+ "183": "Kerry blue terrier",
205
+ "184": "Irish terrier",
206
+ "185": "Norfolk terrier",
207
+ "186": "Norwich terrier",
208
+ "187": "Yorkshire terrier",
209
+ "188": "wire-haired fox terrier",
210
+ "189": "Lakeland terrier",
211
+ "190": "Sealyham terrier, Sealyham",
212
+ "191": "Airedale, Airedale terrier",
213
+ "192": "cairn, cairn terrier",
214
+ "193": "Australian terrier",
215
+ "194": "Dandie Dinmont, Dandie Dinmont terrier",
216
+ "195": "Boston bull, Boston terrier",
217
+ "196": "miniature schnauzer",
218
+ "197": "giant schnauzer",
219
+ "198": "standard schnauzer",
220
+ "199": "Scotch terrier, Scottish terrier, Scottie",
221
+ "200": "Tibetan terrier, chrysanthemum dog",
222
+ "201": "silky terrier, Sydney silky",
223
+ "202": "soft-coated wheaten terrier",
224
+ "203": "West Highland white terrier",
225
+ "204": "Lhasa, Lhasa apso",
226
+ "205": "flat-coated retriever",
227
+ "206": "curly-coated retriever",
228
+ "207": "golden retriever",
229
+ "208": "Labrador retriever",
230
+ "209": "Chesapeake Bay retriever",
231
+ "210": "German short-haired pointer",
232
+ "211": "vizsla, Hungarian pointer",
233
+ "212": "English setter",
234
+ "213": "Irish setter, red setter",
235
+ "214": "Gordon setter",
236
+ "215": "Brittany spaniel",
237
+ "216": "clumber, clumber spaniel",
238
+ "217": "English springer, English springer spaniel",
239
+ "218": "Welsh springer spaniel",
240
+ "219": "cocker spaniel, English cocker spaniel, cocker",
241
+ "220": "Sussex spaniel",
242
+ "221": "Irish water spaniel",
243
+ "222": "kuvasz",
244
+ "223": "schipperke",
245
+ "224": "groenendael",
246
+ "225": "malinois",
247
+ "226": "briard",
248
+ "227": "kelpie",
249
+ "228": "komondor",
250
+ "229": "Old English sheepdog, bobtail",
251
+ "230": "Shetland sheepdog, Shetland sheep dog, Shetland",
252
+ "231": "collie",
253
+ "232": "Border collie",
254
+ "233": "Bouvier des Flandres, Bouviers des Flandres",
255
+ "234": "Rottweiler",
256
+ "235": "German shepherd, German shepherd dog, German police dog, alsatian",
257
+ "236": "Doberman, Doberman pinscher",
258
+ "237": "miniature pinscher",
259
+ "238": "Greater Swiss Mountain dog",
260
+ "239": "Bernese mountain dog",
261
+ "240": "Appenzeller",
262
+ "241": "EntleBucher",
263
+ "242": "boxer",
264
+ "243": "bull mastiff",
265
+ "244": "Tibetan mastiff",
266
+ "245": "French bulldog",
267
+ "246": "Great Dane",
268
+ "247": "Saint Bernard, St Bernard",
269
+ "248": "Eskimo dog, husky",
270
+ "249": "malamute, malemute, Alaskan malamute",
271
+ "250": "Siberian husky",
272
+ "251": "dalmatian, coach dog, carriage dog",
273
+ "252": "affenpinscher, monkey pinscher, monkey dog",
274
+ "253": "basenji",
275
+ "254": "pug, pug-dog",
276
+ "255": "Leonberg",
277
+ "256": "Newfoundland, Newfoundland dog",
278
+ "257": "Great Pyrenees",
279
+ "258": "Samoyed, Samoyede",
280
+ "259": "Pomeranian",
281
+ "260": "chow, chow chow",
282
+ "261": "keeshond",
283
+ "262": "Brabancon griffon",
284
+ "263": "Pembroke, Pembroke Welsh corgi",
285
+ "264": "Cardigan, Cardigan Welsh corgi",
286
+ "265": "toy poodle",
287
+ "266": "miniature poodle",
288
+ "267": "standard poodle",
289
+ "268": "Mexican hairless",
290
+ "269": "timber wolf, grey wolf, gray wolf, Canis lupus",
291
+ "270": "white wolf, Arctic wolf, Canis lupus tundrarum",
292
+ "271": "red wolf, maned wolf, Canis rufus, Canis niger",
293
+ "272": "coyote, prairie wolf, brush wolf, Canis latrans",
294
+ "273": "dingo, warrigal, warragal, Canis dingo",
295
+ "274": "dhole, Cuon alpinus",
296
+ "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
297
+ "276": "hyena, hyaena",
298
+ "277": "red fox, Vulpes vulpes",
299
+ "278": "kit fox, Vulpes macrotis",
300
+ "279": "Arctic fox, white fox, Alopex lagopus",
301
+ "280": "grey fox, gray fox, Urocyon cinereoargenteus",
302
+ "281": "tabby, tabby cat",
303
+ "282": "tiger cat",
304
+ "283": "Persian cat",
305
+ "284": "Siamese cat, Siamese",
306
+ "285": "Egyptian cat",
307
+ "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
308
+ "287": "lynx, catamount",
309
+ "288": "leopard, Panthera pardus",
310
+ "289": "snow leopard, ounce, Panthera uncia",
311
+ "290": "jaguar, panther, Panthera onca, Felis onca",
312
+ "291": "lion, king of beasts, Panthera leo",
313
+ "292": "tiger, Panthera tigris",
314
+ "293": "cheetah, chetah, Acinonyx jubatus",
315
+ "294": "brown bear, bruin, Ursus arctos",
316
+ "295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
317
+ "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
318
+ "297": "sloth bear, Melursus ursinus, Ursus ursinus",
319
+ "298": "mongoose",
320
+ "299": "meerkat, mierkat",
321
+ "300": "tiger beetle",
322
+ "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
323
+ "302": "ground beetle, carabid beetle",
324
+ "303": "long-horned beetle, longicorn, longicorn beetle",
325
+ "304": "leaf beetle, chrysomelid",
326
+ "305": "dung beetle",
327
+ "306": "rhinoceros beetle",
328
+ "307": "weevil",
329
+ "308": "fly",
330
+ "309": "bee",
331
+ "310": "ant, emmet, pismire",
332
+ "311": "grasshopper, hopper",
333
+ "312": "cricket",
334
+ "313": "walking stick, walkingstick, stick insect",
335
+ "314": "cockroach, roach",
336
+ "315": "mantis, mantid",
337
+ "316": "cicada, cicala",
338
+ "317": "leafhopper",
339
+ "318": "lacewing, lacewing fly",
340
+ "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
341
+ "320": "damselfly",
342
+ "321": "admiral",
343
+ "322": "ringlet, ringlet butterfly",
344
+ "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
345
+ "324": "cabbage butterfly",
346
+ "325": "sulphur butterfly, sulfur butterfly",
347
+ "326": "lycaenid, lycaenid butterfly",
348
+ "327": "starfish, sea star",
349
+ "328": "sea urchin",
350
+ "329": "sea cucumber, holothurian",
351
+ "330": "wood rabbit, cottontail, cottontail rabbit",
352
+ "331": "hare",
353
+ "332": "Angora, Angora rabbit",
354
+ "333": "hamster",
355
+ "334": "porcupine, hedgehog",
356
+ "335": "fox squirrel, eastern fox squirrel, Sciurus niger",
357
+ "336": "marmot",
358
+ "337": "beaver",
359
+ "338": "guinea pig, Cavia cobaya",
360
+ "339": "sorrel",
361
+ "340": "zebra",
362
+ "341": "hog, pig, grunter, squealer, Sus scrofa",
363
+ "342": "wild boar, boar, Sus scrofa",
364
+ "343": "warthog",
365
+ "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
366
+ "345": "ox",
367
+ "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
368
+ "347": "bison",
369
+ "348": "ram, tup",
370
+ "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
371
+ "350": "ibex, Capra ibex",
372
+ "351": "hartebeest",
373
+ "352": "impala, Aepyceros melampus",
374
+ "353": "gazelle",
375
+ "354": "Arabian camel, dromedary, Camelus dromedarius",
376
+ "355": "llama",
377
+ "356": "weasel",
378
+ "357": "mink",
379
+ "358": "polecat, fitch, foulmart, foumart, Mustela putorius",
380
+ "359": "black-footed ferret, ferret, Mustela nigripes",
381
+ "360": "otter",
382
+ "361": "skunk, polecat, wood pussy",
383
+ "362": "badger",
384
+ "363": "armadillo",
385
+ "364": "three-toed sloth, ai, Bradypus tridactylus",
386
+ "365": "orangutan, orang, orangutang, Pongo pygmaeus",
387
+ "366": "gorilla, Gorilla gorilla",
388
+ "367": "chimpanzee, chimp, Pan troglodytes",
389
+ "368": "gibbon, Hylobates lar",
390
+ "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
391
+ "370": "guenon, guenon monkey",
392
+ "371": "patas, hussar monkey, Erythrocebus patas",
393
+ "372": "baboon",
394
+ "373": "macaque",
395
+ "374": "langur",
396
+ "375": "colobus, colobus monkey",
397
+ "376": "proboscis monkey, Nasalis larvatus",
398
+ "377": "marmoset",
399
+ "378": "capuchin, ringtail, Cebus capucinus",
400
+ "379": "howler monkey, howler",
401
+ "380": "titi, titi monkey",
402
+ "381": "spider monkey, Ateles geoffroyi",
403
+ "382": "squirrel monkey, Saimiri sciureus",
404
+ "383": "Madagascar cat, ring-tailed lemur, Lemur catta",
405
+ "384": "indri, indris, Indri indri, Indri brevicaudatus",
406
+ "385": "Indian elephant, Elephas maximus",
407
+ "386": "African elephant, Loxodonta africana",
408
+ "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
409
+ "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
410
+ "389": "barracouta, snoek",
411
+ "390": "eel",
412
+ "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
413
+ "392": "rock beauty, Holocanthus tricolor",
414
+ "393": "anemone fish",
415
+ "394": "sturgeon",
416
+ "395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
417
+ "396": "lionfish",
418
+ "397": "puffer, pufferfish, blowfish, globefish",
419
+ "398": "abacus",
420
+ "399": "abaya",
421
+ "400": "academic gown, academic robe, judge robe",
422
+ "401": "accordion, piano accordion, squeeze box",
423
+ "402": "acoustic guitar",
424
+ "403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
425
+ "404": "airliner",
426
+ "405": "airship, dirigible",
427
+ "406": "altar",
428
+ "407": "ambulance",
429
+ "408": "amphibian, amphibious vehicle",
430
+ "409": "analog clock",
431
+ "410": "apiary, bee house",
432
+ "411": "apron",
433
+ "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
434
+ "413": "assault rifle, assault gun",
435
+ "414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
436
+ "415": "bakery, bakeshop, bakehouse",
437
+ "416": "balance beam, beam",
438
+ "417": "balloon",
439
+ "418": "ballpoint, ballpoint pen, ballpen, Biro",
440
+ "419": "Band Aid",
441
+ "420": "banjo",
442
+ "421": "bannister, banister, balustrade, balusters, handrail",
443
+ "422": "barbell",
444
+ "423": "barber chair",
445
+ "424": "barbershop",
446
+ "425": "barn",
447
+ "426": "barometer",
448
+ "427": "barrel, cask",
449
+ "428": "barrow, garden cart, lawn cart, wheelbarrow",
450
+ "429": "baseball",
451
+ "430": "basketball",
452
+ "431": "bassinet",
453
+ "432": "bassoon",
454
+ "433": "bathing cap, swimming cap",
455
+ "434": "bath towel",
456
+ "435": "bathtub, bathing tub, bath, tub",
457
+ "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
458
+ "437": "beacon, lighthouse, beacon light, pharos",
459
+ "438": "beaker",
460
+ "439": "bearskin, busby, shako",
461
+ "440": "beer bottle",
462
+ "441": "beer glass",
463
+ "442": "bell cote, bell cot",
464
+ "443": "bib",
465
+ "444": "bicycle-built-for-two, tandem bicycle, tandem",
466
+ "445": "bikini, two-piece",
467
+ "446": "binder, ring-binder",
468
+ "447": "binoculars, field glasses, opera glasses",
469
+ "448": "birdhouse",
470
+ "449": "boathouse",
471
+ "450": "bobsled, bobsleigh, bob",
472
+ "451": "bolo tie, bolo, bola tie, bola",
473
+ "452": "bonnet, poke bonnet",
474
+ "453": "bookcase",
475
+ "454": "bookshop, bookstore, bookstall",
476
+ "455": "bottlecap",
477
+ "456": "bow",
478
+ "457": "bow tie, bow-tie, bowtie",
479
+ "458": "brass, memorial tablet, plaque",
480
+ "459": "brassiere, bra, bandeau",
481
+ "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
482
+ "461": "breastplate, aegis, egis",
483
+ "462": "broom",
484
+ "463": "bucket, pail",
485
+ "464": "buckle",
486
+ "465": "bulletproof vest",
487
+ "466": "bullet train, bullet",
488
+ "467": "butcher shop, meat market",
489
+ "468": "cab, hack, taxi, taxicab",
490
+ "469": "caldron, cauldron",
491
+ "470": "candle, taper, wax light",
492
+ "471": "cannon",
493
+ "472": "canoe",
494
+ "473": "can opener, tin opener",
495
+ "474": "cardigan",
496
+ "475": "car mirror",
497
+ "476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
498
+ "477": "carpenters kit, tool kit",
499
+ "478": "carton",
500
+ "479": "car wheel",
501
+ "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
502
+ "481": "cassette",
503
+ "482": "cassette player",
504
+ "483": "castle",
505
+ "484": "catamaran",
506
+ "485": "CD player",
507
+ "486": "cello, violoncello",
508
+ "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
509
+ "488": "chain",
510
+ "489": "chainlink fence",
511
+ "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
512
+ "491": "chain saw, chainsaw",
513
+ "492": "chest",
514
+ "493": "chiffonier, commode",
515
+ "494": "chime, bell, gong",
516
+ "495": "china cabinet, china closet",
517
+ "496": "Christmas stocking",
518
+ "497": "church, church building",
519
+ "498": "cinema, movie theater, movie theatre, movie house, picture palace",
520
+ "499": "cleaver, meat cleaver, chopper",
521
+ "500": "cliff dwelling",
522
+ "501": "cloak",
523
+ "502": "clog, geta, patten, sabot",
524
+ "503": "cocktail shaker",
525
+ "504": "coffee mug",
526
+ "505": "coffeepot",
527
+ "506": "coil, spiral, volute, whorl, helix",
528
+ "507": "combination lock",
529
+ "508": "computer keyboard, keypad",
530
+ "509": "confectionery, confectionary, candy store",
531
+ "510": "container ship, containership, container vessel",
532
+ "511": "convertible",
533
+ "512": "corkscrew, bottle screw",
534
+ "513": "cornet, horn, trumpet, trump",
535
+ "514": "cowboy boot",
536
+ "515": "cowboy hat, ten-gallon hat",
537
+ "516": "cradle",
538
+ "517": "crane",
539
+ "518": "crash helmet",
540
+ "519": "crate",
541
+ "520": "crib, cot",
542
+ "521": "Crock Pot",
543
+ "522": "croquet ball",
544
+ "523": "crutch",
545
+ "524": "cuirass",
546
+ "525": "dam, dike, dyke",
547
+ "526": "desk",
548
+ "527": "desktop computer",
549
+ "528": "dial telephone, dial phone",
550
+ "529": "diaper, nappy, napkin",
551
+ "530": "digital clock",
552
+ "531": "digital watch",
553
+ "532": "dining table, board",
554
+ "533": "dishrag, dishcloth",
555
+ "534": "dishwasher, dish washer, dishwashing machine",
556
+ "535": "disk brake, disc brake",
557
+ "536": "dock, dockage, docking facility",
558
+ "537": "dogsled, dog sled, dog sleigh",
559
+ "538": "dome",
560
+ "539": "doormat, welcome mat",
561
+ "540": "drilling platform, offshore rig",
562
+ "541": "drum, membranophone, tympan",
563
+ "542": "drumstick",
564
+ "543": "dumbbell",
565
+ "544": "Dutch oven",
566
+ "545": "electric fan, blower",
567
+ "546": "electric guitar",
568
+ "547": "electric locomotive",
569
+ "548": "entertainment center",
570
+ "549": "envelope",
571
+ "550": "espresso maker",
572
+ "551": "face powder",
573
+ "552": "feather boa, boa",
574
+ "553": "file, file cabinet, filing cabinet",
575
+ "554": "fireboat",
576
+ "555": "fire engine, fire truck",
577
+ "556": "fire screen, fireguard",
578
+ "557": "flagpole, flagstaff",
579
+ "558": "flute, transverse flute",
580
+ "559": "folding chair",
581
+ "560": "football helmet",
582
+ "561": "forklift",
583
+ "562": "fountain",
584
+ "563": "fountain pen",
585
+ "564": "four-poster",
586
+ "565": "freight car",
587
+ "566": "French horn, horn",
588
+ "567": "frying pan, frypan, skillet",
589
+ "568": "fur coat",
590
+ "569": "garbage truck, dustcart",
591
+ "570": "gasmask, respirator, gas helmet",
592
+ "571": "gas pump, gasoline pump, petrol pump, island dispenser",
593
+ "572": "goblet",
594
+ "573": "go-kart",
595
+ "574": "golf ball",
596
+ "575": "golfcart, golf cart",
597
+ "576": "gondola",
598
+ "577": "gong, tam-tam",
599
+ "578": "gown",
600
+ "579": "grand piano, grand",
601
+ "580": "greenhouse, nursery, glasshouse",
602
+ "581": "grille, radiator grille",
603
+ "582": "grocery store, grocery, food market, market",
604
+ "583": "guillotine",
605
+ "584": "hair slide",
606
+ "585": "hair spray",
607
+ "586": "half track",
608
+ "587": "hammer",
609
+ "588": "hamper",
610
+ "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
611
+ "590": "hand-held computer, hand-held microcomputer",
612
+ "591": "handkerchief, hankie, hanky, hankey",
613
+ "592": "hard disc, hard disk, fixed disk",
614
+ "593": "harmonica, mouth organ, harp, mouth harp",
615
+ "594": "harp",
616
+ "595": "harvester, reaper",
617
+ "596": "hatchet",
618
+ "597": "holster",
619
+ "598": "home theater, home theatre",
620
+ "599": "honeycomb",
621
+ "600": "hook, claw",
622
+ "601": "hoopskirt, crinoline",
623
+ "602": "horizontal bar, high bar",
624
+ "603": "horse cart, horse-cart",
625
+ "604": "hourglass",
626
+ "605": "iPod",
627
+ "606": "iron, smoothing iron",
628
+ "607": "jack-o-lantern",
629
+ "608": "jean, blue jean, denim",
630
+ "609": "jeep, landrover",
631
+ "610": "jersey, T-shirt, tee shirt",
632
+ "611": "jigsaw puzzle",
633
+ "612": "jinrikisha, ricksha, rickshaw",
634
+ "613": "joystick",
635
+ "614": "kimono",
636
+ "615": "knee pad",
637
+ "616": "knot",
638
+ "617": "lab coat, laboratory coat",
639
+ "618": "ladle",
640
+ "619": "lampshade, lamp shade",
641
+ "620": "laptop, laptop computer",
642
+ "621": "lawn mower, mower",
643
+ "622": "lens cap, lens cover",
644
+ "623": "letter opener, paper knife, paperknife",
645
+ "624": "library",
646
+ "625": "lifeboat",
647
+ "626": "lighter, light, igniter, ignitor",
648
+ "627": "limousine, limo",
649
+ "628": "liner, ocean liner",
650
+ "629": "lipstick, lip rouge",
651
+ "630": "Loafer",
652
+ "631": "lotion",
653
+ "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
654
+ "633": "loupe, jewelers loupe",
655
+ "634": "lumbermill, sawmill",
656
+ "635": "magnetic compass",
657
+ "636": "mailbag, postbag",
658
+ "637": "mailbox, letter box",
659
+ "638": "maillot",
660
+ "639": "maillot, tank suit",
661
+ "640": "manhole cover",
662
+ "641": "maraca",
663
+ "642": "marimba, xylophone",
664
+ "643": "mask",
665
+ "644": "matchstick",
666
+ "645": "maypole",
667
+ "646": "maze, labyrinth",
668
+ "647": "measuring cup",
669
+ "648": "medicine chest, medicine cabinet",
670
+ "649": "megalith, megalithic structure",
671
+ "650": "microphone, mike",
672
+ "651": "microwave, microwave oven",
673
+ "652": "military uniform",
674
+ "653": "milk can",
675
+ "654": "minibus",
676
+ "655": "miniskirt, mini",
677
+ "656": "minivan",
678
+ "657": "missile",
679
+ "658": "mitten",
680
+ "659": "mixing bowl",
681
+ "660": "mobile home, manufactured home",
682
+ "661": "Model T",
683
+ "662": "modem",
684
+ "663": "monastery",
685
+ "664": "monitor",
686
+ "665": "moped",
687
+ "666": "mortar",
688
+ "667": "mortarboard",
689
+ "668": "mosque",
690
+ "669": "mosquito net",
691
+ "670": "motor scooter, scooter",
692
+ "671": "mountain bike, all-terrain bike, off-roader",
693
+ "672": "mountain tent",
694
+ "673": "mouse, computer mouse",
695
+ "674": "mousetrap",
696
+ "675": "moving van",
697
+ "676": "muzzle",
698
+ "677": "nail",
699
+ "678": "neck brace",
700
+ "679": "necklace",
701
+ "680": "nipple",
702
+ "681": "notebook, notebook computer",
703
+ "682": "obelisk",
704
+ "683": "oboe, hautboy, hautbois",
705
+ "684": "ocarina, sweet potato",
706
+ "685": "odometer, hodometer, mileometer, milometer",
707
+ "686": "oil filter",
708
+ "687": "organ, pipe organ",
709
+ "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
710
+ "689": "overskirt",
711
+ "690": "oxcart",
712
+ "691": "oxygen mask",
713
+ "692": "packet",
714
+ "693": "paddle, boat paddle",
715
+ "694": "paddlewheel, paddle wheel",
716
+ "695": "padlock",
717
+ "696": "paintbrush",
718
+ "697": "pajama, pyjama, pjs, jammies",
719
+ "698": "palace",
720
+ "699": "panpipe, pandean pipe, syrinx",
721
+ "700": "paper towel",
722
+ "701": "parachute, chute",
723
+ "702": "parallel bars, bars",
724
+ "703": "park bench",
725
+ "704": "parking meter",
726
+ "705": "passenger car, coach, carriage",
727
+ "706": "patio, terrace",
728
+ "707": "pay-phone, pay-station",
729
+ "708": "pedestal, plinth, footstall",
730
+ "709": "pencil box, pencil case",
731
+ "710": "pencil sharpener",
732
+ "711": "perfume, essence",
733
+ "712": "Petri dish",
734
+ "713": "photocopier",
735
+ "714": "pick, plectrum, plectron",
736
+ "715": "pickelhaube",
737
+ "716": "picket fence, paling",
738
+ "717": "pickup, pickup truck",
739
+ "718": "pier",
740
+ "719": "piggy bank, penny bank",
741
+ "720": "pill bottle",
742
+ "721": "pillow",
743
+ "722": "ping-pong ball",
744
+ "723": "pinwheel",
745
+ "724": "pirate, pirate ship",
746
+ "725": "pitcher, ewer",
747
+ "726": "plane, carpenters plane, woodworking plane",
748
+ "727": "planetarium",
749
+ "728": "plastic bag",
750
+ "729": "plate rack",
751
+ "730": "plow, plough",
752
+ "731": "plunger, plumbers helper",
753
+ "732": "Polaroid camera, Polaroid Land camera",
754
+ "733": "pole",
755
+ "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
756
+ "735": "poncho",
757
+ "736": "pool table, billiard table, snooker table",
758
+ "737": "pop bottle, soda bottle",
759
+ "738": "pot, flowerpot",
760
+ "739": "potters wheel",
761
+ "740": "power drill",
762
+ "741": "prayer rug, prayer mat",
763
+ "742": "printer",
764
+ "743": "prison, prison house",
765
+ "744": "projectile, missile",
766
+ "745": "projector",
767
+ "746": "puck, hockey puck",
768
+ "747": "punching bag, punch bag, punching ball, punchball",
769
+ "748": "purse",
770
+ "749": "quill, quill pen",
771
+ "750": "quilt, comforter, comfort, puff",
772
+ "751": "racer, race car, racing car",
773
+ "752": "racket, racquet",
774
+ "753": "radiator",
775
+ "754": "radio, wireless",
776
+ "755": "radio telescope, radio reflector",
777
+ "756": "rain barrel",
778
+ "757": "recreational vehicle, RV, R.V.",
779
+ "758": "reel",
780
+ "759": "reflex camera",
781
+ "760": "refrigerator, icebox",
782
+ "761": "remote control, remote",
783
+ "762": "restaurant, eating house, eating place, eatery",
784
+ "763": "revolver, six-gun, six-shooter",
785
+ "764": "rifle",
786
+ "765": "rocking chair, rocker",
787
+ "766": "rotisserie",
788
+ "767": "rubber eraser, rubber, pencil eraser",
789
+ "768": "rugby ball",
790
+ "769": "rule, ruler",
791
+ "770": "running shoe",
792
+ "771": "safe",
793
+ "772": "safety pin",
794
+ "773": "saltshaker, salt shaker",
795
+ "774": "sandal",
796
+ "775": "sarong",
797
+ "776": "sax, saxophone",
798
+ "777": "scabbard",
799
+ "778": "scale, weighing machine",
800
+ "779": "school bus",
801
+ "780": "schooner",
802
+ "781": "scoreboard",
803
+ "782": "screen, CRT screen",
804
+ "783": "screw",
805
+ "784": "screwdriver",
806
+ "785": "seat belt, seatbelt",
807
+ "786": "sewing machine",
808
+ "787": "shield, buckler",
809
+ "788": "shoe shop, shoe-shop, shoe store",
810
+ "789": "shoji",
811
+ "790": "shopping basket",
812
+ "791": "shopping cart",
813
+ "792": "shovel",
814
+ "793": "shower cap",
815
+ "794": "shower curtain",
816
+ "795": "ski",
817
+ "796": "ski mask",
818
+ "797": "sleeping bag",
819
+ "798": "slide rule, slipstick",
820
+ "799": "sliding door",
821
+ "800": "slot, one-armed bandit",
822
+ "801": "snorkel",
823
+ "802": "snowmobile",
824
+ "803": "snowplow, snowplough",
825
+ "804": "soap dispenser",
826
+ "805": "soccer ball",
827
+ "806": "sock",
828
+ "807": "solar dish, solar collector, solar furnace",
829
+ "808": "sombrero",
830
+ "809": "soup bowl",
831
+ "810": "space bar",
832
+ "811": "space heater",
833
+ "812": "space shuttle",
834
+ "813": "spatula",
835
+ "814": "speedboat",
836
+ "815": "spider web, spiders web",
837
+ "816": "spindle",
838
+ "817": "sports car, sport car",
839
+ "818": "spotlight, spot",
840
+ "819": "stage",
841
+ "820": "steam locomotive",
842
+ "821": "steel arch bridge",
843
+ "822": "steel drum",
844
+ "823": "stethoscope",
845
+ "824": "stole",
846
+ "825": "stone wall",
847
+ "826": "stopwatch, stop watch",
848
+ "827": "stove",
849
+ "828": "strainer",
850
+ "829": "streetcar, tram, tramcar, trolley, trolley car",
851
+ "830": "stretcher",
852
+ "831": "studio couch, day bed",
853
+ "832": "stupa, tope",
854
+ "833": "submarine, pigboat, sub, U-boat",
855
+ "834": "suit, suit of clothes",
856
+ "835": "sundial",
857
+ "836": "sunglass",
858
+ "837": "sunglasses, dark glasses, shades",
859
+ "838": "sunscreen, sunblock, sun blocker",
860
+ "839": "suspension bridge",
861
+ "840": "swab, swob, mop",
862
+ "841": "sweatshirt",
863
+ "842": "swimming trunks, bathing trunks",
864
+ "843": "swing",
865
+ "844": "switch, electric switch, electrical switch",
866
+ "845": "syringe",
867
+ "846": "table lamp",
868
+ "847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
869
+ "848": "tape player",
870
+ "849": "teapot",
871
+ "850": "teddy, teddy bear",
872
+ "851": "television, television system",
873
+ "852": "tennis ball",
874
+ "853": "thatch, thatched roof",
875
+ "854": "theater curtain, theatre curtain",
876
+ "855": "thimble",
877
+ "856": "thresher, thrasher, threshing machine",
878
+ "857": "throne",
879
+ "858": "tile roof",
880
+ "859": "toaster",
881
+ "860": "tobacco shop, tobacconist shop, tobacconist",
882
+ "861": "toilet seat",
883
+ "862": "torch",
884
+ "863": "totem pole",
885
+ "864": "tow truck, tow car, wrecker",
886
+ "865": "toyshop",
887
+ "866": "tractor",
888
+ "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
889
+ "868": "tray",
890
+ "869": "trench coat",
891
+ "870": "tricycle, trike, velocipede",
892
+ "871": "trimaran",
893
+ "872": "tripod",
894
+ "873": "triumphal arch",
895
+ "874": "trolleybus, trolley coach, trackless trolley",
896
+ "875": "trombone",
897
+ "876": "tub, vat",
898
+ "877": "turnstile",
899
+ "878": "typewriter keyboard",
900
+ "879": "umbrella",
901
+ "880": "unicycle, monocycle",
902
+ "881": "upright, upright piano",
903
+ "882": "vacuum, vacuum cleaner",
904
+ "883": "vase",
905
+ "884": "vault",
906
+ "885": "velvet",
907
+ "886": "vending machine",
908
+ "887": "vestment",
909
+ "888": "viaduct",
910
+ "889": "violin, fiddle",
911
+ "890": "volleyball",
912
+ "891": "waffle iron",
913
+ "892": "wall clock",
914
+ "893": "wallet, billfold, notecase, pocketbook",
915
+ "894": "wardrobe, closet, press",
916
+ "895": "warplane, military plane",
917
+ "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
918
+ "897": "washer, automatic washer, washing machine",
919
+ "898": "water bottle",
920
+ "899": "water jug",
921
+ "900": "water tower",
922
+ "901": "whiskey jug",
923
+ "902": "whistle",
924
+ "903": "wig",
925
+ "904": "window screen",
926
+ "905": "window shade",
927
+ "906": "Windsor tie",
928
+ "907": "wine bottle",
929
+ "908": "wing",
930
+ "909": "wok",
931
+ "910": "wooden spoon",
932
+ "911": "wool, woolen, woollen",
933
+ "912": "worm fence, snake fence, snake-rail fence, Virginia fence",
934
+ "913": "wreck",
935
+ "914": "yawl",
936
+ "915": "yurt",
937
+ "916": "web site, website, internet site, site",
938
+ "917": "comic book",
939
+ "918": "crossword puzzle, crossword",
940
+ "919": "street sign",
941
+ "920": "traffic light, traffic signal, stoplight",
942
+ "921": "book jacket, dust cover, dust jacket, dust wrapper",
943
+ "922": "menu",
944
+ "923": "plate",
945
+ "924": "guacamole",
946
+ "925": "consomme",
947
+ "926": "hot pot, hotpot",
948
+ "927": "trifle",
949
+ "928": "ice cream, icecream",
950
+ "929": "ice lolly, lolly, lollipop, popsicle",
951
+ "930": "French loaf",
952
+ "931": "bagel, beigel",
953
+ "932": "pretzel",
954
+ "933": "cheeseburger",
955
+ "934": "hotdog, hot dog, red hot",
956
+ "935": "mashed potato",
957
+ "936": "head cabbage",
958
+ "937": "broccoli",
959
+ "938": "cauliflower",
960
+ "939": "zucchini, courgette",
961
+ "940": "spaghetti squash",
962
+ "941": "acorn squash",
963
+ "942": "butternut squash",
964
+ "943": "cucumber, cuke",
965
+ "944": "artichoke, globe artichoke",
966
+ "945": "bell pepper",
967
+ "946": "cardoon",
968
+ "947": "mushroom",
969
+ "948": "Granny Smith",
970
+ "949": "strawberry",
971
+ "950": "orange",
972
+ "951": "lemon",
973
+ "952": "fig",
974
+ "953": "pineapple, ananas",
975
+ "954": "banana",
976
+ "955": "jackfruit, jak, jack",
977
+ "956": "custard apple",
978
+ "957": "pomegranate",
979
+ "958": "hay",
980
+ "959": "carbonara",
981
+ "960": "chocolate sauce, chocolate syrup",
982
+ "961": "dough",
983
+ "962": "meat loaf, meatloaf",
984
+ "963": "pizza, pizza pie",
985
+ "964": "potpie",
986
+ "965": "burrito",
987
+ "966": "red wine",
988
+ "967": "espresso",
989
+ "968": "cup",
990
+ "969": "eggnog",
991
+ "970": "alp",
992
+ "971": "bubble",
993
+ "972": "cliff, drop, drop-off",
994
+ "973": "coral reef",
995
+ "974": "geyser",
996
+ "975": "lakeside, lakeshore",
997
+ "976": "promontory, headland, head, foreland",
998
+ "977": "sandbar, sand bar",
999
+ "978": "seashore, coast, seacoast, sea-coast",
1000
+ "979": "valley, vale",
1001
+ "980": "volcano",
1002
+ "981": "ballplayer, baseball player",
1003
+ "982": "groom, bridegroom",
1004
+ "983": "scuba diver",
1005
+ "984": "rapeseed",
1006
+ "985": "daisy",
1007
+ "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
1008
+ "987": "corn",
1009
+ "988": "acorn",
1010
+ "989": "hip, rose hip, rosehip",
1011
+ "990": "buckeye, horse chestnut, conker",
1012
+ "991": "coral fungus",
1013
+ "992": "agaric",
1014
+ "993": "gyromitra",
1015
+ "994": "stinkhorn, carrion fungus",
1016
+ "995": "earthstar",
1017
+ "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
1018
+ "997": "bolete",
1019
+ "998": "ear, spike, capitulum",
1020
+ "999": "toilet tissue, toilet paper, bathroom tissue"
1021
+ }
1022
+ }
AFM-L-2-1NFE-guided/pipeline.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: AFMPipeline.
2
+
3
+ Load with native Hugging Face diffusers and trust_remote_code=True.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ from diffusers.image_processor import VaeImageProcessor
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
16
+ from diffusers.utils.torch_utils import randn_tensor
17
+
18
+
19
+ class AFMPipeline(DiffusionPipeline):
20
+ model_cpu_offload_seq = "generator->vae"
21
+
22
+ @staticmethod
23
+ def _coerce_scheduler(scheduler, generator):
24
+ if scheduler is not None and not isinstance(scheduler, (list, tuple)):
25
+ return scheduler
26
+ variant_path = getattr(generator.config, "_name_or_path", None)
27
+ if variant_path:
28
+ scheduler_dir = Path(variant_path).resolve().parent / "scheduler"
29
+ module_path = scheduler_dir / "scheduling_continuous_flow.py"
30
+ config_path = scheduler_dir / "scheduler_config.json"
31
+ if module_path.is_file() and config_path.is_file():
32
+ spec = importlib.util.spec_from_file_location("scheduling_continuous_flow", module_path)
33
+ if spec is not None and spec.loader is not None:
34
+ module = importlib.util.module_from_spec(spec)
35
+ spec.loader.exec_module(module)
36
+ return module.ContinuousFlowMatchScheduler.from_pretrained(str(scheduler_dir))
37
+ raise ValueError("AFMPipeline could not load ContinuousFlowMatchScheduler from the variant folder.")
38
+
39
+ def __init__(
40
+ self,
41
+ generator,
42
+ vae,
43
+ scheduler=None,
44
+ pred_type: str = "x",
45
+ id2label: Optional[Dict[Union[int, str], str]] = None,
46
+ ) -> None:
47
+ super().__init__()
48
+ scheduler = self._coerce_scheduler(scheduler, generator)
49
+ self.register_modules(generator=generator, vae=vae, scheduler=scheduler)
50
+ self.register_to_config(pred_type=pred_type)
51
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
52
+ self._id2label = self._normalize_id2label(id2label)
53
+ self.labels = self._build_label2id(self._id2label)
54
+ self._labels_loaded_from_model_index = bool(self._id2label)
55
+
56
+ @staticmethod
57
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
58
+ if not id2label:
59
+ return {}
60
+ return {int(key): value for key, value in id2label.items()}
61
+
62
+ @staticmethod
63
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
64
+ if not variant_path:
65
+ return {}
66
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
67
+ if not model_index_path.exists():
68
+ return {}
69
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
70
+ id2label = raw.get("id2label")
71
+ if not isinstance(id2label, dict):
72
+ return {}
73
+ return {int(key): value for key, value in id2label.items()}
74
+
75
+ @staticmethod
76
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
77
+ label2id: Dict[str, int] = {}
78
+ for class_id, value in id2label.items():
79
+ for synonym in value.split(","):
80
+ synonym = synonym.strip()
81
+ if synonym:
82
+ label2id[synonym] = int(class_id)
83
+ return dict(sorted(label2id.items()))
84
+
85
+ @property
86
+ def vae_scale_factor(self) -> int:
87
+ block_out_channels = getattr(self.vae.config, "block_out_channels", None)
88
+ if block_out_channels:
89
+ return int(2 ** (len(block_out_channels) - 1))
90
+ return 8
91
+
92
+ @property
93
+ def id2label(self) -> Dict[int, str]:
94
+ self._ensure_labels_loaded()
95
+ return self._id2label
96
+
97
+ def _ensure_labels_loaded(self) -> None:
98
+ if self._labels_loaded_from_model_index:
99
+ return
100
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
101
+ if loaded:
102
+ self._id2label = loaded
103
+ self.labels = self._build_label2id(self._id2label)
104
+ self._labels_loaded_from_model_index = True
105
+
106
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
107
+ self._ensure_labels_loaded()
108
+ labels = [label] if isinstance(label, str) else label
109
+ if not self.labels:
110
+ raise ValueError("No id2label mapping is available in this checkpoint.")
111
+ missing = [item for item in labels if item not in self.labels]
112
+ if missing:
113
+ preview = ", ".join(list(self.labels.keys())[:8])
114
+ raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
115
+ return [self.labels[item] for item in labels]
116
+
117
+ def _normalize_class_labels(
118
+ self,
119
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
120
+ device: torch.device,
121
+ ) -> torch.LongTensor:
122
+ if torch.is_tensor(class_labels):
123
+ return class_labels.to(device=device, dtype=torch.long).reshape(-1)
124
+ if isinstance(class_labels, int):
125
+ class_label_ids = [class_labels]
126
+ elif isinstance(class_labels, str):
127
+ class_label_ids = self.get_label_ids(class_labels)
128
+ elif class_labels and isinstance(class_labels[0], str):
129
+ class_label_ids = self.get_label_ids(class_labels)
130
+ else:
131
+ class_label_ids = list(class_labels)
132
+ return torch.tensor(class_label_ids, device=device, dtype=torch.long).reshape(-1)
133
+
134
+ def _default_image_size(self) -> int:
135
+ transformer = getattr(self.generator, "transformer", None)
136
+ if transformer is not None:
137
+ return int(transformer.config.sample_size) * self.vae_scale_factor
138
+ return 256
139
+
140
+ def check_inputs(
141
+ self,
142
+ height: int,
143
+ width: int,
144
+ num_inference_steps: int,
145
+ output_type: str,
146
+ sampler: str,
147
+ ) -> None:
148
+ if num_inference_steps < 1:
149
+ raise ValueError("`num_inference_steps` must be >= 1.")
150
+ if output_type not in {"pil", "np", "pt", "latent"}:
151
+ raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
152
+ if sampler not in {"euler", "heun"}:
153
+ raise ValueError("sampler must be one of: 'euler', 'heun'.")
154
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
155
+ raise ValueError(
156
+ f"`height` and `width` must be divisible by {self.vae_scale_factor}, got ({height}, {width})."
157
+ )
158
+
159
+ def prepare_latents(
160
+ self,
161
+ batch_size: int,
162
+ height: int,
163
+ width: int,
164
+ dtype: torch.dtype,
165
+ device: torch.device,
166
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
167
+ latents: Optional[torch.Tensor] = None,
168
+ ) -> torch.Tensor:
169
+ if latents is not None:
170
+ return latents.to(device=device, dtype=dtype)
171
+ latent_height = height // self.vae_scale_factor
172
+ latent_width = width // self.vae_scale_factor
173
+ in_channels = int(getattr(self.generator, "in_channels", 4))
174
+ return randn_tensor(
175
+ (batch_size, in_channels, latent_height, latent_width),
176
+ generator=generator,
177
+ device=device,
178
+ dtype=dtype,
179
+ )
180
+
181
+ def decode_latents(self, latents: torch.Tensor, output_type: str = "pil"):
182
+ if output_type == "latent":
183
+ return latents
184
+ scaling_factor = getattr(self.vae.config, "scaling_factor", 0.18215)
185
+ image = self.vae.decode(latents / scaling_factor).sample
186
+ if output_type == "pt":
187
+ return image
188
+ return self.image_processor.postprocess(image, output_type=output_type)
189
+
190
+ def _run_denoising_loop(
191
+ self,
192
+ latents: torch.Tensor,
193
+ class_labels_tensor: torch.Tensor,
194
+ batch_size: int,
195
+ device: torch.device,
196
+ num_inference_steps: int,
197
+ sampler: str,
198
+ pred_type: str,
199
+ ) -> torch.Tensor:
200
+ self.scheduler.set_timesteps(num_inference_steps, device=device, solver=sampler)
201
+ timesteps = self.scheduler.timesteps
202
+ self.generator.eval()
203
+ for t_src, t_tgt in self.progress_bar(list(zip(timesteps[:-1], timesteps[1:]))):
204
+ t_src_batch = t_src.expand(batch_size)
205
+ t_tgt_batch = t_tgt.expand(batch_size)
206
+ outputs = self.generator(latents, class_labels_tensor, t_src_batch, t_tgt_batch)
207
+ if pred_type == "v":
208
+ if sampler == "heun":
209
+ latents_next = self.scheduler.step(
210
+ outputs, t_src, t_tgt, latents, prediction_type="v"
211
+ ).prev_sample
212
+ outputs_next = self.generator(latents_next, class_labels_tensor, t_tgt_batch, t_tgt_batch)
213
+ latents = self.scheduler.step(
214
+ outputs,
215
+ t_src,
216
+ t_tgt,
217
+ latents,
218
+ model_output_next=outputs_next,
219
+ prediction_type="v",
220
+ ).prev_sample
221
+ else:
222
+ latents = self.scheduler.step(
223
+ outputs, t_src, t_tgt, latents, prediction_type="v"
224
+ ).prev_sample
225
+ else:
226
+ latents = outputs
227
+ return latents
228
+
229
+ @torch.inference_mode()
230
+ def __call__(
231
+ self,
232
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
233
+ height: Optional[int] = None,
234
+ width: Optional[int] = None,
235
+ num_inference_steps: Optional[int] = None,
236
+ sampler: str = "euler",
237
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
238
+ latents: Optional[torch.Tensor] = None,
239
+ output_type: str = "pil",
240
+ return_dict: bool = True,
241
+ ):
242
+ default_size = self._default_image_size()
243
+ height = int(height or default_size)
244
+ width = int(width or default_size)
245
+ if num_inference_steps is None:
246
+ num_inference_steps = int(getattr(self.generator.config, "num_inference_steps", 1))
247
+ self.check_inputs(height, width, num_inference_steps, output_type, sampler)
248
+
249
+ device = getattr(self, "_execution_device", None) or next(self.generator.parameters()).device
250
+ dtype = next(self.generator.parameters()).dtype
251
+ pred_type = self.config.pred_type
252
+ class_labels_tensor = self._normalize_class_labels(class_labels, device=device)
253
+ batch_size = class_labels_tensor.shape[0]
254
+ latents = self.prepare_latents(
255
+ batch_size=batch_size,
256
+ height=height,
257
+ width=width,
258
+ dtype=dtype,
259
+ device=device,
260
+ generator=generator,
261
+ latents=latents,
262
+ )
263
+ latents = self._run_denoising_loop(
264
+ latents,
265
+ class_labels_tensor,
266
+ batch_size,
267
+ device,
268
+ num_inference_steps,
269
+ sampler,
270
+ pred_type,
271
+ )
272
+ image = self.decode_latents(latents, output_type=output_type)
273
+ self.maybe_free_model_hooks()
274
+ if not return_dict:
275
+ return (image,)
276
+ return ImagePipelineOutput(images=image)
AFM-L-2-1NFE-guided/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc ADDED
Binary file (5.38 kB). View file
 
AFM-L-2-1NFE-guided/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ContinuousFlowMatchScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "solver": "euler"
5
+ }
AFM-L-2-1NFE-guided/scheduler/scheduling_continuous_flow.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+ from diffusers.utils import BaseOutput
10
+
11
+
12
+ @dataclass
13
+ class ContinuousFlowMatchSchedulerOutput(BaseOutput):
14
+ prev_sample: torch.Tensor
15
+
16
+
17
+ class ContinuousFlowMatchScheduler(SchedulerMixin, ConfigMixin):
18
+ """Flow-matching scheduler for AFM with time in [1, 0]."""
19
+
20
+ order = 2
21
+
22
+ @register_to_config
23
+ def __init__(self, solver: str = "euler"):
24
+ if solver not in {"euler", "heun"}:
25
+ raise ValueError("solver must be one of: 'euler', 'heun'.")
26
+ self.timesteps: Optional[torch.Tensor] = None
27
+ self.num_inference_steps: Optional[int] = None
28
+ self._step_index: Optional[int] = None
29
+
30
+ @property
31
+ def init_noise_sigma(self) -> float:
32
+ return 1.0
33
+
34
+ def set_timesteps(
35
+ self,
36
+ num_inference_steps: int,
37
+ device: Union[str, torch.device, None] = None,
38
+ solver: Optional[str] = None,
39
+ ) -> None:
40
+ if num_inference_steps < 1:
41
+ raise ValueError("num_inference_steps must be >= 1.")
42
+ self.num_inference_steps = num_inference_steps
43
+ if solver == "heun":
44
+ grid_size = (num_inference_steps // 2) + 1
45
+ else:
46
+ grid_size = num_inference_steps + 1
47
+ self.timesteps = torch.linspace(1.0, 0.0, grid_size, device=device, dtype=torch.float32)
48
+ self._step_index = 0
49
+ if solver is not None:
50
+ self.register_to_config(solver=solver)
51
+
52
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
53
+ del timestep
54
+ return sample
55
+
56
+ def _resolve_step_index(self, timestep: Union[float, torch.Tensor, None]) -> int:
57
+ if self._step_index is not None:
58
+ return self._step_index
59
+ if self.timesteps is None:
60
+ raise ValueError("Call `set_timesteps` before `step`.")
61
+ if timestep is None:
62
+ return 0
63
+ t_value = float(timestep) if not isinstance(timestep, torch.Tensor) else float(timestep.flatten()[0])
64
+ matches = (self.timesteps - t_value).abs() < 1e-6
65
+ if matches.any():
66
+ return int(matches.nonzero(as_tuple=False)[0].item())
67
+ return 0
68
+
69
+ def step(
70
+ self,
71
+ model_output: torch.Tensor,
72
+ timestep_src: Union[float, torch.Tensor],
73
+ timestep_tgt: Union[float, torch.Tensor],
74
+ sample: torch.Tensor,
75
+ model_output_next: Optional[torch.Tensor] = None,
76
+ prediction_type: str = "v",
77
+ return_dict: bool = True,
78
+ ) -> Union[ContinuousFlowMatchSchedulerOutput, Tuple[torch.Tensor]]:
79
+ if prediction_type == "x":
80
+ prev_sample = model_output
81
+ else:
82
+ t_src = torch.as_tensor(timestep_src, device=sample.device, dtype=sample.dtype)
83
+ t_tgt = torch.as_tensor(timestep_tgt, device=sample.device, dtype=sample.dtype)
84
+ while t_src.ndim < sample.ndim:
85
+ t_src = t_src.unsqueeze(-1)
86
+ t_tgt = t_tgt.unsqueeze(-1)
87
+ dt = t_src - t_tgt
88
+ if self.config.solver == "heun" and model_output_next is not None:
89
+ prev_sample = sample - dt * 0.5 * (model_output + model_output_next)
90
+ else:
91
+ prev_sample = sample - dt * model_output
92
+
93
+ step_index = self._resolve_step_index(timestep_src)
94
+ self._step_index = step_index + 1
95
+
96
+ if not return_dict:
97
+ return (prev_sample,)
98
+ return ContinuousFlowMatchSchedulerOutput(prev_sample=prev_sample)
AFM-L-2-1NFE-guided/vae/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.36.0",
4
+ "_name_or_path": "stabilityai/sd-vae-ft-mse",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "latents_mean": null,
22
+ "latents_std": null,
23
+ "layers_per_block": 2,
24
+ "mid_block_add_attention": true,
25
+ "norm_num_groups": 32,
26
+ "out_channels": 3,
27
+ "sample_size": 256,
28
+ "scaling_factor": 0.18215,
29
+ "shift_factor": null,
30
+ "up_block_types": [
31
+ "UpDecoderBlock2D",
32
+ "UpDecoderBlock2D",
33
+ "UpDecoderBlock2D",
34
+ "UpDecoderBlock2D"
35
+ ],
36
+ "use_post_quant_conv": true,
37
+ "use_quant_conv": true
38
+ }
AFM-L-2-1NFE-guided/vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d993488569e928462932c8c38a0760b874d166399b14414135bd9c42df5815
3
+ size 334643276
AFM-L-2-1NFE-noguide/demo.png ADDED

Git LFS Details

  • SHA256: acaf057cb18ab2cb8c4f09cf9cdc0029d344c0cd1cfb1d0e76dace6c03506d34
  • Pointer size: 131 Bytes
  • Size of remote file: 116 kB
AFM-L-2-1NFE-noguide/generator/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AFMGenerator2DModel",
3
+ "_diffusers_version": "0.36.0",
4
+ "model_type": "AFM-L/2",
5
+ "architecture": "standard",
6
+ "repeat": 1,
7
+ "use_t_src": false,
8
+ "use_t_tgt": false,
9
+ "pred_type": "x",
10
+ "num_inference_steps": 1,
11
+ "learn_sigma": false,
12
+ "class_dropout_prob": 0.0,
13
+ "input_size": 32,
14
+ "num_classes": 1000,
15
+ "in_channels": 4,
16
+ "depth": 24,
17
+ "hidden_size": 1024,
18
+ "patch_size": 2,
19
+ "num_heads": 16
20
+ }
AFM-L-2-1NFE-noguide/generator/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8519fdc60ab76ee443981ec7a2601933ae54e13b67a247a0cc03e706c239c22
3
+ size 2046434688
AFM-L-2-1NFE-noguide/generator/modeling_afm.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained AFM generator for Hugging Face diffusers checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Dict, Optional
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from torch import nn
14
+
15
+
16
+ def get_dit_transformer_class():
17
+ from diffusers.models.transformers.dit_transformer_2d import DiTTransformer2DModel
18
+
19
+ return DiTTransformer2DModel
20
+
21
+
22
+ def build_dit_config(
23
+ *,
24
+ depth: int = 28,
25
+ hidden_size: int = 1152,
26
+ patch_size: int = 2,
27
+ num_heads: int = 16,
28
+ learn_sigma: bool = False,
29
+ class_dropout_prob: float = 0.0,
30
+ input_size: int = 32,
31
+ num_classes: int = 1000,
32
+ in_channels: int = 4,
33
+ ) -> Dict[str, Any]:
34
+ attention_head_dim = hidden_size // num_heads
35
+ num_embeds_ada_norm = num_classes + (1 if class_dropout_prob > 0 else 0)
36
+ out_channels = in_channels * 2 if learn_sigma else in_channels
37
+ return {
38
+ "sample_size": input_size,
39
+ "num_layers": depth,
40
+ "num_attention_heads": num_heads,
41
+ "attention_head_dim": attention_head_dim,
42
+ "in_channels": in_channels,
43
+ "out_channels": out_channels,
44
+ "patch_size": patch_size,
45
+ "attention_bias": True,
46
+ "activation_fn": "gelu-approximate",
47
+ "num_embeds_ada_norm": num_embeds_ada_norm,
48
+ "norm_type": "ada_norm_zero",
49
+ "norm_elementwise_affine": False,
50
+ "dropout": 0.0,
51
+ "norm_num_groups": 32,
52
+ "norm_eps": 1e-5,
53
+ "upcast_attention": False,
54
+ }
55
+
56
+
57
+ def _convert_legacy_dit_state_dict(state_dict: Dict[str, torch.Tensor], depth: int) -> Dict[str, torch.Tensor]:
58
+ converted = copy.deepcopy(state_dict)
59
+
60
+ converted["pos_embed.proj.weight"] = converted.pop("x_embedder.proj.weight").clone().contiguous()
61
+ converted["pos_embed.proj.bias"] = converted.pop("x_embedder.proj.bias").clone().contiguous()
62
+
63
+ if "t_embedder.mlp.0.weight" in converted:
64
+ timestep_weights = {
65
+ "linear_1.weight": converted.pop("t_embedder.mlp.0.weight"),
66
+ "linear_1.bias": converted.pop("t_embedder.mlp.0.bias"),
67
+ "linear_2.weight": converted.pop("t_embedder.mlp.2.weight"),
68
+ "linear_2.bias": converted.pop("t_embedder.mlp.2.bias"),
69
+ }
70
+ else:
71
+ timestep_weights = None
72
+ class_embedding = converted.pop("y_embedder.embedding_table.weight")
73
+ if class_embedding.shape[0] == 1000:
74
+ null_class = torch.zeros(1, class_embedding.shape[1], dtype=class_embedding.dtype)
75
+ class_embedding = torch.cat([class_embedding, null_class], dim=0)
76
+
77
+ for block_idx in range(depth):
78
+ if timestep_weights is not None:
79
+ for key, tensor in timestep_weights.items():
80
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.timestep_embedder.{key}"] = tensor.clone()
81
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.class_embedder.embedding_table.weight"] = (
82
+ class_embedding.clone()
83
+ )
84
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.weight"] = converted[
85
+ f"blocks.{block_idx}.adaLN_modulation.1.weight"
86
+ ]
87
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.bias"] = converted[
88
+ f"blocks.{block_idx}.adaLN_modulation.1.bias"
89
+ ]
90
+
91
+ q, k, v = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.weight"], 3, dim=0)
92
+ q_bias, k_bias, v_bias = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.bias"], 3, dim=0)
93
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.weight"] = q
94
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.bias"] = q_bias
95
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.weight"] = k
96
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.bias"] = k_bias
97
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.weight"] = v
98
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.bias"] = v_bias
99
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.weight"] = converted[
100
+ f"blocks.{block_idx}.attn.proj.weight"
101
+ ]
102
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.bias"] = converted[
103
+ f"blocks.{block_idx}.attn.proj.bias"
104
+ ]
105
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.weight"] = converted[
106
+ f"blocks.{block_idx}.mlp.fc1.weight"
107
+ ]
108
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.bias"] = converted[
109
+ f"blocks.{block_idx}.mlp.fc1.bias"
110
+ ]
111
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.weight"] = converted[
112
+ f"blocks.{block_idx}.mlp.fc2.weight"
113
+ ]
114
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.bias"] = converted[
115
+ f"blocks.{block_idx}.mlp.fc2.bias"
116
+ ]
117
+
118
+ for suffix in (
119
+ "attn.qkv.weight",
120
+ "attn.qkv.bias",
121
+ "attn.proj.weight",
122
+ "attn.proj.bias",
123
+ "mlp.fc1.weight",
124
+ "mlp.fc1.bias",
125
+ "mlp.fc2.weight",
126
+ "mlp.fc2.bias",
127
+ "adaLN_modulation.1.weight",
128
+ "adaLN_modulation.1.bias",
129
+ ):
130
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
131
+
132
+ converted["proj_out_1.weight"] = converted.pop("final_layer.adaLN_modulation.1.weight")
133
+ converted["proj_out_1.bias"] = converted.pop("final_layer.adaLN_modulation.1.bias")
134
+ converted["proj_out_2.weight"] = converted.pop("final_layer.linear.weight")
135
+ converted["proj_out_2.bias"] = converted.pop("final_layer.linear.bias")
136
+
137
+ converted.pop("pos_embed", None)
138
+ for block_idx in range(depth):
139
+ for suffix in ("norm1.weight", "norm1.bias", "norm2.weight", "norm2.bias"):
140
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
141
+
142
+ return {key: tensor.detach().clone().contiguous() for key, tensor in converted.items()}
143
+
144
+
145
+ def load_legacy_dit_state_dict(
146
+ state_dict: Dict[str, torch.Tensor],
147
+ depth: int,
148
+ patch_size: int,
149
+ hidden_size: int,
150
+ num_heads: int,
151
+ ) -> Dict[str, torch.Tensor]:
152
+ if "transformer_blocks.0.attn1.to_q.weight" in state_dict:
153
+ return state_dict
154
+ if any(key.startswith("blocks.") for key in state_dict):
155
+ return _convert_legacy_dit_state_dict(state_dict, depth)
156
+ return state_dict
157
+
158
+
159
+ def forward_dit_output(
160
+ transformer,
161
+ hidden_states: torch.Tensor,
162
+ timestep: Optional[torch.Tensor],
163
+ class_labels: torch.Tensor,
164
+ extra_cond: Optional[torch.Tensor] = None,
165
+ ) -> torch.Tensor:
166
+ hidden_states = transformer.pos_embed(hidden_states)
167
+
168
+ for block in transformer.transformer_blocks:
169
+ if torch.is_grad_enabled() and transformer.gradient_checkpointing:
170
+ hidden_states = transformer._gradient_checkpointing_func(
171
+ block,
172
+ hidden_states,
173
+ None,
174
+ None,
175
+ None,
176
+ timestep,
177
+ None,
178
+ class_labels,
179
+ )
180
+ else:
181
+ hidden_states = block(
182
+ hidden_states,
183
+ attention_mask=None,
184
+ encoder_hidden_states=None,
185
+ encoder_attention_mask=None,
186
+ timestep=timestep,
187
+ cross_attention_kwargs=None,
188
+ class_labels=class_labels,
189
+ )
190
+
191
+ conditioning = transformer.transformer_blocks[0].norm1.emb(
192
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
193
+ )
194
+ if extra_cond is not None:
195
+ conditioning = conditioning + extra_cond
196
+ shift, scale = transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
197
+ hidden_states = transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
198
+ hidden_states = transformer.proj_out_2(hidden_states)
199
+
200
+ height = width = int(hidden_states.shape[1] ** 0.5)
201
+ hidden_states = hidden_states.reshape(
202
+ shape=(-1, height, width, transformer.patch_size, transformer.patch_size, transformer.out_channels)
203
+ )
204
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
205
+ return hidden_states.reshape(
206
+ shape=(-1, transformer.out_channels, height * transformer.patch_size, width * transformer.patch_size)
207
+ )
208
+
209
+
210
+ def remap_transformer_state_dict(
211
+ state_dict: Dict[str, torch.Tensor],
212
+ legacy_kwargs: Dict[str, int],
213
+ extra_prefixes: tuple[str, ...] = (),
214
+ ) -> Dict[str, torch.Tensor]:
215
+ state_dict = load_legacy_dit_state_dict(state_dict, **legacy_kwargs)
216
+ remapped: Dict[str, torch.Tensor] = {}
217
+ for key, value in state_dict.items():
218
+ if any(key.startswith(prefix) for prefix in extra_prefixes):
219
+ remapped[key] = value
220
+ elif key.startswith("transformer."):
221
+ remapped[key] = value
222
+ else:
223
+ remapped[f"transformer.{key}"] = value
224
+ return remapped
225
+
226
+
227
+ def split_output_channels(output: torch.Tensor, in_channels: int) -> torch.Tensor:
228
+ if output.shape[1] == in_channels:
229
+ return output
230
+ output, _ = output.chunk(2, dim=1)
231
+ return output
232
+
233
+
234
+ class TimestepEmbedder(nn.Module):
235
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
236
+ super().__init__()
237
+ self.mlp = nn.Sequential(
238
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
239
+ nn.SiLU(),
240
+ nn.Linear(hidden_size, hidden_size, bias=True),
241
+ )
242
+ self.frequency_embedding_size = frequency_embedding_size
243
+
244
+ @staticmethod
245
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
246
+ half = dim // 2
247
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
248
+ device=t.device
249
+ )
250
+ args = t[:, None].float() * freqs[None]
251
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
252
+ if dim % 2:
253
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
254
+ return embedding
255
+
256
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
257
+ emb = self.timestep_embedding(t.float(), self.frequency_embedding_size)
258
+ weight_dtype = self.mlp[0].weight.dtype
259
+ return self.mlp(emb.to(dtype=weight_dtype))
260
+
261
+
262
+ class Generator(nn.Module):
263
+ def __init__(
264
+ self,
265
+ *,
266
+ use_t_src: bool = False,
267
+ use_t_tgt: bool = False,
268
+ depth: int = 28,
269
+ hidden_size: int = 1152,
270
+ patch_size: int = 2,
271
+ num_heads: int = 16,
272
+ learn_sigma: bool = False,
273
+ class_dropout_prob: float = 0.0,
274
+ input_size: int = 32,
275
+ num_classes: int = 1000,
276
+ in_channels: int = 4,
277
+ **_,
278
+ ):
279
+ super().__init__()
280
+ self.use_t_src = use_t_src
281
+ self.use_t_tgt = use_t_tgt
282
+ self._legacy_kwargs = {
283
+ "depth": depth,
284
+ "hidden_size": hidden_size,
285
+ "patch_size": patch_size,
286
+ "num_heads": num_heads,
287
+ }
288
+ dit_cls = get_dit_transformer_class()
289
+ self.transformer = dit_cls(
290
+ **build_dit_config(
291
+ depth=depth,
292
+ hidden_size=hidden_size,
293
+ patch_size=patch_size,
294
+ num_heads=num_heads,
295
+ learn_sigma=learn_sigma,
296
+ class_dropout_prob=class_dropout_prob,
297
+ input_size=input_size,
298
+ num_classes=num_classes,
299
+ in_channels=in_channels,
300
+ )
301
+ )
302
+ self.in_channels = in_channels
303
+ if use_t_tgt:
304
+ self.t_tgt_embedder = TimestepEmbedder(hidden_size)
305
+ nn.init.normal_(self.t_tgt_embedder.mlp[0].weight, std=0.02)
306
+ nn.init.normal_(self.t_tgt_embedder.mlp[2].weight, std=0.02)
307
+
308
+ def load_state_dict(self, state_dict, strict: bool = True):
309
+ extra = ("t_tgt_embedder.",)
310
+ has_extra = any(key.startswith(extra) for key in state_dict)
311
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
312
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs, extra_prefixes=extra)
313
+ if self.use_t_tgt and not has_extra:
314
+ strict = False
315
+ if not has_t_embedder:
316
+ strict = False
317
+ out = super().load_state_dict(remapped, strict=strict)
318
+ if not has_t_embedder:
319
+ for name, param in self.named_parameters():
320
+ if "timestep_embedder" in name:
321
+ param.data.zero_()
322
+ return out
323
+
324
+ def forward(self, x, y, t_src=None, t_tgt=None):
325
+ if self.use_t_src and t_src is not None:
326
+ timestep = (t_src * 1000).long()
327
+ else:
328
+ timestep = torch.zeros(x.shape[0], device=x.device, dtype=torch.long)
329
+
330
+ extra_cond = None
331
+ if self.use_t_tgt and t_tgt is not None:
332
+ extra_cond = self.t_tgt_embedder(t_tgt * 1000)
333
+
334
+ output = forward_dit_output(self.transformer, x, timestep, y, extra_cond=extra_cond)
335
+ return split_output_channels(output, self.in_channels)
336
+
337
+
338
+ class GeneratorDeep(nn.Module):
339
+ def __init__(
340
+ self,
341
+ *,
342
+ repeat: int,
343
+ depth: int = 28,
344
+ hidden_size: int = 1152,
345
+ patch_size: int = 2,
346
+ num_heads: int = 16,
347
+ learn_sigma: bool = False,
348
+ class_dropout_prob: float = 0.0,
349
+ input_size: int = 32,
350
+ num_classes: int = 1000,
351
+ in_channels: int = 4,
352
+ **_,
353
+ ):
354
+ super().__init__()
355
+ self.repeat = repeat
356
+ self._legacy_kwargs = {
357
+ "depth": depth,
358
+ "hidden_size": hidden_size,
359
+ "patch_size": patch_size,
360
+ "num_heads": num_heads,
361
+ }
362
+ dit_cls = get_dit_transformer_class()
363
+ self.transformer = dit_cls(
364
+ **build_dit_config(
365
+ depth=depth,
366
+ hidden_size=hidden_size,
367
+ patch_size=patch_size,
368
+ num_heads=num_heads,
369
+ learn_sigma=learn_sigma,
370
+ class_dropout_prob=class_dropout_prob,
371
+ input_size=input_size,
372
+ num_classes=num_classes,
373
+ in_channels=in_channels,
374
+ )
375
+ )
376
+ self.in_channels = in_channels
377
+
378
+ def load_state_dict(self, state_dict, strict: bool = True):
379
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs)
380
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
381
+ if not has_t_embedder:
382
+ strict = False
383
+ out = super().load_state_dict(remapped, strict=strict)
384
+ if not has_t_embedder:
385
+ for name, param in self.named_parameters():
386
+ if "timestep_embedder" in name:
387
+ param.data.zero_()
388
+ return out
389
+
390
+ def forward(self, x, y, *args, **kwargs):
391
+ hidden_states = self.transformer.pos_embed(x)
392
+ for t in torch.arange(1, 0, -1 / self.repeat).tolist():
393
+ timestep = torch.full([x.shape[0]], int(t * 1000), device=x.device, dtype=torch.long)
394
+ for block in self.transformer.transformer_blocks:
395
+ hidden_states = block(
396
+ hidden_states,
397
+ attention_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ timestep=timestep,
401
+ cross_attention_kwargs=None,
402
+ class_labels=y,
403
+ )
404
+
405
+ conditioning = self.transformer.transformer_blocks[0].norm1.emb(
406
+ torch.zeros(x.shape[0], device=x.device, dtype=torch.long),
407
+ y,
408
+ hidden_dtype=hidden_states.dtype,
409
+ )
410
+ shift, scale = self.transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
411
+ hidden_states = self.transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
412
+ hidden_states = self.transformer.proj_out_2(hidden_states)
413
+
414
+ height = width = int(hidden_states.shape[1] ** 0.5)
415
+ hidden_states = hidden_states.reshape(
416
+ shape=(
417
+ -1,
418
+ height,
419
+ width,
420
+ self.transformer.patch_size,
421
+ self.transformer.patch_size,
422
+ self.transformer.out_channels,
423
+ )
424
+ )
425
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
426
+ output = hidden_states.reshape(
427
+ shape=(-1, self.transformer.out_channels, height * self.transformer.patch_size, width * self.transformer.patch_size)
428
+ )
429
+ return split_output_channels(output, self.in_channels)
430
+
431
+
432
+ class AFMGenerator2DModel(Generator, ModelMixin, ConfigMixin):
433
+ config_name = "config.json"
434
+
435
+ @register_to_config
436
+ def __init__(
437
+ self,
438
+ model_type: str = "AFM-XL/2",
439
+ architecture: str = "standard",
440
+ repeat: int = 1,
441
+ use_t_src: bool = False,
442
+ use_t_tgt: bool = False,
443
+ depth: int = 28,
444
+ hidden_size: int = 1152,
445
+ patch_size: int = 2,
446
+ num_heads: int = 16,
447
+ learn_sigma: bool = False,
448
+ class_dropout_prob: float = 0.0,
449
+ input_size: int = 32,
450
+ num_classes: int = 1000,
451
+ in_channels: int = 4,
452
+ pred_type: str = "x",
453
+ num_inference_steps: int = 1,
454
+ ) -> None:
455
+ if architecture == "deep":
456
+ raise ValueError("Use AFMGeneratorDeep2DModel for deep AFM checkpoints.")
457
+ Generator.__init__(
458
+ self,
459
+ use_t_src=use_t_src,
460
+ use_t_tgt=use_t_tgt,
461
+ depth=depth,
462
+ hidden_size=hidden_size,
463
+ patch_size=patch_size,
464
+ num_heads=num_heads,
465
+ learn_sigma=learn_sigma,
466
+ class_dropout_prob=class_dropout_prob,
467
+ input_size=input_size,
468
+ num_classes=num_classes,
469
+ in_channels=in_channels,
470
+ )
471
+
472
+
473
+ class AFMGeneratorDeep2DModel(GeneratorDeep, ModelMixin, ConfigMixin):
474
+ config_name = "config.json"
475
+
476
+ @register_to_config
477
+ def __init__(
478
+ self,
479
+ model_type: str = "AFM-XL/2",
480
+ architecture: str = "deep",
481
+ repeat: int = 2,
482
+ use_t_src: bool = False,
483
+ use_t_tgt: bool = False,
484
+ depth: int = 28,
485
+ hidden_size: int = 1152,
486
+ patch_size: int = 2,
487
+ num_heads: int = 16,
488
+ learn_sigma: bool = False,
489
+ class_dropout_prob: float = 0.0,
490
+ input_size: int = 32,
491
+ num_classes: int = 1000,
492
+ in_channels: int = 4,
493
+ pred_type: str = "x",
494
+ num_inference_steps: int = 1,
495
+ ) -> None:
496
+ GeneratorDeep.__init__(
497
+ self,
498
+ repeat=repeat,
499
+ depth=depth,
500
+ hidden_size=hidden_size,
501
+ patch_size=patch_size,
502
+ num_heads=num_heads,
503
+ learn_sigma=learn_sigma,
504
+ class_dropout_prob=class_dropout_prob,
505
+ input_size=input_size,
506
+ num_classes=num_classes,
507
+ in_channels=in_channels,
508
+ )
509
+
510
+
511
+ __all__ = ["AFMGenerator2DModel", "AFMGeneratorDeep2DModel"]
AFM-L-2-1NFE-noguide/model_index.json ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "AFMPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "generator": [
8
+ "modeling_afm",
9
+ "AFMGenerator2DModel"
10
+ ],
11
+ "vae": [
12
+ "diffusers",
13
+ "AutoencoderKL"
14
+ ],
15
+ "scheduler": [
16
+ "scheduling_continuous_flow",
17
+ "ContinuousFlowMatchScheduler"
18
+ ],
19
+ "pred_type": "x",
20
+ "id2label": {
21
+ "0": "tench, Tinca tinca",
22
+ "1": "goldfish, Carassius auratus",
23
+ "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
24
+ "3": "tiger shark, Galeocerdo cuvieri",
25
+ "4": "hammerhead, hammerhead shark",
26
+ "5": "electric ray, crampfish, numbfish, torpedo",
27
+ "6": "stingray",
28
+ "7": "cock",
29
+ "8": "hen",
30
+ "9": "ostrich, Struthio camelus",
31
+ "10": "brambling, Fringilla montifringilla",
32
+ "11": "goldfinch, Carduelis carduelis",
33
+ "12": "house finch, linnet, Carpodacus mexicanus",
34
+ "13": "junco, snowbird",
35
+ "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
36
+ "15": "robin, American robin, Turdus migratorius",
37
+ "16": "bulbul",
38
+ "17": "jay",
39
+ "18": "magpie",
40
+ "19": "chickadee",
41
+ "20": "water ouzel, dipper",
42
+ "21": "kite",
43
+ "22": "bald eagle, American eagle, Haliaeetus leucocephalus",
44
+ "23": "vulture",
45
+ "24": "great grey owl, great gray owl, Strix nebulosa",
46
+ "25": "European fire salamander, Salamandra salamandra",
47
+ "26": "common newt, Triturus vulgaris",
48
+ "27": "eft",
49
+ "28": "spotted salamander, Ambystoma maculatum",
50
+ "29": "axolotl, mud puppy, Ambystoma mexicanum",
51
+ "30": "bullfrog, Rana catesbeiana",
52
+ "31": "tree frog, tree-frog",
53
+ "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
54
+ "33": "loggerhead, loggerhead turtle, Caretta caretta",
55
+ "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
56
+ "35": "mud turtle",
57
+ "36": "terrapin",
58
+ "37": "box turtle, box tortoise",
59
+ "38": "banded gecko",
60
+ "39": "common iguana, iguana, Iguana iguana",
61
+ "40": "American chameleon, anole, Anolis carolinensis",
62
+ "41": "whiptail, whiptail lizard",
63
+ "42": "agama",
64
+ "43": "frilled lizard, Chlamydosaurus kingi",
65
+ "44": "alligator lizard",
66
+ "45": "Gila monster, Heloderma suspectum",
67
+ "46": "green lizard, Lacerta viridis",
68
+ "47": "African chameleon, Chamaeleo chamaeleon",
69
+ "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
70
+ "49": "African crocodile, Nile crocodile, Crocodylus niloticus",
71
+ "50": "American alligator, Alligator mississipiensis",
72
+ "51": "triceratops",
73
+ "52": "thunder snake, worm snake, Carphophis amoenus",
74
+ "53": "ringneck snake, ring-necked snake, ring snake",
75
+ "54": "hognose snake, puff adder, sand viper",
76
+ "55": "green snake, grass snake",
77
+ "56": "king snake, kingsnake",
78
+ "57": "garter snake, grass snake",
79
+ "58": "water snake",
80
+ "59": "vine snake",
81
+ "60": "night snake, Hypsiglena torquata",
82
+ "61": "boa constrictor, Constrictor constrictor",
83
+ "62": "rock python, rock snake, Python sebae",
84
+ "63": "Indian cobra, Naja naja",
85
+ "64": "green mamba",
86
+ "65": "sea snake",
87
+ "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
88
+ "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
89
+ "68": "sidewinder, horned rattlesnake, Crotalus cerastes",
90
+ "69": "trilobite",
91
+ "70": "harvestman, daddy longlegs, Phalangium opilio",
92
+ "71": "scorpion",
93
+ "72": "black and gold garden spider, Argiope aurantia",
94
+ "73": "barn spider, Araneus cavaticus",
95
+ "74": "garden spider, Aranea diademata",
96
+ "75": "black widow, Latrodectus mactans",
97
+ "76": "tarantula",
98
+ "77": "wolf spider, hunting spider",
99
+ "78": "tick",
100
+ "79": "centipede",
101
+ "80": "black grouse",
102
+ "81": "ptarmigan",
103
+ "82": "ruffed grouse, partridge, Bonasa umbellus",
104
+ "83": "prairie chicken, prairie grouse, prairie fowl",
105
+ "84": "peacock",
106
+ "85": "quail",
107
+ "86": "partridge",
108
+ "87": "African grey, African gray, Psittacus erithacus",
109
+ "88": "macaw",
110
+ "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
111
+ "90": "lorikeet",
112
+ "91": "coucal",
113
+ "92": "bee eater",
114
+ "93": "hornbill",
115
+ "94": "hummingbird",
116
+ "95": "jacamar",
117
+ "96": "toucan",
118
+ "97": "drake",
119
+ "98": "red-breasted merganser, Mergus serrator",
120
+ "99": "goose",
121
+ "100": "black swan, Cygnus atratus",
122
+ "101": "tusker",
123
+ "102": "echidna, spiny anteater, anteater",
124
+ "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
125
+ "104": "wallaby, brush kangaroo",
126
+ "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
127
+ "106": "wombat",
128
+ "107": "jellyfish",
129
+ "108": "sea anemone, anemone",
130
+ "109": "brain coral",
131
+ "110": "flatworm, platyhelminth",
132
+ "111": "nematode, nematode worm, roundworm",
133
+ "112": "conch",
134
+ "113": "snail",
135
+ "114": "slug",
136
+ "115": "sea slug, nudibranch",
137
+ "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
138
+ "117": "chambered nautilus, pearly nautilus, nautilus",
139
+ "118": "Dungeness crab, Cancer magister",
140
+ "119": "rock crab, Cancer irroratus",
141
+ "120": "fiddler crab",
142
+ "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
143
+ "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
144
+ "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
145
+ "124": "crayfish, crawfish, crawdad, crawdaddy",
146
+ "125": "hermit crab",
147
+ "126": "isopod",
148
+ "127": "white stork, Ciconia ciconia",
149
+ "128": "black stork, Ciconia nigra",
150
+ "129": "spoonbill",
151
+ "130": "flamingo",
152
+ "131": "little blue heron, Egretta caerulea",
153
+ "132": "American egret, great white heron, Egretta albus",
154
+ "133": "bittern",
155
+ "134": "crane",
156
+ "135": "limpkin, Aramus pictus",
157
+ "136": "European gallinule, Porphyrio porphyrio",
158
+ "137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
159
+ "138": "bustard",
160
+ "139": "ruddy turnstone, Arenaria interpres",
161
+ "140": "red-backed sandpiper, dunlin, Erolia alpina",
162
+ "141": "redshank, Tringa totanus",
163
+ "142": "dowitcher",
164
+ "143": "oystercatcher, oyster catcher",
165
+ "144": "pelican",
166
+ "145": "king penguin, Aptenodytes patagonica",
167
+ "146": "albatross, mollymawk",
168
+ "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
169
+ "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
170
+ "149": "dugong, Dugong dugon",
171
+ "150": "sea lion",
172
+ "151": "Chihuahua",
173
+ "152": "Japanese spaniel",
174
+ "153": "Maltese dog, Maltese terrier, Maltese",
175
+ "154": "Pekinese, Pekingese, Peke",
176
+ "155": "Shih-Tzu",
177
+ "156": "Blenheim spaniel",
178
+ "157": "papillon",
179
+ "158": "toy terrier",
180
+ "159": "Rhodesian ridgeback",
181
+ "160": "Afghan hound, Afghan",
182
+ "161": "basset, basset hound",
183
+ "162": "beagle",
184
+ "163": "bloodhound, sleuthhound",
185
+ "164": "bluetick",
186
+ "165": "black-and-tan coonhound",
187
+ "166": "Walker hound, Walker foxhound",
188
+ "167": "English foxhound",
189
+ "168": "redbone",
190
+ "169": "borzoi, Russian wolfhound",
191
+ "170": "Irish wolfhound",
192
+ "171": "Italian greyhound",
193
+ "172": "whippet",
194
+ "173": "Ibizan hound, Ibizan Podenco",
195
+ "174": "Norwegian elkhound, elkhound",
196
+ "175": "otterhound, otter hound",
197
+ "176": "Saluki, gazelle hound",
198
+ "177": "Scottish deerhound, deerhound",
199
+ "178": "Weimaraner",
200
+ "179": "Staffordshire bullterrier, Staffordshire bull terrier",
201
+ "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
202
+ "181": "Bedlington terrier",
203
+ "182": "Border terrier",
204
+ "183": "Kerry blue terrier",
205
+ "184": "Irish terrier",
206
+ "185": "Norfolk terrier",
207
+ "186": "Norwich terrier",
208
+ "187": "Yorkshire terrier",
209
+ "188": "wire-haired fox terrier",
210
+ "189": "Lakeland terrier",
211
+ "190": "Sealyham terrier, Sealyham",
212
+ "191": "Airedale, Airedale terrier",
213
+ "192": "cairn, cairn terrier",
214
+ "193": "Australian terrier",
215
+ "194": "Dandie Dinmont, Dandie Dinmont terrier",
216
+ "195": "Boston bull, Boston terrier",
217
+ "196": "miniature schnauzer",
218
+ "197": "giant schnauzer",
219
+ "198": "standard schnauzer",
220
+ "199": "Scotch terrier, Scottish terrier, Scottie",
221
+ "200": "Tibetan terrier, chrysanthemum dog",
222
+ "201": "silky terrier, Sydney silky",
223
+ "202": "soft-coated wheaten terrier",
224
+ "203": "West Highland white terrier",
225
+ "204": "Lhasa, Lhasa apso",
226
+ "205": "flat-coated retriever",
227
+ "206": "curly-coated retriever",
228
+ "207": "golden retriever",
229
+ "208": "Labrador retriever",
230
+ "209": "Chesapeake Bay retriever",
231
+ "210": "German short-haired pointer",
232
+ "211": "vizsla, Hungarian pointer",
233
+ "212": "English setter",
234
+ "213": "Irish setter, red setter",
235
+ "214": "Gordon setter",
236
+ "215": "Brittany spaniel",
237
+ "216": "clumber, clumber spaniel",
238
+ "217": "English springer, English springer spaniel",
239
+ "218": "Welsh springer spaniel",
240
+ "219": "cocker spaniel, English cocker spaniel, cocker",
241
+ "220": "Sussex spaniel",
242
+ "221": "Irish water spaniel",
243
+ "222": "kuvasz",
244
+ "223": "schipperke",
245
+ "224": "groenendael",
246
+ "225": "malinois",
247
+ "226": "briard",
248
+ "227": "kelpie",
249
+ "228": "komondor",
250
+ "229": "Old English sheepdog, bobtail",
251
+ "230": "Shetland sheepdog, Shetland sheep dog, Shetland",
252
+ "231": "collie",
253
+ "232": "Border collie",
254
+ "233": "Bouvier des Flandres, Bouviers des Flandres",
255
+ "234": "Rottweiler",
256
+ "235": "German shepherd, German shepherd dog, German police dog, alsatian",
257
+ "236": "Doberman, Doberman pinscher",
258
+ "237": "miniature pinscher",
259
+ "238": "Greater Swiss Mountain dog",
260
+ "239": "Bernese mountain dog",
261
+ "240": "Appenzeller",
262
+ "241": "EntleBucher",
263
+ "242": "boxer",
264
+ "243": "bull mastiff",
265
+ "244": "Tibetan mastiff",
266
+ "245": "French bulldog",
267
+ "246": "Great Dane",
268
+ "247": "Saint Bernard, St Bernard",
269
+ "248": "Eskimo dog, husky",
270
+ "249": "malamute, malemute, Alaskan malamute",
271
+ "250": "Siberian husky",
272
+ "251": "dalmatian, coach dog, carriage dog",
273
+ "252": "affenpinscher, monkey pinscher, monkey dog",
274
+ "253": "basenji",
275
+ "254": "pug, pug-dog",
276
+ "255": "Leonberg",
277
+ "256": "Newfoundland, Newfoundland dog",
278
+ "257": "Great Pyrenees",
279
+ "258": "Samoyed, Samoyede",
280
+ "259": "Pomeranian",
281
+ "260": "chow, chow chow",
282
+ "261": "keeshond",
283
+ "262": "Brabancon griffon",
284
+ "263": "Pembroke, Pembroke Welsh corgi",
285
+ "264": "Cardigan, Cardigan Welsh corgi",
286
+ "265": "toy poodle",
287
+ "266": "miniature poodle",
288
+ "267": "standard poodle",
289
+ "268": "Mexican hairless",
290
+ "269": "timber wolf, grey wolf, gray wolf, Canis lupus",
291
+ "270": "white wolf, Arctic wolf, Canis lupus tundrarum",
292
+ "271": "red wolf, maned wolf, Canis rufus, Canis niger",
293
+ "272": "coyote, prairie wolf, brush wolf, Canis latrans",
294
+ "273": "dingo, warrigal, warragal, Canis dingo",
295
+ "274": "dhole, Cuon alpinus",
296
+ "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
297
+ "276": "hyena, hyaena",
298
+ "277": "red fox, Vulpes vulpes",
299
+ "278": "kit fox, Vulpes macrotis",
300
+ "279": "Arctic fox, white fox, Alopex lagopus",
301
+ "280": "grey fox, gray fox, Urocyon cinereoargenteus",
302
+ "281": "tabby, tabby cat",
303
+ "282": "tiger cat",
304
+ "283": "Persian cat",
305
+ "284": "Siamese cat, Siamese",
306
+ "285": "Egyptian cat",
307
+ "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
308
+ "287": "lynx, catamount",
309
+ "288": "leopard, Panthera pardus",
310
+ "289": "snow leopard, ounce, Panthera uncia",
311
+ "290": "jaguar, panther, Panthera onca, Felis onca",
312
+ "291": "lion, king of beasts, Panthera leo",
313
+ "292": "tiger, Panthera tigris",
314
+ "293": "cheetah, chetah, Acinonyx jubatus",
315
+ "294": "brown bear, bruin, Ursus arctos",
316
+ "295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
317
+ "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
318
+ "297": "sloth bear, Melursus ursinus, Ursus ursinus",
319
+ "298": "mongoose",
320
+ "299": "meerkat, mierkat",
321
+ "300": "tiger beetle",
322
+ "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
323
+ "302": "ground beetle, carabid beetle",
324
+ "303": "long-horned beetle, longicorn, longicorn beetle",
325
+ "304": "leaf beetle, chrysomelid",
326
+ "305": "dung beetle",
327
+ "306": "rhinoceros beetle",
328
+ "307": "weevil",
329
+ "308": "fly",
330
+ "309": "bee",
331
+ "310": "ant, emmet, pismire",
332
+ "311": "grasshopper, hopper",
333
+ "312": "cricket",
334
+ "313": "walking stick, walkingstick, stick insect",
335
+ "314": "cockroach, roach",
336
+ "315": "mantis, mantid",
337
+ "316": "cicada, cicala",
338
+ "317": "leafhopper",
339
+ "318": "lacewing, lacewing fly",
340
+ "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
341
+ "320": "damselfly",
342
+ "321": "admiral",
343
+ "322": "ringlet, ringlet butterfly",
344
+ "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
345
+ "324": "cabbage butterfly",
346
+ "325": "sulphur butterfly, sulfur butterfly",
347
+ "326": "lycaenid, lycaenid butterfly",
348
+ "327": "starfish, sea star",
349
+ "328": "sea urchin",
350
+ "329": "sea cucumber, holothurian",
351
+ "330": "wood rabbit, cottontail, cottontail rabbit",
352
+ "331": "hare",
353
+ "332": "Angora, Angora rabbit",
354
+ "333": "hamster",
355
+ "334": "porcupine, hedgehog",
356
+ "335": "fox squirrel, eastern fox squirrel, Sciurus niger",
357
+ "336": "marmot",
358
+ "337": "beaver",
359
+ "338": "guinea pig, Cavia cobaya",
360
+ "339": "sorrel",
361
+ "340": "zebra",
362
+ "341": "hog, pig, grunter, squealer, Sus scrofa",
363
+ "342": "wild boar, boar, Sus scrofa",
364
+ "343": "warthog",
365
+ "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
366
+ "345": "ox",
367
+ "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
368
+ "347": "bison",
369
+ "348": "ram, tup",
370
+ "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
371
+ "350": "ibex, Capra ibex",
372
+ "351": "hartebeest",
373
+ "352": "impala, Aepyceros melampus",
374
+ "353": "gazelle",
375
+ "354": "Arabian camel, dromedary, Camelus dromedarius",
376
+ "355": "llama",
377
+ "356": "weasel",
378
+ "357": "mink",
379
+ "358": "polecat, fitch, foulmart, foumart, Mustela putorius",
380
+ "359": "black-footed ferret, ferret, Mustela nigripes",
381
+ "360": "otter",
382
+ "361": "skunk, polecat, wood pussy",
383
+ "362": "badger",
384
+ "363": "armadillo",
385
+ "364": "three-toed sloth, ai, Bradypus tridactylus",
386
+ "365": "orangutan, orang, orangutang, Pongo pygmaeus",
387
+ "366": "gorilla, Gorilla gorilla",
388
+ "367": "chimpanzee, chimp, Pan troglodytes",
389
+ "368": "gibbon, Hylobates lar",
390
+ "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
391
+ "370": "guenon, guenon monkey",
392
+ "371": "patas, hussar monkey, Erythrocebus patas",
393
+ "372": "baboon",
394
+ "373": "macaque",
395
+ "374": "langur",
396
+ "375": "colobus, colobus monkey",
397
+ "376": "proboscis monkey, Nasalis larvatus",
398
+ "377": "marmoset",
399
+ "378": "capuchin, ringtail, Cebus capucinus",
400
+ "379": "howler monkey, howler",
401
+ "380": "titi, titi monkey",
402
+ "381": "spider monkey, Ateles geoffroyi",
403
+ "382": "squirrel monkey, Saimiri sciureus",
404
+ "383": "Madagascar cat, ring-tailed lemur, Lemur catta",
405
+ "384": "indri, indris, Indri indri, Indri brevicaudatus",
406
+ "385": "Indian elephant, Elephas maximus",
407
+ "386": "African elephant, Loxodonta africana",
408
+ "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
409
+ "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
410
+ "389": "barracouta, snoek",
411
+ "390": "eel",
412
+ "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
413
+ "392": "rock beauty, Holocanthus tricolor",
414
+ "393": "anemone fish",
415
+ "394": "sturgeon",
416
+ "395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
417
+ "396": "lionfish",
418
+ "397": "puffer, pufferfish, blowfish, globefish",
419
+ "398": "abacus",
420
+ "399": "abaya",
421
+ "400": "academic gown, academic robe, judge robe",
422
+ "401": "accordion, piano accordion, squeeze box",
423
+ "402": "acoustic guitar",
424
+ "403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
425
+ "404": "airliner",
426
+ "405": "airship, dirigible",
427
+ "406": "altar",
428
+ "407": "ambulance",
429
+ "408": "amphibian, amphibious vehicle",
430
+ "409": "analog clock",
431
+ "410": "apiary, bee house",
432
+ "411": "apron",
433
+ "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
434
+ "413": "assault rifle, assault gun",
435
+ "414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
436
+ "415": "bakery, bakeshop, bakehouse",
437
+ "416": "balance beam, beam",
438
+ "417": "balloon",
439
+ "418": "ballpoint, ballpoint pen, ballpen, Biro",
440
+ "419": "Band Aid",
441
+ "420": "banjo",
442
+ "421": "bannister, banister, balustrade, balusters, handrail",
443
+ "422": "barbell",
444
+ "423": "barber chair",
445
+ "424": "barbershop",
446
+ "425": "barn",
447
+ "426": "barometer",
448
+ "427": "barrel, cask",
449
+ "428": "barrow, garden cart, lawn cart, wheelbarrow",
450
+ "429": "baseball",
451
+ "430": "basketball",
452
+ "431": "bassinet",
453
+ "432": "bassoon",
454
+ "433": "bathing cap, swimming cap",
455
+ "434": "bath towel",
456
+ "435": "bathtub, bathing tub, bath, tub",
457
+ "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
458
+ "437": "beacon, lighthouse, beacon light, pharos",
459
+ "438": "beaker",
460
+ "439": "bearskin, busby, shako",
461
+ "440": "beer bottle",
462
+ "441": "beer glass",
463
+ "442": "bell cote, bell cot",
464
+ "443": "bib",
465
+ "444": "bicycle-built-for-two, tandem bicycle, tandem",
466
+ "445": "bikini, two-piece",
467
+ "446": "binder, ring-binder",
468
+ "447": "binoculars, field glasses, opera glasses",
469
+ "448": "birdhouse",
470
+ "449": "boathouse",
471
+ "450": "bobsled, bobsleigh, bob",
472
+ "451": "bolo tie, bolo, bola tie, bola",
473
+ "452": "bonnet, poke bonnet",
474
+ "453": "bookcase",
475
+ "454": "bookshop, bookstore, bookstall",
476
+ "455": "bottlecap",
477
+ "456": "bow",
478
+ "457": "bow tie, bow-tie, bowtie",
479
+ "458": "brass, memorial tablet, plaque",
480
+ "459": "brassiere, bra, bandeau",
481
+ "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
482
+ "461": "breastplate, aegis, egis",
483
+ "462": "broom",
484
+ "463": "bucket, pail",
485
+ "464": "buckle",
486
+ "465": "bulletproof vest",
487
+ "466": "bullet train, bullet",
488
+ "467": "butcher shop, meat market",
489
+ "468": "cab, hack, taxi, taxicab",
490
+ "469": "caldron, cauldron",
491
+ "470": "candle, taper, wax light",
492
+ "471": "cannon",
493
+ "472": "canoe",
494
+ "473": "can opener, tin opener",
495
+ "474": "cardigan",
496
+ "475": "car mirror",
497
+ "476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
498
+ "477": "carpenters kit, tool kit",
499
+ "478": "carton",
500
+ "479": "car wheel",
501
+ "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
502
+ "481": "cassette",
503
+ "482": "cassette player",
504
+ "483": "castle",
505
+ "484": "catamaran",
506
+ "485": "CD player",
507
+ "486": "cello, violoncello",
508
+ "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
509
+ "488": "chain",
510
+ "489": "chainlink fence",
511
+ "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
512
+ "491": "chain saw, chainsaw",
513
+ "492": "chest",
514
+ "493": "chiffonier, commode",
515
+ "494": "chime, bell, gong",
516
+ "495": "china cabinet, china closet",
517
+ "496": "Christmas stocking",
518
+ "497": "church, church building",
519
+ "498": "cinema, movie theater, movie theatre, movie house, picture palace",
520
+ "499": "cleaver, meat cleaver, chopper",
521
+ "500": "cliff dwelling",
522
+ "501": "cloak",
523
+ "502": "clog, geta, patten, sabot",
524
+ "503": "cocktail shaker",
525
+ "504": "coffee mug",
526
+ "505": "coffeepot",
527
+ "506": "coil, spiral, volute, whorl, helix",
528
+ "507": "combination lock",
529
+ "508": "computer keyboard, keypad",
530
+ "509": "confectionery, confectionary, candy store",
531
+ "510": "container ship, containership, container vessel",
532
+ "511": "convertible",
533
+ "512": "corkscrew, bottle screw",
534
+ "513": "cornet, horn, trumpet, trump",
535
+ "514": "cowboy boot",
536
+ "515": "cowboy hat, ten-gallon hat",
537
+ "516": "cradle",
538
+ "517": "crane",
539
+ "518": "crash helmet",
540
+ "519": "crate",
541
+ "520": "crib, cot",
542
+ "521": "Crock Pot",
543
+ "522": "croquet ball",
544
+ "523": "crutch",
545
+ "524": "cuirass",
546
+ "525": "dam, dike, dyke",
547
+ "526": "desk",
548
+ "527": "desktop computer",
549
+ "528": "dial telephone, dial phone",
550
+ "529": "diaper, nappy, napkin",
551
+ "530": "digital clock",
552
+ "531": "digital watch",
553
+ "532": "dining table, board",
554
+ "533": "dishrag, dishcloth",
555
+ "534": "dishwasher, dish washer, dishwashing machine",
556
+ "535": "disk brake, disc brake",
557
+ "536": "dock, dockage, docking facility",
558
+ "537": "dogsled, dog sled, dog sleigh",
559
+ "538": "dome",
560
+ "539": "doormat, welcome mat",
561
+ "540": "drilling platform, offshore rig",
562
+ "541": "drum, membranophone, tympan",
563
+ "542": "drumstick",
564
+ "543": "dumbbell",
565
+ "544": "Dutch oven",
566
+ "545": "electric fan, blower",
567
+ "546": "electric guitar",
568
+ "547": "electric locomotive",
569
+ "548": "entertainment center",
570
+ "549": "envelope",
571
+ "550": "espresso maker",
572
+ "551": "face powder",
573
+ "552": "feather boa, boa",
574
+ "553": "file, file cabinet, filing cabinet",
575
+ "554": "fireboat",
576
+ "555": "fire engine, fire truck",
577
+ "556": "fire screen, fireguard",
578
+ "557": "flagpole, flagstaff",
579
+ "558": "flute, transverse flute",
580
+ "559": "folding chair",
581
+ "560": "football helmet",
582
+ "561": "forklift",
583
+ "562": "fountain",
584
+ "563": "fountain pen",
585
+ "564": "four-poster",
586
+ "565": "freight car",
587
+ "566": "French horn, horn",
588
+ "567": "frying pan, frypan, skillet",
589
+ "568": "fur coat",
590
+ "569": "garbage truck, dustcart",
591
+ "570": "gasmask, respirator, gas helmet",
592
+ "571": "gas pump, gasoline pump, petrol pump, island dispenser",
593
+ "572": "goblet",
594
+ "573": "go-kart",
595
+ "574": "golf ball",
596
+ "575": "golfcart, golf cart",
597
+ "576": "gondola",
598
+ "577": "gong, tam-tam",
599
+ "578": "gown",
600
+ "579": "grand piano, grand",
601
+ "580": "greenhouse, nursery, glasshouse",
602
+ "581": "grille, radiator grille",
603
+ "582": "grocery store, grocery, food market, market",
604
+ "583": "guillotine",
605
+ "584": "hair slide",
606
+ "585": "hair spray",
607
+ "586": "half track",
608
+ "587": "hammer",
609
+ "588": "hamper",
610
+ "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
611
+ "590": "hand-held computer, hand-held microcomputer",
612
+ "591": "handkerchief, hankie, hanky, hankey",
613
+ "592": "hard disc, hard disk, fixed disk",
614
+ "593": "harmonica, mouth organ, harp, mouth harp",
615
+ "594": "harp",
616
+ "595": "harvester, reaper",
617
+ "596": "hatchet",
618
+ "597": "holster",
619
+ "598": "home theater, home theatre",
620
+ "599": "honeycomb",
621
+ "600": "hook, claw",
622
+ "601": "hoopskirt, crinoline",
623
+ "602": "horizontal bar, high bar",
624
+ "603": "horse cart, horse-cart",
625
+ "604": "hourglass",
626
+ "605": "iPod",
627
+ "606": "iron, smoothing iron",
628
+ "607": "jack-o-lantern",
629
+ "608": "jean, blue jean, denim",
630
+ "609": "jeep, landrover",
631
+ "610": "jersey, T-shirt, tee shirt",
632
+ "611": "jigsaw puzzle",
633
+ "612": "jinrikisha, ricksha, rickshaw",
634
+ "613": "joystick",
635
+ "614": "kimono",
636
+ "615": "knee pad",
637
+ "616": "knot",
638
+ "617": "lab coat, laboratory coat",
639
+ "618": "ladle",
640
+ "619": "lampshade, lamp shade",
641
+ "620": "laptop, laptop computer",
642
+ "621": "lawn mower, mower",
643
+ "622": "lens cap, lens cover",
644
+ "623": "letter opener, paper knife, paperknife",
645
+ "624": "library",
646
+ "625": "lifeboat",
647
+ "626": "lighter, light, igniter, ignitor",
648
+ "627": "limousine, limo",
649
+ "628": "liner, ocean liner",
650
+ "629": "lipstick, lip rouge",
651
+ "630": "Loafer",
652
+ "631": "lotion",
653
+ "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
654
+ "633": "loupe, jewelers loupe",
655
+ "634": "lumbermill, sawmill",
656
+ "635": "magnetic compass",
657
+ "636": "mailbag, postbag",
658
+ "637": "mailbox, letter box",
659
+ "638": "maillot",
660
+ "639": "maillot, tank suit",
661
+ "640": "manhole cover",
662
+ "641": "maraca",
663
+ "642": "marimba, xylophone",
664
+ "643": "mask",
665
+ "644": "matchstick",
666
+ "645": "maypole",
667
+ "646": "maze, labyrinth",
668
+ "647": "measuring cup",
669
+ "648": "medicine chest, medicine cabinet",
670
+ "649": "megalith, megalithic structure",
671
+ "650": "microphone, mike",
672
+ "651": "microwave, microwave oven",
673
+ "652": "military uniform",
674
+ "653": "milk can",
675
+ "654": "minibus",
676
+ "655": "miniskirt, mini",
677
+ "656": "minivan",
678
+ "657": "missile",
679
+ "658": "mitten",
680
+ "659": "mixing bowl",
681
+ "660": "mobile home, manufactured home",
682
+ "661": "Model T",
683
+ "662": "modem",
684
+ "663": "monastery",
685
+ "664": "monitor",
686
+ "665": "moped",
687
+ "666": "mortar",
688
+ "667": "mortarboard",
689
+ "668": "mosque",
690
+ "669": "mosquito net",
691
+ "670": "motor scooter, scooter",
692
+ "671": "mountain bike, all-terrain bike, off-roader",
693
+ "672": "mountain tent",
694
+ "673": "mouse, computer mouse",
695
+ "674": "mousetrap",
696
+ "675": "moving van",
697
+ "676": "muzzle",
698
+ "677": "nail",
699
+ "678": "neck brace",
700
+ "679": "necklace",
701
+ "680": "nipple",
702
+ "681": "notebook, notebook computer",
703
+ "682": "obelisk",
704
+ "683": "oboe, hautboy, hautbois",
705
+ "684": "ocarina, sweet potato",
706
+ "685": "odometer, hodometer, mileometer, milometer",
707
+ "686": "oil filter",
708
+ "687": "organ, pipe organ",
709
+ "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
710
+ "689": "overskirt",
711
+ "690": "oxcart",
712
+ "691": "oxygen mask",
713
+ "692": "packet",
714
+ "693": "paddle, boat paddle",
715
+ "694": "paddlewheel, paddle wheel",
716
+ "695": "padlock",
717
+ "696": "paintbrush",
718
+ "697": "pajama, pyjama, pjs, jammies",
719
+ "698": "palace",
720
+ "699": "panpipe, pandean pipe, syrinx",
721
+ "700": "paper towel",
722
+ "701": "parachute, chute",
723
+ "702": "parallel bars, bars",
724
+ "703": "park bench",
725
+ "704": "parking meter",
726
+ "705": "passenger car, coach, carriage",
727
+ "706": "patio, terrace",
728
+ "707": "pay-phone, pay-station",
729
+ "708": "pedestal, plinth, footstall",
730
+ "709": "pencil box, pencil case",
731
+ "710": "pencil sharpener",
732
+ "711": "perfume, essence",
733
+ "712": "Petri dish",
734
+ "713": "photocopier",
735
+ "714": "pick, plectrum, plectron",
736
+ "715": "pickelhaube",
737
+ "716": "picket fence, paling",
738
+ "717": "pickup, pickup truck",
739
+ "718": "pier",
740
+ "719": "piggy bank, penny bank",
741
+ "720": "pill bottle",
742
+ "721": "pillow",
743
+ "722": "ping-pong ball",
744
+ "723": "pinwheel",
745
+ "724": "pirate, pirate ship",
746
+ "725": "pitcher, ewer",
747
+ "726": "plane, carpenters plane, woodworking plane",
748
+ "727": "planetarium",
749
+ "728": "plastic bag",
750
+ "729": "plate rack",
751
+ "730": "plow, plough",
752
+ "731": "plunger, plumbers helper",
753
+ "732": "Polaroid camera, Polaroid Land camera",
754
+ "733": "pole",
755
+ "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
756
+ "735": "poncho",
757
+ "736": "pool table, billiard table, snooker table",
758
+ "737": "pop bottle, soda bottle",
759
+ "738": "pot, flowerpot",
760
+ "739": "potters wheel",
761
+ "740": "power drill",
762
+ "741": "prayer rug, prayer mat",
763
+ "742": "printer",
764
+ "743": "prison, prison house",
765
+ "744": "projectile, missile",
766
+ "745": "projector",
767
+ "746": "puck, hockey puck",
768
+ "747": "punching bag, punch bag, punching ball, punchball",
769
+ "748": "purse",
770
+ "749": "quill, quill pen",
771
+ "750": "quilt, comforter, comfort, puff",
772
+ "751": "racer, race car, racing car",
773
+ "752": "racket, racquet",
774
+ "753": "radiator",
775
+ "754": "radio, wireless",
776
+ "755": "radio telescope, radio reflector",
777
+ "756": "rain barrel",
778
+ "757": "recreational vehicle, RV, R.V.",
779
+ "758": "reel",
780
+ "759": "reflex camera",
781
+ "760": "refrigerator, icebox",
782
+ "761": "remote control, remote",
783
+ "762": "restaurant, eating house, eating place, eatery",
784
+ "763": "revolver, six-gun, six-shooter",
785
+ "764": "rifle",
786
+ "765": "rocking chair, rocker",
787
+ "766": "rotisserie",
788
+ "767": "rubber eraser, rubber, pencil eraser",
789
+ "768": "rugby ball",
790
+ "769": "rule, ruler",
791
+ "770": "running shoe",
792
+ "771": "safe",
793
+ "772": "safety pin",
794
+ "773": "saltshaker, salt shaker",
795
+ "774": "sandal",
796
+ "775": "sarong",
797
+ "776": "sax, saxophone",
798
+ "777": "scabbard",
799
+ "778": "scale, weighing machine",
800
+ "779": "school bus",
801
+ "780": "schooner",
802
+ "781": "scoreboard",
803
+ "782": "screen, CRT screen",
804
+ "783": "screw",
805
+ "784": "screwdriver",
806
+ "785": "seat belt, seatbelt",
807
+ "786": "sewing machine",
808
+ "787": "shield, buckler",
809
+ "788": "shoe shop, shoe-shop, shoe store",
810
+ "789": "shoji",
811
+ "790": "shopping basket",
812
+ "791": "shopping cart",
813
+ "792": "shovel",
814
+ "793": "shower cap",
815
+ "794": "shower curtain",
816
+ "795": "ski",
817
+ "796": "ski mask",
818
+ "797": "sleeping bag",
819
+ "798": "slide rule, slipstick",
820
+ "799": "sliding door",
821
+ "800": "slot, one-armed bandit",
822
+ "801": "snorkel",
823
+ "802": "snowmobile",
824
+ "803": "snowplow, snowplough",
825
+ "804": "soap dispenser",
826
+ "805": "soccer ball",
827
+ "806": "sock",
828
+ "807": "solar dish, solar collector, solar furnace",
829
+ "808": "sombrero",
830
+ "809": "soup bowl",
831
+ "810": "space bar",
832
+ "811": "space heater",
833
+ "812": "space shuttle",
834
+ "813": "spatula",
835
+ "814": "speedboat",
836
+ "815": "spider web, spiders web",
837
+ "816": "spindle",
838
+ "817": "sports car, sport car",
839
+ "818": "spotlight, spot",
840
+ "819": "stage",
841
+ "820": "steam locomotive",
842
+ "821": "steel arch bridge",
843
+ "822": "steel drum",
844
+ "823": "stethoscope",
845
+ "824": "stole",
846
+ "825": "stone wall",
847
+ "826": "stopwatch, stop watch",
848
+ "827": "stove",
849
+ "828": "strainer",
850
+ "829": "streetcar, tram, tramcar, trolley, trolley car",
851
+ "830": "stretcher",
852
+ "831": "studio couch, day bed",
853
+ "832": "stupa, tope",
854
+ "833": "submarine, pigboat, sub, U-boat",
855
+ "834": "suit, suit of clothes",
856
+ "835": "sundial",
857
+ "836": "sunglass",
858
+ "837": "sunglasses, dark glasses, shades",
859
+ "838": "sunscreen, sunblock, sun blocker",
860
+ "839": "suspension bridge",
861
+ "840": "swab, swob, mop",
862
+ "841": "sweatshirt",
863
+ "842": "swimming trunks, bathing trunks",
864
+ "843": "swing",
865
+ "844": "switch, electric switch, electrical switch",
866
+ "845": "syringe",
867
+ "846": "table lamp",
868
+ "847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
869
+ "848": "tape player",
870
+ "849": "teapot",
871
+ "850": "teddy, teddy bear",
872
+ "851": "television, television system",
873
+ "852": "tennis ball",
874
+ "853": "thatch, thatched roof",
875
+ "854": "theater curtain, theatre curtain",
876
+ "855": "thimble",
877
+ "856": "thresher, thrasher, threshing machine",
878
+ "857": "throne",
879
+ "858": "tile roof",
880
+ "859": "toaster",
881
+ "860": "tobacco shop, tobacconist shop, tobacconist",
882
+ "861": "toilet seat",
883
+ "862": "torch",
884
+ "863": "totem pole",
885
+ "864": "tow truck, tow car, wrecker",
886
+ "865": "toyshop",
887
+ "866": "tractor",
888
+ "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
889
+ "868": "tray",
890
+ "869": "trench coat",
891
+ "870": "tricycle, trike, velocipede",
892
+ "871": "trimaran",
893
+ "872": "tripod",
894
+ "873": "triumphal arch",
895
+ "874": "trolleybus, trolley coach, trackless trolley",
896
+ "875": "trombone",
897
+ "876": "tub, vat",
898
+ "877": "turnstile",
899
+ "878": "typewriter keyboard",
900
+ "879": "umbrella",
901
+ "880": "unicycle, monocycle",
902
+ "881": "upright, upright piano",
903
+ "882": "vacuum, vacuum cleaner",
904
+ "883": "vase",
905
+ "884": "vault",
906
+ "885": "velvet",
907
+ "886": "vending machine",
908
+ "887": "vestment",
909
+ "888": "viaduct",
910
+ "889": "violin, fiddle",
911
+ "890": "volleyball",
912
+ "891": "waffle iron",
913
+ "892": "wall clock",
914
+ "893": "wallet, billfold, notecase, pocketbook",
915
+ "894": "wardrobe, closet, press",
916
+ "895": "warplane, military plane",
917
+ "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
918
+ "897": "washer, automatic washer, washing machine",
919
+ "898": "water bottle",
920
+ "899": "water jug",
921
+ "900": "water tower",
922
+ "901": "whiskey jug",
923
+ "902": "whistle",
924
+ "903": "wig",
925
+ "904": "window screen",
926
+ "905": "window shade",
927
+ "906": "Windsor tie",
928
+ "907": "wine bottle",
929
+ "908": "wing",
930
+ "909": "wok",
931
+ "910": "wooden spoon",
932
+ "911": "wool, woolen, woollen",
933
+ "912": "worm fence, snake fence, snake-rail fence, Virginia fence",
934
+ "913": "wreck",
935
+ "914": "yawl",
936
+ "915": "yurt",
937
+ "916": "web site, website, internet site, site",
938
+ "917": "comic book",
939
+ "918": "crossword puzzle, crossword",
940
+ "919": "street sign",
941
+ "920": "traffic light, traffic signal, stoplight",
942
+ "921": "book jacket, dust cover, dust jacket, dust wrapper",
943
+ "922": "menu",
944
+ "923": "plate",
945
+ "924": "guacamole",
946
+ "925": "consomme",
947
+ "926": "hot pot, hotpot",
948
+ "927": "trifle",
949
+ "928": "ice cream, icecream",
950
+ "929": "ice lolly, lolly, lollipop, popsicle",
951
+ "930": "French loaf",
952
+ "931": "bagel, beigel",
953
+ "932": "pretzel",
954
+ "933": "cheeseburger",
955
+ "934": "hotdog, hot dog, red hot",
956
+ "935": "mashed potato",
957
+ "936": "head cabbage",
958
+ "937": "broccoli",
959
+ "938": "cauliflower",
960
+ "939": "zucchini, courgette",
961
+ "940": "spaghetti squash",
962
+ "941": "acorn squash",
963
+ "942": "butternut squash",
964
+ "943": "cucumber, cuke",
965
+ "944": "artichoke, globe artichoke",
966
+ "945": "bell pepper",
967
+ "946": "cardoon",
968
+ "947": "mushroom",
969
+ "948": "Granny Smith",
970
+ "949": "strawberry",
971
+ "950": "orange",
972
+ "951": "lemon",
973
+ "952": "fig",
974
+ "953": "pineapple, ananas",
975
+ "954": "banana",
976
+ "955": "jackfruit, jak, jack",
977
+ "956": "custard apple",
978
+ "957": "pomegranate",
979
+ "958": "hay",
980
+ "959": "carbonara",
981
+ "960": "chocolate sauce, chocolate syrup",
982
+ "961": "dough",
983
+ "962": "meat loaf, meatloaf",
984
+ "963": "pizza, pizza pie",
985
+ "964": "potpie",
986
+ "965": "burrito",
987
+ "966": "red wine",
988
+ "967": "espresso",
989
+ "968": "cup",
990
+ "969": "eggnog",
991
+ "970": "alp",
992
+ "971": "bubble",
993
+ "972": "cliff, drop, drop-off",
994
+ "973": "coral reef",
995
+ "974": "geyser",
996
+ "975": "lakeside, lakeshore",
997
+ "976": "promontory, headland, head, foreland",
998
+ "977": "sandbar, sand bar",
999
+ "978": "seashore, coast, seacoast, sea-coast",
1000
+ "979": "valley, vale",
1001
+ "980": "volcano",
1002
+ "981": "ballplayer, baseball player",
1003
+ "982": "groom, bridegroom",
1004
+ "983": "scuba diver",
1005
+ "984": "rapeseed",
1006
+ "985": "daisy",
1007
+ "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
1008
+ "987": "corn",
1009
+ "988": "acorn",
1010
+ "989": "hip, rose hip, rosehip",
1011
+ "990": "buckeye, horse chestnut, conker",
1012
+ "991": "coral fungus",
1013
+ "992": "agaric",
1014
+ "993": "gyromitra",
1015
+ "994": "stinkhorn, carrion fungus",
1016
+ "995": "earthstar",
1017
+ "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
1018
+ "997": "bolete",
1019
+ "998": "ear, spike, capitulum",
1020
+ "999": "toilet tissue, toilet paper, bathroom tissue"
1021
+ }
1022
+ }
AFM-L-2-1NFE-noguide/pipeline.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: AFMPipeline.
2
+
3
+ Load with native Hugging Face diffusers and trust_remote_code=True.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ from diffusers.image_processor import VaeImageProcessor
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
16
+ from diffusers.utils.torch_utils import randn_tensor
17
+
18
+
19
+ class AFMPipeline(DiffusionPipeline):
20
+ model_cpu_offload_seq = "generator->vae"
21
+
22
+ @staticmethod
23
+ def _coerce_scheduler(scheduler, generator):
24
+ if scheduler is not None and not isinstance(scheduler, (list, tuple)):
25
+ return scheduler
26
+ variant_path = getattr(generator.config, "_name_or_path", None)
27
+ if variant_path:
28
+ scheduler_dir = Path(variant_path).resolve().parent / "scheduler"
29
+ module_path = scheduler_dir / "scheduling_continuous_flow.py"
30
+ config_path = scheduler_dir / "scheduler_config.json"
31
+ if module_path.is_file() and config_path.is_file():
32
+ spec = importlib.util.spec_from_file_location("scheduling_continuous_flow", module_path)
33
+ if spec is not None and spec.loader is not None:
34
+ module = importlib.util.module_from_spec(spec)
35
+ spec.loader.exec_module(module)
36
+ return module.ContinuousFlowMatchScheduler.from_pretrained(str(scheduler_dir))
37
+ raise ValueError("AFMPipeline could not load ContinuousFlowMatchScheduler from the variant folder.")
38
+
39
+ def __init__(
40
+ self,
41
+ generator,
42
+ vae,
43
+ scheduler=None,
44
+ pred_type: str = "x",
45
+ id2label: Optional[Dict[Union[int, str], str]] = None,
46
+ ) -> None:
47
+ super().__init__()
48
+ scheduler = self._coerce_scheduler(scheduler, generator)
49
+ self.register_modules(generator=generator, vae=vae, scheduler=scheduler)
50
+ self.register_to_config(pred_type=pred_type)
51
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
52
+ self._id2label = self._normalize_id2label(id2label)
53
+ self.labels = self._build_label2id(self._id2label)
54
+ self._labels_loaded_from_model_index = bool(self._id2label)
55
+
56
+ @staticmethod
57
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
58
+ if not id2label:
59
+ return {}
60
+ return {int(key): value for key, value in id2label.items()}
61
+
62
+ @staticmethod
63
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
64
+ if not variant_path:
65
+ return {}
66
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
67
+ if not model_index_path.exists():
68
+ return {}
69
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
70
+ id2label = raw.get("id2label")
71
+ if not isinstance(id2label, dict):
72
+ return {}
73
+ return {int(key): value for key, value in id2label.items()}
74
+
75
+ @staticmethod
76
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
77
+ label2id: Dict[str, int] = {}
78
+ for class_id, value in id2label.items():
79
+ for synonym in value.split(","):
80
+ synonym = synonym.strip()
81
+ if synonym:
82
+ label2id[synonym] = int(class_id)
83
+ return dict(sorted(label2id.items()))
84
+
85
+ @property
86
+ def vae_scale_factor(self) -> int:
87
+ block_out_channels = getattr(self.vae.config, "block_out_channels", None)
88
+ if block_out_channels:
89
+ return int(2 ** (len(block_out_channels) - 1))
90
+ return 8
91
+
92
+ @property
93
+ def id2label(self) -> Dict[int, str]:
94
+ self._ensure_labels_loaded()
95
+ return self._id2label
96
+
97
+ def _ensure_labels_loaded(self) -> None:
98
+ if self._labels_loaded_from_model_index:
99
+ return
100
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
101
+ if loaded:
102
+ self._id2label = loaded
103
+ self.labels = self._build_label2id(self._id2label)
104
+ self._labels_loaded_from_model_index = True
105
+
106
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
107
+ self._ensure_labels_loaded()
108
+ labels = [label] if isinstance(label, str) else label
109
+ if not self.labels:
110
+ raise ValueError("No id2label mapping is available in this checkpoint.")
111
+ missing = [item for item in labels if item not in self.labels]
112
+ if missing:
113
+ preview = ", ".join(list(self.labels.keys())[:8])
114
+ raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
115
+ return [self.labels[item] for item in labels]
116
+
117
+ def _normalize_class_labels(
118
+ self,
119
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
120
+ device: torch.device,
121
+ ) -> torch.LongTensor:
122
+ if torch.is_tensor(class_labels):
123
+ return class_labels.to(device=device, dtype=torch.long).reshape(-1)
124
+ if isinstance(class_labels, int):
125
+ class_label_ids = [class_labels]
126
+ elif isinstance(class_labels, str):
127
+ class_label_ids = self.get_label_ids(class_labels)
128
+ elif class_labels and isinstance(class_labels[0], str):
129
+ class_label_ids = self.get_label_ids(class_labels)
130
+ else:
131
+ class_label_ids = list(class_labels)
132
+ return torch.tensor(class_label_ids, device=device, dtype=torch.long).reshape(-1)
133
+
134
+ def _default_image_size(self) -> int:
135
+ transformer = getattr(self.generator, "transformer", None)
136
+ if transformer is not None:
137
+ return int(transformer.config.sample_size) * self.vae_scale_factor
138
+ return 256
139
+
140
+ def check_inputs(
141
+ self,
142
+ height: int,
143
+ width: int,
144
+ num_inference_steps: int,
145
+ output_type: str,
146
+ sampler: str,
147
+ ) -> None:
148
+ if num_inference_steps < 1:
149
+ raise ValueError("`num_inference_steps` must be >= 1.")
150
+ if output_type not in {"pil", "np", "pt", "latent"}:
151
+ raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
152
+ if sampler not in {"euler", "heun"}:
153
+ raise ValueError("sampler must be one of: 'euler', 'heun'.")
154
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
155
+ raise ValueError(
156
+ f"`height` and `width` must be divisible by {self.vae_scale_factor}, got ({height}, {width})."
157
+ )
158
+
159
+ def prepare_latents(
160
+ self,
161
+ batch_size: int,
162
+ height: int,
163
+ width: int,
164
+ dtype: torch.dtype,
165
+ device: torch.device,
166
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
167
+ latents: Optional[torch.Tensor] = None,
168
+ ) -> torch.Tensor:
169
+ if latents is not None:
170
+ return latents.to(device=device, dtype=dtype)
171
+ latent_height = height // self.vae_scale_factor
172
+ latent_width = width // self.vae_scale_factor
173
+ in_channels = int(getattr(self.generator, "in_channels", 4))
174
+ return randn_tensor(
175
+ (batch_size, in_channels, latent_height, latent_width),
176
+ generator=generator,
177
+ device=device,
178
+ dtype=dtype,
179
+ )
180
+
181
+ def decode_latents(self, latents: torch.Tensor, output_type: str = "pil"):
182
+ if output_type == "latent":
183
+ return latents
184
+ scaling_factor = getattr(self.vae.config, "scaling_factor", 0.18215)
185
+ image = self.vae.decode(latents / scaling_factor).sample
186
+ if output_type == "pt":
187
+ return image
188
+ return self.image_processor.postprocess(image, output_type=output_type)
189
+
190
+ def _run_denoising_loop(
191
+ self,
192
+ latents: torch.Tensor,
193
+ class_labels_tensor: torch.Tensor,
194
+ batch_size: int,
195
+ device: torch.device,
196
+ num_inference_steps: int,
197
+ sampler: str,
198
+ pred_type: str,
199
+ ) -> torch.Tensor:
200
+ self.scheduler.set_timesteps(num_inference_steps, device=device, solver=sampler)
201
+ timesteps = self.scheduler.timesteps
202
+ self.generator.eval()
203
+ for t_src, t_tgt in self.progress_bar(list(zip(timesteps[:-1], timesteps[1:]))):
204
+ t_src_batch = t_src.expand(batch_size)
205
+ t_tgt_batch = t_tgt.expand(batch_size)
206
+ outputs = self.generator(latents, class_labels_tensor, t_src_batch, t_tgt_batch)
207
+ if pred_type == "v":
208
+ if sampler == "heun":
209
+ latents_next = self.scheduler.step(
210
+ outputs, t_src, t_tgt, latents, prediction_type="v"
211
+ ).prev_sample
212
+ outputs_next = self.generator(latents_next, class_labels_tensor, t_tgt_batch, t_tgt_batch)
213
+ latents = self.scheduler.step(
214
+ outputs,
215
+ t_src,
216
+ t_tgt,
217
+ latents,
218
+ model_output_next=outputs_next,
219
+ prediction_type="v",
220
+ ).prev_sample
221
+ else:
222
+ latents = self.scheduler.step(
223
+ outputs, t_src, t_tgt, latents, prediction_type="v"
224
+ ).prev_sample
225
+ else:
226
+ latents = outputs
227
+ return latents
228
+
229
+ @torch.inference_mode()
230
+ def __call__(
231
+ self,
232
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
233
+ height: Optional[int] = None,
234
+ width: Optional[int] = None,
235
+ num_inference_steps: Optional[int] = None,
236
+ sampler: str = "euler",
237
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
238
+ latents: Optional[torch.Tensor] = None,
239
+ output_type: str = "pil",
240
+ return_dict: bool = True,
241
+ ):
242
+ default_size = self._default_image_size()
243
+ height = int(height or default_size)
244
+ width = int(width or default_size)
245
+ if num_inference_steps is None:
246
+ num_inference_steps = int(getattr(self.generator.config, "num_inference_steps", 1))
247
+ self.check_inputs(height, width, num_inference_steps, output_type, sampler)
248
+
249
+ device = getattr(self, "_execution_device", None) or next(self.generator.parameters()).device
250
+ dtype = next(self.generator.parameters()).dtype
251
+ pred_type = self.config.pred_type
252
+ class_labels_tensor = self._normalize_class_labels(class_labels, device=device)
253
+ batch_size = class_labels_tensor.shape[0]
254
+ latents = self.prepare_latents(
255
+ batch_size=batch_size,
256
+ height=height,
257
+ width=width,
258
+ dtype=dtype,
259
+ device=device,
260
+ generator=generator,
261
+ latents=latents,
262
+ )
263
+ latents = self._run_denoising_loop(
264
+ latents,
265
+ class_labels_tensor,
266
+ batch_size,
267
+ device,
268
+ num_inference_steps,
269
+ sampler,
270
+ pred_type,
271
+ )
272
+ image = self.decode_latents(latents, output_type=output_type)
273
+ self.maybe_free_model_hooks()
274
+ if not return_dict:
275
+ return (image,)
276
+ return ImagePipelineOutput(images=image)
AFM-L-2-1NFE-noguide/scheduler/__pycache__/scheduling_continuous_flow.cpython-312.pyc ADDED
Binary file (5.38 kB). View file
 
AFM-L-2-1NFE-noguide/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ContinuousFlowMatchScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "solver": "euler"
5
+ }
AFM-L-2-1NFE-noguide/scheduler/scheduling_continuous_flow.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+ from diffusers.utils import BaseOutput
10
+
11
+
12
+ @dataclass
13
+ class ContinuousFlowMatchSchedulerOutput(BaseOutput):
14
+ prev_sample: torch.Tensor
15
+
16
+
17
+ class ContinuousFlowMatchScheduler(SchedulerMixin, ConfigMixin):
18
+ """Flow-matching scheduler for AFM with time in [1, 0]."""
19
+
20
+ order = 2
21
+
22
+ @register_to_config
23
+ def __init__(self, solver: str = "euler"):
24
+ if solver not in {"euler", "heun"}:
25
+ raise ValueError("solver must be one of: 'euler', 'heun'.")
26
+ self.timesteps: Optional[torch.Tensor] = None
27
+ self.num_inference_steps: Optional[int] = None
28
+ self._step_index: Optional[int] = None
29
+
30
+ @property
31
+ def init_noise_sigma(self) -> float:
32
+ return 1.0
33
+
34
+ def set_timesteps(
35
+ self,
36
+ num_inference_steps: int,
37
+ device: Union[str, torch.device, None] = None,
38
+ solver: Optional[str] = None,
39
+ ) -> None:
40
+ if num_inference_steps < 1:
41
+ raise ValueError("num_inference_steps must be >= 1.")
42
+ self.num_inference_steps = num_inference_steps
43
+ if solver == "heun":
44
+ grid_size = (num_inference_steps // 2) + 1
45
+ else:
46
+ grid_size = num_inference_steps + 1
47
+ self.timesteps = torch.linspace(1.0, 0.0, grid_size, device=device, dtype=torch.float32)
48
+ self._step_index = 0
49
+ if solver is not None:
50
+ self.register_to_config(solver=solver)
51
+
52
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
53
+ del timestep
54
+ return sample
55
+
56
+ def _resolve_step_index(self, timestep: Union[float, torch.Tensor, None]) -> int:
57
+ if self._step_index is not None:
58
+ return self._step_index
59
+ if self.timesteps is None:
60
+ raise ValueError("Call `set_timesteps` before `step`.")
61
+ if timestep is None:
62
+ return 0
63
+ t_value = float(timestep) if not isinstance(timestep, torch.Tensor) else float(timestep.flatten()[0])
64
+ matches = (self.timesteps - t_value).abs() < 1e-6
65
+ if matches.any():
66
+ return int(matches.nonzero(as_tuple=False)[0].item())
67
+ return 0
68
+
69
+ def step(
70
+ self,
71
+ model_output: torch.Tensor,
72
+ timestep_src: Union[float, torch.Tensor],
73
+ timestep_tgt: Union[float, torch.Tensor],
74
+ sample: torch.Tensor,
75
+ model_output_next: Optional[torch.Tensor] = None,
76
+ prediction_type: str = "v",
77
+ return_dict: bool = True,
78
+ ) -> Union[ContinuousFlowMatchSchedulerOutput, Tuple[torch.Tensor]]:
79
+ if prediction_type == "x":
80
+ prev_sample = model_output
81
+ else:
82
+ t_src = torch.as_tensor(timestep_src, device=sample.device, dtype=sample.dtype)
83
+ t_tgt = torch.as_tensor(timestep_tgt, device=sample.device, dtype=sample.dtype)
84
+ while t_src.ndim < sample.ndim:
85
+ t_src = t_src.unsqueeze(-1)
86
+ t_tgt = t_tgt.unsqueeze(-1)
87
+ dt = t_src - t_tgt
88
+ if self.config.solver == "heun" and model_output_next is not None:
89
+ prev_sample = sample - dt * 0.5 * (model_output + model_output_next)
90
+ else:
91
+ prev_sample = sample - dt * model_output
92
+
93
+ step_index = self._resolve_step_index(timestep_src)
94
+ self._step_index = step_index + 1
95
+
96
+ if not return_dict:
97
+ return (prev_sample,)
98
+ return ContinuousFlowMatchSchedulerOutput(prev_sample=prev_sample)
AFM-L-2-1NFE-noguide/vae/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.36.0",
4
+ "_name_or_path": "stabilityai/sd-vae-ft-mse",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "latents_mean": null,
22
+ "latents_std": null,
23
+ "layers_per_block": 2,
24
+ "mid_block_add_attention": true,
25
+ "norm_num_groups": 32,
26
+ "out_channels": 3,
27
+ "sample_size": 256,
28
+ "scaling_factor": 0.18215,
29
+ "shift_factor": null,
30
+ "up_block_types": [
31
+ "UpDecoderBlock2D",
32
+ "UpDecoderBlock2D",
33
+ "UpDecoderBlock2D",
34
+ "UpDecoderBlock2D"
35
+ ],
36
+ "use_post_quant_conv": true,
37
+ "use_quant_conv": true
38
+ }
AFM-L-2-1NFE-noguide/vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d993488569e928462932c8c38a0760b874d166399b14414135bd9c42df5815
3
+ size 334643276
AFM-M-2-1NFE-guided/demo.png ADDED

Git LFS Details

  • SHA256: 033a1fc178676cf614ca0e2a68bbedd349094dd2e6235e97ac0523aadccd558e
  • Pointer size: 131 Bytes
  • Size of remote file: 108 kB
AFM-M-2-1NFE-guided/generator/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AFMGenerator2DModel",
3
+ "_diffusers_version": "0.36.0",
4
+ "model_type": "AFM-M/2",
5
+ "architecture": "standard",
6
+ "repeat": 1,
7
+ "use_t_src": false,
8
+ "use_t_tgt": false,
9
+ "pred_type": "x",
10
+ "num_inference_steps": 1,
11
+ "learn_sigma": false,
12
+ "class_dropout_prob": 0.0,
13
+ "input_size": 32,
14
+ "num_classes": 1000,
15
+ "in_channels": 4,
16
+ "depth": 16,
17
+ "hidden_size": 1024,
18
+ "patch_size": 2,
19
+ "num_heads": 16
20
+ }
AFM-M-2-1NFE-guided/generator/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12c57e80b3d69a132a46821571db1d7559f7b5df75fc74454b99c394c5c3385c
3
+ size 1367133768
AFM-M-2-1NFE-guided/generator/modeling_afm.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained AFM generator for Hugging Face diffusers checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Dict, Optional
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from torch import nn
14
+
15
+
16
+ def get_dit_transformer_class():
17
+ from diffusers.models.transformers.dit_transformer_2d import DiTTransformer2DModel
18
+
19
+ return DiTTransformer2DModel
20
+
21
+
22
+ def build_dit_config(
23
+ *,
24
+ depth: int = 28,
25
+ hidden_size: int = 1152,
26
+ patch_size: int = 2,
27
+ num_heads: int = 16,
28
+ learn_sigma: bool = False,
29
+ class_dropout_prob: float = 0.0,
30
+ input_size: int = 32,
31
+ num_classes: int = 1000,
32
+ in_channels: int = 4,
33
+ ) -> Dict[str, Any]:
34
+ attention_head_dim = hidden_size // num_heads
35
+ num_embeds_ada_norm = num_classes + (1 if class_dropout_prob > 0 else 0)
36
+ out_channels = in_channels * 2 if learn_sigma else in_channels
37
+ return {
38
+ "sample_size": input_size,
39
+ "num_layers": depth,
40
+ "num_attention_heads": num_heads,
41
+ "attention_head_dim": attention_head_dim,
42
+ "in_channels": in_channels,
43
+ "out_channels": out_channels,
44
+ "patch_size": patch_size,
45
+ "attention_bias": True,
46
+ "activation_fn": "gelu-approximate",
47
+ "num_embeds_ada_norm": num_embeds_ada_norm,
48
+ "norm_type": "ada_norm_zero",
49
+ "norm_elementwise_affine": False,
50
+ "dropout": 0.0,
51
+ "norm_num_groups": 32,
52
+ "norm_eps": 1e-5,
53
+ "upcast_attention": False,
54
+ }
55
+
56
+
57
+ def _convert_legacy_dit_state_dict(state_dict: Dict[str, torch.Tensor], depth: int) -> Dict[str, torch.Tensor]:
58
+ converted = copy.deepcopy(state_dict)
59
+
60
+ converted["pos_embed.proj.weight"] = converted.pop("x_embedder.proj.weight").clone().contiguous()
61
+ converted["pos_embed.proj.bias"] = converted.pop("x_embedder.proj.bias").clone().contiguous()
62
+
63
+ if "t_embedder.mlp.0.weight" in converted:
64
+ timestep_weights = {
65
+ "linear_1.weight": converted.pop("t_embedder.mlp.0.weight"),
66
+ "linear_1.bias": converted.pop("t_embedder.mlp.0.bias"),
67
+ "linear_2.weight": converted.pop("t_embedder.mlp.2.weight"),
68
+ "linear_2.bias": converted.pop("t_embedder.mlp.2.bias"),
69
+ }
70
+ else:
71
+ timestep_weights = None
72
+ class_embedding = converted.pop("y_embedder.embedding_table.weight")
73
+ if class_embedding.shape[0] == 1000:
74
+ null_class = torch.zeros(1, class_embedding.shape[1], dtype=class_embedding.dtype)
75
+ class_embedding = torch.cat([class_embedding, null_class], dim=0)
76
+
77
+ for block_idx in range(depth):
78
+ if timestep_weights is not None:
79
+ for key, tensor in timestep_weights.items():
80
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.timestep_embedder.{key}"] = tensor.clone()
81
+ converted[f"transformer_blocks.{block_idx}.norm1.emb.class_embedder.embedding_table.weight"] = (
82
+ class_embedding.clone()
83
+ )
84
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.weight"] = converted[
85
+ f"blocks.{block_idx}.adaLN_modulation.1.weight"
86
+ ]
87
+ converted[f"transformer_blocks.{block_idx}.norm1.linear.bias"] = converted[
88
+ f"blocks.{block_idx}.adaLN_modulation.1.bias"
89
+ ]
90
+
91
+ q, k, v = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.weight"], 3, dim=0)
92
+ q_bias, k_bias, v_bias = torch.chunk(converted[f"blocks.{block_idx}.attn.qkv.bias"], 3, dim=0)
93
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.weight"] = q
94
+ converted[f"transformer_blocks.{block_idx}.attn1.to_q.bias"] = q_bias
95
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.weight"] = k
96
+ converted[f"transformer_blocks.{block_idx}.attn1.to_k.bias"] = k_bias
97
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.weight"] = v
98
+ converted[f"transformer_blocks.{block_idx}.attn1.to_v.bias"] = v_bias
99
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.weight"] = converted[
100
+ f"blocks.{block_idx}.attn.proj.weight"
101
+ ]
102
+ converted[f"transformer_blocks.{block_idx}.attn1.to_out.0.bias"] = converted[
103
+ f"blocks.{block_idx}.attn.proj.bias"
104
+ ]
105
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.weight"] = converted[
106
+ f"blocks.{block_idx}.mlp.fc1.weight"
107
+ ]
108
+ converted[f"transformer_blocks.{block_idx}.ff.net.0.proj.bias"] = converted[
109
+ f"blocks.{block_idx}.mlp.fc1.bias"
110
+ ]
111
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.weight"] = converted[
112
+ f"blocks.{block_idx}.mlp.fc2.weight"
113
+ ]
114
+ converted[f"transformer_blocks.{block_idx}.ff.net.2.bias"] = converted[
115
+ f"blocks.{block_idx}.mlp.fc2.bias"
116
+ ]
117
+
118
+ for suffix in (
119
+ "attn.qkv.weight",
120
+ "attn.qkv.bias",
121
+ "attn.proj.weight",
122
+ "attn.proj.bias",
123
+ "mlp.fc1.weight",
124
+ "mlp.fc1.bias",
125
+ "mlp.fc2.weight",
126
+ "mlp.fc2.bias",
127
+ "adaLN_modulation.1.weight",
128
+ "adaLN_modulation.1.bias",
129
+ ):
130
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
131
+
132
+ converted["proj_out_1.weight"] = converted.pop("final_layer.adaLN_modulation.1.weight")
133
+ converted["proj_out_1.bias"] = converted.pop("final_layer.adaLN_modulation.1.bias")
134
+ converted["proj_out_2.weight"] = converted.pop("final_layer.linear.weight")
135
+ converted["proj_out_2.bias"] = converted.pop("final_layer.linear.bias")
136
+
137
+ converted.pop("pos_embed", None)
138
+ for block_idx in range(depth):
139
+ for suffix in ("norm1.weight", "norm1.bias", "norm2.weight", "norm2.bias"):
140
+ converted.pop(f"blocks.{block_idx}.{suffix}", None)
141
+
142
+ return {key: tensor.detach().clone().contiguous() for key, tensor in converted.items()}
143
+
144
+
145
+ def load_legacy_dit_state_dict(
146
+ state_dict: Dict[str, torch.Tensor],
147
+ depth: int,
148
+ patch_size: int,
149
+ hidden_size: int,
150
+ num_heads: int,
151
+ ) -> Dict[str, torch.Tensor]:
152
+ if "transformer_blocks.0.attn1.to_q.weight" in state_dict:
153
+ return state_dict
154
+ if any(key.startswith("blocks.") for key in state_dict):
155
+ return _convert_legacy_dit_state_dict(state_dict, depth)
156
+ return state_dict
157
+
158
+
159
+ def forward_dit_output(
160
+ transformer,
161
+ hidden_states: torch.Tensor,
162
+ timestep: Optional[torch.Tensor],
163
+ class_labels: torch.Tensor,
164
+ extra_cond: Optional[torch.Tensor] = None,
165
+ ) -> torch.Tensor:
166
+ hidden_states = transformer.pos_embed(hidden_states)
167
+
168
+ for block in transformer.transformer_blocks:
169
+ if torch.is_grad_enabled() and transformer.gradient_checkpointing:
170
+ hidden_states = transformer._gradient_checkpointing_func(
171
+ block,
172
+ hidden_states,
173
+ None,
174
+ None,
175
+ None,
176
+ timestep,
177
+ None,
178
+ class_labels,
179
+ )
180
+ else:
181
+ hidden_states = block(
182
+ hidden_states,
183
+ attention_mask=None,
184
+ encoder_hidden_states=None,
185
+ encoder_attention_mask=None,
186
+ timestep=timestep,
187
+ cross_attention_kwargs=None,
188
+ class_labels=class_labels,
189
+ )
190
+
191
+ conditioning = transformer.transformer_blocks[0].norm1.emb(
192
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
193
+ )
194
+ if extra_cond is not None:
195
+ conditioning = conditioning + extra_cond
196
+ shift, scale = transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
197
+ hidden_states = transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
198
+ hidden_states = transformer.proj_out_2(hidden_states)
199
+
200
+ height = width = int(hidden_states.shape[1] ** 0.5)
201
+ hidden_states = hidden_states.reshape(
202
+ shape=(-1, height, width, transformer.patch_size, transformer.patch_size, transformer.out_channels)
203
+ )
204
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
205
+ return hidden_states.reshape(
206
+ shape=(-1, transformer.out_channels, height * transformer.patch_size, width * transformer.patch_size)
207
+ )
208
+
209
+
210
+ def remap_transformer_state_dict(
211
+ state_dict: Dict[str, torch.Tensor],
212
+ legacy_kwargs: Dict[str, int],
213
+ extra_prefixes: tuple[str, ...] = (),
214
+ ) -> Dict[str, torch.Tensor]:
215
+ state_dict = load_legacy_dit_state_dict(state_dict, **legacy_kwargs)
216
+ remapped: Dict[str, torch.Tensor] = {}
217
+ for key, value in state_dict.items():
218
+ if any(key.startswith(prefix) for prefix in extra_prefixes):
219
+ remapped[key] = value
220
+ elif key.startswith("transformer."):
221
+ remapped[key] = value
222
+ else:
223
+ remapped[f"transformer.{key}"] = value
224
+ return remapped
225
+
226
+
227
+ def split_output_channels(output: torch.Tensor, in_channels: int) -> torch.Tensor:
228
+ if output.shape[1] == in_channels:
229
+ return output
230
+ output, _ = output.chunk(2, dim=1)
231
+ return output
232
+
233
+
234
+ class TimestepEmbedder(nn.Module):
235
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
236
+ super().__init__()
237
+ self.mlp = nn.Sequential(
238
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
239
+ nn.SiLU(),
240
+ nn.Linear(hidden_size, hidden_size, bias=True),
241
+ )
242
+ self.frequency_embedding_size = frequency_embedding_size
243
+
244
+ @staticmethod
245
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
246
+ half = dim // 2
247
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
248
+ device=t.device
249
+ )
250
+ args = t[:, None].float() * freqs[None]
251
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
252
+ if dim % 2:
253
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
254
+ return embedding
255
+
256
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
257
+ emb = self.timestep_embedding(t.float(), self.frequency_embedding_size)
258
+ weight_dtype = self.mlp[0].weight.dtype
259
+ return self.mlp(emb.to(dtype=weight_dtype))
260
+
261
+
262
+ class Generator(nn.Module):
263
+ def __init__(
264
+ self,
265
+ *,
266
+ use_t_src: bool = False,
267
+ use_t_tgt: bool = False,
268
+ depth: int = 28,
269
+ hidden_size: int = 1152,
270
+ patch_size: int = 2,
271
+ num_heads: int = 16,
272
+ learn_sigma: bool = False,
273
+ class_dropout_prob: float = 0.0,
274
+ input_size: int = 32,
275
+ num_classes: int = 1000,
276
+ in_channels: int = 4,
277
+ **_,
278
+ ):
279
+ super().__init__()
280
+ self.use_t_src = use_t_src
281
+ self.use_t_tgt = use_t_tgt
282
+ self._legacy_kwargs = {
283
+ "depth": depth,
284
+ "hidden_size": hidden_size,
285
+ "patch_size": patch_size,
286
+ "num_heads": num_heads,
287
+ }
288
+ dit_cls = get_dit_transformer_class()
289
+ self.transformer = dit_cls(
290
+ **build_dit_config(
291
+ depth=depth,
292
+ hidden_size=hidden_size,
293
+ patch_size=patch_size,
294
+ num_heads=num_heads,
295
+ learn_sigma=learn_sigma,
296
+ class_dropout_prob=class_dropout_prob,
297
+ input_size=input_size,
298
+ num_classes=num_classes,
299
+ in_channels=in_channels,
300
+ )
301
+ )
302
+ self.in_channels = in_channels
303
+ if use_t_tgt:
304
+ self.t_tgt_embedder = TimestepEmbedder(hidden_size)
305
+ nn.init.normal_(self.t_tgt_embedder.mlp[0].weight, std=0.02)
306
+ nn.init.normal_(self.t_tgt_embedder.mlp[2].weight, std=0.02)
307
+
308
+ def load_state_dict(self, state_dict, strict: bool = True):
309
+ extra = ("t_tgt_embedder.",)
310
+ has_extra = any(key.startswith(extra) for key in state_dict)
311
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
312
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs, extra_prefixes=extra)
313
+ if self.use_t_tgt and not has_extra:
314
+ strict = False
315
+ if not has_t_embedder:
316
+ strict = False
317
+ out = super().load_state_dict(remapped, strict=strict)
318
+ if not has_t_embedder:
319
+ for name, param in self.named_parameters():
320
+ if "timestep_embedder" in name:
321
+ param.data.zero_()
322
+ return out
323
+
324
+ def forward(self, x, y, t_src=None, t_tgt=None):
325
+ if self.use_t_src and t_src is not None:
326
+ timestep = (t_src * 1000).long()
327
+ else:
328
+ timestep = torch.zeros(x.shape[0], device=x.device, dtype=torch.long)
329
+
330
+ extra_cond = None
331
+ if self.use_t_tgt and t_tgt is not None:
332
+ extra_cond = self.t_tgt_embedder(t_tgt * 1000)
333
+
334
+ output = forward_dit_output(self.transformer, x, timestep, y, extra_cond=extra_cond)
335
+ return split_output_channels(output, self.in_channels)
336
+
337
+
338
+ class GeneratorDeep(nn.Module):
339
+ def __init__(
340
+ self,
341
+ *,
342
+ repeat: int,
343
+ depth: int = 28,
344
+ hidden_size: int = 1152,
345
+ patch_size: int = 2,
346
+ num_heads: int = 16,
347
+ learn_sigma: bool = False,
348
+ class_dropout_prob: float = 0.0,
349
+ input_size: int = 32,
350
+ num_classes: int = 1000,
351
+ in_channels: int = 4,
352
+ **_,
353
+ ):
354
+ super().__init__()
355
+ self.repeat = repeat
356
+ self._legacy_kwargs = {
357
+ "depth": depth,
358
+ "hidden_size": hidden_size,
359
+ "patch_size": patch_size,
360
+ "num_heads": num_heads,
361
+ }
362
+ dit_cls = get_dit_transformer_class()
363
+ self.transformer = dit_cls(
364
+ **build_dit_config(
365
+ depth=depth,
366
+ hidden_size=hidden_size,
367
+ patch_size=patch_size,
368
+ num_heads=num_heads,
369
+ learn_sigma=learn_sigma,
370
+ class_dropout_prob=class_dropout_prob,
371
+ input_size=input_size,
372
+ num_classes=num_classes,
373
+ in_channels=in_channels,
374
+ )
375
+ )
376
+ self.in_channels = in_channels
377
+
378
+ def load_state_dict(self, state_dict, strict: bool = True):
379
+ remapped = remap_transformer_state_dict(state_dict, self._legacy_kwargs)
380
+ has_t_embedder = any("t_embedder" in key for key in state_dict)
381
+ if not has_t_embedder:
382
+ strict = False
383
+ out = super().load_state_dict(remapped, strict=strict)
384
+ if not has_t_embedder:
385
+ for name, param in self.named_parameters():
386
+ if "timestep_embedder" in name:
387
+ param.data.zero_()
388
+ return out
389
+
390
+ def forward(self, x, y, *args, **kwargs):
391
+ hidden_states = self.transformer.pos_embed(x)
392
+ for t in torch.arange(1, 0, -1 / self.repeat).tolist():
393
+ timestep = torch.full([x.shape[0]], int(t * 1000), device=x.device, dtype=torch.long)
394
+ for block in self.transformer.transformer_blocks:
395
+ hidden_states = block(
396
+ hidden_states,
397
+ attention_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ timestep=timestep,
401
+ cross_attention_kwargs=None,
402
+ class_labels=y,
403
+ )
404
+
405
+ conditioning = self.transformer.transformer_blocks[0].norm1.emb(
406
+ torch.zeros(x.shape[0], device=x.device, dtype=torch.long),
407
+ y,
408
+ hidden_dtype=hidden_states.dtype,
409
+ )
410
+ shift, scale = self.transformer.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
411
+ hidden_states = self.transformer.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
412
+ hidden_states = self.transformer.proj_out_2(hidden_states)
413
+
414
+ height = width = int(hidden_states.shape[1] ** 0.5)
415
+ hidden_states = hidden_states.reshape(
416
+ shape=(
417
+ -1,
418
+ height,
419
+ width,
420
+ self.transformer.patch_size,
421
+ self.transformer.patch_size,
422
+ self.transformer.out_channels,
423
+ )
424
+ )
425
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
426
+ output = hidden_states.reshape(
427
+ shape=(-1, self.transformer.out_channels, height * self.transformer.patch_size, width * self.transformer.patch_size)
428
+ )
429
+ return split_output_channels(output, self.in_channels)
430
+
431
+
432
+ class AFMGenerator2DModel(Generator, ModelMixin, ConfigMixin):
433
+ config_name = "config.json"
434
+
435
+ @register_to_config
436
+ def __init__(
437
+ self,
438
+ model_type: str = "AFM-XL/2",
439
+ architecture: str = "standard",
440
+ repeat: int = 1,
441
+ use_t_src: bool = False,
442
+ use_t_tgt: bool = False,
443
+ depth: int = 28,
444
+ hidden_size: int = 1152,
445
+ patch_size: int = 2,
446
+ num_heads: int = 16,
447
+ learn_sigma: bool = False,
448
+ class_dropout_prob: float = 0.0,
449
+ input_size: int = 32,
450
+ num_classes: int = 1000,
451
+ in_channels: int = 4,
452
+ pred_type: str = "x",
453
+ num_inference_steps: int = 1,
454
+ ) -> None:
455
+ if architecture == "deep":
456
+ raise ValueError("Use AFMGeneratorDeep2DModel for deep AFM checkpoints.")
457
+ Generator.__init__(
458
+ self,
459
+ use_t_src=use_t_src,
460
+ use_t_tgt=use_t_tgt,
461
+ depth=depth,
462
+ hidden_size=hidden_size,
463
+ patch_size=patch_size,
464
+ num_heads=num_heads,
465
+ learn_sigma=learn_sigma,
466
+ class_dropout_prob=class_dropout_prob,
467
+ input_size=input_size,
468
+ num_classes=num_classes,
469
+ in_channels=in_channels,
470
+ )
471
+
472
+
473
+ class AFMGeneratorDeep2DModel(GeneratorDeep, ModelMixin, ConfigMixin):
474
+ config_name = "config.json"
475
+
476
+ @register_to_config
477
+ def __init__(
478
+ self,
479
+ model_type: str = "AFM-XL/2",
480
+ architecture: str = "deep",
481
+ repeat: int = 2,
482
+ use_t_src: bool = False,
483
+ use_t_tgt: bool = False,
484
+ depth: int = 28,
485
+ hidden_size: int = 1152,
486
+ patch_size: int = 2,
487
+ num_heads: int = 16,
488
+ learn_sigma: bool = False,
489
+ class_dropout_prob: float = 0.0,
490
+ input_size: int = 32,
491
+ num_classes: int = 1000,
492
+ in_channels: int = 4,
493
+ pred_type: str = "x",
494
+ num_inference_steps: int = 1,
495
+ ) -> None:
496
+ GeneratorDeep.__init__(
497
+ self,
498
+ repeat=repeat,
499
+ depth=depth,
500
+ hidden_size=hidden_size,
501
+ patch_size=patch_size,
502
+ num_heads=num_heads,
503
+ learn_sigma=learn_sigma,
504
+ class_dropout_prob=class_dropout_prob,
505
+ input_size=input_size,
506
+ num_classes=num_classes,
507
+ in_channels=in_channels,
508
+ )
509
+
510
+
511
+ __all__ = ["AFMGenerator2DModel", "AFMGeneratorDeep2DModel"]