diff --git a/.gitattributes b/.gitattributes index ed4dba9120069348354e5547463b7062c6216ff1..de01a97753009c646b30f6617299f18d1fec2031 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1213,3 +1213,5 @@ vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/bilateral_cy.cpython- vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text vlmpy310/lib/python3.10/site-packages/skimage/feature/_sift.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text vlmpy310/lib/python3.10/site-packages/skimage/feature/orb_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/percentile_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +vlmpy310/lib/python3.10/site-packages/OpenGL_accelerate/arraydatatype.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88a5a03af1cc4dc5da5abee47dc75e6f1ff65f90 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/__init__.py @@ -0,0 +1,19 @@ +# We are exposing all subpackages to the end-user. +# Because of possible inter-dependency, we want to avoid +# the cyclic imports, thus implementing lazy version +# as per https://peps.python.org/pep-0562/ + +import importlib + +__all__ = [ + "intrinsic", + "qat", + "quantizable", + "quantized", + "sparse", +] + +def __getattr__(name): + if name in __all__: + return importlib.import_module("." + name, __name__) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..53cf965c2e48af87b4542b9414e4e3767ed85e92 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py @@ -0,0 +1,38 @@ +from . import functional +from .modules import * # noqa: F403 +from .modules import MaxPool2d + +__all__ = [ + 'BatchNorm2d', + 'BatchNorm3d', + 'Conv1d', + 'Conv2d', + 'Conv3d', + 'ConvTranspose1d', + 'ConvTranspose2d', + 'ConvTranspose3d', + 'DeQuantize', + 'ELU', + 'Embedding', + 'EmbeddingBag', + 'GroupNorm', + 'Hardswish', + 'InstanceNorm1d', + 'InstanceNorm2d', + 'InstanceNorm3d', + 'LayerNorm', + 'LeakyReLU', + 'Linear', + 'LSTM', + 'MultiheadAttention', + 'Quantize', + 'ReLU6', + 'Sigmoid', + 'Softmax', + 'Dropout', + 'PReLU', + # Wrapper modules + 'FloatFunctional', + 'FXFloatFunctional', + 'QFunctional', +] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..72218184fcfacc20aba8c5359d38999d13493664 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py @@ -0,0 +1,644 @@ +r""" Functional interface (quantized).""" +from typing import List, Optional +import warnings + +import torch +from torch import Tensor +from torch.nn.modules.utils import _pair, _triple +from torch.jit.annotations import BroadcastingList2 + +from .modules.utils import _pair_from_first + +# Although some of the functions and docstrings are mirrored from the torch.nn, +# we want to have them here for future changes. + +__all__ = [ + "avg_pool2d", + "avg_pool3d", + "adaptive_avg_pool2d", + "adaptive_avg_pool3d", + "conv1d", + "conv2d", + "conv3d", + "interpolate", + "linear", + "max_pool1d", + "max_pool2d", + "celu", + "leaky_relu", + "hardtanh", + "hardswish", + "threshold", + "elu", + "hardsigmoid", + "clamp", + "upsample", + "upsample_bilinear", + "upsample_nearest", +] + +def avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, + count_include_pad=True, divisor_override=None): + r""" + Applies 2D average-pooling operation in :math:`kH \times kW` regions by step size + :math:`sH \times sW` steps. The number of output features is equal to the number of + input planes. + + .. note:: The input quantization parameters propagate to the output. + + See :class:`~torch.ao.nn.quantized.AvgPool2d` for details and output shape. + + Args: + input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)` + kernel_size: size of the pooling region. Can be a single number or a + tuple `(kH, kW)` + stride: stride of the pooling operation. Can be a single number or a + tuple `(sH, sW)`. Default: :attr:`kernel_size` + padding: implicit zero paddings on both sides of the input. Can be a + single number or a tuple `(padH, padW)`. Default: 0 + ceil_mode: when True, will use `ceil` instead of `floor` in the formula + to compute the output shape. Default: ``False`` + count_include_pad: when True, will include the zero-padding in the + averaging calculation. Default: ``True`` + divisor_override: if specified, it will be used as divisor, otherwise + size of the pooling region will be used. Default: None + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.avg_pool2d' must be quantized!") + return torch.nn.functional.avg_pool2d(input, kernel_size, stride, padding, + ceil_mode, count_include_pad, + divisor_override) + +def avg_pool3d(input, kernel_size, stride=None, padding=0, ceil_mode=False, + count_include_pad=True, divisor_override=None): + r""" + Applies 3D average-pooling operation in :math:`kD \ times kH \times kW` regions by step size + :math:`sD \times sH \times sW` steps. The number of output features is equal to the number of + input planes. + + .. note:: The input quantization parameters propagate to the output. + + Args: + input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)` + kernel_size: size of the pooling region. Can be a single number or a + tuple `(kD, kH, kW)` + stride: stride of the pooling operation. Can be a single number or a + tuple `(sD, sH, sW)`. Default: :attr:`kernel_size` + padding: implicit zero paddings on both sides of the input. Can be a + single number or a tuple `(padD, padH, padW)`. Default: 0 + ceil_mode: when True, will use `ceil` instead of `floor` in the formula + to compute the output shape. Default: ``False`` + count_include_pad: when True, will include the zero-padding in the + averaging calculation. Default: ``True`` + divisor_override: if specified, it will be used as divisor, otherwise + size of the pooling region will be used. Default: None + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.avg_pool3d' must be quantized!") + return torch.nn.functional.avg_pool3d(input, kernel_size, stride, padding, + ceil_mode, count_include_pad, + divisor_override) + +def adaptive_avg_pool2d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor: + r""" + Applies a 2D adaptive average pooling over a quantized input signal composed + of several quantized input planes. + + .. note:: The input quantization parameters propagate to the output. + + See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool2d` for details and output shape. + + Args: + output_size: the target output size (single integer or + double-integer tuple) + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.functional.adaptive_avg_pool2d' must be quantized!") + return torch.nn.functional.adaptive_avg_pool2d(input, output_size) + +def adaptive_avg_pool3d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor: + r""" + Applies a 3D adaptive average pooling over a quantized input signal composed + of several quantized input planes. + + .. note:: The input quantization parameters propagate to the output. + + See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool3d` for details and output shape. + + Args: + output_size: the target output size (single integer or + double-integer tuple) + """ + if not input.is_quantized: + raise ValueError( + "Input to 'quantized.functional.adaptive_avg_pool3d' must be quantized!") + return torch.nn.functional.adaptive_avg_pool3d(input, output_size) + +def conv1d(input, weight, bias, + stride=1, padding=0, dilation=1, groups=1, + padding_mode='zeros', + scale=1.0, zero_point=0, + dtype=torch.quint8): + r""" + Applies a 1D convolution over a quantized 1D input composed of several input + planes. + + See :class:`~torch.ao.nn.quantized.Conv1d` for details and output shape. + + Args: + input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)` + weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , iW)` + bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`. + stride: the stride of the convolving kernel. Can be a single number or a + tuple `(sW,)`. Default: 1 + padding: implicit paddings on both sides of the input. Can be a + single number or a tuple `(padW,)`. Default: 0 + dilation: the spacing between kernel elements. Can be a single number or + a tuple `(dW,)`. Default: 1 + groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the + number of groups. Default: 1 + padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros" + scale: quantization scale for the output. Default: 1.0 + zero_point: quantization zero_point for the output. Default: 0 + dtype: quantization data type to use. Default: ``torch.quint8`` + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> from torch.ao.nn.quantized import functional as qF + >>> filters = torch.randn(33, 16, 3, dtype=torch.float) + >>> inputs = torch.randn(20, 16, 50, dtype=torch.float) + >>> bias = torch.randn(33, dtype=torch.float) + >>> + >>> scale, zero_point = 1.0, 0 + >>> dtype_inputs = torch.quint8 + >>> dtype_filters = torch.qint8 + >>> + >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters) + >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs) + >>> qF.conv1d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point) + """ # noqa: E501 + if padding_mode != 'zeros': + raise NotImplementedError("Only zero-padding is supported!") + if input.dtype != torch.quint8: + raise NotImplementedError("Only torch.quint8 is supported for activation tensor!") + if weight.dtype != torch.qint8: + raise NotImplementedError("Only torch.qint8 is supported for weight tensor!") + if input.ndim != 3: + raise ValueError("Input shape must be `(N, C, L)`!") + stride = _pair_from_first(stride) + padding = _pair_from_first(padding) + dilation = _pair_from_first(dilation) + + packed_params = torch.ops.quantized.conv1d_prepack( + weight, bias, stride, padding, dilation, groups) + return torch.ops.quantized.conv1d(input, packed_params, scale, zero_point) + +def conv2d(input, weight, bias, + stride=1, padding=0, dilation=1, groups=1, + padding_mode='zeros', + scale=1.0, zero_point=0, + dtype=torch.quint8): + r""" + Applies a 2D convolution over a quantized 2D input composed of several input + planes. + + See :class:`~torch.ao.nn.quantized.Conv2d` for details and output shape. + + Args: + input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)` + weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW)` + bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`. + stride: the stride of the convolving kernel. Can be a single number or a + tuple `(sH, sW)`. Default: 1 + padding: implicit paddings on both sides of the input. Can be a + single number or a tuple `(padH, padW)`. Default: 0 + dilation: the spacing between kernel elements. Can be a single number or + a tuple `(dH, dW)`. Default: 1 + groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the + number of groups. Default: 1 + padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros" + scale: quantization scale for the output. Default: 1.0 + zero_point: quantization zero_point for the output. Default: 0 + dtype: quantization data type to use. Default: ``torch.quint8`` + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> from torch.ao.nn.quantized import functional as qF + >>> filters = torch.randn(8, 4, 3, 3, dtype=torch.float) + >>> inputs = torch.randn(1, 4, 5, 5, dtype=torch.float) + >>> bias = torch.randn(8, dtype=torch.float) + >>> + >>> scale, zero_point = 1.0, 0 + >>> dtype_inputs = torch.quint8 + >>> dtype_filters = torch.qint8 + >>> + >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters) + >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs) + >>> qF.conv2d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point) + """ # noqa: E501 + if padding_mode != 'zeros': + raise NotImplementedError("Only zero-padding is supported!") + if input.dtype != torch.quint8: + raise NotImplementedError("Only torch.quint8 is supported for activation tensor!") + if weight.dtype != torch.qint8: + raise NotImplementedError("Only torch.qint8 is supported for weight tensor!") + if input.ndim != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + stride = _pair(stride) + padding = _pair(padding) + dilation = _pair(dilation) + + packed_params = torch.ops.quantized.conv2d_prepack( + weight, bias, stride, padding, dilation, groups) + return torch.ops.quantized.conv2d(input, packed_params, scale, zero_point) + +def conv3d(input, weight, bias, stride=1, padding=0, dilation=1, groups=1, + padding_mode='zeros', scale=1.0, zero_point=0, dtype=torch.quint8): + r""" + Applies a 3D convolution over a quantized 3D input composed of several input + planes. + + See :class:`~torch.ao.nn.quantized.Conv3d` for details and output shape. + + Args: + input: quantized input tensor of shape + :math:`(\text{minibatch} , \text{in\_channels} , iD , iH , iW)` + weight: quantized filters of shape + :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kD , kH , kW)` + bias: **non-quantized** bias tensor of shape + :math:`(\text{out\_channels})`. The tensor type must be `torch.float`. + stride: the stride of the convolving kernel. Can be a single number or a + tuple `(sD, sH, sW)`. Default: 1 + padding: implicit paddings on both sides of the input. Can be a + single number or a tuple `(padD, padH, padW)`. Default: 0 + dilation: the spacing between kernel elements. Can be a single number or + a tuple `(dD, dH, dW)`. Default: 1 + groups: split input into groups, :math:`\text{in\_channels}` should be + divisible by the number of groups. Default: 1 + padding_mode: the padding mode to use. Only "zeros" is supported for + quantized convolution at the moment. Default: "zeros" + scale: quantization scale for the output. Default: 1.0 + zero_point: quantization zero_point for the output. Default: 0 + dtype: quantization data type to use. Default: ``torch.quint8`` + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> from torch.ao.nn.quantized import functional as qF + >>> filters = torch.randn(8, 4, 3, 3, 3, dtype=torch.float) + >>> inputs = torch.randn(1, 4, 5, 5, 5, dtype=torch.float) + >>> bias = torch.randn(8, dtype=torch.float) + >>> + >>> scale, zero_point = 1.0, 0 + >>> dtype_inputs = torch.quint8 + >>> dtype_filters = torch.qint8 + >>> + >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters) + >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs) + >>> qF.conv3d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point) + """ # noqa: E501 + if padding_mode != 'zeros': + raise NotImplementedError("Only zero-padding is supported!") + if input.dtype != torch.quint8: + raise NotImplementedError("Only torch.quint8 is supported for activation tensor!") + if weight.dtype != torch.qint8: + raise NotImplementedError("Only torch.qint8 is supported for weight tensor!") + if input.ndim != 5: + raise ValueError("Input shape must be `(N, C, D, H, W)`!") + stride = _triple(stride) + padding = _triple(padding) + dilation = _triple(dilation) + + packed_params = torch.ops.quantized.conv3d_prepack( + weight, bias, stride, padding, dilation, groups) + return torch.ops.quantized.conv3d(input, packed_params, scale, zero_point) + +def interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None): + r"""Down/up samples the input to either the given :attr:`size` or the given + :attr:`scale_factor` + + See :func:`torch.nn.functional.interpolate` for implementation details. + + The input dimensions are interpreted in the form: + `mini-batch x channels x [optional depth] x [optional height] x width`. + + .. note:: The input quantization parameters propagate to the output. + + .. note:: Only 2D/3D input is supported for quantized inputs + + .. note:: Only the following modes are supported for the quantized inputs: + + - `bilinear` + - `nearest` + + Args: + input (Tensor): the input tensor + size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]): + output spatial size. + scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple. + mode (str): algorithm used for upsampling: + ``'nearest'`` | ``'bilinear'`` + align_corners (bool, optional): Geometrically, we consider the pixels of the + input and output as squares rather than points. + If set to ``True``, the input and output tensors are aligned by the + center points of their corner pixels, preserving the values at the corner pixels. + If set to ``False``, the input and output tensors are aligned by the corner + points of their corner pixels, and the interpolation uses edge value padding + for out-of-boundary values, making this operation *independent* of input size + when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode` + is ``'bilinear'``. + Default: ``False`` + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.interpolate' must be quantized!") + return torch.nn.functional.interpolate(input, size, scale_factor, mode, + align_corners) + +def linear( + input: Tensor, weight: Tensor, bias: Optional[Tensor] = None, + scale: Optional[float] = None, zero_point: Optional[int] = None +) -> Tensor: + r""" + Applies a linear transformation to the incoming quantized data: + :math:`y = xA^T + b`. + See :class:`~torch.ao.nn.quantized.Linear` + + .. note:: + + Current implementation packs weights on every call, which has penalty on performance. + If you want to avoid the overhead, use :class:`~torch.ao.nn.quantized.Linear`. + + Args: + input (Tensor): Quantized input of type `torch.quint8` + weight (Tensor): Quantized weight of type `torch.qint8` + bias (Tensor): None or fp32 bias of type `torch.float` + scale (double): output scale. If None, derived from the input scale + zero_point (long): output zero point. If None, derived from the input zero_point + + Shape: + - Input: :math:`(N, *, in\_features)` where `*` means any number of + additional dimensions + - Weight: :math:`(out\_features, in\_features)` + - Bias: :math:`(out\_features)` + - Output: :math:`(N, *, out\_features)` + """ + if scale is None: + scale = input.q_scale() + if zero_point is None: + zero_point = input.q_zero_point() + _packed_params = torch.ops.quantized.linear_prepack(weight, bias) + return torch.ops.quantized.linear(input, _packed_params, scale, zero_point) + +def max_pool1d(input, kernel_size, stride=None, padding=0, dilation=1, + ceil_mode=False, return_indices=False): + r"""Applies a 1D max pooling over a quantized input signal composed of + several quantized input planes. + + .. note:: The input quantization parameters are propagated to the output. + + See :class:`~torch.ao.nn.quantized.MaxPool1d` for details. + """ + if return_indices: + raise NotImplementedError("return_indices is not yet implemented!") + if stride is None: + stride = torch.jit.annotate(List[int], []) + return torch.nn.functional.max_pool1d(input, kernel_size, stride, padding, + dilation, ceil_mode=ceil_mode, return_indices=return_indices) + +def max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1, + ceil_mode=False, return_indices=False): + r"""Applies a 2D max pooling over a quantized input signal composed of + several quantized input planes. + + .. note:: The input quantization parameters are propagated to the output. + + See :class:`~torch.ao.nn.quantized.MaxPool2d` for details. + """ + if return_indices: + raise NotImplementedError("return_indices is not yet implemented!") + if stride is None: + stride = torch.jit.annotate(List[int], []) + return torch.nn.functional.max_pool2d(input, kernel_size, stride, padding, + dilation, ceil_mode=ceil_mode, return_indices=return_indices) + +def celu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.) -> Tensor: + r"""celu(input, scale, zero_point, alpha=1.) -> Tensor + + Applies the quantized CELU function element-wise. + + .. math:: + \text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x / \alpha) - 1)) + + Args: + input: quantized input + alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0 + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.celu' must be quantized!") + return torch.ops.quantized.celu(input, scale, zero_point, alpha) + + +def leaky_relu(input: Tensor, negative_slope: float = 0.01, inplace: bool = False, + scale: Optional[float] = None, zero_point: Optional[int] = None): + r""" + Quantized version of the. + leaky_relu(input, negative_slope=0.01, inplace=False, scale, zero_point) -> Tensor + + Applies element-wise, + :math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)` + + Args: + input: Quantized input + negative_slope: The slope of the negative input + inplace: Inplace modification of the input tensor + scale, zero_point: Scale and zero point of the output tensor. + + See :class:`~torch.nn.LeakyReLU` for more details. + """ + if scale is not None and zero_point is not None: + assert not inplace, "Cannot rescale with `inplace`" + output = torch._empty_affine_quantized( + input.shape, scale=scale, zero_point=int(zero_point), dtype=input.dtype) + torch._C._nn.leaky_relu(input, negative_slope, out=output) + return output + if inplace: + result = torch._C._nn.leaky_relu_(input, negative_slope) + else: + result = torch._C._nn.leaky_relu(input, negative_slope) + return result + +def hardtanh(input: Tensor, min_val: float = -1., max_val: float = 1., inplace: bool = False) -> Tensor: + r"""This is the quantized version of :func:`~torch.nn.functional.hardtanh`. + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.hardtanh' must be quantized!") + if inplace: + return torch._C._nn.hardtanh_(input, min_val, max_val) + return torch._C._nn.hardtanh(input, min_val, max_val) + +def hardswish(input: Tensor, scale: float, zero_point: int) -> Tensor: + r"""This is the quantized version of :func:`~torch.nn.functional.hardswish`. + + Args: + input: quantized input + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.hardswish' must be quantized!") + return torch._ops.ops.quantized.hardswish(input, scale, zero_point) + +def threshold(input: Tensor, threshold: float, value: float) -> Tensor: + r"""Applies the quantized version of the threshold function element-wise: + + .. math:: + x = \begin{cases} + x & \text{if~} x > \text{threshold} \\ + \text{value} & \text{otherwise} + \end{cases} + + See :class:`~torch.nn.Threshold` for more details. + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.threshold' must be quantized!") + if threshold is None: + raise ValueError("Input to 'threshold' must be specified!") + if value is None: + raise ValueError("Input to 'value' must be specified!") + return torch._ops.ops.quantized.threshold(input, threshold, value) + +def elu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.) -> Tensor: + r"""This is the quantized version of :func:`~torch.nn.functional.elu`. + + Args: + input: quantized input + scale: quantization scale of the output tensor + zero_point: quantization zero point of the output tensor + alpha: the alpha constant + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.elu' must be quantized!") + return torch.ops.quantized.elu(input, scale, zero_point, alpha) + +def hardsigmoid(input: Tensor, inplace: bool = False) -> Tensor: + r"""This is the quantized version of :func:`~torch.nn.functional.hardsigmoid`. + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.hardsigmoid' must be quantized!") + if inplace: + return torch._C._nn.hardsigmoid_(input) # type: ignore[attr-defined] + return torch._C._nn.hardsigmoid(input) + +def clamp(input: Tensor, min_: float, max_: float) -> Tensor: + r"""float(input, min\_, max\_) -> Tensor + + Applies the clamp function element-wise. + See :class:`~torch.ao.nn.quantized.clamp` for more details. + + Args: + input: quantized input + min_: minimum value for clamping + max_: maximum value for clamping + """ + if not input.is_quantized: + raise ValueError("Input to 'quantized.clamp' must be quantized!") + return torch.clamp(input, min_, max_) + +def upsample(input, size=None, scale_factor=None, mode='nearest', align_corners=None): + r"""Upsamples the input to either the given :attr:`size` or the given + :attr:`scale_factor` + + .. warning:: + This function is deprecated in favor of + :func:`torch.ao.nn.quantized.functional.interpolate`. + This is equivalent with ``nn.quantized.functional.interpolate(...)``. + + See :func:`torch.nn.functional.interpolate` for implementation details. + + The input dimensions are interpreted in the form: + `mini-batch x channels x [optional depth] x [optional height] x width`. + + .. note:: The input quantization parameters propagate to the output. + + .. note:: Only 2D input is supported for quantized inputs + + .. note:: Only the following modes are supported for the quantized inputs: + + - `bilinear` + - `nearest` + + Args: + input (Tensor): quantized input tensor + size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]): + output spatial size. + scale_factor (float or Tuple[float]): multiplier for spatial size. Has to be an integer. + mode (str): algorithm used for upsampling: + ``'nearest'`` | ``'bilinear'`` + align_corners (bool, optional): Geometrically, we consider the pixels of the + input and output as squares rather than points. + If set to ``True``, the input and output tensors are aligned by the + center points of their corner pixels, preserving the values at the corner pixels. + If set to ``False``, the input and output tensors are aligned by the corner + points of their corner pixels, and the interpolation uses edge value padding + for out-of-boundary values, making this operation *independent* of input size + when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode` + is ``'bilinear'``. + Default: ``False`` + + .. warning:: + With ``align_corners = True``, the linearly interpolating modes + (`bilinear`) don't proportionally align the + output and input pixels, and thus the output values can depend on the + input size. This was the default behavior for these modes up to version + 0.3.1. Since then, the default behavior is ``align_corners = False``. + See :class:`~torch.nn.Upsample` for concrete examples on how this + affects the outputs. + """ + warnings.warn("nn.quantized.functional.upsample is deprecated. Use nn.quantized.functional.interpolate instead.") + return interpolate(input, size, scale_factor, mode, align_corners) + +def upsample_bilinear(input, size=None, scale_factor=None): + r"""Upsamples the input, using bilinear upsampling. + + .. warning:: + This function is deprecated in favor of + :func:`torch.ao.nn.quantized.functional.interpolate`. + This is equivalent with + ``nn.quantized.functional.interpolate(..., mode='bilinear', align_corners=True)``. + + .. note:: The input quantization parameters propagate to the output. + + .. note:: Only 2D inputs are supported + + Args: + input (Tensor): quantized input + size (int or Tuple[int, int]): output spatial size. + scale_factor (int or Tuple[int, int]): multiplier for spatial size + """ + # DeprecationWarning is ignored by default + warnings.warn("nn.quantized.functional.upsample_bilinear is deprecated. Use nn.quantized.functional.interpolate instead.") + return interpolate(input, size, scale_factor, mode='bilinear', align_corners=True) + +def upsample_nearest(input, size=None, scale_factor=None): + r"""Upsamples the input, using nearest neighbours' pixel values. + + .. warning:: + This function is deprecated in favor of + :func:`torch.ao.nn.quantized.functional.interpolate`. + This is equivalent with ``nn.quantized.functional.interpolate(..., mode='nearest')``. + + .. note:: The input quantization parameters propagate to the output. + + .. note:: Only 2D inputs are supported + + Args: + input (Tensor): quantized input + size (int or Tuple[int, int] or Tuple[int, int, int]): output spatial + size. + scale_factor (int): multiplier for spatial size. Has to be an integer. + """ + # DeprecationWarning is ignored by default + warnings.warn("nn.quantized.functional.upsample_nearest is deprecated. Use nn.quantized.functional.interpolate instead.") + return interpolate(input, size, scale_factor, mode='nearest') diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..668f765fe3ef0ae082e94a30639fe343034ca306 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py @@ -0,0 +1,131 @@ +import torch + +# The quantized modules use `torch.nn` and `torch.ao.nn.quantizable` +# packages. However, the `quantizable` package uses "lazy imports" +# to avoid circular dependency. +# Hence we need to include it here to make sure it is resolved before +# they are used in the modules. +import torch.ao.nn.quantizable + +from torch.nn.modules.pooling import MaxPool2d + +from .activation import ReLU6, Hardswish, ELU, LeakyReLU, Sigmoid, Softmax, MultiheadAttention, PReLU +from .dropout import Dropout +from .batchnorm import BatchNorm2d, BatchNorm3d +from .normalization import LayerNorm, GroupNorm, InstanceNorm1d, \ + InstanceNorm2d, InstanceNorm3d +from .conv import Conv1d, Conv2d, Conv3d +from .conv import ConvTranspose1d, ConvTranspose2d, ConvTranspose3d +from .linear import Linear +from .embedding_ops import Embedding, EmbeddingBag +from .rnn import LSTM + +from .functional_modules import FloatFunctional, FXFloatFunctional, QFunctional + +__all__ = [ + 'BatchNorm2d', + 'BatchNorm3d', + 'Conv1d', + 'Conv2d', + 'Conv3d', + 'ConvTranspose1d', + 'ConvTranspose2d', + 'ConvTranspose3d', + 'DeQuantize', + 'ELU', + 'Embedding', + 'EmbeddingBag', + 'GroupNorm', + 'Hardswish', + 'InstanceNorm1d', + 'InstanceNorm2d', + 'InstanceNorm3d', + 'LayerNorm', + 'LeakyReLU', + 'Linear', + 'LSTM', + 'MultiheadAttention', + 'Quantize', + 'ReLU6', + 'Sigmoid', + 'Softmax', + 'Dropout', + 'PReLU', + # Wrapper modules + 'FloatFunctional', + 'FXFloatFunctional', + 'QFunctional', +] + +class Quantize(torch.nn.Module): + r"""Quantizes an incoming tensor + + Args: + `scale`: scale of the output Quantized Tensor + `zero_point`: zero_point of output Quantized Tensor + `dtype`: data type of output Quantized Tensor + `factory_kwargs`: Dictionary of kwargs used for configuring initialization + of internal buffers. Currently, `device` and `dtype` are supported. + Example: `factory_kwargs={'device': 'cuda', 'dtype': torch.float64}` + will initialize internal buffers as type `torch.float64` on the current CUDA device. + Note that `dtype` only applies to floating-point buffers. + + Examples:: + >>> t = torch.tensor([[1., -1.], [1., -1.]]) + >>> scale, zero_point, dtype = 1.0, 2, torch.qint8 + >>> qm = Quantize(scale, zero_point, dtype) + >>> # xdoctest: +SKIP + >>> qt = qm(t) + >>> print(qt) + tensor([[ 1., -1.], + [ 1., -1.]], size=(2, 2), dtype=torch.qint8, scale=1.0, zero_point=2) + """ + + scale: torch.Tensor + zero_point: torch.Tensor + + def __init__(self, scale, zero_point, dtype, factory_kwargs=None): + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) + super().__init__() + self.register_buffer('scale', torch.tensor([scale], **factory_kwargs)) + self.register_buffer('zero_point', + torch.tensor([zero_point], dtype=torch.long, + **{k: v for k, v in factory_kwargs.items() if k != 'dtype'})) + self.dtype = dtype + + def forward(self, X): + return torch.quantize_per_tensor(X, float(self.scale), + int(self.zero_point), self.dtype) + + @staticmethod + def from_float(mod): + assert hasattr(mod, 'activation_post_process') + scale, zero_point = mod.activation_post_process.calculate_qparams() + return Quantize(scale.float().item(), zero_point.long().item(), mod.activation_post_process.dtype) + + def extra_repr(self): + return f'scale={self.scale}, zero_point={self.zero_point}, dtype={self.dtype}' + + +class DeQuantize(torch.nn.Module): + r"""Dequantizes an incoming tensor + + Examples:: + >>> input = torch.tensor([[1., -1.], [1., -1.]]) + >>> scale, zero_point, dtype = 1.0, 2, torch.qint8 + >>> qm = Quantize(scale, zero_point, dtype) + >>> # xdoctest: +SKIP + >>> quantized_input = qm(input) + >>> dqm = DeQuantize() + >>> dequantized = dqm(quantized_input) + >>> print(dequantized) + tensor([[ 1., -1.], + [ 1., -1.]], dtype=torch.float32) + """ + + def forward(self, Xq): + return Xq.dequantize() + + @staticmethod + def from_float(mod): + return DeQuantize() diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07eaa159676f386f76075f2fea1ae17f226b1215 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..bfef31268cff11f937b806701d6e6667b1c3622f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py @@ -0,0 +1,106 @@ +import torch +import torch.ao.nn.intrinsic as nni + +__all__ = [ + "BatchNorm2d", + "BatchNorm3d" +] + +class _BatchNorm(torch.nn.modules.batchnorm._BatchNorm): + def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_features, eps, momentum, True, True, **factory_kwargs) + self.register_buffer('scale', torch.tensor(1.0, **factory_kwargs)) + self.register_buffer('zero_point', torch.tensor(0, **factory_kwargs)) + + @staticmethod + def from_float(cls, mod): + activation_post_process = mod.activation_post_process + if type(mod) == cls._NNI_BN_RELU_MODULE: + mod = mod[0] + scale, zero_point = activation_post_process.calculate_qparams() + new_mod = cls(mod.num_features, mod.eps) + new_mod.weight = mod.weight + new_mod.bias = mod.bias + new_mod.running_mean = mod.running_mean + new_mod.running_var = mod.running_var + new_mod.scale = scale + new_mod.zero_point = zero_point + return new_mod + + @classmethod + def from_reference(cls, bn, output_scale, output_zero_point): + qbn = cls( + bn.num_features, + bn.eps, + bn.momentum, + device=bn.weight.device, + dtype=bn.weight.dtype + ) + qbn.weight = bn.weight + qbn.bias = bn.bias + qbn.running_mean = bn.running_mean + qbn.running_var = bn.running_var + qbn.scale = output_scale + qbn.zero_point = output_zero_point + return qbn + +class BatchNorm2d(_BatchNorm): + r"""This is the quantized version of :class:`~torch.nn.BatchNorm2d`. + """ + + _NNI_BN_RELU_MODULE = nni.BNReLU2d + + def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_features, eps, momentum, **factory_kwargs) + + def _get_name(self): + return 'QuantizedBatchNorm2d' + + def _check_input_dim(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + + def forward(self, input: torch.Tensor) -> torch.Tensor: + # disabling this since this is not symbolically traceable + # self._check_input_dim(input) + return torch.ops.quantized.batch_norm2d( + input, self.weight, self.bias, self.running_mean, + self.running_var, self.eps, self.scale, self.zero_point) + + @classmethod + def from_float(cls, mod): + return _BatchNorm.from_float(cls, mod) + +class BatchNorm3d(_BatchNorm): + r"""This is the quantized version of :class:`~torch.nn.BatchNorm3d`. + """ + + _NNI_BN_RELU_MODULE = nni.BNReLU3d + + def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None): + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_features, eps, momentum, **factory_kwargs) + + def _get_name(self): + return 'QuantizedBatchNorm3d' + + def _check_input_dim(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, H, W)`!") + + def forward(self, input: torch.Tensor) -> torch.Tensor: + # disabling this since this is not symbolically traceable + # self._check_input_dim(input) + return torch.ops.quantized.batch_norm3d( + input, self.weight, self.bias, self.running_mean, + self.running_var, self.eps, self.scale, self.zero_point) + + @classmethod + def from_float(cls, mod): + return _BatchNorm.from_float(cls, mod) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/conv.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..22a11014375948f2eaeb609b560f68afb0665721 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/conv.py @@ -0,0 +1,945 @@ +r"""Quantized convolution modules.""" + +from typing import Optional, List, TypeVar + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.ao.nn.intrinsic as nni +import torch.ao.nn.intrinsic.qat as nniqat + +from torch._ops import ops +from torch.nn.common_types import _size_1_t +from torch.nn.modules.utils import _single, _pair, _triple +from torch.nn.utils import fuse_conv_bn_weights + +from .utils import _quantize_weight, WeightedQuantizedModule + +__all__ = ['Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d'] + +_SUPPORTED_PADDING = { + 'zeros', + 'reflect' +} + + +def _reverse_repeat_padding(padding: List[int]) -> List[int]: + _reversed_padding_repeated_twice: List[int] = [] + N = len(padding) + for idx in range(N): + for _ in range(2): + _reversed_padding_repeated_twice.append(padding[N - idx - 1]) + return _reversed_padding_repeated_twice + + +class _ConvNd(WeightedQuantizedModule): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, + padding=0, dilation=1, groups=1, bias=True, + padding_mode='zeros', device=None, dtype=None): + # All subclasses have this signature - See PR #49702s + raise NotImplementedError + + def _init(self, in_channels, out_channels, kernel_size, stride, + padding, dilation, + transposed, output_padding, + groups, bias, + padding_mode='zeros', + device=None, + dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__() + + if in_channels % groups != 0: + raise ValueError('in_channels must be divisible by groups') + if out_channels % groups != 0: + raise ValueError('out_channels must be divisible by groups') + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.dilation = dilation + self.transposed = transposed + self.output_padding = output_padding + self.groups = groups + if padding_mode not in _SUPPORTED_PADDING: + raise ValueError(f"'padding_mode' {padding_mode} is not supported by quantized convolution") + self.padding_mode = padding_mode + # Initialize as NCHW. set_weight will internally transpose to NHWC. + if self.transposed: + weight_shape = [in_channels, out_channels // self.groups] + else: + weight_shape = [out_channels, in_channels // self.groups] + qweight = torch._empty_affine_quantized( + weight_shape + list(kernel_size), + scale=1, zero_point=0, dtype=torch.qint8, + **{k: v for k, v in factory_kwargs.items() if k != 'dtype'}) + bias_float = ( + torch.zeros(out_channels, dtype=torch.float, + **{k: v for k, v in factory_kwargs.items() if k != 'dtype'}) if bias else None) + + self.set_weight_bias(qweight, bias_float) + self.scale = 1.0 + self.zero_point = 0 + + def set_weight_bias(self, qweight, bias_float): + raise NotImplementedError + + def bias(self): + raise NotImplementedError + + def _weight_bias(self): + raise NotImplementedError + + def extra_repr(self): + s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}' + ', stride={stride}, scale={scale}, zero_point={zero_point}') + if self.padding != (0,) * len(self.padding): + s += ', padding={padding}' + if self.dilation != (1,) * len(self.dilation): + s += ', dilation={dilation}' + if self.output_padding != (0,) * len(self.output_padding): + s += ', output_padding={output_padding}' + if self.groups != 1: + s += ', groups={groups}' + if self.bias() is None: + s += ', bias=False' + return s.format(**self.__dict__) + + # ===== Serialization methods ===== + # The special consideration here is that we have to unpack the weights into + # their regular QTensor form for serialization. Packed weights should not + # live outside the process in which they were created, rather they should be + # derived from the QTensor weight. + # self + # |--- weight : Tensor + # |--- bias : Tensor + # + # TODO: maybe change to this when https://github.com/pytorch/pytorch/pull/32958 is landed + # self + # |--- _packed_params : Conv2dPackedParamsBase or Conv3dPackedParamsBase + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + (w, b) = self._weight_bias() + destination[prefix + 'weight'] = w + destination[prefix + 'bias'] = b + destination[prefix + 'scale'] = torch.tensor(self.scale) + destination[prefix + 'zero_point'] = torch.tensor(self.zero_point) + + @torch.jit.export + def __getstate__(self): + (w, b) = self._weight_bias() + return ( + self.in_channels, + self.out_channels, + self.kernel_size, + self.stride, + self.padding, + self.dilation, + self.transposed, + self.output_padding, + self.groups, + self.padding_mode, + w, + b, + self.scale, + self.zero_point, + self.training + ) + + # ===== Deserialization methods ===== + # Counterpart to the serialization methods, we must pack the serialized + # QTensor weight into its packed format for use by the FBGEMM ops. + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + self.set_weight_bias( + state_dict[prefix + 'weight'], state_dict[prefix + 'bias']) + state_dict.pop(prefix + 'weight') + state_dict.pop(prefix + 'bias') + self.scale = float(state_dict[prefix + 'scale']) + state_dict.pop(prefix + 'scale') + self.zero_point = int(state_dict[prefix + 'zero_point']) + state_dict.pop(prefix + 'zero_point') + super()._load_from_state_dict( + state_dict, prefix, local_metadata, False, missing_keys, + unexpected_keys, error_msgs) + + @torch.jit.export + def __setstate__(self, state): + self.in_channels = state[0] + self.out_channels = state[1] + self.kernel_size = state[2] + self.stride = state[3] + self.padding = state[4] + self.dilation = state[5] + self.transposed = state[6] + self.output_padding = state[7] + self.groups = state[8] + self.padding_mode = state[9] + self.set_weight_bias(state[10], state[11]) + self.scale = state[12] + self.zero_point = state[13] + self.training = state[14] + + def __deepcopy__(self, memo): + new_instance = type(self).__new__(type(self)) + torch.nn.Module.__init__(new_instance) + state = self.__getstate__() + new_instance.__setstate__(state) + return new_instance + + def __copy__(self): + return self.__deepcopy__({}) + + @classmethod + def get_qconv(cls, mod, activation_post_process, weight_post_process=None): + r"""Creates a qconv object and returns it. + """ + if weight_post_process is None: + weight_post_process = mod.qconfig.weight() + weight_post_process(mod.weight) + assert weight_post_process.dtype == torch.qint8, \ + 'Weight observer must have a dtype of qint8' + qweight = _quantize_weight(mod.weight.float(), weight_post_process) + # the __init__ call used is the one from derived classes and not the one from _ConvNd + qconv = cls(mod.in_channels, mod.out_channels, mod.kernel_size, + mod.stride, mod.padding, mod.dilation, mod.groups, + mod.bias is not None, mod.padding_mode) + qconv.set_weight_bias(qweight, mod.bias) + if activation_post_process is None or activation_post_process.dtype == torch.float: + return qconv # dynamic quantization doesn't need scale/zero_point + else: + act_scale, act_zp = activation_post_process.calculate_qparams() + qconv.scale = float(act_scale) + qconv.zero_point = int(act_zp) + return qconv + + @staticmethod + def from_float(cls, mod): + if hasattr(mod, "weight_fake_quant"): + # assert type(mod) == cls.__QAT_MODULE, " nnq." + cls.__name__ + \ + # ".from_float only works for " + cls.__QAT_MODULE.__name__ + if type(mod) == cls._NNIQAT_CONV_BN_MODULE: + mod.weight, mod.bias = fuse_conv_bn_weights( + mod.weight, mod.bias, mod.bn.running_mean, mod.bn.running_var, + mod.bn.eps, mod.bn.weight, mod.bn.bias) + assert hasattr(mod, "activation_post_process"), \ + "Input QAT module must have observer attached" + weight_post_process = mod.weight_fake_quant + activation_post_process = mod.activation_post_process + else: + assert type(mod) == cls._FLOAT_MODULE, \ + " nnq." + cls.__name__ + ".from_float only works for " + \ + cls._FLOAT_MODULE.__name__ + " but got:" + str(type(mod)) + assert hasattr(mod, "qconfig"), \ + "Input float module must have qconfig defined." + activation_post_process = None if not hasattr( + mod, "activation_post_process") else mod.activation_post_process + if type(mod) in [cls._NNI_CONV_RELU_MODULE, cls._NNI_CONV_ADD_MODULE, cls._NNI_CONV_ADD_RELU_MODULE]: + mod = mod[0] + weight_post_process = mod.qconfig.weight() + return cls.get_qconv(mod, activation_post_process, weight_post_process) + + @classmethod + def from_reference(cls, ref_qconv, output_scale, output_zero_point): + r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module + Args: + ref_qconv (Module): a reference quantized module, either produced by torch.ao.quantization + utilities or provided by the user + output_scale (float): scale for output Tensor + output_zero_point (int): zero point for output Tensor + """ + qconv = cls( + ref_qconv.in_channels, + ref_qconv.out_channels, + ref_qconv.kernel_size, # type: ignore[arg-type] + ref_qconv.stride, # type: ignore[arg-type] + ref_qconv.padding, # type: ignore[arg-type] + ref_qconv.dilation, # type: ignore[arg-type] + ref_qconv.groups, + ref_qconv.bias is not None, # type: ignore[arg-type] + ref_qconv.padding_mode, + device=ref_qconv.weight.device, + dtype=ref_qconv.weight.dtype) + qweight = ref_qconv.get_quantized_weight() + qconv.set_weight_bias(qweight, ref_qconv.bias) + qconv.scale = float(output_scale) + qconv.zero_point = int(output_zero_point) + return qconv + + +class Conv1d(_ConvNd): + r"""Applies a 1D convolution over a quantized input signal composed of + several quantized input planes. + + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.Conv1d`. + + .. note:: + Only `zeros` is supported for the :attr:`padding_mode` argument. + + .. note:: + Only `torch.quint8` is supported for the input data type. + + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + + See :class:`~torch.nn.Conv1d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> m = nn.quantized.Conv1d(16, 33, 3, stride=2) + >>> input = torch.randn(20, 16, 100) + >>> # quantize input to quint8 + >>> # xdoctest: +SKIP + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, + ... dtype=torch.quint8) + >>> output = m(q_input) + + """ + + _FLOAT_MODULE = nn.Conv1d + _NNIQAT_CONV_BN_MODULE = nniqat.ConvBn1d + _NNI_CONV_RELU_MODULE = nni.ConvReLU1d + _NNI_CONV_ADD_MODULE = None + _NNI_CONV_ADD_RELU_MODULE = None + + def __init__(self, + in_channels: int, + out_channels: int, + kernel_size: _size_1_t, + stride: _size_1_t = 1, + padding: _size_1_t = 0, + dilation: _size_1_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = 'zeros', + device=None, + dtype=None): + factory_kwargs = {'device': device, 'dtype': dtype} + kernel_size = _single(kernel_size) + stride = _single(stride) + padding = padding if isinstance(padding, str) else _single(padding) + dilation = _single(dilation) + + # Subclasses of _ConvNd needs to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, out_channels, kernel_size, stride, padding, dilation, + False, _single(0), groups, bias, padding_mode, **factory_kwargs) + + def _get_name(self): + return 'QuantizedConv1d' + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + if self.padding_mode == 'zeros': + self._packed_params = torch.ops.quantized.conv1d_prepack( + w, b, self.stride, self.padding, self.dilation, self.groups) + else: + self._packed_params = torch.ops.quantized.conv1d_prepack( + w, b, self.stride, _pair(0), self.dilation, + self.groups) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv1d_unpack(self._packed_params) + return w, b + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 3: + raise ValueError("Input shape must be `(N, C, L)`!") + if self.padding_mode != 'zeros': + # Padding in Conv1d is stored as (p, p), need to get (p,) + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1]) + input = F.pad(input, _reversed_padding_repeated_twice, + mode=self.padding_mode) + return ops.quantized.conv1d(input, self._packed_params, self.scale, self.zero_point) + + @classmethod + def from_float(cls, mod): + r"""Creates a quantized module from a float module or qparams_dict. + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + return _ConvNd.from_float(cls, mod) + + +class Conv2d(_ConvNd): + r"""Applies a 2D convolution over a quantized input signal composed of + several quantized input planes. + + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.Conv2d`. + + .. note:: + Only `zeros` is supported for the :attr:`padding_mode` argument. + + .. note:: + Only `torch.quint8` is supported for the input data type. + + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + + See :class:`~torch.nn.Conv2d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> # With square kernels and equal stride + >>> m = nn.quantized.Conv2d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> # non-square kernels and unequal stride and with padding and dilation + >>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)) + >>> input = torch.randn(20, 16, 50, 100) + >>> # quantize input to quint8 + >>> # xdoctest: +SKIP + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + + """ + _FLOAT_MODULE = nn.Conv2d + _NNIQAT_CONV_BN_MODULE = nniqat.ConvBn2d + _NNI_CONV_RELU_MODULE = nni.ConvReLU2d + _NNI_CONV_ADD_MODULE = nni.ConvAdd2d + _NNI_CONV_ADD_RELU_MODULE = nni.ConvAddReLU2d + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, + padding=0, dilation=1, groups=1, bias=True, + padding_mode='zeros', device=None, dtype=None): + factory_kwargs = {'device': device, 'dtype': dtype} + kernel_size = _pair(kernel_size) + stride = _pair(stride) + padding = _pair(padding) + dilation = _pair(dilation) + # Subclasses of _ConvNd need to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, out_channels, kernel_size, stride, padding, dilation, + False, _pair(0), groups, bias, padding_mode, **factory_kwargs) + + def _get_name(self): + return 'QuantizedConv2d' + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + if self.padding_mode == 'zeros': + self._packed_params = torch.ops.quantized.conv2d_prepack( + w, b, self.stride, self.padding, self.dilation, self.groups) + else: + self._packed_params = torch.ops.quantized.conv2d_prepack( + w, b, self.stride, _pair(0), self.dilation, self.groups) + + def _weight_bias(self): + return self._packed_params.unpack() + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + if self.padding_mode != 'zeros': + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding) + input = F.pad(input, _reversed_padding_repeated_twice, + mode=self.padding_mode) + return ops.quantized.conv2d( + input, self._packed_params, self.scale, self.zero_point) + + @classmethod + def from_float(cls, mod): + r"""Creates a quantized module from a float module or qparams_dict. + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + return _ConvNd.from_float(cls, mod) + + +class Conv3d(_ConvNd): + r"""Applies a 3D convolution over a quantized input signal composed of + several quantized input planes. + + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.Conv3d`. + + .. note:: + Only `zeros` is supported for the :attr:`padding_mode` argument. + + .. note:: + Only `torch.quint8` is supported for the input data type. + + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + + See :class:`~torch.nn.Conv3d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> # With square kernels and equal stride + >>> m = nn.quantized.Conv3d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2)) + >>> # non-square kernels and unequal stride and with padding and dilation + >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2)) + >>> input = torch.randn(20, 16, 56, 56, 56) + >>> # quantize input to quint8 + >>> # xdoctest: +SKIP + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + + """ + _FLOAT_MODULE = nn.Conv3d + _NNIQAT_CONV_BN_MODULE = nniqat.ConvBn3d + _NNI_CONV_RELU_MODULE = nni.ConvReLU3d + _NNI_CONV_ADD_MODULE = None + _NNI_CONV_ADD_RELU_MODULE = None + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, + padding=0, dilation=1, groups=1, bias=True, + padding_mode='zeros', device=None, dtype=None): + assert padding_mode != 'reflect', "Conv3d does not support reflection padding" + factory_kwargs = {'device': device, 'dtype': dtype} + kernel_size = _triple(kernel_size) + stride = _triple(stride) + padding = _triple(padding) + dilation = _triple(dilation) + # Subclasses of _ConvNd need to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, out_channels, kernel_size, stride, padding, dilation, + False, _triple(0), groups, bias, padding_mode, **factory_kwargs) + + def _get_name(self): + return 'QuantizedConv3d' + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + if self.padding_mode == 'zeros': + self._packed_params = torch.ops.quantized.conv3d_prepack( + w, b, self.stride, self.padding, self.dilation, self.groups) + else: + self._packed_params = torch.ops.quantized.conv3d_prepack( + w, b, self.stride, _triple(0), self.dilation, self.groups) + + def _weight_bias(self): + return self._packed_params.unpack() + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, D, H, W)`!") + if self.padding_mode != 'zeros': + _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding) + input = F.pad(input, _reversed_padding_repeated_twice, + mode=self.padding_mode) + return ops.quantized.conv3d( + input, self._packed_params, self.scale, self.zero_point) + + @classmethod + def from_float(cls, mod): + r"""Creates a quantized module from a float module or qparams_dict. + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + return _ConvNd.from_float(cls, mod) + +# === Transposed Convolutions === +MOD = TypeVar('MOD', bound=nn.modules.conv._ConvNd) + + +class _ConvTransposeNd(_ConvNd): + + _FLOAT_MODULE = MOD + + def __init__(self, in_channels, out_channels, kernel_size, stride, + padding, dilation, transposed, output_padding, + groups, bias, padding_mode, device=None, dtype=None): + if padding_mode != 'zeros': + raise ValueError(f'Only "zeros" padding mode is supported for {self.__class__.__name__}') + factory_kwargs = {'device': device, 'dtype': dtype} + # Subclasses of _ConvNd need to call _init rather than __init__. See + # discussion on PR #49702 + super()._init( + in_channels, out_channels, kernel_size, stride, + padding, dilation, transposed, output_padding, + groups, bias, padding_mode, **factory_kwargs) + + def _input_padding(self, kernel_size: List[int], dilation: List[int], padding: List[int]) -> List[int]: + res = torch.jit.annotate(List[int], []) + for kdx in range(len(kernel_size)): + pad = (dilation[kdx] * (kernel_size[kdx] - 1) - padding[kdx]) + res.append(pad) + return res + + @classmethod + def from_float(cls, mod): + r"""Creates a quantized module from a float module or qparams_dict. + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + # derived classes override cls._FLOAT_MODULE attribute + msg = ' nnq.' + cls.__name__ + '.from_float only works for ' + \ + cls._FLOAT_MODULE.__name__ # type: ignore[attr-defined] + assert type(mod) == cls._FLOAT_MODULE, msg + assert hasattr(mod, 'qconfig'), \ + 'Input float module must have qconfig defined.' + weight_post_process = mod.qconfig.weight() + weight_post_process(mod.weight) + assert weight_post_process.dtype == torch.qint8, \ + 'Weight observer must have a dtype of qint8' + qweight = _quantize_weight(mod.weight.float(), weight_post_process) + # the __init__ call used is the one from derived classes and not the one from _ConvTransposeNd + qconv = cls(mod.in_channels, mod.out_channels, mod.kernel_size, # type: ignore[call-arg] + mod.stride, mod.padding, mod.output_padding, mod.groups, + mod.bias is not None, mod.dilation, mod.padding_mode) + qconv.set_weight_bias(qweight, mod.bias) + if not hasattr(mod, "activation_post_process") or mod.activation_post_process.dtype == torch.float: + return qconv # dynamic quantization doesn't need scale/zero_point + else: + act_scale, act_zp = mod.activation_post_process.calculate_qparams() + qconv.scale = float(act_scale) + qconv.zero_point = int(act_zp) + return qconv + + @staticmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module + Args: + ref_qconvt (Module): a reference quantized module, either produced by torch.ao.quantization + utilities or provided by the user + output_scale (float): scale for output Tensor + output_zero_point (int): zero point for output Tensor + """ + qconv = cls( + ref_qconvt.in_channels, + ref_qconvt.out_channels, + ref_qconvt.kernel_size, # type: ignore[arg-type] + ref_qconvt.stride, # type: ignore[arg-type] + ref_qconvt.padding, # type: ignore[arg-type] + ref_qconvt.output_padding, # type: ignore[arg-type] + ref_qconvt.groups, + ref_qconvt.bias is not None, # type: ignore[arg-type] + ref_qconvt.dilation, # type: ignore[arg-type] + ref_qconvt.padding_mode, + device=ref_qconvt.weight.device, + dtype=ref_qconvt.weight.dtype) + qweight = ref_qconvt.get_quantized_weight() + qconv.set_weight_bias(qweight, ref_qconvt.bias) + qconv.scale = float(output_scale) + qconv.zero_point = int(output_zero_point) + return qconv + + +class ConvTranspose1d(_ConvTransposeNd): + r"""Applies a 1D transposed convolution operator over an input image + composed of several input planes. + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.ConvTranspose1d`. + + .. note:: Currently only the QNNPACK engine is implemented. + Please, set the `torch.backends.quantized.engine = 'qnnpack'` + + For special notes, please, see :class:`~torch.ao.nn.quantized.Conv1d` + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + See :class:`~torch.nn.ConvTranspose2d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> torch.backends.quantized.engine = 'qnnpack' + >>> from torch.ao.nn import quantized as nnq + >>> # With square kernels and equal stride + >>> m = nnq.ConvTranspose1d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nnq.ConvTranspose1d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> input = torch.randn(20, 16, 50) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> downsample = nnq.Conv1d(16, 16, 3, stride=2, padding=1) + >>> upsample = nnq.ConvTranspose1d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(q_input) + >>> h.size() + torch.Size([1, 16, 6]) + >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12]) + """ + + _FLOAT_MODULE = nn.ConvTranspose1d + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, + padding=0, output_padding=0, groups=1, bias=True, + dilation=1, padding_mode='zeros', device=None, dtype=None): + factory_kwargs = {'device': device, 'dtype': dtype} + kernel_size = _single(kernel_size) + stride = _single(stride) + padding = _single(padding) + dilation = _single(dilation) + output_padding = _single(output_padding) + + super().__init__( + in_channels, out_channels, kernel_size, stride, padding, dilation, + True, output_padding, groups, bias, padding_mode, **factory_kwargs) + + def _get_name(self): + return 'QuantizedConvTranspose1d' + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params = torch.ops.quantized.conv_transpose1d_prepack( + w, b, self.stride, self.padding, self.output_padding, self.dilation, + self.groups) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv_transpose1d_unpack(self._packed_params) + return w, b + + def weight(self): + (w, _) = self._weight_bias() + return w + + def bias(self): + (_, b) = self._weight_bias() + return b + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 3: + raise ValueError("Input shape must be `(N, C, L)`!") + return torch.ops.quantized.conv_transpose1d( + input, self._packed_params, self.scale, self.zero_point) + + @classmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + return _ConvTransposeNd.from_reference(cls, ref_qconvt, output_scale, output_zero_point) + + +class ConvTranspose2d(_ConvTransposeNd): + r"""Applies a 2D transposed convolution operator over an input image + composed of several input planes. + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.ConvTranspose2d`. + + For special notes, please, see :class:`~torch.ao.nn.quantized.Conv2d` + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + See :class:`~torch.nn.ConvTranspose2d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> # QNNPACK or FBGEMM as backend + >>> torch.backends.quantized.engine = 'qnnpack' + >>> # With square kernels and equal stride + >>> import torch.ao.nn.quantized as nnq + >>> m = nnq.ConvTranspose2d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nnq.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> input = torch.randn(20, 16, 50, 100) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12, 12) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> downsample = nnq.Conv2d(16, 16, 3, stride=2, padding=1) + >>> upsample = nnq.ConvTranspose2d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(q_input) + >>> h.size() + torch.Size([1, 16, 6, 6]) + >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12, 12]) + """ + + _FLOAT_MODULE = nn.ConvTranspose2d + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, + padding=0, output_padding=0, groups=1, bias=True, + dilation=1, padding_mode='zeros', device=None, dtype=None): + factory_kwargs = {'device': device, 'dtype': dtype} + kernel_size = _pair(kernel_size) + stride = _pair(stride) + padding = _pair(padding) + dilation = _pair(dilation) + output_padding = _pair(output_padding) + + super().__init__( + in_channels, out_channels, kernel_size, stride, padding, dilation, + True, output_padding, groups, bias, padding_mode, **factory_kwargs) + + def _get_name(self): + return 'QuantizedConvTranspose2d' + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params = torch.ops.quantized.conv_transpose2d_prepack( + w, b, self.stride, self.padding, self.output_padding, self.dilation, + self.groups) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv2d_unpack(self._packed_params) + return w, b + + def weight(self): + (w, _) = self._weight_bias() + return w + + def bias(self): + (_, b) = self._weight_bias() + return b + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + return ops.quantized.conv_transpose2d( + input, self._packed_params, self.scale, self.zero_point) + + @classmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + return _ConvTransposeNd.from_reference(cls, ref_qconvt, output_scale, output_zero_point) + + +class ConvTranspose3d(_ConvTransposeNd): + r"""Applies a 3D transposed convolution operator over an input image + composed of several input planes. + For details on input arguments, parameters, and implementation see + :class:`~torch.nn.ConvTranspose3d`. + + .. note:: Currently only the FBGEMM engine is implemented. + Please, set the `torch.backends.quantized.engine = 'fbgemm'` + + For special notes, please, see :class:`~torch.ao.nn.quantized.Conv3d` + + Attributes: + weight (Tensor): packed tensor derived from the learnable weight + parameter. + scale (Tensor): scalar for the output scale + zero_point (Tensor): scalar for the output zero point + See :class:`~torch.nn.ConvTranspose3d` for other attributes. + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> torch.backends.quantized.engine = 'fbgemm' + >>> from torch.ao.nn import quantized as nnq + >>> # With cubic kernels and equal stride + >>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2) + >>> # non-cubic kernels and unequal stride and with padding + >>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2)) + >>> input = torch.randn(20, 16, 50, 100, 100) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> output = m(q_input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12, 12, 12) + >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8) + >>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1) + >>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(q_input) + >>> h.size() + torch.Size([1, 16, 6, 6, 6]) + >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12, 12, 12]) + """ + + _FLOAT_MODULE = nn.ConvTranspose3d + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, + padding=0, output_padding=0, groups=1, bias=True, + dilation=1, padding_mode='zeros', device=None, dtype=None): + factory_kwargs = {'device': device, 'dtype': dtype} + kernel_size = _triple(kernel_size) + stride = _triple(stride) + padding = _triple(padding) + dilation = _triple(dilation) + output_padding = _triple(output_padding) + + super().__init__( + in_channels, out_channels, kernel_size, stride, padding, dilation, + True, output_padding, groups, bias, padding_mode, **factory_kwargs) + + def _get_name(self): + return 'QuantizedConvTranspose3d' + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params = torch.ops.quantized.conv_transpose3d_prepack( + w, b, self.stride, self.padding, self.output_padding, self.dilation, + self.groups) + + def _weight_bias(self): + w, b = torch.ops.quantized.conv3d_unpack(self._packed_params) + return w, b + + def weight(self): + (w, _) = self._weight_bias() + return w + + def bias(self): + (_, b) = self._weight_bias() + return b + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, T, H, W)`!") + return ops.quantized.conv_transpose3d( + input, self._packed_params, self.scale, self.zero_point) + + @classmethod + def from_reference(cls, ref_qconvt, output_scale, output_zero_point): + return _ConvTransposeNd.from_reference(cls, ref_qconvt, output_scale, output_zero_point) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..64110ab53bed9a7620804a7732caebf36c84d2ca --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py @@ -0,0 +1,27 @@ +import torch + +__all__ = ['Dropout'] + +class Dropout(torch.nn.Dropout): + r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`. + And this is a placeholder to enable models where fp32 tensors + had dropout to work with quantized tensors in train and eval mode. + + Args: + p: probability of an element to be zeroed + inplace: can optionally do the operation in-place. Default: ``False`` + """ + + def forward(self, input): + return input + + def _get_name(self): + return 'QuantizedDropout' + + @classmethod + def from_float(cls, mod): + return cls(mod.p, mod.inplace) + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls(mod.p, mod.inplace) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c4389a60d9b08fa264765ead9ad3f2932e141be9 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py @@ -0,0 +1,295 @@ +import torch +import torch.nn as nn +from torch import Tensor # noqa: F401 +from torch._jit_internal import Optional, List # noqa: F401 + +from .utils import _hide_packed_params_repr +from .utils import _quantize_weight + +__all__ = ['EmbeddingPackedParams', 'Embedding', 'EmbeddingBag'] + +class EmbeddingPackedParams(torch.nn.Module): + _version = 1 + + def __init__(self, num_embeddings, embedding_dim, dtype=torch.quint8): + super().__init__() + self.dtype = dtype + if self.dtype in [torch.quint8, torch.quint4x2]: + scales = torch.ones(num_embeddings, dtype=torch.float) + zero_points = torch.zeros(num_embeddings, dtype=torch.float) + wq = torch._empty_per_channel_affine_quantized([num_embeddings, embedding_dim], scales=scales, + zero_points=zero_points, + axis=0, dtype=self.dtype) + self.set_weight(wq) + else: + raise NotImplementedError(f'Unsupported dtype on quantized embedding! Supports quint8 and quint4x2. Got dtype: {dtype}') + + @torch.jit.export + def set_weight(self, weight: torch.Tensor) -> None: + if self.dtype in [torch.quint8, torch.quint4x2]: + self._packed_weight = torch.ops.quantized.embedding_bag_prepack(weight) + else: + raise NotImplementedError('Unsupported dtype for quantized embedding prepack! Supports quint8 and quint4x2.') + + + @torch.jit.export + def _weight(self): + if self.dtype in [torch.quint8, torch.quint4x2]: + return torch.ops.quantized.embedding_bag_unpack(self._packed_weight) + else: + raise NotImplementedError('Unsupported dtype for quantized embedding unpack! Supports quint8 and quint4x2.') + + def forward(self, x): + return x + + # Version 1 + # self + # |--- _packed_weight : Tensor representing weight of EmbeddingPackedParamsBase + # |--- dtype : torch.dtype + + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + 'dtype'] = self.dtype + destination[prefix + '_packed_weight'] = self._weight() + + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + self.dtype = state_dict[prefix + 'dtype'] + state_dict.pop(prefix + 'dtype') + + weight = state_dict[prefix + '_packed_weight'] + state_dict.pop(prefix + '_packed_weight') + self.set_weight(weight) + + super()._load_from_state_dict(state_dict, prefix, local_metadata, False, + missing_keys, unexpected_keys, error_msgs) + + def __repr__(self): + return self._weight().__repr__() + +class Embedding(torch.nn.Module): + r""" + A quantized Embedding module with quantized packed weights as inputs. + We adopt the same interface as `torch.nn.Embedding`, please see + https://pytorch.org/docs/stable/nn.html#torch.nn.Embedding for documentation. + + Similar to :class:`~torch.nn.Embedding`, attributes will be randomly + initialized at module creation time and will be overwritten later + + Attributes: + weight (Tensor): the non-learnable quantized weights of the module of + shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`. + + Examples:: + >>> m = nn.quantized.Embedding(num_embeddings=10, embedding_dim=12) + >>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8]) + >>> output = m(indices) + >>> print(output.size()) + torch.Size([9, 12]) + + """ + _version = 1 + + def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None, + max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False, + sparse: bool = False, _weight: Optional[Tensor] = None, dtype=torch.quint8) -> None: + super().__init__() + self.num_embeddings = num_embeddings + self.embedding_dim = embedding_dim + self.dtype = dtype + + if _weight is None: + scales = torch.ones(num_embeddings, dtype=torch.float) + zero_points = torch.zeros(num_embeddings, dtype=torch.float) + qweight = torch._empty_per_channel_affine_quantized([num_embeddings, embedding_dim], + scales=scales, zero_points=zero_points, + axis=0, dtype=torch.quint8) + else: + assert list(_weight.shape) == [num_embeddings, embedding_dim], \ + 'Shape of weight does not match num_embeddings and embedding_dim' + qweight = _weight + + self._packed_params = EmbeddingPackedParams(num_embeddings, embedding_dim, dtype) + self._packed_params.set_weight(qweight) + + def forward(self, indices: Tensor) -> Tensor: + if self.dtype == torch.quint4x2: + return torch.ops.quantized.embedding_4bit(self._packed_params._packed_weight, indices) + else: + return torch.ops.quantized.embedding_byte(self._packed_params._packed_weight, indices) + + def _get_name(self): + return 'QuantizedEmbedding' + + def __repr__(self): + return _hide_packed_params_repr(self, EmbeddingPackedParams) + + def extra_repr(self): + extra_repr_str = 'num_embeddings={}, embedding_dim={}, dtype={}, qscheme={}'.format( + self.num_embeddings, self.embedding_dim, self._packed_params.dtype, self.weight().qscheme() + ) + + return extra_repr_str + + def set_weight(self, w: torch.Tensor) -> None: + self._packed_params.set_weight(w) + + def weight(self): + return self._packed_params._weight() + + @classmethod + def from_float(cls, mod): + r"""Create a quantized embedding module from a float module + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by user + """ + if hasattr(mod, 'weight_fake_quant'): + assert type(mod) == torch.ao.nn.qat.Embedding, 'nnq.' + cls.__name__ + '.from_float ' + \ + 'with fake quant only works for ' + torch.ao.nn.qat.Embedding.__name__ + weight_observer = mod.weight_fake_quant + activation_post_process = mod.activation_post_process + else: + assert type(mod) == nn.Embedding, 'nnq.' + cls.__name__ + '.from_float only works for ' + \ + nn.Embedding.__name__ + assert hasattr(mod, 'qconfig'), 'Embedding input float module must have qconfig defined' + from torch.ao.quantization import float_qparams_weight_only_qconfig + if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr] + weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator] + else: + weight_observer = float_qparams_weight_only_qconfig.weight() + + dtype = weight_observer.dtype + is_float_qparams_qconfig = weight_observer.qscheme == torch.per_channel_affine_float_qparams + assert is_float_qparams_qconfig, \ + 'Embedding quantization is only supported with float_qparams_weight_only_qconfig.' + + assert dtype == torch.quint8 or dtype == torch.quint4x2, \ + f'The only supported dtype for nnq.Embedding is torch.quint8 and torch.quint4x2, got {dtype}' + + # Run the observer to calculate qparams. + weight_observer(mod.weight) + qweight = _quantize_weight(mod.weight.float(), weight_observer) + + # Create quantized Embedding module and pass in the quantized weight + qembedding = Embedding(mod.num_embeddings, mod.embedding_dim) + qembedding.set_weight(qweight) + return qembedding + + @classmethod + def from_reference(cls, ref_embedding): + qembedding = cls( + ref_embedding.num_embeddings, + ref_embedding.embedding_dim, + ref_embedding.padding_idx, + ref_embedding.max_norm, + ref_embedding.norm_type, + ref_embedding.scale_grad_by_freq, + ref_embedding.sparse, + ref_embedding.get_quantized_weight(), + ref_embedding.weight_dtype, + ) + return qembedding + +class EmbeddingBag(Embedding): + r""" + A quantized EmbeddingBag module with quantized packed weights as inputs. + We adopt the same interface as `torch.nn.EmbeddingBag`, please see + https://pytorch.org/docs/stable/nn.html#torch.nn.EmbeddingBag for documentation. + + Similar to :class:`~torch.nn.EmbeddingBag`, attributes will be randomly + initialized at module creation time and will be overwritten later + + Attributes: + weight (Tensor): the non-learnable quantized weights of the module of + shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`. + + Examples:: + >>> m = nn.quantized.EmbeddingBag(num_embeddings=10, embedding_dim=12, include_last_offset=True, mode='sum') + >>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8, 6, 6, 9, 1, 6, 8, 8, 3, 2, 3, 6, 3, 6, 5, 7, 0, 8, 4, 6, 5, 8, 2, 3]) + >>> offsets = torch.tensor([0, 19, 20, 28, 28, 32]) + >>> output = m(indices, offsets) + >>> print(output.size()) + torch.Size([5, 12]) + + """ + _version = 1 + + def __init__(self, num_embeddings: int, embedding_dim: int, + max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False, + mode: str = 'sum', sparse: bool = False, _weight: Optional[Tensor] = None, + include_last_offset: bool = False, dtype=torch.quint8) -> None: + super().__init__(num_embeddings, embedding_dim, _weight=_weight, dtype=dtype) + + self.mode = mode + self.pruned_weights = False + self.include_last_offset = include_last_offset + self.dtype = dtype + + def forward(self, indices: Tensor, offsets: Optional[Tensor] = None, per_sample_weights: Optional[Tensor] = None, + compressed_indices_mapping: Optional[Tensor] = None) -> Tensor: + if self.dtype == torch.quint4x2: + return torch.ops.quantized.embedding_bag_4bit(self._packed_params._packed_weight, indices, offsets, False, 0, + self.pruned_weights, per_sample_weights, compressed_indices_mapping, + self.include_last_offset) + else: + return torch.ops.quantized.embedding_bag_byte(self._packed_params._packed_weight, indices, offsets, False, 0, + self.pruned_weights, per_sample_weights, compressed_indices_mapping, + self.include_last_offset) + + def _get_name(self): + return 'QuantizedEmbeddingBag' + + @classmethod + def from_float(cls, mod): + r"""Create a quantized embedding_bag module from a float module + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by user + """ + if hasattr(mod, 'weight_fake_quant'): + weight_observer = mod.weight_fake_quant + else: + assert type(mod) == nn.EmbeddingBag, 'nnq.' + cls.__name__ + '.from_float only works for ' + \ + nn.EmbeddingBag.__name__ + assert hasattr(mod, 'qconfig'), 'EmbeddingBag input float module must have qconfig defined' + from torch.ao.quantization.qconfig import float_qparams_weight_only_qconfig + if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr] + weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator] + else: + weight_observer = float_qparams_weight_only_qconfig.weight() + + dtype = weight_observer.dtype + is_float_qparams_qconfig = weight_observer.qscheme == torch.per_channel_affine_float_qparams + assert is_float_qparams_qconfig, \ + 'EmbeddingBag quantization is only supported with float_qparams_weight_only_qconfig.' + + assert dtype == torch.quint8 or dtype == torch.quint4x2, \ + f'The only supported dtype for nnq.EmbeddingBag is torch.quint8 and torch.quint4x2, got {dtype}' + + # Run the observer to calculate qparams. + weight_observer(mod.weight) + qweight = _quantize_weight(mod.weight.float(), weight_observer) + + # Create quantized EmbeddingBag module and pass in the quantized weight + qembedding_bag = EmbeddingBag(mod.num_embeddings, mod.embedding_dim, dtype=dtype) + qembedding_bag.set_weight(qweight) + return qembedding_bag + + @classmethod + def from_reference(cls, ref_embedding_bag): + qembedding_bag = cls( + ref_embedding_bag.num_embeddings, + ref_embedding_bag.embedding_dim, + ref_embedding_bag.max_norm, + ref_embedding_bag.norm_type, + ref_embedding_bag.scale_grad_by_freq, + ref_embedding_bag.mode, + ref_embedding_bag.sparse, + ref_embedding_bag.get_quantized_weight(), + ref_embedding_bag.include_last_offset, + ref_embedding_bag.weight_dtype, + ) + return qembedding_bag diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/functional_modules.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/functional_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..56778c592173750902554631170e7771bef3755d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/functional_modules.py @@ -0,0 +1,249 @@ +from typing import List + +import torch +from torch import Tensor +from torch._ops import ops + +__all__ = ['FloatFunctional', 'FXFloatFunctional', 'QFunctional'] + +class FloatFunctional(torch.nn.Module): + r"""State collector class for float operations. + + The instance of this class can be used instead of the ``torch.`` prefix for + some operations. See example usage below. + + .. note:: + + This class does not provide a ``forward`` hook. Instead, you must use + one of the underlying functions (e.g. ``add``). + + Examples:: + + >>> f_add = FloatFunctional() + >>> a = torch.tensor(3.0) + >>> b = torch.tensor(4.0) + >>> f_add.add(a, b) # Equivalent to ``torch.add(a, b)`` + + Valid operation names: + - add + - cat + - mul + - add_relu + - add_scalar + - mul_scalar + """ + def __init__(self): + super().__init__() + self.activation_post_process = torch.nn.Identity() + + def forward(self, x): + raise RuntimeError("FloatFunctional is not intended to use the " + + "'forward'. Please use the underlying operation") + + r"""Operation equivalent to ``torch.add(Tensor, Tensor)``""" + def add(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.add(x, y) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.add(Tensor, float)``""" + def add_scalar(self, x: Tensor, y: float) -> Tensor: + r = torch.add(x, y) + # Note: this operation is not observed because the observation is not + # needed for the quantized op. + return r + + r"""Operation equivalent to ``torch.mul(Tensor, Tensor)``""" + def mul(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.mul(x, y) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.mul(Tensor, float)``""" + def mul_scalar(self, x: Tensor, y: float) -> Tensor: + r = torch.mul(x, y) + # Note: this operation is not observed because the observation is not + # needed for the quantized op. + return r + + r"""Operation equivalent to ``torch.cat``""" + def cat(self, x: List[Tensor], dim: int = 0) -> Tensor: + r = torch.cat(x, dim=dim) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``relu(torch.add(x,y))``""" + def add_relu(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.add(x, y) + r = torch.nn.functional.relu(r) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.matmul(Tensor, Tensor)``""" + def matmul(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.matmul(x, y) + r = self.activation_post_process(r) + return r + +class FXFloatFunctional(torch.nn.Module): + r""" module to replace FloatFunctional module before FX graph mode quantization, + since activation_post_process will be inserted in top level module directly + + Valid operation names: + - add + - cat + - mul + - add_relu + - add_scalar + - mul_scalar + """ + def forward(self, x): + raise RuntimeError("FloatFunctional is not intended to use the " + + "'forward'. Please use the underlying operation") + + r"""Operation equivalent to ``torch.add(Tensor, Tensor)``""" + def add(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.add(x, y) + return r + + r"""Operation equivalent to ``torch.add(Tensor, float)``""" + def add_scalar(self, x: Tensor, y: float) -> Tensor: + r = torch.add(x, y) + return r + + r"""Operation equivalent to ``torch.mul(Tensor, Tensor)``""" + def mul(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.mul(x, y) + return r + + r"""Operation equivalent to ``torch.mul(Tensor, float)``""" + def mul_scalar(self, x: Tensor, y: float) -> Tensor: + r = torch.mul(x, y) + return r + + r"""Operation equivalent to ``torch.cat``""" + def cat(self, x: List[Tensor], dim: int = 0) -> Tensor: + r = torch.cat(x, dim=dim) + return r + + r"""Operation equivalent to ``relu(torch.add(x,y))``""" + def add_relu(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.add(x, y) + r = torch.nn.functional.relu(r) + return r + + r"""Operation equivalent to ``torch.matmul(Tensor, Tensor)``""" + def matmul(self, x: Tensor, y: Tensor) -> Tensor: + r = torch.matmul(x, y) + return r + +class QFunctional(torch.nn.Module): + r"""Wrapper class for quantized operations. + + The instance of this class can be used instead of the + ``torch.ops.quantized`` prefix. See example usage below. + + .. note:: + + This class does not provide a ``forward`` hook. Instead, you must use + one of the underlying functions (e.g. ``add``). + + Examples:: + + >>> q_add = QFunctional() + >>> # xdoctest: +SKIP + >>> a = torch.quantize_per_tensor(torch.tensor(3.0), 1.0, 0, torch.qint32) + >>> b = torch.quantize_per_tensor(torch.tensor(4.0), 1.0, 0, torch.qint32) + >>> q_add.add(a, b) # Equivalent to ``torch.ops.quantized.add(a, b, 1.0, 0)`` + + Valid operation names: + - add + - cat + - mul + - add_relu + - add_scalar + - mul_scalar + """ + def __init__(self): + super().__init__() + self.scale = 1.0 + self.zero_point = 0 + self.activation_post_process = torch.nn.Identity() + + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + 'scale'] = torch.tensor(self.scale) + destination[prefix + 'zero_point'] = torch.tensor(self.zero_point) + + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + + self.scale = float(state_dict.pop(prefix + 'scale')) + self.zero_point = int(state_dict.pop(prefix + 'zero_point')) + super()._load_from_state_dict(state_dict, prefix, local_metadata, False, + missing_keys, unexpected_keys, error_msgs) + + def _get_name(self): + return 'QFunctional' + + def extra_repr(self): + return f'scale={self.scale}, zero_point={self.zero_point}' + + def forward(self, x): + raise RuntimeError("Functional is not intended to use the " + + "'forward'. Please use the underlying operation") + + r"""Operation equivalent to ``torch.ops.quantized.add``""" + def add(self, x: Tensor, y: Tensor) -> Tensor: + r = ops.quantized.add(x, y, scale=self.scale, zero_point=self.zero_point) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.ops.quantized.add(Tensor, float)``""" + def add_scalar(self, x: Tensor, y: float) -> Tensor: + r = ops.quantized.add_scalar(x, y) + # Note: this operation is not observed because the observation is not + # needed for the quantized op. + return r + + r"""Operation equivalent to ``torch.ops.quantized.mul(Tensor, Tensor)``""" + def mul(self, x: Tensor, y: Tensor) -> Tensor: + r = ops.quantized.mul(x, y, scale=self.scale, zero_point=self.zero_point) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.ops.quantized.mul(Tensor, float)``""" + def mul_scalar(self, x: Tensor, y: float) -> Tensor: + r = ops.quantized.mul_scalar(x, y) + # Note: this operation is not observed because the observation is not + # needed for the quantized op. + return r + + r"""Operation equivalent to ``torch.ops.quantized.cat``""" + def cat(self, x: List[Tensor], dim: int = 0) -> Tensor: + r = ops.quantized.cat(x, scale=self.scale, zero_point=self.zero_point, dim=dim) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.ops.quantized.add_relu``""" + def add_relu(self, x: Tensor, y: Tensor) -> Tensor: + r = ops.quantized.add_relu(x, y, scale=self.scale, zero_point=self.zero_point) + r = self.activation_post_process(r) + return r + + r"""Operation equivalent to ``torch.ops.quantized.matmul(Tensor, Tensor)``""" + def matmul(self, x: Tensor, y: Tensor) -> Tensor: + r = ops.quantized.matmul(x, y, scale=self.scale, zero_point=self.zero_point) + # Note: this operation is not observed because the observation is not + # needed for the quantized op. + return r + + @classmethod + def from_float(cls, mod): + assert type(mod) == FloatFunctional,\ + "QFunctional.from_float expects an instance of FloatFunctional" + scale, zero_point = mod.activation_post_process.calculate_qparams() # type: ignore[operator] + new_mod = QFunctional() + new_mod.scale = float(scale) + new_mod.zero_point = int(zero_point) + return new_mod diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/linear.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..213934e62962a09c30d5b21eb4eae766959a4f9c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/linear.py @@ -0,0 +1,303 @@ +from collections.abc import Iterable +import torch + +import torch.nn as nn +import torch.ao.nn.intrinsic as nni +import torch.ao.nn.intrinsic.qat as nniqat +from torch.nn.utils.fusion import fuse_linear_bn_weights +from torch.nn.utils.parametrize import type_before_parametrizations + +from typing import Optional + +from .utils import _quantize_weight, _hide_packed_params_repr, WeightedQuantizedModule + +__all__ = ['LinearPackedParams', 'Linear'] + + +class LinearPackedParams(torch.nn.Module): + _version = 3 + + def __init__(self, dtype=torch.qint8): + super().__init__() + self.dtype = dtype + if self.dtype == torch.qint8: + wq = torch._empty_affine_quantized([1, 1], scale=1.0, zero_point=0, dtype=torch.qint8) + elif self.dtype == torch.float16: + wq = torch.zeros([1, 1], dtype=torch.float) + self.set_weight_bias(wq, None) + + @torch.jit.export + def set_weight_bias(self, weight: torch.Tensor, bias: Optional[torch.Tensor]) -> None: + if self.dtype == torch.qint8: + self._packed_params = torch.ops.quantized.linear_prepack(weight, bias) + elif self.dtype == torch.float16: + self._packed_params = torch.ops.quantized.linear_prepack_fp16(weight, bias) + else: + raise RuntimeError('Unsupported dtype on dynamic quantized linear!') + + + @torch.jit.export + def _weight_bias(self): + if self.dtype == torch.qint8: + return torch.ops.quantized.linear_unpack(self._packed_params) + elif self.dtype == torch.float16: + return torch.ops.quantized.linear_unpack_fp16(self._packed_params) + else: + raise RuntimeError('Unsupported dtype on dynamic quantized linear!') + + def forward(self, x): + return x + + # Version 1 + # self + # |--- weight : Tensor + # |--- bias : Tensor + # + # Version 2 + # self + # |--- weight : Tensor + # |--- bias : Tensor + # |--- dtype : torch.dtype + # + # Version 3 + # self + # |--- _packed_params : (Tensor, Tensor) representing (weight, bias) + # of LinearPackedParams + # |--- dtype : torch.dtype + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + 'dtype'] = self.dtype + destination[prefix + '_packed_params'] = self._weight_bias() + + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + version = local_metadata.get('version', None) + if version is None or version < 2: + self.dtype = torch.qint8 + else: + self.dtype = state_dict[prefix + 'dtype'] + state_dict.pop(prefix + 'dtype') + + if version is None or version < 3: + self.set_weight_bias(state_dict[prefix + 'weight'], state_dict[prefix + 'bias']) + state_dict.pop(prefix + 'weight') + state_dict.pop(prefix + 'bias') + + if version == 3: + weight, bias = state_dict[prefix + '_packed_params'] + state_dict.pop(prefix + '_packed_params') + self.set_weight_bias(weight, bias) + + super()._load_from_state_dict(state_dict, prefix, local_metadata, False, + missing_keys, unexpected_keys, error_msgs) + + + def __repr__(self): + return self._weight_bias().__repr__() + + +class Linear(WeightedQuantizedModule): + r""" + A quantized linear module with quantized tensor as inputs and outputs. + We adopt the same interface as `torch.nn.Linear`, please see + https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation. + + Similar to :class:`~torch.nn.Linear`, attributes will be randomly + initialized at module creation time and will be overwritten later + + Attributes: + weight (Tensor): the non-learnable quantized weights of the module of + shape :math:`(\text{out\_features}, \text{in\_features})`. + bias (Tensor): the non-learnable bias of the module of shape :math:`(\text{out\_features})`. + If :attr:`bias` is ``True``, the values are initialized to zero. + scale: `scale` parameter of output Quantized Tensor, type: double + zero_point: `zero_point` parameter for output Quantized Tensor, type: long + + Examples:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE) + >>> m = nn.quantized.Linear(20, 30) + >>> input = torch.randn(128, 20) + >>> # xdoctest: +SKIP + >>> input = torch.quantize_per_tensor(input, 1.0, 0, torch.quint8) + >>> output = m(input) + >>> print(output.size()) + torch.Size([128, 30]) + """ + _version = 3 + _FLOAT_MODULE = (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear) + + def __init__(self, in_features, out_features, bias_=True, + dtype=torch.qint8): + super().__init__() + # We don't muck around with buffers or attributes or anything here + # to keep the module simple. *everything* is simply a Python attribute. + # Serialization logic is explicitly handled in the below serialization and + # deserialization modules + self.in_features = in_features + self.out_features = out_features + bias = None + if bias_: + bias = torch.zeros(out_features, dtype=torch.float) + + if dtype == torch.qint8: + qweight = torch._empty_affine_quantized( + [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8) + elif dtype == torch.float16: + qweight = torch.zeros([out_features, in_features], dtype=torch.float) + else: + raise RuntimeError('Unsupported dtype specified for quantized Linear!') + + self._packed_params = LinearPackedParams(dtype) + self._packed_params.set_weight_bias(qweight, bias) + self.scale = 1.0 + self.zero_point = 0 + + def _get_name(self): + return 'QuantizedLinear' + + def extra_repr(self): + return 'in_features={}, out_features={}, scale={}, zero_point={}, qscheme={}'.format( + self.in_features, self.out_features, self.scale, self.zero_point, self.weight().qscheme() + ) + + def __repr__(self): + return _hide_packed_params_repr(self, LinearPackedParams) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return torch.ops.quantized.linear( + x, self._packed_params._packed_params, self.scale, self.zero_point) + + # ===== Serialization methods ===== + # The special consideration here is that we have to unpack the weights into their + # regular QTensor form for serialization. Packed weights should not live + # outside the process in which they were created, rather they should be derived + # from the QTensor weight. + # + # Version 1 + # self + # |--- scale : float + # |--- zero_point : int + # |--- weight : Tensor + # |--- bias : Tensor + # + # Version 2 + # self + # |--- scale : float + # |--- zero_point : int + # |--- _packed_params : Module + # |--- weight : Tensor + # |--- bias : Tensor + # + # Version 3 + # self + # |--- scale : float + # |--- zero_point : int + # |--- _packed_params : Module + # |--- _packed_params : (Tensor, Tensor) representing weight, bias + # of LinearPackedParams C++ struct + # + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + 'scale'] = torch.tensor(self.scale) + destination[prefix + 'zero_point'] = torch.tensor(self.zero_point) + + # ===== Deserialization methods ===== + # Counterpart to the serialization methods, we must pack the serialized QTensor + # weight into its packed format for use by the FBGEMM ops. + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + self.scale = float(state_dict[prefix + 'scale']) + state_dict.pop(prefix + 'scale') + + self.zero_point = int(state_dict[prefix + 'zero_point']) + state_dict.pop(prefix + 'zero_point') + + version = local_metadata.get('version', None) + + if version is None or version == 1: + # We moved the parameters into a LinearPackedParameters submodule + weight = state_dict.pop(prefix + 'weight') + bias = state_dict.pop(prefix + 'bias') + state_dict.update({prefix + '_packed_params.weight': weight, + prefix + '_packed_params.bias': bias}) + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, False, + missing_keys, unexpected_keys, error_msgs) + + # Function rather than property to make sure that JIT serialization doesn't + # register this as an attribute + def _weight_bias(self): + return self._packed_params._weight_bias() + + def weight(self): + return self._weight_bias()[0] + + def bias(self): + return self._weight_bias()[1] + + def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None: + self._packed_params.set_weight_bias(w, b) + + @classmethod + def from_float(cls, mod): + r"""Create a quantized module from an observed float module + + Args: + mod (Module): a float module, either produced by torch.ao.quantization + utilities or provided by the user + """ + if hasattr(mod, 'weight_fake_quant'): + if type_before_parametrizations(mod) == nniqat.LinearBn1d: + mod.weight, mod.bias = fuse_linear_bn_weights( + mod.weight, mod.bias, mod.bn.running_mean, mod.bn.running_var, + mod.bn.eps, mod.bn.weight, mod.bn.bias) + weight_post_process = mod.weight_fake_quant + activation_post_process = mod.activation_post_process + else: + # This function does not participate in JIT, so it is OK to ignore + # the type mismatch in assignment. Also, mypy has an issue with + # iterables not being implemented, so we are ignoring those too. + if not isinstance(cls._FLOAT_MODULE, Iterable): + cls._FLOAT_MODULE = [cls._FLOAT_MODULE] # type: ignore[assignment] + supported_modules = ', '.join([float_mod.__name__ for float_mod in cls._FLOAT_MODULE]) # type: ignore[attr-defined] + error_msg = f'nnq.{cls.__name__}.from_float only works for {supported_modules}, but got: {type(mod)}' + assert type_before_parametrizations(mod) in cls._FLOAT_MODULE, error_msg.format() # type: ignore[attr-defined] + assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined' + activation_post_process = mod.activation_post_process + if type_before_parametrizations(mod) == nni.LinearReLU: + mod = mod[0] + weight_post_process = mod.qconfig.weight() + weight_post_process(mod.weight) + dtype = weight_post_process.dtype + act_scale, act_zp = activation_post_process.calculate_qparams() + assert dtype == torch.qint8, 'Weight observer must have dtype torch.qint8' + qweight = _quantize_weight(mod.weight.float(), weight_post_process) + qlinear = cls(mod.in_features, + mod.out_features, + dtype=dtype) + qlinear.set_weight_bias(qweight, mod.bias) + qlinear.scale = float(act_scale) + qlinear.zero_point = int(act_zp) + return qlinear + + @classmethod + def from_reference(cls, ref_qlinear, output_scale, output_zero_point): + r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module + + Args: + ref_qlinear (Module): a reference quantized linear module, either produced by torch.ao.quantization + utilities or provided by the user + output_scale (float): scale for output Tensor + output_zero_point (int): zero point for output Tensor + """ + qlinear = cls( + ref_qlinear.in_features, + ref_qlinear.out_features) + qweight = ref_qlinear.get_quantized_weight() + qlinear.set_weight_bias(qweight, ref_qlinear.bias) + + qlinear.scale = float(output_scale) + qlinear.zero_point = int(output_zero_point) + return qlinear diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/normalization.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..f798a241e3242a74d9d022e6f06b140f65bb5b99 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/normalization.py @@ -0,0 +1,199 @@ +import torch + +__all__ = ['LayerNorm', 'GroupNorm', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d'] + +class LayerNorm(torch.nn.LayerNorm): + r"""This is the quantized version of :class:`~torch.nn.LayerNorm`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + + def __init__(self, normalized_shape, weight, bias, scale, zero_point, eps=1e-5, + elementwise_affine=True, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(normalized_shape, eps=eps, elementwise_affine=elementwise_affine, + **factory_kwargs) + self.weight = weight + self.bias = bias + self.register_buffer('scale', torch.tensor(scale, **factory_kwargs)) + self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.layer_norm( + input, self.normalized_shape, weight=self.weight, bias=self.bias, + eps=self.eps, output_scale=self.scale, output_zero_point=self.zero_point) + + def _get_name(self): + return 'QuantizedLayerNorm' + + @classmethod + def from_float(cls, mod): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.normalized_shape, mod.weight, mod.bias, float(scale), + int(zero_point), mod.eps, mod.elementwise_affine) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.normalized_shape, mod.weight, mod.bias, float(scale), + int(zero_point), mod.eps, mod.elementwise_affine) + +class GroupNorm(torch.nn.GroupNorm): + r"""This is the quantized version of :class:`~torch.nn.GroupNorm`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + __constants__ = ['num_groups', 'num_channels', 'eps', 'affine'] + + def __init__(self, num_groups, num_channels, weight, bias, scale, zero_point, eps=1e-5, + affine=True, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_groups, num_channels, eps, affine, **factory_kwargs) + self.weight = weight + self.bias = bias + self.register_buffer('scale', torch.tensor(scale, **factory_kwargs)) + self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.group_norm( + input, self.num_groups, self.weight, self.bias, self.eps, self.scale, + self.zero_point) + + def _get_name(self): + return 'QuantizedGroupNorm' + + @classmethod + def from_float(cls, mod): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_groups, mod.num_channels, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) + return new_mod + +class InstanceNorm1d(torch.nn.InstanceNorm1d): + r"""This is the quantized version of :class:`~torch.nn.InstanceNorm1d`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + def __init__(self, num_features, weight, bias, scale, zero_point, + eps=1e-5, momentum=0.1, affine=False, + track_running_stats=False, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_features, eps, momentum, affine, track_running_stats, **factory_kwargs) + self.weight = weight + self.bias = bias + self.register_buffer('scale', torch.tensor(scale, **factory_kwargs)) + self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.instance_norm( + input, self.weight, self.bias, self.eps, self.scale, + self.zero_point) + + def _get_name(self): + return 'QuantizedInstanceNorm1d' + + @classmethod + def from_float(cls, mod): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) + +class InstanceNorm2d(torch.nn.InstanceNorm2d): + r"""This is the quantized version of :class:`~torch.nn.InstanceNorm2d`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + def __init__(self, num_features, weight, bias, scale, zero_point, + eps=1e-5, momentum=0.1, affine=False, + track_running_stats=False, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_features, eps, momentum, affine, track_running_stats, **factory_kwargs) + self.weight = weight + self.bias = bias + self.register_buffer('scale', torch.tensor(scale, **factory_kwargs)) + self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.instance_norm( + input, self.weight, self.bias, self.eps, self.scale, + self.zero_point) + + def _get_name(self): + return 'QuantizedInstanceNorm2d' + + @classmethod + def from_float(cls, mod): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) + +class InstanceNorm3d(torch.nn.InstanceNorm3d): + r"""This is the quantized version of :class:`~torch.nn.InstanceNorm3d`. + + Additional args: + * **scale** - quantization scale of the output, type: double. + * **zero_point** - quantization zero point of the output, type: long. + + """ + def __init__(self, num_features, weight, bias, scale, zero_point, + eps=1e-5, momentum=0.1, affine=False, + track_running_stats=False, device=None, dtype=None) -> None: + factory_kwargs = {'device': device, 'dtype': dtype} + super().__init__(num_features, eps, momentum, affine, track_running_stats, **factory_kwargs) + self.weight = weight + self.bias = bias + self.register_buffer('scale', torch.tensor(scale, **factory_kwargs)) + self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs)) + + def forward(self, input): + return torch.ops.quantized.instance_norm( + input, self.weight, self.bias, self.eps, self.scale, + self.zero_point) + + def _get_name(self): + return 'QuantizedInstanceNorm3d' + + @classmethod + def from_float(cls, mod): + scale, zero_point = mod.activation_post_process.calculate_qparams() + new_mod = cls( + mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) + return new_mod + + @classmethod + def from_reference(cls, mod, scale, zero_point): + return cls( + mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point), + mod.eps, mod.affine) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7c24c0ca31dc7c1e0ed348667ad4f1cb69cbda31 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py @@ -0,0 +1,117 @@ +import abc +import torch +import itertools +import collections +from torch.nn.modules.module import _addindent + +__all__ = [ + "WeightedQuantizedModule", +] + +class WeightedQuantizedModule(torch.nn.Module, metaclass=abc.ABCMeta): + """Wrapper for quantized modules than can be lowered from reference modules.""" + @classmethod + @abc.abstractmethod + def from_reference(cls, ref_module, output_scale, output_zero_point): + raise NotImplementedError + +def _get_weight_observer(observer): + # FakeQuantize observer + if hasattr(observer, "activation_post_process"): + observer = observer.activation_post_process + # UniformQuantizationObserverBase observer + return observer + +def _needs_weight_clamping(observer, dtype): + observer = _get_weight_observer(observer) + if dtype in [torch.qint8, torch.quint8, torch.qint32]: + info = torch.iinfo(dtype) + return observer.quant_min > info.min or observer.quant_max < info.max + return False + +def _clamp_weights(qweight, observer, scale, zp): + if not _needs_weight_clamping(observer, qweight.dtype): + return qweight + + observer = _get_weight_observer(observer) + min_, max_ = observer.quant_min, observer.quant_max + + # Doing this because can't use torch.ops.quantized.clamp() with per_channel qscheme yet. + qw_int_max = torch.clone(qweight.int_repr()).fill_(max_) + qw_int_min = torch.clone(qweight.int_repr()).fill_(min_) + qw_int = torch.minimum(torch.maximum(qweight.int_repr(), qw_int_min), qw_int_max) + + if observer.qscheme in [torch.per_tensor_symmetric, + torch.per_tensor_affine]: + qweight = torch._make_per_tensor_quantized_tensor(qw_int, scale.item(), zp.item()) + elif observer.qscheme in [torch.per_channel_symmetric, + torch.per_channel_affine, + torch.per_channel_affine_float_qparams]: + qweight = torch._make_per_channel_quantized_tensor(qw_int, scale, zp, axis=observer.ch_axis) + else: + raise ValueError("Unexpected qscheme " + observer.qscheme) + return qweight + +def _quantize_weight(float_wt, observer): + wt_scale, wt_zp = observer.calculate_qparams() + if observer.qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]: + qweight = torch.quantize_per_tensor( + float_wt, + float(wt_scale), int(wt_zp), torch.qint8) + qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp) + elif observer.qscheme in [torch.per_channel_symmetric, torch.per_channel_affine]: + wt_axis = observer.ch_axis + qweight = torch.quantize_per_channel( + float_wt, + wt_scale.to(torch.double), wt_zp.to(torch.int64), wt_axis, torch.qint8) + qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp) + elif observer.qscheme in [torch.per_channel_affine_float_qparams]: + qweight = torch.quantize_per_channel( + float_wt, + wt_scale.to(torch.float), wt_zp.to(torch.float), observer.ch_axis, observer.dtype) + qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp) + else: + raise ValueError("Unexpected qscheme " + observer.qscheme) + return qweight + +def _ntuple_from_first(n): + """Converts the argument to a tuple of size n + with the first element repeated.""" + def parse(x): + while isinstance(x, collections.abc.Sequence): + if len(x) == n: + break + x = x[0] + return tuple(itertools.repeat(x, n)) + return parse + +def _hide_packed_params_repr(self, params): + # We don't want to show `PackedParams` children, hence custom + # `__repr__`. This is the same as nn.Module.__repr__, except the check + # for the `params module`. + extra_lines = [] + extra_repr = self.extra_repr() + # empty string will be split into list [''] + if extra_repr: + extra_lines = extra_repr.split('\n') + child_lines = [] + for key, module in self._modules.items(): + if isinstance(module, params): + continue + mod_str = repr(module) + mod_str = _addindent(mod_str, 2) + child_lines.append('(' + key + '): ' + mod_str) + lines = extra_lines + child_lines + + main_str = self._get_name() + '(' + if lines: + # simple one-liner info, which most builtin Modules will use + if len(extra_lines) == 1 and not child_lines: + main_str += extra_lines[0] + else: + main_str += '\n ' + '\n '.join(lines) + '\n' + + main_str += ')' + return main_str + +_pair_from_first = _ntuple_from_first(2) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a0eab9c9521644825141f0684c7ad5bac6176d1e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py @@ -0,0 +1,23 @@ +from .backend_config import BackendConfig, BackendPatternConfig, DTypeConfig, DTypeWithConstraints, ObservationType +from .fbgemm import get_fbgemm_backend_config +from .native import get_native_backend_config, get_native_backend_config_dict +from .qnnpack import get_qnnpack_backend_config +from .tensorrt import get_tensorrt_backend_config, get_tensorrt_backend_config_dict +from .executorch import get_executorch_backend_config +from .onednn import get_onednn_backend_config + +__all__ = [ + "get_fbgemm_backend_config", + "get_native_backend_config", + "get_native_backend_config_dict", + "get_qnnpack_backend_config", + "get_tensorrt_backend_config", + "get_tensorrt_backend_config_dict", + "get_executorch_backend_config", + "BackendConfig", + "BackendPatternConfig", + "DTypeConfig", + "DTypeWithConstraints", + "ObservationType", + "get_onednn_backend_config", +] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..002e5183a6622a1aa3735caba5821714e2484db0 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bbf76ca6ad0e0383cdac4ef878dcaa65d93cbfa Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca1c406d915c8a75e7a95083236ec2071a46c320 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..276dd7bcfc63203afa6d8a7ad7e96c8d3eb2d329 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fab7334afaef664c52a15c66c776aacdaa19d78 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc8fa589827811395510913795b3a3f8d0ef4b2 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..369984ce801c667bcff0f7cf736ba9583a739db0 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58bb17f92e1a41df8d41a35bd2f6e0b7c81d7df9 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4e946a25ffbbf003d39a020ea75fea185551ce46 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py @@ -0,0 +1,637 @@ +import copy +import operator +import torch +import torch.nn.functional as F +import torch.nn as nn +import torch.ao.nn.intrinsic as nni +import torch.ao.nn.intrinsic.qat as nniqat +import torch.ao.nn.qat as nnqat +import torch.ao.nn.quantized.reference as nnqr +from collections import namedtuple +from typing import Callable, Dict, List, Union +from .backend_config import ( + BackendPatternConfig, + DTypeConfig, + DTypeWithConstraints, + ObservationType, +) +from ..fuser_method_mappings import ( + _sequential_wrapper2, + fuse_conv_bn, + fuse_conv_bn_relu, + fuse_linear_bn, + fuse_convtranspose_bn, +) + +__all__: List[str] = [] + +# TODO: rename to be more explicit, e.g. qat_conv_relu +_ConvMetadata = namedtuple( + "_ConvMetadata", + ["root", "transpose", "bn", "reference", "transpose_reference", + "fused_conv_relu", "fused_conv_bn", "fused_conv_bn_relu", + "qat", "relu_qat", "bn_qat", "bn_relu_qat", + "func", "func_transpose"]) +_Conv1dMetadata = _ConvMetadata( + nn.Conv1d, nn.ConvTranspose1d, nn.BatchNorm1d, nnqr.Conv1d, nnqr.ConvTranspose1d, + nni.ConvReLU1d, nni.ConvBn1d, nni.ConvBnReLU1d, + nnqat.Conv1d, nniqat.ConvReLU1d, nniqat.ConvBn1d, nniqat.ConvBnReLU1d, + F.conv1d, F.conv_transpose1d) +_Conv2dMetadata = _ConvMetadata( + nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d, nnqr.Conv2d, nnqr.ConvTranspose2d, + nni.ConvReLU2d, nni.ConvBn2d, nni.ConvBnReLU2d, + nnqat.Conv2d, nniqat.ConvReLU2d, nniqat.ConvBn2d, nniqat.ConvBnReLU2d, + F.conv2d, F.conv_transpose2d) +_Conv3dMetadata = _ConvMetadata( + nn.Conv3d, nn.ConvTranspose3d, nn.BatchNorm3d, nnqr.Conv3d, nnqr.ConvTranspose3d, + nni.ConvReLU3d, nni.ConvBn3d, nni.ConvBnReLU3d, + nnqat.Conv3d, nniqat.ConvReLU3d, nniqat.ConvBn3d, nniqat.ConvBnReLU3d, + F.conv3d, F.conv_transpose3d) + +# Add constraints for fixed qparams ops like sigmoid and tanh to ensure values +# fall within the proper ranges, e.g. [0, 1] for sigmoid, [-1, 1] for tanh +_FIXED_QPARAM_OP_0TO1_CONSTRAINTS = DTypeWithConstraints( + dtype=torch.quint8, + quant_min_lower_bound=0, + quant_max_upper_bound=255, + scale_exact_match=1.0 / 256.0, + zero_point_exact_match=0, +) +_FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS = DTypeWithConstraints( + dtype=torch.quint8, + quant_min_lower_bound=0, + quant_max_upper_bound=255, + scale_exact_match=2.0 / 256.0, + zero_point_exact_match=128, +) +_FIXED_QPARAMS_OP_TO_CONSTRAINTS: Dict[Union[Callable, str], DTypeWithConstraints] = { + torch.nn.Hardsigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + torch.nn.functional.hardsigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + "hardsigmoid": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + "hardsigmoid_": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + torch.nn.Sigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + torch.sigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + "sigmoid": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + "sigmoid_": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + torch.nn.Softmax: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS, + torch.nn.Tanh: _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS, + torch.tanh: _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS, + "tanh": _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS, + "tanh_": _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS, +} + +def _get_binary_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + binary_op_configs: List[BackendPatternConfig] = [] + num_tensor_args_to_observation_type_mapping = { + # TODO: this is not used right now since we have extra check in prepare + # will need to change this to NO_OBSERVER later after we implemented + # Tensor dtype inference properly + 0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT, + 1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT, + 2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT, + } + for op_with_quantized_bop_scalar_variant in [operator.add, torch.add, operator.mul, torch.mul]: + bop_patterns = [ + (op_with_quantized_bop_scalar_variant, nn.ReLU), + (op_with_quantized_bop_scalar_variant, F.relu), + (op_with_quantized_bop_scalar_variant, torch.relu), + op_with_quantized_bop_scalar_variant + ] + for bop_pattern in bop_patterns: + binary_op_configs.append( + BackendPatternConfig(bop_pattern) + .set_dtype_configs(dtype_configs) # noqa: E131 + ._set_num_tensor_args_to_observation_type(num_tensor_args_to_observation_type_mapping)) + # matmul + binary_op_configs.append( + BackendPatternConfig(torch.matmul) + .set_dtype_configs(dtype_configs) # noqa: E131 + ) + return binary_op_configs + +def _get_linear_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + """ + Return all configs related to linear modules and ops. + """ + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + linear_configs: List[BackendPatternConfig] = [] + + # (1) Single linear modules/functions + # ------------------------------------- + # linear module + linear_configs.append( + BackendPatternConfig(torch.nn.Linear) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear) + .set_qat_module(nnqat.Linear)) + # linear qat module + linear_configs.append( + BackendPatternConfig(nnqat.Linear) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear)) + # functional linear + linear_configs.append( + BackendPatternConfig(torch.nn.functional.linear) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2})) + + # (2) Linear + relu + # ------------------- + # 2.1 linear module + relu fusion config + # linear relu, linear module + relu module + linear_configs.append( + BackendPatternConfig((torch.nn.Linear, torch.nn.ReLU)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(nni.LinearReLU)) + .set_fused_module(nni.LinearReLU)) + # linear relu, linear module + functional relu + linear_configs.append( + BackendPatternConfig((torch.nn.Linear, torch.nn.functional.relu)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(nni.LinearReLU)) + .set_fused_module(nni.LinearReLU)) + + # 2.2 linear module + relu, fused module configs + # linear relu, fused module + linear_configs.append( + BackendPatternConfig(nni.LinearReLU) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear) + .set_qat_module(nniqat.LinearReLU)) + # linear relu, qat fused module + linear_configs.append( + BackendPatternConfig(nniqat.LinearReLU) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear)) + # 2.3 functional linear + relu configs + # linear relu, functional linear + relu module + linear_configs.append( + BackendPatternConfig((F.linear, torch.nn.ReLU)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + # linear relu, functional linear + functional relu + linear_configs.append( + BackendPatternConfig((F.linear, F.relu)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + + # (3) Linear + batchnorm + # ------------------------ + # 3.1 linear bn fusion + linear_configs.append( + BackendPatternConfig((nn.Linear, nn.BatchNorm1d)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuse_linear_bn) + .set_fused_module(nni.LinearBn1d)) + + # 3.2 linear bn fused + # linear bn, fused module + linear_configs.append( + BackendPatternConfig(nni.LinearBn1d) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear) + .set_qat_module(nniqat.LinearBn1d)) + # linear bn, qat fused module + linear_configs.append( + BackendPatternConfig(nniqat.LinearBn1d) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear)) + return linear_configs + +def _get_conv_configs(dtype_configs): + """ + Return all configs related to conv modules and ops. + """ + conv_configs = [] + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + for convs in [_Conv1dMetadata, _Conv2dMetadata, _Conv3dMetadata]: + + # (1) Single conv modules/functions + # ----------------------------------- + # conv module + conv_configs.append( + BackendPatternConfig(convs.root) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + .set_qat_module(convs.qat)) + # conv qat module + conv_configs.append( + BackendPatternConfig(convs.qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference)) + # functional conv + conv_configs.append( + BackendPatternConfig(convs.func) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2})) + + # (2) Conv + relu + # ----------------- + # 2.1 conv module + relu fusion configs + # conv relu fusion, conv module + relu module + conv_configs.append( + BackendPatternConfig((convs.root, torch.nn.ReLU)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu)) + .set_fused_module(convs.fused_conv_relu)) + # conv relu fusion, conv module + functional relu + conv_configs.append( + BackendPatternConfig((convs.root, F.relu)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu)) + .set_fused_module(convs.fused_conv_relu)) + # 2.2 conv module + relu fused module configs + # conv relu, fused module + conv_configs.append( + BackendPatternConfig(convs.fused_conv_relu) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + .set_qat_module(convs.relu_qat)) + # conv relu, qat fused module + conv_configs.append( + BackendPatternConfig(convs.relu_qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference)) + # 2.3 functional conv + relu configs + # conv relu, functional conv + relu module + conv_configs.append( + BackendPatternConfig((convs.func, torch.nn.ReLU)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + # conv relu, functional conv + functional relu + conv_configs.append( + BackendPatternConfig((convs.func, F.relu)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + + # fused conv relu + conv_configs.append( + BackendPatternConfig(convs.fused_conv_relu) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_qat_module(convs.relu_qat)) + + conv_configs.append( + BackendPatternConfig(convs.relu_qat) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference)) + + # (3) Conv + batchnorm (+ relu) + # ------------------------------- + # 3.1 conv bn fusion configs + # conv + bn fusion + conv_configs.append( + BackendPatternConfig((convs.root, convs.bn)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuse_conv_bn) + .set_fused_module(convs.fused_conv_bn)) + # conv + bn + relu module fusion + conv_configs.append( + BackendPatternConfig((convs.root, convs.bn, nn.ReLU)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuse_conv_bn_relu) + .set_fused_module(convs.fused_conv_bn_relu)) + # conv + bn + relu functional fusion + conv_configs.append( + BackendPatternConfig((convs.root, convs.bn, F.relu)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_root_module(convs.root) + .set_fuser_method(fuse_conv_bn_relu) + .set_fused_module(convs.fused_conv_bn_relu)) + # TODO: we can add fusion for torch.relu as well + + # 3.2 conv + bn (+ relu) fused module configs + # fused conv bn + conv_configs.append( + BackendPatternConfig(convs.fused_conv_bn) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_qat_module(convs.bn_qat)) + + # fused conv bn relu + conv_configs.append( + BackendPatternConfig(convs.fused_conv_bn_relu) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_qat_module(convs.bn_relu_qat)) + + # conv bn, qat fused module + conv_configs.append( + BackendPatternConfig(convs.bn_qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference)) + # conv bn relu, qat fused module + conv_configs.append( + BackendPatternConfig(convs.bn_relu_qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference)) + + # (4) conv transpose and its fusion + # 4.1 conv transpose config + conv_configs.append( + BackendPatternConfig(convs.transpose) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_root_module(convs.transpose) + .set_reference_quantized_module(convs.transpose_reference)) + + # 4.2 conv transpose + bn fusion + conv_configs.append( + BackendPatternConfig((convs.transpose, convs.bn)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuse_convtranspose_bn) + .set_root_module(convs.transpose) + .set_reference_quantized_module(convs.transpose_reference)) + + # 4.3 functional conv transpose + conv_configs.append( + BackendPatternConfig(convs.func_transpose) + .set_dtype_configs(dtype_configs) # noqa: E131 + ._set_input_type_to_index({"weight": 1, "bias": 2})) + + return conv_configs + +def _get_cat_config(dtype_configs: List[DTypeConfig]) -> BackendPatternConfig: + return BackendPatternConfig(torch.cat) \ + .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) \ + .set_dtype_configs(dtype_configs) + +def _get_ln_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + ln_configs = [] + ln_configs.append( + BackendPatternConfig(torch.nn.LayerNorm) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + ) + ln_configs.append( + BackendPatternConfig(torch.nn.functional.layer_norm) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 2, "bias": 3}) + ) + return ln_configs + +def _get_default_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + configs = [] + default_ops = [ + torch.nn.ELU, + torch.nn.LeakyReLU, + torch.nn.Hardswish, + torch.nn.InstanceNorm1d, + torch.nn.InstanceNorm2d, + torch.nn.InstanceNorm3d, + torch.nn.Dropout, + torch.nn.PReLU, + torch.nn.functional.elu, + torch.nn.functional.hardswish, + torch.nn.functional.leaky_relu, + torch.nn.functional.dropout, + ] + for op in default_ops: + configs.append( + BackendPatternConfig(op) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs)) + + configs.append( + BackendPatternConfig(torch.nn.functional.group_norm) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 2, "bias": 3}) + ) + + configs.append( + BackendPatternConfig(torch.nn.functional.instance_norm) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 3, "bias": 4}) + ) + return configs + +def _add_fixed_qparams_to_dtype_configs( + dtype_configs: List[DTypeConfig], + constraints: DTypeWithConstraints, +) -> List[DTypeConfig]: + """ + Return a copy of the list of DTypeConfigs where activations are subject to the specified + constraints required for fixed qparams ops. + + If the data type doesn't match the one in the constraints, simply leave the corresponding + DTypeConfig unchanged. + + If `scale_min_lower_bound` or `scale_max_upper_bound` is specified in the activations, + throw an exception since these settings are incompatible with fixed qparams ops. + """ + new_dtype_configs = [] + for dtype_config in dtype_configs: + dc = copy.deepcopy(dtype_config) + for orig_constraints in [dc.input_dtype_with_constraints, dc.output_dtype_with_constraints]: + if orig_constraints.dtype != constraints.dtype: + continue + if orig_constraints.scale_min_lower_bound is not None: + raise ValueError(f"scale_min_lower_bound is invalid for fixed qparams ops: {dtype_config}") + if orig_constraints.scale_max_upper_bound is not None: + raise ValueError(f"scale_max_upper_bound is invalid for fixed qparams ops: {dtype_config}") + orig_constraints.quant_min_lower_bound = constraints.quant_min_lower_bound + orig_constraints.quant_max_upper_bound = constraints.quant_max_upper_bound + orig_constraints.scale_exact_match = constraints.scale_exact_match + orig_constraints.zero_point_exact_match = constraints.zero_point_exact_match + new_dtype_configs.append(dc) + return new_dtype_configs + +def _get_fixed_qparams_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + fixed_qparams_op_configs = [] + for fixed_qparam_op, constraints in _FIXED_QPARAMS_OP_TO_CONSTRAINTS.items(): + new_dtype_configs = _add_fixed_qparams_to_dtype_configs(dtype_configs, constraints) + fixed_qparams_op_configs.append( + BackendPatternConfig(fixed_qparam_op) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(new_dtype_configs)) + return fixed_qparams_op_configs + +def _get_share_qparams_op_configs(dtype_configs): + """ Get the operator config for the operators that works for both float and quantized input + if input is quantized, the output Tensor shares the same quantization parameter + with input. + Example operator: avgpool2d, reshape, transpose, maxpool2d + Example observed operator: + observer_0 - avgpool2d - observer_0 (same observer instance as input) + """ + + def _get_share_qprams_op_backend_config(op): + return BackendPatternConfig(op) \ + .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) \ + .set_dtype_configs(dtype_configs) + + share_qparams_ops = [ + torch.nn.AdaptiveAvgPool1d, + torch.nn.AdaptiveAvgPool2d, + torch.nn.AdaptiveAvgPool3d, + torch.nn.AvgPool1d, + torch.nn.AvgPool2d, + torch.nn.AvgPool3d, + torch.nn.Hardtanh, + torch.nn.Identity, + torch.nn.MaxPool1d, + torch.nn.MaxPool2d, + torch.nn.MaxPool3d, + torch.nn.PixelShuffle, + torch.nn.PixelUnshuffle, + torch.nn.ReLU, + torch.nn.ReLU6, + torch.adaptive_avg_pool1d, + torch.nn.functional.adaptive_avg_pool2d, + torch.nn.functional.adaptive_avg_pool3d, + torch.nn.functional.hardtanh, + torch.nn.functional.hardtanh_, + torch.nn.functional.interpolate, + torch.nn.functional.max_pool1d, + torch.nn.functional.max_pool2d, + torch.nn.functional.max_pool3d, + torch.nn.functional.pixel_shuffle, + torch.nn.functional.pixel_unshuffle, + torch.nn.functional.relu, + torch.nn.functional.relu6, + torch.avg_pool1d, + torch._C._nn.avg_pool2d, + torch._C._nn.avg_pool3d, + torch.clamp, + torch.flatten, + torch.mean, + torch.narrow, + torch.repeat_interleave, + torch.transpose, + torch.squeeze, + torch.stack, + torch.unsqueeze, + operator.floordiv, + "contiguous", + "clamp", + "detach", + "detach_", + "mean", + "permute", + "repeat", + "repeat_interleave", + "reshape", + "resize_", + "relu", + "relu_", + "squeeze", + "squeeze_", + "transpose", + "unsqueeze", + "unsqueeze_", + "view" + ] + return [_get_share_qprams_op_backend_config(op) for op in share_qparams_ops] + +def _get_bn_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + """ Get configs related to batchnorm. """ + bn_configs = [] + bn_to_fused_bn = { + torch.nn.BatchNorm2d: nni.BNReLU2d, + torch.nn.BatchNorm3d: nni.BNReLU3d, + } + for bn in bn_to_fused_bn.keys(): + fused_bn = bn_to_fused_bn[bn] + # bn module + relu module fusion config + bn_configs.append( + BackendPatternConfig((bn, nn.ReLU)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(fused_bn)) + .set_fused_module(fused_bn)) + # bn module + F.relu fusion config + bn_configs.append( + BackendPatternConfig((bn, F.relu)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(fused_bn)) + .set_fused_module(fused_bn)) + bn_configs.append( + BackendPatternConfig(bn) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs)) + + # fused bn configs + for fused_bn in bn_to_fused_bn.values(): + bn_configs.append( + BackendPatternConfig(fused_bn) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs)) + return bn_configs + +def _get_rnn_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + rnn_op_configs = [] + for rnn_op, ref_rnn_op in [ + (nn.GRUCell, nnqr.GRUCell), + (nn.LSTMCell, nnqr.LSTMCell), + (nn.RNNCell, nnqr.RNNCell), + (nn.LSTM, nnqr.LSTM), + (nn.GRU, nnqr.GRU) + ]: + rnn_op_configs.append( + BackendPatternConfig(rnn_op) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(rnn_op) + .set_reference_quantized_module(ref_rnn_op)) + return rnn_op_configs + +def _get_embedding_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]: + embedding_op_configs = [] + for embedding_op, qat_embedding_op, ref_embedding_op in [ + (nn.Embedding, nnqat.Embedding, nnqr.Embedding), + (nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag), + ]: + embedding_op_configs.append( + BackendPatternConfig(embedding_op) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_qat_module(qat_embedding_op) + .set_root_module(embedding_op) + .set_reference_quantized_module(ref_embedding_op)) + + # config for qat op + embedding_op_configs.append( + BackendPatternConfig(qat_embedding_op) + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(embedding_op) + .set_reference_quantized_module(ref_embedding_op)) + return embedding_op_configs + +def _get_tensor_info_op_configs(dtype_configs): + """ + These ops work on tensors of different dtypes but return non-tensors + containing information about the input tensor. + """ + + def _get_config(op): + return BackendPatternConfig(op) \ + .set_observation_type(ObservationType.INPUT_OUTPUT_NOT_OBSERVED) \ + .set_dtype_configs(dtype_configs) + + return [_get_config(op) for op in ("shape", "size")] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py new file mode 100644 index 0000000000000000000000000000000000000000..01e112b688c0428cadb5e31502f18387bcd9282f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py @@ -0,0 +1,160 @@ +import operator +import torch +from torch.ao.quantization.backend_config import ( + BackendConfig, + DTypeConfig, + ObservationType, + BackendPatternConfig, +) + +weighted_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, +) +from typing import List + +def get_linear_configs(): + linear_configs = [] + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + dtype_configs = [weighted_op_quint8_dtype_config] + + # TODO: need to fix the way we insert observers for this pattern + # should be solved in the new fusion API + # reason that this doesn't work: the pattern is a bit complicated and we don't + # have a way to specify which input of the pattern we would like to observe + # pattern: + # bias input weight + # \ | / + # \ | t + # \ | / + # addmm + # we want to observe "weight" as weight, but there is not way to convey this + # information with current pattern language + # + # right now: + # original: + # weight - t \ + # input - addmm + # observed (no hack): + # weight - t - observer \ + # input - observer - addmm + # target: + # weight - observer - t \ + # input - observer - addmm + + # def root_node_getter(node_pattern): + # addmm, bias, act, weight = node_pattern + # return addmm + + # linear_configs.append( + # BackendPatternConfig((torch.ops.aten.addmm.default, MatchAllNode, MatchAllNode, torch.ops.aten.t.default)) + # .set_observation_type(observation_type) # noqa: E131 + # .set_dtype_configs(dtype_configs) + # ._set_root_node_getter(root_node_getter)) + + linear_configs.append( + BackendPatternConfig(torch.ops.aten.addmm.default) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 2, "bias": 0}) + ) + # linear is decomposed to `t - mm` if bias is not present + linear_configs.append( + BackendPatternConfig(torch.ops.aten.mm.default) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1}) + ) + return linear_configs + +def get_conv_configs(): + conv_configs = [] + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + dtype_configs = [weighted_op_quint8_dtype_config] + conv_configs.append( + BackendPatternConfig(torch.ops.aten.convolution.default) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2}) + ) + conv_configs.append( + BackendPatternConfig((torch.ops.aten.convolution.default, torch.ops.aten.relu.default)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2}) + ) + # TODO: remove when functionalization is supported in PT2 mode + conv_configs.append( + BackendPatternConfig((torch.ops.aten.convolution.default, torch.ops.aten.relu_.default)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2}) + ) + return conv_configs + +def get_pooling_configs(): + backend_pattern_configs = [] + observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT + dtype_configs = [weighted_op_quint8_dtype_config] + + def root_node_getter(node_pattern): + getitem, maxpool, index = node_pattern + return maxpool + + backend_pattern_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((operator.getitem, torch.ops.aten.max_pool2d_with_indices.default, 0)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_root_node_getter(root_node_getter) + ) + + return backend_pattern_configs + +def get_relu_configs(): + backend_pattern_configs = [] + observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT + dtype_configs = [weighted_op_quint8_dtype_config] + backend_pattern_configs.append( + BackendPatternConfig(torch.ops.aten.relu.default) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + return backend_pattern_configs + +def get_binary_op_configs(): + binary_op_configs: List[BackendPatternConfig] = [] + dtype_configs = [weighted_op_quint8_dtype_config] + num_tensor_args_to_observation_type_mapping = { + # TODO: this is not used right now since we have extra check in prepare + # will need to change this to NO_OBSERVER later after we implemented + # Tensor dtype inference properly + 0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT, + 1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT, + 2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT, + } + for op_with_quantized_bop_scalar_variant in [torch.ops.aten.add.Tensor, torch.ops.aten.add_.Tensor]: + bop_patterns = [ + (op_with_quantized_bop_scalar_variant, torch.ops.aten.relu.default), + op_with_quantized_bop_scalar_variant, + # TODO: remove when functionalization is supported in pt2_mode + (op_with_quantized_bop_scalar_variant, torch.ops.aten.relu_.default), + ] + for bop_pattern in bop_patterns: + binary_op_configs.append( + BackendPatternConfig(bop_pattern) + .set_dtype_configs(dtype_configs) # noqa: E131 + ._set_num_tensor_args_to_observation_type(num_tensor_args_to_observation_type_mapping)) + + return binary_op_configs + +def get_qnnpack_pt2e_backend_config(): + return ( + BackendConfig("qnnpack_pytorch_2.0_export") + .set_backend_pattern_configs(get_linear_configs()) + .set_backend_pattern_configs(get_binary_op_configs()) + .set_backend_pattern_configs(get_conv_configs()) + .set_backend_pattern_configs(get_pooling_configs()) + .set_backend_pattern_configs(get_relu_configs()) + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py new file mode 100644 index 0000000000000000000000000000000000000000..8c721fa8c3bf495fea6f51a8abc958a739c4e22f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py @@ -0,0 +1,493 @@ +# TODO: rename executorch to qnnpack_executorch since executorch is a general runtime +# not a specific backend + +import operator +from typing import List + +import torch +import torch.ao.nn.qat as nnqat +import torch.ao.nn.quantized.reference as nnqr +import torch.nn as nn +import torch.nn.functional as F + +from ..fuser_method_mappings import ( + _sequential_wrapper2, + fuse_conv_bn, + fuse_conv_bn_relu, +) +from ._common_operator_config_utils import _Conv2dMetadata +from .backend_config import ( + BackendConfig, + BackendPatternConfig, + DTypeConfig, + DTypeWithConstraints, + ObservationType, +) +from .qnnpack import ( + qnnpack_default_op_qint8_symmetric_dtype_config, + qnnpack_weighted_op_qint8_symmetric_dtype_config, +) + + +__all__ = [ + "get_executorch_backend_config", +] + + +# =================== +# | DTYPE CONFIGS | +# =================== + +executorch_weighted_op_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, +) + +executorch_default_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, +) + +executorch_default_dynamic_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.float, + weight_dtype=torch.qint8, + bias_dtype=torch.float, + is_dynamic=True, +) + +executorch_act_qint8_scale_min_2_neg_12 = DTypeWithConstraints( + dtype=torch.qint8, + scale_min_lower_bound=2**-12, +) + +executorch_weight_qint8_neg_127_to_127_scale_min_2_neg_12 = DTypeWithConstraints( + dtype=torch.qint8, + quant_min_lower_bound=-127, + quant_max_upper_bound=127, + scale_min_lower_bound=2**-12, +) + +executorch_default_dynamic_qint8_dtype_config = DTypeConfig( + input_dtype=executorch_act_qint8_scale_min_2_neg_12, + output_dtype=torch.float, + weight_dtype=executorch_weight_qint8_neg_127_to_127_scale_min_2_neg_12, + bias_dtype=torch.float, + is_dynamic=True, +) + +executorch_default_dynamic_float16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float, + weight_dtype=torch.float16, + bias_dtype=torch.float, + is_dynamic=True, +) + +executorch_weight_only_quint8_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint8, +) + + +# ============================= +# | BACKEND PATTERN CONFIGS | +# ============================= + + +def _get_linear_configs() -> List[BackendPatternConfig]: + """ + Return all configs related to linear modules and ops. + """ + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + dtype_configs = [ + qnnpack_weighted_op_qint8_symmetric_dtype_config, + executorch_weighted_op_int8_dtype_config, + executorch_default_dynamic_quint8_dtype_config, + executorch_default_dynamic_qint8_dtype_config, + executorch_default_dynamic_float16_dtype_config, + ] + linear_configs: List[BackendPatternConfig] = [] + # linear module + linear_configs.append( + BackendPatternConfig(torch.nn.Linear) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear) + .set_qat_module(nnqat.Linear) + ) + # linear qat module + linear_configs.append( + BackendPatternConfig(nnqat.Linear) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(torch.nn.Linear) + .set_reference_quantized_module(nnqr.Linear) + ) + # functional linear + linear_configs.append( + BackendPatternConfig(torch.nn.functional.linear) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2}) + ) + return linear_configs + + +def _get_conv_configs() -> List[BackendPatternConfig]: + """ + Return all configs related to conv modules and ops. + """ + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + dtype_configs = [ + qnnpack_weighted_op_qint8_symmetric_dtype_config, + executorch_weighted_op_int8_dtype_config, + ] + conv_configs = [] + for convs in [_Conv2dMetadata]: + # (1) Single conv modules/functions + # ----------------------------------- + # conv module + conv_configs.append( + BackendPatternConfig(convs.root) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + .set_qat_module(convs.qat) + ) + # conv qat module + conv_configs.append( + BackendPatternConfig(convs.qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + ) + # functional conv + conv_configs.append( + BackendPatternConfig(convs.func) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1, "bias": 2}) + ) + + # (2) Conv + relu + # ----------------------------------- + # conv module + relu module + conv_configs.append( + BackendPatternConfig((convs.root, nn.ReLU)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu)) + .set_fused_module(convs.fused_conv_relu) + ) + # conv module + functional relu + conv_configs.append( + BackendPatternConfig((convs.root, F.relu)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu)) + .set_fused_module(convs.fused_conv_relu) + ) + # fused conv relu module + conv_configs.append( + BackendPatternConfig(convs.fused_conv_relu) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + .set_qat_module(convs.relu_qat) + ) + # conv relu, qat fused module + conv_configs.append( + BackendPatternConfig(convs.relu_qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + ) + # functional conv + relu module + conv_configs.append( + BackendPatternConfig((convs.func, nn.ReLU)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ) + # functional conv + functional relu + conv_configs.append( + BackendPatternConfig((convs.func, F.relu)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ) + # fused conv relu + conv_configs.append( + BackendPatternConfig(convs.fused_conv_relu) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_qat_module(convs.relu_qat) + ) + + conv_configs.append( + BackendPatternConfig(convs.relu_qat) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + ) + + # (3) Conv + batchnorm (+ relu) + # ------------------------------- + # conv + batchnorm (+ relu) + conv_configs.append( + BackendPatternConfig((convs.root, convs.bn)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuse_conv_bn) + .set_fused_module(convs.fused_conv_bn) + ) + # conv + bn + relu module fusion + conv_configs.append( + BackendPatternConfig((convs.root, convs.bn, nn.ReLU)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuse_conv_bn_relu) + .set_fused_module(convs.fused_conv_bn_relu) + ) + # conv + bn + relu functional fusion + conv_configs.append( + BackendPatternConfig((convs.root, convs.bn, F.relu)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_root_module(convs.root) + .set_fuser_method(fuse_conv_bn_relu) + .set_fused_module(convs.fused_conv_bn_relu) + ) + # TODO: we can add fusion for torch.relu as well + # 3.2 conv + bn (+ relu) fused module configs + # fused conv bn + conv_configs.append( + BackendPatternConfig(convs.fused_conv_bn) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_qat_module(convs.bn_qat) + ) + + # fused conv bn relu + conv_configs.append( + BackendPatternConfig(convs.fused_conv_bn_relu) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_qat_module(convs.bn_relu_qat) + ) + + # conv bn, qat fused module + conv_configs.append( + BackendPatternConfig(convs.bn_qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + ) + # conv bn relu, qat fused module + conv_configs.append( + BackendPatternConfig(convs.bn_relu_qat) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(convs.root) + .set_reference_quantized_module(convs.reference) + ) + return conv_configs + + +def _get_binary_ops_configs() -> List[BackendPatternConfig]: + """ + Return all configs related to binary ops. + """ + dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + executorch_weighted_op_int8_dtype_config, + ] + num_tensor_args_to_observation_type_mapping = { + # TODO: this is not used right now since we have extra check in prepare + # will need to change this to NO_OBSERVER later after we implemented + # Tensor dtype inference properly + 0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT, + 1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT, + 2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT, + } + binary_op_configs: List[BackendPatternConfig] = [] + for op in [operator.add, torch.add, operator.sub, torch.sub, operator.mul, torch.mul]: + bop_patterns = [ + (op, torch.nn.ReLU), + (op, torch.nn.functional.relu), + (op, torch.relu), + op + ] + for bop_pattern in bop_patterns: + binary_op_configs.append( + BackendPatternConfig(bop_pattern) + .set_dtype_configs(dtype_configs) # noqa: E131 + ._set_num_tensor_args_to_observation_type( + num_tensor_args_to_observation_type_mapping + ) + ) + return binary_op_configs + + +def _get_share_qparams_ops_configs() -> List[BackendPatternConfig]: + """ + Return the operator configs for the operators that works for both float and quantized + input if input is quantized, the output Tensor shares the same quantization parameter + with input. + + Example operator: avgpool2d, reshape, transpose, maxpool2d + Example observed operator: + observer_0 - avgpool2d - observer_0 (same observer instance as input) + """ + observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT + dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + executorch_default_op_quint8_dtype_config, + ] + share_qparams_ops = [ + F.adaptive_avg_pool2d, + F.elu, + F.hardtanh, + F.max_pool2d, + F.pad, + F.relu, + F.relu6, + F.leaky_relu, + F.leaky_relu_, + torch.nn.AdaptiveAvgPool2d, + torch.nn.ConstantPad2d, + torch.nn.ELU, + torch.nn.MaxPool2d, + torch.nn.ReLU6, + torch.nn.Hardtanh, + torch.nn.LeakyReLU, + torch.clamp, + torch.flatten, + torch.mean, + torch.permute, + torch.permute_copy, + torch.squeeze, + "clamp", + "mean", + "permute", + "reshape", + "relu", + "relu_", + "squeeze", + "squeeze_", + "leaky_relu", + ] + share_qparams_op_configs: List[BackendPatternConfig] = [] + for op in share_qparams_ops: + share_qparams_op_configs.append( + BackendPatternConfig(op) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ) + return share_qparams_op_configs + + +def _get_bn_configs() -> List[BackendPatternConfig]: + """ + Return all configs related to batchnorm. + """ + observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + executorch_default_op_quint8_dtype_config, + ] + bn_configs = [] + bn_configs.append( + BackendPatternConfig(nn.BatchNorm2d) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + ) + return bn_configs + + +def _get_cat_configs() -> List[BackendPatternConfig]: + dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + executorch_default_op_quint8_dtype_config, + ] + cat_configs = [] + cat_configs.append( + BackendPatternConfig(torch.cat) + .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) + .set_dtype_configs(dtype_configs) + ) + cat_configs.append( + BackendPatternConfig(torch.concat) + .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) + .set_dtype_configs(dtype_configs) + ) + cat_configs.append( + BackendPatternConfig(torch.concatenate) + .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) + .set_dtype_configs(dtype_configs) + ) + return cat_configs + + +def _get_embedding_op_configs() -> List[BackendPatternConfig]: + dtype_configs = [ + executorch_weight_only_quint8_dtype_config, + ] + embedding_op_configs = [] + for embedding_op, qat_embedding_op, ref_embedding_op in [ + (nn.Embedding, nnqat.Embedding, nnqr.Embedding), + (nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag), + ]: + embedding_op_configs.append( + BackendPatternConfig(embedding_op) + .set_observation_type( + ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + ) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_qat_module(qat_embedding_op) + .set_root_module(embedding_op) + .set_reference_quantized_module(ref_embedding_op) + ) + # config for qat op + embedding_op_configs.append( + BackendPatternConfig(qat_embedding_op) + .set_observation_type( + ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + ) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(embedding_op) + .set_reference_quantized_module(ref_embedding_op) + ) + + # config for functional embedding + embedding_op_configs.append( + BackendPatternConfig(torch.nn.functional.embedding) + .set_observation_type( + ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + ) # noqa: E131 + .set_dtype_configs(dtype_configs) + ._set_input_type_to_index({"weight": 1}) + ) + return embedding_op_configs + + + +# ===================== +# | BACKEND CONFIGS | +# ===================== + + +def get_executorch_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for backends PyTorch lowers to through the Executorch stack. + """ + return ( + BackendConfig("executorch") + .set_backend_pattern_configs(_get_linear_configs()) + .set_backend_pattern_configs(_get_conv_configs()) + .set_backend_pattern_configs(_get_binary_ops_configs()) + .set_backend_pattern_configs(_get_share_qparams_ops_configs()) + .set_backend_pattern_configs(_get_bn_configs()) + .set_backend_pattern_configs(_get_cat_configs()) + .set_backend_pattern_configs(_get_embedding_op_configs()) + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/native.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/native.py new file mode 100644 index 0000000000000000000000000000000000000000..81cfc928adb5b127a09691c5841b4cfd1d564800 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/native.py @@ -0,0 +1,204 @@ +import torch +from ._common_operator_config_utils import ( + _get_binary_op_configs, + _get_bn_configs, + _get_cat_config, + _get_conv_configs, + _get_default_op_configs, + _get_embedding_op_configs, + _get_fixed_qparams_op_configs, + _get_linear_configs, + _get_ln_configs, + _get_rnn_op_configs, + _get_share_qparams_op_configs, + _get_tensor_info_op_configs, +) +from .backend_config import BackendConfig, DTypeConfig + +__all__ = [ + "get_test_only_legacy_native_backend_config", + "default_op_quint8_dtype_config", + "default_op_fp16_dtype_config", + "default_dynamic_int8_dtype_config", + "default_dynamic_float16_dtype_config", + "input_output_only_quint8_dtype_config", + "weight_only_quint8_dtype_config", + "weight_only_quint4x2_dtype_config", + "get_native_backend_config", + "get_native_backend_config_dict", + "get_test_only_legacy_native_backend_config_dict", +] + +# =================== +# | DTYPE CONFIGS | +# =================== + +# weighted op int8 dtype config +# this is config for ops that has quantized weights, like linear, conv +weighted_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, +) + +default_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, +) + +default_op_fp16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float16, + weight_dtype=torch.float16, + bias_dtype=torch.float16, +) + +default_dynamic_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.float, + weight_dtype=torch.qint8, + bias_dtype=torch.float, + # currently the dtype check is not yet enabled, so we provided the dtype_configs but + # it is not really used yet, + # we will enable it a bit later after we moved everything to backend_config_dict + is_dynamic=True, +) + +default_dynamic_float16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float, + weight_dtype=torch.float16, + bias_dtype=torch.float, + # currently the dtype check is not yet enabled, so we provided the dtype_configs but + # it is not really used yet, + # we will enable it a bit later after we moved everything to backend_config_dict + is_dynamic=True, +) + +# Needed for LayerNorm and f.layer_norm, since currently the kernel only supports float weights +input_output_only_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.float, + bias_dtype=torch.float, +) + +weight_only_quint8_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint8, +) + +weight_only_quint4x2_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint4x2, +) + + +# ===================== +# | BACKEND CONFIGS | +# ===================== + +def get_test_only_legacy_native_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) with various additional fp16 ops. + """ + conv_dtype_configs = [weighted_op_quint8_dtype_config] + linear_dtype_configs = [ + weighted_op_quint8_dtype_config, + default_dynamic_int8_dtype_config, + default_dynamic_float16_dtype_config, + default_op_fp16_dtype_config, + ] + binary_op_dtype_configs = [ + default_op_quint8_dtype_config, + default_op_fp16_dtype_config, + ] + default_op_dtype_configs = [default_op_quint8_dtype_config] + fixed_qparams_op_dtype_configs = [ + default_op_quint8_dtype_config, + default_op_fp16_dtype_config, + ] + share_qparams_op_dtype_configs = [ + default_op_quint8_dtype_config, + default_op_fp16_dtype_config + ] + tensor_info_op_dtype_configs = [ + default_op_quint8_dtype_config, + ] + rnn_op_dtype_configs = [ + default_dynamic_int8_dtype_config, + default_dynamic_float16_dtype_config, + ] + embedding_op_dtype_configs = [ + weight_only_quint8_dtype_config, + weight_only_quint4x2_dtype_config, + ] + layer_norm_op_dtype_configs = [input_output_only_quint8_dtype_config] + return BackendConfig("_native_and_fp16") \ + .set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \ + .set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \ + .set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \ + .set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs)) + +def get_native_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack). + """ + # TODO: express this BackendConfig as a union of the FBGEMM and QNNPACK BackendConfigs + conv_dtype_configs = [weighted_op_quint8_dtype_config] + linear_dtype_configs = [ + weighted_op_quint8_dtype_config, + default_dynamic_int8_dtype_config, + default_dynamic_float16_dtype_config, + ] + binary_op_dtype_configs = [default_op_quint8_dtype_config] + default_op_dtype_configs = [default_op_quint8_dtype_config] + fixed_qparams_op_dtype_configs = [default_op_quint8_dtype_config] + share_qparams_op_dtype_configs = [default_op_quint8_dtype_config] + tensor_info_op_dtype_configs = [default_op_quint8_dtype_config] + rnn_op_dtype_configs = [ + default_dynamic_int8_dtype_config, + default_dynamic_float16_dtype_config, + ] + embedding_op_dtype_configs = [ + weight_only_quint8_dtype_config, + weight_only_quint4x2_dtype_config, + ] + layer_norm_op_dtype_configs = [input_output_only_quint8_dtype_config] + return BackendConfig("native") \ + .set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \ + .set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \ + .set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \ + .set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs)) + +def get_native_backend_config_dict(): + """ + Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) in dictionary form. + """ + return get_native_backend_config().to_dict() + +def get_test_only_legacy_native_backend_config_dict(): + """ + Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) with various additional + fp16 ops in dictionary form. + """ + return get_test_only_legacy_native_backend_config().to_dict() diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/observation_type.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/observation_type.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py new file mode 100644 index 0000000000000000000000000000000000000000..8c14637ae3d3f72b0cb7d84c39d74af3ccb4bfca --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py @@ -0,0 +1,542 @@ +import torch +import torch.nn as nn +import torch.ao.nn.intrinsic as nni +import torch.nn.functional as F +import torch.ao.nn.quantized.reference as nnqr +from ._common_operator_config_utils import ( + _get_conv_configs, + _get_linear_configs, + _get_binary_op_configs, + _get_bn_configs, + _get_cat_config, + _get_default_op_configs, + _get_embedding_op_configs, + _get_fixed_qparams_op_configs, + _get_ln_configs, + _get_rnn_op_configs, + _get_share_qparams_op_configs, +) +from .backend_config import ( + BackendPatternConfig, + BackendConfig, + DTypeConfig, + ObservationType, +) +from ..fuser_method_mappings import ( + _sequential_wrapper2, +) +import operator +from torch.ao.quantization.utils import MatchAllNode +import itertools + +# =================== +# | DTYPE CONFIGS | +# =================== + +onednn_weighted_op_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, +) + +onednn_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, +) + +onednn_dynamic_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.float, + weight_dtype=torch.qint8, + bias_dtype=torch.float, + is_dynamic=True, +) + +onednn_weight_only_qint8_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.qint8, +) + +onednn_input_output_only_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.float, + bias_dtype=torch.float, +) + +# =================== +# | FUSER METHODS | +# =================== + +def _fuse_linear_bn_leaky_relu(is_qat, linear, bn, leaky_relu): + r"""Given the linear, bn and leaky_relu modules, fuses them and returns the fused module + Args: + is_qat: a flag for whether we are using quantization aware training fusion + or post training quantization fusion + linear: Module instance of type Linear + bn: BatchNorm1d instance that needs to be fused with the linear layer + leaky_relu: LeakyReLU instance that needs to be fused with the linear layer + Examples:: + >>> # xdoctest: +SKIP(failing) + >>> m1 = nn.Linear(20, 10) + >>> b1 = nn.BatchNorm1d(10) + >>> lr = nn.LeakyReLU(0.01) + >>> m2 = _fuse_linear_bn_leaky_relu(m1, b1, lr) + """ + assert(linear.training == bn.training and bn.training == leaky_relu.training),\ + "Linear, BN and LeakyReLU all must be in the same mode (train or eval)." + + if is_qat: + raise NotImplementedError(f"Cannot fuse train modules: {(linear, bn, leaky_relu)}") + else: + map_to_fused_module_eval = { + nn.Linear: nni.LinearLeakyReLU, + } + fused_module = map_to_fused_module_eval.get(type(linear), None) + if fused_module is not None: + fused_linear = nn.utils.fusion.fuse_linear_bn_eval(linear, bn) + fm = fused_module(fused_linear, leaky_relu) + return fm + else: + raise NotImplementedError(f"Cannot fuse eval modules: {(linear, bn, leaky_relu)}") + +# ====================== +# | CONFIGS FOR CONV | +# ====================== +observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT + +conv_dtype_configs = [onednn_weighted_op_int8_dtype_config] +conv_configs = _get_conv_configs(conv_dtype_configs) + +# (1) Conv2d + Add + +# conv2d Y +# \ / +# add + +# include: +# conv2d conv2d +# \ / +# add + +def _fuse_conv_add_left(is_qat, add, conv, _): + return nni.ConvAdd2d(conv, add) + +def _conv_add_root_node_getter_left(pattern): + _, conv, _ = pattern + return conv + +def _conv_add_extra_inputs_getter_left(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + _, conv, extra_input = pattern + return [extra_input] + +# conv2d +# \ +# bn Y +# \ / +# add + +def _fuse_conv_bn_add_left(is_qat, add, bn_conv, _): + bn, conv = bn_conv + if is_qat: + raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add)}") + else: + fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn) + return nni.ConvAdd2d(fused_conv, add) + +def _conv_bn_add_root_node_getter_left(add_pattern): + _, bn_conv, _ = add_pattern + bn, conv = bn_conv + return conv + +def _conv_bn_add_extra_inputs_getter_left(add_pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + _, bn_conv, extra_input = add_pattern + bn, conv = bn_conv + return [extra_input] + +conv_add_left_optioins = itertools.product( + [True, False], # with_bn + [torch.add, operator.add], # add_op +) + +for with_bn, add_op in conv_add_left_optioins: + if with_bn: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((add_op, (nn.BatchNorm2d, nn.Conv2d), MatchAllNode)) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_bn_add_left) + ._set_root_node_getter(_conv_bn_add_root_node_getter_left) + ._set_extra_inputs_getter(_conv_bn_add_extra_inputs_getter_left) + .set_fused_module(nni.ConvAdd2d)) + else: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((add_op, nn.Conv2d, MatchAllNode)) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_add_left) + ._set_root_node_getter(_conv_add_root_node_getter_left) + ._set_extra_inputs_getter(_conv_add_extra_inputs_getter_left) + .set_fused_module(nni.ConvAdd2d)) + +# Y conv2d +# \ / +# add + +def _fuse_conv_add_right(is_qat, add, _, conv): + return nni.ConvAdd2d(conv, add) + +def _conv_add_root_node_getter_right(pattern): + add, _, conv = pattern + return conv + +def _conv_add_extra_inputs_getter_right(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + _, extra_input, conv = pattern + return [extra_input] + +# conv2d +# / +# Y bn +# \ / +# add + +def _fuse_conv_bn_add_right(is_qat, add, _, bn_conv): + bn, conv = bn_conv + if is_qat: + raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add)}") + else: + fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn) + return nni.ConvAdd2d(fused_conv, add) + +def _conv_bn_add_root_node_getter_right(pattern): + add, _, bn_conv = pattern + bn, conv = bn_conv + return conv + +def _conv_bn_add_extra_inputs_getter_right(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + _, extra_input, bn_conv = pattern + bn, conv = bn_conv + return [extra_input] + +conv_add_optioins = itertools.product( + [True, False], # with_bn + [torch.add, operator.add], # add_op +) + +for with_bn, add_op in conv_add_optioins: + if with_bn: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((add_op, MatchAllNode, (nn.BatchNorm2d, nn.Conv2d))) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_bn_add_right) + ._set_root_node_getter(_conv_bn_add_root_node_getter_right) + ._set_extra_inputs_getter(_conv_bn_add_extra_inputs_getter_right) + .set_fused_module(nni.ConvAdd2d)) + else: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((add_op, MatchAllNode, nn.Conv2d)) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_add_right) + ._set_root_node_getter(_conv_add_root_node_getter_right) + ._set_extra_inputs_getter(_conv_add_extra_inputs_getter_right) + .set_fused_module(nni.ConvAdd2d)) + +conv_configs.append( + BackendPatternConfig(nni.ConvAdd2d) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(conv_dtype_configs) + .set_root_module(nn.Conv2d) + .set_reference_quantized_module(nnqr.Conv2d)) + +# (2) Conv2d + Add + Relu + +# conv2d Y +# \ / +# add +# \ +# relu + +def _fuse_conv_add_relu_left(is_qat, relu, add_pattern): + add, conv, _ = add_pattern + return nni.ConvAddReLU2d(conv, add, relu) + +def _conv_add_relu_root_node_getter_left(pattern): + relu, add_pattern = pattern + _, conv, _ = add_pattern + return conv + +def _conv_add_relu_extra_inputs_getter_left(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + relu, add_pattern = pattern + _, conv, extra_input = add_pattern + return [extra_input] + +# conv2d +# \ +# bn Y +# \ / +# add +# \ +# relu + +def _fuse_conv_bn_add_relu_left(is_qat, relu, add_pattern): + add, bn_conv, _ = add_pattern + bn, conv = bn_conv + if is_qat: + raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add, relu)}") + else: + fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn) + return nni.ConvAddReLU2d(fused_conv, add, relu) + +def _conv_bn_add_relu_root_node_getter_left(pattern): + relu, add_pattern = pattern + _, bn_conv, _ = add_pattern + bn, conv = bn_conv + return conv + +def _conv_bn_add_relu_extra_inputs_getter_left(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + relu, add_pattern = pattern + _, bn_conv, extra_input = add_pattern + bn, conv = bn_conv + return [extra_input] + +conv_add_relu_left_optioins = itertools.product( + [True, False], # with_bn + [torch.add, operator.add], # add_op +) + +for with_bn, add_op in conv_add_relu_left_optioins: + if with_bn: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((nn.ReLU, (add_op, (nn.BatchNorm2d, nn.Conv2d), MatchAllNode))) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_bn_add_relu_left) + ._set_root_node_getter(_conv_bn_add_relu_root_node_getter_left) + ._set_extra_inputs_getter(_conv_bn_add_relu_extra_inputs_getter_left) + .set_fused_module(nni.ConvAddReLU2d)) + else: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((nn.ReLU, (add_op, nn.Conv2d, MatchAllNode))) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_add_relu_left) + ._set_root_node_getter(_conv_add_relu_root_node_getter_left) + ._set_extra_inputs_getter(_conv_add_relu_extra_inputs_getter_left) + .set_fused_module(nni.ConvAddReLU2d)) + +# Y conv2d +# \ / +# add +# \ +# relu + +def _fuse_conv_add_relu_right(is_qat, relu, add_pattern): + add, _, conv = add_pattern + return nni.ConvAddReLU2d(conv, add, relu) + +def _conv_add_relu_root_node_getter_right(pattern): + relu, add_pattern = pattern + _, _, conv = add_pattern + return conv + +def _conv_add_relu_extra_inputs_getter_right(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + relu, add_pattern = pattern + _, extra_input, conv = add_pattern + return [extra_input] + +# conv2d +# / +# Y bn +# \ / +# add +# \ +# relu + +def _fuse_conv_bn_add_relu_right(is_qat, relu, add_pattern): + add, _, bn_conv = add_pattern + bn, conv = bn_conv + if is_qat: + raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add, relu)}") + else: + fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn) + return nni.ConvAddReLU2d(fused_conv, add, relu) + +def _conv_bn_add_relu_root_node_getter_right(pattern): + relu, add_pattern = pattern + _, _, bn_conv = add_pattern + bn, conv = bn_conv + return conv + +def _conv_bn_add_relu_extra_inputs_getter_right(pattern): + """ get inputs pattern for extra inputs, inputs for root node + are assumed to be copied over from root node to the fused node + """ + relu, add_pattern = pattern + _, extra_input, bn_conv = add_pattern + bn, conv = bn_conv + return [extra_input] + +conv_add_relu_optioins = itertools.product( + [True, False], # with_bn + [torch.add, operator.add], # add_op +) + +for with_bn, add_op in conv_add_relu_optioins: + if with_bn: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((nn.ReLU, (add_op, MatchAllNode, (nn.BatchNorm2d, nn.Conv2d)))) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_bn_add_relu_right) + ._set_root_node_getter(_conv_bn_add_relu_root_node_getter_right) + ._set_extra_inputs_getter(_conv_bn_add_relu_extra_inputs_getter_right) + .set_fused_module(nni.ConvAddReLU2d)) + else: + conv_configs.append( + BackendPatternConfig() + ._set_pattern_complex_format((nn.ReLU, (add_op, MatchAllNode, nn.Conv2d))) # noqa: E131 + .set_observation_type(observation_type) + .set_dtype_configs(conv_dtype_configs) + .set_fuser_method(_fuse_conv_add_relu_right) + ._set_root_node_getter(_conv_add_relu_root_node_getter_right) + ._set_extra_inputs_getter(_conv_add_relu_extra_inputs_getter_right) + .set_fused_module(nni.ConvAddReLU2d)) + +conv_configs.append( + BackendPatternConfig(nni.ConvAddReLU2d) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(conv_dtype_configs) + .set_root_module(nn.Conv2d) + .set_reference_quantized_module(nnqr.Conv2d)) + +# ======================== +# | CONFIGS FOR LINEAR | +# ======================== + +linear_dtype_configs = [ + onednn_weighted_op_int8_dtype_config, + onednn_dynamic_int8_dtype_config, +] +linear_configs = _get_linear_configs(linear_dtype_configs) + +def _add_eltwise_fusion_configs(configs, root_module, root_op, post_module, post_op, + dtype_configs, fuser_method, fused_module, observation_type, + ref_quant_module): + # 1 base module + op module fusion config + configs.append( + BackendPatternConfig((root_module, post_module)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuser_method) + .set_fused_module(fused_module)) + # base module + functional post op + configs.append( + BackendPatternConfig((root_module, post_op)) + .set_dtype_configs(dtype_configs) # noqa: E131 + .set_fuser_method(fuser_method) + .set_fused_module(fused_module)) + + # 2 fused module configs + configs.append( + BackendPatternConfig(fused_module) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs) + .set_root_module(root_module) + .set_reference_quantized_module(ref_quant_module)) + + # 3 functional base op + post op configs + configs.append( + BackendPatternConfig((root_op, post_module)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + configs.append( + BackendPatternConfig((root_op, post_op)) + .set_observation_type(observation_type) # noqa: E131 + .set_dtype_configs(dtype_configs)) + +# Configs for linear + leaky_relu fusion +_add_eltwise_fusion_configs(linear_configs, nn.Linear, F.linear, + nn.LeakyReLU, F.leaky_relu, linear_dtype_configs, + _sequential_wrapper2(nni.LinearLeakyReLU), + nni.LinearLeakyReLU, observation_type, nnqr.Linear) + +# Configs for linear module + batchnorm + leaky_relu +linear_configs.append( + BackendPatternConfig((nn.Linear, nn.BatchNorm1d, nn.LeakyReLU)) + .set_dtype_configs(linear_dtype_configs) # noqa: E131 + .set_fuser_method(_fuse_linear_bn_leaky_relu) + .set_fused_module(nni.LinearLeakyReLU)) + +# Configs for linear + tanh fusion +_add_eltwise_fusion_configs(linear_configs, nn.Linear, F.linear, + nn.Tanh, torch.tanh, linear_dtype_configs, + _sequential_wrapper2(nni.LinearTanh), + nni.LinearTanh, observation_type, nnqr.Linear) + +# =========================== +# | CONFIGS FOR OTHER OPS | +# =========================== + +binary_op_dtype_configs = [onednn_op_quint8_dtype_config] +default_op_dtype_configs = [onednn_op_quint8_dtype_config] +fixed_qparams_op_dtype_configs = [onednn_op_quint8_dtype_config] +share_qparams_op_dtype_configs = [onednn_op_quint8_dtype_config] +rnn_op_dtype_configs = [onednn_dynamic_int8_dtype_config] +embedding_op_dtype_configs = [onednn_weight_only_qint8_dtype_config] +layer_norm_op_dtype_configs = [onednn_input_output_only_quint8_dtype_config] + +# ===================== +# | BACKEND CONFIGS | +# ===================== + +def get_onednn_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for PyTorch's native ONEDNN backend. + """ + return BackendConfig("onednn") \ + .set_backend_pattern_configs(conv_configs) \ + .set_backend_pattern_configs(linear_configs) \ + .set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \ + .set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs)) + +__all__ = [ + "get_onednn_backend_config", +] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/qnnpack.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/qnnpack.py new file mode 100644 index 0000000000000000000000000000000000000000..772a25c65574481d70186e9d968039756b2fa0ae --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/qnnpack.py @@ -0,0 +1,160 @@ +import torch +from ._common_operator_config_utils import ( + _get_binary_op_configs, + _get_bn_configs, + _get_cat_config, + _get_conv_configs, + _get_default_op_configs, + _get_embedding_op_configs, + _get_fixed_qparams_op_configs, + _get_linear_configs, + _get_rnn_op_configs, + _get_share_qparams_op_configs, +) +from .backend_config import BackendConfig, DTypeConfig, DTypeWithConstraints + +__all__ = [ + "get_qnnpack_backend_config", +] + +# =================== +# | DTYPE CONFIGS | +# =================== + +qnnpack_weighted_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, +) + +qnnpack_default_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, +) + +qnnpack_default_op_fp16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float16, + weight_dtype=torch.float16, + bias_dtype=torch.float16, +) + +qnnpack_default_dynamic_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.float, + weight_dtype=torch.qint8, + bias_dtype=torch.float, + is_dynamic=True, +) + +qnnpack_default_dynamic_float16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float, + weight_dtype=torch.float16, + bias_dtype=torch.float, + is_dynamic=True, +) + +qnnpack_weight_only_quint8_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint8, +) + +qnnpack_weight_only_quint4x2_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint4x2, +) + +# xnnpack compatible dtype configs + +# We restrict scale values to be 2 ** -12 to ensure the +# requantization scale never falls below the xnnpack lower +# threshold. Additionally, for qint8 weight, we restrict +# the quantization values to [-127, +127], excluding -128. +# For more detail, refer to the description of +# `default_symmetric_qnnpack_qconfig`. + +# TODO: add additional restriction on qscheme to ensure it +# is either per_tensor_symmetric or per_channel_symmetric + +qnnpack_act_qint8_scale_min_2_neg_12 = DTypeWithConstraints( + dtype=torch.qint8, + scale_min_lower_bound=2 ** -12, +) + +qnnpack_weight_qint8_neg_127_to_127_scale_min_2_neg_12 = DTypeWithConstraints( + dtype=torch.qint8, + quant_min_lower_bound=-127, + quant_max_upper_bound=127, + scale_min_lower_bound=2 ** -12, +) + +qnnpack_weighted_op_qint8_symmetric_dtype_config = DTypeConfig( + input_dtype=qnnpack_act_qint8_scale_min_2_neg_12, + output_dtype=qnnpack_act_qint8_scale_min_2_neg_12, + weight_dtype=qnnpack_weight_qint8_neg_127_to_127_scale_min_2_neg_12, + bias_dtype=torch.float, +) + +qnnpack_default_op_qint8_symmetric_dtype_config = DTypeConfig( + input_dtype=qnnpack_act_qint8_scale_min_2_neg_12, + output_dtype=qnnpack_act_qint8_scale_min_2_neg_12, +) + + +# ===================== +# | BACKEND CONFIGS | +# ===================== + +def get_qnnpack_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for PyTorch's native QNNPACK backend. + """ + conv_dtype_configs = [ + qnnpack_weighted_op_qint8_symmetric_dtype_config, + qnnpack_weighted_op_quint8_dtype_config, + ] + linear_dtype_configs = [ + qnnpack_weighted_op_qint8_symmetric_dtype_config, + qnnpack_weighted_op_quint8_dtype_config, + qnnpack_default_dynamic_int8_dtype_config, + qnnpack_default_dynamic_float16_dtype_config, + ] + binary_op_dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + qnnpack_default_op_quint8_dtype_config, + ] + default_op_dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + qnnpack_default_op_quint8_dtype_config, + ] + fixed_qparams_op_dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + qnnpack_default_op_quint8_dtype_config, + ] + share_qparams_op_dtype_configs = [ + qnnpack_default_op_qint8_symmetric_dtype_config, + qnnpack_default_op_quint8_dtype_config, + ] + rnn_op_dtype_configs = [ + qnnpack_default_dynamic_int8_dtype_config, + qnnpack_default_dynamic_float16_dtype_config, + ] + embedding_op_dtype_configs = [ + qnnpack_weight_only_quint8_dtype_config, + qnnpack_weight_only_quint4x2_dtype_config, + ] + return BackendConfig("qnnpack") \ + .set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \ + .set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \ + .set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \ + .set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs)) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/tensorrt.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/tensorrt.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5f761508bbb9e95392bfe07d494f7fba61303d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/tensorrt.py @@ -0,0 +1,81 @@ +import torch +from .backend_config import ( + BackendConfig, + BackendPatternConfig, + DTypeConfig, + ObservationType +) +from ._common_operator_config_utils import ( + _get_binary_op_configs, + _get_linear_configs, + _get_conv_configs, + _get_share_qparams_op_configs, + _get_tensor_info_op_configs, +) + +__all__ = [ + "get_tensorrt_backend_config", + "get_tensorrt_backend_config_dict", +] + +def get_tensorrt_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for the TensorRT backend. + NOTE: Current api will change in the future, it's just to unblock experimentation for + new backends, please don't use it right now. + TODO: add a README when it's more stable + """ + # dtype configs + weighted_op_qint8_dtype_config = DTypeConfig( + input_dtype=torch.qint8, + output_dtype=torch.qint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, + ) + non_weighted_op_qint8_dtype_config = DTypeConfig( + input_dtype=torch.qint8, + output_dtype=torch.qint8, + ) + + addmm_config = BackendPatternConfig(torch.addmm) \ + .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \ + .add_dtype_config(weighted_op_qint8_dtype_config) \ + ._set_input_type_to_index({ + "bias": 0, + "input": 1, + "weight": 2, + }) + cat_config = BackendPatternConfig(torch.cat) \ + .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) \ + .add_dtype_config(non_weighted_op_qint8_dtype_config) + conv_dtype_configs = [ + weighted_op_qint8_dtype_config, + ] + linear_dtype_configs = [ + weighted_op_qint8_dtype_config, + ] + binary_op_dtype_configs = [ + weighted_op_qint8_dtype_config, + ] + share_qparams_op_dtype_configs = [ + non_weighted_op_qint8_dtype_config, + ] + tensor_info_op_dtype_configs = [ + non_weighted_op_qint8_dtype_config, + ] + # there might be things not supported in fx2trt, but it will error out + # during fx2trt conversion and can support them after that + return BackendConfig("tensorrt") \ + .set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \ + .set_backend_pattern_config(addmm_config) \ + .set_backend_pattern_config(cat_config) \ + .set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \ + .set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) + +def get_tensorrt_backend_config_dict(): + """ + Return the `BackendConfig` for the TensorRT backend in dictionary form. + """ + return get_tensorrt_backend_config().to_dict() diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2e738227407907ef942786937eb082f41d9e02ef --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/utils.py @@ -0,0 +1,279 @@ +from typing import Dict, Any, List, Callable, Union, Tuple, Type + +import torch +import torch.nn as nn +import torch.nn.functional as F +from .backend_config import ( + BackendConfig, + BackendPatternConfig, + DTypeConfig, +) +from ..utils import Pattern +from ..fuser_method_mappings import ( + _reverse2, + _reverse3, +) + +__all__ = [ + "get_pattern_to_dtype_configs", + "get_qat_module_classes", + "get_fused_module_classes", + "get_pattern_to_input_type_to_index", + "get_root_module_to_quantized_reference_module", + "get_fuser_method_mapping", + "get_module_to_qat_module", + "get_fusion_pattern_to_root_node_getter", + "get_fusion_pattern_to_extra_inputs_getter", + "remove_boolean_dispatch_from_name", + "pattern_to_human_readable", + "entry_to_pretty_str", +] + +def get_pattern_to_dtype_configs(backend_config: BackendConfig) -> Dict[Pattern, List[DTypeConfig]]: + pattern_to_dtype_configs: Dict[Pattern, List[DTypeConfig]] = {} + for pattern, config in backend_config._pattern_complex_format_to_config.items(): + pattern_to_dtype_configs[pattern] = config.dtype_configs + return pattern_to_dtype_configs + +def get_qat_module_classes(backend_config: BackendConfig) -> Tuple[type, ...]: + qat_module_classes = [] + for config in backend_config.configs: + if config.qat_module is not None: + qat_module_classes.append(config.qat_module) + return tuple(set(qat_module_classes)) + +def get_fused_module_classes(backend_config: BackendConfig) -> Tuple[type, ...]: + fused_module_classes = [] + for config in backend_config.configs: + if config.fused_module is not None: + fused_module_classes.append(config.fused_module) + return tuple(set(fused_module_classes)) + +def get_pattern_to_input_type_to_index(backend_config: BackendConfig) -> Dict[Pattern, Dict[str, int]]: + pattern_to_input_type_to_index: Dict[Pattern, Dict[str, int]] = {} + for pattern, config in backend_config._pattern_complex_format_to_config.items(): + pattern_to_input_type_to_index[pattern] = config._input_type_to_index + return pattern_to_input_type_to_index + +def get_root_module_to_quantized_reference_module( + backend_config: BackendConfig) -> Dict[Type[torch.nn.Module], Type[torch.nn.Module]]: + mapping: Dict[Type[torch.nn.Module], Type[torch.nn.Module]] = {} + for config in backend_config.configs: + if config.root_module is not None and config.reference_quantized_module is not None: + mapping[config.root_module] = config.reference_quantized_module + return mapping + +def get_fuser_method_mapping(backend_config: BackendConfig) -> Dict[Pattern, Union[nn.Sequential, Callable]]: + fuser_method_mapping : Dict[Pattern, Union[nn.Sequential, Callable]] = {} + for pattern, config in backend_config._pattern_complex_format_to_config.items(): + if config.fuser_method is not None: + # Note: both the fuser method and the pattern are specified in forward order in the + # BackendConfig, but the internal pattern matching code uses the reversed nested tuple + # format, so we need to convert both to the internal format + fuser_method = _get_fuser_method_in_reversed_nested_tuple_format(config) + fuser_method_mapping[pattern] = fuser_method + return fuser_method_mapping + +def get_module_to_qat_module(backend_config: BackendConfig) -> Dict[Pattern, Type[torch.nn.Module]]: + module_to_qat_module: Dict[Pattern, Type[torch.nn.Module]] = {} + for pattern, config in backend_config._pattern_complex_format_to_config.items(): + if config.qat_module is not None: + module_to_qat_module[pattern] = config.qat_module + return module_to_qat_module + +def get_fusion_pattern_to_root_node_getter(backend_config: BackendConfig) -> Dict[Pattern, Callable]: + """ Get a map from fusion pattern to a function that returns the root node + from the fusion pattern, e.g. the most common one is: + def get_root_node(node_pattern): + while not isinstance(node_pattern[-1], Node): + node_pattern = node_pattern[-1] + return node_pattern[-1] + This can work for all patterns whose root node is the "last node" in the pattern, + e.g. (torch.add, MatchAllNode, (torch.ReLU, torch.Conv2d)) + """ + root_node_getter_mapping: Dict[Pattern, Callable] = {} + for pattern, config in backend_config._pattern_complex_format_to_config.items(): + if config._root_node_getter is not None: + root_node_getter_mapping[pattern] = config._root_node_getter + return root_node_getter_mapping + +def get_fusion_pattern_to_extra_inputs_getter(backend_config: BackendConfig) -> Dict[Pattern, Callable]: + """ Get a map from fusion pattern to a function that returns extra input nodes + from the fusion pattern, in the order required by the root node. This is optional, + if not specified, we will not copy over any extra inputs for the root node. + Example: + # Let's say we have the pattern (torch.add, MatchAllNode, (torch.nn.BatchNorm2d, torch.nn.Conv2d)) + # and root node is torch.nn.Conv2d, and the node in MatchAllNode would be an extra + # argument to the fused module, we can unpack the pattern and return the node at + # MatchAllNode here + # we can implement extra_inputs_getter as follows: + def extra_inputs_getter(pattern) -> List[Any]: + add, extra_input, conv_pattern = pattern + return [extra_input] + """ + extra_inputs_getter_mapping: Dict[Pattern, Callable] = {} + for pattern, config in backend_config._pattern_complex_format_to_config.items(): + if config._extra_inputs_getter is not None: + extra_inputs_getter_mapping[pattern] = config._extra_inputs_getter + return extra_inputs_getter_mapping + +def remove_boolean_dispatch_from_name(p) -> Any: + """ + Some ops have a default string representation such as + '.fn at 0x7ff1106bf280>', + this function replaces them with the hardcoded function names. + """ + if p is F.fractional_max_pool2d: + return "torch.nn.functional.fractional_max_pool2d" + elif p is F.fractional_max_pool3d: + return "torch.nn.functional.fractional_max_pool3d" + elif p is F.max_pool1d: + return "torch.nn.functional.max_pool1d" + elif p is F.max_pool2d: + return "torch.nn.functional.max_pool2d" + elif p is F.max_pool3d: + return "torch.nn.functional.max_pool3d" + elif p is F.adaptive_max_pool1d: + return "torch.nn.functional.adaptive_max_pool1d" + elif p is F.adaptive_max_pool2d: + return "torch.nn.functional.adaptive_max_pool2d" + elif p is F.adaptive_max_pool3d: + return "torch.nn.functional.adaptive_max_pool3d" + assert "boolean_dispatch" not in str(p), \ + f"{p} does not have a human readable representation in " + \ + "quantization documentation" + return p + +def pattern_to_human_readable(p) -> Any: + if isinstance(p, tuple): + # nested patterns, recurse + return tuple(pattern_to_human_readable(inner_p) for inner_p in p) + elif isinstance(p, str): + # method names are already human readable + return p + else: + p = remove_boolean_dispatch_from_name(p) + return p + +# TODO(future PR): move backend_config_dict to use dataclass and move this logic to +# the corresponding __str__ function +def entry_to_pretty_str(entry) -> str: + """ + Given a backend_config_dict entry, returns a string with the human readable + representation of it. + """ + s = "{\n" + + # always output the pattern first + if "pattern" in entry: + pattern_str = pattern_to_human_readable(entry["pattern"]) + + s += f" 'pattern': {pattern_str},\n" + + # custom output for dtype_configs to make it look nice + if "dtype_configs" in entry: + s += " 'dtype_configs': [\n" + for dtype_config in entry["dtype_configs"]: + s += " {\n" + for k, v in dtype_config.items(): + s += f" '{k}': {v},\n" + s += " },\n" + s += " ],\n" + + # custom output for num_tensor_args_to_observation_type to make it look nice + if "num_tensor_args_to_observation_type" in entry: + s += " 'num_tensor_args_to_observation_type': {\n" + for k, v in entry["num_tensor_args_to_observation_type"].items(): + s += f" {k}: {v},\n" + s += " },\n" + + # output all the other fields + custom_handled_fields = [ + "pattern", + "dtype_configs", + "num_tensor_args_to_observation_type", + ] + for field_name in entry: + if field_name in custom_handled_fields: + continue + s += f" '{field_name}': {entry[field_name]},\n" + + s += "}" + return s + +def _get_pattern_in_reversed_nested_tuple_format(config: BackendPatternConfig) -> Pattern: + """ + Return the pattern specified in the given config in the reversed nested tuple format + used internally in the quantization pattern matching code. + + If the pattern is not a tuple, or the pattern is already specified in the reversed + nested tuple format, return the pattern as is. Otherwise: + + For 2-tuples (a, b), return (b, a). + For 3-tuples (a, b, c), return (c, (b, a)). + + For example: + * Given nn.Linear, return nn.Linear + * Given (nn.Linear, nn.ReLU), return (nn.ReLU, nn.Linear) + * Given (nn.Conv2d, nn.BatchNorm2d, nn.ReLU), return + (nn.ReLU, (nn.BatchNorm2d, nn.Conv2d)) + + For context, the reason why this is needed is the user-facing BackendConfig + API accepts the flat 2-or-3-tuple format in forward order. While this simple + format handles the vast majority of use cases, it does not handle the more + complex ones, and so the internal pattern matching code for quantization uses + the following, more general reversed nested tuple format instead: + + operator = module_type | functional | torch op | native op | MatchAllNode + Pattern = (operator, Pattern, Pattern, ...) | operator + + In the future, we expect to replace the above complex format with the one used + by the subgraph rewriter in torch.fx, so we don't have to maintain our own + complex pattern matching code. Then we won't need this helper function anymore. + """ + if config._pattern_complex_format is not None: + return config._pattern_complex_format + if config.pattern is None: + raise ValueError("Either 'pattern' or 'pattern_complex_format' must be specified") + if not isinstance(config.pattern, tuple): + return config.pattern + + # Pattern is specified in the simple tuple format, need to convert + if len(config.pattern) == 2: + (a, b) = config.pattern + return (b, a) + elif len(config.pattern) == 3: + (a, b, c) = config.pattern + return (c, (b, a)) + else: + raise ValueError("Expected a tuple with 2 or 3 elements, got: ", config.pattern) + +def _get_fuser_method_in_reversed_nested_tuple_format(config: BackendPatternConfig) -> Callable: + """ + Return the fuser method specified in the given config in the reversed nested + tuple format used internally in the quantization pattern matching code. + + If pattern is specified in the reversed nested tuple format, we assume the + fuser method is also specified in this format and simply return it as is. + Otherwise, we convert the fuser method as follows: + + * Given f(is_qat, conv, relu), return f'(is_qat, relu, conv) + * Given f(is_qat, conv, bn, relu), return f'(is_qat, relu, bn_conv), + where bn_conv is a 2-tuple (bn, conv) + + The first argument of a fuser method is always `is_qat` and is not affected + in the conversion. We currently only support functions with 3 or 4 arguments. + """ + assert config.fuser_method is not None + if config._pattern_complex_format is not None: + return config.fuser_method + if not isinstance(config.pattern, tuple): + raise ValueError("Expected pattern to be a tuple, got: ", config.pattern) + + # Pattern is specified in the simple tuple format, need to convert + if len(config.pattern) == 2: + return _reverse2(config.fuser_method) + elif len(config.pattern) == 3: + return _reverse3(config.fuser_method) + else: + raise ValueError("Expected a tuple with 2 or 3 elements, got: ", config.pattern) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/x86.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/x86.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f165958f2791d3e6e2f63eceecdcd9e6f6d50c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/x86.py @@ -0,0 +1,113 @@ +import torch +from ._common_operator_config_utils import ( + _get_binary_op_configs, + _get_bn_configs, + _get_cat_config, + _get_conv_configs, + _get_default_op_configs, + _get_embedding_op_configs, + _get_fixed_qparams_op_configs, + _get_linear_configs, + _get_rnn_op_configs, + _get_share_qparams_op_configs, + _get_tensor_info_op_configs, +) +from .backend_config import BackendConfig, DTypeConfig + +__all__ = [ + "get_x86_backend_config", +] + +# =================== +# | DTYPE CONFIGS | +# =================== + +# X86 aligns with FBGEMM for now + +x86_weighted_op_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, + weight_dtype=torch.qint8, + bias_dtype=torch.float, +) + +x86_default_op_quint8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.quint8, +) + +x86_default_op_fp16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float16, + weight_dtype=torch.float16, + bias_dtype=torch.float16, +) + +x86_default_dynamic_int8_dtype_config = DTypeConfig( + input_dtype=torch.quint8, + output_dtype=torch.float, + weight_dtype=torch.qint8, + bias_dtype=torch.float, + is_dynamic=True, +) + +x86_default_dynamic_float16_dtype_config = DTypeConfig( + input_dtype=torch.float16, + output_dtype=torch.float, + weight_dtype=torch.float16, + bias_dtype=torch.float, + is_dynamic=True, +) + +x86_weight_only_quint8_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint8, +) + +x86_weight_only_quint4x2_dtype_config = DTypeConfig( + input_dtype=torch.float, + output_dtype=torch.float, + weight_dtype=torch.quint4x2, +) + + +# ===================== +# | BACKEND CONFIGS | +# ===================== + +def get_x86_backend_config() -> BackendConfig: + """ + Return the `BackendConfig` for PyTorch's native x86 backend. + """ + conv_dtype_configs = [x86_weighted_op_int8_dtype_config] + linear_dtype_configs = [ + x86_weighted_op_int8_dtype_config, + x86_default_dynamic_int8_dtype_config, + x86_default_dynamic_float16_dtype_config, + ] + binary_op_dtype_configs = [x86_weighted_op_int8_dtype_config] + default_op_dtype_configs = [x86_default_op_quint8_dtype_config] + fixed_qparams_op_dtype_configs = [x86_weighted_op_int8_dtype_config] + share_qparams_op_dtype_configs = [x86_default_op_quint8_dtype_config] + tensor_info_op_dtype_configs = [x86_default_op_quint8_dtype_config] + rnn_op_dtype_configs = [ + x86_default_dynamic_int8_dtype_config, + x86_default_dynamic_float16_dtype_config, + ] + embedding_op_dtype_configs = [ + x86_weight_only_quint8_dtype_config, + x86_weight_only_quint4x2_dtype_config, + ] + return BackendConfig("x86") \ + .set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \ + .set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \ + .set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \ + .set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \ + .set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs)) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6951a7a4f3033c7e9977404668f58307fd6631f7 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f28e5573a4eaf01851a6e226a87adb4de3d9e876 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be6b39fd096fcd66d0970a4ed9d19bbe2357750 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ecd2376aa5a454fb575b50fefdc2476727dc5bf Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39097c5fed806a84795b919701a5c153e8f7356a Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73c77b63faf28369230e1d00a05c9dc4685c0e64 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2800b335e0a9181e0bcd452ab800dea866d3592 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9801be959f820db0273d2cec0d971f678c4662c0 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e5b5827f8939edefa64eba13ea9cef543561e75 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6824e640347cf3203f44a2e97e94eb843a992da1 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2204e4d63450c506cfb38ff26e3cc30597e11096 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96571712d51a7d6392f724df15b4d7ad7772d7e8 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3d741ba9abc6cc4ec2254470c67dc8c1e182b3d Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2385fb8c2bd4f4fa9e90533a85eb6138bf70775d Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35c46098f60be0297601a071d374c757f0bf8bc6 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b4174f37ab91c49c0b8a78f1224b01b06344f46 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a4233896966b1a9542b70c1f3a03d8d846ee6e1 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a807456c775f3f1607639ebda9db53aab1aaeb31 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/utils.py @@ -0,0 +1,58 @@ +from typing import List + +import torch +from torch.ao.quantization.quantizer.quantizer import QuantizationAnnotation +from torch.fx import Node + + +def _annotate_input_qspec_map(node: Node, input_node: Node, qspec): + quantization_annotation = node.meta.get( + "quantization_annotation", QuantizationAnnotation() + ) + if quantization_annotation.input_qspec_map is None: + quantization_annotation.input_qspec_map = {} + quantization_annotation.input_qspec_map[input_node] = qspec + node.meta["quantization_annotation"] = quantization_annotation + + +def _annotate_output_qspec(node: Node, qspec): + quantization_annotation = node.meta.get( + "quantization_annotation", QuantizationAnnotation() + ) + quantization_annotation.output_qspec = qspec + node.meta["quantization_annotation"] = quantization_annotation + + +def _is_sym_size_node(node: Node): + return ( + node.op == "call_function" + and node.target == torch.ops.aten.sym_size.default + or node.target == torch.ops.aten.sym_numel.default + or node.target == torch.ops.aten.sym_numel + or node.target == torch.ops.aten.sym_size + ) + + +def _node_only_used_for_sym_size(node: Node, partition_nodes: List[Node]): + """ + This utility is used to handle cases when dynami_shape=True tracing leads + to symint nodes in the pattern of linear module. In those cases, we need to + distinguish between the nodes that are in input for just extracting value of + some dimentions (and symint nodes) vs. the one that is activation. + For example: + graph(x, y, weight): + size_0 = torch.ops.aten.sym_size([x], [0]) + size_1 = torch.ops.aten.sym_size([y], [1]) + view_size = size_0 * size_1 + size_3 = torch.ops.aten.sym_size([x], [2]) + vie_out = torch.ops.aten.view(x, [view_size, size_3]) + return mm(view_out, weight) + In the example above y node is not actual input. It exist only to extract size_1 + """ + if _is_sym_size_node(node): + return True + + return all( + ((user not in partition_nodes) or _is_sym_size_node(user)) + for user in node.users + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/xnnpack_quantizer.py b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/xnnpack_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc20ebe520fcd14f431764e19886e03bda31771 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/xnnpack_quantizer.py @@ -0,0 +1,484 @@ +from __future__ import annotations + +import copy +import functools + +from typing import Any, Callable, Dict, List, Optional, Set + +import torch +import torch._dynamo as torchdynamo +import torch.nn.functional as F +from torch.ao.quantization.fake_quantize import FusedMovingAvgObsFakeQuantize +from torch.ao.quantization.observer import ( + HistogramObserver, + MinMaxObserver, + MovingAverageMinMaxObserver, + MovingAveragePerChannelMinMaxObserver, + PerChannelMinMaxObserver, + PlaceholderObserver, +) + +from torch.ao.quantization.qconfig import _ObserverOrFakeQuantizeConstructor + +from torch.ao.quantization.quantizer import QuantizationSpec, Quantizer + +from torch.ao.quantization.quantizer.xnnpack_quantizer_utils import ( + OP_TO_ANNOTATOR, + OperatorConfig, + OperatorPatternType, + QuantizationConfig, +) + +from torch.fx import Node + + +__all__ = [ + "XNNPACKQuantizer", + "get_symmetric_quantization_config", +] + + +def _get_dynamo_graph(function: Callable, inputs) -> torch.fx.Graph: + gm, _ = torchdynamo.export(function, aten_graph=True)(*inputs) + gm.graph.eliminate_dead_code() + return gm.graph + + +def _get_linear_patterns(input_size: List[int]): + in_channels = input_size[-1] + out_channels = 8 # hard coding but this should not matter + weight = torch.ones((out_channels, in_channels)) + bias = torch.ones((out_channels,)) + act = torch.ones(input_size) + + def linear_op(act, weight, bias=None): + return F.linear(act, weight, bias) + + pattern_w_bias = _get_dynamo_graph(linear_op, (act, weight, bias)) + pattern_wo_bias = _get_dynamo_graph(linear_op, (act, weight)) + return [pattern_w_bias, pattern_wo_bias] + + +def _supported_symmetric_quantized_operators() -> Dict[str, List[OperatorPatternType]]: + supported_operators: Dict[str, List[OperatorPatternType]] = { + # Both conv and linear should be able to handle relu + hardtanh fusion since + # those are clamp ops + "conv2d": [ + [torch.nn.Conv2d, torch.nn.ReLU], + [torch.nn.Conv2d, F.relu], + [F.conv2d, torch.nn.ReLU], + [F.conv2d, F.relu], + ], + "linear": [[torch.nn.Linear], [F.linear]], + "add": [[torch.add]], + "max_pool2d": [[torch.nn.MaxPool2d], [F.max_pool2d]], + "adaptive_avg_pool2d": [ + [torch.nn.AdaptiveAvgPool2d], + [F.adaptive_avg_pool2d], + ], + } + return copy.deepcopy(supported_operators) + + +def _get_supported_symmetric_config_and_operators() -> List[OperatorConfig]: + supported_config_and_operators: List[OperatorConfig] = [] + for quantization_config in [ + get_symmetric_quantization_config(), + get_symmetric_quantization_config(is_qat=True), + get_symmetric_quantization_config(is_per_channel=True), + get_symmetric_quantization_config(is_per_channel=True, is_qat=True), + ]: + ops = _supported_symmetric_quantized_operators() + for pattern_list in ops.values(): + supported_config_and_operators.append( + OperatorConfig(quantization_config, pattern_list) + ) + return copy.deepcopy(supported_config_and_operators) + + +@functools.lru_cache +def get_symmetric_quantization_config( + is_per_channel: bool = False, + is_qat: bool = False, + is_dynamic: bool = False, +): + if is_qat: + if is_dynamic: + raise NotImplementedError( + "dynamic quantization for qat is not yet implemented." + ) + act_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize + else: + if is_dynamic: + act_observer_or_fake_quant_ctr = PlaceholderObserver # type: ignore[assignment] + else: + act_observer_or_fake_quant_ctr = HistogramObserver # type: ignore[assignment] + + act_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-128, + quant_max=127, + qscheme=torch.per_tensor_affine, + is_dynamic=is_dynamic, + observer_or_fake_quant_ctr=act_observer_or_fake_quant_ctr.with_args( + eps=2**-12 + ), + ) + qscheme = ( + torch.per_channel_symmetric if is_per_channel else torch.per_tensor_symmetric + ) + weight_observer_or_fake_quant_ctr: _ObserverOrFakeQuantizeConstructor = ( + MinMaxObserver + ) + if is_qat: + weight_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize + elif is_per_channel: + weight_observer_or_fake_quant_ctr = PerChannelMinMaxObserver + + extra_args: Dict[str, Any] = {"eps": 2**-12} + if is_qat: + if qscheme == torch.per_tensor_symmetric: + extra_args["observer"] = MovingAverageMinMaxObserver + else: + extra_args["observer"] = MovingAveragePerChannelMinMaxObserver # type: ignore[dict-item] + weight_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-127, + quant_max=127, + qscheme=qscheme, + ch_axis=0, + is_dynamic=False, + observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + + bias_observer_or_fake_quant_ctr: _ObserverOrFakeQuantizeConstructor = ( + PlaceholderObserver + ) + bias_quantization_spec = QuantizationSpec( + dtype=torch.float, observer_or_fake_quant_ctr=bias_observer_or_fake_quant_ctr + ) + if is_dynamic: + quantization_config = QuantizationConfig( + act_quantization_spec, + None, + weight_quantization_spec, + bias_quantization_spec, + is_qat, + ) + else: + quantization_config = QuantizationConfig( + act_quantization_spec, + act_quantization_spec, + weight_quantization_spec, + bias_quantization_spec, + is_qat, + ) + return quantization_config + + +def _get_supported_config_and_operators() -> List[OperatorConfig]: + return _get_supported_symmetric_config_and_operators() + + +def _get_module_name_filter(module_name: str): + """Get the module_name_filter function for a given module name, the filter accepts + a node and checks if the node comes from a module that has certain module name + + For example: + node: linear_op = call_function[...](...) # comes from a module with name blocks.sub.linear1 + + + >> module_name_filter = _get_module_name_filter("blocks.sub") + >> print(module_name_filter(node)) + True # the node is from "blocks.sub" based on the fully qualified name "blocks.sub.linear1" + """ + + def module_name_filter(n: Node) -> bool: + # example: { + # 'L__self___sub': ("L['self'].sub", ), + # 'L__self___sub_linear': ("L['self'].sub.linear", ) + # } + nn_module_stack = n.meta["nn_module_stack"] + names = [ + n[len("L__self___") :].replace("_", ".") for n in nn_module_stack.keys() + ] + return module_name in names + + return module_name_filter + + +def _get_module_type_filter(tp: Callable): + """Get the module_type_filter function for a given module type, the filter accepts + a node and checks if the node comes from a module that has certain module type + + For example: + node: linear_op = call_function[...](...) # comes from a module with type Block -> Sub -> Linear + + + >> module_type_filter = _get_module_type_filter(Sub) # submodule with type `Sub`, under the `Block` submodule + >> print(module_type_filter(node)) + True # the node is from the submodule `Sub` (same for `Block` and `Linear` as well) + """ + + def module_type_filter(n: Node) -> bool: + # example: { + # 'L__self___sub': ("L['self'].sub", ), + # 'L__self___sub_linear': ("L['self'].sub.linear", ) + # } + nn_module_stack = n.meta["nn_module_stack"] + types = [t for _, t in nn_module_stack.values()] + return tp in types + + return module_type_filter + + +class XNNPACKQuantizer(Quantizer): + supported_config_and_operators = _get_supported_config_and_operators() + + def __init__(self): + super().__init__() + self.global_config: Optional[QuantizationConfig] = None + self.operator_type_config: Dict[str, Optional[QuantizationConfig]] = {} + self.module_type_config: Dict[Callable, Optional[QuantizationConfig]] = {} + self.module_name_config: Dict[str, Optional[QuantizationConfig]] = {} + + @classmethod + def get_supported_quantization_configs(cls) -> List[QuantizationConfig]: + op_configs: Set[QuantizationConfig] = set({}) + for spec, _ in cls.supported_config_and_operators: + op_configs.add(spec) + return list(op_configs) + + @classmethod + def get_supported_operator_for_quantization_config( + cls, quantization_config: Optional[QuantizationConfig] + ) -> List[OperatorPatternType]: + if quantization_config is None: + all_ops = [] + for _, ops in cls.supported_config_and_operators: + all_ops.extend(ops) + return all_ops + + for config, ops in cls.supported_config_and_operators: + # note: this assumes each entry in cls.supported_spec_and_operators + # corresponds to one spec, e.g. we don't have + # [(spec1, op_list1), (spec1, op_list2), (spec2, op_list3)] + # where the first and second entry have the same spec but did not + # merge the op list + if config == quantization_config: + return ops + return [] + + def set_global(self, quantization_config: QuantizationConfig) -> XNNPACKQuantizer: + self.global_config = quantization_config + return self + + def set_operator_type( + self, operator_type: str, quantization_config: QuantizationConfig + ) -> XNNPACKQuantizer: + self.operator_type_config[operator_type] = quantization_config + return self + + def set_module_type( + self, module_type: Callable, quantization_config: QuantizationConfig + ): + """Set quantization_config for a submodule with type: `module_type`, for example: + quantizer.set_module_name(Sub) or quantizer.set_module_name(nn.Linear), it will quantize all supported operator/operator + patterns in the submodule with this module type with the given `quantization_config` + """ + self.module_type_config[module_type] = quantization_config + return self + + def set_module_name( + self, module_name: str, quantization_config: Optional[QuantizationConfig] + ): + """Set quantization_config for a submodule with name: `module_name`, for example: + quantizer.set_module_name("blocks.sub"), it will quantize all supported operator/operator + patterns in the submodule with this module name with the given `quantization_config` + """ + assert ( + quantization_config is not None + ), " quantization_config == None is not supported yet" + self.module_name_config[module_name] = quantization_config + return self + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """just handling global spec for now""" + # hacked for handling dynamic linear quant. will fix later. + if self.global_config and self.global_config.input_activation.is_dynamic: # type: ignore[union-attr] + model = self._annotate_for_dynamic_quantization_config(model) + else: + model = self._annotate_for_static_quantization_config(model) + return model + + def _annotate_all_patterns( + self, + model: torch.fx.GraphModule, + config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> torch.fx.GraphModule: + # TODO: implement the support for None to be canceling out previous annotations + if config is None: + return model + + # assert config is not None + + self._annotate_linear(model, config, filter_fn) + self._annotate_conv2d_patterns(model, config, filter_fn) + self._annotate_max_pool2d(model, config, filter_fn) + self._annotate_add_patterns(model, config, filter_fn) + OP_TO_ANNOTATOR["mul_relu"](model, config, filter_fn) + OP_TO_ANNOTATOR["mul"](model, config, filter_fn) + self._annotate_adaptive_avg_pool2d(model, config, filter_fn) + self._annotate_gru_io_only(model, config, filter_fn) + return model + + def _annotate_for_static_quantization_config( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + for module_name, config in self.module_name_config.items(): + self._annotate_all_patterns( + model, config, _get_module_name_filter(module_name) + ) + + for module_type, config in self.module_type_config.items(): + self._annotate_all_patterns( + model, config, _get_module_type_filter(module_type) + ) + + self._annotate_all_patterns(model, self.global_config) + return model + + def _annotate_for_dynamic_quantization_config( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + for module_name, config in self.module_name_config.items(): + self._annotate_linear(model, config, _get_module_name_filter(module_name)) + + for module_type, config in self.module_type_config.items(): + self._annotate_linear(model, config, _get_module_type_filter(module_type)) + + self._annotate_linear(model, self.global_config) + return model + + def _annotate_conv2d_patterns( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + if quantization_config is None: + return + + if quantization_config.is_qat: + self._annotate_conv2d_bn_relu(gm, quantization_config, filter_fn) + self._annotate_conv2d_bn(gm, quantization_config, filter_fn) + self._annotate_conv2d_relu(gm, quantization_config, filter_fn) + self._annotate_conv2d(gm, quantization_config, filter_fn) + + def _annotate_conv2d_bn( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + """ + Note: This is only used for QAT. In PTQ, batchnorm should already be fused into the conv. + """ + return OP_TO_ANNOTATOR["conv2d_bn"](gm, quantization_config, filter_fn) + + def _annotate_conv2d_bn_relu( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + """ + Note: This is only used for QAT. In PTQ, batchnorm should already be fused into the conv. + """ + return OP_TO_ANNOTATOR["conv2d_bn_relu"](gm, quantization_config, filter_fn) + + def _annotate_conv2d_relu( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["conv2d_relu"](gm, quantization_config, filter_fn) + + def _annotate_conv2d( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["conv2d"](gm, quantization_config, filter_fn) + + def _annotate_linear( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["linear"](gm, quantization_config, filter_fn) + + def _annotate_adaptive_avg_pool2d( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["adaptive_avg_pool2d"]( + gm, quantization_config, filter_fn + ) + + # TODO: move this to BoltNNQuantizer? + def _annotate_gru_io_only( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["gru_io_only"](gm, quantization_config, filter_fn) + + def _annotate_max_pool2d( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["max_pool2d"](gm, quantization_config, filter_fn) + + def _annotate_add_patterns( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + self._annotate_add_relu(gm, quantization_config, filter_fn) + self._annotate_add(gm, quantization_config, filter_fn) + + def _annotate_add_relu( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["add_relu"](gm, quantization_config, filter_fn) + + def _annotate_add( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> None: + return OP_TO_ANNOTATOR["add"](gm, quantization_config, filter_fn) + + def validate(self, model: torch.fx.GraphModule) -> None: + pass + + @classmethod + def get_supported_operators(cls) -> List[OperatorConfig]: + return cls.supported_config_and_operators diff --git a/vlmpy310/lib/python3.10/site-packages/OpenGL_accelerate/arraydatatype.cpython-310-x86_64-linux-gnu.so b/vlmpy310/lib/python3.10/site-packages/OpenGL_accelerate/arraydatatype.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fe7ef99ee7dcd501be5aeb3bc000584fdfc3b689 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/OpenGL_accelerate/arraydatatype.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:022e8c0a5f6cb22d0a40820ae5fc59a763b15a68db23308aa2ce7d196b7cc7a8 +size 2431976 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/percentile_cy.cpython-310-x86_64-linux-gnu.so b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/percentile_cy.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..37fdcabf07d015d5810cbf2a176cba9da776f587 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/percentile_cy.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17b653b3072b64404c6040ae0c8b03cba1db98f9c842323ef5bd464a04f43cd4 +size 1247280 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_flood_fill.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_flood_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..330e3b1d3da258fbcd20567cc5c9f0bc32c09eee --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_flood_fill.py @@ -0,0 +1,310 @@ +"""flood_fill.py - in place flood fill algorithm + +This module provides a function to fill all equal (or within tolerance) values +connected to a given seed point with a different value. +""" + +import numpy as np + +from ..util import crop +from ._flood_fill_cy import _flood_fill_equal, _flood_fill_tolerance +from ._util import ( + _offsets_to_raveled_neighbors, + _resolve_neighborhood, + _set_border_values, +) +from .._shared.dtype import numeric_dtype_min_max + + +def flood_fill( + image, + seed_point, + new_value, + *, + footprint=None, + connectivity=None, + tolerance=None, + in_place=False, +): + """Perform flood filling on an image. + + Starting at a specific `seed_point`, connected points equal or within + `tolerance` of the seed value are found, then set to `new_value`. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + seed_point : tuple or int + The point in `image` used as the starting point for the flood fill. If + the image is 1D, this point may be given as an integer. + new_value : `image` type + New value to set the entire fill. This must be chosen in agreement + with the dtype of `image`. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel. It must contain only 1's and 0's, have the + same number of dimensions as `image`. If not given, all adjacent pixels + are considered as part of the neighborhood (fully connected). + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + tolerance : float or int, optional + If None (default), adjacent values must be strictly equal to the + value of `image` at `seed_point` to be filled. This is fastest. + If a tolerance is provided, adjacent points with values within plus or + minus tolerance from the seed point are filled (inclusive). + in_place : bool, optional + If True, flood filling is applied to `image` in place. If False, the + flood filled result is returned without modifying the input `image` + (default). + + Returns + ------- + filled : ndarray + An array with the same shape as `image` is returned, with values in + areas connected to and equal (or within tolerance of) the seed point + replaced with `new_value`. + + Notes + ----- + The conceptual analogy of this operation is the 'paint bucket' tool in many + raster graphics programs. + + Examples + -------- + >>> from skimage.morphology import flood_fill + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, with full connectivity (diagonals included): + + >>> flood_fill(image, (1, 1), 5) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [5, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, excluding diagonal points (connectivity 1): + + >>> flood_fill(image, (1, 1), 5, connectivity=1) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill with a tolerance: + + >>> flood_fill(image, (0, 0), 5, tolerance=1) + array([[5, 5, 5, 5, 5, 5, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 5, 5, 3]]) + """ + mask = flood( + image, + seed_point, + footprint=footprint, + connectivity=connectivity, + tolerance=tolerance, + ) + + if not in_place: + image = image.copy() + + image[mask] = new_value + return image + + +def flood(image, seed_point, *, footprint=None, connectivity=None, tolerance=None): + """Mask corresponding to a flood fill. + + Starting at a specific `seed_point`, connected points equal or within + `tolerance` of the seed value are found. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + seed_point : tuple or int + The point in `image` used as the starting point for the flood fill. If + the image is 1D, this point may be given as an integer. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel. It must contain only 1's and 0's, have the + same number of dimensions as `image`. If not given, all adjacent pixels + are considered as part of the neighborhood (fully connected). + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + tolerance : float or int, optional + If None (default), adjacent values must be strictly equal to the + initial value of `image` at `seed_point`. This is fastest. If a value + is given, a comparison will be done at every point and if within + tolerance of the initial value will also be filled (inclusive). + + Returns + ------- + mask : ndarray + A Boolean array with the same shape as `image` is returned, with True + values for areas connected to and equal (or within tolerance of) the + seed point. All other values are False. + + Notes + ----- + The conceptual analogy of this operation is the 'paint bucket' tool in many + raster graphics programs. This function returns just the mask + representing the fill. + + If indices are desired rather than masks for memory reasons, the user can + simply run `numpy.nonzero` on the result, save the indices, and discard + this mask. + + Examples + -------- + >>> from skimage.morphology import flood + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, with full connectivity (diagonals included): + + >>> mask = flood(image, (1, 1)) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [5, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, excluding diagonal points (connectivity 1): + + >>> mask = flood(image, (1, 1), connectivity=1) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill with a tolerance: + + >>> mask = flood(image, (0, 0), tolerance=1) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[5, 5, 5, 5, 5, 5, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 5, 5, 3]]) + """ + # Correct start point in ravelled image - only copy if non-contiguous + image = np.asarray(image) + if image.flags.f_contiguous is True: + order = 'F' + elif image.flags.c_contiguous is True: + order = 'C' + else: + image = np.ascontiguousarray(image) + order = 'C' + + # Shortcut for rank zero + if 0 in image.shape: + return np.zeros(image.shape, dtype=bool) + + # Convenience for 1d input + try: + iter(seed_point) + except TypeError: + seed_point = (seed_point,) + + seed_value = image[seed_point] + seed_point = tuple(np.asarray(seed_point) % image.shape) + + footprint = _resolve_neighborhood( + footprint, connectivity, image.ndim, enforce_adjacency=False + ) + center = tuple(s // 2 for s in footprint.shape) + # Compute padding width as the maximum offset to neighbors on each axis. + # Generates a 2-tuple of (pad_start, pad_end) for each axis. + pad_width = [ + (np.max(np.abs(idx - c)),) * 2 for idx, c in zip(np.nonzero(footprint), center) + ] + + # Must annotate borders + working_image = np.pad( + image, pad_width, mode='constant', constant_values=image.min() + ) + # Stride-aware neighbors - works for both C- and Fortran-contiguity + ravelled_seed_idx = np.ravel_multi_index( + [i + pad_start for i, (pad_start, pad_end) in zip(seed_point, pad_width)], + working_image.shape, + order=order, + ) + neighbor_offsets = _offsets_to_raveled_neighbors( + working_image.shape, footprint, center=center, order=order + ) + + # Use a set of flags; see _flood_fill_cy.pyx for meanings + flags = np.zeros(working_image.shape, dtype=np.uint8, order=order) + _set_border_values(flags, value=2, border_width=pad_width) + + try: + if tolerance is not None: + tolerance = abs(tolerance) + # Account for over- & underflow problems with seed_value ± tolerance + # in a way that works with NumPy 1 & 2 + min_value, max_value = numeric_dtype_min_max(seed_value.dtype) + low_tol = max(min_value.item(), seed_value.item() - tolerance) + high_tol = min(max_value.item(), seed_value.item() + tolerance) + + _flood_fill_tolerance( + working_image.ravel(order), + flags.ravel(order), + neighbor_offsets, + ravelled_seed_idx, + seed_value, + low_tol, + high_tol, + ) + else: + _flood_fill_equal( + working_image.ravel(order), + flags.ravel(order), + neighbor_offsets, + ravelled_seed_idx, + seed_value, + ) + except TypeError: + if working_image.dtype == np.float16: + # Provide the user with clearer error message + raise TypeError( + "dtype of `image` is float16 which is not " + "supported, try upcasting to float32" + ) + else: + raise + + # Output what the user requested; view does not create a new copy. + return crop(flags, pad_width, copy=False).view(bool) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_skeletonize.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_skeletonize.py new file mode 100644 index 0000000000000000000000000000000000000000..62e01f9685d510f13e0b202c9162f233fb296e8f --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_skeletonize.py @@ -0,0 +1,655 @@ +""" +Algorithms for computing the skeleton of a binary image +""" + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import check_nD +from ..util import crop +from ._skeletonize_lee_cy import _compute_thin_image +from ._skeletonize_various_cy import ( + _fast_skeletonize, + _skeletonize_loop, + _table_lookup_index, +) + + +def skeletonize(image, *, method=None): + """Compute the skeleton of the input image via thinning. + + Parameters + ---------- + image : (M, N[, P]) ndarray of bool or int + The image containing the objects to be skeletonized. Each connected component + in the image is reduced to a single-pixel wide skeleton. The image is binarized + prior to thinning; thus, adjacent objects of different intensities are + considered as one. Zero or ``False`` values represent the background, nonzero + or ``True`` values -- foreground. + method : {'zhang', 'lee'}, optional + Which algorithm to use. Zhang's algorithm [Zha84]_ only works for + 2D images, and is the default for 2D. Lee's algorithm [Lee94]_ + works for 2D or 3D images and is the default for 3D. + + Returns + ------- + skeleton : (M, N[, P]) ndarray of bool + The thinned image. + + See Also + -------- + medial_axis + + References + ---------- + .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models + via 3-D medial surface/axis thinning algorithms. + Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. + + .. [Zha84] A fast parallel algorithm for thinning digital patterns, + T. Y. Zhang and C. Y. Suen, Communications of the ACM, + March 1984, Volume 27, Number 3. + + Examples + -------- + >>> X, Y = np.ogrid[0:9, 0:9] + >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(bool) + >>> ellipse.view(np.uint8) + array([[0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + >>> skel = skeletonize(ellipse) + >>> skel.view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + image = image.astype(bool, order="C", copy=False) + + if method not in {'zhang', 'lee', None}: + raise ValueError( + f'skeletonize method should be either "lee" or "zhang", ' f'got {method}.' + ) + if image.ndim == 2 and (method is None or method == 'zhang'): + skeleton = _skeletonize_zhang(image) + elif image.ndim == 3 and method == 'zhang': + raise ValueError('skeletonize method "zhang" only works for 2D ' 'images.') + elif image.ndim == 3 or (image.ndim == 2 and method == 'lee'): + skeleton = _skeletonize_lee(image) + else: + raise ValueError( + f'skeletonize requires a 2D or 3D image as input, ' f'got {image.ndim}D.' + ) + return skeleton + + +def _skeletonize_zhang(image): + """Return the skeleton of a 2D binary image. + + Thinning is used to reduce each connected component in a binary image + to a single-pixel wide skeleton. + + Parameters + ---------- + image : numpy.ndarray + An image containing the objects to be skeletonized. Zeros or ``False`` + represent background, nonzero values or ``True`` are foreground. + + Returns + ------- + skeleton : ndarray + A matrix containing the thinned image. + + See Also + -------- + medial_axis, skeletonize, thin + + Notes + ----- + The algorithm [Zha84]_ works by making successive passes of the image, + removing pixels on object borders. This continues until no + more pixels can be removed. The image is correlated with a + mask that assigns each pixel a number in the range [0...255] + corresponding to each possible pattern of its 8 neighboring + pixels. A look up table is then used to assign the pixels a + value of 0, 1, 2 or 3, which are selectively removed during + the iterations. + + Note that this algorithm will give different results than a + medial axis transform, which is also often referred to as + "skeletonization". + + References + ---------- + .. [Zha84] A fast parallel algorithm for thinning digital patterns, + T. Y. Zhang and C. Y. Suen, Communications of the ACM, + March 1984, Volume 27, Number 3. + + Examples + -------- + >>> X, Y = np.ogrid[0:9, 0:9] + >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(bool) + >>> ellipse.view(np.uint8) + array([[0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + >>> skel = skeletonize(ellipse) + >>> skel.view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + if image.ndim != 2: + raise ValueError("Zhang's skeletonize method requires a 2D array") + return _fast_skeletonize(image) + + +# --------- Skeletonization and thinning based on Guo and Hall 1989 --------- + + +def _generate_thin_luts(): + """generate LUTs for thinning algorithm (for reference)""" + + def nabe(n): + return np.array([n >> i & 1 for i in range(0, 9)]).astype(bool) + + def G1(n): + s = 0 + bits = nabe(n) + for i in (0, 2, 4, 6): + if not (bits[i]) and (bits[i + 1] or bits[(i + 2) % 8]): + s += 1 + return s == 1 + + g1_lut = np.array([G1(n) for n in range(256)]) + + def G2(n): + n1, n2 = 0, 0 + bits = nabe(n) + for k in (1, 3, 5, 7): + if bits[k] or bits[k - 1]: + n1 += 1 + if bits[k] or bits[(k + 1) % 8]: + n2 += 1 + return min(n1, n2) in [2, 3] + + g2_lut = np.array([G2(n) for n in range(256)]) + + g12_lut = g1_lut & g2_lut + + def G3(n): + bits = nabe(n) + return not ((bits[1] or bits[2] or not (bits[7])) and bits[0]) + + def G3p(n): + bits = nabe(n) + return not ((bits[5] or bits[6] or not (bits[3])) and bits[4]) + + g3_lut = np.array([G3(n) for n in range(256)]) + g3p_lut = np.array([G3p(n) for n in range(256)]) + + g123_lut = g12_lut & g3_lut + g123p_lut = g12_lut & g3p_lut + + return g123_lut, g123p_lut + + +# fmt: off +G123_LUT = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=bool) + +G123P_LUT = np.array([0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, + 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=bool) +# fmt: on + + +def thin(image, max_num_iter=None): + """ + Perform morphological thinning of a binary image. + + Parameters + ---------- + image : binary (M, N) ndarray + The image to thin. If this input isn't already a binary image, + it gets converted into one: In this case, zero values are considered + background (False), nonzero values are considered foreground (True). + max_num_iter : int, number of iterations, optional + Regardless of the value of this parameter, the thinned image + is returned immediately if an iteration produces no change. + If this parameter is specified it thus sets an upper bound on + the number of iterations performed. + + Returns + ------- + out : ndarray of bool + Thinned image. + + See Also + -------- + skeletonize, medial_axis + + Notes + ----- + This algorithm [1]_ works by making multiple passes over the image, + removing pixels matching a set of criteria designed to thin + connected regions while preserving eight-connected components and + 2 x 2 squares [2]_. In each of the two sub-iterations the algorithm + correlates the intermediate skeleton image with a neighborhood mask, + then looks up each neighborhood in a lookup table indicating whether + the central pixel should be deleted in that sub-iteration. + + References + ---------- + .. [1] Z. Guo and R. W. Hall, "Parallel thinning with + two-subiteration algorithms," Comm. ACM, vol. 32, no. 3, + pp. 359-373, 1989. :DOI:`10.1145/62065.62074` + .. [2] Lam, L., Seong-Whan Lee, and Ching Y. Suen, "Thinning + Methodologies-A Comprehensive Survey," IEEE Transactions on + Pattern Analysis and Machine Intelligence, Vol 14, No. 9, + p. 879, 1992. :DOI:`10.1109/34.161346` + + Examples + -------- + >>> square = np.zeros((7, 7), dtype=bool) + >>> square[1:-1, 2:-2] = 1 + >>> square[0, 1] = 1 + >>> square.view(np.uint8) + array([[0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> skel = thin(square) + >>> skel.view(np.uint8) + array([[0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + # check that image is 2d + check_nD(image, 2) + + # convert image to uint8 with values in {0, 1} + skel = np.asanyarray(image, dtype=bool).copy().view(np.uint8) + + # neighborhood mask + mask = np.array([[8, 4, 2], [16, 0, 1], [32, 64, 128]], dtype=np.uint8) + + # iterate until convergence, up to the iteration limit + max_num_iter = max_num_iter or np.inf + num_iter = 0 + n_pts_old, n_pts_new = np.inf, np.sum(skel) + while n_pts_old != n_pts_new and num_iter < max_num_iter: + n_pts_old = n_pts_new + + # perform the two "subiterations" described in the paper + for lut in [G123_LUT, G123P_LUT]: + # correlate image with neighborhood mask + N = ndi.correlate(skel, mask, mode='constant') + # take deletion decision from this subiteration's LUT + D = np.take(lut, N) + # perform deletion + skel[D] = 0 + + n_pts_new = np.sum(skel) # count points after thinning + num_iter += 1 + + return skel.astype(bool) + + +# --------- Skeletonization by medial axis transform -------- + +_eight_connect = ndi.generate_binary_structure(2, 2) + + +def medial_axis(image, mask=None, return_distance=False, *, rng=None): + """Compute the medial axis transform of a binary image. + + Parameters + ---------- + image : binary ndarray, shape (M, N) + The image of the shape to skeletonize. If this input isn't already a + binary image, it gets converted into one: In this case, zero values are + considered background (False), nonzero values are considered + foreground (True). + mask : binary ndarray, shape (M, N), optional + If a mask is given, only those elements in `image` with a true + value in `mask` are used for computing the medial axis. + return_distance : bool, optional + If true, the distance transform is returned as well as the skeleton. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The PRNG determines the order in which pixels are processed for + tiebreaking. + + .. versionadded:: 0.19 + + Returns + ------- + out : ndarray of bools + Medial axis transform of the image + dist : ndarray of ints, optional + Distance transform of the image (only returned if `return_distance` + is True) + + See Also + -------- + skeletonize, thin + + Notes + ----- + This algorithm computes the medial axis transform of an image + as the ridges of its distance transform. + + The different steps of the algorithm are as follows + * A lookup table is used, that assigns 0 or 1 to each configuration of + the 3x3 binary square, whether the central pixel should be removed + or kept. We want a point to be removed if it has more than one neighbor + and if removing it does not change the number of connected components. + + * The distance transform to the background is computed, as well as + the cornerness of the pixel. + + * The foreground (value of 1) points are ordered by + the distance transform, then the cornerness. + + * A cython function is called to reduce the image to its skeleton. It + processes pixels in the order determined at the previous step, and + removes or maintains a pixel according to the lookup table. Because + of the ordering, it is possible to process all pixels in only one + pass. + + Examples + -------- + >>> square = np.zeros((7, 7), dtype=bool) + >>> square[1:-1, 2:-2] = 1 + >>> square.view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> medial_axis(square).view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + global _eight_connect + if mask is None: + masked_image = image.astype(bool) + else: + masked_image = image.astype(bool).copy() + masked_image[~mask] = False + # + # Build lookup table - three conditions + # 1. Keep only positive pixels (center_is_foreground array). + # AND + # 2. Keep if removing the pixel results in a different connectivity + # (if the number of connected components is different with and + # without the central pixel) + # OR + # 3. Keep if # pixels in neighborhood is 2 or less + # Note that table is independent of image + center_is_foreground = (np.arange(512) & 2**4).astype(bool) + table = ( + center_is_foreground # condition 1. + & ( + np.array( + [ + ndi.label(_pattern_of(index), _eight_connect)[1] + != ndi.label(_pattern_of(index & ~(2**4)), _eight_connect)[1] + for index in range(512) + ] + ) # condition 2 + | np.array([np.sum(_pattern_of(index)) < 3 for index in range(512)]) + ) + # condition 3 + ) + + # Build distance transform + distance = ndi.distance_transform_edt(masked_image) + if return_distance: + store_distance = distance.copy() + + # Corners + # The processing order along the edge is critical to the shape of the + # resulting skeleton: if you process a corner first, that corner will + # be eroded and the skeleton will miss the arm from that corner. Pixels + # with fewer neighbors are more "cornery" and should be processed last. + # We use a cornerness_table lookup table where the score of a + # configuration is the number of background (0-value) pixels in the + # 3x3 neighborhood + cornerness_table = np.array( + [9 - np.sum(_pattern_of(index)) for index in range(512)] + ) + corner_score = _table_lookup(masked_image, cornerness_table) + + # Define arrays for inner loop + i, j = np.mgrid[0 : image.shape[0], 0 : image.shape[1]] + result = masked_image.copy() + distance = distance[result] + i = np.ascontiguousarray(i[result], dtype=np.intp) + j = np.ascontiguousarray(j[result], dtype=np.intp) + result = np.ascontiguousarray(result, np.uint8) + + # Determine the order in which pixels are processed. + # We use a random # for tiebreaking. Assign each pixel in the image a + # predictable, random # so that masking doesn't affect arbitrary choices + # of skeletons + # + generator = np.random.default_rng(rng) + tiebreaker = generator.permutation(np.arange(masked_image.sum())) + order = np.lexsort((tiebreaker, corner_score[masked_image], distance)) + order = np.ascontiguousarray(order, dtype=np.int32) + + table = np.ascontiguousarray(table, dtype=np.uint8) + # Remove pixels not belonging to the medial axis + _skeletonize_loop(result, i, j, order, table) + + result = result.astype(bool) + if mask is not None: + result[~mask] = image[~mask] + if return_distance: + return result, store_distance + else: + return result + + +def _pattern_of(index): + """ + Return the pattern represented by an index value + Byte decomposition of index + """ + return np.array( + [ + [index & 2**0, index & 2**1, index & 2**2], + [index & 2**3, index & 2**4, index & 2**5], + [index & 2**6, index & 2**7, index & 2**8], + ], + bool, + ) + + +def _table_lookup(image, table): + """ + Perform a morphological transform on an image, directed by its + neighbors + + Parameters + ---------- + image : ndarray + A binary image + table : ndarray + A 512-element table giving the transform of each pixel given + the values of that pixel and its 8-connected neighbors. + + Returns + ------- + result : ndarray of same shape as `image` + Transformed image + + Notes + ----- + The pixels are numbered like this:: + + 0 1 2 + 3 4 5 + 6 7 8 + + The index at a pixel is the sum of 2** for pixels + that evaluate to true. + """ + # + # We accumulate into the indexer to get the index into the table + # at each point in the image + # + if image.shape[0] < 3 or image.shape[1] < 3: + image = image.astype(bool) + indexer = np.zeros(image.shape, int) + indexer[1:, 1:] += image[:-1, :-1] * 2**0 + indexer[1:, :] += image[:-1, :] * 2**1 + indexer[1:, :-1] += image[:-1, 1:] * 2**2 + + indexer[:, 1:] += image[:, :-1] * 2**3 + indexer[:, :] += image[:, :] * 2**4 + indexer[:, :-1] += image[:, 1:] * 2**5 + + indexer[:-1, 1:] += image[1:, :-1] * 2**6 + indexer[:-1, :] += image[1:, :] * 2**7 + indexer[:-1, :-1] += image[1:, 1:] * 2**8 + else: + indexer = _table_lookup_index(np.ascontiguousarray(image, np.uint8)) + image = table[indexer] + return image + + +def _skeletonize_lee(image): + """Compute the skeleton of a binary image. + + Thinning is used to reduce each connected component in a binary image + to a single-pixel wide skeleton. + + Parameters + ---------- + image : ndarray, 2D or 3D + An image containing the objects to be skeletonized. Zeros or ``False`` + represent background, nonzero values or ``True`` are foreground. + + Returns + ------- + skeleton : ndarray of bool + The thinned image. + + See Also + -------- + skeletonize, medial_axis + + Notes + ----- + The method of [Lee94]_ uses an octree data structure to examine a 3x3x3 + neighborhood of a pixel. The algorithm proceeds by iteratively sweeping + over the image, and removing pixels at each iteration until the image + stops changing. Each iteration consists of two steps: first, a list of + candidates for removal is assembled; then pixels from this list are + rechecked sequentially, to better preserve connectivity of the image. + + The algorithm this function implements is different from the algorithms + used by either `skeletonize` or `medial_axis`, thus for 2D images the + results produced by this function are generally different. + + References + ---------- + .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models + via 3-D medial surface/axis thinning algorithms. + Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. + + """ + # make sure the image is 3D or 2D + if image.ndim < 2 or image.ndim > 3: + raise ValueError( + "skeletonize can only handle 2D or 3D images; " + f"got image.ndim = {image.ndim} instead." + ) + + image_o = image.astype(bool, order="C", copy=False) + + # make a 2D input image 3D and pad it w/ zeros to simplify dealing w/ boundaries + # NB: careful here to not clobber the original *and* minimize copying + if image.ndim == 2: + image_o = image_o[np.newaxis, ...] + image_o = np.pad(image_o, pad_width=1, mode='constant') # copies + + # do the computation + image_o = _compute_thin_image(image_o) + + # crop it back and restore the original intensity range + image_o = crop(image_o, crop_width=1) + if image.ndim == 2: + image_o = image_o[0] + + return image_o diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_util.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..bcdfdb643e08b95f2d6a36ef1719991180353113 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/_util.py @@ -0,0 +1,328 @@ +"""Utility functions used in the morphology subpackage.""" + +import numpy as np +from scipy import ndimage as ndi + + +def _validate_connectivity(image_dim, connectivity, offset): + """Convert any valid connectivity to a footprint and offset. + + Parameters + ---------- + image_dim : int + The number of dimensions of the input image. + connectivity : int, array, or None + The neighborhood connectivity. An integer is interpreted as in + ``scipy.ndimage.generate_binary_structure``, as the maximum number + of orthogonal steps to reach a neighbor. An array is directly + interpreted as a footprint and its shape is validated against + the input image shape. ``None`` is interpreted as a connectivity of 1. + offset : tuple of int, or None + The coordinates of the center of the footprint. + + Returns + ------- + c_connectivity : array of bool + The footprint (structuring element) corresponding to the input + `connectivity`. + offset : array of int + The offset corresponding to the center of the footprint. + + Raises + ------ + ValueError: + If the image dimension and the connectivity or offset dimensions don't + match. + """ + if connectivity is None: + connectivity = 1 + + if np.isscalar(connectivity): + c_connectivity = ndi.generate_binary_structure(image_dim, connectivity) + else: + c_connectivity = np.array(connectivity, bool) + if c_connectivity.ndim != image_dim: + raise ValueError("Connectivity dimension must be same as image") + + if offset is None: + if any([x % 2 == 0 for x in c_connectivity.shape]): + raise ValueError("Connectivity array must have an unambiguous " "center") + + offset = np.array(c_connectivity.shape) // 2 + + return c_connectivity, offset + + +def _raveled_offsets_and_distances( + image_shape, + *, + footprint=None, + connectivity=1, + center=None, + spacing=None, + order='C', +): + """Compute offsets to neighboring pixels in raveled coordinate space. + + This function also returns the corresponding distances from the center + pixel given a spacing (assumed to be 1 along each axis by default). + + Parameters + ---------- + image_shape : tuple of int + The shape of the image for which the offsets are being computed. + footprint : array of bool + The footprint of the neighborhood, expressed as an n-dimensional array + of 1s and 0s. If provided, the connectivity argument is ignored. + connectivity : {1, ..., ndim} + The square connectivity of the neighborhood: the number of orthogonal + steps allowed to consider a pixel a neighbor. See + `scipy.ndimage.generate_binary_structure`. Ignored if footprint is + provided. + center : tuple of int + Tuple of indices to the center of the footprint. If not provided, it + is assumed to be the center of the footprint, either provided or + generated by the connectivity argument. + spacing : tuple of float + The spacing between pixels/voxels along each axis. + order : 'C' or 'F' + The ordering of the array, either C or Fortran ordering. + + Returns + ------- + raveled_offsets : ndarray + Linear offsets to a samples neighbors in the raveled image, sorted by + their distance from the center. + distances : ndarray + The pixel distances corresponding to each offset. + + Notes + ----- + This function will return values even if `image_shape` contains a dimension + length that is smaller than `footprint`. + + Examples + -------- + >>> off, d = _raveled_offsets_and_distances( + ... (4, 5), footprint=np.ones((4, 3)), center=(1, 1) + ... ) + >>> off + array([-5, -1, 1, 5, -6, -4, 4, 6, 10, 9, 11]) + >>> d[0] + 1.0 + >>> d[-1] # distance from (1, 1) to (3, 2) + 2.236... + """ + ndim = len(image_shape) + if footprint is None: + footprint = ndi.generate_binary_structure(rank=ndim, connectivity=connectivity) + if center is None: + center = tuple(s // 2 for s in footprint.shape) + + if not footprint.ndim == ndim == len(center): + raise ValueError( + "number of dimensions in image shape, footprint and its" + "center index does not match" + ) + + offsets = np.stack( + [(idx - c) for idx, c in zip(np.nonzero(footprint), center)], axis=-1 + ) + + if order == 'F': + offsets = offsets[:, ::-1] + image_shape = image_shape[::-1] + elif order != 'C': + raise ValueError("order must be 'C' or 'F'") + + # Scale offsets in each dimension and sum + ravel_factors = image_shape[1:] + (1,) + ravel_factors = np.cumprod(ravel_factors[::-1])[::-1] + raveled_offsets = (offsets * ravel_factors).sum(axis=1) + + # Sort by distance + if spacing is None: + spacing = np.ones(ndim) + weighted_offsets = offsets * spacing + distances = np.sqrt(np.sum(weighted_offsets**2, axis=1)) + sorted_raveled_offsets = raveled_offsets[np.argsort(distances, kind="stable")] + sorted_distances = np.sort(distances, kind="stable") + + # If any dimension in image_shape is smaller than footprint.shape + # duplicates might occur, remove them + if any(x < y for x, y in zip(image_shape, footprint.shape)): + # np.unique reorders, which we don't want + _, indices = np.unique(sorted_raveled_offsets, return_index=True) + indices = np.sort(indices, kind="stable") + sorted_raveled_offsets = sorted_raveled_offsets[indices] + sorted_distances = sorted_distances[indices] + + # Remove "offset to center" + sorted_raveled_offsets = sorted_raveled_offsets[1:] + sorted_distances = sorted_distances[1:] + + return sorted_raveled_offsets, sorted_distances + + +def _offsets_to_raveled_neighbors(image_shape, footprint, center, order='C'): + """Compute offsets to a samples neighbors if the image would be raveled. + + Parameters + ---------- + image_shape : tuple + The shape of the image for which the offsets are computed. + footprint : ndarray + The footprint (structuring element) determining the neighborhood + expressed as an n-D array of 1's and 0's. + center : tuple + Tuple of indices to the center of `footprint`. + order : {"C", "F"}, optional + Whether the image described by `image_shape` is in row-major (C-style) + or column-major (Fortran-style) order. + + Returns + ------- + raveled_offsets : ndarray + Linear offsets to a samples neighbors in the raveled image, sorted by + their distance from the center. + + Notes + ----- + This function will return values even if `image_shape` contains a dimension + length that is smaller than `footprint`. + + Examples + -------- + >>> _offsets_to_raveled_neighbors((4, 5), np.ones((4, 3)), (1, 1)) + array([-5, -1, 1, 5, -6, -4, 4, 6, 10, 9, 11]) + >>> _offsets_to_raveled_neighbors((2, 3, 2), np.ones((3, 3, 3)), (1, 1, 1)) + array([-6, -2, -1, 1, 2, 6, -8, -7, -5, -4, -3, 3, 4, 5, 7, 8, -9, + 9]) + """ + raveled_offsets = _raveled_offsets_and_distances( + image_shape, footprint=footprint, center=center, order=order + )[0] + + return raveled_offsets + + +def _resolve_neighborhood(footprint, connectivity, ndim, enforce_adjacency=True): + """Validate or create a footprint (structuring element). + + Depending on the values of `connectivity` and `footprint` this function + either creates a new footprint (`footprint` is None) using `connectivity` + or validates the given footprint (`footprint` is not None). + + Parameters + ---------- + footprint : ndarray + The footprint (structuring) element used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + ndim : int + Number of dimensions `footprint` ought to have. + enforce_adjacency : bool + A boolean that determines whether footprint must only specify direct + neighbors. + + Returns + ------- + footprint : ndarray + Validated or new footprint specifying the neighborhood. + + Examples + -------- + >>> _resolve_neighborhood(None, 1, 2) + array([[False, True, False], + [ True, True, True], + [False, True, False]]) + >>> _resolve_neighborhood(None, None, 3).shape + (3, 3, 3) + """ + if footprint is None: + if connectivity is None: + connectivity = ndim + footprint = ndi.generate_binary_structure(ndim, connectivity) + else: + # Validate custom structured element + footprint = np.asarray(footprint, dtype=bool) + # Must specify neighbors for all dimensions + if footprint.ndim != ndim: + raise ValueError( + "number of dimensions in image and footprint do not" "match" + ) + # Must only specify direct neighbors + if enforce_adjacency and any(s != 3 for s in footprint.shape): + raise ValueError("dimension size in footprint is not 3") + elif any((s % 2 != 1) for s in footprint.shape): + raise ValueError("footprint size must be odd along all dimensions") + + return footprint + + +def _set_border_values(image, value, border_width=1): + """Set edge values along all axes to a constant value. + + Parameters + ---------- + image : ndarray + The array to modify inplace. + value : scalar + The value to use. Should be compatible with `image`'s dtype. + border_width : int or sequence of tuples + A sequence with one 2-tuple per axis where the first and second values + are the width of the border at the start and end of the axis, + respectively. If an int is provided, a uniform border width along all + axes is used. + + Examples + -------- + >>> image = np.zeros((4, 5), dtype=int) + >>> _set_border_values(image, 1) + >>> image + array([[1, 1, 1, 1, 1], + [1, 0, 0, 0, 1], + [1, 0, 0, 0, 1], + [1, 1, 1, 1, 1]]) + >>> image = np.zeros((8, 8), dtype=int) + >>> _set_border_values(image, 1, border_width=((1, 1), (2, 3))) + >>> image + array([[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]]) + """ + if np.isscalar(border_width): + border_width = ((border_width, border_width),) * image.ndim + elif len(border_width) != image.ndim: + raise ValueError('length of `border_width` must match image.ndim') + for axis, npad in enumerate(border_width): + if len(npad) != 2: + raise ValueError('each sequence in `border_width` must have ' 'length 2') + w_start, w_end = npad + if w_start == w_end == 0: + continue + elif w_start == w_end == 1: + # Index first and last element in the current dimension + sl = (slice(None),) * axis + ((0, -1),) + (...,) + image[sl] = value + continue + if w_start > 0: + # set first w_start entries along axis to value + sl = (slice(None),) * axis + (slice(0, w_start),) + (...,) + image[sl] = value + if w_end > 0: + # set last w_end entries along axis to value + sl = (slice(None),) * axis + (slice(-w_end, None),) + (...,) + image[sl] = value diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/binary.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f9bc06a75aab26945e9623315e2b605c1169b2 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/binary.py @@ -0,0 +1,320 @@ +""" +Binary morphological operations +""" + +import numpy as np +from scipy import ndimage as ndi + +from .footprints import _footprint_is_sequence, pad_footprint +from .misc import default_footprint + + +def _iterate_binary_func(binary_func, image, footprint, out, border_value): + """Helper to call `binary_func` for each footprint in a sequence. + + binary_func is a binary morphology function that accepts "structure", + "output" and "iterations" keyword arguments + (e.g. `scipy.ndimage.binary_erosion`). + """ + fp, num_iter = footprint[0] + binary_func( + image, structure=fp, output=out, iterations=num_iter, border_value=border_value + ) + for fp, num_iter in footprint[1:]: + # Note: out.copy() because the computation cannot be in-place! + # SciPy <= 1.7 did not automatically make a copy if needed. + binary_func( + out.copy(), + structure=fp, + output=out, + iterations=num_iter, + border_value=border_value, + ) + return out + + +# The default_footprint decorator provides a diamond footprint as +# default with the same dimension as the input image and size 3 along each +# axis. +@default_footprint +def binary_erosion(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological erosion of an image. + + This function returns the same result as grayscale erosion but performs + faster for binary images. + + Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all + pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright + regions and enlarges dark regions. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'max' or 'ignore', pixels outside the image domain are assumed + to be `True`, which causes them to not influence the result. + Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + eroded : ndarray of bool or uint + The result of the morphological erosion taking values in + ``[False, True]``. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + For even-sized footprints, :func:`skimage.morphology.erosion` and + this function produce an output that differs: one is shifted by one pixel + compared to the other. + + See also + -------- + skimage.morphology.isotropic_erosion + + """ + if out is None: + out = np.empty(image.shape, dtype=bool) + + if mode not in {"max", "min", "ignore"}: + raise ValueError(f"unsupported mode, got {mode!r}") + border_value = False if mode == 'min' else True + + footprint = pad_footprint(footprint, pad_end=True) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_binary_func( + binary_func=ndi.binary_erosion, + image=image, + footprint=footprint, + out=out, + border_value=border_value, + ) + return out + + +@default_footprint +def binary_dilation(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological dilation of an image. + + This function returns the same result as grayscale dilation but performs + faster for binary images. + + Morphological dilation sets a pixel at ``(i,j)`` to the maximum over all + pixels in the neighborhood centered at ``(i,j)``. Dilation enlarges bright + regions and shrinks dark regions. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'min' or 'ignore', pixels outside the image domain are assumed + to be `False`, which causes them to not influence the result. + Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + dilated : ndarray of bool or uint + The result of the morphological dilation with values in + ``[False, True]``. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + For non-symmetric footprints, :func:`skimage.morphology.binary_dilation` + and :func:`skimage.morphology.dilation` produce an output that differs: + `binary_dilation` mirrors the footprint, whereas `dilation` does not. + + See also + -------- + skimage.morphology.isotropic_dilation + + """ + if out is None: + out = np.empty(image.shape, dtype=bool) + + if mode not in {"max", "min", "ignore"}: + raise ValueError(f"unsupported mode, got {mode!r}") + border_value = True if mode == 'max' else False + + footprint = pad_footprint(footprint, pad_end=True) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_binary_func( + binary_func=ndi.binary_dilation, + image=image, + footprint=footprint, + out=out, + border_value=border_value, + ) + return out + + +@default_footprint +def binary_opening(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological opening of an image. + + This function returns the same result as grayscale opening but performs + faster for binary images. + + The morphological opening on an image is defined as an erosion followed by + a dilation. Opening can remove small bright spots (i.e. "salt") and connect + small dark cracks. This tends to "open" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'ignore', pixels outside the image domain are assumed to be `True` + for the erosion and `False` for the dilation, which causes them to not + influence the result. Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + opening : ndarray of bool + The result of the morphological opening. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + See also + -------- + skimage.morphology.isotropic_opening + + """ + tmp = binary_erosion(image, footprint, mode=mode) + out = binary_dilation(tmp, footprint, out=out, mode=mode) + return out + + +@default_footprint +def binary_closing(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological closing of an image. + + This function returns the same result as grayscale closing but performs + faster for binary images. + + The morphological closing on an image is defined as a dilation followed by + an erosion. Closing can remove small dark spots (i.e. "pepper") and connect + small bright cracks. This tends to "close" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'ignore', pixels outside the image domain are assumed to be `True` + for the erosion and `False` for the dilation, which causes them to not + influence the result. Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + closing : ndarray of bool + The result of the morphological closing. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + See also + -------- + skimage.morphology.isotropic_closing + + """ + tmp = binary_dilation(image, footprint, mode=mode) + out = binary_erosion(tmp, footprint, out=out, mode=mode) + return out diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/extrema.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/extrema.py new file mode 100644 index 0000000000000000000000000000000000000000..a87cef0c0a2e335bf6bfe773c0660a9f6451ba0a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/extrema.py @@ -0,0 +1,549 @@ +"""extrema.py - local minima and maxima + +This module provides functions to find local maxima and minima of an image. +Here, local maxima (minima) are defined as connected sets of pixels with equal +gray level which is strictly greater (smaller) than the gray level of all +pixels in direct neighborhood of the connected set. In addition, the module +provides the related functions h-maxima and h-minima. + +Soille, P. (2003). Morphological Image Analysis: Principles and Applications +(2nd ed.), Chapter 6. Springer-Verlag New York, Inc. +""" + +import numpy as np + +from .._shared.utils import warn +from ..util import dtype_limits, invert, crop +from . import grayreconstruct, _util +from ._extrema_cy import _local_maxima + + +def _add_constant_clip(image, const_value): + """Add constant to the image while handling overflow issues gracefully.""" + min_dtype, max_dtype = dtype_limits(image, clip_negative=False) + + if const_value > (max_dtype - min_dtype): + raise ValueError( + "The added constant is not compatible" "with the image data type." + ) + + result = image + const_value + result[image > max_dtype - const_value] = max_dtype + return result + + +def _subtract_constant_clip(image, const_value): + """Subtract constant from image while handling underflow issues.""" + min_dtype, max_dtype = dtype_limits(image, clip_negative=False) + + if const_value > (max_dtype - min_dtype): + raise ValueError( + "The subtracted constant is not compatible" "with the image data type." + ) + + result = image - const_value + result[image < (const_value + min_dtype)] = min_dtype + return result + + +def h_maxima(image, h, footprint=None): + """Determine all maxima of the image with height >= h. + + The local maxima are defined as connected sets of pixels with equal + gray level strictly greater than the gray level of all pixels in direct + neighborhood of the set. + + A local maximum M of height h is a local maximum for which + there is at least one path joining M with an equal or higher local maximum + on which the minimal value is f(M) - h (i.e. the values along the path + are not decreasing by more than h with respect to the maximum's value) + and no path to an equal or higher local maximum for which the minimal + value is greater. + + The global maxima of the image are also found by this function. + + Parameters + ---------- + image : ndarray + The input image for which the maxima are to be calculated. + h : unsigned integer + The minimal height of all extracted maxima. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the ball of radius 1 according to the maximum norm + (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) + + Returns + ------- + h_max : ndarray + The local maxima of height >= h and the global maxima. + The resulting image is a binary image, where pixels belonging to + the determined maxima take value 1, the others take value 0. + + See Also + -------- + skimage.morphology.h_minima + skimage.morphology.local_maxima + skimage.morphology.local_minima + + References + ---------- + .. [1] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import extrema + + We create an image (quadratic function with a maximum in the center and + 4 additional constant maxima. + The heights of the maxima are: 1, 21, 41, 61, 81 + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all maxima with a height of at least 40: + + >>> maxima = extrema.h_maxima(f, 40) + + The resulting image will contain 3 local maxima. + """ + + # Check for h value that is larger then range of the image. If this + # is True then there are no h-maxima in the image. + if h > np.ptp(image): + return np.zeros(image.shape, dtype=np.uint8) + + # Check for floating point h value. For this to work properly + # we need to explicitly convert image to float64. + # + # FIXME: This could give incorrect results if image is int64 and + # has a very high dynamic range. The dtype of image is + # changed to float64, and different integer values could + # become the same float due to rounding. + # + # >>> ii64 = np.iinfo(np.int64) + # >>> a = np.array([ii64.max, ii64.max - 2]) + # >>> a[0] == a[1] + # False + # >>> b = a.astype(np.float64) + # >>> b[0] == b[1] + # True + # + if np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer): + if (h % 1) != 0: + warn( + 'possible precision loss converting image to ' + 'floating point. To silence this warning, ' + 'ensure image and h have same data type.', + stacklevel=2, + ) + image = image.astype(float) + else: + h = image.dtype.type(h) + + if h == 0: + raise ValueError("h = 0 is ambiguous, use local_maxima() " "instead?") + + if np.issubdtype(image.dtype, np.floating): + # The purpose of the resolution variable is to allow for the + # small rounding errors that inevitably occur when doing + # floating point arithmetic. We want shifted_img to be + # guaranteed to be h less than image. If we only subtract h + # there may be pixels were shifted_img ends up being + # slightly greater than image - h. + # + # The resolution is scaled based on the pixel values in the + # image because floating point precision is relative. A + # very large value of 1.0e10 will have a large precision, + # say +-1.0e4, and a very small value of 1.0e-10 will have + # a very small precision, say +-1.0e-16. + # + resolution = 2 * np.finfo(image.dtype).resolution * np.abs(image) + shifted_img = image - h - resolution + else: + shifted_img = _subtract_constant_clip(image, h) + + rec_img = grayreconstruct.reconstruction( + shifted_img, image, method='dilation', footprint=footprint + ) + residue_img = image - rec_img + return (residue_img >= h).astype(np.uint8) + + +def h_minima(image, h, footprint=None): + """Determine all minima of the image with depth >= h. + + The local minima are defined as connected sets of pixels with equal + gray level strictly smaller than the gray levels of all pixels in direct + neighborhood of the set. + + A local minimum M of depth h is a local minimum for which + there is at least one path joining M with an equal or lower local minimum + on which the maximal value is f(M) + h (i.e. the values along the path + are not increasing by more than h with respect to the minimum's value) + and no path to an equal or lower local minimum for which the maximal + value is smaller. + + The global minima of the image are also found by this function. + + Parameters + ---------- + image : ndarray + The input image for which the minima are to be calculated. + h : unsigned integer + The minimal depth of all extracted minima. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the ball of radius 1 according to the maximum norm + (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) + + Returns + ------- + h_min : ndarray + The local minima of depth >= h and the global minima. + The resulting image is a binary image, where pixels belonging to + the determined minima take value 1, the others take value 0. + + See Also + -------- + skimage.morphology.h_maxima + skimage.morphology.local_maxima + skimage.morphology.local_minima + + References + ---------- + .. [1] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import extrema + + We create an image (quadratic function with a minimum in the center and + 4 additional constant maxima. + The depth of the minima are: 1, 21, 41, 61, 81 + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 160; f[2:4,7:9] = 140; f[7:9,2:4] = 120; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all minima with a depth of at least 40: + + >>> minima = extrema.h_minima(f, 40) + + The resulting image will contain 3 local minima. + """ + if h > np.ptp(image): + return np.zeros(image.shape, dtype=np.uint8) + + if np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer): + if (h % 1) != 0: + warn( + 'possible precision loss converting image to ' + 'floating point. To silence this warning, ' + 'ensure image and h have same data type.', + stacklevel=2, + ) + image = image.astype(float) + else: + h = image.dtype.type(h) + + if h == 0: + raise ValueError("h = 0 is ambiguous, use local_minima() " "instead?") + + if np.issubdtype(image.dtype, np.floating): + resolution = 2 * np.finfo(image.dtype).resolution * np.abs(image) + shifted_img = image + h + resolution + else: + shifted_img = _add_constant_clip(image, h) + + rec_img = grayreconstruct.reconstruction( + shifted_img, image, method='erosion', footprint=footprint + ) + residue_img = rec_img - image + return (residue_img >= h).astype(np.uint8) + + +def local_maxima( + image, footprint=None, connectivity=None, indices=False, allow_borders=True +): + """Find local maxima of n-dimensional array. + + The local maxima are defined as connected sets of pixels with equal gray + level (plateaus) strictly greater than the gray levels of all pixels in the + neighborhood. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + indices : bool, optional + If True, the output will be a tuple of one-dimensional arrays + representing the indices of local maxima in each dimension. If False, + the output will be a boolean array with the same shape as `image`. + allow_borders : bool, optional + If true, plateaus that touch the image border are valid maxima. + + Returns + ------- + maxima : ndarray or tuple[ndarray] + If `indices` is false, a boolean array with the same shape as `image` + is returned with ``True`` indicating the position of local maxima + (``False`` otherwise). If `indices` is true, a tuple of one-dimensional + arrays containing the coordinates (indices) of all found maxima. + + Warns + ----- + UserWarning + If `allow_borders` is false and any dimension of the given `image` is + shorter than 3 samples, maxima can't exist and a warning is shown. + + See Also + -------- + skimage.morphology.local_minima + skimage.morphology.h_maxima + skimage.morphology.h_minima + + Notes + ----- + This function operates on the following ideas: + + 1. Make a first pass over the image's last dimension and flag candidates + for local maxima by comparing pixels in only one direction. + If the pixels aren't connected in the last dimension all pixels are + flagged as candidates instead. + + For each candidate: + + 2. Perform a flood-fill to find all connected pixels that have the same + gray value and are part of the plateau. + 3. Consider the connected neighborhood of a plateau: if no bordering sample + has a higher gray level, mark the plateau as a definite local maximum. + + Examples + -------- + >>> from skimage.morphology import local_maxima + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Find local maxima by comparing to all neighboring pixels (maximal + connectivity): + + >>> local_maxima(image) + array([[False, False, False, False, False, False, False], + [False, True, True, False, False, False, False], + [False, True, True, False, False, False, False], + [ True, False, False, False, False, False, True]]) + >>> local_maxima(image, indices=True) + (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) + + Find local maxima without comparing to diagonal pixels (connectivity 1): + + >>> local_maxima(image, connectivity=1) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [ True, False, False, False, False, False, True]]) + + and exclude maxima that border the image edge: + + >>> local_maxima(image, connectivity=1, allow_borders=False) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [False, False, False, False, False, False, False]]) + """ + image = np.asarray(image, order="C") + if image.size == 0: + # Return early for empty input + if indices: + # Make sure that output is a tuple of 1 empty array per dimension + return np.nonzero(image) + else: + return np.zeros(image.shape, dtype=bool) + + if allow_borders: + # Ensure that local maxima are always at least one smaller sample away + # from the image border + image = np.pad(image, 1, mode='constant', constant_values=image.min()) + + # Array of flags used to store the state of each pixel during evaluation. + # See _extrema_cy.pyx for their meaning + flags = np.zeros(image.shape, dtype=np.uint8) + _util._set_border_values(flags, value=3) + + if any(s < 3 for s in image.shape): + # Warn and skip if any dimension is smaller than 3 + # -> no maxima can exist & footprint can't be applied + warn( + "maxima can't exist for an image with any dimension smaller 3 " + "if borders aren't allowed", + stacklevel=3, + ) + else: + footprint = _util._resolve_neighborhood(footprint, connectivity, image.ndim) + neighbor_offsets = _util._offsets_to_raveled_neighbors( + image.shape, footprint, center=((1,) * image.ndim) + ) + + try: + _local_maxima(image.ravel(), flags.ravel(), neighbor_offsets) + except TypeError: + if image.dtype == np.float16: + # Provide the user with clearer error message + raise TypeError( + "dtype of `image` is float16 which is not " + "supported, try upcasting to float32" + ) + else: + raise # Otherwise raise original message + + if allow_borders: + # Revert padding performed at the beginning of the function + flags = crop(flags, 1) + else: + # No padding was performed but set edge values back to 0 + _util._set_border_values(flags, value=0) + + if indices: + return np.nonzero(flags) + else: + return flags.view(bool) + + +def local_minima( + image, footprint=None, connectivity=None, indices=False, allow_borders=True +): + """Find local minima of n-dimensional array. + + The local minima are defined as connected sets of pixels with equal gray + level (plateaus) strictly smaller than the gray levels of all pixels in the + neighborhood. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + indices : bool, optional + If True, the output will be a tuple of one-dimensional arrays + representing the indices of local minima in each dimension. If False, + the output will be a boolean array with the same shape as `image`. + allow_borders : bool, optional + If true, plateaus that touch the image border are valid minima. + + Returns + ------- + minima : ndarray or tuple[ndarray] + If `indices` is false, a boolean array with the same shape as `image` + is returned with ``True`` indicating the position of local minima + (``False`` otherwise). If `indices` is true, a tuple of one-dimensional + arrays containing the coordinates (indices) of all found minima. + + See Also + -------- + skimage.morphology.local_maxima + skimage.morphology.h_maxima + skimage.morphology.h_minima + + Notes + ----- + This function operates on the following ideas: + + 1. Make a first pass over the image's last dimension and flag candidates + for local minima by comparing pixels in only one direction. + If the pixels aren't connected in the last dimension all pixels are + flagged as candidates instead. + + For each candidate: + + 2. Perform a flood-fill to find all connected pixels that have the same + gray value and are part of the plateau. + 3. Consider the connected neighborhood of a plateau: if no bordering sample + has a smaller gray level, mark the plateau as a definite local minimum. + + Examples + -------- + >>> from skimage.morphology import local_minima + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = -1 + >>> image[3, 0] = -1 + >>> image[1:3, 4:6] = -2 + >>> image[3, 6] = -3 + >>> image + array([[ 0, 0, 0, 0, 0, 0, 0], + [ 0, -1, -1, 0, -2, -2, 0], + [ 0, -1, -1, 0, -2, -2, 0], + [-1, 0, 0, 0, 0, 0, -3]]) + + Find local minima by comparing to all neighboring pixels (maximal + connectivity): + + >>> local_minima(image) + array([[False, False, False, False, False, False, False], + [False, True, True, False, False, False, False], + [False, True, True, False, False, False, False], + [ True, False, False, False, False, False, True]]) + >>> local_minima(image, indices=True) + (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) + + Find local minima without comparing to diagonal pixels (connectivity 1): + + >>> local_minima(image, connectivity=1) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [ True, False, False, False, False, False, True]]) + + and exclude minima that border the image edge: + + >>> local_minima(image, connectivity=1, allow_borders=False) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [False, False, False, False, False, False, False]]) + """ + return local_maxima( + image=invert(image, signed_float=True), + footprint=footprint, + connectivity=connectivity, + indices=indices, + allow_borders=allow_borders, + ) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/grayreconstruct.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/grayreconstruct.py new file mode 100644 index 0000000000000000000000000000000000000000..e924fab6c8a347b5d5e061b5bb5b056f11c2d1a2 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/grayreconstruct.py @@ -0,0 +1,217 @@ +import numpy as np + +from .._shared.utils import _supported_float_type +from ..filters._rank_order import rank_order +from ._grayreconstruct import reconstruction_loop + + +def reconstruction(seed, mask, method='dilation', footprint=None, offset=None): + """Perform a morphological reconstruction of an image. + + Morphological reconstruction by dilation is similar to basic morphological + dilation: high-intensity values will replace nearby low-intensity values. + The basic dilation operator, however, uses a footprint to + determine how far a value in the input image can spread. In contrast, + reconstruction uses two images: a "seed" image, which specifies the values + that spread, and a "mask" image, which gives the maximum allowed value at + each pixel. The mask image, like the footprint, limits the spread + of high-intensity values. Reconstruction by erosion is simply the inverse: + low-intensity values spread from the seed image and are limited by the mask + image, which represents the minimum allowed value. + + Alternatively, you can think of reconstruction as a way to isolate the + connected regions of an image. For dilation, reconstruction connects + regions marked by local maxima in the seed image: neighboring pixels + less-than-or-equal-to those seeds are connected to the seeded region. + Local maxima with values larger than the seed image will get truncated to + the seed value. + + Parameters + ---------- + seed : ndarray + The seed image (a.k.a. marker image), which specifies the values that + are dilated or eroded. + mask : ndarray + The maximum (dilation) / minimum (erosion) allowed value at each pixel. + method : {'dilation'|'erosion'}, optional + Perform reconstruction by dilation or erosion. In dilation (or + erosion), the seed image is dilated (or eroded) until limited by the + mask image. For dilation, each seed value must be less than or equal + to the corresponding mask value; for erosion, the reverse is true. + Default is 'dilation'. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the n-D square of radius equal to 1 (i.e. a 3x3 square + for 2D images, a 3x3x3 cube for 3D images, etc.) + offset : ndarray, optional + The coordinates of the center of the footprint. + Default is located on the geometrical center of the footprint, in that + case footprint dimensions must be odd. + + Returns + ------- + reconstructed : ndarray + The result of morphological reconstruction. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import reconstruction + + First, we create a sinusoidal mask image with peaks at middle and ends. + + >>> x = np.linspace(0, 4 * np.pi) + >>> y_mask = np.cos(x) + + Then, we create a seed image initialized to the minimum mask value (for + reconstruction by dilation, min-intensity values don't spread) and add + "seeds" to the left and right peak, but at a fraction of peak value (1). + + >>> y_seed = y_mask.min() * np.ones_like(x) + >>> y_seed[0] = 0.5 + >>> y_seed[-1] = 0 + >>> y_rec = reconstruction(y_seed, y_mask) + + The reconstructed image (or curve, in this case) is exactly the same as the + mask image, except that the peaks are truncated to 0.5 and 0. The middle + peak disappears completely: Since there were no seed values in this peak + region, its reconstructed value is truncated to the surrounding value (-1). + + As a more practical example, we try to extract the bright features of an + image by subtracting a background image created by reconstruction. + + >>> y, x = np.mgrid[:20:0.5, :20:0.5] + >>> bumps = np.sin(x) + np.sin(y) + + To create the background image, set the mask image to the original image, + and the seed image to the original image with an intensity offset, `h`. + + >>> h = 0.3 + >>> seed = bumps - h + >>> background = reconstruction(seed, bumps) + + The resulting reconstructed image looks exactly like the original image, + but with the peaks of the bumps cut off. Subtracting this reconstructed + image from the original image leaves just the peaks of the bumps + + >>> hdome = bumps - background + + This operation is known as the h-dome of the image and leaves features + of height `h` in the subtracted image. + + Notes + ----- + The algorithm is taken from [1]_. Applications for grayscale reconstruction + are discussed in [2]_ and [3]_. + + References + ---------- + .. [1] Robinson, "Efficient morphological reconstruction: a downhill + filter", Pattern Recognition Letters 25 (2004) 1759-1767. + .. [2] Vincent, L., "Morphological Grayscale Reconstruction in Image + Analysis: Applications and Efficient Algorithms", IEEE Transactions + on Image Processing (1993) + .. [3] Soille, P., "Morphological Image Analysis: Principles and + Applications", Chapter 6, 2nd edition (2003), ISBN 3540429883. + """ + assert tuple(seed.shape) == tuple(mask.shape) + if method == 'dilation' and np.any(seed > mask): + raise ValueError( + "Intensity of seed image must be less than that " + "of the mask image for reconstruction by dilation." + ) + elif method == 'erosion' and np.any(seed < mask): + raise ValueError( + "Intensity of seed image must be greater than that " + "of the mask image for reconstruction by erosion." + ) + + if footprint is None: + footprint = np.ones([3] * seed.ndim, dtype=bool) + else: + footprint = footprint.astype(bool, copy=True) + + if offset is None: + if not all([d % 2 == 1 for d in footprint.shape]): + raise ValueError("Footprint dimensions must all be odd") + offset = np.array([d // 2 for d in footprint.shape]) + else: + if offset.ndim != footprint.ndim: + raise ValueError("Offset and footprint ndims must be equal.") + if not all([(0 <= o < d) for o, d in zip(offset, footprint.shape)]): + raise ValueError("Offset must be included inside footprint") + + # Cross out the center of the footprint + footprint[tuple(slice(d, d + 1) for d in offset)] = False + + # Make padding for edges of reconstructed image so we can ignore boundaries + dims = np.zeros(seed.ndim + 1, dtype=int) + dims[1:] = np.array(seed.shape) + (np.array(footprint.shape) - 1) + dims[0] = 2 + inside_slices = tuple(slice(o, o + s) for o, s in zip(offset, seed.shape)) + # Set padded region to minimum image intensity and mask along first axis so + # we can interleave image and mask pixels when sorting. + if method == 'dilation': + pad_value = np.min(seed) + elif method == 'erosion': + pad_value = np.max(seed) + else: + raise ValueError( + "Reconstruction method can be one of 'erosion' " + f"or 'dilation'. Got '{method}'." + ) + float_dtype = _supported_float_type(mask.dtype) + images = np.full(dims, pad_value, dtype=float_dtype) + images[(0, *inside_slices)] = seed + images[(1, *inside_slices)] = mask + + # determine whether image is large enough to require 64-bit integers + isize = images.size + # use -isize so we get a signed dtype rather than an unsigned one + signed_int_dtype = np.result_type(np.min_scalar_type(-isize), np.int32) + # the corresponding unsigned type has same char, but uppercase + unsigned_int_dtype = np.dtype(signed_int_dtype.char.upper()) + + # Create a list of strides across the array to get the neighbors within + # a flattened array + value_stride = np.array(images.strides[1:]) // images.dtype.itemsize + image_stride = images.strides[0] // images.dtype.itemsize + footprint_mgrid = np.mgrid[ + [slice(-o, d - o) for d, o in zip(footprint.shape, offset)] + ] + footprint_offsets = footprint_mgrid[:, footprint].transpose() + nb_strides = np.array( + [ + np.sum(value_stride * footprint_offset) + for footprint_offset in footprint_offsets + ], + signed_int_dtype, + ) + images = images.reshape(-1) + + # Erosion goes smallest to largest; dilation goes largest to smallest. + index_sorted = np.argsort(images).astype(signed_int_dtype, copy=False) + if method == 'dilation': + index_sorted = index_sorted[::-1] + + # Make a linked list of pixels sorted by value. -1 is the list terminator. + prev = np.full(isize, -1, signed_int_dtype) + next = np.full(isize, -1, signed_int_dtype) + prev[index_sorted[1:]] = index_sorted[:-1] + next[index_sorted[:-1]] = index_sorted[1:] + + # Cython inner-loop compares the rank of pixel values. + if method == 'dilation': + value_rank, value_map = rank_order(images) + elif method == 'erosion': + value_rank, value_map = rank_order(-images) + value_map = -value_map + + start = index_sorted[0] + value_rank = value_rank.astype(unsigned_int_dtype, copy=False) + reconstruction_loop(value_rank, prev, next, nb_strides, start, image_stride) + + # Reshape reconstructed image to original image shape and remove padding. + rec_img = value_map[value_rank[:image_stride]] + rec_img.shape = np.array(seed.shape) + (np.array(footprint.shape) - 1) + return rec_img[inside_slices] diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/isotropic.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/isotropic.py new file mode 100644 index 0000000000000000000000000000000000000000..6234a5f21e600632e85e21d85422c7805546ce95 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/isotropic.py @@ -0,0 +1,194 @@ +""" +Binary morphological operations +""" + +import numpy as np +from scipy import ndimage as ndi + + +def isotropic_erosion(image, radius, out=None, spacing=None): + """Return binary morphological erosion of an image. + + This function returns the same result as :func:`skimage.morphology.binary_erosion` + but performs faster for large circular structuring elements. + This works by applying a threshold to the exact Euclidean distance map + of the image [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius by which regions should be eroded. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + eroded : ndarray of bool + The result of the morphological erosion taking values in + ``[False, True]``. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + dist = ndi.distance_transform_edt(image, sampling=spacing) + return np.greater(dist, radius, out=out) + + +def isotropic_dilation(image, radius, out=None, spacing=None): + """Return binary morphological dilation of an image. + + This function returns the same result as :func:`skimage.morphology.binary_dilation` + but performs faster for large circular structuring elements. + This works by applying a threshold to the exact Euclidean distance map + of the inverted image [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius by which regions should be dilated. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + dilated : ndarray of bool + The result of the morphological dilation with values in + ``[False, True]``. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + dist = ndi.distance_transform_edt(np.logical_not(image), sampling=spacing) + return np.less_equal(dist, radius, out=out) + + +def isotropic_opening(image, radius, out=None, spacing=None): + """Return binary morphological opening of an image. + + This function returns the same result as :func:`skimage.morphology.binary_opening` + but performs faster for large circular structuring elements. + This works by thresholding the exact Euclidean distance map [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius with which the regions should be opened. + out : ndarray of bool, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + opened : ndarray of bool + The result of the morphological opening. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + eroded = isotropic_erosion(image, radius, out=out, spacing=spacing) + return isotropic_dilation(eroded, radius, out=out, spacing=spacing) + + +def isotropic_closing(image, radius, out=None, spacing=None): + """Return binary morphological closing of an image. + + This function returns the same result as binary :func:`skimage.morphology.binary_closing` + but performs faster for large circular structuring elements. + This works by thresholding the exact Euclidean distance map [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius with which the regions should be closed. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + is passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + closed : ndarray of bool + The result of the morphological closing. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + dilated = isotropic_dilation(image, radius, out=out, spacing=spacing) + return isotropic_erosion(dilated, radius, out=out, spacing=spacing) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/misc.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..30d302c00a1eb890ce63eda7b1c6a53127f8947a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/misc.py @@ -0,0 +1,454 @@ +"""Miscellaneous morphology functions.""" + +import numpy as np +import functools +from scipy import ndimage as ndi +from scipy.spatial import cKDTree + +from .._shared.utils import warn +from ._misc_cy import _remove_objects_by_distance + + +# Our function names don't exactly correspond to ndimages. +# This dictionary translates from our names to scipy's. +funcs = ('erosion', 'dilation', 'opening', 'closing') +skimage2ndimage = {x: 'grey_' + x for x in funcs} + +# These function names are the same in ndimage. +funcs = ( + 'binary_erosion', + 'binary_dilation', + 'binary_opening', + 'binary_closing', + 'black_tophat', + 'white_tophat', +) +skimage2ndimage.update({x: x for x in funcs}) + + +def default_footprint(func): + """Decorator to add a default footprint to morphology functions. + + Parameters + ---------- + func : function + A morphology function such as erosion, dilation, opening, closing, + white_tophat, or black_tophat. + + Returns + ------- + func_out : function + The function, using a default footprint of same dimension + as the input image with connectivity 1. + + """ + + @functools.wraps(func) + def func_out(image, footprint=None, *args, **kwargs): + if footprint is None: + footprint = ndi.generate_binary_structure(image.ndim, 1) + return func(image, footprint=footprint, *args, **kwargs) + + return func_out + + +def _check_dtype_supported(ar): + # Should use `issubdtype` for bool below, but there's a bug in numpy 1.7 + if not (ar.dtype == bool or np.issubdtype(ar.dtype, np.integer)): + raise TypeError( + "Only bool or integer image types are supported. " f"Got {ar.dtype}." + ) + + +def remove_small_objects(ar, min_size=64, connectivity=1, *, out=None): + """Remove objects smaller than the specified size. + + Expects ar to be an array with labeled objects, and removes objects + smaller than min_size. If `ar` is bool, the image is first labeled. + This leads to potentially different behavior for bool and 0-and-1 + arrays. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the objects of interest. If the array type is + int, the ints must be non-negative. + min_size : int, optional (default: 64) + The smallest allowable object size. + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. Used during + labelling if `ar` is bool. + out : ndarray + Array of the same shape as `ar`, into which the output is + placed. By default, a new array is created. + + Raises + ------ + TypeError + If the input array is of an invalid type, such as float or string. + ValueError + If the input array contains negative values. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small connected components removed. + + See Also + -------- + skimage.morphology.remove_objects_by_distance + + Examples + -------- + >>> from skimage import morphology + >>> a = np.array([[0, 0, 0, 1, 0], + ... [1, 1, 1, 0, 0], + ... [1, 1, 1, 0, 1]], bool) + >>> b = morphology.remove_small_objects(a, 6) + >>> b + array([[False, False, False, False, False], + [ True, True, True, False, False], + [ True, True, True, False, False]]) + >>> c = morphology.remove_small_objects(a, 7, connectivity=2) + >>> c + array([[False, False, False, True, False], + [ True, True, True, False, False], + [ True, True, True, False, False]]) + >>> d = morphology.remove_small_objects(a, 6, out=a) + >>> d is a + True + + """ + # Raising type error if not int or bool + _check_dtype_supported(ar) + + if out is None: + out = ar.copy() + else: + out[:] = ar + + if min_size == 0: # shortcut for efficiency + return out + + if out.dtype == bool: + footprint = ndi.generate_binary_structure(ar.ndim, connectivity) + ccs = np.zeros_like(ar, dtype=np.int32) + ndi.label(ar, footprint, output=ccs) + else: + ccs = out + + try: + component_sizes = np.bincount(ccs.ravel()) + except ValueError: + raise ValueError( + "Negative value labels are not supported. Try " + "relabeling the input with `scipy.ndimage.label` or " + "`skimage.morphology.label`." + ) + + if len(component_sizes) == 2 and out.dtype != bool: + warn( + "Only one label was provided to `remove_small_objects`. " + "Did you mean to use a boolean array?" + ) + + too_small = component_sizes < min_size + too_small_mask = too_small[ccs] + out[too_small_mask] = 0 + + return out + + +def remove_small_holes(ar, area_threshold=64, connectivity=1, *, out=None): + """Remove contiguous holes smaller than the specified size. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the connected components of interest. + area_threshold : int, optional (default: 64) + The maximum area, in pixels, of a contiguous hole that will be filled. + Replaces `min_size`. + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. + out : ndarray + Array of the same shape as `ar` and bool dtype, into which the + output is placed. By default, a new array is created. + + Raises + ------ + TypeError + If the input array is of an invalid type, such as float or string. + ValueError + If the input array contains negative values. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small holes within connected components removed. + + Examples + -------- + >>> from skimage import morphology + >>> a = np.array([[1, 1, 1, 1, 1, 0], + ... [1, 1, 1, 0, 1, 0], + ... [1, 0, 0, 1, 1, 0], + ... [1, 1, 1, 1, 1, 0]], bool) + >>> b = morphology.remove_small_holes(a, 2) + >>> b + array([[ True, True, True, True, True, False], + [ True, True, True, True, True, False], + [ True, False, False, True, True, False], + [ True, True, True, True, True, False]]) + >>> c = morphology.remove_small_holes(a, 2, connectivity=2) + >>> c + array([[ True, True, True, True, True, False], + [ True, True, True, False, True, False], + [ True, False, False, True, True, False], + [ True, True, True, True, True, False]]) + >>> d = morphology.remove_small_holes(a, 2, out=a) + >>> d is a + True + + Notes + ----- + If the array type is int, it is assumed that it contains already-labeled + objects. The labels are not kept in the output image (this function always + outputs a bool image). It is suggested that labeling is completed after + using this function. + + """ + _check_dtype_supported(ar) + + # Creates warning if image is an integer image + if ar.dtype != bool: + warn( + "Any labeled images will be returned as a boolean array. " + "Did you mean to use a boolean array?", + UserWarning, + ) + + if out is not None: + if out.dtype != bool: + raise TypeError("out dtype must be bool") + else: + out = ar.astype(bool, copy=True) + + # Creating the inverse of ar + np.logical_not(ar, out=out) + + # removing small objects from the inverse of ar + out = remove_small_objects(out, area_threshold, connectivity, out=out) + + np.logical_not(out, out=out) + + return out + + +def remove_objects_by_distance( + label_image, + min_distance, + *, + priority=None, + p_norm=2, + spacing=None, + out=None, +): + """Remove objects, in specified order, until remaining are a minimum distance apart. + + Remove labeled objects from an image until the remaining ones are spaced + more than a given distance from one another. By default, smaller objects + are removed first. + + Parameters + ---------- + label_image : ndarray of integers + An n-dimensional array containing object labels, e.g. as returned by + :func:`~.label`. A value of zero is considered background, all other + object IDs must be positive integers. + min_distance : int or float + Remove objects whose distance to other objects is not greater than this + positive value. Objects with a lower `priority` are removed first. + priority : ndarray, optional + Defines the priority with which objects are removed. Expects a + 1-dimensional array of length + :func:`np.amax(label_image) + 1 ` that contains the priority + for each object's label at the respective index. Objects with a lower value + are removed first until all remaining objects fulfill the distance + requirement. If not given, priority is given to objects with a higher + number of samples and their label value second. + p_norm : int or float, optional + The Minkowski distance of order p, used to calculate the distance + between objects. The default ``2`` corresponds to the Euclidean + distance, ``1`` to the "Manhattan" distance, and ``np.inf`` to the + Chebyshev distance. + spacing : sequence of float, optional + The pixel spacing along each axis of `label_image`. If not specified, + a grid spacing of unity (1) is implied. + out : ndarray, optional + Array of the same shape and dtype as `image`, into which the output is + placed. By default, a new array is created. + + Returns + ------- + out : ndarray + Array of the same shape as `label_image`, for which objects that violate + the `min_distance` condition were removed. + + See Also + -------- + skimage.morphology.remove_small_objects + Remove objects smaller than the specified size. + + Notes + ----- + The basic steps of this algorithm work as follows: + + 1. Find the indices for of all given objects and separate them depending on + if they point to an object's border or not. + 2. Sort indices by their label value, ensuring that indices which point to + the same object are next to each other. This optimization allows finding + all parts of an object, simply by stepping to the neighboring indices. + 3. Sort boundary indices by `priority`. Use a stable-sort to preserve the + ordering from the previous sorting step. If `priority` is not given, + use :func:`numpy.bincount` as a fallback. + 4. Construct a :class:`scipy.spatial.cKDTree` from the boundary indices. + 5. Iterate across boundary indices in priority-sorted order, and query the + kd-tree for objects that are too close. Remove ones that are and don't + take them into account when evaluating other objects later on. + + The performance of this algorithm depends on the number of samples in + `label_image` that belong to an object's border. + + Examples + -------- + >>> import skimage as ski + >>> ski.morphology.remove_objects_by_distance(np.array([2, 0, 1, 1]), 2) + array([0, 0, 1, 1]) + >>> ski.morphology.remove_objects_by_distance( + ... np.array([2, 0, 1, 1]), 2, priority=np.array([0, 1, 9]) + ... ) + array([2, 0, 0, 0]) + >>> label_image = np.array( + ... [[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + ... [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + ... [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0], + ... [2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]] + ... ) + >>> ski.morphology.remove_objects_by_distance( + ... label_image, min_distance=3 + ... ) + array([[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]]) + """ + if min_distance < 0: + raise ValueError(f"min_distance must be >= 0, was {min_distance}") + if not np.issubdtype(label_image.dtype, np.integer): + raise ValueError( + f"`label_image` must be of integer dtype, got {label_image.dtype}" + ) + if out is None: + out = label_image.copy(order="C") + elif out is not label_image: + out[:] = label_image + # May create a copy if order is not C, account for that later + out_raveled = out.ravel(order="C") + + if spacing is not None: + spacing = np.array(spacing) + if spacing.shape != (out.ndim,) or spacing.min() <= 0: + raise ValueError( + "`spacing` must contain exactly one positive factor " + "for each dimension of `label_image`" + ) + + indices = np.flatnonzero(out_raveled) + # Optimization: Split indices into those on the object boundaries and inner + # ones. The KDTree is built only from the boundary indices, which reduces + # the size of the critical loop significantly! Remaining indices are only + # used to remove the inner parts of objects as well. + if (spacing is None or np.all(spacing[0] == spacing)) and p_norm <= 2: + # For unity spacing we can make the borders more sparse by using a + # lower connectivity + footprint = ndi.generate_binary_structure(out.ndim, 1) + else: + footprint = ndi.generate_binary_structure(out.ndim, out.ndim) + border = ( + ndi.maximum_filter(out, footprint=footprint) + != ndi.minimum_filter(out, footprint=footprint) + ).ravel()[indices] + border_indices = indices[border] + inner_indices = indices[~border] + + if border_indices.size == 0: + # Image without any or only one object, return early + return out + + # Sort by label ID first, so that IDs of the same object are contiguous + # in the sorted index. This allows fast discovery of the whole object by + # simple iteration up or down the index! + border_indices = border_indices[np.argsort(out_raveled[border_indices])] + inner_indices = inner_indices[np.argsort(out_raveled[inner_indices])] + + if priority is None: + if not np.can_cast(out.dtype, np.intp, casting="safe"): + # bincount expects intp (32-bit) on WASM or i386, so down-cast to that + priority = np.bincount(out_raveled.astype(np.intp, copy=False)) + else: + priority = np.bincount(out_raveled) + # `priority` can only be indexed by positive object IDs, + # `border_indices` contains all unique sorted IDs so check the lowest / first + smallest_id = out_raveled[border_indices[0]] + if smallest_id < 0: + raise ValueError(f"found object with negative ID {smallest_id!r}") + + try: + # Sort by priority second using a stable sort to preserve the contiguous + # sorting of objects. Because each pixel in an object has the same + # priority we don't need to worry about separating objects. + border_indices = border_indices[ + np.argsort(priority[out_raveled[border_indices]], kind="stable")[::-1] + ] + except IndexError as error: + # Use np.amax only for the exception path to provide a nicer error message + expected_shape = (np.amax(out_raveled) + 1,) + if priority.shape != expected_shape: + raise ValueError( + "shape of `priority` must be (np.amax(label_image) + 1,), " + f"expected {expected_shape}, got {priority.shape} instead" + ) from error + else: + raise + + # Construct kd-tree from unraveled border indices (optionally scale by `spacing`) + unraveled_indices = np.unravel_index(border_indices, out.shape) + if spacing is not None: + unraveled_indices = tuple( + unraveled_indices[dim] * spacing[dim] for dim in range(out.ndim) + ) + kdtree = cKDTree(data=np.asarray(unraveled_indices, dtype=np.float64).T) + + _remove_objects_by_distance( + out=out_raveled, + border_indices=border_indices, + inner_indices=inner_indices, + kdtree=kdtree, + min_distance=min_distance, + p_norm=p_norm, + shape=label_image.shape, + ) + + if out_raveled.base is not out: + # `out_raveled` is a copy, re-assign + out[:] = out_raveled.reshape(out.shape) + return out diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__init__.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_binary.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_binary.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15a8646991a209d3b42e8714d1e273f418ec6292 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_binary.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_convex_hull.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_convex_hull.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f01234aeb9c97922a9dc8e6b6090a53a37bedc9b Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_convex_hull.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_reconstruction.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_reconstruction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6288f63579bddd2a785ac0fc3e75277851609aba Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/__pycache__/test_reconstruction.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_binary.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_binary.py new file mode 100644 index 0000000000000000000000000000000000000000..a35e8447f5caf6fa872c5df03b8c8d763134c704 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_binary.py @@ -0,0 +1,349 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal, assert_equal +from scipy import ndimage as ndi + +from skimage import data, color, morphology +from skimage.util import img_as_bool +from skimage.morphology import binary, footprints, gray, footprint_rectangle + + +img = color.rgb2gray(data.astronaut()) +bw_img = img > 100 / 255.0 + + +def test_non_square_image(): + footprint = footprint_rectangle((3, 3)) + binary_res = binary.binary_erosion(bw_img[:100, :200], footprint) + gray_res = img_as_bool(gray.erosion(bw_img[:100, :200], footprint)) + assert_array_equal(binary_res, gray_res) + + +def test_binary_erosion(): + footprint = footprint_rectangle((3, 3)) + binary_res = binary.binary_erosion(bw_img, footprint) + gray_res = img_as_bool(gray.erosion(bw_img, footprint)) + assert_array_equal(binary_res, gray_res) + + +def test_binary_dilation(): + footprint = footprint_rectangle((3, 3)) + binary_res = binary.binary_dilation(bw_img, footprint) + gray_res = img_as_bool(gray.dilation(bw_img, footprint)) + assert_array_equal(binary_res, gray_res) + + +def test_binary_closing(): + footprint = footprint_rectangle((3, 3)) + binary_res = binary.binary_closing(bw_img, footprint) + gray_res = img_as_bool(gray.closing(bw_img, footprint)) + assert_array_equal(binary_res, gray_res) + + +def test_binary_closing_extensive(): + footprint = np.array([[0, 0, 1], [0, 1, 1], [1, 1, 1]]) + + result_default = binary.binary_closing(bw_img, footprint=footprint) + assert np.all(result_default >= bw_img) + + # mode="min" is expected to be not extensive + result_min = binary.binary_closing(img, footprint=footprint, mode="min") + assert not np.all(result_min >= bw_img) + + +def test_binary_opening(): + footprint = footprint_rectangle((3, 3)) + binary_res = binary.binary_opening(bw_img, footprint) + gray_res = img_as_bool(gray.opening(bw_img, footprint)) + assert_array_equal(binary_res, gray_res) + + +def test_binary_opening_anti_extensive(): + footprint = np.array([[0, 0, 1], [0, 1, 1], [1, 1, 1]]) + + result_default = binary.binary_opening(bw_img, footprint=footprint) + assert np.all(result_default <= bw_img) + + # mode="max" is expected to be not extensive + result_max = binary.binary_opening(bw_img, footprint=footprint, mode="max") + assert not np.all(result_max <= bw_img) + + +def _get_decomp_test_data(function, ndim=2): + if function == 'binary_erosion': + img = np.ones((17,) * ndim, dtype=np.uint8) + img[8, 8] = 0 + elif function == 'binary_dilation': + img = np.zeros((17,) * ndim, dtype=np.uint8) + img[8, 8] = 1 + else: + img = data.binary_blobs(32, n_dim=ndim, rng=1) + return img + + +@pytest.mark.parametrize( + "function", + ["binary_erosion", "binary_dilation", "binary_closing", "binary_opening"], +) +@pytest.mark.parametrize("nrows", (3, 7, 11)) +@pytest.mark.parametrize("ncols", (3, 7, 11)) +@pytest.mark.parametrize("decomposition", ['separable', 'sequence']) +def test_rectangle_decomposition(function, nrows, ncols, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprint_rectangle((nrows, ncols), decomposition=None) + footprint = footprint_rectangle((nrows, ncols), decomposition=decomposition) + img = _get_decomp_test_data(function) + func = getattr(binary, function) + expected = func(img, footprint=footprint_ndarray) + out = func(img, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["binary_erosion", "binary_dilation", "binary_closing", "binary_opening"], +) +@pytest.mark.parametrize("m", (0, 1, 2, 3, 4, 5)) +@pytest.mark.parametrize("n", (0, 1, 2, 3, 4, 5)) +@pytest.mark.parametrize("decomposition", ['sequence']) +@pytest.mark.filterwarnings( + "ignore:.*falling back to decomposition='separable':UserWarning:skimage" +) +def test_octagon_decomposition(function, m, n, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + if m == 0 and n == 0: + with pytest.raises(ValueError): + footprints.octagon(m, n, decomposition=decomposition) + else: + footprint_ndarray = footprints.octagon(m, n, decomposition=None) + footprint = footprints.octagon(m, n, decomposition=decomposition) + img = _get_decomp_test_data(function) + func = getattr(binary, function) + expected = func(img, footprint=footprint_ndarray) + out = func(img, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["binary_erosion", "binary_dilation", "binary_closing", "binary_opening"], +) +@pytest.mark.parametrize("radius", (1, 2, 5)) +@pytest.mark.parametrize("decomposition", ['sequence']) +def test_diamond_decomposition(function, radius, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprints.diamond(radius, decomposition=None) + footprint = footprints.diamond(radius, decomposition=decomposition) + img = _get_decomp_test_data(function) + func = getattr(binary, function) + expected = func(img, footprint=footprint_ndarray) + out = func(img, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["binary_erosion", "binary_dilation", "binary_closing", "binary_opening"], +) +@pytest.mark.parametrize("shape", [(3, 3, 3), (3, 4, 5)]) +@pytest.mark.parametrize("decomposition", ['separable', 'sequence']) +@pytest.mark.filterwarnings( + "ignore:.*falling back to decomposition='separable':UserWarning:skimage" +) +def test_cube_decomposition(function, shape, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprint_rectangle(shape, decomposition=None) + footprint = footprint_rectangle(shape, decomposition=decomposition) + img = _get_decomp_test_data(function, ndim=3) + func = getattr(binary, function) + expected = func(img, footprint=footprint_ndarray) + out = func(img, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["binary_erosion", "binary_dilation", "binary_closing", "binary_opening"], +) +@pytest.mark.parametrize("radius", (1, 2, 3)) +@pytest.mark.parametrize("decomposition", ['sequence']) +def test_octahedron_decomposition(function, radius, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprints.octahedron(radius, decomposition=None) + footprint = footprints.octahedron(radius, decomposition=decomposition) + img = _get_decomp_test_data(function, ndim=3) + func = getattr(binary, function) + expected = func(img, footprint=footprint_ndarray) + out = func(img, footprint=footprint) + assert_array_equal(expected, out) + + +def test_footprint_overflow(): + footprint = np.ones((17, 17), dtype=np.uint8) + img = np.zeros((20, 20), dtype=bool) + img[2:19, 2:19] = True + binary_res = binary.binary_erosion(img, footprint) + gray_res = img_as_bool(gray.erosion(img, footprint)) + assert_array_equal(binary_res, gray_res) + + +def test_out_argument(): + for func in (binary.binary_erosion, binary.binary_dilation): + footprint = np.ones((3, 3), dtype=np.uint8) + img = np.ones((10, 10)) + out = np.zeros_like(img) + out_saved = out.copy() + func(img, footprint, out=out) + assert np.any(out != out_saved) + assert_array_equal(out, func(img, footprint)) + + +binary_functions = [ + binary.binary_erosion, + binary.binary_dilation, + binary.binary_opening, + binary.binary_closing, +] + + +@pytest.mark.parametrize("func", binary_functions) +@pytest.mark.parametrize("mode", ['max', 'min', 'ignore']) +def test_supported_mode(func, mode): + img = np.ones((10, 10), dtype=bool) + func(img, mode=mode) + + +@pytest.mark.parametrize("func", binary_functions) +@pytest.mark.parametrize("mode", ["reflect", 3, None]) +def test_unsupported_mode(func, mode): + img = np.ones((10, 10)) + with pytest.raises(ValueError, match="unsupported mode"): + func(img, mode=mode) + + +@pytest.mark.parametrize("function", binary_functions) +def test_default_footprint(function): + footprint = morphology.diamond(radius=1) + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + im_expected = function(image, footprint) + im_test = function(image) + assert_array_equal(im_expected, im_test) + + +def test_3d_fallback_default_footprint(): + # 3x3x3 cube inside a 7x7x7 image: + image = np.zeros((7, 7, 7), bool) + image[2:-2, 2:-2, 2:-2] = 1 + + opened = binary.binary_opening(image) + + # expect a "hyper-cross" centered in the 5x5x5: + image_expected = np.zeros((7, 7, 7), dtype=bool) + image_expected[2:5, 2:5, 2:5] = ndi.generate_binary_structure(3, 1) + assert_array_equal(opened, image_expected) + + +binary_3d_fallback_functions = [binary.binary_opening, binary.binary_closing] + + +@pytest.mark.parametrize("function", binary_3d_fallback_functions) +def test_3d_fallback_cube_footprint(function): + # 3x3x3 cube inside a 7x7x7 image: + image = np.zeros((7, 7, 7), bool) + image[2:-2, 2:-2, 2:-2] = 1 + + cube = np.ones((3, 3, 3), dtype=np.uint8) + + new_image = function(image, cube) + assert_array_equal(new_image, image) + + +def test_2d_ndimage_equivalence(): + image = np.zeros((9, 9), np.uint16) + image[2:-2, 2:-2] = 2**14 + image[3:-3, 3:-3] = 2**15 + image[4, 4] = 2**16 - 1 + + bin_opened = binary.binary_opening(image) + bin_closed = binary.binary_closing(image) + + footprint = ndi.generate_binary_structure(2, 1) + ndimage_opened = ndi.binary_opening(image, structure=footprint) + ndimage_closed = ndi.binary_closing(image, structure=footprint) + + assert_array_equal(bin_opened, ndimage_opened) + assert_array_equal(bin_closed, ndimage_closed) + + +def test_binary_output_2d(): + image = np.zeros((9, 9), np.uint16) + image[2:-2, 2:-2] = 2**14 + image[3:-3, 3:-3] = 2**15 + image[4, 4] = 2**16 - 1 + + bin_opened = binary.binary_opening(image) + bin_closed = binary.binary_closing(image) + + int_opened = np.empty_like(image, dtype=np.uint8) + int_closed = np.empty_like(image, dtype=np.uint8) + binary.binary_opening(image, out=int_opened) + binary.binary_closing(image, out=int_closed) + + assert_equal(bin_opened.dtype, bool) + assert_equal(bin_closed.dtype, bool) + + assert_equal(int_opened.dtype, np.uint8) + assert_equal(int_closed.dtype, np.uint8) + + +def test_binary_output_3d(): + image = np.zeros((9, 9, 9), np.uint16) + image[2:-2, 2:-2, 2:-2] = 2**14 + image[3:-3, 3:-3, 3:-3] = 2**15 + image[4, 4, 4] = 2**16 - 1 + + bin_opened = binary.binary_opening(image) + bin_closed = binary.binary_closing(image) + + int_opened = np.empty_like(image, dtype=np.uint8) + int_closed = np.empty_like(image, dtype=np.uint8) + binary.binary_opening(image, out=int_opened) + binary.binary_closing(image, out=int_closed) + + assert_equal(bin_opened.dtype, bool) + assert_equal(bin_closed.dtype, bool) + + assert_equal(int_opened.dtype, np.uint8) + assert_equal(int_closed.dtype, np.uint8) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_convex_hull.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_convex_hull.py new file mode 100644 index 0000000000000000000000000000000000000000..e4495a0941155c861517d313423a79b8dbabb629 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_convex_hull.py @@ -0,0 +1,349 @@ +import numpy as np +from skimage.morphology import convex_hull_image, convex_hull_object +from skimage.morphology._convex_hull import possible_hull + +from skimage._shared import testing +from skimage._shared.testing import assert_array_equal +from skimage._shared._warnings import expected_warnings + + +def test_basic(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + assert_array_equal(convex_hull_image(image), expected) + + +def test_empty_image(): + image = np.zeros((6, 6), dtype=bool) + with expected_warnings(['entirely zero']): + assert_array_equal(convex_hull_image(image), image) + + +def test_qhull_offset_example(): + nonzeros = ( + ( + [ + 1367, + 1368, + 1368, + 1368, + 1369, + 1369, + 1369, + 1369, + 1369, + 1370, + 1370, + 1370, + 1370, + 1370, + 1370, + 1370, + 1371, + 1371, + 1371, + 1371, + 1371, + 1371, + 1371, + 1371, + 1371, + 1372, + 1372, + 1372, + 1372, + 1372, + 1372, + 1372, + 1372, + 1372, + 1373, + 1373, + 1373, + 1373, + 1373, + 1373, + 1373, + 1373, + 1373, + 1374, + 1374, + 1374, + 1374, + 1374, + 1374, + 1374, + 1375, + 1375, + 1375, + 1375, + 1375, + 1376, + 1376, + 1376, + 1377, + 1372, + ] + ), + ( + [ + 151, + 150, + 151, + 152, + 149, + 150, + 151, + 152, + 153, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 155, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 148, + 149, + 150, + 151, + 152, + 149, + 150, + 151, + 150, + 155, + ] + ), + ) + image = np.zeros((1392, 1040), dtype=bool) + image[nonzeros] = True + expected = image.copy() + assert_array_equal(convex_hull_image(image), expected) + + +def test_pathological_qhull_example(): + image = np.array( + [[0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0]], + dtype=bool, + ) + expected = np.array( + [[0, 0, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0]], + dtype=bool, + ) + assert_array_equal(convex_hull_image(image), expected) + + +def test_pathological_qhull_labels(): + image = np.array( + [[0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0]], + dtype=bool, + ) + + expected = np.array( + [[0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0]], + dtype=bool, + ) + + actual = convex_hull_image(image, include_borders=False) + assert_array_equal(actual, expected) + + +def test_possible_hull(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + expected = np.array( + [ + [1, 4], + [2, 3], + [3, 2], + [4, 1], + [4, 1], + [3, 2], + [2, 3], + [1, 4], + [2, 5], + [3, 6], + [4, 7], + [2, 5], + [3, 6], + [4, 7], + [4, 2], + [4, 3], + [4, 4], + [4, 5], + [4, 6], + ] + ) + + ph = possible_hull(image) + assert_array_equal(ph, expected) + + +def test_object(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0, 1, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 1, 0], + [1, 0, 0, 0, 0, 0, 1, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + expected_conn_1 = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0, 1, 0, 1], + [1, 1, 1, 0, 0, 0, 0, 1, 0], + [1, 1, 0, 0, 0, 0, 1, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + assert_array_equal(convex_hull_object(image, connectivity=1), expected_conn_1) + + expected_conn_2 = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0, 1, 1, 1], + [1, 1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 0, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + assert_array_equal(convex_hull_object(image, connectivity=2), expected_conn_2) + + with testing.raises(ValueError): + convex_hull_object(image, connectivity=3) + + out = convex_hull_object(image, connectivity=1) + assert_array_equal(out, expected_conn_1) + + +def test_non_c_contiguous(): + # 2D Fortran-contiguous + image = np.ones((2, 2), order='F', dtype=bool) + assert_array_equal(convex_hull_image(image), image) + # 3D Fortran-contiguous + image = np.ones((2, 2, 2), order='F', dtype=bool) + assert_array_equal(convex_hull_image(image), image) + # 3D non-contiguous + image = np.transpose(np.ones((2, 2, 2), dtype=bool), [0, 2, 1]) + assert_array_equal(convex_hull_image(image), image) + + +@testing.fixture +def images2d3d(): + from ...measure.tests.test_regionprops import SAMPLE as image + + image3d = np.stack((image, image, image)) + return image, image3d + + +def test_consistent_2d_3d_hulls(images2d3d): + image, image3d = images2d3d + chimage = convex_hull_image(image) + chimage[8, 0] = True # correct for single point exactly on hull edge + chimage3d = convex_hull_image(image3d) + assert_array_equal(chimage3d[1], chimage) + + +def test_few_points(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + image3d = np.stack([image, image, image]) + with testing.assert_warns(UserWarning): + chimage3d = convex_hull_image(image3d) + assert_array_equal(chimage3d, np.zeros(image3d.shape, dtype=bool)) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_extrema.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_extrema.py new file mode 100644 index 0000000000000000000000000000000000000000..1966ecb9b19e15f70a9d34d7ea52843e4fdc8fde --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_extrema.py @@ -0,0 +1,713 @@ +import math +import unittest + +import numpy as np +from numpy.testing import assert_equal +from pytest import raises, warns + +from skimage._shared.testing import expected_warnings +from skimage.morphology import extrema + + +eps = 1e-12 + + +def diff(a, b): + a = np.asarray(a, dtype=np.float64) + b = np.asarray(b, dtype=np.float64) + t = ((a - b) ** 2).sum() + return math.sqrt(t) + + +class TestExtrema: + def test_saturated_arithmetic(self): + """Adding/subtracting a constant and clipping""" + # Test for unsigned integer + data = np.array( + [[250, 251, 5, 5], [100, 200, 253, 252], [4, 10, 1, 3]], dtype=np.uint8 + ) + # adding the constant + img_constant_added = extrema._add_constant_clip(data, 4) + expected = np.array( + [[254, 255, 9, 9], [104, 204, 255, 255], [8, 14, 5, 7]], dtype=np.uint8 + ) + error = diff(img_constant_added, expected) + assert error < eps + img_constant_subtracted = extrema._subtract_constant_clip(data, 4) + expected = np.array( + [[246, 247, 1, 1], [96, 196, 249, 248], [0, 6, 0, 0]], dtype=np.uint8 + ) + error = diff(img_constant_subtracted, expected) + assert error < eps + + # Test for signed integer + data = np.array([[32767, 32766], [-32768, -32767]], dtype=np.int16) + img_constant_added = extrema._add_constant_clip(data, 1) + expected = np.array([[32767, 32767], [-32767, -32766]], dtype=np.int16) + error = diff(img_constant_added, expected) + assert error < eps + img_constant_subtracted = extrema._subtract_constant_clip(data, 1) + expected = np.array([[32766, 32765], [-32768, -32768]], dtype=np.int16) + error = diff(img_constant_subtracted, expected) + assert error < eps + + def test_h_maxima(self): + """h-maxima for various data types""" + + data = np.array( + [ + [10, 11, 13, 14, 14, 15, 14, 14, 13, 11], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + [13, 15, 40, 40, 18, 18, 18, 60, 60, 15], + [14, 16, 40, 40, 19, 19, 19, 60, 60, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [15, 16, 18, 19, 19, 20, 19, 19, 18, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [14, 16, 80, 80, 19, 19, 19, 100, 100, 16], + [13, 15, 80, 80, 18, 18, 18, 100, 100, 15], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + ], + dtype=np.uint8, + ) + + expected_result = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + for dtype in [np.uint8, np.uint64, np.int8, np.int64]: + data = data.astype(dtype) + out = extrema.h_maxima(data, 40) + + error = diff(expected_result, out) + assert error < eps + + def test_h_minima(self): + """h-minima for various data types""" + + data = np.array( + [ + [10, 11, 13, 14, 14, 15, 14, 14, 13, 11], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + [13, 15, 40, 40, 18, 18, 18, 60, 60, 15], + [14, 16, 40, 40, 19, 19, 19, 60, 60, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [15, 16, 18, 19, 19, 20, 19, 19, 18, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [14, 16, 80, 80, 19, 19, 19, 100, 100, 16], + [13, 15, 80, 80, 18, 18, 18, 100, 100, 15], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + ], + dtype=np.uint8, + ) + data = 100 - data + expected_result = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + for dtype in [np.uint8, np.uint64, np.int8, np.int64]: + data = data.astype(dtype) + out = extrema.h_minima(data, 40) + + error = diff(expected_result, out) + assert error < eps + assert out.dtype == expected_result.dtype + + def test_extrema_float(self): + """specific tests for float type""" + data = np.array( + [ + [0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14, 0.14, 0.13, 0.11], + [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13], + [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18, 0.60, 0.60, 0.15], + [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19, 0.60, 0.60, 0.16], + [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16], + [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19, 0.19, 0.18, 0.16], + [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16], + [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19, 1.0, 1.0, 0.16], + [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18, 1.0, 1.0, 0.15], + [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13], + ], + dtype=np.float32, + ) + inverted_data = 1.0 - data + + out = extrema.h_maxima(data, 0.003) + expected_result = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + error = diff(expected_result, out) + assert error < eps + + out = extrema.h_minima(inverted_data, 0.003) + error = diff(expected_result, out) + assert error < eps + + def test_h_maxima_float_image(self): + """specific tests for h-maxima float image type""" + w = 10 + x, y = np.mgrid[0:w, 0:w] + data = 20 - 0.2 * ((x - w / 2) ** 2 + (y - w / 2) ** 2) + data[2:4, 2:4] = 40 + data[2:4, 7:9] = 60 + data[7:9, 2:4] = 80 + data[7:9, 7:9] = 100 + data = data.astype(np.float32) + + expected_result = np.zeros_like(data) + expected_result[(data > 19.9)] = 1.0 + + for h in [1.0e-12, 1.0e-6, 1.0e-3, 1.0e-2, 1.0e-1, 0.1]: + out = extrema.h_maxima(data, h) + error = diff(expected_result, out) + assert error < eps + + def test_h_maxima_float_h(self): + """specific tests for h-maxima float h parameter""" + data = np.array( + [ + [0, 0, 0, 0, 0], + [0, 3, 3, 3, 0], + [0, 3, 4, 3, 0], + [0, 3, 3, 3, 0], + [0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + h_vals = np.linspace(1.0, 2.0, 100) + failures = 0 + + for h in h_vals: + if h % 1 != 0: + msgs = ['possible precision loss converting image'] + else: + msgs = [] + + with expected_warnings(msgs): + maxima = extrema.h_maxima(data, h) + + if maxima[2, 2] == 0: + failures += 1 + + assert failures == 0 + + def test_h_maxima_large_h(self): + """test that h-maxima works correctly for large h""" + data = np.array( + [ + [10, 10, 10, 10, 10], + [10, 13, 13, 13, 10], + [10, 13, 14, 13, 10], + [10, 13, 13, 13, 10], + [10, 10, 10, 10, 10], + ], + dtype=np.uint8, + ) + + maxima = extrema.h_maxima(data, 5) + assert np.sum(maxima) == 0 + + data = np.array( + [ + [10, 10, 10, 10, 10], + [10, 13, 13, 13, 10], + [10, 13, 14, 13, 10], + [10, 13, 13, 13, 10], + [10, 10, 10, 10, 10], + ], + dtype=np.float32, + ) + + maxima = extrema.h_maxima(data, 5.0) + assert np.sum(maxima) == 0 + + def test_h_minima_float_image(self): + """specific tests for h-minima float image type""" + w = 10 + x, y = np.mgrid[0:w, 0:w] + data = 180 + 0.2 * ((x - w / 2) ** 2 + (y - w / 2) ** 2) + data[2:4, 2:4] = 160 + data[2:4, 7:9] = 140 + data[7:9, 2:4] = 120 + data[7:9, 7:9] = 100 + data = data.astype(np.float32) + + expected_result = np.zeros_like(data) + expected_result[(data < 180.1)] = 1.0 + + for h in [1.0e-12, 1.0e-6, 1.0e-3, 1.0e-2, 1.0e-1, 0.1]: + out = extrema.h_minima(data, h) + error = diff(expected_result, out) + assert error < eps + + def test_h_minima_float_h(self): + """specific tests for h-minima float h parameter""" + data = np.array( + [ + [4, 4, 4, 4, 4], + [4, 1, 1, 1, 4], + [4, 1, 0, 1, 4], + [4, 1, 1, 1, 4], + [4, 4, 4, 4, 4], + ], + dtype=np.uint8, + ) + + h_vals = np.linspace(1.0, 2.0, 100) + failures = 0 + for h in h_vals: + if h % 1 != 0: + msgs = ['possible precision loss converting image'] + else: + msgs = [] + + with expected_warnings(msgs): + minima = extrema.h_minima(data, h) + + if minima[2, 2] == 0: + failures += 1 + + assert failures == 0 + + def test_h_minima_large_h(self): + """test that h-minima works correctly for large h""" + data = np.array( + [ + [14, 14, 14, 14, 14], + [14, 11, 11, 11, 14], + [14, 11, 10, 11, 14], + [14, 11, 11, 11, 14], + [14, 14, 14, 14, 14], + ], + dtype=np.uint8, + ) + + maxima = extrema.h_minima(data, 5) + assert np.sum(maxima) == 0 + + data = np.array( + [ + [14, 14, 14, 14, 14], + [14, 11, 11, 11, 14], + [14, 11, 10, 11, 14], + [14, 11, 11, 11, 14], + [14, 14, 14, 14, 14], + ], + dtype=np.float32, + ) + + maxima = extrema.h_minima(data, 5.0) + assert np.sum(maxima) == 0 + + +class TestLocalMaxima(unittest.TestCase): + """Some tests for local_minima are included as well.""" + + supported_dtypes = [ + np.uint8, + np.uint16, + np.uint32, + np.uint64, + np.int8, + np.int16, + np.int32, + np.int64, + np.float32, + np.float64, + ] + image = np.array( + [ + [1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 2, 0, 0, 3, 3, 0, 0, 4, 0, 2, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 4, 4, 0, 3, 0, 0, 0], + [0, 2, 0, 1, 0, 2, 1, 0, 0, 0, 0, 3, 0, 0, 0], + [0, 0, 2, 0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + # Connectivity 2, maxima can touch border, returned with default values + expected_default = np.array( + [ + [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + # Connectivity 1 (cross), maxima can touch border + expected_cross = np.array( + [ + [1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0], + [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + def test_empty(self): + """Test result with empty image.""" + result = extrema.local_maxima(np.array([[]]), indices=False) + assert result.size == 0 + assert result.dtype == bool + assert result.shape == (1, 0) + + result = extrema.local_maxima(np.array([]), indices=True) + assert isinstance(result, tuple) + assert len(result) == 1 + assert result[0].size == 0 + assert result[0].dtype == np.intp + + result = extrema.local_maxima(np.array([[]]), indices=True) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0].size == 0 + assert result[0].dtype == np.intp + assert result[1].size == 0 + assert result[1].dtype == np.intp + + def test_dtypes(self): + """Test results with default configuration for all supported dtypes.""" + for dtype in self.supported_dtypes: + result = extrema.local_maxima(self.image.astype(dtype)) + assert result.dtype == bool + assert_equal(result, self.expected_default) + + def test_dtypes_old(self): + """ + Test results with default configuration and data copied from old unit + tests for all supported dtypes. + """ + data = np.array( + [ + [10, 11, 13, 14, 14, 15, 14, 14, 13, 11], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + [13, 15, 40, 40, 18, 18, 18, 60, 60, 15], + [14, 16, 40, 40, 19, 19, 19, 60, 60, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [15, 16, 18, 19, 19, 20, 19, 19, 18, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [14, 16, 80, 80, 19, 19, 19, 100, 100, 16], + [13, 15, 80, 80, 18, 18, 18, 100, 100, 15], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + ], + dtype=np.uint8, + ) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + for dtype in self.supported_dtypes: + image = data.astype(dtype) + result = extrema.local_maxima(image) + assert result.dtype == bool + assert_equal(result, expected) + + def test_connectivity(self): + """Test results if footprint is a scalar.""" + # Connectivity 1: generates cross shaped footprint + result_conn1 = extrema.local_maxima(self.image, connectivity=1) + assert result_conn1.dtype == bool + assert_equal(result_conn1, self.expected_cross) + + # Connectivity 2: generates square shaped footprint + result_conn2 = extrema.local_maxima(self.image, connectivity=2) + assert result_conn2.dtype == bool + assert_equal(result_conn2, self.expected_default) + + # Connectivity 3: generates square shaped footprint + result_conn3 = extrema.local_maxima(self.image, connectivity=3) + assert result_conn3.dtype == bool + assert_equal(result_conn3, self.expected_default) + + def test_footprint(self): + """Test results if footprint is given.""" + footprint_cross = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=bool) + result_footprint_cross = extrema.local_maxima( + self.image, footprint=footprint_cross + ) + assert result_footprint_cross.dtype == bool + assert_equal(result_footprint_cross, self.expected_cross) + + for footprint in [ + ((True,) * 3,) * 3, + np.ones((3, 3), dtype=np.float64), + np.ones((3, 3), dtype=np.uint8), + np.ones((3, 3), dtype=bool), + ]: + # Test different dtypes for footprint which expects a boolean array + # but will accept and convert other types if possible + result_footprint_square = extrema.local_maxima( + self.image, footprint=footprint + ) + assert result_footprint_square.dtype == bool + assert_equal(result_footprint_square, self.expected_default) + + footprint_x = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]], dtype=bool) + expected_footprint_x = np.array( + [ + [1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + result_footprint_x = extrema.local_maxima(self.image, footprint=footprint_x) + assert result_footprint_x.dtype == bool + assert_equal(result_footprint_x, expected_footprint_x) + + def test_indices(self): + """Test output if indices of peaks are desired.""" + # Connectivity 1 + expected_conn1 = np.nonzero(self.expected_cross) + result_conn1 = extrema.local_maxima(self.image, connectivity=1, indices=True) + assert_equal(result_conn1, expected_conn1) + + # Connectivity 2 + expected_conn2 = np.nonzero(self.expected_default) + result_conn2 = extrema.local_maxima(self.image, connectivity=2, indices=True) + assert_equal(result_conn2, expected_conn2) + + def test_allow_borders(self): + """Test maxima detection at the image border.""" + # Use connectivity 1 to allow many maxima, only filtering at border is + # of interest + result_with_boder = extrema.local_maxima( + self.image, connectivity=1, allow_borders=True + ) + assert result_with_boder.dtype == bool + assert_equal(result_with_boder, self.expected_cross) + + expected_without_border = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0], + [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + result_without_border = extrema.local_maxima( + self.image, connectivity=1, allow_borders=False + ) + assert result_with_boder.dtype == bool + assert_equal(result_without_border, expected_without_border) + + def test_nd(self): + """Test one- and three-dimensional case.""" + # One-dimension + x_1d = np.array([1, 1, 0, 1, 2, 3, 0, 2, 1, 2, 0]) + expected_1d = np.array([1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0], dtype=bool) + result_1d = extrema.local_maxima(x_1d) + assert result_1d.dtype == bool + assert_equal(result_1d, expected_1d) + + # 3-dimensions (adapted from old unit test) + x_3d = np.zeros((8, 8, 8), dtype=np.uint8) + expected_3d = np.zeros((8, 8, 8), dtype=bool) + # first maximum: only one pixel + x_3d[1, 1:3, 1:3] = 100 + x_3d[2, 2, 2] = 200 + x_3d[3, 1:3, 1:3] = 100 + expected_3d[2, 2, 2] = 1 + # second maximum: three pixels in z-direction + x_3d[5:8, 1, 1] = 200 + expected_3d[5:8, 1, 1] = 1 + # third: two maxima in 0 and 3. + x_3d[0, 5:8, 5:8] = 200 + x_3d[1, 6, 6] = 100 + x_3d[2, 5:7, 5:7] = 200 + x_3d[0:3, 5:8, 5:8] += 50 + expected_3d[0, 5:8, 5:8] = 1 + expected_3d[2, 5:7, 5:7] = 1 + # four : one maximum in the corner of the square + x_3d[6:8, 6:8, 6:8] = 200 + x_3d[7, 7, 7] = 255 + expected_3d[7, 7, 7] = 1 + result_3d = extrema.local_maxima(x_3d) + assert result_3d.dtype == bool + assert_equal(result_3d, expected_3d) + + def test_constant(self): + """Test behaviour for 'flat' images.""" + const_image = np.full((7, 6), 42, dtype=np.uint8) + expected = np.zeros((7, 6), dtype=np.uint8) + for dtype in self.supported_dtypes: + const_image = const_image.astype(dtype) + # test for local maxima + result = extrema.local_maxima(const_image) + assert result.dtype == bool + assert_equal(result, expected) + # test for local minima + result = extrema.local_minima(const_image) + assert result.dtype == bool + assert_equal(result, expected) + + def test_extrema_float(self): + """Specific tests for float type.""" + # Copied from old unit test for local_maxima + image = np.array( + [ + [0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14, 0.14, 0.13, 0.11], + [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13], + [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18, 0.60, 0.60, 0.15], + [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19, 0.60, 0.60, 0.16], + [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16], + [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19, 0.19, 0.18, 0.16], + [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16], + [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19, 1.0, 1.0, 0.16], + [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18, 1.0, 1.0, 0.15], + [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13], + ], + dtype=np.float32, + ) + inverted_image = 1.0 - image + expected_result = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + + # Test for local maxima with automatic step calculation + result = extrema.local_maxima(image) + assert result.dtype == bool + assert_equal(result, expected_result) + + # Test for local minima with automatic step calculation + result = extrema.local_minima(inverted_image) + assert result.dtype == bool + assert_equal(result, expected_result) + + def test_extrema_small_float(self): + image = np.array( + [ + [9.89232736e-20, 8.78543302e-20, 8.78543302e-20, 9.89232736e-20], + [8.78543302e-20, 6.38842355e-20, 6.38842355e-20, 8.78543302e-20], + [8.78543302e-20, 6.38842355e-20, 6.38842355e-20, 8.78543302e-20], + [9.89232736e-20, 8.78543302e-20, 8.78543302e-20, 9.89232736e-20], + ] + ) + + result = extrema.local_minima(image) + + expected_result = np.array( + [ + [False, False, False, False], + [False, True, True, False], + [False, True, True, False], + [False, False, False, False], + ] + ) + + assert_equal(result, expected_result) + + def test_exceptions(self): + """Test if input validation triggers correct exceptions.""" + # Mismatching number of dimensions + with raises(ValueError, match="number of dimensions"): + extrema.local_maxima(self.image, footprint=np.ones((3, 3, 3), dtype=bool)) + with raises(ValueError, match="number of dimensions"): + extrema.local_maxima(self.image, footprint=np.ones((3,), dtype=bool)) + + # All dimensions in footprint must be of size 3 + with raises(ValueError, match="dimension size"): + extrema.local_maxima(self.image, footprint=np.ones((2, 3), dtype=bool)) + with raises(ValueError, match="dimension size"): + extrema.local_maxima(self.image, footprint=np.ones((5, 5), dtype=bool)) + + with raises(TypeError, match="float16 which is not supported"): + extrema.local_maxima(np.empty(1, dtype=np.float16)) + + def test_small_array(self): + """Test output for arrays with dimension smaller 3. + + If any dimension of an array is smaller than 3 and `allow_borders` is + false a footprint, which has at least 3 elements in each + dimension, can't be applied. This is an implementation detail so + `local_maxima` should still return valid output (see gh-3261). + + If `allow_borders` is true the array is padded internally and there is + no problem. + """ + warning_msg = "maxima can't exist .* any dimension smaller 3 .*" + x = np.array([0, 1]) + extrema.local_maxima(x, allow_borders=True) # no warning + with warns(UserWarning, match=warning_msg): + result = extrema.local_maxima(x, allow_borders=False) + assert_equal(result, [0, 0]) + assert result.dtype == bool + + x = np.array([[1, 2], [2, 2]]) + extrema.local_maxima(x, allow_borders=True, indices=True) # no warning + with warns(UserWarning, match=warning_msg): + result = extrema.local_maxima(x, allow_borders=False, indices=True) + assert_equal(result, np.zeros((2, 0), dtype=np.intp)) + assert result[0].dtype == np.intp + assert result[1].dtype == np.intp diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_flood_fill.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_flood_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2c9eb19d3a3dfad34d93107532d1b4e22cdb60 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_flood_fill.py @@ -0,0 +1,360 @@ +import numpy as np +import pytest + +from skimage.morphology import flood, flood_fill + +eps = 1e-12 + + +def test_empty_input(): + # Test shortcut + output = flood_fill(np.empty(0), (), 2) + assert output.size == 0 + + # Boolean output type + assert flood(np.empty(0), ()).dtype == bool + + # Maintain shape, even with zero size present + assert flood(np.empty((20, 0, 4)), ()).shape == (20, 0, 4) + + +def test_float16(): + image = np.array([9.0, 0.1, 42], dtype=np.float16) + with pytest.raises(TypeError, match="dtype of `image` is float16"): + flood_fill(image, 0, 1) + + +@pytest.mark.parametrize("tolerance", [-150, 150, -379, 379]) +def test_overrange_tolerance_int(tolerance): + image = np.arange(256, dtype=np.uint8).reshape((8, 8, 4)) + seed = (3, 4, 2) + expected = np.zeros_like(image) + output = flood_fill(image, seed, 0, tolerance=tolerance) + np.testing.assert_equal(output, expected) + + +def test_overrange_tolerance_float(): + max_value = np.finfo(np.float32).max + + image = np.random.uniform(size=(64, 64), low=-1.0, high=1.0).astype(np.float32) + image *= max_value + + expected = np.ones_like(image) + output = flood_fill(image, (0, 1), 1.0, tolerance=max_value.item() * 10) + + np.testing.assert_equal(output, expected) + + +def test_inplace_int(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3], + [0, 1, 1, 1, 3, 3, 4], + ] + ) + + flood_fill(image, (0, 0), 5, in_place=True) + + expected = np.array( + [ + [5, 5, 5, 5, 5, 5, 5], + [5, 1, 1, 5, 2, 2, 5], + [5, 1, 1, 5, 2, 2, 5], + [1, 5, 5, 5, 5, 5, 3], + [5, 1, 1, 1, 3, 3, 4], + ] + ) + + np.testing.assert_array_equal(image, expected) + + +def test_inplace_float(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3], + [0, 1, 1, 1, 3, 3, 4], + ], + dtype=np.float32, + ) + + flood_fill(image, (0, 0), 5, in_place=True) + + expected = np.array( + [ + [5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0], + [5.0, 1.0, 1.0, 5.0, 2.0, 2.0, 5.0], + [5.0, 1.0, 1.0, 5.0, 2.0, 2.0, 5.0], + [1.0, 5.0, 5.0, 5.0, 5.0, 5.0, 3.0], + [5.0, 1.0, 1.0, 1.0, 3.0, 3.0, 4.0], + ], + dtype=np.float32, + ) + + np.testing.assert_allclose(image, expected) + + +def test_inplace_noncontiguous(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3], + [0, 1, 1, 1, 3, 3, 4], + ] + ) + + # Transpose is noncontiguous + image2 = image[::2, ::2] + + flood_fill(image2, (0, 0), 5, in_place=True) + + # The inplace modified result + expected2 = np.array([[5, 5, 5, 5], [5, 1, 2, 5], [5, 1, 3, 4]]) + + np.testing.assert_allclose(image2, expected2) + + # Projected back through the view, `image` also modified + expected = np.array( + [ + [5, 0, 5, 0, 5, 0, 5], + [0, 1, 1, 0, 2, 2, 0], + [5, 1, 1, 0, 2, 2, 5], + [1, 0, 0, 0, 0, 0, 3], + [5, 1, 1, 1, 3, 3, 4], + ] + ) + + np.testing.assert_allclose(image, expected) + + +def test_1d(): + image = np.arange(11) + expected = np.array([0, 1, -20, -20, -20, -20, -20, -20, -20, 9, 10]) + + output = flood_fill(image, 5, -20, tolerance=3) + output2 = flood_fill(image, (5,), -20, tolerance=3) + + np.testing.assert_equal(output, expected) + np.testing.assert_equal(output, output2) + + +def test_wraparound(): + # If the borders (or neighbors) aren't correctly accounted for, this fails, + # because the algorithm uses an ravelled array. + test = np.zeros((5, 7), dtype=np.float64) + test[:, 3] = 100 + + expected = np.array( + [ + [-1.0, -1.0, -1.0, 100.0, 0.0, 0.0, 0.0], + [-1.0, -1.0, -1.0, 100.0, 0.0, 0.0, 0.0], + [-1.0, -1.0, -1.0, 100.0, 0.0, 0.0, 0.0], + [-1.0, -1.0, -1.0, 100.0, 0.0, 0.0, 0.0], + [-1.0, -1.0, -1.0, 100.0, 0.0, 0.0, 0.0], + ] + ) + + np.testing.assert_equal(flood_fill(test, (0, 0), -1), expected) + + +def test_neighbors(): + # This test will only pass if the neighbors are exactly correct + test = np.zeros((5, 7), dtype=np.float64) + test[:, 3] = 100 + + expected = np.array( + [ + [0, 0, 0, 255, 0, 0, 0], + [0, 0, 0, 255, 0, 0, 0], + [0, 0, 0, 255, 0, 0, 0], + [0, 0, 0, 255, 0, 0, 0], + [0, 0, 0, 255, 0, 0, 0], + ] + ) + output = flood_fill(test, (0, 3), 255) + + np.testing.assert_equal(output, expected) + + test[2] = 100 + expected[2] = 255 + + output2 = flood_fill(test, (2, 3), 255) + + np.testing.assert_equal(output2, expected) + + +def test_footprint(): + # Basic tests for nonstandard footprints + footprint = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]]) # Cannot grow left or down + + output = flood_fill( + np.zeros((5, 6), dtype=np.uint8), (3, 1), 255, footprint=footprint + ) + + expected = np.array( + [ + [0, 255, 255, 255, 255, 255], + [0, 255, 255, 255, 255, 255], + [0, 255, 255, 255, 255, 255], + [0, 255, 255, 255, 255, 255], + [0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + np.testing.assert_equal(output, expected) + + footprint = np.array([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) # Cannot grow right or up + + output = flood_fill( + np.zeros((5, 6), dtype=np.uint8), (1, 4), 255, footprint=footprint + ) + + expected = np.array( + [ + [0, 0, 0, 0, 0, 0], + [255, 255, 255, 255, 255, 0], + [255, 255, 255, 255, 255, 0], + [255, 255, 255, 255, 255, 0], + [255, 255, 255, 255, 255, 0], + ], + dtype=np.uint8, + ) + + np.testing.assert_equal(output, expected) + + +def test_basic_nd(): + for dimension in (3, 4, 5): + shape = (5,) * dimension + hypercube = np.zeros(shape) + slice_mid = tuple(slice(1, -1, None) for dim in range(dimension)) + hypercube[slice_mid] = 1 # sum is 3**dimension + filled = flood_fill(hypercube, (2,) * dimension, 2) + + # Test that the middle sum is correct + assert filled.sum() == 3**dimension * 2 + + # Test that the entire array is as expected + np.testing.assert_equal( + filled, np.pad(np.ones((3,) * dimension) * 2, 1, 'constant') + ) + + +@pytest.mark.parametrize("tolerance", [None, 0]) +def test_f_order(tolerance): + image = np.array( + [ + [0, 0, 0, 0], + [1, 0, 0, 0], + [0, 1, 0, 0], + ], + order="F", + ) + expected = np.array( + [ + [0, 0, 0, 0], + [1, 0, 0, 0], + [0, 1, 0, 0], + ], + dtype=bool, + ) + + mask = flood(image, seed_point=(1, 0), tolerance=tolerance) + np.testing.assert_array_equal(expected, mask) + + mask = flood(image, seed_point=(2, 1), tolerance=tolerance) + np.testing.assert_array_equal(expected, mask) + + +def test_negative_indexing_seed_point(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3], + [0, 1, 1, 1, 3, 3, 4], + ], + dtype=np.float32, + ) + + expected = np.array( + [ + [5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0], + [5.0, 1.0, 1.0, 5.0, 2.0, 2.0, 5.0], + [5.0, 1.0, 1.0, 5.0, 2.0, 2.0, 5.0], + [1.0, 5.0, 5.0, 5.0, 5.0, 5.0, 3.0], + [5.0, 1.0, 1.0, 1.0, 3.0, 3.0, 4.0], + ], + dtype=np.float32, + ) + + image = flood_fill(image, (0, -1), 5) + + np.testing.assert_allclose(image, expected) + + +def test_non_adjacent_footprint(): + # Basic tests for non-adjacent footprints + footprint = np.array( + [ + [1, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 1], + ] + ) + + output = flood_fill( + np.zeros((5, 6), dtype=np.uint8), (2, 3), 255, footprint=footprint + ) + + expected = np.array( + [ + [0, 255, 0, 0, 0, 255], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 255, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 255, 0, 0, 0, 255], + ], + dtype=np.uint8, + ) + + np.testing.assert_equal(output, expected) + + footprint = np.array( + [ + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ] + ) + + image = np.zeros((5, 10), dtype=np.uint8) + image[:, (3, 7, 8)] = 100 + + output = flood_fill(image, (0, 0), 255, footprint=footprint) + + expected = np.array( + [ + [255, 255, 255, 100, 255, 255, 255, 100, 100, 0], + [255, 255, 255, 100, 255, 255, 255, 100, 100, 0], + [255, 255, 255, 100, 255, 255, 255, 100, 100, 0], + [255, 255, 255, 100, 255, 255, 255, 100, 100, 0], + [255, 255, 255, 100, 255, 255, 255, 100, 100, 0], + ], + dtype=np.uint8, + ) + + np.testing.assert_equal(output, expected) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_footprints.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_footprints.py new file mode 100644 index 0000000000000000000000000000000000000000..7889b2a22900c6b24152294d0dc7f1b1fb0fb361 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_footprints.py @@ -0,0 +1,281 @@ +""" +Tests for Morphological footprints +(skimage.morphology.footprint) + +Author: Damian Eads +""" + +import numpy as np +import pytest +from numpy.testing import assert_equal + +from skimage._shared.testing import fetch, assert_stacklevel +from skimage.morphology import footprints +from skimage.morphology import footprint_rectangle, footprint_from_sequence + + +class TestFootprints: + def strel_worker(self, fn, func): + matlab_masks = np.load(fetch(fn)) + k = 0 + for arrname in sorted(matlab_masks): + expected_mask = matlab_masks[arrname] + actual_mask = func(k) + if expected_mask.shape == (1,): + expected_mask = expected_mask[:, np.newaxis] + assert_equal(expected_mask, actual_mask) + k = k + 1 + + def strel_worker_3d(self, fn, func): + matlab_masks = np.load(fetch(fn)) + k = 0 + for arrname in sorted(matlab_masks): + expected_mask = matlab_masks[arrname] + actual_mask = func(k) + if expected_mask.shape == (1,): + expected_mask = expected_mask[:, np.newaxis] + # Test center slice for each dimension. This gives a good + # indication of validity without the need for a 3D reference + # mask. + c = int(expected_mask.shape[0] / 2) + assert_equal(expected_mask, actual_mask[c, :, :]) + assert_equal(expected_mask, actual_mask[:, c, :]) + assert_equal(expected_mask, actual_mask[:, :, c]) + k = k + 1 + + def test_footprint_disk(self): + """Test disk footprints""" + self.strel_worker("data/disk-matlab-output.npz", footprints.disk) + + def test_footprint_diamond(self): + """Test diamond footprints""" + self.strel_worker("data/diamond-matlab-output.npz", footprints.diamond) + + def test_footprint_ball(self): + """Test ball footprints""" + self.strel_worker_3d("data/disk-matlab-output.npz", footprints.ball) + + def test_footprint_octahedron(self): + """Test octahedron footprints""" + self.strel_worker_3d("data/diamond-matlab-output.npz", footprints.octahedron) + + def test_footprint_octagon(self): + """Test octagon footprints""" + expected_mask1 = np.array( + [ + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + ], + dtype=np.uint8, + ) + actual_mask1 = footprints.octagon(5, 3) + expected_mask2 = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8) + actual_mask2 = footprints.octagon(1, 1) + assert_equal(expected_mask1, actual_mask1) + assert_equal(expected_mask2, actual_mask2) + + def test_footprint_ellipse(self): + """Test ellipse footprints""" + expected_mask1 = np.array( + [ + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + ], + dtype=np.uint8, + ) + actual_mask1 = footprints.ellipse(5, 3) + expected_mask2 = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], dtype=np.uint8) + actual_mask2 = footprints.ellipse(1, 1) + assert_equal(expected_mask1, actual_mask1) + assert_equal(expected_mask2, actual_mask2) + assert_equal(expected_mask1, footprints.ellipse(3, 5).T) + assert_equal(expected_mask2, footprints.ellipse(1, 1).T) + + def test_footprint_star(self): + """Test star footprints""" + expected_mask1 = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + actual_mask1 = footprints.star(4) + expected_mask2 = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], dtype=np.uint8) + actual_mask2 = footprints.star(1) + assert_equal(expected_mask1, actual_mask1) + assert_equal(expected_mask2, actual_mask2) + + +@pytest.mark.parametrize( + 'function, args, supports_sequence_decomposition', + [ + (footprints.disk, (3,), True), + (footprints.ball, (3,), True), + (footprints.diamond, (3,), True), + (footprints.octahedron, (3,), True), + (footprint_rectangle, ((3, 5),), True), + (footprints.ellipse, (3, 4), False), + (footprints.octagon, (3, 4), True), + (footprints.star, (3,), False), + ], +) +@pytest.mark.parametrize("dtype", [np.uint8, np.float64]) +def test_footprint_dtype(function, args, supports_sequence_decomposition, dtype): + # make sure footprint dtype matches what was requested + footprint = function(*args, dtype=dtype) + assert footprint.dtype == dtype + + if supports_sequence_decomposition: + sequence = function(*args, dtype=dtype, decomposition='sequence') + assert all([fp_tuple[0].dtype == dtype for fp_tuple in sequence]) + + +@pytest.mark.parametrize("function", ["disk", "ball"]) +@pytest.mark.parametrize("radius", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 50, 75, 100]) +def test_nsphere_series_approximation(function, radius): + fp_func = getattr(footprints, function) + expected = fp_func(radius, strict_radius=False, decomposition=None) + footprint_sequence = fp_func(radius, strict_radius=False, decomposition="sequence") + approximate = footprints.footprint_from_sequence(footprint_sequence) + assert approximate.shape == expected.shape + + # verify that maximum error does not exceed some fraction of the size + error = np.sum(np.abs(expected.astype(int) - approximate.astype(int))) + if radius == 1: + assert error == 0 + else: + max_error = 0.1 if function == "disk" else 0.15 + assert error / expected.size <= max_error + + +@pytest.mark.parametrize("radius", [1, 2, 3, 4, 5, 10, 20, 50, 75]) +@pytest.mark.parametrize("strict_radius", [False, True]) +def test_disk_crosses_approximation(radius, strict_radius): + fp_func = footprints.disk + expected = fp_func(radius, strict_radius=strict_radius, decomposition=None) + footprint_sequence = fp_func( + radius, strict_radius=strict_radius, decomposition="crosses" + ) + approximate = footprints.footprint_from_sequence(footprint_sequence) + assert approximate.shape == expected.shape + + # verify that maximum error does not exceed some fraction of the size + error = np.sum(np.abs(expected.astype(int) - approximate.astype(int))) + max_error = 0.05 + assert error / expected.size <= max_error + + +@pytest.mark.parametrize("width", [3, 8, 20, 50]) +@pytest.mark.parametrize("height", [3, 8, 20, 50]) +def test_ellipse_crosses_approximation(width, height): + fp_func = footprints.ellipse + expected = fp_func(width, height, decomposition=None) + footprint_sequence = fp_func(width, height, decomposition="crosses") + approximate = footprints.footprint_from_sequence(footprint_sequence) + assert approximate.shape == expected.shape + + # verify that maximum error does not exceed some fraction of the size + error = np.sum(np.abs(expected.astype(int) - approximate.astype(int))) + max_error = 0.05 + assert error / expected.size <= max_error + + +def test_disk_series_approximation_unavailable(): + # ValueError if radius is too large (only precomputed up to radius=250) + with pytest.raises(ValueError): + footprints.disk(radius=10000, decomposition="sequence") + + +def test_ball_series_approximation_unavailable(): + # ValueError if radius is too large (only precomputed up to radius=100) + with pytest.raises(ValueError): + footprints.ball(radius=10000, decomposition="sequence") + + +@pytest.mark.parametrize("as_sequence", [tuple, None]) +def test_mirror_footprint(as_sequence): + footprint = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]], np.uint8) + expected_res = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]], dtype=np.uint8) + if as_sequence is not None: + footprint = as_sequence([(footprint, 2), (footprint.T, 3)]) + expected_res = as_sequence([(expected_res, 2), (expected_res.T, 3)]) + + actual_res = footprints.mirror_footprint(footprint) + assert type(expected_res) is type(actual_res) + assert_equal(expected_res, actual_res) + + +@pytest.mark.parametrize("as_sequence", [tuple, None]) +@pytest.mark.parametrize("pad_end", [True, False]) +def test_pad_footprint(as_sequence, pad_end): + footprint = np.array([[0, 0], [1, 0], [1, 1]], np.uint8) + pad_width = [(0, 0), (0, 1)] if pad_end is True else [(0, 0), (1, 0)] + expected_res = np.pad(footprint, pad_width) + if as_sequence is not None: + footprint = as_sequence([(footprint, 2), (footprint.T, 3)]) + expected_res = as_sequence([(expected_res, 2), (expected_res.T, 3)]) + + actual_res = footprints.pad_footprint(footprint, pad_end=pad_end) + assert type(expected_res) is type(actual_res) + assert_equal(expected_res, actual_res) + + +class Test_footprint_rectangule: + @pytest.mark.parametrize("i", [0, 1, 2, 3, 4]) + @pytest.mark.parametrize("j", [0, 1, 2, 3, 4]) + def test_rectangle(self, i, j): + desired = np.ones((i, j), dtype='uint8') + actual = footprint_rectangle((i, j)) + assert_equal(actual, desired) + + @pytest.mark.parametrize("i", [0, 1, 2, 3, 4]) + @pytest.mark.parametrize("j", [0, 1, 2, 3, 4]) + @pytest.mark.parametrize("k", [0, 1, 2, 3, 4]) + def test_cuboid(self, i, j, k): + desired = np.ones((i, j, k), dtype='uint8') + actual = footprint_rectangle((i, j, k)) + assert_equal(actual, desired) + + @pytest.mark.parametrize("shape", [(3,), (5, 5), (5, 5, 7)]) + @pytest.mark.parametrize("decomposition", ["separable", "sequence"]) + def test_decomposition(self, shape, decomposition): + regular = footprint_rectangle(shape) + decomposed = footprint_rectangle(shape, decomposition=decomposition) + recomposed = footprint_from_sequence(decomposed) + assert_equal(recomposed, regular) + + @pytest.mark.parametrize("shape", [(2,), (3, 4)]) + def test_uneven_sequence_decomposition_warning(self, shape): + """Should fall back to decomposition="separable" for uneven footprint size.""" + desired = footprint_rectangle(shape, decomposition="separable") + regex = "decomposition='sequence' is only supported for uneven footprints" + with pytest.warns(UserWarning, match=regex) as record: + actual = footprint_rectangle(shape, decomposition="sequence") + assert_stacklevel(record) + assert_equal(actual, desired) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_gray.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_gray.py new file mode 100644 index 0000000000000000000000000000000000000000..7073f22845c2d9078cca6dadcd500235c4371264 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_gray.py @@ -0,0 +1,500 @@ +import numpy as np +import pytest +from scipy import ndimage as ndi +from numpy.testing import assert_allclose, assert_array_equal, assert_equal + +from skimage import color, data, transform +from skimage._shared._warnings import expected_warnings +from skimage._shared.testing import fetch, assert_stacklevel +from skimage.morphology import gray, footprints, footprint_rectangle +from skimage.util import img_as_uint, img_as_ubyte + + +@pytest.fixture +def cam_image(): + from skimage import data + + return np.ascontiguousarray(data.camera()[64:112, 64:96]) + + +@pytest.fixture +def cell3d_image(): + from skimage import data + + return np.ascontiguousarray(data.cells3d()[30:48, 0, 20:36, 20:32]) + + +gray_morphology_funcs = ( + gray.erosion, + gray.dilation, + gray.opening, + gray.closing, + gray.white_tophat, + gray.black_tophat, +) + + +class TestMorphology: + # These expected outputs were generated with skimage v0.22.0 + PR #6695 + # using: + # + # from skimage.morphology.tests.test_gray import TestMorphology + # import numpy as np + # output = TestMorphology()._build_expected_output() + # np.savez_compressed('gray_morph_output.npz', **output) + + def _build_expected_output(self): + def square(n): + return footprint_rectangle((n, n)) + + footprints_2D = ( + square, + footprints.diamond, + footprints.disk, + footprints.star, + ) + + image = img_as_ubyte( + transform.downscale_local_mean(color.rgb2gray(data.coffee()), (20, 20)) + ) + + output = {} + for n in range(1, 4): + for strel in footprints_2D: + for func in gray_morphology_funcs: + key = f'{strel.__name__}_{n}_{func.__name__}' + output[key] = func(image, strel(n)) + + return output + + def test_gray_morphology(self): + expected = dict(np.load(fetch('data/gray_morph_output.npz'))) + calculated = self._build_expected_output() + assert_equal(expected, calculated) + + def test_gray_closing_extensive(self): + img = data.coins() + footprint = np.array([[0, 0, 1], [0, 1, 1], [1, 1, 1]]) + + # Default mode="reflect" is not extensive for backwards-compatibility + result_default = gray.closing(img, footprint=footprint) + assert not np.all(result_default >= img) + + result = gray.closing(img, footprint=footprint, mode="ignore") + assert np.all(result >= img) + + def test_gray_opening_anti_extensive(self): + img = data.coins() + footprint = np.array([[0, 0, 1], [0, 1, 1], [1, 1, 1]]) + + # Default mode="reflect" is not extensive for backwards-compatibility + result_default = gray.opening(img, footprint=footprint) + assert not np.all(result_default <= img) + + result_ignore = gray.opening(img, footprint=footprint, mode="ignore") + assert np.all(result_ignore <= img) + + @pytest.mark.parametrize("func", gray_morphology_funcs) + @pytest.mark.parametrize("mode", gray._SUPPORTED_MODES) + def test_supported_mode(self, func, mode): + img = np.ones((10, 10)) + func(img, mode=mode) + + @pytest.mark.parametrize("func", gray_morphology_funcs) + @pytest.mark.parametrize("mode", ["", "symmetric", 3, None]) + def test_unsupported_mode(self, func, mode): + img = np.ones((10, 10)) + with pytest.raises(ValueError, match="unsupported mode"): + func(img, mode=mode) + + +class TestEccentricStructuringElements: + def setup_class(self): + self.black_pixel = 255 * np.ones((6, 6), dtype=np.uint8) + self.black_pixel[2, 2] = 0 + self.white_pixel = 255 - self.black_pixel + self.footprints = [ + footprint_rectangle((2, 2)), + footprint_rectangle((2, 1)), + footprint_rectangle((2, 1)), + ] + + def test_dilate_erode_symmetry(self): + for s in self.footprints: + c = gray.erosion(self.black_pixel, s) + d = gray.dilation(self.white_pixel, s) + assert np.all(c == (255 - d)) + + def test_open_black_pixel(self): + for s in self.footprints: + gray_open = gray.opening(self.black_pixel, s) + assert np.all(gray_open == self.black_pixel) + + def test_close_white_pixel(self): + for s in self.footprints: + gray_close = gray.closing(self.white_pixel, s) + assert np.all(gray_close == self.white_pixel) + + def test_open_white_pixel(self): + for s in self.footprints: + assert np.all(gray.opening(self.white_pixel, s) == 0) + + def test_close_black_pixel(self): + for s in self.footprints: + assert np.all(gray.closing(self.black_pixel, s) == 255) + + def test_white_tophat_white_pixel(self): + for s in self.footprints: + tophat = gray.white_tophat(self.white_pixel, s) + assert np.all(tophat == self.white_pixel) + + def test_black_tophat_black_pixel(self): + for s in self.footprints: + tophat = gray.black_tophat(self.black_pixel, s) + assert np.all(tophat == self.white_pixel) + + def test_white_tophat_black_pixel(self): + for s in self.footprints: + tophat = gray.white_tophat(self.black_pixel, s) + assert np.all(tophat == 0) + + def test_black_tophat_white_pixel(self): + for s in self.footprints: + tophat = gray.black_tophat(self.white_pixel, s) + assert np.all(tophat == 0) + + +gray_functions = [ + gray.erosion, + gray.dilation, + gray.opening, + gray.closing, + gray.white_tophat, + gray.black_tophat, +] + + +@pytest.mark.parametrize("function", gray_functions) +def test_default_footprint(function): + strel = footprints.diamond(radius=1) + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + im_expected = function(image, strel) + im_test = function(image) + assert_array_equal(im_expected, im_test) + + +def test_3d_fallback_default_footprint(): + # 3x3x3 cube inside a 7x7x7 image: + image = np.zeros((7, 7, 7), bool) + image[2:-2, 2:-2, 2:-2] = 1 + + opened = gray.opening(image) + + # expect a "hyper-cross" centered in the 5x5x5: + image_expected = np.zeros((7, 7, 7), dtype=bool) + image_expected[2:5, 2:5, 2:5] = ndi.generate_binary_structure(3, 1) + assert_array_equal(opened, image_expected) + + +gray_3d_fallback_functions = [gray.closing, gray.opening] + + +@pytest.mark.parametrize("function", gray_3d_fallback_functions) +def test_3d_fallback_cube_footprint(function): + # 3x3x3 cube inside a 7x7x7 image: + image = np.zeros((7, 7, 7), bool) + image[2:-2, 2:-2, 2:-2] = 1 + + cube = np.ones((3, 3, 3), dtype=np.uint8) + + new_image = function(image, cube) + assert_array_equal(new_image, image) + + +def test_3d_fallback_white_tophat(): + image = np.zeros((7, 7, 7), dtype=bool) + image[2, 2:4, 2:4] = 1 + image[3, 2:5, 2:5] = 1 + image[4, 3:5, 3:5] = 1 + + with expected_warnings([r'operator.*deprecated|\A\Z']): + new_image = gray.white_tophat(image) + footprint = ndi.generate_binary_structure(3, 1) + with expected_warnings([r'operator.*deprecated|\A\Z']): + image_expected = ndi.white_tophat( + image.view(dtype=np.uint8), footprint=footprint + ) + assert_array_equal(new_image, image_expected) + + +def test_3d_fallback_black_tophat(): + image = np.ones((7, 7, 7), dtype=bool) + image[2, 2:4, 2:4] = 0 + image[3, 2:5, 2:5] = 0 + image[4, 3:5, 3:5] = 0 + + with expected_warnings([r'operator.*deprecated|\A\Z']): + new_image = gray.black_tophat(image) + footprint = ndi.generate_binary_structure(3, 1) + with expected_warnings([r'operator.*deprecated|\A\Z']): + image_expected = ndi.black_tophat( + image.view(dtype=np.uint8), footprint=footprint + ) + assert_array_equal(new_image, image_expected) + + +def test_2d_ndimage_equivalence(): + image = np.zeros((9, 9), np.uint8) + image[2:-2, 2:-2] = 128 + image[3:-3, 3:-3] = 196 + image[4, 4] = 255 + + opened = gray.opening(image) + closed = gray.closing(image) + + footprint = ndi.generate_binary_structure(2, 1) + ndimage_opened = ndi.grey_opening(image, footprint=footprint) + ndimage_closed = ndi.grey_closing(image, footprint=footprint) + + assert_array_equal(opened, ndimage_opened) + assert_array_equal(closed, ndimage_closed) + + +# float test images +im = np.array( + [ + [0.55, 0.72, 0.6, 0.54, 0.42], + [0.65, 0.44, 0.89, 0.96, 0.38], + [0.79, 0.53, 0.57, 0.93, 0.07], + [0.09, 0.02, 0.83, 0.78, 0.87], + [0.98, 0.8, 0.46, 0.78, 0.12], + ] +) + +eroded = np.array( + [ + [0.55, 0.44, 0.54, 0.42, 0.38], + [0.44, 0.44, 0.44, 0.38, 0.07], + [0.09, 0.02, 0.53, 0.07, 0.07], + [0.02, 0.02, 0.02, 0.78, 0.07], + [0.09, 0.02, 0.46, 0.12, 0.12], + ] +) + +dilated = np.array( + [ + [0.72, 0.72, 0.89, 0.96, 0.54], + [0.79, 0.89, 0.96, 0.96, 0.96], + [0.79, 0.79, 0.93, 0.96, 0.93], + [0.98, 0.83, 0.83, 0.93, 0.87], + [0.98, 0.98, 0.83, 0.78, 0.87], + ] +) + +opened = np.array( + [ + [0.55, 0.55, 0.54, 0.54, 0.42], + [0.55, 0.44, 0.54, 0.44, 0.38], + [0.44, 0.53, 0.53, 0.78, 0.07], + [0.09, 0.02, 0.78, 0.78, 0.78], + [0.09, 0.46, 0.46, 0.78, 0.12], + ] +) + +closed = np.array( + [ + [0.72, 0.72, 0.72, 0.54, 0.54], + [0.72, 0.72, 0.89, 0.96, 0.54], + [0.79, 0.79, 0.79, 0.93, 0.87], + [0.79, 0.79, 0.83, 0.78, 0.87], + [0.98, 0.83, 0.78, 0.78, 0.78], + ] +) + + +def test_float(): + assert_allclose(gray.erosion(im), eroded) + assert_allclose(gray.dilation(im), dilated) + assert_allclose(gray.opening(im), opened) + assert_allclose(gray.closing(im), closed) + + +def test_uint16(): + im16, eroded16, dilated16, opened16, closed16 = map( + img_as_uint, [im, eroded, dilated, opened, closed] + ) + assert_allclose(gray.erosion(im16), eroded16) + assert_allclose(gray.dilation(im16), dilated16) + assert_allclose(gray.opening(im16), opened16) + assert_allclose(gray.closing(im16), closed16) + + +def test_discontiguous_out_array(): + image = np.array([[5, 6, 2], [7, 2, 2], [3, 5, 1]], np.uint8) + out_array_big = np.zeros((5, 5), np.uint8) + out_array = out_array_big[::2, ::2] + expected_dilation = np.array( + [ + [7, 0, 6, 0, 6], + [0, 0, 0, 0, 0], + [7, 0, 7, 0, 2], + [0, 0, 0, 0, 0], + [7, 0, 5, 0, 5], + ], + np.uint8, + ) + expected_erosion = np.array( + [ + [5, 0, 2, 0, 2], + [0, 0, 0, 0, 0], + [2, 0, 2, 0, 1], + [0, 0, 0, 0, 0], + [3, 0, 1, 0, 1], + ], + np.uint8, + ) + gray.dilation(image, out=out_array) + assert_array_equal(out_array_big, expected_dilation) + gray.erosion(image, out=out_array) + assert_array_equal(out_array_big, expected_erosion) + + +def test_1d_erosion(): + image = np.array([1, 2, 3, 2, 1]) + expected = np.array([1, 1, 2, 1, 1]) + eroded = gray.erosion(image) + assert_array_equal(eroded, expected) + + +@pytest.mark.parametrize( + "function", + ["erosion", "dilation", "closing", "opening", "white_tophat", "black_tophat"], +) +@pytest.mark.parametrize("nrows", [3, 7, 11]) +@pytest.mark.parametrize("ncols", [3, 7, 11]) +@pytest.mark.parametrize("decomposition", ['separable', 'sequence']) +def test_rectangle_decomposition(cam_image, function, nrows, ncols, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprint_rectangle((nrows, ncols), decomposition=None) + footprint = footprint_rectangle((nrows, ncols), decomposition=decomposition) + func = getattr(gray, function) + expected = func(cam_image, footprint=footprint_ndarray) + out = func(cam_image, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["erosion", "dilation", "closing", "opening", "white_tophat", "black_tophat"], +) +@pytest.mark.parametrize("radius", (2, 3)) +@pytest.mark.parametrize("decomposition", ['sequence']) +def test_diamond_decomposition(cam_image, function, radius, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprints.diamond(radius, decomposition=None) + footprint = footprints.diamond(radius, decomposition=decomposition) + func = getattr(gray, function) + expected = func(cam_image, footprint=footprint_ndarray) + out = func(cam_image, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["erosion", "dilation", "closing", "opening", "white_tophat", "black_tophat"], +) +@pytest.mark.parametrize("m", (0, 1, 3, 5)) +@pytest.mark.parametrize("n", (0, 1, 2, 3)) +@pytest.mark.parametrize("decomposition", ['sequence']) +@pytest.mark.filterwarnings( + "ignore:.*falling back to decomposition='separable':UserWarning:skimage" +) +def test_octagon_decomposition(cam_image, function, m, n, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + if m == 0 and n == 0: + with pytest.raises(ValueError): + footprints.octagon(m, n, decomposition=decomposition) + else: + footprint_ndarray = footprints.octagon(m, n, decomposition=None) + footprint = footprints.octagon(m, n, decomposition=decomposition) + func = getattr(gray, function) + expected = func(cam_image, footprint=footprint_ndarray) + out = func(cam_image, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["erosion", "dilation", "closing", "opening", "white_tophat", "black_tophat"], +) +@pytest.mark.parametrize("shape", [(5, 5, 5), (5, 5, 7)]) +@pytest.mark.parametrize("decomposition", ['separable', 'sequence']) +def test_cube_decomposition(cell3d_image, function, shape, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprint_rectangle(shape, decomposition=None) + footprint = footprint_rectangle(shape, decomposition=decomposition) + func = getattr(gray, function) + expected = func(cell3d_image, footprint=footprint_ndarray) + out = func(cell3d_image, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize( + "function", + ["erosion", "dilation", "closing", "opening", "white_tophat", "black_tophat"], +) +@pytest.mark.parametrize("radius", (3,)) +@pytest.mark.parametrize("decomposition", ['sequence']) +def test_octahedron_decomposition(cell3d_image, function, radius, decomposition): + """Validate footprint decomposition for various shapes. + + comparison is made to the case without decomposition. + """ + footprint_ndarray = footprints.octahedron(radius, decomposition=None) + footprint = footprints.octahedron(radius, decomposition=decomposition) + func = getattr(gray, function) + expected = func(cell3d_image, footprint=footprint_ndarray) + out = func(cell3d_image, footprint=footprint) + assert_array_equal(expected, out) + + +@pytest.mark.parametrize("func", [gray.erosion, gray.dilation]) +@pytest.mark.parametrize("name", ["shift_x", "shift_y"]) +@pytest.mark.parametrize("value", [True, False, None]) +def test_deprecated_shift(func, name, value): + img = np.ones(10) + func(img) # Shouldn't warn + + regex = "`shift_x` and `shift_y` are deprecated" + with pytest.warns(FutureWarning, match=regex) as record: + func(img, **{name: value}) + assert_stacklevel(record) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_isotropic.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_isotropic.py new file mode 100644 index 0000000000000000000000000000000000000000..d74f5198ee632b9fd8a7a4471d3688224646c89d --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_isotropic.py @@ -0,0 +1,83 @@ +import numpy as np +from numpy.testing import assert_array_equal + +from skimage import color, data, morphology +from skimage.morphology import binary, isotropic +from skimage.util import img_as_bool + +img = color.rgb2gray(data.astronaut()) +bw_img = img > 100 / 255.0 + + +def test_non_square_image(): + isotropic_res = isotropic.isotropic_erosion(bw_img[:100, :200], 3) + binary_res = img_as_bool( + binary.binary_erosion(bw_img[:100, :200], morphology.disk(3)) + ) + assert_array_equal(isotropic_res, binary_res) + + +def test_isotropic_erosion(): + isotropic_res = isotropic.isotropic_erosion(bw_img, 3) + binary_res = img_as_bool(binary.binary_erosion(bw_img, morphology.disk(3))) + assert_array_equal(isotropic_res, binary_res) + + +def _disk_with_spacing(radius, dtype=np.uint8, *, strict_radius=True, spacing=None): + # Identical to morphology.disk, but with a spacing parameter and without decomposition. + # This is different from morphology.ellipse which produces a slightly different footprint. + L = np.arange(-radius, radius + 1) + X, Y = np.meshgrid(L, L) + + if spacing is not None: + X *= spacing[1] + Y *= spacing[0] + + if not strict_radius: + radius += 0.5 + return np.array((X**2 + Y**2) <= radius**2, dtype=dtype) + + +def test_isotropic_erosion_spacing(): + isotropic_res = isotropic.isotropic_dilation(bw_img, 6, spacing=(1, 2)) + binary_res = img_as_bool( + binary.binary_dilation(bw_img, _disk_with_spacing(6, spacing=(1, 2))) + ) + assert_array_equal(isotropic_res, binary_res) + + +def test_isotropic_dilation(): + isotropic_res = isotropic.isotropic_dilation(bw_img, 3) + binary_res = img_as_bool(binary.binary_dilation(bw_img, morphology.disk(3))) + assert_array_equal(isotropic_res, binary_res) + + +def test_isotropic_closing(): + isotropic_res = isotropic.isotropic_closing(bw_img, 3) + binary_res = img_as_bool(binary.binary_closing(bw_img, morphology.disk(3))) + assert_array_equal(isotropic_res, binary_res) + + +def test_isotropic_opening(): + isotropic_res = isotropic.isotropic_opening(bw_img, 3) + binary_res = img_as_bool(binary.binary_opening(bw_img, morphology.disk(3))) + assert_array_equal(isotropic_res, binary_res) + + +def test_footprint_overflow(): + img = np.zeros((20, 20), dtype=bool) + img[2:19, 2:19] = True + isotropic_res = isotropic.isotropic_erosion(img, 9) + binary_res = img_as_bool(binary.binary_erosion(img, morphology.disk(9))) + assert_array_equal(isotropic_res, binary_res) + + +def test_out_argument(): + for func in (isotropic.isotropic_erosion, isotropic.isotropic_dilation): + radius = 3 + img = np.ones((10, 10)) + out = np.zeros_like(img) + out_saved = out.copy() + func(img, radius, out=out) + assert np.any(out != out_saved) + assert_array_equal(out, func(img, radius)) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_max_tree.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_max_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..c37d4c4c1d41c35598b62d89aba9054b2213dcb8 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_max_tree.py @@ -0,0 +1,469 @@ +import numpy as np +from skimage.morphology import max_tree, area_closing, area_opening +from skimage.morphology import max_tree_local_maxima, diameter_opening +from skimage.morphology import diameter_closing +from skimage.util import invert + +from skimage._shared.testing import assert_array_equal, TestCase + +eps = 1e-12 + + +def _full_type_test(img, param, expected, func, param_scale=False, **keywords): + # images as they are + out = func(img, param, **keywords) + assert_array_equal(out, expected) + + # unsigned int + for dt in [np.uint32, np.uint64]: + img_cast = img.astype(dt) + out = func(img_cast, param, **keywords) + exp_cast = expected.astype(dt) + assert_array_equal(out, exp_cast) + + # float + data_float = img.astype(np.float64) + data_float = data_float / 255.0 + expected_float = expected.astype(np.float64) + expected_float = expected_float / 255.0 + if param_scale: + param_cast = param / 255.0 + else: + param_cast = param + for dt in [np.float32, np.float64]: + data_cast = data_float.astype(dt) + out = func(data_cast, param_cast, **keywords) + exp_cast = expected_float.astype(dt) + error_img = 255.0 * exp_cast - 255.0 * out + error = (error_img >= 1.0).sum() + assert error < eps + + # signed images + img_signed = img.astype(np.int16) + img_signed = img_signed - 128 + exp_signed = expected.astype(np.int16) + exp_signed = exp_signed - 128 + for dt in [np.int8, np.int16, np.int32, np.int64]: + img_s = img_signed.astype(dt) + out = func(img_s, param, **keywords) + exp_s = exp_signed.astype(dt) + assert_array_equal(out, exp_s) + + +class TestMaxtree(TestCase): + def test_max_tree(self): + "Test for max tree" + img_type = np.uint8 + img = np.array( + [[10, 8, 8, 9], [7, 7, 9, 9], [8, 7, 10, 10], [9, 9, 10, 10]], + dtype=img_type, + ) + + P_exp = np.array( + [[1, 4, 1, 1], [4, 4, 3, 3], [1, 4, 3, 10], [3, 3, 10, 10]], dtype=np.int64 + ) + + S_exp = np.array( + [4, 5, 9, 1, 2, 8, 3, 6, 7, 12, 13, 0, 10, 11, 14, 15], dtype=np.int64 + ) + + for img_type in [np.uint8, np.uint16, np.uint32, np.uint64]: + img = img.astype(img_type) + P, S = max_tree(img, connectivity=2) + assert_array_equal(P, P_exp) + assert_array_equal(S, S_exp) + + for img_type in [np.int8, np.int16, np.int32, np.int64]: + img = img.astype(img_type) + img_shifted = img - 9 + P, S = max_tree(img_shifted, connectivity=2) + assert_array_equal(P, P_exp) + assert_array_equal(S, S_exp) + + img_float = img.astype(float) + img_float = (img_float - 8) / 2.0 + for img_type in [np.float32, np.float64]: + img_float = img_float.astype(img_type) + P, S = max_tree(img_float, connectivity=2) + assert_array_equal(P, P_exp) + assert_array_equal(S, S_exp) + + return + + def test_area_closing(self): + "Test for Area Closing (2 thresholds, all types)" + + # original image + img = np.array( + [ + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [240, 200, 200, 240, 200, 240, 200, 200, 240, 240, 200, 240], + [240, 200, 40, 240, 240, 240, 240, 240, 240, 240, 40, 240], + [240, 240, 240, 240, 100, 240, 100, 100, 240, 240, 200, 240], + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [200, 200, 200, 200, 200, 200, 200, 240, 200, 200, 255, 255], + [200, 255, 200, 200, 200, 255, 200, 240, 255, 255, 255, 40], + [200, 200, 200, 100, 200, 200, 200, 240, 255, 255, 255, 255], + [200, 200, 200, 100, 200, 200, 200, 240, 200, 200, 255, 255], + [200, 200, 200, 200, 200, 40, 200, 240, 240, 100, 255, 255], + [200, 40, 255, 255, 255, 40, 200, 255, 200, 200, 255, 255], + [200, 200, 200, 200, 200, 200, 200, 255, 255, 255, 255, 255], + ], + dtype=np.uint8, + ) + + # expected area closing with area 2 + expected_2 = np.array( + [ + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [240, 200, 200, 240, 240, 240, 200, 200, 240, 240, 200, 240], + [240, 200, 200, 240, 240, 240, 240, 240, 240, 240, 200, 240], + [240, 240, 240, 240, 240, 240, 100, 100, 240, 240, 200, 240], + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [200, 200, 200, 200, 200, 200, 200, 240, 200, 200, 255, 255], + [200, 255, 200, 200, 200, 255, 200, 240, 255, 255, 255, 255], + [200, 200, 200, 100, 200, 200, 200, 240, 255, 255, 255, 255], + [200, 200, 200, 100, 200, 200, 200, 240, 200, 200, 255, 255], + [200, 200, 200, 200, 200, 40, 200, 240, 240, 200, 255, 255], + [200, 200, 255, 255, 255, 40, 200, 255, 200, 200, 255, 255], + [200, 200, 200, 200, 200, 200, 200, 255, 255, 255, 255, 255], + ], + dtype=np.uint8, + ) + + # expected diameter closing with diameter 4 + expected_4 = np.array( + [ + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [240, 200, 200, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [240, 200, 200, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240], + [200, 200, 200, 200, 200, 200, 200, 240, 240, 240, 255, 255], + [200, 255, 200, 200, 200, 255, 200, 240, 255, 255, 255, 255], + [200, 200, 200, 200, 200, 200, 200, 240, 255, 255, 255, 255], + [200, 200, 200, 200, 200, 200, 200, 240, 200, 200, 255, 255], + [200, 200, 200, 200, 200, 200, 200, 240, 240, 200, 255, 255], + [200, 200, 255, 255, 255, 200, 200, 255, 200, 200, 255, 255], + [200, 200, 200, 200, 200, 200, 200, 255, 255, 255, 255, 255], + ], + dtype=np.uint8, + ) + + # _full_type_test makes a test with many image types. + _full_type_test(img, 2, expected_2, area_closing, connectivity=2) + _full_type_test(img, 4, expected_4, area_closing, connectivity=2) + + P, S = max_tree(invert(img), connectivity=2) + _full_type_test(img, 4, expected_4, area_closing, parent=P, tree_traverser=S) + + def test_area_opening(self): + "Test for Area Opening (2 thresholds, all types)" + + # original image + img = np.array( + [ + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [15, 55, 55, 15, 55, 15, 55, 55, 15, 15, 55, 15], + [15, 55, 215, 15, 15, 15, 15, 15, 15, 15, 215, 15], + [15, 15, 15, 15, 155, 15, 155, 155, 15, 15, 55, 15], + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [55, 55, 55, 55, 55, 55, 55, 15, 55, 55, 0, 0], + [55, 0, 55, 55, 55, 0, 55, 15, 0, 0, 0, 215], + [55, 55, 55, 155, 55, 55, 55, 15, 0, 0, 0, 0], + [55, 55, 55, 155, 55, 55, 55, 15, 55, 55, 0, 0], + [55, 55, 55, 55, 55, 215, 55, 15, 15, 155, 0, 0], + [55, 215, 0, 0, 0, 215, 55, 0, 55, 55, 0, 0], + [55, 55, 55, 55, 55, 55, 55, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + # expected area closing with area 2 + expected_2 = np.array( + [ + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [15, 55, 55, 15, 15, 15, 55, 55, 15, 15, 55, 15], + [15, 55, 55, 15, 15, 15, 15, 15, 15, 15, 55, 15], + [15, 15, 15, 15, 15, 15, 155, 155, 15, 15, 55, 15], + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [55, 55, 55, 55, 55, 55, 55, 15, 55, 55, 0, 0], + [55, 0, 55, 55, 55, 0, 55, 15, 0, 0, 0, 0], + [55, 55, 55, 155, 55, 55, 55, 15, 0, 0, 0, 0], + [55, 55, 55, 155, 55, 55, 55, 15, 55, 55, 0, 0], + [55, 55, 55, 55, 55, 215, 55, 15, 15, 55, 0, 0], + [55, 55, 0, 0, 0, 215, 55, 0, 55, 55, 0, 0], + [55, 55, 55, 55, 55, 55, 55, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + # expected diameter closing with diameter 4 + expected_4 = np.array( + [ + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [15, 55, 55, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [15, 55, 55, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15], + [55, 55, 55, 55, 55, 55, 55, 15, 15, 15, 0, 0], + [55, 0, 55, 55, 55, 0, 55, 15, 0, 0, 0, 0], + [55, 55, 55, 55, 55, 55, 55, 15, 0, 0, 0, 0], + [55, 55, 55, 55, 55, 55, 55, 15, 55, 55, 0, 0], + [55, 55, 55, 55, 55, 55, 55, 15, 15, 55, 0, 0], + [55, 55, 0, 0, 0, 55, 55, 0, 55, 55, 0, 0], + [55, 55, 55, 55, 55, 55, 55, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + # _full_type_test makes a test with many image types. + _full_type_test(img, 2, expected_2, area_opening, connectivity=2) + _full_type_test(img, 4, expected_4, area_opening, connectivity=2) + + P, S = max_tree(img, connectivity=2) + _full_type_test(img, 4, expected_4, area_opening, parent=P, tree_traverser=S) + + def test_diameter_closing(self): + "Test for Diameter Opening (2 thresholds, all types)" + img = np.array( + [ + [97, 95, 93, 92, 91, 90, 90, 90, 91, 92, 93, 95], + [95, 93, 91, 89, 88, 88, 88, 88, 88, 89, 91, 93], + [93, 63, 63, 63, 63, 86, 86, 86, 87, 43, 43, 91], + [92, 89, 88, 86, 85, 85, 84, 85, 85, 43, 43, 89], + [91, 88, 87, 85, 84, 84, 83, 84, 84, 85, 87, 88], + [90, 88, 86, 85, 84, 83, 83, 83, 84, 85, 86, 88], + [90, 88, 86, 84, 83, 83, 82, 83, 83, 84, 86, 88], + [90, 88, 86, 85, 84, 83, 83, 83, 84, 85, 86, 88], + [91, 88, 87, 85, 84, 84, 83, 84, 84, 85, 87, 88], + [92, 89, 23, 23, 85, 85, 84, 85, 85, 3, 3, 89], + [93, 91, 23, 23, 87, 86, 86, 86, 87, 88, 3, 91], + [95, 93, 91, 89, 88, 88, 88, 88, 88, 89, 91, 93], + ], + dtype=np.uint8, + ) + + ex2 = np.array( + [ + [97, 95, 93, 92, 91, 90, 90, 90, 91, 92, 93, 95], + [95, 93, 91, 89, 88, 88, 88, 88, 88, 89, 91, 93], + [93, 63, 63, 63, 63, 86, 86, 86, 87, 43, 43, 91], + [92, 89, 88, 86, 85, 85, 84, 85, 85, 43, 43, 89], + [91, 88, 87, 85, 84, 84, 83, 84, 84, 85, 87, 88], + [90, 88, 86, 85, 84, 83, 83, 83, 84, 85, 86, 88], + [90, 88, 86, 84, 83, 83, 83, 83, 83, 84, 86, 88], + [90, 88, 86, 85, 84, 83, 83, 83, 84, 85, 86, 88], + [91, 88, 87, 85, 84, 84, 83, 84, 84, 85, 87, 88], + [92, 89, 23, 23, 85, 85, 84, 85, 85, 3, 3, 89], + [93, 91, 23, 23, 87, 86, 86, 86, 87, 88, 3, 91], + [95, 93, 91, 89, 88, 88, 88, 88, 88, 89, 91, 93], + ], + dtype=np.uint8, + ) + + ex4 = np.array( + [ + [97, 95, 93, 92, 91, 90, 90, 90, 91, 92, 93, 95], + [95, 93, 91, 89, 88, 88, 88, 88, 88, 89, 91, 93], + [93, 63, 63, 63, 63, 86, 86, 86, 87, 84, 84, 91], + [92, 89, 88, 86, 85, 85, 84, 85, 85, 84, 84, 89], + [91, 88, 87, 85, 84, 84, 83, 84, 84, 85, 87, 88], + [90, 88, 86, 85, 84, 83, 83, 83, 84, 85, 86, 88], + [90, 88, 86, 84, 83, 83, 83, 83, 83, 84, 86, 88], + [90, 88, 86, 85, 84, 83, 83, 83, 84, 85, 86, 88], + [91, 88, 87, 85, 84, 84, 83, 84, 84, 85, 87, 88], + [92, 89, 84, 84, 85, 85, 84, 85, 85, 84, 84, 89], + [93, 91, 84, 84, 87, 86, 86, 86, 87, 88, 84, 91], + [95, 93, 91, 89, 88, 88, 88, 88, 88, 89, 91, 93], + ], + dtype=np.uint8, + ) + + # _full_type_test makes a test with many image types. + _full_type_test(img, 2, ex2, diameter_closing, connectivity=2) + _full_type_test(img, 4, ex4, diameter_closing, connectivity=2) + + P, S = max_tree(invert(img), connectivity=2) + _full_type_test(img, 4, ex4, diameter_opening, parent=P, tree_traverser=S) + + def test_diameter_opening(self): + "Test for Diameter Opening (2 thresholds, all types)" + img = np.array( + [ + [5, 7, 9, 11, 12, 12, 12, 12, 12, 11, 9, 7], + [7, 10, 11, 13, 14, 14, 15, 14, 14, 13, 11, 10], + [9, 40, 40, 40, 40, 16, 16, 16, 16, 60, 60, 11], + [11, 13, 15, 16, 17, 18, 18, 18, 17, 60, 60, 13], + [12, 14, 16, 17, 18, 19, 19, 19, 18, 17, 16, 14], + [12, 14, 16, 18, 19, 19, 19, 19, 19, 18, 16, 14], + [12, 15, 16, 18, 19, 19, 20, 19, 19, 18, 16, 15], + [12, 14, 16, 18, 19, 19, 19, 19, 19, 18, 16, 14], + [12, 14, 16, 17, 18, 19, 19, 19, 18, 17, 16, 14], + [11, 13, 80, 80, 17, 18, 18, 18, 17, 100, 100, 13], + [9, 11, 80, 80, 16, 16, 16, 16, 16, 15, 100, 11], + [7, 10, 11, 13, 14, 14, 15, 14, 14, 13, 11, 10], + ] + ) + + ex2 = np.array( + [ + [5, 7, 9, 11, 12, 12, 12, 12, 12, 11, 9, 7], + [7, 10, 11, 13, 14, 14, 15, 14, 14, 13, 11, 10], + [9, 40, 40, 40, 40, 16, 16, 16, 16, 60, 60, 11], + [11, 13, 15, 16, 17, 18, 18, 18, 17, 60, 60, 13], + [12, 14, 16, 17, 18, 19, 19, 19, 18, 17, 16, 14], + [12, 14, 16, 18, 19, 19, 19, 19, 19, 18, 16, 14], + [12, 15, 16, 18, 19, 19, 19, 19, 19, 18, 16, 15], + [12, 14, 16, 18, 19, 19, 19, 19, 19, 18, 16, 14], + [12, 14, 16, 17, 18, 19, 19, 19, 18, 17, 16, 14], + [11, 13, 80, 80, 17, 18, 18, 18, 17, 100, 100, 13], + [9, 11, 80, 80, 16, 16, 16, 16, 16, 15, 100, 11], + [7, 10, 11, 13, 14, 14, 15, 14, 14, 13, 11, 10], + ] + ) + + ex4 = np.array( + [ + [5, 7, 9, 11, 12, 12, 12, 12, 12, 11, 9, 7], + [7, 10, 11, 13, 14, 14, 15, 14, 14, 13, 11, 10], + [9, 40, 40, 40, 40, 16, 16, 16, 16, 18, 18, 11], + [11, 13, 15, 16, 17, 18, 18, 18, 17, 18, 18, 13], + [12, 14, 16, 17, 18, 19, 19, 19, 18, 17, 16, 14], + [12, 14, 16, 18, 19, 19, 19, 19, 19, 18, 16, 14], + [12, 15, 16, 18, 19, 19, 19, 19, 19, 18, 16, 15], + [12, 14, 16, 18, 19, 19, 19, 19, 19, 18, 16, 14], + [12, 14, 16, 17, 18, 19, 19, 19, 18, 17, 16, 14], + [11, 13, 18, 18, 17, 18, 18, 18, 17, 18, 18, 13], + [9, 11, 18, 18, 16, 16, 16, 16, 16, 15, 18, 11], + [7, 10, 11, 13, 14, 14, 15, 14, 14, 13, 11, 10], + ] + ) + + # _full_type_test makes a test with many image types. + _full_type_test(img, 2, ex2, diameter_opening, connectivity=2) + _full_type_test(img, 4, ex4, diameter_opening, connectivity=2) + + P, S = max_tree(img, connectivity=2) + _full_type_test(img, 4, ex4, diameter_opening, parent=P, tree_traverser=S) + + def test_local_maxima(self): + "local maxima for various data types" + data = np.array( + [ + [10, 11, 13, 14, 14, 15, 14, 14, 13, 11], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + [13, 15, 40, 40, 18, 18, 18, 60, 60, 15], + [14, 16, 40, 40, 19, 19, 19, 60, 60, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [15, 16, 18, 19, 19, 20, 19, 19, 18, 16], + [14, 16, 18, 19, 19, 19, 19, 19, 18, 16], + [14, 16, 80, 80, 19, 19, 19, 100, 100, 16], + [13, 15, 80, 80, 18, 18, 18, 100, 100, 15], + [11, 13, 15, 16, 16, 16, 16, 16, 15, 13], + ], + dtype=np.uint8, + ) + expected_result = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint64, + ) + for dtype in [np.uint8, np.uint64, np.int8, np.int64]: + test_data = data.astype(dtype) + out = max_tree_local_maxima(test_data, connectivity=1) + out_bin = out > 0 + assert_array_equal(expected_result, out_bin) + assert out.dtype == expected_result.dtype + assert np.max(out) == 5 + + P, S = max_tree(test_data) + out = max_tree_local_maxima(test_data, parent=P, tree_traverser=S) + + assert_array_equal(expected_result, out_bin) + + assert out.dtype == expected_result.dtype + assert np.max(out) == 5 + + def test_extrema_float(self): + "specific tests for float type" + data = np.array( + [ + [0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14, 0.14, 0.13, 0.11], + [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13], + [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18, 0.60, 0.60, 0.15], + [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19, 0.60, 0.60, 0.16], + [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16], + [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19, 0.19, 0.18, 0.16], + [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16], + [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19, 4.0, 1.0, 0.16], + [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18, 1.0, 1.0, 0.15], + [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13], + ], + dtype=np.float32, + ) + + expected_result = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.uint8, + ) + + # test for local maxima + out = max_tree_local_maxima(data, connectivity=1) + out_bin = out > 0 + assert_array_equal(expected_result, out_bin) + assert np.max(out) == 6 + + def test_3d(self): + """tests the detection of maxima in 3D.""" + img = np.zeros((8, 8, 8), dtype=np.uint8) + local_maxima = np.zeros((8, 8, 8), dtype=np.uint64) + + # first maximum: only one pixel + img[1, 1:3, 1:3] = 100 + img[2, 2, 2] = 200 + img[3, 1:3, 1:3] = 100 + local_maxima[2, 2, 2] = 1 + + # second maximum: three pixels in z-direction + img[5:8, 1, 1] = 200 + local_maxima[5:8, 1, 1] = 1 + + # third: two maxima in 0 and 3. + img[0, 5:8, 5:8] = 200 + img[1, 6, 6] = 100 + img[2, 5:7, 5:7] = 200 + img[0:3, 5:8, 5:8] += 50 + local_maxima[0, 5:8, 5:8] = 1 + local_maxima[2, 5:7, 5:7] = 1 + + # four : one maximum in the corner of the square + img[6:8, 6:8, 6:8] = 200 + img[7, 7, 7] = 255 + local_maxima[7, 7, 7] = 1 + + out = max_tree_local_maxima(img) + out_bin = out > 0 + assert_array_equal(local_maxima, out_bin) + assert np.max(out) == 5 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_misc.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..82d68ca1aa1468dd804f4ecd603b3c7e70e6bafb --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_misc.py @@ -0,0 +1,521 @@ +import numpy as np +import pytest +import scipy as sp + +from skimage.morphology import ( + remove_small_objects, + remove_small_holes, + remove_objects_by_distance, + local_maxima, + label, +) + +from skimage._shared import testing +from skimage._shared.testing import assert_array_equal, assert_equal +from skimage._shared._warnings import expected_warnings + + +test_image = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 1]], bool) + +# Dtypes supported by the `label_image` parameter in `remove_objects_by_distance` +supported_dtypes = [ + np.uint8, + np.uint16, + np.uint32, + np.int8, + np.int16, + np.int32, + np.int64, +] + + +def test_one_connectivity(): + expected = np.array([[0, 0, 0, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], bool) + observed = remove_small_objects(test_image, min_size=6) + assert_array_equal(observed, expected) + + +def test_two_connectivity(): + expected = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], bool) + observed = remove_small_objects(test_image, min_size=7, connectivity=2) + assert_array_equal(observed, expected) + + +def test_in_place(): + image = test_image.copy() + observed = remove_small_objects(image, min_size=6, out=image) + assert_equal( + observed is image, True, "remove_small_objects in_place argument failed." + ) + + +@pytest.mark.parametrize("in_dtype", [bool, int, np.int32]) +@pytest.mark.parametrize("out_dtype", [bool, int, np.int32]) +def test_out(in_dtype, out_dtype): + image = test_image.astype(in_dtype, copy=True) + expected_out = np.empty_like(test_image, dtype=out_dtype) + + if out_dtype != bool: + # object with only 1 label will warn on non-bool output dtype + exp_warn = ["Only one label was provided"] + else: + exp_warn = [] + + with expected_warnings(exp_warn): + out = remove_small_objects(image, min_size=6, out=expected_out) + + assert out is expected_out + + +def test_labeled_image(): + labeled_image = np.array( + [[2, 2, 2, 0, 1], [2, 2, 2, 0, 1], [2, 0, 0, 0, 0], [0, 0, 3, 3, 3]], dtype=int + ) + expected = np.array( + [[2, 2, 2, 0, 0], [2, 2, 2, 0, 0], [2, 0, 0, 0, 0], [0, 0, 3, 3, 3]], dtype=int + ) + observed = remove_small_objects(labeled_image, min_size=3) + assert_array_equal(observed, expected) + + +def test_uint_image(): + labeled_image = np.array( + [[2, 2, 2, 0, 1], [2, 2, 2, 0, 1], [2, 0, 0, 0, 0], [0, 0, 3, 3, 3]], + dtype=np.uint8, + ) + expected = np.array( + [[2, 2, 2, 0, 0], [2, 2, 2, 0, 0], [2, 0, 0, 0, 0], [0, 0, 3, 3, 3]], + dtype=np.uint8, + ) + observed = remove_small_objects(labeled_image, min_size=3) + assert_array_equal(observed, expected) + + +def test_single_label_warning(): + image = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], int) + with expected_warnings(['use a boolean array?']): + remove_small_objects(image, min_size=6) + + +def test_float_input(): + float_test = np.random.rand(5, 5) + with testing.raises(TypeError): + remove_small_objects(float_test) + + +def test_negative_input(): + negative_int = np.random.randint(-4, -1, size=(5, 5)) + with testing.raises(ValueError): + remove_small_objects(negative_int) + + +test_holes_image = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + ], + bool, +) + + +def test_one_connectivity_holes(): + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + ], + bool, + ) + observed = remove_small_holes(test_holes_image, area_threshold=3) + assert_array_equal(observed, expected) + + +def test_two_connectivity_holes(): + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + ], + bool, + ) + observed = remove_small_holes(test_holes_image, area_threshold=3, connectivity=2) + assert_array_equal(observed, expected) + + +def test_in_place_holes(): + image = test_holes_image.copy() + observed = remove_small_holes(image, area_threshold=3, out=image) + assert_equal( + observed is image, True, "remove_small_holes in_place argument failed." + ) + + +def test_out_remove_small_holes(): + image = test_holes_image.copy() + expected_out = np.empty_like(image) + out = remove_small_holes(image, area_threshold=3, out=expected_out) + + assert out is expected_out + + +def test_non_bool_out(): + image = test_holes_image.copy() + expected_out = np.empty_like(image, dtype=int) + with testing.raises(TypeError): + remove_small_holes(image, area_threshold=3, out=expected_out) + + +def test_labeled_image_holes(): + labeled_holes_image = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + [0, 0, 0, 0, 0, 0, 0, 2, 0, 2], + [0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + ], + dtype=int, + ) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + ], + dtype=bool, + ) + with expected_warnings(['returned as a boolean array']): + observed = remove_small_holes(labeled_holes_image, area_threshold=3) + assert_array_equal(observed, expected) + + +def test_uint_image_holes(): + labeled_holes_image = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + [0, 0, 0, 0, 0, 0, 0, 2, 0, 2], + [0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + ], + dtype=np.uint8, + ) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + ], + dtype=bool, + ) + with expected_warnings(['returned as a boolean array']): + observed = remove_small_holes(labeled_holes_image, area_threshold=3) + assert_array_equal(observed, expected) + + +def test_label_warning_holes(): + labeled_holes_image = np.array( + [ + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + [0, 0, 0, 0, 0, 0, 0, 2, 0, 2], + [0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + ], + dtype=int, + ) + with expected_warnings(['use a boolean array?']): + remove_small_holes(labeled_holes_image, area_threshold=3) + remove_small_holes(labeled_holes_image.astype(bool), area_threshold=3) + + +def test_float_input_holes(): + float_test = np.random.rand(5, 5) + with testing.raises(TypeError): + remove_small_holes(float_test) + + +class Test_remove_near_objects: + @pytest.mark.parametrize("min_distance", [2.1, 5, 30.99, 49]) + @pytest.mark.parametrize("dtype", supported_dtypes) + def test_min_distance_1d(self, min_distance, dtype): + # First 3 objects are only just to close, last one is just far enough + d = int(np.floor(min_distance)) + labels = np.zeros(d * 3 + 2, dtype=dtype) + labels[[0, d, 2 * d, 3 * d + 1]] = 1 + labels, _ = sp.ndimage.label(labels, output=dtype) + desired = labels.copy() + desired[d] = 0 + + result = remove_objects_by_distance(labels, min_distance) + assert result.dtype == desired.dtype + assert_array_equal(result, desired) + + @pytest.mark.parametrize("dtype", supported_dtypes) + @pytest.mark.parametrize("order", ["C", "F"]) + def test_handcrafted_2d(self, dtype, order): + label = np.array( + [ + [8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 3, 0, 0, 0, 5, 0, 0, 0, 0], + [2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7], + ], + dtype=dtype, + order=order, + ) + priority = np.arange(10) + desired = np.array( + [ + [8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7], + ], + dtype=dtype, + ) + result = remove_objects_by_distance(label, 3, priority=priority) + assert result.flags["C_CONTIGUOUS"] + assert_array_equal(result, desired) + + @pytest.mark.parametrize("ndim", [1, 2, 3, 4, 5]) + def test_large_objects_nd(self, ndim): + shape = (5,) * ndim + a = np.ones(shape, dtype=np.uint8) + a[-2, ...] = 0 + labels, _ = sp.ndimage.label(a) + desired = labels.copy() + desired[-2:, ...] = 0 + + result = remove_objects_by_distance(labels, 2) + assert_array_equal(result, desired) + + @pytest.mark.parametrize("distance", [5, 50, 100]) + @pytest.mark.parametrize("p_norm", [1, 2, np.inf]) + def test_random(self, distance, p_norm): + rng = np.random.default_rng(1713648513) + image = rng.random(size=(400, 400)) + maxima = local_maxima(image) + objects = label(maxima) + + spaced_objects = remove_objects_by_distance(objects, distance, p_norm=p_norm) + kdtree = sp.spatial.cKDTree( + np.array(np.nonzero(spaced_objects), dtype=np.float64).transpose(), + ) + + # Compute distance between all objects that are equal or smaller `distance` + distances = kdtree.sparse_distance_matrix( + kdtree, max_distance=distance, p=p_norm + ) + # There should be no objects left + assert distances.count_nonzero() == 0 + + # But increasing by 1 should reveal a few objects + distances = kdtree.sparse_distance_matrix( + kdtree, max_distance=distance + 1, p=p_norm + ) + assert distances.count_nonzero() > 0 + + @pytest.mark.parametrize("value", [0, 1]) + @pytest.mark.parametrize("dtype", supported_dtypes) + def test_constant(self, value, dtype): + labels = np.empty((10, 10), dtype=dtype) + labels.fill(value) + + result = remove_objects_by_distance(labels, 3) + assert_array_equal(labels, result) + + def test_empty(self): + labels = np.empty((3, 3, 0), dtype=int) + result = remove_objects_by_distance(labels, 3) + assert_equal(labels, result) + + def test_priority(self): + labels = np.array([0, 1, 4, 1]) + + # Object with more samples takes precedence + result = remove_objects_by_distance(labels, 3) + desired = np.array([0, 1, 0, 1]) + assert_array_equal(result, desired) + + # Assigning priority with equal values, sorts by higher label ID second + priority = np.array([0, 1, 1, 1, 1]) + result = remove_objects_by_distance(labels, 3, priority=priority) + desired = np.array([0, 0, 4, 0]) + assert_array_equal(result, desired) + + # But given a different priority that order can be overruled + priority = np.array([0, 1, 1, 1, -1]) + result = remove_objects_by_distance(labels, 3, priority=priority) + desired = np.array([0, 1, 0, 1]) + assert_array_equal(result, desired) + + @pytest.mark.parametrize("order", ["C", "F"]) + def test_out(self, order): + labels_original = np.array([[1, 0, 2], [1, 0, 2]], order=order) + desired = np.array([[0, 0, 2], [0, 0, 2]], order=order) + + # By default, input image is not modified + labels = labels_original.copy(order=order) + remove_objects_by_distance(labels, 2) + assert_array_equal(labels, labels_original) + + # But modified if passed to `out` + remove_objects_by_distance(labels, 2, out=labels) + assert labels.flags[f"{order}_CONTIGUOUS"] + assert_array_equal(labels, desired) + + @pytest.mark.parametrize("min_distance", [-10, -0.1]) + def test_negative_min_distance(self, min_distance): + labels = np.array([1, 0, 2]) + with pytest.raises(ValueError, match="must be >= 0"): + remove_objects_by_distance(labels, min_distance) + + def test_p_norm(self): + labels = np.array([[2, 0], [0, 1]]) + removed = np.array([[2, 0], [0, 0]]) + + # p_norm=2, default (Euclidean distance) + result = remove_objects_by_distance(labels, 1.4) + assert_array_equal(result, labels) + result = remove_objects_by_distance(labels, np.sqrt(2)) + assert_array_equal(result, removed) + + # p_norm=1 (Manhatten distance) + result = remove_objects_by_distance( + labels, + min_distance=1.9, + p_norm=1, + ) + assert_array_equal(result, labels) + result = remove_objects_by_distance(labels, 2, p_norm=1) + assert_array_equal(result, removed) + + # p_norm=np.inf (Chebyshev distance) + result = remove_objects_by_distance(labels, 0.9, p_norm=np.inf) + assert_array_equal(result, labels) + result = remove_objects_by_distance(labels, 1, p_norm=np.inf) + assert_array_equal(result, removed) + + @pytest.mark.parametrize( + "shape", + [ + (0,), + ], + ) + def test_priority_shape(self, shape): + remove_objects_by_distance(np.array([0, 0, 0]), 3, priority=np.ones((0,))) + remove_objects_by_distance(np.array([0, 0, 0]), 3, priority=np.ones((1,))) + + error_msg = r"shape of `priority` must be \(np\.amax\(label_image\) \+ 1,\)" + with pytest.raises(ValueError, match=error_msg): + remove_objects_by_distance(np.array([1, 0, 0]), 3, priority=np.ones((0,))) + with pytest.raises(ValueError, match=error_msg): + remove_objects_by_distance(np.array([1, 0, 0]), 3, priority=np.ones((1,))) + with pytest.raises(ValueError, match=error_msg): + remove_objects_by_distance(np.array([1, 0, 0]), 3, priority=np.ones((1,))) + + def test_negative_label_ids(self): + labels = np.array( + [ + [1, 1, -1, 2, 2, 2], + [1, 1, 3, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [3, 3, 3, 3, 3, 3], + ] + ) + with pytest.raises(ValueError, match=".*object with negative ID"): + remove_objects_by_distance(labels, 1, priority=np.ones(4)) + + def test_objects_with_inside(self): + labels = np.array( + [ + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [3, 3, 3, 3, 3, 3], + ] + ) + desired = np.array( + [ + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [3, 3, 3, 3, 3, 3], + ] + ) + result = remove_objects_by_distance(labels, 1, priority=np.arange(4)) + assert_array_equal(result, desired) + + def test_spacing(self): + labels = np.array( + [[1, 0, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 0, 4]], dtype=int + ) + + # Stretch second dimension + result = remove_objects_by_distance(labels, 3, spacing=(1, 3)) + expected = np.array( + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 0, 4]], dtype=int + ) + np.testing.assert_array_equal(result, expected) + + # Compress second dimension + result = remove_objects_by_distance(labels, 1, spacing=(1, 1 / 3)) + expected = np.array( + [[0, 0, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 4]], dtype=int + ) + np.testing.assert_array_equal(result, expected) + + @pytest.mark.parametrize("spacing", [(-1, -1), (1,), (1, 1, 1), [[1, 1]], 1]) + def test_spacing_raises(self, spacing): + labels = np.array( + [[1, 0, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 0, 4]], dtype=int + ) + regex = ".*must contain exactly one positive factor for each dimension" + with pytest.raises(ValueError, match=regex): + remove_objects_by_distance(labels, 3, spacing=spacing) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_reconstruction.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_reconstruction.py new file mode 100644 index 0000000000000000000000000000000000000000..5a69020ed8aa9670012bbadf83e0e716a733b151 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_reconstruction.py @@ -0,0 +1,190 @@ +import math +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal + +from skimage._shared.utils import _supported_float_type +from skimage.morphology.grayreconstruct import reconstruction + + +def test_zeros(): + """Test reconstruction with image and mask of zeros""" + assert_array_almost_equal(reconstruction(np.zeros((5, 7)), np.zeros((5, 7))), 0) + + +def test_image_equals_mask(): + """Test reconstruction where the image and mask are the same""" + assert_array_almost_equal(reconstruction(np.ones((7, 5)), np.ones((7, 5))), 1) + + +def test_image_less_than_mask(): + """Test reconstruction where the image is uniform and less than mask""" + image = np.ones((5, 5)) + mask = np.ones((5, 5)) * 2 + assert_array_almost_equal(reconstruction(image, mask), 1) + + +def test_one_image_peak(): + """Test reconstruction with one peak pixel""" + image = np.ones((5, 5)) + image[2, 2] = 2 + mask = np.ones((5, 5)) * 3 + assert_array_almost_equal(reconstruction(image, mask), 2) + + +# minsize chosen to test sizes covering use of 8, 16 and 32-bit integers +# internally +@pytest.mark.parametrize('minsize', [None, 200, 20000, 40000, 80000]) +@pytest.mark.parametrize('dtype', [np.uint8, np.float32]) +def test_two_image_peaks(minsize, dtype): + """Test reconstruction with two peak pixels isolated by the mask""" + image = np.array( + [ + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 2, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 3, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + dtype=dtype, + ) + + mask = np.array( + [ + [4, 4, 4, 1, 1, 1, 1, 1, 1], + [4, 4, 4, 1, 1, 1, 1, 1, 1], + [4, 4, 4, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 4, 4, 4, 1], + [1, 1, 1, 1, 1, 4, 4, 4, 1], + [1, 1, 1, 1, 1, 4, 4, 4, 1], + ], + dtype=dtype, + ) + + expected = np.array( + [ + [2, 2, 2, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 3, 3, 3, 1], + [1, 1, 1, 1, 1, 3, 3, 3, 1], + [1, 1, 1, 1, 1, 3, 3, 3, 1], + ], + dtype=dtype, + ) + if minsize is not None: + # increase data size by tiling (done to test various int types) + nrow = math.ceil(math.sqrt(minsize / image.size)) + ncol = math.ceil(minsize / (image.size * nrow)) + image = np.tile(image, (nrow, ncol)) + mask = np.tile(mask, (nrow, ncol)) + expected = np.tile(expected, (nrow, ncol)) + out = reconstruction(image, mask) + assert out.dtype == _supported_float_type(mask.dtype) + assert_array_almost_equal(out, expected) + + +def test_zero_image_one_mask(): + """Test reconstruction with an image of all zeros and a mask that's not""" + result = reconstruction(np.zeros((10, 10)), np.ones((10, 10))) + assert_array_almost_equal(result, 0) + + +@pytest.mark.parametrize( + 'dtype', + [ + np.int8, + np.uint8, + np.int16, + np.uint16, + np.int32, + np.uint32, + np.int64, + np.uint64, + np.float16, + np.float32, + np.float64, + ], +) +def test_fill_hole(dtype): + """Test reconstruction by erosion, which should fill holes in mask.""" + seed = np.array([0, 8, 8, 8, 8, 8, 8, 8, 8, 0], dtype=dtype) + mask = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0], dtype=dtype) + result = reconstruction(seed, mask, method='erosion') + assert result.dtype == _supported_float_type(mask.dtype) + expected = np.array([0, 3, 6, 4, 4, 4, 4, 4, 2, 0], dtype=dtype) + assert_array_almost_equal(result, expected) + + +def test_invalid_seed(): + seed = np.ones((5, 5)) + mask = np.ones((5, 5)) + with pytest.raises(ValueError): + reconstruction(seed * 2, mask, method='dilation') + with pytest.raises(ValueError): + reconstruction(seed * 0.5, mask, method='erosion') + + +def test_invalid_footprint(): + seed = np.ones((5, 5)) + mask = np.ones((5, 5)) + with pytest.raises(ValueError): + reconstruction(seed, mask, footprint=np.ones((4, 4))) + with pytest.raises(ValueError): + reconstruction(seed, mask, footprint=np.ones((3, 4))) + reconstruction(seed, mask, footprint=np.ones((3, 3))) + + +def test_invalid_method(): + seed = np.array([0, 8, 8, 8, 8, 8, 8, 8, 8, 0]) + mask = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0]) + with pytest.raises(ValueError): + reconstruction(seed, mask, method='foo') + + +def test_invalid_offset_not_none(): + """Test reconstruction with invalid not None offset parameter""" + image = np.array( + [ + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 2, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 3, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + ] + ) + + mask = np.array( + [ + [4, 4, 4, 1, 1, 1, 1, 1], + [4, 4, 4, 1, 1, 1, 1, 1], + [4, 4, 4, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 4, 4, 4], + [1, 1, 1, 1, 1, 4, 4, 4], + [1, 1, 1, 1, 1, 4, 4, 4], + ] + ) + with pytest.raises(ValueError): + reconstruction( + image, + mask, + method='dilation', + footprint=np.ones((3, 3)), + offset=np.array([3, 0]), + ) + + +def test_offset_not_none(): + """Test reconstruction with valid offset parameter""" + seed = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0]) + mask = np.array([0, 8, 6, 8, 8, 8, 8, 4, 4, 0]) + expected = np.array([0, 3, 6, 6, 6, 6, 6, 4, 4, 0]) + + assert_array_almost_equal( + reconstruction( + seed, mask, method='dilation', footprint=np.ones(3), offset=np.array([0]) + ), + expected, + ) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_skeletonize.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_skeletonize.py new file mode 100644 index 0000000000000000000000000000000000000000..17b84e3eb183b42f40b2503b52e56b2d8d88d95a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_skeletonize.py @@ -0,0 +1,368 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal +import scipy.ndimage as ndi + +from skimage import io, draw +from skimage._shared.testing import fetch +from skimage.data import binary_blobs +from skimage.morphology import medial_axis, skeletonize, thin +from skimage.morphology._skeletonize import G123_LUT, G123P_LUT, _generate_thin_luts + + +class TestSkeletonize: + @pytest.mark.parametrize("method", ["zhang", "lee"]) + def test_no_foreground(self, method): + image = np.zeros((5, 5)) + result = skeletonize(image, method=method) + assert_array_equal(result, np.zeros((5, 5))) + + @pytest.mark.parametrize( + "ndim,method", [(1, "zhang"), (3, "zhang"), (1, "lee"), (4, "lee")] + ) + def test_wrong_ndim(self, ndim, method): + image = np.zeros((5,) * ndim, dtype=bool) + with pytest.raises(ValueError): + skeletonize(image, method=method) + + def test_wrong_method(self): + image = np.ones((5, 5), dtype=bool) + with pytest.raises(ValueError): + skeletonize(image, method="foo") + + @pytest.mark.parametrize("method", ["zhang", "lee"]) + def test_skeletonize_all_foreground(self, method): + image = np.ones((3, 4), dtype=bool) + result = skeletonize(image, method=method) + if method == "zhang": + expected = np.array([[0, 0, 1, 0], [1, 1, 0, 0], [0, 0, 0, 0]], dtype=bool) + else: # "lee" + expected = np.array([[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]], dtype=bool) + assert_array_equal(result, expected) + + @pytest.mark.parametrize("method", ["zhang", "lee"]) + def test_single_point(self, method): + image = np.zeros((5, 5), dtype=bool) + image[3, 3] = 1 + result = skeletonize(image, method=method) + assert_array_equal(result, image) + + @pytest.mark.parametrize("method", ["zhang", "lee"]) + def test_vec_1d(self, method): + # Corner case of a 2D image, which is a 1D vector + image = np.ones((5, 1), dtype=bool) + result = skeletonize(image, method=method) + assert_array_equal(result, image) + + @pytest.mark.parametrize("method", ["zhang", "lee"]) + def test_already_thinned(self, method): + image = np.array( + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 1, 1, 1, 0], + [1, 0, 0, 0, 0], + ], + dtype=bool, + ) + result = skeletonize(image, method=method) + assert_array_equal(result, image) + + def test_output(self): + image = io.imread(fetch("data/bw_text.png"), as_gray=True) + + # make black the foreground + image = image == 0 + result = skeletonize(image) + + expected = np.load(fetch("data/bw_text_skeleton.npy")) + assert_array_equal(result, expected) + + @pytest.mark.parametrize("method", ["zhang", "lee"]) + @pytest.mark.parametrize("dtype", [bool, float, int]) + def test_num_neighbors(self, method, dtype): + # an empty image + image = np.zeros((300, 300), dtype=dtype) + + # foreground object 1 + image[10:-10, 10:100] = 1 + image[-100:-10, 10:-10] = 2 + image[10:-10, -100:-10] = 3 + + # foreground object 2 + rs, cs = draw.line(250, 150, 10, 280) + for i in range(10): + image[rs + i, cs] = 4 + rs, cs = draw.line(10, 150, 250, 280) + for i in range(20): + image[rs + i, cs] = 5 + + # foreground object 3 + ir, ic = np.indices(image.shape) + circle1 = (ic - 135) ** 2 + (ir - 150) ** 2 < 30**2 + circle2 = (ic - 135) ** 2 + (ir - 150) ** 2 < 20**2 + image[circle1] = 1 + image[circle2] = 0 + result = skeletonize(image, method=method).astype(np.uint8) + + # there should never be a 2x2 block of foreground pixels in a skeleton + mask = np.array([[1, 1], [1, 1]], np.uint8) + blocks = ndi.correlate(result, mask, mode="constant") + assert not np.any(blocks == 4) + + def test_lut_fix(self): + image = np.array( + [ + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + result = skeletonize(image) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + assert np.all(result == expected) + + @pytest.mark.parametrize("ndim,method", [(2, "zhang"), (2, "lee"), (3, "lee")]) + @pytest.mark.parametrize("dtype", [bool, np.uint8]) + def test_input_not_modified(self, method, ndim, dtype): + # Skeletonize must not modify the input image + image = np.ones((3,) * ndim, dtype=dtype) + image = np.pad(image, 1) + original = image.copy() + _ = skeletonize(image, method=method) + np.testing.assert_array_equal(image, original) + + @pytest.mark.parametrize("method", ["zhang", "lee"]) + def test_input_float_conv(self, method): + # Check that the floats are correctly handled. Also check non-contiguous input + image = np.random.random((16, 16))[::2, ::2] + image[image < 0.5] = 0.0 + + original = image.copy() + result = skeletonize(image, method=method) + + assert result.dtype == bool + assert_array_equal(image, original) + + def test_two_hole_image_vs_fiji(self): + # Test a simple 2D image against FIJI + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + result = skeletonize(image, method="lee") + assert_array_equal(result, expected) + + def test_3d_vs_fiji(self): + # Generate an image with blobs and compare its skeleton + # to the one generated by FIJI (Plugins>Skeleton->Skeletonize) + image = binary_blobs(32, 0.05, n_dim=3, rng=1234) + image = image[:-2, ...] + + result = skeletonize(image) + expected = io.imread(fetch("data/_blobs_3d_fiji_skeleton.tif")).astype(bool) + assert_array_equal(result, expected) + + +class TestThin: + @property + def input_image(self): + # Image to test thinning with + ii = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 2, 3, 4, 5, 0], + [0, 1, 0, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 6, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + dtype=float, + ) + return ii + + def test_all_zeros(self): + image = np.zeros((10, 10), dtype=bool) + assert np.all(thin(image) == False) + + @pytest.mark.parametrize("dtype", [bool, float, int]) + def test_thin_copies_input(self, dtype): + """Ensure thinning does not modify the input image.""" + image = self.input_image.astype(dtype) + original = image.copy() + thin(image) + np.testing.assert_array_equal(image, original) + + @pytest.mark.parametrize("dtype", [bool, float, int]) + def test_iter_1(self, dtype): + image = self.input_image.astype(dtype) + result = thin(image, 1).astype(bool) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 1, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + assert_array_equal(result, expected) + + @pytest.mark.parametrize("dtype", [bool, float, int]) + def test_noiter(self, dtype): + image = self.input_image.astype(dtype) + result = thin(image).astype(bool) + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 1, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + assert_array_equal(result, expected) + + def test_baddim(self): + for ii in [np.zeros(3, dtype=bool), np.zeros((3, 3, 3), dtype=bool)]: + with pytest.raises(ValueError): + thin(ii) + + def test_lut_generation(self): + g123, g123p = _generate_thin_luts() + + assert_array_equal(g123, G123_LUT) + assert_array_equal(g123p, G123P_LUT) + + +class TestMedialAxis: + def test_all_zeros(self): + result = medial_axis(np.zeros((10, 10), dtype=bool)) + assert np.all(result == False) + + def test_all_zeros_masked(self): + result = medial_axis( + np.zeros((10, 10), dtype=bool), np.zeros((10, 10), dtype=bool) + ) + assert np.all(result == False) + + @pytest.mark.parametrize("dtype", [bool, float, int]) + def test_vertical_line(self, dtype): + # Image is a thick vertical line (see gh-3861) + image = np.zeros((9, 9), dtype=dtype) + image[:, 2] = 1 + image[:, 3] = 2 + image[:, 4] = 3 + + expected = np.full(image.shape, False) + expected[:, 3] = True + + result = medial_axis(image) + assert_array_equal(result, expected) + + def test_rectangle(self): + image = np.zeros((9, 15), dtype=bool) + image[1:-1, 1:-1] = True + # Excepted are four diagonals from the corners, meeting in a horizontal line + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + result = medial_axis(image) + assert np.all(result == expected) + result, distance = medial_axis(image, return_distance=True) + assert distance.max() == 4 + + def test_rectange_with_hole(self): + image = np.zeros((9, 15), dtype=bool) + image[1:-1, 1:-1] = True + image[4, 4:-4] = False + expected = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=bool, + ) + result = medial_axis(image) + assert np.all(result == expected) + + def test_narrow_image(self): + # Image is a 1-pixel thin strip + image = np.zeros((1, 5), dtype=bool) + image[:, 1:-1] = True + result = medial_axis(image) + assert np.all(result == image) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_util.py b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..1d50dcdec2c0c466a29db381d71c33a44450ba4f --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/morphology/tests/test_util.py @@ -0,0 +1,221 @@ +"""Tests for `_util`.""" + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from skimage.morphology import _util + + +@pytest.mark.parametrize("image_shape", [(111,), (33, 44), (22, 55, 11), (6, 5, 4, 3)]) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_offsets_to_raveled_neighbors_highest_connectivity(image_shape, order): + """ + Check scenarios where footprint is always of the highest connectivity + and all dimensions are > 2. + """ + footprint = np.ones((3,) * len(image_shape), dtype=bool) + center = (1,) * len(image_shape) + offsets = _util._offsets_to_raveled_neighbors(image_shape, footprint, center, order) + + # Assert only neighbors are present, center was removed + assert len(offsets) == footprint.sum() - 1 + assert 0 not in offsets + # Assert uniqueness + assert len(set(offsets)) == offsets.size + # offsets form pairs of with same value but different signs + # if footprint is symmetric around center + assert all(-x in offsets for x in offsets) + + # Construct image whose values are the Manhattan distance to its center + image_center = tuple(s // 2 for s in image_shape) + coords = [ + np.abs(np.arange(s, dtype=np.intp) - c) + for s, c in zip(image_shape, image_center) + ] + grid = np.meshgrid(*coords, indexing="ij") + image = np.sum(grid, axis=0) + + image_raveled = image.ravel(order) + image_center_raveled = np.ravel_multi_index(image_center, image_shape, order=order) + + # Sample raveled image around its center + samples = [] + for offset in offsets: + index = image_center_raveled + offset + samples.append(image_raveled[index]) + + # Assert that center with value 0 wasn't selected + assert np.min(samples) == 1 + # Assert that only neighbors where selected + # (highest value == connectivity) + assert np.max(samples) == len(image_shape) + # Assert that nearest neighbors are selected first + assert list(sorted(samples)) == samples + + +@pytest.mark.parametrize( + "image_shape", [(2,), (2, 2), (2, 1, 2), (2, 2, 1, 2), (0, 2, 1, 2)] +) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_offsets_to_raveled_neighbors_footprint_smaller_image(image_shape, order): + """ + Test if a dimension indicated by `image_shape` is smaller than in + `footprint`. + """ + footprint = np.ones((3,) * len(image_shape), dtype=bool) + center = (1,) * len(image_shape) + offsets = _util._offsets_to_raveled_neighbors(image_shape, footprint, center, order) + + # Assert only neighbors are present, center and duplicates (possible + # for this scenario) where removed + assert len(offsets) <= footprint.sum() - 1 + assert 0 not in offsets + # Assert uniqueness + assert len(set(offsets)) == offsets.size + # offsets form pairs of with same value but different signs + # if footprint is symmetric around center + assert all(-x in offsets for x in offsets) + + +def test_offsets_to_raveled_neighbors_explicit_0(): + """Check reviewed example.""" + image_shape = (100, 200, 3) + footprint = np.ones((3, 3, 3), dtype=bool) + center = (1, 1, 1) + offsets = _util._offsets_to_raveled_neighbors(image_shape, footprint, center) + + desired = np.array( + [ + -600, + -3, + -1, + 1, + 3, + 600, + -603, + -601, + -599, + -597, + -4, + -2, + 2, + 4, + 597, + 599, + 601, + 603, + -604, + -602, + -598, + -596, + 596, + 598, + 602, + 604, + ] + ) + assert_array_equal(offsets, desired) + + +def test_offsets_to_raveled_neighbors_explicit_1(): + """Check reviewed example where footprint is larger in last dimension.""" + image_shape = (10, 9, 8, 3) + footprint = np.ones((3, 3, 3, 4), dtype=bool) + center = (1, 1, 1, 1) + offsets = _util._offsets_to_raveled_neighbors(image_shape, footprint, center) + + desired = np.array( + [ + -216, + -24, + -3, + -1, + 1, + 3, + 24, + 216, + -240, + -219, + -217, + -215, + -213, + -192, + -27, + -25, + -23, + -21, + -4, + -2, + 2, + 4, + 21, + 23, + 25, + 27, + 192, + 213, + 215, + 217, + 219, + 240, + -243, + -241, + -239, + -237, + -220, + -218, + -214, + -212, + -195, + -193, + -191, + -189, + -28, + -26, + -22, + -20, + 20, + 22, + 26, + 28, + 189, + 191, + 193, + 195, + 212, + 214, + 218, + 220, + 237, + 239, + 241, + 243, + -244, + -242, + -238, + -236, + -196, + -194, + -190, + -188, + 188, + 190, + 194, + 196, + 236, + 238, + 242, + 244, + 5, + -211, + -19, + 29, + 221, + -235, + -187, + 197, + 245, + ] + ) + assert_array_equal(offsets, desired)