Upload 3 files
Browse filesFiles changed (3)
- config.jsonAdded+24
- inference.pyAdded+208
- taxonomy.csvAdded+35
123456789101112131415161718192021222324{ "architectures": [ "Dinov2Model" ], "attention_probs_dropout_prob": 0.0, "drop_path_rate": 0.0, "hidden_act": "gelu", "hidden_dropout_prob": 0.0, "hidden_size": 1024, "image_size": 518, "initializer_range": 0.02, "layer_norm_eps": 1e-06, "layerscale_value": 1.0, "mlp_ratio": 4, "model_type": "dinov2", "num_attention_heads": 16, "num_channels": 3, "num_hidden_layers": 24, "patch_size": 14, "qkv_bias": true, "torch_dtype": "float32", "transformers_version": "4.31.0.dev0", "use_swiglu_ffn": false}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208"""Inference script for AFR-DFV-v1 (African tropical forests, DeepForestVision)
Model: DeepForestVision v1Input: 224x224 RGB, ImageNet-normalisedFramework: PyTorch (HuggingFace transformers, DINOv2-large)Classes: 34 African tropical forest speciesDeveloper: MNHN-OFVI
Ported from AddaxAI's legacy classify_detections.py (dfv-v1), with onedeliberate change: the architecture is built from a local config.jsonrather than fetched from the Hub. See below.
Files expected in the model directory: - DFV.pt the fine-tuned weights - config.json facebook/dinov2-large's config, copied verbatim
Author: Peter van Lunteren"""
from __future__ import annotations
from collections import OrderedDictfrom pathlib import Path
import numpy as npimport torchimport torch.nn as nnfrom PIL import Image, ImageFilefrom torch import tensorfrom torchvision.transforms import InterpolationMode, transformsfrom transformers import AutoConfig, AutoModelForImageClassification
# Don't freak out over truncated imagesImageFile.LOAD_TRUNCATED_IMAGES = True
CROP_SIZE = 224BACKBONE = "dinov2_large"
# Class order is the model's output order and must not be reordered.CLASS_NAMES = [ 'aardvark', 'baboon', 'honey badger', 'bird', 'black-and-white colobus', 'blue duiker', 'blue monkey', 'african buffalo', 'bushbuck', 'bushpig', 'chimpanzee', 'civet_genet', 'elephant', 'galago_potto', 'african golden cat', 'gorilla', 'guineafowl', 'hyrax', 'side-striped jackal', 'leopard', "l'hoest's monkey", 'mandrill', 'mongoose', 'monkey', 'pangolin', 'porcupine', 'red colobus_red-capped mangabey', 'red duiker', 'rodent', 'serval', 'spotted hyena', 'squirrel', 'water chevrotain', 'yellow-backed duiker']
class _Model(nn.Module): """ DINOv2-large with a 34-way head.
The legacy adapter builds this with `AutoModelForImageClassification.from_pretrained('facebook/dinov2-large')`, which downloads 1.2GB of pretrained weights from the Hub and then throws every one of them away: `load_weights` below does a strict `load_state_dict`, and DFV.pt carries all 441 keys the model has, so nothing of the download survives.
Building from a local config instead is therefore identical in result, needs no network at inference time, and does not make an offline machine fail. Verified: from_config + DFV.pt loads strict with missing=0, unexpected=0. """
def __init__(self, model_dir: Path) -> None: super().__init__() config = AutoConfig.from_pretrained(str(model_dir)) self.base_model = AutoModelForImageClassification.from_config(config) self.base_model.classifier = nn.Linear( self.base_model.classifier.in_features, len(CLASS_NAMES) ) self.backbone = BACKBONE self.nbclasses = len(CLASS_NAMES)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.base_model(x)
def load_weights(self, path: Path, map_location) -> None: weights = torch.load(path, map_location=map_location) # The checkpoint was saved from a module that held the backbone # directly, so its keys need the base_model prefix. renamed = OrderedDict( ( key.replace("dinov2", "base_model.dinov2").replace( "classifier", "base_model.classifier" ), value, ) for key, value in weights.items() ) self.load_state_dict(renamed)
class ModelInference: """DeepForestVision African tropical forest classifier."""
def __init__(self, model_dir: Path, model_path: Path) -> None: self.model_dir = Path(model_dir) self.model_path = Path(model_path) self.model: _Model | None = None self.device: torch.device | None = None self.preprocess = transforms.Compose([ transforms.Resize( size=(CROP_SIZE, CROP_SIZE), interpolation=InterpolationMode.BICUBIC, max_size=None, antialias=None, ), transforms.ToTensor(), transforms.Normalize( mean=tensor([0.4850, 0.4560, 0.4060]), std=tensor([0.2290, 0.2240, 0.2250]), ), ])
# ------------------------------------------------------------------ # Required interface # ------------------------------------------------------------------
def check_gpu(self) -> bool: if torch.cuda.is_available(): return True try: return bool(torch.backends.mps.is_built() and torch.backends.mps.is_available()) except AttributeError: return False
def load_model(self) -> None: # Matches the legacy adapter's device order: CUDA first, then MPS. if torch.cuda.is_available(): self.device = torch.device("cuda") else: try: mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except AttributeError: mps = False self.device = torch.device("mps" if mps else "cpu")
model = _Model(self.model_dir) model.load_weights(self.model_path, self.device) self.model = model.to(self.device).eval()
def get_crop( self, image: Image.Image, bbox: tuple[float, float, float, float] ) -> Image.Image: """ Square the box by growing its shorter side, then clamp to the image. Note this squares by *expanding*, and does not pad: a box against an edge comes out non-square, and the Resize below stretches it. """ width, height = image.size xmin = int(round(bbox[0] * width)) ymin = int(round(bbox[1] * height)) xmax = int(round(bbox[2] * width)) + xmin ymax = int(round(bbox[3] * height)) + ymin xsize = xmax - xmin ysize = ymax - ymin if xsize > ysize: ymin -= int((xsize - ysize) / 2) ymax += int((xsize - ysize) / 2) if ysize > xsize: xmin -= int((ysize - xsize) / 2) xmax += int((ysize - xsize) / 2) return image.crop( (max(0, xmin), max(0, ymin), min(xmax, image.width), min(ymax, image.height)) )
def get_classification(self, crop: Image.Image) -> list[list]: """Per-crop inference. Returns [[name, prob], ...] for all classes.""" probs = self._forward(np.stack([self.get_tensor(crop)]))[0] return [[CLASS_NAMES[i], float(probs[i])] for i in range(len(probs))]
def get_class_names(self) -> dict[str, str]: """1-indexed mapping {id: class_name} for the output JSON.""" return {str(i + 1): name for i, name in enumerate(CLASS_NAMES)}
# ------------------------------------------------------------------ # Optional batch interface # ------------------------------------------------------------------
def get_tensor(self, crop: Image.Image) -> np.ndarray: if crop.mode != "RGB": crop = crop.convert("RGB") return self.preprocess(crop).numpy()
def classify_batch(self, batch: np.ndarray) -> list[list[list]]: probs = self._forward(batch) return [ [[CLASS_NAMES[j], float(p[j])] for j in range(len(p))] for p in probs ]
# ------------------------------------------------------------------ # Internals # ------------------------------------------------------------------
def _forward(self, batch: np.ndarray) -> np.ndarray: assert self.model is not None tensor_in = torch.from_numpy(batch).to(self.device) with torch.no_grad(): return self.model(tensor_in).logits.softmax(dim=1).cpu().numpy()1234567891011121314151617181920212223242526272829303132333435model_class,class,order,family,genus,species
aardvark,mammalia,tubulidentata,orycteropodidae,orycteropus,afer
african buffalo,mammalia,artiodactyla,bovidae,syncerus,caffer
african golden cat,mammalia,carnivora,felidae,profelis,aurata
baboon,mammalia,primates,cercopithecidae,papio,
bird,aves,,,,
black-and-white colobus,mammalia,primates,cercopithecidae,colobus,guereza
blue duiker,mammalia,artiodactyla,bovidae,philantomba,monticola
blue monkey,mammalia,primates,cercopithecidae,cercopithecus,mitis
bushbuck,mammalia,artiodactyla,bovidae,tragelaphus,scriptus
bushpig,mammalia,artiodactyla,suidae,,
chimpanzee,mammalia,primates,hominidae,pan,troglodytes
civet_genet,mammalia,carnivora,,,
elephant,mammalia,proboscidea,elephantidae,loxodonta,
galago_potto,mammalia,primates,,,
gorilla,mammalia,primates,hominidae,gorilla,
guineafowl,aves,galliformes,numididae,,
honey badger,mammalia,carnivora,mustelidae,mellivora,capensis
hyrax,mammalia,hyracoidea,procaviidae,,
side-striped jackal,mammalia,carnivora,canidae,canis,adustus
leopard,mammalia,carnivora,felidae,panthera,pardus
l'hoest's monkey,mammalia,primates,cercopithecidae,allochrocebus,lhoesti
mandrill,mammalia,primates,cercopithecidae,mandrillus,sphinx
mongoose,mammalia,carnivora,herpestidae,,
monkey,mammalia,primates,cercopithecidae,,
pangolin,mammalia,pholidota,manidae,,
porcupine,mammalia,rodentia,hystricidae,,
red colobus_red-capped mangabey,mammalia,primates,cercopithecidae,,
red duiker,mammalia,artiodactyla,bovidae,cephalophus,
rodent,mammalia,rodentia,,,
serval,mammalia,carnivora,felidae,leptailurus,serval
spotted hyena,mammalia,carnivora,hyaenidae,crocuta,crocuta
squirrel,mammalia,rodentia,sciuridae,,
water chevrotain,mammalia,artiodactyla,tragulidae,hyemoschus,aquaticus
yellow-backed duiker,mammalia,artiodactyla,bovidae,cephalophus,silvicultorconfig.jsonAdded+24
inference.pyAdded+208
taxonomy.csvAdded+35