ZTWHHH commited on
Commit
f8a1614
·
verified ·
1 Parent(s): a5813c5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py +0 -0
  4. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py +5 -0
  6. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py +180 -0
  9. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-310.pyc +0 -0
  10. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-310.pyc +0 -0
  11. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-310.pyc +0 -0
  12. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-310.pyc +0 -0
  13. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py +152 -0
  14. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-310.pyc +0 -0
  15. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-310.pyc +0 -0
  16. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-310.pyc +0 -0
  17. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py +39 -0
  18. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py +165 -0
  19. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py +93 -0
  20. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py +8 -0
  21. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-310.pyc +0 -0
  22. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-310.pyc +0 -0
  23. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-310.pyc +0 -0
  24. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-310.pyc +0 -0
  25. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-310.pyc +0 -0
  26. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-310.pyc +0 -0
  27. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-310.pyc +0 -0
  28. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-310.pyc +0 -0
  29. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py +310 -0
  30. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py +48 -0
  31. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py +59 -0
  32. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py +59 -0
  33. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py +475 -0
  34. llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py +29 -0
  35. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__init__.py +0 -0
  36. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-310.pyc +0 -0
  37. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-310.pyc +0 -0
  38. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-310.pyc +0 -0
  39. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-310.pyc +0 -0
  40. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py +159 -0
  41. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py +107 -0
  42. llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py +47 -0
  43. llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__init__.py +0 -0
  44. llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/base_sparsifier.py +353 -0
  45. llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/nearly_diagonal_sparsifier.py +55 -0
  46. llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/utils.py +136 -0
  47. llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/weight_norm_sparsifier.py +199 -0
  48. vlmpy310/lib/python3.10/site-packages/skimage/_shared/_dependency_checks.py +7 -0
  49. vlmpy310/lib/python3.10/site-packages/skimage/_shared/_geometry.py +54 -0
  50. vlmpy310/lib/python3.10/site-packages/skimage/_shared/coord.py +124 -0
.gitattributes CHANGED
@@ -1208,3 +1208,6 @@ vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/core_cy_3d.cpython-31
1208
  llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/lowering.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1209
  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
1210
  llava_next/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
1208
  llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/lowering.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1209
  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
1210
  llava_next/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text
1211
+ vlmpy310/lib/python3.10/site-packages/skimage/feature/_canny_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1212
+ 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
1213
+ vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (208 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .base_data_scheduler import BaseDataScheduler
2
+
3
+ __all__ = [
4
+ "BaseDataScheduler",
5
+ ]
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (286 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-310.pyc ADDED
Binary file (7.12 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ import weakref
3
+ import abc
4
+ import warnings
5
+
6
+ from ..data_sparsifier import BaseDataSparsifier
7
+
8
+ __all__ = ['BaseDataScheduler']
9
+
10
+
11
+ class BaseDataScheduler:
12
+ r"""
13
+ The BaseDataScheduler is the abstract scheduler class specifically for the
14
+ BaseDataSparsifier class. This class controls a specific hyperparameter of
15
+ the sparsifier class and varies it across the training process (or across time).
16
+
17
+ Args:
18
+ data_sparsifier (instance of BaseDataSparsifier)
19
+ Implemented class data sparsifier class wherein the update_mask is implemented
20
+ schedule_param (str)
21
+ A specific hyperparameter of the passed sparsifier that needs to be scheduled/varied
22
+ last_epoch (int, default=-1)
23
+ This is specifically is passed when training needs to be resumed from a particular
24
+ point.
25
+ verbose (bool, default=False)
26
+ Verbosity of the BaseDataScheduler
27
+
28
+ The *get_hyperparam()* function needs to be implemented by the user.
29
+ """
30
+ def __init__(self, data_sparsifier, schedule_param: str, last_epoch=-1, verbose=False):
31
+ # Attach sparsifier
32
+ if not isinstance(data_sparsifier, BaseDataSparsifier):
33
+ raise TypeError('{} is not an instance of torch.ao.pruning.BaseDataSparsifier'.format(
34
+ type(data_sparsifier).__name__))
35
+ self.data_sparsifier = data_sparsifier
36
+ self.schedule_param = schedule_param
37
+
38
+ # Initialize epoch and base hyper-params
39
+ self.base_param = {
40
+ name: config.get(schedule_param, None)
41
+ for name, config in self.data_sparsifier.data_groups.items()
42
+ }
43
+
44
+ self.last_epoch = last_epoch
45
+
46
+ # Following https://github.com/pytorch/pytorch/issues/20124
47
+ # We would like to ensure that `scheduler.step()` is called after
48
+ # `sparsifier.step()`
49
+ def with_counter(method):
50
+ if getattr(method, '_with_counter', False):
51
+ # `sparsifier.step()` has already been replaced, return.
52
+ return method
53
+
54
+ # Keep a weak reference to the sparsifier instance to prevent
55
+ # cyclic references.
56
+ instance_ref = weakref.ref(method.__self__)
57
+ # Get the unbound method for the same purpose.
58
+ func = method.__func__
59
+ cls = instance_ref().__class__
60
+ del method
61
+
62
+ @wraps(func)
63
+ def wrapper(*args, **kwargs):
64
+ instance = instance_ref()
65
+ instance._step_count += 1 # type: ignore[union-attr]
66
+ wrapped = func.__get__(instance, cls)
67
+ return wrapped(*args, **kwargs)
68
+
69
+ # Note that the returned function here is no longer a bound method,
70
+ # so attributes like `__func__` and `__self__` no longer exist.
71
+ wrapper._with_counter = True # type: ignore[attr-defined]
72
+ return wrapper
73
+
74
+ self.data_sparsifier.step = with_counter(self.data_sparsifier.step) # type: ignore[assignment]
75
+ self.data_sparsifier._step_count = 0 # type: ignore[attr-defined]
76
+ self._step_count: int = 0
77
+ self.verbose = verbose
78
+
79
+ # Housekeeping
80
+ self._get_sp_called_within_step: bool = False # sp -> schedule parameter
81
+ self.step()
82
+
83
+ @abc.abstractmethod
84
+ def get_schedule_param(self):
85
+ r"""
86
+ Abstract method that needs to be implemented by the child class.
87
+ The expected return type should is a dictionary of name to schedule_param value
88
+ The returned values will be updated in sparsifier when the scheduler step() function
89
+ is called.
90
+
91
+ Example:
92
+ >>> def get_schedule_param(self):
93
+ ... new_param = {}
94
+ ... for name in self.sparsifier.data_groups.keys():
95
+ ... new_param[name] = self.sparsifier.data_groups[name][self.schedule_param] * 0.5
96
+ ... return new_param
97
+
98
+ When the step() function is called, the value in self.sparsifier.data_groups[name][self.schedule_param]
99
+ would be halved
100
+ """
101
+ raise NotImplementedError
102
+
103
+ def __repr__(self):
104
+ format_string = self.__class__.__name__ + ' ('
105
+ format_string += '\n'
106
+ format_string += f'Data Sparsifier {self.data_sparsifier}\n'
107
+ format_string += f' {self.schedule_param}: {self.base_param}\n'
108
+ format_string += ')'
109
+ return format_string
110
+
111
+ def state_dict(self):
112
+ """Returns the state of the scheduler as a :class:`dict`.
113
+
114
+ It contains an entry for every variable in self.__dict__ which
115
+ is not the sparsifier.
116
+
117
+ Note:
118
+ The scheduler class does not track the state of the data_sparsifier.
119
+ Make sure to store the state of the sparsifier before storing the
120
+ state of the scheduler
121
+ """
122
+ return {key: value for key, value in self.__dict__.items() if key != 'data_sparsifier'}
123
+
124
+ def load_state_dict(self, state_dict):
125
+ """Loads the schedulers state.
126
+
127
+ Note:
128
+ Remember to restore the state of the data_sparsifier before the scheduler.
129
+
130
+ Args:
131
+ state_dict (dict): scheduler state. Should be an object returned
132
+ from a call to :meth:`state_dict`.
133
+ """
134
+ self.__dict__.update(state_dict)
135
+
136
+ def get_last_param(self):
137
+ return self._last_param
138
+
139
+ def step(self):
140
+ # Raise warning if trying to call scheduler step before the sparsifier.
141
+ # https://github.com/pytorch/pytorch/issues/20124
142
+ if self._step_count == 1:
143
+ if not hasattr(self.data_sparsifier.step, "_with_counter"):
144
+ warnings.warn("Seems like `data_sparsifier.step()` has been overridden after sparsity scheduler "
145
+ "initialization. Please, make sure to call `data_sparsifier.step()` before "
146
+ "`scheduler.step()`.", UserWarning)
147
+
148
+ # Just check if there were two first scheduler.step() calls before sparsifier.step()
149
+ elif self.data_sparsifier._step_count < 1: # type: ignore[attr-defined]
150
+ warnings.warn("Detected call of `scheduler.step()` before `data_sparsifier.step()`. "
151
+ "You have to make sure you run the data_sparsifier.step() BEFORE any "
152
+ "calls to the scheduler.step().", UserWarning)
153
+ self._step_count += 1
154
+
155
+ class _enable_get_sp_call:
156
+
157
+ def __init__(self, o):
158
+ self.o = o
159
+
160
+ def __enter__(self):
161
+ self.o._get_sp_called_within_step = True
162
+ return self
163
+
164
+ def __exit__(self, type, value, traceback):
165
+ self.o._get_sp_called_within_step = False
166
+
167
+ with _enable_get_sp_call(self):
168
+ self.last_epoch += 1
169
+ updated_scheduler_params = self.get_schedule_param()
170
+
171
+ for name, param in updated_scheduler_params.items():
172
+ self.data_sparsifier.data_groups[name][self.schedule_param] = param
173
+ if self.verbose:
174
+ print(f"Adjusting {self.schedule_param} for group {name} to {param}")
175
+
176
+ self._last_param = {
177
+ name: config.get(self.schedule_param, None)
178
+ for name, config in self.data_sparsifier.data_groups.items()
179
+ }
180
+ self.data_sparsifier.enable_mask_update = True
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (361 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-310.pyc ADDED
Binary file (5.69 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-310.pyc ADDED
Binary file (4.08 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+ from functools import reduce
4
+ from typing import Any, List, Optional, Tuple
5
+
6
+ from .base_data_sparsifier import BaseDataSparsifier
7
+
8
+ __all__ = ['DataNormSparsifier']
9
+
10
+
11
+ class DataNormSparsifier(BaseDataSparsifier):
12
+ r"""L1-Norm Sparsifier
13
+ This sparsifier computes the *L1-norm* of every sparse block and "zeroes-out" the
14
+ ones with the lowest norm. The level of sparsity defines how many of the
15
+ blocks is removed.
16
+ This sparsifier is controlled by three variables:
17
+ 1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out
18
+ 2. `sparse_block_shape` defines the shape of the sparse blocks. Note that
19
+ the sparse blocks originate at the zero-index of the tensor.
20
+ 3. `zeros_per_block` is the number of zeros that we are expecting in each
21
+ sparse block. By default we assume that all elements within a block are
22
+ zeroed-out. However, setting this variable sets the target number of
23
+ zeros per block. The zeros within each block are chosen as the *smallest
24
+ absolute values*.
25
+ Args:
26
+ sparsity_level: The target level of sparsity
27
+ sparse_block_shape: The shape of a sparse block
28
+ zeros_per_block: Number of zeros in a sparse block
29
+ Note::
30
+ All arguments to the DataNormSparsifier constructor are "default"
31
+ arguments and could be overriden by the configuration provided in the
32
+ `add_data` step.
33
+ """
34
+ def __init__(self, data_list: Optional[List[Tuple[str, Any]]] = None, sparsity_level: float = 0.5,
35
+ sparse_block_shape: Tuple[int, int] = (1, 4),
36
+ zeros_per_block: Optional[int] = None, norm: str = 'L1'):
37
+ if zeros_per_block is None:
38
+ zeros_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
39
+
40
+ assert norm in ['L1', 'L2'], "only L1 and L2 norm supported at the moment"
41
+
42
+ defaults = {'sparsity_level': sparsity_level, 'sparse_block_shape': sparse_block_shape,
43
+ 'zeros_per_block': zeros_per_block}
44
+ self.norm = norm
45
+ super().__init__(data_list=data_list, **defaults)
46
+
47
+ def __get_scatter_folded_mask(self, data, dim, indices, output_size, sparse_block_shape):
48
+ mask = torch.ones_like(data)
49
+ mask.scatter_(dim=dim, index=indices, value=0) # zeroing out
50
+ mask = F.fold(mask, output_size=output_size, kernel_size=sparse_block_shape,
51
+ stride=sparse_block_shape)
52
+ mask = mask.to(torch.int8)
53
+ return mask
54
+
55
+ def __get_block_level_mask(self, data,
56
+ sparse_block_shape, zeros_per_block):
57
+
58
+ # Assume data is a squeezed tensor
59
+ height, width = data.shape[-2], data.shape[-1]
60
+ block_height, block_width = sparse_block_shape
61
+ values_per_block = block_height * block_width
62
+
63
+ # just return zeros if zeroing all elements in block
64
+ if values_per_block == zeros_per_block:
65
+ return torch.zeros_like(data, dtype=torch.int8)
66
+
67
+ # creating additional height and width to support padding
68
+ dh = (block_height - height % block_height) % block_height
69
+ dw = (block_width - width % block_width) % block_width
70
+
71
+ # create a new padded tensor like data (to match the block_shape)
72
+ padded_data = torch.ones(height + dh, width + dw, dtype=data.dtype, device=data.device)
73
+ padded_data = padded_data * torch.nan # can also be replaced with 0 to stop the removal of edge data
74
+ padded_data[0:height, 0:width] = data
75
+ unfolded_data = F.unfold(padded_data[None, None, :], kernel_size=sparse_block_shape,
76
+ stride=sparse_block_shape)
77
+
78
+ _, sorted_idx = torch.sort(unfolded_data, dim=1)
79
+ sorted_idx = sorted_idx[:, :zeros_per_block, :] # zero out zeros_per_block number of elements
80
+
81
+ mask = self.__get_scatter_folded_mask(data=unfolded_data, dim=1, indices=sorted_idx, output_size=padded_data.shape,
82
+ sparse_block_shape=sparse_block_shape)
83
+
84
+ mask = mask.squeeze(0).squeeze(0)[:height, :width].contiguous() # remove padding and make contiguous
85
+ return mask
86
+
87
+ def __get_data_level_mask(self, data, sparsity_level,
88
+ sparse_block_shape):
89
+
90
+ height, width = data.shape[-2], data.shape[-1]
91
+ block_height, block_width = sparse_block_shape
92
+ dh = (block_height - height % block_height) % block_height
93
+ dw = (block_width - width % block_width) % block_width
94
+
95
+ data_norm = F.avg_pool2d(data[None, None, :], kernel_size=sparse_block_shape,
96
+ stride=sparse_block_shape, ceil_mode=True)
97
+
98
+ values_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
99
+
100
+ data_norm = data_norm.flatten()
101
+ num_blocks = len(data_norm)
102
+
103
+ data_norm = data_norm.repeat(1, values_per_block, 1) # get similar shape after unfold
104
+ _, sorted_idx = torch.sort(data_norm, dim=2)
105
+
106
+ threshold_idx = round(sparsity_level * num_blocks) # number of blocks to remove
107
+ sorted_idx = sorted_idx[:, :, :threshold_idx]
108
+
109
+ mask = self.__get_scatter_folded_mask(data=data_norm, dim=2, indices=sorted_idx,
110
+ output_size=(height + dh, width + dw),
111
+ sparse_block_shape=sparse_block_shape)
112
+
113
+ mask = mask.squeeze(0).squeeze(0)[:height, :width] # squeeze only the first 2 dimension
114
+ return mask
115
+
116
+ def update_mask(self, name, data, sparsity_level,
117
+ sparse_block_shape, zeros_per_block, **kwargs):
118
+
119
+ values_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
120
+ if zeros_per_block > values_per_block:
121
+ raise ValueError("Number of zeros per block cannot be more than "
122
+ "the total number of elements in that block.")
123
+ if zeros_per_block < 0:
124
+ raise ValueError("Number of zeros per block should be positive.")
125
+
126
+ if self.norm == 'L1':
127
+ data_norm = torch.abs(data).squeeze() # absolute value based (L1)
128
+ else:
129
+ data_norm = (data * data).squeeze() # square every element for L2
130
+
131
+ if len(data_norm.shape) > 2: # only supports 2 dimensional data at the moment
132
+ raise ValueError("only supports 2-D at the moment")
133
+
134
+ elif len(data_norm.shape) == 1: # in case the data is bias (or 1D)
135
+ data_norm = data_norm[None, :]
136
+
137
+ mask = self.get_mask(name)
138
+ if sparsity_level <= 0 or zeros_per_block == 0:
139
+ mask.data = torch.ones_like(mask)
140
+ elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block):
141
+ mask.data = torch.zeros_like(mask)
142
+
143
+ # Fetch the high level mask that zeros out entire blocks
144
+ data_lvl_mask = self.__get_data_level_mask(data=data_norm, sparsity_level=sparsity_level,
145
+ sparse_block_shape=sparse_block_shape)
146
+
147
+ # Fetch block level mask that zeros out 'zeros_per_block' number of elements in every block
148
+ block_lvl_mask = self.__get_block_level_mask(data=data_norm, sparse_block_shape=sparse_block_shape,
149
+ zeros_per_block=zeros_per_block)
150
+
151
+ # zero out the entries inside those blocks whose block is sparsified
152
+ mask.data = torch.where(data_lvl_mask == 1, data_lvl_mask, block_lvl_mask)
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (212 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (222 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-310.pyc ADDED
Binary file (6.21 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from torch.ao.pruning._experimental.data_sparsifier.base_data_sparsifier import SUPPORTED_TYPES
3
+
4
+ logger: logging.Logger = logging.getLogger(__name__)
5
+
6
+
7
+ def _attach_model_to_data_sparsifier(module, data_sparsifier, config=None):
8
+ """Attaches a data sparsifier to all the layers of the module.
9
+ Essentially, loop over all the weight parameters in the module and
10
+ attach it to the data sparsifier.
11
+ Note::
12
+ The '.' in the layer names are replaced with '_' (refer to _get_valid_name() below)
13
+ before attaching to the sparsifier. This is because, the data
14
+ sparsifier uses a dummy model inside to store the weight parameters.
15
+ """
16
+ if config is None:
17
+ config = {}
18
+ for name, parameter in module.named_parameters():
19
+ if type(parameter) in SUPPORTED_TYPES:
20
+ valid_name = _get_valid_name(name)
21
+ # will be defaulted to default configs
22
+ data_sparsifier.add_data(name=valid_name, data=parameter, **config.get(valid_name, {}))
23
+
24
+
25
+ def _get_valid_name(name):
26
+ return name.replace('.', '_') # . is not allowed as a name
27
+
28
+
29
+ def _log_sparsified_level(model, data_sparsifier) -> None:
30
+ # Show the level of sparsity AFTER step:
31
+ for name, parameter in model.named_parameters():
32
+ if type(parameter) not in SUPPORTED_TYPES:
33
+ continue
34
+ valid_name = _get_valid_name(name)
35
+ mask = data_sparsifier.get_mask(name=valid_name)
36
+ sparsity_level = 1.0 - mask.float().mean()
37
+ logger.info(
38
+ "Sparsity in layer %s = % .2%", name, sparsity_level
39
+ )
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ from copy import deepcopy
3
+ import torch
4
+ from typing import Any, Optional, Dict
5
+ import pytorch_lightning as pl # type: ignore[import]
6
+
7
+ from ._data_sparstity_utils import (
8
+ _attach_model_to_data_sparsifier,
9
+ _log_sparsified_level,
10
+ _get_valid_name
11
+ )
12
+
13
+
14
+ class PostTrainingDataSparsity(pl.callbacks.Callback):
15
+ """Lightning callback that enables post-training sparsity.
16
+
17
+ This callback aims to sparsify the model inside lightning module after training.
18
+ **Note that the model is copied and then sparsified, so the existing model is not modified**
19
+
20
+ The sparsified model can be used for comparison and can be accessed using
21
+ <callback_obj>.sparsified
22
+
23
+ Args:
24
+ data_sparsifier_class (some implemented class of BaseDataSparsifier)
25
+ The data sparsifier object of this class is created when the
26
+ training starts.
27
+ Note: Objects should not be passed in here as they are created
28
+ once the training completes.
29
+
30
+ data_sparsifier_args (Dict)
31
+ Dictionary of args to be passed to the data sparsifier.
32
+ Note: data_list arg should be ignored
33
+
34
+ Hooks implemented:
35
+ on_fit_end()
36
+ 1. copies the model and attaches it to the sparsifier
37
+ 2. sparsier step() is called
38
+ 3. squashes the mask()
39
+ """
40
+ def __init__(self, data_sparsifier_class, data_sparsifier_args):
41
+ super().__init__()
42
+ self.data_sparsifier_class = data_sparsifier_class
43
+ self.data_sparsifier_args = data_sparsifier_args
44
+ self.data_sparsifier: Any = None
45
+ self.sparsified: Optional[torch.nn.Module] = None
46
+
47
+ def on_fit_end(self, trainer, pl_module) -> None:
48
+ self.sparsified = deepcopy(pl_module.model).eval()
49
+ self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args)
50
+
51
+ _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier)
52
+
53
+ self.data_sparsifier.step()
54
+
55
+ self.data_sparsifier.squash_mask() # currently squashes params for all mask
56
+
57
+ _log_sparsified_level(self.sparsified, self.data_sparsifier)
58
+
59
+
60
+ class TrainingAwareDataSparsity(pl.callbacks.Callback):
61
+ """Lightning callback that enables in-training sparsity.
62
+
63
+ This callback aims to sparsify the model inside lightning module during training.
64
+ **Note that the model is copied and then sparsified, so the existing model is not modified**
65
+
66
+ The sparsified model can be used for comparison and can be accessed using
67
+ <callback_obj>.sparsified
68
+
69
+ Args:
70
+ data_sparsifier_class (some implemented class of BaseDataSparsifier)
71
+ The data sparsifier object of this class is created when the
72
+ training starts.
73
+ Note: Objects should not be passed in here as they are created
74
+ when the training starts.
75
+
76
+ data_sparsifier_args (Dict)
77
+ Dictionary of args to be passed to the data sparsifier.
78
+ Note: data_list arg should be ignored
79
+
80
+ data_scheduler_class (some implemented class of BaseDataScheduler)
81
+ The data scheduler of this class is created when the training starts
82
+ Note: Objects should not be passed in here as they are created
83
+ when the training starts.
84
+
85
+ data_scheduler_args(Dict)
86
+ Dictionary of args to be passed to the data scheduler.
87
+ **Note: data_sparsifier arg should be ignored as the recipe
88
+ creates and pass sparsifier object into the class**
89
+
90
+ Hooks implemented:
91
+ on_train_start()
92
+ Data sparsifier and scheduler objects are created.
93
+ Pytorch model attached to the sparsifier
94
+
95
+ on_train_epoch_start()
96
+ Loads the state_dict of the data sparsifier
97
+
98
+ on_train_epoch_end()
99
+ 1. Copies the model and attaches it to the sparsifier
100
+ 2. sparsifier step() and scheduler step()
101
+ 3. Dump state_dict of the current sparsifier
102
+
103
+ on_train_end()
104
+ squash mask
105
+ """
106
+ def __init__(self, data_sparsifier_class, data_sparsifier_args,
107
+ data_scheduler_class, data_scheduler_args):
108
+ super().__init__()
109
+ # data sparsifier objects
110
+ self.data_sparsifier_class = data_sparsifier_class
111
+ self.data_sparsifier_args = data_sparsifier_args
112
+
113
+ # scheduler objects
114
+ self.data_scheduler_class = data_scheduler_class
115
+ self.data_scheduler_args = data_scheduler_args
116
+
117
+ # fields
118
+ self.data_sparsifier: Any = None
119
+ self.data_scheduler: Any = None
120
+ self.sparsified: Optional[torch.nn.Module] = None
121
+
122
+ self.data_sparsifier_state_dict: Any = None
123
+
124
+ def on_train_start(self, trainer, pl_module) -> None:
125
+ # create sparsifier
126
+ self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args)
127
+ self.sparsified = deepcopy(pl_module.model)
128
+
129
+ _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier) # just to populate the base_sl in the scheduler
130
+
131
+ # create scheduler
132
+ args = deepcopy(self.data_scheduler_args)
133
+ args['data_sparsifier'] = self.data_sparsifier
134
+ self.data_scheduler = self.data_scheduler_class(**args)
135
+
136
+ def on_train_epoch_start(self, trainer, pl_module):
137
+ if self.data_sparsifier_state_dict is None:
138
+ return # probably first epoch
139
+
140
+ # load the existing config for each data
141
+ self.data_sparsifier.load_state_dict(self.data_sparsifier_state_dict)
142
+
143
+ def __create_config_based_on_state(self, pl_module):
144
+ config: Dict = defaultdict()
145
+ if self.data_sparsifier_state_dict is None:
146
+ return config
147
+ for name, _ in pl_module.model.named_parameters():
148
+ valid_name = _get_valid_name(name)
149
+ config[valid_name] = self.data_sparsifier.data_groups[valid_name]
150
+
151
+ return config
152
+
153
+ def on_train_epoch_end(self, trainer, pl_module):
154
+ self.sparsified = deepcopy(pl_module.model)
155
+ config = self.__create_config_based_on_state(pl_module)
156
+
157
+ # attach model to the data sparsifier
158
+ _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier, config=config)
159
+ self.data_sparsifier.step()
160
+ self.data_scheduler.step()
161
+
162
+ self.data_sparsifier_state_dict = self.data_sparsifier.state_dict()
163
+
164
+ def on_train_end(self, trainer, pl_module):
165
+ self.data_sparsifier.squash_mask()
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional, Union
2
+
3
+ import torch
4
+
5
+ from .base_structured_sparsifier import BaseStructuredSparsifier
6
+
7
+ __all__ = ["FPGMPruner"]
8
+
9
+
10
+ class FPGMPruner(BaseStructuredSparsifier):
11
+ r"""Filter Pruning via Geometric Median (FPGM) Structured Pruner
12
+ This sparsifier prune fliter (row) in a tensor according to distances among filters according to
13
+ `Filter Pruning via Geometric Median for Deep Convolutional Neural Networks Acceleration <https://arxiv.org/abs/1811.00250>`_.
14
+
15
+ This sparsifier is controlled by three variables:
16
+ 1. `sparsity_level` defines the number of filters (rows) that are zeroed-out.
17
+ 2. `dist` defines the distance measurement type. Default: 3 (L2 distance).
18
+ Available options are: [1, 2, (custom callable distance function)].
19
+
20
+ Note::
21
+ Inputs should be a 4D convolutional tensor of shape (N, C, H, W).
22
+ - N: output channels size
23
+ - C: input channels size
24
+ - H: height of kernel
25
+ - W: width of kernel
26
+ """
27
+
28
+ def __init__(
29
+ self, sparsity_level: float = 0.5, dist: Optional[Union[Callable, int]] = None
30
+ ):
31
+ defaults = {
32
+ "sparsity_level": sparsity_level,
33
+ }
34
+
35
+ if dist is None:
36
+ dist = 2
37
+
38
+ if callable(dist):
39
+ self.dist_fn = dist
40
+ elif dist == 1:
41
+ self.dist_fn = lambda x: torch.cdist(x, x, p=1)
42
+ elif dist == 2:
43
+ self.dist_fn = lambda x: torch.cdist(x, x, p=2)
44
+ else:
45
+ raise NotImplementedError("Distance function is not yet implemented.")
46
+ super().__init__(defaults=defaults)
47
+
48
+ def _compute_distance(self, t):
49
+ r"""Compute distance across all entries in tensor `t` along all dimension
50
+ except for the one identified by dim.
51
+ Args:
52
+ t (torch.Tensor): tensor representing the parameter to prune
53
+ Returns:
54
+ distance (torch.Tensor): distance computed across filtters
55
+ """
56
+ dim = 0 # prune filter (row)
57
+
58
+ size = t.size(dim)
59
+ slc = [slice(None)] * t.dim()
60
+
61
+ # flatten the tensor along the dimension
62
+ t_flatten = [
63
+ t[tuple(slc[:dim] + [slice(i, i + 1)] + slc[dim + 1 :])].reshape(-1)
64
+ for i in range(size)
65
+ ]
66
+ t_flatten = torch.stack(t_flatten)
67
+
68
+ # distance measurement
69
+ dist_matrix = self.dist_fn(t_flatten)
70
+
71
+ # more similar with other filter indicates large in the sum of row
72
+ distance = torch.sum(torch.abs(dist_matrix), 1)
73
+
74
+ return distance
75
+
76
+ def update_mask(self, module, tensor_name, sparsity_level, **kwargs):
77
+ tensor_weight = getattr(module, tensor_name)
78
+ mask = getattr(module.parametrizations, tensor_name)[0].mask
79
+
80
+ if sparsity_level <= 0:
81
+ mask.data = torch.ones_like(mask).bool()
82
+ elif sparsity_level >= 1.0:
83
+ mask.data = torch.zeros_like(mask).bool()
84
+ else:
85
+ distance = self._compute_distance(tensor_weight)
86
+
87
+ tensor_size = tensor_weight.shape[0] # prune filter (row)
88
+ nparams_toprune = round(sparsity_level * tensor_size)
89
+ nparams_toprune = min(
90
+ max(nparams_toprune, 0), tensor_size
91
+ ) # clamp to [0, tensor_size]
92
+ topk = torch.topk(distance, k=nparams_toprune, largest=False)
93
+ mask[topk.indices] = False
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .base_structured_sparsifier import BaseStructuredSparsifier
2
+ from .parametrization import (
3
+ FakeStructuredSparsity,
4
+ BiasHook,
5
+ )
6
+ from .saliency_pruner import SaliencyPruner
7
+ from .lstm_saliency_pruner import LSTMSaliencyPruner
8
+ from .FPGM_pruner import FPGMPruner
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-310.pyc ADDED
Binary file (3.58 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (512 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-310.pyc ADDED
Binary file (6.69 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-310.pyc ADDED
Binary file (2.61 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain
2
+ from operator import getitem
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from torch.fx import symbolic_trace
7
+ from torch.nn.utils import parametrize
8
+ from typing import Type, Set, Dict, Callable, Tuple, Optional, Union
9
+
10
+ from torch.ao.pruning import BaseSparsifier
11
+ from .parametrization import FakeStructuredSparsity, BiasHook, module_contains_param
12
+ from .match_utils import apply_match, MatchAllNode
13
+ from .prune_functions import (
14
+ prune_linear,
15
+ prune_linear_linear,
16
+ prune_linear_activation_linear,
17
+ prune_conv2d,
18
+ prune_conv2d_conv2d,
19
+ prune_conv2d_activation_conv2d,
20
+ prune_conv2d_activation_pool_conv2d,
21
+ prune_conv2d_pool_activation_conv2d,
22
+ prune_conv2d_pool_flatten_linear,
23
+ prune_lstm_output_linear,
24
+ prune_lstm_output_layernorm_linear,
25
+ )
26
+
27
+
28
+ def _get_supported_structured_pruning_modules():
29
+ SUPPORTED_STRUCTURED_PRUNING_MODULES = { # added to config if None given
30
+ nn.Linear,
31
+ nn.Conv2d,
32
+ nn.LSTM,
33
+ }
34
+ return SUPPORTED_STRUCTURED_PRUNING_MODULES
35
+
36
+
37
+ def _get_supported_activation_functions():
38
+ SUPPORTED_ACTIVATION_FUNCTIONS = {
39
+ F.relu,
40
+ F.rrelu,
41
+ F.hardtanh,
42
+ F.relu6,
43
+ F.sigmoid,
44
+ F.hardsigmoid,
45
+ F.tanh,
46
+ F.silu,
47
+ F.mish,
48
+ F.hardswish,
49
+ F.elu,
50
+ F.celu,
51
+ F.selu,
52
+ F.hardshrink,
53
+ F.leaky_relu,
54
+ F.logsigmoid,
55
+ F.softplus,
56
+ F.prelu,
57
+ F.softsign,
58
+ F.tanhshrink,
59
+ F.gelu,
60
+ }
61
+ return SUPPORTED_ACTIVATION_FUNCTIONS
62
+
63
+
64
+ def _get_supported_activation_modules():
65
+ SUPPORTED_ACTIVATION_MODULES = {
66
+ nn.ReLU,
67
+ nn.RReLU,
68
+ nn.Hardtanh,
69
+ nn.ReLU6,
70
+ nn.Sigmoid,
71
+ nn.Hardsigmoid,
72
+ nn.Tanh,
73
+ nn.SiLU,
74
+ nn.Mish,
75
+ nn.Hardswish,
76
+ nn.ELU,
77
+ nn.CELU,
78
+ nn.SELU,
79
+ nn.Hardshrink,
80
+ nn.LeakyReLU,
81
+ nn.LogSigmoid,
82
+ nn.Softplus,
83
+ nn.PReLU,
84
+ nn.Softsign,
85
+ nn.Tanhshrink,
86
+ nn.GELU,
87
+ }
88
+ return SUPPORTED_ACTIVATION_MODULES
89
+
90
+
91
+ def _get_default_structured_pruning_patterns() -> Dict[
92
+ Tuple[Union[Type[nn.Module], Callable, MatchAllNode, str], ...],
93
+ Callable[..., None],
94
+ ]:
95
+ """
96
+ Returns the patterns for conv2d / linear conversion for each element in the activation functions/modules defined above.
97
+ """
98
+ patterns: Dict[
99
+ Tuple[Union[Type[nn.Module], Callable, MatchAllNode, str], ...],
100
+ Callable[..., None],
101
+ ] = {
102
+ # linear -> linear
103
+ (nn.Linear, "output"): prune_linear,
104
+ (nn.Linear, nn.Linear): prune_linear_linear,
105
+ # conv2d -> conv2d
106
+ (nn.Conv2d, "output"): prune_conv2d,
107
+ (nn.Conv2d, nn.Conv2d): prune_conv2d_conv2d,
108
+ # TODO LSTM Structured pruning does not support returned state currently.
109
+ # Should find a way to explicitly match getitem(0) instead of getitem.
110
+ # This will also require changing the pruning function.
111
+ # lstm -> getitem(0) -> linear
112
+ (nn.LSTM, getitem, nn.Linear): prune_lstm_output_linear,
113
+ # lstm -> getitem(0) -> layernorm -> linear
114
+ (nn.LSTM, getitem, nn.LayerNorm, nn.Linear): prune_lstm_output_layernorm_linear,
115
+ }
116
+
117
+ for activation in chain(
118
+ _get_supported_activation_functions(), _get_supported_activation_modules()
119
+ ):
120
+ patterns.update(
121
+ {
122
+ # linear -> activation -> linear
123
+ (nn.Linear, activation, nn.Linear): prune_linear_activation_linear,
124
+ # conv2d -> activation -> conv2d
125
+ (nn.Conv2d, activation, nn.Conv2d): prune_conv2d_activation_conv2d,
126
+ # conv2d -> activation -> pool -> conv2d
127
+ (
128
+ nn.Conv2d,
129
+ activation,
130
+ nn.AvgPool2d,
131
+ nn.Conv2d,
132
+ ): prune_conv2d_activation_pool_conv2d,
133
+ (
134
+ nn.Conv2d,
135
+ activation,
136
+ F.avg_pool2d,
137
+ nn.Conv2d,
138
+ ): prune_conv2d_activation_pool_conv2d,
139
+ (
140
+ nn.Conv2d,
141
+ activation,
142
+ nn.MaxPool2d,
143
+ nn.Conv2d,
144
+ ): prune_conv2d_activation_pool_conv2d,
145
+ (
146
+ nn.Conv2d,
147
+ activation,
148
+ F.max_pool2d,
149
+ nn.Conv2d,
150
+ ): prune_conv2d_activation_pool_conv2d,
151
+ # conv2d -> pool -> activation -> conv2d
152
+ (
153
+ nn.Conv2d,
154
+ nn.AvgPool2d,
155
+ activation,
156
+ nn.Conv2d,
157
+ ): prune_conv2d_pool_activation_conv2d,
158
+ (
159
+ nn.Conv2d,
160
+ F.avg_pool2d,
161
+ activation,
162
+ nn.Conv2d,
163
+ ): prune_conv2d_pool_activation_conv2d,
164
+ (
165
+ nn.Conv2d,
166
+ nn.MaxPool2d,
167
+ activation,
168
+ nn.Conv2d,
169
+ ): prune_conv2d_pool_activation_conv2d,
170
+ (
171
+ nn.Conv2d,
172
+ F.max_pool2d,
173
+ activation,
174
+ nn.Conv2d,
175
+ ): prune_conv2d_pool_activation_conv2d,
176
+ # conv2d -> adaptive pool -> flatten -> linear
177
+ (
178
+ nn.Conv2d,
179
+ nn.AdaptiveAvgPool2d,
180
+ nn.Flatten,
181
+ nn.Linear,
182
+ ): prune_conv2d_pool_flatten_linear,
183
+ (
184
+ nn.Conv2d,
185
+ nn.AdaptiveAvgPool2d,
186
+ torch.flatten,
187
+ nn.Linear,
188
+ ): prune_conv2d_pool_flatten_linear,
189
+ (
190
+ nn.Conv2d,
191
+ nn.AdaptiveMaxPool2d,
192
+ nn.Flatten,
193
+ nn.Linear,
194
+ ): prune_conv2d_pool_flatten_linear,
195
+ (
196
+ nn.Conv2d,
197
+ nn.AdaptiveMaxPool2d,
198
+ torch.flatten,
199
+ nn.Linear,
200
+ ): prune_conv2d_pool_flatten_linear,
201
+ }
202
+ )
203
+ return patterns
204
+
205
+
206
+ class BaseStructuredSparsifier(BaseSparsifier):
207
+ r"""Base class for structured pruning.
208
+
209
+ Abstract methods that need to be implemented:
210
+ - update_mask: Function to compute a new mask for all keys in the
211
+ `groups` attribute.
212
+
213
+ Args:
214
+ - defaults [dict]: default configurations will be attached to the
215
+ configuration. Only the keys that don't exist in the `config` will
216
+ be updated.
217
+ """
218
+
219
+ def __init__(self, defaults, patterns=None):
220
+ super().__init__(defaults)
221
+ if patterns is None:
222
+ patterns = _get_default_structured_pruning_patterns()
223
+ self.patterns = patterns
224
+
225
+ def make_config_from_model(
226
+ self,
227
+ model: nn.Module,
228
+ SUPPORTED_MODULES: Optional[Set[Type]] = None,
229
+ ) -> None:
230
+ if SUPPORTED_MODULES is None:
231
+ SUPPORTED_MODULES = _get_supported_structured_pruning_modules()
232
+ super().make_config_from_model(model, SUPPORTED_MODULES=SUPPORTED_MODULES)
233
+
234
+ def _prepare(self, *args, **kwargs) -> None:
235
+ r"""This function will attach the FakeStructuredSparsity parameterizations
236
+ and BiasHooks at the appropriate points in the model.
237
+ """
238
+ for config in self.groups:
239
+ module = config["module"]
240
+ tensor_name = config["tensor_name"]
241
+ parametrization = config.get("parametrization", FakeStructuredSparsity)
242
+ tensor = getattr(module, tensor_name)
243
+
244
+ mask = config.get(
245
+ "mask",
246
+ torch.ones(tensor.shape[0], dtype=torch.bool, device=tensor.device),
247
+ )
248
+ self.state[config["tensor_fqn"]]["mask"] = mask
249
+ parametrize.register_parametrization(
250
+ module, tensor_name, parametrization(mask)
251
+ )
252
+
253
+ # if linear / conv, we add in bias hooks
254
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
255
+ prune_bias = config.get("prune_bias", True)
256
+ if module.bias is not None:
257
+ module.register_parameter(
258
+ "_bias", nn.Parameter(module.bias.detach())
259
+ )
260
+ module.bias = None
261
+ module.prune_bias = prune_bias
262
+
263
+ module.register_forward_hook(
264
+ BiasHook(module.parametrizations.weight[0], prune_bias)
265
+ )
266
+
267
+ def prune(self) -> None:
268
+ r"""
269
+ This function will FX symbolically trace the model and then find instances of the patterns
270
+ defined in self.patterns (by default SUPPORTED_STRUCTURED_PRUNING_PATTERNS ).
271
+
272
+ For each pattern, it will apply to corresponding conversion function, which will modify the output
273
+ and input size expected by the modules within the pattern
274
+ """
275
+
276
+ self.traced = symbolic_trace(self.model)
277
+ modules = dict(self.traced.named_modules())
278
+
279
+ # Right now we check for matches simply by iterating across all the patterns
280
+ # if this is slow we can store patterns in a trie-structure and modify this code for faster lookup
281
+ for node in self.traced.graph.nodes:
282
+ for pattern, convert_fn in self.patterns.items():
283
+ matched = apply_match(modules, pattern, node, [])
284
+ if matched is None:
285
+ continue
286
+
287
+ first_module = modules.get(node.target)
288
+ # check if first module exists and has appropriate parameterization, otherwise skip
289
+ if (
290
+ first_module is not None
291
+ and parametrize.is_parametrized(first_module)
292
+ and module_contains_param(first_module, FakeStructuredSparsity)
293
+ ):
294
+ convert_block = []
295
+ for node in matched:
296
+ if node.op == "call_module":
297
+ convert_block.append(modules.get(node.target))
298
+ elif node.op == "call_function":
299
+ convert_block.append(node.target)
300
+ convert_fn(*convert_block)
301
+
302
+ for module in self.traced.modules():
303
+ if module_contains_param(module, FakeStructuredSparsity):
304
+ raise Exception(
305
+ f"Error: {module} still contains FakeStructuredSparsity parametrizations!"
306
+ )
307
+
308
+ self.traced.graph.lint()
309
+ self.traced.recompile()
310
+ return self.traced
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import cast
2
+
3
+ import torch
4
+ from .base_structured_sparsifier import BaseStructuredSparsifier, FakeStructuredSparsity
5
+
6
+ class LSTMSaliencyPruner(BaseStructuredSparsifier):
7
+ """
8
+ Prune packed LSTM weights based on saliency.
9
+ For each layer {k} inside a LSTM, we have two packed weight matrices
10
+ - weight_ih_l{k}
11
+ - weight_hh_l{k}
12
+
13
+ These tensors pack the weights for the 4 linear layers together for efficiency.
14
+
15
+ [W_ii | W_if | W_ig | W_io]
16
+
17
+ Pruning this tensor directly will lead to weights being misassigned when unpacked.
18
+ To ensure that each packed linear layer is pruned the same amount:
19
+ 1. We split the packed weight into the 4 constituent linear parts
20
+ 2. Update the mask for each individual piece using saliency individually
21
+
22
+ This applies to both weight_ih_l{k} and weight_hh_l{k}.
23
+ """
24
+
25
+ def update_mask(self, module, tensor_name, **kwargs):
26
+ weights = getattr(module, tensor_name)
27
+
28
+ for p in getattr(module.parametrizations, tensor_name):
29
+ if isinstance(p, FakeStructuredSparsity):
30
+ mask = cast(torch.Tensor, p.mask)
31
+
32
+ # select weights based on magnitude
33
+ if weights.dim() <= 1:
34
+ raise Exception("Structured pruning can only be applied to a 2+dim weight tensor!")
35
+ # take norm over all but first dim
36
+ dims = tuple(range(1, weights.dim()))
37
+ saliency = weights.norm(dim=dims, p=1)
38
+
39
+ # handle weights in 4 groups
40
+ split_size = len(mask) // 4
41
+ masks = torch.split(mask, split_size)
42
+ saliencies = torch.split(saliency, split_size)
43
+
44
+ for keep_mask, sal in zip(masks, saliencies):
45
+ # mask smallest k values to be removed
46
+ k = int(len(keep_mask) * kwargs["sparsity_level"])
47
+ prune = sal.topk(k, largest=False, sorted=False).indices
48
+ keep_mask.data[prune] = False # modifies underlying p.mask directly
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contains utility functions to check if a pattern is in the graph and return the matching nodes
3
+ """
4
+ import torch
5
+ from torch import nn
6
+ from torch.ao.quantization.utils import (
7
+ MatchAllNode,
8
+ )
9
+ from torch.fx import Node
10
+ from torch.nn.utils import parametrize
11
+ from typing import Any, Dict, List, Optional, Tuple, Union
12
+
13
+ def _match(modules: Dict[str, nn.ModuleDict], node: Node, current: Union[nn.Module, Any]) -> bool:
14
+ r"""
15
+ checks to see if a single node of a pattern matches
16
+ """
17
+ if isinstance(current, type) and issubclass(current, MatchAllNode):
18
+ return True
19
+ if not isinstance(node, Node):
20
+ return False
21
+ if isinstance(current, type) and issubclass(current, torch.nn.Module):
22
+ return (
23
+ node.op == "call_module"
24
+ and parametrize.type_before_parametrizations(modules[node.target])
25
+ == current
26
+ )
27
+ elif callable(current):
28
+ return node.op == "call_function" and node.target is current
29
+ elif isinstance(current, str):
30
+ return node.target == current
31
+ return False
32
+
33
+ def apply_match(
34
+ modules: Dict[str, nn.ModuleDict],
35
+ pattern: Union[Tuple[Any], Any],
36
+ node: Node,
37
+ matched_node_pattern: List[Node],
38
+ ) -> Optional[List[Node]]:
39
+ r"""
40
+ This function will return the matched nodes if the pattern matches the node given
41
+ If there is no match, it will return None
42
+ """
43
+ if isinstance(pattern, tuple):
44
+ if len(pattern) == 1:
45
+ if _match(modules, node, pattern[0]):
46
+ return matched_node_pattern + [node]
47
+
48
+ first, *rest = pattern
49
+ if _match(modules, node, first):
50
+ if rest is None:
51
+ return matched_node_pattern + [node]
52
+
53
+ for user in node.users:
54
+ return apply_match(
55
+ modules, tuple(rest), user, matched_node_pattern + [node]
56
+ )
57
+ elif _match(modules, node, pattern):
58
+ return [node]
59
+ return None
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch.nn.utils.parametrize import is_parametrized
4
+
5
+
6
+ def module_contains_param(module, parametrization):
7
+ if is_parametrized(module):
8
+ # see if any of the module tensors have a parametriztion attached that matches the one passed in
9
+ return any(
10
+ any(isinstance(param, parametrization) for param in param_list)
11
+ for key, param_list in module.parametrizations.items()
12
+ )
13
+ return False
14
+
15
+
16
+ # Structured Pruning Parameterizations
17
+ class FakeStructuredSparsity(nn.Module):
18
+ r"""
19
+ Parametrization for Structured Pruning. Like FakeSparsity, this should be attached to
20
+ the 'weight' or any other parameter that requires a mask.
21
+
22
+ Instead of an element-wise bool mask, this parameterization uses a row-wise bool mask.
23
+ """
24
+
25
+ def __init__(self, mask):
26
+ super().__init__()
27
+ self.register_buffer("mask", mask)
28
+
29
+ def forward(self, x):
30
+ assert isinstance(self.mask, torch.Tensor)
31
+ assert self.mask.shape[0] == x.shape[0]
32
+ shape = [1] * len(x.shape)
33
+ shape[0] = -1
34
+ return self.mask.reshape(shape) * x
35
+
36
+ def state_dict(self, *args, **kwargs):
37
+ # avoid double saving masks
38
+ return {}
39
+
40
+
41
+ class BiasHook:
42
+ def __init__(self, parametrization, prune_bias):
43
+ self.param = parametrization
44
+ self.prune_bias = prune_bias
45
+
46
+ def __call__(self, module, input, output):
47
+
48
+ if getattr(module, "_bias", None) is not None:
49
+ bias = module._bias.data
50
+ if self.prune_bias:
51
+ bias[~self.param.mask] = 0
52
+
53
+ # reshape bias to broadcast over output dimensions
54
+ idx = [1] * len(output.shape)
55
+ idx[1] = -1
56
+ bias = bias.reshape(idx)
57
+
58
+ output += bias
59
+ return output
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Collection of conversion functions for linear / conv2d structured pruning
3
+ Also contains utilities for bias propagation
4
+ """
5
+ from typing import cast, Optional, Callable, Tuple
6
+
7
+ import torch
8
+ from torch import nn, Tensor
9
+ from torch.nn.utils import parametrize
10
+ from torch.nn.utils.parametrize import ParametrizationList
11
+ from .parametrization import FakeStructuredSparsity, BiasHook
12
+
13
+ # BIAS PROPAGATION
14
+ def _remove_bias_handles(module: nn.Module) -> None:
15
+ if hasattr(module, "_forward_hooks"):
16
+ bias_hooks = []
17
+ for key, hook in module._forward_hooks.items():
18
+ if isinstance(hook, BiasHook):
19
+ bias_hooks.append(key)
20
+
21
+ for key in bias_hooks:
22
+ del module._forward_hooks[key]
23
+
24
+
25
+ def _get_adjusted_next_layer_bias(
26
+ next_layer: nn.Module, pruned_biases: Tensor, mask: Tensor
27
+ ) -> nn.Parameter:
28
+ r"""Returns new adjusted bias for the second supported module"""
29
+ if parametrize.is_parametrized(next_layer):
30
+ # need to access original weight
31
+ parametrization_dict = cast(nn.ModuleDict, next_layer.parametrizations)
32
+ weight_parameterizations = cast(
33
+ ParametrizationList, parametrization_dict.weight
34
+ )
35
+ next_weight = weight_parameterizations.original
36
+ else:
37
+ next_weight = cast(Tensor, next_layer.weight)
38
+
39
+ scaling_weight = next_weight[:, ~mask]
40
+ if isinstance(next_layer, nn.Conv2d): # checking for Conv2d
41
+ # Propagating first layer pruned biases and calculating the new second layer bias
42
+ # involves more steps since the Conv2d scaling weight has extra dimensions,
43
+ # so adding bias involves broadcasting, logically:
44
+ # for each channel k in range(oC):
45
+ # scaled_biases = sum(first_bias[pruned_idx] @ next_weight[k, pruned_idx, :, :].T)
46
+ # new_next_bias[k] = old_next_bias[k] + scaled_biases
47
+ scaling_product = torch.matmul(
48
+ pruned_biases.reshape(1, -1), torch.transpose(scaling_weight, 1, 2)
49
+ )
50
+ sum_range = list(range(len(scaling_product.shape)))[
51
+ 1:
52
+ ] # all but the first dimension
53
+ scaled_biases = torch.sum(scaling_product, sum_range)
54
+ elif isinstance(next_layer, nn.Linear): # Linear
55
+ scaled_biases = torch.matmul(
56
+ pruned_biases, torch.transpose(scaling_weight, 0, 1)
57
+ ) # recall b2_new = b1 @ w2.T + b2
58
+ else:
59
+ raise NotImplementedError(f"Type {type(next_layer)} not supported yet.")
60
+
61
+ if (
62
+ parametrize.is_parametrized(next_layer)
63
+ and getattr(next_layer, "_bias", None) is not None
64
+ ): # next_layer is parametrized & has original bias ._bias
65
+ adjusted_bias = nn.Parameter(scaled_biases + next_layer._bias)
66
+ elif (
67
+ not parametrize.is_parametrized(next_layer) and next_layer.bias is not None
68
+ ): # next_layer not parametrized & has .bias
69
+ adjusted_bias = nn.Parameter(scaled_biases + next_layer.bias)
70
+ else: # next_layer has no bias
71
+ adjusted_bias = nn.Parameter(scaled_biases)
72
+ return adjusted_bias
73
+
74
+
75
+ def _prune_module_bias(module: nn.Module, mask: Tensor) -> None:
76
+ r"""Applies mask to given modules bias"""
77
+ # prune bias along with weights, discard pruned indices of bias
78
+ original_bias = cast(Tensor, getattr(module, "_bias", module.bias))
79
+ if original_bias is not None:
80
+ module.bias = nn.Parameter(original_bias[mask])
81
+
82
+ # remove _bias parameter
83
+ if hasattr(module, "_bias"):
84
+ delattr(module, "_bias")
85
+
86
+
87
+ def _propogate_module_bias(module: nn.Module, mask: Tensor) -> Optional[Tensor]:
88
+ r"""
89
+ In the case that we need to propagate biases, this function will return the biases we need
90
+ """
91
+ # set current module bias
92
+ if module.bias is not None:
93
+ module.bias = nn.Parameter(cast(Tensor, module.bias)[mask])
94
+ elif getattr(module, "_bias", None) is not None:
95
+ module.bias = nn.Parameter(cast(Tensor, module._bias)[mask])
96
+
97
+ # get pruned biases to propagate to subsequent layer
98
+ if getattr(module, "_bias", None) is not None:
99
+ pruned_biases = cast(Tensor, module._bias)[~mask]
100
+ else:
101
+ pruned_biases = None
102
+
103
+ if hasattr(module, "_bias"):
104
+ delattr(module, "_bias")
105
+
106
+ return pruned_biases
107
+
108
+
109
+ # LINEAR
110
+ def _prune_linear_helper(linear: nn.Linear) -> Tensor:
111
+ # expects linear to be a parameterized linear module
112
+ parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
113
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
114
+ for p in weight_parameterizations:
115
+ if isinstance(p, FakeStructuredSparsity):
116
+ mask = cast(Tensor, p.mask)
117
+
118
+ with torch.no_grad():
119
+ parametrize.remove_parametrizations(linear, "weight", leave_parametrized=True)
120
+ linear.weight = nn.Parameter(linear.weight[mask])
121
+ linear.out_features = linear.weight.shape[0]
122
+ _remove_bias_handles(linear)
123
+
124
+ return mask
125
+
126
+
127
+ def prune_linear(linear: nn.Linear) -> None:
128
+ mask = _prune_linear_helper(linear)
129
+ if getattr(linear, "prune_bias", False):
130
+ _prune_module_bias(linear, mask)
131
+
132
+
133
+ def prune_linear_linear(linear1: nn.Linear, linear2: nn.Linear) -> None:
134
+ prune_linear_activation_linear(linear1, None, linear2)
135
+
136
+
137
+ def prune_linear_activation_linear(
138
+ linear1: nn.Linear,
139
+ activation: Optional[Callable[[Tensor], Tensor]],
140
+ linear2: nn.Linear,
141
+ ):
142
+ mask = _prune_linear_helper(linear1)
143
+ if getattr(linear1, "prune_bias", False):
144
+ _prune_module_bias(linear1, mask)
145
+ else:
146
+ pruned_biases = _propogate_module_bias(linear1, mask)
147
+ if pruned_biases is not None:
148
+ if activation:
149
+ pruned_biases = activation(pruned_biases)
150
+ linear2.bias = _get_adjusted_next_layer_bias(linear2, pruned_biases, mask)
151
+
152
+ with torch.no_grad():
153
+ if parametrize.is_parametrized(linear2):
154
+ parametrization_dict = cast(nn.ModuleDict, linear2.parametrizations)
155
+ weight_parameterizations = cast(
156
+ ParametrizationList, parametrization_dict.weight
157
+ )
158
+
159
+ weight_parameterizations.original = nn.Parameter(
160
+ weight_parameterizations.original[:, mask]
161
+ )
162
+ linear2.in_features = weight_parameterizations.original.shape[1]
163
+ else:
164
+ linear2.weight = nn.Parameter(linear2.weight[:, mask])
165
+ linear2.in_features = linear2.weight.shape[1]
166
+
167
+
168
+ # CONV2D
169
+ def _prune_conv2d_helper(conv2d: nn.Conv2d) -> Tensor:
170
+ parametrization_dict = cast(nn.ModuleDict, conv2d.parametrizations)
171
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
172
+ for p in weight_parameterizations:
173
+ if isinstance(p, FakeStructuredSparsity):
174
+ mask = cast(Tensor, p.mask)
175
+
176
+ with torch.no_grad():
177
+ parametrize.remove_parametrizations(conv2d, "weight", leave_parametrized=True)
178
+ conv2d.weight = nn.Parameter(conv2d.weight[mask])
179
+ conv2d.out_channels = conv2d.weight.shape[0]
180
+
181
+ _remove_bias_handles(conv2d)
182
+ return mask
183
+
184
+
185
+ def prune_conv2d_padded(conv2d_1: nn.Conv2d) -> None:
186
+ parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations)
187
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
188
+ for p in weight_parameterizations:
189
+ if isinstance(p, FakeStructuredSparsity):
190
+ mask = cast(Tensor, p.mask)
191
+
192
+ with torch.no_grad():
193
+ parametrize.remove_parametrizations(conv2d_1, "weight", leave_parametrized=True)
194
+
195
+ if getattr(conv2d_1, "_bias", None) is not None:
196
+ if (
197
+ conv2d_1.bias is not None
198
+ ): # conv2d_1 has original bias and bias propagated from previous layer
199
+ new_bias = torch.zeros(conv2d_1.bias.shape)
200
+ new_bias[mask] = conv2d_1.bias[mask]
201
+ # adjusted bias that to keep in conv2d_1
202
+ new_bias[~mask] = cast(Tensor, conv2d_1._bias)[~mask]
203
+ # pruned biases that are kept instead of propagated
204
+ conv2d_1.bias = nn.Parameter(new_bias)
205
+ else: # conv2d_1 has only original bias
206
+ conv2d_1.bias = nn.Parameter(cast(Tensor, conv2d_1._bias))
207
+ else:
208
+ # no original bias, only propagated bias
209
+ if (
210
+ conv2d_1.bias is not None
211
+ ): # conv2d_1 has bias propagated from previous layer
212
+ conv2d_1.bias.data[~mask] = 0
213
+
214
+ if hasattr(conv2d_1, "_bias"):
215
+ delattr(conv2d_1, "_bias")
216
+
217
+
218
+ def prune_conv2d(conv2d: nn.Conv2d) -> None:
219
+ mask = _prune_conv2d_helper(conv2d)
220
+ if getattr(conv2d, "prune_bias", False):
221
+ _prune_module_bias(conv2d, mask)
222
+
223
+
224
+ def prune_conv2d_conv2d(conv2d_1: nn.Conv2d, conv2d_2: nn.Conv2d) -> None:
225
+ prune_conv2d_activation_conv2d(conv2d_1, None, conv2d_2)
226
+
227
+
228
+ def prune_conv2d_activation_conv2d(
229
+ conv2d_1: nn.Conv2d,
230
+ activation: Optional[Callable[[Tensor], Tensor]],
231
+ conv2d_2: nn.Conv2d,
232
+ ):
233
+ r"""
234
+ Fusion Pattern for conv2d -> some activation module / function -> conv2d layers
235
+ """
236
+ parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations)
237
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
238
+ for p in weight_parameterizations:
239
+ if isinstance(p, FakeStructuredSparsity):
240
+ mask = cast(Tensor, p.mask)
241
+
242
+ prune_bias = getattr(conv2d_1, "prune_bias", False)
243
+ if (
244
+ hasattr(conv2d_2, "padding")
245
+ and cast(Tuple[int], conv2d_2.padding) > (0, 0)
246
+ and (conv2d_1.bias is not None or getattr(conv2d_1, "_bias", None) is not None)
247
+ ):
248
+ prune_conv2d_padded(conv2d_1)
249
+ else:
250
+ mask = _prune_conv2d_helper(conv2d_1)
251
+ if prune_bias:
252
+ _prune_module_bias(conv2d_1, mask)
253
+ else:
254
+ pruned_biases = _propogate_module_bias(conv2d_1, mask)
255
+ if pruned_biases is not None:
256
+ if activation:
257
+ pruned_biases = activation(pruned_biases)
258
+ conv2d_2.bias = _get_adjusted_next_layer_bias(
259
+ conv2d_2, pruned_biases, mask
260
+ )
261
+
262
+ if (
263
+ not (
264
+ hasattr(conv2d_2, "padding")
265
+ and cast(Tuple[int], conv2d_2.padding) > (0, 0)
266
+ )
267
+ or conv2d_1.bias is None
268
+ ):
269
+ with torch.no_grad():
270
+ if parametrize.is_parametrized(conv2d_2):
271
+ parametrization_dict = cast(
272
+ nn.ModuleDict, conv2d_2.parametrizations
273
+ )
274
+ weight_parameterizations = cast(
275
+ ParametrizationList, parametrization_dict.weight
276
+ )
277
+ weight_parameterizations.original = nn.Parameter(
278
+ weight_parameterizations.original[:, mask]
279
+ )
280
+ conv2d_2.in_channels = weight_parameterizations.original.shape[1]
281
+ else:
282
+ conv2d_2.weight = nn.Parameter(conv2d_2.weight[:, mask])
283
+ conv2d_2.in_channels = conv2d_2.weight.shape[1]
284
+
285
+
286
+ def prune_conv2d_pool_activation_conv2d(
287
+ c1: nn.Conv2d,
288
+ pool: nn.Module,
289
+ activation: Optional[Callable[[Tensor], Tensor]],
290
+ c2: nn.Conv2d,
291
+ ) -> None:
292
+ prune_conv2d_activation_conv2d(c1, activation, c2)
293
+
294
+
295
+ def prune_conv2d_activation_pool_conv2d(
296
+ c1: nn.Conv2d,
297
+ activation: Optional[Callable[[Tensor], Tensor]],
298
+ pool: nn.Module,
299
+ c2: nn.Conv2d,
300
+ ) -> None:
301
+ prune_conv2d_activation_conv2d(c1, activation, c2)
302
+
303
+
304
+ def prune_conv2d_pool_flatten_linear(
305
+ conv2d: nn.Conv2d,
306
+ pool: nn.Module,
307
+ flatten: Optional[Callable[[Tensor], Tensor]],
308
+ linear: nn.Linear,
309
+ ) -> None:
310
+ mask = _prune_conv2d_helper(conv2d)
311
+
312
+ # We map the pruned indices of the Conv2d output to the flattened indices of the Linear following the Flatten layer.
313
+ # we determine the flattening scale (h * w), and readjust `first_pruned_indices`
314
+ # (each idx maps to range idx * h * w to (idx+1) * h * w), `first_valid_indices`,
315
+ # and `pruned_biases` (repeat each bias by h * w).
316
+ if parametrize.is_parametrized(linear):
317
+ parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
318
+ weight_parameterizations = cast(
319
+ ParametrizationList, parametrization_dict.weight
320
+ )
321
+ linear_ic = weight_parameterizations.original.shape[1]
322
+ else:
323
+ linear_ic = linear.weight.shape[1]
324
+
325
+ conv2d_oc = len(mask)
326
+ assert (
327
+ linear_ic % conv2d_oc == 0
328
+ ), f"Flattening from dimensions {conv2d_oc} to {linear_ic} not supported"
329
+
330
+ flatten_scale = linear_ic // conv2d_oc
331
+ flattened_mask = torch.tensor(
332
+ [[val] * flatten_scale for val in mask], dtype=torch.bool, device=mask.device
333
+ ).flatten()
334
+
335
+ if getattr(conv2d, "prune_bias", False):
336
+ _prune_module_bias(conv2d, mask)
337
+ else:
338
+ pruned_biases = cast(Tensor, _propogate_module_bias(conv2d, mask))
339
+ flattened_pruned_biases = torch.tensor(
340
+ [[bias] * flatten_scale for bias in pruned_biases], device=mask.device
341
+ ).flatten()
342
+ linear.bias = _get_adjusted_next_layer_bias(
343
+ linear, flattened_pruned_biases, flattened_mask
344
+ )
345
+
346
+ with torch.no_grad():
347
+ if parametrize.is_parametrized(linear):
348
+ parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
349
+ weight_parameterizations = cast(
350
+ ParametrizationList, parametrization_dict.weight
351
+ )
352
+ weight_parameterizations.original = nn.Parameter(
353
+ weight_parameterizations.original[:, flattened_mask]
354
+ )
355
+ linear.in_features = weight_parameterizations.original.shape[1]
356
+ else:
357
+ linear.weight = nn.Parameter(linear.weight[:, flattened_mask])
358
+ linear.in_features = linear.weight.shape[1]
359
+
360
+
361
+ def prune_lstm_output_linear(
362
+ lstm: nn.LSTM, getitem: Callable, linear: nn.Linear
363
+ ) -> None:
364
+ prune_lstm_output_layernorm_linear(lstm, getitem, None, linear)
365
+
366
+
367
+ def prune_lstm_output_layernorm_linear(
368
+ lstm: nn.LSTM,
369
+ getitem: Callable,
370
+ layernorm: Optional[nn.LayerNorm],
371
+ linear: nn.Linear,
372
+ ) -> None:
373
+ for i in range(lstm.num_layers):
374
+ if parametrize.is_parametrized(lstm, f"weight_ih_l{i}"):
375
+ parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations)
376
+ weight_parameterizations = cast(
377
+ ParametrizationList, parametrization_dict[f"weight_ih_l{i}"]
378
+ )
379
+ mask = weight_parameterizations[0].mask
380
+
381
+ with torch.no_grad():
382
+ parametrize.remove_parametrizations(
383
+ lstm, f"weight_ih_l{i}", leave_parametrized=True
384
+ )
385
+ setattr(
386
+ lstm,
387
+ f"weight_ih_l{i}",
388
+ nn.Parameter(getattr(lstm, f"weight_ih_l{i}")[mask]),
389
+ )
390
+ setattr(
391
+ lstm,
392
+ f"bias_ih_l{i}",
393
+ nn.Parameter(getattr(lstm, f"bias_ih_l{i}")[mask]),
394
+ )
395
+
396
+ if parametrize.is_parametrized(lstm, f"weight_hh_l{i}"):
397
+ parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations)
398
+ weight_parameterizations = cast(
399
+ ParametrizationList, parametrization_dict[f"weight_hh_l{i}"]
400
+ )
401
+ mask = weight_parameterizations[0].mask
402
+
403
+ with torch.no_grad():
404
+ parametrize.remove_parametrizations(
405
+ lstm, f"weight_hh_l{i}", leave_parametrized=True
406
+ )
407
+ # splitting out hidden-hidden masks
408
+ W_hi, W_hf, W_hg, W_ho = torch.split(
409
+ getattr(lstm, f"weight_hh_l{i}"), lstm.hidden_size
410
+ )
411
+ M_hi, M_hf, M_hg, M_ho = torch.split(mask, lstm.hidden_size)
412
+
413
+ # resize each individual weight separately
414
+ W_hi = W_hi[M_hi][:, M_hi]
415
+ W_hf = W_hf[M_hf][:, M_hf]
416
+ W_hg = W_hg[M_hg][:, M_hg]
417
+ W_ho = W_ho[M_ho][:, M_ho]
418
+
419
+ # concat, use this as new weight
420
+ new_weight = torch.cat((W_hi, W_hf, W_hg, W_ho))
421
+ setattr(lstm, f"weight_hh_l{i}", nn.Parameter(new_weight))
422
+ setattr(
423
+ lstm,
424
+ f"bias_hh_l{i}",
425
+ nn.Parameter(getattr(lstm, f"bias_hh_l{i}")[mask]),
426
+ )
427
+
428
+ # If this is the final layer, then we need to prune linear layer columns
429
+ if i + 1 == lstm.num_layers:
430
+ lstm.hidden_size = int(M_hi.sum())
431
+ with torch.no_grad():
432
+ if parametrize.is_parametrized(linear):
433
+ parametrization_dict = cast(
434
+ nn.ModuleDict, linear.parametrizations
435
+ )
436
+ weight_parameterizations = cast(
437
+ ParametrizationList, parametrization_dict.weight
438
+ )
439
+
440
+ weight_parameterizations.original = nn.Parameter(
441
+ weight_parameterizations.original[:, M_ho]
442
+ )
443
+ linear.in_features = weight_parameterizations.original.shape[1]
444
+ else:
445
+ linear.weight = nn.Parameter(linear.weight[:, M_ho])
446
+ linear.in_features = linear.weight.shape[1]
447
+
448
+ # if layernorm module, prune weight and bias
449
+ if layernorm is not None:
450
+ layernorm.normalized_shape = (linear.in_features,)
451
+ layernorm.weight = nn.Parameter(layernorm.weight[M_ho])
452
+ layernorm.bias = nn.Parameter(layernorm.bias[M_ho])
453
+
454
+ # otherwise need to prune the columns of the input of the next LSTM layer
455
+ else:
456
+ with torch.no_grad():
457
+ if parametrize.is_parametrized(lstm, f"weight_ih_l{i+1}"):
458
+ parametrization_dict = cast(
459
+ nn.ModuleDict, lstm.parametrizations
460
+ )
461
+ weight_parameterizations = cast(
462
+ ParametrizationList,
463
+ getattr(parametrization_dict, f"weight_ih_l{i+1}"),
464
+ )
465
+
466
+ weight_parameterizations.original = nn.Parameter(
467
+ weight_parameterizations.original[:, M_ho]
468
+ )
469
+ else:
470
+ next_layer_weight = getattr(lstm, f"weight_ih_l{i+1}")
471
+ setattr(
472
+ lstm,
473
+ f"weight_ih_l{i+1}",
474
+ nn.Parameter(next_layer_weight[:, M_ho]),
475
+ )
llava_next/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base_structured_sparsifier import BaseStructuredSparsifier
2
+
3
+
4
+ class SaliencyPruner(BaseStructuredSparsifier):
5
+ """
6
+ Prune rows based on the saliency (L1 norm) of each row.
7
+
8
+ This pruner works on N-Dimensional weight tensors.
9
+ For each row, we will calculate the saliency, whic is the sum the L1 norm of all weights in that row.
10
+ We expect that the resulting saliency vector has the same shape as our mask.
11
+ We then pick elements to remove until we reach the target sparsity_level.
12
+ """
13
+
14
+ def update_mask(self, module, tensor_name, **kwargs):
15
+ # tensor_name will give you the FQN, all other entries in sparse config is present in kwargs
16
+ weights = getattr(module, tensor_name)
17
+ mask = getattr(module.parametrizations, tensor_name)[0].mask
18
+
19
+ # use negative weights so we can use topk (we prune out the smallest)
20
+ if weights.dim() <= 1:
21
+ raise Exception("Structured pruning can only be applied to a 2+dim weight tensor!")
22
+ saliency = -weights.norm(dim=tuple(range(1, weights.dim())), p=1)
23
+ assert saliency.shape == mask.shape
24
+
25
+ num_to_pick = int(len(mask) * kwargs["sparsity_level"])
26
+ prune = saliency.topk(num_to_pick).indices
27
+
28
+ # Set the mask to be false for the rows we want to prune
29
+ mask.data[prune] = False
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (182 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-310.pyc ADDED
Binary file (5.81 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-310.pyc ADDED
Binary file (3.88 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from torch.ao.pruning import BaseSparsifier
3
+
4
+ from functools import wraps
5
+ import warnings
6
+ import weakref
7
+
8
+ __all__ = ["BaseScheduler"]
9
+
10
+ class BaseScheduler:
11
+
12
+ def __init__(self, sparsifier, last_epoch=-1, verbose=False):
13
+
14
+ # Attach sparsifier
15
+ if not isinstance(sparsifier, BaseSparsifier):
16
+ raise TypeError(f'{type(sparsifier).__name__} is not an instance of torch.ao.pruning.BaseSparsifier')
17
+ self.sparsifier = sparsifier
18
+
19
+ # Initialize epoch and base sparsity levels
20
+
21
+ self.base_sl = [group['sparsity_level'] for group in sparsifier.groups]
22
+ self.last_epoch = last_epoch
23
+
24
+ # Following https://github.com/pytorch/pytorch/issues/20124
25
+ # We would like to ensure that `scheduler.step()` is called after
26
+ # `sparsifier.step()`
27
+ def with_counter(method):
28
+ if getattr(method, '_with_counter', False):
29
+ # `sparsifier.step()` has already been replaced, return.
30
+ return method
31
+
32
+ # Keep a weak reference to the sparsifier instance to prevent
33
+ # cyclic references.
34
+ instance_ref = weakref.ref(method.__self__)
35
+ # Get the unbound method for the same purpose.
36
+ func = method.__func__
37
+ cls = instance_ref().__class__
38
+ del method
39
+
40
+ @wraps(func)
41
+ def wrapper(*args, **kwargs):
42
+ instance = instance_ref()
43
+ instance._step_count += 1 # type: ignore[union-attr]
44
+ wrapped = func.__get__(instance, cls)
45
+ return wrapped(*args, **kwargs)
46
+
47
+ # Note that the returned function here is no longer a bound method,
48
+ # so attributes like `__func__` and `__self__` no longer exist.
49
+ wrapper._with_counter = True # type: ignore[attr-defined]
50
+ return wrapper
51
+
52
+ self.sparsifier.step = with_counter(self.sparsifier.step) # type: ignore[assignment]
53
+ self.sparsifier._step_count = 0 # type: ignore[attr-defined]
54
+ self._step_count: int = 0
55
+ self.verbose = verbose
56
+
57
+ # Housekeeping
58
+ self._get_sl_called_within_step: bool = False
59
+
60
+ self.step()
61
+
62
+ def state_dict(self):
63
+ """Returns the state of the scheduler as a :class:`dict`.
64
+
65
+ It contains an entry for every variable in self.__dict__ which
66
+ is not the sparsifier.
67
+ """
68
+ return {key: value for key, value in self.__dict__.items() if key != 'sparsifier'}
69
+
70
+ def load_state_dict(self, state_dict):
71
+ """Loads the schedulers state.
72
+
73
+ Args:
74
+ state_dict (dict): scheduler state. Should be an object returned
75
+ from a call to :meth:`state_dict`.
76
+ """
77
+ self.__dict__.update(state_dict)
78
+
79
+ def get_last_sl(self):
80
+ """ Return last computed sparsity level by current scheduler.
81
+ """
82
+ return self._last_sl
83
+
84
+ def get_sl(self):
85
+ # Compute sparsity level using chainable form of the scheduler
86
+ # Note: This method is not intended to be called directly, and is only
87
+ # used by the ".step" method. Use .get_last_sl() instead.
88
+ if not self._get_sl_called_within_step:
89
+ warnings.warn(
90
+ "To get the last sparsity level computed by the scheduler, "
91
+ "please use `get_last_sl()`.")
92
+ raise NotImplementedError
93
+
94
+ def print_sl(self, is_verbose, group, sl, epoch=None):
95
+ """Display the current sparsity level.
96
+ """
97
+ if is_verbose:
98
+ if epoch is None:
99
+ print(f'Adjusting sparsity level of group {group} to {sl:.4e}.')
100
+ else:
101
+ print(f'Epoch {epoch:5d}: adjusting sparsity level of group {group} to {sl:.4e}.')
102
+
103
+ def __repr__(self):
104
+ format_string = self.__class__.__name__ + ' ('
105
+ format_string += '\n'
106
+ format_string += f'Sparsifier {self.sparsifier}\n'
107
+ format_string += f' base_sl: {self.base_sl}\n'
108
+ format_string += ')'
109
+ return format_string
110
+
111
+ def step(self, epoch=None):
112
+ # Raise warning if trying to call scheduler step before the sparsifier.
113
+ # https://github.com/pytorch/pytorch/issues/20124
114
+ if self._step_count == 1:
115
+ if not hasattr(self.sparsifier.step, "_with_counter"):
116
+ warnings.warn("Seems like `sparsifier.step()` has been overridden after sparsity scheduler "
117
+ "initialization. Please, make sure to call `sparsifier.step()` before "
118
+ "`scheduler.step()`.", UserWarning)
119
+
120
+ # Just check if there were two first scheduler.step() calls before sparsifier.step()
121
+ elif self.sparsifier._step_count < 1: # type: ignore[attr-defined]
122
+ warnings.warn("Detected call of `scheduler.step()` before `sparsifier.step()`. "
123
+ "You have to make sure you run the sparsifier.step() BEFORE any "
124
+ "calls to the scheduler.step().", UserWarning)
125
+ self._step_count += 1
126
+
127
+ class _enable_get_sl_call:
128
+
129
+ def __init__(self, o):
130
+ self.o = o
131
+
132
+ def __enter__(self):
133
+ self.o._get_sl_called_within_step = True
134
+ return self
135
+
136
+ def __exit__(self, type, value, traceback):
137
+ self.o._get_sl_called_within_step = False
138
+
139
+ with _enable_get_sl_call(self):
140
+ self.last_epoch += 1
141
+ values = self.get_sl()
142
+
143
+ for i, data in enumerate(zip(self.sparsifier.groups, values)):
144
+ param_group, sl = data
145
+ param_group['sparsity_level'] = sl
146
+ self.print_sl(self.verbose, i, sl, epoch)
147
+
148
+ self._last_sl = [group['sparsity_level'] for group in self.sparsifier.groups]
149
+ self.sparsifier.enable_mask_update = True
150
+
151
+ def _make_sure_a_list(self, var):
152
+ r"""Utility that extends it to the same length as the .groups, ensuring it is a list"""
153
+ n = len(self.sparsifier.groups)
154
+ if not isinstance(var, (list, tuple)):
155
+ return [var] * n
156
+ else:
157
+ if len(var) != n:
158
+ raise ValueError(f"Expected variable of length {n}, but got {len(var)}")
159
+ return list(var) # We want the result to be in a list, not tuple
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ from .base_scheduler import BaseScheduler
4
+
5
+ __all__ = ["CubicSL"]
6
+
7
+ def _clamp(x, lo, hi):
8
+ return max(lo, min(hi, x))
9
+
10
+
11
+ class CubicSL(BaseScheduler):
12
+ r"""Sets the sparsity level of each parameter group to the final sl
13
+ plus a given exponential function.
14
+
15
+ .. math::
16
+
17
+ s_i = s_f + (s_0 - s_f) \cdot \left( 1 - \frac{t - t_0}{n\Delta t} \right)^3
18
+
19
+ where :math:`s_i` is the sparsity at epoch :math:`t`, :math;`s_f` is the final
20
+ sparsity level, :math:`f(i)` is the function to be applied to the current epoch
21
+ :math:`t`, initial epoch :math:`t_0`, and final epoch :math:`t_f`.
22
+ :math:`\Delta t` is used to control how often the update of the sparsity level
23
+ happens. By default,
24
+
25
+ Args:
26
+ sparsifier (BaseSparsifier): Wrapped sparsifier.
27
+ init_sl (int, list): Initial level of sparsity
28
+ init_t (int, list): Initial step, when pruning starts
29
+ delta_t (int, list): Pruning frequency
30
+ total_t (int, list): Total number of pruning steps
31
+ initially_zero (bool, list): If True, sets the level of sparsity to 0
32
+ before init_t (:math:`t_0`). Otherwise, the sparsity level before
33
+ init_t (:math:`t_0`) is set to init_sl(:math:`s_0`)
34
+ last_epoch (int): The index of last epoch. Default: -1.
35
+ verbose (bool): If ``True``, prints a message to stdout for
36
+ each update. Default: ``False``.
37
+ """
38
+ def __init__(self,
39
+ sparsifier,
40
+ init_sl=0.0,
41
+ init_t=0,
42
+ delta_t=10,
43
+ total_t=100,
44
+ initially_zero=False,
45
+ last_epoch=-1,
46
+ verbose=False
47
+ ):
48
+ self.sparsifier = sparsifier
49
+
50
+ self.init_sl = self._make_sure_a_list(init_sl)
51
+ self.init_t = self._make_sure_a_list(init_t)
52
+ self.delta_t = self._make_sure_a_list(delta_t)
53
+ self.total_t = self._make_sure_a_list(total_t)
54
+
55
+ self.initially_zero = self._make_sure_a_list(initially_zero)
56
+
57
+ super().__init__(sparsifier, last_epoch, verbose)
58
+
59
+ @staticmethod
60
+ def sparsity_compute_fn(s_0, s_f, t, t_0, dt, n, initially_zero=False):
61
+ r""""Computes the current level of sparsity.
62
+
63
+ Based on https://arxiv.org/pdf/1710.01878.pdf
64
+
65
+ Args:
66
+ s_0: Initial level of sparsity, :math:`s_i`
67
+ s_f: Target level of sparsity, :math:`s_f`
68
+ t: Current step, :math:`t`
69
+ t_0: Initial step, :math:`t_0`
70
+ dt: Pruning frequency, :math:`\Delta T`
71
+ n: Pruning steps, :math:`n`
72
+ initially_zero: Sets the level of sparsity to 0 before t_0.
73
+ If False, sets to s_0
74
+
75
+ Returns:
76
+ The sparsity level :math:`s_t` at the current step :math:`t`
77
+ """
78
+ if initially_zero and t < t_0:
79
+ return 0
80
+ s_t = s_f + (s_0 - s_f) * (1.0 - (t - t_0) / (dt * n)) ** 3
81
+ s_t = _clamp(s_t, s_0, s_f)
82
+ return s_t
83
+
84
+ def get_sl(self):
85
+ if not self._get_sl_called_within_step:
86
+ warnings.warn(
87
+ "To get the last sparsity level computed by the scheduler, "
88
+ "please use `get_last_sl()`.")
89
+ return [
90
+ self.sparsity_compute_fn(
91
+ s_0=initial_sparsity,
92
+ s_f=final_sparsity,
93
+ t=self.last_epoch,
94
+ t_0=initial_epoch,
95
+ dt=delta_epoch,
96
+ n=interval_epochs,
97
+ initially_zero=initially_zero
98
+ ) for initial_sparsity, final_sparsity, initial_epoch, delta_epoch, interval_epochs, initially_zero in
99
+ zip(
100
+ self.init_sl,
101
+ self.base_sl,
102
+ self.init_t,
103
+ self.delta_t,
104
+ self.total_t,
105
+ self.initially_zero
106
+ )
107
+ ]
llava_next/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ from .base_scheduler import BaseScheduler
4
+
5
+ __all__ = ["LambdaSL"]
6
+
7
+ class LambdaSL(BaseScheduler):
8
+ """Sets the sparsity level of each parameter group to the final sl
9
+ times a given function. When last_epoch=-1, sets initial sl as zero.
10
+ Args:
11
+ sparsifier (BaseSparsifier): Wrapped sparsifier.
12
+ sl_lambda (function or list): A function which computes a multiplicative
13
+ factor given an integer parameter epoch, or a list of such
14
+ functions, one for each group in sparsifier.param_groups.
15
+ last_epoch (int): The index of last epoch. Default: -1.
16
+ verbose (bool): If ``True``, prints a message to stdout for
17
+ each update. Default: ``False``.
18
+ Example:
19
+ >>> # Assuming sparsifier has two groups.
20
+ >>> lambda1 = lambda epoch: epoch // 30
21
+ >>> lambda2 = lambda epoch: 0.95 ** epoch
22
+ >>> # xdoctest: +SKIP
23
+ >>> scheduler = LambdaSL(sparsifier, sl_lambda=[lambda1, lambda2])
24
+ >>> for epoch in range(100):
25
+ >>> train(...)
26
+ >>> validate(...)
27
+ >>> scheduler.step()
28
+ """
29
+
30
+ def __init__(self, sparsifier, sl_lambda, last_epoch=-1, verbose=False):
31
+ self.sparsifier = sparsifier
32
+
33
+ if not isinstance(sl_lambda, list) and not isinstance(sl_lambda, tuple):
34
+ self.sl_lambdas = [sl_lambda] * len(sparsifier.groups)
35
+ else:
36
+ if len(sl_lambda) != len(sparsifier.groups):
37
+ raise ValueError(f"Expected {len(sparsifier.groups)} lr_lambdas, but got {len(sl_lambda)}")
38
+ self.sl_lambdas = list(sl_lambda)
39
+ super().__init__(sparsifier, last_epoch, verbose)
40
+
41
+ def get_sl(self):
42
+ if not self._get_sl_called_within_step:
43
+ warnings.warn(
44
+ "To get the last sparsity level computed by the scheduler, "
45
+ "please use `get_last_sl()`.")
46
+ return [base_sl * lmbda(self.last_epoch)
47
+ for lmbda, base_sl in zip(self.sl_lambdas, self.base_sl)]
llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/base_sparsifier.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import copy
3
+ from collections import defaultdict
4
+ from typing import Any, Dict, Optional, Set, Tuple, List, Type
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn.utils import parametrize
9
+ from torch.nn.utils.parametrize import type_before_parametrizations
10
+
11
+ from .utils import (
12
+ module_contains_param,
13
+ swap_module,
14
+ FakeSparsity,
15
+ get_arg_info_from_tensor_fqn,
16
+ module_to_fqn,
17
+ )
18
+
19
+ __all__ = ["BaseSparsifier"]
20
+
21
+ SUPPORTED_MODULES = {nn.Linear}
22
+
23
+ KEYS_NOT_IN_STATE_DICT = ["module", "module_fqn", "tensor_name"]
24
+
25
+ __all__ = ["BaseSparsifier"]
26
+
27
+
28
+ # TODO update desc with new config args
29
+ class BaseSparsifier(abc.ABC):
30
+ r"""Base class for all sparsifiers.
31
+
32
+ Abstract methods that need to be implemented:
33
+
34
+ - update_mask: Function to compute a new mask for all keys in the
35
+ `groups`.
36
+
37
+ Args:
38
+ - model [nn.Module]: model to configure. The model itself is not saved
39
+ but used for the state_dict saving / loading.
40
+ - config [list]: configuration elements should be a dict map that includes
41
+ `tensor_fqn` of tensors to sparsify
42
+ - defaults [dict]: default configurations will be attached to the
43
+ configuration. Only the keys that don't exist in the `config` will
44
+ be updated.
45
+
46
+ Example::
47
+
48
+ >>> # xdoctest: +SKIP("Can't instantiate abstract class BaseSparsifier with abstract method update_mask")
49
+ >>> config = [{'tensor_fqn': 'layer1.weight', 'tensor_fqn': 'linear2.weight2', 'sparsity_level': 0.5}]
50
+ >>> defaults = {'sparsity_level': 0.7}
51
+ >>> # model.layer1.weight will have `sparsity_level` = 0.7 (getting default)
52
+ >>> sparsifier = BaseSparsifier(config, defaults)
53
+ """
54
+
55
+ def __init__(self, defaults: Optional[Dict[str, Any]] = None):
56
+ super().__init__()
57
+ self.defaults: Dict[str, Any] = defaults or {}
58
+
59
+ self.state: Dict[str, Dict] = defaultdict(dict)
60
+ self.groups: List[Dict[str, Any]] = []
61
+ self.enable_mask_update = True
62
+
63
+ def __getstate__(self) -> Dict[str, Any]:
64
+ return {
65
+ "defaults": self.defaults,
66
+ "state": self.state,
67
+ "groups": self.groups,
68
+ }
69
+
70
+ def __setstate__(self, state: Dict[str, Dict[str, Any]]) -> None:
71
+ self.__dict__.update(state)
72
+
73
+ def __repr__(self):
74
+ format_string = self.__class__.__name__ + " ("
75
+ for i, sparse_args in enumerate(self.groups):
76
+ module = sparse_args["module"]
77
+ format_string += "\n"
78
+ format_string += f"\tGroup {i}\n"
79
+ format_string += f"\t module: {module}\n"
80
+ for key in sorted(sparse_args.keys()):
81
+ if key == "module":
82
+ continue
83
+ format_string += f"\t {key}: {sparse_args[key]}\n"
84
+ format_string += ")"
85
+ return format_string
86
+
87
+ def state_dict(self) -> Dict[str, Any]:
88
+ r"""Returns the state of the optimizer as a :class:`dict`.
89
+
90
+ It contains:
91
+ * state - current state of the sparsification.
92
+ * groups - a list containing all sparsity configuration groups
93
+ with the key 'tensor_fqn' specifying the path to the sparsified tensor within a model
94
+
95
+ TODO: Need a clean way of loading the state of the "prepared" module
96
+ """
97
+
98
+ groups: List[Dict[str, Any]] = [
99
+ dict(
100
+ filter(
101
+ lambda key_value: key_value[0] not in KEYS_NOT_IN_STATE_DICT,
102
+ mg.items(),
103
+ )
104
+ )
105
+ for mg in self.groups
106
+ ]
107
+
108
+ return {
109
+ "state": self.state,
110
+ "groups": groups,
111
+ }
112
+
113
+ def load_state_dict(self, state_dict: Dict[str, Any], strict: bool = True):
114
+ groups = copy.deepcopy(state_dict["groups"])
115
+ states = state_dict["state"]
116
+ for tensor_fqn, s in states.items():
117
+ arg_info = get_arg_info_from_tensor_fqn(self.model, tensor_fqn)
118
+ module = arg_info["module"]
119
+ tensor_name = arg_info["tensor_name"]
120
+ if strict and module is None:
121
+ raise RuntimeError(f"Error loading {tensor_fqn} into the model")
122
+
123
+ found = False
124
+ for p in module.parametrizations[tensor_name]:
125
+ if isinstance(p, FakeSparsity):
126
+ found = True
127
+ break
128
+ if not found:
129
+ p = FakeSparsity(torch.ones(getattr(module, tensor_name).shape))
130
+ parametrize.register_parametrization(module, tensor_name, p)
131
+ if s.get("mask", None) is not None:
132
+ mask = s.pop("mask")
133
+ p.mask = mask
134
+
135
+ for mg in groups:
136
+ if mg["tensor_fqn"] == tensor_fqn:
137
+ mg.update(arg_info)
138
+ self.__setstate__({"state": states, "groups": groups})
139
+
140
+ def make_config_from_model(
141
+ self,
142
+ model: nn.Module,
143
+ SUPPORTED_MODULES: Set[Type] = SUPPORTED_MODULES,
144
+ ) -> None:
145
+ self.config = []
146
+ stack = [model]
147
+ while stack:
148
+ module = stack.pop()
149
+ for name, child in module.named_children():
150
+ if type(child) in SUPPORTED_MODULES:
151
+ module_fqn = module_to_fqn(model, child)
152
+ assert isinstance(module_fqn, str) # for mypy
153
+ self.config.append({"tensor_fqn": module_fqn + ".weight"})
154
+ else:
155
+ stack.append(child)
156
+
157
+ def prepare(self, model, config):
158
+ r"""Prepares a model, by adding the parametrizations.
159
+
160
+ Note::
161
+
162
+ The model is modified inplace. If you need to preserve the original
163
+ model, use copy.deepcopy.
164
+ """
165
+ self.model = model # TODO: Need to figure out how to load without this.
166
+ self.config = config
167
+
168
+ # If no config -- try getting all the supported layers
169
+ if self.config is None:
170
+ self.make_config_from_model(model)
171
+
172
+ # TODO: Remove the configuration by reference ('module')
173
+ for module_config in self.config:
174
+ assert isinstance(module_config, dict), (
175
+ "config elements should be dicts not modules i.e.:"
176
+ "[{`tensor_fqn`: `foo.bar.weight`}, {`tensor_fqn`: ... }, ...]"
177
+ )
178
+
179
+ assert isinstance(self.defaults, Dict) # for mypy
180
+ local_args = copy.deepcopy(self.defaults)
181
+ local_args.update(module_config)
182
+
183
+ tensor_fqn = local_args.get("tensor_fqn", None)
184
+ assert tensor_fqn is not None, (
185
+ "tensor_fqn is a required argument in the sparsity config which"
186
+ "replaces previous `module` and [module]`fqn` arguments"
187
+ )
188
+
189
+ # populate all information from tensor_fqn
190
+ info_from_tensor_fqn = get_arg_info_from_tensor_fqn(model, tensor_fqn)
191
+
192
+ # check that whatever was put into local_args agrees with what was obtained
193
+ # from tensor_fqn
194
+ for key in info_from_tensor_fqn.keys():
195
+ if key in local_args:
196
+ assert (
197
+ info_from_tensor_fqn[key] == local_args[key]
198
+ or (
199
+ key == "tensor_fqn"
200
+ and "." + info_from_tensor_fqn[key] == local_args[key]
201
+ )
202
+ # info_from_tensor_fqn will chop leading '.' from tensor_fqn so ignore that
203
+ ), (
204
+ f"Given both `{key}` and `tensor_fqn` in the config, it is expected them to agree!"
205
+ )
206
+ local_args.update(info_from_tensor_fqn)
207
+ self.groups.append(local_args)
208
+ self._prepare()
209
+
210
+ def _prepare(self, *args, **kwargs):
211
+ r"""Adds mask parametrization to the layer weight"""
212
+ for config in self.groups:
213
+ module = config["module"]
214
+ tensor_name = config["tensor_name"]
215
+ parametrization = config.get("parametrization", FakeSparsity)
216
+ mask = config.get("mask", torch.ones_like(getattr(module, tensor_name)))
217
+ self.state[config["tensor_fqn"]]["mask"] = mask
218
+ parametrize.register_parametrization(
219
+ module, tensor_name, parametrization(mask)
220
+ )
221
+
222
+ def squash_mask(
223
+ self,
224
+ params_to_keep: Optional[Tuple[str, ...]] = None,
225
+ params_to_keep_per_layer: Optional[Dict[str, Tuple[str, ...]]] = None,
226
+ *args,
227
+ **kwargs,
228
+ ):
229
+ r"""Squashes the sparse masks into the appropriate tensors.
230
+
231
+ If either the `params_to_keep` or `params_to_keep_per_layer` is set,
232
+ the module will have a `sparse_params` dict attached to it.
233
+
234
+ Args:
235
+ params_to_keep: List of keys to save in the module or a dict
236
+ representing the modules and keys that will have
237
+ sparsity parameters saved
238
+ params_to_keep_per_layer: Dict to specify the params that should be
239
+ saved for specific layers. The keys in the dict
240
+ should be the module fqn, while the values should
241
+ be a list of strings with the names of the variables
242
+ to save in the `sparse_params`
243
+
244
+ Examples:
245
+ >>> # xdoctest: +SKIP("locals are undefined")
246
+ >>> # Don't save any sparse params
247
+ >>> sparsifier.squash_mask()
248
+ >>> hasattr(model.submodule1, 'sparse_params')
249
+ False
250
+
251
+ >>> # Keep sparse params per layer
252
+ >>> sparsifier.squash_mask(
253
+ ... params_to_keep_per_layer={
254
+ ... 'submodule1.linear1': ('foo', 'bar'),
255
+ ... 'submodule2.linear42': ('baz',)
256
+ ... })
257
+ >>> print(model.submodule1.linear1.sparse_params)
258
+ {'foo': 42, 'bar': 24}
259
+ >>> print(model.submodule2.linear42.sparse_params)
260
+ {'baz': 0.1}
261
+
262
+ >>> # Keep sparse params for all layers
263
+ >>> sparsifier.squash_mask(params_to_keep=('foo', 'bar'))
264
+ >>> print(model.submodule1.linear1.sparse_params)
265
+ {'foo': 42, 'bar': 24}
266
+ >>> print(model.submodule2.linear42.sparse_params)
267
+ {'foo': 42, 'bar': 24}
268
+
269
+ >>> # Keep some sparse params for all layers, and specific ones for
270
+ >>> # some other layers
271
+ >>> sparsifier.squash_mask(
272
+ ... params_to_keep=('foo', 'bar'),
273
+ ... params_to_keep_per_layer={
274
+ ... 'submodule2.linear42': ('baz',)
275
+ ... })
276
+ >>> print(model.submodule1.linear1.sparse_params)
277
+ {'foo': 42, 'bar': 24}
278
+ >>> print(model.submodule2.linear42.sparse_params)
279
+ {'foo': 42, 'bar': 24, 'baz': 0.1}
280
+ """
281
+ for config in self.groups:
282
+ module = config["module"]
283
+ tensor_name = config["tensor_name"]
284
+ parametrize.remove_parametrizations(
285
+ module, tensor_name, leave_parametrized=True
286
+ )
287
+ sparse_params = {}
288
+ if params_to_keep is not None:
289
+ global_params = {k: config[k] for k in params_to_keep}
290
+ sparse_params.update(global_params)
291
+ if params_to_keep_per_layer is not None:
292
+ params = params_to_keep_per_layer.get(config["module_fqn"], None)
293
+ if params is not None:
294
+ per_layer_params = {k: config[k] for k in params}
295
+ sparse_params.update(per_layer_params)
296
+ if sparse_params:
297
+ # TODO handle multiple tensor being quantized on a single module, where to store sparse_params?
298
+ module.sparse_params = sparse_params
299
+
300
+ def convert(
301
+ self,
302
+ module: nn.Module,
303
+ mapping: Optional[Dict[Type[nn.Module], Type[nn.Module]]] = None,
304
+ inplace: bool = False,
305
+ parameterization: Type[nn.Module] = FakeSparsity,
306
+ ):
307
+ r"""Converts submodules in input module to a different module according to `mapping`
308
+ by calling `from_dense` method on the target module class
309
+ Args:
310
+ module: input module
311
+ mapping: a dictionary that maps from source module type to target
312
+ module type, can be overwritten to allow swapping user defined
313
+ Modules
314
+ inplace: carry out model transformations in-place, the original module
315
+ is mutated
316
+ """
317
+ if mapping is None:
318
+ raise NotImplementedError("Need to auto generate mapping ")
319
+ if not inplace:
320
+ module = copy.deepcopy(module)
321
+
322
+ reassign = {}
323
+ for name, mod in module.named_children():
324
+ # leaf node
325
+ if (
326
+ module_contains_param(mod, parameterization)
327
+ and type_before_parametrizations(mod) in mapping
328
+ ):
329
+ reassign[name] = swap_module(mod, mapping)
330
+ else:
331
+ # recurse
332
+ reassign[name] = self.convert(
333
+ mod,
334
+ mapping=mapping,
335
+ inplace=True,
336
+ parameterization=parameterization,
337
+ )
338
+
339
+ for key, value in reassign.items():
340
+ module._modules[key] = value
341
+
342
+ return module
343
+
344
+ def step(self, use_path: bool = True) -> None:
345
+ if not self.enable_mask_update:
346
+ return
347
+ with torch.no_grad():
348
+ for config in self.groups:
349
+ self.update_mask(**config)
350
+
351
+ @abc.abstractmethod
352
+ def update_mask(self, module: nn.Module, tensor_name: str, **kwargs):
353
+ pass
llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/nearly_diagonal_sparsifier.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from . import base_sparsifier
4
+
5
+
6
+ class NearlyDiagonalSparsifier(base_sparsifier.BaseSparsifier):
7
+ r"""Nearly Diagonal Sparsifier
8
+
9
+ This sparsifier creates a nearly diagonal mask to be applied to the weight matrix.
10
+ Nearly Diagonal Matrix is a matrix that contains non-zero elements near the diagonal and the rest are zero.
11
+ An example of a nearly diagonal matrix with degree (or nearliness) 3 and 5 are follows respectively.
12
+ 1 1 0 0 1 1 1 0
13
+ 1 1 1 0 1 1 1 1
14
+ 0 1 1 1 1 1 1 1
15
+ 0 0 1 1 0 1 1 1
16
+ Note that a nearly diagonal matrix with degree 1 is just a matrix with main diagonal populated
17
+
18
+ This sparsifier is controlled by one variable:
19
+ 1. `nearliness` defines the number of non-zero diagonal lines that are closest to the main diagonal.
20
+ Currently - supports only odd number
21
+
22
+ Note:
23
+ This can be accelerated (vectorized) once the Spdiagonal feature (PR: #78439) is landed or the banded matrix
24
+ feature is landed: https://stackoverflow.com/questions/52463972/generating-banded-matrices-using-numpy
25
+
26
+ Args:
27
+ nearliness: The degree of nearliness (default = 1)
28
+
29
+ """
30
+ def __init__(self, nearliness: int = 1):
31
+ defaults = {'nearliness': nearliness}
32
+ super().__init__(defaults=defaults)
33
+
34
+ def update_mask(self, module, tensor_name, nearliness,
35
+ **kwargs):
36
+ mask = getattr(module.parametrizations, tensor_name)[0].mask
37
+ mask.data = torch.zeros_like(mask)
38
+ if nearliness <= 0:
39
+ return
40
+
41
+ tensor = getattr(module, tensor_name)
42
+ height, width = tensor.shape
43
+
44
+ if nearliness % 2 == 0:
45
+ raise ValueError("nearliness can only be an odd number")
46
+ dist_to_diagonal = nearliness // 2
47
+ # check
48
+ if dist_to_diagonal >= min(height, width):
49
+ raise ValueError("nearliness cannot be larger than the dimensions of tensor.")
50
+
51
+ for row in range(0, height):
52
+ # Bounds of entries that needs to be set to 1
53
+ low = max(0, row - dist_to_diagonal)
54
+ high = min(width, row + dist_to_diagonal + 1)
55
+ mask[row, low:high].fill_(1)
llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/utils.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional, Type
2
+ from torch.nn.utils.parametrize import type_before_parametrizations, is_parametrized
3
+ from itertools import chain
4
+
5
+ from torch import nn
6
+
7
+ __all__ = [
8
+ "module_contains_param",
9
+ "swap_module",
10
+ "module_to_fqn",
11
+ "fqn_to_module",
12
+ "get_arg_info_from_tensor_fqn",
13
+ "FakeSparsity",
14
+ ]
15
+
16
+
17
+ def module_contains_param(module: nn.Module, parametrization: Type[nn.Module]) -> bool:
18
+ if is_parametrized(module):
19
+ # see if any of the module tensors have a parametriztion attached that matches the one passed in
20
+ return any(
21
+ any(isinstance(param, parametrization) for param in param_list)
22
+ for key, param_list in module.parametrizations.items() # type: ignore[union-attr,operator]
23
+ )
24
+ return False
25
+
26
+
27
+ def swap_module(
28
+ mod: nn.Module, mapping: Dict[Type[nn.Module], Type[nn.Module]]
29
+ ) -> nn.Module:
30
+ r"""Swaps the module using from_dense according to the mapping passed in.
31
+ Args:
32
+ mod: input module
33
+ mapping: a dictionary that maps from nn module to sparse nn module
34
+ Return:
35
+ The corresponding sparse module of `mod` according to mapping, created using from_dense
36
+ """
37
+ if type_before_parametrizations(mod) in mapping:
38
+ sparse_mod = mapping[type_before_parametrizations(mod)]
39
+
40
+ # TODO Fix this typing, as Type[Module] has no attribute "from_dense"
41
+ new_mod = sparse_mod.from_dense(mod) # type: ignore[attr-defined]
42
+
43
+ # Preserve module's pre forward hooks. They'll be called on quantized input
44
+ for pre_hook_fn in mod._forward_pre_hooks.values():
45
+ new_mod.register_forward_pre_hook(pre_hook_fn)
46
+ # Preserve module's post forward hooks except _observer_forward_hook
47
+ # After convert they'll work with quantized output
48
+ for hook_fn in mod._forward_hooks.values():
49
+ new_mod.register_forward_hook(hook_fn)
50
+
51
+ # respect device affinity when swapping modules
52
+ devices = {p.device for p in chain(mod.parameters(), mod.buffers())}
53
+ assert len(devices) <= 1, (
54
+ f"swap_module only works with cpu or single-device CUDA modules, but got devices {devices}"
55
+ )
56
+ device = next(iter(devices)) if len(devices) > 0 else None
57
+ if device:
58
+ new_mod.to(device)
59
+
60
+ return new_mod
61
+
62
+ else:
63
+ return mod
64
+
65
+
66
+ def module_to_fqn(
67
+ model: nn.Module, module: nn.Module, prefix: str = ""
68
+ ) -> Optional[str]:
69
+ """
70
+ Returns the fqn for a module or None if module not a descendent of model.
71
+ """
72
+ if module is model:
73
+ return ""
74
+ for name, child in model.named_children():
75
+ fqn = module_to_fqn(child, module, ".")
76
+ if isinstance(fqn, str):
77
+ return prefix + name + fqn
78
+ return None
79
+
80
+
81
+ def fqn_to_module(model: Optional[nn.Module], path: str) -> Optional[nn.Module]:
82
+ """
83
+ Given an fqn, returns the corresponding module or tensor or None if the fqn given by `path`
84
+ doesn't correspond to anything. Similar to model.get_submodule(path) but works for tensors.
85
+ """
86
+ if path != "":
87
+ for name in path.split("."):
88
+ model = getattr(model, name, None)
89
+ return model
90
+
91
+
92
+ def get_arg_info_from_tensor_fqn(model: nn.Module, tensor_fqn: str) -> Dict[str, Any]:
93
+ """
94
+ Uses tensor_fqn to obtain a dict containing module_fqn, module and tensor_name
95
+ """
96
+ # string manip to split tensor_fqn into module_fqn and tensor_name
97
+ # if tensor_fqn is 'weight' then module_fqn and tensor_name are '' and 'weight'
98
+ # if tensor_fqn is 'linear.weight' then module_fqn and tensor_name are 'linear' and 'weight'
99
+ tensor_name = tensor_fqn.split(".")[-1]
100
+ module_fqn = tensor_fqn[: -len(tensor_name) - ("." in tensor_fqn)]
101
+
102
+ module = fqn_to_module(model, module_fqn)
103
+
104
+ return {
105
+ "module_fqn": module_fqn,
106
+ "module": module,
107
+ "tensor_name": tensor_name,
108
+ "tensor_fqn": tensor_fqn,
109
+ }
110
+
111
+
112
+ # Parametrizations
113
+ class FakeSparsity(nn.Module):
114
+ r"""Parametrization for the weights. Should be attached to the 'weight' or
115
+ any other parameter that requires a mask applied to it.
116
+
117
+ Note::
118
+
119
+ Once the mask is passed, the variable should not change the id. The
120
+ contents of the mask can change, but the mask reference itself should
121
+ not.
122
+ """
123
+
124
+ def __init__(self, mask):
125
+ super().__init__()
126
+ self.register_buffer("mask", mask)
127
+
128
+ def forward(self, x):
129
+ assert self.mask.shape == x.shape
130
+ return self.mask * x
131
+
132
+ def state_dict(self, *args, **kwargs):
133
+ # We don't want to let the parametrizations to save the mask.
134
+ # That way we make sure that the linear module doesn't store the masks
135
+ # alongside their parametrizations.
136
+ return {}
llava_next/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/weight_norm_sparsifier.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import reduce
2
+ from typing import Callable, Optional, Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+ from .base_sparsifier import BaseSparsifier
8
+
9
+ __all__ = ["WeightNormSparsifier"]
10
+
11
+ def _flat_idx_to_2d(idx, shape):
12
+ rows = idx // shape[1]
13
+ cols = idx % shape[1]
14
+ return rows, cols
15
+
16
+ class WeightNormSparsifier(BaseSparsifier):
17
+ r"""Weight-Norm Sparsifier
18
+
19
+ This sparsifier computes the norm of every sparse block and "zeroes-out" the
20
+ ones with the lowest norm. The level of sparsity defines how many of the
21
+ blocks is removed.
22
+
23
+ This sparsifier is controlled by three variables:
24
+ 1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out
25
+ 2. `sparse_block_shape` defines the shape of the sparse blocks. Note that
26
+ the sparse blocks originate at the zero-index of the tensor.
27
+ 3. `zeros_per_block` is the number of zeros that we are expecting in each
28
+ sparse block. By default we assume that all elements within a block are
29
+ zeroed-out. However, setting this variable sets the target number of
30
+ zeros per block. The zeros within each block are chosen as the *smallest
31
+ absolute values*.
32
+
33
+ Args:
34
+
35
+ sparsity_level: The target level of sparsity
36
+ sparse_block_shape: The shape of a sparse block (see note below)
37
+ zeros_per_block: Number of zeros in a sparse block
38
+ norm: Norm to use. Could be either `int` or a callable.
39
+ If `int`, only L1 and L2 are implemented.
40
+
41
+ Note::
42
+ The `sparse_block_shape` is tuple representing (block_ROWS, block_COLS),
43
+ irrespective of what the rows / cols mean in the data tensor. That means,
44
+ if you were to sparsify a weight tensor in the nn.Linear, which has a
45
+ weight shape `(Cout, Cin)`, the `block_ROWS` would refer to the output
46
+ channels, while the `block_COLS` would refer to the input channels.
47
+
48
+ Note::
49
+ All arguments to the WeightNormSparsifier constructor are "default"
50
+ arguments and could be overriden by the configuration provided in the
51
+ `prepare` step.
52
+ """
53
+ def __init__(self,
54
+ sparsity_level: float = 0.5,
55
+ sparse_block_shape: Tuple[int, int] = (1, 4),
56
+ zeros_per_block: Optional[int] = None,
57
+ norm: Optional[Union[Callable, int]] = None):
58
+ if zeros_per_block is None:
59
+ zeros_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
60
+ defaults = {
61
+ "sparsity_level": sparsity_level,
62
+ "sparse_block_shape": sparse_block_shape,
63
+ "zeros_per_block": zeros_per_block,
64
+ }
65
+ if norm is None:
66
+ norm = 2
67
+ if callable(norm):
68
+ self.norm_fn = norm
69
+ elif norm == 1:
70
+ self.norm_fn = lambda T: T.abs()
71
+ elif norm == 2:
72
+ self.norm_fn = lambda T: T * T
73
+ else:
74
+ raise NotImplementedError(f"L-{norm} is not yet implemented.")
75
+ super().__init__(defaults=defaults)
76
+
77
+ def _scatter_fold_block_mask(self, output_shape, dim, indices, block_shape,
78
+ mask=None, input_shape=None, device=None):
79
+ r"""Creates patches of size `block_shape` after scattering the indices."""
80
+ if mask is None:
81
+ assert input_shape is not None
82
+ mask = torch.ones(input_shape, device=device)
83
+ mask.scatter_(dim=dim, index=indices, value=0)
84
+ mask.data = F.fold(mask, output_size=output_shape, kernel_size=block_shape, stride=block_shape)
85
+ return mask
86
+
87
+ def _make_tensor_mask(self, data, input_shape, sparsity_level, sparse_block_shape, mask=None):
88
+ r"""Creates a tensor-level mask.
89
+
90
+ Tensor-level mask is described as a mask, where the granularity of sparsification of the
91
+ smallest patch is the sparse_block_shape. That means, that for a given mask and a
92
+ sparse_block_shape, the smallest "patch" of zeros/ones could be the sparse_block_shape.
93
+
94
+ In this context, `sparsity_level` describes the fraction of sparse patches.
95
+ """
96
+ h, w = data.shape[-2:]
97
+ block_h, block_w = sparse_block_shape
98
+ dh = (block_h - h % block_h) % block_h
99
+ dw = (block_w - w % block_w) % block_w
100
+
101
+ if mask is None:
102
+ mask = torch.ones(h + dh, w + dw, device=data.device)
103
+
104
+ if sparsity_level >= 1.0:
105
+ mask.data = torch.zeros_like(mask)
106
+ return mask
107
+ elif sparsity_level <= 0.0:
108
+ mask.data = torch.ones_like(mask)
109
+ return mask
110
+
111
+ values_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
112
+ if values_per_block > 1:
113
+ # Reduce the data
114
+ data = F.avg_pool2d(
115
+ data[None, None, :], kernel_size=sparse_block_shape, stride=sparse_block_shape, ceil_mode=True
116
+ )
117
+ data = data.flatten()
118
+ num_blocks = len(data)
119
+
120
+ data = data.repeat(1, values_per_block, 1)
121
+
122
+ threshold_idx = int(round(sparsity_level * num_blocks))
123
+ threshold_idx = max(0, min(num_blocks - 1, threshold_idx)) # Sanity check
124
+ _, sorted_idx = torch.topk(data, k=threshold_idx, dim=2, largest=False)
125
+
126
+ # Temp reshape for mask
127
+ mask_reshape = mask.reshape(data.shape) # data might be reshaped
128
+ self._scatter_fold_block_mask(
129
+ dim=2, output_shape=(h + dh, w + dw),
130
+ indices=sorted_idx, block_shape=sparse_block_shape, mask=mask_reshape
131
+ )
132
+ mask.data = mask_reshape.squeeze().reshape(mask.shape)[:h, :w].contiguous()
133
+ return mask
134
+
135
+ def _make_block_mask(self, data, sparse_block_shape, zeros_per_block, mask=None):
136
+ r"""Creates a block-level mask.
137
+
138
+ Block-level mask is described as a mask, where the granularity of sparsification of the
139
+ largest patch is the sparse_block_shape. That means that for a given mask and a
140
+ sparse_block_shape, the sparsity is computed only within a patch of a size sparse_block_shape.
141
+
142
+ In this context the `zeros_per_block` describes the number of zeroed-out elements within a patch.
143
+ """
144
+ h, w = data.shape[-2:]
145
+ block_h, block_w = sparse_block_shape
146
+ dh = (block_h - h % block_h) % block_h
147
+ dw = (block_w - w % block_w) % block_w
148
+ values_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
149
+
150
+ if mask is None:
151
+ mask = torch.ones((h + dh, w + dw), device=data.device)
152
+
153
+ if values_per_block == zeros_per_block:
154
+ # Everything should be sparsified
155
+ mask.data = torch.zeros_like(mask)
156
+ return mask
157
+
158
+ # create a new padded tensor like data (to match the block_shape)
159
+ padded_data = torch.ones(h + dh, w + dw, dtype=data.dtype, device=data.device)
160
+ padded_data.fill_(torch.nan)
161
+ padded_data[:h, :w] = data
162
+ unfolded_data = F.unfold(padded_data[None, None, :], kernel_size=sparse_block_shape, stride=sparse_block_shape)
163
+
164
+ # Temp reshape for mask
165
+ mask_reshape = mask.reshape(unfolded_data.shape)
166
+ _, sorted_idx = torch.topk(unfolded_data, k=zeros_per_block, dim=1, largest=False)
167
+
168
+ self._scatter_fold_block_mask(
169
+ dim=1, indices=sorted_idx, output_shape=padded_data.shape, block_shape=sparse_block_shape, mask=mask_reshape
170
+ )
171
+
172
+ mask.data = mask_reshape.squeeze().reshape(mask.shape).contiguous()
173
+ return mask
174
+
175
+ def update_mask(self, module, tensor_name, sparsity_level, sparse_block_shape,
176
+ zeros_per_block, **kwargs):
177
+ values_per_block = reduce((lambda x, y: x * y), sparse_block_shape)
178
+ if zeros_per_block > values_per_block:
179
+ raise ValueError(
180
+ "Number of zeros per block cannot be more than the total number of elements in that block."
181
+ )
182
+ if zeros_per_block < 0:
183
+ raise ValueError("Number of zeros per block should be positive.")
184
+
185
+ mask = getattr(module.parametrizations, tensor_name)[0].mask
186
+ if sparsity_level <= 0 or zeros_per_block == 0:
187
+ mask.data = torch.ones_like(mask)
188
+ elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block):
189
+ mask.data = torch.zeros_like(mask)
190
+ else:
191
+ ww = self.norm_fn(getattr(module, tensor_name))
192
+ tensor_mask = self._make_tensor_mask(
193
+ data=ww, input_shape=ww.shape, sparsity_level=sparsity_level, sparse_block_shape=sparse_block_shape
194
+ )
195
+ if values_per_block != zeros_per_block:
196
+ block_mask = self._make_block_mask(data=ww, sparse_block_shape=sparse_block_shape,
197
+ zeros_per_block=zeros_per_block)
198
+ tensor_mask = torch.logical_or(tensor_mask, block_mask)
199
+ mask.data = tensor_mask
vlmpy310/lib/python3.10/site-packages/skimage/_shared/_dependency_checks.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .version_requirements import is_installed
2
+ import sys
3
+ import platform
4
+
5
+ has_mpl = is_installed("matplotlib", ">=3.3")
6
+
7
+ is_wasm = (sys.platform == "emscripten") or (platform.machine() in ["wasm32", "wasm64"])
vlmpy310/lib/python3.10/site-packages/skimage/_shared/_geometry.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['polygon_clip', 'polygon_area']
2
+
3
+ import numpy as np
4
+
5
+ from .version_requirements import require
6
+
7
+
8
+ @require("matplotlib", ">=3.3")
9
+ def polygon_clip(rp, cp, r0, c0, r1, c1):
10
+ """Clip a polygon to the given bounding box.
11
+
12
+ Parameters
13
+ ----------
14
+ rp, cp : (K,) ndarray of double
15
+ Row and column coordinates of the polygon.
16
+ (r0, c0), (r1, c1) : double
17
+ Top-left and bottom-right coordinates of the bounding box.
18
+
19
+ Returns
20
+ -------
21
+ r_clipped, c_clipped : (L,) ndarray of double
22
+ Coordinates of clipped polygon.
23
+
24
+ Notes
25
+ -----
26
+ This makes use of Sutherland-Hodgman clipping as implemented in
27
+ AGG 2.4 and exposed in Matplotlib.
28
+
29
+ """
30
+ from matplotlib import path, transforms
31
+
32
+ poly = path.Path(np.vstack((rp, cp)).T, closed=True)
33
+ clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
34
+ poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
35
+
36
+ return poly_clipped[:, 0], poly_clipped[:, 1]
37
+
38
+
39
+ def polygon_area(pr, pc):
40
+ """Compute the area of a polygon.
41
+
42
+ Parameters
43
+ ----------
44
+ pr, pc : (K,) array of float
45
+ Polygon row and column coordinates.
46
+
47
+ Returns
48
+ -------
49
+ a : float
50
+ Area of the polygon.
51
+ """
52
+ pr = np.asarray(pr)
53
+ pc = np.asarray(pc)
54
+ return 0.5 * np.abs(np.sum((pc[:-1] * pr[1:]) - (pc[1:] * pr[:-1])))
vlmpy310/lib/python3.10/site-packages/skimage/_shared/coord.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.spatial import cKDTree, distance
3
+
4
+
5
+ def _ensure_spacing(coord, spacing, p_norm, max_out):
6
+ """Returns a subset of coord where a minimum spacing is guaranteed.
7
+
8
+ Parameters
9
+ ----------
10
+ coord : ndarray
11
+ The coordinates of the considered points.
12
+ spacing : float
13
+ the maximum allowed spacing between the points.
14
+ p_norm : float
15
+ Which Minkowski p-norm to use. Should be in the range [1, inf].
16
+ A finite large p may cause a ValueError if overflow can occur.
17
+ ``inf`` corresponds to the Chebyshev distance and 2 to the
18
+ Euclidean distance.
19
+ max_out: int
20
+ If not None, at most the first ``max_out`` candidates are
21
+ returned.
22
+
23
+ Returns
24
+ -------
25
+ output : ndarray
26
+ A subset of coord where a minimum spacing is guaranteed.
27
+
28
+ """
29
+
30
+ # Use KDtree to find the peaks that are too close to each other
31
+ tree = cKDTree(coord)
32
+
33
+ indices = tree.query_ball_point(coord, r=spacing, p=p_norm)
34
+ rejected_peaks_indices = set()
35
+ naccepted = 0
36
+ for idx, candidates in enumerate(indices):
37
+ if idx not in rejected_peaks_indices:
38
+ # keep current point and the points at exactly spacing from it
39
+ candidates.remove(idx)
40
+ dist = distance.cdist(
41
+ [coord[idx]], coord[candidates], "minkowski", p=p_norm
42
+ ).reshape(-1)
43
+ candidates = [c for c, d in zip(candidates, dist) if d < spacing]
44
+
45
+ # candidates.remove(keep)
46
+ rejected_peaks_indices.update(candidates)
47
+ naccepted += 1
48
+ if max_out is not None and naccepted >= max_out:
49
+ break
50
+
51
+ # Remove the peaks that are too close to each other
52
+ output = np.delete(coord, tuple(rejected_peaks_indices), axis=0)
53
+ if max_out is not None:
54
+ output = output[:max_out]
55
+
56
+ return output
57
+
58
+
59
+ def ensure_spacing(
60
+ coords,
61
+ spacing=1,
62
+ p_norm=np.inf,
63
+ min_split_size=50,
64
+ max_out=None,
65
+ *,
66
+ max_split_size=2000,
67
+ ):
68
+ """Returns a subset of coord where a minimum spacing is guaranteed.
69
+
70
+ Parameters
71
+ ----------
72
+ coords : array_like
73
+ The coordinates of the considered points.
74
+ spacing : float
75
+ the maximum allowed spacing between the points.
76
+ p_norm : float
77
+ Which Minkowski p-norm to use. Should be in the range [1, inf].
78
+ A finite large p may cause a ValueError if overflow can occur.
79
+ ``inf`` corresponds to the Chebyshev distance and 2 to the
80
+ Euclidean distance.
81
+ min_split_size : int
82
+ Minimum split size used to process ``coords`` by batch to save
83
+ memory. If None, the memory saving strategy is not applied.
84
+ max_out : int
85
+ If not None, only the first ``max_out`` candidates are returned.
86
+ max_split_size : int
87
+ Maximum split size used to process ``coords`` by batch to save
88
+ memory. This number was decided by profiling with a large number
89
+ of points. Too small a number results in too much looping in
90
+ Python instead of C, slowing down the process, while too large
91
+ a number results in large memory allocations, slowdowns, and,
92
+ potentially, in the process being killed -- see gh-6010. See
93
+ benchmark results `here
94
+ <https://github.com/scikit-image/scikit-image/pull/6035#discussion_r751518691>`_.
95
+
96
+ Returns
97
+ -------
98
+ output : array_like
99
+ A subset of coord where a minimum spacing is guaranteed.
100
+
101
+ """
102
+ output = coords
103
+ if len(coords):
104
+ coords = np.atleast_2d(coords)
105
+ if min_split_size is None:
106
+ batch_list = [coords]
107
+ else:
108
+ coord_count = len(coords)
109
+ split_idx = [min_split_size]
110
+ split_size = min_split_size
111
+ while coord_count - split_idx[-1] > max_split_size:
112
+ split_size *= 2
113
+ split_idx.append(split_idx[-1] + min(split_size, max_split_size))
114
+ batch_list = np.array_split(coords, split_idx)
115
+
116
+ output = np.zeros((0, coords.shape[1]), dtype=coords.dtype)
117
+ for batch in batch_list:
118
+ output = _ensure_spacing(
119
+ np.vstack([output, batch]), spacing, p_norm, max_out
120
+ )
121
+ if max_out is not None and len(output) >= max_out:
122
+ break
123
+
124
+ return output