diff --git a/.gitattributes b/.gitattributes index 40af7e00ac1f93f9c5eb3728a95bdf0135c897a7..86cb55fad37ec8edf2cb46416f7634e50f365e6a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1208,3 +1208,6 @@ vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/core_cy_3d.cpython-31 llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/lowering.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/core_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text llava_next/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text +vlmpy310/lib/python3.10/site-packages/skimage/feature/_canny_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/bilateral_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.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/pruning/_experimental/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6eff7b10f9216da76d18b14d3e440c252aff14f Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c785a8bd310590f579e0576c896fae7ee72aa4f Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7a6f98e2d12628c6095c761d936b35f0ec891d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py @@ -0,0 +1,5 @@ +from .base_data_scheduler import BaseDataScheduler + +__all__ = [ + "BaseDataScheduler", +] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83bfd0b34796284fa819b9029cc0400ebffee603 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3d8e25623c72913ab0b937e16f0a543f4d9a854 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4060f95435b6a4a57bc38b4d7943e482a47a87 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py @@ -0,0 +1,180 @@ +from functools import wraps +import weakref +import abc +import warnings + +from ..data_sparsifier import BaseDataSparsifier + +__all__ = ['BaseDataScheduler'] + + +class BaseDataScheduler: + r""" + The BaseDataScheduler is the abstract scheduler class specifically for the + BaseDataSparsifier class. This class controls a specific hyperparameter of + the sparsifier class and varies it across the training process (or across time). + + Args: + data_sparsifier (instance of BaseDataSparsifier) + Implemented class data sparsifier class wherein the update_mask is implemented + schedule_param (str) + A specific hyperparameter of the passed sparsifier that needs to be scheduled/varied + last_epoch (int, default=-1) + This is specifically is passed when training needs to be resumed from a particular + point. + verbose (bool, default=False) + Verbosity of the BaseDataScheduler + + The *get_hyperparam()* function needs to be implemented by the user. + """ + def __init__(self, data_sparsifier, schedule_param: str, last_epoch=-1, verbose=False): + # Attach sparsifier + if not isinstance(data_sparsifier, BaseDataSparsifier): + raise TypeError('{} is not an instance of torch.ao.pruning.BaseDataSparsifier'.format( + type(data_sparsifier).__name__)) + self.data_sparsifier = data_sparsifier + self.schedule_param = schedule_param + + # Initialize epoch and base hyper-params + self.base_param = { + name: config.get(schedule_param, None) + for name, config in self.data_sparsifier.data_groups.items() + } + + self.last_epoch = last_epoch + + # Following https://github.com/pytorch/pytorch/issues/20124 + # We would like to ensure that `scheduler.step()` is called after + # `sparsifier.step()` + def with_counter(method): + if getattr(method, '_with_counter', False): + # `sparsifier.step()` has already been replaced, return. + return method + + # Keep a weak reference to the sparsifier instance to prevent + # cyclic references. + instance_ref = weakref.ref(method.__self__) + # Get the unbound method for the same purpose. + func = method.__func__ + cls = instance_ref().__class__ + del method + + @wraps(func) + def wrapper(*args, **kwargs): + instance = instance_ref() + instance._step_count += 1 # type: ignore[union-attr] + wrapped = func.__get__(instance, cls) + return wrapped(*args, **kwargs) + + # Note that the returned function here is no longer a bound method, + # so attributes like `__func__` and `__self__` no longer exist. + wrapper._with_counter = True # type: ignore[attr-defined] + return wrapper + + self.data_sparsifier.step = with_counter(self.data_sparsifier.step) # type: ignore[assignment] + self.data_sparsifier._step_count = 0 # type: ignore[attr-defined] + self._step_count: int = 0 + self.verbose = verbose + + # Housekeeping + self._get_sp_called_within_step: bool = False # sp -> schedule parameter + self.step() + + @abc.abstractmethod + def get_schedule_param(self): + r""" + Abstract method that needs to be implemented by the child class. + The expected return type should is a dictionary of name to schedule_param value + The returned values will be updated in sparsifier when the scheduler step() function + is called. + + Example: + >>> def get_schedule_param(self): + ... new_param = {} + ... for name in self.sparsifier.data_groups.keys(): + ... new_param[name] = self.sparsifier.data_groups[name][self.schedule_param] * 0.5 + ... return new_param + + When the step() function is called, the value in self.sparsifier.data_groups[name][self.schedule_param] + would be halved + """ + raise NotImplementedError + + def __repr__(self): + format_string = self.__class__.__name__ + ' (' + format_string += '\n' + format_string += f'Data Sparsifier {self.data_sparsifier}\n' + format_string += f' {self.schedule_param}: {self.base_param}\n' + format_string += ')' + return format_string + + def state_dict(self): + """Returns the state of the scheduler as a :class:`dict`. + + It contains an entry for every variable in self.__dict__ which + is not the sparsifier. + + Note: + The scheduler class does not track the state of the data_sparsifier. + Make sure to store the state of the sparsifier before storing the + state of the scheduler + """ + return {key: value for key, value in self.__dict__.items() if key != 'data_sparsifier'} + + def load_state_dict(self, state_dict): + """Loads the schedulers state. + + Note: + Remember to restore the state of the data_sparsifier before the scheduler. + + Args: + state_dict (dict): scheduler state. Should be an object returned + from a call to :meth:`state_dict`. + """ + self.__dict__.update(state_dict) + + def get_last_param(self): + return self._last_param + + def step(self): + # Raise warning if trying to call scheduler step before the sparsifier. + # https://github.com/pytorch/pytorch/issues/20124 + if self._step_count == 1: + if not hasattr(self.data_sparsifier.step, "_with_counter"): + warnings.warn("Seems like `data_sparsifier.step()` has been overridden after sparsity scheduler " + "initialization. Please, make sure to call `data_sparsifier.step()` before " + "`scheduler.step()`.", UserWarning) + + # Just check if there were two first scheduler.step() calls before sparsifier.step() + elif self.data_sparsifier._step_count < 1: # type: ignore[attr-defined] + warnings.warn("Detected call of `scheduler.step()` before `data_sparsifier.step()`. " + "You have to make sure you run the data_sparsifier.step() BEFORE any " + "calls to the scheduler.step().", UserWarning) + self._step_count += 1 + + class _enable_get_sp_call: + + def __init__(self, o): + self.o = o + + def __enter__(self): + self.o._get_sp_called_within_step = True + return self + + def __exit__(self, type, value, traceback): + self.o._get_sp_called_within_step = False + + with _enable_get_sp_call(self): + self.last_epoch += 1 + updated_scheduler_params = self.get_schedule_param() + + for name, param in updated_scheduler_params.items(): + self.data_sparsifier.data_groups[name][self.schedule_param] = param + if self.verbose: + print(f"Adjusting {self.schedule_param} for group {name} to {param}") + + self._last_param = { + name: config.get(self.schedule_param, None) + for name, config in self.data_sparsifier.data_groups.items() + } + self.data_sparsifier.enable_mask_update = True diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f3c80aecf8baf9c74351a669540a70700bded88 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98b43898ee50ae696eb6b2b0da0d92be086ba593 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f0ab218a78fa1711709348e0a029ecf8b0a181a Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15d25c9fef028af3f444f140344a33f15563a5b6 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py new file mode 100644 index 0000000000000000000000000000000000000000..28f32bbabe1760a54798401b8cf5232cc5faa28a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py @@ -0,0 +1,152 @@ +import torch +from torch.nn import functional as F +from functools import reduce +from typing import Any, List, Optional, Tuple + +from .base_data_sparsifier import BaseDataSparsifier + +__all__ = ['DataNormSparsifier'] + + +class DataNormSparsifier(BaseDataSparsifier): + r"""L1-Norm Sparsifier + This sparsifier computes the *L1-norm* of every sparse block and "zeroes-out" the + ones with the lowest norm. The level of sparsity defines how many of the + blocks is removed. + This sparsifier is controlled by three variables: + 1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out + 2. `sparse_block_shape` defines the shape of the sparse blocks. Note that + the sparse blocks originate at the zero-index of the tensor. + 3. `zeros_per_block` is the number of zeros that we are expecting in each + sparse block. By default we assume that all elements within a block are + zeroed-out. However, setting this variable sets the target number of + zeros per block. The zeros within each block are chosen as the *smallest + absolute values*. + Args: + sparsity_level: The target level of sparsity + sparse_block_shape: The shape of a sparse block + zeros_per_block: Number of zeros in a sparse block + Note:: + All arguments to the DataNormSparsifier constructor are "default" + arguments and could be overriden by the configuration provided in the + `add_data` step. + """ + def __init__(self, data_list: Optional[List[Tuple[str, Any]]] = None, sparsity_level: float = 0.5, + sparse_block_shape: Tuple[int, int] = (1, 4), + zeros_per_block: Optional[int] = None, norm: str = 'L1'): + if zeros_per_block is None: + zeros_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + + assert norm in ['L1', 'L2'], "only L1 and L2 norm supported at the moment" + + defaults = {'sparsity_level': sparsity_level, 'sparse_block_shape': sparse_block_shape, + 'zeros_per_block': zeros_per_block} + self.norm = norm + super().__init__(data_list=data_list, **defaults) + + def __get_scatter_folded_mask(self, data, dim, indices, output_size, sparse_block_shape): + mask = torch.ones_like(data) + mask.scatter_(dim=dim, index=indices, value=0) # zeroing out + mask = F.fold(mask, output_size=output_size, kernel_size=sparse_block_shape, + stride=sparse_block_shape) + mask = mask.to(torch.int8) + return mask + + def __get_block_level_mask(self, data, + sparse_block_shape, zeros_per_block): + + # Assume data is a squeezed tensor + height, width = data.shape[-2], data.shape[-1] + block_height, block_width = sparse_block_shape + values_per_block = block_height * block_width + + # just return zeros if zeroing all elements in block + if values_per_block == zeros_per_block: + return torch.zeros_like(data, dtype=torch.int8) + + # creating additional height and width to support padding + dh = (block_height - height % block_height) % block_height + dw = (block_width - width % block_width) % block_width + + # create a new padded tensor like data (to match the block_shape) + padded_data = torch.ones(height + dh, width + dw, dtype=data.dtype, device=data.device) + padded_data = padded_data * torch.nan # can also be replaced with 0 to stop the removal of edge data + padded_data[0:height, 0:width] = data + unfolded_data = F.unfold(padded_data[None, None, :], kernel_size=sparse_block_shape, + stride=sparse_block_shape) + + _, sorted_idx = torch.sort(unfolded_data, dim=1) + sorted_idx = sorted_idx[:, :zeros_per_block, :] # zero out zeros_per_block number of elements + + mask = self.__get_scatter_folded_mask(data=unfolded_data, dim=1, indices=sorted_idx, output_size=padded_data.shape, + sparse_block_shape=sparse_block_shape) + + mask = mask.squeeze(0).squeeze(0)[:height, :width].contiguous() # remove padding and make contiguous + return mask + + def __get_data_level_mask(self, data, sparsity_level, + sparse_block_shape): + + height, width = data.shape[-2], data.shape[-1] + block_height, block_width = sparse_block_shape + dh = (block_height - height % block_height) % block_height + dw = (block_width - width % block_width) % block_width + + data_norm = F.avg_pool2d(data[None, None, :], kernel_size=sparse_block_shape, + stride=sparse_block_shape, ceil_mode=True) + + values_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + + data_norm = data_norm.flatten() + num_blocks = len(data_norm) + + data_norm = data_norm.repeat(1, values_per_block, 1) # get similar shape after unfold + _, sorted_idx = torch.sort(data_norm, dim=2) + + threshold_idx = round(sparsity_level * num_blocks) # number of blocks to remove + sorted_idx = sorted_idx[:, :, :threshold_idx] + + mask = self.__get_scatter_folded_mask(data=data_norm, dim=2, indices=sorted_idx, + output_size=(height + dh, width + dw), + sparse_block_shape=sparse_block_shape) + + mask = mask.squeeze(0).squeeze(0)[:height, :width] # squeeze only the first 2 dimension + return mask + + def update_mask(self, name, data, sparsity_level, + sparse_block_shape, zeros_per_block, **kwargs): + + values_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + if zeros_per_block > values_per_block: + raise ValueError("Number of zeros per block cannot be more than " + "the total number of elements in that block.") + if zeros_per_block < 0: + raise ValueError("Number of zeros per block should be positive.") + + if self.norm == 'L1': + data_norm = torch.abs(data).squeeze() # absolute value based (L1) + else: + data_norm = (data * data).squeeze() # square every element for L2 + + if len(data_norm.shape) > 2: # only supports 2 dimensional data at the moment + raise ValueError("only supports 2-D at the moment") + + elif len(data_norm.shape) == 1: # in case the data is bias (or 1D) + data_norm = data_norm[None, :] + + mask = self.get_mask(name) + if sparsity_level <= 0 or zeros_per_block == 0: + mask.data = torch.ones_like(mask) + elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block): + mask.data = torch.zeros_like(mask) + + # Fetch the high level mask that zeros out entire blocks + data_lvl_mask = self.__get_data_level_mask(data=data_norm, sparsity_level=sparsity_level, + sparse_block_shape=sparse_block_shape) + + # Fetch block level mask that zeros out 'zeros_per_block' number of elements in every block + block_lvl_mask = self.__get_block_level_mask(data=data_norm, sparse_block_shape=sparse_block_shape, + zeros_per_block=zeros_per_block) + + # zero out the entries inside those blocks whose block is sparsified + mask.data = torch.where(data_lvl_mask == 1, data_lvl_mask, block_lvl_mask) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c345a8e3804788cb766f8d200625cda36d098097 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc922536abbc998d551bf2ea9b681eb9aa32ffe2 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22bae96e51d3d59d14f5e106b3db78785fb8d695 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..922c81322cfe4245dacc9f827d2aa97e675661da --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py @@ -0,0 +1,39 @@ +import logging +from torch.ao.pruning._experimental.data_sparsifier.base_data_sparsifier import SUPPORTED_TYPES + +logger: logging.Logger = logging.getLogger(__name__) + + +def _attach_model_to_data_sparsifier(module, data_sparsifier, config=None): + """Attaches a data sparsifier to all the layers of the module. + Essentially, loop over all the weight parameters in the module and + attach it to the data sparsifier. + Note:: + The '.' in the layer names are replaced with '_' (refer to _get_valid_name() below) + before attaching to the sparsifier. This is because, the data + sparsifier uses a dummy model inside to store the weight parameters. + """ + if config is None: + config = {} + for name, parameter in module.named_parameters(): + if type(parameter) in SUPPORTED_TYPES: + valid_name = _get_valid_name(name) + # will be defaulted to default configs + data_sparsifier.add_data(name=valid_name, data=parameter, **config.get(valid_name, {})) + + +def _get_valid_name(name): + return name.replace('.', '_') # . is not allowed as a name + + +def _log_sparsified_level(model, data_sparsifier) -> None: + # Show the level of sparsity AFTER step: + for name, parameter in model.named_parameters(): + if type(parameter) not in SUPPORTED_TYPES: + continue + valid_name = _get_valid_name(name) + mask = data_sparsifier.get_mask(name=valid_name) + sparsity_level = 1.0 - mask.float().mean() + logger.info( + "Sparsity in layer %s = % .2%", name, sparsity_level + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py new file mode 100644 index 0000000000000000000000000000000000000000..c36c35bcf5241a21f542cb52fd5134ce869c7a74 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py @@ -0,0 +1,165 @@ +from collections import defaultdict +from copy import deepcopy +import torch +from typing import Any, Optional, Dict +import pytorch_lightning as pl # type: ignore[import] + +from ._data_sparstity_utils import ( + _attach_model_to_data_sparsifier, + _log_sparsified_level, + _get_valid_name +) + + +class PostTrainingDataSparsity(pl.callbacks.Callback): + """Lightning callback that enables post-training sparsity. + + This callback aims to sparsify the model inside lightning module after training. + **Note that the model is copied and then sparsified, so the existing model is not modified** + + The sparsified model can be used for comparison and can be accessed using + .sparsified + + Args: + data_sparsifier_class (some implemented class of BaseDataSparsifier) + The data sparsifier object of this class is created when the + training starts. + Note: Objects should not be passed in here as they are created + once the training completes. + + data_sparsifier_args (Dict) + Dictionary of args to be passed to the data sparsifier. + Note: data_list arg should be ignored + + Hooks implemented: + on_fit_end() + 1. copies the model and attaches it to the sparsifier + 2. sparsier step() is called + 3. squashes the mask() + """ + def __init__(self, data_sparsifier_class, data_sparsifier_args): + super().__init__() + self.data_sparsifier_class = data_sparsifier_class + self.data_sparsifier_args = data_sparsifier_args + self.data_sparsifier: Any = None + self.sparsified: Optional[torch.nn.Module] = None + + def on_fit_end(self, trainer, pl_module) -> None: + self.sparsified = deepcopy(pl_module.model).eval() + self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args) + + _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier) + + self.data_sparsifier.step() + + self.data_sparsifier.squash_mask() # currently squashes params for all mask + + _log_sparsified_level(self.sparsified, self.data_sparsifier) + + +class TrainingAwareDataSparsity(pl.callbacks.Callback): + """Lightning callback that enables in-training sparsity. + + This callback aims to sparsify the model inside lightning module during training. + **Note that the model is copied and then sparsified, so the existing model is not modified** + + The sparsified model can be used for comparison and can be accessed using + .sparsified + + Args: + data_sparsifier_class (some implemented class of BaseDataSparsifier) + The data sparsifier object of this class is created when the + training starts. + Note: Objects should not be passed in here as they are created + when the training starts. + + data_sparsifier_args (Dict) + Dictionary of args to be passed to the data sparsifier. + Note: data_list arg should be ignored + + data_scheduler_class (some implemented class of BaseDataScheduler) + The data scheduler of this class is created when the training starts + Note: Objects should not be passed in here as they are created + when the training starts. + + data_scheduler_args(Dict) + Dictionary of args to be passed to the data scheduler. + **Note: data_sparsifier arg should be ignored as the recipe + creates and pass sparsifier object into the class** + + Hooks implemented: + on_train_start() + Data sparsifier and scheduler objects are created. + Pytorch model attached to the sparsifier + + on_train_epoch_start() + Loads the state_dict of the data sparsifier + + on_train_epoch_end() + 1. Copies the model and attaches it to the sparsifier + 2. sparsifier step() and scheduler step() + 3. Dump state_dict of the current sparsifier + + on_train_end() + squash mask + """ + def __init__(self, data_sparsifier_class, data_sparsifier_args, + data_scheduler_class, data_scheduler_args): + super().__init__() + # data sparsifier objects + self.data_sparsifier_class = data_sparsifier_class + self.data_sparsifier_args = data_sparsifier_args + + # scheduler objects + self.data_scheduler_class = data_scheduler_class + self.data_scheduler_args = data_scheduler_args + + # fields + self.data_sparsifier: Any = None + self.data_scheduler: Any = None + self.sparsified: Optional[torch.nn.Module] = None + + self.data_sparsifier_state_dict: Any = None + + def on_train_start(self, trainer, pl_module) -> None: + # create sparsifier + self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args) + self.sparsified = deepcopy(pl_module.model) + + _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier) # just to populate the base_sl in the scheduler + + # create scheduler + args = deepcopy(self.data_scheduler_args) + args['data_sparsifier'] = self.data_sparsifier + self.data_scheduler = self.data_scheduler_class(**args) + + def on_train_epoch_start(self, trainer, pl_module): + if self.data_sparsifier_state_dict is None: + return # probably first epoch + + # load the existing config for each data + self.data_sparsifier.load_state_dict(self.data_sparsifier_state_dict) + + def __create_config_based_on_state(self, pl_module): + config: Dict = defaultdict() + if self.data_sparsifier_state_dict is None: + return config + for name, _ in pl_module.model.named_parameters(): + valid_name = _get_valid_name(name) + config[valid_name] = self.data_sparsifier.data_groups[valid_name] + + return config + + def on_train_epoch_end(self, trainer, pl_module): + self.sparsified = deepcopy(pl_module.model) + config = self.__create_config_based_on_state(pl_module) + + # attach model to the data sparsifier + _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier, config=config) + self.data_sparsifier.step() + self.data_scheduler.step() + + self.data_sparsifier_state_dict = self.data_sparsifier.state_dict() + + def on_train_end(self, trainer, pl_module): + self.data_sparsifier.squash_mask() diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c3d20052ba21e92502e5bc416df5621051c823 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py @@ -0,0 +1,93 @@ +from typing import Callable, Optional, Union + +import torch + +from .base_structured_sparsifier import BaseStructuredSparsifier + +__all__ = ["FPGMPruner"] + + +class FPGMPruner(BaseStructuredSparsifier): + r"""Filter Pruning via Geometric Median (FPGM) Structured Pruner + This sparsifier prune fliter (row) in a tensor according to distances among filters according to + `Filter Pruning via Geometric Median for Deep Convolutional Neural Networks Acceleration `_. + + This sparsifier is controlled by three variables: + 1. `sparsity_level` defines the number of filters (rows) that are zeroed-out. + 2. `dist` defines the distance measurement type. Default: 3 (L2 distance). + Available options are: [1, 2, (custom callable distance function)]. + + Note:: + Inputs should be a 4D convolutional tensor of shape (N, C, H, W). + - N: output channels size + - C: input channels size + - H: height of kernel + - W: width of kernel + """ + + def __init__( + self, sparsity_level: float = 0.5, dist: Optional[Union[Callable, int]] = None + ): + defaults = { + "sparsity_level": sparsity_level, + } + + if dist is None: + dist = 2 + + if callable(dist): + self.dist_fn = dist + elif dist == 1: + self.dist_fn = lambda x: torch.cdist(x, x, p=1) + elif dist == 2: + self.dist_fn = lambda x: torch.cdist(x, x, p=2) + else: + raise NotImplementedError("Distance function is not yet implemented.") + super().__init__(defaults=defaults) + + def _compute_distance(self, t): + r"""Compute distance across all entries in tensor `t` along all dimension + except for the one identified by dim. + Args: + t (torch.Tensor): tensor representing the parameter to prune + Returns: + distance (torch.Tensor): distance computed across filtters + """ + dim = 0 # prune filter (row) + + size = t.size(dim) + slc = [slice(None)] * t.dim() + + # flatten the tensor along the dimension + t_flatten = [ + t[tuple(slc[:dim] + [slice(i, i + 1)] + slc[dim + 1 :])].reshape(-1) + for i in range(size) + ] + t_flatten = torch.stack(t_flatten) + + # distance measurement + dist_matrix = self.dist_fn(t_flatten) + + # more similar with other filter indicates large in the sum of row + distance = torch.sum(torch.abs(dist_matrix), 1) + + return distance + + def update_mask(self, module, tensor_name, sparsity_level, **kwargs): + tensor_weight = getattr(module, tensor_name) + mask = getattr(module.parametrizations, tensor_name)[0].mask + + if sparsity_level <= 0: + mask.data = torch.ones_like(mask).bool() + elif sparsity_level >= 1.0: + mask.data = torch.zeros_like(mask).bool() + else: + distance = self._compute_distance(tensor_weight) + + tensor_size = tensor_weight.shape[0] # prune filter (row) + nparams_toprune = round(sparsity_level * tensor_size) + nparams_toprune = min( + max(nparams_toprune, 0), tensor_size + ) # clamp to [0, tensor_size] + topk = torch.topk(distance, k=nparams_toprune, largest=False) + mask[topk.indices] = False diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f017aa9e2e2c673909197d9424d95b196ff30c3 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py @@ -0,0 +1,8 @@ +from .base_structured_sparsifier import BaseStructuredSparsifier +from .parametrization import ( + FakeStructuredSparsity, + BiasHook, +) +from .saliency_pruner import SaliencyPruner +from .lstm_saliency_pruner import LSTMSaliencyPruner +from .FPGM_pruner import FPGMPruner diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db377c236dfb45cb8fc116d2b8ec63eadecbd72c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed9d30ae5d264b4bd69ea267a833c62d21d18ad3 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3e345b60c64e4703f2f619a2927a57805353614 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a10dc88781d023913cfa7f27439a799aebc96796 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24bf77c29e07cd953fefe27b72eaeb72a66d6313 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cca6c40a0e63abfa6715b5df23133783243344d3 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53f2350418fddb988201b9c6c7552d1891d6231c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aadebbc1cc508a599fc46d811c2470e749c1849a Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py new file mode 100644 index 0000000000000000000000000000000000000000..c9fa549dddc29880407881ec8092df425e4da716 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py @@ -0,0 +1,310 @@ +from itertools import chain +from operator import getitem +import torch +import torch.nn.functional as F +from torch import nn +from torch.fx import symbolic_trace +from torch.nn.utils import parametrize +from typing import Type, Set, Dict, Callable, Tuple, Optional, Union + +from torch.ao.pruning import BaseSparsifier +from .parametrization import FakeStructuredSparsity, BiasHook, module_contains_param +from .match_utils import apply_match, MatchAllNode +from .prune_functions import ( + prune_linear, + prune_linear_linear, + prune_linear_activation_linear, + prune_conv2d, + prune_conv2d_conv2d, + prune_conv2d_activation_conv2d, + prune_conv2d_activation_pool_conv2d, + prune_conv2d_pool_activation_conv2d, + prune_conv2d_pool_flatten_linear, + prune_lstm_output_linear, + prune_lstm_output_layernorm_linear, +) + + +def _get_supported_structured_pruning_modules(): + SUPPORTED_STRUCTURED_PRUNING_MODULES = { # added to config if None given + nn.Linear, + nn.Conv2d, + nn.LSTM, + } + return SUPPORTED_STRUCTURED_PRUNING_MODULES + + +def _get_supported_activation_functions(): + SUPPORTED_ACTIVATION_FUNCTIONS = { + F.relu, + F.rrelu, + F.hardtanh, + F.relu6, + F.sigmoid, + F.hardsigmoid, + F.tanh, + F.silu, + F.mish, + F.hardswish, + F.elu, + F.celu, + F.selu, + F.hardshrink, + F.leaky_relu, + F.logsigmoid, + F.softplus, + F.prelu, + F.softsign, + F.tanhshrink, + F.gelu, + } + return SUPPORTED_ACTIVATION_FUNCTIONS + + +def _get_supported_activation_modules(): + SUPPORTED_ACTIVATION_MODULES = { + nn.ReLU, + nn.RReLU, + nn.Hardtanh, + nn.ReLU6, + nn.Sigmoid, + nn.Hardsigmoid, + nn.Tanh, + nn.SiLU, + nn.Mish, + nn.Hardswish, + nn.ELU, + nn.CELU, + nn.SELU, + nn.Hardshrink, + nn.LeakyReLU, + nn.LogSigmoid, + nn.Softplus, + nn.PReLU, + nn.Softsign, + nn.Tanhshrink, + nn.GELU, + } + return SUPPORTED_ACTIVATION_MODULES + + +def _get_default_structured_pruning_patterns() -> Dict[ + Tuple[Union[Type[nn.Module], Callable, MatchAllNode, str], ...], + Callable[..., None], +]: + """ + Returns the patterns for conv2d / linear conversion for each element in the activation functions/modules defined above. + """ + patterns: Dict[ + Tuple[Union[Type[nn.Module], Callable, MatchAllNode, str], ...], + Callable[..., None], + ] = { + # linear -> linear + (nn.Linear, "output"): prune_linear, + (nn.Linear, nn.Linear): prune_linear_linear, + # conv2d -> conv2d + (nn.Conv2d, "output"): prune_conv2d, + (nn.Conv2d, nn.Conv2d): prune_conv2d_conv2d, + # TODO LSTM Structured pruning does not support returned state currently. + # Should find a way to explicitly match getitem(0) instead of getitem. + # This will also require changing the pruning function. + # lstm -> getitem(0) -> linear + (nn.LSTM, getitem, nn.Linear): prune_lstm_output_linear, + # lstm -> getitem(0) -> layernorm -> linear + (nn.LSTM, getitem, nn.LayerNorm, nn.Linear): prune_lstm_output_layernorm_linear, + } + + for activation in chain( + _get_supported_activation_functions(), _get_supported_activation_modules() + ): + patterns.update( + { + # linear -> activation -> linear + (nn.Linear, activation, nn.Linear): prune_linear_activation_linear, + # conv2d -> activation -> conv2d + (nn.Conv2d, activation, nn.Conv2d): prune_conv2d_activation_conv2d, + # conv2d -> activation -> pool -> conv2d + ( + nn.Conv2d, + activation, + nn.AvgPool2d, + nn.Conv2d, + ): prune_conv2d_activation_pool_conv2d, + ( + nn.Conv2d, + activation, + F.avg_pool2d, + nn.Conv2d, + ): prune_conv2d_activation_pool_conv2d, + ( + nn.Conv2d, + activation, + nn.MaxPool2d, + nn.Conv2d, + ): prune_conv2d_activation_pool_conv2d, + ( + nn.Conv2d, + activation, + F.max_pool2d, + nn.Conv2d, + ): prune_conv2d_activation_pool_conv2d, + # conv2d -> pool -> activation -> conv2d + ( + nn.Conv2d, + nn.AvgPool2d, + activation, + nn.Conv2d, + ): prune_conv2d_pool_activation_conv2d, + ( + nn.Conv2d, + F.avg_pool2d, + activation, + nn.Conv2d, + ): prune_conv2d_pool_activation_conv2d, + ( + nn.Conv2d, + nn.MaxPool2d, + activation, + nn.Conv2d, + ): prune_conv2d_pool_activation_conv2d, + ( + nn.Conv2d, + F.max_pool2d, + activation, + nn.Conv2d, + ): prune_conv2d_pool_activation_conv2d, + # conv2d -> adaptive pool -> flatten -> linear + ( + nn.Conv2d, + nn.AdaptiveAvgPool2d, + nn.Flatten, + nn.Linear, + ): prune_conv2d_pool_flatten_linear, + ( + nn.Conv2d, + nn.AdaptiveAvgPool2d, + torch.flatten, + nn.Linear, + ): prune_conv2d_pool_flatten_linear, + ( + nn.Conv2d, + nn.AdaptiveMaxPool2d, + nn.Flatten, + nn.Linear, + ): prune_conv2d_pool_flatten_linear, + ( + nn.Conv2d, + nn.AdaptiveMaxPool2d, + torch.flatten, + nn.Linear, + ): prune_conv2d_pool_flatten_linear, + } + ) + return patterns + + +class BaseStructuredSparsifier(BaseSparsifier): + r"""Base class for structured pruning. + + Abstract methods that need to be implemented: + - update_mask: Function to compute a new mask for all keys in the + `groups` attribute. + + Args: + - defaults [dict]: default configurations will be attached to the + configuration. Only the keys that don't exist in the `config` will + be updated. + """ + + def __init__(self, defaults, patterns=None): + super().__init__(defaults) + if patterns is None: + patterns = _get_default_structured_pruning_patterns() + self.patterns = patterns + + def make_config_from_model( + self, + model: nn.Module, + SUPPORTED_MODULES: Optional[Set[Type]] = None, + ) -> None: + if SUPPORTED_MODULES is None: + SUPPORTED_MODULES = _get_supported_structured_pruning_modules() + super().make_config_from_model(model, SUPPORTED_MODULES=SUPPORTED_MODULES) + + def _prepare(self, *args, **kwargs) -> None: + r"""This function will attach the FakeStructuredSparsity parameterizations + and BiasHooks at the appropriate points in the model. + """ + for config in self.groups: + module = config["module"] + tensor_name = config["tensor_name"] + parametrization = config.get("parametrization", FakeStructuredSparsity) + tensor = getattr(module, tensor_name) + + mask = config.get( + "mask", + torch.ones(tensor.shape[0], dtype=torch.bool, device=tensor.device), + ) + self.state[config["tensor_fqn"]]["mask"] = mask + parametrize.register_parametrization( + module, tensor_name, parametrization(mask) + ) + + # if linear / conv, we add in bias hooks + if isinstance(module, (nn.Linear, nn.Conv2d)): + prune_bias = config.get("prune_bias", True) + if module.bias is not None: + module.register_parameter( + "_bias", nn.Parameter(module.bias.detach()) + ) + module.bias = None + module.prune_bias = prune_bias + + module.register_forward_hook( + BiasHook(module.parametrizations.weight[0], prune_bias) + ) + + def prune(self) -> None: + r""" + This function will FX symbolically trace the model and then find instances of the patterns + defined in self.patterns (by default SUPPORTED_STRUCTURED_PRUNING_PATTERNS ). + + For each pattern, it will apply to corresponding conversion function, which will modify the output + and input size expected by the modules within the pattern + """ + + self.traced = symbolic_trace(self.model) + modules = dict(self.traced.named_modules()) + + # Right now we check for matches simply by iterating across all the patterns + # if this is slow we can store patterns in a trie-structure and modify this code for faster lookup + for node in self.traced.graph.nodes: + for pattern, convert_fn in self.patterns.items(): + matched = apply_match(modules, pattern, node, []) + if matched is None: + continue + + first_module = modules.get(node.target) + # check if first module exists and has appropriate parameterization, otherwise skip + if ( + first_module is not None + and parametrize.is_parametrized(first_module) + and module_contains_param(first_module, FakeStructuredSparsity) + ): + convert_block = [] + for node in matched: + if node.op == "call_module": + convert_block.append(modules.get(node.target)) + elif node.op == "call_function": + convert_block.append(node.target) + convert_fn(*convert_block) + + for module in self.traced.modules(): + if module_contains_param(module, FakeStructuredSparsity): + raise Exception( + f"Error: {module} still contains FakeStructuredSparsity parametrizations!" + ) + + self.traced.graph.lint() + self.traced.recompile() + return self.traced diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0d74d6dc933552fefd47e0e950749079a627fb --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py @@ -0,0 +1,48 @@ +from typing import cast + +import torch +from .base_structured_sparsifier import BaseStructuredSparsifier, FakeStructuredSparsity + +class LSTMSaliencyPruner(BaseStructuredSparsifier): + """ + Prune packed LSTM weights based on saliency. + For each layer {k} inside a LSTM, we have two packed weight matrices + - weight_ih_l{k} + - weight_hh_l{k} + + These tensors pack the weights for the 4 linear layers together for efficiency. + + [W_ii | W_if | W_ig | W_io] + + Pruning this tensor directly will lead to weights being misassigned when unpacked. + To ensure that each packed linear layer is pruned the same amount: + 1. We split the packed weight into the 4 constituent linear parts + 2. Update the mask for each individual piece using saliency individually + + This applies to both weight_ih_l{k} and weight_hh_l{k}. + """ + + def update_mask(self, module, tensor_name, **kwargs): + weights = getattr(module, tensor_name) + + for p in getattr(module.parametrizations, tensor_name): + if isinstance(p, FakeStructuredSparsity): + mask = cast(torch.Tensor, p.mask) + + # select weights based on magnitude + if weights.dim() <= 1: + raise Exception("Structured pruning can only be applied to a 2+dim weight tensor!") + # take norm over all but first dim + dims = tuple(range(1, weights.dim())) + saliency = weights.norm(dim=dims, p=1) + + # handle weights in 4 groups + split_size = len(mask) // 4 + masks = torch.split(mask, split_size) + saliencies = torch.split(saliency, split_size) + + for keep_mask, sal in zip(masks, saliencies): + # mask smallest k values to be removed + k = int(len(keep_mask) * kwargs["sparsity_level"]) + prune = sal.topk(k, largest=False, sorted=False).indices + keep_mask.data[prune] = False # modifies underlying p.mask directly diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f7a9f6293d9aa935eaf117377630e32386f5c1 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py @@ -0,0 +1,59 @@ +""" +Contains utility functions to check if a pattern is in the graph and return the matching nodes +""" +import torch +from torch import nn +from torch.ao.quantization.utils import ( + MatchAllNode, +) +from torch.fx import Node +from torch.nn.utils import parametrize +from typing import Any, Dict, List, Optional, Tuple, Union + +def _match(modules: Dict[str, nn.ModuleDict], node: Node, current: Union[nn.Module, Any]) -> bool: + r""" + checks to see if a single node of a pattern matches + """ + if isinstance(current, type) and issubclass(current, MatchAllNode): + return True + if not isinstance(node, Node): + return False + if isinstance(current, type) and issubclass(current, torch.nn.Module): + return ( + node.op == "call_module" + and parametrize.type_before_parametrizations(modules[node.target]) + == current + ) + elif callable(current): + return node.op == "call_function" and node.target is current + elif isinstance(current, str): + return node.target == current + return False + +def apply_match( + modules: Dict[str, nn.ModuleDict], + pattern: Union[Tuple[Any], Any], + node: Node, + matched_node_pattern: List[Node], +) -> Optional[List[Node]]: + r""" + This function will return the matched nodes if the pattern matches the node given + If there is no match, it will return None + """ + if isinstance(pattern, tuple): + if len(pattern) == 1: + if _match(modules, node, pattern[0]): + return matched_node_pattern + [node] + + first, *rest = pattern + if _match(modules, node, first): + if rest is None: + return matched_node_pattern + [node] + + for user in node.users: + return apply_match( + modules, tuple(rest), user, matched_node_pattern + [node] + ) + elif _match(modules, node, pattern): + return [node] + return None diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py new file mode 100644 index 0000000000000000000000000000000000000000..df94f7093b53db9dba9106a53b4bab0a2b9bb961 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py @@ -0,0 +1,59 @@ +import torch +from torch import nn +from torch.nn.utils.parametrize import is_parametrized + + +def module_contains_param(module, parametrization): + if is_parametrized(module): + # see if any of the module tensors have a parametriztion attached that matches the one passed in + return any( + any(isinstance(param, parametrization) for param in param_list) + for key, param_list in module.parametrizations.items() + ) + return False + + +# Structured Pruning Parameterizations +class FakeStructuredSparsity(nn.Module): + r""" + Parametrization for Structured Pruning. Like FakeSparsity, this should be attached to + the 'weight' or any other parameter that requires a mask. + + Instead of an element-wise bool mask, this parameterization uses a row-wise bool mask. + """ + + def __init__(self, mask): + super().__init__() + self.register_buffer("mask", mask) + + def forward(self, x): + assert isinstance(self.mask, torch.Tensor) + assert self.mask.shape[0] == x.shape[0] + shape = [1] * len(x.shape) + shape[0] = -1 + return self.mask.reshape(shape) * x + + def state_dict(self, *args, **kwargs): + # avoid double saving masks + return {} + + +class BiasHook: + def __init__(self, parametrization, prune_bias): + self.param = parametrization + self.prune_bias = prune_bias + + def __call__(self, module, input, output): + + if getattr(module, "_bias", None) is not None: + bias = module._bias.data + if self.prune_bias: + bias[~self.param.mask] = 0 + + # reshape bias to broadcast over output dimensions + idx = [1] * len(output.shape) + idx[1] = -1 + bias = bias.reshape(idx) + + output += bias + return output diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c94e0887adf43ca07ec7018d1b5e9703519da6 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py @@ -0,0 +1,475 @@ +""" +Collection of conversion functions for linear / conv2d structured pruning +Also contains utilities for bias propagation +""" +from typing import cast, Optional, Callable, Tuple + +import torch +from torch import nn, Tensor +from torch.nn.utils import parametrize +from torch.nn.utils.parametrize import ParametrizationList +from .parametrization import FakeStructuredSparsity, BiasHook + +# BIAS PROPAGATION +def _remove_bias_handles(module: nn.Module) -> None: + if hasattr(module, "_forward_hooks"): + bias_hooks = [] + for key, hook in module._forward_hooks.items(): + if isinstance(hook, BiasHook): + bias_hooks.append(key) + + for key in bias_hooks: + del module._forward_hooks[key] + + +def _get_adjusted_next_layer_bias( + next_layer: nn.Module, pruned_biases: Tensor, mask: Tensor +) -> nn.Parameter: + r"""Returns new adjusted bias for the second supported module""" + if parametrize.is_parametrized(next_layer): + # need to access original weight + parametrization_dict = cast(nn.ModuleDict, next_layer.parametrizations) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict.weight + ) + next_weight = weight_parameterizations.original + else: + next_weight = cast(Tensor, next_layer.weight) + + scaling_weight = next_weight[:, ~mask] + if isinstance(next_layer, nn.Conv2d): # checking for Conv2d + # Propagating first layer pruned biases and calculating the new second layer bias + # involves more steps since the Conv2d scaling weight has extra dimensions, + # so adding bias involves broadcasting, logically: + # for each channel k in range(oC): + # scaled_biases = sum(first_bias[pruned_idx] @ next_weight[k, pruned_idx, :, :].T) + # new_next_bias[k] = old_next_bias[k] + scaled_biases + scaling_product = torch.matmul( + pruned_biases.reshape(1, -1), torch.transpose(scaling_weight, 1, 2) + ) + sum_range = list(range(len(scaling_product.shape)))[ + 1: + ] # all but the first dimension + scaled_biases = torch.sum(scaling_product, sum_range) + elif isinstance(next_layer, nn.Linear): # Linear + scaled_biases = torch.matmul( + pruned_biases, torch.transpose(scaling_weight, 0, 1) + ) # recall b2_new = b1 @ w2.T + b2 + else: + raise NotImplementedError(f"Type {type(next_layer)} not supported yet.") + + if ( + parametrize.is_parametrized(next_layer) + and getattr(next_layer, "_bias", None) is not None + ): # next_layer is parametrized & has original bias ._bias + adjusted_bias = nn.Parameter(scaled_biases + next_layer._bias) + elif ( + not parametrize.is_parametrized(next_layer) and next_layer.bias is not None + ): # next_layer not parametrized & has .bias + adjusted_bias = nn.Parameter(scaled_biases + next_layer.bias) + else: # next_layer has no bias + adjusted_bias = nn.Parameter(scaled_biases) + return adjusted_bias + + +def _prune_module_bias(module: nn.Module, mask: Tensor) -> None: + r"""Applies mask to given modules bias""" + # prune bias along with weights, discard pruned indices of bias + original_bias = cast(Tensor, getattr(module, "_bias", module.bias)) + if original_bias is not None: + module.bias = nn.Parameter(original_bias[mask]) + + # remove _bias parameter + if hasattr(module, "_bias"): + delattr(module, "_bias") + + +def _propogate_module_bias(module: nn.Module, mask: Tensor) -> Optional[Tensor]: + r""" + In the case that we need to propagate biases, this function will return the biases we need + """ + # set current module bias + if module.bias is not None: + module.bias = nn.Parameter(cast(Tensor, module.bias)[mask]) + elif getattr(module, "_bias", None) is not None: + module.bias = nn.Parameter(cast(Tensor, module._bias)[mask]) + + # get pruned biases to propagate to subsequent layer + if getattr(module, "_bias", None) is not None: + pruned_biases = cast(Tensor, module._bias)[~mask] + else: + pruned_biases = None + + if hasattr(module, "_bias"): + delattr(module, "_bias") + + return pruned_biases + + +# LINEAR +def _prune_linear_helper(linear: nn.Linear) -> Tensor: + # expects linear to be a parameterized linear module + parametrization_dict = cast(nn.ModuleDict, linear.parametrizations) + weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) + for p in weight_parameterizations: + if isinstance(p, FakeStructuredSparsity): + mask = cast(Tensor, p.mask) + + with torch.no_grad(): + parametrize.remove_parametrizations(linear, "weight", leave_parametrized=True) + linear.weight = nn.Parameter(linear.weight[mask]) + linear.out_features = linear.weight.shape[0] + _remove_bias_handles(linear) + + return mask + + +def prune_linear(linear: nn.Linear) -> None: + mask = _prune_linear_helper(linear) + if getattr(linear, "prune_bias", False): + _prune_module_bias(linear, mask) + + +def prune_linear_linear(linear1: nn.Linear, linear2: nn.Linear) -> None: + prune_linear_activation_linear(linear1, None, linear2) + + +def prune_linear_activation_linear( + linear1: nn.Linear, + activation: Optional[Callable[[Tensor], Tensor]], + linear2: nn.Linear, +): + mask = _prune_linear_helper(linear1) + if getattr(linear1, "prune_bias", False): + _prune_module_bias(linear1, mask) + else: + pruned_biases = _propogate_module_bias(linear1, mask) + if pruned_biases is not None: + if activation: + pruned_biases = activation(pruned_biases) + linear2.bias = _get_adjusted_next_layer_bias(linear2, pruned_biases, mask) + + with torch.no_grad(): + if parametrize.is_parametrized(linear2): + parametrization_dict = cast(nn.ModuleDict, linear2.parametrizations) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict.weight + ) + + weight_parameterizations.original = nn.Parameter( + weight_parameterizations.original[:, mask] + ) + linear2.in_features = weight_parameterizations.original.shape[1] + else: + linear2.weight = nn.Parameter(linear2.weight[:, mask]) + linear2.in_features = linear2.weight.shape[1] + + +# CONV2D +def _prune_conv2d_helper(conv2d: nn.Conv2d) -> Tensor: + parametrization_dict = cast(nn.ModuleDict, conv2d.parametrizations) + weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) + for p in weight_parameterizations: + if isinstance(p, FakeStructuredSparsity): + mask = cast(Tensor, p.mask) + + with torch.no_grad(): + parametrize.remove_parametrizations(conv2d, "weight", leave_parametrized=True) + conv2d.weight = nn.Parameter(conv2d.weight[mask]) + conv2d.out_channels = conv2d.weight.shape[0] + + _remove_bias_handles(conv2d) + return mask + + +def prune_conv2d_padded(conv2d_1: nn.Conv2d) -> None: + parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations) + weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) + for p in weight_parameterizations: + if isinstance(p, FakeStructuredSparsity): + mask = cast(Tensor, p.mask) + + with torch.no_grad(): + parametrize.remove_parametrizations(conv2d_1, "weight", leave_parametrized=True) + + if getattr(conv2d_1, "_bias", None) is not None: + if ( + conv2d_1.bias is not None + ): # conv2d_1 has original bias and bias propagated from previous layer + new_bias = torch.zeros(conv2d_1.bias.shape) + new_bias[mask] = conv2d_1.bias[mask] + # adjusted bias that to keep in conv2d_1 + new_bias[~mask] = cast(Tensor, conv2d_1._bias)[~mask] + # pruned biases that are kept instead of propagated + conv2d_1.bias = nn.Parameter(new_bias) + else: # conv2d_1 has only original bias + conv2d_1.bias = nn.Parameter(cast(Tensor, conv2d_1._bias)) + else: + # no original bias, only propagated bias + if ( + conv2d_1.bias is not None + ): # conv2d_1 has bias propagated from previous layer + conv2d_1.bias.data[~mask] = 0 + + if hasattr(conv2d_1, "_bias"): + delattr(conv2d_1, "_bias") + + +def prune_conv2d(conv2d: nn.Conv2d) -> None: + mask = _prune_conv2d_helper(conv2d) + if getattr(conv2d, "prune_bias", False): + _prune_module_bias(conv2d, mask) + + +def prune_conv2d_conv2d(conv2d_1: nn.Conv2d, conv2d_2: nn.Conv2d) -> None: + prune_conv2d_activation_conv2d(conv2d_1, None, conv2d_2) + + +def prune_conv2d_activation_conv2d( + conv2d_1: nn.Conv2d, + activation: Optional[Callable[[Tensor], Tensor]], + conv2d_2: nn.Conv2d, +): + r""" + Fusion Pattern for conv2d -> some activation module / function -> conv2d layers + """ + parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations) + weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) + for p in weight_parameterizations: + if isinstance(p, FakeStructuredSparsity): + mask = cast(Tensor, p.mask) + + prune_bias = getattr(conv2d_1, "prune_bias", False) + if ( + hasattr(conv2d_2, "padding") + and cast(Tuple[int], conv2d_2.padding) > (0, 0) + and (conv2d_1.bias is not None or getattr(conv2d_1, "_bias", None) is not None) + ): + prune_conv2d_padded(conv2d_1) + else: + mask = _prune_conv2d_helper(conv2d_1) + if prune_bias: + _prune_module_bias(conv2d_1, mask) + else: + pruned_biases = _propogate_module_bias(conv2d_1, mask) + if pruned_biases is not None: + if activation: + pruned_biases = activation(pruned_biases) + conv2d_2.bias = _get_adjusted_next_layer_bias( + conv2d_2, pruned_biases, mask + ) + + if ( + not ( + hasattr(conv2d_2, "padding") + and cast(Tuple[int], conv2d_2.padding) > (0, 0) + ) + or conv2d_1.bias is None + ): + with torch.no_grad(): + if parametrize.is_parametrized(conv2d_2): + parametrization_dict = cast( + nn.ModuleDict, conv2d_2.parametrizations + ) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict.weight + ) + weight_parameterizations.original = nn.Parameter( + weight_parameterizations.original[:, mask] + ) + conv2d_2.in_channels = weight_parameterizations.original.shape[1] + else: + conv2d_2.weight = nn.Parameter(conv2d_2.weight[:, mask]) + conv2d_2.in_channels = conv2d_2.weight.shape[1] + + +def prune_conv2d_pool_activation_conv2d( + c1: nn.Conv2d, + pool: nn.Module, + activation: Optional[Callable[[Tensor], Tensor]], + c2: nn.Conv2d, +) -> None: + prune_conv2d_activation_conv2d(c1, activation, c2) + + +def prune_conv2d_activation_pool_conv2d( + c1: nn.Conv2d, + activation: Optional[Callable[[Tensor], Tensor]], + pool: nn.Module, + c2: nn.Conv2d, +) -> None: + prune_conv2d_activation_conv2d(c1, activation, c2) + + +def prune_conv2d_pool_flatten_linear( + conv2d: nn.Conv2d, + pool: nn.Module, + flatten: Optional[Callable[[Tensor], Tensor]], + linear: nn.Linear, +) -> None: + mask = _prune_conv2d_helper(conv2d) + + # We map the pruned indices of the Conv2d output to the flattened indices of the Linear following the Flatten layer. + # we determine the flattening scale (h * w), and readjust `first_pruned_indices` + # (each idx maps to range idx * h * w to (idx+1) * h * w), `first_valid_indices`, + # and `pruned_biases` (repeat each bias by h * w). + if parametrize.is_parametrized(linear): + parametrization_dict = cast(nn.ModuleDict, linear.parametrizations) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict.weight + ) + linear_ic = weight_parameterizations.original.shape[1] + else: + linear_ic = linear.weight.shape[1] + + conv2d_oc = len(mask) + assert ( + linear_ic % conv2d_oc == 0 + ), f"Flattening from dimensions {conv2d_oc} to {linear_ic} not supported" + + flatten_scale = linear_ic // conv2d_oc + flattened_mask = torch.tensor( + [[val] * flatten_scale for val in mask], dtype=torch.bool, device=mask.device + ).flatten() + + if getattr(conv2d, "prune_bias", False): + _prune_module_bias(conv2d, mask) + else: + pruned_biases = cast(Tensor, _propogate_module_bias(conv2d, mask)) + flattened_pruned_biases = torch.tensor( + [[bias] * flatten_scale for bias in pruned_biases], device=mask.device + ).flatten() + linear.bias = _get_adjusted_next_layer_bias( + linear, flattened_pruned_biases, flattened_mask + ) + + with torch.no_grad(): + if parametrize.is_parametrized(linear): + parametrization_dict = cast(nn.ModuleDict, linear.parametrizations) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict.weight + ) + weight_parameterizations.original = nn.Parameter( + weight_parameterizations.original[:, flattened_mask] + ) + linear.in_features = weight_parameterizations.original.shape[1] + else: + linear.weight = nn.Parameter(linear.weight[:, flattened_mask]) + linear.in_features = linear.weight.shape[1] + + +def prune_lstm_output_linear( + lstm: nn.LSTM, getitem: Callable, linear: nn.Linear +) -> None: + prune_lstm_output_layernorm_linear(lstm, getitem, None, linear) + + +def prune_lstm_output_layernorm_linear( + lstm: nn.LSTM, + getitem: Callable, + layernorm: Optional[nn.LayerNorm], + linear: nn.Linear, +) -> None: + for i in range(lstm.num_layers): + if parametrize.is_parametrized(lstm, f"weight_ih_l{i}"): + parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict[f"weight_ih_l{i}"] + ) + mask = weight_parameterizations[0].mask + + with torch.no_grad(): + parametrize.remove_parametrizations( + lstm, f"weight_ih_l{i}", leave_parametrized=True + ) + setattr( + lstm, + f"weight_ih_l{i}", + nn.Parameter(getattr(lstm, f"weight_ih_l{i}")[mask]), + ) + setattr( + lstm, + f"bias_ih_l{i}", + nn.Parameter(getattr(lstm, f"bias_ih_l{i}")[mask]), + ) + + if parametrize.is_parametrized(lstm, f"weight_hh_l{i}"): + parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict[f"weight_hh_l{i}"] + ) + mask = weight_parameterizations[0].mask + + with torch.no_grad(): + parametrize.remove_parametrizations( + lstm, f"weight_hh_l{i}", leave_parametrized=True + ) + # splitting out hidden-hidden masks + W_hi, W_hf, W_hg, W_ho = torch.split( + getattr(lstm, f"weight_hh_l{i}"), lstm.hidden_size + ) + M_hi, M_hf, M_hg, M_ho = torch.split(mask, lstm.hidden_size) + + # resize each individual weight separately + W_hi = W_hi[M_hi][:, M_hi] + W_hf = W_hf[M_hf][:, M_hf] + W_hg = W_hg[M_hg][:, M_hg] + W_ho = W_ho[M_ho][:, M_ho] + + # concat, use this as new weight + new_weight = torch.cat((W_hi, W_hf, W_hg, W_ho)) + setattr(lstm, f"weight_hh_l{i}", nn.Parameter(new_weight)) + setattr( + lstm, + f"bias_hh_l{i}", + nn.Parameter(getattr(lstm, f"bias_hh_l{i}")[mask]), + ) + + # If this is the final layer, then we need to prune linear layer columns + if i + 1 == lstm.num_layers: + lstm.hidden_size = int(M_hi.sum()) + with torch.no_grad(): + if parametrize.is_parametrized(linear): + parametrization_dict = cast( + nn.ModuleDict, linear.parametrizations + ) + weight_parameterizations = cast( + ParametrizationList, parametrization_dict.weight + ) + + weight_parameterizations.original = nn.Parameter( + weight_parameterizations.original[:, M_ho] + ) + linear.in_features = weight_parameterizations.original.shape[1] + else: + linear.weight = nn.Parameter(linear.weight[:, M_ho]) + linear.in_features = linear.weight.shape[1] + + # if layernorm module, prune weight and bias + if layernorm is not None: + layernorm.normalized_shape = (linear.in_features,) + layernorm.weight = nn.Parameter(layernorm.weight[M_ho]) + layernorm.bias = nn.Parameter(layernorm.bias[M_ho]) + + # otherwise need to prune the columns of the input of the next LSTM layer + else: + with torch.no_grad(): + if parametrize.is_parametrized(lstm, f"weight_ih_l{i+1}"): + parametrization_dict = cast( + nn.ModuleDict, lstm.parametrizations + ) + weight_parameterizations = cast( + ParametrizationList, + getattr(parametrization_dict, f"weight_ih_l{i+1}"), + ) + + weight_parameterizations.original = nn.Parameter( + weight_parameterizations.original[:, M_ho] + ) + else: + next_layer_weight = getattr(lstm, f"weight_ih_l{i+1}") + setattr( + lstm, + f"weight_ih_l{i+1}", + nn.Parameter(next_layer_weight[:, M_ho]), + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py new file mode 100644 index 0000000000000000000000000000000000000000..f965fa647de9e880cf82474527d1b01b49c80871 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py @@ -0,0 +1,29 @@ +from .base_structured_sparsifier import BaseStructuredSparsifier + + +class SaliencyPruner(BaseStructuredSparsifier): + """ + Prune rows based on the saliency (L1 norm) of each row. + + This pruner works on N-Dimensional weight tensors. + For each row, we will calculate the saliency, whic is the sum the L1 norm of all weights in that row. + We expect that the resulting saliency vector has the same shape as our mask. + We then pick elements to remove until we reach the target sparsity_level. + """ + + def update_mask(self, module, tensor_name, **kwargs): + # tensor_name will give you the FQN, all other entries in sparse config is present in kwargs + weights = getattr(module, tensor_name) + mask = getattr(module.parametrizations, tensor_name)[0].mask + + # use negative weights so we can use topk (we prune out the smallest) + if weights.dim() <= 1: + raise Exception("Structured pruning can only be applied to a 2+dim weight tensor!") + saliency = -weights.norm(dim=tuple(range(1, weights.dim())), p=1) + assert saliency.shape == mask.shape + + num_to_pick = int(len(mask) * kwargs["sparsity_level"]) + prune = saliency.topk(num_to_pick).indices + + # Set the mask to be false for the rows we want to prune + mask.data[prune] = False diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb768fe77250395585c0d0201ee4f32088023313 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5574721c8597b7d9cff7e66e922acc95ad6f0a49 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb334c6929046ec40b394037b5c679f18333e7b6 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54484f81397f07c9a941b758746c0c313543565b Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..3391d3e73cd657dc3b23c1f8f00b8e5ddf63a3c7 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py @@ -0,0 +1,159 @@ + +from torch.ao.pruning import BaseSparsifier + +from functools import wraps +import warnings +import weakref + +__all__ = ["BaseScheduler"] + +class BaseScheduler: + + def __init__(self, sparsifier, last_epoch=-1, verbose=False): + + # Attach sparsifier + if not isinstance(sparsifier, BaseSparsifier): + raise TypeError(f'{type(sparsifier).__name__} is not an instance of torch.ao.pruning.BaseSparsifier') + self.sparsifier = sparsifier + + # Initialize epoch and base sparsity levels + + self.base_sl = [group['sparsity_level'] for group in sparsifier.groups] + self.last_epoch = last_epoch + + # Following https://github.com/pytorch/pytorch/issues/20124 + # We would like to ensure that `scheduler.step()` is called after + # `sparsifier.step()` + def with_counter(method): + if getattr(method, '_with_counter', False): + # `sparsifier.step()` has already been replaced, return. + return method + + # Keep a weak reference to the sparsifier instance to prevent + # cyclic references. + instance_ref = weakref.ref(method.__self__) + # Get the unbound method for the same purpose. + func = method.__func__ + cls = instance_ref().__class__ + del method + + @wraps(func) + def wrapper(*args, **kwargs): + instance = instance_ref() + instance._step_count += 1 # type: ignore[union-attr] + wrapped = func.__get__(instance, cls) + return wrapped(*args, **kwargs) + + # Note that the returned function here is no longer a bound method, + # so attributes like `__func__` and `__self__` no longer exist. + wrapper._with_counter = True # type: ignore[attr-defined] + return wrapper + + self.sparsifier.step = with_counter(self.sparsifier.step) # type: ignore[assignment] + self.sparsifier._step_count = 0 # type: ignore[attr-defined] + self._step_count: int = 0 + self.verbose = verbose + + # Housekeeping + self._get_sl_called_within_step: bool = False + + self.step() + + def state_dict(self): + """Returns the state of the scheduler as a :class:`dict`. + + It contains an entry for every variable in self.__dict__ which + is not the sparsifier. + """ + return {key: value for key, value in self.__dict__.items() if key != 'sparsifier'} + + def load_state_dict(self, state_dict): + """Loads the schedulers state. + + Args: + state_dict (dict): scheduler state. Should be an object returned + from a call to :meth:`state_dict`. + """ + self.__dict__.update(state_dict) + + def get_last_sl(self): + """ Return last computed sparsity level by current scheduler. + """ + return self._last_sl + + def get_sl(self): + # Compute sparsity level using chainable form of the scheduler + # Note: This method is not intended to be called directly, and is only + # used by the ".step" method. Use .get_last_sl() instead. + if not self._get_sl_called_within_step: + warnings.warn( + "To get the last sparsity level computed by the scheduler, " + "please use `get_last_sl()`.") + raise NotImplementedError + + def print_sl(self, is_verbose, group, sl, epoch=None): + """Display the current sparsity level. + """ + if is_verbose: + if epoch is None: + print(f'Adjusting sparsity level of group {group} to {sl:.4e}.') + else: + print(f'Epoch {epoch:5d}: adjusting sparsity level of group {group} to {sl:.4e}.') + + def __repr__(self): + format_string = self.__class__.__name__ + ' (' + format_string += '\n' + format_string += f'Sparsifier {self.sparsifier}\n' + format_string += f' base_sl: {self.base_sl}\n' + format_string += ')' + return format_string + + def step(self, epoch=None): + # Raise warning if trying to call scheduler step before the sparsifier. + # https://github.com/pytorch/pytorch/issues/20124 + if self._step_count == 1: + if not hasattr(self.sparsifier.step, "_with_counter"): + warnings.warn("Seems like `sparsifier.step()` has been overridden after sparsity scheduler " + "initialization. Please, make sure to call `sparsifier.step()` before " + "`scheduler.step()`.", UserWarning) + + # Just check if there were two first scheduler.step() calls before sparsifier.step() + elif self.sparsifier._step_count < 1: # type: ignore[attr-defined] + warnings.warn("Detected call of `scheduler.step()` before `sparsifier.step()`. " + "You have to make sure you run the sparsifier.step() BEFORE any " + "calls to the scheduler.step().", UserWarning) + self._step_count += 1 + + class _enable_get_sl_call: + + def __init__(self, o): + self.o = o + + def __enter__(self): + self.o._get_sl_called_within_step = True + return self + + def __exit__(self, type, value, traceback): + self.o._get_sl_called_within_step = False + + with _enable_get_sl_call(self): + self.last_epoch += 1 + values = self.get_sl() + + for i, data in enumerate(zip(self.sparsifier.groups, values)): + param_group, sl = data + param_group['sparsity_level'] = sl + self.print_sl(self.verbose, i, sl, epoch) + + self._last_sl = [group['sparsity_level'] for group in self.sparsifier.groups] + self.sparsifier.enable_mask_update = True + + def _make_sure_a_list(self, var): + r"""Utility that extends it to the same length as the .groups, ensuring it is a list""" + n = len(self.sparsifier.groups) + if not isinstance(var, (list, tuple)): + return [var] * n + else: + if len(var) != n: + raise ValueError(f"Expected variable of length {n}, but got {len(var)}") + return list(var) # We want the result to be in a list, not tuple diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..76fc61daa288a65dce80be6907535b5f313efa6b --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py @@ -0,0 +1,107 @@ +import warnings + +from .base_scheduler import BaseScheduler + +__all__ = ["CubicSL"] + +def _clamp(x, lo, hi): + return max(lo, min(hi, x)) + + +class CubicSL(BaseScheduler): + r"""Sets the sparsity level of each parameter group to the final sl + plus a given exponential function. + + .. math:: + + s_i = s_f + (s_0 - s_f) \cdot \left( 1 - \frac{t - t_0}{n\Delta t} \right)^3 + + where :math:`s_i` is the sparsity at epoch :math:`t`, :math;`s_f` is the final + sparsity level, :math:`f(i)` is the function to be applied to the current epoch + :math:`t`, initial epoch :math:`t_0`, and final epoch :math:`t_f`. + :math:`\Delta t` is used to control how often the update of the sparsity level + happens. By default, + + Args: + sparsifier (BaseSparsifier): Wrapped sparsifier. + init_sl (int, list): Initial level of sparsity + init_t (int, list): Initial step, when pruning starts + delta_t (int, list): Pruning frequency + total_t (int, list): Total number of pruning steps + initially_zero (bool, list): If True, sets the level of sparsity to 0 + before init_t (:math:`t_0`). Otherwise, the sparsity level before + init_t (:math:`t_0`) is set to init_sl(:math:`s_0`) + last_epoch (int): The index of last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + """ + def __init__(self, + sparsifier, + init_sl=0.0, + init_t=0, + delta_t=10, + total_t=100, + initially_zero=False, + last_epoch=-1, + verbose=False + ): + self.sparsifier = sparsifier + + self.init_sl = self._make_sure_a_list(init_sl) + self.init_t = self._make_sure_a_list(init_t) + self.delta_t = self._make_sure_a_list(delta_t) + self.total_t = self._make_sure_a_list(total_t) + + self.initially_zero = self._make_sure_a_list(initially_zero) + + super().__init__(sparsifier, last_epoch, verbose) + + @staticmethod + def sparsity_compute_fn(s_0, s_f, t, t_0, dt, n, initially_zero=False): + r""""Computes the current level of sparsity. + + Based on https://arxiv.org/pdf/1710.01878.pdf + + Args: + s_0: Initial level of sparsity, :math:`s_i` + s_f: Target level of sparsity, :math:`s_f` + t: Current step, :math:`t` + t_0: Initial step, :math:`t_0` + dt: Pruning frequency, :math:`\Delta T` + n: Pruning steps, :math:`n` + initially_zero: Sets the level of sparsity to 0 before t_0. + If False, sets to s_0 + + Returns: + The sparsity level :math:`s_t` at the current step :math:`t` + """ + if initially_zero and t < t_0: + return 0 + s_t = s_f + (s_0 - s_f) * (1.0 - (t - t_0) / (dt * n)) ** 3 + s_t = _clamp(s_t, s_0, s_f) + return s_t + + def get_sl(self): + if not self._get_sl_called_within_step: + warnings.warn( + "To get the last sparsity level computed by the scheduler, " + "please use `get_last_sl()`.") + return [ + self.sparsity_compute_fn( + s_0=initial_sparsity, + s_f=final_sparsity, + t=self.last_epoch, + t_0=initial_epoch, + dt=delta_epoch, + n=interval_epochs, + initially_zero=initially_zero + ) for initial_sparsity, final_sparsity, initial_epoch, delta_epoch, interval_epochs, initially_zero in + zip( + self.init_sl, + self.base_sl, + self.init_t, + self.delta_t, + self.total_t, + self.initially_zero + ) + ] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..a88d99a1f83b4b352025452b5863b1275c187b4d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py @@ -0,0 +1,47 @@ +import warnings + +from .base_scheduler import BaseScheduler + +__all__ = ["LambdaSL"] + +class LambdaSL(BaseScheduler): + """Sets the sparsity level of each parameter group to the final sl + times a given function. When last_epoch=-1, sets initial sl as zero. + Args: + sparsifier (BaseSparsifier): Wrapped sparsifier. + sl_lambda (function or list): A function which computes a multiplicative + factor given an integer parameter epoch, or a list of such + functions, one for each group in sparsifier.param_groups. + last_epoch (int): The index of last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + Example: + >>> # Assuming sparsifier has two groups. + >>> lambda1 = lambda epoch: epoch // 30 + >>> lambda2 = lambda epoch: 0.95 ** epoch + >>> # xdoctest: +SKIP + >>> scheduler = LambdaSL(sparsifier, sl_lambda=[lambda1, lambda2]) + >>> for epoch in range(100): + >>> train(...) + >>> validate(...) + >>> scheduler.step() + """ + + def __init__(self, sparsifier, sl_lambda, last_epoch=-1, verbose=False): + self.sparsifier = sparsifier + + if not isinstance(sl_lambda, list) and not isinstance(sl_lambda, tuple): + self.sl_lambdas = [sl_lambda] * len(sparsifier.groups) + else: + if len(sl_lambda) != len(sparsifier.groups): + raise ValueError(f"Expected {len(sparsifier.groups)} lr_lambdas, but got {len(sl_lambda)}") + self.sl_lambdas = list(sl_lambda) + super().__init__(sparsifier, last_epoch, verbose) + + def get_sl(self): + if not self._get_sl_called_within_step: + warnings.warn( + "To get the last sparsity level computed by the scheduler, " + "please use `get_last_sl()`.") + return [base_sl * lmbda(self.last_epoch) + for lmbda, base_sl in zip(self.sl_lambdas, self.base_sl)] diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__init__.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/base_sparsifier.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/base_sparsifier.py new file mode 100644 index 0000000000000000000000000000000000000000..1c210ace344d8fb24dfbe096a00119179073ccdc --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/base_sparsifier.py @@ -0,0 +1,353 @@ +import abc +import copy +from collections import defaultdict +from typing import Any, Dict, Optional, Set, Tuple, List, Type + +import torch +from torch import nn +from torch.nn.utils import parametrize +from torch.nn.utils.parametrize import type_before_parametrizations + +from .utils import ( + module_contains_param, + swap_module, + FakeSparsity, + get_arg_info_from_tensor_fqn, + module_to_fqn, +) + +__all__ = ["BaseSparsifier"] + +SUPPORTED_MODULES = {nn.Linear} + +KEYS_NOT_IN_STATE_DICT = ["module", "module_fqn", "tensor_name"] + +__all__ = ["BaseSparsifier"] + + +# TODO update desc with new config args +class BaseSparsifier(abc.ABC): + r"""Base class for all sparsifiers. + + Abstract methods that need to be implemented: + + - update_mask: Function to compute a new mask for all keys in the + `groups`. + + Args: + - model [nn.Module]: model to configure. The model itself is not saved + but used for the state_dict saving / loading. + - config [list]: configuration elements should be a dict map that includes + `tensor_fqn` of tensors to sparsify + - defaults [dict]: default configurations will be attached to the + configuration. Only the keys that don't exist in the `config` will + be updated. + + Example:: + + >>> # xdoctest: +SKIP("Can't instantiate abstract class BaseSparsifier with abstract method update_mask") + >>> config = [{'tensor_fqn': 'layer1.weight', 'tensor_fqn': 'linear2.weight2', 'sparsity_level': 0.5}] + >>> defaults = {'sparsity_level': 0.7} + >>> # model.layer1.weight will have `sparsity_level` = 0.7 (getting default) + >>> sparsifier = BaseSparsifier(config, defaults) + """ + + def __init__(self, defaults: Optional[Dict[str, Any]] = None): + super().__init__() + self.defaults: Dict[str, Any] = defaults or {} + + self.state: Dict[str, Dict] = defaultdict(dict) + self.groups: List[Dict[str, Any]] = [] + self.enable_mask_update = True + + def __getstate__(self) -> Dict[str, Any]: + return { + "defaults": self.defaults, + "state": self.state, + "groups": self.groups, + } + + def __setstate__(self, state: Dict[str, Dict[str, Any]]) -> None: + self.__dict__.update(state) + + def __repr__(self): + format_string = self.__class__.__name__ + " (" + for i, sparse_args in enumerate(self.groups): + module = sparse_args["module"] + format_string += "\n" + format_string += f"\tGroup {i}\n" + format_string += f"\t module: {module}\n" + for key in sorted(sparse_args.keys()): + if key == "module": + continue + format_string += f"\t {key}: {sparse_args[key]}\n" + format_string += ")" + return format_string + + def state_dict(self) -> Dict[str, Any]: + r"""Returns the state of the optimizer as a :class:`dict`. + + It contains: + * state - current state of the sparsification. + * groups - a list containing all sparsity configuration groups + with the key 'tensor_fqn' specifying the path to the sparsified tensor within a model + + TODO: Need a clean way of loading the state of the "prepared" module + """ + + groups: List[Dict[str, Any]] = [ + dict( + filter( + lambda key_value: key_value[0] not in KEYS_NOT_IN_STATE_DICT, + mg.items(), + ) + ) + for mg in self.groups + ] + + return { + "state": self.state, + "groups": groups, + } + + def load_state_dict(self, state_dict: Dict[str, Any], strict: bool = True): + groups = copy.deepcopy(state_dict["groups"]) + states = state_dict["state"] + for tensor_fqn, s in states.items(): + arg_info = get_arg_info_from_tensor_fqn(self.model, tensor_fqn) + module = arg_info["module"] + tensor_name = arg_info["tensor_name"] + if strict and module is None: + raise RuntimeError(f"Error loading {tensor_fqn} into the model") + + found = False + for p in module.parametrizations[tensor_name]: + if isinstance(p, FakeSparsity): + found = True + break + if not found: + p = FakeSparsity(torch.ones(getattr(module, tensor_name).shape)) + parametrize.register_parametrization(module, tensor_name, p) + if s.get("mask", None) is not None: + mask = s.pop("mask") + p.mask = mask + + for mg in groups: + if mg["tensor_fqn"] == tensor_fqn: + mg.update(arg_info) + self.__setstate__({"state": states, "groups": groups}) + + def make_config_from_model( + self, + model: nn.Module, + SUPPORTED_MODULES: Set[Type] = SUPPORTED_MODULES, + ) -> None: + self.config = [] + stack = [model] + while stack: + module = stack.pop() + for name, child in module.named_children(): + if type(child) in SUPPORTED_MODULES: + module_fqn = module_to_fqn(model, child) + assert isinstance(module_fqn, str) # for mypy + self.config.append({"tensor_fqn": module_fqn + ".weight"}) + else: + stack.append(child) + + def prepare(self, model, config): + r"""Prepares a model, by adding the parametrizations. + + Note:: + + The model is modified inplace. If you need to preserve the original + model, use copy.deepcopy. + """ + self.model = model # TODO: Need to figure out how to load without this. + self.config = config + + # If no config -- try getting all the supported layers + if self.config is None: + self.make_config_from_model(model) + + # TODO: Remove the configuration by reference ('module') + for module_config in self.config: + assert isinstance(module_config, dict), ( + "config elements should be dicts not modules i.e.:" + "[{`tensor_fqn`: `foo.bar.weight`}, {`tensor_fqn`: ... }, ...]" + ) + + assert isinstance(self.defaults, Dict) # for mypy + local_args = copy.deepcopy(self.defaults) + local_args.update(module_config) + + tensor_fqn = local_args.get("tensor_fqn", None) + assert tensor_fqn is not None, ( + "tensor_fqn is a required argument in the sparsity config which" + "replaces previous `module` and [module]`fqn` arguments" + ) + + # populate all information from tensor_fqn + info_from_tensor_fqn = get_arg_info_from_tensor_fqn(model, tensor_fqn) + + # check that whatever was put into local_args agrees with what was obtained + # from tensor_fqn + for key in info_from_tensor_fqn.keys(): + if key in local_args: + assert ( + info_from_tensor_fqn[key] == local_args[key] + or ( + key == "tensor_fqn" + and "." + info_from_tensor_fqn[key] == local_args[key] + ) + # info_from_tensor_fqn will chop leading '.' from tensor_fqn so ignore that + ), ( + f"Given both `{key}` and `tensor_fqn` in the config, it is expected them to agree!" + ) + local_args.update(info_from_tensor_fqn) + self.groups.append(local_args) + self._prepare() + + def _prepare(self, *args, **kwargs): + r"""Adds mask parametrization to the layer weight""" + for config in self.groups: + module = config["module"] + tensor_name = config["tensor_name"] + parametrization = config.get("parametrization", FakeSparsity) + mask = config.get("mask", torch.ones_like(getattr(module, tensor_name))) + self.state[config["tensor_fqn"]]["mask"] = mask + parametrize.register_parametrization( + module, tensor_name, parametrization(mask) + ) + + def squash_mask( + self, + params_to_keep: Optional[Tuple[str, ...]] = None, + params_to_keep_per_layer: Optional[Dict[str, Tuple[str, ...]]] = None, + *args, + **kwargs, + ): + r"""Squashes the sparse masks into the appropriate tensors. + + If either the `params_to_keep` or `params_to_keep_per_layer` is set, + the module will have a `sparse_params` dict attached to it. + + Args: + params_to_keep: List of keys to save in the module or a dict + representing the modules and keys that will have + sparsity parameters saved + params_to_keep_per_layer: Dict to specify the params that should be + saved for specific layers. The keys in the dict + should be the module fqn, while the values should + be a list of strings with the names of the variables + to save in the `sparse_params` + + Examples: + >>> # xdoctest: +SKIP("locals are undefined") + >>> # Don't save any sparse params + >>> sparsifier.squash_mask() + >>> hasattr(model.submodule1, 'sparse_params') + False + + >>> # Keep sparse params per layer + >>> sparsifier.squash_mask( + ... params_to_keep_per_layer={ + ... 'submodule1.linear1': ('foo', 'bar'), + ... 'submodule2.linear42': ('baz',) + ... }) + >>> print(model.submodule1.linear1.sparse_params) + {'foo': 42, 'bar': 24} + >>> print(model.submodule2.linear42.sparse_params) + {'baz': 0.1} + + >>> # Keep sparse params for all layers + >>> sparsifier.squash_mask(params_to_keep=('foo', 'bar')) + >>> print(model.submodule1.linear1.sparse_params) + {'foo': 42, 'bar': 24} + >>> print(model.submodule2.linear42.sparse_params) + {'foo': 42, 'bar': 24} + + >>> # Keep some sparse params for all layers, and specific ones for + >>> # some other layers + >>> sparsifier.squash_mask( + ... params_to_keep=('foo', 'bar'), + ... params_to_keep_per_layer={ + ... 'submodule2.linear42': ('baz',) + ... }) + >>> print(model.submodule1.linear1.sparse_params) + {'foo': 42, 'bar': 24} + >>> print(model.submodule2.linear42.sparse_params) + {'foo': 42, 'bar': 24, 'baz': 0.1} + """ + for config in self.groups: + module = config["module"] + tensor_name = config["tensor_name"] + parametrize.remove_parametrizations( + module, tensor_name, leave_parametrized=True + ) + sparse_params = {} + if params_to_keep is not None: + global_params = {k: config[k] for k in params_to_keep} + sparse_params.update(global_params) + if params_to_keep_per_layer is not None: + params = params_to_keep_per_layer.get(config["module_fqn"], None) + if params is not None: + per_layer_params = {k: config[k] for k in params} + sparse_params.update(per_layer_params) + if sparse_params: + # TODO handle multiple tensor being quantized on a single module, where to store sparse_params? + module.sparse_params = sparse_params + + def convert( + self, + module: nn.Module, + mapping: Optional[Dict[Type[nn.Module], Type[nn.Module]]] = None, + inplace: bool = False, + parameterization: Type[nn.Module] = FakeSparsity, + ): + r"""Converts submodules in input module to a different module according to `mapping` + by calling `from_dense` method on the target module class + Args: + module: input module + mapping: a dictionary that maps from source module type to target + module type, can be overwritten to allow swapping user defined + Modules + inplace: carry out model transformations in-place, the original module + is mutated + """ + if mapping is None: + raise NotImplementedError("Need to auto generate mapping ") + if not inplace: + module = copy.deepcopy(module) + + reassign = {} + for name, mod in module.named_children(): + # leaf node + if ( + module_contains_param(mod, parameterization) + and type_before_parametrizations(mod) in mapping + ): + reassign[name] = swap_module(mod, mapping) + else: + # recurse + reassign[name] = self.convert( + mod, + mapping=mapping, + inplace=True, + parameterization=parameterization, + ) + + for key, value in reassign.items(): + module._modules[key] = value + + return module + + def step(self, use_path: bool = True) -> None: + if not self.enable_mask_update: + return + with torch.no_grad(): + for config in self.groups: + self.update_mask(**config) + + @abc.abstractmethod + def update_mask(self, module: nn.Module, tensor_name: str, **kwargs): + pass diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/nearly_diagonal_sparsifier.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/nearly_diagonal_sparsifier.py new file mode 100644 index 0000000000000000000000000000000000000000..4f44e81485dffa976b94626213af326f0500a05a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/nearly_diagonal_sparsifier.py @@ -0,0 +1,55 @@ +import torch + +from . import base_sparsifier + + +class NearlyDiagonalSparsifier(base_sparsifier.BaseSparsifier): + r"""Nearly Diagonal Sparsifier + + This sparsifier creates a nearly diagonal mask to be applied to the weight matrix. + Nearly Diagonal Matrix is a matrix that contains non-zero elements near the diagonal and the rest are zero. + An example of a nearly diagonal matrix with degree (or nearliness) 3 and 5 are follows respectively. + 1 1 0 0 1 1 1 0 + 1 1 1 0 1 1 1 1 + 0 1 1 1 1 1 1 1 + 0 0 1 1 0 1 1 1 + Note that a nearly diagonal matrix with degree 1 is just a matrix with main diagonal populated + + This sparsifier is controlled by one variable: + 1. `nearliness` defines the number of non-zero diagonal lines that are closest to the main diagonal. + Currently - supports only odd number + + Note: + This can be accelerated (vectorized) once the Spdiagonal feature (PR: #78439) is landed or the banded matrix + feature is landed: https://stackoverflow.com/questions/52463972/generating-banded-matrices-using-numpy + + Args: + nearliness: The degree of nearliness (default = 1) + + """ + def __init__(self, nearliness: int = 1): + defaults = {'nearliness': nearliness} + super().__init__(defaults=defaults) + + def update_mask(self, module, tensor_name, nearliness, + **kwargs): + mask = getattr(module.parametrizations, tensor_name)[0].mask + mask.data = torch.zeros_like(mask) + if nearliness <= 0: + return + + tensor = getattr(module, tensor_name) + height, width = tensor.shape + + if nearliness % 2 == 0: + raise ValueError("nearliness can only be an odd number") + dist_to_diagonal = nearliness // 2 + # check + if dist_to_diagonal >= min(height, width): + raise ValueError("nearliness cannot be larger than the dimensions of tensor.") + + for row in range(0, height): + # Bounds of entries that needs to be set to 1 + low = max(0, row - dist_to_diagonal) + high = min(width, row + dist_to_diagonal + 1) + mask[row, low:high].fill_(1) diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/utils.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..98f489904cc45340167cfae5f2362ee70ccb8fca --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/utils.py @@ -0,0 +1,136 @@ +from typing import Any, Dict, Optional, Type +from torch.nn.utils.parametrize import type_before_parametrizations, is_parametrized +from itertools import chain + +from torch import nn + +__all__ = [ + "module_contains_param", + "swap_module", + "module_to_fqn", + "fqn_to_module", + "get_arg_info_from_tensor_fqn", + "FakeSparsity", +] + + +def module_contains_param(module: nn.Module, parametrization: Type[nn.Module]) -> bool: + if is_parametrized(module): + # see if any of the module tensors have a parametriztion attached that matches the one passed in + return any( + any(isinstance(param, parametrization) for param in param_list) + for key, param_list in module.parametrizations.items() # type: ignore[union-attr,operator] + ) + return False + + +def swap_module( + mod: nn.Module, mapping: Dict[Type[nn.Module], Type[nn.Module]] +) -> nn.Module: + r"""Swaps the module using from_dense according to the mapping passed in. + Args: + mod: input module + mapping: a dictionary that maps from nn module to sparse nn module + Return: + The corresponding sparse module of `mod` according to mapping, created using from_dense + """ + if type_before_parametrizations(mod) in mapping: + sparse_mod = mapping[type_before_parametrizations(mod)] + + # TODO Fix this typing, as Type[Module] has no attribute "from_dense" + new_mod = sparse_mod.from_dense(mod) # type: ignore[attr-defined] + + # Preserve module's pre forward hooks. They'll be called on quantized input + for pre_hook_fn in mod._forward_pre_hooks.values(): + new_mod.register_forward_pre_hook(pre_hook_fn) + # Preserve module's post forward hooks except _observer_forward_hook + # After convert they'll work with quantized output + for hook_fn in mod._forward_hooks.values(): + new_mod.register_forward_hook(hook_fn) + + # respect device affinity when swapping modules + devices = {p.device for p in chain(mod.parameters(), mod.buffers())} + assert len(devices) <= 1, ( + f"swap_module only works with cpu or single-device CUDA modules, but got devices {devices}" + ) + device = next(iter(devices)) if len(devices) > 0 else None + if device: + new_mod.to(device) + + return new_mod + + else: + return mod + + +def module_to_fqn( + model: nn.Module, module: nn.Module, prefix: str = "" +) -> Optional[str]: + """ + Returns the fqn for a module or None if module not a descendent of model. + """ + if module is model: + return "" + for name, child in model.named_children(): + fqn = module_to_fqn(child, module, ".") + if isinstance(fqn, str): + return prefix + name + fqn + return None + + +def fqn_to_module(model: Optional[nn.Module], path: str) -> Optional[nn.Module]: + """ + Given an fqn, returns the corresponding module or tensor or None if the fqn given by `path` + doesn't correspond to anything. Similar to model.get_submodule(path) but works for tensors. + """ + if path != "": + for name in path.split("."): + model = getattr(model, name, None) + return model + + +def get_arg_info_from_tensor_fqn(model: nn.Module, tensor_fqn: str) -> Dict[str, Any]: + """ + Uses tensor_fqn to obtain a dict containing module_fqn, module and tensor_name + """ + # string manip to split tensor_fqn into module_fqn and tensor_name + # if tensor_fqn is 'weight' then module_fqn and tensor_name are '' and 'weight' + # if tensor_fqn is 'linear.weight' then module_fqn and tensor_name are 'linear' and 'weight' + tensor_name = tensor_fqn.split(".")[-1] + module_fqn = tensor_fqn[: -len(tensor_name) - ("." in tensor_fqn)] + + module = fqn_to_module(model, module_fqn) + + return { + "module_fqn": module_fqn, + "module": module, + "tensor_name": tensor_name, + "tensor_fqn": tensor_fqn, + } + + +# Parametrizations +class FakeSparsity(nn.Module): + r"""Parametrization for the weights. Should be attached to the 'weight' or + any other parameter that requires a mask applied to it. + + Note:: + + Once the mask is passed, the variable should not change the id. The + contents of the mask can change, but the mask reference itself should + not. + """ + + def __init__(self, mask): + super().__init__() + self.register_buffer("mask", mask) + + def forward(self, x): + assert self.mask.shape == x.shape + return self.mask * x + + def state_dict(self, *args, **kwargs): + # We don't want to let the parametrizations to save the mask. + # That way we make sure that the linear module doesn't store the masks + # alongside their parametrizations. + return {} diff --git a/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/weight_norm_sparsifier.py b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/weight_norm_sparsifier.py new file mode 100644 index 0000000000000000000000000000000000000000..36903ddb9e0541ac6df885e10731828a0c69cb1f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/weight_norm_sparsifier.py @@ -0,0 +1,199 @@ +from functools import reduce +from typing import Callable, Optional, Tuple, Union + +import torch +import torch.nn.functional as F + +from .base_sparsifier import BaseSparsifier + +__all__ = ["WeightNormSparsifier"] + +def _flat_idx_to_2d(idx, shape): + rows = idx // shape[1] + cols = idx % shape[1] + return rows, cols + +class WeightNormSparsifier(BaseSparsifier): + r"""Weight-Norm Sparsifier + + This sparsifier computes the norm of every sparse block and "zeroes-out" the + ones with the lowest norm. The level of sparsity defines how many of the + blocks is removed. + + This sparsifier is controlled by three variables: + 1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out + 2. `sparse_block_shape` defines the shape of the sparse blocks. Note that + the sparse blocks originate at the zero-index of the tensor. + 3. `zeros_per_block` is the number of zeros that we are expecting in each + sparse block. By default we assume that all elements within a block are + zeroed-out. However, setting this variable sets the target number of + zeros per block. The zeros within each block are chosen as the *smallest + absolute values*. + + Args: + + sparsity_level: The target level of sparsity + sparse_block_shape: The shape of a sparse block (see note below) + zeros_per_block: Number of zeros in a sparse block + norm: Norm to use. Could be either `int` or a callable. + If `int`, only L1 and L2 are implemented. + + Note:: + The `sparse_block_shape` is tuple representing (block_ROWS, block_COLS), + irrespective of what the rows / cols mean in the data tensor. That means, + if you were to sparsify a weight tensor in the nn.Linear, which has a + weight shape `(Cout, Cin)`, the `block_ROWS` would refer to the output + channels, while the `block_COLS` would refer to the input channels. + + Note:: + All arguments to the WeightNormSparsifier constructor are "default" + arguments and could be overriden by the configuration provided in the + `prepare` step. + """ + def __init__(self, + sparsity_level: float = 0.5, + sparse_block_shape: Tuple[int, int] = (1, 4), + zeros_per_block: Optional[int] = None, + norm: Optional[Union[Callable, int]] = None): + if zeros_per_block is None: + zeros_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + defaults = { + "sparsity_level": sparsity_level, + "sparse_block_shape": sparse_block_shape, + "zeros_per_block": zeros_per_block, + } + if norm is None: + norm = 2 + if callable(norm): + self.norm_fn = norm + elif norm == 1: + self.norm_fn = lambda T: T.abs() + elif norm == 2: + self.norm_fn = lambda T: T * T + else: + raise NotImplementedError(f"L-{norm} is not yet implemented.") + super().__init__(defaults=defaults) + + def _scatter_fold_block_mask(self, output_shape, dim, indices, block_shape, + mask=None, input_shape=None, device=None): + r"""Creates patches of size `block_shape` after scattering the indices.""" + if mask is None: + assert input_shape is not None + mask = torch.ones(input_shape, device=device) + mask.scatter_(dim=dim, index=indices, value=0) + mask.data = F.fold(mask, output_size=output_shape, kernel_size=block_shape, stride=block_shape) + return mask + + def _make_tensor_mask(self, data, input_shape, sparsity_level, sparse_block_shape, mask=None): + r"""Creates a tensor-level mask. + + Tensor-level mask is described as a mask, where the granularity of sparsification of the + smallest patch is the sparse_block_shape. That means, that for a given mask and a + sparse_block_shape, the smallest "patch" of zeros/ones could be the sparse_block_shape. + + In this context, `sparsity_level` describes the fraction of sparse patches. + """ + h, w = data.shape[-2:] + block_h, block_w = sparse_block_shape + dh = (block_h - h % block_h) % block_h + dw = (block_w - w % block_w) % block_w + + if mask is None: + mask = torch.ones(h + dh, w + dw, device=data.device) + + if sparsity_level >= 1.0: + mask.data = torch.zeros_like(mask) + return mask + elif sparsity_level <= 0.0: + mask.data = torch.ones_like(mask) + return mask + + values_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + if values_per_block > 1: + # Reduce the data + data = F.avg_pool2d( + data[None, None, :], kernel_size=sparse_block_shape, stride=sparse_block_shape, ceil_mode=True + ) + data = data.flatten() + num_blocks = len(data) + + data = data.repeat(1, values_per_block, 1) + + threshold_idx = int(round(sparsity_level * num_blocks)) + threshold_idx = max(0, min(num_blocks - 1, threshold_idx)) # Sanity check + _, sorted_idx = torch.topk(data, k=threshold_idx, dim=2, largest=False) + + # Temp reshape for mask + mask_reshape = mask.reshape(data.shape) # data might be reshaped + self._scatter_fold_block_mask( + dim=2, output_shape=(h + dh, w + dw), + indices=sorted_idx, block_shape=sparse_block_shape, mask=mask_reshape + ) + mask.data = mask_reshape.squeeze().reshape(mask.shape)[:h, :w].contiguous() + return mask + + def _make_block_mask(self, data, sparse_block_shape, zeros_per_block, mask=None): + r"""Creates a block-level mask. + + Block-level mask is described as a mask, where the granularity of sparsification of the + largest patch is the sparse_block_shape. That means that for a given mask and a + sparse_block_shape, the sparsity is computed only within a patch of a size sparse_block_shape. + + In this context the `zeros_per_block` describes the number of zeroed-out elements within a patch. + """ + h, w = data.shape[-2:] + block_h, block_w = sparse_block_shape + dh = (block_h - h % block_h) % block_h + dw = (block_w - w % block_w) % block_w + values_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + + if mask is None: + mask = torch.ones((h + dh, w + dw), device=data.device) + + if values_per_block == zeros_per_block: + # Everything should be sparsified + mask.data = torch.zeros_like(mask) + return mask + + # create a new padded tensor like data (to match the block_shape) + padded_data = torch.ones(h + dh, w + dw, dtype=data.dtype, device=data.device) + padded_data.fill_(torch.nan) + padded_data[:h, :w] = data + unfolded_data = F.unfold(padded_data[None, None, :], kernel_size=sparse_block_shape, stride=sparse_block_shape) + + # Temp reshape for mask + mask_reshape = mask.reshape(unfolded_data.shape) + _, sorted_idx = torch.topk(unfolded_data, k=zeros_per_block, dim=1, largest=False) + + self._scatter_fold_block_mask( + dim=1, indices=sorted_idx, output_shape=padded_data.shape, block_shape=sparse_block_shape, mask=mask_reshape + ) + + mask.data = mask_reshape.squeeze().reshape(mask.shape).contiguous() + return mask + + def update_mask(self, module, tensor_name, sparsity_level, sparse_block_shape, + zeros_per_block, **kwargs): + values_per_block = reduce((lambda x, y: x * y), sparse_block_shape) + if zeros_per_block > values_per_block: + raise ValueError( + "Number of zeros per block cannot be more than the total number of elements in that block." + ) + if zeros_per_block < 0: + raise ValueError("Number of zeros per block should be positive.") + + mask = getattr(module.parametrizations, tensor_name)[0].mask + if sparsity_level <= 0 or zeros_per_block == 0: + mask.data = torch.ones_like(mask) + elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block): + mask.data = torch.zeros_like(mask) + else: + ww = self.norm_fn(getattr(module, tensor_name)) + tensor_mask = self._make_tensor_mask( + data=ww, input_shape=ww.shape, sparsity_level=sparsity_level, sparse_block_shape=sparse_block_shape + ) + if values_per_block != zeros_per_block: + block_mask = self._make_block_mask(data=ww, sparse_block_shape=sparse_block_shape, + zeros_per_block=zeros_per_block) + tensor_mask = torch.logical_or(tensor_mask, block_mask) + mask.data = tensor_mask diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/_dependency_checks.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/_dependency_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2cb660e5dddbff22b6ee859c3f214c4d484e82 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/_dependency_checks.py @@ -0,0 +1,7 @@ +from .version_requirements import is_installed +import sys +import platform + +has_mpl = is_installed("matplotlib", ">=3.3") + +is_wasm = (sys.platform == "emscripten") or (platform.machine() in ["wasm32", "wasm64"]) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/_geometry.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..2c486e9194aef9e1ce1e6bc43fcd90ea10dd6db6 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/_geometry.py @@ -0,0 +1,54 @@ +__all__ = ['polygon_clip', 'polygon_area'] + +import numpy as np + +from .version_requirements import require + + +@require("matplotlib", ">=3.3") +def polygon_clip(rp, cp, r0, c0, r1, c1): + """Clip a polygon to the given bounding box. + + Parameters + ---------- + rp, cp : (K,) ndarray of double + Row and column coordinates of the polygon. + (r0, c0), (r1, c1) : double + Top-left and bottom-right coordinates of the bounding box. + + Returns + ------- + r_clipped, c_clipped : (L,) ndarray of double + Coordinates of clipped polygon. + + Notes + ----- + This makes use of Sutherland-Hodgman clipping as implemented in + AGG 2.4 and exposed in Matplotlib. + + """ + from matplotlib import path, transforms + + poly = path.Path(np.vstack((rp, cp)).T, closed=True) + clip_rect = transforms.Bbox([[r0, c0], [r1, c1]]) + poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0] + + return poly_clipped[:, 0], poly_clipped[:, 1] + + +def polygon_area(pr, pc): + """Compute the area of a polygon. + + Parameters + ---------- + pr, pc : (K,) array of float + Polygon row and column coordinates. + + Returns + ------- + a : float + Area of the polygon. + """ + pr = np.asarray(pr) + pc = np.asarray(pc) + return 0.5 * np.abs(np.sum((pc[:-1] * pr[1:]) - (pc[1:] * pr[:-1]))) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/coord.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/coord.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ffbc20c1d7832e7a806d72cc58a7bb1606425f --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/coord.py @@ -0,0 +1,124 @@ +import numpy as np +from scipy.spatial import cKDTree, distance + + +def _ensure_spacing(coord, spacing, p_norm, max_out): + """Returns a subset of coord where a minimum spacing is guaranteed. + + Parameters + ---------- + coord : ndarray + The coordinates of the considered points. + spacing : float + the maximum allowed spacing between the points. + p_norm : float + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + ``inf`` corresponds to the Chebyshev distance and 2 to the + Euclidean distance. + max_out: int + If not None, at most the first ``max_out`` candidates are + returned. + + Returns + ------- + output : ndarray + A subset of coord where a minimum spacing is guaranteed. + + """ + + # Use KDtree to find the peaks that are too close to each other + tree = cKDTree(coord) + + indices = tree.query_ball_point(coord, r=spacing, p=p_norm) + rejected_peaks_indices = set() + naccepted = 0 + for idx, candidates in enumerate(indices): + if idx not in rejected_peaks_indices: + # keep current point and the points at exactly spacing from it + candidates.remove(idx) + dist = distance.cdist( + [coord[idx]], coord[candidates], "minkowski", p=p_norm + ).reshape(-1) + candidates = [c for c, d in zip(candidates, dist) if d < spacing] + + # candidates.remove(keep) + rejected_peaks_indices.update(candidates) + naccepted += 1 + if max_out is not None and naccepted >= max_out: + break + + # Remove the peaks that are too close to each other + output = np.delete(coord, tuple(rejected_peaks_indices), axis=0) + if max_out is not None: + output = output[:max_out] + + return output + + +def ensure_spacing( + coords, + spacing=1, + p_norm=np.inf, + min_split_size=50, + max_out=None, + *, + max_split_size=2000, +): + """Returns a subset of coord where a minimum spacing is guaranteed. + + Parameters + ---------- + coords : array_like + The coordinates of the considered points. + spacing : float + the maximum allowed spacing between the points. + p_norm : float + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + ``inf`` corresponds to the Chebyshev distance and 2 to the + Euclidean distance. + min_split_size : int + Minimum split size used to process ``coords`` by batch to save + memory. If None, the memory saving strategy is not applied. + max_out : int + If not None, only the first ``max_out`` candidates are returned. + max_split_size : int + Maximum split size used to process ``coords`` by batch to save + memory. This number was decided by profiling with a large number + of points. Too small a number results in too much looping in + Python instead of C, slowing down the process, while too large + a number results in large memory allocations, slowdowns, and, + potentially, in the process being killed -- see gh-6010. See + benchmark results `here + `_. + + Returns + ------- + output : array_like + A subset of coord where a minimum spacing is guaranteed. + + """ + output = coords + if len(coords): + coords = np.atleast_2d(coords) + if min_split_size is None: + batch_list = [coords] + else: + coord_count = len(coords) + split_idx = [min_split_size] + split_size = min_split_size + while coord_count - split_idx[-1] > max_split_size: + split_size *= 2 + split_idx.append(split_idx[-1] + min(split_size, max_split_size)) + batch_list = np.array_split(coords, split_idx) + + output = np.zeros((0, coords.shape[1]), dtype=coords.dtype) + for batch in batch_list: + output = _ensure_spacing( + np.vstack([output, batch]), spacing, p_norm, max_out + ) + if max_out is not None and len(output) >= max_out: + break + + return output diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/dtype.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..6aed88c21b12bf527d66eadd68f34bbe503f243f --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/dtype.py @@ -0,0 +1,73 @@ +import numpy as np + +# Define classes of supported dtypes and Python scalar types +# Variables ending in `_dtypes` only contain numpy.dtypes of the respective +# class; variables ending in `_types` additionally include Python scalar types. +signed_integer_dtypes = {np.int8, np.int16, np.int32, np.int64} +signed_integer_types = signed_integer_dtypes | {int} + +unsigned_integer_dtypes = {np.uint8, np.uint16, np.uint32, np.uint64} + +integer_dtypes = signed_integer_dtypes | unsigned_integer_dtypes +integer_types = signed_integer_types | unsigned_integer_dtypes + +floating_dtypes = {np.float16, np.float32, np.float64} +floating_types = floating_dtypes | {float} + +complex_dtypes = {np.complex64, np.complex128} +complex_types = complex_dtypes | {complex} + +inexact_dtypes = floating_dtypes | complex_dtypes +inexact_types = floating_types | complex_types + +bool_types = {np.dtype(bool), bool} + +numeric_dtypes = integer_dtypes | inexact_dtypes | {np.bool_} +numeric_types = integer_types | inexact_types | bool_types + + +def numeric_dtype_min_max(dtype): + """Return minimum and maximum representable value for a given dtype. + + A convenient wrapper around `numpy.finfo` and `numpy.iinfo` that + additionally supports numpy.bool as well. + + Parameters + ---------- + dtype : numpy.dtype + The dtype. Tries to convert Python "types" such as int or float, to + the corresponding NumPy dtype. + + Returns + ------- + min, max : number + Minimum and maximum of the given `dtype`. These scalars are themselves + of the given `dtype`. + + Examples + -------- + >>> import numpy as np + >>> numeric_dtype_min_max(np.uint8) + (0, 255) + >>> numeric_dtype_min_max(bool) + (False, True) + >>> numeric_dtype_min_max(np.float64) + (-1.7976931348623157e+308, 1.7976931348623157e+308) + >>> numeric_dtype_min_max(int) + (-9223372036854775808, 9223372036854775807) + """ + dtype = np.dtype(dtype) + if np.issubdtype(dtype, np.integer): + info = np.iinfo(dtype) + min_ = dtype.type(info.min) + max_ = dtype.type(info.max) + elif np.issubdtype(dtype, np.inexact): + info = np.finfo(dtype) + min_ = info.min + max_ = info.max + elif np.issubdtype(dtype, np.dtype(bool)): + min_ = dtype.type(False) + max_ = dtype.type(True) + else: + raise ValueError(f"unsupported dtype {dtype!r}") + return min_, max_ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/filters.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..530454718cd2b794214bc41de34f93fe84413739 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/filters.py @@ -0,0 +1,136 @@ +"""Filters used across multiple skimage submodules. + +These are defined here to avoid circular imports. + +The unit tests remain under skimage/filters/tests/ +""" + +from collections.abc import Iterable + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import ( + _supported_float_type, + convert_to_float, +) + + +def gaussian( + image, + sigma=1, + *, + mode='nearest', + cval=0, + preserve_range=False, + truncate=4.0, + channel_axis=None, + out=None, +): + """Multi-dimensional Gaussian filter. + + Parameters + ---------- + image : ndarray + Input image (grayscale or color) to filter. + sigma : scalar or sequence of scalars, optional + Standard deviation for Gaussian kernel. The standard + deviations of the Gaussian filter are given for each axis as a + sequence, or as a single number, in which case it is equal for + all axes. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The ``mode`` parameter determines how the array borders are + handled, where ``cval`` is the value when mode is equal to + 'constant'. Default is 'nearest'. + cval : scalar, optional + Value to fill past edges of input if ``mode`` is 'constant'. Default + is 0.0 + preserve_range : bool, optional + If True, keep the original range of values. Otherwise, the input + ``image`` is converted according to the conventions of ``img_as_float`` + (Normalized first to values [-1.0 ; 1.0] or [0 ; 1.0] depending on + dtype of input) + + For more information, see: + https://scikit-image.org/docs/dev/user_guide/data_types.html + truncate : float, optional + Truncate the filter at this many standard deviations. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + `channel_axis` was added in 0.19. + out : ndarray, optional + If given, the filtered image will be stored in this array. + + .. versionadded:: 0.23 + `out` was added in 0.23. + + Returns + ------- + filtered_image : ndarray + the filtered array + + Notes + ----- + This function is a wrapper around :func:`scipy.ndimage.gaussian_filter`. + + Integer arrays are converted to float. + + `out` should be of floating-point data type since `gaussian` converts the + input `image` to float. If `out` is not provided, another array + will be allocated and returned as the result. + + The multi-dimensional filter is implemented as a sequence of + one-dimensional convolution filters. The intermediate arrays are + stored in the same data type as the output. Therefore, for output + types with a limited precision, the results may be imprecise + because intermediate results may be stored with insufficient + precision. + + Examples + -------- + >>> import skimage as ski + >>> a = np.zeros((3, 3)) + >>> a[1, 1] = 1 + >>> a + array([[0., 0., 0.], + [0., 1., 0.], + [0., 0., 0.]]) + >>> ski.filters.gaussian(a, sigma=0.4) # mild smoothing + array([[0.00163116, 0.03712502, 0.00163116], + [0.03712502, 0.84496158, 0.03712502], + [0.00163116, 0.03712502, 0.00163116]]) + >>> ski.filters.gaussian(a, sigma=1) # more smoothing + array([[0.05855018, 0.09653293, 0.05855018], + [0.09653293, 0.15915589, 0.09653293], + [0.05855018, 0.09653293, 0.05855018]]) + >>> # Several modes are possible for handling boundaries + >>> ski.filters.gaussian(a, sigma=1, mode='reflect') + array([[0.08767308, 0.12075024, 0.08767308], + [0.12075024, 0.16630671, 0.12075024], + [0.08767308, 0.12075024, 0.08767308]]) + >>> # For RGB images, each is filtered separately + >>> image = ski.data.astronaut() + >>> filtered_img = ski.filters.gaussian(image, sigma=1, channel_axis=-1) + + """ + if np.any(np.asarray(sigma) < 0.0): + raise ValueError("Sigma values less than zero are not valid") + if channel_axis is not None: + # do not filter across channels + if not isinstance(sigma, Iterable): + sigma = [sigma] * (image.ndim - 1) + if len(sigma) == image.ndim - 1: + sigma = list(sigma) + sigma.insert(channel_axis % image.ndim, 0) + image = convert_to_float(image, preserve_range) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if (out is not None) and (not np.issubdtype(out.dtype, np.floating)): + raise ValueError(f"dtype of `out` must be float; got {out.dtype!r}.") + return ndi.gaussian_filter( + image, sigma, output=out, mode=mode, cval=cval, truncate=truncate + ) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/interpolation.cpython-310-x86_64-linux-gnu.so b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/interpolation.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b7b0a3f00e12bf4456f0929fc4095ac3cae05f03 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/interpolation.cpython-310-x86_64-linux-gnu.so differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tester.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tester.py new file mode 100644 index 0000000000000000000000000000000000000000..f1247e4111d85d2717fe0b05ab180fe327e65fc0 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tester.py @@ -0,0 +1,131 @@ +import os +import sys + + +def _show_skimage_info(): + import skimage + + print(f"skimage version {skimage.__version__}") + + +class PytestTester: + """ + Pytest test runner. + + This class is made available in ``skimage._shared.testing``, and a test + function is typically added to a package's __init__.py like so:: + + from skimage._shared.testing import PytestTester + test = PytestTester(__name__) + del PytestTester + + Calling this test function finds and runs all tests associated with the + module and all its sub-modules. + + Attributes + ---------- + module_name : str + Full path to the package to test. + + Parameters + ---------- + module_name : module name + The name of the module to test. + + """ + + def __init__(self, module_name): + self.module_name = module_name + + def __call__( + self, + label='fast', + verbose=1, + extra_argv=None, + doctests=False, + coverage=False, + durations=-1, + tests=None, + ): + """ + Run tests for module using pytest. + + Parameters + ---------- + label : {'fast', 'full'}, optional + Identifies the tests to run. When set to 'fast', tests decorated + with `pytest.mark.slow` are skipped, when 'full', the slow marker + is ignored. + verbose : int, optional + Verbosity value for test outputs, in the range 1-3. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytests. + doctests : bool, optional + .. note:: Not supported + coverage : bool, optional + If True, report coverage of scikit-image code. Default is False. + Requires installation of (pip) pytest-cov. + durations : int, optional + If < 0, do nothing, If 0, report time of all tests, if > 0, + report the time of the slowest `timer` tests. Default is -1. + tests : test or list of tests + Tests to be executed with pytest '--pyargs' + + Returns + ------- + result : bool + Return True on success, false otherwise. + """ + import pytest + + module = sys.modules[self.module_name] + module_path = os.path.abspath(module.__path__[0]) + + # setup the pytest arguments + pytest_args = ["-l"] + + # offset verbosity. The "-q" cancels a "-v". + pytest_args += ["-q"] + + # Filter out annoying import messages. Want these in both develop and + # release mode. + pytest_args += [ + "-W ignore:Not importing directory", + "-W ignore:numpy.dtype size changed", + "-W ignore:numpy.ufunc size changed", + ] + + if doctests: + raise ValueError("Doctests not supported") + + if extra_argv: + pytest_args += list(extra_argv) + + if verbose > 1: + pytest_args += ["-" + "v" * (verbose - 1)] + + if coverage: + pytest_args += ["--cov=" + module_path] + + if label == "fast": + pytest_args += ["-m", "not slow"] + elif label != "full": + pytest_args += ["-m", label] + + if durations >= 0: + pytest_args += [f"--durations={durations}"] + + if tests is None: + tests = [self.module_name] + + pytest_args += ["--pyargs"] + list(tests) + + # run tests. + _show_skimage_info() + + try: + code = pytest.main(pytest_args) + except SystemExit as exc: + code = exc.code + + return code == 0 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/testing.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..da038563846e948b1e2fb647380ad6b9500b8aa5 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/testing.py @@ -0,0 +1,311 @@ +""" +Testing utilities. +""" + +import os +import platform +import re +import struct +import sys +import functools +import inspect +from tempfile import NamedTemporaryFile + +import numpy as np +from numpy import testing +from numpy.testing import ( + TestCase, + assert_, + assert_warns, + assert_no_warnings, + assert_equal, + assert_almost_equal, + assert_array_equal, + assert_allclose, + assert_array_almost_equal, + assert_array_almost_equal_nulp, + assert_array_less, +) + +from .. import data, io +from ..data._fetchers import _fetch +from ..util import img_as_uint, img_as_float, img_as_int, img_as_ubyte +from ._warnings import expected_warnings +from ._dependency_checks import is_wasm + +import pytest + + +skipif = pytest.mark.skipif +xfail = pytest.mark.xfail +parametrize = pytest.mark.parametrize +raises = pytest.raises +fixture = pytest.fixture + +SKIP_RE = re.compile(r"(\s*>>>.*?)(\s*)#\s*skip\s+if\s+(.*)$") + +# true if python is running in 32bit mode +# Calculate the size of a void * pointer in bits +# https://docs.python.org/3/library/struct.html +arch32 = struct.calcsize("P") * 8 == 32 + + +def assert_less(a, b, msg=None): + message = f"{a!r} is not lower than {b!r}" + if msg is not None: + message += ": " + msg + assert a < b, message + + +def assert_greater(a, b, msg=None): + message = f"{a!r} is not greater than {b!r}" + if msg is not None: + message += ": " + msg + assert a > b, message + + +def doctest_skip_parser(func): + """Decorator replaces custom skip test markup in doctests + + Say a function has a docstring:: + + >>> something, HAVE_AMODULE, HAVE_BMODULE = 0, False, False + >>> something # skip if not HAVE_AMODULE + 0 + >>> something # skip if HAVE_BMODULE + 0 + + This decorator will evaluate the expression after ``skip if``. If this + evaluates to True, then the comment is replaced by ``# doctest: +SKIP``. If + False, then the comment is just removed. The expression is evaluated in the + ``globals`` scope of `func`. + + For example, if the module global ``HAVE_AMODULE`` is False, and module + global ``HAVE_BMODULE`` is False, the returned function will have docstring:: + + >>> something # doctest: +SKIP + >>> something + else # doctest: +SKIP + >>> something # doctest: +SKIP + + """ + lines = func.__doc__.split('\n') + new_lines = [] + for line in lines: + match = SKIP_RE.match(line) + if match is None: + new_lines.append(line) + continue + code, space, expr = match.groups() + + try: + # Works as a function decorator + if eval(expr, func.__globals__): + code = code + space + "# doctest: +SKIP" + except AttributeError: + # Works as a class decorator + if eval(expr, func.__init__.__globals__): + code = code + space + "# doctest: +SKIP" + + new_lines.append(code) + func.__doc__ = "\n".join(new_lines) + return func + + +def roundtrip(image, plugin, suffix): + """Save and read an image using a specified plugin""" + if '.' not in suffix: + suffix = '.' + suffix + with NamedTemporaryFile(suffix=suffix, delete=False) as temp_file: + fname = temp_file.name + io.imsave(fname, image, plugin=plugin) + new = io.imread(fname, plugin=plugin) + try: + os.remove(fname) + except Exception: + pass + return new + + +def color_check(plugin, fmt='png'): + """Check roundtrip behavior for color images. + + All major input types should be handled as ubytes and read + back correctly. + """ + img = img_as_ubyte(data.chelsea()) + r1 = roundtrip(img, plugin, fmt) + testing.assert_allclose(img, r1) + + img2 = img > 128 + r2 = roundtrip(img2, plugin, fmt) + testing.assert_allclose(img2, r2.astype(bool)) + + img3 = img_as_float(img) + r3 = roundtrip(img3, plugin, fmt) + testing.assert_allclose(r3, img) + + img4 = img_as_int(img) + if fmt.lower() in (('tif', 'tiff')): + img4 -= 100 + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img4) + else: + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img_as_ubyte(img4)) + + img5 = img_as_uint(img) + r5 = roundtrip(img5, plugin, fmt) + testing.assert_allclose(r5, img) + + +def mono_check(plugin, fmt='png'): + """Check the roundtrip behavior for images that support most types. + + All major input types should be handled. + """ + + img = img_as_ubyte(data.moon()) + r1 = roundtrip(img, plugin, fmt) + testing.assert_allclose(img, r1) + + img2 = img > 128 + r2 = roundtrip(img2, plugin, fmt) + testing.assert_allclose(img2, r2.astype(bool)) + + img3 = img_as_float(img) + r3 = roundtrip(img3, plugin, fmt) + if r3.dtype.kind == 'f': + testing.assert_allclose(img3, r3) + else: + testing.assert_allclose(r3, img_as_uint(img)) + + img4 = img_as_int(img) + if fmt.lower() in (('tif', 'tiff')): + img4 -= 100 + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img4) + else: + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img_as_uint(img4)) + + img5 = img_as_uint(img) + r5 = roundtrip(img5, plugin, fmt) + testing.assert_allclose(r5, img5) + + +def fetch(data_filename): + """Attempt to fetch data, but if unavailable, skip the tests.""" + try: + return _fetch(data_filename) + except (ConnectionError, ModuleNotFoundError): + pytest.skip(f'Unable to download {data_filename}', allow_module_level=True) + + +# Ref: about the lack of threading support in WASM, please see +# https://github.com/pyodide/pyodide/issues/237 +def run_in_parallel(num_threads=2, warnings_matching=None): + """Decorator to run the same function multiple times in parallel. + + This decorator is useful to ensure that separate threads execute + concurrently and correctly while releasing the GIL. + + It is currently skipped when running on WASM-based platforms, as + the threading module is not supported. + + Parameters + ---------- + num_threads : int, optional + The number of times the function is run in parallel. + + warnings_matching: list or None + This parameter is passed on to `expected_warnings` so as not to have + race conditions with the warnings filters. A single + `expected_warnings` context manager is used for all threads. + If None, then no warnings are checked. + + """ + + assert num_threads > 0 + + def wrapper(func): + if is_wasm: + # Threading isn't supported on WASM, return early + return func + + import threading + + @functools.wraps(func) + def inner(*args, **kwargs): + with expected_warnings(warnings_matching): + threads = [] + for i in range(num_threads - 1): + thread = threading.Thread(target=func, args=args, kwargs=kwargs) + threads.append(thread) + for thread in threads: + thread.start() + + func(*args, **kwargs) + + for thread in threads: + thread.join() + + return inner + + return wrapper + + +def assert_stacklevel(warnings, *, offset=-1): + """Assert correct stacklevel of captured warnings. + + When scikit-image raises warnings, the stacklevel should ideally be set + so that the origin of the warnings will point to the public function + that was called by the user and not necessarily the very place where the + warnings were emitted (which may be inside some internal function). + This utility function helps with checking that + the stacklevel was set correctly on warnings captured by `pytest.warns`. + + Parameters + ---------- + warnings : collections.abc.Iterable[warning.WarningMessage] + Warnings that were captured by `pytest.warns`. + offset : int, optional + Offset from the line this function is called to the line were the + warning is supposed to originate from. For multiline calls, the + first line is relevant. Defaults to -1 which corresponds to the line + right above the one where this function is called. + + Raises + ------ + AssertionError + If a warning in `warnings` does not match the expected line number or + file name. + + Examples + -------- + >>> def test_something(): + ... with pytest.warns(UserWarning, match="some message") as record: + ... something_raising_a_warning() + ... assert_stacklevel(record) + ... + >>> def test_another_thing(): + ... with pytest.warns(UserWarning, match="some message") as record: + ... iam_raising_many_warnings( + ... "A long argument that forces the call to wrap." + ... ) + ... assert_stacklevel(record, offset=-3) + """ + __tracebackhide__ = True # Hide traceback for py.test + + frame = inspect.stack()[1].frame # 0 is current frame, 1 is outer frame + line_number = frame.f_lineno + offset + filename = frame.f_code.co_filename + expected = f"{filename}:{line_number}" + for warning in warnings: + actual = f"{warning.filename}:{warning.lineno}" + msg = ( + "Warning with wrong stacklevel:\n" + f" Expected: {expected}\n" + f" Actual: {actual}\n" + f" {warning.category.__name__}: {warning.message}" + ) + assert actual == expected, msg diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__init__.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_coord.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_coord.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09c91f0d81e60ee6e4cf4d387163910e5e9afdae Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_coord.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_dtype.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_dtype.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a88a96eee3d084631faadc35bb1e8a495b678d3b Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_dtype.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_fast_exp.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_fast_exp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6370a1cf2d153a309660b21971a4cac0565842b2 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_fast_exp.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_geometry.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_geometry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45c7e2c01f23f7a9987151c250922cace7131c87 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_geometry.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_interpolation.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_interpolation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d2c9ddedeb4f565e4530933184d7761ba2ab5ce Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_interpolation.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_safe_as_int.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_safe_as_int.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0661ac22c0c207778e35bd897f81740bb47e3742 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_safe_as_int.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_utils.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b7c1eb103efb74eb2355c032b797008d61d11ed Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_utils.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_version_requirements.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_version_requirements.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edcdf6dfefb13255e9a5817ebdf8f88b54909df2 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/__pycache__/test_version_requirements.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_coord.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_coord.py new file mode 100644 index 0000000000000000000000000000000000000000..0aad2685ac034a1f1fe29a47411973b997913d88 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_coord.py @@ -0,0 +1,91 @@ +import time + +import numpy as np +import pytest +from scipy.spatial.distance import pdist, minkowski + +from skimage._shared.coord import ensure_spacing + + +@pytest.mark.parametrize("p", [1, 2, np.inf]) +@pytest.mark.parametrize("size", [30, 50, None]) +def test_ensure_spacing_trivial(p, size): + # --- Empty input + assert ensure_spacing([], p_norm=p) == [] + + # --- A unique point + coord = np.random.randn(1, 2) + assert np.array_equal(coord, ensure_spacing(coord, p_norm=p, min_split_size=size)) + + # --- Verified spacing + coord = np.random.randn(100, 2) + + # --- 0 spacing + assert np.array_equal( + coord, ensure_spacing(coord, spacing=0, p_norm=p, min_split_size=size) + ) + + # Spacing is chosen to be half the minimum distance + spacing = pdist(coord, metric=minkowski, p=p).min() * 0.5 + + out = ensure_spacing(coord, spacing=spacing, p_norm=p, min_split_size=size) + + assert np.array_equal(coord, out) + + +@pytest.mark.parametrize("ndim", [1, 2, 3, 4, 5]) +@pytest.mark.parametrize("size", [2, 10, None]) +def test_ensure_spacing_nD(ndim, size): + coord = np.ones((5, ndim)) + + expected = np.ones((1, ndim)) + + assert np.array_equal(ensure_spacing(coord, min_split_size=size), expected) + + +@pytest.mark.parametrize("p", [1, 2, np.inf]) +@pytest.mark.parametrize("size", [50, 100, None]) +def test_ensure_spacing_batch_processing(p, size): + coord = np.random.randn(100, 2) + + # --- Consider the average distance btween the point as spacing + spacing = np.median(pdist(coord, metric=minkowski, p=p)) + + expected = ensure_spacing(coord, spacing=spacing, p_norm=p) + + assert np.array_equal( + ensure_spacing(coord, spacing=spacing, p_norm=p, min_split_size=size), expected + ) + + +def test_max_batch_size(): + """Small batches are slow, large batches -> large allocations -> also slow. + + https://github.com/scikit-image/scikit-image/pull/6035#discussion_r751518691 + """ + coords = np.random.randint(low=0, high=1848, size=(40000, 2)) + tstart = time.time() + ensure_spacing(coords, spacing=100, min_split_size=50, max_split_size=2000) + dur1 = time.time() - tstart + + tstart = time.time() + ensure_spacing(coords, spacing=100, min_split_size=50, max_split_size=20000) + dur2 = time.time() - tstart + + # Originally checked dur1 < dur2 to assert that the default batch size was + # faster than a much larger batch size. However, on rare occasion a CI test + # case would fail with dur1 ~5% larger than dur2. To be more robust to + # variable load or differences across architectures, we relax this here. + assert dur1 < 1.33 * dur2 + + +@pytest.mark.parametrize("p", [1, 2, np.inf]) +@pytest.mark.parametrize("size", [30, 50, None]) +def test_ensure_spacing_p_norm(p, size): + coord = np.random.randn(100, 2) + + # --- Consider the average distance btween the point as spacing + spacing = np.median(pdist(coord, metric=minkowski, p=p)) + out = ensure_spacing(coord, spacing=spacing, p_norm=p, min_split_size=size) + + assert pdist(out, metric=minkowski, p=p).min() > spacing diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_dtype.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..c4afdce96e54be71335dec5c1ce5fc7cc7cafcda --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_dtype.py @@ -0,0 +1,14 @@ +import numpy as np +import pytest + + +from ..dtype import numeric_dtype_min_max, numeric_types + + +class Test_numeric_dtype_min_max: + @pytest.mark.parametrize("dtype", numeric_types) + def test_all_numeric_types(self, dtype): + min_, max_ = numeric_dtype_min_max(dtype) + assert np.isscalar(min_) + assert np.isscalar(max_) + assert min_ < max_ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_fast_exp.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_fast_exp.py new file mode 100644 index 0000000000000000000000000000000000000000..9d26885f8b06d913bfbb86b932fe0840d17c2c1a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_fast_exp.py @@ -0,0 +1,20 @@ +from ..fast_exp import fast_exp +import numpy as np + + +def test_fast_exp(): + X = np.linspace(-5, 0, 5000, endpoint=True) + + # Ground truth + Y = np.exp(X) + + # Approximation at double precision + _y_f64 = np.array([fast_exp['float64_t'](x) for x in X]) + + # Approximation at single precision + _y_f32 = np.array( + [fast_exp['float32_t'](x) for x in X.astype('float32')], dtype='float32' + ) + + for _y in [_y_f64, _y_f32]: + assert np.abs(Y - _y).mean() < 3e-3 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_geometry.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..153dfedbc808a39fa2de747f275235d4708eaa25 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_geometry.py @@ -0,0 +1,81 @@ +import pytest +from skimage._shared._geometry import polygon_clip, polygon_area + +import numpy as np +from numpy.testing import assert_equal, assert_almost_equal + +pytest.importorskip("matplotlib") + + +hand = np.array( + [ + [1.64516129, 1.16145833], + [1.64516129, 1.59375], + [1.35080645, 1.921875], + [1.375, 2.18229167], + [1.68548387, 1.9375], + [1.60887097, 2.55208333], + [1.68548387, 2.69791667], + [1.76209677, 2.56770833], + [1.83064516, 1.97395833], + [1.89516129, 2.75], + [1.9516129, 2.84895833], + [2.01209677, 2.76041667], + [1.99193548, 1.99479167], + [2.11290323, 2.63020833], + [2.2016129, 2.734375], + [2.25403226, 2.60416667], + [2.14919355, 1.953125], + [2.30645161, 2.36979167], + [2.39112903, 2.36979167], + [2.41532258, 2.1875], + [2.1733871, 1.703125], + [2.07782258, 1.16666667], + ] +) + + +def test_polygon_area(): + x = [0, 0, 1, 1] + y = [0, 1, 1, 0] + + assert_almost_equal(polygon_area(y, x), 1) + + x = [0, 0, 1] + y = [0, 1, 1] + + assert_almost_equal(polygon_area(y, x), 0.5) + + x = [0, 0, 0.5, 1, 1, 0.5] + y = [0, 1, 0.5, 1, 0, 0.5] + + assert_almost_equal(polygon_area(y, x), 0.5) + + +def test_poly_clip(): + x = [0, 1, 2, 1] + y = [0, -1, 0, 1] + + yc, xc = polygon_clip(y, x, 0, 0, 1, 1) + assert_equal(polygon_area(yc, xc), 0.5) + + x = [-1, 1.5, 1.5, -1] + y = [0.5, 0.5, 1.5, 1.5] + yc, xc = polygon_clip(y, x, 0, 0, 1, 1) + assert_equal(polygon_area(yc, xc), 0.5) + + +def test_hand_clip(): + (r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5) + clip_r, clip_c = polygon_clip(hand[:, 1], hand[:, 0], r0, c0, r1, c1) + assert_equal(clip_r.size, 19) + assert_equal(clip_r[0], clip_r[-1]) + assert_equal(clip_c[0], clip_c[-1]) + + (r0, c0, r1, c1) = (1.0, 1.5, 1.7, 2.5) + clip_r, clip_c = polygon_clip(hand[:, 1], hand[:, 0], r0, c0, r1, c1) + assert_equal(clip_r.size, 6) + + (r0, c0, r1, c1) = (1.0, 1.5, 1.5, 2.5) + clip_r, clip_c = polygon_clip(hand[:, 1], hand[:, 0], r0, c0, r1, c1) + assert_equal(clip_r.size, 5) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_interpolation.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..1b795b9909ad485000402d09b88d0302f8a95fea --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_interpolation.py @@ -0,0 +1,28 @@ +from skimage._shared.interpolation import coord_map_py +from skimage._shared.testing import assert_array_equal + + +def test_coord_map(): + symmetric = [coord_map_py(4, n, 'S') for n in range(-6, 6)] + expected_symmetric = [2, 3, 3, 2, 1, 0, 0, 1, 2, 3, 3, 2] + assert_array_equal(symmetric, expected_symmetric) + + wrap = [coord_map_py(4, n, 'W') for n in range(-6, 6)] + expected_wrap = [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1] + assert_array_equal(wrap, expected_wrap) + + edge = [coord_map_py(4, n, 'E') for n in range(-6, 6)] + expected_edge = [0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 3] + assert_array_equal(edge, expected_edge) + + reflect = [coord_map_py(4, n, 'R') for n in range(-6, 6)] + expected_reflect = [0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1] + assert_array_equal(reflect, expected_reflect) + + reflect = [coord_map_py(1, n, 'R') for n in range(-6, 6)] + expected_reflect = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + assert_array_equal(reflect, expected_reflect) + + other = [coord_map_py(4, n, 'undefined') for n in range(-6, 6)] + expected_other = list(range(-6, 6)) + assert_array_equal(other, expected_other) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_safe_as_int.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_safe_as_int.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5cb003a1b1ae81a54989a915bab1bbff97b0b2 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_safe_as_int.py @@ -0,0 +1,41 @@ +import numpy as np +from skimage._shared.utils import safe_as_int +from skimage._shared import testing + + +def test_int_cast_not_possible(): + with testing.raises(ValueError): + safe_as_int(7.1) + with testing.raises(ValueError): + safe_as_int([7.1, 0.9]) + with testing.raises(ValueError): + safe_as_int(np.r_[7.1, 0.9]) + with testing.raises(ValueError): + safe_as_int((7.1, 0.9)) + with testing.raises(ValueError): + safe_as_int(((3, 4, 1), (2, 7.6, 289))) + with testing.raises(ValueError): + safe_as_int(7.1, 0.09) + with testing.raises(ValueError): + safe_as_int([7.1, 0.9], 0.09) + with testing.raises(ValueError): + safe_as_int(np.r_[7.1, 0.9], 0.09) + with testing.raises(ValueError): + safe_as_int((7.1, 0.9), 0.09) + with testing.raises(ValueError): + safe_as_int(((3, 4, 1), (2, 7.6, 289)), 0.25) + + +def test_int_cast_possible(): + testing.assert_equal(safe_as_int(7.1, atol=0.11), 7) + testing.assert_equal(safe_as_int(-7.1, atol=0.11), -7) + testing.assert_equal(safe_as_int(41.9, atol=0.11), 42) + testing.assert_array_equal( + safe_as_int([2, 42, 5789234.0, 87, 4]), np.r_[2, 42, 5789234, 87, 4] + ) + testing.assert_array_equal( + safe_as_int( + np.r_[[[3, 4, 1.000000001], [7, 2, -8.999999999], [6, 9, -4234918347.0]]] + ), + np.r_[[[3, 4, 1], [7, 2, -9], [6, 9, -4234918347]]], + ) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_testing.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..17969348b19f7590dfcf01a9bec8b01f6f843973 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_testing.py @@ -0,0 +1,154 @@ +"""Testing decorators module""" + +import inspect +import re +import warnings + +import pytest +from numpy.testing import assert_equal +from skimage._shared.testing import ( + doctest_skip_parser, + run_in_parallel, + assert_stacklevel, +) +from skimage._shared import testing +from skimage._shared._dependency_checks import is_wasm + +from skimage._shared._warnings import expected_warnings +from warnings import warn + + +def test_skipper(): + def f(): + pass + + class c: + def __init__(self): + self.me = "I think, therefore..." + + docstring = """ Header + + >>> something # skip if not HAVE_AMODULE + >>> something + else + >>> a = 1 # skip if not HAVE_BMODULE + >>> something2 # skip if HAVE_AMODULE + """ + f.__doc__ = docstring + c.__doc__ = docstring + + global HAVE_AMODULE, HAVE_BMODULE + HAVE_AMODULE = False + HAVE_BMODULE = True + + f2 = doctest_skip_parser(f) + c2 = doctest_skip_parser(c) + assert f is f2 + assert c is c2 + + expected = """ Header + + >>> something # doctest: +SKIP + >>> something + else + >>> a = 1 + >>> something2 + """ + assert_equal(f2.__doc__, expected) + assert_equal(c2.__doc__, expected) + + HAVE_AMODULE = True + HAVE_BMODULE = False + f.__doc__ = docstring + c.__doc__ = docstring + f2 = doctest_skip_parser(f) + c2 = doctest_skip_parser(c) + + assert f is f2 + expected = """ Header + + >>> something + >>> something + else + >>> a = 1 # doctest: +SKIP + >>> something2 # doctest: +SKIP + """ + assert_equal(f2.__doc__, expected) + assert_equal(c2.__doc__, expected) + + del HAVE_AMODULE + f.__doc__ = docstring + c.__doc__ = docstring + with testing.raises(NameError): + doctest_skip_parser(f) + with testing.raises(NameError): + doctest_skip_parser(c) + + +@pytest.mark.skipif(is_wasm, reason="Cannot start threads in WASM") +def test_run_in_parallel(): + state = [] + + @run_in_parallel() + def change_state1(): + state.append(None) + + change_state1() + assert len(state) == 2 + + @run_in_parallel(num_threads=1) + def change_state2(): + state.append(None) + + change_state2() + assert len(state) == 3 + + @run_in_parallel(num_threads=3) + def change_state3(): + state.append(None) + + change_state3() + assert len(state) == 6 + + +@pytest.mark.skipif(is_wasm, reason="Cannot run parallel code in WASM") +def test_parallel_warning(): + @run_in_parallel() + def change_state_warns_fails(): + warn("Test warning for test parallel", stacklevel=2) + + with expected_warnings(['Test warning for test parallel']): + change_state_warns_fails() + + @run_in_parallel(warnings_matching=['Test warning for test parallel']) + def change_state_warns_passes(): + warn("Test warning for test parallel", stacklevel=2) + + change_state_warns_passes() + + +def test_expected_warnings_noop(): + # This will ensure the line beolow it behaves like a no-op + with expected_warnings(['Expected warnings test']): + # This should behave as a no-op + with expected_warnings(None): + warn('Expected warnings test') + + +class Test_assert_stacklevel: + def raise_warning(self, *args, **kwargs): + warnings.warn(*args, **kwargs) + + def test_correct_stacklevel(self): + # Should pass if stacklevel is set correctly + with pytest.warns(UserWarning, match="passes") as record: + self.raise_warning("passes", UserWarning, stacklevel=2) + assert_stacklevel(record) + + @pytest.mark.parametrize("level", [1, 3]) + def test_wrong_stacklevel(self, level): + # AssertionError should be raised for wrong stacklevel + with pytest.warns(UserWarning, match="wrong") as record: + self.raise_warning("wrong", UserWarning, stacklevel=level) + # Check that message contains expected line on right side + line_number = inspect.currentframe().f_lineno - 2 + regex = ".*" + re.escape(f"Expected: {__file__}:{line_number}") + with pytest.raises(AssertionError, match=regex): + assert_stacklevel(record, offset=-5) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_utils.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e21e3b9cda808db42e655ee85777d68fe167fb --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_utils.py @@ -0,0 +1,516 @@ +import sys +import warnings + +import numpy as np +import pytest + +from skimage._shared import testing +from skimage._shared.utils import ( + _supported_float_type, + _validate_interpolation_order, + change_default_value, + channel_as_last_axis, + check_nD, + deprecate_func, + deprecate_parameter, + DEPRECATED, +) + +complex_dtypes = [np.complex64, np.complex128] +if hasattr(np, 'complex256'): + complex_dtypes += [np.complex256] + +have_numpydoc = False +try: + import numpydoc # noqa: F401 + + have_numpydoc = True +except ImportError: + pass + + +def test_change_default_value(): + @change_default_value('arg1', new_value=-1, changed_version='0.12') + def foo(arg0, arg1=0, arg2=1): + """Expected docstring""" + return arg0, arg1, arg2 + + @change_default_value( + 'arg1', + new_value=-1, + changed_version='0.12', + warning_msg="Custom warning message", + ) + def bar(arg0, arg1=0, arg2=1): + """Expected docstring""" + return arg0, arg1, arg2 + + # Assert warning messages + with pytest.warns(FutureWarning) as record: + assert foo(0) == (0, 0, 1) + assert bar(0) == (0, 0, 1) + + expected_msg = ( + "The new recommended value for arg1 is -1. Until " + "version 0.12, the default arg1 value is 0. From " + "version 0.12, the arg1 default value will be -1. " + "To avoid this warning, please explicitly set arg1 value." + ) + + assert str(record[0].message) == expected_msg + assert str(record[1].message) == "Custom warning message" + + # Assert that nothing happens if arg1 is set + with warnings.catch_warnings(record=True) as recorded: + # No kwargs + assert foo(0, 2) == (0, 2, 1) + assert foo(0, arg1=0) == (0, 0, 1) + + # Function name and doc is preserved + assert foo.__name__ == 'foo' + if sys.flags.optimize < 2: + # if PYTHONOPTIMIZE is set to 2, docstrings are stripped + assert foo.__doc__ == 'Expected docstring' + # Assert no warnings were raised + assert len(recorded) == 0 + + +def test_check_nD(): + z = np.random.random(200**2).reshape((200, 200)) + x = z[10:30, 30:10] + with testing.raises(ValueError): + check_nD(x, 2) + + +@pytest.mark.parametrize( + 'dtype', [bool, int, np.uint8, np.uint16, float, np.float32, np.float64] +) +@pytest.mark.parametrize('order', [None, -1, 0, 1, 2, 3, 4, 5, 6]) +def test_validate_interpolation_order(dtype, order): + if order is None: + # Default order + assert _validate_interpolation_order(dtype, None) == 0 if dtype == bool else 1 + elif order < 0 or order > 5: + # Order not in valid range + with testing.raises(ValueError): + _validate_interpolation_order(dtype, order) + elif dtype == bool and order != 0: + # Deprecated order for bool array + with pytest.raises(ValueError): + _validate_interpolation_order(bool, order) + else: + # Valid use case + assert _validate_interpolation_order(dtype, order) == order + + +@pytest.mark.parametrize( + 'dtype', + [ + bool, + np.float16, + np.float32, + np.float64, + np.uint8, + np.uint16, + np.uint32, + np.uint64, + np.int8, + np.int16, + np.int32, + np.int64, + ], +) +def test_supported_float_dtype_real(dtype): + float_dtype = _supported_float_type(dtype) + if dtype in [np.float16, np.float32]: + assert float_dtype == np.float32 + else: + assert float_dtype == np.float64 + + +@pytest.mark.parametrize('dtype', complex_dtypes) +@pytest.mark.parametrize('allow_complex', [False, True]) +def test_supported_float_dtype_complex(dtype, allow_complex): + if allow_complex: + float_dtype = _supported_float_type(dtype, allow_complex=allow_complex) + if dtype == np.complex64: + assert float_dtype == np.complex64 + else: + assert float_dtype == np.complex128 + else: + with testing.raises(ValueError): + _supported_float_type(dtype, allow_complex=allow_complex) + + +@pytest.mark.parametrize('dtype', ['f', 'float32', np.float32, np.dtype(np.float32)]) +def test_supported_float_dtype_input_kinds(dtype): + assert _supported_float_type(dtype) == np.float32 + + +@pytest.mark.parametrize( + 'dtypes, expected', + [ + ((np.float16, np.float64), np.float64), + ((np.float32, np.uint16, np.int8), np.float64), + ((np.float32, np.float16), np.float32), + ], +) +def test_supported_float_dtype_sequence(dtypes, expected): + float_dtype = _supported_float_type(dtypes) + assert float_dtype == expected + + +@channel_as_last_axis(multichannel_output=False) +def _decorated_channel_axis_size(x, *, channel_axis=None): + if channel_axis is None: + return None + assert channel_axis == -1 + return x.shape[-1] + + +@testing.parametrize('channel_axis', [None, 0, 1, 2, -1, -2, -3]) +def test_decorated_channel_axis_shape(channel_axis): + # Verify that channel_as_last_axis modifies the channel_axis as expected + + # need unique size per axis here + x = np.zeros((2, 3, 4)) + + size = _decorated_channel_axis_size(x, channel_axis=channel_axis) + if channel_axis is None: + assert size is None + else: + assert size == x.shape[channel_axis] + + +@deprecate_func( + deprecated_version="x", removed_version="y", hint="You are on your own." +) +def _deprecated_func(): + """Dummy function used in `test_deprecate_func`. + + The decorated function must be outside the test function, otherwise it + seems that the warning does not point at the calling location. + """ + + +def test_deprecate_func(): + with pytest.warns(FutureWarning) as record: + _deprecated_func() + testing.assert_stacklevel(record) + + assert len(record) == 1 + assert record[0].message.args[0] == ( + "`_deprecated_func` is deprecated since version x and will be removed in " + "version y. You are on your own." + ) + + +@deprecate_parameter("old1", start_version="0.10", stop_version="0.12") +@deprecate_parameter("old0", start_version="0.10", stop_version="0.12") +def _func_deprecated_params(arg0, old0=DEPRECATED, old1=DEPRECATED, arg1=None): + """Expected docstring. + + Parameters + ---------- + arg0 : int + First unchanged parameter. + arg1 : int, optional + Second unchanged parameter. + """ + return arg0, old0, old1, arg1 + + +@deprecate_parameter("old1", new_name="new0", start_version="0.10", stop_version="0.12") +@deprecate_parameter("old0", new_name="new1", start_version="0.10", stop_version="0.12") +def _func_replace_params( + arg0, old0=DEPRECATED, old1=DEPRECATED, new0=None, new1=None, arg1=None +): + """Expected docstring. + + Parameters + ---------- + arg0 : int + First unchanged parameter. + new0 : int, optional + First new parameter. + + .. versionadded:: 0.10 + new1 : int, optional + Second new parameter. + + .. versionadded:: 0.10 + arg1 : int, optional + Second unchanged parameter. + """ + return arg0, old0, old1, new0, new1, arg1 + + +class Test_deprecate_parameter: + @pytest.mark.skipif(not have_numpydoc, reason="requires numpydoc") + def test_docstring_removed_param(self): + # function name and doc are preserved + assert _func_deprecated_params.__name__ == "_func_deprecated_params" + if sys.flags.optimize < 2: + # if PYTHONOPTIMIZE is set to 2, docstrings are stripped + assert ( + _func_deprecated_params.__doc__ + == """Expected docstring. + + + Parameters + ---------- + arg0 : int + First unchanged parameter. + arg1 : int, optional + Second unchanged parameter. + + Other Parameters + ---------------- + old0 : DEPRECATED + `old0` is deprecated. + + .. deprecated:: 0.10 + old1 : DEPRECATED + `old1` is deprecated. + + .. deprecated:: 0.10 +""" + ) + + @pytest.mark.skipif(not have_numpydoc, reason="requires numpydoc") + def test_docstring_replaced_param(self): + assert _func_replace_params.__name__ == "_func_replace_params" + if sys.flags.optimize < 2: + # if PYTHONOPTIMIZE is set to 2, docstrings are stripped + assert ( + _func_replace_params.__doc__ + == """Expected docstring. + + + Parameters + ---------- + arg0 : int + First unchanged parameter. + new0 : int, optional + First new parameter. + + .. versionadded:: 0.10 + new1 : int, optional + Second new parameter. + + .. versionadded:: 0.10 + arg1 : int, optional + Second unchanged parameter. + + Other Parameters + ---------------- + old0 : DEPRECATED + Deprecated in favor of `new1`. + + .. deprecated:: 0.10 + old1 : DEPRECATED + Deprecated in favor of `new0`. + + .. deprecated:: 0.10 +""" + ) + + def test_warning_removed_param(self): + match = ( + r".*`old[01]` is deprecated since version 0\.10 and will be removed " + r"in 0\.12.* see the documentation of .*_func_deprecated_params`." + ) + with pytest.warns(FutureWarning, match=match): + assert _func_deprecated_params(1, 2) == (1, 2, DEPRECATED, None) + with pytest.warns(FutureWarning, match=match): + assert _func_deprecated_params(1, 2, 3) == (1, 2, 3, None) + with pytest.warns(FutureWarning, match=match): + assert _func_deprecated_params(1, old0=2) == ( + 1, + 2, + DEPRECATED, + None, + ) + with pytest.warns(FutureWarning, match=match): + assert _func_deprecated_params(1, old1=2) == ( + 1, + DEPRECATED, + 2, + None, + ) + + with warnings.catch_warnings(record=True) as record: + assert _func_deprecated_params(1, arg1=3) == (1, DEPRECATED, DEPRECATED, 3) + assert len(record) == 0 + + def test_warning_replaced_param(self): + match = ( + r".*`old[0,1]` is deprecated since version 0\.10 and will be removed " + r"in 0\.12.* see the documentation of .*_func_replace_params`." + ) + + with pytest.warns(FutureWarning, match=match): + assert _func_replace_params(1, 2) == ( + 1, + DEPRECATED, + DEPRECATED, + None, + 2, + None, + ) + + with pytest.warns(FutureWarning, match=match) as records: + assert _func_replace_params(1, 2, 3) == ( + 1, + DEPRECATED, + DEPRECATED, + 3, + 2, + None, + ) + assert len(records) == 2 + assert "`old1` is deprecated" in records[0].message.args[0] + assert "`old0` is deprecated" in records[1].message.args[0] + + with pytest.warns(FutureWarning, match=match): + assert _func_replace_params(1, old0=2) == ( + 1, + DEPRECATED, + DEPRECATED, + None, + 2, + None, + ) + + with pytest.warns(FutureWarning, match=match): + assert _func_replace_params(1, old1=3) == ( + 1, + DEPRECATED, + DEPRECATED, + 3, + None, + None, + ) + + # Otherwise, no warnings are emitted! + with warnings.catch_warnings(record=True) as record: + assert _func_replace_params(1, new0=2, new1=3) == ( + 1, + DEPRECATED, + DEPRECATED, + 2, + 3, + None, + ) + assert len(record) == 0 + + def test_missing_DEPRECATED(self): + decorate = deprecate_parameter( + "old", start_version="0.10", stop_version="0.12", stacklevel=2 + ) + + def foo(arg0, old=None): + return arg0, old + + with pytest.raises(RuntimeError, match="Expected .* "): + decorate(foo) + + def bar(arg0, old=DEPRECATED): + return arg0 + + assert decorate(bar)(1) == 1 + + def test_new_keyword_only(self): + @deprecate_parameter( + "old", + new_name="new", + start_version="0.19", + stop_version="0.21", + ) + def foo(arg0, old=DEPRECATED, *, new=1, arg3=None): + """Expected docstring""" + return arg0, new, arg3 + + # Assert that nothing happens when the function is called with the + # new API + with warnings.catch_warnings(record=True) as recorded: + # No kwargs + assert foo(0) == (0, 1, None) + # Kwargs without deprecated argument + assert foo(0, new=1, arg3=2) == (0, 1, 2) + assert foo(0, new=2) == (0, 2, None) + assert foo(0, arg3=2) == (0, 1, 2) + assert len(recorded) == 0 + + def test_conflicting_old_and_new(self): + match = r".*`old[0,1]` is deprecated" + with pytest.warns(FutureWarning, match=match): + with pytest.raises(ValueError, match=".* avoid conflicting values"): + _func_replace_params(1, old0=2, new1=2) + + with pytest.warns(FutureWarning, match=match): + with pytest.raises(ValueError, match=".* avoid conflicting values"): + _func_replace_params(1, old1=2, new0=2) + + with pytest.warns(FutureWarning, match=match): + with pytest.raises(ValueError, match=".* avoid conflicting values"): + _func_replace_params(1, old0=1, old1=1, new0=1, new1=1) + + def test_wrong_call_signature(self): + """Check that normal errors for faulty calls are unchanged.""" + with pytest.raises( + TypeError, match=r".* required positional argument\: 'arg0'" + ): + _func_replace_params() + + with pytest.warns(FutureWarning, match=r".*`old[0,1]` is deprecated"): + with pytest.raises( + TypeError, match=".* multiple values for argument 'old0'" + ): + _func_deprecated_params(1, 2, old0=2) + + def test_wrong_param_name(self): + with pytest.raises(ValueError, match="'old' is not in list"): + + @deprecate_parameter("old", start_version="0.10", stop_version="0.12") + def foo(arg0): + pass + + with pytest.raises(ValueError, match="'new' is not in list"): + + @deprecate_parameter( + "old", new_name="new", start_version="0.10", stop_version="0.12" + ) + def bar(arg0, old, arg1): + pass + + def test_warning_location(self): + with pytest.warns(FutureWarning) as records: + _func_deprecated_params(1, old0=2, old1=2) + testing.assert_stacklevel(records) + assert len(records) == 2 + + def test_stacklevel(self): + @deprecate_parameter( + "old", + start_version="0.19", + stop_version="0.21", + ) + def foo(arg0, old=DEPRECATED): + pass + + with pytest.raises(RuntimeError, match="Set stacklevel manually"): + foo(0, 1) + + @deprecate_parameter( + "old", + start_version="0.19", + stop_version="0.21", + stacklevel=2, + ) + def bar(arg0, old=DEPRECATED): + pass + + with pytest.warns(FutureWarning, match="`old` is deprecated") as records: + bar(0, 1) + testing.assert_stacklevel(records) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_version_requirements.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_version_requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..be07eea96524f05c8ddda5343d7614f0faf3bcce --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_version_requirements.py @@ -0,0 +1,40 @@ +"""Tests for the version requirement functions.""" + +import numpy as np +from numpy.testing import assert_equal +from skimage._shared import version_requirements as version_req +from skimage._shared import testing + + +def test_get_module_version(): + assert version_req.get_module_version('numpy') + assert version_req.get_module_version('scipy') + with testing.raises(ImportError): + version_req.get_module_version('fakenumpy') + + +def test_is_installed(): + assert version_req.is_installed('python', '>=2.7') + assert not version_req.is_installed('numpy', '<1.0') + + +def test_require(): + # A function that only runs on Python >2.7 and numpy > 1.5 (should pass) + @version_req.require('python', '>2.7') + @version_req.require('numpy', '>1.5') + def foo(): + return 1 + + assert_equal(foo(), 1) + + # function that requires scipy < 0.1 (should fail) + @version_req.require('scipy', '<0.1') + def bar(): + return 0 + + with testing.raises(ImportError): + bar() + + +def test_get_module(): + assert version_req.get_module("numpy") is np diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_warnings.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..e8751daa4f6d2b39e7514eeb5138aceabe40fc35 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/tests/test_warnings.py @@ -0,0 +1,37 @@ +import os +from skimage._shared._warnings import expected_warnings +import pytest + + +@pytest.fixture(scope='function') +def setup(): + # Remove any environment variable if it exists + old_strictness = os.environ.pop('SKIMAGE_TEST_STRICT_WARNINGS', None) + yield + # Add the user's desired strictness + if old_strictness is not None: + os.environ['SKIMAGE_TEST_STRICT_WARNINGS'] = old_strictness + + +def test_strict_warnigns_default(setup): + # By default we should fail on missing expected warnings + with pytest.raises(ValueError): + with expected_warnings(['some warnings']): + pass + + +@pytest.mark.parametrize('strictness', ['1', 'true', 'True', 'TRUE']) +def test_strict_warning_true(setup, strictness): + os.environ['SKIMAGE_TEST_STRICT_WARNINGS'] = strictness + with pytest.raises(ValueError): + with expected_warnings(['some warnings']): + pass + + +@pytest.mark.parametrize('strictness', ['0', 'false', 'False', 'FALSE']) +def test_strict_warning_false(setup, strictness): + # If the user doesn't wish to be strict about warnings + # the following shouldn't raise any error + os.environ['SKIMAGE_TEST_STRICT_WARNINGS'] = strictness + with expected_warnings(['some warnings']): + pass diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/utils.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a793509fb39e9bc7fe85e7010d829dc16ab48617 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/utils.py @@ -0,0 +1,891 @@ +import functools +import inspect +import sys +import warnings + +import numpy as np + +from ._warnings import all_warnings, warn + +__all__ = [ + 'deprecate_func', + 'get_bound_method_class', + 'all_warnings', + 'safe_as_int', + 'check_shape_equality', + 'check_nD', + 'warn', + 'reshape_nd', + 'identity', + 'slice_at_axis', + "deprecate_parameter", + "DEPRECATED", +] + + +def _count_wrappers(func): + """Count the number of wrappers around `func`.""" + unwrapped = func + count = 0 + while hasattr(unwrapped, "__wrapped__"): + unwrapped = unwrapped.__wrapped__ + count += 1 + return count + + +def _warning_stacklevel(func): + """Find stacklevel for a warning raised from a wrapper around `func`. + + Try to determine the number of + + Parameters + ---------- + func : Callable + + + Returns + ------- + stacklevel : int + The stacklevel. Minimum of 2. + """ + # Count number of wrappers around `func` + wrapped_count = _count_wrappers(func) + + # Count number of total wrappers around global version of `func` + module = sys.modules.get(func.__module__) + try: + for name in func.__qualname__.split("."): + global_func = getattr(module, name) + except AttributeError as e: + raise RuntimeError( + f"Could not access `{func.__qualname__}` in {module!r}, " + f" may be a closure. Set stacklevel manually. ", + ) from e + else: + global_wrapped_count = _count_wrappers(global_func) + + stacklevel = global_wrapped_count - wrapped_count + 1 + return max(stacklevel, 2) + + +def _get_stack_length(func): + """Return function call stack length.""" + _func = func.__globals__.get(func.__name__, func) + length = _count_wrappers(_func) + return length + + +class _DecoratorBaseClass: + """Used to manage decorators' warnings stacklevel. + + The `_stack_length` class variable is used to store the number of + times a function is wrapped by a decorator. + + Let `stack_length` be the total number of times a decorated + function is wrapped, and `stack_rank` be the rank of the decorator + in the decorators stack. The stacklevel of a warning is then + `stacklevel = 1 + stack_length - stack_rank`. + """ + + _stack_length = {} + + def get_stack_length(self, func): + length = self._stack_length.get(func.__name__, _get_stack_length(func)) + return length + + +class change_default_value(_DecoratorBaseClass): + """Decorator for changing the default value of an argument. + + Parameters + ---------- + arg_name: str + The name of the argument to be updated. + new_value: any + The argument new value. + changed_version : str + The package version in which the change will be introduced. + warning_msg: str + Optional warning message. If None, a generic warning message + is used. + + """ + + def __init__(self, arg_name, *, new_value, changed_version, warning_msg=None): + self.arg_name = arg_name + self.new_value = new_value + self.warning_msg = warning_msg + self.changed_version = changed_version + + def __call__(self, func): + parameters = inspect.signature(func).parameters + arg_idx = list(parameters.keys()).index(self.arg_name) + old_value = parameters[self.arg_name].default + + stack_rank = _count_wrappers(func) + + if self.warning_msg is None: + self.warning_msg = ( + f'The new recommended value for {self.arg_name} is ' + f'{self.new_value}. Until version {self.changed_version}, ' + f'the default {self.arg_name} value is {old_value}. ' + f'From version {self.changed_version}, the {self.arg_name} ' + f'default value will be {self.new_value}. To avoid ' + f'this warning, please explicitly set {self.arg_name} value.' + ) + + @functools.wraps(func) + def fixed_func(*args, **kwargs): + stacklevel = 1 + self.get_stack_length(func) - stack_rank + if len(args) < arg_idx + 1 and self.arg_name not in kwargs.keys(): + # warn that arg_name default value changed: + warnings.warn(self.warning_msg, FutureWarning, stacklevel=stacklevel) + return func(*args, **kwargs) + + return fixed_func + + +class PatchClassRepr(type): + """Control class representations in rendered signatures.""" + + def __repr__(cls): + return f"<{cls.__name__}>" + + +class DEPRECATED(metaclass=PatchClassRepr): + """Signal value to help with deprecating parameters that use None. + + This is a proxy object, used to signal that a parameter has not been set. + This is useful if ``None`` is already used for a different purpose or just + to highlight a deprecated parameter in the signature. + """ + + +class deprecate_parameter: + """Deprecate a parameter of a function. + + Parameters + ---------- + deprecated_name : str + The name of the deprecated parameter. + start_version : str + The package version in which the warning was introduced. + stop_version : str + The package version in which the warning will be replaced by + an error / the deprecation is completed. + template : str, optional + If given, this message template is used instead of the default one. + new_name : str, optional + If given, the default message will recommend the new parameter name and an + error will be raised if the user uses both old and new names for the + same parameter. + modify_docstring : bool, optional + If the wrapped function has a docstring, add the deprecated parameters + to the "Other Parameters" section. + stacklevel : int, optional + This decorator attempts to detect the appropriate stacklevel for the + deprecation warning automatically. If this fails, e.g., due to + decorating a closure, you can set the stacklevel manually. The + outermost decorator should have stacklevel 2, the next inner one + stacklevel 3, etc. + + Notes + ----- + Assign `DEPRECATED` as the new default value for the deprecated parameter. + This marks the status of the parameter also in the signature and rendered + HTML docs. + + This decorator can be stacked to deprecate more than one parameter. + + Examples + -------- + >>> from skimage._shared.utils import deprecate_parameter, DEPRECATED + >>> @deprecate_parameter( + ... "b", new_name="c", start_version="0.1", stop_version="0.3" + ... ) + ... def foo(a, b=DEPRECATED, *, c=None): + ... return a, c + + Calling ``foo(1, b=2)`` will warn with:: + + FutureWarning: Parameter `b` is deprecated since version 0.1 and will + be removed in 0.3 (or later). To avoid this warning, please use the + parameter `c` instead. For more details, see the documentation of + `foo`. + """ + + DEPRECATED = DEPRECATED # Make signal value accessible for convenience + + remove_parameter_template = ( + "Parameter `{deprecated_name}` is deprecated since version " + "{deprecated_version} and will be removed in {changed_version} (or " + "later). To avoid this warning, please do not use the parameter " + "`{deprecated_name}`. For more details, see the documentation of " + "`{func_name}`." + ) + + replace_parameter_template = ( + "Parameter `{deprecated_name}` is deprecated since version " + "{deprecated_version} and will be removed in {changed_version} (or " + "later). To avoid this warning, please use the parameter `{new_name}` " + "instead. For more details, see the documentation of `{func_name}`." + ) + + def __init__( + self, + deprecated_name, + *, + start_version, + stop_version, + template=None, + new_name=None, + modify_docstring=True, + stacklevel=None, + ): + self.deprecated_name = deprecated_name + self.new_name = new_name + self.template = template + self.start_version = start_version + self.stop_version = stop_version + self.modify_docstring = modify_docstring + self.stacklevel = stacklevel + + def __call__(self, func): + parameters = inspect.signature(func).parameters + deprecated_idx = list(parameters.keys()).index(self.deprecated_name) + if self.new_name: + new_idx = list(parameters.keys()).index(self.new_name) + else: + new_idx = False + + if parameters[self.deprecated_name].default is not DEPRECATED: + raise RuntimeError( + f"Expected `{self.deprecated_name}` to have the value {DEPRECATED!r} " + f"to indicate its status in the rendered signature." + ) + + if self.template is not None: + template = self.template + elif self.new_name is not None: + template = self.replace_parameter_template + else: + template = self.remove_parameter_template + warning_message = template.format( + deprecated_name=self.deprecated_name, + deprecated_version=self.start_version, + changed_version=self.stop_version, + func_name=func.__qualname__, + new_name=self.new_name, + ) + + @functools.wraps(func) + def fixed_func(*args, **kwargs): + deprecated_value = DEPRECATED + new_value = DEPRECATED + + # Extract value of deprecated parameter + if len(args) > deprecated_idx: + deprecated_value = args[deprecated_idx] + # Overwrite old with DEPRECATED if replacement exists + if self.new_name is not None: + args = ( + args[:deprecated_idx] + + (DEPRECATED,) + + args[deprecated_idx + 1 :] + ) + if self.deprecated_name in kwargs.keys(): + deprecated_value = kwargs[self.deprecated_name] + # Overwrite old with DEPRECATED if replacement exists + if self.new_name is not None: + kwargs[self.deprecated_name] = DEPRECATED + + # Extract value of new parameter (if present) + if new_idx is not False and len(args) > new_idx: + new_value = args[new_idx] + if self.new_name and self.new_name in kwargs.keys(): + new_value = kwargs[self.new_name] + + if deprecated_value is not DEPRECATED: + stacklevel = ( + self.stacklevel + if self.stacklevel is not None + else _warning_stacklevel(func) + ) + warnings.warn( + warning_message, category=FutureWarning, stacklevel=stacklevel + ) + + if new_value is not DEPRECATED: + raise ValueError( + f"Both deprecated parameter `{self.deprecated_name}` " + f"and new parameter `{self.new_name}` are used. Use " + f"only the latter to avoid conflicting values." + ) + elif self.new_name is not None: + # Assign old value to new one + kwargs[self.new_name] = deprecated_value + + return func(*args, **kwargs) + + if self.modify_docstring and func.__doc__ is not None: + newdoc = _docstring_add_deprecated( + func, {self.deprecated_name: self.new_name}, self.start_version + ) + fixed_func.__doc__ = newdoc + + return fixed_func + + +def _docstring_add_deprecated(func, kwarg_mapping, deprecated_version): + """Add deprecated kwarg(s) to the "Other Params" section of a docstring. + + Parameters + ---------- + func : function + The function whose docstring we wish to update. + kwarg_mapping : dict + A dict containing {old_arg: new_arg} key/value pairs, see + `deprecate_parameter`. + deprecated_version : str + A major.minor version string specifying when old_arg was + deprecated. + + Returns + ------- + new_doc : str + The updated docstring. Returns the original docstring if numpydoc is + not available. + """ + if func.__doc__ is None: + return None + try: + from numpydoc.docscrape import FunctionDoc, Parameter + except ImportError: + # Return an unmodified docstring if numpydoc is not available. + return func.__doc__ + + Doc = FunctionDoc(func) + for old_arg, new_arg in kwarg_mapping.items(): + desc = [] + if new_arg is None: + desc.append(f'`{old_arg}` is deprecated.') + else: + desc.append(f'Deprecated in favor of `{new_arg}`.') + + desc += ['', f'.. deprecated:: {deprecated_version}'] + Doc['Other Parameters'].append( + Parameter(name=old_arg, type='DEPRECATED', desc=desc) + ) + new_docstring = str(Doc) + + # new_docstring will have a header starting with: + # + # .. function:: func.__name__ + # + # and some additional blank lines. We strip these off below. + split = new_docstring.split('\n') + no_header = split[1:] + while not no_header[0].strip(): + no_header.pop(0) + + # Store the initial description before any of the Parameters fields. + # Usually this is a single line, but the while loop covers any case + # where it is not. + descr = no_header.pop(0) + while no_header[0].strip(): + descr += '\n ' + no_header.pop(0) + descr += '\n\n' + # '\n ' rather than '\n' here to restore the original indentation. + final_docstring = descr + '\n '.join(no_header) + # strip any extra spaces from ends of lines + final_docstring = '\n'.join([line.rstrip() for line in final_docstring.split('\n')]) + return final_docstring + + +class channel_as_last_axis: + """Decorator for automatically making channels axis last for all arrays. + + This decorator reorders axes for compatibility with functions that only + support channels along the last axis. After the function call is complete + the channels axis is restored back to its original position. + + Parameters + ---------- + channel_arg_positions : tuple of int, optional + Positional arguments at the positions specified in this tuple are + assumed to be multichannel arrays. The default is to assume only the + first argument to the function is a multichannel array. + channel_kwarg_names : tuple of str, optional + A tuple containing the names of any keyword arguments corresponding to + multichannel arrays. + multichannel_output : bool, optional + A boolean that should be True if the output of the function is not a + multichannel array and False otherwise. This decorator does not + currently support the general case of functions with multiple outputs + where some or all are multichannel. + + """ + + def __init__( + self, + channel_arg_positions=(0,), + channel_kwarg_names=(), + multichannel_output=True, + ): + self.arg_positions = set(channel_arg_positions) + self.kwarg_names = set(channel_kwarg_names) + self.multichannel_output = multichannel_output + + def __call__(self, func): + @functools.wraps(func) + def fixed_func(*args, **kwargs): + channel_axis = kwargs.get('channel_axis', None) + + if channel_axis is None: + return func(*args, **kwargs) + + # TODO: convert scalars to a tuple in anticipation of eventually + # supporting a tuple of channel axes. Right now, only an + # integer or a single-element tuple is supported, though. + if np.isscalar(channel_axis): + channel_axis = (channel_axis,) + if len(channel_axis) > 1: + raise ValueError("only a single channel axis is currently supported") + + if channel_axis == (-1,) or channel_axis == -1: + return func(*args, **kwargs) + + if self.arg_positions: + new_args = [] + for pos, arg in enumerate(args): + if pos in self.arg_positions: + new_args.append(np.moveaxis(arg, channel_axis[0], -1)) + else: + new_args.append(arg) + new_args = tuple(new_args) + else: + new_args = args + + for name in self.kwarg_names: + kwargs[name] = np.moveaxis(kwargs[name], channel_axis[0], -1) + + # now that we have moved the channels axis to the last position, + # change the channel_axis argument to -1 + kwargs["channel_axis"] = -1 + + # Call the function with the fixed arguments + out = func(*new_args, **kwargs) + if self.multichannel_output: + out = np.moveaxis(out, -1, channel_axis[0]) + return out + + return fixed_func + + +class deprecate_func(_DecoratorBaseClass): + """Decorate a deprecated function and warn when it is called. + + Adapted from . + + Parameters + ---------- + deprecated_version : str + The package version when the deprecation was introduced. + removed_version : str + The package version in which the deprecated function will be removed. + hint : str, optional + A hint on how to address this deprecation, + e.g., "Use `skimage.submodule.alternative_func` instead." + + Examples + -------- + >>> @deprecate_func( + ... deprecated_version="1.0.0", + ... removed_version="1.2.0", + ... hint="Use `bar` instead." + ... ) + ... def foo(): + ... pass + + Calling ``foo`` will warn with:: + + FutureWarning: `foo` is deprecated since version 1.0.0 + and will be removed in version 1.2.0. Use `bar` instead. + """ + + def __init__(self, *, deprecated_version, removed_version=None, hint=None): + self.deprecated_version = deprecated_version + self.removed_version = removed_version + self.hint = hint + + def __call__(self, func): + message = ( + f"`{func.__name__}` is deprecated since version " + f"{self.deprecated_version}" + ) + if self.removed_version: + message += f" and will be removed in version {self.removed_version}." + if self.hint: + # Prepend space and make sure it closes with "." + message += f" {self.hint.rstrip('.')}." + + stack_rank = _count_wrappers(func) + + @functools.wraps(func) + def wrapped(*args, **kwargs): + stacklevel = 1 + self.get_stack_length(func) - stack_rank + warnings.warn(message, category=FutureWarning, stacklevel=stacklevel) + return func(*args, **kwargs) + + # modify docstring to display deprecation warning + doc = f'**Deprecated:** {message}' + if wrapped.__doc__ is None: + wrapped.__doc__ = doc + else: + wrapped.__doc__ = doc + '\n\n ' + wrapped.__doc__ + + return wrapped + + +def get_bound_method_class(m): + """Return the class for a bound method.""" + return m.im_class if sys.version < '3' else m.__self__.__class__ + + +def safe_as_int(val, atol=1e-3): + """ + Attempt to safely cast values to integer format. + + Parameters + ---------- + val : scalar or iterable of scalars + Number or container of numbers which are intended to be interpreted as + integers, e.g., for indexing purposes, but which may not carry integer + type. + atol : float + Absolute tolerance away from nearest integer to consider values in + ``val`` functionally integers. + + Returns + ------- + val_int : NumPy scalar or ndarray of dtype `np.int64` + Returns the input value(s) coerced to dtype `np.int64` assuming all + were within ``atol`` of the nearest integer. + + Notes + ----- + This operation calculates ``val`` modulo 1, which returns the mantissa of + all values. Then all mantissas greater than 0.5 are subtracted from one. + Finally, the absolute tolerance from zero is calculated. If it is less + than ``atol`` for all value(s) in ``val``, they are rounded and returned + in an integer array. Or, if ``val`` was a scalar, a NumPy scalar type is + returned. + + If any value(s) are outside the specified tolerance, an informative error + is raised. + + Examples + -------- + >>> safe_as_int(7.0) + 7 + + >>> safe_as_int([9, 4, 2.9999999999]) + array([9, 4, 3]) + + >>> safe_as_int(53.1) + Traceback (most recent call last): + ... + ValueError: Integer argument required but received 53.1, check inputs. + + >>> safe_as_int(53.01, atol=0.01) + 53 + + """ + mod = np.asarray(val) % 1 # Extract mantissa + + # Check for and subtract any mod values > 0.5 from 1 + if mod.ndim == 0: # Scalar input, cannot be indexed + if mod > 0.5: + mod = 1 - mod + else: # Iterable input, now ndarray + mod[mod > 0.5] = 1 - mod[mod > 0.5] # Test on each side of nearest int + + try: + np.testing.assert_allclose(mod, 0, atol=atol) + except AssertionError: + raise ValueError( + f'Integer argument required but received ' f'{val}, check inputs.' + ) + + return np.round(val).astype(np.int64) + + +def check_shape_equality(*images): + """Check that all images have the same shape""" + image0 = images[0] + if not all(image0.shape == image.shape for image in images[1:]): + raise ValueError('Input images must have the same dimensions.') + return + + +def slice_at_axis(sl, axis): + """ + Construct tuple of slices to slice an array in the given dimension. + + Parameters + ---------- + sl : slice + The slice for the given dimension. + axis : int + The axis to which `sl` is applied. All other dimensions are left + "unsliced". + + Returns + ------- + sl : tuple of slices + A tuple with slices matching `shape` in length. + + Examples + -------- + >>> slice_at_axis(slice(None, 3, -1), 1) + (slice(None, None, None), slice(None, 3, -1), Ellipsis) + """ + return (slice(None),) * axis + (sl,) + (...,) + + +def reshape_nd(arr, ndim, dim): + """Reshape a 1D array to have n dimensions, all singletons but one. + + Parameters + ---------- + arr : array, shape (N,) + Input array + ndim : int + Number of desired dimensions of reshaped array. + dim : int + Which dimension/axis will not be singleton-sized. + + Returns + ------- + arr_reshaped : array, shape ([1, ...], N, [1,...]) + View of `arr` reshaped to the desired shape. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> arr = rng.random(7) + >>> reshape_nd(arr, 2, 0).shape + (7, 1) + >>> reshape_nd(arr, 3, 1).shape + (1, 7, 1) + >>> reshape_nd(arr, 4, -1).shape + (1, 1, 1, 7) + """ + if arr.ndim != 1: + raise ValueError("arr must be a 1D array") + new_shape = [1] * ndim + new_shape[dim] = -1 + return np.reshape(arr, new_shape) + + +def check_nD(array, ndim, arg_name='image'): + """ + Verify an array meets the desired ndims and array isn't empty. + + Parameters + ---------- + array : array-like + Input array to be validated + ndim : int or iterable of ints + Allowable ndim or ndims for the array. + arg_name : str, optional + The name of the array in the original function. + + """ + array = np.asanyarray(array) + msg_incorrect_dim = "The parameter `%s` must be a %s-dimensional array" + msg_empty_array = "The parameter `%s` cannot be an empty array" + if isinstance(ndim, int): + ndim = [ndim] + if array.size == 0: + raise ValueError(msg_empty_array % (arg_name)) + if array.ndim not in ndim: + raise ValueError( + msg_incorrect_dim % (arg_name, '-or-'.join([str(n) for n in ndim])) + ) + + +def convert_to_float(image, preserve_range): + """Convert input image to float image with the appropriate range. + + Parameters + ---------- + image : ndarray + Input image. + preserve_range : bool + Determines if the range of the image should be kept or transformed + using img_as_float. Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + + Notes + ----- + * Input images with `float32` data type are not upcast. + + Returns + ------- + image : ndarray + Transformed version of the input. + + """ + if image.dtype == np.float16: + return image.astype(np.float32) + if preserve_range: + # Convert image to double only if it is not single or double + # precision float + if image.dtype.char not in 'df': + image = image.astype(float) + else: + from ..util.dtype import img_as_float + + image = img_as_float(image) + return image + + +def _validate_interpolation_order(image_dtype, order): + """Validate and return spline interpolation's order. + + Parameters + ---------- + image_dtype : dtype + Image dtype. + order : int, optional + The order of the spline interpolation. The order has to be in + the range 0-5. See `skimage.transform.warp` for detail. + + Returns + ------- + order : int + if input order is None, returns 0 if image_dtype is bool and 1 + otherwise. Otherwise, image_dtype is checked and input order + is validated accordingly (order > 0 is not supported for bool + image dtype) + + """ + + if order is None: + return 0 if image_dtype == bool else 1 + + if order < 0 or order > 5: + raise ValueError("Spline interpolation order has to be in the " "range 0-5.") + + if image_dtype == bool and order != 0: + raise ValueError( + "Input image dtype is bool. Interpolation is not defined " + "with bool data type. Please set order to 0 or explicitly " + "cast input image to another data type." + ) + + return order + + +def _to_np_mode(mode): + """Convert padding modes from `ndi.correlate` to `np.pad`.""" + mode_translation_dict = dict(nearest='edge', reflect='symmetric', mirror='reflect') + if mode in mode_translation_dict: + mode = mode_translation_dict[mode] + return mode + + +def _to_ndimage_mode(mode): + """Convert from `numpy.pad` mode name to the corresponding ndimage mode.""" + mode_translation_dict = dict( + constant='constant', + edge='nearest', + symmetric='reflect', + reflect='mirror', + wrap='wrap', + ) + if mode not in mode_translation_dict: + raise ValueError( + f"Unknown mode: '{mode}', or cannot translate mode. The " + f"mode should be one of 'constant', 'edge', 'symmetric', " + f"'reflect', or 'wrap'. See the documentation of numpy.pad for " + f"more info." + ) + return _fix_ndimage_mode(mode_translation_dict[mode]) + + +def _fix_ndimage_mode(mode): + # SciPy 1.6.0 introduced grid variants of constant and wrap which + # have less surprising behavior for images. Use these when available + grid_modes = {'constant': 'grid-constant', 'wrap': 'grid-wrap'} + return grid_modes.get(mode, mode) + + +new_float_type = { + # preserved types + np.float32().dtype.char: np.float32, + np.float64().dtype.char: np.float64, + np.complex64().dtype.char: np.complex64, + np.complex128().dtype.char: np.complex128, + # altered types + np.float16().dtype.char: np.float32, + 'g': np.float64, # np.float128 ; doesn't exist on windows + 'G': np.complex128, # np.complex256 ; doesn't exist on windows +} + + +def _supported_float_type(input_dtype, allow_complex=False): + """Return an appropriate floating-point dtype for a given dtype. + + float32, float64, complex64, complex128 are preserved. + float16 is promoted to float32. + complex256 is demoted to complex128. + Other types are cast to float64. + + Parameters + ---------- + input_dtype : np.dtype or tuple of np.dtype + The input dtype. If a tuple of multiple dtypes is provided, each + dtype is first converted to a supported floating point type and the + final dtype is then determined by applying `np.result_type` on the + sequence of supported floating point types. + allow_complex : bool, optional + If False, raise a ValueError on complex-valued inputs. + + Returns + ------- + float_type : dtype + Floating-point dtype for the image. + """ + if isinstance(input_dtype, tuple): + return np.result_type(*(_supported_float_type(d) for d in input_dtype)) + input_dtype = np.dtype(input_dtype) + if not allow_complex and input_dtype.kind == 'c': + raise ValueError("complex valued input is not supported") + return new_float_type.get(input_dtype.char, np.float64) + + +def identity(image, *args, **kwargs): + """Returns the first argument unmodified.""" + return image + + +def as_binary_ndarray(array, *, variable_name): + """Return `array` as a numpy.ndarray of dtype bool. + + Raises + ------ + ValueError: + An error including the given `variable_name` if `array` can not be + safely cast to a boolean array. + """ + array = np.asarray(array) + if array.dtype != bool: + if np.any((array != 1) & (array != 0)): + raise ValueError( + f"{variable_name} array is not of dtype boolean or " + f"contains values other than 0 and 1 so cannot be " + f"safely cast to boolean array." + ) + return np.asarray(array, dtype=bool) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/_shared/version_requirements.py b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/version_requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..f55ebb3369c68a3bd9cb60910e451d6239812291 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/_shared/version_requirements.py @@ -0,0 +1,138 @@ +import sys + +from packaging import version as _version + + +def _check_version(actver, version, cmp_op): + """ + Check version string of an active module against a required version. + + If dev/prerelease tags result in TypeError for string-number comparison, + it is assumed that the dependency is satisfied. + Users on dev branches are responsible for keeping their own packages up to + date. + """ + try: + if cmp_op == '>': + return _version.parse(actver) > _version.parse(version) + elif cmp_op == '>=': + return _version.parse(actver) >= _version.parse(version) + elif cmp_op == '=': + return _version.parse(actver) == _version.parse(version) + elif cmp_op == '<': + return _version.parse(actver) < _version.parse(version) + else: + return False + except TypeError: + return True + + +def get_module_version(module_name): + """Return module version or None if version can't be retrieved.""" + mod = __import__(module_name, fromlist=[module_name.rpartition('.')[-1]]) + return getattr(mod, '__version__', getattr(mod, 'VERSION', None)) + + +def is_installed(name, version=None): + """Test if *name* is installed. + + Parameters + ---------- + name : str + Name of module or "python" + version : str, optional + Version string to test against. + If version is not None, checking version + (must have an attribute named '__version__' or 'VERSION') + Version may start with =, >=, > or < to specify the exact requirement + + Returns + ------- + out : bool + True if `name` is installed matching the optional version. + """ + if name.lower() == 'python': + actver = sys.version[:6] + else: + try: + actver = get_module_version(name) + except ImportError: + return False + if version is None: + return True + else: + # since version_requirements is in the critical import path, + # we lazy import re + import re + + match = re.search('[0-9]', version) + assert match is not None, "Invalid version number" + symb = version[: match.start()] + if not symb: + symb = '=' + assert symb in ('>=', '>', '=', '<'), f"Invalid version condition '{symb}'" + version = version[match.start() :] + return _check_version(actver, version, symb) + + +def require(name, version=None): + """Return decorator that forces a requirement for a function or class. + + Parameters + ---------- + name : str + Name of module or "python". + version : str, optional + Version string to test against. + If version is not None, checking version + (must have an attribute named '__version__' or 'VERSION') + Version may start with =, >=, > or < to specify the exact requirement + + Returns + ------- + func : function + A decorator that raises an ImportError if a function is run + in the absence of the input dependency. + """ + # since version_requirements is in the critical import path, we lazy import + # functools + import functools + + def decorator(obj): + @functools.wraps(obj) + def func_wrapped(*args, **kwargs): + if is_installed(name, version): + return obj(*args, **kwargs) + else: + msg = f'"{obj}" in "{obj.__module__}" requires "{name}' + if version is not None: + msg += f" {version}" + raise ImportError(msg + '"') + + return func_wrapped + + return decorator + + +def get_module(module_name, version=None): + """Return a module object of name *module_name* if installed. + + Parameters + ---------- + module_name : str + Name of module. + version : str, optional + Version string to test against. + If version is not None, checking version + (must have an attribute named '__version__' or 'VERSION') + Version may start with =, >=, > or < to specify the exact requirement + + Returns + ------- + mod : module or None + Module if *module_name* is installed matching the optional version + or None otherwise. + """ + if not is_installed(module_name, version): + return None + return __import__(module_name, fromlist=[module_name.rpartition('.')[-1]]) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/feature/_canny_cy.cpython-310-x86_64-linux-gnu.so b/vlmpy310/lib/python3.10/site-packages/skimage/feature/_canny_cy.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..64a683190aed39994480d8b5f23dc7a8f00a2276 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/feature/_canny_cy.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e05ac5bc312179e82b35b323afea15dde311dec02fcd387de6dfea89193382af +size 281520 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/bilateral_cy.cpython-310-x86_64-linux-gnu.so b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/bilateral_cy.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9ec1f0dad97c79ea6951f8bfce950c7b657448da --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/bilateral_cy.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7272ee34ce4f1696ef7ea7afb9dcf6e09228f7b8545775128a591173c2f2ba61 +size 577496 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so b/vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b19bbca55cf2525a46f60c76670c9d2076531c41 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be37ef59c2206cb3e142749f0d7403c9faaee7fb066d86605b7d12dd33be7877 +size 863048