olfp commited on
Commit
054c447
1 Parent(s): 7d8e86d

Upload 162 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +15 -35
  2. .gitignore +143 -0
  3. LICENSE.txt +21 -0
  4. README.md +6 -5
  5. app.py +307 -0
  6. cldm/cldm.py +442 -0
  7. cldm/ddim_hacked.py +318 -0
  8. cldm/hack.py +111 -0
  9. cldm/logger.py +76 -0
  10. cldm/model.py +28 -0
  11. configs/anydoor.yaml +85 -0
  12. configs/datasets.yaml +68 -0
  13. configs/demo.yaml +4 -0
  14. configs/inference.yaml +3 -0
  15. css/style.css +39 -0
  16. dinov2/.github/workflows/lint.yaml +39 -0
  17. dinov2/.gitignore +13 -0
  18. dinov2/CODE_OF_CONDUCT.md +80 -0
  19. dinov2/CONTRIBUTING.md +31 -0
  20. dinov2/LICENSE +400 -0
  21. dinov2/MODEL_CARD.md +201 -0
  22. dinov2/README.md +248 -0
  23. dinov2/conda.yaml +22 -0
  24. dinov2/dinov2/__init__.py +7 -0
  25. dinov2/dinov2/configs/__init__.py +23 -0
  26. dinov2/dinov2/configs/eval/vitb14_pretrain.yaml +6 -0
  27. dinov2/dinov2/configs/eval/vitg14_pretrain.yaml +7 -0
  28. dinov2/dinov2/configs/eval/vitl14_pretrain.yaml +6 -0
  29. dinov2/dinov2/configs/eval/vits14_pretrain.yaml +6 -0
  30. dinov2/dinov2/configs/ssl_default_config.yaml +115 -0
  31. dinov2/dinov2/configs/train/vitg14.yaml +26 -0
  32. dinov2/dinov2/configs/train/vitl14.yaml +26 -0
  33. dinov2/dinov2/configs/train/vitl16_short.yaml +6 -0
  34. dinov2/dinov2/data/__init__.py +11 -0
  35. dinov2/dinov2/data/adapters.py +32 -0
  36. dinov2/dinov2/data/augmentations.py +119 -0
  37. dinov2/dinov2/data/collate.py +50 -0
  38. dinov2/dinov2/data/datasets/__init__.py +8 -0
  39. dinov2/dinov2/data/datasets/decoders.py +40 -0
  40. dinov2/dinov2/data/datasets/extended.py +47 -0
  41. dinov2/dinov2/data/datasets/image_net.py +251 -0
  42. dinov2/dinov2/data/datasets/image_net_22k.py +304 -0
  43. dinov2/dinov2/data/loaders.py +223 -0
  44. dinov2/dinov2/data/masking.py +87 -0
  45. dinov2/dinov2/data/samplers.py +230 -0
  46. dinov2/dinov2/data/transforms.py +92 -0
  47. dinov2/dinov2/distributed/__init__.py +271 -0
  48. dinov2/dinov2/eval/__init__.py +5 -0
  49. dinov2/dinov2/eval/knn.py +404 -0
  50. dinov2/dinov2/eval/linear.py +625 -0
.gitattributes CHANGED
@@ -1,35 +1,15 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ examples/Gradio/FG/012.jpg filter=lfs diff=lfs merge=lfs -text
2
+ examples/Gradio/FG/03.jpg filter=lfs diff=lfs merge=lfs -text
3
+ examples/Gradio/FG/04[[:space:]]3.jpg filter=lfs diff=lfs merge=lfs -text
4
+ examples/Gradio/FG/04[[:space:]]4.jpg filter=lfs diff=lfs merge=lfs -text
5
+ examples/Gradio/FG/04.jpg filter=lfs diff=lfs merge=lfs -text
6
+ examples/Gradio/BG/00.png filter=lfs diff=lfs merge=lfs -text
7
+ examples/Gradio/BG/08.jpg filter=lfs diff=lfs merge=lfs -text
8
+ examples/Gradio/FG/01.jpg filter=lfs diff=lfs merge=lfs -text
9
+ examples/Gradio/FG/06.jpg filter=lfs diff=lfs merge=lfs -text
10
+ examples/Gradio/FG/09.jpg filter=lfs diff=lfs merge=lfs -text
11
+ examples/Gradio/FG/6.jpg filter=lfs diff=lfs merge=lfs -text
12
+ examples/Gradio/FG/7.jpg filter=lfs diff=lfs merge=lfs -text
13
+ examples/Gradio/FG/8.jpg filter=lfs diff=lfs merge=lfs -text
14
+ examples/Gradio/BG/5.jpg filter=lfs diff=lfs merge=lfs -text
15
+ examples/Gradio/BG/6.jpg filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.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 CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Anydoor
3
- emoji: 🌖
4
- colorFrom: blue
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.14.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: AnyDoor Online
3
+ emoji: 👁
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 3.50.2
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,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ #sys.path.append('.')
4
+ import cv2
5
+ import einops
6
+ import numpy as np
7
+ import torch
8
+ import random
9
+ import gradio as gr
10
+ import albumentations as A
11
+ from PIL import Image
12
+ import torchvision.transforms as T
13
+ from mydatasets.data_utils import *
14
+ from cldm.model import create_model, load_state_dict
15
+ from cldm.ddim_hacked import DDIMSampler
16
+ from omegaconf import OmegaConf
17
+ from cldm.hack import disable_verbosity, enable_sliced_attention
18
+ from huggingface_hub import snapshot_download
19
+
20
+
21
+ snapshot_download(repo_id="xichenhku/AnyDoor_models", local_dir="./AnyDoor_models")
22
+ snapshot_download(repo_id="xichenhku/mask_refine", local_dir="./mask_refine")
23
+
24
+ cv2.setNumThreads(0)
25
+ cv2.ocl.setUseOpenCL(False)
26
+
27
+ save_memory = False
28
+ disable_verbosity()
29
+ if save_memory:
30
+ enable_sliced_attention()
31
+
32
+
33
+ config = OmegaConf.load('./configs/demo.yaml')
34
+ model_ckpt = config.pretrained_model
35
+ model_config = config.config_file
36
+ use_interactive_seg = config.config_file
37
+
38
+
39
+ model = create_model(model_config ).cpu()
40
+ model.load_state_dict(load_state_dict(model_ckpt, location='cuda'))
41
+ model = model.cuda()
42
+ ddim_sampler = DDIMSampler(model)
43
+
44
+ if use_interactive_seg:
45
+ from iseg.coarse_mask_refine_util import BaselineModel
46
+ model_path = './mask_refine/coarse_mask_refine.pth'
47
+ iseg_model = BaselineModel().eval()
48
+ weights = torch.load(model_path , map_location='cpu')['state_dict']
49
+ iseg_model.load_state_dict(weights, strict= True)
50
+
51
+
52
+ def crop_back( pred, tar_image, extra_sizes, tar_box_yyxx_crop):
53
+ H1, W1, H2, W2 = extra_sizes
54
+ y1,y2,x1,x2 = tar_box_yyxx_crop
55
+ pred = cv2.resize(pred, (W2, H2))
56
+ m = 3 # maigin_pixel
57
+
58
+ if W1 == H1:
59
+ tar_image[y1+m :y2-m, x1+m:x2-m, :] = pred[m:-m, m:-m]
60
+ return tar_image
61
+
62
+ if W1 < W2:
63
+ pad1 = int((W2 - W1) / 2)
64
+ pad2 = W2 - W1 - pad1
65
+ pred = pred[:,pad1: -pad2, :]
66
+ else:
67
+ pad1 = int((H2 - H1) / 2)
68
+ pad2 = H2 - H1 - pad1
69
+ pred = pred[pad1: -pad2, :, :]
70
+ tar_image[y1+m :y2-m, x1+m:x2-m, :] = pred[m:-m, m:-m]
71
+ return tar_image
72
+
73
+
74
+ def inference_single_image(ref_image,
75
+ ref_mask,
76
+ tar_image,
77
+ tar_mask,
78
+ strength,
79
+ ddim_steps,
80
+ scale,
81
+ seed,
82
+ enable_shape_control
83
+ ):
84
+ raw_background = tar_image.copy()
85
+ item = process_pairs(ref_image, ref_mask, tar_image, tar_mask, enable_shape_control = enable_shape_control)
86
+
87
+ ref = item['ref']
88
+ hint = item['hint']
89
+ num_samples = 1
90
+
91
+ control = torch.from_numpy(hint.copy()).float().cuda()
92
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
93
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
94
+
95
+
96
+ clip_input = torch.from_numpy(ref.copy()).float().cuda()
97
+ clip_input = torch.stack([clip_input for _ in range(num_samples)], dim=0)
98
+ clip_input = einops.rearrange(clip_input, 'b h w c -> b c h w').clone()
99
+
100
+ H,W = 512,512
101
+
102
+ cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning( clip_input )]}
103
+ un_cond = {"c_concat": [control],
104
+ "c_crossattn": [model.get_learned_conditioning([torch.zeros((1,3,224,224))] * num_samples)]}
105
+ shape = (4, H // 8, W // 8)
106
+
107
+ if save_memory:
108
+ model.low_vram_shift(is_diffusing=True)
109
+
110
+ model.control_scales = ([strength] * 13)
111
+ samples, _ = ddim_sampler.sample(ddim_steps, num_samples,
112
+ shape, cond, verbose=False, eta=0,
113
+ unconditional_guidance_scale=scale,
114
+ unconditional_conditioning=un_cond)
115
+
116
+ if save_memory:
117
+ model.low_vram_shift(is_diffusing=False)
118
+
119
+ x_samples = model.decode_first_stage(samples)
120
+ x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy()
121
+
122
+ result = x_samples[0][:,:,::-1]
123
+ result = np.clip(result,0,255)
124
+
125
+ pred = x_samples[0]
126
+ pred = np.clip(pred,0,255)[1:,:,:]
127
+ sizes = item['extra_sizes']
128
+ tar_box_yyxx_crop = item['tar_box_yyxx_crop']
129
+ tar_image = crop_back(pred, tar_image, sizes, tar_box_yyxx_crop)
130
+
131
+ # keep background unchanged
132
+ y1,y2,x1,x2 = item['tar_box_yyxx']
133
+ raw_background[y1:y2, x1:x2, :] = tar_image[y1:y2, x1:x2, :]
134
+ return raw_background
135
+
136
+
137
+ def process_pairs(ref_image, ref_mask, tar_image, tar_mask, max_ratio = 0.8, enable_shape_control = False):
138
+ # ========= Reference ===========
139
+ # ref expand
140
+ ref_box_yyxx = get_bbox_from_mask(ref_mask)
141
+
142
+ # ref filter mask
143
+ ref_mask_3 = np.stack([ref_mask,ref_mask,ref_mask],-1)
144
+ masked_ref_image = ref_image * ref_mask_3 + np.ones_like(ref_image) * 255 * (1-ref_mask_3)
145
+
146
+ y1,y2,x1,x2 = ref_box_yyxx
147
+ masked_ref_image = masked_ref_image[y1:y2,x1:x2,:]
148
+ ref_mask = ref_mask[y1:y2,x1:x2]
149
+
150
+ ratio = np.random.randint(11, 15) / 10 #11,13
151
+ masked_ref_image, ref_mask = expand_image_mask(masked_ref_image, ref_mask, ratio=ratio)
152
+ ref_mask_3 = np.stack([ref_mask,ref_mask,ref_mask],-1)
153
+
154
+ # to square and resize
155
+ masked_ref_image = pad_to_square(masked_ref_image, pad_value = 255, random = False)
156
+ masked_ref_image = cv2.resize(masked_ref_image.astype(np.uint8), (224,224) ).astype(np.uint8)
157
+
158
+ ref_mask_3 = pad_to_square(ref_mask_3 * 255, pad_value = 0, random = False)
159
+ ref_mask_3 = cv2.resize(ref_mask_3.astype(np.uint8), (224,224) ).astype(np.uint8)
160
+ ref_mask = ref_mask_3[:,:,0]
161
+
162
+ # collage aug
163
+ masked_ref_image_compose, ref_mask_compose = masked_ref_image, ref_mask
164
+ ref_mask_3 = np.stack([ref_mask_compose,ref_mask_compose,ref_mask_compose],-1)
165
+ ref_image_collage = sobel(masked_ref_image_compose, ref_mask_compose/255)
166
+
167
+ # ========= Target ===========
168
+ tar_box_yyxx = get_bbox_from_mask(tar_mask)
169
+ tar_box_yyxx = expand_bbox(tar_mask, tar_box_yyxx, ratio=[1.1,1.2]) #1.1 1.3
170
+ tar_box_yyxx_full = tar_box_yyxx
171
+
172
+ # crop
173
+ tar_box_yyxx_crop = expand_bbox(tar_image, tar_box_yyxx, ratio=[1.3, 3.0])
174
+ tar_box_yyxx_crop = box2squre(tar_image, tar_box_yyxx_crop) # crop box
175
+ y1,y2,x1,x2 = tar_box_yyxx_crop
176
+
177
+ cropped_target_image = tar_image[y1:y2,x1:x2,:]
178
+ cropped_tar_mask = tar_mask[y1:y2,x1:x2]
179
+
180
+ tar_box_yyxx = box_in_box(tar_box_yyxx, tar_box_yyxx_crop)
181
+ y1,y2,x1,x2 = tar_box_yyxx
182
+
183
+ # collage
184
+ ref_image_collage = cv2.resize(ref_image_collage.astype(np.uint8), (x2-x1, y2-y1))
185
+ ref_mask_compose = cv2.resize(ref_mask_compose.astype(np.uint8), (x2-x1, y2-y1))
186
+ ref_mask_compose = (ref_mask_compose > 128).astype(np.uint8)
187
+
188
+ collage = cropped_target_image.copy()
189
+ collage[y1:y2,x1:x2,:] = ref_image_collage
190
+
191
+ collage_mask = cropped_target_image.copy() * 0.0
192
+ collage_mask[y1:y2,x1:x2,:] = 1.0
193
+ if enable_shape_control:
194
+ collage_mask = np.stack([cropped_tar_mask,cropped_tar_mask,cropped_tar_mask],-1)
195
+
196
+ # the size before pad
197
+ H1, W1 = collage.shape[0], collage.shape[1]
198
+
199
+ cropped_target_image = pad_to_square(cropped_target_image, pad_value = 0, random = False).astype(np.uint8)
200
+ collage = pad_to_square(collage, pad_value = 0, random = False).astype(np.uint8)
201
+ collage_mask = pad_to_square(collage_mask, pad_value = 2, random = False).astype(np.uint8)
202
+
203
+ # the size after pad
204
+ H2, W2 = collage.shape[0], collage.shape[1]
205
+
206
+ cropped_target_image = cv2.resize(cropped_target_image.astype(np.uint8), (512,512)).astype(np.float32)
207
+ collage = cv2.resize(collage.astype(np.uint8), (512,512)).astype(np.float32)
208
+ collage_mask = cv2.resize(collage_mask.astype(np.uint8), (512,512), interpolation = cv2.INTER_NEAREST).astype(np.float32)
209
+ collage_mask[collage_mask == 2] = -1
210
+
211
+ masked_ref_image = masked_ref_image / 255
212
+ cropped_target_image = cropped_target_image / 127.5 - 1.0
213
+ collage = collage / 127.5 - 1.0
214
+ collage = np.concatenate([collage, collage_mask[:,:,:1] ] , -1)
215
+
216
+ item = dict(ref=masked_ref_image.copy(), jpg=cropped_target_image.copy(), hint=collage.copy(),
217
+ extra_sizes=np.array([H1, W1, H2, W2]),
218
+ tar_box_yyxx_crop=np.array( tar_box_yyxx_crop ),
219
+ tar_box_yyxx=np.array(tar_box_yyxx_full),
220
+ )
221
+ return item
222
+
223
+
224
+ ref_dir='./examples/Gradio/FG'
225
+ image_dir='./examples/Gradio/BG'
226
+ 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 ]
227
+ ref_list.sort()
228
+ 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]
229
+ image_list.sort()
230
+
231
+ def mask_image(image, mask):
232
+ blanc = np.ones_like(image) * 255
233
+ mask = np.stack([mask,mask,mask],-1) / 255
234
+ masked_image = mask * ( 0.5 * blanc + 0.5 * image) + (1-mask) * image
235
+ return masked_image.astype(np.uint8)
236
+
237
+ def run_local(base,
238
+ ref,
239
+ *args):
240
+ image = base["image"].convert("RGB")
241
+ mask = base["mask"].convert("L")
242
+ ref_image = ref["image"].convert("RGB")
243
+ ref_mask = ref["mask"].convert("L")
244
+ image = np.asarray(image)
245
+ mask = np.asarray(mask)
246
+ mask = np.where(mask > 128, 1, 0).astype(np.uint8)
247
+ ref_image = np.asarray(ref_image)
248
+ ref_mask = np.asarray(ref_mask)
249
+ ref_mask = np.where(ref_mask > 128, 1, 0).astype(np.uint8)
250
+
251
+ synthesis = inference_single_image(ref_image.copy(), ref_mask.copy(), image.copy(), mask.copy(), *args)
252
+ synthesis = torch.from_numpy(synthesis).permute(2, 0, 1)
253
+ synthesis = synthesis.permute(1, 2, 0).numpy()
254
+ return [synthesis]
255
+
256
+
257
+ demo = gr.Blocks(
258
+ css="css/style.css"
259
+ )
260
+
261
+ with demo:
262
+ with gr.Column():
263
+ # gr.Markdown("# Play with AnyDoor to Teleport your Target Objects! ")
264
+
265
+ gr.Markdown("# Télécharger / sélectionner des images pour l'arrière-plan (à gauche) et l'objet de référence (à droite)")
266
+ # gr.Markdown("### You could draw coarse masks on the background to indicate the desired location and shape.")
267
+ # gr.Markdown("### <u>Do not forget</u> to annotate the target object on the reference image.")
268
+ with gr.Row():
269
+ base = gr.Image(label="Arrière-plan", source="upload", tool="sketch", type="pil", height=512, brush_color='#FFFFFF', mask_opacity=0.5)
270
+ ref = gr.Image(label="Référence", source="upload", tool="sketch", type="pil", height=512, brush_color='#FFFFFF', mask_opacity=0.5)
271
+ with gr.Row():
272
+ with gr.Column():
273
+ gr.Examples(image_list, inputs=[base],label="Exemples - Image d'arrière-plan",examples_per_page=16)
274
+ with gr.Column():
275
+ gr.Examples(ref_list, inputs=[ref],label="Exemples - Objet de référence",examples_per_page=16)
276
+ run_local_button = gr.Button(label="Generate", value="Exécuter")
277
+
278
+ with gr.Row():
279
+ baseline_gallery = gr.Gallery(label='Sortie', show_label=True, elem_id="gallery", columns=1, height=768)
280
+ with gr.Accordion("Advanced Option", open=False):
281
+ num_samples = 1
282
+ strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
283
+ ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=30, step=1)
284
+ scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=4.5, step=0.1)
285
+ seed = gr.Slider(label="Seed", minimum=-1, maximum=999999999, step=1, value=-1)
286
+ reference_mask_refine = gr.Checkbox(label='Reference Mask Refine', value=True, interactive = True)
287
+ enable_shape_control = gr.Checkbox(label='Enable Shape Control', value=False, interactive = True)
288
+
289
+ gr.Markdown("### Guidelines")
290
+ gr.Markdown(" Higher guidance-scale makes higher fidelity, while lower one makes more harmonized blending.")
291
+ gr.Markdown(" Users should annotate the mask of the target object, too coarse mask would lead to bad generation.\
292
+ Reference Mask Refine provides a segmentation model to refine the coarse mask. ")
293
+ gr.Markdown(" Enable shape control means the generation results would consider user-drawn masks to control the shape & pose; otherwise it \
294
+ considers the location and size to adjust automatically.")
295
+
296
+ run_local_button.click(fn=run_local,
297
+ inputs=[base,
298
+ ref,
299
+ strength,
300
+ ddim_steps,
301
+ scale,
302
+ seed,
303
+ enable_shape_control,
304
+ ],
305
+ outputs=[baseline_gallery]
306
+ )
307
+ demo.launch()
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,4 @@
 
 
 
 
 
1
+ pretrained_model: ./AnyDoor_models/general_v0.1/general_v0.1.ckpt
2
+ config_file: configs/anydoor.yaml
3
+ save_memory: False
4
+ use_interactive_seg: True
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
css/style.css ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ div.svelte-s6ybro {
2
+ display: flex;
3
+ flex-direction: column;
4
+ position: absolute;
5
+ top: 8px;
6
+ right: 8px;
7
+ justify-content: flex-end;
8
+ gap: 4px;
9
+ z-index: 50;
10
+ }
11
+
12
+ .wrap.svelte-p4aq0j.svelte-p4aq0j {
13
+ display: flex;
14
+ flex-direction: column;
15
+ position: absolute;
16
+ top: 113px;
17
+ right: 8px;
18
+ justify-content: flex-end;
19
+ z-index: 50;
20
+ }
21
+
22
+ div.svelte-1030q2h {
23
+ width: 25px;
24
+ height: 25px;
25
+ padding: 2px;
26
+ }
27
+
28
+ .start-prompt.svelte-yigbas {
29
+ font-size: 0;
30
+ }
31
+
32
+ .start-prompt.svelte-yigbas::after {
33
+ content: "Commencer a dessiner";
34
+ font-size: 20px;
35
+ }
36
+
37
+ footer.svelte-1ax1toq.svelte-1ax1toq.svelte-1ax1toq {
38
+ display: none;
39
+ }
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
dinov2/dinov2/data/adapters.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Tuple
8
+
9
+ from torch.utils.data import Dataset
10
+
11
+
12
+ class DatasetWithEnumeratedTargets(Dataset):
13
+ def __init__(self, dataset):
14
+ self._dataset = dataset
15
+
16
+ def get_image_data(self, index: int) -> bytes:
17
+ return self._dataset.get_image_data(index)
18
+
19
+ def get_target(self, index: int) -> Tuple[Any, int]:
20
+ target = self._dataset.get_target(index)
21
+ return (index, target)
22
+
23
+ def get_sample_decoder(self, index: int) -> Any:
24
+ return self._dataset.get_sample_decoder(index)
25
+
26
+ def __getitem__(self, index: int) -> Tuple[Any, Tuple[Any, int]]:
27
+ image, target = self._dataset[index]
28
+ target = index if target is None else target
29
+ return image, (index, target)
30
+
31
+ def __len__(self) -> int:
32
+ return len(self._dataset)
dinov2/dinov2/data/augmentations.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
8
+
9
+ from torchvision import transforms
10
+
11
+ from .transforms import (
12
+ GaussianBlur,
13
+ make_normalize_transform,
14
+ )
15
+
16
+
17
+ logger = logging.getLogger("dinov2")
18
+
19
+
20
+ class DataAugmentationDINO(object):
21
+ def __init__(
22
+ self,
23
+ global_crops_scale,
24
+ local_crops_scale,
25
+ local_crops_number,
26
+ global_crops_size=224,
27
+ local_crops_size=96,
28
+ ):
29
+ self.global_crops_scale = global_crops_scale
30
+ self.local_crops_scale = local_crops_scale
31
+ self.local_crops_number = local_crops_number
32
+ self.global_crops_size = global_crops_size
33
+ self.local_crops_size = local_crops_size
34
+
35
+ logger.info("###################################")
36
+ logger.info("Using data augmentation parameters:")
37
+ logger.info(f"global_crops_scale: {global_crops_scale}")
38
+ logger.info(f"local_crops_scale: {local_crops_scale}")
39
+ logger.info(f"local_crops_number: {local_crops_number}")
40
+ logger.info(f"global_crops_size: {global_crops_size}")
41
+ logger.info(f"local_crops_size: {local_crops_size}")
42
+ logger.info("###################################")
43
+
44
+ # random resized crop and flip
45
+ self.geometric_augmentation_global = transforms.Compose(
46
+ [
47
+ transforms.RandomResizedCrop(
48
+ global_crops_size, scale=global_crops_scale, interpolation=transforms.InterpolationMode.BICUBIC
49
+ ),
50
+ transforms.RandomHorizontalFlip(p=0.5),
51
+ ]
52
+ )
53
+
54
+ self.geometric_augmentation_local = transforms.Compose(
55
+ [
56
+ transforms.RandomResizedCrop(
57
+ local_crops_size, scale=local_crops_scale, interpolation=transforms.InterpolationMode.BICUBIC
58
+ ),
59
+ transforms.RandomHorizontalFlip(p=0.5),
60
+ ]
61
+ )
62
+
63
+ # color distorsions / blurring
64
+ color_jittering = transforms.Compose(
65
+ [
66
+ transforms.RandomApply(
67
+ [transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)],
68
+ p=0.8,
69
+ ),
70
+ transforms.RandomGrayscale(p=0.2),
71
+ ]
72
+ )
73
+
74
+ global_transfo1_extra = GaussianBlur(p=1.0)
75
+
76
+ global_transfo2_extra = transforms.Compose(
77
+ [
78
+ GaussianBlur(p=0.1),
79
+ transforms.RandomSolarize(threshold=128, p=0.2),
80
+ ]
81
+ )
82
+
83
+ local_transfo_extra = GaussianBlur(p=0.5)
84
+
85
+ # normalization
86
+ self.normalize = transforms.Compose(
87
+ [
88
+ transforms.ToTensor(),
89
+ make_normalize_transform(),
90
+ ]
91
+ )
92
+
93
+ self.global_transfo1 = transforms.Compose([color_jittering, global_transfo1_extra, self.normalize])
94
+ self.global_transfo2 = transforms.Compose([color_jittering, global_transfo2_extra, self.normalize])
95
+ self.local_transfo = transforms.Compose([color_jittering, local_transfo_extra, self.normalize])
96
+
97
+ def __call__(self, image):
98
+ output = {}
99
+
100
+ # global crops:
101
+ im1_base = self.geometric_augmentation_global(image)
102
+ global_crop_1 = self.global_transfo1(im1_base)
103
+
104
+ im2_base = self.geometric_augmentation_global(image)
105
+ global_crop_2 = self.global_transfo2(im2_base)
106
+
107
+ output["global_crops"] = [global_crop_1, global_crop_2]
108
+
109
+ # global crops for teacher:
110
+ output["global_crops_teacher"] = [global_crop_1, global_crop_2]
111
+
112
+ # local crops:
113
+ local_crops = [
114
+ self.local_transfo(self.geometric_augmentation_local(image)) for _ in range(self.local_crops_number)
115
+ ]
116
+ output["local_crops"] = local_crops
117
+ output["offsets"] = ()
118
+
119
+ return output
dinov2/dinov2/data/collate.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch
8
+ import random
9
+
10
+
11
+ def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=None, mask_generator=None):
12
+ # dtype = torch.half # TODO: Remove
13
+
14
+ n_global_crops = len(samples_list[0][0]["global_crops"])
15
+ n_local_crops = len(samples_list[0][0]["local_crops"])
16
+
17
+ collated_global_crops = torch.stack([s[0]["global_crops"][i] for i in range(n_global_crops) for s in samples_list])
18
+
19
+ collated_local_crops = torch.stack([s[0]["local_crops"][i] for i in range(n_local_crops) for s in samples_list])
20
+
21
+ B = len(collated_global_crops)
22
+ N = n_tokens
23
+ n_samples_masked = int(B * mask_probability)
24
+ probs = torch.linspace(*mask_ratio_tuple, n_samples_masked + 1)
25
+ upperbound = 0
26
+ masks_list = []
27
+ for i in range(0, n_samples_masked):
28
+ prob_min = probs[i]
29
+ prob_max = probs[i + 1]
30
+ masks_list.append(torch.BoolTensor(mask_generator(int(N * random.uniform(prob_min, prob_max)))))
31
+ upperbound += int(N * prob_max)
32
+ for i in range(n_samples_masked, B):
33
+ masks_list.append(torch.BoolTensor(mask_generator(0)))
34
+
35
+ random.shuffle(masks_list)
36
+
37
+ collated_masks = torch.stack(masks_list).flatten(1)
38
+ mask_indices_list = collated_masks.flatten().nonzero().flatten()
39
+
40
+ masks_weight = (1 / collated_masks.sum(-1).clamp(min=1.0)).unsqueeze(-1).expand_as(collated_masks)[collated_masks]
41
+
42
+ return {
43
+ "collated_global_crops": collated_global_crops.to(dtype),
44
+ "collated_local_crops": collated_local_crops.to(dtype),
45
+ "collated_masks": collated_masks,
46
+ "mask_indices_list": mask_indices_list,
47
+ "masks_weight": masks_weight,
48
+ "upperbound": upperbound,
49
+ "n_masked_patches": torch.full((1,), fill_value=mask_indices_list.shape[0], dtype=torch.long),
50
+ }
dinov2/dinov2/data/datasets/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
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 .image_net import ImageNet
8
+ from .image_net_22k import ImageNet22k
dinov2/dinov2/data/datasets/decoders.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 io import BytesIO
8
+ from typing import Any, Tuple
9
+
10
+ from PIL import Image
11
+
12
+
13
+ class Decoder:
14
+ def decode(self) -> Any:
15
+ raise NotImplementedError
16
+
17
+
18
+ class ImageDataDecoder(Decoder):
19
+ def __init__(self, image_data: bytes) -> None:
20
+ self._image_data = image_data
21
+
22
+ def decode(self) -> Image:
23
+ f = BytesIO(self._image_data)
24
+ return Image.open(f).convert(mode="RGB")
25
+
26
+
27
+ class TargetDecoder(Decoder):
28
+ def __init__(self, target: Any):
29
+ self._target = target
30
+
31
+ def decode(self) -> Any:
32
+ return self._target
33
+
34
+
35
+ class TupleDecoder(Decoder):
36
+ def __init__(self, *decoders: Decoder):
37
+ self._decoders: Tuple[Decoder, ...] = decoders
38
+
39
+ def decode(self) -> Any:
40
+ return (decoder.decode() for decoder in self._decoders)
dinov2/dinov2/data/datasets/extended.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Tuple
8
+
9
+ from torchvision.datasets import VisionDataset
10
+
11
+ from .decoders import Decoder, TargetDecoder, ImageDataDecoder, TupleDecoder
12
+
13
+
14
+ class ExtendedVisionDataset(VisionDataset):
15
+ def __init__(self, *args, **kwargs) -> None:
16
+ super().__init__(*args, **kwargs) # type: ignore
17
+
18
+ def get_image_data(self, index: int) -> bytes:
19
+ raise NotImplementedError
20
+
21
+ def get_target(self, index: int) -> Any:
22
+ raise NotImplementedError
23
+
24
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
25
+ try:
26
+ image_data = self.get_image_data(index)
27
+ image = ImageDataDecoder(image_data).decode()
28
+ except Exception as e:
29
+ raise RuntimeError(f"can not read image for sample {index}") from e
30
+ target = self.get_target(index)
31
+ target = TargetDecoder(target).decode()
32
+
33
+ if self.transforms is not None:
34
+ image, target = self.transforms(image, target)
35
+
36
+ return image, target
37
+
38
+ def get_sample_decoder(self, index: int) -> Decoder:
39
+ image_data = self.get_image_data(index)
40
+ target = self.get_target(index)
41
+ return TupleDecoder(
42
+ ImageDataDecoder(image_data),
43
+ TargetDecoder(target),
44
+ )
45
+
46
+ def __len__(self) -> int:
47
+ raise NotImplementedError
dinov2/dinov2/data/datasets/image_net.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 csv
8
+ from enum import Enum
9
+ import os
10
+ from typing import Callable, List, Optional, Tuple, Union
11
+
12
+ import numpy as np
13
+
14
+ from .extended import ExtendedVisionDataset
15
+
16
+
17
+ _Labels = int
18
+
19
+
20
+ class _Split(Enum):
21
+ TRAIN = "train"
22
+ VAL = "val"
23
+ TEST = "test" # NOTE: torchvision does not support the test split
24
+
25
+ @property
26
+ def length(self) -> int:
27
+ split_lengths = {
28
+ _Split.TRAIN: 1_281_167,
29
+ _Split.VAL: 50_000,
30
+ _Split.TEST: 100_000,
31
+ }
32
+ return split_lengths[self]
33
+
34
+ def get_dirname(self, class_id: Optional[str] = None) -> str:
35
+ return self.value if class_id is None else os.path.join(self.value, class_id)
36
+
37
+ def get_image_relpath(self, actual_index: int, class_id: Optional[str] = None) -> str:
38
+ dirname = self.get_dirname(class_id)
39
+ if self == _Split.TRAIN:
40
+ basename = f"{class_id}_{actual_index}"
41
+ else: # self in (_Split.VAL, _Split.TEST):
42
+ basename = f"ILSVRC2012_{self.value}_{actual_index:08d}"
43
+ return os.path.join(dirname, basename + ".JPEG")
44
+
45
+ def parse_image_relpath(self, image_relpath: str) -> Tuple[str, int]:
46
+ assert self != _Split.TEST
47
+ dirname, filename = os.path.split(image_relpath)
48
+ class_id = os.path.split(dirname)[-1]
49
+ basename, _ = os.path.splitext(filename)
50
+ actual_index = int(basename.split("_")[-1])
51
+ return class_id, actual_index
52
+
53
+
54
+ class ImageNet(ExtendedVisionDataset):
55
+ Labels = Union[_Labels]
56
+ Split = Union[_Split]
57
+
58
+ def __init__(
59
+ self,
60
+ *,
61
+ split: "ImageNet.Split",
62
+ root: str,
63
+ extra: str,
64
+ transforms: Optional[Callable] = None,
65
+ transform: Optional[Callable] = None,
66
+ target_transform: Optional[Callable] = None,
67
+ ) -> None:
68
+ super().__init__(root, transforms, transform, target_transform)
69
+ self._extra_root = extra
70
+
71
+ self._split = split
72
+
73
+ entries_path = self._get_entries_path(split, root)
74
+ self._entries = self._load_extra(entries_path)
75
+
76
+ self._class_ids = None
77
+ self._class_names = None
78
+
79
+ if split == _Split.TEST:
80
+ return
81
+
82
+ class_ids_path = self._get_class_ids_path(split, root)
83
+ self._class_ids = self._load_extra(class_ids_path)
84
+
85
+ class_names_path = self._get_class_names_path(split, root)
86
+ self._class_names = self._load_extra(class_names_path)
87
+
88
+ @property
89
+ def split(self) -> "ImageNet.Split":
90
+ return self._split
91
+
92
+ def _load_extra(self, extra_path: str) -> np.ndarray:
93
+ extra_root = self._extra_root
94
+ extra_full_path = os.path.join(extra_root, extra_path)
95
+ return np.load(extra_full_path, mmap_mode="r")
96
+
97
+ def _save_extra(self, extra_array: np.ndarray, extra_path: str) -> None:
98
+ extra_root = self._extra_root
99
+ extra_full_path = os.path.join(extra_root, extra_path)
100
+ os.makedirs(extra_root, exist_ok=True)
101
+ np.save(extra_full_path, extra_array)
102
+
103
+ def _get_entries_path(self, split: "ImageNet.Split", root: Optional[str] = None) -> str:
104
+ return f"entries-{split.value.upper()}.npy"
105
+
106
+ def _get_class_ids_path(self, split: "ImageNet.Split", root: Optional[str] = None) -> str:
107
+ return f"class-ids-{split.value.upper()}.npy"
108
+
109
+ def _get_class_names_path(self, split: "ImageNet.Split", root: Optional[str] = None) -> str:
110
+ return f"class-names-{split.value.upper()}.npy"
111
+
112
+ def find_class_id(self, class_index: int) -> str:
113
+ assert self._class_ids is not None
114
+ return str(self._class_ids[class_index])
115
+
116
+ def find_class_name(self, class_index: int) -> str:
117
+ assert self._class_names is not None
118
+ return str(self._class_names[class_index])
119
+
120
+ def get_image_data(self, index: int) -> bytes:
121
+ actual_index = self._entries[index]["actual_index"]
122
+ class_id = self.get_class_id(index)
123
+ image_relpath = self.split.get_image_relpath(actual_index, class_id)
124
+ image_full_path = os.path.join(self.root, image_relpath)
125
+ with open(image_full_path, mode="rb") as f:
126
+ image_data = f.read()
127
+ return image_data
128
+
129
+ def get_target(self, index: int) -> Optional[_Labels]:
130
+ class_index = self._entries[index]["class_index"]
131
+ return None if self.split == _Split.TEST else int(class_index)
132
+
133
+ def get_targets(self) -> Optional[np.ndarray]:
134
+ return None if self.split == _Split.TEST else self._entries["class_index"]
135
+
136
+ def get_class_id(self, index: int) -> Optional[str]:
137
+ class_id = self._entries[index]["class_id"]
138
+ return None if self.split == _Split.TEST else str(class_id)
139
+
140
+ def get_class_name(self, index: int) -> Optional[str]:
141
+ class_name = self._entries[index]["class_name"]
142
+ return None if self.split == _Split.TEST else str(class_name)
143
+
144
+ def __len__(self) -> int:
145
+ assert len(self._entries) == self.split.length
146
+ return len(self._entries)
147
+
148
+ def _load_labels(self, root: str) -> List[Tuple[str, str]]:
149
+ path = os.path.join(root, "labels.txt")
150
+ labels = []
151
+
152
+ try:
153
+ with open(path, "r") as f:
154
+ reader = csv.reader(f)
155
+ for row in reader:
156
+ class_id, class_name = row
157
+ labels.append((class_id, class_name))
158
+ except OSError as e:
159
+ raise RuntimeError(f'can not read labels file "{path}"') from e
160
+
161
+ return labels
162
+
163
+ def _dump_entries(self, split: "ImageNet.Split", root: Optional[str] = None) -> None:
164
+ # NOTE: Using torchvision ImageFolder for consistency
165
+ from torchvision.datasets import ImageFolder
166
+
167
+ root = self.root
168
+ labels = self._load_labels(root)
169
+
170
+ if split == ImageNet.Split.TEST:
171
+ dataset = None
172
+ sample_count = split.length
173
+ max_class_id_length, max_class_name_length = 0, 0
174
+ else:
175
+ dataset_root = os.path.join(root, split.get_dirname())
176
+ dataset = ImageFolder(dataset_root)
177
+ sample_count = len(dataset)
178
+ max_class_id_length, max_class_name_length = -1, -1
179
+ for sample in dataset.samples:
180
+ _, class_index = sample
181
+ class_id, class_name = labels[class_index]
182
+ max_class_id_length = max(len(class_id), max_class_id_length)
183
+ max_class_name_length = max(len(class_name), max_class_name_length)
184
+
185
+ dtype = np.dtype(
186
+ [
187
+ ("actual_index", "<u4"),
188
+ ("class_index", "<u4"),
189
+ ("class_id", f"U{max_class_id_length}"),
190
+ ("class_name", f"U{max_class_name_length}"),
191
+ ]
192
+ )
193
+ entries_array = np.empty(sample_count, dtype=dtype)
194
+
195
+ if split == ImageNet.Split.TEST:
196
+ for index in range(sample_count):
197
+ entries_array[index] = (index + 1, np.uint32(-1), "", "")
198
+ else:
199
+ class_names = {class_id: class_name for class_id, class_name in labels}
200
+
201
+ assert dataset
202
+ for index, _ in enumerate(dataset):
203
+ image_full_path, class_index = dataset.samples[index]
204
+ image_relpath = os.path.relpath(image_full_path, root)
205
+ class_id, actual_index = split.parse_image_relpath(image_relpath)
206
+ class_name = class_names[class_id]
207
+ entries_array[index] = (actual_index, class_index, class_id, class_name)
208
+
209
+ entries_path = self._get_entries_path(split, root)
210
+ self._save_extra(entries_array, entries_path)
211
+
212
+ def _dump_class_ids_and_names(self, split: "ImageNet.Split", root: Optional[str] = None) -> None:
213
+ if split == ImageNet.Split.TEST:
214
+ return
215
+
216
+ root = self.get_root(root)
217
+ entries_path = self._get_entries_path(split, root)
218
+ entries_array = self._load_extra(entries_path)
219
+
220
+ max_class_id_length, max_class_name_length, max_class_index = -1, -1, -1
221
+ for entry in entries_array:
222
+ class_index, class_id, class_name = (
223
+ entry["class_index"],
224
+ entry["class_id"],
225
+ entry["class_name"],
226
+ )
227
+ max_class_index = max(int(class_index), max_class_index)
228
+ max_class_id_length = max(len(str(class_id)), max_class_id_length)
229
+ max_class_name_length = max(len(str(class_name)), max_class_name_length)
230
+
231
+ class_count = max_class_index + 1
232
+ class_ids_array = np.empty(class_count, dtype=f"U{max_class_id_length}")
233
+ class_names_array = np.empty(class_count, dtype=f"U{max_class_name_length}")
234
+ for entry in entries_array:
235
+ class_index, class_id, class_name = (
236
+ entry["class_index"],
237
+ entry["class_id"],
238
+ entry["class_name"],
239
+ )
240
+ class_ids_array[class_index] = class_id
241
+ class_names_array[class_index] = class_name
242
+
243
+ class_ids_path = self._get_class_ids_path(split, root)
244
+ self._save_extra(class_ids_array, class_ids_path)
245
+
246
+ class_names_path = self._get_class_names_path(split, root)
247
+ self._save_extra(class_names_array, class_names_path)
248
+
249
+ def dump_extra(self, split: "ImageNet.Split", root: Optional[str] = None) -> None:
250
+ self._dump_entries(split, root)
251
+ self._dump_class_ids_and_names(split, root)
dinov2/dinov2/data/datasets/image_net_22k.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclasses import dataclass
8
+ from enum import Enum
9
+ from functools import lru_cache
10
+ from gzip import GzipFile
11
+ from io import BytesIO
12
+ from mmap import ACCESS_READ, mmap
13
+ import os
14
+ from typing import Any, Callable, List, Optional, Set, Tuple
15
+ import warnings
16
+
17
+ import numpy as np
18
+
19
+ from .extended import ExtendedVisionDataset
20
+
21
+
22
+ _Labels = int
23
+
24
+ _DEFAULT_MMAP_CACHE_SIZE = 16 # Warning: This can exhaust file descriptors
25
+ _IMAGES_SUBDIR_IMAGENET_21KP = "062717"
26
+
27
+
28
+ @dataclass
29
+ class _ClassEntry:
30
+ block_offset: int
31
+ maybe_filename: Optional[str] = None
32
+
33
+
34
+ @dataclass
35
+ class _Entry:
36
+ class_index: int # noqa: E701
37
+ start_offset: int
38
+ end_offset: int
39
+ filename: str
40
+
41
+
42
+ class _Split(Enum):
43
+ TRAIN = "train"
44
+ VAL = "val"
45
+
46
+ @property
47
+ def length(self) -> int:
48
+ return {
49
+ _Split.TRAIN: 11_797_647,
50
+ _Split.VAL: 561_050,
51
+ }[self]
52
+
53
+ def entries_path(self):
54
+ return f"imagenet21kp_{self.value}.txt"
55
+
56
+
57
+ def _get_tarball_path(class_id: str) -> str:
58
+ return f"{class_id}.tar"
59
+
60
+
61
+ def _make_mmap_tarball(tarballs_root: str, mmap_cache_size: int):
62
+ @lru_cache(maxsize=mmap_cache_size)
63
+ def _mmap_tarball(class_id: str) -> mmap:
64
+ tarball_path = _get_tarball_path(class_id)
65
+ tarball_full_path = os.path.join(tarballs_root, tarball_path)
66
+ with open(tarball_full_path) as f:
67
+ return mmap(fileno=f.fileno(), length=0, access=ACCESS_READ)
68
+
69
+ return _mmap_tarball
70
+
71
+
72
+ class ImageNet22k(ExtendedVisionDataset):
73
+ _GZIPPED_INDICES: Set[int] = {
74
+ 841_545,
75
+ 1_304_131,
76
+ 2_437_921,
77
+ 2_672_079,
78
+ 2_795_676,
79
+ 2_969_786,
80
+ 6_902_965,
81
+ 6_903_550,
82
+ 6_903_628,
83
+ 7_432_557,
84
+ 7_432_589,
85
+ 7_813_809,
86
+ 8_329_633,
87
+ 10_296_990,
88
+ 10_417_652,
89
+ 10_492_265,
90
+ 10_598_078,
91
+ 10_782_398,
92
+ 10_902_612,
93
+ 11_203_736,
94
+ 11_342_890,
95
+ 11_397_596,
96
+ 11_589_762,
97
+ 11_705_103,
98
+ 12_936_875,
99
+ 13_289_782,
100
+ }
101
+ Labels = _Labels
102
+
103
+ def __init__(
104
+ self,
105
+ *,
106
+ root: str,
107
+ extra: str,
108
+ transforms: Optional[Callable] = None,
109
+ transform: Optional[Callable] = None,
110
+ target_transform: Optional[Callable] = None,
111
+ mmap_cache_size: int = _DEFAULT_MMAP_CACHE_SIZE,
112
+ ) -> None:
113
+ super().__init__(root, transforms, transform, target_transform)
114
+ self._extra_root = extra
115
+
116
+ entries_path = self._get_entries_path(root)
117
+ self._entries = self._load_extra(entries_path)
118
+
119
+ class_ids_path = self._get_class_ids_path(root)
120
+ self._class_ids = self._load_extra(class_ids_path)
121
+
122
+ self._gzipped_indices = ImageNet22k._GZIPPED_INDICES
123
+ self._mmap_tarball = _make_mmap_tarball(self._tarballs_root, mmap_cache_size)
124
+
125
+ def _get_entries_path(self, root: Optional[str] = None) -> str:
126
+ return "entries.npy"
127
+
128
+ def _get_class_ids_path(self, root: Optional[str] = None) -> str:
129
+ return "class-ids.npy"
130
+
131
+ def _find_class_ids(self, path: str) -> List[str]:
132
+ class_ids = []
133
+
134
+ with os.scandir(path) as entries:
135
+ for entry in entries:
136
+ root, ext = os.path.splitext(entry.name)
137
+ if ext != ".tar":
138
+ continue
139
+ class_ids.append(root)
140
+
141
+ return sorted(class_ids)
142
+
143
+ def _load_entries_class_ids(self, root: Optional[str] = None) -> Tuple[List[_Entry], List[str]]:
144
+ root = self.get_root(root)
145
+ entries: List[_Entry] = []
146
+ class_ids = self._find_class_ids(root)
147
+
148
+ for class_index, class_id in enumerate(class_ids):
149
+ path = os.path.join(root, "blocks", f"{class_id}.log")
150
+ class_entries = []
151
+
152
+ try:
153
+ with open(path) as f:
154
+ for line in f:
155
+ line = line.rstrip()
156
+ block, filename = line.split(":")
157
+ block_offset = int(block[6:])
158
+ filename = filename[1:]
159
+
160
+ maybe_filename = None
161
+ if filename != "** Block of NULs **":
162
+ maybe_filename = filename
163
+ _, ext = os.path.splitext(filename)
164
+ # assert ext == ".JPEG"
165
+
166
+ class_entry = _ClassEntry(block_offset, maybe_filename)
167
+ class_entries.append(class_entry)
168
+ except OSError as e:
169
+ raise RuntimeError(f'can not read blocks file "{path}"') from e
170
+
171
+ assert class_entries[-1].maybe_filename is None
172
+
173
+ for class_entry1, class_entry2 in zip(class_entries, class_entries[1:]):
174
+ assert class_entry1.block_offset <= class_entry2.block_offset
175
+ start_offset = 512 * class_entry1.block_offset
176
+ end_offset = 512 * class_entry2.block_offset
177
+ assert class_entry1.maybe_filename is not None
178
+ filename = class_entry1.maybe_filename
179
+ entry = _Entry(class_index, start_offset, end_offset, filename)
180
+ # Skip invalid image files (PIL throws UnidentifiedImageError)
181
+ if filename == "n06470073_47249.JPEG":
182
+ continue
183
+ entries.append(entry)
184
+
185
+ return entries, class_ids
186
+
187
+ def _load_extra(self, extra_path: str) -> np.ndarray:
188
+ extra_root = self._extra_root
189
+ extra_full_path = os.path.join(extra_root, extra_path)
190
+ return np.load(extra_full_path, mmap_mode="r")
191
+
192
+ def _save_extra(self, extra_array: np.ndarray, extra_path: str) -> None:
193
+ extra_root = self._extra_root
194
+ extra_full_path = os.path.join(extra_root, extra_path)
195
+ os.makedirs(extra_root, exist_ok=True)
196
+ np.save(extra_full_path, extra_array)
197
+
198
+ @property
199
+ def _tarballs_root(self) -> str:
200
+ return self.root
201
+
202
+ def find_class_id(self, class_index: int) -> str:
203
+ return str(self._class_ids[class_index])
204
+
205
+ def get_image_data(self, index: int) -> bytes:
206
+ entry = self._entries[index]
207
+ class_id = entry["class_id"]
208
+ class_mmap = self._mmap_tarball(class_id)
209
+
210
+ start_offset, end_offset = entry["start_offset"], entry["end_offset"]
211
+ try:
212
+ mapped_data = class_mmap[start_offset:end_offset]
213
+ data = mapped_data[512:] # Skip entry header block
214
+
215
+ if len(data) >= 2 and tuple(data[:2]) == (0x1F, 0x8B):
216
+ assert index in self._gzipped_indices, f"unexpected gzip header for sample {index}"
217
+ with GzipFile(fileobj=BytesIO(data)) as g:
218
+ data = g.read()
219
+ except Exception as e:
220
+ raise RuntimeError(f"can not retrieve image data for sample {index} " f'from "{class_id}" tarball') from e
221
+
222
+ return data
223
+
224
+ def get_target(self, index: int) -> Any:
225
+ return int(self._entries[index]["class_index"])
226
+
227
+ def get_targets(self) -> np.ndarray:
228
+ return self._entries["class_index"]
229
+
230
+ def get_class_id(self, index: int) -> str:
231
+ return str(self._entries[index]["class_id"])
232
+
233
+ def get_class_ids(self) -> np.ndarray:
234
+ return self._entries["class_id"]
235
+
236
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
237
+ with warnings.catch_warnings():
238
+ warnings.simplefilter("ignore")
239
+ return super().__getitem__(index)
240
+
241
+ def __len__(self) -> int:
242
+ return len(self._entries)
243
+
244
+ def _dump_entries(self, *args, **kwargs) -> None:
245
+ entries, class_ids = self._load_entries_class_ids(*args, **kwargs)
246
+
247
+ max_class_id_length, max_filename_length, max_class_index = -1, -1, -1
248
+ for entry in entries:
249
+ class_id = class_ids[entry.class_index]
250
+ max_class_index = max(entry.class_index, max_class_index)
251
+ max_class_id_length = max(len(class_id), max_class_id_length)
252
+ max_filename_length = max(len(entry.filename), max_filename_length)
253
+
254
+ dtype = np.dtype(
255
+ [
256
+ ("class_index", "<u4"),
257
+ ("class_id", f"U{max_class_id_length}"),
258
+ ("start_offset", "<u4"),
259
+ ("end_offset", "<u4"),
260
+ ("filename", f"U{max_filename_length}"),
261
+ ]
262
+ )
263
+ sample_count = len(entries)
264
+ entries_array = np.empty(sample_count, dtype=dtype)
265
+ for i, entry in enumerate(entries):
266
+ class_index = entry.class_index
267
+ class_id = class_ids[class_index]
268
+ start_offset = entry.start_offset
269
+ end_offset = entry.end_offset
270
+ filename = entry.filename
271
+ entries_array[i] = (
272
+ class_index,
273
+ class_id,
274
+ start_offset,
275
+ end_offset,
276
+ filename,
277
+ )
278
+
279
+ entries_path = self._get_entries_path(*args, **kwargs)
280
+ self._save_extra(entries_array, entries_path)
281
+
282
+ def _dump_class_ids(self, *args, **kwargs) -> None:
283
+ entries_path = self._get_entries_path(*args, **kwargs)
284
+ entries_array = self._load_extra(entries_path)
285
+
286
+ max_class_id_length, max_class_index = -1, -1
287
+ for entry in entries_array:
288
+ class_index, class_id = entry["class_index"], entry["class_id"]
289
+ max_class_index = max(int(class_index), max_class_index)
290
+ max_class_id_length = max(len(str(class_id)), max_class_id_length)
291
+
292
+ class_ids_array = np.empty(max_class_index + 1, dtype=f"U{max_class_id_length}")
293
+ for entry in entries_array:
294
+ class_index, class_id = entry["class_index"], entry["class_id"]
295
+ class_ids_array[class_index] = class_id
296
+ class_ids_path = self._get_class_ids_path(*args, **kwargs)
297
+ self._save_extra(class_ids_array, class_ids_path)
298
+
299
+ def _dump_extra(self, *args, **kwargs) -> None:
300
+ self._dump_entries(*args, *kwargs)
301
+ self._dump_class_ids(*args, *kwargs)
302
+
303
+ def dump_extra(self, root: Optional[str] = None) -> None:
304
+ return self._dump_extra(root)
dinov2/dinov2/data/loaders.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
8
+ from enum import Enum
9
+ from typing import Any, Callable, List, Optional, TypeVar
10
+
11
+ import torch
12
+ from torch.utils.data import Sampler
13
+
14
+ from .datasets import ImageNet, ImageNet22k
15
+ from .samplers import EpochSampler, InfiniteSampler, ShardedInfiniteSampler
16
+
17
+
18
+ logger = logging.getLogger("dinov2")
19
+
20
+
21
+ class SamplerType(Enum):
22
+ DISTRIBUTED = 0
23
+ EPOCH = 1
24
+ INFINITE = 2
25
+ SHARDED_INFINITE = 3
26
+ SHARDED_INFINITE_NEW = 4
27
+
28
+
29
+ def _make_bool_str(b: bool) -> str:
30
+ return "yes" if b else "no"
31
+
32
+
33
+ def _make_sample_transform(image_transform: Optional[Callable] = None, target_transform: Optional[Callable] = None):
34
+ def transform(sample):
35
+ image, target = sample
36
+ if image_transform is not None:
37
+ image = image_transform(image)
38
+ if target_transform is not None:
39
+ target = target_transform(target)
40
+ return image, target
41
+
42
+ return transform
43
+
44
+
45
+ def _parse_dataset_str(dataset_str: str):
46
+ tokens = dataset_str.split(":")
47
+
48
+ name = tokens[0]
49
+ kwargs = {}
50
+
51
+ for token in tokens[1:]:
52
+ key, value = token.split("=")
53
+ assert key in ("root", "extra", "split")
54
+ kwargs[key] = value
55
+
56
+ if name == "ImageNet":
57
+ class_ = ImageNet
58
+ if "split" in kwargs:
59
+ kwargs["split"] = ImageNet.Split[kwargs["split"]]
60
+ elif name == "ImageNet22k":
61
+ class_ = ImageNet22k
62
+ else:
63
+ raise ValueError(f'Unsupported dataset "{name}"')
64
+
65
+ return class_, kwargs
66
+
67
+
68
+ def make_dataset(
69
+ *,
70
+ dataset_str: str,
71
+ transform: Optional[Callable] = None,
72
+ target_transform: Optional[Callable] = None,
73
+ ):
74
+ """
75
+ Creates a dataset with the specified parameters.
76
+
77
+ Args:
78
+ dataset_str: A dataset string description (e.g. ImageNet:split=TRAIN).
79
+ transform: A transform to apply to images.
80
+ target_transform: A transform to apply to targets.
81
+
82
+ Returns:
83
+ The created dataset.
84
+ """
85
+ logger.info(f'using dataset: "{dataset_str}"')
86
+
87
+ class_, kwargs = _parse_dataset_str(dataset_str)
88
+ dataset = class_(transform=transform, target_transform=target_transform, **kwargs)
89
+
90
+ logger.info(f"# of dataset samples: {len(dataset):,d}")
91
+
92
+ # Aggregated datasets do not expose (yet) these attributes, so add them.
93
+ if not hasattr(dataset, "transform"):
94
+ setattr(dataset, "transform", transform)
95
+ if not hasattr(dataset, "target_transform"):
96
+ setattr(dataset, "target_transform", target_transform)
97
+
98
+ return dataset
99
+
100
+
101
+ def _make_sampler(
102
+ *,
103
+ dataset,
104
+ type: Optional[SamplerType] = None,
105
+ shuffle: bool = False,
106
+ seed: int = 0,
107
+ size: int = -1,
108
+ advance: int = 0,
109
+ ) -> Optional[Sampler]:
110
+ sample_count = len(dataset)
111
+
112
+ if type == SamplerType.INFINITE:
113
+ logger.info("sampler: infinite")
114
+ if size > 0:
115
+ raise ValueError("sampler size > 0 is invalid")
116
+ return InfiniteSampler(
117
+ sample_count=sample_count,
118
+ shuffle=shuffle,
119
+ seed=seed,
120
+ advance=advance,
121
+ )
122
+ elif type in (SamplerType.SHARDED_INFINITE, SamplerType.SHARDED_INFINITE_NEW):
123
+ logger.info("sampler: sharded infinite")
124
+ if size > 0:
125
+ raise ValueError("sampler size > 0 is invalid")
126
+ # TODO: Remove support for old shuffling
127
+ use_new_shuffle_tensor_slice = type == SamplerType.SHARDED_INFINITE_NEW
128
+ return ShardedInfiniteSampler(
129
+ sample_count=sample_count,
130
+ shuffle=shuffle,
131
+ seed=seed,
132
+ advance=advance,
133
+ use_new_shuffle_tensor_slice=use_new_shuffle_tensor_slice,
134
+ )
135
+ elif type == SamplerType.EPOCH:
136
+ logger.info("sampler: epoch")
137
+ if advance > 0:
138
+ raise NotImplementedError("sampler advance > 0 is not supported")
139
+ size = size if size > 0 else sample_count
140
+ logger.info(f"# of samples / epoch: {size:,d}")
141
+ return EpochSampler(
142
+ size=size,
143
+ sample_count=sample_count,
144
+ shuffle=shuffle,
145
+ seed=seed,
146
+ )
147
+ elif type == SamplerType.DISTRIBUTED:
148
+ logger.info("sampler: distributed")
149
+ if size > 0:
150
+ raise ValueError("sampler size > 0 is invalid")
151
+ if advance > 0:
152
+ raise ValueError("sampler advance > 0 is invalid")
153
+ return torch.utils.data.DistributedSampler(
154
+ dataset=dataset,
155
+ shuffle=shuffle,
156
+ seed=seed,
157
+ drop_last=False,
158
+ )
159
+
160
+ logger.info("sampler: none")
161
+ return None
162
+
163
+
164
+ T = TypeVar("T")
165
+
166
+
167
+ def make_data_loader(
168
+ *,
169
+ dataset,
170
+ batch_size: int,
171
+ num_workers: int,
172
+ shuffle: bool = True,
173
+ seed: int = 0,
174
+ sampler_type: Optional[SamplerType] = SamplerType.INFINITE,
175
+ sampler_size: int = -1,
176
+ sampler_advance: int = 0,
177
+ drop_last: bool = True,
178
+ persistent_workers: bool = False,
179
+ collate_fn: Optional[Callable[[List[T]], Any]] = None,
180
+ ):
181
+ """
182
+ Creates a data loader with the specified parameters.
183
+
184
+ Args:
185
+ dataset: A dataset (third party, LaViDa or WebDataset).
186
+ batch_size: The size of batches to generate.
187
+ num_workers: The number of workers to use.
188
+ shuffle: Whether to shuffle samples.
189
+ seed: The random seed to use.
190
+ sampler_type: Which sampler to use: EPOCH, INFINITE, SHARDED_INFINITE, SHARDED_INFINITE_NEW, DISTRIBUTED or None.
191
+ sampler_size: The number of images per epoch (when applicable) or -1 for the entire dataset.
192
+ sampler_advance: How many samples to skip (when applicable).
193
+ drop_last: Whether the last non-full batch of data should be dropped.
194
+ persistent_workers: maintain the workers Dataset instances alive after a dataset has been consumed once.
195
+ collate_fn: Function that performs batch collation
196
+ """
197
+
198
+ sampler = _make_sampler(
199
+ dataset=dataset,
200
+ type=sampler_type,
201
+ shuffle=shuffle,
202
+ seed=seed,
203
+ size=sampler_size,
204
+ advance=sampler_advance,
205
+ )
206
+
207
+ logger.info("using PyTorch data loader")
208
+ data_loader = torch.utils.data.DataLoader(
209
+ dataset,
210
+ sampler=sampler,
211
+ batch_size=batch_size,
212
+ num_workers=num_workers,
213
+ pin_memory=True,
214
+ drop_last=drop_last,
215
+ persistent_workers=persistent_workers,
216
+ collate_fn=collate_fn,
217
+ )
218
+
219
+ try:
220
+ logger.info(f"# of batches: {len(data_loader):,d}")
221
+ except TypeError: # data loader has no length
222
+ logger.info("infinite data loader")
223
+ return data_loader
dinov2/dinov2/data/masking.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 random
8
+ import math
9
+ import numpy as np
10
+
11
+
12
+ class MaskingGenerator:
13
+ def __init__(
14
+ self,
15
+ input_size,
16
+ num_masking_patches=None,
17
+ min_num_patches=4,
18
+ max_num_patches=None,
19
+ min_aspect=0.3,
20
+ max_aspect=None,
21
+ ):
22
+ if not isinstance(input_size, tuple):
23
+ input_size = (input_size,) * 2
24
+ self.height, self.width = input_size
25
+
26
+ self.num_patches = self.height * self.width
27
+ self.num_masking_patches = num_masking_patches
28
+
29
+ self.min_num_patches = min_num_patches
30
+ self.max_num_patches = num_masking_patches if max_num_patches is None else max_num_patches
31
+
32
+ max_aspect = max_aspect or 1 / min_aspect
33
+ self.log_aspect_ratio = (math.log(min_aspect), math.log(max_aspect))
34
+
35
+ def __repr__(self):
36
+ repr_str = "Generator(%d, %d -> [%d ~ %d], max = %d, %.3f ~ %.3f)" % (
37
+ self.height,
38
+ self.width,
39
+ self.min_num_patches,
40
+ self.max_num_patches,
41
+ self.num_masking_patches,
42
+ self.log_aspect_ratio[0],
43
+ self.log_aspect_ratio[1],
44
+ )
45
+ return repr_str
46
+
47
+ def get_shape(self):
48
+ return self.height, self.width
49
+
50
+ def _mask(self, mask, max_mask_patches):
51
+ delta = 0
52
+ for _ in range(10):
53
+ target_area = random.uniform(self.min_num_patches, max_mask_patches)
54
+ aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))
55
+ h = int(round(math.sqrt(target_area * aspect_ratio)))
56
+ w = int(round(math.sqrt(target_area / aspect_ratio)))
57
+ if w < self.width and h < self.height:
58
+ top = random.randint(0, self.height - h)
59
+ left = random.randint(0, self.width - w)
60
+
61
+ num_masked = mask[top : top + h, left : left + w].sum()
62
+ # Overlap
63
+ if 0 < h * w - num_masked <= max_mask_patches:
64
+ for i in range(top, top + h):
65
+ for j in range(left, left + w):
66
+ if mask[i, j] == 0:
67
+ mask[i, j] = 1
68
+ delta += 1
69
+
70
+ if delta > 0:
71
+ break
72
+ return delta
73
+
74
+ def __call__(self, num_masking_patches=0):
75
+ mask = np.zeros(shape=self.get_shape(), dtype=bool)
76
+ mask_count = 0
77
+ while mask_count < num_masking_patches:
78
+ max_mask_patches = num_masking_patches - mask_count
79
+ max_mask_patches = min(max_mask_patches, self.max_num_patches)
80
+
81
+ delta = self._mask(mask, max_mask_patches)
82
+ if delta == 0:
83
+ break
84
+ else:
85
+ mask_count += delta
86
+
87
+ return mask
dinov2/dinov2/data/samplers.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 itertools
8
+ from typing import Any, Optional
9
+ import warnings
10
+
11
+ import numpy as np
12
+ import torch
13
+ from torch.utils.data.sampler import Sampler
14
+
15
+ import dinov2.distributed as distributed
16
+
17
+
18
+ class EpochSampler(Sampler):
19
+ def __init__(
20
+ self,
21
+ *,
22
+ size: int,
23
+ sample_count: int,
24
+ shuffle: bool = False,
25
+ seed: int = 0,
26
+ start: Optional[int] = None,
27
+ step: Optional[int] = None,
28
+ ):
29
+ self._size = size
30
+ self._sample_count = sample_count
31
+ self._shuffle = shuffle
32
+ self._seed = seed
33
+ self._start = distributed.get_global_rank() if start is None else start
34
+ self._step = distributed.get_global_size() if step is None else step
35
+ self._epoch = 0
36
+
37
+ def __iter__(self):
38
+ count = (self._size + self._sample_count - 1) // self._sample_count
39
+ tiled_indices = np.tile(np.arange(self._sample_count), count)
40
+ if self._shuffle:
41
+ seed = self._seed * self._epoch if self._seed != 0 else self._epoch
42
+ rng = np.random.default_rng(seed)
43
+ iterable = rng.choice(tiled_indices, self._size, replace=False)
44
+ else:
45
+ iterable = tiled_indices[: self._size]
46
+
47
+ yield from itertools.islice(iterable, self._start, None, self._step)
48
+
49
+ def __len__(self):
50
+ return (self._size - self._start + self._step - 1) // self._step
51
+
52
+ def set_epoch(self, epoch):
53
+ self._epoch = epoch
54
+
55
+
56
+ def _get_numpy_dtype(size: int) -> Any:
57
+ return np.int32 if size <= 2**31 else np.int64
58
+
59
+
60
+ def _get_torch_dtype(size: int) -> Any:
61
+ return torch.int32 if size <= 2**31 else torch.int64
62
+
63
+
64
+ def _generate_randperm_indices(*, size: int, generator: torch.Generator):
65
+ """Generate the indices of a random permutation."""
66
+ dtype = _get_torch_dtype(size)
67
+ # This is actually matching PyTorch's CPU implementation, see: https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/TensorFactories.cpp#L900-L921
68
+ perm = torch.arange(size, dtype=dtype)
69
+ for i in range(size):
70
+ j = torch.randint(i, size, size=(1,), generator=generator).item()
71
+
72
+ # Always swap even if no-op
73
+ value = perm[j].item()
74
+ perm[j] = perm[i].item()
75
+ perm[i] = value
76
+ yield value
77
+
78
+
79
+ class InfiniteSampler(Sampler):
80
+ def __init__(
81
+ self,
82
+ *,
83
+ sample_count: int,
84
+ shuffle: bool = False,
85
+ seed: int = 0,
86
+ start: Optional[int] = None,
87
+ step: Optional[int] = None,
88
+ advance: int = 0,
89
+ ):
90
+ self._sample_count = sample_count
91
+ self._seed = seed
92
+ self._shuffle = shuffle
93
+ self._start = distributed.get_global_rank() if start is None else start
94
+ self._step = distributed.get_global_size() if step is None else step
95
+ self._advance = advance
96
+
97
+ def __iter__(self):
98
+ if self._shuffle:
99
+ iterator = self._shuffled_iterator()
100
+ else:
101
+ iterator = self._iterator()
102
+
103
+ yield from itertools.islice(iterator, self._advance, None)
104
+
105
+ def _iterator(self):
106
+ assert not self._shuffle
107
+
108
+ while True:
109
+ iterable = range(self._sample_count)
110
+ yield from itertools.islice(iterable, self._start, None, self._step)
111
+
112
+ def _shuffled_iterator(self):
113
+ assert self._shuffle
114
+
115
+ # Instantiate a generator here (rather than in the ctor) to keep the class
116
+ # picklable (requirement of mp.spawn)
117
+ generator = torch.Generator().manual_seed(self._seed)
118
+
119
+ while True:
120
+ iterable = _generate_randperm_indices(size=self._sample_count, generator=generator)
121
+ yield from itertools.islice(iterable, self._start, None, self._step)
122
+
123
+
124
+ # The following function is somewhat equivalent to _new_shuffle_tensor_slice below,
125
+ # but avoids a full in-place random permutation generation.
126
+ def _shuffle_tensor_slice(
127
+ *, tensor: torch.Tensor, start: int = 0, step: int = 1, generator: torch.Generator
128
+ ) -> np.ndarray:
129
+ stop = len(tensor)
130
+ count = stop // step
131
+ drop_count = stop - step * count
132
+ if drop_count:
133
+ warnings.warn(f"# of dropped samples: {drop_count}")
134
+
135
+ dtype = _get_numpy_dtype(stop)
136
+ result = np.empty(count, dtype=dtype)
137
+
138
+ for i in range(count):
139
+ j = torch.randint(0, i + 1, size=(1,), generator=generator).item() if i > 0 else 0
140
+
141
+ result[i] = result[j]
142
+ result[j] = tensor[start + i * step].item()
143
+
144
+ return result
145
+
146
+
147
+ def _new_shuffle_tensor_slice(
148
+ *, tensor: torch.Tensor, start: int = 0, step: int = 1, generator: torch.Generator
149
+ ) -> np.ndarray:
150
+ stop = len(tensor)
151
+ count = stop // step
152
+ dtype = torch.int64 # Needed for using randperm result as indices
153
+ count = stop // step
154
+ drop_count = stop - step * count
155
+ if drop_count:
156
+ warnings.warn(f"# of dropped samples: {drop_count}")
157
+ indices = torch.randperm(count, dtype=dtype, generator=generator)
158
+ return tensor[start::step][indices].numpy()
159
+
160
+
161
+ def _make_seed(seed: int, start: int, iter_count: int) -> int:
162
+ # NOTE: Tried a few variants (including iter_count << 32), this one worked best.
163
+ return seed + start + (iter_count << 24)
164
+
165
+
166
+ class ShardedInfiniteSampler(Sampler):
167
+ def __init__(
168
+ self,
169
+ *,
170
+ sample_count: int,
171
+ shuffle: bool = False,
172
+ seed: int = 0,
173
+ start: Optional[int] = None,
174
+ step: Optional[int] = None,
175
+ advance: int = 0,
176
+ use_new_shuffle_tensor_slice: bool = False,
177
+ ):
178
+ self._sample_count = sample_count
179
+ self._seed = seed
180
+ self._shuffle = shuffle
181
+ self._start = distributed.get_global_rank() if start is None else start
182
+ self._step = distributed.get_global_size() if step is None else step
183
+ self._advance = advance
184
+ self._iter_count = 0
185
+ self._shuffle_tensor_slice_fn = (
186
+ _new_shuffle_tensor_slice if use_new_shuffle_tensor_slice else _shuffle_tensor_slice
187
+ )
188
+
189
+ def __iter__(self):
190
+ iter_count = self._advance // self._sample_count
191
+ if iter_count > 0:
192
+ self._advance -= iter_count * self._sample_count
193
+ self._iter_count += iter_count
194
+
195
+ if self._shuffle:
196
+ iterator = self._shuffled_iterator()
197
+ else:
198
+ iterator = self._iterator()
199
+
200
+ yield from itertools.islice(iterator, self._advance, None)
201
+
202
+ def _iterator(self):
203
+ assert not self._shuffle
204
+
205
+ while True:
206
+ iterable = range(self._sample_count)
207
+ yield from itertools.islice(iterable, self._start, None, self._step)
208
+
209
+ def _shuffled_iterator(self):
210
+ assert self._shuffle
211
+
212
+ # Instantiate a generator here (rather than in the ctor) to be keep the class
213
+ # picklable (requirement of mp.spawn)
214
+ generator = torch.Generator()
215
+
216
+ # Always shuffle everything first
217
+ generator.manual_seed(self._seed)
218
+ dtype = _get_torch_dtype(self._sample_count)
219
+ perm = torch.randperm(self._sample_count, dtype=dtype, generator=generator)
220
+
221
+ while True:
222
+ # Re-seed on each iteration to allow skipping whole permutations
223
+ seed = _make_seed(self._seed, self._start, self._iter_count)
224
+ generator.manual_seed(seed)
225
+
226
+ iterable = self._shuffle_tensor_slice_fn(
227
+ tensor=perm, start=self._start, step=self._step, generator=generator
228
+ )
229
+ yield from iterable
230
+ self._iter_count += 1
dinov2/dinov2/data/transforms.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Sequence
8
+
9
+ import torch
10
+ from torchvision import transforms
11
+
12
+
13
+ class GaussianBlur(transforms.RandomApply):
14
+ """
15
+ Apply Gaussian Blur to the PIL image.
16
+ """
17
+
18
+ def __init__(self, *, p: float = 0.5, radius_min: float = 0.1, radius_max: float = 2.0):
19
+ # NOTE: torchvision is applying 1 - probability to return the original image
20
+ keep_p = 1 - p
21
+ transform = transforms.GaussianBlur(kernel_size=9, sigma=(radius_min, radius_max))
22
+ super().__init__(transforms=[transform], p=keep_p)
23
+
24
+
25
+ class MaybeToTensor(transforms.ToTensor):
26
+ """
27
+ Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor, or keep as is if already a tensor.
28
+ """
29
+
30
+ def __call__(self, pic):
31
+ """
32
+ Args:
33
+ pic (PIL Image, numpy.ndarray or torch.tensor): Image to be converted to tensor.
34
+ Returns:
35
+ Tensor: Converted image.
36
+ """
37
+ if isinstance(pic, torch.Tensor):
38
+ return pic
39
+ return super().__call__(pic)
40
+
41
+
42
+ # Use timm's names
43
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
44
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
45
+
46
+
47
+ def make_normalize_transform(
48
+ mean: Sequence[float] = IMAGENET_DEFAULT_MEAN,
49
+ std: Sequence[float] = IMAGENET_DEFAULT_STD,
50
+ ) -> transforms.Normalize:
51
+ return transforms.Normalize(mean=mean, std=std)
52
+
53
+
54
+ # This roughly matches torchvision's preset for classification training:
55
+ # https://github.com/pytorch/vision/blob/main/references/classification/presets.py#L6-L44
56
+ def make_classification_train_transform(
57
+ *,
58
+ crop_size: int = 224,
59
+ interpolation=transforms.InterpolationMode.BICUBIC,
60
+ hflip_prob: float = 0.5,
61
+ mean: Sequence[float] = IMAGENET_DEFAULT_MEAN,
62
+ std: Sequence[float] = IMAGENET_DEFAULT_STD,
63
+ ):
64
+ transforms_list = [transforms.RandomResizedCrop(crop_size, interpolation=interpolation)]
65
+ if hflip_prob > 0.0:
66
+ transforms_list.append(transforms.RandomHorizontalFlip(hflip_prob))
67
+ transforms_list.extend(
68
+ [
69
+ MaybeToTensor(),
70
+ make_normalize_transform(mean=mean, std=std),
71
+ ]
72
+ )
73
+ return transforms.Compose(transforms_list)
74
+
75
+
76
+ # This matches (roughly) torchvision's preset for classification evaluation:
77
+ # https://github.com/pytorch/vision/blob/main/references/classification/presets.py#L47-L69
78
+ def make_classification_eval_transform(
79
+ *,
80
+ resize_size: int = 256,
81
+ interpolation=transforms.InterpolationMode.BICUBIC,
82
+ crop_size: int = 224,
83
+ mean: Sequence[float] = IMAGENET_DEFAULT_MEAN,
84
+ std: Sequence[float] = IMAGENET_DEFAULT_STD,
85
+ ) -> transforms.Compose:
86
+ transforms_list = [
87
+ transforms.Resize(resize_size, interpolation=interpolation),
88
+ transforms.CenterCrop(crop_size),
89
+ MaybeToTensor(),
90
+ make_normalize_transform(mean=mean, std=std),
91
+ ]
92
+ return transforms.Compose(transforms_list)
dinov2/dinov2/distributed/__init__.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
8
+ import random
9
+ import re
10
+ import socket
11
+ from typing import Dict, List
12
+
13
+ import torch
14
+ import torch.distributed as dist
15
+
16
+ _LOCAL_RANK = -1
17
+ _LOCAL_WORLD_SIZE = -1
18
+
19
+
20
+ def is_enabled() -> bool:
21
+ """
22
+ Returns:
23
+ True if distributed training is enabled
24
+ """
25
+ return dist.is_available() and dist.is_initialized()
26
+
27
+
28
+ def get_global_size() -> int:
29
+ """
30
+ Returns:
31
+ The number of processes in the process group
32
+ """
33
+ return dist.get_world_size() if is_enabled() else 1
34
+
35
+
36
+ def get_global_rank() -> int:
37
+ """
38
+ Returns:
39
+ The rank of the current process within the global process group.
40
+ """
41
+ return dist.get_rank() if is_enabled() else 0
42
+
43
+
44
+ def get_local_rank() -> int:
45
+ """
46
+ Returns:
47
+ The rank of the current process within the local (per-machine) process group.
48
+ """
49
+ if not is_enabled():
50
+ return 0
51
+ assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE
52
+ return _LOCAL_RANK
53
+
54
+
55
+ def get_local_size() -> int:
56
+ """
57
+ Returns:
58
+ The size of the per-machine process group,
59
+ i.e. the number of processes per machine.
60
+ """
61
+ if not is_enabled():
62
+ return 1
63
+ assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE
64
+ return _LOCAL_WORLD_SIZE
65
+
66
+
67
+ def is_main_process() -> bool:
68
+ """
69
+ Returns:
70
+ True if the current process is the main one.
71
+ """
72
+ return get_global_rank() == 0
73
+
74
+
75
+ def _restrict_print_to_main_process() -> None:
76
+ """
77
+ This function disables printing when not in the main process
78
+ """
79
+ import builtins as __builtin__
80
+
81
+ builtin_print = __builtin__.print
82
+
83
+ def print(*args, **kwargs):
84
+ force = kwargs.pop("force", False)
85
+ if is_main_process() or force:
86
+ builtin_print(*args, **kwargs)
87
+
88
+ __builtin__.print = print
89
+
90
+
91
+ def _get_master_port(seed: int = 0) -> int:
92
+ MIN_MASTER_PORT, MAX_MASTER_PORT = (20_000, 60_000)
93
+
94
+ master_port_str = os.environ.get("MASTER_PORT")
95
+ if master_port_str is None:
96
+ rng = random.Random(seed)
97
+ return rng.randint(MIN_MASTER_PORT, MAX_MASTER_PORT)
98
+
99
+ return int(master_port_str)
100
+
101
+
102
+ def _get_available_port() -> int:
103
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
104
+ # A "" host address means INADDR_ANY i.e. binding to all interfaces.
105
+ # Note this is not compatible with IPv6.
106
+ s.bind(("", 0))
107
+ port = s.getsockname()[1]
108
+ return port
109
+
110
+
111
+ _TORCH_DISTRIBUTED_ENV_VARS = (
112
+ "MASTER_ADDR",
113
+ "MASTER_PORT",
114
+ "RANK",
115
+ "WORLD_SIZE",
116
+ "LOCAL_RANK",
117
+ "LOCAL_WORLD_SIZE",
118
+ )
119
+
120
+
121
+ def _collect_env_vars() -> Dict[str, str]:
122
+ return {env_var: os.environ[env_var] for env_var in _TORCH_DISTRIBUTED_ENV_VARS if env_var in os.environ}
123
+
124
+
125
+ def _is_slurm_job_process() -> bool:
126
+ return "SLURM_JOB_ID" in os.environ
127
+
128
+
129
+ def _parse_slurm_node_list(s: str) -> List[str]:
130
+ nodes = []
131
+ # Extract "hostname", "hostname[1-2,3,4-5]," substrings
132
+ p = re.compile(r"(([^\[]+)(?:\[([^\]]+)\])?),?")
133
+ for m in p.finditer(s):
134
+ prefix, suffixes = s[m.start(2) : m.end(2)], s[m.start(3) : m.end(3)]
135
+ for suffix in suffixes.split(","):
136
+ span = suffix.split("-")
137
+ if len(span) == 1:
138
+ nodes.append(prefix + suffix)
139
+ else:
140
+ width = len(span[0])
141
+ start, end = int(span[0]), int(span[1]) + 1
142
+ nodes.extend([prefix + f"{i:0{width}}" for i in range(start, end)])
143
+ return nodes
144
+
145
+
146
+ def _check_env_variable(key: str, new_value: str):
147
+ # Only check for difference with preset environment variables
148
+ if key in os.environ and os.environ[key] != new_value:
149
+ raise RuntimeError(f"Cannot export environment variables as {key} is already set")
150
+
151
+
152
+ class _TorchDistributedEnvironment:
153
+ def __init__(self):
154
+ self.master_addr = "127.0.0.1"
155
+ self.master_port = 0
156
+ self.rank = -1
157
+ self.world_size = -1
158
+ self.local_rank = -1
159
+ self.local_world_size = -1
160
+
161
+ if _is_slurm_job_process():
162
+ return self._set_from_slurm_env()
163
+
164
+ env_vars = _collect_env_vars()
165
+ if not env_vars:
166
+ # Environment is not set
167
+ pass
168
+ elif len(env_vars) == len(_TORCH_DISTRIBUTED_ENV_VARS):
169
+ # Environment is fully set
170
+ return self._set_from_preset_env()
171
+ else:
172
+ # Environment is partially set
173
+ collected_env_vars = ", ".join(env_vars.keys())
174
+ raise RuntimeError(f"Partially set environment: {collected_env_vars}")
175
+
176
+ if torch.cuda.device_count() > 0:
177
+ return self._set_from_local()
178
+
179
+ raise RuntimeError("Can't initialize PyTorch distributed environment")
180
+
181
+ # Slurm job created with sbatch, submitit, etc...
182
+ def _set_from_slurm_env(self):
183
+ # logger.info("Initialization from Slurm environment")
184
+ job_id = int(os.environ["SLURM_JOB_ID"])
185
+ node_count = int(os.environ["SLURM_JOB_NUM_NODES"])
186
+ nodes = _parse_slurm_node_list(os.environ["SLURM_JOB_NODELIST"])
187
+ assert len(nodes) == node_count
188
+
189
+ self.master_addr = nodes[0]
190
+ self.master_port = _get_master_port(seed=job_id)
191
+ self.rank = int(os.environ["SLURM_PROCID"])
192
+ self.world_size = int(os.environ["SLURM_NTASKS"])
193
+ assert self.rank < self.world_size
194
+ self.local_rank = int(os.environ["SLURM_LOCALID"])
195
+ self.local_world_size = self.world_size // node_count
196
+ assert self.local_rank < self.local_world_size
197
+
198
+ # Single node job with preset environment (i.e. torchrun)
199
+ def _set_from_preset_env(self):
200
+ # logger.info("Initialization from preset environment")
201
+ self.master_addr = os.environ["MASTER_ADDR"]
202
+ self.master_port = os.environ["MASTER_PORT"]
203
+ self.rank = int(os.environ["RANK"])
204
+ self.world_size = int(os.environ["WORLD_SIZE"])
205
+ assert self.rank < self.world_size
206
+ self.local_rank = int(os.environ["LOCAL_RANK"])
207
+ self.local_world_size = int(os.environ["LOCAL_WORLD_SIZE"])
208
+ assert self.local_rank < self.local_world_size
209
+
210
+ # Single node and GPU job (i.e. local script run)
211
+ def _set_from_local(self):
212
+ # logger.info("Initialization from local")
213
+ self.master_addr = "127.0.0.1"
214
+ self.master_port = _get_available_port()
215
+ self.rank = 0
216
+ self.world_size = 1
217
+ self.local_rank = 0
218
+ self.local_world_size = 1
219
+
220
+ def export(self, *, overwrite: bool) -> "_TorchDistributedEnvironment":
221
+ # See the "Environment variable initialization" section from
222
+ # https://pytorch.org/docs/stable/distributed.html for the complete list of
223
+ # environment variables required for the env:// initialization method.
224
+ env_vars = {
225
+ "MASTER_ADDR": self.master_addr,
226
+ "MASTER_PORT": str(self.master_port),
227
+ "RANK": str(self.rank),
228
+ "WORLD_SIZE": str(self.world_size),
229
+ "LOCAL_RANK": str(self.local_rank),
230
+ "LOCAL_WORLD_SIZE": str(self.local_world_size),
231
+ }
232
+ if not overwrite:
233
+ for k, v in env_vars.items():
234
+ _check_env_variable(k, v)
235
+
236
+ os.environ.update(env_vars)
237
+ return self
238
+
239
+
240
+ def enable(*, set_cuda_current_device: bool = True, overwrite: bool = False, allow_nccl_timeout: bool = False):
241
+ """Enable distributed mode
242
+
243
+ Args:
244
+ set_cuda_current_device: If True, call torch.cuda.set_device() to set the
245
+ current PyTorch CUDA device to the one matching the local rank.
246
+ overwrite: If True, overwrites already set variables. Else fails.
247
+ """
248
+
249
+ global _LOCAL_RANK, _LOCAL_WORLD_SIZE
250
+ if _LOCAL_RANK >= 0 or _LOCAL_WORLD_SIZE >= 0:
251
+ raise RuntimeError("Distributed mode has already been enabled")
252
+ torch_env = _TorchDistributedEnvironment()
253
+ torch_env.export(overwrite=overwrite)
254
+
255
+ if set_cuda_current_device:
256
+ torch.cuda.set_device(torch_env.local_rank)
257
+
258
+ if allow_nccl_timeout:
259
+ # This allows to use torch distributed timeout in a NCCL backend
260
+ key, value = "NCCL_ASYNC_ERROR_HANDLING", "1"
261
+ if not overwrite:
262
+ _check_env_variable(key, value)
263
+ os.environ[key] = value
264
+
265
+ dist.init_process_group(backend="nccl")
266
+ dist.barrier()
267
+
268
+ # Finalize setup
269
+ _LOCAL_RANK = torch_env.local_rank
270
+ _LOCAL_WORLD_SIZE = torch_env.local_world_size
271
+ _restrict_print_to_main_process()
dinov2/dinov2/eval/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
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.
dinov2/dinov2/eval/knn.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
8
+ from functools import partial
9
+ import json
10
+ import logging
11
+ import os
12
+ import sys
13
+ from typing import List, Optional
14
+
15
+ import torch
16
+ from torch.nn.functional import one_hot, softmax
17
+
18
+ import dinov2.distributed as distributed
19
+ from dinov2.data import SamplerType, make_data_loader, make_dataset
20
+ from dinov2.data.transforms import make_classification_eval_transform
21
+ from dinov2.eval.metrics import AccuracyAveraging, build_topk_accuracy_metric
22
+ from dinov2.eval.setup import get_args_parser as get_setup_args_parser
23
+ from dinov2.eval.setup import setup_and_build_model
24
+ from dinov2.eval.utils import ModelWithNormalize, evaluate, extract_features
25
+
26
+
27
+ logger = logging.getLogger("dinov2")
28
+
29
+
30
+ def get_args_parser(
31
+ description: Optional[str] = None,
32
+ parents: Optional[List[argparse.ArgumentParser]] = [],
33
+ add_help: bool = True,
34
+ ):
35
+ setup_args_parser = get_setup_args_parser(parents=parents, add_help=False)
36
+ parents = [setup_args_parser]
37
+ parser = argparse.ArgumentParser(
38
+ description=description,
39
+ parents=parents,
40
+ add_help=add_help,
41
+ )
42
+ parser.add_argument(
43
+ "--train-dataset",
44
+ dest="train_dataset_str",
45
+ type=str,
46
+ help="Training dataset",
47
+ )
48
+ parser.add_argument(
49
+ "--val-dataset",
50
+ dest="val_dataset_str",
51
+ type=str,
52
+ help="Validation dataset",
53
+ )
54
+ parser.add_argument(
55
+ "--nb_knn",
56
+ nargs="+",
57
+ type=int,
58
+ help="Number of NN to use. 20 is usually working the best.",
59
+ )
60
+ parser.add_argument(
61
+ "--temperature",
62
+ type=float,
63
+ help="Temperature used in the voting coefficient",
64
+ )
65
+ parser.add_argument(
66
+ "--gather-on-cpu",
67
+ action="store_true",
68
+ help="Whether to gather the train features on cpu, slower"
69
+ "but useful to avoid OOM for large datasets (e.g. ImageNet22k).",
70
+ )
71
+ parser.add_argument(
72
+ "--batch-size",
73
+ type=int,
74
+ help="Batch size.",
75
+ )
76
+ parser.add_argument(
77
+ "--n-per-class-list",
78
+ nargs="+",
79
+ type=int,
80
+ help="Number to take per class",
81
+ )
82
+ parser.add_argument(
83
+ "--n-tries",
84
+ type=int,
85
+ help="Number of tries",
86
+ )
87
+ parser.set_defaults(
88
+ train_dataset_str="ImageNet:split=TRAIN",
89
+ val_dataset_str="ImageNet:split=VAL",
90
+ nb_knn=[10, 20, 100, 200],
91
+ temperature=0.07,
92
+ batch_size=256,
93
+ n_per_class_list=[-1],
94
+ n_tries=1,
95
+ )
96
+ return parser
97
+
98
+
99
+ class KnnModule(torch.nn.Module):
100
+ """
101
+ Gets knn of test features from all processes on a chunk of the train features
102
+
103
+ Each rank gets a chunk of the train features as well as a chunk of the test features.
104
+ In `compute_neighbors`, for each rank one after the other, its chunk of test features
105
+ is sent to all devices, partial knns are computed with each chunk of train features
106
+ then collated back on the original device.
107
+ """
108
+
109
+ def __init__(self, train_features, train_labels, nb_knn, T, device, num_classes=1000):
110
+ super().__init__()
111
+
112
+ self.global_rank = distributed.get_global_rank()
113
+ self.global_size = distributed.get_global_size()
114
+
115
+ self.device = device
116
+ self.train_features_rank_T = train_features.chunk(self.global_size)[self.global_rank].T.to(self.device)
117
+ self.candidates = train_labels.chunk(self.global_size)[self.global_rank].view(1, -1).to(self.device)
118
+
119
+ self.nb_knn = nb_knn
120
+ self.max_k = max(self.nb_knn)
121
+ self.T = T
122
+ self.num_classes = num_classes
123
+
124
+ def _get_knn_sims_and_labels(self, similarity, train_labels):
125
+ topk_sims, indices = similarity.topk(self.max_k, largest=True, sorted=True)
126
+ neighbors_labels = torch.gather(train_labels, 1, indices)
127
+ return topk_sims, neighbors_labels
128
+
129
+ def _similarity_for_rank(self, features_rank, source_rank):
130
+ # Send the features from `source_rank` to all ranks
131
+ broadcast_shape = torch.tensor(features_rank.shape).to(self.device)
132
+ torch.distributed.broadcast(broadcast_shape, source_rank)
133
+
134
+ broadcasted = features_rank
135
+ if self.global_rank != source_rank:
136
+ broadcasted = torch.zeros(*broadcast_shape, dtype=features_rank.dtype, device=self.device)
137
+ torch.distributed.broadcast(broadcasted, source_rank)
138
+
139
+ # Compute the neighbors for `source_rank` among `train_features_rank_T`
140
+ similarity_rank = torch.mm(broadcasted, self.train_features_rank_T)
141
+ candidate_labels = self.candidates.expand(len(similarity_rank), -1)
142
+ return self._get_knn_sims_and_labels(similarity_rank, candidate_labels)
143
+
144
+ def _gather_all_knn_for_rank(self, topk_sims, neighbors_labels, target_rank):
145
+ # Gather all neighbors for `target_rank`
146
+ topk_sims_rank = retrieved_rank = None
147
+ if self.global_rank == target_rank:
148
+ topk_sims_rank = [torch.zeros_like(topk_sims) for _ in range(self.global_size)]
149
+ retrieved_rank = [torch.zeros_like(neighbors_labels) for _ in range(self.global_size)]
150
+
151
+ torch.distributed.gather(topk_sims, topk_sims_rank, dst=target_rank)
152
+ torch.distributed.gather(neighbors_labels, retrieved_rank, dst=target_rank)
153
+
154
+ if self.global_rank == target_rank:
155
+ # Perform a second top-k on the k * global_size retrieved neighbors
156
+ topk_sims_rank = torch.cat(topk_sims_rank, dim=1)
157
+ retrieved_rank = torch.cat(retrieved_rank, dim=1)
158
+ results = self._get_knn_sims_and_labels(topk_sims_rank, retrieved_rank)
159
+ return results
160
+ return None
161
+
162
+ def compute_neighbors(self, features_rank):
163
+ for rank in range(self.global_size):
164
+ topk_sims, neighbors_labels = self._similarity_for_rank(features_rank, rank)
165
+ results = self._gather_all_knn_for_rank(topk_sims, neighbors_labels, rank)
166
+ if results is not None:
167
+ topk_sims_rank, neighbors_labels_rank = results
168
+ return topk_sims_rank, neighbors_labels_rank
169
+
170
+ def forward(self, features_rank):
171
+ """
172
+ Compute the results on all values of `self.nb_knn` neighbors from the full `self.max_k`
173
+ """
174
+ assert all(k <= self.max_k for k in self.nb_knn)
175
+
176
+ topk_sims, neighbors_labels = self.compute_neighbors(features_rank)
177
+ batch_size = neighbors_labels.shape[0]
178
+ topk_sims_transform = softmax(topk_sims / self.T, 1)
179
+ matmul = torch.mul(
180
+ one_hot(neighbors_labels, num_classes=self.num_classes),
181
+ topk_sims_transform.view(batch_size, -1, 1),
182
+ )
183
+ probas_for_k = {k: torch.sum(matmul[:, :k, :], 1) for k in self.nb_knn}
184
+ return probas_for_k
185
+
186
+
187
+ class DictKeysModule(torch.nn.Module):
188
+ def __init__(self, keys):
189
+ super().__init__()
190
+ self.keys = keys
191
+
192
+ def forward(self, features_dict, targets):
193
+ for k in self.keys:
194
+ features_dict = features_dict[k]
195
+ return {"preds": features_dict, "target": targets}
196
+
197
+
198
+ def create_module_dict(*, module, n_per_class_list, n_tries, nb_knn, train_features, train_labels):
199
+ modules = {}
200
+ mapping = create_class_indices_mapping(train_labels)
201
+ for npc in n_per_class_list:
202
+ if npc < 0: # Only one try needed when using the full data
203
+ full_module = module(
204
+ train_features=train_features,
205
+ train_labels=train_labels,
206
+ nb_knn=nb_knn,
207
+ )
208
+ modules["full"] = ModuleDictWithForward({"1": full_module})
209
+ continue
210
+ all_tries = {}
211
+ for t in range(n_tries):
212
+ final_indices = filter_train(mapping, npc, seed=t)
213
+ k_list = list(set(nb_knn + [npc]))
214
+ k_list = sorted([el for el in k_list if el <= npc])
215
+ all_tries[str(t)] = module(
216
+ train_features=train_features[final_indices],
217
+ train_labels=train_labels[final_indices],
218
+ nb_knn=k_list,
219
+ )
220
+ modules[f"{npc} per class"] = ModuleDictWithForward(all_tries)
221
+
222
+ return ModuleDictWithForward(modules)
223
+
224
+
225
+ def filter_train(mapping, n_per_class, seed):
226
+ torch.manual_seed(seed)
227
+ final_indices = []
228
+ for k in mapping.keys():
229
+ index = torch.randperm(len(mapping[k]))[:n_per_class]
230
+ final_indices.append(mapping[k][index])
231
+ return torch.cat(final_indices).squeeze()
232
+
233
+
234
+ def create_class_indices_mapping(labels):
235
+ unique_labels, inverse = torch.unique(labels, return_inverse=True)
236
+ mapping = {unique_labels[i]: (inverse == i).nonzero() for i in range(len(unique_labels))}
237
+ return mapping
238
+
239
+
240
+ class ModuleDictWithForward(torch.nn.ModuleDict):
241
+ def forward(self, *args, **kwargs):
242
+ return {k: module(*args, **kwargs) for k, module in self._modules.items()}
243
+
244
+
245
+ def eval_knn(
246
+ model,
247
+ train_dataset,
248
+ val_dataset,
249
+ accuracy_averaging,
250
+ nb_knn,
251
+ temperature,
252
+ batch_size,
253
+ num_workers,
254
+ gather_on_cpu,
255
+ n_per_class_list=[-1],
256
+ n_tries=1,
257
+ ):
258
+ model = ModelWithNormalize(model)
259
+
260
+ logger.info("Extracting features for train set...")
261
+ train_features, train_labels = extract_features(
262
+ model, train_dataset, batch_size, num_workers, gather_on_cpu=gather_on_cpu
263
+ )
264
+ logger.info(f"Train features created, shape {train_features.shape}.")
265
+
266
+ val_dataloader = make_data_loader(
267
+ dataset=val_dataset,
268
+ batch_size=batch_size,
269
+ num_workers=num_workers,
270
+ sampler_type=SamplerType.DISTRIBUTED,
271
+ drop_last=False,
272
+ shuffle=False,
273
+ persistent_workers=True,
274
+ )
275
+ num_classes = train_labels.max() + 1
276
+ metric_collection = build_topk_accuracy_metric(accuracy_averaging, num_classes=num_classes)
277
+
278
+ device = torch.cuda.current_device()
279
+ partial_module = partial(KnnModule, T=temperature, device=device, num_classes=num_classes)
280
+ knn_module_dict = create_module_dict(
281
+ module=partial_module,
282
+ n_per_class_list=n_per_class_list,
283
+ n_tries=n_tries,
284
+ nb_knn=nb_knn,
285
+ train_features=train_features,
286
+ train_labels=train_labels,
287
+ )
288
+ postprocessors, metrics = {}, {}
289
+ for n_per_class, knn_module in knn_module_dict.items():
290
+ for t, knn_try in knn_module.items():
291
+ postprocessors = {
292
+ **postprocessors,
293
+ **{(n_per_class, t, k): DictKeysModule([n_per_class, t, k]) for k in knn_try.nb_knn},
294
+ }
295
+ metrics = {**metrics, **{(n_per_class, t, k): metric_collection.clone() for k in knn_try.nb_knn}}
296
+ model_with_knn = torch.nn.Sequential(model, knn_module_dict)
297
+
298
+ # ============ evaluation ... ============
299
+ logger.info("Start the k-NN classification.")
300
+ _, results_dict = evaluate(model_with_knn, val_dataloader, postprocessors, metrics, device)
301
+
302
+ # Averaging the results over the n tries for each value of n_per_class
303
+ for n_per_class, knn_module in knn_module_dict.items():
304
+ first_try = list(knn_module.keys())[0]
305
+ k_list = knn_module[first_try].nb_knn
306
+ for k in k_list:
307
+ keys = results_dict[(n_per_class, first_try, k)].keys() # keys are e.g. `top-1` and `top-5`
308
+ results_dict[(n_per_class, k)] = {
309
+ key: torch.mean(torch.stack([results_dict[(n_per_class, t, k)][key] for t in knn_module.keys()]))
310
+ for key in keys
311
+ }
312
+ for t in knn_module.keys():
313
+ del results_dict[(n_per_class, t, k)]
314
+
315
+ return results_dict
316
+
317
+
318
+ def eval_knn_with_model(
319
+ model,
320
+ output_dir,
321
+ train_dataset_str="ImageNet:split=TRAIN",
322
+ val_dataset_str="ImageNet:split=VAL",
323
+ nb_knn=(10, 20, 100, 200),
324
+ temperature=0.07,
325
+ autocast_dtype=torch.float,
326
+ accuracy_averaging=AccuracyAveraging.MEAN_ACCURACY,
327
+ transform=None,
328
+ gather_on_cpu=False,
329
+ batch_size=256,
330
+ num_workers=5,
331
+ n_per_class_list=[-1],
332
+ n_tries=1,
333
+ ):
334
+ transform = transform or make_classification_eval_transform()
335
+
336
+ train_dataset = make_dataset(
337
+ dataset_str=train_dataset_str,
338
+ transform=transform,
339
+ )
340
+ val_dataset = make_dataset(
341
+ dataset_str=val_dataset_str,
342
+ transform=transform,
343
+ )
344
+
345
+ with torch.cuda.amp.autocast(dtype=autocast_dtype):
346
+ results_dict_knn = eval_knn(
347
+ model=model,
348
+ train_dataset=train_dataset,
349
+ val_dataset=val_dataset,
350
+ accuracy_averaging=accuracy_averaging,
351
+ nb_knn=nb_knn,
352
+ temperature=temperature,
353
+ batch_size=batch_size,
354
+ num_workers=num_workers,
355
+ gather_on_cpu=gather_on_cpu,
356
+ n_per_class_list=n_per_class_list,
357
+ n_tries=n_tries,
358
+ )
359
+
360
+ results_dict = {}
361
+ if distributed.is_main_process():
362
+ for knn_ in results_dict_knn.keys():
363
+ top1 = results_dict_knn[knn_]["top-1"].item() * 100.0
364
+ top5 = results_dict_knn[knn_]["top-5"].item() * 100.0
365
+ results_dict[f"{knn_} Top 1"] = top1
366
+ results_dict[f"{knn_} Top 5"] = top5
367
+ logger.info(f"{knn_} classifier result: Top1: {top1:.2f} Top5: {top5:.2f}")
368
+
369
+ metrics_file_path = os.path.join(output_dir, "results_eval_knn.json")
370
+ with open(metrics_file_path, "a") as f:
371
+ for k, v in results_dict.items():
372
+ f.write(json.dumps({k: v}) + "\n")
373
+
374
+ if distributed.is_enabled():
375
+ torch.distributed.barrier()
376
+ return results_dict
377
+
378
+
379
+ def main(args):
380
+ model, autocast_dtype = setup_and_build_model(args)
381
+ eval_knn_with_model(
382
+ model=model,
383
+ output_dir=args.output_dir,
384
+ train_dataset_str=args.train_dataset_str,
385
+ val_dataset_str=args.val_dataset_str,
386
+ nb_knn=args.nb_knn,
387
+ temperature=args.temperature,
388
+ autocast_dtype=autocast_dtype,
389
+ accuracy_averaging=AccuracyAveraging.MEAN_ACCURACY,
390
+ transform=None,
391
+ gather_on_cpu=args.gather_on_cpu,
392
+ batch_size=args.batch_size,
393
+ num_workers=5,
394
+ n_per_class_list=args.n_per_class_list,
395
+ n_tries=args.n_tries,
396
+ )
397
+ return 0
398
+
399
+
400
+ if __name__ == "__main__":
401
+ description = "DINOv2 k-NN evaluation"
402
+ args_parser = get_args_parser(description=description)
403
+ args = args_parser.parse_args()
404
+ sys.exit(main(args))
dinov2/dinov2/eval/linear.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
8
+ from functools import partial
9
+ import json
10
+ import logging
11
+ import os
12
+ import sys
13
+ from typing import List, Optional
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn as nn
18
+ from torch.nn.parallel import DistributedDataParallel
19
+ from fvcore.common.checkpoint import Checkpointer, PeriodicCheckpointer
20
+
21
+ from dinov2.data import SamplerType, make_data_loader, make_dataset
22
+ from dinov2.data.transforms import make_classification_eval_transform, make_classification_train_transform
23
+ import dinov2.distributed as distributed
24
+ from dinov2.eval.metrics import MetricType, build_metric
25
+ from dinov2.eval.setup import get_args_parser as get_setup_args_parser
26
+ from dinov2.eval.setup import setup_and_build_model
27
+ from dinov2.eval.utils import ModelWithIntermediateLayers, evaluate
28
+ from dinov2.logging import MetricLogger
29
+
30
+
31
+ logger = logging.getLogger("dinov2")
32
+
33
+
34
+ def get_args_parser(
35
+ description: Optional[str] = None,
36
+ parents: Optional[List[argparse.ArgumentParser]] = [],
37
+ add_help: bool = True,
38
+ ):
39
+ setup_args_parser = get_setup_args_parser(parents=parents, add_help=False)
40
+ parents = [setup_args_parser]
41
+ parser = argparse.ArgumentParser(
42
+ description=description,
43
+ parents=parents,
44
+ add_help=add_help,
45
+ )
46
+ parser.add_argument(
47
+ "--train-dataset",
48
+ dest="train_dataset_str",
49
+ type=str,
50
+ help="Training dataset",
51
+ )
52
+ parser.add_argument(
53
+ "--val-dataset",
54
+ dest="val_dataset_str",
55
+ type=str,
56
+ help="Validation dataset",
57
+ )
58
+ parser.add_argument(
59
+ "--test-datasets",
60
+ dest="test_dataset_strs",
61
+ type=str,
62
+ nargs="+",
63
+ help="Test datasets, none to reuse the validation dataset",
64
+ )
65
+ parser.add_argument(
66
+ "--epochs",
67
+ type=int,
68
+ help="Number of training epochs",
69
+ )
70
+ parser.add_argument(
71
+ "--batch-size",
72
+ type=int,
73
+ help="Batch Size (per GPU)",
74
+ )
75
+ parser.add_argument(
76
+ "--num-workers",
77
+ type=int,
78
+ help="Number de Workers",
79
+ )
80
+ parser.add_argument(
81
+ "--epoch-length",
82
+ type=int,
83
+ help="Length of an epoch in number of iterations",
84
+ )
85
+ parser.add_argument(
86
+ "--save-checkpoint-frequency",
87
+ type=int,
88
+ help="Number of epochs between two named checkpoint saves.",
89
+ )
90
+ parser.add_argument(
91
+ "--eval-period-iterations",
92
+ type=int,
93
+ help="Number of iterations between two evaluations.",
94
+ )
95
+ parser.add_argument(
96
+ "--learning-rates",
97
+ nargs="+",
98
+ type=float,
99
+ help="Learning rates to grid search.",
100
+ )
101
+ parser.add_argument(
102
+ "--no-resume",
103
+ action="store_true",
104
+ help="Whether to not resume from existing checkpoints",
105
+ )
106
+ parser.add_argument(
107
+ "--val-metric-type",
108
+ type=MetricType,
109
+ choices=list(MetricType),
110
+ help="Validation metric",
111
+ )
112
+ parser.add_argument(
113
+ "--test-metric-types",
114
+ type=MetricType,
115
+ choices=list(MetricType),
116
+ nargs="+",
117
+ help="Evaluation metric",
118
+ )
119
+ parser.add_argument(
120
+ "--classifier-fpath",
121
+ type=str,
122
+ help="Path to a file containing pretrained linear classifiers",
123
+ )
124
+ parser.add_argument(
125
+ "--val-class-mapping-fpath",
126
+ type=str,
127
+ help="Path to a file containing a mapping to adjust classifier outputs",
128
+ )
129
+ parser.add_argument(
130
+ "--test-class-mapping-fpaths",
131
+ nargs="+",
132
+ type=str,
133
+ help="Path to a file containing a mapping to adjust classifier outputs",
134
+ )
135
+ parser.set_defaults(
136
+ train_dataset_str="ImageNet:split=TRAIN",
137
+ val_dataset_str="ImageNet:split=VAL",
138
+ test_dataset_strs=None,
139
+ epochs=10,
140
+ batch_size=128,
141
+ num_workers=8,
142
+ epoch_length=1250,
143
+ save_checkpoint_frequency=20,
144
+ eval_period_iterations=1250,
145
+ learning_rates=[1e-5, 2e-5, 5e-5, 1e-4, 2e-4, 5e-4, 1e-3, 2e-3, 5e-3, 1e-2, 2e-2, 5e-2, 0.1],
146
+ val_metric_type=MetricType.MEAN_ACCURACY,
147
+ test_metric_types=None,
148
+ classifier_fpath=None,
149
+ val_class_mapping_fpath=None,
150
+ test_class_mapping_fpaths=[None],
151
+ )
152
+ return parser
153
+
154
+
155
+ def has_ddp_wrapper(m: nn.Module) -> bool:
156
+ return isinstance(m, DistributedDataParallel)
157
+
158
+
159
+ def remove_ddp_wrapper(m: nn.Module) -> nn.Module:
160
+ return m.module if has_ddp_wrapper(m) else m
161
+
162
+
163
+ def _pad_and_collate(batch):
164
+ maxlen = max(len(targets) for image, targets in batch)
165
+ padded_batch = [
166
+ (image, np.pad(targets, (0, maxlen - len(targets)), constant_values=-1)) for image, targets in batch
167
+ ]
168
+ return torch.utils.data.default_collate(padded_batch)
169
+
170
+
171
+ def create_linear_input(x_tokens_list, use_n_blocks, use_avgpool):
172
+ intermediate_output = x_tokens_list[-use_n_blocks:]
173
+ output = torch.cat([class_token for _, class_token in intermediate_output], dim=-1)
174
+ if use_avgpool:
175
+ output = torch.cat(
176
+ (
177
+ output,
178
+ torch.mean(intermediate_output[-1][0], dim=1), # patch tokens
179
+ ),
180
+ dim=-1,
181
+ )
182
+ output = output.reshape(output.shape[0], -1)
183
+ return output.float()
184
+
185
+
186
+ class LinearClassifier(nn.Module):
187
+ """Linear layer to train on top of frozen features"""
188
+
189
+ def __init__(self, out_dim, use_n_blocks, use_avgpool, num_classes=1000):
190
+ super().__init__()
191
+ self.out_dim = out_dim
192
+ self.use_n_blocks = use_n_blocks
193
+ self.use_avgpool = use_avgpool
194
+ self.num_classes = num_classes
195
+ self.linear = nn.Linear(out_dim, num_classes)
196
+ self.linear.weight.data.normal_(mean=0.0, std=0.01)
197
+ self.linear.bias.data.zero_()
198
+
199
+ def forward(self, x_tokens_list):
200
+ output = create_linear_input(x_tokens_list, self.use_n_blocks, self.use_avgpool)
201
+ return self.linear(output)
202
+
203
+
204
+ class AllClassifiers(nn.Module):
205
+ def __init__(self, classifiers_dict):
206
+ super().__init__()
207
+ self.classifiers_dict = nn.ModuleDict()
208
+ self.classifiers_dict.update(classifiers_dict)
209
+
210
+ def forward(self, inputs):
211
+ return {k: v.forward(inputs) for k, v in self.classifiers_dict.items()}
212
+
213
+ def __len__(self):
214
+ return len(self.classifiers_dict)
215
+
216
+
217
+ class LinearPostprocessor(nn.Module):
218
+ def __init__(self, linear_classifier, class_mapping=None):
219
+ super().__init__()
220
+ self.linear_classifier = linear_classifier
221
+ self.register_buffer("class_mapping", None if class_mapping is None else torch.LongTensor(class_mapping))
222
+
223
+ def forward(self, samples, targets):
224
+ preds = self.linear_classifier(samples)
225
+ return {
226
+ "preds": preds[:, self.class_mapping] if self.class_mapping is not None else preds,
227
+ "target": targets,
228
+ }
229
+
230
+
231
+ def scale_lr(learning_rates, batch_size):
232
+ return learning_rates * (batch_size * distributed.get_global_size()) / 256.0
233
+
234
+
235
+ def setup_linear_classifiers(sample_output, n_last_blocks_list, learning_rates, batch_size, num_classes=1000):
236
+ linear_classifiers_dict = nn.ModuleDict()
237
+ optim_param_groups = []
238
+ for n in n_last_blocks_list:
239
+ for avgpool in [False, True]:
240
+ for _lr in learning_rates:
241
+ lr = scale_lr(_lr, batch_size)
242
+ out_dim = create_linear_input(sample_output, use_n_blocks=n, use_avgpool=avgpool).shape[1]
243
+ linear_classifier = LinearClassifier(
244
+ out_dim, use_n_blocks=n, use_avgpool=avgpool, num_classes=num_classes
245
+ )
246
+ linear_classifier = linear_classifier.cuda()
247
+ linear_classifiers_dict[
248
+ f"classifier_{n}_blocks_avgpool_{avgpool}_lr_{lr:.5f}".replace(".", "_")
249
+ ] = linear_classifier
250
+ optim_param_groups.append({"params": linear_classifier.parameters(), "lr": lr})
251
+
252
+ linear_classifiers = AllClassifiers(linear_classifiers_dict)
253
+ if distributed.is_enabled():
254
+ linear_classifiers = nn.parallel.DistributedDataParallel(linear_classifiers)
255
+
256
+ return linear_classifiers, optim_param_groups
257
+
258
+
259
+ @torch.no_grad()
260
+ def evaluate_linear_classifiers(
261
+ feature_model,
262
+ linear_classifiers,
263
+ data_loader,
264
+ metric_type,
265
+ metrics_file_path,
266
+ training_num_classes,
267
+ iteration,
268
+ prefixstring="",
269
+ class_mapping=None,
270
+ best_classifier_on_val=None,
271
+ ):
272
+ logger.info("running validation !")
273
+
274
+ num_classes = len(class_mapping) if class_mapping is not None else training_num_classes
275
+ metric = build_metric(metric_type, num_classes=num_classes)
276
+ postprocessors = {k: LinearPostprocessor(v, class_mapping) for k, v in linear_classifiers.classifiers_dict.items()}
277
+ metrics = {k: metric.clone() for k in linear_classifiers.classifiers_dict}
278
+
279
+ _, results_dict_temp = evaluate(
280
+ feature_model,
281
+ data_loader,
282
+ postprocessors,
283
+ metrics,
284
+ torch.cuda.current_device(),
285
+ )
286
+
287
+ logger.info("")
288
+ results_dict = {}
289
+ max_accuracy = 0
290
+ best_classifier = ""
291
+ for i, (classifier_string, metric) in enumerate(results_dict_temp.items()):
292
+ logger.info(f"{prefixstring} -- Classifier: {classifier_string} * {metric}")
293
+ if (
294
+ best_classifier_on_val is None and metric["top-1"].item() > max_accuracy
295
+ ) or classifier_string == best_classifier_on_val:
296
+ max_accuracy = metric["top-1"].item()
297
+ best_classifier = classifier_string
298
+
299
+ results_dict["best_classifier"] = {"name": best_classifier, "accuracy": max_accuracy}
300
+
301
+ logger.info(f"best classifier: {results_dict['best_classifier']}")
302
+
303
+ if distributed.is_main_process():
304
+ with open(metrics_file_path, "a") as f:
305
+ f.write(f"iter: {iteration}\n")
306
+ for k, v in results_dict.items():
307
+ f.write(json.dumps({k: v}) + "\n")
308
+ f.write("\n")
309
+
310
+ return results_dict
311
+
312
+
313
+ def eval_linear(
314
+ *,
315
+ feature_model,
316
+ linear_classifiers,
317
+ train_data_loader,
318
+ val_data_loader,
319
+ metrics_file_path,
320
+ optimizer,
321
+ scheduler,
322
+ output_dir,
323
+ max_iter,
324
+ checkpoint_period, # In number of iter, creates a new file every period
325
+ running_checkpoint_period, # Period to update main checkpoint file
326
+ eval_period,
327
+ metric_type,
328
+ training_num_classes,
329
+ resume=True,
330
+ classifier_fpath=None,
331
+ val_class_mapping=None,
332
+ ):
333
+ checkpointer = Checkpointer(linear_classifiers, output_dir, optimizer=optimizer, scheduler=scheduler)
334
+ start_iter = checkpointer.resume_or_load(classifier_fpath or "", resume=resume).get("iteration", -1) + 1
335
+
336
+ periodic_checkpointer = PeriodicCheckpointer(checkpointer, checkpoint_period, max_iter=max_iter)
337
+ iteration = start_iter
338
+ logger.info("Starting training from iteration {}".format(start_iter))
339
+ metric_logger = MetricLogger(delimiter=" ")
340
+ header = "Training"
341
+
342
+ for data, labels in metric_logger.log_every(
343
+ train_data_loader,
344
+ 10,
345
+ header,
346
+ max_iter,
347
+ start_iter,
348
+ ):
349
+ data = data.cuda(non_blocking=True)
350
+ labels = labels.cuda(non_blocking=True)
351
+
352
+ features = feature_model(data)
353
+ outputs = linear_classifiers(features)
354
+
355
+ losses = {f"loss_{k}": nn.CrossEntropyLoss()(v, labels) for k, v in outputs.items()}
356
+ loss = sum(losses.values())
357
+
358
+ # compute the gradients
359
+ optimizer.zero_grad()
360
+ loss.backward()
361
+
362
+ # step
363
+ optimizer.step()
364
+ scheduler.step()
365
+
366
+ # log
367
+ if iteration % 10 == 0:
368
+ torch.cuda.synchronize()
369
+ metric_logger.update(loss=loss.item())
370
+ metric_logger.update(lr=optimizer.param_groups[0]["lr"])
371
+ print("lr", optimizer.param_groups[0]["lr"])
372
+
373
+ if iteration - start_iter > 5:
374
+ if iteration % running_checkpoint_period == 0:
375
+ torch.cuda.synchronize()
376
+ if distributed.is_main_process():
377
+ logger.info("Checkpointing running_checkpoint")
378
+ periodic_checkpointer.save("running_checkpoint_linear_eval", iteration=iteration)
379
+ torch.cuda.synchronize()
380
+ periodic_checkpointer.step(iteration)
381
+
382
+ if eval_period > 0 and (iteration + 1) % eval_period == 0 and iteration != max_iter - 1:
383
+ _ = evaluate_linear_classifiers(
384
+ feature_model=feature_model,
385
+ linear_classifiers=remove_ddp_wrapper(linear_classifiers),
386
+ data_loader=val_data_loader,
387
+ metrics_file_path=metrics_file_path,
388
+ prefixstring=f"ITER: {iteration}",
389
+ metric_type=metric_type,
390
+ training_num_classes=training_num_classes,
391
+ iteration=iteration,
392
+ class_mapping=val_class_mapping,
393
+ )
394
+ torch.cuda.synchronize()
395
+
396
+ iteration = iteration + 1
397
+
398
+ val_results_dict = evaluate_linear_classifiers(
399
+ feature_model=feature_model,
400
+ linear_classifiers=remove_ddp_wrapper(linear_classifiers),
401
+ data_loader=val_data_loader,
402
+ metrics_file_path=metrics_file_path,
403
+ metric_type=metric_type,
404
+ training_num_classes=training_num_classes,
405
+ iteration=iteration,
406
+ class_mapping=val_class_mapping,
407
+ )
408
+ return val_results_dict, feature_model, linear_classifiers, iteration
409
+
410
+
411
+ def make_eval_data_loader(test_dataset_str, batch_size, num_workers, metric_type):
412
+ test_dataset = make_dataset(
413
+ dataset_str=test_dataset_str,
414
+ transform=make_classification_eval_transform(),
415
+ )
416
+ test_data_loader = make_data_loader(
417
+ dataset=test_dataset,
418
+ batch_size=batch_size,
419
+ num_workers=num_workers,
420
+ sampler_type=SamplerType.DISTRIBUTED,
421
+ drop_last=False,
422
+ shuffle=False,
423
+ persistent_workers=False,
424
+ collate_fn=_pad_and_collate if metric_type == MetricType.IMAGENET_REAL_ACCURACY else None,
425
+ )
426
+ return test_data_loader
427
+
428
+
429
+ def test_on_datasets(
430
+ feature_model,
431
+ linear_classifiers,
432
+ test_dataset_strs,
433
+ batch_size,
434
+ num_workers,
435
+ test_metric_types,
436
+ metrics_file_path,
437
+ training_num_classes,
438
+ iteration,
439
+ best_classifier_on_val,
440
+ prefixstring="",
441
+ test_class_mappings=[None],
442
+ ):
443
+ results_dict = {}
444
+ for test_dataset_str, class_mapping, metric_type in zip(test_dataset_strs, test_class_mappings, test_metric_types):
445
+ logger.info(f"Testing on {test_dataset_str}")
446
+ test_data_loader = make_eval_data_loader(test_dataset_str, batch_size, num_workers, metric_type)
447
+ dataset_results_dict = evaluate_linear_classifiers(
448
+ feature_model,
449
+ remove_ddp_wrapper(linear_classifiers),
450
+ test_data_loader,
451
+ metric_type,
452
+ metrics_file_path,
453
+ training_num_classes,
454
+ iteration,
455
+ prefixstring="",
456
+ class_mapping=class_mapping,
457
+ best_classifier_on_val=best_classifier_on_val,
458
+ )
459
+ results_dict[f"{test_dataset_str}_accuracy"] = 100.0 * dataset_results_dict["best_classifier"]["accuracy"]
460
+ return results_dict
461
+
462
+
463
+ def run_eval_linear(
464
+ model,
465
+ output_dir,
466
+ train_dataset_str,
467
+ val_dataset_str,
468
+ batch_size,
469
+ epochs,
470
+ epoch_length,
471
+ num_workers,
472
+ save_checkpoint_frequency,
473
+ eval_period_iterations,
474
+ learning_rates,
475
+ autocast_dtype,
476
+ test_dataset_strs=None,
477
+ resume=True,
478
+ classifier_fpath=None,
479
+ val_class_mapping_fpath=None,
480
+ test_class_mapping_fpaths=[None],
481
+ val_metric_type=MetricType.MEAN_ACCURACY,
482
+ test_metric_types=None,
483
+ ):
484
+ seed = 0
485
+
486
+ if test_dataset_strs is None:
487
+ test_dataset_strs = [val_dataset_str]
488
+ if test_metric_types is None:
489
+ test_metric_types = [val_metric_type] * len(test_dataset_strs)
490
+ else:
491
+ assert len(test_metric_types) == len(test_dataset_strs)
492
+ assert len(test_dataset_strs) == len(test_class_mapping_fpaths)
493
+
494
+ train_transform = make_classification_train_transform()
495
+ train_dataset = make_dataset(
496
+ dataset_str=train_dataset_str,
497
+ transform=train_transform,
498
+ )
499
+ training_num_classes = len(torch.unique(torch.Tensor(train_dataset.get_targets().astype(int))))
500
+ sampler_type = SamplerType.SHARDED_INFINITE
501
+ # sampler_type = SamplerType.INFINITE
502
+
503
+ n_last_blocks_list = [1, 4]
504
+ n_last_blocks = max(n_last_blocks_list)
505
+ autocast_ctx = partial(torch.cuda.amp.autocast, enabled=True, dtype=autocast_dtype)
506
+ feature_model = ModelWithIntermediateLayers(model, n_last_blocks, autocast_ctx)
507
+ sample_output = feature_model(train_dataset[0][0].unsqueeze(0).cuda())
508
+
509
+ linear_classifiers, optim_param_groups = setup_linear_classifiers(
510
+ sample_output,
511
+ n_last_blocks_list,
512
+ learning_rates,
513
+ batch_size,
514
+ training_num_classes,
515
+ )
516
+
517
+ optimizer = torch.optim.SGD(optim_param_groups, momentum=0.9, weight_decay=0)
518
+ max_iter = epochs * epoch_length
519
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, max_iter, eta_min=0)
520
+ checkpointer = Checkpointer(linear_classifiers, output_dir, optimizer=optimizer, scheduler=scheduler)
521
+ start_iter = checkpointer.resume_or_load(classifier_fpath or "", resume=resume).get("iteration", -1) + 1
522
+ train_data_loader = make_data_loader(
523
+ dataset=train_dataset,
524
+ batch_size=batch_size,
525
+ num_workers=num_workers,
526
+ shuffle=True,
527
+ seed=seed,
528
+ sampler_type=sampler_type,
529
+ sampler_advance=start_iter,
530
+ drop_last=True,
531
+ persistent_workers=True,
532
+ )
533
+ val_data_loader = make_eval_data_loader(val_dataset_str, batch_size, num_workers, val_metric_type)
534
+
535
+ checkpoint_period = save_checkpoint_frequency * epoch_length
536
+
537
+ if val_class_mapping_fpath is not None:
538
+ logger.info(f"Using class mapping from {val_class_mapping_fpath}")
539
+ val_class_mapping = np.load(val_class_mapping_fpath)
540
+ else:
541
+ val_class_mapping = None
542
+
543
+ test_class_mappings = []
544
+ for class_mapping_fpath in test_class_mapping_fpaths:
545
+ if class_mapping_fpath is not None and class_mapping_fpath != "None":
546
+ logger.info(f"Using class mapping from {class_mapping_fpath}")
547
+ class_mapping = np.load(class_mapping_fpath)
548
+ else:
549
+ class_mapping = None
550
+ test_class_mappings.append(class_mapping)
551
+
552
+ metrics_file_path = os.path.join(output_dir, "results_eval_linear.json")
553
+ val_results_dict, feature_model, linear_classifiers, iteration = eval_linear(
554
+ feature_model=feature_model,
555
+ linear_classifiers=linear_classifiers,
556
+ train_data_loader=train_data_loader,
557
+ val_data_loader=val_data_loader,
558
+ metrics_file_path=metrics_file_path,
559
+ optimizer=optimizer,
560
+ scheduler=scheduler,
561
+ output_dir=output_dir,
562
+ max_iter=max_iter,
563
+ checkpoint_period=checkpoint_period,
564
+ running_checkpoint_period=epoch_length,
565
+ eval_period=eval_period_iterations,
566
+ metric_type=val_metric_type,
567
+ training_num_classes=training_num_classes,
568
+ resume=resume,
569
+ val_class_mapping=val_class_mapping,
570
+ classifier_fpath=classifier_fpath,
571
+ )
572
+ results_dict = {}
573
+ if len(test_dataset_strs) > 1 or test_dataset_strs[0] != val_dataset_str:
574
+ results_dict = test_on_datasets(
575
+ feature_model,
576
+ linear_classifiers,
577
+ test_dataset_strs,
578
+ batch_size,
579
+ 0, # num_workers,
580
+ test_metric_types,
581
+ metrics_file_path,
582
+ training_num_classes,
583
+ iteration,
584
+ val_results_dict["best_classifier"]["name"],
585
+ prefixstring="",
586
+ test_class_mappings=test_class_mappings,
587
+ )
588
+ results_dict["best_classifier"] = val_results_dict["best_classifier"]["name"]
589
+ results_dict[f"{val_dataset_str}_accuracy"] = 100.0 * val_results_dict["best_classifier"]["accuracy"]
590
+ logger.info("Test Results Dict " + str(results_dict))
591
+
592
+ return results_dict
593
+
594
+
595
+ def main(args):
596
+ model, autocast_dtype = setup_and_build_model(args)
597
+ run_eval_linear(
598
+ model=model,
599
+ output_dir=args.output_dir,
600
+ train_dataset_str=args.train_dataset_str,
601
+ val_dataset_str=args.val_dataset_str,
602
+ test_dataset_strs=args.test_dataset_strs,
603
+ batch_size=args.batch_size,
604
+ epochs=args.epochs,
605
+ epoch_length=args.epoch_length,
606
+ num_workers=args.num_workers,
607
+ save_checkpoint_frequency=args.save_checkpoint_frequency,
608
+ eval_period_iterations=args.eval_period_iterations,
609
+ learning_rates=args.learning_rates,
610
+ autocast_dtype=autocast_dtype,
611
+ resume=not args.no_resume,
612
+ classifier_fpath=args.classifier_fpath,
613
+ val_metric_type=args.val_metric_type,
614
+ test_metric_types=args.test_metric_types,
615
+ val_class_mapping_fpath=args.val_class_mapping_fpath,
616
+ test_class_mapping_fpaths=args.test_class_mapping_fpaths,
617
+ )
618
+ return 0
619
+
620
+
621
+ if __name__ == "__main__":
622
+ description = "DINOv2 linear evaluation"
623
+ args_parser = get_args_parser(description=description)
624
+ args = args_parser.parse_args()
625
+ sys.exit(main(args))