汐知 commited on
Commit
19a149b
0 Parent(s):
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +143 -0
  2. LICENSE.txt +21 -0
  3. README.md +13 -0
  4. app.py +297 -0
  5. cldm/cldm.py +442 -0
  6. cldm/ddim_hacked.py +318 -0
  7. cldm/hack.py +111 -0
  8. cldm/logger.py +76 -0
  9. cldm/model.py +28 -0
  10. configs/anydoor.yaml +85 -0
  11. configs/datasets.yaml +68 -0
  12. configs/demo.yaml +3 -0
  13. configs/inference.yaml +3 -0
  14. datasets/Preprocess/mvimagenet.txt +0 -0
  15. datasets/Preprocess/uvo_process.py +29 -0
  16. datasets/base.py +220 -0
  17. datasets/data_utils.py +356 -0
  18. datasets/dreambooth.py +84 -0
  19. datasets/dresscode.py +61 -0
  20. datasets/fashiontryon.py +75 -0
  21. datasets/lvis.py +77 -0
  22. datasets/mose.py +94 -0
  23. datasets/mvimagenet.py +81 -0
  24. datasets/saliency_modular.py +91 -0
  25. datasets/sam.py +78 -0
  26. datasets/uvo.py +79 -0
  27. datasets/uvo_val.py +87 -0
  28. datasets/vipseg.py +96 -0
  29. datasets/vitonhd.py +61 -0
  30. datasets/ytb_vis.py +85 -0
  31. datasets/ytb_vos.py +87 -0
  32. dinov2/.github/workflows/lint.yaml +39 -0
  33. dinov2/.gitignore +13 -0
  34. dinov2/CODE_OF_CONDUCT.md +80 -0
  35. dinov2/CONTRIBUTING.md +31 -0
  36. dinov2/LICENSE +400 -0
  37. dinov2/MODEL_CARD.md +201 -0
  38. dinov2/README.md +248 -0
  39. dinov2/conda.yaml +22 -0
  40. dinov2/dinov2/__init__.py +7 -0
  41. dinov2/dinov2/configs/__init__.py +23 -0
  42. dinov2/dinov2/configs/eval/vitb14_pretrain.yaml +6 -0
  43. dinov2/dinov2/configs/eval/vitg14_pretrain.yaml +7 -0
  44. dinov2/dinov2/configs/eval/vitl14_pretrain.yaml +6 -0
  45. dinov2/dinov2/configs/eval/vits14_pretrain.yaml +6 -0
  46. dinov2/dinov2/configs/ssl_default_config.yaml +115 -0
  47. dinov2/dinov2/configs/train/vitg14.yaml +26 -0
  48. dinov2/dinov2/configs/train/vitl14.yaml +26 -0
  49. dinov2/dinov2/configs/train/vitl16_short.yaml +6 -0
  50. dinov2/dinov2/data/__init__.py +11 -0
.gitignore ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .idea/
2
+ examples/
3
+ training/
4
+ lightning_logs/
5
+ image_log/
6
+
7
+ *.pth
8
+ *.pt
9
+ *.ckpt
10
+ *.safetensors
11
+
12
+ gradio_pose2image_private.py
13
+ gradio_canny2image_private.py
14
+
15
+ # Byte-compiled / optimized / DLL files
16
+ __pycache__/
17
+ *.py[cod]
18
+ *$py.class
19
+
20
+ # C extensions
21
+ *.so
22
+
23
+ # Distribution / packaging
24
+ .Python
25
+ build/
26
+ develop-eggs/
27
+ dist/
28
+ downloads/
29
+ eggs/
30
+ .eggs/
31
+ lib/
32
+ lib64/
33
+ parts/
34
+ sdist/
35
+ var/
36
+ wheels/
37
+ pip-wheel-metadata/
38
+ share/python-wheels/
39
+ *.egg-info/
40
+ .installed.cfg
41
+ *.egg
42
+ MANIFEST
43
+
44
+ # PyInstaller
45
+ # Usually these files are written by a python script from a template
46
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
47
+ *.manifest
48
+ *.spec
49
+
50
+ # Installer logs
51
+ pip-log.txt
52
+ pip-delete-this-directory.txt
53
+
54
+ # Unit test / coverage reports
55
+ htmlcov/
56
+ .tox/
57
+ .nox/
58
+ .coverage
59
+ .coverage.*
60
+ .cache
61
+ nosetests.xml
62
+ coverage.xml
63
+ *.cover
64
+ *.py,cover
65
+ .hypothesis/
66
+ .pytest_cache/
67
+
68
+ # Translations
69
+ *.mo
70
+ *.pot
71
+
72
+ # Django stuff:
73
+ *.log
74
+ local_settings.py
75
+ db.sqlite3
76
+ db.sqlite3-journal
77
+
78
+ # Flask stuff:
79
+ instance/
80
+ .webassets-cache
81
+
82
+ # Scrapy stuff:
83
+ .scrapy
84
+
85
+ # Sphinx documentation
86
+ docs/_build/
87
+
88
+ # PyBuilder
89
+ target/
90
+
91
+ # Jupyter Notebook
92
+ .ipynb_checkpoints
93
+
94
+ # IPython
95
+ profile_default/
96
+ ipython_config.py
97
+
98
+ # pyenv
99
+ .python-version
100
+
101
+ # pipenv
102
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
103
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
104
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
105
+ # install all needed dependencies.
106
+ #Pipfile.lock
107
+
108
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
109
+ __pypackages__/
110
+
111
+ # Celery stuff
112
+ celerybeat-schedule
113
+ celerybeat.pid
114
+
115
+ # SageMath parsed files
116
+ *.sage.py
117
+
118
+ # Environments
119
+ .env
120
+ .venv
121
+ env/
122
+ venv/
123
+ ENV/
124
+ env.bak/
125
+ venv.bak/
126
+
127
+ # Spyder project settings
128
+ .spyderproject
129
+ .spyproject
130
+
131
+ # Rope project settings
132
+ .ropeproject
133
+
134
+ # mkdocs documentation
135
+ /site
136
+
137
+ # mypy
138
+ .mypy_cache/
139
+ .dmypy.json
140
+ dmypy.json
141
+
142
+ # Pyre type checker
143
+ .pyre/
LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DAMO Vision Intelligence Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: AnyDoor Online
3
+ emoji: 👁
4
+ colorFrom: green
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 4.12.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import einops
3
+ import numpy as np
4
+ import torch
5
+ import random
6
+ import gradio as gr
7
+ import os
8
+ import albumentations as A
9
+ from PIL import Image
10
+ import torchvision.transforms as T
11
+ from datasets.data_utils import *
12
+ from cldm.model import create_model, load_state_dict
13
+ from cldm.ddim_hacked import DDIMSampler
14
+ from omegaconf import OmegaConf
15
+ from cldm.hack import disable_verbosity, enable_sliced_attention
16
+ from huggingface_hub import snapshot_download
17
+
18
+ snapshot_download(repo_id="xichenhku/AnyDoor_models", local_dir="./AnyDoor_models")
19
+
20
+
21
+ cv2.setNumThreads(0)
22
+ cv2.ocl.setUseOpenCL(False)
23
+
24
+ save_memory = False
25
+ disable_verbosity()
26
+ if save_memory:
27
+ enable_sliced_attention()
28
+
29
+
30
+ config = OmegaConf.load('./configs/demo.yaml')
31
+ model_ckpt = config.pretrained_model
32
+ model_config = config.config_file
33
+
34
+
35
+
36
+
37
+ model = create_model(model_config ).cpu()
38
+ model.load_state_dict(load_state_dict(model_ckpt, location='cuda'))
39
+ model = model.cuda()
40
+ ddim_sampler = DDIMSampler(model)
41
+
42
+
43
+ def crop_back( pred, tar_image, extra_sizes, tar_box_yyxx_crop):
44
+ H1, W1, H2, W2 = extra_sizes
45
+ y1,y2,x1,x2 = tar_box_yyxx_crop
46
+ pred = cv2.resize(pred, (W2, H2))
47
+ m = 3 # maigin_pixel
48
+
49
+ if W1 == H1:
50
+ tar_image[y1+m :y2-m, x1+m:x2-m, :] = pred[m:-m, m:-m]
51
+ return tar_image
52
+
53
+ if W1 < W2:
54
+ pad1 = int((W2 - W1) / 2)
55
+ pad2 = W2 - W1 - pad1
56
+ pred = pred[:,pad1: -pad2, :]
57
+ else:
58
+ pad1 = int((H2 - H1) / 2)
59
+ pad2 = H2 - H1 - pad1
60
+ pred = pred[pad1: -pad2, :, :]
61
+ tar_image[y1+m :y2-m, x1+m:x2-m, :] = pred[m:-m, m:-m]
62
+ return tar_image
63
+
64
+
65
+ def inference_single_image(ref_image,
66
+ ref_mask,
67
+ tar_image,
68
+ tar_mask,
69
+ num_samples,
70
+ strength,
71
+ ddim_steps,
72
+ scale,
73
+ seed,
74
+ ):
75
+ raw_background = tar_image.copy()
76
+ item = process_pairs(ref_image, ref_mask, tar_image, tar_mask)
77
+
78
+ ref = item['ref']
79
+ hint = item['hint']
80
+ num_samples = 1
81
+
82
+ control = torch.from_numpy(hint.copy()).float().cuda()
83
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
84
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
85
+
86
+
87
+ clip_input = torch.from_numpy(ref.copy()).float().cuda()
88
+ clip_input = torch.stack([clip_input for _ in range(num_samples)], dim=0)
89
+ clip_input = einops.rearrange(clip_input, 'b h w c -> b c h w').clone()
90
+
91
+ H,W = 512,512
92
+
93
+ cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning( clip_input )]}
94
+ un_cond = {"c_concat": [control],
95
+ "c_crossattn": [model.get_learned_conditioning([torch.zeros((1,3,224,224))] * num_samples)]}
96
+ shape = (4, H // 8, W // 8)
97
+
98
+ if save_memory:
99
+ model.low_vram_shift(is_diffusing=True)
100
+
101
+ model.control_scales = ([strength] * 13)
102
+ samples, _ = ddim_sampler.sample(ddim_steps, num_samples,
103
+ shape, cond, verbose=False, eta=0,
104
+ unconditional_guidance_scale=scale,
105
+ unconditional_conditioning=un_cond)
106
+
107
+ if save_memory:
108
+ model.low_vram_shift(is_diffusing=False)
109
+
110
+ x_samples = model.decode_first_stage(samples)
111
+ x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy()
112
+
113
+ result = x_samples[0][:,:,::-1]
114
+ result = np.clip(result,0,255)
115
+
116
+ pred = x_samples[0]
117
+ pred = np.clip(pred,0,255)[1:,:,:]
118
+ sizes = item['extra_sizes']
119
+ tar_box_yyxx_crop = item['tar_box_yyxx_crop']
120
+ tar_image = crop_back(pred, tar_image, sizes, tar_box_yyxx_crop)
121
+
122
+ # keep background unchanged
123
+ y1,y2,x1,x2 = item['tar_box_yyxx']
124
+ raw_background[y1:y2, x1:x2, :] = tar_image[y1:y2, x1:x2, :]
125
+ return raw_background
126
+
127
+
128
+ def process_pairs(ref_image, ref_mask, tar_image, tar_mask, max_ratio = 0.8):
129
+ # ========= Reference ===========
130
+ # ref expand
131
+ ref_box_yyxx = get_bbox_from_mask(ref_mask)
132
+
133
+ # ref filter mask
134
+ ref_mask_3 = np.stack([ref_mask,ref_mask,ref_mask],-1)
135
+ masked_ref_image = ref_image * ref_mask_3 + np.ones_like(ref_image) * 255 * (1-ref_mask_3)
136
+
137
+ y1,y2,x1,x2 = ref_box_yyxx
138
+ masked_ref_image = masked_ref_image[y1:y2,x1:x2,:]
139
+ ref_mask = ref_mask[y1:y2,x1:x2]
140
+
141
+ ratio = np.random.randint(11, 15) / 10 #11,13
142
+ masked_ref_image, ref_mask = expand_image_mask(masked_ref_image, ref_mask, ratio=ratio)
143
+ ref_mask_3 = np.stack([ref_mask,ref_mask,ref_mask],-1)
144
+
145
+ # to square and resize
146
+ masked_ref_image = pad_to_square(masked_ref_image, pad_value = 255, random = False)
147
+ masked_ref_image = cv2.resize(masked_ref_image.astype(np.uint8), (224,224) ).astype(np.uint8)
148
+
149
+ ref_mask_3 = pad_to_square(ref_mask_3 * 255, pad_value = 0, random = False)
150
+ ref_mask_3 = cv2.resize(ref_mask_3.astype(np.uint8), (224,224) ).astype(np.uint8)
151
+ ref_mask = ref_mask_3[:,:,0]
152
+
153
+ # collage aug
154
+ masked_ref_image_compose, ref_mask_compose = masked_ref_image, ref_mask
155
+ ref_mask_3 = np.stack([ref_mask_compose,ref_mask_compose,ref_mask_compose],-1)
156
+ ref_image_collage = sobel(masked_ref_image_compose, ref_mask_compose/255)
157
+
158
+ # ========= Target ===========
159
+ tar_box_yyxx = get_bbox_from_mask(tar_mask)
160
+ tar_box_yyxx = expand_bbox(tar_mask, tar_box_yyxx, ratio=[1.1,1.2]) #1.1 1.3
161
+ tar_box_yyxx_full = tar_box_yyxx
162
+
163
+ # crop
164
+ tar_box_yyxx_crop = expand_bbox(tar_image, tar_box_yyxx, ratio=[1.3, 3.0])
165
+ tar_box_yyxx_crop = box2squre(tar_image, tar_box_yyxx_crop) # crop box
166
+ y1,y2,x1,x2 = tar_box_yyxx_crop
167
+
168
+ cropped_target_image = tar_image[y1:y2,x1:x2,:]
169
+ cropped_tar_mask = tar_mask[y1:y2,x1:x2]
170
+
171
+ tar_box_yyxx = box_in_box(tar_box_yyxx, tar_box_yyxx_crop)
172
+ y1,y2,x1,x2 = tar_box_yyxx
173
+
174
+ # collage
175
+ ref_image_collage = cv2.resize(ref_image_collage.astype(np.uint8), (x2-x1, y2-y1))
176
+ ref_mask_compose = cv2.resize(ref_mask_compose.astype(np.uint8), (x2-x1, y2-y1))
177
+ ref_mask_compose = (ref_mask_compose > 128).astype(np.uint8)
178
+
179
+ collage = cropped_target_image.copy()
180
+ collage[y1:y2,x1:x2,:] = ref_image_collage
181
+
182
+ collage_mask = cropped_target_image.copy() * 0.0
183
+ collage_mask[y1:y2,x1:x2,:] = 1.0
184
+ collage_mask = np.stack([cropped_tar_mask,cropped_tar_mask,cropped_tar_mask],-1)
185
+
186
+ # the size before pad
187
+ H1, W1 = collage.shape[0], collage.shape[1]
188
+
189
+ cropped_target_image = pad_to_square(cropped_target_image, pad_value = 0, random = False).astype(np.uint8)
190
+ collage = pad_to_square(collage, pad_value = 0, random = False).astype(np.uint8)
191
+ collage_mask = pad_to_square(collage_mask, pad_value = 0, random = False).astype(np.uint8)
192
+
193
+ # the size after pad
194
+ H2, W2 = collage.shape[0], collage.shape[1]
195
+
196
+ cropped_target_image = cv2.resize(cropped_target_image.astype(np.uint8), (512,512)).astype(np.float32)
197
+ collage = cv2.resize(collage.astype(np.uint8), (512,512)).astype(np.float32)
198
+ collage_mask = (cv2.resize(collage_mask.astype(np.uint8), (512,512)).astype(np.float32) > 0.5).astype(np.float32)
199
+
200
+ masked_ref_image = masked_ref_image / 255
201
+ cropped_target_image = cropped_target_image / 127.5 - 1.0
202
+ collage = collage / 127.5 - 1.0
203
+ collage = np.concatenate([collage, collage_mask[:,:,:1] ] , -1)
204
+
205
+ item = dict(ref=masked_ref_image.copy(), jpg=cropped_target_image.copy(), hint=collage.copy(),
206
+ extra_sizes=np.array([H1, W1, H2, W2]),
207
+ tar_box_yyxx_crop=np.array( tar_box_yyxx_crop ),
208
+ tar_box_yyxx=np.array(tar_box_yyxx_full),
209
+ )
210
+ return item
211
+
212
+
213
+ ref_dir='./examples/Gradio/FG'
214
+ image_dir='./examples/Gradio/BG'
215
+ ref_list=[os.path.join(ref_dir,file) for file in os.listdir(ref_dir) if '.jpg' in file or '.png' in file or '.jpeg' in file ]
216
+ ref_list.sort()
217
+ image_list=[os.path.join(image_dir,file) for file in os.listdir(image_dir) if '.jpg' in file or '.png' in file or '.jpeg' in file]
218
+ image_list.sort()
219
+
220
+ def mask_image(image, mask):
221
+ blanc = np.ones_like(image) * 255
222
+ mask = np.stack([mask,mask,mask],-1) / 255
223
+ masked_image = mask * ( 0.5 * blanc + 0.5 * image) + (1-mask) * image
224
+ return masked_image.astype(np.uint8)
225
+
226
+ def run_local(base,
227
+ ref,
228
+ *args):
229
+ image = base["image"].convert("RGB")
230
+ mask = base["mask"].convert("L")
231
+ ref_image = ref["image"].convert("RGB")
232
+ ref_mask = ref["mask"].convert("L")
233
+ image = np.asarray(image)
234
+ mask = np.asarray(mask)
235
+ mask = np.where(mask > 128, 255, 0).astype(np.uint8)
236
+ ref_image = np.asarray(ref_image)
237
+ ref_mask = np.asarray(ref_mask)
238
+ ref_mask = np.where(ref_mask > 128, 1, 0).astype(np.uint8)
239
+
240
+ processed_item = process_pairs(ref_image.copy(), ref_mask.copy(), image.copy(), mask.copy(), max_ratio = 0.8)
241
+ masked_ref = (processed_item['ref']*255)
242
+
243
+ mased_image = mask_image(image, mask)
244
+ #synthesis = image
245
+ synthesis = inference_single_image(ref_image.copy(), ref_mask.copy(), image.copy(), mask.copy(), *args)
246
+ synthesis = torch.from_numpy(synthesis).permute(2, 0, 1)
247
+ synthesis = synthesis.permute(1, 2, 0).numpy()
248
+
249
+ masked_ref = cv2.resize(masked_ref.astype(np.uint8), (512,512))
250
+ return [synthesis]
251
+
252
+
253
+
254
+ with gr.Blocks() as demo:
255
+ with gr.Column():
256
+ gr.Markdown("# Play with AnyDoor to Teleport your Target Objects! ")
257
+ with gr.Row():
258
+ baseline_gallery = gr.Gallery(label='Output', show_label=True, elem_id="gallery", columns=1, height=768)
259
+ with gr.Accordion("Advanced Option", open=True):
260
+ num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
261
+ strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
262
+ ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=30, step=1)
263
+ scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=5.0, step=0.1)
264
+ seed = gr.Slider(label="Seed", minimum=-1, maximum=999999999, step=1, value=-1)
265
+ gr.Markdown(" Higher guidance-scale makes higher fidelity, while lower guidance-scale leads to more harmonized blending.")
266
+
267
+
268
+
269
+
270
+
271
+ gr.Markdown("# Upload / Select Images for the Background (left) and Reference Object (right)")
272
+ gr.Markdown("### Your could draw coarse masks on the background to indicate the desired location and shape.")
273
+ gr.Markdown("### <u>Do not forget</u> to annotate the target object on the reference image.")
274
+ with gr.Row():
275
+ base = gr.Image(label="Background", source="upload", tool="sketch", type="pil", height=512, brush_color='#FFFFFF', mask_opacity=0.5)
276
+ ref = gr.Image(label="Reference", source="upload", tool="sketch", type="pil", height=512, brush_color='#FFFFFF', mask_opacity=0.5)
277
+ run_local_button = gr.Button(label="Generate", value="Run")
278
+
279
+ with gr.Row():
280
+ with gr.Column():
281
+ gr.Examples(image_list, inputs=[base],label="Examples - Background Image",examples_per_page=16)
282
+ with gr.Column():
283
+ gr.Examples(ref_list, inputs=[ref],label="Examples - Reference Object",examples_per_page=16)
284
+
285
+ run_local_button.click(fn=run_local,
286
+ inputs=[base,
287
+ ref,
288
+ num_samples,
289
+ strength,
290
+ ddim_steps,
291
+ scale,
292
+ seed,
293
+ ],
294
+ outputs=[baseline_gallery]
295
+ )
296
+
297
+ demo.launch(server_name="0.0.0.0")
cldm/cldm.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import einops
2
+ import torch
3
+ import torch as th
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from ldm.modules.diffusionmodules.util import (
7
+ conv_nd,
8
+ linear,
9
+ zero_module,
10
+ timestep_embedding,
11
+ )
12
+ from einops import rearrange, repeat
13
+ from torchvision.utils import make_grid
14
+ from ldm.modules.attention import SpatialTransformer
15
+ from ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock
16
+ from ldm.models.diffusion.ddpm import LatentDiffusion
17
+ from ldm.util import log_txt_as_img, exists, instantiate_from_config
18
+ from ldm.models.diffusion.ddim import DDIMSampler
19
+
20
+
21
+ class ControlledUnetModel(UNetModel):
22
+ def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs):
23
+ hs = []
24
+ with torch.no_grad():
25
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
26
+ emb = self.time_embed(t_emb)
27
+ h = x.type(self.dtype)
28
+ for module in self.input_blocks:
29
+ h = module(h, emb, context)
30
+ hs.append(h)
31
+ h = self.middle_block(h, emb, context)
32
+
33
+ if control is not None:
34
+ h += control.pop()
35
+
36
+ for i, module in enumerate(self.output_blocks):
37
+ if only_mid_control or control is None:
38
+ h = torch.cat([h, hs.pop()], dim=1)
39
+ else:
40
+ h = torch.cat([h, hs.pop() + control.pop()], dim=1)
41
+ h = module(h, emb, context)
42
+
43
+ h = h.type(x.dtype)
44
+ return self.out(h)
45
+
46
+
47
+ class ControlNet(nn.Module):
48
+ def __init__(
49
+ self,
50
+ image_size,
51
+ in_channels,
52
+ model_channels,
53
+ hint_channels,
54
+ num_res_blocks,
55
+ attention_resolutions,
56
+ dropout=0,
57
+ channel_mult=(1, 2, 4, 8),
58
+ conv_resample=True,
59
+ dims=2,
60
+ use_checkpoint=False,
61
+ use_fp16=False,
62
+ num_heads=-1,
63
+ num_head_channels=-1,
64
+ num_heads_upsample=-1,
65
+ use_scale_shift_norm=False,
66
+ resblock_updown=False,
67
+ use_new_attention_order=False,
68
+ use_spatial_transformer=False, # custom transformer support
69
+ transformer_depth=1, # custom transformer support
70
+ context_dim=None, # custom transformer support
71
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
72
+ legacy=True,
73
+ disable_self_attentions=None,
74
+ num_attention_blocks=None,
75
+ disable_middle_self_attn=False,
76
+ use_linear_in_transformer=False,
77
+ ):
78
+ super().__init__()
79
+ if use_spatial_transformer:
80
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
81
+
82
+ if context_dim is not None:
83
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
84
+ from omegaconf.listconfig import ListConfig
85
+ if type(context_dim) == ListConfig:
86
+ context_dim = list(context_dim)
87
+
88
+ if num_heads_upsample == -1:
89
+ num_heads_upsample = num_heads
90
+
91
+ if num_heads == -1:
92
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
93
+
94
+ if num_head_channels == -1:
95
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
96
+
97
+ self.dims = dims
98
+ self.image_size = image_size
99
+ self.in_channels = in_channels
100
+ self.model_channels = model_channels
101
+ if isinstance(num_res_blocks, int):
102
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
103
+ else:
104
+ if len(num_res_blocks) != len(channel_mult):
105
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
106
+ "as a list/tuple (per-level) with the same length as channel_mult")
107
+ self.num_res_blocks = num_res_blocks
108
+ if disable_self_attentions is not None:
109
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
110
+ assert len(disable_self_attentions) == len(channel_mult)
111
+ if num_attention_blocks is not None:
112
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
113
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
114
+ print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
115
+ f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
116
+ f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
117
+ f"attention will still not be set.")
118
+
119
+ self.attention_resolutions = attention_resolutions
120
+ self.dropout = dropout
121
+ self.channel_mult = channel_mult
122
+ self.conv_resample = conv_resample
123
+ self.use_checkpoint = use_checkpoint
124
+ self.dtype = th.float16 if use_fp16 else th.float32
125
+ self.num_heads = num_heads
126
+ self.num_head_channels = num_head_channels
127
+ self.num_heads_upsample = num_heads_upsample
128
+ self.predict_codebook_ids = n_embed is not None
129
+
130
+ time_embed_dim = model_channels * 4
131
+ self.time_embed = nn.Sequential(
132
+ linear(model_channels, time_embed_dim),
133
+ nn.SiLU(),
134
+ linear(time_embed_dim, time_embed_dim),
135
+ )
136
+
137
+ self.input_blocks = nn.ModuleList(
138
+ [
139
+ TimestepEmbedSequential(
140
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
141
+ )
142
+ ]
143
+ )
144
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
145
+
146
+ self.input_hint_block = TimestepEmbedSequential(
147
+ conv_nd(dims, hint_channels, 16, 3, padding=1),
148
+ nn.SiLU(),
149
+ conv_nd(dims, 16, 16, 3, padding=1),
150
+ nn.SiLU(),
151
+ conv_nd(dims, 16, 32, 3, padding=1, stride=2),
152
+ nn.SiLU(),
153
+ conv_nd(dims, 32, 32, 3, padding=1),
154
+ nn.SiLU(),
155
+ conv_nd(dims, 32, 96, 3, padding=1, stride=2),
156
+ nn.SiLU(),
157
+ conv_nd(dims, 96, 96, 3, padding=1),
158
+ nn.SiLU(),
159
+ conv_nd(dims, 96, 256, 3, padding=1, stride=2),
160
+ nn.SiLU(),
161
+ zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
162
+ )
163
+
164
+ self._feature_size = model_channels
165
+ input_block_chans = [model_channels]
166
+ ch = model_channels
167
+ ds = 1
168
+ for level, mult in enumerate(channel_mult):
169
+ for nr in range(self.num_res_blocks[level]):
170
+ layers = [
171
+ ResBlock(
172
+ ch,
173
+ time_embed_dim,
174
+ dropout,
175
+ out_channels=mult * model_channels,
176
+ dims=dims,
177
+ use_checkpoint=use_checkpoint,
178
+ use_scale_shift_norm=use_scale_shift_norm,
179
+ )
180
+ ]
181
+ ch = mult * model_channels
182
+ if ds in attention_resolutions:
183
+ if num_head_channels == -1:
184
+ dim_head = ch // num_heads
185
+ else:
186
+ num_heads = ch // num_head_channels
187
+ dim_head = num_head_channels
188
+ if legacy:
189
+ # num_heads = 1
190
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
191
+ if exists(disable_self_attentions):
192
+ disabled_sa = disable_self_attentions[level]
193
+ else:
194
+ disabled_sa = False
195
+
196
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
197
+ layers.append(
198
+ AttentionBlock(
199
+ ch,
200
+ use_checkpoint=use_checkpoint,
201
+ num_heads=num_heads,
202
+ num_head_channels=dim_head,
203
+ use_new_attention_order=use_new_attention_order,
204
+ ) if not use_spatial_transformer else SpatialTransformer(
205
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
206
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
207
+ use_checkpoint=use_checkpoint
208
+ )
209
+ )
210
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
211
+ self.zero_convs.append(self.make_zero_conv(ch))
212
+ self._feature_size += ch
213
+ input_block_chans.append(ch)
214
+ if level != len(channel_mult) - 1:
215
+ out_ch = ch
216
+ self.input_blocks.append(
217
+ TimestepEmbedSequential(
218
+ ResBlock(
219
+ ch,
220
+ time_embed_dim,
221
+ dropout,
222
+ out_channels=out_ch,
223
+ dims=dims,
224
+ use_checkpoint=use_checkpoint,
225
+ use_scale_shift_norm=use_scale_shift_norm,
226
+ down=True,
227
+ )
228
+ if resblock_updown
229
+ else Downsample(
230
+ ch, conv_resample, dims=dims, out_channels=out_ch
231
+ )
232
+ )
233
+ )
234
+ ch = out_ch
235
+ input_block_chans.append(ch)
236
+ self.zero_convs.append(self.make_zero_conv(ch))
237
+ ds *= 2
238
+ self._feature_size += ch
239
+
240
+ if num_head_channels == -1:
241
+ dim_head = ch // num_heads
242
+ else:
243
+ num_heads = ch // num_head_channels
244
+ dim_head = num_head_channels
245
+ if legacy:
246
+ # num_heads = 1
247
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
248
+ self.middle_block = TimestepEmbedSequential(
249
+ ResBlock(
250
+ ch,
251
+ time_embed_dim,
252
+ dropout,
253
+ dims=dims,
254
+ use_checkpoint=use_checkpoint,
255
+ use_scale_shift_norm=use_scale_shift_norm,
256
+ ),
257
+ AttentionBlock(
258
+ ch,
259
+ use_checkpoint=use_checkpoint,
260
+ num_heads=num_heads,
261
+ num_head_channels=dim_head,
262
+ use_new_attention_order=use_new_attention_order,
263
+ ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
264
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
265
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
266
+ use_checkpoint=use_checkpoint
267
+ ),
268
+ ResBlock(
269
+ ch,
270
+ time_embed_dim,
271
+ dropout,
272
+ dims=dims,
273
+ use_checkpoint=use_checkpoint,
274
+ use_scale_shift_norm=use_scale_shift_norm,
275
+ ),
276
+ )
277
+ self.middle_block_out = self.make_zero_conv(ch)
278
+ self._feature_size += ch
279
+
280
+ def make_zero_conv(self, channels):
281
+ return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
282
+
283
+ def forward(self, x, hint, timesteps, context, **kwargs):
284
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
285
+ emb = self.time_embed(t_emb) # 1,1280
286
+
287
+ # 1,320,64,64
288
+ guided_hint = self.input_hint_block(hint, emb, context)
289
+ outs = []
290
+
291
+ h = x.type(self.dtype)
292
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
293
+ if guided_hint is not None:
294
+ # skip the first layer
295
+ h = guided_hint
296
+ guided_hint = None
297
+ else:
298
+ h_new = module(h, emb, context)
299
+ h = h_new
300
+ outs.append(zero_conv(h, emb, context))
301
+
302
+ h_new = self.middle_block(h, emb, context)
303
+ outs.append(self.middle_block_out(h_new, emb, context))
304
+ return outs
305
+
306
+
307
+ class ControlLDM(LatentDiffusion):
308
+
309
+ def __init__(self, control_stage_config, control_key, only_mid_control, *args, **kwargs):
310
+ super().__init__(*args, **kwargs)
311
+ self.control_model = instantiate_from_config(control_stage_config)
312
+ self.control_key = control_key
313
+ self.only_mid_control = only_mid_control
314
+ self.control_scales = [1.0] * 13
315
+
316
+ @torch.no_grad()
317
+ def get_input(self, batch, k, bs=None, *args, **kwargs):
318
+ x, c = super().get_input(batch, self.first_stage_key, *args, **kwargs)
319
+ control = batch[self.control_key]
320
+ if bs is not None:
321
+ control = control[:bs]
322
+ control = control.to(self.device)
323
+ control = einops.rearrange(control, 'b h w c -> b c h w')
324
+ control = control.to(memory_format=torch.contiguous_format).float()
325
+ self.time_steps = batch['time_steps']
326
+ return x, dict(c_crossattn=[c], c_concat=[control])
327
+
328
+ def apply_model(self, x_noisy, t, cond, *args, **kwargs):
329
+ assert isinstance(cond, dict)
330
+ diffusion_model = self.model.diffusion_model
331
+
332
+ cond_txt = torch.cat(cond['c_crossattn'], 1)
333
+
334
+ if cond['c_concat'] is None:
335
+ eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
336
+ else:
337
+ control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt)
338
+ control = [c * scale for c, scale in zip(control, self.control_scales)]
339
+ eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control)
340
+ return eps
341
+
342
+ @torch.no_grad()
343
+ def get_unconditional_conditioning(self, N):
344
+ uncond = self.get_learned_conditioning([ torch.zeros((1,3,224,224)) ] * N)
345
+ return uncond
346
+
347
+ @torch.no_grad()
348
+ def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None,
349
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
350
+ plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None,
351
+ use_ema_scope=True,
352
+ **kwargs):
353
+ use_ddim = ddim_steps is not None
354
+
355
+ log = dict()
356
+ z, c = self.get_input(batch, self.first_stage_key, bs=N)
357
+ c_cat, c = c["c_concat"][0][:N], c["c_crossattn"][0][:N]
358
+ N = min(z.shape[0], N)
359
+ n_row = min(z.shape[0], n_row)
360
+ log["reconstruction"] = self.decode_first_stage(z)
361
+
362
+ # ==== visualize the shape mask or the high-frequency map ====
363
+ guide_mask = (c_cat[:,-1,:,:].unsqueeze(1) + 1) * 0.5
364
+ guide_mask = torch.cat([guide_mask,guide_mask,guide_mask],1)
365
+ HF_map = c_cat[:,:3,:,:] #* 2.0 - 1.0
366
+
367
+ log["control"] = HF_map
368
+
369
+ cond_image = batch[self.cond_stage_key].cpu().numpy().copy()
370
+ log["conditioning"] = torch.permute( torch.tensor(cond_image), (0,3,1,2)) * 2.0 - 1.0
371
+ if plot_diffusion_rows:
372
+ # get diffusion row
373
+ diffusion_row = list()
374
+ z_start = z[:n_row]
375
+ for t in range(self.num_timesteps):
376
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
377
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
378
+ t = t.to(self.device).long()
379
+ noise = torch.randn_like(z_start)
380
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
381
+ diffusion_row.append(self.decode_first_stage(z_noisy))
382
+
383
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
384
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
385
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
386
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
387
+ log["diffusion_row"] = diffusion_grid
388
+
389
+ if sample:
390
+ # get denoise row
391
+ samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
392
+ batch_size=N, ddim=use_ddim,
393
+ ddim_steps=ddim_steps, eta=ddim_eta)
394
+ x_samples = self.decode_first_stage(samples)
395
+ log["samples"] = x_samples
396
+ if plot_denoise_rows:
397
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
398
+ log["denoise_row"] = denoise_grid
399
+
400
+ if unconditional_guidance_scale > 1.0:
401
+ uc_cross = self.get_unconditional_conditioning(N)
402
+ uc_cat = c_cat # torch.zeros_like(c_cat)
403
+ uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
404
+ samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
405
+ batch_size=N, ddim=use_ddim,
406
+ ddim_steps=ddim_steps, eta=ddim_eta,
407
+ unconditional_guidance_scale=unconditional_guidance_scale,
408
+ unconditional_conditioning=uc_full,
409
+ )
410
+ x_samples_cfg = self.decode_first_stage(samples_cfg)
411
+ log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg #* 2.0 - 1.0
412
+ return log
413
+
414
+ @torch.no_grad()
415
+ def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
416
+ ddim_sampler = DDIMSampler(self)
417
+ b, c, h, w = cond["c_concat"][0].shape
418
+ shape = (self.channels, h // 8, w // 8)
419
+ samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs)
420
+ return samples, intermediates
421
+
422
+ def configure_optimizers(self):
423
+ lr = self.learning_rate
424
+ params = list(self.control_model.parameters())
425
+ if not self.sd_locked:
426
+ params += list(self.model.diffusion_model.output_blocks.parameters())
427
+ params += list(self.model.diffusion_model.out.parameters())
428
+ params += list(self.cond_stage_model.projector.parameters())
429
+ opt = torch.optim.AdamW(params, lr=lr)
430
+ return opt
431
+
432
+ def low_vram_shift(self, is_diffusing):
433
+ if is_diffusing:
434
+ self.model = self.model.cuda()
435
+ self.control_model = self.control_model.cuda()
436
+ self.first_stage_model = self.first_stage_model.cpu()
437
+ self.cond_stage_model = self.cond_stage_model.cpu()
438
+ else:
439
+ self.model = self.model.cpu()
440
+ self.control_model = self.control_model.cpu()
441
+ self.first_stage_model = self.first_stage_model.cuda()
442
+ self.cond_stage_model = self.cond_stage_model.cuda()
cldm/ddim_hacked.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+
7
+ from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
8
+
9
+
10
+ class DDIMSampler(object):
11
+ def __init__(self, model, schedule="linear", **kwargs):
12
+ super().__init__()
13
+ self.model = model
14
+ self.ddpm_num_timesteps = model.num_timesteps
15
+ self.schedule = schedule
16
+
17
+ def register_buffer(self, name, attr):
18
+ if type(attr) == torch.Tensor:
19
+ if attr.device != torch.device("cuda"):
20
+ attr = attr.to(torch.device("cuda"))
21
+ setattr(self, name, attr)
22
+
23
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
24
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
25
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
26
+ alphas_cumprod = self.model.alphas_cumprod
27
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
28
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
29
+
30
+ self.register_buffer('betas', to_torch(self.model.betas))
31
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
32
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
33
+
34
+ # calculations for diffusion q(x_t | x_{t-1}) and others
35
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
36
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
37
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
38
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
39
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
40
+
41
+ # ddim sampling parameters
42
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
43
+ ddim_timesteps=self.ddim_timesteps,
44
+ eta=ddim_eta,verbose=verbose)
45
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
46
+ self.register_buffer('ddim_alphas', ddim_alphas)
47
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
48
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
49
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
50
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
51
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
52
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
53
+
54
+ @torch.no_grad()
55
+ def sample(self,
56
+ S,
57
+ batch_size,
58
+ shape,
59
+ conditioning=None,
60
+ callback=None,
61
+ normals_sequence=None,
62
+ img_callback=None,
63
+ quantize_x0=False,
64
+ eta=0.,
65
+ mask=None,
66
+ x0=None,
67
+ temperature=1.,
68
+ noise_dropout=0.,
69
+ score_corrector=None,
70
+ corrector_kwargs=None,
71
+ verbose=True,
72
+ x_T=None,
73
+ log_every_t=100,
74
+ unconditional_guidance_scale=1.,
75
+ unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
76
+ dynamic_threshold=None,
77
+ ucg_schedule=None,
78
+ **kwargs
79
+ ):
80
+ if conditioning is not None:
81
+ if isinstance(conditioning, dict):
82
+ ctmp = conditioning[list(conditioning.keys())[0]]
83
+ while isinstance(ctmp, list): ctmp = ctmp[0]
84
+ cbs = ctmp.shape[0]
85
+ if cbs != batch_size:
86
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
87
+
88
+ elif isinstance(conditioning, list):
89
+ for ctmp in conditioning:
90
+ if ctmp.shape[0] != batch_size:
91
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
92
+
93
+ else:
94
+ if conditioning.shape[0] != batch_size:
95
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
96
+
97
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
98
+ # sampling
99
+ C, H, W = shape
100
+ size = (batch_size, C, H, W)
101
+ print(f'Data shape for DDIM sampling is {size}, eta {eta}')
102
+
103
+ samples, intermediates = self.ddim_sampling(conditioning, size,
104
+ callback=callback,
105
+ img_callback=img_callback,
106
+ quantize_denoised=quantize_x0,
107
+ mask=mask, x0=x0,
108
+ ddim_use_original_steps=False,
109
+ noise_dropout=noise_dropout,
110
+ temperature=temperature,
111
+ score_corrector=score_corrector,
112
+ corrector_kwargs=corrector_kwargs,
113
+ x_T=x_T,
114
+ log_every_t=log_every_t,
115
+ unconditional_guidance_scale=unconditional_guidance_scale,
116
+ unconditional_conditioning=unconditional_conditioning,
117
+ dynamic_threshold=dynamic_threshold,
118
+ ucg_schedule=ucg_schedule
119
+ )
120
+ return samples, intermediates
121
+
122
+ @torch.no_grad()
123
+ def ddim_sampling(self, cond, shape,
124
+ x_T=None, ddim_use_original_steps=False,
125
+ callback=None, timesteps=None, quantize_denoised=False,
126
+ mask=None, x0=None, img_callback=None, log_every_t=100,
127
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
128
+ unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
129
+ ucg_schedule=None):
130
+ device = self.model.betas.device
131
+ b = shape[0]
132
+ #x_T 1,4,64,64
133
+ if x_T is None:
134
+ img = torch.randn(shape, device=device)
135
+ else:
136
+ img = x_T
137
+
138
+ if timesteps is None:
139
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
140
+ elif timesteps is not None and not ddim_use_original_steps:
141
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
142
+ timesteps = self.ddim_timesteps[:subset_end]
143
+
144
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
145
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
146
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
147
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
148
+
149
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
150
+
151
+ for i, step in enumerate(iterator):
152
+ index = total_steps - i - 1
153
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
154
+
155
+ if mask is not None:
156
+ assert x0 is not None
157
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
158
+ img = img_orig * mask + (1. - mask) * img
159
+
160
+ if ucg_schedule is not None:
161
+ assert len(ucg_schedule) == len(time_range)
162
+ unconditional_guidance_scale = ucg_schedule[i]
163
+
164
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
165
+ quantize_denoised=quantize_denoised, temperature=temperature,
166
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
167
+ corrector_kwargs=corrector_kwargs,
168
+ unconditional_guidance_scale=unconditional_guidance_scale,
169
+ unconditional_conditioning=unconditional_conditioning,
170
+ dynamic_threshold=dynamic_threshold)
171
+ img, pred_x0 = outs
172
+ if callback: callback(i)
173
+ if img_callback: img_callback(pred_x0, i)
174
+
175
+ if index % log_every_t == 0 or index == total_steps - 1:
176
+ intermediates['x_inter'].append(img)
177
+ intermediates['pred_x0'].append(pred_x0)
178
+
179
+ return img, intermediates
180
+
181
+ @torch.no_grad()
182
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
183
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
184
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
185
+ dynamic_threshold=None):
186
+ b, *_, device = *x.shape, x.device
187
+
188
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
189
+ model_output = self.model.apply_model(x, t, c)
190
+ else:
191
+ model_t = self.model.apply_model(x, t, c)
192
+ model_uncond = self.model.apply_model(x, t, unconditional_conditioning)
193
+ model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
194
+
195
+ if self.model.parameterization == "v":
196
+ e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
197
+ else:
198
+ e_t = model_output
199
+
200
+ if score_corrector is not None:
201
+ assert self.model.parameterization == "eps", 'not implemented'
202
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
203
+
204
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
205
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
206
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
207
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
208
+ # select parameters corresponding to the currently considered timestep
209
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
210
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
211
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
212
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
213
+
214
+ # current prediction for x_0
215
+ if self.model.parameterization != "v":
216
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
217
+ else:
218
+ pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
219
+
220
+ if quantize_denoised:
221
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
222
+
223
+ if dynamic_threshold is not None:
224
+ raise NotImplementedError()
225
+
226
+ # direction pointing to x_t
227
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
228
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
229
+ if noise_dropout > 0.:
230
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
231
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
232
+ return x_prev, pred_x0
233
+
234
+ @torch.no_grad()
235
+ def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
236
+ unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
237
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
238
+ num_reference_steps = timesteps.shape[0]
239
+
240
+ assert t_enc <= num_reference_steps
241
+ num_steps = t_enc
242
+
243
+ if use_original_steps:
244
+ alphas_next = self.alphas_cumprod[:num_steps]
245
+ alphas = self.alphas_cumprod_prev[:num_steps]
246
+ else:
247
+ alphas_next = self.ddim_alphas[:num_steps]
248
+ alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
249
+
250
+ x_next = x0
251
+ intermediates = []
252
+ inter_steps = []
253
+ for i in tqdm(range(num_steps), desc='Encoding Image'):
254
+ t = torch.full((x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long)
255
+ if unconditional_guidance_scale == 1.:
256
+ noise_pred = self.model.apply_model(x_next, t, c)
257
+ else:
258
+ assert unconditional_conditioning is not None
259
+ e_t_uncond, noise_pred = torch.chunk(
260
+ self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
261
+ torch.cat((unconditional_conditioning, c))), 2)
262
+ noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
263
+
264
+ xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
265
+ weighted_noise_pred = alphas_next[i].sqrt() * (
266
+ (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
267
+ x_next = xt_weighted + weighted_noise_pred
268
+ if return_intermediates and i % (
269
+ num_steps // return_intermediates) == 0 and i < num_steps - 1:
270
+ intermediates.append(x_next)
271
+ inter_steps.append(i)
272
+ elif return_intermediates and i >= num_steps - 2:
273
+ intermediates.append(x_next)
274
+ inter_steps.append(i)
275
+ if callback: callback(i)
276
+
277
+ out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
278
+ if return_intermediates:
279
+ out.update({'intermediates': intermediates})
280
+ return x_next, out
281
+
282
+ @torch.no_grad()
283
+ def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
284
+ # fast, but does not allow for exact reconstruction
285
+ # t serves as an index to gather the correct alphas
286
+ if use_original_steps:
287
+ sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
288
+ sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
289
+ else:
290
+ sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
291
+ sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
292
+
293
+ if noise is None:
294
+ noise = torch.randn_like(x0)
295
+ return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
296
+ extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
297
+
298
+ @torch.no_grad()
299
+ def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
300
+ use_original_steps=False, callback=None):
301
+
302
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
303
+ timesteps = timesteps[:t_start]
304
+
305
+ time_range = np.flip(timesteps)
306
+ total_steps = timesteps.shape[0]
307
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
308
+
309
+ iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
310
+ x_dec = x_latent
311
+ for i, step in enumerate(iterator):
312
+ index = total_steps - i - 1
313
+ ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
314
+ x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
315
+ unconditional_guidance_scale=unconditional_guidance_scale,
316
+ unconditional_conditioning=unconditional_conditioning)
317
+ if callback: callback(i)
318
+ return x_dec
cldm/hack.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import einops
3
+
4
+ import ldm.modules.encoders.modules
5
+ import ldm.modules.attention
6
+
7
+ from transformers import logging
8
+ from ldm.modules.attention import default
9
+
10
+
11
+ def disable_verbosity():
12
+ logging.set_verbosity_error()
13
+ print('logging improved.')
14
+ return
15
+
16
+
17
+ def enable_sliced_attention():
18
+ ldm.modules.attention.CrossAttention.forward = _hacked_sliced_attentin_forward
19
+ print('Enabled sliced_attention.')
20
+ return
21
+
22
+
23
+ def hack_everything(clip_skip=0):
24
+ disable_verbosity()
25
+ ldm.modules.encoders.modules.FrozenCLIPEmbedder.forward = _hacked_clip_forward
26
+ ldm.modules.encoders.modules.FrozenCLIPEmbedder.clip_skip = clip_skip
27
+ print('Enabled clip hacks.')
28
+ return
29
+
30
+
31
+ # Written by Lvmin
32
+ def _hacked_clip_forward(self, text):
33
+ PAD = self.tokenizer.pad_token_id
34
+ EOS = self.tokenizer.eos_token_id
35
+ BOS = self.tokenizer.bos_token_id
36
+
37
+ def tokenize(t):
38
+ return self.tokenizer(t, truncation=False, add_special_tokens=False)["input_ids"]
39
+
40
+ def transformer_encode(t):
41
+ if self.clip_skip > 1:
42
+ rt = self.transformer(input_ids=t, output_hidden_states=True)
43
+ return self.transformer.text_model.final_layer_norm(rt.hidden_states[-self.clip_skip])
44
+ else:
45
+ return self.transformer(input_ids=t, output_hidden_states=False).last_hidden_state
46
+
47
+ def split(x):
48
+ return x[75 * 0: 75 * 1], x[75 * 1: 75 * 2], x[75 * 2: 75 * 3]
49
+
50
+ def pad(x, p, i):
51
+ return x[:i] if len(x) >= i else x + [p] * (i - len(x))
52
+
53
+ raw_tokens_list = tokenize(text)
54
+ tokens_list = []
55
+
56
+ for raw_tokens in raw_tokens_list:
57
+ raw_tokens_123 = split(raw_tokens)
58
+ raw_tokens_123 = [[BOS] + raw_tokens_i + [EOS] for raw_tokens_i in raw_tokens_123]
59
+ raw_tokens_123 = [pad(raw_tokens_i, PAD, 77) for raw_tokens_i in raw_tokens_123]
60
+ tokens_list.append(raw_tokens_123)
61
+
62
+ tokens_list = torch.IntTensor(tokens_list).to(self.device)
63
+
64
+ feed = einops.rearrange(tokens_list, 'b f i -> (b f) i')
65
+ y = transformer_encode(feed)
66
+ z = einops.rearrange(y, '(b f) i c -> b (f i) c', f=3)
67
+
68
+ return z
69
+
70
+
71
+ # Stolen from https://github.com/basujindal/stable-diffusion/blob/main/optimizedSD/splitAttention.py
72
+ def _hacked_sliced_attentin_forward(self, x, context=None, mask=None):
73
+ h = self.heads
74
+
75
+ q = self.to_q(x)
76
+ context = default(context, x)
77
+ k = self.to_k(context)
78
+ v = self.to_v(context)
79
+ del context, x
80
+
81
+ q, k, v = map(lambda t: einops.rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
82
+
83
+ limit = k.shape[0]
84
+ att_step = 1
85
+ q_chunks = list(torch.tensor_split(q, limit // att_step, dim=0))
86
+ k_chunks = list(torch.tensor_split(k, limit // att_step, dim=0))
87
+ v_chunks = list(torch.tensor_split(v, limit // att_step, dim=0))
88
+
89
+ q_chunks.reverse()
90
+ k_chunks.reverse()
91
+ v_chunks.reverse()
92
+ sim = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
93
+ del k, q, v
94
+ for i in range(0, limit, att_step):
95
+ q_buffer = q_chunks.pop()
96
+ k_buffer = k_chunks.pop()
97
+ v_buffer = v_chunks.pop()
98
+ sim_buffer = torch.einsum('b i d, b j d -> b i j', q_buffer, k_buffer) * self.scale
99
+
100
+ del k_buffer, q_buffer
101
+ # attention, what we cannot get enough of, by chunks
102
+
103
+ sim_buffer = sim_buffer.softmax(dim=-1)
104
+
105
+ sim_buffer = torch.einsum('b i j, b j d -> b i d', sim_buffer, v_buffer)
106
+ del v_buffer
107
+ sim[i:i + att_step, :, :] = sim_buffer
108
+
109
+ del sim_buffer
110
+ sim = einops.rearrange(sim, '(b h) n d -> b n (h d)', h=h)
111
+ return self.to_out(sim)
cldm/logger.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torchvision
6
+ from PIL import Image
7
+ from pytorch_lightning.callbacks import Callback
8
+ from pytorch_lightning.utilities.distributed import rank_zero_only
9
+
10
+
11
+ class ImageLogger(Callback):
12
+ def __init__(self, batch_frequency=2000, max_images=4, clamp=True, increase_log_steps=True,
13
+ rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
14
+ log_images_kwargs=None):
15
+ super().__init__()
16
+ self.rescale = rescale
17
+ self.batch_freq = batch_frequency
18
+ self.max_images = max_images
19
+ if not increase_log_steps:
20
+ self.log_steps = [self.batch_freq]
21
+ self.clamp = clamp
22
+ self.disabled = disabled
23
+ self.log_on_batch_idx = log_on_batch_idx
24
+ self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
25
+ self.log_first_step = log_first_step
26
+
27
+ @rank_zero_only
28
+ def log_local(self, save_dir, split, images, global_step, current_epoch, batch_idx):
29
+ root = os.path.join(save_dir, "image_log", split)
30
+ for k in images:
31
+ grid = torchvision.utils.make_grid(images[k], nrow=4)
32
+ if self.rescale:
33
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
34
+ grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
35
+ grid = grid.numpy()
36
+ grid = (grid * 255).astype(np.uint8)
37
+ filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(k, global_step, current_epoch, batch_idx)
38
+ path = os.path.join(root, filename)
39
+ os.makedirs(os.path.split(path)[0], exist_ok=True)
40
+ Image.fromarray(grid).save(path)
41
+
42
+ def log_img(self, pl_module, batch, batch_idx, split="train"):
43
+ check_idx = batch_idx # if self.log_on_batch_idx else pl_module.global_step
44
+ if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
45
+ hasattr(pl_module, "log_images") and
46
+ callable(pl_module.log_images) and
47
+ self.max_images > 0):
48
+ logger = type(pl_module.logger)
49
+
50
+ is_train = pl_module.training
51
+ if is_train:
52
+ pl_module.eval()
53
+
54
+ with torch.no_grad():
55
+ images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
56
+
57
+ for k in images:
58
+ N = min(images[k].shape[0], self.max_images)
59
+ images[k] = images[k][:N]
60
+ if isinstance(images[k], torch.Tensor):
61
+ images[k] = images[k].detach().cpu()
62
+ if self.clamp:
63
+ images[k] = torch.clamp(images[k], -1., 1.)
64
+
65
+ self.log_local(pl_module.logger.save_dir, split, images,
66
+ pl_module.global_step, pl_module.current_epoch, batch_idx)
67
+
68
+ if is_train:
69
+ pl_module.train()
70
+
71
+ def check_frequency(self, check_idx):
72
+ return check_idx % self.batch_freq == 0
73
+
74
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
75
+ if not self.disabled:
76
+ self.log_img(pl_module, batch, batch_idx, split="train")
cldm/model.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+
4
+ from omegaconf import OmegaConf
5
+ from ldm.util import instantiate_from_config
6
+
7
+
8
+ def get_state_dict(d):
9
+ return d.get('state_dict', d)
10
+
11
+
12
+ def load_state_dict(ckpt_path, location='cpu'):
13
+ _, extension = os.path.splitext(ckpt_path)
14
+ if extension.lower() == ".safetensors":
15
+ import safetensors.torch
16
+ state_dict = safetensors.torch.load_file(ckpt_path, device=location)
17
+ else:
18
+ state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location)))
19
+ state_dict = get_state_dict(state_dict)
20
+ print(f'Loaded state_dict from [{ckpt_path}]')
21
+ return state_dict
22
+
23
+
24
+ def create_model(config_path):
25
+ config = OmegaConf.load(config_path)
26
+ model = instantiate_from_config(config.model).cpu()
27
+ print(f'Loaded model config from [{config_path}]')
28
+ return model
configs/anydoor.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ target: cldm.cldm.ControlLDM
3
+ params:
4
+ linear_start: 0.00085
5
+ linear_end: 0.0120
6
+ num_timesteps_cond: 1
7
+ log_every_t: 200
8
+ timesteps: 1000
9
+ first_stage_key: "jpg"
10
+ cond_stage_key: "ref"
11
+ control_key: "hint"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+ only_mid_control: False
20
+
21
+ control_stage_config:
22
+ target: cldm.cldm.ControlNet
23
+ params:
24
+ use_checkpoint: True
25
+ image_size: 32 # unused
26
+ in_channels: 4
27
+ hint_channels: 4 #3
28
+ model_channels: 320
29
+ attention_resolutions: [ 4, 2, 1 ]
30
+ num_res_blocks: 2
31
+ channel_mult: [ 1, 2, 4, 4 ]
32
+ num_head_channels: 64 # need to fix for flash-attn
33
+ use_spatial_transformer: True
34
+ use_linear_in_transformer: True
35
+ transformer_depth: 1
36
+ context_dim: 1024
37
+ legacy: False
38
+
39
+ unet_config:
40
+ target: cldm.cldm.ControlledUnetModel
41
+ params:
42
+ use_checkpoint: True
43
+ image_size: 32 # unused
44
+ in_channels: 4
45
+ out_channels: 4
46
+ model_channels: 320
47
+ attention_resolutions: [ 4, 2, 1 ]
48
+ num_res_blocks: 2
49
+ channel_mult: [ 1, 2, 4, 4 ]
50
+ num_head_channels: 64 # need to fix for flash-attn
51
+ use_spatial_transformer: True
52
+ use_linear_in_transformer: True
53
+ transformer_depth: 1
54
+ context_dim: 1024
55
+ legacy: False
56
+
57
+ first_stage_config:
58
+ target: ldm.models.autoencoder.AutoencoderKL
59
+ params:
60
+ embed_dim: 4
61
+ monitor: val/rec_loss
62
+ ddconfig:
63
+ #attn_type: "vanilla-xformers"
64
+ double_z: true
65
+ z_channels: 4
66
+ resolution: 256
67
+ in_channels: 3
68
+ out_ch: 3
69
+ ch: 128
70
+ ch_mult:
71
+ - 1
72
+ - 2
73
+ - 4
74
+ - 4
75
+ num_res_blocks: 2
76
+ attn_resolutions: []
77
+ dropout: 0.0
78
+ lossconfig:
79
+ target: torch.nn.Identity
80
+
81
+ cond_stage_config:
82
+ target: ldm.modules.encoders.modules.FrozenDinoV2Encoder
83
+ weight: path/dinov2_vitg14_pretrain.pth
84
+
85
+
configs/datasets.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Train:
2
+ YoutubeVOS:
3
+ image_dir: path/YTBVOS/train/JPEGImages/
4
+ anno: path/YTBVOS/train/Annotations
5
+ meta: path/YTBVOS/train/meta.json
6
+
7
+ YoutubeVIS:
8
+ image_dir: path/youtubevis/train/JPEGImages/
9
+ anno: path/youtubevis/train/Annotations/
10
+ meta: path/youtubevis/train/meta.json
11
+
12
+ VIPSeg:
13
+ image_dir: path/VIPSeg/VIPSeg_720P/images/
14
+ anno: path/VIPSeg/VIPSeg_720P/panomasksRGB/
15
+
16
+ UVO:
17
+ train:
18
+ image_dir: path/UVO/uvo_frames_sparse
19
+ video_json: path/UVO/UVO_sparse_train_video_with_interpolation.json
20
+ image_json: path/UVO/UVO_sparse_train_video_with_interpolation_reorg.json
21
+ val:
22
+ image_dir: path/UVO/uvo_frames_sparse
23
+ video_json: path/UVO/VideoSparseSet/UVO_sparse_val_video_with_interpolation.json
24
+ image_json: path/UVO/VideoSparseSet/UVO_sparse_val_video_interpolation_reorg.json
25
+
26
+ Mose:
27
+ image_dir: path/MOSE/train/JPEGImages/
28
+ anno: path/MOSE/train/Annotations/
29
+
30
+ MVImageNet:
31
+ txt: ./datasets/Preprocess/mvimagenet.txt
32
+ image_dir: /mnt/workspace/xizhi/data/MVImgNet/
33
+
34
+ VitonHD:
35
+ image_dir: path/TryOn/VitonHD/train/cloth/
36
+
37
+ Dresscode:
38
+ image_dir: /mnt/workspace/xizhi/data/dresscode/DressCode/upper_body/label_maps/
39
+
40
+ FashionTryon:
41
+ image_dir: path/TryOn/FashionTryOn/train
42
+
43
+ Lvis:
44
+ image_dir: path/COCO/train2017
45
+ json_path: path/lvis_v1/lvis_v1_train.json
46
+
47
+ SAM:
48
+ sub1: path/SAM/0000
49
+ sub2: path/SAM/0001
50
+ sub3: path/SAM/0002
51
+ sub4: path/SAM/0004
52
+
53
+ Saliency:
54
+ MSRA_root: path/Saliency/MSRA10K_Imgs_GT/
55
+ TR_root: path/Saliency/DUTS-TR/DUTS-TR-Image/
56
+ TE_root: path/Saliency/DUTS-TE/DUTS-TE-Image/
57
+ HFlickr_root: path/HFlickr/masks/
58
+
59
+ Test:
60
+ DreamBooth:
61
+ fg_dir: path/DreamBooth/AnyDoor_DreamBooth
62
+ bg_dir: path/DreamBooth/v1_800
63
+
64
+ VitonHDTest:
65
+ image_dir: path/TryOn/VitonHD/test/cloth
66
+
67
+
68
+
configs/demo.yaml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pretrained_model: ./AnyDoor_models/general_v0.1/general_v0.1.ckpt
2
+ config_file: configs/anydoor.yaml
3
+ save_memory: False
configs/inference.yaml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pretrained_model: path/epoch=1-step=8687.ckpt
2
+ config_file: configs/anydoor.yaml
3
+ save_memory: False
datasets/Preprocess/mvimagenet.txt ADDED
The diff for this file is too large to render. See raw diff
 
datasets/Preprocess/uvo_process.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import json
3
+ import os
4
+ from pycocotools import mask as mask_utils
5
+ import numpy as np
6
+ from tqdm import tqdm
7
+
8
+ json_path = 'path/UVO/UVO_sparse_train_video_with_interpolation.json'
9
+ output_path = "path/UVO/UVO_sparse_train_video_with_interpolation_reorg.json"
10
+
11
+ with open(json_path, 'r') as fcc_file:
12
+ data = json.load(fcc_file)
13
+
14
+ info = data['info']
15
+ videos = data['videos']
16
+ print(len(videos))
17
+
18
+
19
+ uvo_dict = {}
20
+ for video in tqdm(videos):
21
+ vid = video['id']
22
+ file_names = video['file_names']
23
+ uvo_dict[vid] = file_names
24
+
25
+
26
+ with open(output_path,"w") as f:
27
+ json.dump(uvo_dict,f)
28
+ print('finish')
29
+
datasets/base.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ cv2.setNumThreads(0)
10
+ cv2.ocl.setUseOpenCL(False)
11
+ import albumentations as A
12
+
13
+
14
+ class BaseDataset(Dataset):
15
+ def __init__(self):
16
+ image_mask_dict = {}
17
+ self.data = []
18
+
19
+ def __len__(self):
20
+ # We adjust the ratio of different dataset by setting the length.
21
+ pass
22
+
23
+
24
+ def aug_data_back(self, image):
25
+ transform = A.Compose([
26
+ A.ColorJitter(p=0.5, brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5),
27
+ A.ChannelShuffle()
28
+ ])
29
+ transformed = transform(image=image.astype(np.uint8))
30
+ transformed_image = transformed["image"]
31
+ return transformed_image
32
+
33
+ def aug_data_mask(self, image, mask):
34
+ transform = A.Compose([
35
+ A.HorizontalFlip(p=0.5),
36
+ A.RandomBrightnessContrast(p=0.5),
37
+ #A.Rotate(limit=20, border_mode=cv2.BORDER_CONSTANT, value=(0,0,0)),
38
+ ])
39
+
40
+ transformed = transform(image=image.astype(np.uint8), mask = mask)
41
+ transformed_image = transformed["image"]
42
+ transformed_mask = transformed["mask"]
43
+ return transformed_image, transformed_mask
44
+
45
+
46
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
47
+ pass_flag = True
48
+ H,W = image.shape[0], image.shape[1]
49
+ H,W = H * ratio, W * ratio
50
+ y1,y2,x1,x2 = yyxx
51
+ h,w = y2-y1,x2-x1
52
+ if mode == 'max':
53
+ if h > H or w > W:
54
+ pass_flag = False
55
+ elif mode == 'min':
56
+ if h < H or w < W:
57
+ pass_flag = False
58
+ return pass_flag
59
+
60
+
61
+ def __getitem__(self, idx):
62
+ while(True):
63
+ try:
64
+ idx = np.random.randint(0, len(self.data)-1)
65
+ item = self.get_sample(idx)
66
+ return item
67
+ except:
68
+ idx = np.random.randint(0, len(self.data)-1)
69
+
70
+ def get_sample(self, idx):
71
+ # Implemented for each specific dataset
72
+ pass
73
+
74
+ def sample_timestep(self, max_step =1000):
75
+ if np.random.rand() < 0.3:
76
+ step = np.random.randint(0,max_step)
77
+ return np.array([step])
78
+
79
+ if self.dynamic == 1:
80
+ # coarse videos
81
+ step_start = max_step // 2
82
+ step_end = max_step
83
+ elif self.dynamic == 0:
84
+ # static images
85
+ step_start = 0
86
+ step_end = max_step // 2
87
+ else:
88
+ # fine multi-view images/videos/3Ds
89
+ step_start = 0
90
+ step_end = max_step
91
+ step = np.random.randint(step_start, step_end)
92
+ return np.array([step])
93
+
94
+ def check_mask_area(self, mask):
95
+ H,W = mask.shape[0], mask.shape[1]
96
+ ratio = mask.sum() / (H * W)
97
+ if ratio > 0.8 * 0.8 or ratio < 0.1 * 0.1:
98
+ return False
99
+ else:
100
+ return True
101
+
102
+
103
+ def process_pairs(self, ref_image, ref_mask, tar_image, tar_mask, max_ratio = 0.8):
104
+ assert mask_score(ref_mask) > 0.90
105
+ assert self.check_mask_area(ref_mask) == True
106
+ assert self.check_mask_area(tar_mask) == True
107
+
108
+ # ========= Reference ===========
109
+ '''
110
+ # similate the case that the mask for reference object is coarse. Seems useless :(
111
+
112
+ if np.random.uniform(0, 1) < 0.7:
113
+ ref_mask_clean = ref_mask.copy()
114
+ ref_mask_clean = np.stack([ref_mask_clean,ref_mask_clean,ref_mask_clean],-1)
115
+ ref_mask = perturb_mask(ref_mask, 0.6, 0.9)
116
+
117
+ # select a fake bg to avoid the background leakage
118
+ fake_target = tar_image.copy()
119
+ h,w = ref_image.shape[0], ref_image.shape[1]
120
+ fake_targe = cv2.resize(fake_target, (w,h))
121
+ fake_back = np.fliplr(np.flipud(fake_target))
122
+ fake_back = self.aug_data_back(fake_back)
123
+ ref_image = ref_mask_clean * ref_image + (1-ref_mask_clean) * fake_back
124
+ '''
125
+
126
+ # Get the outline Box of the reference image
127
+ ref_box_yyxx = get_bbox_from_mask(ref_mask)
128
+ assert self.check_region_size(ref_mask, ref_box_yyxx, ratio = 0.10, mode = 'min') == True
129
+
130
+ # Filtering background for the reference image
131
+ ref_mask_3 = np.stack([ref_mask,ref_mask,ref_mask],-1)
132
+ masked_ref_image = ref_image * ref_mask_3 + np.ones_like(ref_image) * 255 * (1-ref_mask_3)
133
+
134
+ y1,y2,x1,x2 = ref_box_yyxx
135
+ masked_ref_image = masked_ref_image[y1:y2,x1:x2,:]
136
+ ref_mask = ref_mask[y1:y2,x1:x2]
137
+
138
+ ratio = np.random.randint(11, 15) / 10
139
+ masked_ref_image, ref_mask = expand_image_mask(masked_ref_image, ref_mask, ratio=ratio)
140
+ ref_mask_3 = np.stack([ref_mask,ref_mask,ref_mask],-1)
141
+
142
+ # Padding reference image to square and resize to 224
143
+ masked_ref_image = pad_to_square(masked_ref_image, pad_value = 255, random = False)
144
+ masked_ref_image = cv2.resize(masked_ref_image.astype(np.uint8), (224,224) ).astype(np.uint8)
145
+
146
+ ref_mask_3 = pad_to_square(ref_mask_3 * 255, pad_value = 0, random = False)
147
+ ref_mask_3 = cv2.resize(ref_mask_3.astype(np.uint8), (224,224) ).astype(np.uint8)
148
+ ref_mask = ref_mask_3[:,:,0]
149
+
150
+ # Augmenting reference image
151
+ #masked_ref_image_aug = self.aug_data(masked_ref_image)
152
+
153
+ # Getting for high-freqency map
154
+ masked_ref_image_compose, ref_mask_compose = self.aug_data_mask(masked_ref_image, ref_mask)
155
+ masked_ref_image_aug = masked_ref_image_compose.copy()
156
+
157
+ ref_mask_3 = np.stack([ref_mask_compose,ref_mask_compose,ref_mask_compose],-1)
158
+ ref_image_collage = sobel(masked_ref_image_compose, ref_mask_compose/255)
159
+
160
+
161
+ # ========= Training Target ===========
162
+ tar_box_yyxx = get_bbox_from_mask(tar_mask)
163
+ tar_box_yyxx = expand_bbox(tar_mask, tar_box_yyxx, ratio=[1.1,1.2]) #1.1 1.3
164
+ assert self.check_region_size(tar_mask, tar_box_yyxx, ratio = max_ratio, mode = 'max') == True
165
+
166
+ # Cropping around the target object
167
+ tar_box_yyxx_crop = expand_bbox(tar_image, tar_box_yyxx, ratio=[1.3, 3.0])
168
+ tar_box_yyxx_crop = box2squre(tar_image, tar_box_yyxx_crop) # crop box
169
+ y1,y2,x1,x2 = tar_box_yyxx_crop
170
+ cropped_target_image = tar_image[y1:y2,x1:x2,:]
171
+ cropped_tar_mask = tar_mask[y1:y2,x1:x2]
172
+ tar_box_yyxx = box_in_box(tar_box_yyxx, tar_box_yyxx_crop)
173
+ y1,y2,x1,x2 = tar_box_yyxx
174
+
175
+ # Prepairing collage image
176
+ ref_image_collage = cv2.resize(ref_image_collage.astype(np.uint8), (x2-x1, y2-y1))
177
+ ref_mask_compose = cv2.resize(ref_mask_compose.astype(np.uint8), (x2-x1, y2-y1))
178
+ ref_mask_compose = (ref_mask_compose > 128).astype(np.uint8)
179
+
180
+ collage = cropped_target_image.copy()
181
+ collage[y1:y2,x1:x2,:] = ref_image_collage
182
+
183
+ collage_mask = cropped_target_image.copy() * 0.0
184
+ collage_mask[y1:y2,x1:x2,:] = 1.0
185
+
186
+ if np.random.uniform(0, 1) < 0.7:
187
+ cropped_tar_mask = perturb_mask(cropped_tar_mask)
188
+ collage_mask = np.stack([cropped_tar_mask,cropped_tar_mask,cropped_tar_mask],-1)
189
+
190
+ H1, W1 = collage.shape[0], collage.shape[1]
191
+
192
+ cropped_target_image = pad_to_square(cropped_target_image, pad_value = 0, random = False).astype(np.uint8)
193
+ collage = pad_to_square(collage, pad_value = 0, random = False).astype(np.uint8)
194
+ collage_mask = pad_to_square(collage_mask, pad_value = 2, random = False).astype(np.uint8)
195
+ H2, W2 = collage.shape[0], collage.shape[1]
196
+
197
+ cropped_target_image = cv2.resize(cropped_target_image.astype(np.uint8), (512,512)).astype(np.float32)
198
+ collage = cv2.resize(collage.astype(np.uint8), (512,512)).astype(np.float32)
199
+ collage_mask = cv2.resize(collage_mask.astype(np.uint8), (512,512), interpolation = cv2.INTER_NEAREST).astype(np.float32)
200
+ collage_mask[collage_mask == 2] = -1
201
+
202
+ # Prepairing dataloader items
203
+ masked_ref_image_aug = masked_ref_image_aug / 255
204
+ cropped_target_image = cropped_target_image / 127.5 - 1.0
205
+ collage = collage / 127.5 - 1.0
206
+ collage = np.concatenate([collage, collage_mask[:,:,:1] ] , -1)
207
+
208
+ item = dict(
209
+ ref=masked_ref_image_aug.copy(),
210
+ jpg=cropped_target_image.copy(),
211
+ hint=collage.copy(),
212
+ extra_sizes=np.array([H1, W1, H2, W2]),
213
+ tar_box_yyxx_crop=np.array(tar_box_yyxx_crop)
214
+ )
215
+ return item
216
+
217
+
218
+
219
+
220
+
datasets/data_utils.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import cv2
4
+
5
+
6
+ def mask_score(mask):
7
+ '''Scoring the mask according to connectivity.'''
8
+ mask = mask.astype(np.uint8)
9
+ if mask.sum() < 10:
10
+ return 0
11
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
12
+ cnt_area = [cv2.contourArea(cnt) for cnt in contours]
13
+ conc_score = np.max(cnt_area) / sum(cnt_area)
14
+ return conc_score
15
+
16
+
17
+ def sobel(img, mask, thresh = 50):
18
+ '''Calculating the high-frequency map.'''
19
+ H,W = img.shape[0], img.shape[1]
20
+ img = cv2.resize(img,(256,256))
21
+ mask = (cv2.resize(mask,(256,256)) > 0.5).astype(np.uint8)
22
+ kernel = np.ones((5,5),np.uint8)
23
+ mask = cv2.erode(mask, kernel, iterations = 2)
24
+
25
+ Ksize = 3
26
+ sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=Ksize)
27
+ sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=Ksize)
28
+ sobel_X = cv2.convertScaleAbs(sobelx)
29
+ sobel_Y = cv2.convertScaleAbs(sobely)
30
+ scharr = cv2.addWeighted(sobel_X, 0.5, sobel_Y, 0.5, 0)
31
+ scharr = np.max(scharr,-1) * mask
32
+
33
+ scharr[scharr < thresh] = 0.0
34
+ scharr = np.stack([scharr,scharr,scharr],-1)
35
+ scharr = (scharr.astype(np.float32)/255 * img.astype(np.float32) ).astype(np.uint8)
36
+ scharr = cv2.resize(scharr,(W,H))
37
+ return scharr
38
+
39
+
40
+ def resize_and_pad(image, box):
41
+ '''Fitting an image to the box region while keeping the aspect ratio.'''
42
+ y1,y2,x1,x2 = box
43
+ H,W = y2-y1, x2-x1
44
+ h,w = image.shape[0], image.shape[1]
45
+ r_box = W / H
46
+ r_image = w / h
47
+ if r_box >= r_image:
48
+ h_target = H
49
+ w_target = int(w * H / h)
50
+ image = cv2.resize(image, (w_target, h_target))
51
+
52
+ w1 = (W - w_target) // 2
53
+ w2 = W - w_target - w1
54
+ pad_param = ((0,0),(w1,w2),(0,0))
55
+ image = np.pad(image, pad_param, 'constant', constant_values=255)
56
+ else:
57
+ w_target = W
58
+ h_target = int(h * W / w)
59
+ image = cv2.resize(image, (w_target, h_target))
60
+
61
+ h1 = (H-h_target) // 2
62
+ h2 = H - h_target - h1
63
+ pad_param =((h1,h2),(0,0),(0,0))
64
+ image = np.pad(image, pad_param, 'constant', constant_values=255)
65
+ return image
66
+
67
+
68
+
69
+ def expand_image_mask(image, mask, ratio=1.4):
70
+ h,w = image.shape[0], image.shape[1]
71
+ H,W = int(h * ratio), int(w * ratio)
72
+ h1 = int((H - h) // 2)
73
+ h2 = H - h - h1
74
+ w1 = int((W -w) // 2)
75
+ w2 = W -w - w1
76
+
77
+ pad_param_image = ((h1,h2),(w1,w2),(0,0))
78
+ pad_param_mask = ((h1,h2),(w1,w2))
79
+ image = np.pad(image, pad_param_image, 'constant', constant_values=255)
80
+ mask = np.pad(mask, pad_param_mask, 'constant', constant_values=0)
81
+ return image, mask
82
+
83
+
84
+ def resize_box(yyxx, H,W,h,w):
85
+ y1,y2,x1,x2 = yyxx
86
+ y1,y2 = int(y1/H * h), int(y2/H * h)
87
+ x1,x2 = int(x1/W * w), int(x2/W * w)
88
+ y1,y2 = min(y1,h), min(y2,h)
89
+ x1,x2 = min(x1,w), min(x2,w)
90
+ return (y1,y2,x1,x2)
91
+
92
+
93
+ def get_bbox_from_mask(mask):
94
+ h,w = mask.shape[0],mask.shape[1]
95
+
96
+ if mask.sum() < 10:
97
+ return 0,h,0,w
98
+ rows = np.any(mask,axis=1)
99
+ cols = np.any(mask,axis=0)
100
+ y1,y2 = np.where(rows)[0][[0,-1]]
101
+ x1,x2 = np.where(cols)[0][[0,-1]]
102
+ return (y1,y2,x1,x2)
103
+
104
+
105
+ def expand_bbox(mask,yyxx,ratio=[1.2,2.0], min_crop=0):
106
+ y1,y2,x1,x2 = yyxx
107
+ ratio = np.random.randint( ratio[0] * 10, ratio[1] * 10 ) / 10
108
+ H,W = mask.shape[0], mask.shape[1]
109
+ xc, yc = 0.5 * (x1 + x2), 0.5 * (y1 + y2)
110
+ h = ratio * (y2-y1+1)
111
+ w = ratio * (x2-x1+1)
112
+ h = max(h,min_crop)
113
+ w = max(w,min_crop)
114
+
115
+ x1 = int(xc - w * 0.5)
116
+ x2 = int(xc + w * 0.5)
117
+ y1 = int(yc - h * 0.5)
118
+ y2 = int(yc + h * 0.5)
119
+
120
+ x1 = max(0,x1)
121
+ x2 = min(W,x2)
122
+ y1 = max(0,y1)
123
+ y2 = min(H,y2)
124
+ return (y1,y2,x1,x2)
125
+
126
+
127
+ def box2squre(image, box):
128
+ H,W = image.shape[0], image.shape[1]
129
+ y1,y2,x1,x2 = box
130
+ cx = (x1 + x2) // 2
131
+ cy = (y1 + y2) // 2
132
+ h,w = y2-y1, x2-x1
133
+
134
+ if h >= w:
135
+ x1 = cx - h//2
136
+ x2 = cx + h//2
137
+ else:
138
+ y1 = cy - w//2
139
+ y2 = cy + w//2
140
+ x1 = max(0,x1)
141
+ x2 = min(W,x2)
142
+ y1 = max(0,y1)
143
+ y2 = min(H,y2)
144
+ return (y1,y2,x1,x2)
145
+
146
+
147
+ def pad_to_square(image, pad_value = 255, random = False):
148
+ H,W = image.shape[0], image.shape[1]
149
+ if H == W:
150
+ return image
151
+
152
+ padd = abs(H - W)
153
+ if random:
154
+ padd_1 = int(np.random.randint(0,padd))
155
+ else:
156
+ padd_1 = int(padd / 2)
157
+ padd_2 = padd - padd_1
158
+
159
+ if H > W:
160
+ pad_param = ((0,0),(padd_1,padd_2),(0,0))
161
+ else:
162
+ pad_param = ((padd_1,padd_2),(0,0),(0,0))
163
+
164
+ image = np.pad(image, pad_param, 'constant', constant_values=pad_value)
165
+ return image
166
+
167
+
168
+
169
+ def box_in_box(small_box, big_box):
170
+ y1,y2,x1,x2 = small_box
171
+ y1_b, _, x1_b, _ = big_box
172
+ y1,y2,x1,x2 = y1 - y1_b ,y2 - y1_b, x1 - x1_b ,x2 - x1_b
173
+ return (y1,y2,x1,x2 )
174
+
175
+
176
+
177
+ def shuffle_image(image, N):
178
+ height, width = image.shape[:2]
179
+
180
+ block_height = height // N
181
+ block_width = width // N
182
+ blocks = []
183
+
184
+ for i in range(N):
185
+ for j in range(N):
186
+ block = image[i*block_height:(i+1)*block_height, j*block_width:(j+1)*block_width]
187
+ blocks.append(block)
188
+
189
+ np.random.shuffle(blocks)
190
+ shuffled_image = np.zeros((height, width, 3), dtype=np.uint8)
191
+
192
+ for i in range(N):
193
+ for j in range(N):
194
+ shuffled_image[i*block_height:(i+1)*block_height, j*block_width:(j+1)*block_width] = blocks[i*N+j]
195
+ return shuffled_image
196
+
197
+
198
+ def get_mosaic_mask(image, fg_mask, N=16, ratio = 0.5):
199
+ ids = [i for i in range(N * N)]
200
+ masked_number = int(N * N * ratio)
201
+ masked_id = np.random.choice(ids, masked_number, replace=False)
202
+
203
+
204
+
205
+ height, width = image.shape[:2]
206
+ mask = np.ones((height, width))
207
+
208
+ block_height = height // N
209
+ block_width = width // N
210
+
211
+ b_id = 0
212
+ for i in range(N):
213
+ for j in range(N):
214
+ if b_id in masked_id:
215
+ mask[i*block_height:(i+1)*block_height, j*block_width:(j+1)*block_width] = mask[i*block_height:(i+1)*block_height, j*block_width:(j+1)*block_width] * 0
216
+ b_id += 1
217
+ mask = mask * fg_mask
218
+ mask3 = np.stack([mask,mask,mask],-1).copy().astype(np.uint8)
219
+ noise = q_x(image)
220
+ noise_mask = image * mask3 + noise * (1-mask3)
221
+ return noise_mask
222
+
223
+ def extract_canney_noise(image, mask, dilate=True):
224
+ h,w = image.shape[0],image.shape[1]
225
+ mask = cv2.resize(mask.astype(np.uint8),(w,h)) > 0.5
226
+ kernel = np.ones((8, 8), dtype=np.uint8)
227
+ mask = cv2.erode(mask.astype(np.uint8), kernel, 10)
228
+
229
+ canny = cv2.Canny(image, 50,100) * mask
230
+ kernel = np.ones((8, 8), dtype=np.uint8)
231
+ mask = (cv2.dilate(canny, kernel, 5) > 128).astype(np.uint8)
232
+ mask = np.stack([mask,mask,mask],-1)
233
+
234
+ pure_noise = q_x(image, t=1) * 0 + 255
235
+ canny_noise = mask * image + (1-mask) * pure_noise
236
+ return canny_noise
237
+
238
+
239
+ def get_random_structure(size):
240
+ choice = np.random.randint(1, 5)
241
+
242
+ if choice == 1:
243
+ return cv2.getStructuringElement(cv2.MORPH_RECT, (size, size))
244
+ elif choice == 2:
245
+ return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
246
+ elif choice == 3:
247
+ return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size//2))
248
+ elif choice == 4:
249
+ return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size//2, size))
250
+
251
+ def random_dilate(seg, min=3, max=10):
252
+ size = np.random.randint(min, max)
253
+ kernel = get_random_structure(size)
254
+ seg = cv2.dilate(seg,kernel,iterations = 1)
255
+ return seg
256
+
257
+ def random_erode(seg, min=3, max=10):
258
+ size = np.random.randint(min, max)
259
+ kernel = get_random_structure(size)
260
+ seg = cv2.erode(seg,kernel,iterations = 1)
261
+ return seg
262
+
263
+ def compute_iou(seg, gt):
264
+ intersection = seg*gt
265
+ union = seg+gt
266
+ return (np.count_nonzero(intersection) + 1e-6) / (np.count_nonzero(union) + 1e-6)
267
+
268
+
269
+ def select_max_region(mask):
270
+ nums, labels, stats, centroids = cv2.connectedComponentsWithStats(mask, connectivity=8)
271
+ background = 0
272
+ for row in range(stats.shape[0]):
273
+ if stats[row, :][0] == 0 and stats[row, :][1] == 0:
274
+ background = row
275
+ stats_no_bg = np.delete(stats, background, axis=0)
276
+ max_idx = stats_no_bg[:, 4].argmax()
277
+ max_region = np.where(labels==max_idx+1, 1, 0)
278
+
279
+ return max_region.astype(np.uint8)
280
+
281
+
282
+
283
+ def perturb_mask(gt, min_iou = 0.3, max_iou = 0.99):
284
+ iou_target = np.random.uniform(min_iou, max_iou)
285
+ h, w = gt.shape
286
+ gt = gt.astype(np.uint8)
287
+ seg = gt.copy()
288
+
289
+ # Rare case
290
+ if h <= 2 or w <= 2:
291
+ print('GT too small, returning original')
292
+ return seg
293
+
294
+ # Do a bunch of random operations
295
+ for _ in range(250):
296
+ for _ in range(4):
297
+ lx, ly = np.random.randint(w), np.random.randint(h)
298
+ lw, lh = np.random.randint(lx+1,w+1), np.random.randint(ly+1,h+1)
299
+
300
+ # Randomly set one pixel to 1/0. With the following dilate/erode, we can create holes/external regions
301
+ if np.random.rand() < 0.1:
302
+ cx = int((lx + lw) / 2)
303
+ cy = int((ly + lh) / 2)
304
+ seg[cy, cx] = np.random.randint(2) * 255
305
+
306
+ # Dilate/erode
307
+ if np.random.rand() < 0.5:
308
+ seg[ly:lh, lx:lw] = random_dilate(seg[ly:lh, lx:lw])
309
+ else:
310
+ seg[ly:lh, lx:lw] = random_erode(seg[ly:lh, lx:lw])
311
+
312
+ seg = np.logical_or(seg, gt).astype(np.uint8)
313
+ #seg = select_max_region(seg)
314
+
315
+ if compute_iou(seg, gt) < iou_target:
316
+ break
317
+ seg = select_max_region(seg.astype(np.uint8))
318
+ return seg.astype(np.uint8)
319
+
320
+
321
+ def q_x(x_0,t=65):
322
+ '''Adding noise for and given image.'''
323
+ x_0 = torch.from_numpy(x_0).float() / 127.5 - 1
324
+ num_steps = 100
325
+
326
+ betas = torch.linspace(-6,6,num_steps)
327
+ betas = torch.sigmoid(betas)*(0.5e-2 - 1e-5)+1e-5
328
+
329
+ alphas = 1-betas
330
+ alphas_prod = torch.cumprod(alphas,0)
331
+
332
+ alphas_prod_p = torch.cat([torch.tensor([1]).float(),alphas_prod[:-1]],0)
333
+ alphas_bar_sqrt = torch.sqrt(alphas_prod)
334
+ one_minus_alphas_bar_log = torch.log(1 - alphas_prod)
335
+ one_minus_alphas_bar_sqrt = torch.sqrt(1 - alphas_prod)
336
+
337
+ noise = torch.randn_like(x_0)
338
+ alphas_t = alphas_bar_sqrt[t]
339
+ alphas_1_m_t = one_minus_alphas_bar_sqrt[t]
340
+ return (alphas_t * x_0 + alphas_1_m_t * noise).numpy() * 127.5 + 127.5
341
+
342
+
343
+ def extract_target_boundary(img, target_mask):
344
+ Ksize = 3
345
+ sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=Ksize)
346
+ sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=Ksize)
347
+
348
+ # sobel-x
349
+ sobel_X = cv2.convertScaleAbs(sobelx)
350
+ # sobel-y
351
+ sobel_Y = cv2.convertScaleAbs(sobely)
352
+ # sobel-xy
353
+ scharr = cv2.addWeighted(sobel_X, 0.5, sobel_Y, 0.5, 0)
354
+ scharr = np.max(scharr,-1).astype(np.float32)/255
355
+ scharr = scharr * target_mask.astype(np.float32)
356
+ return scharr
datasets/dreambooth.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+
11
+ class DreamBoothDataset(BaseDataset):
12
+ def __init__(self, fg_dir, bg_dir):
13
+ self.bg_dir = bg_dir
14
+ bg_data = os.listdir(self.bg_dir)
15
+ self.bg_data = [i for i in bg_data if 'mask' in i]
16
+ self.image_dir = fg_dir
17
+ self.data = os.listdir(self.image_dir)
18
+ self.size = (512,512)
19
+ self.clip_size = (224,224)
20
+ '''
21
+ Dynamic:
22
+ 0: Static View, High Quality
23
+ 1: Multi-view, Low Quality
24
+ 2: Multi-view, High Quality
25
+ '''
26
+ self.dynamic = 1
27
+
28
+ def __len__(self):
29
+ return len(self.data)
30
+
31
+ def __getitem__(self, idx):
32
+ idx = np.random.randint(0, len(self.data)-1)
33
+ item = self.get_sample(idx)
34
+ return item
35
+
36
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
37
+ pass_flag = True
38
+ H,W = image.shape[0], image.shape[1]
39
+ H,W = H * ratio, W * ratio
40
+ y1,y2,x1,x2 = yyxx
41
+ h,w = y2-y1,x2-x1
42
+ if mode == 'max':
43
+ if h > H and w > W:
44
+ pass_flag = False
45
+ elif mode == 'min':
46
+ if h < H and w < W:
47
+ pass_flag = False
48
+ return pass_flag
49
+
50
+ def get_alpha_mask(self, mask_path):
51
+ image = cv2.imread( mask_path, cv2.IMREAD_UNCHANGED)
52
+ mask = (image[:,:,-1] > 128).astype(np.uint8)
53
+ return mask
54
+
55
+ def get_sample(self, idx):
56
+ dir_name = self.data[idx]
57
+ dir_path = os.path.join(self.image_dir, dir_name)
58
+ images = os.listdir(dir_path)
59
+ image_name = [i for i in images if '.png' in i][0]
60
+ image_path = os.path.join(dir_path, image_name)
61
+
62
+ image = cv2.imread( image_path, cv2.IMREAD_UNCHANGED)
63
+ mask = (image[:,:,-1] > 128).astype(np.uint8)
64
+ image = image[:,:,:-1]
65
+
66
+ image = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB)
67
+ ref_image = image
68
+ ref_mask = mask
69
+ ref_image, ref_mask = expand_image_mask(image, mask, ratio=1.4)
70
+ bg_idx = np.random.randint(0, len(self.bg_data)-1)
71
+
72
+ tar_mask_name = self.bg_data[bg_idx]
73
+ tar_mask_path = os.path.join(self.bg_dir, tar_mask_name)
74
+ tar_image_path = tar_mask_path.replace('_mask','_GT')
75
+
76
+ tar_image = cv2.imread(tar_image_path).astype(np.uint8)
77
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
78
+ tar_mask = (cv2.imread(tar_mask_path) > 128).astype(np.uint8)[:,:,0]
79
+
80
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
81
+ sampled_time_steps = self.sample_timestep()
82
+ item_with_collage['time_steps'] = sampled_time_steps
83
+ return item_with_collage
84
+
datasets/dresscode.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ import albumentations as A
11
+
12
+ class DresscodeDataset(BaseDataset):
13
+ def __init__(self, image_dir):
14
+ self.image_root = image_dir
15
+ self.data = os.listdir(self.image_root)
16
+ self.size = (512,512)
17
+ self.clip_size = (224,224)
18
+ self.dynamic = 2
19
+
20
+ def __len__(self):
21
+ return 20000
22
+
23
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
24
+ pass_flag = True
25
+ H,W = image.shape[0], image.shape[1]
26
+ H,W = H * ratio, W * ratio
27
+ y1,y2,x1,x2 = yyxx
28
+ h,w = y2-y1,x2-x1
29
+ if mode == 'max':
30
+ if h > H and w > W:
31
+ pass_flag = False
32
+ elif mode == 'min':
33
+ if h < H and w < W:
34
+ pass_flag = False
35
+ return pass_flag
36
+
37
+ def get_sample(self, idx):
38
+ tar_mask_path = os.path.join(self.image_root, self.data[idx])
39
+ tar_image_path = tar_mask_path.replace('label_maps/','images/').replace('_4.png','_0.jpg')
40
+ ref_image_path = tar_mask_path.replace('label_maps/','images/').replace('_4.png','_1.jpg')
41
+
42
+ # Read Image and Mask
43
+ ref_image = cv2.imread(ref_image_path)
44
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
45
+
46
+ tar_image = cv2.imread(tar_image_path)
47
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
48
+
49
+ ref_mask = (ref_image < 240).astype(np.uint8)[:,:,0]
50
+
51
+
52
+ tar_mask = Image.open(tar_mask_path ).convert('P')
53
+ tar_mask= np.array(tar_mask)
54
+ tar_mask = tar_mask == 4
55
+
56
+
57
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask, max_ratio = 1.0)
58
+ sampled_time_steps = self.sample_timestep()
59
+ item_with_collage['time_steps'] = sampled_time_steps
60
+ return item_with_collage
61
+
datasets/fashiontryon.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ import albumentations as A
11
+
12
+ class FashionTryonDataset(BaseDataset):
13
+ def __init__(self, image_dir):
14
+ self.image_root = image_dir
15
+ self.data =os.listdir(self.image_root)
16
+ self.size = (512,512)
17
+ self.clip_size = (224,224)
18
+ self.dynamic = 2
19
+
20
+ def __len__(self):
21
+ return 5000
22
+
23
+ def aug_data(self, image):
24
+ transform = A.Compose([
25
+ A.RandomBrightnessContrast(p=0.5),
26
+ ])
27
+ transformed = transform(image=image.astype(np.uint8))
28
+ transformed_image = transformed["image"]
29
+ return transformed_image
30
+
31
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
32
+ pass_flag = True
33
+ H,W = image.shape[0], image.shape[1]
34
+ H,W = H * ratio, W * ratio
35
+ y1,y2,x1,x2 = yyxx
36
+ h,w = y2-y1,x2-x1
37
+ if mode == 'max':
38
+ if h > H and w > W:
39
+ pass_flag = False
40
+ elif mode == 'min':
41
+ if h < H and w < W:
42
+ pass_flag = False
43
+ return pass_flag
44
+
45
+ def get_sample(self, idx):
46
+ cloth_dir = os.path.join(self.image_root, self.data[idx])
47
+ ref_image_path = os.path.join(cloth_dir, 'target.jpg')
48
+
49
+ ref_image = cv2.imread(ref_image_path)
50
+ ref_image = cv2.cvtColor(ref_image.copy(), cv2.COLOR_BGR2RGB)
51
+
52
+ ref_mask_path = os.path.join(cloth_dir,'mask.jpg')
53
+ ref_mask = cv2.imread(ref_mask_path)[:,:,0] > 128
54
+
55
+ target_dirs = [i for i in os.listdir(cloth_dir ) if '.jpg' not in i]
56
+ target_dir_name = np.random.choice(target_dirs)
57
+
58
+ target_image_path = os.path.join(cloth_dir, target_dir_name + '.jpg')
59
+ target_image= cv2.imread(target_image_path)
60
+ tar_image = cv2.cvtColor(target_image.copy(), cv2.COLOR_BGR2RGB)
61
+
62
+ target_mask_path = os.path.join(cloth_dir, target_dir_name, 'segment.png')
63
+ tar_mask= cv2.imread(target_mask_path)[:,:,0]
64
+ target_mask = tar_mask == 7
65
+ kernel = np.ones((3, 3), dtype=np.uint8)
66
+ tar_mask = cv2.erode(target_mask.astype(np.uint8), kernel, iterations=3)
67
+
68
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask, max_ratio = 1.0)
69
+ sampled_time_steps = self.sample_timestep()
70
+ item_with_collage['time_steps'] = sampled_time_steps
71
+ return item_with_collage
72
+
73
+
74
+
75
+
datasets/lvis.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ from pycocotools import mask as mask_utils
11
+ from lvis import LVIS
12
+
13
+ class LvisDataset(BaseDataset):
14
+ def __init__(self, image_dir, json_path):
15
+ self.image_dir = image_dir
16
+ self.json_path = json_path
17
+ lvis_api = LVIS(json_path)
18
+ img_ids = sorted(lvis_api.imgs.keys())
19
+ imgs = lvis_api.load_imgs(img_ids)
20
+ anns = [lvis_api.img_ann_map[img_id] for img_id in img_ids]
21
+ self.data = imgs
22
+ self.annos = anns
23
+ self.lvis_api = lvis_api
24
+ self.size = (512,512)
25
+ self.clip_size = (224,224)
26
+ self.dynamic = 0
27
+
28
+ def register_subset(self, path):
29
+ data = os.listdir(path)
30
+ data = [ os.path.join(path, i) for i in data if '.json' in i]
31
+ self.data = self.data + data
32
+
33
+ def get_sample(self, idx):
34
+ # ==== get pairs =====
35
+ image_name = self.data[idx]['coco_url'].split('/')[-1]
36
+ image_path = os.path.join(self.image_dir, image_name)
37
+ image = cv2.imread(image_path)
38
+ ref_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
39
+
40
+ anno = self.annos[idx]
41
+ obj_ids = []
42
+ for i in range(len(anno)):
43
+ obj = anno[i]
44
+ area = obj['area']
45
+ if area > 3600:
46
+ obj_ids.append(i)
47
+ assert len(anno) > 0
48
+ obj_id = np.random.choice(obj_ids)
49
+ anno = anno[obj_id]
50
+ ref_mask = self.lvis_api.ann_to_mask(anno)
51
+
52
+ tar_image, tar_mask = ref_image.copy(), ref_mask.copy()
53
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
54
+ sampled_time_steps = self.sample_timestep()
55
+ item_with_collage['time_steps'] = sampled_time_steps
56
+ return item_with_collage
57
+
58
+ def __len__(self):
59
+ return 20000
60
+
61
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
62
+ pass_flag = True
63
+ H,W = image.shape[0], image.shape[1]
64
+ H,W = H * ratio, W * ratio
65
+ y1,y2,x1,x2 = yyxx
66
+ h,w = y2-y1,x2-x1
67
+ if mode == 'max':
68
+ if h > H or w > W:
69
+ pass_flag = False
70
+ elif mode == 'min':
71
+ if h < H or w < W:
72
+ pass_flag = False
73
+ return pass_flag
74
+
75
+
76
+
77
+
datasets/mose.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from PIL import Image
10
+ from .base import BaseDataset
11
+
12
+ class MoseDataset(BaseDataset):
13
+ def __init__(self, image_dir, anno):
14
+ self.image_root = image_dir
15
+ self.anno_root = anno
16
+
17
+ video_dirs = []
18
+ video_dirs = os.listdir(self.image_root)
19
+ self.data = video_dirs
20
+ self.size = (512,512)
21
+ self.clip_size = (224,224)
22
+ self.dynamic = 2
23
+
24
+ def __len__(self):
25
+ return 40000
26
+
27
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
28
+ pass_flag = True
29
+ H,W = image.shape[0], image.shape[1]
30
+ H,W = H * ratio, W * ratio
31
+ y1,y2,x1,x2 = yyxx
32
+ h,w = y2-y1,x2-x1
33
+ if mode == 'max':
34
+ if h > H or w > W:
35
+ pass_flag = False
36
+ elif mode == 'min':
37
+ if h < H or w < W:
38
+ pass_flag = False
39
+ return pass_flag
40
+
41
+ def get_sample(self, idx):
42
+ video_name = self.data[idx]
43
+ video_path = os.path.join(self.image_root, video_name)
44
+ frames = os.listdir(video_path)
45
+
46
+ # Sampling frames
47
+ min_interval = len(frames) // 10
48
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
49
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
50
+ end_frame_index = min(end_frame_index, len(frames) - 1)
51
+
52
+ # Get image path
53
+ ref_image_name = frames[start_frame_index]
54
+ tar_image_name = frames[end_frame_index]
55
+ ref_image_path = os.path.join(self.image_root, video_name, ref_image_name)
56
+ tar_image_path = os.path.join(self.image_root, video_name, tar_image_name)
57
+
58
+ ref_mask_path = ref_image_path.replace('JPEGImages','Annotations').replace('.jpg', '.png')
59
+ tar_mask_path = tar_image_path.replace('JPEGImages','Annotations').replace('.jpg', '.png')
60
+
61
+ # Read Image and Mask
62
+ ref_image = cv2.imread(ref_image_path)
63
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
64
+
65
+ tar_image = cv2.imread(tar_image_path)
66
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
67
+
68
+ ref_mask = Image.open(ref_mask_path ).convert('P')
69
+ ref_mask= np.array(ref_mask)
70
+
71
+ tar_mask = Image.open(tar_mask_path ).convert('P')
72
+ tar_mask= np.array(tar_mask)
73
+
74
+ ref_ids = np.unique(ref_mask)
75
+ tar_ids = np.unique(tar_mask)
76
+
77
+ common_ids = list(np.intersect1d(ref_ids, tar_ids))
78
+ common_ids = [ i for i in common_ids if i != 0 ]
79
+ assert len(common_ids) > 0
80
+ chosen_id = np.random.choice(common_ids)
81
+ ref_mask = ref_mask == chosen_id
82
+ tar_mask = tar_mask == chosen_id
83
+ len_mask = len( self.check_connect( ref_mask.astype(np.uint8) ) )
84
+ assert len_mask == 1
85
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
86
+ sampled_time_steps = self.sample_timestep()
87
+ item_with_collage['time_steps'] = sampled_time_steps
88
+ return item_with_collage
89
+
90
+ def check_connect(self, mask):
91
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
92
+ cnt_area = [cv2.contourArea(cnt) for cnt in contours]
93
+ return cnt_area
94
+
datasets/mvimagenet.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+
11
+ class MVImageNetDataset(BaseDataset):
12
+ def __init__(self, txt, image_dir):
13
+ with open(txt,"r") as f:
14
+ data = f.read().split('\n')[:-1]
15
+ self.image_dir = image_dir
16
+ self.data = data
17
+ self.size = (512,512)
18
+ self.clip_size = (224,224)
19
+ self.dynamic = 2
20
+
21
+ def __len__(self):
22
+ return 40000
23
+
24
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
25
+ pass_flag = True
26
+ H,W = image.shape[0], image.shape[1]
27
+ H,W = H * ratio, W * ratio
28
+ y1,y2,x1,x2 = yyxx
29
+ h,w = y2-y1,x2-x1
30
+ if mode == 'max':
31
+ if h > H and w > W:
32
+ pass_flag = False
33
+ elif mode == 'min':
34
+ if h < H and w < W:
35
+ pass_flag = False
36
+ return pass_flag
37
+
38
+ def get_alpha_mask(self, mask_path):
39
+ image = cv2.imread( mask_path, cv2.IMREAD_UNCHANGED)
40
+ mask = (image[:,:,-1] > 128).astype(np.uint8)
41
+ return mask
42
+
43
+ def get_sample(self, idx):
44
+ object_dir = self.data[idx].replace('MVDir/', self.image_dir)
45
+ frames = os.listdir(object_dir)
46
+ frames = [ i for i in frames if '.png' in i]
47
+
48
+ # Sampling frames
49
+ min_interval = len(frames) // 8
50
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
51
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
52
+ end_frame_index = min(end_frame_index, len(frames) - 1)
53
+
54
+ # Get image path
55
+ ref_mask_name = frames[start_frame_index]
56
+ tar_mask_name = frames[end_frame_index]
57
+
58
+ ref_image_name = ref_mask_name.split('_')[0] + '.jpg'
59
+ tar_image_name = tar_mask_name.split('_')[0] + '.jpg'
60
+
61
+ ref_mask_path = os.path.join(object_dir, ref_mask_name)
62
+ tar_mask_path = os.path.join(object_dir, tar_mask_name)
63
+ ref_image_path = os.path.join(object_dir, ref_image_name)
64
+ tar_image_path = os.path.join(object_dir, tar_image_name)
65
+
66
+ # Read Image and Mask
67
+ ref_image = cv2.imread(ref_image_path).astype(np.uint8)
68
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
69
+
70
+ tar_image = cv2.imread(tar_image_path).astype(np.uint8)
71
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
72
+
73
+ ref_mask = self.get_alpha_mask(ref_mask_path)
74
+ tar_mask = self.get_alpha_mask(tar_mask_path)
75
+
76
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
77
+ sampled_time_steps = self.sample_timestep()
78
+ item_with_collage['time_steps'] = sampled_time_steps
79
+
80
+ return item_with_collage
81
+
datasets/saliency_modular.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+
11
+ class SaliencyDataset(BaseDataset):
12
+ def __init__(self, MSRA_root, TR_root, TE_root, HFlickr_root):
13
+ image_mask_dict = {}
14
+
15
+ # ====== MSRA-10k ======
16
+ file_lst = os.listdir(MSRA_root)
17
+ image_lst = [MSRA_root+i for i in file_lst if '.jpg' in i]
18
+ for i in image_lst:
19
+ mask_path = i.replace('.jpg','.png')
20
+ image_mask_dict[i] = mask_path
21
+
22
+ # ===== DUT-TR ========
23
+ file_lst = os.listdir(TR_root)
24
+ image_lst = [TR_root+i for i in file_lst if '.jpg' in i]
25
+ for i in image_lst:
26
+ mask_path = i.replace('.jpg','.png').replace('DUTS-TR-Image','DUTS-TR-Mask')
27
+ image_mask_dict[i] = mask_path
28
+
29
+ # ===== DUT-TE ========
30
+ file_lst = os.listdir(TE_root)
31
+ image_lst = [TE_root+i for i in file_lst if '.jpg' in i]
32
+ for i in image_lst:
33
+ mask_path = i.replace('.jpg','.png').replace('DUTS-TE-Image','DUTS-TE-Mask')
34
+ image_mask_dict[i] = mask_path
35
+
36
+ # ===== HFlickr =======
37
+ file_lst = os.listdir(HFlickr_root)
38
+ mask_list = [HFlickr_root+i for i in file_lst if '.png' in i]
39
+ for i in file_lst:
40
+ image_name = i.split('_')[0] +'.jpg'
41
+ image_path = HFlickr_root.replace('masks', 'real_images') + image_name
42
+ mask_path = HFlickr_root + i
43
+ image_mask_dict[image_path] = mask_path
44
+
45
+ self.image_mask_dict = image_mask_dict
46
+ self.data = list(self.image_mask_dict.keys() )
47
+ self.size = (512,512)
48
+ self.clip_size = (224,224)
49
+ self.dynamic = 0
50
+
51
+ def __len__(self):
52
+ return 20000
53
+
54
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
55
+ pass_flag = True
56
+ H,W = image.shape[0], image.shape[1]
57
+ H,W = H * ratio, W * ratio
58
+ y1,y2,x1,x2 = yyxx
59
+ h,w = y2-y1,x2-x1
60
+ if mode == 'max':
61
+ if h > H or w > W:
62
+ pass_flag = False
63
+ elif mode == 'min':
64
+ if h < H or w < W:
65
+ pass_flag = False
66
+ return pass_flag
67
+
68
+ def get_sample(self, idx):
69
+
70
+ # ==== get pairs =====
71
+ image_path = self.data[idx]
72
+ mask_path = self.image_mask_dict[image_path]
73
+
74
+ instances_mask = cv2.imread(mask_path)
75
+ if len(instances_mask.shape) == 3:
76
+ instances_mask = instances_mask[:,:,0]
77
+ instances_mask = (instances_mask > 128).astype(np.uint8)
78
+ # ======================
79
+ ref_image = cv2.imread(image_path)
80
+ ref_image = cv2.cvtColor(ref_image.copy(), cv2.COLOR_BGR2RGB)
81
+ tar_image = ref_image
82
+
83
+ ref_mask = instances_mask
84
+ tar_mask = instances_mask
85
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
86
+ sampled_time_steps = self.sample_timestep()
87
+ item_with_collage['time_steps'] = sampled_time_steps
88
+ return item_with_collage
89
+
90
+
91
+
datasets/sam.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ from pycocotools import mask as mask_utils
11
+
12
+ class SAMDataset(BaseDataset):
13
+ def __init__(self, sub1, sub2, sub3, sub4):
14
+ image_mask_dict = {}
15
+ self.data = []
16
+ self.register_subset(sub1)
17
+ self.register_subset(sub2)
18
+ self.register_subset(sub3)
19
+ self.register_subset(sub4)
20
+ self.size = (512,512)
21
+ self.clip_size = (224,224)
22
+ self.dynamic = 0
23
+
24
+ def register_subset(self, path):
25
+ data = os.listdir(path)
26
+ data = [ os.path.join(path, i) for i in data if '.json' in i]
27
+ self.data = self.data + data
28
+
29
+ def get_sample(self, idx):
30
+ # ==== get pairs =====
31
+ json_path = self.data[idx]
32
+ image_path = json_path.replace('.json', '.jpg')
33
+
34
+ with open(json_path, 'r') as json_file:
35
+ data = json.load(json_file)
36
+ annotation = data['annotations']
37
+
38
+ valid_ids = []
39
+ for i in range(len(annotation)):
40
+ area = annotation[i]['area']
41
+ if area > 100 * 100 * 5:
42
+ valid_ids.append(i)
43
+
44
+ chosen_id = np.random.choice(valid_ids)
45
+ mask = mask_utils.decode(annotation[chosen_id]["segmentation"] )
46
+ # ======================
47
+
48
+ image = cv2.imread(image_path)
49
+ ref_image = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB)
50
+ tar_image = ref_image
51
+
52
+ ref_mask = mask
53
+ tar_mask = mask
54
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
55
+ sampled_time_steps = self.sample_timestep()
56
+ item_with_collage['time_steps'] = sampled_time_steps
57
+ return item_with_collage
58
+
59
+ def __len__(self):
60
+ return 20000
61
+
62
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
63
+ pass_flag = True
64
+ H,W = image.shape[0], image.shape[1]
65
+ H,W = H * ratio, W * ratio
66
+ y1,y2,x1,x2 = yyxx
67
+ h,w = y2-y1,x2-x1
68
+ if mode == 'max':
69
+ if h > H or w > W:
70
+ pass_flag = False
71
+ elif mode == 'min':
72
+ if h < H or w < W:
73
+ pass_flag = False
74
+ return pass_flag
75
+
76
+
77
+
78
+
datasets/uvo.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ from pycocotools import mask as mask_utils
11
+
12
+ class UVODataset(BaseDataset):
13
+ def __init__(self, image_dir, video_json, image_json):
14
+ json_path = video_json
15
+ with open(json_path, 'r') as fcc_file:
16
+ data = json.load(fcc_file)
17
+
18
+ image_json_path = image_json
19
+ with open(image_json_path , 'r') as image_file:
20
+ video_dict = json.load(image_file)
21
+
22
+ self.image_root = image_dir
23
+ self.data = data['annotations']
24
+ self.video_dict = video_dict
25
+ self.size = (512,512)
26
+ self.clip_size = (224,224)
27
+ self.dynamic = 1
28
+
29
+ def __len__(self):
30
+ return 25000
31
+
32
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
33
+ pass_flag = True
34
+ H,W = image.shape[0], image.shape[1]
35
+ H,W = H * ratio, W * ratio
36
+ y1,y2,x1,x2 = yyxx
37
+ h,w = y2-y1,x2-x1
38
+ if mode == 'max':
39
+ if h > H and w > W:
40
+ pass_flag = False
41
+ elif mode == 'min':
42
+ if h < H and w < W:
43
+ pass_flag = False
44
+ return pass_flag
45
+
46
+ def get_sample(self, idx):
47
+ ins_anno = self.data[idx]
48
+ video_id = str(ins_anno['video_id'])
49
+ video_names = self.video_dict[video_id]
50
+ masks = ins_anno['segmentations']
51
+ frames = video_names
52
+
53
+ # Sampling frames
54
+ min_interval = len(frames) // 10
55
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
56
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
57
+ end_frame_index = min(end_frame_index, len(frames) - 1)
58
+
59
+ # Get image path
60
+ ref_image_name = frames[start_frame_index]
61
+ tar_image_name = frames[end_frame_index]
62
+ ref_image_path = os.path.join(self.image_root, ref_image_name)
63
+ tar_image_path = os.path.join(self.image_root, tar_image_name)
64
+
65
+ # Read Image and Mask
66
+ ref_image = cv2.imread(ref_image_path)
67
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
68
+
69
+ tar_image = cv2.imread(tar_image_path)
70
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
71
+
72
+ ref_mask = mask_utils.decode(masks[start_frame_index])
73
+ tar_mask = mask_utils.decode(masks[end_frame_index])
74
+
75
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
76
+ sampled_time_steps = self.sample_timestep()
77
+ item_with_collage['time_steps'] = sampled_time_steps
78
+ return item_with_collage
79
+
datasets/uvo_val.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ from pycocotools import mask as mask_utils
11
+
12
+ class UVOValDataset(BaseDataset):
13
+ def __init__(self, image_dir, video_json, image_json):
14
+ json_path = video_json
15
+ with open(json_path, 'r') as fcc_file:
16
+ data = json.load(fcc_file)
17
+ image_json_path = image_json
18
+ with open(image_json_path , 'r') as image_file:
19
+ video_dict = json.load(image_file)
20
+ self.image_root = image_dir
21
+ self.data = data['annotations']
22
+ self.video_dict = video_dict
23
+ self.size = (512,512)
24
+ self.clip_size = (224,224)
25
+ self.dynamic = 1
26
+
27
+ def __len__(self):
28
+ return 8000
29
+
30
+ def __getitem__(self, idx):
31
+ while(1):
32
+ idx = np.random.randint(0, len(self.data)-1)
33
+ try:
34
+ item = self.get_sample(idx)
35
+ return item
36
+ except:
37
+ idx = np.random.randint(0, len(self.data)-1)
38
+
39
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
40
+ pass_flag = True
41
+ H,W = image.shape[0], image.shape[1]
42
+ H,W = H * ratio, W * ratio
43
+ y1,y2,x1,x2 = yyxx
44
+ h,w = y2-y1,x2-x1
45
+ if mode == 'max':
46
+ if h > H and w > W:
47
+ pass_flag = False
48
+ elif mode == 'min':
49
+ if h < H and w < W:
50
+ pass_flag = False
51
+ return pass_flag
52
+
53
+ def get_sample(self, idx):
54
+ ins_anno = self.data[idx]
55
+ video_id = str(ins_anno['video_id'])
56
+
57
+ video_names = self.video_dict[video_id]
58
+ masks = ins_anno['segmentations']
59
+ frames = video_names
60
+
61
+ # Sampling frames
62
+ min_interval = len(frames) // 5
63
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
64
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
65
+ end_frame_index = min(end_frame_index, len(frames) - 1)
66
+
67
+ # Get image path
68
+ ref_image_name = frames[start_frame_index]
69
+ tar_image_name = frames[end_frame_index]
70
+ ref_image_path = os.path.join(self.image_root, ref_image_name)
71
+ tar_image_path = os.path.join(self.image_root, tar_image_name)
72
+
73
+ # Read Image and Mask
74
+ ref_image = cv2.imread(ref_image_path)
75
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
76
+
77
+ tar_image = cv2.imread(tar_image_path)
78
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
79
+
80
+ ref_mask = mask_utils.decode(masks[start_frame_index])
81
+ tar_mask = mask_utils.decode(masks[end_frame_index])
82
+
83
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
84
+ sampled_time_steps = self.sample_timestep()
85
+ item_with_collage['time_steps'] = sampled_time_steps
86
+ return item_with_collage
87
+
datasets/vipseg.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from panopticapi.utils import rgb2id
10
+ from PIL import Image
11
+ from .base import BaseDataset
12
+
13
+ class VIPSegDataset(BaseDataset):
14
+ def __init__(self, image_dir, anno):
15
+ self.image_root = image_dir
16
+ self.anno_root = anno
17
+ video_dirs = []
18
+ video_dirs = os.listdir(self.image_root)
19
+ self.data = video_dirs
20
+ self.size = (512,512)
21
+ self.clip_size = (224,224)
22
+ self.dynamic = 1
23
+
24
+ def __len__(self):
25
+ return 30000
26
+
27
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
28
+ pass_flag = True
29
+ H,W = image.shape[0], image.shape[1]
30
+ H,W = H * ratio, W * ratio
31
+ y1,y2,x1,x2 = yyxx
32
+ h,w = y2-y1,x2-x1
33
+ if mode == 'max':
34
+ if h > H or w > W:
35
+ pass_flag = False
36
+ elif mode == 'min':
37
+ if h < H or w < W:
38
+ pass_flag = False
39
+ return pass_flag
40
+
41
+ def get_sample(self, idx):
42
+ video_name = self.data[idx]
43
+ video_path = os.path.join(self.image_root, video_name)
44
+ frames = os.listdir(video_path)
45
+
46
+ # Sampling frames
47
+ min_interval = len(frames) // 100
48
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
49
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
50
+ end_frame_index = min(end_frame_index, len(frames) - 1)
51
+
52
+ # Get image path
53
+ ref_image_name = frames[start_frame_index]
54
+ tar_image_name = frames[end_frame_index]
55
+ ref_image_path = os.path.join(self.image_root, video_name, ref_image_name)
56
+ tar_image_path = os.path.join(self.image_root, video_name, tar_image_name)
57
+
58
+ ref_mask_path = ref_image_path.replace('images','panomasksRGB').replace('.jpg', '.png')
59
+ tar_mask_path = tar_image_path.replace('images','panomasksRGB').replace('.jpg', '.png')
60
+
61
+ # Read Image and Mask
62
+ ref_image = cv2.imread(ref_image_path)
63
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
64
+
65
+ tar_image = cv2.imread(tar_image_path)
66
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
67
+
68
+ ref_mask = np.array(Image.open(ref_mask_path).convert('RGB'))
69
+ ref_mask = rgb2id(ref_mask)
70
+
71
+ tar_mask = np.array(Image.open(tar_mask_path).convert('RGB'))
72
+ tar_mask = rgb2id(tar_mask)
73
+
74
+ ref_ids = np.unique(ref_mask)
75
+ tar_ids = np.unique(tar_mask)
76
+
77
+ common_ids = list(np.intersect1d(ref_ids, tar_ids))
78
+ common_ids = [ i for i in common_ids if i != 0 ]
79
+
80
+ chosen_id = np.random.choice(common_ids)
81
+ ref_mask = ref_mask == chosen_id
82
+ tar_mask = tar_mask == chosen_id
83
+
84
+ len_mask = len( self.check_connect( ref_mask.astype(np.uint8) ) )
85
+ assert len_mask == 1
86
+
87
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
88
+ sampled_time_steps = self.sample_timestep()
89
+ item_with_collage['time_steps'] = sampled_time_steps
90
+ return item_with_collage
91
+
92
+ def check_connect(self, mask):
93
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
94
+ cnt_area = [cv2.contourArea(cnt) for cnt in contours]
95
+ return cnt_area
96
+
datasets/vitonhd.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+ import albumentations as A
11
+
12
+ class VitonHDDataset(BaseDataset):
13
+ def __init__(self, image_dir):
14
+ self.image_root = image_dir
15
+ self.data = os.listdir(self.image_root)
16
+ self.size = (512,512)
17
+ self.clip_size = (224,224)
18
+ self.dynamic = 2
19
+
20
+ def __len__(self):
21
+ return 20000
22
+
23
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
24
+ pass_flag = True
25
+ H,W = image.shape[0], image.shape[1]
26
+ H,W = H * ratio, W * ratio
27
+ y1,y2,x1,x2 = yyxx
28
+ h,w = y2-y1,x2-x1
29
+ if mode == 'max':
30
+ if h > H and w > W:
31
+ pass_flag = False
32
+ elif mode == 'min':
33
+ if h < H and w < W:
34
+ pass_flag = False
35
+ return pass_flag
36
+
37
+ def get_sample(self, idx):
38
+
39
+ ref_image_path = os.path.join(self.image_root, self.data[idx])
40
+ tar_image_path = ref_image_path.replace('/cloth/', '/image/')
41
+ ref_mask_path = ref_image_path.replace('/cloth/','/cloth-mask/')
42
+ tar_mask_path = ref_image_path.replace('/cloth/', '/image-parse-v3/').replace('.jpg','.png')
43
+
44
+ # Read Image and Mask
45
+ ref_image = cv2.imread(ref_image_path)
46
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
47
+
48
+ tar_image = cv2.imread(tar_image_path)
49
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
50
+
51
+ ref_mask = (cv2.imread(ref_mask_path) > 128).astype(np.uint8)[:,:,0]
52
+
53
+ tar_mask = Image.open(tar_mask_path ).convert('P')
54
+ tar_mask= np.array(tar_mask)
55
+ tar_mask = tar_mask == 5
56
+
57
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask, max_ratio = 1.0)
58
+ sampled_time_steps = self.sample_timestep()
59
+ item_with_collage['time_steps'] = sampled_time_steps
60
+ return item_with_collage
61
+
datasets/ytb_vis.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+
11
+ class YoutubeVISDataset(BaseDataset):
12
+ def __init__(self, image_dir, anno, meta):
13
+ self.image_root = image_dir
14
+ self.anno_root = anno
15
+ self.meta_file = meta
16
+
17
+ video_dirs = []
18
+ with open(self.meta_file) as f:
19
+ records = json.load(f)
20
+ records = records["videos"]
21
+ for video_id in records:
22
+ video_dirs.append(video_id)
23
+
24
+ self.records = records
25
+ self.data = video_dirs
26
+ self.size = (512,512)
27
+ self.clip_size = (224,224)
28
+ self.dynamic = 1
29
+
30
+ def __len__(self):
31
+ return 40000
32
+
33
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
34
+ pass_flag = True
35
+ H,W = image.shape[0], image.shape[1]
36
+ H,W = H * ratio, W * ratio
37
+ y1,y2,x1,x2 = yyxx
38
+ h,w = y2-y1,x2-x1
39
+ if mode == 'max':
40
+ if h > H and w > W:
41
+ pass_flag = False
42
+ elif mode == 'min':
43
+ if h < H and w < W:
44
+ pass_flag = False
45
+ return pass_flag
46
+
47
+ def get_sample(self, idx):
48
+ video_id = list(self.records.keys())[idx]
49
+ objects_id = np.random.choice( list(self.records[video_id]["objects"].keys()) )
50
+ frames = self.records[video_id]["objects"][objects_id]["frames"]
51
+
52
+ # Sampling frames
53
+ min_interval = len(frames) // 10
54
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
55
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
56
+ end_frame_index = min(end_frame_index, len(frames) - 1)
57
+
58
+ # Get image path
59
+ ref_image_name = frames[start_frame_index]
60
+ tar_image_name = frames[end_frame_index]
61
+ ref_image_path = os.path.join(self.image_root, video_id, ref_image_name) + '.jpg'
62
+ tar_image_path = os.path.join(self.image_root, video_id, tar_image_name) + '.jpg'
63
+ ref_mask_path = ref_image_path.replace('JPEGImages','Annotations').replace('.jpg', '.png')
64
+ tar_mask_path = tar_image_path.replace('JPEGImages','Annotations').replace('.jpg', '.png')
65
+
66
+ # Read Image and Mask
67
+ ref_image = cv2.imread(ref_image_path)
68
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
69
+
70
+ tar_image = cv2.imread(tar_image_path)
71
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
72
+
73
+ ref_mask = Image.open(ref_mask_path ).convert('P')
74
+ ref_mask= np.array(ref_mask)
75
+ ref_mask = ref_mask == int(objects_id)
76
+
77
+ tar_mask = Image.open(tar_mask_path ).convert('P')
78
+ tar_mask= np.array(tar_mask)
79
+ tar_mask = tar_mask == int(objects_id)
80
+
81
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
82
+ sampled_time_steps = self.sample_timestep()
83
+ item_with_collage['time_steps'] = sampled_time_steps
84
+ return item_with_collage
85
+
datasets/ytb_vos.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import cv2
3
+ import numpy as np
4
+ import os
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ import cv2
8
+ from .data_utils import *
9
+ from .base import BaseDataset
10
+
11
+ class YoutubeVOSDataset(BaseDataset):
12
+ def __init__(self, image_dir, anno, meta):
13
+ self.image_root = image_dir
14
+ self.anno_root = anno
15
+ self.meta_file = meta
16
+
17
+ video_dirs = []
18
+ with open(self.meta_file) as f:
19
+ records = json.load(f)
20
+ records = records["videos"]
21
+ for video_id in records:
22
+ video_dirs.append(video_id)
23
+
24
+ self.records = records
25
+ self.data = video_dirs
26
+ self.size = (512,512)
27
+ self.clip_size = (224,224)
28
+ self.dynamic = 1
29
+
30
+ def __len__(self):
31
+ return 40000
32
+
33
+ def check_region_size(self, image, yyxx, ratio, mode = 'max'):
34
+ pass_flag = True
35
+ H,W = image.shape[0], image.shape[1]
36
+ H,W = H * ratio, W * ratio
37
+ y1,y2,x1,x2 = yyxx
38
+ h,w = y2-y1,x2-x1
39
+ if mode == 'max':
40
+ if h > H and w > W:
41
+ pass_flag = False
42
+ elif mode == 'min':
43
+ if h < H and w < W:
44
+ pass_flag = False
45
+ return pass_flag
46
+
47
+ def get_sample(self, idx):
48
+ video_id = list(self.records.keys())[idx]
49
+ objects_id = np.random.choice( list(self.records[video_id]["objects"].keys()) )
50
+ frames = self.records[video_id]["objects"][objects_id]["frames"]
51
+
52
+ # Sampling frames
53
+ min_interval = len(frames) // 10
54
+ start_frame_index = np.random.randint(low=0, high=len(frames) - min_interval)
55
+ end_frame_index = start_frame_index + np.random.randint(min_interval, len(frames) - start_frame_index )
56
+ end_frame_index = min(end_frame_index, len(frames) - 1)
57
+
58
+ # Get image path
59
+ ref_image_name = frames[start_frame_index]
60
+ tar_image_name = frames[end_frame_index]
61
+ ref_image_path = os.path.join(self.image_root, video_id, ref_image_name) + '.jpg'
62
+ tar_image_path = os.path.join(self.image_root, video_id, tar_image_name) + '.jpg'
63
+ ref_mask_path = ref_image_path.replace('JPEGImages','Annotations').replace('.jpg', '.png')
64
+ tar_mask_path = tar_image_path.replace('JPEGImages','Annotations').replace('.jpg', '.png')
65
+
66
+ # Read Image and Mask
67
+ ref_image = cv2.imread(ref_image_path)
68
+ ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB)
69
+
70
+ tar_image = cv2.imread(tar_image_path)
71
+ tar_image = cv2.cvtColor(tar_image, cv2.COLOR_BGR2RGB)
72
+
73
+ ref_mask = Image.open(ref_mask_path ).convert('P')
74
+ ref_mask= np.array(ref_mask)
75
+ ref_mask = ref_mask == int(objects_id)
76
+
77
+ tar_mask = Image.open(tar_mask_path ).convert('P')
78
+ tar_mask= np.array(tar_mask)
79
+ tar_mask = tar_mask == int(objects_id)
80
+
81
+
82
+ item_with_collage = self.process_pairs(ref_image, ref_mask, tar_image, tar_mask)
83
+ sampled_time_steps = self.sample_timestep()
84
+ item_with_collage['time_steps'] = sampled_time_steps
85
+ return item_with_collage
86
+
87
+
dinov2/.github/workflows/lint.yaml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Lint
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - master
10
+ - 'gh/**'
11
+
12
+ jobs:
13
+ run-linters:
14
+ name: Run linters
15
+ runs-on: ubuntu-20.04
16
+
17
+ steps:
18
+ - name: Checkout repository
19
+ uses: actions/checkout@v3
20
+ - name: Set up Python
21
+ uses: actions/setup-python@v4
22
+ with:
23
+ python-version: 3.9
24
+ cache: 'pip'
25
+ cache-dependency-path: '**/requirements*.txt'
26
+ - name: Install Python (development) dependencies
27
+ run: |
28
+ pip install -r requirements-dev.txt
29
+ - name: Run flake8
30
+ run: |
31
+ flake8
32
+ - name: Run black
33
+ if: always()
34
+ run: |
35
+ black --check dinov2
36
+ - name: Run pylint
37
+ if: always()
38
+ run: |
39
+ pylint --exit-zero dinov2
dinov2/.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ build/
2
+ dist/
3
+ *.egg-info/
4
+ **/__pycache__/
5
+
6
+ **/.ipynb_checkpoints
7
+ **/.ipynb_checkpoints/**
8
+
9
+ **/notebooks
10
+
11
+ *.swp
12
+
13
+ .vscode/
dinov2/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <opensource-conduct@meta.com>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
dinov2/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to DINOv2
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Ensure the test suite passes.
12
+ 5. Make sure your code lints.
13
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
14
+
15
+ ## Contributor License Agreement ("CLA")
16
+ In order to accept your pull request, we need you to submit a CLA. You only need
17
+ to do this once to work on any of Meta's open source projects.
18
+
19
+ Complete your CLA here: <https://code.facebook.com/cla>
20
+
21
+ ## Issues
22
+ We use GitHub issues to track public bugs. Please ensure your description is
23
+ clear and has sufficient instructions to be able to reproduce the issue.
24
+
25
+ Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
26
+ disclosure of security bugs. In those cases, please go through the process
27
+ outlined on that page and do not file a public issue.
28
+
29
+ ## License
30
+ By contributing to DINOv2, you agree that your contributions will be licensed
31
+ under the LICENSE file in the root directory of this source tree.
dinov2/LICENSE ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Attribution-NonCommercial 4.0 International
3
+
4
+ =======================================================================
5
+
6
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
7
+ does not provide legal services or legal advice. Distribution of
8
+ Creative Commons public licenses does not create a lawyer-client or
9
+ other relationship. Creative Commons makes its licenses and related
10
+ information available on an "as-is" basis. Creative Commons gives no
11
+ warranties regarding its licenses, any material licensed under their
12
+ terms and conditions, or any related information. Creative Commons
13
+ disclaims all liability for damages resulting from their use to the
14
+ fullest extent possible.
15
+
16
+ Using Creative Commons Public Licenses
17
+
18
+ Creative Commons public licenses provide a standard set of terms and
19
+ conditions that creators and other rights holders may use to share
20
+ original works of authorship and other material subject to copyright
21
+ and certain other rights specified in the public license below. The
22
+ following considerations are for informational purposes only, are not
23
+ exhaustive, and do not form part of our licenses.
24
+
25
+ Considerations for licensors: Our public licenses are
26
+ intended for use by those authorized to give the public
27
+ permission to use material in ways otherwise restricted by
28
+ copyright and certain other rights. Our licenses are
29
+ irrevocable. Licensors should read and understand the terms
30
+ and conditions of the license they choose before applying it.
31
+ Licensors should also secure all rights necessary before
32
+ applying our licenses so that the public can reuse the
33
+ material as expected. Licensors should clearly mark any
34
+ material not subject to the license. This includes other CC-
35
+ licensed material, or material used under an exception or
36
+ limitation to copyright. More considerations for licensors:
37
+ wiki.creativecommons.org/Considerations_for_licensors
38
+
39
+ Considerations for the public: By using one of our public
40
+ licenses, a licensor grants the public permission to use the
41
+ licensed material under specified terms and conditions. If
42
+ the licensor's permission is not necessary for any reason--for
43
+ example, because of any applicable exception or limitation to
44
+ copyright--then that use is not regulated by the license. Our
45
+ licenses grant only permissions under copyright and certain
46
+ other rights that a licensor has authority to grant. Use of
47
+ the licensed material may still be restricted for other
48
+ reasons, including because others have copyright or other
49
+ rights in the material. A licensor may make special requests,
50
+ such as asking that all changes be marked or described.
51
+ Although not required by our licenses, you are encouraged to
52
+ respect those requests where reasonable. More_considerations
53
+ for the public:
54
+ wiki.creativecommons.org/Considerations_for_licensees
55
+
56
+ =======================================================================
57
+
58
+ Creative Commons Attribution-NonCommercial 4.0 International Public
59
+ License
60
+
61
+ By exercising the Licensed Rights (defined below), You accept and agree
62
+ to be bound by the terms and conditions of this Creative Commons
63
+ Attribution-NonCommercial 4.0 International Public License ("Public
64
+ License"). To the extent this Public License may be interpreted as a
65
+ contract, You are granted the Licensed Rights in consideration of Your
66
+ acceptance of these terms and conditions, and the Licensor grants You
67
+ such rights in consideration of benefits the Licensor receives from
68
+ making the Licensed Material available under these terms and
69
+ conditions.
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+ Section 2 -- Scope.
142
+
143
+ a. License grant.
144
+
145
+ 1. Subject to the terms and conditions of this Public License,
146
+ the Licensor hereby grants You a worldwide, royalty-free,
147
+ non-sublicensable, non-exclusive, irrevocable license to
148
+ exercise the Licensed Rights in the Licensed Material to:
149
+
150
+ a. reproduce and Share the Licensed Material, in whole or
151
+ in part, for NonCommercial purposes only; and
152
+
153
+ b. produce, reproduce, and Share Adapted Material for
154
+ NonCommercial purposes only.
155
+
156
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
157
+ Exceptions and Limitations apply to Your use, this Public
158
+ License does not apply, and You do not need to comply with
159
+ its terms and conditions.
160
+
161
+ 3. Term. The term of this Public License is specified in Section
162
+ 6(a).
163
+
164
+ 4. Media and formats; technical modifications allowed. The
165
+ Licensor authorizes You to exercise the Licensed Rights in
166
+ all media and formats whether now known or hereafter created,
167
+ and to make technical modifications necessary to do so. The
168
+ Licensor waives and/or agrees not to assert any right or
169
+ authority to forbid You from making technical modifications
170
+ necessary to exercise the Licensed Rights, including
171
+ technical modifications necessary to circumvent Effective
172
+ Technological Measures. For purposes of this Public License,
173
+ simply making modifications authorized by this Section 2(a)
174
+ (4) never produces Adapted Material.
175
+
176
+ 5. Downstream recipients.
177
+
178
+ a. Offer from the Licensor -- Licensed Material. Every
179
+ recipient of the Licensed Material automatically
180
+ receives an offer from the Licensor to exercise the
181
+ Licensed Rights under the terms and conditions of this
182
+ Public License.
183
+
184
+ b. No downstream restrictions. You may not offer or impose
185
+ any additional or different terms or conditions on, or
186
+ apply any Effective Technological Measures to, the
187
+ Licensed Material if doing so restricts exercise of the
188
+ Licensed Rights by any recipient of the Licensed
189
+ Material.
190
+
191
+ 6. No endorsement. Nothing in this Public License constitutes or
192
+ may be construed as permission to assert or imply that You
193
+ are, or that Your use of the Licensed Material is, connected
194
+ with, or sponsored, endorsed, or granted official status by,
195
+ the Licensor or others designated to receive attribution as
196
+ provided in Section 3(a)(1)(A)(i).
197
+
198
+ b. Other rights.
199
+
200
+ 1. Moral rights, such as the right of integrity, are not
201
+ licensed under this Public License, nor are publicity,
202
+ privacy, and/or other similar personality rights; however, to
203
+ the extent possible, the Licensor waives and/or agrees not to
204
+ assert any such rights held by the Licensor to the limited
205
+ extent necessary to allow You to exercise the Licensed
206
+ Rights, but not otherwise.
207
+
208
+ 2. Patent and trademark rights are not licensed under this
209
+ Public License.
210
+
211
+ 3. To the extent possible, the Licensor waives any right to
212
+ collect royalties from You for the exercise of the Licensed
213
+ Rights, whether directly or through a collecting society
214
+ under any voluntary or waivable statutory or compulsory
215
+ licensing scheme. In all other cases the Licensor expressly
216
+ reserves any right to collect such royalties, including when
217
+ the Licensed Material is used other than for NonCommercial
218
+ purposes.
219
+
220
+ Section 3 -- License Conditions.
221
+
222
+ Your exercise of the Licensed Rights is expressly made subject to the
223
+ following conditions.
224
+
225
+ a. Attribution.
226
+
227
+ 1. If You Share the Licensed Material (including in modified
228
+ form), You must:
229
+
230
+ a. retain the following if it is supplied by the Licensor
231
+ with the Licensed Material:
232
+
233
+ i. identification of the creator(s) of the Licensed
234
+ Material and any others designated to receive
235
+ attribution, in any reasonable manner requested by
236
+ the Licensor (including by pseudonym if
237
+ designated);
238
+
239
+ ii. a copyright notice;
240
+
241
+ iii. a notice that refers to this Public License;
242
+
243
+ iv. a notice that refers to the disclaimer of
244
+ warranties;
245
+
246
+ v. a URI or hyperlink to the Licensed Material to the
247
+ extent reasonably practicable;
248
+
249
+ b. indicate if You modified the Licensed Material and
250
+ retain an indication of any previous modifications; and
251
+
252
+ c. indicate the Licensed Material is licensed under this
253
+ Public License, and include the text of, or the URI or
254
+ hyperlink to, this Public License.
255
+
256
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
257
+ reasonable manner based on the medium, means, and context in
258
+ which You Share the Licensed Material. For example, it may be
259
+ reasonable to satisfy the conditions by providing a URI or
260
+ hyperlink to a resource that includes the required
261
+ information.
262
+
263
+ 3. If requested by the Licensor, You must remove any of the
264
+ information required by Section 3(a)(1)(A) to the extent
265
+ reasonably practicable.
266
+
267
+ 4. If You Share Adapted Material You produce, the Adapter's
268
+ License You apply must not prevent recipients of the Adapted
269
+ Material from complying with this Public License.
270
+
271
+ Section 4 -- Sui Generis Database Rights.
272
+
273
+ Where the Licensed Rights include Sui Generis Database Rights that
274
+ apply to Your use of the Licensed Material:
275
+
276
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
277
+ to extract, reuse, reproduce, and Share all or a substantial
278
+ portion of the contents of the database for NonCommercial purposes
279
+ only;
280
+
281
+ b. if You include all or a substantial portion of the database
282
+ contents in a database in which You have Sui Generis Database
283
+ Rights, then the database in which You have Sui Generis Database
284
+ Rights (but not its individual contents) is Adapted Material; and
285
+
286
+ c. You must comply with the conditions in Section 3(a) if You Share
287
+ all or a substantial portion of the contents of the database.
288
+
289
+ For the avoidance of doubt, this Section 4 supplements and does not
290
+ replace Your obligations under this Public License where the Licensed
291
+ Rights include other Copyright and Similar Rights.
292
+
293
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
294
+
295
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
296
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
297
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
298
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
299
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
300
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
301
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
302
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
303
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
304
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
305
+
306
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
307
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
308
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
309
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
310
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
311
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
312
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
313
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
314
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
315
+
316
+ c. The disclaimer of warranties and limitation of liability provided
317
+ above shall be interpreted in a manner that, to the extent
318
+ possible, most closely approximates an absolute disclaimer and
319
+ waiver of all liability.
320
+
321
+ Section 6 -- Term and Termination.
322
+
323
+ a. This Public License applies for the term of the Copyright and
324
+ Similar Rights licensed here. However, if You fail to comply with
325
+ this Public License, then Your rights under this Public License
326
+ terminate automatically.
327
+
328
+ b. Where Your right to use the Licensed Material has terminated under
329
+ Section 6(a), it reinstates:
330
+
331
+ 1. automatically as of the date the violation is cured, provided
332
+ it is cured within 30 days of Your discovery of the
333
+ violation; or
334
+
335
+ 2. upon express reinstatement by the Licensor.
336
+
337
+ For the avoidance of doubt, this Section 6(b) does not affect any
338
+ right the Licensor may have to seek remedies for Your violations
339
+ of this Public License.
340
+
341
+ c. For the avoidance of doubt, the Licensor may also offer the
342
+ Licensed Material under separate terms or conditions or stop
343
+ distributing the Licensed Material at any time; however, doing so
344
+ will not terminate this Public License.
345
+
346
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
347
+ License.
348
+
349
+ Section 7 -- Other Terms and Conditions.
350
+
351
+ a. The Licensor shall not be bound by any additional or different
352
+ terms or conditions communicated by You unless expressly agreed.
353
+
354
+ b. Any arrangements, understandings, or agreements regarding the
355
+ Licensed Material not stated herein are separate from and
356
+ independent of the terms and conditions of this Public License.
357
+
358
+ Section 8 -- Interpretation.
359
+
360
+ a. For the avoidance of doubt, this Public License does not, and
361
+ shall not be interpreted to, reduce, limit, restrict, or impose
362
+ conditions on any use of the Licensed Material that could lawfully
363
+ be made without permission under this Public License.
364
+
365
+ b. To the extent possible, if any provision of this Public License is
366
+ deemed unenforceable, it shall be automatically reformed to the
367
+ minimum extent necessary to make it enforceable. If the provision
368
+ cannot be reformed, it shall be severed from this Public License
369
+ without affecting the enforceability of the remaining terms and
370
+ conditions.
371
+
372
+ c. No term or condition of this Public License will be waived and no
373
+ failure to comply consented to unless expressly agreed to by the
374
+ Licensor.
375
+
376
+ d. Nothing in this Public License constitutes or may be interpreted
377
+ as a limitation upon, or waiver of, any privileges and immunities
378
+ that apply to the Licensor or You, including from the legal
379
+ processes of any jurisdiction or authority.
380
+
381
+ =======================================================================
382
+
383
+ Creative Commons is not a party to its public
384
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
385
+ its public licenses to material it publishes and in those instances
386
+ will be considered the “Licensor.” The text of the Creative Commons
387
+ public licenses is dedicated to the public domain under the CC0 Public
388
+ Domain Dedication. Except for the limited purpose of indicating that
389
+ material is shared under a Creative Commons public license or as
390
+ otherwise permitted by the Creative Commons policies published at
391
+ creativecommons.org/policies, Creative Commons does not authorize the
392
+ use of the trademark "Creative Commons" or any other trademark or logo
393
+ of Creative Commons without its prior written consent including,
394
+ without limitation, in connection with any unauthorized modifications
395
+ to any of its public licenses or any other arrangements,
396
+ understandings, or agreements concerning use of licensed material. For
397
+ the avoidance of doubt, this paragraph does not form part of the
398
+ public licenses.
399
+
400
+ Creative Commons may be contacted at creativecommons.org.
dinov2/MODEL_CARD.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Card for DINOv2-S/B/L/g
2
+
3
+ These are Vision Transformer models trained following the method described in the paper:
4
+ "DINOv2: Learning Robust Visual Features without Supervision"
5
+
6
+ We provide 4 models: 1 ViT-g trained from scratch, and 3 ViT-S/B/L models distilled from the ViT-g.
7
+
8
+ ## Model Details
9
+ The model takes an image as input and returns a class token and patch tokens.
10
+
11
+ The embedding dimension is:
12
+ - 384 for ViT-S.
13
+ - 768 for ViT-B.
14
+ - 1024 for ViT-L.
15
+ - 1536 for ViT-g.
16
+
17
+ The models follow a Transformer architecture, with a patch size of 14.
18
+
19
+ For a 224x224 image, this results in 1 class token + 256 patch tokens.
20
+
21
+ The models can accept larger images provided the image shapes are multiples of the patch size (14).
22
+ If this condition is not verified, the model will crop to the closest smaller multiple of the patch size.
23
+
24
+ ### Model Description
25
+
26
+ - **Developed by:** Meta AI
27
+ - **Model type:** Vision Transformer
28
+ - **License:** CC-BY-NC
29
+
30
+ - **Repository:** https://github.com/facebookresearch/dinov2
31
+ - **Paper:** https://arxiv.org/abs/2304.07193
32
+ - **Demo:** https://dinov2.metademolab.com/
33
+
34
+ ## Uses
35
+
36
+ The models are vision backbones providing multi-purpose features for downstream tasks.
37
+
38
+ ### Direct Use
39
+
40
+ The models can be used without fine-tuning, with downstream classifiers as simple as linear layers, to obtain competitive results:
41
+ - on depth estimation, semantic segmentation, using linear layers.
42
+ - on image classification, using k-NN classifiers on the class token.
43
+ - on image classification, with logistic regression classifiers applied on the class token.
44
+ - on image classification, with a linear layer applied on the class token and the average of the patch tokens.
45
+ - on image retrieval using nearest neighbors.
46
+
47
+ ### Downstream Use
48
+
49
+ It is technically possible to perform fine-tuning on the models, for small gains (we measured +2% on ImageNet-1k classification).
50
+ We recommend keeping this as a very last step and only when necessary, as the features already provide good performance out-of-the-box.
51
+
52
+ ## Bias, Risks, and Limitations
53
+
54
+ Despite improvements thanks to the training method not using annotations, we still observe significant biases in our models toward rich households from Western countries.
55
+
56
+ ### Recommendations
57
+
58
+ We expect fine-tuning will increase the biases in the features produced by the model as they will be tuned to the fine-tuning labels.
59
+
60
+ ## How to Get Started with the Model
61
+
62
+ Use the code below to get started with the model.
63
+
64
+ ```python
65
+ import torch
66
+ dinov2_vits14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')
67
+ dinov2_vitb14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')
68
+ dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')
69
+ dinov2_vitg14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitg14')
70
+ ```
71
+
72
+ ## Training Details
73
+
74
+ ### Training Data
75
+
76
+ - **Training data:** LVD-142M (see paper)
77
+ - **Training regime:** fp16 using PyTorch-FSDP mixed-precision.
78
+
79
+ ### Training Procedure
80
+
81
+ - **Training objective:**
82
+ - DINO self-distillation loss with multi-crop
83
+ - iBOT masked-image modeling loss
84
+ - KoLeo regularization on [CLS] tokens
85
+ - **Architectures:**
86
+ - ViT-S (21M params): Patch size 14, embedding dimension 384, 6 heads, MLP FFN
87
+ - ViT-B (86M params): Patch size 14, embedding dimension 768, 12 heads, MLP FFN
88
+ - ViT-L (0.3B params): Patch size 14, embedding dimension 1024, 16 heads, MLP FFN
89
+ - ViT-g (1.1B params): Patch size 14, embedding dimension 1536, 24 heads, SwiGLU FFN
90
+ - **Distillation:**
91
+ - Distillation follows the standard DINOv2 pretraining procedure, except the teacher is a pretrained ViT-g, frozen.
92
+
93
+ ## Evaluation
94
+
95
+ We refer users to the associated paper for the evaluation protocols.
96
+
97
+ <table>
98
+ <tr>
99
+ <th>model</th>
100
+ <th colspan="3">ImageNet-1k</th>
101
+ <th>NYU-Depth v2</th>
102
+ <th>SUN-RGBD</th>
103
+ <th>ADE20k</th>
104
+ <th>iNaturalist 2018</th>
105
+ <th>Oxford-H</th>
106
+ </tr>
107
+ <tr>
108
+ <th rowspan="2">task</th>
109
+ <th>classif. (acc)</th>
110
+ <th>classif. (acc)</th>
111
+ <th>classif. V2 (acc)</th>
112
+ <th>depth (RMSE)</th>
113
+ <th>depth (RMSE)</th>
114
+ <th>segm. (mAP)</th>
115
+ <th>classif. (acc)</th>
116
+ <th>retrieval (mAP)</th>
117
+ </tr>
118
+ <tr>
119
+ <!-- <th>^</th> -->
120
+ <th>k-NN</th>
121
+ <th>linear</th>
122
+ <th>linear</th>
123
+ <th>linear<br />4 layers</th>
124
+ <th>NYU-D transfer</th>
125
+ <th>multiscale</th>
126
+ <th>linear</th>
127
+ <th>nearest neighbor</th>
128
+ </tr>
129
+ <tr>
130
+ <td>ViT-S/14</td>
131
+ <td align="right">79.0%</td>
132
+ <td align="right">81.1%</td>
133
+ <td align="right">70.8%</td>
134
+ <td align="right">0.417</td>
135
+ <td align="right">0.431</td>
136
+ <td align="right">47.2</td>
137
+ <td align="right">69.5%</td>
138
+ <td align="right">43.2</td>
139
+ </tr>
140
+ <tr>
141
+ <td>ViT-B/14</td>
142
+ <td align="right">82.1%</td>
143
+ <td align="right">84.5%</td>
144
+ <td align="right">74.9%</td>
145
+ <td align="right">0.362</td>
146
+ <td align="right">0.400</td>
147
+ <td align="right">51.3</td>
148
+ <td align="right">76.3%</td>
149
+ <td align="right">49.5</td>
150
+ </tr>
151
+ <tr>
152
+ <td>ViT-L/14</td>
153
+ <td align="right">83.5%</td>
154
+ <td align="right">86.3%</td>
155
+ <td align="right">77.6%</td>
156
+ <td align="right">0.333</td>
157
+ <td align="right">0.396</td>
158
+ <td align="right">53.1</td>
159
+ <td align="right">79.8%</td>
160
+ <td align="right">54.0</td>
161
+ </tr>
162
+ <tr>
163
+ <td>ViT-g/14</td>
164
+ <td align="right">83.5%</td>
165
+ <td align="right">86.5%</td>
166
+ <td align="right">78.4%</td>
167
+ <td align="right">0.298</td>
168
+ <td align="right">0.362</td>
169
+ <td align="right">53.0</td>
170
+ <td align="right">81.6%</td>
171
+ <td align="right">52.3</td>
172
+ </tr>
173
+ </table>
174
+
175
+ ## Environmental Impact
176
+
177
+ - **Hardware Type:** Nvidia A100
178
+ - **Hours used:** 22,000 for ViT-g, 4,500 for ViT-S distillation, 5,300 for ViT-B distillation, 8,000 for ViT-L distillation
179
+ - **Cloud Provider:** Private infra
180
+ - **Compute Region:** USA
181
+ - **Carbon Emitted:** 7t CO2eq
182
+
183
+ #### Hardware
184
+
185
+ Nvidia A100 GPUs
186
+
187
+ #### Software
188
+
189
+ PyTorch 2.0,
190
+ xFormers 0.0.18
191
+
192
+ **BibTeX**
193
+
194
+ ```
195
+ @misc{oquab2023dinov2,
196
+ title={DINOv2: Learning Robust Visual Features without Supervision},
197
+ author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy and Szafraniec, Marc and Khalidov, Vasil and Fernandez, Pierre and Haziza, Daniel and Massa, Francisco and El-Nouby, Alaaeldin and Howes, Russell and Huang, Po-Yao and Xu, Hu and Sharma, Vasu and Li, Shang-Wen and Galuba, Wojciech and Rabbat, Mike and Assran, Mido and Ballas, Nicolas and Synnaeve, Gabriel and Misra, Ishan and Jegou, Herve and Mairal, Julien and Labatut, Patrick and Joulin, Armand and Bojanowski, Piotr},
198
+ journal={arXiv:2304.07193},
199
+ year={2023}
200
+ }
201
+ ```
dinov2/README.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DINOv2: Learning Robust Visual Features without Supervision
2
+
3
+ **[Meta AI Research, FAIR](https://ai.facebook.com/research/)**
4
+
5
+ Maxime Oquab,
6
+ Timothée Darcet,
7
+ Théo Moutakanni,
8
+ Huy Vo,
9
+ Marc Szafraniec,
10
+ Vasil Khalidov,
11
+ Patrick Labatut,
12
+ Armand Joulin,
13
+ Piotr Bojanowski
14
+
15
+ [[`Paper`](https://arxiv.org/abs/2304.07193)] [[`Blog`](https://ai.facebook.com/blog/dino-v2-computer-vision-self-supervised-learning/)] [[`Demo`](https://dinov2.metademolab.com)] [[`BibTeX`](#citing-dinov2)]
16
+
17
+ PyTorch implementation and pretrained models for DINOv2. For details, see the paper: **DINOv2: Learning Robust Visual Features without Supervision**.
18
+
19
+ DINOv2 models produce high-performance visual features that can be directly employed with classifiers as simple as linear layers on a variety of computer vision tasks; these visual features are robust and perform well across domains without any requirement for fine-tuning. The models were pretrained on a dataset of 142 M images without using any labels or annotations.
20
+
21
+
22
+ https://user-images.githubusercontent.com/60359573/230078733-5faffa19-e6ce-4c55-9200-62dd76f8236a.mp4
23
+
24
+ <div align="center">
25
+ Visualization of the three first principal components of the patch features of all frames, mapped to RGB values.
26
+ </div>
27
+
28
+ ## Pretrained models
29
+
30
+ <table>
31
+ <tr>
32
+ <th>model</th>
33
+ <th># of<br />params</th>
34
+ <th>ImageNet<br />k-NN</th>
35
+ <th>ImageNet<br />linear</th>
36
+ <th>download</th>
37
+ </tr>
38
+ <tr>
39
+ <td>ViT-S/14 distilled</td>
40
+ <td align="right">21 M</td>
41
+ <td align="right">79.0%</td>
42
+ <td align="right">81.1%</td>
43
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_pretrain.pth">backbone only</a></td>
44
+ </tr>
45
+ <tr>
46
+ <td>ViT-B/14 distilled</td>
47
+ <td align="right">86 M</td>
48
+ <td align="right">82.1%</td>
49
+ <td align="right">84.5%</td>
50
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_pretrain.pth">backbone only</a></td>
51
+ </tr>
52
+ <tr>
53
+ <td>ViT-L/14 distilled</td>
54
+ <td align="right">300 M</td>
55
+ <td align="right">83.5%</td>
56
+ <td align="right">86.3%</td>
57
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth">backbone only</a></td>
58
+ </tr>
59
+ <tr>
60
+ <td>ViT-g/14</td>
61
+ <td align="right">1,100 M</td>
62
+ <td align="right">83.5%</td>
63
+ <td align="right">86.5%</td>
64
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth">backbone only</a></td>
65
+ </tr>
66
+ </table>
67
+
68
+
69
+ ### Pretrained models via PyTorch Hub
70
+
71
+ Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install the PyTorch and torchvision dependencies (these are the only required dependencies). Installing both PyTorch and torchvision with CUDA support is strongly recommended.
72
+
73
+ The corresponding model card can be found in the [[`MODEL_CARD.md`](MODEL_CARD.md)] file.
74
+
75
+ ```python
76
+ import torch
77
+
78
+ dinov2_vits14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')
79
+ dinov2_vitb14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')
80
+ dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')
81
+ dinov2_vitg14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitg14')
82
+ ```
83
+
84
+ ## Installation
85
+
86
+ The training and evaluation code requires PyTorch 2.0 and xFormers 0.0.18 as well as a number of other 3rd party packages. To setup all the required dependencies for training and evaluation, please follow the instructions below:
87
+
88
+ *conda* **(Recommended)** - Create and activate a `dinov2` conda environment using the provided environment definition:
89
+
90
+ ```shell
91
+ conda env create -f conda.yaml
92
+ conda activate dinov2
93
+ ```
94
+
95
+ *pip* - Use the provided `requirements.txt` to install the dependencies:
96
+
97
+ ```shell
98
+ pip install -r requirements.txt
99
+ ```
100
+
101
+ ## Data preparation
102
+
103
+ Expected contents for the ImageNet-1k data folder:
104
+ - `<root>/test/ILSVRC2012_test_00000001.JPEG`
105
+ - `<root>/test/[..]`
106
+ - `<root>/test/ILSVRC2012_test_00100000.JPEG`
107
+ - `<root>/train/n01440764/n01440764_10026.JPEG`
108
+ - `<root>/train/[...]`
109
+ - `<root>/train/n15075141/n15075141_9993.JPEG`
110
+ - `<root>/val/n01440764/ILSVRC2012_val_00000293.JPEG`
111
+ - `<root>/val/[...]`
112
+ - `<root>/val/n15075141/ILSVRC2012_val_00049174.JPEG`
113
+ - `<root>/labels.txt`
114
+
115
+ For ImageNet-22k, please adapt the Dataset object accordingly.
116
+
117
+ ## Training
118
+
119
+ ### Fast setup: training DINOv2 ViT-L/16 on ImageNet-1k
120
+
121
+ Run DINOv2 on 4 A100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit.
122
+
123
+ ```shell
124
+ python dinov2/run/train/train.py \
125
+ --nodes 4 \
126
+ --config-file dinov2/configs/train/vitl16_short.yaml \
127
+ --output-dir <PATH/TO/OUTPUT/DIR> \
128
+ train.dataset_path=ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
129
+ ```
130
+
131
+ Training time is approximately 1 day and the resulting checkpoint should reach 81.6% on k-NN eval and 82.9% on linear eval.
132
+
133
+ The training code saves the weights of the teacher in the `eval` folder every 12500 iterations for evaluation.
134
+
135
+ ### Long setup: training DINOv2 ViT-L/14 on ImageNet-22k
136
+
137
+ Run on 12 A100-80GB nodes (96 GPUs) in a SLURM cluster environment with submitit.
138
+
139
+ ```
140
+ python dinov2/run/train/train.py \
141
+ --nodes 12 \
142
+ --config-file dinov2/configs/train/vitl14.yaml \
143
+ --output-dir <PATH/TO/OUTPUT/DIR> \
144
+ train.dataset_path=ImageNet22k:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
145
+ ```
146
+
147
+ Training time is approximately 3.3 days and the resulting checkpoint should reach 82.0% on k-NN eval and 84.5% on linear eval.
148
+
149
+ The training code saves the weights of the teacher in the `eval` folder every 12500 iterations for evaluation.
150
+
151
+
152
+ ## Evaluation
153
+
154
+ The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node:
155
+
156
+ ### k-NN classification on ImageNet-1k
157
+
158
+ ```
159
+ python dinov2/run/eval/knn.py \
160
+ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \
161
+ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \
162
+ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/knn \
163
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
164
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
165
+ ```
166
+
167
+ ### Logistic regression classification on ImageNet-1k
168
+
169
+ ```
170
+ python dinov2/run/eval/log_regression.py \
171
+ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \
172
+ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \
173
+ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/logreg \
174
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
175
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
176
+ ```
177
+
178
+ ### Linear classification with data augmentation on ImageNet-1k
179
+
180
+ ```
181
+ python dinov2/run/eval/linear.py \
182
+ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \
183
+ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \
184
+ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/linear \
185
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
186
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
187
+ ```
188
+
189
+ We release the weights from evaluating the different models:
190
+
191
+ <table>
192
+ <tr>
193
+ <th>model</th>
194
+ <th>ImageNet<br />top-1</th>
195
+ <th>linear evaluation</th>
196
+ </tr>
197
+ <tr>
198
+ <td>ViT-S/14 distilled</td>
199
+ <td align="right">81.1%</td>
200
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_linear_head.pth">linear head weights</a></td>
201
+ </tr>
202
+ <tr>
203
+ <td>ViT-B/14 distilled</td>
204
+ <td align="right">84.5%</td>
205
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_linear_head.pth">linear head weights</a></td>
206
+ </tr>
207
+ <tr>
208
+ <td>ViT-L/14 distilled</td>
209
+ <td align="right">86.3%</td>
210
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_linear_head.pth">linear head weights</a></td>
211
+ </tr>
212
+ <tr>
213
+ <td>ViT-g/14</td>
214
+ <td align="right">86.5%</td>
215
+ <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_linear_head.pth">linear head weights</a></td>
216
+ </tr>
217
+ </table>
218
+
219
+ The performance of the provided pretrained model weights can be evaluated as follows on ImageNet-1k:
220
+
221
+ ```
222
+ python dinov2/run/eval/linear.py \
223
+ --config-file dinov2/configs/eval/vitg14_pretrain.yaml \
224
+ --pretrained-weights https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth \
225
+ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
226
+ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
227
+ ```
228
+
229
+ ## License
230
+
231
+ This repository and the models are released under the CC-BY-NC as found in the [LICENSE](LICENSE) file.
232
+
233
+ ## Contributing
234
+
235
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
236
+
237
+ ## Citing DINOv2
238
+
239
+ If you find this repository useful, please consider giving a star :star: and citation :t-rex::
240
+
241
+ ```
242
+ @misc{oquab2023dinov2,
243
+ title={DINOv2: Learning Robust Visual Features without Supervision},
244
+ author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy and Szafraniec, Marc and Khalidov, Vasil and Fernandez, Pierre and Haziza, Daniel and Massa, Francisco and El-Nouby, Alaaeldin and Howes, Russell and Huang, Po-Yao and Xu, Hu and Sharma, Vasu and Li, Shang-Wen and Galuba, Wojciech and Rabbat, Mike and Assran, Mido and Ballas, Nicolas and Synnaeve, Gabriel and Misra, Ishan and Jegou, Herve and Mairal, Julien and Labatut, Patrick and Joulin, Armand and Bojanowski, Piotr},
245
+ journal={arXiv:2304.07193},
246
+ year={2023}
247
+ }
248
+ ```
dinov2/conda.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: dinov2
2
+ channels:
3
+ - defaults
4
+ - pytorch
5
+ - nvidia
6
+ - xformers
7
+ - conda-forge
8
+ dependencies:
9
+ - python=3.9
10
+ - pytorch::pytorch=2.0.0
11
+ - pytorch::pytorch-cuda=11.7.0
12
+ - pytorch::torchvision=0.15.0
13
+ - omegaconf
14
+ - torchmetrics=0.10.3
15
+ - fvcore
16
+ - iopath
17
+ - xformers::xformers=0.0.18
18
+ - pip
19
+ - pip:
20
+ - git+https://github.com/facebookincubator/submitit
21
+ - --extra-index-url https://pypi.nvidia.com
22
+ - cuml-cu11
dinov2/dinov2/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ __version__ = "0.0.1"
dinov2/dinov2/configs/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import pathlib
8
+
9
+ from omegaconf import OmegaConf
10
+
11
+
12
+ def load_config(config_name: str):
13
+ config_filename = config_name + ".yaml"
14
+ return OmegaConf.load(pathlib.Path(__file__).parent.resolve() / config_filename)
15
+
16
+
17
+ dinov2_default_config = load_config("ssl_default_config")
18
+
19
+
20
+ def load_and_merge_config(config_name: str):
21
+ default_config = OmegaConf.create(dinov2_default_config)
22
+ loaded_config = load_config(config_name)
23
+ return OmegaConf.merge(default_config, loaded_config)
dinov2/dinov2/configs/eval/vitb14_pretrain.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_base
3
+ patch_size: 14
4
+ crops:
5
+ global_crops_size: 518 # this is to set up the position embeddings properly
6
+ local_crops_size: 98
dinov2/dinov2/configs/eval/vitg14_pretrain.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_giant2
3
+ patch_size: 14
4
+ ffn_layer: swiglufused
5
+ crops:
6
+ global_crops_size: 518 # this is to set up the position embeddings properly
7
+ local_crops_size: 98
dinov2/dinov2/configs/eval/vitl14_pretrain.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_large
3
+ patch_size: 14
4
+ crops:
5
+ global_crops_size: 518 # this is to set up the position embeddings properly
6
+ local_crops_size: 98
dinov2/dinov2/configs/eval/vits14_pretrain.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ student:
2
+ arch: vit_small
3
+ patch_size: 14
4
+ crops:
5
+ global_crops_size: 518 # this is to set up the position embeddings properly
6
+ local_crops_size: 98
dinov2/dinov2/configs/ssl_default_config.yaml ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL:
2
+ WEIGHTS: ''
3
+ compute_precision:
4
+ grad_scaler: true
5
+ teacher:
6
+ backbone:
7
+ sharding_strategy: SHARD_GRAD_OP
8
+ mixed_precision:
9
+ param_dtype: fp16
10
+ reduce_dtype: fp16
11
+ buffer_dtype: fp32
12
+ dino_head:
13
+ sharding_strategy: SHARD_GRAD_OP
14
+ mixed_precision:
15
+ param_dtype: fp16
16
+ reduce_dtype: fp16
17
+ buffer_dtype: fp32
18
+ ibot_head:
19
+ sharding_strategy: SHARD_GRAD_OP
20
+ mixed_precision:
21
+ param_dtype: fp16
22
+ reduce_dtype: fp16
23
+ buffer_dtype: fp32
24
+ student:
25
+ backbone:
26
+ sharding_strategy: SHARD_GRAD_OP
27
+ mixed_precision:
28
+ param_dtype: fp16
29
+ reduce_dtype: fp16
30
+ buffer_dtype: fp32
31
+ dino_head:
32
+ sharding_strategy: SHARD_GRAD_OP
33
+ mixed_precision:
34
+ param_dtype: fp16
35
+ reduce_dtype: fp32
36
+ buffer_dtype: fp32
37
+ ibot_head:
38
+ sharding_strategy: SHARD_GRAD_OP
39
+ mixed_precision:
40
+ param_dtype: fp16
41
+ reduce_dtype: fp32
42
+ buffer_dtype: fp32
43
+ dino:
44
+ loss_weight: 1.0
45
+ head_n_prototypes: 65536
46
+ head_bottleneck_dim: 256
47
+ head_nlayers: 3
48
+ head_hidden_dim: 2048
49
+ koleo_loss_weight: 0.1
50
+ ibot:
51
+ loss_weight: 1.0
52
+ mask_sample_probability: 0.5
53
+ mask_ratio_min_max:
54
+ - 0.1
55
+ - 0.5
56
+ separate_head: false
57
+ head_n_prototypes: 65536
58
+ head_bottleneck_dim: 256
59
+ head_nlayers: 3
60
+ head_hidden_dim: 2048
61
+ train:
62
+ batch_size_per_gpu: 64
63
+ dataset_path: ImageNet:split=TRAIN
64
+ output_dir: .
65
+ saveckp_freq: 20
66
+ seed: 0
67
+ num_workers: 10
68
+ OFFICIAL_EPOCH_LENGTH: 1250
69
+ cache_dataset: true
70
+ centering: "centering" # or "sinkhorn_knopp"
71
+ student:
72
+ arch: vit_large
73
+ patch_size: 16
74
+ drop_path_rate: 0.3
75
+ layerscale: 1.0e-05
76
+ drop_path_uniform: true
77
+ pretrained_weights: ''
78
+ ffn_layer: "mlp"
79
+ block_chunks: 0
80
+ qkv_bias: true
81
+ proj_bias: true
82
+ ffn_bias: true
83
+ teacher:
84
+ momentum_teacher: 0.992
85
+ final_momentum_teacher: 1
86
+ warmup_teacher_temp: 0.04
87
+ teacher_temp: 0.07
88
+ warmup_teacher_temp_epochs: 30
89
+ optim:
90
+ epochs: 100
91
+ weight_decay: 0.04
92
+ weight_decay_end: 0.4
93
+ base_lr: 0.004 # learning rate for a batch size of 1024
94
+ lr: 0. # will be set after applying scaling rule
95
+ warmup_epochs: 10
96
+ min_lr: 1.0e-06
97
+ clip_grad: 3.0
98
+ freeze_last_layer_epochs: 1
99
+ scaling_rule: sqrt_wrt_1024
100
+ patch_embed_lr_mult: 0.2
101
+ layerwise_decay: 0.9
102
+ adamw_beta1: 0.9
103
+ adamw_beta2: 0.999
104
+ crops:
105
+ global_crops_scale:
106
+ - 0.32
107
+ - 1.0
108
+ local_crops_number: 8
109
+ local_crops_scale:
110
+ - 0.05
111
+ - 0.32
112
+ global_crops_size: 224
113
+ local_crops_size: 96
114
+ evaluation:
115
+ eval_period_iterations: 12500
dinov2/dinov2/configs/train/vitg14.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dino:
2
+ head_n_prototypes: 131072
3
+ head_bottleneck_dim: 384
4
+ ibot:
5
+ separate_head: true
6
+ head_n_prototypes: 131072
7
+ train:
8
+ batch_size_per_gpu: 12
9
+ dataset_path: ImageNet22k
10
+ centering: sinkhorn_knopp
11
+ student:
12
+ arch: vit_giant2
13
+ patch_size: 14
14
+ drop_path_rate: 0.4
15
+ ffn_layer: swiglufused
16
+ block_chunks: 4
17
+ teacher:
18
+ momentum_teacher: 0.994
19
+ optim:
20
+ epochs: 500
21
+ weight_decay_end: 0.2
22
+ base_lr: 2.0e-04 # learning rate for a batch size of 1024
23
+ warmup_epochs: 80
24
+ layerwise_decay: 1.0
25
+ crops:
26
+ local_crops_size: 98
dinov2/dinov2/configs/train/vitl14.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dino:
2
+ head_n_prototypes: 131072
3
+ head_bottleneck_dim: 384
4
+ ibot:
5
+ separate_head: true
6
+ head_n_prototypes: 131072
7
+ train:
8
+ batch_size_per_gpu: 32
9
+ dataset_path: ImageNet22k
10
+ centering: sinkhorn_knopp
11
+ student:
12
+ arch: vit_large
13
+ patch_size: 14
14
+ drop_path_rate: 0.4
15
+ ffn_layer: swiglufused
16
+ block_chunks: 4
17
+ teacher:
18
+ momentum_teacher: 0.994
19
+ optim:
20
+ epochs: 500
21
+ weight_decay_end: 0.2
22
+ base_lr: 2.0e-04 # learning rate for a batch size of 1024
23
+ warmup_epochs: 80
24
+ layerwise_decay: 1.0
25
+ crops:
26
+ local_crops_size: 98
dinov2/dinov2/configs/train/vitl16_short.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # this corresponds to the default config
2
+ train:
3
+ dataset_path: ImageNet:split=TRAIN
4
+ batch_size_per_gpu: 64
5
+ student:
6
+ block_chunks: 4
dinov2/dinov2/data/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .adapters import DatasetWithEnumeratedTargets
8
+ from .loaders import make_data_loader, make_dataset, SamplerType
9
+ from .collate import collate_data_and_cast
10
+ from .masking import MaskingGenerator
11
+ from .augmentations import DataAugmentationDINO