BiliSakura commited on
Commit
eca8fd2
·
verified ·
1 Parent(s): c1d88a6

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
+ Self-Flow-XL-2-256/demo.png filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: diffusers
3
+ pipeline_tag: unconditional-image-generation
4
+ tags:
5
+ - diffusers
6
+ - self-flow
7
+ - image-generation
8
+ - class-conditional
9
+ - imagenet
10
+ - flow-matching
11
+ license: apache-2.0
12
+ inference: true
13
+ widget:
14
+ - output:
15
+ url: Self-Flow-XL-2-256/demo.png
16
+ language:
17
+ - en
18
+ ---
19
+
20
+ # Self-Flow-diffusers
21
+
22
+ Diffusers-ready checkpoints for **Self-Flow** (Self-Supervised Flow Matching), converted from the [official Self-Flow release](https://github.com/black-forest-labs/Self-Flow) for local/offline use.
23
+
24
+ This root folder is a model collection that contains:
25
+
26
+ - `Self-Flow-XL-2-256`
27
+
28
+ Each subfolder is a self-contained Diffusers model repo with:
29
+
30
+ - `pipeline.py` (`SelfFlowPipeline`)
31
+ - `transformer/transformer_selfflow.py` and weights
32
+ - `scheduler/scheduling_flow_match_selfflow.py` (`SelfFlowFlowMatchScheduler`, SDE flow matching)
33
+ - `scheduler/scheduler_config.json`
34
+ - `vae/` (`stabilityai/sd-vae-ft-ema`)
35
+
36
+ Each variant embeds English `id2label` in `model_index.json`, so class labels can be passed as ImageNet ids or English synonym strings.
37
+
38
+ ## Demo
39
+
40
+ ![Self-Flow-XL-2-256 demo](Self-Flow-XL-2-256/demo.png)
41
+
42
+ Class-conditional sample (ImageNet class **207**, golden retriever), `Self-Flow-XL/2` at 256×256, 250 steps, CFG 3.5, seed 42.
43
+
44
+ ## Model Paths
45
+
46
+ Use paths relative to this root README:
47
+
48
+ | Model | Resolution | Local path |
49
+ | --- | ---: | --- |
50
+ | Self-Flow-XL/2 | 256×256 | `./Self-Flow-XL-2-256` |
51
+
52
+ ## Recommended inference
53
+
54
+ | Setting | Value |
55
+ | --- | --- |
56
+ | Resolution | 256×256 |
57
+ | Sampler | Self-Flow SDE flow matching |
58
+ | Steps | 250 |
59
+ | CFG scale | 3.5 |
60
+ | Guidance interval | `(0.0, 0.7)` when CFG > 1 |
61
+ | Dtype | `bfloat16` (recommended on Ampere+) |
62
+ | VAE | `stabilityai/sd-vae-ft-ema` |
63
+
64
+ ## Inference Demo (Diffusers)
65
+
66
+ ```python
67
+ from pathlib import Path
68
+ import torch
69
+ from diffusers import DiffusionPipeline
70
+
71
+ model_dir = Path("./Self-Flow-XL-2-256").resolve()
72
+ device = "cuda" if torch.cuda.is_available() else "cpu"
73
+
74
+ pipe = DiffusionPipeline.from_pretrained(
75
+ str(model_dir),
76
+ local_files_only=True,
77
+ custom_pipeline=str(model_dir / "pipeline.py"),
78
+ trust_remote_code=True,
79
+ torch_dtype=torch.bfloat16,
80
+ )
81
+ pipe.to(device)
82
+
83
+ generator = torch.Generator(device=device).manual_seed(42)
84
+
85
+ print(pipe.id2label[207])
86
+ print(pipe.get_label_ids("golden retriever")) # [207]
87
+
88
+ image = pipe(
89
+ class_labels="golden retriever",
90
+ num_inference_steps=250,
91
+ guidance_scale=3.5,
92
+ generator=generator,
93
+ ).images[0]
94
+ image.save("self_flow_xl_256_demo.png")
95
+ ```
Self-Flow-XL-2-256/README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: diffusers
4
+ pipeline_tag: unconditional-image-generation
5
+ tags:
6
+ - diffusers
7
+ - self-flow
8
+ - image-generation
9
+ - class-conditional
10
+ - imagenet
11
+ inference: true
12
+ ---
13
+
14
+ # Self-Flow-XL-2-256
15
+
16
+ Self-contained Diffusers checkpoint for **Self-Flow-XL/2** on ImageNet 256×256, converted from the official Self-Flow release.
17
+
18
+ ## Recommended inference
19
+
20
+ | Setting | Value |
21
+ | --- | --- |
22
+ | Resolution | 256×256 |
23
+ | Sampler | Self-Flow SDE flow matching |
24
+ | Steps | 250 |
25
+ | CFG scale | 3.5 |
26
+ | Guidance interval | `(0.0, 0.7)` when CFG > 1 |
27
+ | Dtype | `bfloat16` (recommended on Ampere+) |
28
+ | VAE | `stabilityai/sd-vae-ft-ema` |
29
+
30
+ ```python
31
+ from pathlib import Path
32
+ import torch
33
+ from diffusers import DiffusionPipeline
34
+
35
+ model_dir = Path("./Self-Flow-XL-2-256").resolve()
36
+ pipe = DiffusionPipeline.from_pretrained(
37
+ str(model_dir),
38
+ local_files_only=True,
39
+ custom_pipeline=str(model_dir / "pipeline.py"),
40
+ trust_remote_code=True,
41
+ torch_dtype=torch.bfloat16,
42
+ )
43
+ pipe.to("cuda")
44
+
45
+ generator = torch.Generator(device="cuda").manual_seed(42)
46
+ image = pipe(
47
+ class_labels="golden retriever",
48
+ num_inference_steps=250,
49
+ guidance_scale=3.5,
50
+ generator=generator,
51
+ ).images[0]
52
+ image.save("demo.png")
53
+ ```
54
+
55
+ ## Components
56
+
57
+ - `pipeline.py`
58
+ - `token_utils.py`
59
+ - `transformer/transformer_selfflow.py`
60
+ - `transformer/diffusion_pytorch_model.safetensors`
61
+ - `scheduler/scheduling_flow_match_selfflow.py`
62
+ - `scheduler/scheduler_config.json`
63
+ - `vae_pretrained_model_name_or_path.txt`
Self-Flow-XL-2-256/demo.png ADDED

Git LFS Details

  • SHA256: 91864e0659598d4531df3b3dabeba9ee4dd6a9ba26d70d09c234067a43434f07
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
Self-Flow-XL-2-256/model_index.json ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline",
4
+ "SelfFlowPipeline"
5
+ ],
6
+ "_diffusers_version": "0.36.0",
7
+ "transformer": [
8
+ "transformer_selfflow",
9
+ "SelfFlowTransformer2DModel"
10
+ ],
11
+ "scheduler": [
12
+ "scheduling_flow_match_selfflow",
13
+ "SelfFlowFlowMatchScheduler"
14
+ ],
15
+ "vae": [
16
+ "diffusers",
17
+ "AutoencoderKL"
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
+ }
Self-Flow-XL-2-256/pipeline.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hub custom pipeline: SelfFlowPipeline.
2
+ Load with native Hugging Face diffusers and trust_remote_code=True.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import importlib
8
+ import inspect
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional, Tuple, Union
13
+
14
+ import torch
15
+ from einops import rearrange
16
+
17
+ from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler
18
+ from diffusers.image_processor import VaeImageProcessor
19
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
20
+ from diffusers.schedulers import KarrasDiffusionSchedulers
21
+ from diffusers.utils.torch_utils import randn_tensor
22
+
23
+ DEFAULT_LATENT_SIZE = 32
24
+ DEFAULT_IMAGE_SIZE = 256
25
+
26
+
27
+ def _prc_img(x: torch.Tensor, t_coord: torch.Tensor | None = None, l_coord: torch.Tensor | None = None):
28
+ _, h, w = x.shape
29
+ x_coords = {
30
+ "t": torch.arange(1, device=x.device) if t_coord is None else t_coord,
31
+ "h": torch.arange(h, device=x.device),
32
+ "w": torch.arange(w, device=x.device),
33
+ "l": torch.arange(1, device=x.device) if l_coord is None else l_coord,
34
+ }
35
+ x_ids = torch.cartesian_prod(x_coords["t"], x_coords["h"], x_coords["w"], x_coords["l"])
36
+ x = rearrange(x, "c h w -> (h w) c")
37
+ return x, x_ids
38
+
39
+
40
+ def _batched_prc_img(
41
+ x: torch.Tensor, t_coord: torch.Tensor | None = None, l_coord: torch.Tensor | None = None
42
+ ):
43
+ results = []
44
+ for i in range(len(x)):
45
+ results.append(
46
+ _prc_img(
47
+ x[i],
48
+ t_coord[i] if t_coord is not None else None,
49
+ l_coord[i] if l_coord is not None else None,
50
+ )
51
+ )
52
+ x_out, x_ids = zip(*results)
53
+ return torch.stack(x_out), torch.stack(x_ids)
54
+
55
+
56
+ def _compress_time(t_ids: torch.Tensor) -> torch.Tensor:
57
+ t_ids_max = torch.max(t_ids)
58
+ t_remap = torch.zeros((t_ids_max + 1,), device=t_ids.device, dtype=t_ids.dtype)
59
+ t_unique_sorted_ids = torch.unique(t_ids, sorted=True)
60
+ t_remap[t_unique_sorted_ids] = torch.arange(len(t_unique_sorted_ids), device=t_ids.device, dtype=t_ids.dtype)
61
+ return t_remap[t_ids]
62
+
63
+
64
+ def _scatter_ids(x: torch.Tensor, x_ids: torch.Tensor) -> list[torch.Tensor]:
65
+ x_list = []
66
+ for data, pos in zip(x, x_ids):
67
+ _, ch = data.shape
68
+ t_ids = pos[:, 0].to(torch.int64)
69
+ h_ids = pos[:, 1].to(torch.int64)
70
+ w_ids = pos[:, 2].to(torch.int64)
71
+ t_ids_cmpr = _compress_time(t_ids)
72
+ t = torch.max(t_ids_cmpr) + 1
73
+ h = torch.max(h_ids) + 1
74
+ w = torch.max(w_ids) + 1
75
+ flat_ids = t_ids_cmpr * w * h + h_ids * w + w_ids
76
+ out = torch.zeros((t * h * w, ch), device=data.device, dtype=data.dtype)
77
+ out.scatter_(0, flat_ids.unsqueeze(1).expand(-1, ch), data)
78
+ x_list.append(rearrange(out, "(t h w) c -> 1 c t h w", t=t, h=h, w=w))
79
+ return x_list
80
+
81
+
82
+ def _scattercat(x: torch.Tensor, x_ids: torch.Tensor) -> torch.Tensor:
83
+ return torch.cat(_scatter_ids(x, x_ids), 0).squeeze(2)
84
+
85
+
86
+ class SelfFlowPipeline(DiffusionPipeline):
87
+ """
88
+ Pipeline for class-conditional Self-Flow image generation on ImageNet 256×256 latents.
89
+
90
+ Default sampling uses 250 SDE steps with classifier-free guidance scale 3.5
91
+ over flow times `(0.0, 0.7)`.
92
+ """
93
+
94
+ model_cpu_offload_seq = "transformer->vae"
95
+ _optional_components = ["vae"]
96
+
97
+ def __init__(
98
+ self,
99
+ transformer,
100
+ scheduler: KarrasDiffusionSchedulers,
101
+ vae=None,
102
+ id2label: Optional[Dict[Union[int, str], str]] = None,
103
+ ):
104
+ super().__init__()
105
+ if scheduler is None:
106
+ scheduler = FlowMatchEulerDiscreteScheduler(
107
+ num_train_timesteps=1000,
108
+ shift=1.0,
109
+ stochastic_sampling=False,
110
+ )
111
+ self.register_modules(transformer=transformer, scheduler=scheduler, vae=vae)
112
+ self.image_processor = VaeImageProcessor()
113
+ self._id2label = self._normalize_id2label(id2label)
114
+ self.labels = self._build_label2id(self._id2label)
115
+ self._labels_loaded_from_model_index = bool(self._id2label)
116
+
117
+ def _ensure_labels_loaded(self) -> None:
118
+ if self._labels_loaded_from_model_index:
119
+ return
120
+ loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
121
+ if loaded:
122
+ self._id2label = loaded
123
+ self.labels = self._build_label2id(self._id2label)
124
+ self._labels_loaded_from_model_index = True
125
+
126
+ @staticmethod
127
+ def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
128
+ if not id2label:
129
+ return {}
130
+ return {int(key): value for key, value in id2label.items()}
131
+
132
+ @staticmethod
133
+ def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
134
+ if not variant_path:
135
+ return {}
136
+ variant_dir = Path(variant_path).resolve()
137
+ model_index_path = variant_dir / "model_index.json"
138
+ if not model_index_path.exists():
139
+ return {}
140
+ raw = json.loads(model_index_path.read_text(encoding="utf-8"))
141
+ id2label = raw.get("id2label")
142
+ if not isinstance(id2label, dict):
143
+ return {}
144
+ return {int(key): value for key, value in id2label.items()}
145
+
146
+ @staticmethod
147
+ def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
148
+ label2id: Dict[str, int] = {}
149
+ for class_id, value in id2label.items():
150
+ for synonym in value.split(","):
151
+ synonym = synonym.strip()
152
+ if synonym:
153
+ label2id[synonym] = int(class_id)
154
+ return dict(sorted(label2id.items()))
155
+
156
+ @property
157
+ def id2label(self) -> Dict[int, str]:
158
+ self._ensure_labels_loaded()
159
+ return self._id2label
160
+
161
+ def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
162
+ self._ensure_labels_loaded()
163
+ label2id = self.labels
164
+ if not label2id:
165
+ raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.")
166
+
167
+ if isinstance(label, str):
168
+ label = [label]
169
+
170
+ missing = [item for item in label if item not in label2id]
171
+ if missing:
172
+ preview = ", ".join(list(label2id.keys())[:8])
173
+ raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
174
+ return [label2id[item] for item in label]
175
+
176
+ def _normalize_class_labels(
177
+ self,
178
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
179
+ ) -> torch.LongTensor:
180
+ if torch.is_tensor(class_labels):
181
+ return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
182
+
183
+ if isinstance(class_labels, int):
184
+ class_label_ids = [class_labels]
185
+ elif isinstance(class_labels, str):
186
+ class_label_ids = self.get_label_ids(class_labels)
187
+ elif class_labels and isinstance(class_labels[0], str):
188
+ class_label_ids = self.get_label_ids(class_labels)
189
+ else:
190
+ class_label_ids = list(class_labels)
191
+
192
+ return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
193
+
194
+ @classmethod
195
+ def from_pretrained(cls, pretrained_model_name_or_path=None, subfolder=None, **kwargs):
196
+ repo_root = Path(__file__).resolve().parent
197
+
198
+ if pretrained_model_name_or_path in (None, "", "."):
199
+ variant = repo_root
200
+ else:
201
+ variant = Path(pretrained_model_name_or_path)
202
+ if not variant.is_absolute():
203
+ candidate = (Path.cwd() / variant).resolve()
204
+ variant = candidate if candidate.exists() else (repo_root / variant).resolve()
205
+ if subfolder:
206
+ variant = variant / subfolder
207
+
208
+ model_kwargs = dict(kwargs)
209
+ inserted: List[str] = []
210
+
211
+ def _load_component(folder: str, module_name: str, class_name: str):
212
+ comp_dir = variant / folder
213
+ module_path = comp_dir / f"{module_name}.py"
214
+ has_weights = (comp_dir / "config.json").exists() or (comp_dir / "scheduler_config.json").exists()
215
+ if not module_path.exists() or not has_weights:
216
+ return None
217
+
218
+ comp_path = str(comp_dir)
219
+ if comp_path not in sys.path:
220
+ sys.path.insert(0, comp_path)
221
+ inserted.append(comp_path)
222
+
223
+ module = importlib.import_module(module_name)
224
+ component_cls = getattr(module, class_name)
225
+ return component_cls.from_pretrained(str(comp_dir), **model_kwargs)
226
+
227
+ try:
228
+ transformer = _load_component("transformer", "transformer_selfflow", "SelfFlowTransformer2DModel")
229
+ if transformer is None:
230
+ raise ValueError(f"No loadable transformer found under {variant}")
231
+
232
+ scheduler = cls._load_scheduler_from_variant(variant, model_kwargs)
233
+
234
+ vae = None
235
+ vae_dir = variant / "vae"
236
+ if vae_dir.exists() and (vae_dir / "config.json").exists():
237
+ vae = AutoencoderKL.from_pretrained(str(vae_dir), **model_kwargs)
238
+ elif (variant / "vae_pretrained_model_name_or_path.txt").exists():
239
+ vae_name = (variant / "vae_pretrained_model_name_or_path.txt").read_text(encoding="utf-8").strip()
240
+ vae = AutoencoderKL.from_pretrained(vae_name, **model_kwargs)
241
+
242
+ id2label = cls._read_id2label_from_model_index(str(variant))
243
+ pipe = cls(transformer=transformer, scheduler=scheduler, vae=vae, id2label=id2label)
244
+ if hasattr(pipe, "register_to_config"):
245
+ pipe.register_to_config(_name_or_path=str(variant))
246
+ return pipe
247
+ finally:
248
+ for comp_path in inserted:
249
+ if comp_path in sys.path:
250
+ sys.path.remove(comp_path)
251
+
252
+ @classmethod
253
+ def _load_scheduler_from_variant(cls, variant: Path, model_kwargs: dict):
254
+ scheduler_dir = variant / "scheduler"
255
+ config_path = scheduler_dir / "scheduler_config.json"
256
+ if not config_path.exists():
257
+ raise ValueError(f"No scheduler config found under {scheduler_dir}")
258
+
259
+ scheduler_entry = None
260
+ model_index_path = variant / "model_index.json"
261
+ if model_index_path.exists():
262
+ scheduler_entry = json.loads(model_index_path.read_text(encoding="utf-8")).get("scheduler")
263
+
264
+ if scheduler_entry is None:
265
+ class_name = json.loads(config_path.read_text(encoding="utf-8")).get("_class_name")
266
+ if not class_name:
267
+ raise ValueError(f"Missing `_class_name` in {config_path}")
268
+ scheduler_entry = ["diffusers", class_name]
269
+
270
+ if not isinstance(scheduler_entry, list) or len(scheduler_entry) != 2:
271
+ raise ValueError(f"Invalid scheduler entry in model_index.json: {scheduler_entry}")
272
+
273
+ module_name, class_name = scheduler_entry
274
+ if module_name == "diffusers":
275
+ import diffusers.schedulers as schedulers_pkg
276
+
277
+ scheduler_cls = getattr(schedulers_pkg, class_name)
278
+ return scheduler_cls.from_pretrained(str(scheduler_dir), **model_kwargs)
279
+
280
+ comp_path = str(scheduler_dir)
281
+ if comp_path not in sys.path:
282
+ sys.path.insert(0, comp_path)
283
+ try:
284
+ module = importlib.import_module(module_name)
285
+ scheduler_cls = getattr(module, class_name)
286
+ return scheduler_cls.from_pretrained(str(scheduler_dir), **model_kwargs)
287
+ finally:
288
+ if comp_path in sys.path:
289
+ sys.path.remove(comp_path)
290
+
291
+ @staticmethod
292
+ def prepare_extra_step_kwargs(
293
+ scheduler: KarrasDiffusionSchedulers,
294
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
295
+ ) -> Dict[str, Any]:
296
+ kwargs: Dict[str, Any] = {}
297
+ step_params = set(inspect.signature(scheduler.step).parameters.keys())
298
+ if "generator" in step_params:
299
+ kwargs["generator"] = generator
300
+ return kwargs
301
+
302
+ def _patchify_latents(self, latents: torch.Tensor) -> torch.Tensor:
303
+ patch_size = self.transformer.config.patch_size
304
+ return rearrange(
305
+ latents,
306
+ "b c (h p1) (w p2) -> b (c p1 p2) h w",
307
+ p1=patch_size,
308
+ p2=patch_size,
309
+ )
310
+
311
+ def _unpatchify_latents(self, latents: torch.Tensor) -> torch.Tensor:
312
+ patch_size = self.transformer.config.patch_size
313
+ channels = self.transformer.config.in_channels
314
+ return rearrange(
315
+ latents,
316
+ "b (c p1 p2) h w -> b c (h p1) (w p2)",
317
+ p1=patch_size,
318
+ p2=patch_size,
319
+ c=channels,
320
+ )
321
+
322
+ def prepare_token_latents(
323
+ self,
324
+ batch_size: int,
325
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
326
+ dtype: Optional[torch.dtype] = None,
327
+ device: Optional[torch.device] = None,
328
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
329
+ patch_size = self.transformer.config.patch_size
330
+ channels = self.transformer.config.in_channels
331
+ latent_size = self.transformer.config.input_size
332
+
333
+ latents = randn_tensor(
334
+ (batch_size, channels, latent_size, latent_size),
335
+ generator=generator,
336
+ device=device,
337
+ dtype=dtype,
338
+ )
339
+ patched = self._patchify_latents(latents)
340
+ tokens, token_ids = _batched_prc_img(patched)
341
+ return tokens.to(device=device, dtype=dtype), token_ids.to(device=device)
342
+
343
+ @staticmethod
344
+ def _apply_classifier_free_guidance(
345
+ model_output: torch.Tensor,
346
+ guidance_scale: float,
347
+ ) -> torch.Tensor:
348
+ if guidance_scale <= 1.0:
349
+ return model_output
350
+ model_output_uncond, model_output_cond = model_output.chunk(2)
351
+ return model_output_uncond + guidance_scale * (model_output_cond - model_output_uncond)
352
+
353
+ def decode_latents(self, latents: torch.Tensor, output_type: str = "pil"):
354
+ if self.vae is None:
355
+ if output_type == "latent":
356
+ return latents
357
+ raise ValueError("Cannot decode latents without a VAE.")
358
+
359
+ scaling_factor = getattr(self.vae.config, "scaling_factor", 0.18215)
360
+ vae_dtype = next(self.vae.parameters()).dtype
361
+ latents = (latents / scaling_factor).to(dtype=vae_dtype)
362
+ if output_type == "latent":
363
+ return latents
364
+ image = self.vae.decode(latents, return_dict=False)[0]
365
+ return self.image_processor.postprocess(image, output_type=output_type)
366
+
367
+ @torch.inference_mode()
368
+ def __call__(
369
+ self,
370
+ class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
371
+ num_inference_steps: int = 250,
372
+ guidance_scale: float = 3.5,
373
+ guidance_interval: Tuple[float, float] = (0.0, 0.7),
374
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
375
+ output_type: str = "pil",
376
+ return_dict: bool = True,
377
+ ) -> Union[ImagePipelineOutput, Tuple]:
378
+ r"""
379
+ Generate class-conditional images with Self-Flow.
380
+
381
+ Args:
382
+ class_labels (`int`, `str`, `list[int]`, `list[str]`, or `torch.LongTensor`):
383
+ ImageNet class indices or human-readable English label strings.
384
+ num_inference_steps (`int`, defaults to `250`):
385
+ Number of SDE denoising steps.
386
+ guidance_scale (`float`, defaults to `3.5`):
387
+ Classifier-free guidance scale. CFG is active when `guidance_scale > 1.0`
388
+ and the current flow time lies within `guidance_interval`.
389
+ guidance_interval (`tuple[float, float]`, defaults to `(0.0, 0.7)`):
390
+ Flow-time range `(low, high)` where CFG is applied.
391
+ generator (`torch.Generator`, *optional*):
392
+ RNG for reproducibility.
393
+ output_type (`str`, defaults to `"pil"`):
394
+ `"pil"`, `"np"`, `"pt"`, or `"latent"`.
395
+ return_dict (`bool`, defaults to `True`):
396
+ Return [`ImagePipelineOutput`] if True.
397
+ """
398
+ device = self._execution_device
399
+ dtype = next(self.transformer.parameters()).dtype
400
+
401
+ class_labels_tensor = self._normalize_class_labels(class_labels)
402
+ batch_size = class_labels_tensor.shape[0]
403
+ tokens, token_ids = self.prepare_token_latents(batch_size, generator=generator, dtype=dtype, device=device)
404
+
405
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
406
+ null_labels = torch.full_like(class_labels_tensor, self.transformer.config.num_classes - 1)
407
+ guidance_low, guidance_high = guidance_interval
408
+
409
+ timestep_list = self.scheduler.timesteps.tolist()
410
+ for timestep_value in self.progress_bar(timestep_list[:-1]):
411
+ flow_time = float(timestep_value)
412
+ guidance_active = guidance_scale > 1.0 and guidance_low <= flow_time <= guidance_high
413
+
414
+ if guidance_active:
415
+ model_tokens = torch.cat([tokens, tokens], dim=0)
416
+ labels = torch.cat([null_labels, class_labels_tensor], dim=0)
417
+ else:
418
+ if guidance_scale > 1.0 and tokens.shape[0] > batch_size:
419
+ tokens = tokens[batch_size:]
420
+ model_tokens = tokens
421
+ labels = class_labels_tensor
422
+
423
+ model_t = 1.0 - flow_time
424
+ timestep_batch = torch.full((model_tokens.shape[0],), model_t, device=device, dtype=dtype)
425
+ model_output = self.transformer(
426
+ model_tokens,
427
+ timestep_batch,
428
+ labels,
429
+ return_dict=True,
430
+ ).sample.to(torch.float32)
431
+ model_output = -model_output
432
+
433
+ if guidance_active:
434
+ model_output = self._apply_classifier_free_guidance(model_output, guidance_scale)
435
+ model_output = torch.cat([model_output, model_output], dim=0)
436
+
437
+ tokens = self.scheduler.step(
438
+ model_output,
439
+ timestep_value,
440
+ model_tokens,
441
+ generator=generator,
442
+ ).prev_sample.to(dtype)
443
+
444
+ if guidance_active:
445
+ tokens = tokens[batch_size:]
446
+
447
+ if guidance_scale > 1.0 and tokens.shape[0] > batch_size:
448
+ tokens = tokens[batch_size:]
449
+
450
+ final_time = float(timestep_list[-1])
451
+ final_model_t = 1.0 - final_time
452
+ final_timestep = torch.full((tokens.shape[0],), final_model_t, device=device, dtype=dtype)
453
+ final_output = self.transformer(
454
+ tokens,
455
+ final_timestep,
456
+ class_labels_tensor,
457
+ return_dict=True,
458
+ ).sample.to(torch.float32)
459
+ final_output = -final_output
460
+ tokens = self.scheduler.step(
461
+ final_output,
462
+ final_time,
463
+ tokens,
464
+ generator=generator,
465
+ ).prev_sample.to(dtype)
466
+
467
+ spatial = _scattercat(tokens, token_ids)
468
+ latents = self._unpatchify_latents(spatial)
469
+ images = self.decode_latents(latents, output_type=output_type)
470
+
471
+ self.maybe_free_model_hooks()
472
+ if not return_dict:
473
+ return (images,)
474
+ return ImagePipelineOutput(images=images)
475
+
476
+
477
+ SelfFlowPipelineOutput = ImagePipelineOutput
Self-Flow-XL-2-256/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "SelfFlowFlowMatchScheduler",
3
+ "_diffusers_version": "0.36.0",
4
+ "num_train_timesteps": 1000,
5
+ "path_type": "Linear",
6
+ "prediction": "velocity",
7
+ "sampling_method": "Euler",
8
+ "diffusion_form": "sigma",
9
+ "diffusion_norm": 1.0,
10
+ "last_step": "Euler",
11
+ "last_step_size": 0.04,
12
+ "reverse": true
13
+ }
Self-Flow-XL-2-256/scheduler/scheduling_flow_match_selfflow.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ from dataclasses import dataclass
9
+ from typing import Optional, Tuple, Union
10
+
11
+ import numpy as np
12
+ import torch
13
+
14
+ try:
15
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
16
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
17
+ from diffusers.utils import BaseOutput
18
+ except Exception: # pragma: no cover
19
+ class BaseOutput(dict):
20
+ def __post_init__(self):
21
+ self.update(self.__dict__)
22
+
23
+ class _Config(dict):
24
+ def __getattr__(self, key):
25
+ try:
26
+ return self[key]
27
+ except KeyError as error:
28
+ raise AttributeError(key) from error
29
+
30
+ class ConfigMixin:
31
+ config_name = "scheduler_config.json"
32
+
33
+ class SchedulerMixin:
34
+ def set_timesteps(self, *args, **kwargs):
35
+ raise NotImplementedError
36
+
37
+ def register_to_config(init):
38
+ def wrapper(self, *args, **kwargs):
39
+ import inspect
40
+
41
+ signature = inspect.signature(init)
42
+ bound = signature.bind(self, *args, **kwargs)
43
+ bound.apply_defaults()
44
+ self.config = _Config({key: value for key, value in bound.arguments.items() if key != "self"})
45
+ init(self, *args, **kwargs)
46
+
47
+ return wrapper
48
+
49
+
50
+ @dataclass
51
+ class SelfFlowFlowMatchSchedulerOutput(BaseOutput):
52
+ prev_sample: torch.FloatTensor
53
+
54
+
55
+ def _expand_t_like_x(t, x):
56
+ dims = [1] * (len(x.size()) - 1)
57
+ return t.view(t.size(0), *dims)
58
+
59
+
60
+ class _ICPlan:
61
+ def compute_alpha_t(self, t):
62
+ return t, 1
63
+
64
+ def compute_sigma_t(self, t):
65
+ return 1 - t, -1
66
+
67
+ def compute_d_alpha_alpha_ratio_t(self, t):
68
+ return 1 / t
69
+
70
+ def compute_diffusion(self, x, t, form="constant", norm=1.0):
71
+ t = _expand_t_like_x(t, x)
72
+ choices = {
73
+ "constant": norm,
74
+ "SBDM": norm * self._compute_drift(x, t)[1],
75
+ "sigma": norm * self.compute_sigma_t(t)[0],
76
+ "linear": norm * (1 - t),
77
+ "decreasing": 0.25 * (norm * torch.cos(np.pi * t) + 1) ** 2,
78
+ "increasing-decreasing": norm * torch.sin(np.pi * t) ** 2,
79
+ }
80
+ return choices[form]
81
+
82
+ def _compute_drift(self, x, t):
83
+ t = _expand_t_like_x(t, x)
84
+ alpha_ratio = self.compute_d_alpha_alpha_ratio_t(t)
85
+ sigma_t, d_sigma_t = self.compute_sigma_t(t)
86
+ drift = alpha_ratio * x
87
+ diffusion = alpha_ratio * (sigma_t**2) - sigma_t * d_sigma_t
88
+ return -drift, diffusion
89
+
90
+ def get_score_from_velocity(self, velocity, x, t):
91
+ t = _expand_t_like_x(t, x)
92
+ alpha_t, d_alpha_t = self.compute_alpha_t(t)
93
+ sigma_t, d_sigma_t = self.compute_sigma_t(t)
94
+ mean = x
95
+ reverse_alpha_ratio = alpha_t / d_alpha_t
96
+ var = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t
97
+ score = (reverse_alpha_ratio * velocity - mean) / torch.clamp(var, min=1e-8)
98
+ # At t=1 the variance vanishes; SDE drift reduces to pure velocity.
99
+ score = torch.where(var.abs() < 1e-6, torch.zeros_like(score), score)
100
+ return score
101
+
102
+
103
+ class SelfFlowFlowMatchScheduler(SchedulerMixin, ConfigMixin):
104
+ """
105
+ Flow-matching SDE scheduler used by Self-Flow ImageNet models.
106
+ """
107
+
108
+ config_name = "scheduler_config.json"
109
+
110
+ @register_to_config
111
+ def __init__(
112
+ self,
113
+ num_train_timesteps: int = 1000,
114
+ path_type: str = "Linear",
115
+ prediction: str = "velocity",
116
+ sampling_method: str = "Euler",
117
+ diffusion_form: str = "sigma",
118
+ diffusion_norm: float = 1.0,
119
+ last_step: str = "Mean",
120
+ last_step_size: float = 0.04,
121
+ reverse: bool = True,
122
+ ):
123
+ self.num_train_timesteps = num_train_timesteps
124
+ self.path_sampler = _ICPlan()
125
+ self.timesteps: Optional[torch.Tensor] = None
126
+ self.sigmas: Optional[torch.Tensor] = None
127
+ self._step_index = 0
128
+ self._dt = 1.0
129
+ self._mean_sample: Optional[torch.Tensor] = None
130
+
131
+ def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
132
+ t0, t1 = 0.0, 1.0
133
+ timesteps = torch.linspace(t0, t1, num_inference_steps, device=device)
134
+ self.timesteps = timesteps
135
+ self.sigmas = 1.0 - timesteps
136
+ self.num_inference_steps = num_inference_steps
137
+ self._step_index = 0
138
+ if len(timesteps) > 1:
139
+ self._dt = float(timesteps[1] - timesteps[0])
140
+ else:
141
+ self._dt = 1.0
142
+ self._mean_sample = None
143
+
144
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[int, torch.Tensor]) -> torch.Tensor:
145
+ del timestep
146
+ return sample
147
+
148
+ def _velocity_drift(self, velocity: torch.Tensor) -> torch.Tensor:
149
+ return velocity
150
+
151
+ def _sde_drift(self, sample: torch.Tensor, timestep: torch.Tensor, velocity: torch.Tensor) -> torch.Tensor:
152
+ diffusion = self.path_sampler.compute_diffusion(
153
+ sample,
154
+ timestep,
155
+ form=self.config.diffusion_form,
156
+ norm=self.config.diffusion_norm,
157
+ )
158
+ score = self.path_sampler.get_score_from_velocity(velocity, sample, timestep)
159
+ return self._velocity_drift(velocity) + diffusion * score
160
+
161
+ def _prepare_timestep(self, timestep: Union[float, torch.Tensor], sample: torch.Tensor) -> torch.Tensor:
162
+ if not torch.is_tensor(timestep):
163
+ timestep = torch.tensor([timestep], device=sample.device, dtype=sample.dtype)
164
+ if timestep.ndim == 0:
165
+ timestep = timestep.unsqueeze(0)
166
+ if timestep.numel() == 1:
167
+ timestep = timestep.expand(sample.shape[0])
168
+ return timestep.to(device=sample.device, dtype=sample.dtype)
169
+
170
+ def step(
171
+ self,
172
+ model_output: torch.Tensor,
173
+ timestep: Union[float, torch.Tensor],
174
+ sample: torch.Tensor,
175
+ generator: Optional[torch.Generator] = None,
176
+ return_dict: bool = True,
177
+ ) -> Union[SelfFlowFlowMatchSchedulerOutput, Tuple[torch.Tensor]]:
178
+ if self.timesteps is None:
179
+ raise ValueError("Call `set_timesteps` before `step`.")
180
+
181
+ timestep_tensor = self._prepare_timestep(timestep, sample)
182
+ velocity = model_output.to(torch.float32)
183
+ sample = sample.to(torch.float32)
184
+
185
+ is_last = self._step_index >= len(self.timesteps) - 1
186
+ if is_last and self.config.last_step is not None and self.config.last_step_size > 0:
187
+ drift = self._sde_drift(sample, timestep_tensor, velocity)
188
+ if self.config.last_step == "Mean":
189
+ sample = sample + drift * self.config.last_step_size
190
+ elif self.config.last_step == "Euler":
191
+ sample = sample + self._velocity_drift(velocity) * self.config.last_step_size
192
+ self._step_index += 1
193
+ elif not is_last:
194
+ if self.config.sampling_method == "Euler":
195
+ if self._mean_sample is None:
196
+ self._mean_sample = sample
197
+ noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype)
198
+ dw = noise * math.sqrt(self._dt)
199
+ drift = self._sde_drift(sample, timestep_tensor, velocity)
200
+ diffusion = self.path_sampler.compute_diffusion(
201
+ sample,
202
+ timestep_tensor,
203
+ form=self.config.diffusion_form,
204
+ norm=self.config.diffusion_norm,
205
+ )
206
+ self._mean_sample = sample + drift * self._dt
207
+ sample = self._mean_sample + torch.sqrt(2 * diffusion) * dw
208
+ elif self.config.sampling_method == "Heun":
209
+ noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype)
210
+ dw = noise * math.sqrt(self._dt)
211
+ t_cur = timestep_tensor
212
+ diffusion = self.path_sampler.compute_diffusion(
213
+ sample,
214
+ t_cur,
215
+ form=self.config.diffusion_form,
216
+ norm=self.config.diffusion_norm,
217
+ )
218
+ xhat = sample + torch.sqrt(2 * diffusion) * dw
219
+ k1 = self._sde_drift(xhat, t_cur, velocity)
220
+ xp = xhat + self._dt * k1
221
+ k2 = self._sde_drift(xp, t_cur + self._dt, velocity)
222
+ sample = xhat + 0.5 * self._dt * (k1 + k2)
223
+ self._mean_sample = xhat
224
+ else:
225
+ raise NotImplementedError(f"Sampling method {self.config.sampling_method} is not implemented.")
226
+ self._step_index += 1
227
+ else:
228
+ self._step_index += 1
229
+
230
+ prev_sample = sample
231
+ if not return_dict:
232
+ return (prev_sample,)
233
+ return SelfFlowFlowMatchSchedulerOutput(prev_sample=prev_sample)
Self-Flow-XL-2-256/transformer/config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "SelfFlowTransformer2DModel",
3
+ "class_dropout_prob": 0.0,
4
+ "depth": 28,
5
+ "hidden_size": 1152,
6
+ "in_channels": 4,
7
+ "input_size": 32,
8
+ "learn_sigma": true,
9
+ "mlp_ratio": 4.0,
10
+ "num_classes": 1001,
11
+ "num_heads": 16,
12
+ "patch_size": 2,
13
+ "per_token_timestep": true
14
+ }
Self-Flow-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:f78e3ba96474e7466f20aa8af40ffaa88248fb61afb19158606357565b530359
3
+ size 2721795664
Self-Flow-XL-2-256/transformer/transformer_selfflow.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+
5
+ from __future__ import annotations
6
+
7
+ import collections.abc
8
+ import math
9
+ from dataclasses import dataclass
10
+ from itertools import repeat
11
+ from typing import Optional, Tuple, Union
12
+
13
+ import numpy as np
14
+ import torch
15
+ import torch.nn as nn
16
+ from einops import rearrange
17
+ from timm.models.vision_transformer import Attention, Mlp
18
+
19
+ try:
20
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
21
+ from diffusers.models.modeling_utils import ModelMixin
22
+ from diffusers.utils import BaseOutput
23
+ except Exception: # pragma: no cover
24
+ class BaseOutput(dict):
25
+ def __post_init__(self):
26
+ self.update(self.__dict__)
27
+
28
+ class _Config(dict):
29
+ def __getattr__(self, key):
30
+ try:
31
+ return self[key]
32
+ except KeyError as error:
33
+ raise AttributeError(key) from error
34
+
35
+ class ConfigMixin:
36
+ config_name = "config.json"
37
+
38
+ class ModelMixin(nn.Module):
39
+ pass
40
+
41
+ def register_to_config(init):
42
+ def wrapper(self, *args, **kwargs):
43
+ import inspect
44
+
45
+ signature = inspect.signature(init)
46
+ bound = signature.bind(self, *args, **kwargs)
47
+ bound.apply_defaults()
48
+ self.config = _Config({key: value for key, value in bound.arguments.items() if key != "self"})
49
+ init(self, *args, **kwargs)
50
+
51
+ return wrapper
52
+
53
+
54
+ def _ntuple(n):
55
+ def parse(x):
56
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
57
+ return tuple(x)
58
+ return tuple(repeat(x, n))
59
+
60
+ return parse
61
+
62
+
63
+ to_2tuple = _ntuple(2)
64
+
65
+
66
+ @dataclass
67
+ class SelfFlowTransformer2DModelOutput(BaseOutput):
68
+ sample: torch.FloatTensor
69
+
70
+
71
+ class PatchedPatchEmbed(nn.Module):
72
+ def __init__(
73
+ self,
74
+ img_size: int = 224,
75
+ patch_size: int = 16,
76
+ in_chans: int = 3,
77
+ embed_dim: int = 768,
78
+ bias: bool = True,
79
+ ):
80
+ super().__init__()
81
+ self.patch_size = to_2tuple(patch_size)
82
+ img_size = to_2tuple(img_size)
83
+ self.grid_size = (
84
+ img_size[0] // self.patch_size[0],
85
+ img_size[1] // self.patch_size[1],
86
+ )
87
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
88
+ patch_dim = self.patch_size[0] * self.patch_size[1] * in_chans
89
+ self.proj = nn.Linear(patch_dim, embed_dim, bias=bias)
90
+
91
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
92
+ return self.proj(x)
93
+
94
+
95
+ def modulate(x, shift, scale):
96
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
97
+
98
+
99
+ def modulate_per_token(x, shift, scale):
100
+ return x * (1 + scale) + shift
101
+
102
+
103
+ class TimestepEmbedder(nn.Module):
104
+ def __init__(self, hidden_size, frequency_embedding_size=256):
105
+ super().__init__()
106
+ self.mlp = nn.Sequential(
107
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
108
+ nn.SiLU(),
109
+ nn.Linear(hidden_size, hidden_size, bias=True),
110
+ )
111
+ self.frequency_embedding_size = frequency_embedding_size
112
+
113
+ @staticmethod
114
+ def timestep_embedding(t, dim, max_period=10000):
115
+ half = dim // 2
116
+ freqs = torch.exp(
117
+ -math.log(max_period)
118
+ * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device)
119
+ / half
120
+ )
121
+ args = t[:, None].float() * freqs[None]
122
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
123
+ if dim % 2:
124
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
125
+ return embedding
126
+
127
+ def forward(self, t):
128
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
129
+ t_freq = t_freq.to(dtype=self.mlp[0].weight.dtype)
130
+ return self.mlp(t_freq)
131
+
132
+
133
+ class LabelEmbedder(nn.Module):
134
+ def __init__(self, num_classes, hidden_size, dropout_prob):
135
+ super().__init__()
136
+ use_cfg_embedding = dropout_prob > 0
137
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
138
+ self.num_classes = num_classes
139
+ self.dropout_prob = dropout_prob
140
+
141
+ def token_drop(self, labels, force_drop_ids=None):
142
+ if force_drop_ids is None:
143
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
144
+ else:
145
+ drop_ids = force_drop_ids == 1
146
+ return torch.where(drop_ids, self.num_classes, labels)
147
+
148
+ def forward(self, labels, train, force_drop_ids=None):
149
+ use_dropout = self.dropout_prob > 0
150
+ if (train and use_dropout) or (force_drop_ids is not None):
151
+ labels = self.token_drop(labels, force_drop_ids)
152
+ return self.embedding_table(labels)
153
+
154
+
155
+ class DiTBlock(nn.Module):
156
+ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):
157
+ super().__init__()
158
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
159
+ self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)
160
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
161
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
162
+ approx_gelu = lambda: nn.GELU(approximate="tanh")
163
+ self.mlp = Mlp(
164
+ in_features=hidden_size,
165
+ hidden_features=mlp_hidden_dim,
166
+ act_layer=approx_gelu,
167
+ drop=0,
168
+ )
169
+ self.adaLN_modulation = nn.Sequential(
170
+ nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True)
171
+ )
172
+
173
+ def forward(self, x, c):
174
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(
175
+ 6, dim=1
176
+ )
177
+ x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa))
178
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
179
+ return x
180
+
181
+
182
+ class PerTokenDiTBlock(DiTBlock):
183
+ def forward(self, x, c):
184
+ batch_size, seq_len, hidden_dim = c.shape
185
+ c_flat = c.reshape(-1, hidden_dim)
186
+ modulation_flat = self.adaLN_modulation(c_flat)
187
+ modulation = modulation_flat.reshape(batch_size, seq_len, -1)
188
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = modulation.chunk(6, dim=-1)
189
+ x = x + gate_msa * self.attn(modulate_per_token(self.norm1(x), shift_msa, scale_msa))
190
+ x = x + gate_mlp * self.mlp(modulate_per_token(self.norm2(x), shift_mlp, scale_mlp))
191
+ return x
192
+
193
+
194
+ class FinalLayer(nn.Module):
195
+ def __init__(self, hidden_size, patch_size, out_channels):
196
+ super().__init__()
197
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
198
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
199
+ self.adaLN_modulation = nn.Sequential(
200
+ nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True)
201
+ )
202
+
203
+ def forward(self, x, c):
204
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
205
+ x = modulate(self.norm_final(x), shift, scale)
206
+ return self.linear(x)
207
+
208
+
209
+ class PerTokenFinalLayer(FinalLayer):
210
+ def forward(self, x, c):
211
+ batch_size, seq_len, hidden_dim = c.shape
212
+ c_flat = c.reshape(-1, hidden_dim)
213
+ modulation_flat = self.adaLN_modulation(c_flat)
214
+ modulation = modulation_flat.reshape(batch_size, seq_len, -1)
215
+ shift, scale = modulation.chunk(2, dim=-1)
216
+ x = modulate_per_token(self.norm_final(x), shift, scale)
217
+ return self.linear(x)
218
+
219
+
220
+ class SimpleHead(nn.Module):
221
+ def __init__(self, in_dim, out_dim):
222
+ super().__init__()
223
+ self.linear1 = nn.Linear(in_dim, in_dim + out_dim)
224
+ self.linear2 = nn.Linear(in_dim + out_dim, out_dim)
225
+ self.act = nn.SiLU()
226
+
227
+ def forward(self, x):
228
+ x = self.linear1(x)
229
+ return self.linear2(self.act(x))
230
+
231
+
232
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
233
+ grid_h = np.arange(grid_size, dtype=np.float32)
234
+ grid_w = np.arange(grid_size, dtype=np.float32)
235
+ grid = np.meshgrid(grid_w, grid_h)
236
+ grid = np.stack(grid, axis=0)
237
+ grid = grid.reshape([2, 1, grid_size, grid_size])
238
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
239
+ if cls_token and extra_tokens > 0:
240
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
241
+ return pos_embed
242
+
243
+
244
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
245
+ assert embed_dim % 2 == 0
246
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])
247
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])
248
+ return np.concatenate([emb_h, emb_w], axis=1)
249
+
250
+
251
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
252
+ assert embed_dim % 2 == 0
253
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
254
+ omega /= embed_dim / 2.0
255
+ omega = 1.0 / 10000**omega
256
+ pos = pos.reshape(-1)
257
+ out = np.einsum("m,d->md", pos, omega)
258
+ return np.concatenate([np.sin(out), np.cos(out)], axis=1)
259
+
260
+
261
+ class SelfFlowTransformer2DModel(ModelMixin, ConfigMixin):
262
+ """
263
+ Self-Flow diffusion transformer with per-token timestep conditioning (SiT-XL/2).
264
+ """
265
+
266
+ config_name = "config.json"
267
+
268
+ @register_to_config
269
+ def __init__(
270
+ self,
271
+ input_size: int = 32,
272
+ patch_size: int = 2,
273
+ in_channels: int = 4,
274
+ hidden_size: int = 1152,
275
+ depth: int = 28,
276
+ num_heads: int = 16,
277
+ mlp_ratio: float = 4.0,
278
+ num_classes: int = 1001,
279
+ class_dropout_prob: float = 0.0,
280
+ learn_sigma: bool = True,
281
+ per_token_timestep: bool = True,
282
+ ):
283
+ super().__init__()
284
+ self.learn_sigma = learn_sigma
285
+ self.in_channels = in_channels
286
+ self.out_channels = in_channels * 2 if learn_sigma else in_channels
287
+ self.patch_size = patch_size
288
+ self.num_heads = num_heads
289
+ self.per_token_timestep = per_token_timestep
290
+
291
+ self.x_embedder = PatchedPatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)
292
+ self.t_embedder = TimestepEmbedder(hidden_size)
293
+ self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
294
+
295
+ num_patches = self.x_embedder.num_patches
296
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
297
+
298
+ block_cls = PerTokenDiTBlock if per_token_timestep else DiTBlock
299
+ self.blocks = nn.ModuleList(
300
+ [block_cls(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)]
301
+ )
302
+ final_cls = PerTokenFinalLayer if per_token_timestep else FinalLayer
303
+ self.final_layer = final_cls(hidden_size, patch_size, self.out_channels)
304
+ self.projector = SimpleHead(hidden_size, hidden_size)
305
+
306
+ self.initialize_weights()
307
+
308
+ def initialize_weights(self):
309
+ def _basic_init(module):
310
+ if isinstance(module, nn.Linear):
311
+ torch.nn.init.xavier_uniform_(module.weight)
312
+ if module.bias is not None:
313
+ nn.init.constant_(module.bias, 0)
314
+
315
+ self.apply(_basic_init)
316
+
317
+ pos_embed = get_2d_sincos_pos_embed(
318
+ self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5)
319
+ )
320
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
321
+
322
+ w = self.x_embedder.proj.weight.data
323
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
324
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
325
+
326
+ nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
327
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
328
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
329
+
330
+ for block in self.blocks:
331
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
332
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
333
+
334
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
335
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
336
+ nn.init.constant_(self.final_layer.linear.weight, 0)
337
+ nn.init.constant_(self.final_layer.linear.bias, 0)
338
+
339
+ def shufflechannel(self, x):
340
+ p = self.x_embedder.patch_size[0]
341
+ x = rearrange(x, "b l (p q c) -> b l (c p q)", p=p, q=p, c=self.out_channels)
342
+ if self.learn_sigma:
343
+ x, _ = x.chunk(2, dim=2)
344
+ return x
345
+
346
+ def _embed_forward(
347
+ self,
348
+ hidden_states: torch.Tensor,
349
+ timestep: torch.Tensor,
350
+ class_labels: torch.Tensor,
351
+ ) -> torch.Tensor:
352
+ x = self.x_embedder(hidden_states) + self.pos_embed
353
+ batch_size, seq_len, _ = x.shape
354
+
355
+ if self.config.per_token_timestep:
356
+ if timestep.ndim == 1:
357
+ t_emb = self.t_embedder(timestep).unsqueeze(1).expand(-1, seq_len, -1)
358
+ elif timestep.ndim == 2:
359
+ t_flat = timestep.reshape(-1)
360
+ t_emb = self.t_embedder(t_flat).reshape(batch_size, seq_len, -1)
361
+ else:
362
+ raise ValueError(f"Timesteps must be 1D or 2D, got shape {timestep.shape}")
363
+ y_emb = self.y_embedder(class_labels, self.training).unsqueeze(1).expand(-1, seq_len, -1)
364
+ conditioning = t_emb + y_emb
365
+ for block in self.blocks:
366
+ x = block(x, conditioning)
367
+ x = self.final_layer(x, conditioning)
368
+ else:
369
+ t_emb = self.t_embedder(timestep)
370
+ y_emb = self.y_embedder(class_labels, self.training)
371
+ conditioning = t_emb + y_emb
372
+ for block in self.blocks:
373
+ x = block(x, conditioning)
374
+ x = self.final_layer(x, conditioning)
375
+ return x
376
+
377
+ def forward(
378
+ self,
379
+ hidden_states: torch.Tensor,
380
+ timestep: Union[torch.Tensor, float],
381
+ class_labels: torch.LongTensor,
382
+ return_dict: bool = True,
383
+ ) -> Union[SelfFlowTransformer2DModelOutput, torch.Tensor]:
384
+ """
385
+ Args:
386
+ hidden_states: Token tensor `(batch, seq_len, patch_dim)` with `patch_dim = in_channels * patch_size^2`.
387
+ timestep: Flow time in `[0, 1]` along the SDE path (noise at 0, data at 1).
388
+ The pipeline passes `1 - flow_time` so that, together with the internal
389
+ `1 - t` remap and output negation, the effective embedder time matches
390
+ the official Self-Flow `reverse=True` sampling convention.
391
+ class_labels: ImageNet class indices (use `num_classes` index for unconditional).
392
+ """
393
+ if not torch.is_tensor(timestep):
394
+ timestep = torch.tensor([timestep], device=hidden_states.device, dtype=hidden_states.dtype)
395
+ timestep = timestep.to(device=hidden_states.device, dtype=hidden_states.dtype)
396
+ if timestep.ndim == 1 and timestep.numel() == 1 and hidden_states.shape[0] > 1:
397
+ timestep = timestep.expand(hidden_states.shape[0])
398
+
399
+ # Match legacy inference convention: model expects noise decreasing from 1 -> 0.
400
+ timestep = 1 - timestep
401
+
402
+ class_labels = class_labels.to(device=hidden_states.device, dtype=torch.long).reshape(-1)
403
+ if class_labels.numel() == 1 and hidden_states.shape[0] > 1:
404
+ class_labels = class_labels.expand(hidden_states.shape[0])
405
+
406
+ sample = self._embed_forward(hidden_states, timestep, class_labels)
407
+ sample = self.shufflechannel(sample)
408
+ sample = -sample
409
+
410
+ if not return_dict:
411
+ return sample
412
+ return SelfFlowTransformer2DModelOutput(sample=sample)
Self-Flow-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
+ }
Self-Flow-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