dinov2
Addax-Data-Science commited on
Commit
11758d4
·
verified ·
1 Parent(s): e6449c1

Upload 3 files

Browse files
Files changed (3) hide show
  1. config.json +24 -0
  2. inference.py +208 -0
  3. taxonomy.csv +35 -0
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Dinov2Model"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.0,
6
+ "drop_path_rate": 0.0,
7
+ "hidden_act": "gelu",
8
+ "hidden_dropout_prob": 0.0,
9
+ "hidden_size": 1024,
10
+ "image_size": 518,
11
+ "initializer_range": 0.02,
12
+ "layer_norm_eps": 1e-06,
13
+ "layerscale_value": 1.0,
14
+ "mlp_ratio": 4,
15
+ "model_type": "dinov2",
16
+ "num_attention_heads": 16,
17
+ "num_channels": 3,
18
+ "num_hidden_layers": 24,
19
+ "patch_size": 14,
20
+ "qkv_bias": true,
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.31.0.dev0",
23
+ "use_swiglu_ffn": false
24
+ }
inference.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script for AFR-DFV-v1 (African tropical forests, DeepForestVision)
3
+
4
+ Model: DeepForestVision v1
5
+ Input: 224x224 RGB, ImageNet-normalised
6
+ Framework: PyTorch (HuggingFace transformers, DINOv2-large)
7
+ Classes: 34 African tropical forest species
8
+ Developer: MNHN-OFVI
9
+
10
+ Ported from AddaxAI's legacy classify_detections.py (dfv-v1), with one
11
+ deliberate change: the architecture is built from a local config.json
12
+ rather than fetched from the Hub. See below.
13
+
14
+ Files expected in the model directory:
15
+ - DFV.pt the fine-tuned weights
16
+ - config.json facebook/dinov2-large's config, copied verbatim
17
+
18
+ Author: Peter van Lunteren
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from collections import OrderedDict
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn as nn
29
+ from PIL import Image, ImageFile
30
+ from torch import tensor
31
+ from torchvision.transforms import InterpolationMode, transforms
32
+ from transformers import AutoConfig, AutoModelForImageClassification
33
+
34
+ # Don't freak out over truncated images
35
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
36
+
37
+ CROP_SIZE = 224
38
+ BACKBONE = "dinov2_large"
39
+
40
+ # Class order is the model's output order and must not be reordered.
41
+ CLASS_NAMES = [
42
+ 'aardvark', 'baboon', 'honey badger', 'bird',
43
+ 'black-and-white colobus', 'blue duiker', 'blue monkey',
44
+ 'african buffalo', 'bushbuck', 'bushpig', 'chimpanzee', 'civet_genet',
45
+ 'elephant', 'galago_potto', 'african golden cat', 'gorilla',
46
+ 'guineafowl', 'hyrax', 'side-striped jackal', 'leopard',
47
+ "l'hoest's monkey", 'mandrill', 'mongoose', 'monkey', 'pangolin',
48
+ 'porcupine', 'red colobus_red-capped mangabey', 'red duiker', 'rodent',
49
+ 'serval', 'spotted hyena', 'squirrel', 'water chevrotain',
50
+ 'yellow-backed duiker'
51
+ ]
52
+
53
+
54
+ class _Model(nn.Module):
55
+ """
56
+ DINOv2-large with a 34-way head.
57
+
58
+ The legacy adapter builds this with
59
+ `AutoModelForImageClassification.from_pretrained('facebook/dinov2-large')`,
60
+ which downloads 1.2GB of pretrained weights from the Hub and then
61
+ throws every one of them away: `load_weights` below does a strict
62
+ `load_state_dict`, and DFV.pt carries all 441 keys the model has, so
63
+ nothing of the download survives.
64
+
65
+ Building from a local config instead is therefore identical in
66
+ result, needs no network at inference time, and does not make an
67
+ offline machine fail. Verified: from_config + DFV.pt loads strict with
68
+ missing=0, unexpected=0.
69
+ """
70
+
71
+ def __init__(self, model_dir: Path) -> None:
72
+ super().__init__()
73
+ config = AutoConfig.from_pretrained(str(model_dir))
74
+ self.base_model = AutoModelForImageClassification.from_config(config)
75
+ self.base_model.classifier = nn.Linear(
76
+ self.base_model.classifier.in_features, len(CLASS_NAMES)
77
+ )
78
+ self.backbone = BACKBONE
79
+ self.nbclasses = len(CLASS_NAMES)
80
+
81
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
82
+ return self.base_model(x)
83
+
84
+ def load_weights(self, path: Path, map_location) -> None:
85
+ weights = torch.load(path, map_location=map_location)
86
+ # The checkpoint was saved from a module that held the backbone
87
+ # directly, so its keys need the base_model prefix.
88
+ renamed = OrderedDict(
89
+ (
90
+ key.replace("dinov2", "base_model.dinov2").replace(
91
+ "classifier", "base_model.classifier"
92
+ ),
93
+ value,
94
+ )
95
+ for key, value in weights.items()
96
+ )
97
+ self.load_state_dict(renamed)
98
+
99
+
100
+ class ModelInference:
101
+ """DeepForestVision African tropical forest classifier."""
102
+
103
+ def __init__(self, model_dir: Path, model_path: Path) -> None:
104
+ self.model_dir = Path(model_dir)
105
+ self.model_path = Path(model_path)
106
+ self.model: _Model | None = None
107
+ self.device: torch.device | None = None
108
+ self.preprocess = transforms.Compose([
109
+ transforms.Resize(
110
+ size=(CROP_SIZE, CROP_SIZE),
111
+ interpolation=InterpolationMode.BICUBIC,
112
+ max_size=None,
113
+ antialias=None,
114
+ ),
115
+ transforms.ToTensor(),
116
+ transforms.Normalize(
117
+ mean=tensor([0.4850, 0.4560, 0.4060]),
118
+ std=tensor([0.2290, 0.2240, 0.2250]),
119
+ ),
120
+ ])
121
+
122
+ # ------------------------------------------------------------------
123
+ # Required interface
124
+ # ------------------------------------------------------------------
125
+
126
+ def check_gpu(self) -> bool:
127
+ if torch.cuda.is_available():
128
+ return True
129
+ try:
130
+ return bool(torch.backends.mps.is_built() and torch.backends.mps.is_available())
131
+ except AttributeError:
132
+ return False
133
+
134
+ def load_model(self) -> None:
135
+ # Matches the legacy adapter's device order: CUDA first, then MPS.
136
+ if torch.cuda.is_available():
137
+ self.device = torch.device("cuda")
138
+ else:
139
+ try:
140
+ mps = torch.backends.mps.is_built() and torch.backends.mps.is_available()
141
+ except AttributeError:
142
+ mps = False
143
+ self.device = torch.device("mps" if mps else "cpu")
144
+
145
+ model = _Model(self.model_dir)
146
+ model.load_weights(self.model_path, self.device)
147
+ self.model = model.to(self.device).eval()
148
+
149
+ def get_crop(
150
+ self, image: Image.Image, bbox: tuple[float, float, float, float]
151
+ ) -> Image.Image:
152
+ """
153
+ Square the box by growing its shorter side, then clamp to the
154
+ image. Note this squares by *expanding*, and does not pad: a box
155
+ against an edge comes out non-square, and the Resize below
156
+ stretches it.
157
+ """
158
+ width, height = image.size
159
+ xmin = int(round(bbox[0] * width))
160
+ ymin = int(round(bbox[1] * height))
161
+ xmax = int(round(bbox[2] * width)) + xmin
162
+ ymax = int(round(bbox[3] * height)) + ymin
163
+ xsize = xmax - xmin
164
+ ysize = ymax - ymin
165
+ if xsize > ysize:
166
+ ymin -= int((xsize - ysize) / 2)
167
+ ymax += int((xsize - ysize) / 2)
168
+ if ysize > xsize:
169
+ xmin -= int((ysize - xsize) / 2)
170
+ xmax += int((ysize - xsize) / 2)
171
+ return image.crop(
172
+ (max(0, xmin), max(0, ymin), min(xmax, image.width), min(ymax, image.height))
173
+ )
174
+
175
+ def get_classification(self, crop: Image.Image) -> list[list]:
176
+ """Per-crop inference. Returns [[name, prob], ...] for all classes."""
177
+ probs = self._forward(np.stack([self.get_tensor(crop)]))[0]
178
+ return [[CLASS_NAMES[i], float(probs[i])] for i in range(len(probs))]
179
+
180
+ def get_class_names(self) -> dict[str, str]:
181
+ """1-indexed mapping {id: class_name} for the output JSON."""
182
+ return {str(i + 1): name for i, name in enumerate(CLASS_NAMES)}
183
+
184
+ # ------------------------------------------------------------------
185
+ # Optional batch interface
186
+ # ------------------------------------------------------------------
187
+
188
+ def get_tensor(self, crop: Image.Image) -> np.ndarray:
189
+ if crop.mode != "RGB":
190
+ crop = crop.convert("RGB")
191
+ return self.preprocess(crop).numpy()
192
+
193
+ def classify_batch(self, batch: np.ndarray) -> list[list[list]]:
194
+ probs = self._forward(batch)
195
+ return [
196
+ [[CLASS_NAMES[j], float(p[j])] for j in range(len(p))]
197
+ for p in probs
198
+ ]
199
+
200
+ # ------------------------------------------------------------------
201
+ # Internals
202
+ # ------------------------------------------------------------------
203
+
204
+ def _forward(self, batch: np.ndarray) -> np.ndarray:
205
+ assert self.model is not None
206
+ tensor_in = torch.from_numpy(batch).to(self.device)
207
+ with torch.no_grad():
208
+ return self.model(tensor_in).logits.softmax(dim=1).cpu().numpy()
taxonomy.csv ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model_class,class,order,family,genus,species
2
+ aardvark,mammalia,tubulidentata,orycteropodidae,orycteropus,afer
3
+ african buffalo,mammalia,artiodactyla,bovidae,syncerus,caffer
4
+ african golden cat,mammalia,carnivora,felidae,profelis,aurata
5
+ baboon,mammalia,primates,cercopithecidae,papio,
6
+ bird,aves,,,,
7
+ black-and-white colobus,mammalia,primates,cercopithecidae,colobus,guereza
8
+ blue duiker,mammalia,artiodactyla,bovidae,philantomba,monticola
9
+ blue monkey,mammalia,primates,cercopithecidae,cercopithecus,mitis
10
+ bushbuck,mammalia,artiodactyla,bovidae,tragelaphus,scriptus
11
+ bushpig,mammalia,artiodactyla,suidae,,
12
+ chimpanzee,mammalia,primates,hominidae,pan,troglodytes
13
+ civet_genet,mammalia,carnivora,,,
14
+ elephant,mammalia,proboscidea,elephantidae,loxodonta,
15
+ galago_potto,mammalia,primates,,,
16
+ gorilla,mammalia,primates,hominidae,gorilla,
17
+ guineafowl,aves,galliformes,numididae,,
18
+ honey badger,mammalia,carnivora,mustelidae,mellivora,capensis
19
+ hyrax,mammalia,hyracoidea,procaviidae,,
20
+ side-striped jackal,mammalia,carnivora,canidae,canis,adustus
21
+ leopard,mammalia,carnivora,felidae,panthera,pardus
22
+ l'hoest's monkey,mammalia,primates,cercopithecidae,allochrocebus,lhoesti
23
+ mandrill,mammalia,primates,cercopithecidae,mandrillus,sphinx
24
+ mongoose,mammalia,carnivora,herpestidae,,
25
+ monkey,mammalia,primates,cercopithecidae,,
26
+ pangolin,mammalia,pholidota,manidae,,
27
+ porcupine,mammalia,rodentia,hystricidae,,
28
+ red colobus_red-capped mangabey,mammalia,primates,cercopithecidae,,
29
+ red duiker,mammalia,artiodactyla,bovidae,cephalophus,
30
+ rodent,mammalia,rodentia,,,
31
+ serval,mammalia,carnivora,felidae,leptailurus,serval
32
+ spotted hyena,mammalia,carnivora,hyaenidae,crocuta,crocuta
33
+ squirrel,mammalia,rodentia,sciuridae,,
34
+ water chevrotain,mammalia,artiodactyla,tragulidae,hyemoschus,aquaticus
35
+ yellow-backed duiker,mammalia,artiodactyla,bovidae,cephalophus,silvicultor