compressed-tensors 0.3.1__py3-none-any.whl → 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,10 +16,5 @@
16
16
 
17
17
  from .base import ModelCompressor
18
18
  from .dense import DenseCompressor
19
- from .helpers import (
20
- infer_compressor_from_model_config,
21
- load_compressed,
22
- save_compressed,
23
- save_compressed_model,
24
- )
19
+ from .helpers import load_compressed, save_compressed, save_compressed_model
25
20
  from .sparse_bitmask import BitmaskCompressor, BitmaskTensor
@@ -22,6 +22,7 @@ from compressed_tensors.utils import get_safetensors_folder
22
22
  from torch import Tensor
23
23
  from torch.nn import Module, Parameter
24
24
  from tqdm import tqdm
25
+ from transformers import AutoConfig
25
26
 
26
27
 
27
28
  __all__ = ["ModelCompressor"]
@@ -34,6 +35,29 @@ class ModelCompressor(RegistryMixin):
34
35
  :param config: config specifying compression parameters
35
36
  """
36
37
 
38
+ @classmethod
39
+ def from_pretrained(
40
+ cls, pretrained_model_name_or_path: str
41
+ ) -> Optional["ModelCompressor"]:
42
+ """
43
+ Given a path to a model config, extract a sparsity config if it exists and
44
+ return the associated ModelCompressor
45
+
46
+ :param pretrained_model_name_or_path: path to model config on disk or HF hub
47
+ :return: matching compressor if config contains a sparsity config
48
+ """
49
+ config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
50
+ sparsity_config = getattr(config, SPARSITY_CONFIG_NAME, None)
51
+ if sparsity_config is None:
52
+ return None
53
+
54
+ format = sparsity_config.get("format")
55
+ sparsity_config = CompressionConfig.load_from_registry(
56
+ format, **sparsity_config
57
+ )
58
+ compressor = cls.load_from_registry(format, config=sparsity_config)
59
+ return compressor
60
+
37
61
  def __init__(self, config: Optional[CompressionConfig] = None):
38
62
  self.config = config
39
63
 
@@ -47,7 +71,7 @@ class ModelCompressor(RegistryMixin):
47
71
  raise NotImplementedError()
48
72
 
49
73
  def decompress(
50
- self, path_to_model_or_tensors: str
74
+ self, path_to_model_or_tensors: str, device: str = "cpu"
51
75
  ) -> Generator[Tuple[str, Tensor], None, None]:
52
76
  """
53
77
  Reads a compressed state dict located at path_to_model_or_tensors
@@ -29,6 +29,6 @@ class DenseCompressor(ModelCompressor):
29
29
  return model_state
30
30
 
31
31
  def decompress(
32
- self, path_to_model_or_tensors: str, device: str
32
+ self, path_to_model_or_tensors: str, device: str = "cpu"
33
33
  ) -> Generator[Tuple[str, Tensor], None, None]:
34
34
  return iter([])
@@ -16,45 +16,21 @@ from pathlib import Path
16
16
  from typing import Dict, Generator, Optional, Tuple, Union
17
17
 
18
18
  import torch
19
- from compressed_tensors.base import SPARSITY_CONFIG_NAME
20
19
  from compressed_tensors.compressors import ModelCompressor
21
20
  from compressed_tensors.config import CompressionConfig, CompressionFormat
22
21
  from compressed_tensors.utils.safetensors_load import get_weight_mappings
23
22
  from safetensors import safe_open
24
23
  from safetensors.torch import save_file
25
24
  from torch import Tensor
26
- from transformers import AutoConfig
27
25
 
28
26
 
29
27
  __all__ = [
30
- "infer_compressor_from_model_config",
31
28
  "load_compressed",
32
29
  "save_compressed",
33
30
  "save_compressed_model",
34
31
  ]
35
32
 
36
33
 
37
- def infer_compressor_from_model_config(
38
- pretrained_model_name_or_path: str,
39
- ) -> Optional[ModelCompressor]:
40
- """
41
- Given a path to a model config, extract a sparsity config if it exists and return
42
- the associated ModelCompressor
43
-
44
- :param pretrained_model_name_or_path: path to model config on disk or HF hub
45
- :return: matching compressor if config contains a sparsity config
46
- """
47
- config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
48
- sparsity_config = getattr(config, SPARSITY_CONFIG_NAME, None)
49
- if sparsity_config is None:
50
- return None
51
-
52
- format = sparsity_config.get("format")
53
- sparsity_config = CompressionConfig.load_from_registry(format, **sparsity_config)
54
- compressor = ModelCompressor.load_from_registry(format, config=sparsity_config)
55
- return compressor
56
-
57
-
58
34
  def save_compressed(
59
35
  tensors: Dict[str, Tensor],
60
36
  save_path: Union[str, Path],
@@ -75,8 +75,9 @@ class BitmaskCompressor(ModelCompressor):
75
75
  self, path_to_model_or_tensors: str, device: str = "cpu"
76
76
  ) -> Generator[Tuple[str, Tensor], None, None]:
77
77
  """
78
- Reads a bitmask compressed state dict located at path_to_model_or_tensors
79
- and returns a generator for sequentially decompressing back to a dense state dict
78
+ Reads a bitmask compressed state dict located
79
+ at path_to_model_or_tensors and returns a generator
80
+ for sequentially decompressing back to a dense state dict
80
81
 
81
82
  :param model_path: path to compressed safetensors model (directory with
82
83
  one or more safetensors files) or compressed tensors file
@@ -111,7 +111,7 @@ def wrap_module_forward_quantized(module: Module, scheme: QuantizationScheme):
111
111
 
112
112
 
113
113
  def _maybe_calibrate_or_quantize(
114
- module: Module, value: Module, base_name: str, args: "QuantizationArgs"
114
+ module: Module, value: torch.Tensor, base_name: str, args: "QuantizationArgs"
115
115
  ) -> torch.Tensor:
116
116
  # only run quantized for the included stages
117
117
  if module.quantization_status not in {
@@ -120,17 +120,23 @@ def _maybe_calibrate_or_quantize(
120
120
  }:
121
121
  return value
122
122
 
123
- device = next(module.parameters()).device
124
- scale = getattr(module, f"{base_name}_scale")
125
- zero_point = getattr(module, f"{base_name}_zero_point")
126
-
127
- if module.quantization_status == QuantizationStatus.CALIBRATION:
128
- # get observer and get new quant params from observation
123
+ if args.dynamic:
124
+ # dynamic quantization - get scale and zero point directly from observer
129
125
  observer = getattr(module, f"{base_name}_observer")
130
- updated_scale, updated_zero_point = observer(value)
131
-
132
- # update scale and zero point
133
- scale.data = updated_scale.to(device)
134
- zero_point.data = updated_zero_point.to(device)
126
+ scale, zero_point = observer(value)
127
+ else:
128
+ # static quantization - get previous scale and zero point from layer
129
+ scale = getattr(module, f"{base_name}_scale")
130
+ zero_point = getattr(module, f"{base_name}_zero_point")
131
+
132
+ if module.quantization_status == QuantizationStatus.CALIBRATION:
133
+ # calibration mode - get new quant params from observer
134
+ observer = getattr(module, f"{base_name}_observer")
135
+ updated_scale, updated_zero_point = observer(value)
136
+
137
+ # update scale and zero point
138
+ device = next(module.parameters()).device
139
+ scale.data = updated_scale.to(device)
140
+ zero_point.data = updated_zero_point.to(device)
135
141
 
136
142
  return fake_quantize(value, scale, zero_point, args)
@@ -30,17 +30,17 @@ def freeze_module_quantization(module: Module):
30
30
 
31
31
  :param module: module to freeze quantization for
32
32
  """
33
- if not getattr(module, "quantization_scheme", None):
33
+ scheme = getattr(module, "quantization_scheme", None)
34
+ if not scheme:
34
35
  # no quantization scheme nothing to do
35
36
  return
36
37
 
37
- # delete observers from module
38
- observer_names = []
39
- for submodule_name, _ in module.named_modules():
40
- if "." not in submodule_name and submodule_name.endswith("_observer"):
41
- # delete any observers that belong directly to this module
42
- observer_names.append(submodule_name)
43
- for observer_name in observer_names:
44
- delattr(module, observer_name)
38
+ # delete observers from module if not dynamic
39
+ if scheme.input_activations and not scheme.input_activations.dynamic:
40
+ delattr(module, "input_observer")
41
+ if scheme.weights and not scheme.weights.dynamic:
42
+ delattr(module, "weight_observer")
43
+ if scheme.output_activations and not scheme.output_activations.dynamic:
44
+ delattr(module, "output_observer")
45
45
 
46
46
  module.quantization_status = QuantizationStatus.FROZEN
@@ -80,6 +80,13 @@ def initialize_module_for_quantization(
80
80
  def _initialize_scale_zero_point_observer(
81
81
  module: Module, base_name: str, quantization_args: QuantizationArgs
82
82
  ):
83
+ # initialize observer module and attach as submodule
84
+ observer = quantization_args.get_observer()
85
+ module.register_module(f"{base_name}_observer", observer)
86
+
87
+ if quantization_args.dynamic:
88
+ return # no need to register a scale and zero point for a dynamic observer
89
+
83
90
  device = next(module.parameters()).device
84
91
 
85
92
  # initializes empty scale and zero point parameters for the module
@@ -90,7 +97,3 @@ def _initialize_scale_zero_point_observer(
90
97
  torch.empty(0, device=device, dtype=int), requires_grad=False
91
98
  )
92
99
  module.register_parameter(f"{base_name}_zero_point", init_zero_point)
93
-
94
- # initialize observer module and attach as submodule
95
- observer = quantization_args.get_observer()
96
- module.register_module(f"{base_name}_observer", observer)
@@ -23,10 +23,10 @@ from torch import FloatTensor, IntTensor, Tensor
23
23
  __all__ = ["MemorylessObserver"]
24
24
 
25
25
 
26
- @Observer.register("memoryless")
26
+ @Observer.register("memoryless", alias=["dynamic"])
27
27
  class MemorylessObserver(Observer):
28
28
  """
29
- Implements a dynamic quantization observer that sets the scale and
29
+ Implements a quantization observer that sets the scale and
30
30
  zero point based on the latest observed value without tracking state
31
31
  """
32
32
 
@@ -53,6 +53,11 @@ class QuantizationArgs(BaseModel):
53
53
  :param group_size: group length to use for the group strategy
54
54
  :param block_structure: 2d block structure to use for the block strategy, must be
55
55
  of the format "2x4", "8x16", etc.
56
+ :param dynamic: set True to perform dynamic quantization - values will not be
57
+ calibrated during calibration phase, instead during inference new quantization
58
+ ranges will be observed with every sample. Defaults to False for static
59
+ quantization. Note that enabling dynamic quantization will change the default
60
+ observer to a memoryless one
56
61
  """
57
62
 
58
63
  num_bits: int = 8
@@ -61,6 +66,7 @@ class QuantizationArgs(BaseModel):
61
66
  strategy: QuantizationStrategy = QuantizationStrategy.TENSOR
62
67
  group_size: Optional[int] = None
63
68
  block_structure: Optional[str] = None
69
+ dynamic: bool = False
64
70
  observer: str = Field(
65
71
  default="minmax",
66
72
  description=(
@@ -82,4 +88,9 @@ class QuantizationArgs(BaseModel):
82
88
  """
83
89
  from compressed_tensors.quantization.observers.base import Observer
84
90
 
91
+ if self.observer == "minmax" and self.dynamic:
92
+ # override defualt observer for dynamic, you never want minmax which
93
+ # keeps state across samples for dynamic
94
+ self.observer = "memoryless"
95
+
85
96
  return Observer.load_from_registry(self.observer, quantization_args=self)
@@ -30,11 +30,25 @@ from transformers import AutoConfig
30
30
 
31
31
  __all__ = [
32
32
  "infer_compressor_from_model_config",
33
+ "infer_compression_config_from_model_config",
33
34
  "load_compressed",
34
35
  "save_compressed",
35
36
  "save_compressed_model",
36
37
  ]
37
38
 
39
+ def infer_compressor_from_model_config(
40
+ pretrained_model_name_or_path: str,
41
+ ) -> Optional[CompressionConfig]:
42
+ """
43
+ Given a path to a model config, extract a sparsity config if it exists and return
44
+ the associated CompressionConfig
45
+
46
+ :param pretrained_model_name_or_path: path to model config on disk or HF hub
47
+ :return: matching compression config if config contains a sparsity config
48
+ """
49
+ config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
50
+ return getattr(config, SPARSITY_CONFIG_NAME, None)
51
+
38
52
 
39
53
  def infer_compressor_from_model_config(
40
54
  pretrained_model_name_or_path: str,
@@ -46,14 +60,8 @@ def infer_compressor_from_model_config(
46
60
  :param pretrained_model_name_or_path: path to model config on disk or HF hub
47
61
  :return: matching compressor if config contains a sparsity config
48
62
  """
49
- config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
50
- sparsity_config = getattr(config, SPARSITY_CONFIG_NAME, None)
51
- if sparsity_config is None:
52
- return None
53
-
54
- format = sparsity_config.get("format")
55
- sparsity_config = CompressionConfig.load_from_registry(format, **sparsity_config)
56
- compressor = ModelCompressor.load_from_registry(format, config=sparsity_config)
63
+ sparsity_config = infer_compressor_from_model_config(pretrained_model_name_or_path)
64
+ compressor = ModelCompressor.load_from_registry(sparsity_config.format, config=sparsity_config)
57
65
  return compressor
58
66
 
59
67
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: compressed-tensors
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Library for utilization of compressed safetensors of neural network models
5
5
  Home-page: https://github.com/neuralmagic/compressed-tensors
6
6
  Author: Neuralmagic, Inc.
@@ -103,4 +103,7 @@ save_compressed_model(model, "compressed_model.safetensors", compression_format=
103
103
  state_dict = dict(load_compressed("compressed_model.safetensors", compression_config))
104
104
  ```
105
105
 
106
+ For more in-depth tutorial on bitmask compression, refer to the [notebook](https://github.com/neuralmagic/compressed-tensors/blob/d707c5b84bc3fef164aebdcd97cb6eaa571982f8/examples/bitmask_compression.ipynb).
107
+
108
+
106
109
 
@@ -1,38 +1,38 @@
1
1
  compressed_tensors/__init__.py,sha256=SV1csvHUVCd8kHXz6UDZim1HZ_fAVG3vfk-j_4Bb6hY,789
2
2
  compressed_tensors/base.py,sha256=8zbgK87LpHkKoSknM55svXCT4E4dLLjPijwF9HfzmsQ,717
3
- compressed_tensors/compressors/__init__.py,sha256=3ZHKWSIWTjMx8XXgLtoP9JaVaCTvRecguLZTxLAAkKk,898
4
- compressed_tensors/compressors/base.py,sha256=F1smyJ6x2Sfq43tuP0QE9wZuhVqnewq-XUFPMtdU9yQ,2936
5
- compressed_tensors/compressors/dense.py,sha256=_VTusI3XjaY-zOdB_d7z4zOgPTJi9TJZZHF13g9ulS4,1263
6
- compressed_tensors/compressors/helpers.py,sha256=kSseqbwnu3JHZUKH8u4kQo5bmd87FvCcmWe0u2ikysA,6421
7
- compressed_tensors/compressors/sparse_bitmask.py,sha256=PYAK_Hcy2T57zlbpwl1FYkslluIr2x-d0Rh048YAtpI,8639
3
+ compressed_tensors/compressors/__init__.py,sha256=UcHp0CwUBJoS2MBN6mLUT7B3uRf1TEoRGbME7gLPD38,841
4
+ compressed_tensors/compressors/base.py,sha256=CqQo00ZIkAWpy0yVux5TXhK7WK_6Ws6qb5mCAvIoxB4,3902
5
+ compressed_tensors/compressors/dense.py,sha256=ig9lItmyCX5-VzgMuUqea-s8fHsTjPj5-0VIsPLl0g0,1271
6
+ compressed_tensors/compressors/helpers.py,sha256=wstgUEUYUCTMMu6G1YLF9G7vXqIJPj3MsWhqwU4J6Vw,5458
7
+ compressed_tensors/compressors/sparse_bitmask.py,sha256=VbCGFC4Q3nfhKWqJdkM4hKQmrZZqLT8wLNxbVt4kLSs,8647
8
8
  compressed_tensors/config/__init__.py,sha256=ZBqWn3r6ku1qfmlHHYp0mQueY0i7Pwhr9rbQk9dDlMc,704
9
9
  compressed_tensors/config/base.py,sha256=IP-3Y416w-811WozDzKHycIBXjdlG4Ddy7vpbwhOPD8,1373
10
10
  compressed_tensors/config/dense.py,sha256=xtkri7DkP7USu44FnSoTgTSqdGegCBtjRf3DfblSEL0,1311
11
11
  compressed_tensors/config/sparse_bitmask.py,sha256=y8fmQaOoGjIiI4FR6BJjfIqisAcqNQ_zjKyjT75bXwY,1284
12
12
  compressed_tensors/quantization/__init__.py,sha256=83J5bPB7PavN2TfCoW7_vEDhfYpm4TDrqYO9vdSQ5bk,760
13
- compressed_tensors/quantization/quant_args.py,sha256=dxSrq0_88ORQXcyIMYqoMZJvYEjnqdYl37f7lgZQqhw,2742
13
+ compressed_tensors/quantization/quant_args.py,sha256=cZhe5hRmvU_HnnUDw1kmqzMAGFb0r5t0IL2cobBNw28,3371
14
14
  compressed_tensors/quantization/quant_config.py,sha256=DWx8ae3gDlw99zAn3MUN9I4qeksbbmITmOXHRynqPB8,6650
15
15
  compressed_tensors/quantization/quant_scheme.py,sha256=X3oqmZPiIKtX5tEKKUj-0N6hB68NeiU2b1GcQEQPadQ,1480
16
16
  compressed_tensors/quantization/lifecycle/__init__.py,sha256=fM9XBtPgJX6z54PTm3Sd0SpK5od95ibwaSf2FFR8DqE,772
17
17
  compressed_tensors/quantization/lifecycle/apply.py,sha256=WXUL3q1g0s244k0wuqGYZPXTXiscdyrp7RScN2j_KGA,6651
18
18
  compressed_tensors/quantization/lifecycle/calibration.py,sha256=mLns4jlaWmBwOW8Jtlm5bMX-JET1AiZYUBO7qa-XuxI,1776
19
- compressed_tensors/quantization/lifecycle/forward.py,sha256=hnjk7pocZLDhLdMx237FKayYdvsdKbYSjTmSN5xbQO8,4599
20
- compressed_tensors/quantization/lifecycle/frozen.py,sha256=NHNmlDIaxurifqeI_qZC8xa4BstQsBNdOCXJjRzAfNU,1596
21
- compressed_tensors/quantization/lifecycle/initialize.py,sha256=8pifqZQSgVqWYI_Qtv6QfBICPbCTFHy48OWPeQsxEHQ,3578
19
+ compressed_tensors/quantization/lifecycle/forward.py,sha256=COTlfH92JkwM9Vd6m07tK_dhSiC77SFS0-MHU_DbQko,4941
20
+ compressed_tensors/quantization/lifecycle/frozen.py,sha256=FF7BleuOUX46Egk7F1ZE5r4fjWt9jG5-tO8BjXU1r78,1606
21
+ compressed_tensors/quantization/lifecycle/initialize.py,sha256=U6g9qifSF6pagQZQZEwd-rwWC6uQ_dZXn1wg6nr1Abg,3697
22
22
  compressed_tensors/quantization/observers/__init__.py,sha256=DNH31NQYrIBBcmHsMyFA6whh4pbRsLwuNa6L8AeXaGc,745
23
23
  compressed_tensors/quantization/observers/base.py,sha256=O76dAxkin7bB602e9kjmxc84p71-PxBtjIq5L69xplI,2786
24
24
  compressed_tensors/quantization/observers/helpers.py,sha256=SxvOf9zwZ9NDRC3E4Xm7z3RqHcbcPtCABLKX9GnGGHM,2109
25
- compressed_tensors/quantization/observers/memoryless.py,sha256=3f6bUlcf5mzOHPkTRhoQ7Zd8xu_pUmj8e3Y85fGysSU,1848
25
+ compressed_tensors/quantization/observers/memoryless.py,sha256=ZHTPh4aURE8LvHBFaP--HIC2JanMX5-VRdIkE2JHthw,1859
26
26
  compressed_tensors/quantization/observers/min_max.py,sha256=uAcZd5aY6WKM-KumTb2ybX28s8iKGVy6Nrje5Sddqew,2439
27
27
  compressed_tensors/quantization/utils/__init__.py,sha256=VdtEmP0bvuND_IGQnyqUPc5lnFp-1_yD7StKSX4x80w,656
28
28
  compressed_tensors/quantization/utils/helpers.py,sha256=N_wYfrPcFr__Q1mn6mHoNUTclwpTW8P5PDHkR7GvXWo,3694
29
29
  compressed_tensors/registry/__init__.py,sha256=FwLSNYqfIrb5JD_6OK_MT4_svvKTN_nEhpgQlQvGbjI,658
30
30
  compressed_tensors/registry/registry.py,sha256=fxjOjh2wklCvJhQxwofdy-zV8q7MkQ85SLG77nml2iA,11890
31
31
  compressed_tensors/utils/__init__.py,sha256=5DrYjoZbaEvSkJcC-GRSbM_RBHVF4tG9gMd3zsJnjLw,665
32
- compressed_tensors/utils/helpers.py,sha256=wLgiPrk7Vn29AijOGQGk3UnXItRd1jpROS6FxHoC4VQ,5530
32
+ compressed_tensors/utils/helpers.py,sha256=b2zQimHNn3emCgUGsVYMpaWQJH_tR9Uso819bU5r78Y,5909
33
33
  compressed_tensors/utils/safetensors_load.py,sha256=wo9UirGrGlenBqZeqotvpCT7D5MEdjCo2J3HeRaIFoU,8502
34
- compressed_tensors-0.3.1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
35
- compressed_tensors-0.3.1.dist-info/METADATA,sha256=vpGRbjHWdPUTl9HFoDxIkwAKQJNpff75P4pKC3nJE4A,3850
36
- compressed_tensors-0.3.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
37
- compressed_tensors-0.3.1.dist-info/top_level.txt,sha256=w2i-GyPs2s1UwVxvutSvN_lM22SXC2hQFBmoMcPnV7Y,19
38
- compressed_tensors-0.3.1.dist-info/RECORD,,
34
+ compressed_tensors-0.3.2.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
35
+ compressed_tensors-0.3.2.dist-info/METADATA,sha256=658VPFfv3kqbIbEjY0tJNOkRoTdeZApVUbqcC1vtMLM,4060
36
+ compressed_tensors-0.3.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
37
+ compressed_tensors-0.3.2.dist-info/top_level.txt,sha256=w2i-GyPs2s1UwVxvutSvN_lM22SXC2hQFBmoMcPnV7Y,19
38
+ compressed_tensors-0.3.2.dist-info/RECORD,,