compressed-tensors 0.3.0__tar.gz → 0.3.2__tar.gz
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.
- compressed-tensors-0.3.2/LICENSE +201 -0
- compressed-tensors-0.3.2/PKG-INFO +100 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/README.md +3 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/setup.py +10 -3
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/__init__.py +1 -6
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/base.py +25 -1
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/dense.py +1 -1
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/helpers.py +0 -24
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/sparse_bitmask.py +3 -2
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/lifecycle/forward.py +18 -12
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/lifecycle/frozen.py +9 -9
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/lifecycle/initialize.py +7 -4
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/observers/memoryless.py +2 -2
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/quant_args.py +11 -0
- compressed-tensors-0.3.2/src/compressed_tensors.egg-info/PKG-INFO +100 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors.egg-info/SOURCES.txt +1 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors.egg-info/requires.txt +1 -1
- compressed-tensors-0.3.0/PKG-INFO +0 -13
- compressed-tensors-0.3.0/src/compressed_tensors.egg-info/PKG-INFO +0 -13
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/pyproject.toml +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/setup.cfg +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/base.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/config/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/config/base.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/config/dense.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/config/sparse_bitmask.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/lifecycle/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/lifecycle/apply.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/lifecycle/calibration.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/observers/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/observers/base.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/observers/helpers.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/observers/min_max.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/quant_config.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/quant_scheme.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/utils/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/quantization/utils/helpers.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/registry/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/registry/registry.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/utils/__init__.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/utils/safetensors_load.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors.egg-info/dependency_links.txt +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors.egg-info/top_level.txt +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/tests/test_bitmask.py +0 -0
- {compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/tests/test_registry.py +0 -0
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
@@ -0,0 +1,100 @@
|
|
1
|
+
Metadata-Version: 2.1
|
2
|
+
Name: compressed-tensors
|
3
|
+
Version: 0.3.2
|
4
|
+
Summary: Library for utilization of compressed safetensors of neural network models
|
5
|
+
Home-page: https://github.com/neuralmagic/compressed-tensors
|
6
|
+
Author: Neuralmagic, Inc.
|
7
|
+
Author-email: support@neuralmagic.com
|
8
|
+
License: Apache 2.0
|
9
|
+
Platform: UNKNOWN
|
10
|
+
Description-Content-Type: text/markdown
|
11
|
+
Provides-Extra: dev
|
12
|
+
License-File: LICENSE
|
13
|
+
|
14
|
+
# compressed-tensors
|
15
|
+
|
16
|
+
This repository extends a [safetensors](https://github.com/huggingface/safetensors) format to efficiently store sparse and/or quantized tensors on disk. `compressed-tensors` format supports multiple compression types to minimize the disk space and facilitate the tensor manipulation.
|
17
|
+
|
18
|
+
## Motivation
|
19
|
+
|
20
|
+
### Reduce disk space by saving sparse tensors in a compressed format
|
21
|
+
|
22
|
+
The compressed format stores the data much more efficiently by taking advantage of two properties of tensors:
|
23
|
+
|
24
|
+
- Sparse tensors -> due to a large number of entries that are equal to zero.
|
25
|
+
- Quantized -> due to their low precision representation.
|
26
|
+
|
27
|
+
### Introduce an elegant interface to save/load compressed tensors
|
28
|
+
|
29
|
+
The library provides the user with the ability to compress/decompress tensors. The properties of tensors are defined by human-readable configs, allowing the users to understand the compression format at a quick glance.
|
30
|
+
|
31
|
+
## Installation
|
32
|
+
|
33
|
+
### Pip
|
34
|
+
|
35
|
+
```bash
|
36
|
+
pip install compressed-tensors
|
37
|
+
```
|
38
|
+
|
39
|
+
### From source
|
40
|
+
|
41
|
+
```bash
|
42
|
+
git clone https://github.com/neuralmagic/compressed-tensors
|
43
|
+
cd compressed-tensors
|
44
|
+
pip install -e .
|
45
|
+
```
|
46
|
+
|
47
|
+
## Getting started
|
48
|
+
|
49
|
+
### Saving/Loading Compressed Tensors (Bitmask Compression)
|
50
|
+
|
51
|
+
The function `save_compressed` uses the `compression_format` argument to apply compression to tensors.
|
52
|
+
The function `load_compressed` reverses the process: converts the compressed weights on disk to decompressed weights in device memory.
|
53
|
+
|
54
|
+
```python
|
55
|
+
from compressed_tensors import save_compressed, load_compressed, BitmaskConfig
|
56
|
+
from torch import Tensor
|
57
|
+
from typing import Dict
|
58
|
+
|
59
|
+
# the example BitmaskConfig method efficiently compresses
|
60
|
+
# tensors with large number of zero entries
|
61
|
+
compression_config = BitmaskConfig()
|
62
|
+
|
63
|
+
tensors: Dict[str, Tensor] = {"tensor_1": Tensor(
|
64
|
+
[[0.0, 0.0, 0.0],
|
65
|
+
[1.0, 1.0, 1.0]]
|
66
|
+
)}
|
67
|
+
# compress tensors using BitmaskConfig compression format (save them efficiently on disk)
|
68
|
+
save_compressed(tensors, "model.safetensors", compression_format=compression_config.format)
|
69
|
+
|
70
|
+
# decompress tensors (load_compressed returns a generator for memory efficiency)
|
71
|
+
decompressed_tensors = {}
|
72
|
+
for tensor_name, tensor in load_compressed("model.safetensors", compression_config = compression_config):
|
73
|
+
decompressed_tensors[tensor_name] = tensor
|
74
|
+
```
|
75
|
+
|
76
|
+
## Saving/Loading Compressed Models (Bitmask Compression)
|
77
|
+
|
78
|
+
We can apply bitmask compression to a whole model. For more detailed example see `example` directory.
|
79
|
+
```python
|
80
|
+
from compressed_tensors import save_compressed_model, load_compressed, BitmaskConfig
|
81
|
+
from transformers import AutoModelForCausalLM
|
82
|
+
|
83
|
+
model_name = "neuralmagic/llama2.c-stories110M-pruned50"
|
84
|
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
85
|
+
|
86
|
+
original_state_dict = model.state_dict()
|
87
|
+
|
88
|
+
compression_config = BitmaskConfig()
|
89
|
+
|
90
|
+
# save compressed model weights
|
91
|
+
save_compressed_model(model, "compressed_model.safetensors", compression_format=compression_config.format)
|
92
|
+
|
93
|
+
# load compressed model weights (`dict` turns generator into a dictionary)
|
94
|
+
state_dict = dict(load_compressed("compressed_model.safetensors", compression_config))
|
95
|
+
```
|
96
|
+
|
97
|
+
For more in-depth tutorial on bitmask compression, refer to the [notebook](https://github.com/neuralmagic/compressed-tensors/blob/d707c5b84bc3fef164aebdcd97cb6eaa571982f8/examples/bitmask_compression.ipynb).
|
98
|
+
|
99
|
+
|
100
|
+
|
@@ -80,3 +80,6 @@ save_compressed_model(model, "compressed_model.safetensors", compression_format=
|
|
80
80
|
# load compressed model weights (`dict` turns generator into a dictionary)
|
81
81
|
state_dict = dict(load_compressed("compressed_model.safetensors", compression_config))
|
82
82
|
```
|
83
|
+
|
84
|
+
For more in-depth tutorial on bitmask compression, refer to the [notebook](https://github.com/neuralmagic/compressed-tensors/blob/d707c5b84bc3fef164aebdcd97cb6eaa571982f8/examples/bitmask_compression.ipynb).
|
85
|
+
|
@@ -14,7 +14,10 @@
|
|
14
14
|
|
15
15
|
|
16
16
|
from setuptools import setup, find_packages
|
17
|
-
from typing import List, Dict
|
17
|
+
from typing import List, Dict, Tuple
|
18
|
+
|
19
|
+
def _setup_long_description() -> Tuple[str, str]:
|
20
|
+
return open("README.md", "r", encoding="utf-8").read(), "text/markdown"
|
18
21
|
|
19
22
|
def _setup_packages() -> List:
|
20
23
|
return find_packages(
|
@@ -22,17 +25,21 @@ def _setup_packages() -> List:
|
|
22
25
|
)
|
23
26
|
|
24
27
|
def _setup_install_requires() -> List:
|
25
|
-
return ["torch>=1.7.0", "transformers
|
28
|
+
return ["torch>=1.7.0", "transformers<4.41", "pydantic<2.7"]
|
26
29
|
|
27
30
|
def _setup_extras() -> Dict:
|
28
31
|
return {"dev": ["black==22.12.0", "isort==5.8.0", "wheel>=0.36.2", "flake8>=3.8.3", "pytest>=6.0.0", "nbconvert>=7.16.3"]}
|
29
32
|
|
30
33
|
setup(
|
31
34
|
name="compressed-tensors",
|
32
|
-
version="0.3.
|
35
|
+
version="0.3.2",
|
33
36
|
author="Neuralmagic, Inc.",
|
34
37
|
author_email="support@neuralmagic.com",
|
38
|
+
license="Apache 2.0",
|
35
39
|
description="Library for utilization of compressed safetensors of neural network models",
|
40
|
+
long_description=_setup_long_description()[0],
|
41
|
+
long_description_content_type=_setup_long_description()[1],
|
42
|
+
url="https://github.com/neuralmagic/compressed-tensors",
|
36
43
|
extras_require=_setup_extras(),
|
37
44
|
install_requires=_setup_install_requires(),
|
38
45
|
package_dir={"": "src"},
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/__init__.py
RENAMED
@@ -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
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/base.py
RENAMED
@@ -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
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/dense.py
RENAMED
@@ -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([])
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/compressors/helpers.py
RENAMED
@@ -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
|
79
|
-
and returns a generator
|
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:
|
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
|
-
|
124
|
-
|
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
|
-
|
131
|
-
|
132
|
-
#
|
133
|
-
scale
|
134
|
-
zero_point
|
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
|
-
|
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
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
|
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
|
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)
|
@@ -0,0 +1,100 @@
|
|
1
|
+
Metadata-Version: 2.1
|
2
|
+
Name: compressed-tensors
|
3
|
+
Version: 0.3.2
|
4
|
+
Summary: Library for utilization of compressed safetensors of neural network models
|
5
|
+
Home-page: https://github.com/neuralmagic/compressed-tensors
|
6
|
+
Author: Neuralmagic, Inc.
|
7
|
+
Author-email: support@neuralmagic.com
|
8
|
+
License: Apache 2.0
|
9
|
+
Platform: UNKNOWN
|
10
|
+
Description-Content-Type: text/markdown
|
11
|
+
Provides-Extra: dev
|
12
|
+
License-File: LICENSE
|
13
|
+
|
14
|
+
# compressed-tensors
|
15
|
+
|
16
|
+
This repository extends a [safetensors](https://github.com/huggingface/safetensors) format to efficiently store sparse and/or quantized tensors on disk. `compressed-tensors` format supports multiple compression types to minimize the disk space and facilitate the tensor manipulation.
|
17
|
+
|
18
|
+
## Motivation
|
19
|
+
|
20
|
+
### Reduce disk space by saving sparse tensors in a compressed format
|
21
|
+
|
22
|
+
The compressed format stores the data much more efficiently by taking advantage of two properties of tensors:
|
23
|
+
|
24
|
+
- Sparse tensors -> due to a large number of entries that are equal to zero.
|
25
|
+
- Quantized -> due to their low precision representation.
|
26
|
+
|
27
|
+
### Introduce an elegant interface to save/load compressed tensors
|
28
|
+
|
29
|
+
The library provides the user with the ability to compress/decompress tensors. The properties of tensors are defined by human-readable configs, allowing the users to understand the compression format at a quick glance.
|
30
|
+
|
31
|
+
## Installation
|
32
|
+
|
33
|
+
### Pip
|
34
|
+
|
35
|
+
```bash
|
36
|
+
pip install compressed-tensors
|
37
|
+
```
|
38
|
+
|
39
|
+
### From source
|
40
|
+
|
41
|
+
```bash
|
42
|
+
git clone https://github.com/neuralmagic/compressed-tensors
|
43
|
+
cd compressed-tensors
|
44
|
+
pip install -e .
|
45
|
+
```
|
46
|
+
|
47
|
+
## Getting started
|
48
|
+
|
49
|
+
### Saving/Loading Compressed Tensors (Bitmask Compression)
|
50
|
+
|
51
|
+
The function `save_compressed` uses the `compression_format` argument to apply compression to tensors.
|
52
|
+
The function `load_compressed` reverses the process: converts the compressed weights on disk to decompressed weights in device memory.
|
53
|
+
|
54
|
+
```python
|
55
|
+
from compressed_tensors import save_compressed, load_compressed, BitmaskConfig
|
56
|
+
from torch import Tensor
|
57
|
+
from typing import Dict
|
58
|
+
|
59
|
+
# the example BitmaskConfig method efficiently compresses
|
60
|
+
# tensors with large number of zero entries
|
61
|
+
compression_config = BitmaskConfig()
|
62
|
+
|
63
|
+
tensors: Dict[str, Tensor] = {"tensor_1": Tensor(
|
64
|
+
[[0.0, 0.0, 0.0],
|
65
|
+
[1.0, 1.0, 1.0]]
|
66
|
+
)}
|
67
|
+
# compress tensors using BitmaskConfig compression format (save them efficiently on disk)
|
68
|
+
save_compressed(tensors, "model.safetensors", compression_format=compression_config.format)
|
69
|
+
|
70
|
+
# decompress tensors (load_compressed returns a generator for memory efficiency)
|
71
|
+
decompressed_tensors = {}
|
72
|
+
for tensor_name, tensor in load_compressed("model.safetensors", compression_config = compression_config):
|
73
|
+
decompressed_tensors[tensor_name] = tensor
|
74
|
+
```
|
75
|
+
|
76
|
+
## Saving/Loading Compressed Models (Bitmask Compression)
|
77
|
+
|
78
|
+
We can apply bitmask compression to a whole model. For more detailed example see `example` directory.
|
79
|
+
```python
|
80
|
+
from compressed_tensors import save_compressed_model, load_compressed, BitmaskConfig
|
81
|
+
from transformers import AutoModelForCausalLM
|
82
|
+
|
83
|
+
model_name = "neuralmagic/llama2.c-stories110M-pruned50"
|
84
|
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
85
|
+
|
86
|
+
original_state_dict = model.state_dict()
|
87
|
+
|
88
|
+
compression_config = BitmaskConfig()
|
89
|
+
|
90
|
+
# save compressed model weights
|
91
|
+
save_compressed_model(model, "compressed_model.safetensors", compression_format=compression_config.format)
|
92
|
+
|
93
|
+
# load compressed model weights (`dict` turns generator into a dictionary)
|
94
|
+
state_dict = dict(load_compressed("compressed_model.safetensors", compression_config))
|
95
|
+
```
|
96
|
+
|
97
|
+
For more in-depth tutorial on bitmask compression, refer to the [notebook](https://github.com/neuralmagic/compressed-tensors/blob/d707c5b84bc3fef164aebdcd97cb6eaa571982f8/examples/bitmask_compression.ipynb).
|
98
|
+
|
99
|
+
|
100
|
+
|
@@ -1,13 +0,0 @@
|
|
1
|
-
Metadata-Version: 2.1
|
2
|
-
Name: compressed-tensors
|
3
|
-
Version: 0.3.0
|
4
|
-
Summary: Library for utilization of compressed safetensors of neural network models
|
5
|
-
Home-page: UNKNOWN
|
6
|
-
Author: Neuralmagic, Inc.
|
7
|
-
Author-email: support@neuralmagic.com
|
8
|
-
License: UNKNOWN
|
9
|
-
Platform: UNKNOWN
|
10
|
-
Provides-Extra: dev
|
11
|
-
|
12
|
-
UNKNOWN
|
13
|
-
|
@@ -1,13 +0,0 @@
|
|
1
|
-
Metadata-Version: 2.1
|
2
|
-
Name: compressed-tensors
|
3
|
-
Version: 0.3.0
|
4
|
-
Summary: Library for utilization of compressed safetensors of neural network models
|
5
|
-
Home-page: UNKNOWN
|
6
|
-
Author: Neuralmagic, Inc.
|
7
|
-
Author-email: support@neuralmagic.com
|
8
|
-
License: UNKNOWN
|
9
|
-
Platform: UNKNOWN
|
10
|
-
Provides-Extra: dev
|
11
|
-
|
12
|
-
UNKNOWN
|
13
|
-
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/config/__init__.py
RENAMED
File without changes
|
File without changes
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/config/dense.py
RENAMED
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/registry/__init__.py
RENAMED
File without changes
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/registry/registry.py
RENAMED
File without changes
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors/utils/__init__.py
RENAMED
File without changes
|
File without changes
|
File without changes
|
{compressed-tensors-0.3.0 → compressed-tensors-0.3.2}/src/compressed_tensors.egg-info/top_level.txt
RENAMED
File without changes
|
File without changes
|
File without changes
|