BiliSakura commited on
Commit
561f88a
·
verified ·
1 Parent(s): c7623dc

Upload folder using huggingface_hub

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
+ FiTv1-XL-2-256/demo.png filter=lfs diff=lfs merge=lfs -text
FiTv1-XL-2-256/README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: diffusers
4
+ pipeline_tag: unconditional-image-generation
5
+ tags:
6
+ - diffusers
7
+ - fit
8
+ - image-generation
9
+ - class-conditional
10
+ - imagenet
11
+ inference: true
12
+ ---
13
+
14
+ # FiTv1-XL-2-256
15
+
16
+ Self-contained Diffusers checkpoint for **FiTv1-XL/2**, converted from [`InfImagine/FiT`](https://huggingface.co/InfImagine/FiT).
17
+
18
+ Each subfolder is a self-contained Diffusers model repo with:
19
+
20
+ - `model_index.json` (includes ImageNet `id2label`)
21
+ - `pipeline.py` (custom `FiTPipeline`)
22
+ - `transformer/fit_transformer_2d.py` and weights
23
+ - `scheduler/scheduling_fit_improved.py` and `scheduler_config.json`
24
+ - `vae/diffusion_pytorch_model.safetensors`
25
+
26
+ ## Recommended inference (256×256)
27
+
28
+ | Setting | Value |
29
+ | --- | --- |
30
+ | Resolution | 256×256 |
31
+ | Sampler | improved diffusion (DDPM respaced) |
32
+ | Steps | 250 |
33
+ | CFG scale | 1.5 |
34
+ | Dtype | `bfloat16` (recommended on Ampere+) |
35
+ | VAE | `stabilityai/sd-vae-ft-ema` (bundled under `vae/`) |
36
+
37
+ ```python
38
+ from pathlib import Path
39
+ import torch
40
+ from diffusers import DiffusionPipeline
41
+
42
+ model_dir = Path("./FiTv1-XL-2-256").resolve()
43
+ pipe = DiffusionPipeline.from_pretrained(
44
+ str(model_dir),
45
+ local_files_only=True,
46
+ custom_pipeline=str(model_dir / "pipeline.py"),
47
+ trust_remote_code=True,
48
+ torch_dtype=torch.bfloat16,
49
+ )
50
+ pipe.to("cuda")
51
+
52
+ print(pipe.id2label[207])
53
+ print(pipe.get_label_ids("golden retriever"))
54
+
55
+ generator = torch.Generator(device="cuda").manual_seed(42)
56
+ image = pipe(
57
+ class_labels="golden retriever",
58
+ height=256,
59
+ width=256,
60
+ num_inference_steps=250,
61
+ guidance_scale=1.5,
62
+ generator=generator,
63
+ ).images[0]
64
+ image.save("demo.png")
65
+ ```
FiTv1-XL-2-256/demo.png ADDED

Git LFS Details

  • SHA256: 5e38af76d6f83632058c958517367d351c4a4c8d6d03eb65e337f38ebc977f68
  • Pointer size: 131 Bytes
  • Size of remote file: 127 kB
FiTv1-XL-2-256/model_index.json ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "FiTPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "transformer": [
8
+ "fit_transformer_2d",
9
+ "FiTTransformer2DModel"
10
+ ],
11
+ "vae": [
12
+ "diffusers",
13
+ "AutoencoderKL"
14
+ ],
15
+ "scheduler": [
16
+ "diffusers",
17
+ "DDPMScheduler"
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
+ }
FiTv1-XL-2-256/pipeline.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: FiTPipeline.
2
+ Load with native Hugging Face diffusers and trust_remote_code=True.
3
+ """
4
+
5
+ import importlib
6
+ import inspect
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Tuple, Union
11
+
12
+ import diffusers.schedulers as diffusers_schedulers
13
+ import torch
14
+ from huggingface_hub import snapshot_download
15
+
16
+ from diffusers import AutoencoderKL
17
+ from diffusers.image_processor import VaeImageProcessor
18
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
19
+ from diffusers.schedulers import KarrasDiffusionSchedulers
20
+ from diffusers.utils.torch_utils import randn_tensor
21
+
22
+ # Local component classes are loaded dynamically in from_pretrained.
23
+
24
+ DEFAULT_NATIVE_RESOLUTION = 256
25
+
26
+ EXAMPLE_DOC_STRING = """
27
+ Examples:
28
+ ```py
29
+ >>> from pathlib import Path
30
+ >>> import torch
31
+ >>> from diffusers import DiffusionPipeline, DDIMScheduler
32
+
33
+ >>> model_dir = Path("./FiTv1-XL-2-256").resolve()
34
+ >>> pipe = DiffusionPipeline.from_pretrained(
35
+ ... str(model_dir),
36
+ ... local_files_only=True,
37
+ ... custom_pipeline=str(model_dir / "pipeline.py"),
38
+ ... trust_remote_code=True,
39
+ ... torch_dtype=torch.float32,
40
+ ... )
41
+ >>> pipe.to("cuda")
42
+ >>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
43
+
44
+ >>> print(pipe.id2label[207])
45
+ >>> print(pipe.get_label_ids("golden retriever"))
46
+
47
+ >>> generator = torch.Generator(device="cuda").manual_seed(42)
48
+ >>> image = pipe(
49
+ ... class_labels="golden retriever",
50
+ ... height=256,
51
+ ... width=256,
52
+ ... num_inference_steps=250,
53
+ ... guidance_scale=1.5,
54
+ ... generator=generator,
55
+ ... ).images[0]
56
+ >>> image.save("demo.png")
57
+ ```
58
+ """
59
+
60
+
61
+ class FiTPipeline(DiffusionPipeline):
62
+ r"""
63
+ Pipeline for class-conditional image generation with FiTv1 (DDPM sampling).
64
+ """
65
+
66
+ model_cpu_offload_seq = "transformer->vae"
67
+ _optional_components = ["vae"]
68
+
69
+ def __init__(
70
+ self,
71
+ transformer: Any,
72
+ scheduler: KarrasDiffusionSchedulers,
73
+ vae: Any = None,
74
+ id2label: Optional[Dict[Union[int, str], str]] = None,
75
+ null_class_id: Optional[int] = None,
76
+ ):
77
+ super().__init__()
78
+ self.register_modules(transformer=transformer, scheduler=scheduler, vae=vae)
79
+ self.image_processor = VaeImageProcessor()
80
+
81
+ if null_class_id is None:
82
+ null_class_id = int(getattr(self.transformer.config, "num_classes", 1000))
83
+ self.register_to_config(null_class_id=int(null_class_id))
84
+
85
+ self._id2label = self._normalize_id2label(id2label)
86
+ self.labels = self._build_label2id(self._id2label)
87
+ self._labels_loaded_from_model_index = bool(self._id2label)
88
+
89
+ @property
90
+ def vae_scale_factor(self) -> int:
91
+ if self.vae is None:
92
+ return 8
93
+ block_out_channels = getattr(self.vae.config, "block_out_channels", None)
94
+ if block_out_channels:
95
+ return int(2 ** (len(block_out_channels) - 1))
96
+ return 8
97
+
98
+ @classmethod
99
+ def from_pretrained(cls, pretrained_model_name_or_path=None, subfolder=None, **kwargs):
100
+ """Load a self-contained variant folder locally or from the Hub."""
101
+ repo_root = Path(__file__).resolve().parent
102
+
103
+ if pretrained_model_name_or_path in (None, "", "."):
104
+ variant = repo_root
105
+ elif (
106
+ isinstance(pretrained_model_name_or_path, str)
107
+ and "/" in pretrained_model_name_or_path
108
+ and not Path(pretrained_model_name_or_path).exists()
109
+ ):
110
+ hub_kwargs = dict(kwargs.pop("hub_kwargs", {}))
111
+ if subfolder:
112
+ hub_kwargs.setdefault("allow_patterns", [f"{subfolder}/**"])
113
+ cache_dir = snapshot_download(pretrained_model_name_or_path, **hub_kwargs)
114
+ variant = Path(cache_dir) / subfolder if subfolder else Path(cache_dir)
115
+ else:
116
+ variant = Path(pretrained_model_name_or_path)
117
+ if not variant.is_absolute():
118
+ candidate = (Path.cwd() / variant).resolve()
119
+ variant = candidate if candidate.exists() else (repo_root / variant).resolve()
120
+ if subfolder:
121
+ variant = variant / subfolder
122
+
123
+ id2label_override = kwargs.pop("id2label", None)
124
+ null_class_id_override = kwargs.pop("null_class_id", None)
125
+ model_kwargs = dict(kwargs)
126
+ inserted: List[str] = []
127
+
128
+ def _load_component(folder: str, module_name: str, class_name: str):
129
+ comp_dir = variant / folder
130
+ module_path = comp_dir / f"{module_name}.py"
131
+ has_weights = (comp_dir / "config.json").exists() or (comp_dir / "scheduler_config.json").exists()
132
+ if not module_path.exists() or not has_weights:
133
+ return None
134
+
135
+ comp_path = str(comp_dir)
136
+ if comp_path not in sys.path:
137
+ sys.path.insert(0, comp_path)
138
+ inserted.append(comp_path)
139
+
140
+ module = importlib.import_module(module_name)
141
+ component_cls = getattr(module, class_name)
142
+ return component_cls.from_pretrained(str(comp_dir), **model_kwargs)
143
+
144
+ try:
145
+ transformer = _load_component("transformer", "fit_transformer_2d", "FiTTransformer2DModel")
146
+ if transformer is None:
147
+ raise ValueError(f"No loadable transformer found under {variant}")
148
+
149
+ scheduler = cls._load_scheduler_from_variant(variant, model_kwargs)
150
+
151
+ vae = None
152
+ vae_dir = variant / "vae"
153
+ if vae_dir.exists() and (vae_dir / "config.json").exists():
154
+ vae = AutoencoderKL.from_pretrained(str(vae_dir), **model_kwargs)
155
+
156
+ id2label = id2label_override or cls._read_id2label_from_model_index(str(variant))
157
+ null_class_id = null_class_id_override if null_class_id_override is not None else cls._read_null_class_id(
158
+ str(variant)
159
+ )
160
+ pipe = cls(
161
+ transformer=transformer,
162
+ scheduler=scheduler,
163
+ vae=vae,
164
+ id2label=id2label,
165
+ null_class_id=null_class_id,
166
+ )
167
+ if hasattr(pipe, "register_to_config"):
168
+ pipe.register_to_config(_name_or_path=str(variant))
169
+ return pipe
170
+ finally:
171
+ for comp_path in inserted:
172
+ if comp_path in sys.path:
173
+ sys.path.remove(comp_path)
174
+
175
+ @classmethod
176
+ def _load_scheduler_from_variant(cls, variant: Path, model_kwargs: Dict[str, object]) -> KarrasDiffusionSchedulers:
177
+ scheduler_dir = variant / "scheduler"
178
+ config_path = scheduler_dir / "scheduler_config.json"
179
+ if not config_path.exists():
180
+ raise ValueError(f"No scheduler config found under {scheduler_dir}")
181
+
182
+ scheduler_entry = None
183
+ model_index_path = variant / "model_index.json"
184
+ if model_index_path.exists():
185
+ scheduler_entry = json.loads(model_index_path.read_text(encoding="utf-8")).get("scheduler")
186
+
187
+ if scheduler_entry is None:
188
+ class_name = json.loads(config_path.read_text(encoding="utf-8")).get("_class_name")
189
+ if not class_name:
190
+ raise ValueError(f"Missing `_class_name` in {config_path}")
191
+ scheduler_entry = ["diffusers", class_name]
192
+
193
+ if not isinstance(scheduler_entry, list) or len(scheduler_entry) != 2:
194
+ raise ValueError(f"Invalid scheduler entry in model_index.json: {scheduler_entry}")
195
+
196
+ library_name, class_name = scheduler_entry
197
+ if library_name != "diffusers":
198
+ raise ValueError(f"Unsupported scheduler library: {library_name}")
199
+
200
+ scheduler_cls = getattr(diffusers_schedulers, class_name)
201
+ return scheduler_cls.from_pretrained(str(scheduler_dir), **model_kwargs)
202
+
203
+ @staticmethod
204
+ def _prepare_model_output_for_scheduler(
205
+ model_out: torch.Tensor,
206
+ latent_channels: int,
207
+ scheduler: KarrasDiffusionSchedulers,
208
+ ) -> torch.Tensor:
209
+ if model_out.shape[1] != latent_channels * 2:
210
+ return model_out
211
+
212
+ variance_type = getattr(scheduler.config, "variance_type", None)
213
+ if scheduler.__class__.__name__ == "DDPMScheduler" and variance_type in ("learned", "learned_range"):
214
+ return model_out
215
+
216
+ model_output, _ = torch.split(model_out, latent_channels, dim=1)
217
+ return model_output
218
+
219
+ @staticmethod
220
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
221
+ if not id2label:
222
+ return {}
223
+ return {int(key): value for key, value in id2label.items()}
224
+
225
+ @staticmethod
226
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
227
+ if not variant_path:
228
+ return {}
229
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
230
+ if not model_index_path.exists():
231
+ return {}
232
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
233
+ id2label = raw.get("id2label")
234
+ if not isinstance(id2label, dict):
235
+ return {}
236
+ return {int(key): value for key, value in id2label.items()}
237
+
238
+ @staticmethod
239
+ def _read_null_class_id(variant_path: Optional[str]) -> Optional[int]:
240
+ if not variant_path:
241
+ return None
242
+ model_index_path = Path(variant_path).resolve() / "model_index.json"
243
+ if not model_index_path.exists():
244
+ return None
245
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
246
+ if "null_class_id" in raw:
247
+ return int(raw["null_class_id"])
248
+ return None
249
+
250
+ @staticmethod
251
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
252
+ label2id: Dict[str, int] = {}
253
+ for class_id, value in id2label.items():
254
+ for synonym in value.split(","):
255
+ synonym = synonym.strip()
256
+ if synonym:
257
+ label2id[synonym] = int(class_id)
258
+ return dict(sorted(label2id.items()))
259
+
260
+ @property
261
+ def id2label(self) -> Dict[int, str]:
262
+ self._ensure_labels_loaded()
263
+ return self._id2label
264
+
265
+ def _ensure_labels_loaded(self) -> None:
266
+ if self._labels_loaded_from_model_index:
267
+ return
268
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
269
+ if loaded:
270
+ self._id2label = loaded
271
+ self.labels = self._build_label2id(self._id2label)
272
+ self._labels_loaded_from_model_index = True
273
+
274
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
275
+ labels = [label] if isinstance(label, str) else label
276
+ self._ensure_labels_loaded()
277
+ if not self.labels:
278
+ raise ValueError("No id2label mapping is available in this checkpoint.")
279
+ missing = [item for item in labels if item not in self.labels]
280
+ if missing:
281
+ preview = ", ".join(list(self.labels.keys())[:8])
282
+ raise ValueError(f"Unknown labels: {missing}. Example valid labels: {preview}, ...")
283
+ return [self.labels[item] for item in labels]
284
+
285
+ def _normalize_class_labels(
286
+ self,
287
+ class_labels: Union[int, str, List[Union[int, str]], torch.Tensor],
288
+ ) -> List[int]:
289
+ if isinstance(class_labels, torch.Tensor):
290
+ class_labels = class_labels.detach().cpu().tolist()
291
+ if isinstance(class_labels, int):
292
+ return [class_labels]
293
+ if isinstance(class_labels, str):
294
+ return self.get_label_ids(class_labels)
295
+ if not class_labels:
296
+ raise ValueError("`class_labels` cannot be empty.")
297
+ if isinstance(class_labels[0], str):
298
+ return self.get_label_ids(class_labels) # type: ignore[arg-type]
299
+ return [int(class_id) for class_id in class_labels] # type: ignore[union-attr]
300
+
301
+ @staticmethod
302
+ def prepare_extra_step_kwargs(
303
+ scheduler: KarrasDiffusionSchedulers,
304
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
305
+ ) -> Dict[str, Any]:
306
+ kwargs: Dict[str, Any] = {}
307
+ step_params = set(inspect.signature(scheduler.step).parameters.keys())
308
+ if "generator" in step_params:
309
+ kwargs["generator"] = generator
310
+ return kwargs
311
+
312
+ @staticmethod
313
+ def _expand_timestep(timestep, batch_size: int, device: torch.device) -> torch.Tensor:
314
+ if not torch.is_tensor(timestep):
315
+ timestep = torch.tensor([timestep], dtype=torch.long, device=device)
316
+ elif timestep.ndim == 0:
317
+ timestep = timestep[None].to(device=device)
318
+ return timestep.expand(batch_size)
319
+
320
+ @staticmethod
321
+ def _prepare_grid_mask_size(
322
+ batch_size: int,
323
+ n_patch_h: int,
324
+ n_patch_w: int,
325
+ device: torch.device,
326
+ dtype: torch.dtype,
327
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
328
+ grid_h = torch.arange(n_patch_h, dtype=torch.long, device=device)
329
+ grid_w = torch.arange(n_patch_w, dtype=torch.long, device=device)
330
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy")
331
+ grid = torch.cat([grid[0].reshape(1, -1), grid[1].reshape(1, -1)], dim=0).repeat(batch_size, 1, 1)
332
+ mask = torch.ones(batch_size, n_patch_h * n_patch_w, device=device, dtype=dtype)
333
+ size = torch.tensor((n_patch_h, n_patch_w), device=device, dtype=torch.long).repeat(batch_size, 1)[:, None, :]
334
+ return grid, mask, size
335
+
336
+ @torch.inference_mode()
337
+ def __call__(
338
+ self,
339
+ class_labels: Union[int, str, List[Union[int, str]], torch.Tensor] = 207,
340
+ height: Optional[int] = None,
341
+ width: Optional[int] = None,
342
+ num_inference_steps: int = 250,
343
+ guidance_scale: float = 1.5,
344
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
345
+ latents: Optional[torch.Tensor] = None,
346
+ output_type: str = "pil",
347
+ return_dict: bool = True,
348
+ ) -> Union[ImagePipelineOutput, Tuple]:
349
+ class_labels_list = self._normalize_class_labels(class_labels)
350
+ batch_size = len(class_labels_list)
351
+ height = DEFAULT_NATIVE_RESOLUTION if height is None else int(height)
352
+ width = DEFAULT_NATIVE_RESOLUTION if width is None else int(width)
353
+
354
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
355
+ raise ValueError(
356
+ f"`height` and `width` must be divisible by {self.vae_scale_factor}, got ({height}, {width})."
357
+ )
358
+ if output_type not in {"pil", "np", "pt", "latent"}:
359
+ raise ValueError(f"Unsupported `output_type`: {output_type}")
360
+
361
+ device = self._execution_device
362
+ model_dtype = next(self.transformer.parameters()).dtype
363
+ latent_h = height // self.vae_scale_factor
364
+ latent_w = width // self.vae_scale_factor
365
+ patch_size = int(self.transformer.config.patch_size)
366
+ n_patch_h, n_patch_w = latent_h // patch_size, latent_w // patch_size
367
+ latent_channels = (patch_size**2) * int(self.transformer.in_channels)
368
+
369
+ extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator)
370
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
371
+
372
+ if latents is None:
373
+ latents = randn_tensor(
374
+ (batch_size, latent_channels, n_patch_h * n_patch_w),
375
+ generator=generator,
376
+ device=device,
377
+ dtype=model_dtype,
378
+ )
379
+ else:
380
+ latents = latents.to(device=device, dtype=model_dtype)
381
+ expected = (batch_size, latent_channels, n_patch_h * n_patch_w)
382
+ if tuple(latents.shape) != expected:
383
+ raise ValueError(f"Invalid `latents` shape: {tuple(latents.shape)}. Expected {expected}.")
384
+
385
+ grid, mask, size = self._prepare_grid_mask_size(batch_size, n_patch_h, n_patch_w, device, model_dtype)
386
+ class_labels_tensor = torch.tensor(class_labels_list, device=device, dtype=torch.long)
387
+
388
+ using_cfg = guidance_scale > 1.0
389
+ if using_cfg:
390
+ y_null = torch.full((batch_size,), int(self.config.null_class_id), device=device, dtype=torch.long)
391
+ y = torch.cat([class_labels_tensor, y_null], dim=0)
392
+ grid = torch.cat([grid, grid], dim=0)
393
+ mask = torch.cat([mask, mask], dim=0)
394
+ size = torch.cat([size, size], dim=0)
395
+
396
+ for timestep in self.progress_bar(self.scheduler.timesteps):
397
+ latent_model_input = latents
398
+ if using_cfg:
399
+ latent_model_input = torch.cat([latents, latents], dim=0)
400
+
401
+ timestep_tensor = self._expand_timestep(timestep, latent_model_input.shape[0], device)
402
+
403
+ if using_cfg:
404
+ model_out = self.transformer.forward_with_cfg(
405
+ latent_model_input,
406
+ timestep_tensor,
407
+ y=y,
408
+ grid=grid,
409
+ mask=mask,
410
+ size=size,
411
+ cfg_scale=guidance_scale,
412
+ )
413
+ model_out = model_out.chunk(2, dim=0)[0]
414
+ else:
415
+ model_out = self.transformer(
416
+ latents,
417
+ timestep_tensor,
418
+ y=class_labels_tensor,
419
+ grid=grid,
420
+ mask=mask,
421
+ size=size,
422
+ )
423
+
424
+ model_output = self._prepare_model_output_for_scheduler(model_out, latent_channels, self.scheduler)
425
+
426
+ latents = self.scheduler.step(model_output, timestep, latents, **extra_step_kwargs).prev_sample
427
+
428
+ latents = latents[..., : n_patch_h * n_patch_w]
429
+ latents = self.transformer.unpatchify(latents, (latent_h, latent_w))
430
+
431
+ if self.vae is not None:
432
+ vae_dtype = next(self.vae.parameters()).dtype
433
+ latents = latents.to(dtype=vae_dtype)
434
+ latents = self.vae.decode(latents / self.vae.config.scaling_factor).sample
435
+ image = self.image_processor.postprocess(latents, output_type=output_type)
436
+ elif output_type == "latent":
437
+ image = latents
438
+ else:
439
+ raise ValueError("Cannot decode latents without a VAE.")
440
+
441
+ self.maybe_free_model_hooks()
442
+ if not return_dict:
443
+ return (image,)
444
+ return ImagePipelineOutput(images=image)
445
+
446
+
447
+ __all__ = ["FiTPipeline"]
FiTv1-XL-2-256/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "DDPMScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "beta_end": 0.02,
5
+ "beta_schedule": "linear",
6
+ "beta_start": 0.0001,
7
+ "clip_sample": false,
8
+ "clip_sample_range": 1.0,
9
+ "num_train_timesteps": 1000,
10
+ "prediction_type": "epsilon",
11
+ "variance_type": "learned_range",
12
+ "timestep_spacing": "linspace",
13
+ "steps_offset": 0,
14
+ "trained_betas": null
15
+ }
FiTv1-XL-2-256/transformer/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "FiTTransformer2DModel",
3
+ "class_dropout_prob": 0.1,
4
+ "context_size": 256,
5
+ "depth": 28,
6
+ "hidden_size": 1152,
7
+ "in_channels": 4,
8
+ "learn_sigma": true,
9
+ "mlp_ratio": 4.0,
10
+ "num_classes": 1000,
11
+ "num_heads": 16,
12
+ "patch_size": 2,
13
+ "rel_pos_embed": "rope",
14
+ "use_swiglu": true,
15
+ "use_swiglu_large": true
16
+ }
FiTv1-XL-2-256/transformer/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e51188080ca2aefd5b1d2d6fe7abc7211663b2dd69049aefb6f40892337aa9e8
3
+ size 3294432464
FiTv1-XL-2-256/transformer/fit_transformer_2d.py ADDED
@@ -0,0 +1,993 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Self-contained FiT Hub module (generated by scripts/bundle_fit_hub_modules.py)."""
16
+
17
+ import torch
18
+ from torch import Tensor
19
+ from typing import List, Tuple
20
+ import torch.nn as nn
21
+ import math
22
+ from math import pi
23
+ from typing import Optional, Any, Union, Tuple
24
+ from torch import nn
25
+ from einops import rearrange, repeat
26
+ from functools import lru_cache
27
+ import numpy as np
28
+ import torch.nn.functional as F
29
+ from torch import nn, Tensor
30
+ from torch.jit import Final
31
+ from timm.layers.mlp import SwiGLU, Mlp
32
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
33
+ from functools import partial
34
+ from typing import Optional
35
+ from einops import rearrange
36
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
37
+ from diffusers.models.modeling_utils import ModelMixin
38
+
39
+ try:
40
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
41
+ from diffusers.models.modeling_utils import ModelMixin
42
+ except Exception: # pragma: no cover
43
+ class ConfigMixin:
44
+ def register_to_config(self, **kwargs):
45
+ if not hasattr(self, "_config"):
46
+ self._config = {}
47
+ self._config.update(kwargs)
48
+
49
+ @property
50
+ def config(self):
51
+ return self._config
52
+
53
+ def register_to_config(func):
54
+ return func
55
+
56
+ class ModelMixin(nn.Module):
57
+ pass
58
+
59
+ def modulate(x, shift, scale):
60
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
61
+
62
+
63
+ def get_parameter_dtype(parameter: torch.nn.Module):
64
+ try:
65
+ params = tuple(parameter.parameters())
66
+ if len(params) > 0:
67
+ return params[0].dtype
68
+
69
+ buffers = tuple(parameter.buffers())
70
+ if len(buffers) > 0:
71
+ return buffers[0].dtype
72
+
73
+ except StopIteration:
74
+ # For torch.nn.DataParallel compatibility in PyTorch 1.5
75
+
76
+ def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
77
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
78
+ return tuples
79
+
80
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
81
+ first_tuple = next(gen)
82
+ return first_tuple[1].dtype
83
+
84
+ def create_norm(norm_type: str, dim: int, eps: float = 1e-6):
85
+ if norm_type is None or norm_type == "":
86
+ return nn.Identity()
87
+ norm_type = norm_type.lower()
88
+
89
+ if norm_type == "w_layernorm":
90
+ return nn.LayerNorm(dim, eps=eps, bias=False)
91
+ elif norm_type == "layernorm":
92
+ return nn.LayerNorm(dim, eps=eps, elementwise_affine=False, bias=False)
93
+ elif norm_type == "w_rmsnorm":
94
+ return RMSNorm(dim, eps=eps)
95
+ elif norm_type == "rmsnorm":
96
+ return RMSNorm(dim, include_weight=False, eps=eps)
97
+ elif norm_type == "none":
98
+ return nn.Identity()
99
+ else:
100
+ raise NotImplementedError(f"Unknown norm_type: '{norm_type}'")
101
+
102
+
103
+ class RMSNorm(nn.Module):
104
+ def __init__(self, dim: int, include_weight: bool = True, eps: float = 1e-6):
105
+ super().__init__()
106
+ self.eps = eps
107
+ self.include_weight = include_weight
108
+ self.weight = nn.Parameter(torch.ones(dim)) if include_weight else None
109
+
110
+ def _norm(self, x: torch.Tensor):
111
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
112
+
113
+ def forward(self, x: torch.Tensor):
114
+ output = self._norm(x.float()).type_as(x)
115
+ if self.weight is not None:
116
+ return output * self.weight
117
+ return output
118
+
119
+ def reset_parameters(self):
120
+ if self.weight is not None:
121
+ torch.nn.init.ones_(self.weight)
122
+
123
+ # --------------------------------------------------------
124
+ # FiT: A Flexible Vision Transformer for Image Generation
125
+ #
126
+ # Based on the following repository
127
+ # https://github.com/lucidrains/rotary-embedding-torch
128
+ # https://github.com/jquesnelle/yarn/blob/HEAD/scaled_rope
129
+ # https://colab.research.google.com/drive/1VI2nhlyKvd5cw4-zHvAIk00cAVj2lCCC#scrollTo=b80b3f37
130
+ # --------------------------------------------------------
131
+
132
+
133
+
134
+ #################################################################################
135
+ # NTK Operations #
136
+ #################################################################################
137
+
138
+ def find_correction_factor(num_rotations, dim, base=10000, max_position_embeddings=2048):
139
+ return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations
140
+
141
+ def find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
142
+ low = math.floor(find_correction_factor(low_rot, dim, base, max_position_embeddings))
143
+ high = math.ceil(find_correction_factor(high_rot, dim, base, max_position_embeddings))
144
+ return max(low, 0), min(high, dim-1) #Clamp values just in case
145
+
146
+ def linear_ramp_mask(min, max, dim):
147
+ if min == max:
148
+ max += 0.001 #Prevent singularity
149
+
150
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
151
+ ramp_func = torch.clamp(linear_func, 0, 1)
152
+ return ramp_func
153
+
154
+ def find_newbase_ntk(dim, base=10000, scale=1):
155
+ # Base change formula
156
+ return base * scale ** (dim / (dim-2))
157
+
158
+ def get_mscale(scale=torch.Tensor):
159
+ # if scale <= 1:
160
+ # return 1.0
161
+ # return 0.1 * math.log(scale) + 1.0
162
+ return torch.where(scale <= 1., torch.tensor(1.0), 0.1 * torch.log(scale) + 1.0)
163
+
164
+ def get_proportion(L_test, L_train):
165
+ L_test = L_test * 2
166
+ return torch.where(torch.tensor(L_test/L_train) <= 1., torch.tensor(1.0), torch.sqrt(torch.log(torch.tensor(L_test))/torch.log(torch.tensor(L_train))))
167
+ # return torch.sqrt(torch.log(torch.tensor(L_test))/torch.log(torch.tensor(L_train)))
168
+
169
+
170
+
171
+ #################################################################################
172
+ # Rotate Q or K #
173
+ #################################################################################
174
+
175
+ def rotate_half(x):
176
+ x = rearrange(x, '... (d r) -> ... d r', r = 2)
177
+ x1, x2 = x.unbind(dim = -1)
178
+ x = torch.stack((-x2, x1), dim = -1)
179
+ return rearrange(x, '... d r -> ... (d r)')
180
+
181
+
182
+
183
+ #################################################################################
184
+ # Core Vision RoPE #
185
+ #################################################################################
186
+
187
+ class VisionRotaryEmbedding(nn.Module):
188
+ def __init__(
189
+ self,
190
+ head_dim: int, # embed dimension for each head
191
+ custom_freqs: str = 'normal',
192
+ theta: int = 10000,
193
+ online_rope: bool = False,
194
+ max_cached_len: int = 256,
195
+ max_pe_len_h: Optional[int] = None,
196
+ max_pe_len_w: Optional[int] = None,
197
+ decouple: bool = False,
198
+ ori_max_pe_len: Optional[int] = None,
199
+ ):
200
+ super().__init__()
201
+
202
+ dim = head_dim // 2
203
+ assert dim % 2 == 0 # accually, this is important
204
+ self.dim = dim
205
+ self.custom_freqs = custom_freqs.lower()
206
+ self.theta = theta
207
+ self.decouple = decouple
208
+ self.ori_max_pe_len = ori_max_pe_len
209
+
210
+ self.custom_freqs = custom_freqs.lower()
211
+ if not online_rope:
212
+ if self.custom_freqs == 'normal':
213
+ freqs_h = 1. / (theta ** (torch.arange(0, dim, 2).float() / dim))
214
+ freqs_w = 1. / (theta ** (torch.arange(0, dim, 2).float() / dim))
215
+ else:
216
+ if decouple:
217
+ freqs_h = self.get_1d_rope_freqs(theta, dim, max_pe_len_h, ori_max_pe_len)
218
+ freqs_w = self.get_1d_rope_freqs(theta, dim, max_pe_len_w, ori_max_pe_len)
219
+ else:
220
+ max_pe_len = max(max_pe_len_h, max_pe_len_w)
221
+ freqs_h = self.get_1d_rope_freqs(theta, dim, max_pe_len, ori_max_pe_len)
222
+ freqs_w = self.get_1d_rope_freqs(theta, dim, max_pe_len, ori_max_pe_len)
223
+
224
+ attn_factor = 1.0
225
+ scale = torch.clamp_min(torch.tensor(max(max_pe_len_h, max_pe_len_w)) / ori_max_pe_len, 1.0) # dynamic scale
226
+ self.mscale = get_mscale(scale).to(scale) * attn_factor # Get n-d magnitude scaling corrected for interpolation
227
+ self.proportion1 = get_proportion(max(max_pe_len_h, max_pe_len_w), ori_max_pe_len)
228
+ self.proportion2 = get_proportion(max_pe_len_h * max_pe_len_w, ori_max_pe_len ** 2)
229
+
230
+ self.register_buffer('freqs_h', freqs_h, persistent=False)
231
+ self.register_buffer('freqs_w', freqs_w, persistent=False)
232
+
233
+ freqs_h_cached = torch.einsum('..., f -> ... f', torch.arange(max_cached_len), self.freqs_h)
234
+ freqs_h_cached = repeat(freqs_h_cached, '... n -> ... (n r)', r = 2)
235
+ self.register_buffer('freqs_h_cached', freqs_h_cached, persistent=False)
236
+ freqs_w_cached = torch.einsum('..., f -> ... f', torch.arange(max_cached_len), self.freqs_w)
237
+ freqs_w_cached = repeat(freqs_w_cached, '... n -> ... (n r)', r = 2)
238
+ self.register_buffer('freqs_w_cached', freqs_w_cached, persistent=False)
239
+
240
+
241
+ def get_1d_rope_freqs(self, theta, dim, max_pe_len, ori_max_pe_len):
242
+ # scaling operations for extrapolation
243
+ assert isinstance(ori_max_pe_len, int)
244
+ # scale = max_pe_len / ori_max_pe_len
245
+ if not isinstance(max_pe_len, torch.Tensor):
246
+ max_pe_len = torch.tensor(max_pe_len)
247
+ scale = torch.clamp_min(max_pe_len / ori_max_pe_len, 1.0) # dynamic scale
248
+
249
+ if self.custom_freqs == 'linear': # equal to position interpolation
250
+ freqs = 1. / torch.einsum('..., f -> ... f', scale, theta ** (torch.arange(0, dim, 2).float() / dim))
251
+ elif self.custom_freqs == 'ntk-aware' or self.custom_freqs == 'ntk-aware-pro1' or self.custom_freqs == 'ntk-aware-pro2':
252
+ freqs = 1. / torch.pow(
253
+ find_newbase_ntk(dim, theta, scale).view(-1, 1),
254
+ (torch.arange(0, dim, 2).to(scale).float() / dim)
255
+ ).squeeze()
256
+ elif self.custom_freqs == 'ntk-by-parts':
257
+ #Interpolation constants found experimentally for LLaMA (might not be totally optimal though)
258
+ #Do not change unless there is a good reason for doing so!
259
+ beta_0 = 1.25
260
+ beta_1 = 0.75
261
+ gamma_0 = 16
262
+ gamma_1 = 2
263
+ ntk_factor = 1
264
+ extrapolation_factor = 1
265
+
266
+ #Three RoPE extrapolation/interpolation methods
267
+ freqs_base = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
268
+ freqs_linear = 1.0 / torch.einsum('..., f -> ... f', scale, (theta ** (torch.arange(0, dim, 2).to(scale).float() / dim)))
269
+ freqs_ntk = 1. / torch.pow(
270
+ find_newbase_ntk(dim, theta, scale).view(-1, 1),
271
+ (torch.arange(0, dim, 2).to(scale).float() / dim)
272
+ ).squeeze()
273
+
274
+ #Combine NTK and Linear
275
+ low, high = find_correction_range(beta_0, beta_1, dim, theta, ori_max_pe_len)
276
+ freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(scale)) * ntk_factor
277
+ freqs = freqs_linear * (1 - freqs_mask) + freqs_ntk * freqs_mask
278
+
279
+ #Combine Extrapolation and NTK and Linear
280
+ low, high = find_correction_range(gamma_0, gamma_1, dim, theta, ori_max_pe_len)
281
+ freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(scale)) * extrapolation_factor
282
+ freqs = freqs * (1 - freqs_mask) + freqs_base * freqs_mask
283
+
284
+ elif self.custom_freqs == 'yarn':
285
+ #Interpolation constants found experimentally for LLaMA (might not be totally optimal though)
286
+ #Do not change unless there is a good reason for doing so!
287
+ beta_fast = 32
288
+ beta_slow = 1
289
+ extrapolation_factor = 1
290
+
291
+ freqs_extrapolation = 1.0 / (theta ** (torch.arange(0, dim, 2).to(scale).float() / dim))
292
+ freqs_interpolation = 1.0 / torch.einsum('..., f -> ... f', scale, (theta ** (torch.arange(0, dim, 2).to(scale).float() / dim)))
293
+
294
+ low, high = find_correction_range(beta_fast, beta_slow, dim, theta, ori_max_pe_len)
295
+ freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(scale).float()) * extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
296
+ freqs = freqs_interpolation * (1 - freqs_mask) + freqs_extrapolation * freqs_mask
297
+ else:
298
+ raise ValueError(f'Unknown modality {self.custom_freqs}. Only support normal, linear, ntk-aware, ntk-by-parts, yarn!')
299
+ return freqs
300
+
301
+
302
+ def online_get_2d_rope_from_grid(self, grid, size):
303
+ '''
304
+ grid: (B, 2, N)
305
+ N = H * W
306
+ the first dimension represents width, and the second reprensents height
307
+ e.g., [0. 1. 2. 3. 0. 1. 2. 3. 0. 1. 2. 3.]
308
+ [0. 0. 0. 0. 1. 1. 1. 1. 2. 2. 2. 2.]
309
+ size: (B, 1, 2), h goes first and w goes last
310
+ '''
311
+ size = size.squeeze() # (B, 1, 2) -> (B, 2)
312
+ if self.decouple:
313
+ size_h = size[:, 0]
314
+ size_w = size[:, 1]
315
+ freqs_h = self.get_1d_rope_freqs(self.theta, self.dim, size_h, self.ori_max_pe_len)
316
+ freqs_w = self.get_1d_rope_freqs(self.theta, self.dim, size_w, self.ori_max_pe_len)
317
+ else:
318
+ size_max = torch.max(size[:, 0], size[:, 1])
319
+ freqs_h = self.get_1d_rope_freqs(self.theta, self.dim, size_max, self.ori_max_pe_len)
320
+ freqs_w = self.get_1d_rope_freqs(self.theta, self.dim, size_max, self.ori_max_pe_len)
321
+ freqs_w = grid[:, 0][..., None] * freqs_w[:, None, :]
322
+ freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2)
323
+
324
+ freqs_h = grid[:, 1][..., None] * freqs_h[:, None, :]
325
+ freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2)
326
+
327
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1) # (B, N, D)
328
+
329
+ if self.custom_freqs == 'yarn':
330
+ freqs_cos = freqs.cos() * self.mscale[:, None, None]
331
+ freqs_sin = freqs.sin() * self.mscale[:, None, None]
332
+ elif self.custom_freqs == 'ntk-aware-pro1':
333
+ freqs_cos = freqs.cos() * self.proportion1[:, None, None]
334
+ freqs_sin = freqs.sin() * self.proportion1[:, None, None]
335
+ elif self.custom_freqs == 'ntk-aware-pro2':
336
+ freqs_cos = freqs.cos() * self.proportion2[:, None, None]
337
+ freqs_sin = freqs.sin() * self.proportion2[:, None, None]
338
+ else:
339
+ freqs_cos = freqs.cos()
340
+ freqs_sin = freqs.sin()
341
+
342
+ return freqs_cos, freqs_sin
343
+
344
+ @lru_cache()
345
+ def get_2d_rope_from_grid(self, grid):
346
+ '''
347
+ grid: (B, 2, N)
348
+ N = H * W
349
+ the first dimension represents width, and the second reprensents height
350
+ e.g., [0. 1. 2. 3. 0. 1. 2. 3. 0. 1. 2. 3.]
351
+ [0. 0. 0. 0. 1. 1. 1. 1. 2. 2. 2. 2.]
352
+ '''
353
+ freqs_w = torch.einsum('..., f -> ... f', grid[:, 0], self.freqs_w)
354
+ freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2)
355
+
356
+ freqs_h = torch.einsum('..., f -> ... f', grid[:, 1], self.freqs_h)
357
+ freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2)
358
+
359
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1) # (B, N, D)
360
+
361
+ if self.custom_freqs == 'yarn':
362
+ freqs_cos = freqs.cos() * self.mscale
363
+ freqs_sin = freqs.sin() * self.mscale
364
+ elif self.custom_freqs == 'ntk-aware-pro1':
365
+ freqs_cos = freqs.cos() * self.proportion1
366
+ freqs_sin = freqs.sin() * self.proportion1
367
+ elif self.custom_freqs == 'ntk-aware-pro2':
368
+ freqs_cos = freqs.cos() * self.proportion2
369
+ freqs_sin = freqs.sin() * self.proportion2
370
+ else:
371
+ freqs_cos = freqs.cos()
372
+ freqs_sin = freqs.sin()
373
+
374
+ return freqs_cos, freqs_sin
375
+
376
+ @lru_cache()
377
+ def get_cached_2d_rope_from_grid(self, grid: torch.Tensor):
378
+ '''
379
+ grid: (B, 2, N)
380
+ N = H * W
381
+ the first dimension represents width, and the second reprensents height
382
+ e.g., [0. 1. 2. 3. 0. 1. 2. 3. 0. 1. 2. 3.]
383
+ [0. 0. 0. 0. 1. 1. 1. 1. 2. 2. 2. 2.]
384
+ '''
385
+ freqs_w, freqs_h = self.freqs_w_cached[grid[:, 0]], self.freqs_h_cached[grid[:, 1]]
386
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1) # (B, N, D)
387
+
388
+ if self.custom_freqs == 'yarn':
389
+ freqs_cos = freqs.cos() * self.mscale
390
+ freqs_sin = freqs.sin() * self.mscale
391
+ elif self.custom_freqs == 'ntk-aware-pro1':
392
+ freqs_cos = freqs.cos() * self.proportion1
393
+ freqs_sin = freqs.sin() * self.proportion1
394
+ elif self.custom_freqs == 'ntk-aware-pro2':
395
+ freqs_cos = freqs.cos() * self.proportion2
396
+ freqs_sin = freqs.sin() * self.proportion2
397
+ else:
398
+ freqs_cos = freqs.cos()
399
+ freqs_sin = freqs.sin()
400
+
401
+ return freqs_cos, freqs_sin
402
+
403
+ @lru_cache()
404
+ def get_cached_21d_rope_from_grid(self, grid: torch.Tensor): # for 3d rope formulation 2 !
405
+ '''
406
+ grid: (B, 3, N)
407
+ N = H * W * T
408
+ the first dimension represents width, and the second reprensents height, and the third reprensents time
409
+ e.g., [0. 1. 2. 3. 0. 1. 2. 3. 0. 1. 2. 3.]
410
+ [0. 0. 0. 0. 1. 1. 1. 1. 2. 2. 2. 2.]
411
+ [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
412
+ '''
413
+ freqs_w, freqs_h = self.freqs_w_cached[grid[:, 0]+grid[:, 2]], self.freqs_h_cached[grid[:, 1]+grid[:, 2]]
414
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1) # (B, N, D)
415
+
416
+ if self.custom_freqs == 'yarn':
417
+ freqs_cos = freqs.cos() * self.mscale
418
+ freqs_sin = freqs.sin() * self.mscale
419
+ elif self.custom_freqs == 'ntk-aware-pro1':
420
+ freqs_cos = freqs.cos() * self.proportion1
421
+ freqs_sin = freqs.sin() * self.proportion1
422
+ elif self.custom_freqs == 'ntk-aware-pro2':
423
+ freqs_cos = freqs.cos() * self.proportion2
424
+ freqs_sin = freqs.sin() * self.proportion2
425
+ else:
426
+ freqs_cos = freqs.cos()
427
+ freqs_sin = freqs.sin()
428
+
429
+ return freqs_cos, freqs_sin
430
+
431
+ def forward(self, x, grid):
432
+ '''
433
+ x: (B, n_head, N, D)
434
+ grid: (B, 2, N)
435
+ '''
436
+ # freqs_cos, freqs_sin = self.get_2d_rope_from_grid(grid)
437
+ # freqs_cos, freqs_sin = freqs_cos.unsqueeze(1), freqs_sin.unsqueeze(1)
438
+ # using cache to accelerate, this is the same with the above codes:
439
+ freqs_cos, freqs_sin = self.get_cached_2d_rope_from_grid(grid)
440
+ freqs_cos, freqs_sin = freqs_cos.unsqueeze(1), freqs_sin.unsqueeze(1)
441
+ return x * freqs_cos + rotate_half(x) * freqs_sin
442
+
443
+ #################################################################################
444
+ # Embedding Layers for Patches, Timesteps and Class Labels #
445
+ #################################################################################
446
+
447
+ class PatchEmbedder(nn.Module):
448
+ """
449
+ Embeds latent features into vector representations
450
+ """
451
+ def __init__(self,
452
+ input_dim,
453
+ embed_dim,
454
+ bias: bool = True,
455
+ norm_layer: Optional[Callable] = None,
456
+ ):
457
+ super().__init__()
458
+
459
+ self.proj = nn.Linear(input_dim, embed_dim, bias=bias)
460
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
461
+
462
+ def forward(self, x):
463
+ x = self.proj(x) # (B, L, patch_size ** 2 * C) -> (B, L, D)
464
+ x = self.norm(x)
465
+ return x
466
+
467
+ class TimestepEmbedder(nn.Module):
468
+ """
469
+ Embeds scalar timesteps into vector representations.
470
+ """
471
+ def __init__(self, hidden_size, frequency_embedding_size=256):
472
+ super().__init__()
473
+ self.mlp = nn.Sequential(
474
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
475
+ nn.SiLU(),
476
+ nn.Linear(hidden_size, hidden_size, bias=True),
477
+ )
478
+ self.frequency_embedding_size = frequency_embedding_size
479
+
480
+ @staticmethod
481
+ def timestep_embedding(t, dim, max_period=10000):
482
+ """
483
+ Create sinusoidal timestep embeddings.
484
+ :param t: a 1-D Tensor of N indices, one per batch element.
485
+ These may be fractional.
486
+ :param dim: the dimension of the output.
487
+ :param max_period: controls the minimum frequency of the embeddings.
488
+ :return: an (N, D) Tensor of positional embeddings.
489
+ """
490
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
491
+ half = dim // 2
492
+ freqs = torch.exp(
493
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
494
+ ).to(device=t.device)
495
+ args = t[:, None] * freqs[None]
496
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
497
+ if dim % 2:
498
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1]).to(device=t.device)], dim=-1)
499
+ return embedding.to(dtype=t.dtype)
500
+
501
+ def forward(self, t):
502
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
503
+ t_emb = self.mlp(t_freq)
504
+ return t_emb
505
+
506
+
507
+ class LabelEmbedder(nn.Module):
508
+ """
509
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
510
+ """
511
+ def __init__(self, num_classes, hidden_size, dropout_prob):
512
+ super().__init__()
513
+ use_cfg_embedding = dropout_prob > 0
514
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
515
+ self.num_classes = num_classes
516
+ self.dropout_prob = dropout_prob
517
+
518
+ def token_drop(self, labels, force_drop_ids=None):
519
+ """
520
+ Drops labels to enable classifier-free guidance.
521
+ """
522
+ if force_drop_ids is None:
523
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
524
+ else:
525
+ drop_ids = force_drop_ids == 1
526
+ labels = torch.where(drop_ids, self.num_classes, labels)
527
+ return labels
528
+
529
+ def forward(self, labels, train, force_drop_ids=None):
530
+ use_dropout = self.dropout_prob > 0
531
+ if (train and use_dropout) or (force_drop_ids is not None):
532
+ labels = self.token_drop(labels, force_drop_ids)
533
+ embeddings = self.embedding_table(labels)
534
+ return embeddings
535
+
536
+
537
+
538
+
539
+ #################################################################################
540
+ # Attention #
541
+ #################################################################################
542
+
543
+ # modified from timm and eva-02
544
+ # https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py
545
+ # https://github.com/baaivision/EVA/blob/master/EVA-02/asuka/modeling_finetune.py
546
+
547
+
548
+ class Attention(nn.Module):
549
+
550
+ def __init__(self,
551
+ dim: int,
552
+ num_heads: int = 8,
553
+ qkv_bias: bool = False,
554
+ q_norm: Optional[str] = None,
555
+ k_norm: Optional[str] = None,
556
+ qk_norm_weight: bool = False,
557
+ attn_drop: float = 0.,
558
+ proj_drop: float = 0.,
559
+ rel_pos_embed: Optional[str] = None,
560
+ add_rel_pe_to_v: bool = False,
561
+ ) -> None:
562
+ super().__init__()
563
+ assert dim % num_heads == 0, 'dim should be divisible by num_heads'
564
+ self.num_heads = num_heads
565
+ self.head_dim = dim // num_heads
566
+ self.scale = self.head_dim ** -0.5
567
+
568
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
569
+ if q_norm == 'layernorm' and qk_norm_weight == True:
570
+ q_norm = 'w_layernorm'
571
+ if k_norm == 'layernorm' and qk_norm_weight == True:
572
+ k_norm = 'w_layernorm'
573
+
574
+ self.q_norm = create_norm(q_norm, self.head_dim)
575
+ self.k_norm = create_norm(k_norm, self.head_dim)
576
+
577
+
578
+ self.attn_drop = nn.Dropout(attn_drop)
579
+ self.proj = nn.Linear(dim, dim)
580
+ self.proj_drop = nn.Dropout(proj_drop)
581
+
582
+ self.rel_pos_embed = None if rel_pos_embed==None else rel_pos_embed.lower()
583
+ self.add_rel_pe_to_v = add_rel_pe_to_v
584
+
585
+
586
+
587
+ def forward(self,
588
+ x: torch.Tensor,
589
+ mask: Optional[torch.Tensor] = None,
590
+ freqs_cos: Optional[torch.Tensor] = None,
591
+ freqs_sin: Optional[torch.Tensor] = None,
592
+ ) -> torch.Tensor:
593
+ B, N, C = x.shape
594
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
595
+ q, k, v = qkv.unbind(0) # (B, n_h, N, D_h)
596
+ q, k = self.q_norm(q), self.k_norm(k)
597
+
598
+ if self.rel_pos_embed in ['rope', 'xpos']: # multiplicative rel_pos_embed
599
+ if self.add_rel_pe_to_v:
600
+ v = v * freqs_cos + rotate_half(v) * freqs_sin
601
+ q = q * freqs_cos + rotate_half(q) * freqs_sin
602
+ k = k * freqs_cos + rotate_half(k) * freqs_sin
603
+
604
+ attn_mask = mask[:, None, None, :] # (B, N) -> (B, 1, 1, N)
605
+ attn_mask = (attn_mask == attn_mask.transpose(-2, -1)) # (B, 1, 1, N) x (B, 1, N, 1) -> (B, 1, N, N)
606
+ mask = torch.not_equal(mask, torch.zeros_like(mask)).to(mask) # (B, N) -> (B, N)
607
+
608
+
609
+ if x.device.type == "cpu":
610
+ x = F.scaled_dot_product_attention(
611
+ q, k, v, attn_mask=attn_mask,
612
+ dropout_p=self.attn_drop.p if self.training else 0.,
613
+ )
614
+ else:
615
+ with torch.backends.cuda.sdp_kernel(enable_flash=True):
616
+ '''
617
+ F.scaled_dot_product_attention is the efficient implementation equivalent to the following:
618
+ attn_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0) if is_causal else attn_mask
619
+ attn_mask = attn_mask.masked_fill(not attn_mask, -float('inf')) if attn_mask.dtype==torch.bool else attn_mask
620
+ attn_weight = torch.softmax((Q @ K.transpose(-2, -1) / math.sqrt(Q.size(-1))) + attn_mask, dim=-1)
621
+ attn_weight = torch.dropout(attn_weight, dropout_p)
622
+ return attn_weight @ V
623
+ In conclusion:
624
+ boolean attn_mask will mask the attention matrix where attn_mask is False
625
+ non-boolean attn_mask will be directly added to Q@K.T
626
+ '''
627
+ x = F.scaled_dot_product_attention(
628
+ q, k, v, attn_mask=attn_mask,
629
+ dropout_p=self.attn_drop.p if self.training else 0.,
630
+ )
631
+ x = x.transpose(1, 2).reshape(B, N, C)
632
+ x = x * mask[..., None] # mask: (B, N) -> (B, N, 1)
633
+ x = self.proj(x)
634
+ x = self.proj_drop(x)
635
+ return x
636
+
637
+ #################################################################################
638
+ # Basic FiT Module #
639
+ #################################################################################
640
+
641
+ class FiTBlock(nn.Module):
642
+ """
643
+ A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning.
644
+ """
645
+ def __init__(self,
646
+ hidden_size,
647
+ num_heads,
648
+ mlp_ratio=4.0,
649
+ swiglu=True,
650
+ swiglu_large=False,
651
+ rel_pos_embed=None,
652
+ add_rel_pe_to_v=False,
653
+ norm_layer: str = 'layernorm',
654
+ q_norm: Optional[str] = None,
655
+ k_norm: Optional[str] = None,
656
+ qk_norm_weight: bool = False,
657
+ qkv_bias=True,
658
+ ffn_bias=True,
659
+ adaln_bias=True,
660
+ adaln_type='normal',
661
+ adaln_lora_dim: int = None,
662
+ **block_kwargs
663
+ ):
664
+ super().__init__()
665
+ self.norm1 = create_norm(norm_layer, hidden_size)
666
+ self.norm2 = create_norm(norm_layer, hidden_size)
667
+
668
+ self.attn = Attention(
669
+ hidden_size, num_heads=num_heads, rel_pos_embed=rel_pos_embed,
670
+ q_norm=q_norm, k_norm=k_norm, qk_norm_weight=qk_norm_weight,
671
+ qkv_bias=qkv_bias, add_rel_pe_to_v=add_rel_pe_to_v,
672
+ **block_kwargs
673
+ )
674
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
675
+ if swiglu:
676
+ if swiglu_large:
677
+ self.mlp = SwiGLU(in_features=hidden_size, hidden_features=mlp_hidden_dim, bias=ffn_bias)
678
+ else:
679
+ self.mlp = SwiGLU(in_features=hidden_size, hidden_features=(mlp_hidden_dim*2)//3, bias=ffn_bias)
680
+ else:
681
+ self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=lambda: nn.GELU(approximate="tanh"), bias=ffn_bias)
682
+ if adaln_type == 'normal':
683
+ self.adaLN_modulation = nn.Sequential(
684
+ nn.SiLU(),
685
+ nn.Linear(hidden_size, 6 * hidden_size, bias=adaln_bias)
686
+ )
687
+ elif adaln_type == 'lora':
688
+ self.adaLN_modulation = nn.Sequential(
689
+ nn.SiLU(),
690
+ nn.Linear(hidden_size, adaln_lora_dim, bias=adaln_bias),
691
+ nn.Linear(adaln_lora_dim, 6 * hidden_size, bias=adaln_bias)
692
+ )
693
+ elif adaln_type == 'swiglu':
694
+ self.adaLN_modulation = SwiGLU(
695
+ in_features=hidden_size, hidden_features=(hidden_size//4)*3, out_features=6*hidden_size, bias=adaln_bias
696
+ )
697
+
698
+ def forward(self, x, c, mask, freqs_cos, freqs_sin, global_adaln=0.0):
699
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.adaLN_modulation(c) + global_adaln).chunk(6, dim=1)
700
+ x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), mask, freqs_cos, freqs_sin)
701
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
702
+ return x
703
+
704
+ class FinalLayer(nn.Module):
705
+ """
706
+ The final layer of DiT.
707
+ """
708
+ def __init__(self, hidden_size, patch_size, out_channels, norm_layer: str = 'layernorm', adaln_bias=True, adaln_type='normal'):
709
+ super().__init__()
710
+ self.norm_final = create_norm(norm_type=norm_layer, dim=hidden_size)
711
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
712
+ if adaln_type == 'swiglu':
713
+ self.adaLN_modulation = SwiGLU(in_features=hidden_size, hidden_features=hidden_size//2, out_features=2*hidden_size, bias=adaln_bias)
714
+ else: # adaln_type in ['normal', 'lora']
715
+ self.adaLN_modulation = nn.Sequential(
716
+ nn.SiLU(),
717
+ nn.Linear(hidden_size, 2 * hidden_size, bias=adaln_bias)
718
+ )
719
+
720
+ def forward(self, x, c):
721
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
722
+ x = modulate(self.norm_final(x), shift, scale)
723
+ x = self.linear(x)
724
+ return x
725
+
726
+ class FiTTransformer2DModel(ModelMixin, ConfigMixin):
727
+ """
728
+ FiT backbone as a Hugging Face Diffusers `ModelMixin` / `ConfigMixin` module.
729
+
730
+ Checkpoints from the original FiT layout load with identical state dict keys.
731
+ """
732
+
733
+ config_name = "config.json"
734
+ _supports_gradient_checkpointing = True
735
+
736
+ @register_to_config
737
+ def __init__(
738
+ self,
739
+ context_size: int = 256,
740
+ patch_size: int = 2,
741
+ in_channels: int = 4,
742
+ hidden_size: int = 1152,
743
+ depth: int = 28,
744
+ num_heads: int = 16,
745
+ mlp_ratio: float = 4.0,
746
+ class_dropout_prob: float = 0.1,
747
+ num_classes: int = 1000,
748
+ learn_sigma: bool = True,
749
+ use_sit: bool = False,
750
+ use_checkpoint: bool = False,
751
+ use_swiglu: bool = False,
752
+ use_swiglu_large: bool = False,
753
+ rel_pos_embed: Optional[str] = "rope",
754
+ norm_type: str = "layernorm",
755
+ q_norm: Optional[str] = None,
756
+ k_norm: Optional[str] = None,
757
+ qk_norm_weight: bool = False,
758
+ qkv_bias: bool = True,
759
+ ffn_bias: bool = True,
760
+ adaln_bias: bool = True,
761
+ adaln_type: str = "normal",
762
+ adaln_lora_dim: Optional[int] = None,
763
+ rope_theta: float = 10000.0,
764
+ custom_freqs: str = "normal",
765
+ max_pe_len_h: Optional[int] = None,
766
+ max_pe_len_w: Optional[int] = None,
767
+ decouple: bool = False,
768
+ ori_max_pe_len: Optional[int] = None,
769
+ online_rope: bool = False,
770
+ add_rel_pe_to_v: bool = False,
771
+ pretrain_ckpt: Optional[str] = None,
772
+ ignore_keys: Optional[list] = None,
773
+ finetune: Optional[str] = None,
774
+ time_shifting: int = 1,
775
+ ):
776
+ super().__init__()
777
+ self.context_size = context_size
778
+ self.hidden_size = hidden_size
779
+ assert not (learn_sigma and use_sit)
780
+ self.learn_sigma = learn_sigma
781
+ self.use_sit = use_sit
782
+ self.use_checkpoint = use_checkpoint
783
+ self.depth = depth
784
+ self.mlp_ratio = mlp_ratio
785
+ self.class_dropout_prob = class_dropout_prob
786
+ self.num_classes = num_classes
787
+ self.in_channels = in_channels
788
+ self.out_channels = self.in_channels * 2 if learn_sigma else in_channels
789
+ self.patch_size = patch_size
790
+ self.num_heads = num_heads
791
+ self.adaln_type = adaln_type
792
+ self.online_rope = online_rope
793
+ self.time_shifting = time_shifting
794
+
795
+ self.x_embedder = PatchEmbedder(in_channels * patch_size**2, hidden_size, bias=True)
796
+ self.t_embedder = TimestepEmbedder(hidden_size)
797
+ self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
798
+
799
+ self.rope_embedder = VisionRotaryEmbedding(
800
+ head_dim=hidden_size // num_heads,
801
+ theta=rope_theta,
802
+ custom_freqs=custom_freqs,
803
+ online_rope=online_rope,
804
+ max_pe_len_h=max_pe_len_h,
805
+ max_pe_len_w=max_pe_len_w,
806
+ decouple=decouple,
807
+ ori_max_pe_len=ori_max_pe_len,
808
+ )
809
+
810
+ if adaln_type == "lora":
811
+ self.global_adaLN_modulation = nn.Sequential(
812
+ nn.SiLU(),
813
+ nn.Linear(hidden_size, 6 * hidden_size, bias=adaln_bias),
814
+ )
815
+ else:
816
+ self.global_adaLN_modulation = None
817
+
818
+ self.blocks = nn.ModuleList(
819
+ [
820
+ FiTBlock(
821
+ hidden_size,
822
+ num_heads,
823
+ mlp_ratio=mlp_ratio,
824
+ swiglu=use_swiglu,
825
+ swiglu_large=use_swiglu_large,
826
+ rel_pos_embed=rel_pos_embed,
827
+ add_rel_pe_to_v=add_rel_pe_to_v,
828
+ norm_layer=norm_type,
829
+ q_norm=q_norm,
830
+ k_norm=k_norm,
831
+ qk_norm_weight=qk_norm_weight,
832
+ qkv_bias=qkv_bias,
833
+ ffn_bias=ffn_bias,
834
+ adaln_bias=adaln_bias,
835
+ adaln_type=adaln_type,
836
+ adaln_lora_dim=adaln_lora_dim,
837
+ )
838
+ for _ in range(depth)
839
+ ]
840
+ )
841
+ self.final_layer = FinalLayer(
842
+ hidden_size,
843
+ patch_size,
844
+ self.out_channels,
845
+ norm_layer=norm_type,
846
+ adaln_bias=adaln_bias,
847
+ adaln_type=adaln_type,
848
+ )
849
+ self.initialize_weights(pretrain_ckpt=pretrain_ckpt, ignore=ignore_keys)
850
+ if finetune is not None:
851
+ self.apply_finetune(finetune_type=finetune, unfreeze=ignore_keys)
852
+
853
+ def initialize_weights(self, pretrain_ckpt=None, ignore=None):
854
+ def _basic_init(module):
855
+ if isinstance(module, nn.Linear):
856
+ torch.nn.init.xavier_uniform_(module.weight)
857
+ if module.bias is not None:
858
+ nn.init.constant_(module.bias, 0)
859
+
860
+ self.apply(_basic_init)
861
+
862
+ w = self.x_embedder.proj.weight.data
863
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
864
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
865
+
866
+ nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
867
+
868
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
869
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
870
+
871
+ for block in self.blocks:
872
+ if self.adaln_type in ["normal", "lora"]:
873
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
874
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
875
+ elif self.adaln_type == "swiglu":
876
+ nn.init.constant_(block.adaLN_modulation.fc2.weight, 0)
877
+ nn.init.constant_(block.adaLN_modulation.fc2.bias, 0)
878
+ if self.adaln_type == "lora":
879
+ nn.init.constant_(self.global_adaLN_modulation[-1].weight, 0)
880
+ nn.init.constant_(self.global_adaLN_modulation[-1].bias, 0)
881
+ if self.adaln_type == "swiglu":
882
+ nn.init.constant_(self.final_layer.adaLN_modulation.fc2.weight, 0)
883
+ nn.init.constant_(self.final_layer.adaLN_modulation.fc2.bias, 0)
884
+ else:
885
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
886
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
887
+ nn.init.constant_(self.final_layer.linear.weight, 0)
888
+ nn.init.constant_(self.final_layer.linear.bias, 0)
889
+
890
+ keys = list(self.state_dict().keys())
891
+ ignore_keys = []
892
+ if ignore is not None:
893
+ for ign in ignore:
894
+ for key in keys:
895
+ if ign in key:
896
+ ignore_keys.append(key)
897
+ ignore_keys = list(set(ignore_keys))
898
+
899
+ def unpatchify(self, x, hw):
900
+ h, w = hw
901
+ p = self.patch_size
902
+ if self.use_sit:
903
+ x = rearrange(x, "b (h w) c -> b h w c", h=h // p, w=w // p)
904
+ x = rearrange(x, "b h w (c p1 p2) -> b c (h p1) (w p2)", p1=p, p2=p)
905
+ else:
906
+ x = rearrange(x, "b c (h w) -> b c h w", h=h // p, w=w // p)
907
+ x = rearrange(x, "b (c p1 p2) h w -> b c (h p1) (w p2)", p1=p, p2=p)
908
+ return x
909
+
910
+ def forward(self, x, t, y, grid, mask, size=None):
911
+ dtype = self.x_embedder.proj.weight.dtype
912
+ x = x.to(dtype=dtype)
913
+ mask = mask.to(dtype=dtype)
914
+ # Flow-matching (FiTv2 / use_sit) expects t in [0, 1]. Improved diffusion (FiTv1)
915
+ # passes integer timesteps 0..T-1 directly to TimestepEmbedder, like DiT.
916
+ if self.use_sit:
917
+ t = torch.clamp(self.time_shifting * t / (1 + (self.time_shifting - 1) * t), max=1.0)
918
+ t = t.float().to(dtype)
919
+ if not self.use_sit:
920
+ x = rearrange(x, "B C N -> B N C")
921
+ x = self.x_embedder(x)
922
+ t = self.t_embedder(t)
923
+ y = self.y_embedder(y, self.training)
924
+ c = t + y
925
+
926
+ if self.online_rope:
927
+ freqs_cos, freqs_sin = self.rope_embedder.online_get_2d_rope_from_grid(grid, size)
928
+ freqs_cos, freqs_sin = freqs_cos.unsqueeze(1), freqs_sin.unsqueeze(1)
929
+ else:
930
+ freqs_cos, freqs_sin = self.rope_embedder.get_cached_2d_rope_from_grid(grid)
931
+ freqs_cos, freqs_sin = freqs_cos.unsqueeze(1), freqs_sin.unsqueeze(1)
932
+ freqs_cos = freqs_cos.to(dtype=dtype)
933
+ freqs_sin = freqs_sin.to(dtype=dtype)
934
+ if self.global_adaLN_modulation is not None:
935
+ global_adaln = self.global_adaLN_modulation(c)
936
+ else:
937
+ global_adaln = 0.0
938
+
939
+ if not self.use_checkpoint:
940
+ for block in self.blocks:
941
+ x = block(x, c, mask, freqs_cos, freqs_sin, global_adaln)
942
+ else:
943
+ for block in self.blocks:
944
+ x = torch.utils.checkpoint.checkpoint(
945
+ self.ckpt_wrapper(block), x, c, mask, freqs_cos, freqs_sin, global_adaln, use_reentrant=False
946
+ )
947
+ x = self.final_layer(x, c)
948
+ x = x * mask[..., None]
949
+ if not self.use_sit:
950
+ x = rearrange(x, "B N C -> B C N")
951
+ return x
952
+
953
+ def forward_with_cfg(self, x, t, y, grid, mask, size, cfg_scale, scale_pow=0.0):
954
+ half = x[: len(x) // 2]
955
+ combined = torch.cat([half, half], dim=0)
956
+ model_out = self.forward(combined, t, y, grid, mask, size)
957
+ C_cfg = 3 * self.patch_size * self.patch_size
958
+ if self.use_sit:
959
+ eps, rest = model_out[:, :, :C_cfg], model_out[:, :, C_cfg:]
960
+ else:
961
+ eps, rest = model_out[:, :C_cfg], model_out[:, C_cfg:]
962
+ cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
963
+ if scale_pow == 0.0:
964
+ real_cfg_scale = cfg_scale
965
+ else:
966
+ scale_step = (1 - torch.cos(((1 - torch.clamp_max(t, 1.0)) ** scale_pow) * torch.pi)) * 1 / 2
967
+ real_cfg_scale = (cfg_scale - 1) * scale_step + 1
968
+ real_cfg_scale = real_cfg_scale[: len(x) // 2].view(-1, 1, 1)
969
+ if self.use_sit:
970
+ t = t / (self.time_shifting + (1 - self.time_shifting) * t)
971
+ half_eps = uncond_eps + real_cfg_scale * (cond_eps - uncond_eps)
972
+ eps = torch.cat([half_eps, half_eps], dim=0)
973
+ if self.use_sit:
974
+ return torch.cat([eps, rest], dim=2)
975
+ return torch.cat([eps, rest], dim=1)
976
+
977
+ def ckpt_wrapper(self, module):
978
+ def ckpt_forward(*inputs):
979
+ return module(*inputs)
980
+
981
+ return ckpt_forward
982
+
983
+ def apply_finetune(self, finetune_type, unfreeze):
984
+ if finetune_type == "full":
985
+ return
986
+ for _, param in self.named_parameters():
987
+ param.requires_grad = False
988
+ if unfreeze is None:
989
+ return
990
+ for unf in unfreeze:
991
+ for name, param in self.named_parameters():
992
+ if unf in name:
993
+ param.requires_grad = True
FiTv1-XL-2-256/vae/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.38.0",
4
+ "_name_or_path": "stabilityai/sd-vae-ft-ema",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "latents_mean": null,
22
+ "latents_std": null,
23
+ "layers_per_block": 2,
24
+ "mid_block_add_attention": true,
25
+ "norm_num_groups": 32,
26
+ "out_channels": 3,
27
+ "sample_size": 256,
28
+ "scaling_factor": 0.18215,
29
+ "shift_factor": null,
30
+ "up_block_types": [
31
+ "UpDecoderBlock2D",
32
+ "UpDecoderBlock2D",
33
+ "UpDecoderBlock2D",
34
+ "UpDecoderBlock2D"
35
+ ],
36
+ "use_post_quant_conv": true,
37
+ "use_quant_conv": true
38
+ }
FiTv1-XL-2-256/vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:703abdcd7c389316b5128faa9b750a530ea1680b453170b27afebac5e4db30c4
3
+ size 334643268