BiliSakura commited on
Commit
3d7e8b9
·
verified ·
1 Parent(s): ee9e2f6

Upload folder using huggingface_hub

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