Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(models)!: ViT, SigLip2 and TinyViT input checks; MobileViT mode; TinyViT-21M 384/512 windows and builder overrides (#6056)

Dmytro Mishkin9c813720475b
diff --git a/changelog.d/6056.breaking.md b/changelog.d/6056.breaking.md
new file mode 100644
index 000000000..ba5eefc1f
--- /dev/null
+++ b/changelog.d/6056.breaking.md
@@ -0,0 +1,5 @@
+Some calls of the vision backbones of `kornia.models` that ran now raise:
+
+- `VisionTransformer` and `SigLip2VisionEmbeddings`, and so `SigLip2VisionModel`, `SigLip2Model` and `PaliGemma`, raise `ValueError` for an input whose height and width are not both `image_size`, and `VisionTransformer` also for a channel count other than `in_channels`. With a `backbone`, `VisionTransformer` checks the backbone's token grid instead: it raises `ValueError` when the grid is not the one the backbone gives for an `image_size` input, which the position embeddings are built for, and inputs of other sizes that give that grid, through adaptive pooling for example, keep working. An input whose patch count happened to fit the position table returned a result with misplaced position embeddings or dropped columns: for `VisionTransformer(image_size=224, patch_size=16)`, `(1, 3, 112, 448)` added the 14 x 14 positions to a 7 x 28 patch grid and `(1, 3, 224, 239)` dropped its last 15 columns. Other sizes and a channel mismatch raised `RuntimeError` inside the model, for example `(1, 3, 240, 240)` and `(1, 1, 224, 224)`; the `ValueError` of `VisionTransformer` fired only when both the size and the channel count were wrong.
+- `TinyViT` raises `ValueError` for an input whose token grid is not the one its attention stages are built for, that of an `img_size` x `img_size` image; sides from `img_size - 7` to `img_size` round to that grid and keep working. An input with the same number of tokens on another grid returned a result with its tokens read as the wrong grid: at `img_size=224`, `(1, 3, 112, 448)` returned `(1, 1000)` from a 14 x 56 grid read as 28 x 28, and with `mobile_sam=True` at `img_size=1024`, a `(1, 3, 512, 2048)` input returned feature maps. Other sizes raised `RuntimeError`, for example `(1, 3, 224, 256)`.
+- `TinyViT.from_config("21m", ...)` builds the `"in1k_384"` and `"in1k_512"` checkpoints with 12- and 16-px windows (see the bug fixes), so a state dict saved from such a model built before, with 7-px windows, no longer loads into the model the same call builds: `load_state_dict` raises `RuntimeError` for the size of every attention bias, `(6, 49)` against `(6, 144)` in `layers.1.blocks.0.attn.attention_biases` at 384. Pass `window_sizes=[7, 7, 14, 7]` to build the model that state dict belongs to.
diff --git a/changelog.d/6056.fixed.md b/changelog.d/6056.fixed.md
new file mode 100644
index 000000000..291428bd4
--- /dev/null
+++ b/changelog.d/6056.fixed.md
@@ -0,0 +1,5 @@
+Fixes in the vision backbones of `kornia.models`:
+
+- `MobileViT` raises `ValueError` for a `mode` other than `"xxs"`, `"xs"` or `"s"`, where it raised `UnboundLocalError`.
+- `TinyViT.from_config("21m", ...)` builds the `"in1k_384"` and `"in1k_512"` checkpoints, named explicitly or picked by `pretrained=True` for an `img_size` of at least 384 or 512, with the window sizes they were trained with, `[12, 12, 24, 12]` and `[16, 16, 32, 16]`, as the reference TinyViT does. It built them with the 224-px windows `[7, 7, 14, 7]`, so their 12- and 16-px attention biases were bicubic-resized to 7 px without a warning, e.g. `(6, 144)` to `(6, 49)` in stage 1. Random init and the other checkpoints keep `[7, 7, 14, 7]`.
+- `TinyViT.from_config` passes `embed_dims`, `depths`, `num_heads`, `window_sizes` and `drop_path_rate` to the model in place of the variant's values. Each of them raised `TypeError: ... got multiple values for keyword argument`.
diff --git a/docs/source/models/efficient_vit.rst b/docs/source/models/efficient_vit.rst
index 1fb1bea8a..037f75741 100644
--- a/docs/source/models/efficient_vit.rst
+++ b/docs/source/models/efficient_vit.rst
@@ -19,11 +19,14 @@ Run it
.. code-block:: python
import torch
+ from kornia.enhance import normalize
from kornia.io import load_image
from kornia.geometry import resize
from kornia.models.efficient_vit import EfficientViT, EfficientViTConfig
image = resize(load_image("panda.jpg")[None], (224, 224)) # (1, 3, 224, 224) float in [0, 1]
+ # the backbones were trained on images normalized with the ImageNet mean and standard deviation
+ image = normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225]))
model = EfficientViT.from_config(EfficientViTConfig.from_pretrained("b1", 224)).eval()
with torch.no_grad():
diff --git a/docs/source/models/tiny_vit.rst b/docs/source/models/tiny_vit.rst
index 505ba36a8..f52656b3a 100644
--- a/docs/source/models/tiny_vit.rst
+++ b/docs/source/models/tiny_vit.rst
@@ -20,11 +20,14 @@ Run it
.. code-block:: python
import torch
+ from kornia.enhance import normalize
from kornia.io import load_image
from kornia.geometry import resize
from kornia.models.tiny_vit import TinyViT
image = resize(load_image("panda.jpg")[None], (224, 224)) # (1, 3, 224, 224) float in [0, 1]
+ # the checkpoints were trained on images normalized with the ImageNet mean and standard deviation
+ image = normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225]))
model = TinyViT.from_config("5m", pretrained=True).eval() # '5m', '11m' or '21m'; ImageNet-1k head
with torch.no_grad():
@@ -40,8 +43,15 @@ Run it
Top-5 ImageNet classes predicted by TinyViT-5M for the input on the left.
``pretrained`` also accepts ``'in22k'`` and, for ``'21m'``, the higher-resolution ``'in1k_384'`` and
-``'in1k_512'`` checkpoints; pass ``img_size=`` to run at another resolution and the attention biases are
-interpolated. The ImageNet-22k checkpoint carries a 21841-class head, so load it with
+``'in1k_512'`` checkpoints. ``pretrained=True`` picks them for an ``img_size`` of at least 384 or 512, and they are
+built with the windows they were trained with, ``window_sizes=[12, 12, 24, 12]`` and ``[16, 16, 32, 16]``; named
+explicitly, they build at the ``img_size`` you pass (224 by default), so pass ``img_size=384`` or ``512`` to run
+them at their resolution. Every other model keeps the 224-px windows ``[7, 7, 14, 7]`` at any ``img_size``, unless
+you pass ``window_sizes=``, and the attention biases are interpolated only when the windows differ from the
+checkpoint's. ``img_size`` must be a multiple of 32 and the input ``img_size`` square (sides down to
+``img_size - 7`` round to the same token grid; other sizes raise ``ValueError``), and accuracy is not preserved away
+from a checkpoint's resolution: on the panda above, TinyViT-5M's probability of the right class drops from 0.37 at
+224 px to 0.02 at ``img_size=256``. The ImageNet-22k checkpoint carries a 21841-class head, so load it with
``TinyViT.from_config("5m", pretrained="in22k", num_classes=21841)``: with the default ``num_classes=1000`` the
head does not match, is reset to zeros with a warning, the model returns all-zero logits, and it stays in training
mode as a backbone to fine-tune. For feature extraction replace the head and switch to evaluation mode:
diff --git a/docs/source/models/vit.rst b/docs/source/models/vit.rst
index 518b8d434..5acc513c7 100644
--- a/docs/source/models/vit.rst
+++ b/docs/source/models/vit.rst
@@ -23,11 +23,14 @@ Run it
.. code-block:: python
import torch
+ from kornia.enhance import normalize
from kornia.io import load_image
from kornia.geometry import resize
from kornia.models.vit import VisionTransformer
image = resize(load_image("panda.jpg")[None], (224, 224)) # (1, 3, 224, 224) float in [0, 1]
+ # the AugReg weights were trained on images normalized with mean = std = 0.5, i.e. in [-1, 1]
+ image = normalize(image, torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]))
vit = VisionTransformer.from_config("vit_b/16", pretrained=True).eval() # AugReg ImageNet-21k weights
with torch.no_grad():
diff --git a/kornia/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.py
index ba2c1d8df..ddc191e2b 100644
--- a/kornia/models/efficient_vit/model.py
+++ b/kornia/models/efficient_vit/model.py
@@ -41,7 +41,9 @@ class EfficientViTConfig:
The model weights are hosted on HuggingFace's model hub: https://huggingface.co/kornia.
Args:
- checkpoint: URL or local path of model weights.
+ checkpoint: URL or local path of model weights. :meth:`EfficientViT.from_config` reads the architecture from
+ the file name, which must start with the model type and a ``-`` (``b0``, ``b1``, ``b2``, ``b3``, ``l0``,
+ ``l1``, ``l2`` or ``l3``), as in ``b1-r224.pt``: ``my_efficientvit.pt`` raises ``ValueError``.
"""
@@ -62,7 +64,12 @@ class EfficientViTConfig:
class EfficientViT(ModelBase[EfficientViTConfig]):
- """EfficientViT backbone model."""
+ """EfficientViT backbone model.
+
+ The pretrained backbones were trained on images normalized with the ImageNet mean and standard deviation, so a
+ :math:`[0, 1]` image goes in as
+ ``kornia.enhance.normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225]))``.
+ """
def __init__(self, backbone: vit.EfficientViTBackbone | vit.EfficientViTLargeBackbone) -> None:
super().__init__()
@@ -107,14 +114,15 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
return EfficientViT(backbone=model).eval()
- def forward(self, images: torch.Tensor) -> torch.Tensor:
+ def forward(self, images: torch.Tensor) -> dict[str, torch.Tensor]:
"""Extract features from the input images.
Args:
images: input images tensor of shape :math:`(B, C, H, W)`.
Returns:
- Dict[str, torch.Tensor]: a dictionary containing the features.
+ a dictionary with the input under ``"input"``, the output of each stage under ``"stage0"``,
+ ``"stage1"``, and so on, and the last stage's output again under ``"stage_final"``.
"""
return self.backbone(images)
diff --git a/kornia/models/siglip2/vision_encoder.py b/kornia/models/siglip2/vision_encoder.py
index 1d82b02a8..9ab75478b 100644
--- a/kornia/models/siglip2/vision_encoder.py
+++ b/kornia/models/siglip2/vision_encoder.py
@@ -77,11 +77,22 @@ class SigLip2VisionEmbeddings(nn.Module):
"""Forward pass.
Args:
- pixel_values: Input images of shape (batch_size, num_channels, height, width).
+ pixel_values: Input images of shape (batch_size, num_channels, height, width), with height and width
+ both equal to ``config.image_size``: the position embeddings are a fixed table of the
+ ``image_size // patch_size`` square patch grid, without interpolation.
Returns:
Embedded patches of shape (batch_size, num_patches, hidden_size).
+
+ Raises:
+ ValueError: if (height, width) is not ``(image_size, image_size)``.
"""
+ if tuple(pixel_values.shape[-2:]) != (self.image_size, self.image_size):
+ raise ValueError(
+ f"Input images must be {self.image_size}x{self.image_size} (config.image_size): the position "
+ f"embeddings cover that size only. Got: {tuple(pixel_values.shape)}"
+ )
+
# extract patches from the image
embeddings = self.patch_embedding(pixel_values) # (batch_size, hidden_size, H', W')
embeddings = embeddings.flatten(2).transpose(1, 2) # (batch_size, num_patches, hidden_size)
@@ -317,7 +328,8 @@ class SigLip2VisionModel(nn.Module):
"""Forward pass.
Args:
- pixel_values: Input images of shape (batch_size, num_channels, height, width).
+ pixel_values: Input images of shape (batch_size, num_channels, height, width), with height and width
+ both equal to ``config.image_size`` (see :class:`SigLip2VisionEmbeddings`).
attention_mask: Optional mask of the patches, ``1``/``True`` for a patch to keep and ``0``/``False`` for
a padded one: :math:`(B, N)`, :math:`(B, N, N)` or :math:`(B, 1, N, N)` for :math:`N` patches (see
:class:`SigLip2Attention`). It excludes the padded patches from the encoder, where no patch attends
@@ -329,6 +341,9 @@ class SigLip2VisionModel(nn.Module):
- Pooled output, attention-pooled by the probe head (:class:`SigLip2MultiheadAttentionPoolingHead`)
- Last hidden state
- All hidden states (if output_hidden_states=True)
+
+ Raises:
+ ValueError: if (height, width) is not ``(config.image_size, config.image_size)``.
"""
# Get embeddings
hidden_states = self.embeddings(pixel_values)
diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.py
index 0d3523b7b..a138d5946 100644
--- a/kornia/models/tiny_vit.py
+++ b/kornia/models/tiny_vit.py
@@ -149,6 +149,8 @@ class PatchMerging(nn.Module):
KORNIA_CHECK(stride in (1, 2), "stride must be either 1 or 2")
super().__init__()
self.input_resolution = _make_pair(input_resolution)
+ # The token grid the next stage is built for (TinyViT.__init__ divides the resolution the same way).
+ self.output_resolution = (self.input_resolution[0] // stride, self.input_resolution[1] // stride)
self.conv1 = ConvBN(dim, out_dim, 1, activation=activation)
self.conv2 = ConvBN(out_dim, out_dim, 3, stride, 1, groups=out_dim, activation=activation)
self.conv3 = ConvBN(out_dim, out_dim, 1)
@@ -164,10 +166,22 @@ class PatchMerging(nn.Module):
Token tensor with shape :math:`(B, H_{out} * W_{out}, C_{out})`.
The spatial size is reduced when this layer was configured with
stride ``2``.
+
+ Raises:
+ ValueError: if :math:`(H_{out}, W_{out})` is not the grid the next stage is built for: the input of a
+ :class:`TinyViT` is not ``img_size`` (the first patch merging reads the image's own grid from a
+ :math:`(B, C, H, W)` map), or ``img_size`` is not a multiple of 32 (of 16 with ``mobile_sam=True``),
+ so the stride-2 convolution rounds an odd grid up where the stages were built for it rounded down.
"""
if x.ndim == 3:
x = x.transpose(1, 2).unflatten(2, self.input_resolution) # (B, H * W, C) -> (B, C, H, W)
x = self.conv3(self.conv2(self.conv1(x)))
+ if tuple(x.shape[-2:]) != self.output_resolution:
+ raise ValueError(
+ f"The input gives a {x.shape[-2]}x{x.shape[-1]} token grid, but the TinyViT stages are built for the "
+ f"{self.output_resolution[0]}x{self.output_resolution[1]} grid of an img_size x img_size image "
+ "(img_size must be a multiple of 32, of 16 with mobile_sam=True)."
+ )
return x.flatten(2).transpose(1, 2) # (B, C, H, W) -> (B, H * W, C)
@@ -495,8 +509,13 @@ class BasicLayer(nn.Module):
class TinyViT(nn.Module):
"""TinyViT model, as described in https://arxiv.org/abs/2207.10666.
+ The pretrained checkpoints of :meth:`from_config` were trained on images normalized with the ImageNet mean and
+ standard deviation, so a :math:`[0, 1]` image goes in as
+ ``kornia.enhance.normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225]))``.
+
Args:
- img_size: Size of input image.
+ img_size: Size of the square input image, a multiple of 32 (of 16 with ``mobile_sam=True``). The attention
+ stages are built for the token grid of an ``img_size`` image (see :meth:`forward`).
in_chans: Number of input image's channels.
num_classes: Number of output classes.
embed_dims: List of embedding dimensions.
@@ -510,7 +529,7 @@ class TinyViT(nn.Module):
mbconv_expand_ratio: Expansion ratio used in MBConv block.
local_conv_size: Kernel size of convolution used in TinyViTBlock
activation: activation function.
- mobile_same: Whether to use modifications for MobileSAM.
+ mobile_sam: Whether to use modifications for MobileSAM.
"""
@@ -604,7 +623,16 @@ class TinyViT(nn.Module):
self.head = nn.Linear(embed_dims[-1], num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
- """Classify images if ``mobile_sam=False``, produce feature maps if ``mobile_sam=True``."""
+ """Classify images if ``mobile_sam=False``, produce feature maps if ``mobile_sam=True``.
+
+ Args:
+ x: images :math:`(B, C, H, W)` with :math:`H = W =` ``img_size``. The strided convolutions before the
+ first attention stage round up, so :math:`H` and :math:`W` from ``img_size - 7`` to ``img_size`` give
+ the same token grid and run too.
+
+ Raises:
+ ValueError: if the input gives a token grid other than that of an ``img_size`` image.
+ """
x = self.patch_embed(x)
x = self.layers(x)
@@ -628,13 +656,25 @@ class TinyViT(nn.Module):
Args:
variant: TinyViT variant. Possible values: ``'5m'``, ``'11m'``, ``'21m'``.
pretrained: whether to use pre-trained weights. Possible values: ``False``, ``True``, ``'in22k'``,
- ``'in1k'``. For TinyViT-21M (``variant='21m'``), ``'in1k_384'``, ``'in1k_512'`` are also available.
- **kwargs: other keyword arguments that will be passed to :class:`TinyViT`.
+ ``'in1k'``. For TinyViT-21M (``variant='21m'``), ``'in1k_384'``, ``'in1k_512'`` are also available;
+ named, they build at the ``img_size`` you pass (224 by default), so pass ``img_size=384`` or ``512``
+ to run them at their resolution.
+ **kwargs: other keyword arguments that will be passed to :class:`TinyViT`. They override the variant's
+ ``embed_dims``, ``depths``, ``num_heads``, ``window_sizes`` and ``drop_path_rate``.
.. note::
- When ``img_size`` is different from the pre-trained size, bicubic interpolation will be performed on
- attention biases. When using ``pretrained=True``, ImageNet-1k checkpoint (``'in1k'``) is used.
- For feature extraction or fine-tuning, ImageNet-22k checkpoint (``'in22k'``) is preferred.
+ ``pretrained=True`` loads the ImageNet-1k checkpoint (``'in1k'``); for TinyViT-21M it loads ``'in1k_384'``
+ when ``img_size`` is at least 384 and ``'in1k_512'`` when it is at least 512. For feature extraction or
+ fine-tuning, the ImageNet-22k checkpoint (``'in22k'``) is preferred.
+
+ ``img_size`` does not change the window sizes: they are the 224-px ``[7, 7, 14, 7]`` at every
+ ``img_size``, except that the TinyViT-21M ``'in1k_384'`` and ``'in1k_512'`` checkpoints get the windows
+ they were trained with, ``[12, 12, 24, 12]`` and ``[16, 16, 32, 16]``. A ``window_sizes`` argument
+ overrides them. The checkpoint's attention biases are interpolated (bicubic) only when the window sizes
+ differ from the checkpoint's. ``img_size`` must be a multiple of 32 (of 16 with ``mobile_sam=True``), and
+ a checkpoint's accuracy is not preserved away from the resolution it was trained at: on the panda image of
+ the :doc:`/models/tiny_vit` example, TinyViT-5M's probability of the right class drops from 0.37 at 224 px
+ to 0.02 at ``img_size=256``.
With ``pretrained`` and a ``num_classes`` other than the checkpoint's, the classification head is reset to
zeros, and the model, a pretrained backbone to fine-tune, stays in training mode. The ``'in22k'``
@@ -738,14 +778,12 @@ def _load_pretrained(model: TinyViT, url: str | list[str]) -> TinyViT:
def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
- model = TinyViT(
- embed_dims=[64, 128, 160, 320],
- depths=[2, 2, 6, 2],
- num_heads=[2, 4, 5, 10],
- window_sizes=[7, 7, 14, 7],
- drop_path_rate=0.0,
- **kwargs,
- )
+ kwargs.setdefault("embed_dims", [64, 128, 160, 320])
+ kwargs.setdefault("depths", [2, 2, 6, 2])
+ kwargs.setdefault("num_heads", [2, 4, 5, 10])
+ kwargs.setdefault("window_sizes", [7, 7, 14, 7])
+ kwargs.setdefault("drop_path_rate", 0.0)
+ model = TinyViT(**kwargs)
if pretrained:
if pretrained is True:
@@ -758,14 +796,12 @@ def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
- model = TinyViT(
- embed_dims=[64, 128, 256, 448],
- depths=[2, 2, 6, 2],
- num_heads=[2, 4, 8, 14],
- window_sizes=[7, 7, 14, 7],
- drop_path_rate=0.1,
- **kwargs,
- )
+ kwargs.setdefault("embed_dims", [64, 128, 256, 448])
+ kwargs.setdefault("depths", [2, 2, 6, 2])
+ kwargs.setdefault("num_heads", [2, 4, 8, 14])
+ kwargs.setdefault("window_sizes", [7, 7, 14, 7])
+ kwargs.setdefault("drop_path_rate", 0.1)
+ model = TinyViT(**kwargs)
if pretrained:
if pretrained is True:
@@ -777,25 +813,28 @@ def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
return model
+# The window sizes the TinyViT-21M 384 and 512 checkpoints were trained with (Cream ``tiny_vit_21m_384`` and
+# ``tiny_vit_21m_512``); the other 21M checkpoints use the 224-px windows (7, 7, 14, 7).
+_TINY_VIT_21M_WINDOW_SIZES = {"in1k_384": (12, 12, 24, 12), "in1k_512": (16, 16, 32, 16)}
+
+
def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
- model = TinyViT(
- embed_dims=[96, 192, 384, 576],
- depths=[2, 2, 6, 2],
- num_heads=[3, 6, 12, 18],
- window_sizes=[7, 7, 14, 7],
- drop_path_rate=0.2,
- **kwargs,
- )
+ # The checkpoint is resolved before the model is built, which takes that checkpoint's window sizes.
+ if pretrained is True:
+ img_size = kwargs.get("img_size", 224)
+ pretrained = "in1k_512" if img_size >= 512 else "in1k_384" if img_size >= 384 else "in1k"
+ window_sizes = (7, 7, 14, 7)
+ if isinstance(pretrained, str):
+ window_sizes = _TINY_VIT_21M_WINDOW_SIZES.get(pretrained, window_sizes)
+
+ kwargs.setdefault("embed_dims", [96, 192, 384, 576])
+ kwargs.setdefault("depths", [2, 2, 6, 2])
+ kwargs.setdefault("num_heads", [3, 6, 12, 18])
+ kwargs.setdefault("window_sizes", list(window_sizes))
+ kwargs.setdefault("drop_path_rate", 0.2)
+ model = TinyViT(**kwargs)
if pretrained:
- if pretrained is True:
- pretrained = "in1k"
- img_size = kwargs.get("img_size", 224)
- if img_size >= 384:
- pretrained = "in1k_384"
- if img_size >= 512:
- pretrained = "in1k_512"
-
url = urls["21m"][pretrained]
model = _load_pretrained(model, url)
diff --git a/kornia/models/vit.py b/kornia/models/vit.py
index 2e6c4d2cd..474253652 100644
--- a/kornia/models/vit.py
+++ b/kornia/models/vit.py
@@ -162,23 +162,33 @@ class PatchEmbedding(nn.Module):
self.patch_size = patch_size
# logic needed in case a backbone is passed
+ self.custom_backbone = backbone is not None
self.backbone = backbone or nn.Conv2d(in_channels, out_channels, kernel_size=patch_size, stride=patch_size)
+ # The token grid the position embeddings are built for: the backbone's output grid for an ``image_size``
+ # input, or the patch grid of that input.
+ self.grid_size: tuple[int, int]
if backbone is not None:
- out_channels, feat_size = self._compute_feats_dims((in_channels, image_size, image_size))
+ out_channels, self.grid_size = self._compute_feats_dims((in_channels, image_size, image_size))
self.out_channels = out_channels
else:
- feat_size = (image_size // patch_size) ** 2
+ self.grid_size = (image_size // patch_size, image_size // patch_size)
+ feat_size = self.grid_size[0] * self.grid_size[1]
self.cls_token = nn.Parameter(torch.randn(1, 1, out_channels))
self.positions = nn.Parameter(torch.randn(feat_size + 1, out_channels))
- def _compute_feats_dims(self, image_size: tuple[int, int, int]) -> tuple[int, int]:
+ def _compute_feats_dims(self, image_size: tuple[int, int, int]) -> tuple[int, tuple[int, int]]:
out = self.backbone(torch.zeros(1, *image_size)).detach()
- return out.shape[-3], out.shape[-2] * out.shape[-1]
+ return out.shape[-3], (out.shape[-2], out.shape[-1])
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.backbone(x)
- B, N, _, _ = x.shape
+ B, N, height, width = x.shape
+ if (height, width) != self.grid_size:
+ raise ValueError(
+ f"The patch embedding gives a {height}x{width} token grid, but the position embeddings are built for "
+ f"the {self.grid_size[0]}x{self.grid_size[1]} grid of an image_size input."
+ )
x = x.view(B, N, -1).permute(0, 2, 1) # BxNxE
cls_tokens = self.cls_token.repeat(B, 1, 1) # Bx1xE
# prepend the cls token to the input
@@ -195,6 +205,13 @@ class VisionTransformer(nn.Module):
The method is inspired from existing implementations of the paper :cite:`dosovitskiy2020vit`.
+ Without a ``backbone``, the input must be ``image_size`` square with ``in_channels`` channels. With one, the
+ backbone's token grid must be the one it gives for an ``image_size`` input, which the position embeddings are
+ built for; a backbone that ends in adaptive pooling, for example, gives that grid at any input size. The AugReg
+ weights that :meth:`from_config` loads were trained on images normalized with mean = std = 0.5 per channel, so a
+ :math:`[0, 1]` image goes in as
+ ``kornia.enhance.normalize(image, torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]))``.
+
.. warning::
This is an experimental API subject to changes in favor of flexibility.
@@ -207,7 +224,8 @@ class VisionTransformer(nn.Module):
num_heads: the number of attention heads.
dropout_rate: dropout rate.
dropout_attn: attention dropout rate.
- backbone: an nn.Module to compute the image patches embeddings.
+ backbone: an nn.Module to compute the image patches embeddings, as a :math:`(B, D, h, w)` map. The position
+ embeddings are sized from its output for an ``image_size`` input.
Example:
>>> img = torch.rand(1, 3, 224, 224)
@@ -256,20 +274,31 @@ class VisionTransformer(nn.Module):
"""Encode an image batch into Vision Transformer token embeddings.
Args:
- x: Image tensor with shape :math:`(B, C, H, W)`, where
- :math:`B` is batch size, :math:`C` must match
- ``self.in_channels``, and :math:`H` and :math:`W` are expected
- to match ``self.image_size``.
+ x: Image tensor with shape :math:`(B, C, H, W)`. Without a
+ ``backbone``, :math:`C` must equal ``self.in_channels`` and
+ :math:`H` and :math:`W` must both equal ``self.image_size``;
+ with one, the backbone's token grid must be the one it gives
+ for an ``image_size`` input. The position embeddings are a
+ fixed table, one row per token of that grid.
Returns:
Normalized token embedding tensor produced by patch embedding and
the transformer encoder. The output shape follows the encoder
layout, usually :math:`(B, N, D)`.
+
+ Raises:
+ ValueError: without a ``backbone``, if :math:`C` is not ``in_channels`` or :math:`(H, W)` is not
+ ``(image_size, image_size)``; with one, if the backbone's token grid is not the one it gives for an
+ ``image_size`` input.
"""
if not isinstance(x, torch.Tensor):
raise TypeError(f"Input x type is not a torch.Tensor. Got: {type(x)}")
- if self.image_size not in (*x.shape[-2:],) and x.shape[-3] != self.in_channels:
+ # A backbone's token grid is checked once it has run (PatchEmbedding.forward): an adaptive one gives the grid
+ # of an image_size input at other sizes too.
+ if not self.patch_embedding.custom_backbone and (
+ x.shape[-3] != self.in_channels or tuple(x.shape[-2:]) != (self.image_size, self.image_size)
+ ):
raise ValueError(
f"Input image shape must be Bx{self.in_channels}x{self.image_size}x{self.image_size}. Got: {x.shape}"
)
diff --git a/kornia/models/vit_mobile.py b/kornia/models/vit_mobile.py
index 8758de884..583176930 100644
--- a/kornia/models/vit_mobile.py
+++ b/kornia/models/vit_mobile.py
@@ -321,9 +321,15 @@ class MobileViT(nn.Module):
Args:
mode: 'xxs', 'xs' or 's', defaults to 'xxs'.
in_channels: the number of channels for the input image.
- patch_size: image_size must be divisible by patch_size.
+ patch_size: the patch size :math:`(p_h, p_w)` the MobileViT blocks unfold their feature maps into, at strides
+ 8, 16 and 32 of the input. Each of those maps must split into whole patches, which an input height and
+ width that are multiples of :math:`32 p_h` and :math:`32 p_w` guarantee: with the default ``(2, 2)``,
+ 192, 256 and 320 px run, and 224 and 288 px raise.
dropout: dropout ratio in Transformer.
+ Raises:
+ ValueError: if ``mode`` is not ``'xxs'``, ``'xs'`` or ``'s'``.
+
Example:
>>> img = torch.rand(1, 3, 256, 256)
>>> mvit = MobileViT(mode='xxs')
@@ -348,6 +354,8 @@ class MobileViT(nn.Module):
expansion = 4
dims = [144, 192, 240]
channels = [16, 32, 64, 64, 96, 96, 128, 128, 160, 160, 640]
+ else:
+ raise ValueError(f"mode must be 'xxs', 'xs' or 's'. Got: {mode!r}")
kernel_size = 3
depth = [2, 4, 3]
diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.py
index 5e4aa3189..23d9d7786 100644
--- a/tests/models/test_efficient_vit.py
+++ b/tests/models/test_efficient_vit.py
@@ -221,3 +221,16 @@ class TestEfficientViT:
config = EfficientViTConfig.from_pretrained(model_type, resolution)
assert model_type in config.checkpoint
assert str(resolution) in config.checkpoint
+
+ def test_forward_returns_a_dict(self, device, dtype):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ model = EfficientViT(backbone=vit.efficientvit_backbone_b0()).to(device, dtype).eval()
+ image = torch.rand(1, 3, 64, 96, device=device, dtype=dtype)
+
+ with torch.no_grad():
+ out = model(image)
+
+ assert isinstance(out, dict)
+ # stride 32: (64 // 32, 96 // 32)
+ assert out["stage_final"].shape[-2:] == (2, 3)
diff --git a/tests/models/test_mobile_vit.py b/tests/models/test_mobile_vit.py
index b0918410c..77b4fb1fa 100644
--- a/tests/models/test_mobile_vit.py
+++ b/tests/models/test_mobile_vit.py
@@ -38,3 +38,8 @@ class TestMobileViT(BaseTester):
out = mvit(img)
assert isinstance(out, torch.Tensor)
assert out.shape == (B, channel[mode], 4, 4)
+
+ @pytest.mark.device_agnostic
+ def test_unknown_mode_raises(self):
+ with pytest.raises(ValueError, match="'xxs', 'xs' or 's'"):
+ MobileViT(mode="m")
diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.py
index 6b1fe18ba..0a80939ff 100644
--- a/tests/models/test_siglip2.py
+++ b/tests/models/test_siglip2.py
@@ -716,6 +716,49 @@ class TestSigLip2Components(BaseTester):
num_patches = (config.image_size // config.patch_size) ** 2
assert output.shape == (batch_size, num_patches, config.hidden_size)
+ @pytest.mark.parametrize(
+ "size",
+ [(16, 64), (8, 128), (33, 39), (32, 39), (39, 32), (40, 40)],
+ ids=["2x8-grid", "1x16-grid", "33x39", "32x39", "39x32", "40x40"],
+ )
+ def test_vision_embeddings_reject_other_sizes(self, device, dtype, size):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ config = SigLip2VisionConfig(
+ image_size=32,
+ patch_size=8,
+ hidden_size=32,
+ num_hidden_layers=1,
+ num_attention_heads=4,
+ intermediate_size=64,
+ )
+ embeddings = SigLip2VisionEmbeddings(config).to(device, dtype)
+ model = SigLip2VisionModel(config).to(device, dtype)
+
+ with torch.no_grad():
+ assert embeddings(torch.rand(1, 3, 32, 32, device=device, dtype=dtype)).shape == (1, 16, 32)
+ # The position table is the (32 // 8) ** 2 = 16 cells of a 4 x 4 grid. The patch grids 2 x 8 of 16 x 64,
+ # 1 x 16 of 8 x 128 and 4 x 4 of 33 x 39, 32 x 39 and 39 x 32 (remainders dropped) also have 16 cells;
+ # 40 x 40 gives 5 x 5. 32 x 39 and 39 x 32 have one side right, so the check must test both.
+ pixel_values = torch.rand(1, 3, *size, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="32"):
+ embeddings(pixel_values)
+ # SigLip2VisionModel, and through it SigLip2Model and PaliGemma, embed the image first.
+ with pytest.raises(ValueError, match="32"):
+ model(pixel_values)
+
+ def test_dynamo_fullgraph_vision_embeddings(self, device, dtype, torch_optimizer):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # The size check reads static shapes: it must compile without a graph break.
+ embeddings = SigLip2VisionEmbeddings(_tiny_vision_config()).to(device, dtype).eval()
+ pixel_values = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)
+
+ embeddings_optimized = torch_optimizer(embeddings, fullgraph=True)
+
+ with torch.no_grad():
+ self.assert_close(embeddings_optimized(pixel_values), embeddings(pixel_values))
+
def test_vision_encoder(self, device, dtype):
"""Test SigLip2VisionEncoder."""
config = SigLip2VisionConfig(
diff --git a/tests/models/test_tiny_vit.py b/tests/models/test_tiny_vit.py
index 8960f1232..110d8608d 100644
--- a/tests/models/test_tiny_vit.py
+++ b/tests/models/test_tiny_vit.py
@@ -22,7 +22,7 @@ import pytest
import torch
from torch import nn
-from kornia.models.tiny_vit import Attention, TinyViT
+from kornia.models.tiny_vit import Attention, TinyViT, urls
from testing.base import BaseTester
@@ -55,6 +55,15 @@ def _fake_5m_checkpoint(url: str | list[str], *args: object, **kwargs: object) -
return TinyViT.from_config("5m", num_classes=num_classes).state_dict()
+def _windows(model: TinyViT) -> list[int]:
+ # The window size of each attention stage; stage 0 is convolutional.
+ return [layer.blocks[0].window_size for layer in model.layers[1:]]
+
+
+# TinyViT-21M's layout, from Cream tiny_vit_21m_224/_384/_512 (microsoft/Cream@8dc3882, TinyViT/models/tiny_vit.py).
+_21M_LAYOUT = {"embed_dims": [96, 192, 384, 576], "depths": [2, 2, 6, 2], "num_heads": [3, 6, 12, 18]}
+
+
def _image(batch_size: int = 1, seed: int = 0) -> torch.Tensor:
# TinyViT takes only its square ``img_size`` (224 by default).
return torch.rand(batch_size, 3, 224, 224, generator=torch.Generator().manual_seed(seed))
@@ -92,12 +101,14 @@ class TestTinyViT(BaseTester):
def test_module(self): ...
@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 8, reason="not working for py3.8")
- def test_dynamo(self, device, dtype, torch_optimizer):
+ def test_dynamo(self, device, dtype, torch_optimizer, cudnn_tf32_follows_option):
op = TinyViT().to(device=device, dtype=dtype)
img = torch.rand(1, 3, op.img_size, op.img_size, device=device, dtype=dtype)
op_optimized = torch_optimizer(op)
- self.assert_close(op(img), op_optimized(img))
+ # As in test_dynamo_eval_mode: inductor keeps fused half-precision intermediates in float32.
+ tol = {torch.float16: 1e-2, torch.bfloat16: 5e-2}.get(dtype)
+ self.assert_close(op(img), op_optimized(img), rtol=tol, atol=tol)
@pytest.mark.slow
@pytest.mark.parametrize("pretrained", [False, True])
@@ -206,8 +217,161 @@ class TestTinyViT(BaseTester):
assert not model.head.bias.any()
assert _modes(model) == {True}
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ ("img_size", "key", "window", "pretrained_values", "num_classes"),
+ [
+ # True picks in1k below 384 px; the in22k checkpoint has a 21841-class head and is only reached by name.
+ (224, "in1k", 7, (True, "in1k"), 1000),
+ (224, "in22k", 7, ("in22k",), 21841),
+ (384, "in1k_384", 12, (True, "in1k_384"), 1000),
+ (512, "in1k_512", 16, (True, "in1k_512"), 1000),
+ ],
+ )
+ def test_21m_checkpoints_keep_their_windows(
+ self, monkeypatch, img_size, key, window, pretrained_values, num_classes
+ ):
+ # Cream builds tiny_vit_21m_224 with window_sizes [7, 7, 14, 7], tiny_vit_21m_384 with [12, 12, 24, 12] and
+ # tiny_vit_21m_512 with [16, 16, 32, 16] (microsoft/Cream@8dc3882, TinyViT/models/tiny_vit.py); each checkpoint
+ # holds the attention biases of its windows. The stand-in has that shape and N(0, 1) biases.
+ windows = [window, window, 2 * window, window]
+ stand_in = TinyViT(img_size=img_size, window_sizes=windows, num_classes=num_classes, **_21M_LAYOUT)
+ checkpoint = _random_biases(stand_in).state_dict()
+ biases = {k: v.clone() for k, v in checkpoint.items() if "attention_biases" in k}
+ fetched: list[str | list[str]] = []
+
+ def fake_loader(url: str | list[str], *args: object, **kwargs: object) -> dict[str, torch.Tensor]:
+ fetched.append(url)
+ return dict(checkpoint)
+
+ monkeypatch.setattr("kornia.models.tiny_vit.load_state_dict_from_url", fake_loader)
+
+ for pretrained in pretrained_values:
+ model = TinyViT.from_config("21m", pretrained=pretrained, img_size=img_size, num_classes=num_classes)
+ assert fetched[-1] == urls["21m"][key]
+ assert _windows(model) == windows[1:]
+ # Loaded as they are: interpolating them to other windows would change their shape.
+ state_dict = model.state_dict()
+ for name, bias in biases.items():
+ assert torch.equal(state_dict[name], bias), name
+
+ # An explicit ``window_sizes`` wins; the biases are then interpolated to it.
+ model = TinyViT.from_config(
+ "21m", pretrained=key, img_size=img_size, num_classes=num_classes, window_sizes=[8, 8, 16, 8]
+ )
+ assert _windows(model) == [8, 16, 8]
+ # Random init has no checkpoint to follow and keeps the 224-px windows.
+ assert _windows(TinyViT.from_config("21m", img_size=img_size)) == [7, 14, 7]
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ ("variant", "embed_dims", "num_heads"),
+ # Each stage's dimension stays divisible by its number of heads, which TinyViTBlock checks; the defaults are
+ # 5m [2, 4, 5, 10], 11m [2, 4, 8, 14] and 21m [3, 6, 12, 18] heads.
+ [
+ ("5m", [32, 64, 160, 320], [2, 4, 4, 8]),
+ ("11m", [32, 64, 256, 448], [1, 2, 4, 7]),
+ ("21m", [48, 96, 384, 576], [2, 4, 8, 12]),
+ ],
+ )
+ def test_builder_arguments_can_be_overridden(self, variant, embed_dims, num_heads):
+ model = TinyViT.from_config(
+ variant,
+ window_sizes=[8, 8, 16, 8],
+ drop_path_rate=0.3,
+ embed_dims=embed_dims,
+ depths=[1, 1, 2, 1],
+ num_heads=num_heads,
+ )
+
+ assert _windows(model) == [8, 16, 8]
+ stage_dims = [model.layers[0].blocks[0].conv3.c.out_channels]
+ stage_dims += [layer.blocks[0].attn.norm.normalized_shape[0] for layer in model.layers[1:]]
+ assert stage_dims == embed_dims
+ assert [len(layer.blocks) for layer in model.layers] == [1, 1, 2, 1]
+ # Stage 0 is convolutional and has no heads.
+ assert [layer.blocks[0].attn.num_heads for layer in model.layers[1:]] == num_heads[1:]
+ # The stochastic depth rate rises linearly to drop_path_rate at the last block.
+ assert model.layers[-1].blocks[-1].drop_path1.drop_prob == pytest.approx(0.3)
+
+ @pytest.mark.parametrize(
+ ("img_size", "mobile_sam", "size"),
+ [
+ (224, False, (224, 224)),
+ (224, False, (220, 220)),
+ (224, False, (217, 224)),
+ (64, True, (64, 64)),
+ (64, True, (57, 64)),
+ ],
+ )
+ def test_forward_takes_sizes_of_its_token_grid(self, device, dtype, img_size, mobile_sam, size):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # The stem and the first patch merging downsample by 8 with ceil rounding, so sides from img_size - 7 to
+ # img_size give the img_size // 8 grid the attention stages are built for, and their result is correct.
+ model = TinyViT.from_config("5m", img_size=img_size, mobile_sam=mobile_sam).to(device, dtype).eval()
+
+ with torch.no_grad():
+ out = model(torch.rand(1, 3, *size, device=device, dtype=dtype))
+
+ assert out.shape == ((1, 256, img_size // 16, img_size // 16) if mobile_sam else (1, 1000))
+
+ @pytest.mark.parametrize(
+ ("img_size", "mobile_sam", "size"),
+ [
+ (224, False, (112, 448)),
+ (224, False, (448, 112)),
+ (224, False, (216, 216)),
+ (224, False, (225, 225)),
+ (224, False, (224, 256)),
+ (224, False, (256, 224)),
+ (64, True, (32, 128)),
+ ],
+ )
+ def test_forward_rejects_other_token_grids(self, device, dtype, img_size, mobile_sam, size):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # 112 x 448 and 448 x 112 give 14 x 56 and 56 x 14 grids of the 784 tokens of 28 x 28, which the stages would
+ # read as 28 x 28; 32 x 128 gives MobileSAM's 4 x 16 grid of the 64 tokens of 8 x 8. 216 and 225 give 27 x 27
+ # and 29 x 29; 224 x 256 and 256 x 224 have one side right (28 x 32 and 32 x 28).
+ model = TinyViT.from_config("5m", img_size=img_size, mobile_sam=mobile_sam).to(device, dtype).eval()
+
+ with torch.no_grad(), pytest.raises(ValueError, match=f"{img_size // 8}x{img_size // 8}"):
+ model(torch.rand(1, 3, *size, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize(("img_size", "mobile_sam"), [(80, False), (240, False), (72, True)])
+ def test_img_size_off_the_merging_grid_is_named_in_the_error(self, device, dtype, img_size, mobile_sam):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # The stride-2 convolutions round an odd grid up where the stages were built for it rounded down, so such an
+ # img_size rejects its own img_size x img_size input: the error names the img_size rule.
+ model = TinyViT.from_config("5m", img_size=img_size, mobile_sam=mobile_sam).to(device, dtype).eval()
+
+ with (
+ torch.no_grad(),
+ pytest.raises(ValueError, match="img_size must be a multiple of 32, of 16 with mobile_sam"),
+ ):
+ model(torch.rand(1, 3, img_size, img_size, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("mobile_sam", [False, True])
+ def test_dynamo_fullgraph(self, device, dtype, torch_optimizer, mobile_sam, cudnn_tf32_follows_option):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # The token-grid check reads static shapes: it must compile without a graph break.
+ op = _random_biases(TinyViT.from_config("5m", img_size=64, mobile_sam=mobile_sam)).eval().to(device, dtype)
+ img = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
+
+ op_optimized = torch_optimizer(op, fullgraph=True)
+ # As in test_dynamo_eval_mode: inductor keeps fused half-precision intermediates in float32. MobileSAM's feature
+ # map reaches about 4.7, where a bfloat16 ulp is 0.031: over 128 seeds on CUDA the largest difference was 0.080,
+ # so that case gets an absolute 0.125 (four ulps there) instead of 5e-2 + 5e-2 * |value|.
+ tol = {torch.float16: 1e-2, torch.bfloat16: 5e-2}.get(dtype)
+ rtol, atol = (0.0, 0.125) if mobile_sam and dtype == torch.bfloat16 else (tol, tol)
+ with torch.no_grad():
+ self.assert_close(op(img), op_optimized(img), rtol=rtol, atol=atol)
+
@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 8, reason="not working for py3.8")
- def test_dynamo_eval_mode(self, device, dtype, torch_optimizer):
+ def test_dynamo_eval_mode(self, device, dtype, torch_optimizer, cudnn_tf32_follows_option):
if device.type == "mps" and dtype == torch.float64:
pytest.skip("MPS does not support float64")
# Evaluation mode first, then the cast: the order of a pretrained model moved to its device.
diff --git a/tests/models/test_vision_transformer.py b/tests/models/test_vision_transformer.py
index 64f39d855..86b5c4460 100644
--- a/tests/models/test_vision_transformer.py
+++ b/tests/models/test_vision_transformer.py
@@ -17,6 +17,7 @@
import pytest
import torch
+from torch import nn
from kornia.models.vit import VisionTransformer
@@ -60,16 +61,79 @@ class TestVisionTransformer(BaseTester):
with pytest.raises(ValueError):
VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)
+ @pytest.mark.parametrize(
+ "shape",
+ [(1, 3, 112, 448), (1, 3, 224, 239), (1, 3, 239, 224), (1, 3, 224, 240), (1, 3, 240, 240), (1, 1, 224, 224)],
+ ids=["7x28-grid", "224x239", "239x224", "224x240", "240x240", "one-channel"],
+ )
+ def test_forward_rejects_other_sizes(self, device, dtype, shape):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ vit = VisionTransformer(image_size=224, patch_size=16, depth=1).to(device, dtype)
+ assert vit(torch.rand(1, 3, 224, 224, device=device, dtype=dtype)).shape == (1, 197, 768)
+
+ # The position table holds (224 // 16) ** 2 + 1 = 197 rows. A 112 x 448 image has a 7 x 28 grid of
+ # 196 = 14 * 14 patches, and 224 x 239 and 239 x 224 a 14 x 14 grid (the last 239 - 14 * 16 = 15 columns or
+ # rows dropped), so these fit the table; 224 x 240 (14 x 15 + 1 = 211 tokens), 240 x 240 (15 x 15 + 1 = 226)
+ # and one channel do not. 224 x 239 and 239 x 224 have one side right, so the check must test both.
+ with pytest.raises(ValueError, match="224"):
+ vit(torch.rand(shape, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("with_backbone", [False, True], ids=["patches", "adaptive-backbone"])
+ def test_dynamo_fullgraph(self, device, dtype, torch_optimizer, with_backbone):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # The size and token-grid checks read static shapes: they must compile without a graph break. The adaptive
+ # backbone gives its 2 x 2 grid for the 32 x 64 input as well.
+ backbone = nn.Sequential(nn.Conv2d(3, 64, 16, 16), nn.AdaptiveAvgPool2d((2, 2))) if with_backbone else None
+ vit = VisionTransformer(image_size=32, patch_size=16, embed_dim=64, depth=1, num_heads=2, backbone=backbone)
+ vit = vit.to(device, dtype).eval()
+ img = torch.rand(2, 3, 32, 64 if with_backbone else 32, device=device, dtype=dtype)
+
+ vit_optimized = torch_optimizer(vit, fullgraph=True)
+
+ # Inductor keeps fused half-precision intermediates in float32 where eager rounds every op: on the CPU in
+ # bfloat16, one of the 640 outputs differs from eager by 0.031, two bfloat16 steps at its value of 2.9.
+ low_tolerance = dtype in (torch.float16, torch.bfloat16)
+ with torch.no_grad():
+ self.assert_close(vit_optimized(img), vit(img), low_tolerance=low_tolerance)
+
def test_backbone(self, device, dtype):
def backbone_mock(x):
return torch.ones(1, 128, 14, 14, device=device, dtype=dtype)
+ # The mock gives its 14 x 14 grid, the one the position table is built for, whatever the input size.
img = torch.rand(1, 3, 32, 32, device=device, dtype=dtype)
vit = VisionTransformer(backbone=backbone_mock, num_heads=8).to(device, dtype)
out = vit(img)
assert out.shape == (1, 197, 128)
assert len(vit.encoder_results) == 12
+ @pytest.mark.parametrize("size", [(224, 224), (256, 256), (448, 448), (224, 448), (192, 320), (112, 448)])
+ def test_adaptive_backbone_takes_other_sizes(self, device, dtype, size):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ if device.type == "mps" and any((side // 16) % 14 for side in size):
+ pytest.skip("MPS adaptive pooling needs a grid divisible by its output size (pytorch/pytorch#96056)")
+ # Adaptive pooling gives the 14 x 14 grid of a 224 input at every size, so the positions match the tokens.
+ backbone = nn.Sequential(nn.Conv2d(3, 64, 16, 16), nn.AdaptiveAvgPool2d((14, 14)))
+ vit = VisionTransformer(image_size=224, num_heads=4, depth=1, backbone=backbone).to(device, dtype)
+
+ assert vit(torch.rand(1, 3, *size, device=device, dtype=dtype)).shape == (1, 197, 64)
+
+ @pytest.mark.parametrize("size", [(112, 448), (240, 240)], ids=["7x28-grid", "15x15-grid"])
+ def test_backbone_rejects_other_token_grids(self, device, dtype, size):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # A stride-16 backbone gives the 14 x 14 grid only for a 224 input. 112 x 448 gives 7 x 28, 196 tokens that
+ # fit the table with misplaced positions, and 240 x 240 gives 15 x 15.
+ vit = VisionTransformer(image_size=224, num_heads=4, depth=1, backbone=nn.Conv2d(3, 64, 16, 16))
+ vit = vit.to(device, dtype)
+ assert vit(torch.rand(1, 3, 224, 224, device=device, dtype=dtype)).shape == (1, 197, 64)
+
+ with pytest.raises(ValueError, match="14x14"):
+ vit(torch.rand(1, 3, *size, device=device, dtype=dtype))
+
@pytest.mark.device_agnostic
def test_from_config_pretrained(self):
# vit_s/32 is the checkpoint whose Hub repository does not follow the URL pattern (#5226).