π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(models): batch-16 close-out β figures fed as trained, TinyViT-21M drop path, one DexiNed (#6107)
Dmytro Mishkin01d41275b28b
diff --git a/changelog.d/6107.added.md b/changelog.d/6107.added.mdnew file mode 100644index 000000000..2d9628614--- /dev/null+++ b/changelog.d/6107.added.md@@ -0,0 +1 @@+`kornia.filters.dexined.DexiNed` is now the same class as `kornia.models.dexined.DexiNed`, which that module re-exports with its building blocks, so it gains `to_onnx` and its ONNX declarations. A whole model pickled from `kornia.filters.dexined` still loads, and a newly pickled one is stored under `kornia.models.dexined`.diff --git a/changelog.d/6107.fixed.md b/changelog.d/6107.fixed.mdnew file mode 100644index 000000000..e21d4235d--- /dev/null+++ b/changelog.d/6107.fixed.md@@ -0,0 +1 @@+`TinyViT.from_config("21m", ...)` with the `'in1k_384'` or `'in1k_512'` checkpoint (also reached by `pretrained=True` at `img_size` 384 or more) builds with `drop_path_rate=0.1`, the stochastic depth rate those checkpoints were fine-tuned with (Cream `tiny_vit_21m_384` and `tiny_vit_21m_512`). It used TinyViT-21M's 224-px rate of 0.2. Only training changes: DropPath does nothing in evaluation mode. A `drop_path_rate` argument still overrides the default.diff --git a/docs/generate_model_examples.py b/docs/generate_model_examples.pyindex 37466cc7a..e2e81765f 100644--- a/docs/generate_model_examples.py+++ b/docs/generate_model_examples.py@@ -190,8 +190,10 @@ def figure_efficient_vit() -> None:image = sample("panda.jpg", (224, 224))model = EfficientViT.from_config(EfficientViTConfig.from_pretrained("b1", 224)).eval()+ # the backbones were trained on images normalized with the ImageNet mean and standard deviation+ x = K.enhance.normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225]))with torch.no_grad():- feats = model(image) # dict of feature maps: "input", "stage0" ... "stage_final"+ feats = model(x) # dict of feature maps: "input", "stage0" ... "stage_final"stages = [k for k in feats if k.startswith("stage")]fig, axs = plt.subplots(1, 1 + len(stages), figsize=(2.3 * (1 + len(stages)), 2.6))@@ -214,8 +216,10 @@ def figure_tiny_vit() -> None:image = sample("panda.jpg", (224, 224))model = TinyViT.from_config("5m", pretrained=True).eval() # ImageNet-1k weights+ # the checkpoints were trained on images normalized with the ImageNet mean and standard deviation+ x = K.enhance.normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225]))with torch.no_grad():- logits = model(image) # (1, 1000)+ logits = model(x) # (1, 1000)fig, axs = plt.subplots(1, 2, figsize=(9, 3), width_ratios=[1, 1.6])show(axs[0], image, "input 224x224")@@ -230,8 +234,10 @@ def figure_vit() -> None:image = sample("panda.jpg", (224, 224))vit = VisionTransformer.from_config("vit_b/16", pretrained=True).eval() # AugReg ImageNet-21k weights+ # the AugReg weights were trained on images normalized with mean = std = 0.5, i.e. in [-1, 1]+ x = K.enhance.normalize(image, torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]))with torch.no_grad():- tokens = vit(image) # (1, 197, 768): class token + 14x14 patch tokens+ tokens = vit(x) # (1, 197, 768): class token + 14x14 patch tokensfig, axs = plt.subplots(1, 3, figsize=(11, 3.2), width_ratios=[1, 1, 1.3])show(axs[0], image, "input 224x224 β 14x14 patches of 16 px")diff --git a/docs/source/_static/img/models/efficient_vit.jpg b/docs/source/_static/img/models/efficient_vit.jpgindex 146c479e8..e2ca8f0e5 100644Binary files a/docs/source/_static/img/models/efficient_vit.jpg and b/docs/source/_static/img/models/efficient_vit.jpg differdiff --git a/docs/source/_static/img/models/mobile_sam.jpg b/docs/source/_static/img/models/mobile_sam.jpgindex 7247bd5e5..7b8c37edc 100644Binary files a/docs/source/_static/img/models/mobile_sam.jpg and b/docs/source/_static/img/models/mobile_sam.jpg differdiff --git a/docs/source/_static/img/models/segment_anything.jpg b/docs/source/_static/img/models/segment_anything.jpgindex 0267f04d9..bde6e49c1 100644Binary files a/docs/source/_static/img/models/segment_anything.jpg and b/docs/source/_static/img/models/segment_anything.jpg differdiff --git a/docs/source/_static/img/models/tiny_vit.jpg b/docs/source/_static/img/models/tiny_vit.jpgindex 3becd1e41..ccfca36f0 100644Binary files a/docs/source/_static/img/models/tiny_vit.jpg and b/docs/source/_static/img/models/tiny_vit.jpg differdiff --git a/docs/source/_static/img/models/vit.jpg b/docs/source/_static/img/models/vit.jpgindex 1c6539930..1a9e47e7d 100644Binary files a/docs/source/_static/img/models/vit.jpg and b/docs/source/_static/img/models/vit.jpg differdiff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 56e49778c..862a9078a 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -1287,7 +1287,11 @@ Pretrained models- A model built with complete pretrained weights comes back in evaluation mode (``model.training`` is ``False``).A randomly initialised model stays in PyTorch's default training mode. So does a model whose weights are only partlypretrained, such as a pretrained backbone with a newly initialised classification head. Call ``.train()`` to- fine-tune a pretrained model, and ``.eval()`` before running inference on a random one.+ fine-tune a pretrained model, and ``.eval()`` before running inference on a random one. The ``kornia.feature``+ pipelines are the exception: ``KeyNetDetector``, ``KeyNetHardNet``, ``KeyNetAffNetHardNet``, ``GFTTAffNetHardNet``,+ ``LAFDescriptor`` and ``LightGlueMatcher`` put only their pretrained networks in evaluation mode and report+ ``training`` as ``True`` themselves, so that an ``ori_module`` or ``aff_module`` you pass to ``KeyNetDetector`` keeps+ its own mode (see :ref:`local-features-conventions`).- Constructors, ``from_config``, ``from_pretrained`` and the builders set the mode once, when they build the model.``load_checkpoint`` and ``load_state_dict`` on an existing module leave its mode as it is: after loading your ownweights, call ``.eval()``.diff --git a/docs/source/models/tiny_vit.rst b/docs/source/models/tiny_vit.rstindex f52656b3a..23e6044e0 100644--- a/docs/source/models/tiny_vit.rst+++ b/docs/source/models/tiny_vit.rst@@ -38,7 +38,7 @@ Run it.. figure:: /_static/img/models/tiny_vit.jpg:align: center- :alt: A panda photo next to a bar chart of the five most probable ImageNet classes, with giant panda far ahead.+ :alt: A panda photo next to a bar chart of the five most probable ImageNet classes, with giant panda first.Top-5 ImageNet classes predicted by TinyViT-5M for the input on the left.diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex 0c1e4c4a9..651044f2e 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -15,458 +15,21 @@# limitations under the License.#-# adapted from: https://github.com/xavysp/DexiNed/blob/d944b70eb6eaf40e22f8467c1e12919aa600d8e4/model.py--from __future__ import annotations--import os-from collections import OrderedDict-from typing import ClassVar, Optional--import torch-import torch.nn.functional as F-from torch import nn--from kornia.core.check import KORNIA_CHECK-from kornia.core.download import hf_url, load_state_dict_from_url--url: str | list[str] = [- hf_url("dexined", "DexiNed_BIPED_10.pth"),- "https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",-]---def weight_init(m: nn.Module) -> None:- """Initialize weights."""- if isinstance(m, (nn.Conv2d,)):- # torch.nn.init.xavier_uniform_(m.weight, gain=1.0)- torch.nn.init.xavier_normal_(m.weight, gain=1.0)- # torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)- if m.weight.data.shape[1] == torch.Size([1]):- torch.nn.init.normal_(m.weight, mean=0.0)-- if m.bias is not None:- torch.nn.init.zeros_(m.bias)-- # for fusion layer- if isinstance(m, (nn.ConvTranspose2d,)):- # torch.nn.init.xavier_uniform_(m.weight, gain=1.0)- torch.nn.init.xavier_normal_(m.weight, gain=1.0)- # torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)-- if m.weight.data.shape[1] == torch.Size([1]):- torch.nn.init.normal_(m.weight, std=0.1)- if m.bias is not None:- torch.nn.init.zeros_(m.bias)---class CoFusion(nn.Module):- """Implement the weight-fusion layer for multi-scale edge maps.-- Args:- in_ch: The number of input channels.- out_ch: The number of output channels.- """-- def __init__(self, in_ch: int, out_ch: int) -> None:- super().__init__()- self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)- self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)- self.conv3 = nn.Conv2d(64, out_ch, kernel_size=3, stride=1, padding=1)- self.relu = nn.ReLU()- self.norm_layer1 = nn.GroupNorm(4, 64)- self.norm_layer2 = nn.GroupNorm(4, 64)-- def forward(self, x: torch.Tensor) -> torch.Tensor:- """Fuse side-output edge maps into a single edge response.-- The input contains edge predictions from several depths of the DexiNed- network concatenated along the channel dimension. This block predicts- attention weights from those stacked responses and uses them to combine- the side outputs into one refined edge map.-- Args:- x: Concatenated side-output tensor with shape- :math:`(B, C_{side}, H, W)`, where :math:`B` is the batch size,- :math:`C_{side}` is the number of stacked side-output channels,- :math:`H` is the height, and :math:`W` is the width.-- Returns:- Tensor with shape :math:`(B, 1, H, W)` containing the fused edge- response. Larger values indicate locations that the network- considers more likely to be image boundaries.- """- # fusecat = torch.cat(x, dim=1)- attn = self.relu(self.norm_layer1(self.conv1(x)))- attn = self.relu(self.norm_layer2(self.conv2(attn)))- attn = F.softmax(self.conv3(attn), dim=1)-- # return ((fusecat * attn).sum(1)).unsqueeze(1)- return ((x * attn).sum(1))[:, None, ...]---class _DenseLayer(nn.Sequential):- def __init__(self, input_features: int, out_features: int) -> None:- super().__init__(- OrderedDict(- [- # Out of place: a dense block's input is also read by a side branch, which saved it for backward.- ("relu1", nn.ReLU()),- ("conv1", nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),- ("norm1", nn.BatchNorm2d(out_features)),- ("relu2", nn.ReLU(inplace=True)),- ("conv2", nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),- ("norm2", nn.BatchNorm2d(out_features)),- ]- )- )-- def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]:- x1, x2 = x[0], x[1]- x3: torch.Tensor = x1- for mod in self:- x3 = mod(x3)- return [0.5 * (x3 + x2), x2]---class _DenseBlock(nn.Sequential):- def __init__(self, num_layers: int, input_features: int, out_features: int) -> None:- super().__init__()- for i in range(num_layers):- layer = _DenseLayer(input_features, out_features)- self.add_module(f"denselayer{(i + 1)}", layer)- input_features = out_features-- def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]:- x_out = x- for mod in self:- x_out = mod(x_out)- return x_out---class UpConvBlock(nn.Module):- """Implement an upsampling convolutional block for edge refinement.-- Args:- in_features: The number of input channels.- up_scale: The scale factor for upsampling.- """-- def __init__(self, in_features: int, up_scale: int) -> None:- super().__init__()- self.up_factor = 2- self.constant_features = 16-- layers = self.make_deconv_layers(in_features, up_scale)- KORNIA_CHECK(layers is not None, "layers cannot be none")- self.features = nn.Sequential(*layers)-- def make_deconv_layers(self, in_features: int, up_scale: int) -> nn.ModuleList:- """Build the transposed-convolution stages used by an upsampling branch.-- Each stage reduces or preserves the feature-channel count and increases- the spatial resolution by a factor of two. The final stage emits a- single-channel side-output edge map, while intermediate stages use the- block's constant feature width.-- Args:- in_features: Number of channels in the input feature map entering- the first upsampling stage.- up_scale: Number of progressive upsampling stages to create. A- value of ``0`` means no transposed-convolution stages are added.-- Returns:- ``nn.ModuleList`` containing the convolution, activation, and- transposed-convolution layers that are later wrapped by- ``nn.Sequential`` in ``self.features``.- """- layers = nn.ModuleList([])- all_pads = [0, 0, 1, 3, 7]- for i in range(up_scale):- kernel_size = 2**up_scale- pad = all_pads[up_scale] # kernel_size-1- out_features = self.compute_out_features(i, up_scale)- layers.append(nn.Conv2d(in_features, out_features, 1))- layers.append(nn.ReLU(inplace=True))- layers.append(nn.ConvTranspose2d(out_features, out_features, kernel_size, stride=2, padding=pad))- in_features = out_features- return layers-- def compute_out_features(self, idx: int, up_scale: int) -> int:- """Return the channel count produced by one upsampling stage.-- DexiNed side branches keep a fixed number of channels in intermediate- upsampling stages and collapse to a single edge channel at the end.- This helper centralizes that rule while ``make_deconv_layers`` builds- the branch.-- Args:- idx: Zero-based stage index. ``0`` is the first stage and- ``up_scale - 1`` is the final stage.- up_scale: Total number of upsampling stages in the branch.-- Returns:- ``1`` for the final stage, because the side output is an edge map,- otherwise ``self.constant_features`` for intermediate feature maps.- """- return 1 if idx == up_scale - 1 else self.constant_features-- def forward(self, x: torch.Tensor, out_shape: list[int]) -> torch.Tensor:- """Convert a backbone feature map into an aligned side-output edge map.-- The stored upsampling layers progressively increase the resolution of- ``x``. A final bilinear interpolation aligns the branch output exactly- to ``out_shape`` so that side outputs from different backbone depths can- be concatenated later.-- Args:- x: Feature tensor with shape :math:`(B, C, H_{in}, W_{in})`, where- :math:`B` is the batch size, :math:`C` is the number of input- feature channels, and :math:`H_{in}`, :math:`W_{in}` are the- current feature-map height and width.- out_shape: Target spatial size ``[H, W]`` used for the final- interpolation, where :math:`H` is the desired height and- :math:`W` is the desired width.-- Returns:- Side-output tensor resized to ``out_shape``, typically with shape- :math:`(B, 1, H, W)` for an edge prediction branch.- """- out = self.features(x)- return F.interpolate(out, out_shape, mode="bilinear")---class SingleConvBlock(nn.Module):- """Implement a single convolutional layer with optional Batch Normalization.-- Args:- in_features: The number of input channels.- out_features: The number of output channels.- stride: The stride of the convolution.- use_bs: Whether to use Batch Normalization. Default: True.- """-- def __init__(self, in_features: int, out_features: int, stride: int, use_bs: bool = True) -> None:- super().__init__()- self.use_bn = use_bs- self.conv = nn.Conv2d(in_features, out_features, 1, stride=stride, bias=True)- self.bn = nn.BatchNorm2d(out_features)-- def forward(self, x: torch.Tensor) -> torch.Tensor:- """Project feature channels with a pointwise convolution.-- A ``1x1`` convolution mixes information across channels without- changing the spatial resolution. When ``use_bn`` was enabled during- construction, batch normalization is applied after the projection.-- Args:- x: Feature map tensor with shape :math:`(B, C_{in}, H, W)`, where- :math:`B` is the batch size, :math:`C_{in}` is the number of- input channels, :math:`H` is the height, and :math:`W` is the- width.-- Returns:- Tensor with shape :math:`(B, C_{out}, H, W)`, where- :math:`C_{out}` is the ``out_features`` value configured for this- block.- """- x = self.conv(x)- if self.use_bn:- x = self.bn(x)- return x---class DoubleConvBlock(nn.Sequential):- """Apply two consecutive convolutional blocks for edge feature extraction."""-- def __init__(- self,- in_features: int,- mid_features: int,- out_features: Optional[int] = None,- stride: int = 1,- use_act: bool = True,- ) -> None:- super().__init__()- if out_features is None:- out_features = mid_features- self.add_module("conv1", nn.Conv2d(in_features, mid_features, 3, padding=1, stride=stride))- self.add_module("bn1", nn.BatchNorm2d(mid_features))- self.add_module("relu1", nn.ReLU(inplace=True))- self.add_module("conv2", nn.Conv2d(mid_features, out_features, 3, padding=1))- self.add_module("bn2", nn.BatchNorm2d(out_features))- if use_act:- self.add_module("relu2", nn.ReLU(inplace=True))---class DexiNed(nn.Module):- r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.-- The input is a BGR image with pixel values in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``:- the pretrained weights were trained on images read with ``cv2.imread`` and shifted by that mean- (xavysp/DexiNed@d944b70).-- Return:- The fused edge logits, one tensor with shape :math:`(B,1,H,W)`.-- Example:- >>> img = torch.rand(1, 3, 320, 320)- >>> net = DexiNed(pretrained=False)- >>> out = net(img)- >>> out.shape- torch.Size([1, 1, 320, 320])-- """-- ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]- ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]-- def __init__(self, pretrained: bool) -> None:- super().__init__()- self.block_1 = DoubleConvBlock(3, 32, 64, stride=2)- self.block_2 = DoubleConvBlock(64, 128, use_act=False)- self.dblock_3 = _DenseBlock(2, 128, 256) # [128,256,100,100]- self.dblock_4 = _DenseBlock(3, 256, 512)- self.dblock_5 = _DenseBlock(3, 512, 512)- self.dblock_6 = _DenseBlock(3, 512, 256)- self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)-- # left skip connections, figure in Journal- self.side_1 = SingleConvBlock(64, 128, 2)- self.side_2 = SingleConvBlock(128, 256, 2)- self.side_3 = SingleConvBlock(256, 512, 2)- self.side_4 = SingleConvBlock(512, 512, 1)- self.side_5 = SingleConvBlock(512, 256, 1)-- # right skip connections, figure in Journal paper- self.pre_dense_2 = SingleConvBlock(128, 256, 2)- self.pre_dense_3 = SingleConvBlock(128, 256, 1)- self.pre_dense_4 = SingleConvBlock(256, 512, 1)- self.pre_dense_5 = SingleConvBlock(512, 512, 1)- self.pre_dense_6 = SingleConvBlock(512, 256, 1)-- # USNet- self.up_block_1 = UpConvBlock(64, 1)- self.up_block_2 = UpConvBlock(128, 1)- self.up_block_3 = UpConvBlock(256, 2)- self.up_block_4 = UpConvBlock(512, 3)- self.up_block_5 = UpConvBlock(512, 4)- self.up_block_6 = UpConvBlock(256, 4)- self.block_cat = SingleConvBlock(6, 1, stride=1, use_bs=False) # hed fusion method- # self.block_cat = CoFusion(6,6)# cats fusion method-- if pretrained:- self.load_from_file(url)- else:- self.apply(weight_init)-- def load_from_file(self, path_file: str | list[str]) -> None:- """Load pretrained DexiNed weights and switch the module to eval mode.-- The checkpoint is loaded on CPU and then applied with strict key- matching. After loading, ``eval()`` is called so layers such as batch- normalization use inference behavior.-- Args:- path_file: path of a local checkpoint file, a URL accepted by- :func:`kornia.core.download.load_state_dict_from_url`, or a list- of candidate URLs tried in order (HF-first fallback). A string- naming an existing file (a leading ``~`` is expanded) is read with- :func:`torch.load` and ``weights_only=True``; anything else goes- through the hub cache, which is keyed by base name.- """- local = os.path.expanduser(path_file) if isinstance(path_file, str) else None- if local is not None and os.path.isfile(local):- with open(local, "rb") as f:- pretrained_dict = torch.load(f, map_location=torch.device("cpu"), weights_only=True)- else:- pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))- self.load_state_dict(pretrained_dict, strict=True)- self.eval()-- def get_features(self, x: torch.Tensor) -> list[torch.Tensor]:- """Compute the DexiNed side-output edge maps before final fusion.-- The image is processed through the stacked backbone blocks. Each block- produces a feature map at a different semantic depth and spatial scale;- the corresponding side branch upsamples it back to the original image- resolution. The returned list is later concatenated and fused by- a 1x1 convolution (``block_cat``).-- Args:- x: Input BGR image tensor in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``, with- shape :math:`(B, 3, H, W)`, where :math:`B` is the batch size, :math:`H` is the image height, and- :math:`W` is the image width.-- Returns:- List of six tensors, each aligned to the input spatial size. Every- tensor represents a side-output edge prediction with batch- dimension :math:`B` and spatial dimensions :math:`H` and- :math:`W`.- """- # Block 1- block_1 = self.block_1(x)- block_1_side = self.side_1(block_1)-- # Block 2- block_2 = self.block_2(block_1)- block_2_down = self.maxpool(block_2)- block_2_add = block_2_down + block_1_side- block_2_side = self.side_2(block_2_add)-- # Block 3- block_3_pre_dense = self.pre_dense_3(block_2_down)- block_3, _ = self.dblock_3([block_2_add, block_3_pre_dense])- block_3_down = self.maxpool(block_3) # [128,256,50,50]- block_3_add = block_3_down + block_2_side- block_3_side = self.side_3(block_3_add)-- # Block 4- block_2_resize_half = self.pre_dense_2(block_2_down)- block_4_pre_dense = self.pre_dense_4(block_3_down + block_2_resize_half)- block_4, _ = self.dblock_4([block_3_add, block_4_pre_dense])- block_4_down = self.maxpool(block_4)- block_4_add = block_4_down + block_3_side- block_4_side = self.side_4(block_4_add)-- # Block 5- block_5_pre_dense = self.pre_dense_5(block_4_down) # block_5_pre_dense_512 +block_4_down- block_5, _ = self.dblock_5([block_4_add, block_5_pre_dense])- block_5_add = block_5 + block_4_side-- # Block 6- block_6_pre_dense = self.pre_dense_6(block_5)- block_6, _ = self.dblock_6([block_5_add, block_6_pre_dense])-- # upsampling blocks- out_shape = x.shape[-2:]- out_1 = self.up_block_1(block_1, out_shape)- out_2 = self.up_block_2(block_2, out_shape)- out_3 = self.up_block_3(block_3, out_shape)- out_4 = self.up_block_4(block_4, out_shape)- out_5 = self.up_block_5(block_5, out_shape)- out_6 = self.up_block_6(block_6, out_shape)- return [out_1, out_2, out_3, out_4, out_5, out_6]-- def forward(self, x: torch.Tensor) -> torch.Tensor:- """Predict a fused edge map from a BGR image batch.-- The forward pass collects six multi-scale side outputs, concatenates- them along the channel dimension, and applies the fusion block to- produce the final edge response. This keeps both low-level edge detail- and deeper semantic boundary information in the prediction.-- Args:- x: Input BGR image tensor in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``, with- shape :math:`(B, 3, H, W)`, where :math:`B` is the batch size, :math:`H` is the image height, and- :math:`W` is the image width.-- Returns:- Tensor with shape :math:`(B, 1, H, W)` containing the fused edge- logits for each image in the batch.- """- features = self.get_features(x)-- # torch.cat multiscale outputs- block_cat = torch.cat(features, 1) # Bx6xHxW- return self.block_cat(block_cat) # Bx1xHxW+"""DexiNed under its old import path.++The network lives in :mod:`kornia.models.dexined`. This module re-exports it and its building blocks, so+``kornia.filters.dexined.DexiNed`` is the same class as :class:`kornia.models.dexined.DexiNed`. The private blocks+are re-exported too: a whole model pickled with ``torch.save`` from this module names them.+"""++from kornia.models.dexined import ( # noqa: F401+ CoFusion,+ DexiNed,+ DoubleConvBlock,+ SingleConvBlock,+ UpConvBlock,+ _DenseBlock,+ _DenseLayer,+ weight_init,+)+from kornia.models.dexined import _url as url # noqa: F401diff --git a/kornia/models/paligemma/modeling_paligemma.py b/kornia/models/paligemma/modeling_paligemma.pyindex cf8de21a0..6f5ca6696 100644--- a/kornia/models/paligemma/modeling_paligemma.py+++ b/kornia/models/paligemma/modeling_paligemma.py@@ -321,7 +321,8 @@ class PaliGemma(nn.Module):Args:input_ids: Text tokens only (batch, input_seq_len), without ``<image>`` placeholder tokens: the imagetokens are prepended to them, not substituted for placeholders.- pixel_values: Images (batch, channels, height, width)+ pixel_values: Images (batch, channels, height, width), with height and width both equal to+ ``config.vision_config.image_size``: the vision tower raises ``ValueError`` for any other size.attention_mask: Optional attention mask over the image and text positions together, in a form:func:`~torch.nn.functional.scaled_dot_product_attention` broadcasts against the(batch, heads, total_seq_len, total_seq_len) scores, e.g. (batch, 1, total_seq_len, total_seq_len).diff --git a/kornia/models/processors/naflex.py b/kornia/models/processors/naflex.pyindex fb1d831c3..07e984471 100644--- a/kornia/models/processors/naflex.py+++ b/kornia/models/processors/naflex.py@@ -198,7 +198,7 @@ class NaFlex(nn.Module):)# A square grid on an image whose sides differ by at least one patch of the longer side takes rectangular# patches. That is right for a rectangular patch embedding, but for square patches the grid is not square- # (#6004: 8 x 32 at patch 16 for 128 x 512) and the table goes in the wrong layout. N, H and W cannot tell the+ # (8 x 32 at patch 16 for 128 x 512) and the table goes in the wrong layout. N, H and W cannot tell the# two apart, so warn. A square-patch convolution of stride s, overlapping or not, with padding up to half its# kernel never warns: its grid is square only for sides H < W less than s apart, and H >= (side - 1) * s, so# (W - H) * side < (side - 1) * s + (W - H) <= W.diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.pyindex a138d5946..82a46cfc0 100644--- a/kornia/models/tiny_vit.py+++ b/kornia/models/tiny_vit.py@@ -669,12 +669,13 @@ class TinyViT(nn.Module):``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``.+ they were trained with, ``[12, 12, 24, 12]`` and ``[16, 16, 32, 16]``, and the stochastic depth rate+ they were fine-tuned with, ``drop_path_rate=0.1`` instead of TinyViT-21M's 0.2. A ``window_sizes`` or+ ``drop_path_rate`` 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 tozeros, and the model, a pretrained backbone to fine-tune, stays in training mode. The ``'in22k'``@@ -814,7 +815,8 @@ def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:# 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_512``), which also set drop_path_rate 0.1; the other 21M checkpoints use the 224-px windows+# (7, 7, 14, 7) and 0.2, as Cream ``tiny_vit_21m_224`` does._TINY_VIT_21M_WINDOW_SIZES = {"in1k_384": (12, 12, 24, 12), "in1k_512": (16, 16, 32, 16)}@@ -824,14 +826,16 @@ def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT: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)+ drop_path_rate = 0.2+ if isinstance(pretrained, str) and pretrained in _TINY_VIT_21M_WINDOW_SIZES:+ window_sizes = _TINY_VIT_21M_WINDOW_SIZES[pretrained]+ drop_path_rate = 0.1kwargs.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)+ kwargs.setdefault("drop_path_rate", drop_path_rate)model = TinyViT(**kwargs)if pretrained:diff --git a/pyproject.toml b/pyproject.tomlindex 9474830e9..0d9023948 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -120,7 +120,6 @@ omit = ["kornia/feature/aliked/deform_conv2d.py","kornia/feature/disk/_unets/*",# DexiNed vendored architecture (building blocks only; high-level API in kornia/contrib/edge_detection.py is kept)- "kornia/filters/dexined.py","kornia/models/dexined.py",# HuggingFace diffusers wrapper β requires diffusers as optional dep, not unit-testable as a filter"kornia/filters/dissolving.py",diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pyindex 64bc04fcd..81b158590 100644--- a/tests/core/test_weights_prefetch.py+++ b/tests/core/test_weights_prefetch.py@@ -145,10 +145,9 @@ WEIGHT_REGISTRIES: dict[str, tuple[ModuleType, dict[str, Any]]] = {"rt_detr": (rt_detr, rt_detr.URLs),"keynet": (keynet, {"keynet": keynet.KeyNet_URL}),"yunet": (yunet, {"yunet": yunet._url}),- # Two independent registries, identical today, both loading the same cache- # name -- which is what hides the models copy from the coverage check: the- # filters copy accounts for the name either way. Holding both to MODELS also- # holds the two copies equal to each other.+ # kornia.filters.dexined re-exports kornia.models.dexined, so both entries+ # read one list; the filters entry keeps the old import path's ``url`` alias,+ # which testing/reference_data.py reads, under the same guard."dexined": (dexined, {"dexined": dexined.url}),"dexined_model": (dexined_model, {"dexined": dexined_model._url}),"xfeat": (xfeat, {"xfeat": xfeat.XFeat.weights_url}),diff --git a/tests/models/test_dexined.py b/tests/models/test_dexined.pyindex ef701a81e..4df2efa49 100644--- a/tests/models/test_dexined.py+++ b/tests/models/test_dexined.py@@ -56,9 +56,8 @@ class TestDexiNed(BaseTester):out = model(img)self.assert_close(out, expect, atol=1e-3, rtol=1e-2)- @pytest.mark.parametrize("cls", [DexiNed, FilterDexiNed], ids=["models", "filters"])- def test_backward(self, cls, device, dtype):- net = cls(pretrained=False).to(device, dtype)+ def test_backward(self, device, dtype):+ net = DexiNed(pretrained=False).to(device, dtype)# The in-place error does not depend on the size. At 24x36 the smallest training-mode BatchNorm maps are 2x3.# 16x24 reaches 1x2, where BatchNorm normalises two values and the float16 input gradient overflows for some# seeds; 8x12 reaches 1x1, which raises.@@ -75,20 +74,35 @@ class TestDexiNed(BaseTester):assert torch.isfinite(img.grad).all()@pytest.mark.slow- @pytest.mark.parametrize("cls", [DexiNed, FilterDexiNed], ids=["models", "filters"])- def test_gradcheck(self, cls, device):+ def test_gradcheck(self, device):# A full gradcheck: fast mode checks one random projection of the Jacobian and passes a dense layer whose input- # is detached from the graph. 8x12 keeps it to about 16 s per class; in evaluation mode BatchNorm accepts the+ # is detached from the graph. 8x12 keeps it to about 16 s; in evaluation mode BatchNorm accepts the# 1x1 deepest maps.- net = cls(pretrained=False).to(device, torch.float64).eval()+ net = DexiNed(pretrained=False).to(device, torch.float64).eval()img = torch.rand(1, 3, 8, 12, device=device, dtype=torch.float64)self.gradcheck(net, (img,), fast_mode=False)@pytest.mark.skip(reason="DexiNed do not compile with dynamo.")def test_dynamo(self, device, dtype, torch_optimizer): ...+ def test_the_filters_path_is_the_same_class(self):+ # kornia.filters.dexined re-exports the network instead of keeping a second copy of it.+ assert FilterDexiNed is DexiNed++ def test_a_model_pickled_from_the_filters_path_loads(self):+ import pickle++ # A whole model pickled from the old module names its classes there, the private blocks included: pickling+ # every class under that module name and loading it back resolves each name in kornia.filters.dexined.+ model = DexiNed(pretrained=False).eval()+ classes = {type(m) for m in model.modules() if type(m).__module__ == "kornia.models.dexined"}+ assert {cls.__name__ for cls in classes} >= {"DexiNed", "_DenseBlock", "_DenseLayer"}+ for cls in classes:+ # Protocol 0 writes the module name as a text line, so it can be rewritten in place.+ pickled = pickle.dumps(cls, protocol=0).replace(b"kornia.models.dexined", b"kornia.filters.dexined")+ assert pickle.loads(pickled) is cls # noqa: S301+[email protected]("cls", [FilterDexiNed, DexiNed], ids=["filters", "models"])class TestDexiNedLoadFromFile:"""``load_from_file`` reads a local file itself; the hub cache is keyed by base name (#5477)."""@@ -108,7 +122,7 @@ class TestDexiNedLoadFromFile:return loaded@pytest.mark.parametrize("spelling", ["absolute", "home"])- def test_a_local_file_is_loaded_even_when_the_cache_holds_its_name(self, cls, spelling, tmp_path, monkeypatch):+ def test_a_local_file_is_loaded_even_when_the_cache_holds_its_name(self, spelling, tmp_path, monkeypatch):self._hub_with_a_cached_decoy(tmp_path, monkeypatch, "dexined.pth")local = tmp_path / "weights" / "dexined.pth"local.parent.mkdir()@@ -119,7 +133,7 @@ class TestDexiNedLoadFromFile:path_file = "~/weights/dexined.pth"else:path_file = str(local)- model = cls(pretrained=False).train()+ model = DexiNed(pretrained=False).train()loaded = self._record_load_state_dict(model, monkeypatch)model.load_from_file(path_file)@@ -130,9 +144,9 @@ class TestDexiNedLoadFromFile:assert torch.equal(state_dict["w"], torch.ones(3))assert not model.training- def test_a_string_that_names_no_file_is_still_treated_as_a_url(self, cls, tmp_path, monkeypatch):+ def test_a_string_that_names_no_file_is_still_treated_as_a_url(self, tmp_path, monkeypatch):self._hub_with_a_cached_decoy(tmp_path, monkeypatch, "dexined.pth")- model = cls(pretrained=False)+ model = DexiNed(pretrained=False)loaded = self._record_load_state_dict(model, monkeypatch)with pytest.raises(ValueError, match="scheme"):@@ -140,12 +154,12 @@ class TestDexiNedLoadFromFile:assert loaded == []- def test_a_pickled_callable_in_a_local_file_is_refused_and_never_run(self, cls, tmp_path, monkeypatch):+ def test_a_pickled_callable_in_a_local_file_is_refused_and_never_run(self, tmp_path, monkeypatch):# The local branch loads with ``weights_only=True``, as the hub branch does.marker = tmp_path / "marker"path = tmp_path / "dexined.pth"torch.save({"w": torch.ones(3), "extra": CreatesMarkerOnLoad(marker)}, path)- model = cls(pretrained=False)+ model = DexiNed(pretrained=False)loaded = self._record_load_state_dict(model, monkeypatch)with pytest.raises(pickle.UnpicklingError):diff --git a/tests/models/test_tiny_vit.py b/tests/models/test_tiny_vit.pyindex 110d8608d..df2c5ccaf 100644--- a/tests/models/test_tiny_vit.py+++ b/tests/models/test_tiny_vit.py@@ -219,21 +219,22 @@ class TestTinyViT(BaseTester):@pytest.mark.device_agnostic@pytest.mark.parametrize(- ("img_size", "key", "window", "pretrained_values", "num_classes"),+ ("img_size", "key", "window", "drop_path", "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),+ (224, "in1k", 7, 0.2, (True, "in1k"), 1000),+ (224, "in22k", 7, 0.2, ("in22k",), 21841),+ (384, "in1k_384", 12, 0.1, (True, "in1k_384"), 1000),+ (512, "in1k_512", 16, 0.1, (True, "in1k_512"), 1000),],)def test_21m_checkpoints_keep_their_windows(- self, monkeypatch, img_size, key, window, pretrained_values, num_classes+ self, monkeypatch, img_size, key, window, drop_path, 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.+ # holds the attention biases of its windows. The stand-in has that shape and N(0, 1) biases. The same builders+ # set drop_path_rate 0.2, 0.1 and 0.1, the rate of the 384 and 512 fine-tuning configurations.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()@@ -250,18 +251,28 @@ class TestTinyViT(BaseTester):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:]+ # 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(drop_path)# 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.+ # An explicit ``window_sizes`` or ``drop_path_rate`` wins; the biases are then interpolated to the windows.model = TinyViT.from_config(- "21m", pretrained=key, img_size=img_size, num_classes=num_classes, window_sizes=[8, 8, 16, 8]+ "21m",+ pretrained=key,+ img_size=img_size,+ num_classes=num_classes,+ window_sizes=[8, 8, 16, 8],+ drop_path_rate=0.3,)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]+ assert model.layers[-1].blocks[-1].drop_path1.drop_prob == pytest.approx(0.3)+ # Random init has no checkpoint to follow and keeps the 224-px windows and rate.+ model = TinyViT.from_config("21m", img_size=img_size)+ assert _windows(model) == [7, 14, 7]+ assert model.layers[-1].blocks[-1].drop_path1.drop_prob == pytest.approx(0.2)@pytest.mark.device_agnostic@pytest.mark.parametrize(diff --git a/tests/onnx/test_attribute_export_coverage.py b/tests/onnx/test_attribute_export_coverage.pyindex 222a07cdc..bbec7a44c 100644--- a/tests/onnx/test_attribute_export_coverage.py+++ b/tests/onnx/test_attribute_export_coverage.py@@ -59,9 +59,9 @@ from kornia.enhance.adjust import (AdjustSaturationWithGraySubtraction,)from kornia.filters.canny import Canny-from kornia.filters.dexined import DexiNedfrom kornia.filters.motion import MotionBlur3Dfrom kornia.filters.sobel import SpatialGradient, SpatialGradient3d+from kornia.models.dexined import DexiNedfrom kornia.models.segmentation.base import SemanticSegmentation# Every tensor here is created device-free and fed to onnxruntime as numpy, so the accelerator legs must not@@ -77,8 +77,14 @@ if torch_version_lt(2, 5, 0):# ``ONNXProgram`` used below from torch 2.5, and 2.5.1 is a blocking PR leg.pytest.skip("the dynamo ONNX exporter needs torch >= 2.5", allow_module_level=True)-# The packages whose classes declare ``ONNX_EXPORTABLE`` / ``ONNX_DEFAULT_INPUTSHAPE`` (#5215).-_DECLARING_PACKAGES = ("kornia.color", "kornia.enhance", "kornia.filters", "kornia.models.segmentation")+# The packages and modules whose classes declare ``ONNX_EXPORTABLE`` / ``ONNX_DEFAULT_INPUTSHAPE`` (#5215).+_DECLARING_PACKAGES = (+ "kornia.color",+ "kornia.enhance",+ "kornia.filters",+ "kornia.models.dexined",+ "kornia.models.segmentation",+)# A class that keeps ``ONNX_EXPORTABLE = False`` needs a tracking issue: its case is a strict xfail that must# fail inside the exporter, so it turns red once the class exports and the marker can go.@@ -100,10 +106,13 @@ def _declaring_classes() -> set[str]:found = set()for package_name in _DECLARING_PACKAGES:package = importlib.import_module(package_name)- for info in pkgutil.walk_packages(package.__path__, package_name + "."):- module = importlib.import_module(info.name)+ names = [package_name]+ if hasattr(package, "__path__"): # a package, not a single module+ names += [info.name for info in pkgutil.walk_packages(package.__path__, package_name + ".")]+ for name in names:+ module = importlib.import_module(name)for _, cls in inspect.getmembers(module, inspect.isclass):- if cls.__module__ == info.name and {"ONNX_DEFAULT_INPUTSHAPE", "ONNX_EXPORTABLE"} & set(cls.__dict__):+ if cls.__module__ == name and {"ONNX_DEFAULT_INPUTSHAPE", "ONNX_EXPORTABLE"} & set(cls.__dict__):found.add(cls.__qualname__)return found