Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(models)!: implement the Qwen2.5-VL vision tower in kornia.models.qwen25 (#6025)

Parman Mohammadalizadeh4ca00bf5065a
diff --git a/changelog.d/6025.added.md b/changelog.d/6025.added.md
new file mode 100644
index 000000000..36966052d
--- /dev/null
+++ b/changelog.d/6025.added.md
@@ -0,0 +1,7 @@
+`kornia.models.qwen25.Qwen25VisionTransformer` and `Qwen25VisionConfig`, the Qwen2.5-VL vision tower: a
+temporal patch embedding, a 2D rotary position embedding, RMS-normalized blocks with gated MLPs, windowed
+attention with full attention in selected blocks, and the 2 x 2 patch merger. `from_pretrained` strictly
+loads the `visual.*` tensors of a Qwen2.5-VL checkpoint from a local file or directory. On the released
+3B weights it matches Hugging Face `transformers` v4.51.0 on the same preprocessed patches.
+`kornia.core.load_safetensors` gains an `include` predicate that copies only the selected tensors out of
+the file, so a vision tower can be read from a shard it shares with a language model. Closes #6003.
diff --git a/changelog.d/6025.breaking.md b/changelog.d/6025.breaking.md
new file mode 100644
index 000000000..83f65561c
--- /dev/null
+++ b/changelog.d/6025.breaking.md
@@ -0,0 +1 @@
+`kornia.models.qwen25.Qwen2VLVisionTransformer` and the `kornia.models.qwen25.qwen2_vl` module with its blocks (`Qwen2VLPatchMerger`, `Qwen2VLRotaryEmbedding`, `Qwen2VLVisionAttention`, `Qwen2VLMLP`, `Qwen2VLVisionBlock`) are removed, so importing them now raises `ImportError`. They shipped in v0.8.3 and v0.9.0rc1 as a randomly initialised placeholder that was not the Qwen2.5-VL architecture (a plain ViT with a Conv2d patch embedding, LayerNorm, global attention and no positional information), and no weights existed for them. Use `kornia.models.qwen25.Qwen25VisionTransformer`, which takes a `Qwen25VisionConfig` and loads the released Qwen2.5-VL checkpoints.
diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.py
index 7a8f91ad8..967062f2a 100644
--- a/docs/export_support/cases_models.py
+++ b/docs/export_support/cases_models.py
@@ -730,7 +730,7 @@ A(
# ============================================================================= VLM re-implementations (pure PyTorch)
from kornia.models.kimi_vl import KimiVLConfig, KimiVLModel, KimiVLProjectorConfig, MoonViT, MoonViTConfig # noqa: E402
from kornia.models.paligemma import PaliGemma, PaliGemmaConfig # noqa: E402
-from kornia.models.qwen25 import Qwen2VLVisionTransformer # noqa: E402
+from kornia.models.qwen25 import Qwen25VisionConfig, Qwen25VisionTransformer # noqa: E402
from kornia.models.siglip2 import SigLip2Config, SigLip2ImagePreprocessor, SigLip2Model # noqa: E402
from kornia.models.siglip2.config import SigLip2TextConfig, SigLip2VisionConfig # noqa: E402
from kornia.models.smolvlm2 import SmolVLM2 # noqa: E402
@@ -851,12 +851,24 @@ A(
)
A(
mcase(
- "models.qwen25.Qwen2VLVisionTransformer[tiny,random]",
+ "models.qwen25.Qwen25VisionTransformer[tiny,random]",
"models.vlm",
- lambda: ev(Qwen2VLVisionTransformer(embed_dim=32, depth=1, num_heads=2)),
+ lambda: ev(
+ Qwen25VisionTransformer(
+ Qwen25VisionConfig(
+ depth=2,
+ hidden_size=32,
+ intermediate_size=48,
+ num_heads=2,
+ out_hidden_size=16,
+ window_size=56,
+ fullatt_block_indexes=(1,),
+ )
+ )
+ ),
lambda m: m,
- [torch.rand(1, 3, 28, 42)],
- note="pure-PyTorch skeleton; conv14 patch embed + rotary attention blocks",
+ [torch.rand(1, 3, 112, 84)],
+ note="pure-PyTorch Qwen2.5-VL tower; conv3d patch embed, 2D RoPE, windowed + full attention, 2x2 merger",
tags=("model",),
)
)
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index b6bf3786f..1375554e5 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -21392,11 +21392,11 @@
"export": "ok",
"export_detail": "",
"graph_breaks": 0,
- "name": "models.qwen25.Qwen2VLVisionTransformer[tiny,random]",
- "note": "pure-PyTorch skeleton; conv14 patch embed + rotary attention blocks",
+ "name": "models.qwen25.Qwen25VisionTransformer[tiny,random]",
+ "note": "pure-PyTorch Qwen2.5-VL tower; conv3d patch embed, 2D RoPE, windowed + full attention, 2x2 merger",
"onnx": "ok",
"onnx_detail": "",
- "operator": "qwen25.Qwen2VLVisionTransformer",
+ "operator": "qwen25.Qwen25VisionTransformer",
"package": "kornia.models",
"ref": "",
"section": "vlm",
diff --git a/docs/source/models.rst b/docs/source/models.rst
index 801a230cc..cb3bc3661 100644
--- a/docs/source/models.rst
+++ b/docs/source/models.rst
@@ -191,6 +191,29 @@ loading currently supports only the converted Kimi-VL-A3B-Instruct vision encode
model = KimiVLBuilder.from_pretrained_hf().eval()
+.. _Qwen25VisionTransformer:
+
+Qwen25VisionTransformer
+-----------------------
+
+The `Qwen25VisionTransformer` class is the vision tower of Qwen2.5-VL. It takes a batched ``(B, 3, H, W)`` image,
+with ``H`` and ``W`` multiples of 28, already normalized with the CLIP mean and std the checkpoint's
+``preprocessor_config.json`` names, and returns the merged vision tokens. kornia does not host the weights:
+`from_pretrained` reads the ``visual.*`` tensors of a Qwen2.5-VL checkpoint you downloaded yourself.
+
+.. autoclass:: kornia.models.qwen25.Qwen25VisionTransformer
+ :members: forward, from_pretrained
+
+ .. rubric:: Example
+
+ .. code-block:: python
+
+ from kornia.models.qwen25 import Qwen25VisionTransformer
+
+ model = Qwen25VisionTransformer.from_pretrained("path/to/Qwen2.5-VL-3B-Instruct")
+
+.. autoclass:: kornia.models.qwen25.Qwen25VisionConfig
+
----
.. note::
diff --git a/kornia/core/safetensors.py b/kornia/core/safetensors.py
index f39ddf6d5..fe75a6c34 100644
--- a/kornia/core/safetensors.py
+++ b/kornia/core/safetensors.py
@@ -29,7 +29,7 @@ import json
import mmap
import os
import reprlib
-from collections.abc import Iterable
+from collections.abc import Callable, Iterable
from typing import Any, BinaryIO, NamedTuple
import torch
@@ -352,7 +352,11 @@ def _read_and_check_header(path: str, f: BinaryIO) -> tuple[dict[str, _TensorEnt
return parsed, data_start
-def load_safetensors(path: str | os.PathLike[str], device: str | torch.device = "cpu") -> dict[str, torch.Tensor]:
+def load_safetensors(
+ path: str | os.PathLike[str],
+ device: str | torch.device = "cpu",
+ include: Callable[[str], bool] | None = None,
+) -> dict[str, torch.Tensor]:
"""Load a ``.safetensors`` checkpoint into a state dict.
A pure-torch reader for the format described at
@@ -373,6 +377,9 @@ def load_safetensors(path: str | os.PathLike[str], device: str | torch.device =
Args:
path: the checkpoint to read.
device: the device the returned tensors are placed on.
+ include: if given, only the tensors whose name it returns ``True`` for
+ are copied out of the file. The whole header is still validated, so a
+ corrupt entry is rejected even when it is not selected.
Returns:
The state dict, in the order the header lists it.
@@ -398,6 +405,8 @@ def load_safetensors(path: str | os.PathLike[str], device: str | torch.device =
# offsets: the byte buffer starts at ``data_start``.
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY) as buf:
for name, (dtype, shape, start, _, numel) in parsed.items():
+ if include is not None and not include(name):
+ continue
if numel == 0:
# ``torch.frombuffer`` rejects a count of 0, and an empty
# tensor stores no bytes to point at anyway.
diff --git a/kornia/models/qwen25/__init__.py b/kornia/models/qwen25/__init__.py
index 4372947bd..c109daec7 100644
--- a/kornia/models/qwen25/__init__.py
+++ b/kornia/models/qwen25/__init__.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
-from .qwen2_vl import Qwen2VLVisionTransformer
+from .config import Qwen25VisionConfig
+from .vision import Qwen25VisionTransformer
-__all__ = ["Qwen2VLVisionTransformer"]
+__all__ = ["Qwen25VisionConfig", "Qwen25VisionTransformer"]
diff --git a/kornia/models/qwen25/config.py b/kornia/models/qwen25/config.py
new file mode 100644
index 000000000..2c79a7728
--- /dev/null
+++ b/kornia/models/qwen25/config.py
@@ -0,0 +1,77 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Tuple
+
+
+@dataclass
+class Qwen25VisionConfig:
+ """Configuration for the Qwen2.5-VL vision tower.
+
+ The defaults are the ``vision_config`` of the released
+ `Qwen/Qwen2.5-VL-3B-Instruct <https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct/blob/main/config.json>`_
+ checkpoint. The 7B release differs only in ``out_hidden_size`` (3584); the 32B and 72B releases also use
+ ``intermediate_size`` 3456, with ``out_hidden_size`` 5120 and 8192.
+
+ Args:
+ depth: Number of transformer blocks.
+ hidden_size: Token dimension inside the blocks.
+ intermediate_size: Hidden dimension of the gated MLP in each block.
+ num_heads: Number of attention heads.
+ in_channels: Number of input image channels.
+ patch_size: Spatial size of a patch, in pixels.
+ temporal_patch_size: Number of frames one patch spans. A still image is
+ repeated this many times, as the reference image processor does.
+ spatial_merge_size: Side of the square of neighbouring patches the
+ merger concatenates into one output token.
+ window_size: Side of the attention window, in pixels.
+ fullatt_block_indexes: Blocks that attend over the whole image rather
+ than within a window.
+ out_hidden_size: Dimension of the output tokens.
+ rms_norm_eps: Epsilon of the RMS normalizations.
+ rope_theta: Base of the rotary position embedding frequencies.
+ """
+
+ depth: int = 32
+ hidden_size: int = 1280
+ intermediate_size: int = 3420
+ num_heads: int = 16
+ in_channels: int = 3
+ patch_size: int = 14
+ temporal_patch_size: int = 2
+ spatial_merge_size: int = 2
+ window_size: int = 112
+ fullatt_block_indexes: Tuple[int, ...] = (7, 15, 23, 31)
+ out_hidden_size: int = 2048
+ rms_norm_eps: float = 1e-6
+ rope_theta: float = 10000.0
+
+ def __post_init__(self) -> None:
+ if self.hidden_size % self.num_heads != 0:
+ raise ValueError(f"hidden_size ({self.hidden_size}) must be divisible by num_heads ({self.num_heads}).")
+ head_dim = self.hidden_size // self.num_heads
+ if head_dim % 4 != 0:
+ raise ValueError(f"The head dimension ({head_dim}) must be divisible by 4 for the 2D rotary embedding.")
+ merged_patch = self.patch_size * self.spatial_merge_size
+ if self.window_size % merged_patch != 0:
+ raise ValueError(
+ f"window_size ({self.window_size}) must be a multiple of patch_size * spatial_merge_size "
+ f"({merged_patch})."
+ )
diff --git a/kornia/models/qwen25/qwen2_vl.py b/kornia/models/qwen25/qwen2_vl.py
deleted file mode 100644
index e5b7760da..000000000
--- a/kornia/models/qwen25/qwen2_vl.py
+++ /dev/null
@@ -1,242 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-from typing import Optional
-
-import torch
-import torch.nn.functional as F
-from torch import Tensor, nn
-from torch.nn import Module
-
-
-class Qwen2VLPatchMerger(Module):
- """Patch merger block used in the Qwen2-VL vision encoder.
-
- Args:
- dim: The output embedding dimension (e.g., 1280).
- context_window: The context window size (unused in this skeleton but kept for API).
- spatial_merge_size: The spatial merge size (unused in this skeleton).
- """
-
- def __init__(self, dim: int, context_window: int = 224, spatial_merge_size: int = 2) -> None:
- super().__init__()
- self.conv = nn.Conv2d(3, dim, kernel_size=14, stride=14)
- self.ln_q = nn.LayerNorm(dim, eps=1e-6)
-
- def forward(self, x: Tensor) -> Tensor:
- """Convert an image batch into Qwen2-VL patch tokens.
-
- Args:
- x: Image tensor with shape :math:`(B, 3, H, W)`.
-
- Returns:
- Token tensor with shape :math:`(B, N, D)`, where :math:`N` is the
- number of extracted patches and :math:`D` is ``dim``.
- """
- x = self.conv(x)
- x = x.flatten(2)
- x = x.transpose(1, 2)
- return self.ln_q(x)
-
-
-class Qwen2VLRotaryEmbedding(Module):
- """Rotary positional embedding module used in Qwen2-VL vision-language layers.
-
- This module precomputes the inverse frequency spectrum required to build
- rotary position embeddings (RoPE) for a given hidden dimension. The
- frequencies are used to rotate query and key vectors in the attention mechanism,
- encoding relative position information.
-
- Args:
- dim: The feature dimension to be rotated.
- theta: The base frequency scaling factor for the rotary embedding.
- """
-
- def __init__(self, dim: int, theta: float = 10000.0) -> None:
- super().__init__()
- self.dim = dim
- self.theta = theta
-
- inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
- self.register_buffer("inv_freq", inv_freq, persistent=False)
-
- def forward(self, x: Tensor, cu_seqlens: Optional[Tensor] = None) -> Tensor:
- """Return rotary-position input unchanged for this lightweight module.
-
- Args:
- x: Token tensor that would receive rotary position information.
- cu_seqlens: Optional cumulative sequence lengths kept for API
- compatibility with Qwen2-VL implementations.
-
- Returns:
- The input tensor ``x`` unchanged.
- """
- return x
-
-
-class Qwen2VLVisionAttention(Module):
- """Multi-head self-attention module used in the Qwen2-VL vision encoder.
-
- Args:
- dim: Input feature dimension.
- num_heads: Number of attention heads.
- """
-
- def __init__(self, dim: int, num_heads: int = 16) -> None:
- super().__init__()
- self.num_heads = num_heads
- self.head_dim = dim // num_heads
- self.scale = self.head_dim**-0.5
-
- self.qkv = nn.Linear(dim, dim * 3, bias=True)
- self.proj = nn.Linear(dim, dim, bias=True)
-
- def forward(self, x: Tensor, cu_seqlens: Optional[Tensor] = None, rot_pos_emb: Optional[Tensor] = None) -> Tensor:
- """Apply multi-head self-attention to vision tokens.
-
- Args:
- x: Token tensor with shape :math:`(B, N, D)`.
- cu_seqlens: Optional cumulative sequence lengths kept for API
- compatibility.
- rot_pos_emb: Optional rotary positional embedding tensor.
-
- Returns:
- Tensor with shape :math:`(B, N, D)` after attention and output
- projection.
- """
- B, N, C = x.shape
- qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
- q, k, v = qkv[0], qkv[1], qkv[2]
-
- x = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0)
-
- x = x.transpose(1, 2).reshape(B, N, C)
- return self.proj(x)
-
-
-class Qwen2VLMLP(Module):
- """FeedForward MLP used in the Qwen2-VL vision transformer blocks.
-
- Args:
- dim: Input and output feature dimension.
- hidden_dim: Dimension of the hidden layer. If None, defaults to 4 * dim.
- """
-
- def __init__(self, dim: int, hidden_dim: Optional[int] = None) -> None:
- super().__init__()
- if hidden_dim is None:
- hidden_dim = 4 * dim
-
- self.fc1 = nn.Linear(dim, hidden_dim)
- self.act = nn.GELU()
- self.fc2 = nn.Linear(hidden_dim, dim)
-
- def forward(self, x: Tensor) -> Tensor:
- """Apply the Qwen2-VL vision feed-forward network.
-
- Args:
- x: Token tensor with shape :math:`(B, N, D)`.
-
- Returns:
- Tensor with shape :math:`(B, N, D)` after expansion, GELU
- activation, and projection.
- """
- return self.fc2(self.act(self.fc1(x)))
-
-
-class Qwen2VLVisionBlock(Module):
- """Single transformer block for the Qwen2-VL vision encoder.
-
- Applies layer-normalized self-attention followed by an MLP, each with
- residual connections.
-
- Args:
- dim: Token embedding dimension.
- num_heads: Number of attention heads.
- mlp_ratio: MLP hidden dimension multiplier.
- """
-
- def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0) -> None:
- super().__init__()
- self.norm1 = nn.LayerNorm(dim, eps=1e-6)
- self.attn = Qwen2VLVisionAttention(dim, num_heads=num_heads)
-
- self.norm2 = nn.LayerNorm(dim, eps=1e-6)
- self.mlp = Qwen2VLMLP(dim, int(dim * mlp_ratio))
-
- def forward(self, x: Tensor, rot_pos_emb: Optional[Tensor] = None) -> Tensor:
- """Run one Qwen2-VL vision transformer block.
-
- Args:
- x: Vision token tensor with shape :math:`(B, N, D)`.
- rot_pos_emb: Optional rotary positional embedding passed to the
- attention layer.
-
- Returns:
- Tensor with shape :math:`(B, N, D)` after attention, MLP, and
- residual connections.
- """
- x = x + self.attn(self.norm1(x), rot_pos_emb=rot_pos_emb)
- return x + self.mlp(self.norm2(x))
-
-
-class Qwen2VLVisionTransformer(Module):
- """PyTorch implementation of the Qwen2-VL vision encoder.
-
- A ViT-style backbone composed of a patch merger followed by stacked
- transformer blocks with rotary positional embeddings.
-
- Args:
- embed_dim: Embedding dimension.
- depth: Number of transformer blocks.
- num_heads: Number of attention heads.
- mlp_ratio: MLP expansion ratio.
- patch_size: Patch size.
- in_channels: Input channel count.
- """
-
- def __init__(
- self,
- embed_dim: int = 1280,
- depth: int = 32,
- num_heads: int = 16,
- mlp_ratio: float = 4.0,
- in_channels: int = 3,
- ) -> None:
- super().__init__()
- self.patch_embed = Qwen2VLPatchMerger(embed_dim, context_window=224, spatial_merge_size=2)
- self.blocks = nn.ModuleList([Qwen2VLVisionBlock(embed_dim, num_heads, mlp_ratio) for _ in range(depth)])
- self.rotary_pos_emb = Qwen2VLRotaryEmbedding(embed_dim // num_heads)
-
- def forward(self, x: Tensor) -> Tensor:
- """Encode an image batch into Qwen2-VL vision tokens.
-
- Args:
- x: Image tensor with shape :math:`(B, 3, H, W)`.
-
- Returns:
- Token tensor with shape :math:`(B, N, D)` after patch embedding and
- the configured stack of vision transformer blocks.
- """
- x = self.patch_embed(x)
- rot_pos_emb = self.rotary_pos_emb(x)
- for block in self.blocks:
- x = block(x, rot_pos_emb=rot_pos_emb)
-
- return x
diff --git a/kornia/models/qwen25/vision.py b/kornia/models/qwen25/vision.py
new file mode 100644
index 000000000..5ca219c34
--- /dev/null
+++ b/kornia/models/qwen25/vision.py
@@ -0,0 +1,373 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Qwen2.5-VL vision tower.
+
+A port of ``Qwen2_5_VisionTransformerPretrainedModel`` from Hugging Face ``transformers``
+(``models/qwen2_5_vl/modeling_qwen2_5_vl.py``, v4.51.0), taking a batch of images instead of the
+flattened patches and ``grid_thw`` its image processor produces.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from typing import Optional, Tuple
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from kornia.core.safetensors import load_safetensors
+
+from .config import Qwen25VisionConfig
+
+__all__ = ["Qwen25VisionTransformer"]
+
+_WEIGHTS_PREFIX = "visual."
+
+
+def _compute_dtype(dtype: torch.dtype) -> torch.dtype:
+ """Return the dtype the normalizations and rotary embedding run in: float32, or float64 for float64 inputs."""
+ return torch.float64 if dtype == torch.float64 else torch.float32
+
+
+def _merge_order(grid: torch.Tensor, merge_size: int) -> torch.Tensor:
+ """Flatten a ``(gh, gw)`` patch grid so each ``merge_size`` x ``merge_size`` square is contiguous.
+
+ This is the token order of the reference image processor: merged cells in raster order, and the
+ patches of one cell in raster order within it.
+ """
+ gh, gw = grid.shape
+ return grid.reshape(gh // merge_size, merge_size, gw // merge_size, merge_size).permute(0, 2, 1, 3).flatten()
+
+
+def _rotate_half(x: torch.Tensor) -> torch.Tensor:
+ x1, x2 = x.chunk(2, dim=-1)
+ return torch.cat((-x2, x1), dim=-1)
+
+
+class Qwen25RMSNorm(nn.Module):
+ """Root mean square normalization, computed in at least float32.
+
+ Args:
+ dim: Size of the normalized last dimension.
+ eps: Value added to the mean square for numerical stability.
+ """
+
+ def __init__(self, dim: int, eps: float = 1e-6) -> None:
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(dim))
+ self.eps = eps
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Normalize ``x`` over its last dimension.
+
+ Args:
+ x: Tensor with shape :math:`(*, D)`.
+
+ Returns:
+ Tensor with the shape and dtype of ``x``.
+ """
+ h = x.to(_compute_dtype(x.dtype))
+ h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + self.eps)
+ return self.weight * h.to(x.dtype)
+
+
+class Qwen25VisionPatchEmbed(nn.Module):
+ """Patch embedding with a temporal kernel, applied to a still image repeated over time.
+
+ Args:
+ config: Vision tower configuration.
+ """
+
+ def __init__(self, config: Qwen25VisionConfig) -> None:
+ super().__init__()
+ self.temporal_patch_size = config.temporal_patch_size
+ self.merge_size = config.spatial_merge_size
+ kernel = (config.temporal_patch_size, config.patch_size, config.patch_size)
+ self.proj = nn.Conv3d(config.in_channels, config.hidden_size, kernel_size=kernel, stride=kernel, bias=False)
+
+ def forward(self, images: torch.Tensor) -> torch.Tensor:
+ """Embed every patch of ``images``.
+
+ Args:
+ images: Image tensor with shape :math:`(B, C, H, W)`.
+
+ Returns:
+ Patch tokens with shape :math:`(B, N, D)` in merge order, where :math:`N` is the number of patches.
+ """
+ frames = images.unsqueeze(2).expand(-1, -1, self.temporal_patch_size, -1, -1)
+ x = self.proj(frames).squeeze(2)
+ b, d, gh, gw = x.shape
+ m = self.merge_size
+ x = x.reshape(b, d, gh // m, m, gw // m, m).permute(0, 2, 4, 3, 5, 1)
+ return x.reshape(b, gh * gw, d)
+
+
+class Qwen25VisionAttention(nn.Module):
+ """Multi-head self-attention with a 2D rotary embedding on queries and keys.
+
+ Args:
+ dim: Token dimension.
+ num_heads: Number of attention heads.
+ """
+
+ def __init__(self, dim: int, num_heads: int) -> None:
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
+ self.proj = nn.Linear(dim, dim, bias=True)
+
+ def forward(
+ self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ """Attend over the tokens of each image.
+
+ Args:
+ x: Tokens with shape :math:`(B, N, D)`.
+ cos: Rotary cosine table with shape :math:`(N, D / H)`.
+ sin: Rotary sine table with shape :math:`(N, D / H)`.
+ attn_mask: Optional boolean mask with shape :math:`(N, N)`, ``True`` where attention is allowed.
+
+ Returns:
+ Tokens with shape :math:`(B, N, D)`.
+ """
+ b, n, d = x.shape
+ q, k, v = self.qkv(x).reshape(b, n, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4).unbind(0)
+ compute_dtype = _compute_dtype(x.dtype)
+ qf, kf = q.to(compute_dtype), k.to(compute_dtype)
+ q = (qf * cos + _rotate_half(qf) * sin).to(x.dtype)
+ k = (kf * cos + _rotate_half(kf) * sin).to(x.dtype)
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
+ return self.proj(out.transpose(1, 2).reshape(b, n, d))
+
+
+class Qwen25VisionMLP(nn.Module):
+ """Gated feed-forward network, ``down_proj(silu(gate_proj(x)) * up_proj(x))``.
+
+ Args:
+ dim: Token dimension.
+ hidden_dim: Hidden dimension.
+ """
+
+ def __init__(self, dim: int, hidden_dim: int) -> None:
+ super().__init__()
+ self.gate_proj = nn.Linear(dim, hidden_dim, bias=True)
+ self.up_proj = nn.Linear(dim, hidden_dim, bias=True)
+ self.down_proj = nn.Linear(hidden_dim, dim, bias=True)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply the gated MLP.
+
+ Args:
+ x: Tokens with shape :math:`(B, N, D)`.
+
+ Returns:
+ Tokens with shape :math:`(B, N, D)`.
+ """
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
+
+
+class Qwen25VisionBlock(nn.Module):
+ """Pre-norm transformer block of the Qwen2.5-VL vision tower.
+
+ Args:
+ config: Vision tower configuration.
+ """
+
+ def __init__(self, config: Qwen25VisionConfig) -> None:
+ super().__init__()
+ self.norm1 = Qwen25RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.norm2 = Qwen25RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.attn = Qwen25VisionAttention(config.hidden_size, config.num_heads)
+ self.mlp = Qwen25VisionMLP(config.hidden_size, config.intermediate_size)
+
+ def forward(
+ self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ """Run one block.
+
+ Args:
+ x: Tokens with shape :math:`(B, N, D)`.
+ cos: Rotary cosine table with shape :math:`(N, D / H)`.
+ sin: Rotary sine table with shape :math:`(N, D / H)`.
+ attn_mask: Optional boolean attention mask with shape :math:`(N, N)`.
+
+ Returns:
+ Tokens with shape :math:`(B, N, D)`.
+ """
+ x = x + self.attn(self.norm1(x), cos, sin, attn_mask)
+ return x + self.mlp(self.norm2(x))
+
+
+class Qwen25VisionPatchMerger(nn.Module):
+ """Concatenate each square of neighbouring tokens and project it to the output dimension.
+
+ Args:
+ config: Vision tower configuration.
+ """
+
+ def __init__(self, config: Qwen25VisionConfig) -> None:
+ super().__init__()
+ self.merged_dim = config.hidden_size * config.spatial_merge_size**2
+ self.ln_q = Qwen25RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.mlp = nn.Sequential(
+ nn.Linear(self.merged_dim, self.merged_dim),
+ nn.GELU(),
+ nn.Linear(self.merged_dim, config.out_hidden_size),
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Merge tokens.
+
+ Args:
+ x: Tokens with shape :math:`(B, N, D)` in merge order.
+
+ Returns:
+ Merged tokens with shape :math:`(B, N / s^2, D_{out})`, where :math:`s` is the spatial merge size.
+ """
+ b, n, d = x.shape
+ return self.mlp(self.ln_q(x).reshape(b, n * d // self.merged_dim, self.merged_dim))
+
+
+class Qwen25VisionTransformer(nn.Module):
+ """Vision tower of Qwen2.5-VL.
+
+ A ViT with a temporal patch embedding, a 2D rotary position embedding, RMS-normalized blocks with gated MLPs,
+ attention restricted to windows except in ``config.fullatt_block_indexes``, and a merger that turns every
+ 2 x 2 square of patches into one output token. It follows ``Qwen2_5_VisionTransformerPretrainedModel`` in
+ Hugging Face ``transformers`` v4.51.0, with two differences in interface and none in the result:
+
+ - It takes images rather than flattened patches. Each image is repeated over ``temporal_patch_size`` frames,
+ which is what the reference image processor does for a still image.
+ - Windowed attention uses a mask over tokens kept in place, instead of reordering the tokens into windows and
+ back. Attention with a rotary embedding is unchanged by permuting the tokens, so the output matches.
+
+ The input must already be resized and normalized as the checkpoint's ``preprocessor_config.json`` describes:
+ for the released checkpoints, values in :math:`[0, 1]` normalized with mean ``(0.48145466, 0.4578275,
+ 0.40821073)`` and std ``(0.26862954, 0.26130258, 0.27577711)``.
+
+ Args:
+ config: Vision tower configuration. Defaults to the Qwen2.5-VL-3B-Instruct values.
+
+ Example:
+ >>> config = Qwen25VisionConfig(depth=2, hidden_size=32, intermediate_size=48, num_heads=2,
+ ... out_hidden_size=16, fullatt_block_indexes=(1,))
+ >>> model = Qwen25VisionTransformer(config)
+ >>> model(torch.rand(1, 3, 56, 84)).shape
+ torch.Size([1, 6, 16])
+ """
+
+ def __init__(self, config: Optional[Qwen25VisionConfig] = None) -> None:
+ super().__init__()
+ self.config = config if config is not None else Qwen25VisionConfig()
+ self.patch_embed = Qwen25VisionPatchEmbed(self.config)
+ self.blocks = nn.ModuleList([Qwen25VisionBlock(self.config) for _ in range(self.config.depth)])
+ self.merger = Qwen25VisionPatchMerger(self.config)
+
+ def _rotary_tables(
+ self, gh: int, gw: int, device: torch.device, dtype: torch.dtype
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ cfg = self.config
+ rot_dim = cfg.hidden_size // cfg.num_heads // 2
+ inv_freq = 1.0 / (cfg.rope_theta ** (torch.arange(0, rot_dim, 2, device=device, dtype=dtype) / rot_dim))
+ rows = torch.arange(gh, device=device).unsqueeze(1).expand(gh, gw)
+ cols = torch.arange(gw, device=device).unsqueeze(0).expand(gh, gw)
+ rows = _merge_order(rows, cfg.spatial_merge_size).to(dtype)
+ cols = _merge_order(cols, cfg.spatial_merge_size).to(dtype)
+ angles = torch.cat((rows.unsqueeze(1) * inv_freq, cols.unsqueeze(1) * inv_freq), dim=-1)
+ emb = torch.cat((angles, angles), dim=-1)
+ return emb.cos(), emb.sin()
+
+ def _window_mask(self, gh: int, gw: int, device: torch.device) -> torch.Tensor:
+ cfg = self.config
+ patches_per_window = cfg.window_size // cfg.patch_size
+ windows_w = -(-gw // patches_per_window)
+ row_window = torch.arange(gh, device=device) // patches_per_window
+ col_window = torch.arange(gw, device=device) // patches_per_window
+ window = _merge_order(row_window.unsqueeze(1) * windows_w + col_window.unsqueeze(0), cfg.spatial_merge_size)
+ return window.unsqueeze(1) == window.unsqueeze(0)
+
+ def forward(self, images: torch.Tensor) -> torch.Tensor:
+ """Encode a batch of images into vision tokens.
+
+ Args:
+ images: Normalized images with shape :math:`(B, C, H, W)`. ``H`` and ``W`` must be multiples of
+ ``patch_size * spatial_merge_size`` (28 for the released checkpoints).
+
+ Returns:
+ Tokens with shape :math:`(B, H W / (p s)^2, D_{out})` in raster order over the merged grid, where
+ :math:`p` is the patch size and :math:`s` the spatial merge size.
+ """
+ cfg = self.config
+ if images.ndim != 4 or images.shape[1] != cfg.in_channels:
+ raise ValueError(f"Expected images of shape (B, {cfg.in_channels}, H, W). Got {tuple(images.shape)}.")
+ unit = cfg.patch_size * cfg.spatial_merge_size
+ h, w = images.shape[-2:]
+ if h % unit != 0 or w % unit != 0:
+ raise ValueError(f"Image height and width must be multiples of {unit}. Got {h} x {w}.")
+
+ gh, gw = h // cfg.patch_size, w // cfg.patch_size
+ x = self.patch_embed(images)
+ cos, sin = self._rotary_tables(gh, gw, images.device, _compute_dtype(images.dtype))
+ window_mask = self._window_mask(gh, gw, images.device)
+ for i, block in enumerate(self.blocks):
+ x = block(x, cos, sin, None if i in cfg.fullatt_block_indexes else window_mask)
+ return self.merger(x)
+
+ @classmethod
+ def from_pretrained(
+ cls, path: str | os.PathLike[str], config: Optional[Qwen25VisionConfig] = None
+ ) -> Qwen25VisionTransformer:
+ """Build the tower and load the ``visual.*`` weights of a Qwen2.5-VL checkpoint the user downloaded.
+
+ kornia does not host these weights. Only the vision tensors are read, so the language model in the same
+ shards is never copied into memory. The keys are mapped strictly: a missing or unexpected key raises.
+
+ Args:
+ path: A ``.safetensors`` file, or a checkpoint directory containing ``model.safetensors.index.json``
+ or ``model.safetensors``.
+ config: Configuration matching the checkpoint. Defaults to Qwen2.5-VL-3B-Instruct. The 7B checkpoint
+ needs ``out_hidden_size=3584``; the 32B and 72B checkpoints need ``intermediate_size=3456`` and
+ ``out_hidden_size`` 5120 and 8192.
+
+ Returns:
+ The tower with the checkpoint's weights, in float32 and in evaluation mode.
+ """
+ path = os.fspath(path)
+ if os.path.isdir(path):
+ index_path = os.path.join(path, "model.safetensors.index.json")
+ if os.path.exists(index_path):
+ with open(index_path) as f:
+ weight_map = json.load(f)["weight_map"]
+ shards = sorted({shard for key, shard in weight_map.items() if key.startswith(_WEIGHTS_PREFIX)})
+ else:
+ shards = ["model.safetensors"]
+ files = [os.path.join(path, shard) for shard in shards]
+ else:
+ files = [path]
+
+ state_dict = {}
+ for file in files:
+ tensors = load_safetensors(file, include=lambda name: name.startswith(_WEIGHTS_PREFIX))
+ state_dict.update({name[len(_WEIGHTS_PREFIX) :]: tensor for name, tensor in tensors.items()})
+
+ model = cls(config)
+ model.load_state_dict(state_dict, strict=True)
+ return model.eval()
diff --git a/tests/api_surface_removals.json b/tests/api_surface_removals.json
index 43734ffe1..3350d1ff2 100644
--- a/tests/api_surface_removals.json
+++ b/tests/api_surface_removals.json
@@ -5,6 +5,9 @@
"kornia.contrib.boxmot_tracker": [
"BoxMotTracker"
],
+ "kornia.models.qwen25": [
+ "Qwen2VLVisionTransformer"
+ ],
"kornia.models.sam3": [
"ImageEncoderHiera"
],
diff --git a/tests/core/test_safetensors.py b/tests/core/test_safetensors.py
index 1e8b9ad27..a51171dce 100644
--- a/tests/core/test_safetensors.py
+++ b/tests/core/test_safetensors.py
@@ -138,6 +138,25 @@ class TestLoadSafetensors:
assert "__metadata__" not in load_safetensors(path)
+ def test_include_selects_tensors(self, tmp_path, tensors) -> None:
+ path = _write(tmp_path, _build(tensors))
+
+ loaded = load_safetensors(path, include=lambda name: name in {"scale", "empty"})
+
+ assert list(loaded) == ["scale", "empty"]
+ assert torch.equal(loaded["scale"], tensors["scale"])
+ assert loaded["empty"].shape == tensors["empty"].shape
+
+ def test_include_still_validates_unselected_entries(self, tmp_path) -> None:
+ header = {
+ "kept": {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]},
+ "skipped": {"dtype": "F32", "shape": [2], "data_offsets": [4, 8]},
+ }
+ path = _write(tmp_path, _pack(header, b"\x00" * 8))
+
+ with pytest.raises(ValueError, match="skipped"):
+ load_safetensors(path, include=lambda name: name == "kept")
+
def test_reads_a_path_object(self, tmp_path, tensors) -> None:
path = _write(tmp_path, _build(tensors))
diff --git a/tests/integration/models/test_qwen25.py b/tests/integration/models/test_qwen25.py
new file mode 100644
index 000000000..b17eca944
--- /dev/null
+++ b/tests/integration/models/test_qwen25.py
@@ -0,0 +1,65 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Integration test for the Qwen2.5-VL vision tower on the released weights.
+
+Set ``QWEN25_VL_WEIGHTS_DIR`` to a local copy of ``Qwen/Qwen2.5-VL-3B-Instruct`` holding
+``model.safetensors.index.json`` and the shard with the ``visual.*`` tensors
+(``model-00001-of-00002.safetensors``, 3.98 GB). The test is skipped otherwise.
+"""
+
+import os
+
+import pytest
+import torch
+
+from kornia.models.qwen25 import Qwen25VisionTransformer
+
+from testing.base import assert_close
+
+
+def test_qwen25_vision_official_weights():
+ """Match Hugging Face ``transformers`` v4.51.0 on the released 3B weights.
+
+ The expected values come from ``Qwen2_5_VisionTransformerPretrainedModel`` (eager attention, float32) with
+ the same ``visual.*`` tensors, fed the patches its ``Qwen2VLImageProcessor`` makes from this image with
+ resizing, rescaling and normalization disabled. Over the whole ``(30, 2048)`` output the two agree to 1.1e-4,
+ for values up to 28.2.
+ """
+ weights_dir = os.environ.get("QWEN25_VL_WEIGHTS_DIR")
+ if not weights_dir:
+ pytest.skip("QWEN25_VL_WEIGHTS_DIR is not set")
+ if not os.path.exists(os.path.join(weights_dir, "model.safetensors.index.json")):
+ pytest.skip(f"No model.safetensors.index.json in {weights_dir}")
+
+ model = Qwen25VisionTransformer.from_pretrained(weights_dir).eval()
+
+ # 168 x 140 is 6 x 5 merged cells, so the 4 x 4 windows are uneven along both axes.
+ ys, xs = torch.meshgrid(torch.linspace(-1, 1, 168), torch.linspace(-1, 1, 140), indexing="ij")
+ images = torch.stack([torch.sin(3 * xs + ys), torch.cos(2 * ys - xs), xs * ys]).unsqueeze(0)
+
+ with torch.no_grad():
+ out = model(images)
+
+ expected = torch.tensor(
+ [
+ [-1.641796, -1.128161, 0.735769, 1.44872, -1.607152, 1.058822],
+ [0.157594, -1.174068, 0.210073, -0.051154, -0.719309, 0.046013],
+ ]
+ )
+ assert out.shape == (1, 30, 2048)
+ assert_close(out[0, [0, 29], :6], expected, rtol=1e-3, atol=1e-3)
diff --git a/tests/models/qwen25/test_qwen2_vl.py b/tests/models/qwen25/test_qwen2_vl.py
deleted file mode 100644
index 07389dc35..000000000
--- a/tests/models/qwen25/test_qwen2_vl.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import pytest
-import torch
-
-from kornia.models.qwen25.qwen2_vl import (
- Qwen2VLPatchMerger,
- Qwen2VLVisionTransformer,
-)
-
-
-class TestQwen2VL:
- @pytest.mark.parametrize("batch_size", [1, 2])
- def test_smoke(self, batch_size, device, dtype):
- # smaller model β†’ stable
- model = Qwen2VLVisionTransformer(embed_dim=64, depth=2, num_heads=4).to(device=device, dtype=dtype)
-
- x = torch.randn(batch_size, 3, 112, 112, device=device, dtype=dtype)
-
- output = model(x)
-
- assert output.shape == (batch_size, 64, 64)
-
- def test_gradients(self, device):
- model = Qwen2VLVisionTransformer(embed_dim=64, depth=1, num_heads=4).to(device)
-
- x = torch.randn(1, 3, 112, 112, device=device, requires_grad=True)
- output = model(x)
-
- loss = output.mean()
- loss.backward()
-
- assert x.grad is not None
-
- def test_patch_merger(self, device):
- merger = Qwen2VLPatchMerger(dim=64).to(device)
-
- x = torch.randn(1, 3, 112, 112, device=device)
- output = merger(x)
-
- assert output.shape == (1, 64, 64)
-
- def test_batch_consistency(self, device):
- """Ensure outputs are consistent between batch and single input."""
- model = Qwen2VLVisionTransformer(embed_dim=64, depth=2, num_heads=4).to(device)
-
- x = torch.randn(2, 3, 112, 112, device=device)
-
- out_batch = model(x)
- out_single = model(x[:1])
-
- assert torch.allclose(out_batch[0], out_single[0], atol=1e-5)
diff --git a/tests/models/qwen25/test_vision.py b/tests/models/qwen25/test_vision.py
new file mode 100644
index 000000000..0affc6094
--- /dev/null
+++ b/tests/models/qwen25/test_vision.py
@@ -0,0 +1,256 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import json
+import struct
+from pathlib import Path
+
+import pytest
+import torch
+
+from kornia.models.qwen25 import Qwen25VisionConfig, Qwen25VisionTransformer
+
+from testing.base import BaseTester
+
+
+def _tiny_config(**kwargs) -> Qwen25VisionConfig:
+ # A 56-pixel window is 2 x 2 merged cells, so a 112 x 84 image (4 x 3 cells) has four windows of
+ # unequal size, including the narrow column the reference pads.
+ values = {
+ "depth": 2,
+ "hidden_size": 32,
+ "intermediate_size": 48,
+ "num_heads": 2,
+ "out_hidden_size": 16,
+ "window_size": 56,
+ "fullatt_block_indexes": (1,),
+ }
+ values.update(kwargs)
+ return Qwen25VisionConfig(**values)
+
+
+def _seeded(config: Qwen25VisionConfig, image_size: tuple[int, int] = (112, 84)):
+ """Return a float64 CPU model with every parameter drawn from N(0, 0.2^2), and one input image."""
+ model = Qwen25VisionTransformer(config).double().eval()
+ generator = torch.Generator().manual_seed(0)
+ with torch.no_grad():
+ for param in model.parameters():
+ param.copy_(torch.randn(param.shape, generator=generator, dtype=torch.float64) * 0.2)
+ images = torch.randn(1, 3, *image_size, generator=generator, dtype=torch.float64)
+ return model, images
+
+
+def _save_safetensors(tensors: dict[str, torch.Tensor], path: Path) -> None:
+ """Write float32 tensors as a ``.safetensors`` file, straight from the format specification."""
+ header, blob = {}, b""
+ for name, tensor in tensors.items():
+ payload = tensor.to(torch.float32).contiguous().numpy().tobytes()
+ header[name] = {
+ "dtype": "F32",
+ "shape": list(tensor.shape),
+ "data_offsets": [len(blob), len(blob) + len(payload)],
+ }
+ blob += payload
+ encoded = json.dumps(header).encode("utf-8")
+ path.write_bytes(struct.pack("<Q", len(encoded)) + encoded + blob)
+
+
+class TestQwen25VisionTransformer(BaseTester):
+ @pytest.mark.parametrize("batch_size", [0, 1, 2])
+ def test_smoke(self, batch_size, device, dtype):
+ model = Qwen25VisionTransformer(_tiny_config()).to(device, dtype).eval()
+ images = torch.rand(batch_size, 3, 112, 84, device=device, dtype=dtype)
+
+ with torch.no_grad():
+ out = model(images)
+
+ assert out.shape == (batch_size, 12, 16)
+ assert out.dtype == dtype
+ assert out.device.type == device.type
+
+ @pytest.mark.parametrize(("height", "width", "tokens"), [(28, 28, 1), (56, 84, 6), (112, 168, 24)])
+ def test_cardinality(self, height, width, tokens, device, dtype):
+ model = Qwen25VisionTransformer(_tiny_config()).to(device, dtype).eval()
+
+ with torch.no_grad():
+ out = model(torch.rand(1, 3, height, width, device=device, dtype=dtype))
+
+ assert out.shape == (1, tokens, 16)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 30, 28), (1, 3, 28, 42), (1, 1, 28, 28), (3, 28, 28)])
+ def test_exception_input_shape(self, shape, device, dtype):
+ model = Qwen25VisionTransformer(_tiny_config()).to(device, dtype)
+
+ with pytest.raises(ValueError):
+ model(torch.rand(*shape, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [{"hidden_size": 30, "num_heads": 4}, {"hidden_size": 36, "num_heads": 2}, {"window_size": 42}],
+ )
+ def test_exception_config(self, kwargs):
+ with pytest.raises(ValueError):
+ _tiny_config(**kwargs)
+
+ def test_reference_values(self, device, dtype):
+ """Match Hugging Face ``transformers`` v4.51.0 on a tiny random configuration.
+
+ One token from each of the four windows is pinned, so a token assigned to the wrong window shows up. The
+ expected values were produced by copying the seeded weights below into the reference and feeding it
+ the patches of its own image processor (``max abs diff`` 1.6e-7 over the whole float64 output, the
+ reference running its normalizations and rotary embedding in float32)::
+
+ from transformers import Qwen2VLImageProcessor
+ from transformers.models.qwen2_5_vl.configuration_qwen2_5_vl import Qwen2_5_VLVisionConfig
+ from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VisionTransformerPretrainedModel
+
+ model, images = _seeded(_tiny_config())
+ cfg = Qwen2_5_VLVisionConfig(depth=2, hidden_size=32, intermediate_size=48, num_heads=2,
+ out_hidden_size=16, window_size=56, fullatt_block_indexes=[1],
+ hidden_act="silu")
+ ref = Qwen2_5_VisionTransformerPretrainedModel._from_config(cfg, attn_implementation="eager")
+ ref = ref.double().eval()
+ ref.load_state_dict(model.state_dict(), strict=True)
+ proc = Qwen2VLImageProcessor(do_resize=False, do_rescale=False, do_normalize=False)
+ enc = proc(images=[images[0].numpy()], return_tensors="pt", input_data_format="channels_first")
+ expected = ref(enc["pixel_values"].double(), enc["image_grid_thw"])[[0, 5, 6, 11], :6]
+ """
+ model, images = _seeded(_tiny_config())
+ model = model.to(device, dtype)
+ images = images.to(device, dtype)
+ expected = torch.tensor(
+ [
+ [0.09549037857805515, -0.4318030974107194, -0.2147635769408925, 0.04750012480055123,
+ -0.18701005751370206, 0.8672491593678862],
+ [0.5476752592262668, -0.34546495229155505, -1.1540137094169247, 0.6783189091656767,
+ 0.42628693902281506, 1.4598784556874398],
+ [-1.1210075910373243, 0.4016404669306015, 0.6027981222959102, -0.15521229785229282,
+ 1.025392446425122, 0.9670840563199808],
+ [-0.4691275876673318, -0.4147935590654865, -0.00886787003644618, -0.6345986879315241,
+ 0.8549848277851364, 0.8655891917360579],
+ ],
+ device=device,
+ dtype=dtype,
+ ) # fmt: skip
+
+ with torch.no_grad():
+ out = model(images)
+
+ self.assert_close(out[0, [0, 5, 6, 11], :6], expected, low_tolerance=dtype in (torch.float16, torch.bfloat16))
+
+ def test_patch_swap_is_not_a_token_permutation(self, device, dtype):
+ """Swapping two merged cells must change the tokens, not only reorder them, since positions are encoded.
+
+ Every block attends globally here: windowed attention alone already breaks the permutation, so only the
+ rotary embedding can make this test pass.
+ """
+ model = Qwen25VisionTransformer(_tiny_config(fullatt_block_indexes=(0, 1))).to(device, dtype).eval()
+ images = torch.rand(1, 3, 112, 84, device=device, dtype=dtype)
+ swapped = images.clone()
+ swapped[..., 0:28, 0:28] = images[..., 84:112, 56:84]
+ swapped[..., 84:112, 56:84] = images[..., 0:28, 0:28]
+
+ with torch.no_grad():
+ out = model(images)[0].float()
+ out_swapped = model(swapped)[0].float()
+
+ # Under a pure permutation every swapped token would have an exact twin among the original tokens: with the
+ # rotary embedding removed the largest twin distance is below 1e-6, with it above 4e-3 for every dtype.
+ nearest = torch.cdist(out_swapped, out).min(dim=1).values
+ assert nearest.max() > 1e-4
+
+ def test_windowed_block_is_local(self, device, dtype):
+ """With no full-attention block, a change inside one window leaves the tokens of the other windows alone."""
+ model = Qwen25VisionTransformer(_tiny_config(fullatt_block_indexes=())).to(device, dtype).eval()
+ images = torch.rand(1, 3, 112, 84, device=device, dtype=dtype)
+ changed = images.clone()
+ changed[..., 0:56, 0:56] += 1.0
+
+ with torch.no_grad():
+ out = model(images)[0]
+ out_changed = model(changed)[0]
+
+ # The 4 x 3 merged grid in raster order; the first window covers cells (0, 0), (0, 1), (1, 0), (1, 1).
+ inside = [0, 1, 3, 4]
+ outside = [2, 5, 6, 7, 8, 9, 10, 11]
+ self.assert_close(out_changed[outside], out[outside])
+ assert not torch.allclose(out_changed[inside], out[inside])
+
+ def test_batch_consistency(self, device, dtype):
+ model = Qwen25VisionTransformer(_tiny_config()).to(device, dtype).eval()
+ images = torch.rand(2, 3, 56, 84, device=device, dtype=dtype)
+
+ with torch.no_grad():
+ batched = model(images)
+ single = model(images[1:])
+
+ self.assert_close(batched[1:], single)
+
+ def test_gradcheck(self, device):
+ model = Qwen25VisionTransformer(_tiny_config(depth=1, fullatt_block_indexes=())).to(device, torch.float64)
+ images = torch.rand(1, 3, 56, 56, device=device, dtype=torch.float64)
+
+ self.gradcheck(model, (images,))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ model = Qwen25VisionTransformer(_tiny_config()).to(device, dtype).eval()
+ images = torch.rand(1, 3, 112, 84, device=device, dtype=dtype)
+ model_optimized = torch_optimizer(model)
+
+ with torch.no_grad():
+ expected = model(images)
+ actual = model_optimized(images)
+
+ self.assert_close(actual, expected)
+
+
+class TestQwen25FromPretrained:
+ @pytest.fixture
+ def checkpoint(self, tmp_path):
+ """Write a two-shard checkpoint whose first shard mixes vision and language tensors, like the release."""
+ model, _ = _seeded(_tiny_config())
+ vision = {f"visual.{name}": tensor for name, tensor in model.state_dict().items()}
+ _save_safetensors({**vision, "model.embed_tokens.weight": torch.zeros(4, 8)}, tmp_path / "a.st")
+ _save_safetensors({"lm_head.weight": torch.zeros(4, 8)}, tmp_path / "b.st")
+ weight_map = dict.fromkeys(vision, "a.st")
+ weight_map.update({"model.embed_tokens.weight": "a.st", "lm_head.weight": "b.st"})
+ (tmp_path / "model.safetensors.index.json").write_text(json.dumps({"weight_map": weight_map}))
+ return tmp_path, model
+
+ def test_directory(self, checkpoint):
+ path, model = checkpoint
+
+ loaded = Qwen25VisionTransformer.from_pretrained(path, _tiny_config())
+
+ for name, tensor in model.state_dict().items():
+ assert torch.equal(loaded.state_dict()[name], tensor.float()), name
+ assert not loaded.training
+
+ def test_single_file(self, checkpoint):
+ path, model = checkpoint
+
+ loaded = Qwen25VisionTransformer.from_pretrained(path / "a.st", _tiny_config())
+
+ assert torch.equal(loaded.merger.mlp[2].weight, model.merger.mlp[2].weight.float())
+
+ def test_mismatched_config_raises(self, checkpoint):
+ path, _ = checkpoint
+
+ with pytest.raises(RuntimeError):
+ Qwen25VisionTransformer.from_pretrained(path, _tiny_config(depth=3))