taejoon89 commited on
Commit
d9b361e
·
verified ·
1 Parent(s): 1c7dc36

Upload folder using huggingface_hub

Browse files
OpenPath/dinov2/data/datasets/test_data.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ from typing import Any, Tuple
7
+
8
+ from torchvision.datasets import VisionDataset
9
+
10
+ from .extended import ExtendedVisionDataset
11
+ from .decoders import TargetDecoder, ImageDataDecoder
12
+
13
+ from pathlib import Path
14
+ from typing import Callable, List, Optional, Tuple, Union
15
+
16
+ from PIL import Image
17
+
18
+ class TestVisionDataset(ExtendedVisionDataset):
19
+ def __init__(self, root, *args, **kwargs) -> None:
20
+ super().__init__(*args, **kwargs) # type: ignore
21
+
22
+ folder_path = Path(root)
23
+
24
+ # Image extensions to look for
25
+ image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
26
+
27
+ # Recursively find all image files
28
+ self.image_files = [p for p in folder_path.rglob("*") if p.suffix.lower() in image_extensions]
29
+ print("Found this many files", len(self.image_files))
30
+
31
+
32
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
33
+ try:
34
+ path = self.image_files[index]
35
+ image = Image.open(path).convert("RGB")
36
+ except Exception as e:
37
+ raise RuntimeError(f"can not read image for sample {index}") from e
38
+
39
+ #The transform used is a torchvision StandardTransform.
40
+ #This means that it takes as input two things, and runs two different transforms on both.
41
+ if self.transforms is not None:
42
+ print(image.size, path)#Debug only
43
+ return self.transforms(image, None)
44
+
45
+ #this just returns a class index, which we do not need.
46
+ # target = self.get_target(index)
47
+ # target = TargetDecoder(target).decode()
48
+
49
+ #if self.transforms is not None:
50
+ # image, target = self.transforms(image, target)
51
+
52
+ return image, None
53
+
54
+ def __len__(self) -> int:
55
+ return len(self.image_files)
OpenPath/dinov2/hub/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
OpenPath/dinov2/hub/backbones.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ from enum import Enum
7
+ from pathlib import Path
8
+ from typing import Optional, Union
9
+ from urllib.parse import urlparse
10
+
11
+ import torch
12
+
13
+ from .utils import _DINOV2_BASE_URL, _make_dinov2_model_name
14
+
15
+
16
+ class Weights(Enum):
17
+ LVD142M = "LVD142M"
18
+ XRAY_DINO = "XRay-DINO"
19
+
20
+
21
+ def is_url(path: str) -> bool:
22
+ parsed = urlparse(path)
23
+ return parsed.scheme in ("https", "file")
24
+
25
+
26
+ def convert_path_or_url_to_url(path: str) -> str:
27
+ if is_url(path):
28
+ return path
29
+ return Path(path).expanduser().resolve().as_uri()
30
+
31
+
32
+ def _make_dinov2_model(
33
+ *,
34
+ arch_name: str = "vit_large",
35
+ img_size: int = 518,
36
+ patch_size: int = 14,
37
+ init_values: float = 1.0,
38
+ ffn_layer: str = "mlp",
39
+ block_chunks: int = 0,
40
+ num_register_tokens: int = 0,
41
+ interpolate_antialias: bool = False,
42
+ interpolate_offset: float = 0.1,
43
+ pretrained: bool = True,
44
+ weights: Union[Weights, str] = Weights.LVD142M,
45
+ hash: Optional[str] = None,
46
+ check_hash: bool = False,
47
+ **kwargs,
48
+ ):
49
+ from ..models import vision_transformer as vits
50
+
51
+ model_base_name = _make_dinov2_model_name(arch_name, patch_size)
52
+ vit_kwargs = dict(
53
+ img_size=img_size,
54
+ patch_size=patch_size,
55
+ init_values=init_values,
56
+ ffn_layer=ffn_layer,
57
+ block_chunks=block_chunks,
58
+ num_register_tokens=num_register_tokens,
59
+ interpolate_antialias=interpolate_antialias,
60
+ interpolate_offset=interpolate_offset,
61
+ )
62
+ vit_kwargs.update(**kwargs)
63
+ model = vits.__dict__[arch_name](**vit_kwargs)
64
+
65
+ if pretrained:
66
+ if type(weights) is Weights and weights not in {
67
+ Weights.LVD142M,
68
+ Weights.XRAY_DINO,
69
+ }:
70
+ raise ValueError(f"Unsupported weights for the backbone: {weights}")
71
+ elif type(weights) is Weights:
72
+ model_full_name = _make_dinov2_model_name(arch_name, patch_size, num_register_tokens)
73
+ url = _DINOV2_BASE_URL + f"/{model_base_name}/{model_full_name}_pretrain.pth"
74
+ else:
75
+ url = convert_path_or_url_to_url(weights)
76
+ state_dict = torch.hub.load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
77
+ model.load_state_dict(state_dict, strict=True)
78
+
79
+ return model
80
+
81
+
82
+ def dinov2_vits14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
83
+ """
84
+ DINOv2 ViT-S/14 model (optionally) pretrained on the LVD-142M dataset.
85
+ """
86
+ return _make_dinov2_model(arch_name="vit_small", pretrained=pretrained, weights=weights, **kwargs)
87
+
88
+
89
+ def dinov2_vitb14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
90
+ """
91
+ DINOv2 ViT-B/14 model (optionally) pretrained on the LVD-142M dataset.
92
+ """
93
+ return _make_dinov2_model(arch_name="vit_base", pretrained=pretrained, weights=weights, **kwargs)
94
+
95
+
96
+ def dinov2_vitl14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
97
+ """
98
+ DINOv2 ViT-L/14 model (optionally) pretrained on the LVD-142M dataset.
99
+ """
100
+ return _make_dinov2_model(arch_name="vit_large", pretrained=pretrained, weights=weights, **kwargs)
101
+
102
+
103
+ def dinov2_vitg14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
104
+ """
105
+ DINOv2 ViT-g/14 model (optionally) pretrained on the LVD-142M dataset.
106
+ """
107
+ return _make_dinov2_model(
108
+ arch_name="vit_giant2",
109
+ ffn_layer="swiglufused",
110
+ weights=weights,
111
+ pretrained=pretrained,
112
+ **kwargs,
113
+ )
114
+
115
+
116
+ def dinov2_vits14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
117
+ """
118
+ DINOv2 ViT-S/14 model with registers (optionally) pretrained on the LVD-142M dataset.
119
+ """
120
+ return _make_dinov2_model(
121
+ arch_name="vit_small",
122
+ pretrained=pretrained,
123
+ weights=weights,
124
+ num_register_tokens=4,
125
+ interpolate_antialias=True,
126
+ interpolate_offset=0.0,
127
+ **kwargs,
128
+ )
129
+
130
+
131
+ def dinov2_vitb14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
132
+ """
133
+ DINOv2 ViT-B/14 model with registers (optionally) pretrained on the LVD-142M dataset.
134
+ """
135
+ return _make_dinov2_model(
136
+ arch_name="vit_base",
137
+ pretrained=pretrained,
138
+ weights=weights,
139
+ num_register_tokens=4,
140
+ interpolate_antialias=True,
141
+ interpolate_offset=0.0,
142
+ **kwargs,
143
+ )
144
+
145
+
146
+ def dinov2_vitl14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
147
+ """
148
+ DINOv2 ViT-L/14 model with registers (optionally) pretrained on the LVD-142M dataset.
149
+ """
150
+ return _make_dinov2_model(
151
+ arch_name="vit_large",
152
+ pretrained=pretrained,
153
+ weights=weights,
154
+ num_register_tokens=4,
155
+ interpolate_antialias=True,
156
+ interpolate_offset=0.0,
157
+ **kwargs,
158
+ )
159
+
160
+
161
+ def dinov2_vitg14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
162
+ """
163
+ DINOv2 ViT-g/14 model with registers (optionally) pretrained on the LVD-142M dataset.
164
+ """
165
+ return _make_dinov2_model(
166
+ arch_name="vit_giant2",
167
+ ffn_layer="swiglufused",
168
+ weights=weights,
169
+ pretrained=pretrained,
170
+ num_register_tokens=4,
171
+ interpolate_antialias=True,
172
+ interpolate_offset=0.0,
173
+ **kwargs,
174
+ )
OpenPath/dinov2/hub/utils.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ import itertools
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ _DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2"
15
+
16
+
17
+ def _make_dinov2_model_name(arch_name: str, patch_size: int, num_register_tokens: int = 0) -> str:
18
+ compact_arch_name = arch_name.replace("_", "")[:4]
19
+ registers_suffix = f"_reg{num_register_tokens}" if num_register_tokens else ""
20
+ return f"dinov2_{compact_arch_name}{patch_size}{registers_suffix}"
21
+
22
+
23
+ class CenterPadding(nn.Module):
24
+ def __init__(self, multiple):
25
+ super().__init__()
26
+ self.multiple = multiple
27
+
28
+ def _get_pad(self, size):
29
+ new_size = math.ceil(size / self.multiple) * self.multiple
30
+ pad_size = new_size - size
31
+ pad_size_left = pad_size // 2
32
+ pad_size_right = pad_size - pad_size_left
33
+ return pad_size_left, pad_size_right
34
+
35
+ @torch.inference_mode()
36
+ def forward(self, x):
37
+ pads = list(itertools.chain.from_iterable(self._get_pad(m) for m in x.shape[:1:-1]))
38
+ output = F.pad(x, pads)
39
+ return output
OpenPath/dinov2/train/train.py CHANGED
@@ -249,8 +249,9 @@ def _load_pretrained_backbone(cfg, model):
249
  raise AssertionError("Unsupported FFN block type")
250
 
251
  hub_name = _resolve_torchhub_name(cfg)
252
- logger.info("Loading pretrained backbone from torch.hub: %s", hub_name)
253
- model_pretrained = torch.hub.load("facebookresearch/dinov2", hub_name)
 
254
  device = next(model.parameters()).device
255
  model_pretrained = model_pretrained.to(device)
256
  student_backbone = model.student.backbone
 
249
  raise AssertionError("Unsupported FFN block type")
250
 
251
  hub_name = _resolve_torchhub_name(cfg)
252
+ logger.info("Building pretrained DINOv2 backbone (%s) via dinov2.hub.backbones", hub_name)
253
+ from dinov2.hub import backbones as _dinov2_hub_backbones
254
+ model_pretrained = getattr(_dinov2_hub_backbones, hub_name)(pretrained=True)
255
  device = next(model.parameters()).device
256
  model_pretrained = model_pretrained.to(device)
257
  student_backbone = model.student.backbone