BiliSakura commited on
Commit
ed2880b
·
verified ·
1 Parent(s): 95790e3

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ LightningDit-XL-1-256/demo.png filter=lfs diff=lfs merge=lfs -text
LightningDit-XL-1-256/README.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LightningDiT-XL/1-256 (ImageNet)
2
+
3
+ Converted from [`hustvl/lightningdit-xl-imagenet256-800ep`](https://huggingface.co/hustvl/lightningdit-xl-imagenet256-800ep) with VA-VAE [`REPA-E/vavae-hf`](https://huggingface.co/REPA-E/vavae-hf).
4
+
5
+ Uses built-in [`FlowMatchHeunDiscreteScheduler`](https://huggingface.co/docs/diffusers/api/schedulers/flow_match_heun_discrete) (`shift=0.3`, 2nd-order Heun). Swap other [`KarrasDiffusionSchedulers`](https://huggingface.co/docs/diffusers/api/schedulers/overview) at inference time.
6
+
7
+ ```python
8
+ import torch
9
+ from diffusers import DiffusionPipeline
10
+
11
+ pipe = DiffusionPipeline.from_pretrained(
12
+ "path/to/LightningDit-XL-1-256",
13
+ trust_remote_code=True,
14
+ torch_dtype=torch.bfloat16,
15
+ ).to("cuda")
16
+
17
+ class_id = pipe.get_label_ids("golden retriever")[0]
18
+ image = pipe(
19
+ class_labels=class_id,
20
+ num_inference_steps=250,
21
+ guidance_scale=6.7,
22
+ cfg_interval_start=0.125,
23
+ timestep_shift=0.3,
24
+ generator=torch.Generator(device="cuda").manual_seed(0),
25
+ ).images[0]
26
+ ```
27
+
28
+ Patch size 1 (`LightningDiT-XL/1`) on 256×256 ImageNet latents (16×16 tokens).
29
+
30
+ Latent denormalization is applied automatically from VAE `latents_mean` / `latents_std` before decode.
LightningDit-XL-1-256/demo.png ADDED

Git LFS Details

  • SHA256: 0b84788f8348c4e437912d2d739f7b8168b2601ac666e808b5fd74526914f892
  • Pointer size: 131 Bytes
  • Size of remote file: 130 kB
LightningDit-XL-1-256/model_index.json ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "LightningDiTPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "scheduler": [
8
+ "diffusers",
9
+ "FlowMatchHeunDiscreteScheduler"
10
+ ],
11
+ "vae": [
12
+ "diffusers",
13
+ "AutoencoderKL"
14
+ ],
15
+ "transformer": [
16
+ "transformer_lightningdit",
17
+ "LightningDiTTransformer2DModel"
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, devil's 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's 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": "carpenter's 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, jeweler's 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, pj's, 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, carpenter's plane, woodworking plane",
747
+ "727": "planetarium",
748
+ "728": "plastic bag",
749
+ "729": "plate rack",
750
+ "730": "plow, plough",
751
+ "731": "plunger, plumber's 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": "potter's 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, spider's 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 lady's 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
+ }
LightningDit-XL-1-256/pipeline.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Hub custom pipeline for class-conditional LightningDiT image generation.
16
+
17
+ Load with native Hugging Face diffusers via ``DiffusionPipeline.from_pretrained`` and
18
+ ``trust_remote_code=True``.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import inspect
24
+ from typing import Any, Dict, List, Optional, Tuple, Union
25
+
26
+ import torch
27
+
28
+ from diffusers.image_processor import VaeImageProcessor
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
30
+ from diffusers.schedulers import KarrasDiffusionSchedulers
31
+ from diffusers.utils import replace_example_docstring
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+
34
+ EXAMPLE_DOC_STRING = """
35
+ Examples:
36
+ ```py
37
+ >>> from pathlib import Path
38
+ >>> import torch
39
+ >>> from diffusers import DiffusionPipeline
40
+
41
+ >>> model_dir = Path("BiliSakura/LightningDiT-diffusers/LightningDit-XL-1-256")
42
+ >>> pipe = DiffusionPipeline.from_pretrained(
43
+ ... str(model_dir),
44
+ ... local_files_only=True,
45
+ ... custom_pipeline=str(model_dir / "pipeline.py"),
46
+ ... trust_remote_code=True,
47
+ ... torch_dtype=torch.bfloat16,
48
+ ... ).to("cuda")
49
+
50
+ >>> class_id = pipe.get_label_ids("golden retriever")[0]
51
+ >>> image = pipe(
52
+ ... class_labels=class_id,
53
+ ... num_inference_steps=250,
54
+ ... guidance_scale=6.7,
55
+ ... cfg_interval_start=0.125,
56
+ ... generator=torch.Generator(device="cuda").manual_seed(0),
57
+ ... ).images[0]
58
+ ```
59
+ """
60
+
61
+
62
+ def _uses_explicit_next_timestep_scheduler(scheduler: KarrasDiffusionSchedulers) -> bool:
63
+ """True for LightningDiTFlowMatchScheduler (explicit t, t_next); False for built-in FlowMatch schedulers."""
64
+ try:
65
+ return "next_timestep" in inspect.signature(scheduler.step).parameters
66
+ except (TypeError, ValueError):
67
+ return False
68
+
69
+
70
+ class LightningDiTPipeline(DiffusionPipeline):
71
+ r"""
72
+ Pipeline for class-conditional image generation with [LightningDiT](https://github.com/hustvl/LightningDiT).
73
+
74
+ Uses VA-VAE latents and flow-matching velocity prediction. The bundled checkpoint defaults to
75
+ [`FlowMatchHeunDiscreteScheduler`] with `shift=0.3` (2nd-order Heun). Flow time passed to the
76
+ transformer is `1 - sigma` (`t=0` noise, `t=1` data). Latents are denormalized from VAE
77
+ `latents_mean` / `latents_std` before decode.
78
+
79
+ Recommended settings for `LightningDiT-XL/1` ImageNet-256 (800 epochs), matching official inference:
80
+
81
+ - `num_inference_steps=250`
82
+ - `guidance_scale=6.7`
83
+ - `cfg_interval_start=0.125`
84
+ - `cfg_channels=3`
85
+ - `timestep_shift=0.3` (only when the scheduler supports `set_shift`; otherwise set `shift` in
86
+ `scheduler/scheduler_config.json`)
87
+
88
+ Parameters:
89
+ transformer ([`LightningDiTTransformer2DModel`]):
90
+ LightningDiT transformer predicting flow-matching velocity in latent space.
91
+ scheduler ([`FlowMatchHeunDiscreteScheduler`]):
92
+ Flow-matching scheduler. Other [`KarrasDiffusionSchedulers`] may be swapped at load time.
93
+ vae ([`AutoencoderKL`]):
94
+ VA-VAE used to decode latents to pixels.
95
+ id2label (`dict[int, str]`, *optional*):
96
+ ImageNet class id to English label mapping. Values may contain comma-separated synonyms.
97
+ """
98
+
99
+ model_cpu_offload_seq = "transformer->vae"
100
+
101
+ def __init__(
102
+ self,
103
+ transformer,
104
+ vae,
105
+ scheduler,
106
+ id2label=None,
107
+ null_class_id=None,
108
+ ):
109
+ super().__init__()
110
+ self.register_modules(transformer=transformer, vae=vae, scheduler=scheduler)
111
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
112
+
113
+ if null_class_id is None:
114
+ null_class_id = int(getattr(self.transformer.config, "num_classes", 1000))
115
+ self.register_to_config(null_class_id=int(null_class_id))
116
+
117
+ self._id2label = self._normalize_id2label(id2label)
118
+ self.labels = self._build_label2id(self._id2label)
119
+
120
+ @property
121
+ def vae_scale_factor(self) -> int:
122
+ block_out_channels = getattr(self.vae.config, "block_out_channels", None)
123
+ if block_out_channels:
124
+ return int(2 ** (len(block_out_channels) - 1))
125
+ downsample_ratio = getattr(self.vae.config, "downsample_ratio", None)
126
+ if downsample_ratio is not None:
127
+ return int(downsample_ratio)
128
+ return 16
129
+
130
+ @staticmethod
131
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
132
+ if not id2label:
133
+ return {}
134
+ return {int(key): value for key, value in id2label.items()}
135
+
136
+ @staticmethod
137
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
138
+ label2id: Dict[str, int] = {}
139
+ for class_id, value in id2label.items():
140
+ for synonym in value.split(","):
141
+ synonym = synonym.strip()
142
+ if synonym:
143
+ label2id[synonym] = int(class_id)
144
+ return dict(sorted(label2id.items()))
145
+
146
+ @property
147
+ def id2label(self) -> Dict[int, str]:
148
+ return self._id2label
149
+
150
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
151
+ r"""Map English ImageNet labels to class ids."""
152
+ labels = [label] if isinstance(label, str) else label
153
+ if not self.labels:
154
+ raise ValueError("No id2label mapping is available in this checkpoint.")
155
+ missing = [item for item in labels if item not in self.labels]
156
+ if missing:
157
+ preview = ", ".join(list(self.labels.keys())[:8])
158
+ raise ValueError(f"Unknown labels: {missing}. Example valid labels: {preview}, ...")
159
+ return [self.labels[item] for item in labels]
160
+
161
+ def _normalize_class_labels(
162
+ self,
163
+ class_labels: Union[int, str, List[Union[int, str]], torch.Tensor],
164
+ ) -> torch.LongTensor:
165
+ if isinstance(class_labels, torch.Tensor):
166
+ return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
167
+ if isinstance(class_labels, int):
168
+ class_label_ids = [class_labels]
169
+ elif isinstance(class_labels, str):
170
+ class_label_ids = self.get_label_ids(class_labels)
171
+ elif class_labels and isinstance(class_labels[0], str):
172
+ class_label_ids = self.get_label_ids(class_labels) # type: ignore[arg-type]
173
+ else:
174
+ class_label_ids = [int(class_id) for class_id in class_labels] # type: ignore[union-attr]
175
+ return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
176
+
177
+ def _default_image_size(self) -> int:
178
+ return int(self.transformer.config.input_size) * self.vae_scale_factor
179
+
180
+ def check_inputs(
181
+ self,
182
+ height: int,
183
+ width: int,
184
+ num_inference_steps: int,
185
+ output_type: str,
186
+ ) -> None:
187
+ if num_inference_steps < 1:
188
+ raise ValueError("num_inference_steps must be >= 1.")
189
+ if output_type not in {"pil", "np", "pt", "latent"}:
190
+ raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
191
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
192
+ raise ValueError(
193
+ f"height and width must be divisible by the VAE downsample factor {self.vae_scale_factor}."
194
+ )
195
+ latent_height = height // self.vae_scale_factor
196
+ latent_width = width // self.vae_scale_factor
197
+ expected_size = int(self.transformer.config.input_size)
198
+ patch_size = int(self.transformer.config.patch_size)
199
+ if latent_height != expected_size or latent_width != expected_size:
200
+ raise ValueError(
201
+ f"Requested latent size {(latent_height, latent_width)} does not match transformer "
202
+ f"input_size={expected_size}. Use height=width={self._default_image_size()}."
203
+ )
204
+ if latent_height % patch_size != 0 or latent_width % patch_size != 0:
205
+ raise ValueError("Latent height and width must be divisible by transformer patch_size.")
206
+
207
+ @staticmethod
208
+ def prepare_extra_step_kwargs(
209
+ scheduler: KarrasDiffusionSchedulers,
210
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
211
+ ) -> Dict[str, Any]:
212
+ extra_step_kwargs: Dict[str, Any] = {}
213
+ if "generator" in inspect.signature(scheduler.step).parameters:
214
+ extra_step_kwargs["generator"] = generator
215
+ return extra_step_kwargs
216
+
217
+ @staticmethod
218
+ def _flow_time_from_sigma_timestep(timestep: torch.Tensor, num_train_timesteps: int) -> torch.Tensor:
219
+ """Map FlowMatch scheduler timestep (sigma * N) to LightningDiT flow time in [0, 1]."""
220
+ return 1.0 - timestep.to(dtype=torch.float32) / float(num_train_timesteps)
221
+
222
+ @staticmethod
223
+ def _apply_cfg(
224
+ model_output: torch.Tensor,
225
+ guidance_scale: float,
226
+ guidance_active: bool,
227
+ cfg_channels: int,
228
+ ) -> torch.Tensor:
229
+ if guidance_scale <= 1.0 or not guidance_active:
230
+ return model_output
231
+ eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:]
232
+ cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0)
233
+ guided_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
234
+ if rest.numel() == 0:
235
+ return guided_eps
236
+ return torch.cat([guided_eps, rest[: cond_eps.shape[0]]], dim=1)
237
+
238
+ def _resolve_latent_stats(
239
+ self,
240
+ latent_mean: Optional[torch.Tensor],
241
+ latent_std: Optional[torch.Tensor],
242
+ device: torch.device,
243
+ dtype: torch.dtype,
244
+ ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
245
+ if latent_mean is not None and latent_std is not None:
246
+ return latent_mean, latent_std
247
+ if self.vae is None:
248
+ return None, None
249
+ mean = getattr(self.vae.config, "latents_mean", None)
250
+ std = getattr(self.vae.config, "latents_std", None)
251
+ if mean is None or std is None:
252
+ return None, None
253
+ mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1)
254
+ std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1)
255
+ return mean_tensor, std_tensor
256
+
257
+ @staticmethod
258
+ def _denormalize_latents(
259
+ latents: torch.Tensor,
260
+ latent_mean: torch.Tensor,
261
+ latent_std: torch.Tensor,
262
+ latent_multiplier: float,
263
+ ) -> torch.Tensor:
264
+ return (latents * latent_std) / latent_multiplier + latent_mean
265
+
266
+ def decode_latents(self, latents: torch.Tensor, output_type: str = "pil"):
267
+ if output_type == "latent":
268
+ return latents
269
+ vae_dtype = next(self.vae.parameters()).dtype
270
+ latents = latents.to(dtype=vae_dtype)
271
+ scaling_factor = getattr(self.vae.config, "scaling_factor", None)
272
+ if scaling_factor not in (None, 0):
273
+ latents = latents / scaling_factor
274
+ image = self.vae.decode(latents).sample
275
+ if output_type == "pt":
276
+ return image
277
+ return self.image_processor.postprocess(image, output_type=output_type)
278
+
279
+ def _configure_scheduler(self, num_inference_steps: int, device: torch.device, timestep_shift: float):
280
+ if hasattr(self.scheduler, "set_shift"):
281
+ self.scheduler.set_shift(float(timestep_shift))
282
+ if _uses_explicit_next_timestep_scheduler(self.scheduler):
283
+ return self.scheduler.set_timesteps(
284
+ num_inference_steps,
285
+ device=device,
286
+ timestep_shift=float(timestep_shift),
287
+ )
288
+ if getattr(self.scheduler.config, "stochastic_sampling", False):
289
+ raise ValueError(
290
+ "LightningDiT expects deterministic FlowMatch scheduler stepping "
291
+ "(scheduler.config.stochastic_sampling=False)."
292
+ )
293
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
294
+ return self.scheduler.timesteps
295
+
296
+ def _guidance_active(
297
+ self,
298
+ flow_time: float,
299
+ guidance_interval: Tuple[float, float],
300
+ cfg_interval_start: float,
301
+ ) -> bool:
302
+ if flow_time < float(cfg_interval_start):
303
+ return False
304
+ return guidance_interval[0] <= flow_time <= guidance_interval[1]
305
+
306
+ @torch.no_grad()
307
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
308
+ def __call__(
309
+ self,
310
+ class_labels: Union[int, str, List[Union[int, str]], torch.Tensor],
311
+ height: Optional[int] = None,
312
+ width: Optional[int] = None,
313
+ num_inference_steps: int = 250,
314
+ guidance_scale: float = 6.7,
315
+ guidance_interval: Tuple[float, float] = (0.0, 1.0),
316
+ cfg_interval_start: float = 0.125,
317
+ timestep_shift: Optional[float] = None,
318
+ cfg_channels: int = 3,
319
+ latent_mean: Optional[torch.Tensor] = None,
320
+ latent_std: Optional[torch.Tensor] = None,
321
+ latent_multiplier: float = 1.0,
322
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
323
+ output_type: str = "pil",
324
+ return_dict: bool = True,
325
+ ) -> Union[ImagePipelineOutput, Tuple]:
326
+ r"""
327
+ Generate class-conditional images at the transformer's native latent resolution.
328
+
329
+ Args:
330
+ class_labels (`int`, `str`, `list[int]`, `list[str]`, or `torch.Tensor`):
331
+ ImageNet class indices or human-readable English label strings (comma-separated synonyms
332
+ in `id2label` are supported).
333
+ height (`int`, *optional*):
334
+ Output image height in pixels. Defaults to `input_size * vae_scale_factor` (256 for XL/1-256).
335
+ width (`int`, *optional*):
336
+ Output image width in pixels. Defaults to the same value as `height`.
337
+ num_inference_steps (`int`, defaults to `250`):
338
+ Number of flow-matching steps. With [`FlowMatchHeunDiscreteScheduler`], each step may use
339
+ two model evaluations (2nd-order Heun).
340
+ guidance_scale (`float`, defaults to `6.7`):
341
+ Classifier-free guidance scale on the first `cfg_channels` latent channels. CFG is active when
342
+ `guidance_scale > 1.0` and flow time is at least `cfg_interval_start`.
343
+ guidance_interval (`tuple[float, float]`, defaults to `(0.0, 1.0)`):
344
+ Flow-time interval `[low, high]` where CFG is allowed (in addition to `cfg_interval_start`).
345
+ cfg_interval_start (`float`, defaults to `0.125`):
346
+ Minimum flow time before CFG is applied (official LightningDiT XL/1 setting).
347
+ timestep_shift (`float`, *optional*):
348
+ Timestep schedule shift. Defaults to `scheduler.config.shift`. Only applied at runtime if the
349
+ scheduler implements `set_shift` (e.g. [`FlowMatchEulerDiscreteScheduler`]); for
350
+ [`FlowMatchHeunDiscreteScheduler`], set `shift` in `scheduler_config.json` when loading.
351
+ cfg_channels (`int`, defaults to `3`):
352
+ Number of latent channels to apply CFG on.
353
+ latent_mean (`torch.Tensor`, *optional*):
354
+ Per-channel latent mean for denormalization before VAE decode. Read from the VAE config when omitted.
355
+ latent_std (`torch.Tensor`, *optional*):
356
+ Per-channel latent std for denormalization before VAE decode. Read from the VAE config when omitted.
357
+ latent_multiplier (`float`, defaults to `1.0`):
358
+ Divisor applied with `latent_std` during denormalization (`latents * std / multiplier + mean`).
359
+ generator (`torch.Generator`, *optional*):
360
+ RNG for reproducible noise initialization (and scheduler stochastic paths if enabled).
361
+ output_type (`str`, defaults to `"pil"`):
362
+ `"pil"`, `"np"`, `"pt"`, or `"latent"`.
363
+ return_dict (`bool`, defaults to `True`):
364
+ Return [`~pipelines.pipeline_utils.ImagePipelineOutput`] if `True`, else a `(images,)` tuple.
365
+
366
+ Examples:
367
+ <!-- this section is replaced by replace_example_docstring -->
368
+
369
+ Returns:
370
+ [`~pipelines.pipeline_utils.ImagePipelineOutput`] or `tuple`:
371
+ Generated images.
372
+ """
373
+ default_size = self._default_image_size()
374
+ height = int(height or default_size)
375
+ width = int(width or default_size)
376
+ self.check_inputs(height, width, num_inference_steps, output_type)
377
+
378
+ device = self._execution_device
379
+ model_dtype = next(self.transformer.parameters()).dtype
380
+ class_labels_tensor = self._normalize_class_labels(class_labels)
381
+ batch_size = class_labels_tensor.numel()
382
+ null_labels = torch.full_like(class_labels_tensor, int(self.config.null_class_id))
383
+
384
+ if timestep_shift is None:
385
+ timestep_shift = float(getattr(self.scheduler.config, "shift", 0.3))
386
+
387
+ schedule = self._configure_scheduler(num_inference_steps, device, timestep_shift)
388
+ num_train_timesteps = int(self.scheduler.config.num_train_timesteps)
389
+ use_builtin_flow_match = not _uses_explicit_next_timestep_scheduler(self.scheduler)
390
+ extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator) if use_builtin_flow_match else {}
391
+
392
+ latents = randn_tensor(
393
+ (
394
+ batch_size,
395
+ int(self.transformer.config.in_channels),
396
+ height // self.vae_scale_factor,
397
+ width // self.vae_scale_factor,
398
+ ),
399
+ generator=generator,
400
+ device=device,
401
+ dtype=model_dtype,
402
+ )
403
+
404
+ if use_builtin_flow_match:
405
+ for timestep in self.progress_bar(schedule):
406
+ flow_time = float(self._flow_time_from_sigma_timestep(timestep, num_train_timesteps))
407
+ guidance_active = self._guidance_active(flow_time, guidance_interval, cfg_interval_start)
408
+ do_cfg = guidance_scale > 1.0 and guidance_active
409
+
410
+ if do_cfg:
411
+ model_input = torch.cat([latents, latents], dim=0)
412
+ labels = torch.cat([class_labels_tensor, null_labels], dim=0)
413
+ else:
414
+ model_input = latents
415
+ labels = class_labels_tensor
416
+
417
+ flow_time_batch = torch.full((labels.shape[0],), flow_time, device=device, dtype=model_dtype)
418
+ velocity = self.transformer(
419
+ hidden_states=model_input,
420
+ timestep=flow_time_batch,
421
+ class_labels=labels,
422
+ return_dict=True,
423
+ ).sample
424
+ velocity = self._apply_cfg(velocity, guidance_scale, guidance_active, cfg_channels)
425
+
426
+ # FlowMatchEuler/Heun: integrate in sigma space; model expects -velocity
427
+ latents = self.scheduler.step(
428
+ -velocity,
429
+ timestep,
430
+ latents,
431
+ **extra_step_kwargs,
432
+ ).prev_sample
433
+ else:
434
+ for index, timestep in enumerate(self.progress_bar(schedule[:-1])):
435
+ next_timestep = schedule[index + 1]
436
+ flow_time = float(timestep)
437
+ guidance_active = self._guidance_active(flow_time, guidance_interval, cfg_interval_start)
438
+
439
+ if guidance_scale > 1.0 and guidance_active:
440
+ model_input = torch.cat([latents, latents], dim=0)
441
+ labels = torch.cat([class_labels_tensor, null_labels], dim=0)
442
+ else:
443
+ model_input = latents
444
+ labels = class_labels_tensor
445
+
446
+ flow_time_batch = torch.full((labels.shape[0],), flow_time, device=device, dtype=model_dtype)
447
+ velocity = self.transformer(
448
+ hidden_states=model_input,
449
+ timestep=flow_time_batch,
450
+ class_labels=labels,
451
+ return_dict=True,
452
+ ).sample
453
+ velocity = self._apply_cfg(velocity, guidance_scale, guidance_active, cfg_channels)
454
+
455
+ latents = self.scheduler.step(
456
+ velocity, timestep[None], latents, next_timestep[None]
457
+ ).prev_sample
458
+
459
+ latent_mean, latent_std = self._resolve_latent_stats(
460
+ latent_mean, latent_std, device=latents.device, dtype=latents.dtype
461
+ )
462
+ if latent_mean is None or latent_std is None:
463
+ raise ValueError(
464
+ "LightningDiT requires latent denormalization before VAE decode. "
465
+ "Pass latent_mean and latent_std, or use a VAE config with latents_mean/latents_std."
466
+ )
467
+ latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier)
468
+
469
+ image = self.decode_latents(latents, output_type=output_type)
470
+ self.maybe_free_model_hooks()
471
+
472
+ if not return_dict:
473
+ return (image,)
474
+ return ImagePipelineOutput(images=image)
475
+
476
+
477
+ __all__ = ["LightningDiTPipeline"]
LightningDit-XL-1-256/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "FlowMatchHeunDiscreteScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "num_train_timesteps": 1000,
5
+ "shift": 0.3
6
+ }
LightningDit-XL-1-256/transformer/config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "LightningDiTTransformer2DModel",
3
+ "class_dropout_prob": 0.1,
4
+ "depth": 28,
5
+ "hidden_size": 1152,
6
+ "in_channels": 32,
7
+ "input_size": 16,
8
+ "learn_sigma": false,
9
+ "num_classes": 1000,
10
+ "num_heads": 16,
11
+ "patch_size": 1,
12
+ "qk_norm": false,
13
+ "use_rmsnorm": true,
14
+ "use_rope": true,
15
+ "use_swiglu": true,
16
+ "wo_shift": false
17
+ }
LightningDit-XL-1-256/transformer/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8128de9592a66a87948f37c72622086d7958e26f42c8853ca0619f7022e470ff
3
+ size 2701209152
LightningDit-XL-1-256/transformer/transformer_lightningdit.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Optional, Tuple, Union
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+ try:
16
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
17
+ from diffusers.models.modeling_utils import ModelMixin
18
+ from diffusers.utils import BaseOutput
19
+ except Exception: # pragma: no cover
20
+ class BaseOutput(dict):
21
+ def __post_init__(self):
22
+ self.update(self.__dict__)
23
+
24
+ class _Config(dict):
25
+ def __getattr__(self, key):
26
+ try:
27
+ return self[key]
28
+ except KeyError as error:
29
+ raise AttributeError(key) from error
30
+
31
+ class ConfigMixin:
32
+ config_name = "config.json"
33
+
34
+ class ModelMixin(nn.Module):
35
+ pass
36
+
37
+ def register_to_config(init):
38
+ def wrapper(self, *args, **kwargs):
39
+ import inspect
40
+
41
+ signature = inspect.signature(init)
42
+ bound = signature.bind(self, *args, **kwargs)
43
+ bound.apply_defaults()
44
+ self.config = _Config({key: value for key, value in bound.arguments.items() if key != "self"})
45
+ init(self, *args, **kwargs)
46
+
47
+ return wrapper
48
+
49
+
50
+ @dataclass
51
+ class LightningDiTTransformer2DModelOutput(BaseOutput):
52
+ sample: torch.FloatTensor
53
+
54
+
55
+ def _modulate(hidden_states: torch.Tensor, shift: Optional[torch.Tensor], scale: torch.Tensor) -> torch.Tensor:
56
+ if shift is None:
57
+ return hidden_states * (1 + scale.unsqueeze(1))
58
+ return hidden_states * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
59
+
60
+
61
+ class LightningDiTRMSNorm(nn.Module):
62
+ def __init__(self, dim: int, eps: float = 1e-6):
63
+ super().__init__()
64
+ self.eps = eps
65
+ self.weight = nn.Parameter(torch.ones(dim))
66
+
67
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
68
+ normalized = hidden_states * torch.rsqrt(hidden_states.pow(2).mean(-1, keepdim=True) + self.eps)
69
+ return (normalized.float() * self.weight).type_as(hidden_states)
70
+
71
+
72
+ def _rotate_half(hidden_states: torch.Tensor) -> torch.Tensor:
73
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-1], -1, 2)
74
+ x1, x2 = hidden_states.unbind(dim=-1)
75
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
76
+
77
+
78
+ def _broadcat(tensors, dim=-1):
79
+ num_tensors = len(tensors)
80
+ shape_lens = {len(tensor.shape) for tensor in tensors}
81
+ if len(shape_lens) != 1:
82
+ raise ValueError("tensors must all have the same number of dimensions")
83
+ shape_len = shape_lens.pop()
84
+ dim = (dim + shape_len) if dim < 0 else dim
85
+ dims = list(zip(*[list(tensor.shape) for tensor in tensors]))
86
+ expandable_dims = [(index, values) for index, values in enumerate(dims) if index != dim]
87
+ max_dims = [(index, max(values)) for index, values in expandable_dims]
88
+ expanded_dims = [(index, (size,) * num_tensors) for index, size in max_dims]
89
+ expanded_dims.insert(dim, (dim, dims[dim]))
90
+ expandable_shapes = list(zip(*[shape for _, shape in expanded_dims]))
91
+ return torch.cat([tensor.expand(*shape) for tensor, shape in zip(tensors, expandable_shapes)], dim=dim)
92
+
93
+
94
+ class LightningDiTRotaryEmbeddingFast(nn.Module):
95
+ """2D RoPE matching hustvl/LightningDiT VisionRotaryEmbeddingFast."""
96
+
97
+ def __init__(self, dim: int, pt_seq_len: int = 16, theta: int = 10000):
98
+ super().__init__()
99
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
100
+ positions = torch.arange(pt_seq_len, dtype=torch.float32) / float(pt_seq_len) * float(pt_seq_len)
101
+ freqs = torch.einsum("..., f -> ... f", positions, freqs)
102
+ freqs = freqs.repeat_interleave(2, dim=-1)
103
+ freqs = _broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
104
+ self.register_buffer("freqs_cos", freqs.cos().contiguous().view(-1, freqs.shape[-1]))
105
+ self.register_buffer("freqs_sin", freqs.sin().contiguous().view(-1, freqs.shape[-1]))
106
+
107
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
108
+ return hidden_states * self.freqs_cos + _rotate_half(hidden_states) * self.freqs_sin
109
+
110
+
111
+ class LightningDiTPatchEmbed(nn.Module):
112
+ def __init__(self, input_size: int, patch_size: int, in_channels: int, hidden_size: int):
113
+ super().__init__()
114
+ self.input_size = input_size
115
+ self.patch_size = (patch_size, patch_size)
116
+ self.num_patches = (input_size // patch_size) ** 2
117
+ self.proj = nn.Conv2d(in_channels, hidden_size, kernel_size=patch_size, stride=patch_size, bias=True)
118
+
119
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
120
+ hidden_states = self.proj(hidden_states)
121
+ return hidden_states.flatten(2).transpose(1, 2)
122
+
123
+
124
+ class LightningDiTTimestepEmbedder(nn.Module):
125
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256):
126
+ super().__init__()
127
+ self.frequency_embedding_size = frequency_embedding_size
128
+ self.mlp = nn.Sequential(
129
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
130
+ nn.SiLU(),
131
+ nn.Linear(hidden_size, hidden_size, bias=True),
132
+ )
133
+
134
+ @staticmethod
135
+ def get_timestep_embedding(timesteps: torch.Tensor, embedding_dim: int, max_period: int = 10000):
136
+ half = embedding_dim // 2
137
+ exponent = -math.log(max_period) * torch.arange(half, dtype=torch.float32, device=timesteps.device) / half
138
+ freqs = torch.exp(exponent)
139
+ args = timesteps.float()[:, None] * freqs[None]
140
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
141
+ if embedding_dim % 2:
142
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
143
+ return embedding
144
+
145
+ def forward(self, timesteps: torch.Tensor) -> torch.Tensor:
146
+ timestep_freq = self.get_timestep_embedding(timesteps, self.frequency_embedding_size).to(timesteps.dtype)
147
+ return self.mlp(timestep_freq)
148
+
149
+
150
+ class LightningDiTLabelEmbedder(nn.Module):
151
+ def __init__(self, num_classes: int, hidden_size: int, dropout_prob: float):
152
+ super().__init__()
153
+ use_cfg_embedding = dropout_prob > 0
154
+ self.embedding_table = nn.Embedding(num_classes + int(use_cfg_embedding), hidden_size)
155
+ self.num_classes = num_classes
156
+ self.dropout_prob = dropout_prob
157
+
158
+ def token_drop(self, class_labels: torch.Tensor, force_drop_ids: Optional[torch.Tensor] = None) -> torch.Tensor:
159
+ if force_drop_ids is None:
160
+ drop_ids = torch.rand(class_labels.shape[0], device=class_labels.device) < self.dropout_prob
161
+ else:
162
+ drop_ids = force_drop_ids == 1
163
+ return torch.where(drop_ids, self.num_classes, class_labels)
164
+
165
+ def forward(
166
+ self,
167
+ class_labels: torch.LongTensor,
168
+ train: bool = False,
169
+ force_drop_ids: Optional[torch.Tensor] = None,
170
+ ) -> torch.Tensor:
171
+ use_dropout = self.dropout_prob > 0
172
+ if (train and use_dropout) or (force_drop_ids is not None):
173
+ class_labels = self.token_drop(class_labels, force_drop_ids)
174
+ return self.embedding_table(class_labels)
175
+
176
+
177
+ class LightningDiTAttention(nn.Module):
178
+ def __init__(
179
+ self,
180
+ hidden_size: int,
181
+ num_heads: int = 8,
182
+ qk_norm: bool = False,
183
+ use_rmsnorm: bool = False,
184
+ ):
185
+ super().__init__()
186
+ if hidden_size % num_heads != 0:
187
+ raise ValueError("hidden_size must be divisible by num_heads")
188
+ self.num_heads = num_heads
189
+ self.head_dim = hidden_size // num_heads
190
+ norm_layer = LightningDiTRMSNorm if use_rmsnorm else nn.LayerNorm
191
+ self.qkv = nn.Linear(hidden_size, hidden_size * 3, bias=True)
192
+ self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
193
+ self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
194
+ self.proj = nn.Linear(hidden_size, hidden_size)
195
+ self.proj_drop = nn.Dropout(0.0)
196
+
197
+ def forward(self, hidden_states: torch.Tensor, rope: Optional[nn.Module] = None) -> torch.Tensor:
198
+ batch_size, seq_len, _ = hidden_states.shape
199
+ qkv = self.qkv(hidden_states).reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
200
+ query, key, value = qkv.unbind(0)
201
+ query = self.q_norm(query)
202
+ key = self.k_norm(key)
203
+ if rope is not None:
204
+ query = rope(query)
205
+ key = rope(key)
206
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0)
207
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, seq_len, -1)
208
+ return self.proj_drop(self.proj(hidden_states))
209
+
210
+
211
+ class LightningDiTSwiGLUFFN(nn.Module):
212
+ def __init__(self, in_features: int, hidden_features: int):
213
+ super().__init__()
214
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=True)
215
+ self.w3 = nn.Linear(hidden_features, in_features, bias=True)
216
+
217
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
218
+ x1, x2 = self.w12(hidden_states).chunk(2, dim=-1)
219
+ return self.w3(F.silu(x1) * x2)
220
+
221
+
222
+ class LightningDiTBlock(nn.Module):
223
+ def __init__(
224
+ self,
225
+ hidden_size: int,
226
+ num_heads: int,
227
+ mlp_ratio: float = 4.0,
228
+ qk_norm: bool = False,
229
+ use_swiglu: bool = False,
230
+ use_rmsnorm: bool = False,
231
+ wo_shift: bool = False,
232
+ ):
233
+ super().__init__()
234
+ self.wo_shift = wo_shift
235
+ if use_rmsnorm:
236
+ self.norm1 = LightningDiTRMSNorm(hidden_size)
237
+ self.norm2 = LightningDiTRMSNorm(hidden_size)
238
+ else:
239
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
240
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
241
+ self.attn = LightningDiTAttention(hidden_size, num_heads=num_heads, qk_norm=qk_norm, use_rmsnorm=use_rmsnorm)
242
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
243
+ if use_swiglu:
244
+ self.mlp = LightningDiTSwiGLUFFN(hidden_size, int(2 / 3 * mlp_hidden_dim))
245
+ else:
246
+ self.mlp = nn.Sequential(
247
+ nn.Linear(hidden_size, mlp_hidden_dim),
248
+ nn.GELU(approximate="tanh"),
249
+ nn.Linear(mlp_hidden_dim, hidden_size),
250
+ )
251
+ output_dim = 4 * hidden_size if wo_shift else 6 * hidden_size
252
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, output_dim, bias=True))
253
+
254
+ def forward(self, hidden_states: torch.Tensor, conditioning: torch.Tensor, rope=None) -> torch.Tensor:
255
+ if self.wo_shift:
256
+ scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(conditioning).chunk(4, dim=1)
257
+ shift_msa = shift_mlp = None
258
+ else:
259
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(conditioning).chunk(
260
+ 6, dim=1
261
+ )
262
+ hidden_states = hidden_states + gate_msa.unsqueeze(1) * self.attn(
263
+ _modulate(self.norm1(hidden_states), shift_msa, scale_msa), rope=rope
264
+ )
265
+ mlp_input = _modulate(self.norm2(hidden_states), shift_mlp, scale_mlp)
266
+ hidden_states = hidden_states + gate_mlp.unsqueeze(1) * self.mlp(mlp_input)
267
+ return hidden_states
268
+
269
+
270
+ class LightningDiTFinalLayer(nn.Module):
271
+ def __init__(self, hidden_size: int, patch_size: int, out_channels: int, use_rmsnorm: bool = False):
272
+ super().__init__()
273
+ if use_rmsnorm:
274
+ self.norm_final = LightningDiTRMSNorm(hidden_size)
275
+ else:
276
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
277
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
278
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
279
+
280
+ def forward(self, hidden_states: torch.Tensor, conditioning: torch.Tensor) -> torch.Tensor:
281
+ shift, scale = self.adaLN_modulation(conditioning).chunk(2, dim=1)
282
+ hidden_states = _modulate(self.norm_final(hidden_states), shift, scale)
283
+ return self.linear(hidden_states)
284
+
285
+
286
+ def _get_2d_sincos_pos_embed(embed_dim: int, grid_size: int) -> np.ndarray:
287
+ grid_h = np.arange(grid_size, dtype=np.float32)
288
+ grid_w = np.arange(grid_size, dtype=np.float32)
289
+ grid = np.meshgrid(grid_w, grid_h)
290
+ grid = np.stack(grid, axis=0).reshape(2, 1, grid_size, grid_size)
291
+
292
+ def get_1d_sincos(axis_embed_dim: int, positions: np.ndarray) -> np.ndarray:
293
+ omega = np.arange(axis_embed_dim // 2, dtype=np.float64)
294
+ omega = 1.0 / 10000 ** (omega / (axis_embed_dim / 2))
295
+ out = np.einsum("m,d->md", positions.reshape(-1), omega)
296
+ return np.concatenate([np.sin(out), np.cos(out)], axis=1)
297
+
298
+ emb_h = get_1d_sincos(embed_dim // 2, grid[0])
299
+ emb_w = get_1d_sincos(embed_dim // 2, grid[1])
300
+ return np.concatenate([emb_h, emb_w], axis=1)
301
+
302
+
303
+ class LightningDiTTransformer2DModel(ModelMixin, ConfigMixin):
304
+ """
305
+ LightningDiT transformer for class-conditional latent diffusion (flow matching).
306
+
307
+ Predicts velocity on fixed-resolution latent grids. Compatible with original LightningDiT checkpoints.
308
+ """
309
+
310
+ config_name = "config.json"
311
+
312
+ @register_to_config
313
+ def __init__(
314
+ self,
315
+ input_size: int = 16,
316
+ patch_size: int = 1,
317
+ in_channels: int = 32,
318
+ hidden_size: int = 1152,
319
+ depth: int = 28,
320
+ num_heads: int = 16,
321
+ mlp_ratio: float = 4.0,
322
+ class_dropout_prob: float = 0.1,
323
+ num_classes: int = 1000,
324
+ learn_sigma: bool = False,
325
+ qk_norm: bool = False,
326
+ use_swiglu: bool = False,
327
+ use_rope: bool = False,
328
+ use_rmsnorm: bool = False,
329
+ wo_shift: bool = False,
330
+ use_checkpoint: bool = False,
331
+ ):
332
+ super().__init__()
333
+ self.learn_sigma = learn_sigma
334
+ self.in_channels = in_channels
335
+ self.out_channels = in_channels * 2 if learn_sigma else in_channels
336
+ self.patch_size = patch_size
337
+ self.num_heads = num_heads
338
+ self.use_rope = use_rope
339
+ self.use_rmsnorm = use_rmsnorm
340
+ self.use_checkpoint = use_checkpoint
341
+
342
+ self.x_embedder = LightningDiTPatchEmbed(input_size, patch_size, in_channels, hidden_size)
343
+ self.t_embedder = LightningDiTTimestepEmbedder(hidden_size)
344
+ self.y_embedder = LightningDiTLabelEmbedder(num_classes, hidden_size, class_dropout_prob)
345
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.x_embedder.num_patches, hidden_size), requires_grad=False)
346
+
347
+ if use_rope:
348
+ half_head_dim = hidden_size // num_heads // 2
349
+ hw_seq_len = input_size // patch_size
350
+ self.feat_rope = LightningDiTRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len)
351
+ else:
352
+ self.feat_rope = None
353
+
354
+ self.blocks = nn.ModuleList(
355
+ [
356
+ LightningDiTBlock(
357
+ hidden_size,
358
+ num_heads,
359
+ mlp_ratio=mlp_ratio,
360
+ qk_norm=qk_norm,
361
+ use_swiglu=use_swiglu,
362
+ use_rmsnorm=use_rmsnorm,
363
+ wo_shift=wo_shift,
364
+ )
365
+ for _ in range(depth)
366
+ ]
367
+ )
368
+ self.final_layer = LightningDiTFinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm)
369
+ self.initialize_weights()
370
+
371
+ def initialize_weights(self):
372
+ def _basic_init(module):
373
+ if isinstance(module, nn.Linear):
374
+ nn.init.xavier_uniform_(module.weight)
375
+ if module.bias is not None:
376
+ nn.init.constant_(module.bias, 0)
377
+
378
+ self.apply(_basic_init)
379
+ pos_embed = _get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5))
380
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
381
+ weight = self.x_embedder.proj.weight.data
382
+ nn.init.xavier_uniform_(weight.view(weight.shape[0], -1))
383
+ nn.init.constant_(self.x_embedder.proj.bias, 0.0)
384
+ nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
385
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
386
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
387
+ for block in self.blocks:
388
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0.0)
389
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0.0)
390
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0.0)
391
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0.0)
392
+ nn.init.constant_(self.final_layer.linear.weight, 0.0)
393
+ nn.init.constant_(self.final_layer.linear.bias, 0.0)
394
+
395
+ def unpatchify(self, hidden_states: torch.Tensor) -> torch.Tensor:
396
+ channels = self.out_channels
397
+ patch = self.x_embedder.patch_size[0]
398
+ height = width = int(hidden_states.shape[1] ** 0.5)
399
+ hidden_states = hidden_states.reshape(hidden_states.shape[0], height, width, patch, patch, channels)
400
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
401
+ return hidden_states.reshape(hidden_states.shape[0], channels, height * patch, width * patch)
402
+
403
+ def forward(
404
+ self,
405
+ hidden_states: torch.Tensor,
406
+ timestep: Union[torch.Tensor, float],
407
+ class_labels: torch.LongTensor,
408
+ return_dict: bool = True,
409
+ force_drop_ids: Optional[torch.Tensor] = None,
410
+ ) -> Union[LightningDiTTransformer2DModelOutput, Tuple[torch.Tensor, ...]]:
411
+ if not torch.is_tensor(timestep):
412
+ timestep = torch.tensor([timestep], device=hidden_states.device, dtype=hidden_states.dtype)
413
+ timestep = timestep.to(device=hidden_states.device, dtype=hidden_states.dtype).flatten()
414
+ if timestep.numel() == 1:
415
+ timestep = timestep.repeat(hidden_states.shape[0])
416
+
417
+ hidden_states = self.x_embedder(hidden_states) + self.pos_embed
418
+ conditioning = self.t_embedder(timestep) + self.y_embedder(
419
+ class_labels, train=self.training, force_drop_ids=force_drop_ids
420
+ )
421
+
422
+ for block in self.blocks:
423
+ if self.use_checkpoint and self.training:
424
+ hidden_states = torch.utils.checkpoint.checkpoint(
425
+ block, hidden_states, conditioning, self.feat_rope, use_reentrant=False
426
+ )
427
+ else:
428
+ hidden_states = block(hidden_states, conditioning, self.feat_rope)
429
+
430
+ hidden_states = self.final_layer(hidden_states, conditioning)
431
+ hidden_states = self.unpatchify(hidden_states)
432
+ if self.learn_sigma:
433
+ hidden_states, _ = hidden_states.chunk(2, dim=1)
434
+
435
+ if not return_dict:
436
+ return (hidden_states,)
437
+ return LightningDiTTransformer2DModelOutput(sample=hidden_states)
438
+
439
+ @staticmethod
440
+ def apply_classifier_free_guidance(
441
+ model_output: torch.Tensor,
442
+ guidance_scale: float,
443
+ cfg_channels: int = 3,
444
+ ) -> torch.Tensor:
445
+ """Apply LightningDiT-style CFG on the first `cfg_channels` latent channels only."""
446
+ if guidance_scale <= 1.0:
447
+ return model_output
448
+ eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:]
449
+ cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0)
450
+ half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
451
+ if rest.numel() == 0:
452
+ return half_eps
453
+ cond_rest, _ = torch.chunk(rest, 2, dim=0)
454
+ return torch.cat([half_eps, cond_rest], dim=1)
LightningDit-XL-1-256/vae/config.json ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.33.0",
4
+ "act_fn": "silu",
5
+ "block_out_channels": [
6
+ 128,
7
+ 128,
8
+ 256,
9
+ 256,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D",
17
+ "AttnDownEncoderBlock2D"
18
+ ],
19
+ "force_upcast": true,
20
+ "in_channels": 3,
21
+ "latent_channels": 32,
22
+ "latents_mean": [
23
+ 0.5984622836112976,
24
+ -0.49917176365852356,
25
+ 0.6440029144287109,
26
+ -0.09708389639854431,
27
+ -1.1909630298614502,
28
+ -1.4331622123718262,
29
+ 0.468532919883728,
30
+ 0.6259251832962036,
31
+ 0.6319502592086792,
32
+ -0.48967328667640686,
33
+ -0.7445162534713745,
34
+ 1.159562349319458,
35
+ 0.8456217050552368,
36
+ 0.5008237957954407,
37
+ 0.22926893830299377,
38
+ 0.4753556549549103,
39
+ -0.4378734230995178,
40
+ 0.831696093082428,
41
+ -0.07508569955825806,
42
+ 0.30632293224334717,
43
+ 0.4664529263973236,
44
+ -0.09140774607658386,
45
+ -0.8271016478538513,
46
+ 0.0780751183629036,
47
+ 1.4150785207748413,
48
+ 1.379238486289978,
49
+ 0.2695842981338501,
50
+ -0.757322371006012,
51
+ 0.2812993824481964,
52
+ -0.3091999292373657,
53
+ 0.07785388082265854,
54
+ 0.3496664762496948
55
+ ],
56
+ "latents_std": [
57
+ 3.8461380004882812,
58
+ 4.269914627075195,
59
+ 3.576843738555908,
60
+ 3.5911104679107666,
61
+ 3.6230573654174805,
62
+ 3.48101806640625,
63
+ 3.307461738586426,
64
+ 3.509265422821045,
65
+ 3.554058074951172,
66
+ 3.606724500656128,
67
+ 3.7057900428771973,
68
+ 3.6314077377319336,
69
+ 3.6295316219329834,
70
+ 3.62050199508667,
71
+ 3.259028196334839,
72
+ 3.186753034591675,
73
+ 3.8258144855499268,
74
+ 3.5999391078948975,
75
+ 3.296635150909424,
76
+ 3.2261290550231934,
77
+ 3.2191944122314453,
78
+ 3.105457305908203,
79
+ 3.580496072769165,
80
+ 4.356914043426514,
81
+ 3.3085410594940186,
82
+ 3.207587480545044,
83
+ 4.515047073364258,
84
+ 3.486992359161377,
85
+ 3.0415804386138916,
86
+ 3.486884832382202,
87
+ 4.431032657623291,
88
+ 4.088115692138672
89
+ ],
90
+ "layers_per_block": 2,
91
+ "mid_block_add_attention": true,
92
+ "norm_num_groups": 32,
93
+ "out_channels": 3,
94
+ "sample_size": 32,
95
+ "scaling_factor": null,
96
+ "shift_factor": null,
97
+ "up_block_types": [
98
+ "AttnUpDecoderBlock2D",
99
+ "UpDecoderBlock2D",
100
+ "UpDecoderBlock2D",
101
+ "UpDecoderBlock2D",
102
+ "UpDecoderBlock2D"
103
+ ],
104
+ "use_post_quant_conv": true,
105
+ "use_quant_conv": true
106
+ }
LightningDit-XL-1-256/vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8b32dcc4e6697c809be51c1b5b8eef9f451fb5dc66eaeafdb1864145af4619d
3
+ size 279382964
README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: diffusers
3
+ pipeline_tag: unconditional-image-generation
4
+ tags:
5
+ - diffusers
6
+ - lightningdit
7
+ - image-generation
8
+ - class-conditional
9
+ - imagenet
10
+ - flow-matching
11
+ license: mit
12
+ inference: true
13
+ widget:
14
+ - output:
15
+ url: LightningDit-XL-1-256/demo.png
16
+ language:
17
+ - en
18
+ ---
19
+
20
+ # LightningDiT-diffusers
21
+
22
+ Diffusers-ready checkpoints for **LightningDiT** (VA-VAE–aligned latent diffusion with flow matching), converted from [`hustvl/lightningdit-xl-imagenet256-800ep`](https://huggingface.co/hustvl/lightningdit-xl-imagenet256-800ep) for local/offline use.
23
+
24
+ This root folder is a model collection that contains:
25
+
26
+ - `LightningDit-XL-1-256`
27
+
28
+ Each subfolder is a self-contained Diffusers model repo with:
29
+
30
+ - `pipeline.py` (`LightningDiTPipeline`)
31
+ - `transformer/transformer_lightningdit.py` and weights
32
+ - `scheduler/scheduler_config.json` (`FlowMatchHeunDiscreteScheduler`, `shift=0.3`)
33
+ - `vae/` ([`REPA-E/vavae-hf`](https://huggingface.co/REPA-E/vavae-hf))
34
+
35
+ Each variant embeds English `id2label` in `model_index.json`, so class labels can be passed as ImageNet ids or English synonym strings.
36
+
37
+ ## Demo
38
+
39
+ ![LightningDiT-XL-1-256 demo](LightningDit-XL-1-256/demo.png)
40
+
41
+ Class-conditional sample (ImageNet class **207**, golden retriever), `LightningDiT-XL/1` at 256×256, 250 steps, CFG 6.7, `cfg_interval_start=0.125`, `timestep_shift=0.3`, seed 0.
42
+
43
+ ## Model Paths
44
+
45
+ | Model | Resolution | Local path |
46
+ | --- | ---: | --- |
47
+ | LightningDiT-XL/1 | 256×256 | `./LightningDit-XL-1-256` |
48
+
49
+ ## Inference
50
+
51
+ ```python
52
+ import torch
53
+ from diffusers import DiffusionPipeline
54
+
55
+ pipe = DiffusionPipeline.from_pretrained(
56
+ "./LightningDit-XL-1-256",
57
+ trust_remote_code=True,
58
+ torch_dtype=torch.bfloat16,
59
+ ).to("cuda")
60
+
61
+ class_id = pipe.get_label_ids("golden retriever")[0]
62
+ image = pipe(
63
+ class_labels=class_id,
64
+ num_inference_steps=250,
65
+ guidance_scale=6.7,
66
+ cfg_interval_start=0.125,
67
+ timestep_shift=0.3,
68
+ generator=torch.Generator(device="cuda").manual_seed(0),
69
+ ).images[0]
70
+ ```
71
+
72
+ ## Citation
73
+
74
+ ```bibtex
75
+ @inproceedings{yao2025reconstruction,
76
+ title={Reconstruction vs. Generation: Taming Optimization Dilemma in Latent Diffusion Models},
77
+ author={Yao, Jingfeng and Yang, Bin and Wang, Xinggang},
78
+ booktitle={CVPR},
79
+ year={2025}
80
+ }
81
+ ```