weixin_72661020/vit_small_patch14_reg4_dinov2.lvd142m
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Model card for vit_small_patch14_reg4_dinov2.lvd142m

A Vision Transformer (ViT) image feature model with registers. Pretrained on LVD-142M with self-supervised DINOv2 method.

Model Details

  • Model Type: Image classification / feature backbone
  • Model Stats:
    • Params (M): 22.1
    • GMACs: 29.6
    • Activations (M): 57.5
    • Image size: 518 x 518
  • Papers:
    • Vision Transformers Need Registers: https://arxiv.org/abs/2309.16588
    • DINOv2: Learning Robust Visual Features without Supervision: https://arxiv.org/abs/2304.07193
    • An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale: https://arxiv.org/abs/2010.11929v2
  • Original: https://github.com/facebookresearch/dinov2
  • Pretrain Dataset: LVD-142M

Model Usage

Image Classification

from urllib.request import urlopen
from PIL import Image
import timm

img = Image.open(urlopen(
    'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
))

model = timm.create_model('vit_small_patch14_reg4_dinov2.lvd142m', pretrained=True)
model = model.eval()

# get model specific transforms (normalization, resize)
data_config = timm.data.resolve_model_data_config(model)
transforms = timm.data.create_transform(**data_config, is_training=False)

output = model(transforms(img).unsqueeze(0))  # unsqueeze single image into batch of 1

top5_probabilities, top5_class_indices = torch.topk(output.softmax(dim=1) * 100, k=5)

Image Embeddings

from urllib.request import urlopen
from PIL import Image
import timm

img = Image.open(urlopen(
    'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
))

model = timm.create_model(
    'vit_small_patch14_reg4_dinov2.lvd142m',
    pretrained=True,
    num_classes=0,  # remove classifier nn.Linear
)
model = model.eval()

# get model specific transforms (normalization, resize)
data_config = timm.data.resolve_model_data_config(model)
transforms = timm.data.create_transform(**data_config, is_training=False)

output = model(transforms(img).unsqueeze(0))  # output is (batch_size, num_features) shaped tensor

# or equivalently (without needing to set num_classes=0)

output = model.forward_features(transforms(img).unsqueeze(0))
# output is unpooled, a (1, 1374, 384) shaped tensor

output = model.forward_head(output, pre_logits=True)
# output is a (1, num_features) shaped tensor

Model Comparison

Explore the dataset and runtime metrics of this model in timm model results.

Citation

@article{darcet2023vision,
  title={Vision Transformers Need Registers},
  author={Darcet, Timoth{'e}e and Oquab, Maxime and Mairal, Julien and Bojanowski, Piotr},
  journal={arXiv preprint arXiv:2309.16588},
  year={2023}
}
@misc{oquab2023dinov2,
  title={DINOv2: Learning Robust Visual Features without Supervision},
  author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy V. 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},
  journal={arXiv:2304.07193},
  year={2023}
}
@article{dosovitskiy2020vit,
  title={An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale},
  author={Dosovitskiy, Alexey and Beyer, Lucas and Kolesnikov, Alexander and Weissenborn, Dirk and Zhai, Xiaohua and Unterthiner, Thomas and  Dehghani, Mostafa and Minderer, Matthias and Heigold, Georg and Gelly, Sylvain and Uszkoreit, Jakob and Houlsby, Neil},
  journal={ICLR},
  year={2021}
}
@misc{rw2019timm,
  author = {Ross Wightman},
  title = {PyTorch Image Models},
  year = {2019},
  publisher = {GitHub},
  journal = {GitHub repository},
  doi = {10.5281/zenodo.4414861},
  howpublished = {\url{https://github.com/huggingface/pytorch-image-models}}
}

Ascend NPU Adaptation

This section documents the adaptation and validation of vit_small_patch14_reg4_dinov2.lvd142m on Huawei Ascend Ascend910B4 NPU.

Related Links

  • Original mirror repository (GitCode): https://gitcode.com/hf_mirrors/timm/vit_small_patch14_reg4_dinov2.lvd142m
  • Weights download (hf-mirror): https://hf-mirror.com/timm/vit_small_patch14_reg4_dinov2.lvd142m
  • Weights download (HuggingFace): https://huggingface.co/timm/vit_small_patch14_reg4_dinov2.lvd142m
  • timm official repository: https://github.com/huggingface/pytorch-image-models

1. Validation Environment

ComponentVersion
torch2.9.0+cpu
torch-npu2.9.0
timm1.0.27
transformers4.57.6
CANN8.5.1
  • NPU: 1 logical card (Ascend910B4)
  • Validation date: 2026-05-09

2. Model Loading and NPU Adaptation

Since timm pulls weights from HuggingFace Hub by default, it is recommended to set HF_ENDPOINT to a mirror site in China:

export HF_ENDPOINT=https://hf-mirror.com

Example code to load the model and move it to NPU:

import torch
import torch_npu
import timm

device = torch.device("npu:0")
torch.npu.set_device(device)

model = timm.create_model(
    "vit_small_patch14_reg4_dinov2.lvd142m",
    pretrained=True
)
model = model.to(device).eval()

# Get model preprocessing config
data_config = timm.data.resolve_model_data_config(model)
input_size = data_config["input_size"]  # (3, 518, 518)

The model runs directly on NPU without any additional operator replacement or code modifications. timm's VisionTransformer implementation is fully compatible with torch_npu.

3. Smoke Validation

3.1 Basic Inference Validation

import torch
import torch_npu
import timm

device = torch.device("npu:0")
model = timm.create_model("vit_small_patch14_reg4_dinov2.lvd142m", pretrained=True)
model = model.to(device).eval()

dummy_input = torch.randn(1, 3, 518, 518).to(device)
with torch.no_grad():
    output = model(dummy_input)

print(f"Output shape: {output.shape}")      # torch.Size([1, 384])
print(f"Output range: [{output.min():.4f}, {output.max():.4f}]")

Validation results:

  • Output dimension: [1, 384] (as expected)
  • Output value range: [-4.2467, 6.4520]
  • Output mean: -0.0271
  • No errors, inference successful

3.2 Precision Comparison (NPU vs CPU)

Using the same weights and input, compare the output differences between NPU and CPU:

MetricValue
Max Absolute Diff0.018992
Mean Absolute Diff0.005008

Conclusion: The floating-point difference between NPU inference results and the CPU baseline is within the 1e-2 order of magnitude, meeting the precision requirements for visual feature extraction tasks.

4. Performance Reference

On a single Ascend910B4 card, inference throughput and latency were tested using fp32 precision (excluding preprocessing).

Batch SizeThroughput (samples/s)Latency (ms/batch)
194.4810.58
4254.0115.75
8267.6629.89
16253.8463.03

Test notes:

  • Input size: 3 x 518 x 518
  • Warmup iterations: 10
  • Formal test iterations: 100
  • Synchronization method: torch.npu.synchronize() after each batch

From the data, batch=8 achieves the best throughput (approximately 267 samples/s), with an average inference latency of about 3.7 ms per image.

5. Validation Script

The complete script used for this validation is provided with the repository:

python validate_npu.py

The script covers:

  1. NPU device detection and model loading
  2. Single/batch inference output verification (shape, dtype, value range)
  3. NPU vs CPU precision comparison
  4. Multi-batch-size performance benchmark testing

6. Notes

  1. HF_ENDPOINT: In domestic network environments, be sure to set export HF_ENDPOINT=https://hf-mirror.com. Otherwise, timm downloading weights from the official HuggingFace site will time out.
  2. CANN Log Directory: If torch_npu prompts can not create directory: /home/atomgit/ascend/log on the first run, it can be ignored and does not affect inference. To eliminate the message, manually create that directory.
  3. Input Size: This model was trained with an input of 518 x 518, which differs from the standard ViT's 224 x 224. Please pay attention to input_size when using it.
  4. Precision Mode: Current validation is based on fp32. For further acceleration, you can try torch.npu.set_amp_dtype(torch.float16) for mixed-precision inference, but additional verification of precision loss is required.

7. File List

FileDescription
model.safetensorsModel weights (approx. 85MB)
validate_npu.pyNPU adaptation validation script
README.mdAdaptation documentation (this file)
validation_output.txtRaw output log from the validation script