ADAPT-Chase commited on
Commit
5aed0ba
·
verified ·
1 Parent(s): 0038318

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 +6 -0
  2. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors-0.10.2.dist-info/licenses/LICENSE +201 -0
  3. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/__pycache__/__init__.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/__pycache__/base.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/__pycache__/version.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__init__.py +22 -0
  7. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__pycache__/__init__.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__pycache__/base.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__pycache__/helpers.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/base.py +202 -0
  11. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/helpers.py +137 -0
  12. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/__init__.py +17 -0
  13. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/__pycache__/__init__.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/__pycache__/model_compressor.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/model_compressor.py +784 -0
  16. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__init__.py +19 -0
  17. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/__init__.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/base.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/naive_quantized.cpython-312.pyc +0 -0
  20. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/nvfp4_quantized.cpython-312.pyc +0 -0
  21. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/pack_quantized.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/base.py +263 -0
  23. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/naive_quantized.py +154 -0
  24. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/nvfp4_quantized.py +190 -0
  25. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/pack_quantized.py +309 -0
  26. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__init__.py +19 -0
  27. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/__init__.cpython-312.pyc +0 -0
  28. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/base.cpython-312.pyc +0 -0
  29. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/dense.cpython-312.pyc +0 -0
  30. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/sparse_24_bitmask.cpython-312.pyc +0 -0
  31. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/sparse_bitmask.cpython-312.pyc +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/base.py +202 -0
  33. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/dense.py +67 -0
  34. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/sparse_24_bitmask.py +242 -0
  35. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/sparse_bitmask.py +169 -0
  36. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/__init__.py +16 -0
  37. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/__pycache__/__init__.cpython-312.pyc +0 -0
  38. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/__pycache__/marlin_24.cpython-312.pyc +0 -0
  39. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/marlin_24.py +273 -0
  40. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__init__.py +19 -0
  41. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/__init__.cpython-312.pyc +0 -0
  42. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/base.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/dense.cpython-312.pyc +0 -0
  44. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/sparse_24_bitmask.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/sparse_bitmask.cpython-312.pyc +0 -0
  46. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/base.py +112 -0
  47. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/dense.py +36 -0
  48. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/sparse_24_bitmask.py +40 -0
  49. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/sparse_bitmask.py +36 -0
  50. tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/linear/__init__.py +13 -0
.gitattributes CHANGED
@@ -4592,3 +4592,9 @@ tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/mistral_instr
4592
  tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/tekken_240718.json filter=lfs diff=lfs merge=lfs -text
4593
  tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/tekken_240911.json filter=lfs diff=lfs merge=lfs -text
4594
  tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/tokenizer.model.v1 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
4592
  tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/tekken_240718.json filter=lfs diff=lfs merge=lfs -text
4593
  tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/tekken_240911.json filter=lfs diff=lfs merge=lfs -text
4594
  tool_server/.venv/lib/python3.12/site-packages/mistral_common/data/tokenizer.model.v1 filter=lfs diff=lfs merge=lfs -text
4595
+ tool_server/.venv/lib/python3.12/site-packages/xgrammar/lib64/libgmock_main.a filter=lfs diff=lfs merge=lfs -text
4596
+ tool_server/.venv/lib/python3.12/site-packages/xgrammar/lib64/libgmock.a filter=lfs diff=lfs merge=lfs -text
4597
+ tool_server/.venv/lib/python3.12/site-packages/xgrammar/lib64/libgtest.a filter=lfs diff=lfs merge=lfs -text
4598
+ tool_server/.venv/lib/python3.12/site-packages/vllm/vllm_flash_attn/_vllm_fa2_C.abi3.so filter=lfs diff=lfs merge=lfs -text
4599
+ tool_server/.venv/lib/python3.12/site-packages/vllm/vllm_flash_attn/_vllm_fa3_C.abi3.so filter=lfs diff=lfs merge=lfs -text
4600
+ tool_server/.venv/lib/python3.12/site-packages/vllm/config/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors-0.10.2.dist-info/licenses/LICENSE ADDED
@@ -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.
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (392 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/__pycache__/base.cpython-312.pyc ADDED
Binary file (488 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/__pycache__/version.cpython-312.pyc ADDED
Binary file (649 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # flake8: noqa
16
+
17
+ from .base import *
18
+ from .helpers import *
19
+ from .model_compressors import *
20
+ from .quantized_compressors import *
21
+ from .sparse_compressors import *
22
+ from .sparse_quantized_compressors import *
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (394 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__pycache__/base.cpython-312.pyc ADDED
Binary file (7.86 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/__pycache__/helpers.cpython-312.pyc ADDED
Binary file (5.69 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/base.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ from typing import Dict, Generator, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from compressed_tensors.config import SparsityCompressionConfig
20
+ from compressed_tensors.quantization import QuantizationArgs, QuantizationConfig
21
+ from compressed_tensors.registry import RegistryMixin
22
+ from compressed_tensors.utils import has_offloaded_params
23
+ from torch import Tensor
24
+ from torch.nn import Module
25
+
26
+
27
+ __all__ = ["BaseCompressor"]
28
+
29
+
30
+ class BaseCompressor(RegistryMixin, ABC):
31
+ """
32
+ Base class representing a model compression algorithm. Each child class should
33
+ implement compression_param_info, compress_weight and decompress_weight.
34
+
35
+ Compressors support compressing/decompressing a full module state dict or a single
36
+ quantized PyTorch leaf module.
37
+
38
+ Model Load Lifecycle (run_compressed=False):
39
+ - ModelCompressor.decompress()
40
+ - apply_quantization_config()
41
+ - BaseCompressor.decompress()
42
+
43
+ Model Save Lifecycle:
44
+ - ModelCompressor.compress()
45
+ - BaseCompressor.compress()
46
+
47
+
48
+ Module Lifecycle (run_compressed=True):
49
+ - apply_quantization_config()
50
+ - compressed_module = CompressedLinear(module)
51
+ - initialize_module_for_quantization()
52
+ - BaseCompressor.compression_param_info()
53
+ - register_parameters()
54
+ - compressed_module.forward()
55
+ -compressed_module.decompress()
56
+
57
+
58
+ :param config: config specifying compression parameters
59
+ """
60
+
61
+ def __init__(
62
+ self, config: Union[SparsityCompressionConfig, QuantizationConfig, None] = None
63
+ ):
64
+ self.config = config
65
+
66
+ def compression_param_info(
67
+ self,
68
+ weight_shape: torch.Size,
69
+ quantization_args: Optional[QuantizationArgs] = None,
70
+ ) -> Dict[str, Tuple[torch.Size, torch.dtype]]:
71
+ """
72
+ Creates a dictionary of expected shapes and dtypes for each compression
73
+ parameter used by the compressor
74
+
75
+ :param weight_shape: uncompressed weight shape
76
+ :param quantization_args: quantization parameters for the weight
77
+ :return: dictionary mapping compressed parameter names to shape and dtype
78
+ """
79
+ raise NotImplementedError()
80
+
81
+ @property
82
+ @abstractmethod
83
+ def compression_param_names(self) -> Tuple[str]:
84
+ """
85
+ Returns a tuple of compression parameter names introduced by
86
+ the compressor during compression
87
+ """
88
+ raise NotImplementedError()
89
+
90
+ @abstractmethod
91
+ def compress(
92
+ self,
93
+ model_state: Dict[str, Tensor],
94
+ **kwargs,
95
+ ) -> Dict[str, Tensor]:
96
+ """
97
+ Compresses a dense state dict
98
+
99
+ :param model_state: state dict of uncompressed model
100
+ :param kwargs: additional arguments for compression
101
+ :return: compressed state dict
102
+ """
103
+ raise NotImplementedError()
104
+
105
+ @abstractmethod
106
+ def decompress(
107
+ self,
108
+ path_to_model_or_tensors: str,
109
+ device: str = "cpu",
110
+ **kwargs,
111
+ ) -> Generator[Tuple[str, Tensor], None, None]:
112
+ """
113
+ Reads a compressed state dict located at path_to_model_or_tensors
114
+ and returns a generator for sequentially decompressing back to a
115
+ dense state dict
116
+
117
+ :param path_to_model_or_tensors: path to compressed safetensors model (directory
118
+ with one or more safetensors files) or compressed tensors file
119
+ :param names_to_scheme: quantization args for each quantized weight
120
+ :param device: optional device to load intermediate weights into
121
+ :return: compressed state dict
122
+ """
123
+ raise NotImplementedError()
124
+
125
+ def compress_module(self, module: Module) -> Optional[Dict[str, torch.Tensor]]:
126
+ """
127
+ Compresses a single quantized leaf PyTorch module. If the module is not
128
+ quantized, this function has no effect.
129
+
130
+ :param module: PyTorch module to compress
131
+ :return: dictionary of compressed weight data, or None if module is not
132
+ quantized
133
+ """
134
+ if not hasattr(module, "quantization_scheme"):
135
+ return None # module is not quantized
136
+ quantization_scheme = module.quantization_scheme
137
+ if not hasattr(quantization_scheme, "weights"):
138
+ return None # weights are not quantized
139
+
140
+ quantization_args = quantization_scheme.weights
141
+ weight = getattr(module, "weight", None)
142
+ weight_scale = getattr(module, "weight_scale", None)
143
+ weight_zero_point = getattr(module, "weight_zero_point", None)
144
+
145
+ return self.compress_weight(
146
+ weight=weight,
147
+ scale=weight_scale,
148
+ zero_point=weight_zero_point,
149
+ quantization_args=quantization_args,
150
+ )
151
+
152
+ def compress_weight(
153
+ self,
154
+ weight: Tensor,
155
+ **kwargs,
156
+ ) -> Dict[str, torch.Tensor]:
157
+ """
158
+ Compresses a single uncompressed weight
159
+
160
+ :param weight: uncompressed weight tensor
161
+ :param kwargs: additional arguments for compression
162
+ """
163
+ raise NotImplementedError()
164
+
165
+ def decompress_module(self, module: Module):
166
+ """
167
+ Decompresses a single compressed leaf PyTorch module. If the module is not
168
+ quantized, this function has no effect.
169
+
170
+ :param module: PyTorch module to decompress
171
+ :return: tensor of the decompressed weight, or None if module is not quantized
172
+ """
173
+
174
+ params_device = next(module.parameters()).device
175
+ device = "cpu" if has_offloaded_params(module) else params_device
176
+
177
+ if not hasattr(module, "quantization_scheme"):
178
+ return None # module is not quantized
179
+ quantization_scheme = module.quantization_scheme
180
+ if not hasattr(quantization_scheme, "weights"):
181
+ return None # weights are not quantized
182
+
183
+ quantization_args = quantization_scheme.weights
184
+ compressed_data = {}
185
+ for name, parameter in module.named_parameters():
186
+ compressed_data[name] = parameter
187
+
188
+ return self.decompress_weight(
189
+ compressed_data=compressed_data, quantization_args=quantization_args
190
+ ).to(device)
191
+
192
+ def decompress_weight(
193
+ self, compressed_data: Dict[str, Tensor], **kwargs
194
+ ) -> torch.Tensor:
195
+ """
196
+ Decompresses a single compressed weight
197
+
198
+ :param compressed_data: dictionary of data needed for decompression
199
+ :param kwargs: additional arguments for decompression
200
+ :return: tensor of the decompressed weight
201
+ """
202
+ raise NotImplementedError()
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/helpers.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from pathlib import Path
16
+ from typing import Dict, Generator, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from compressed_tensors.compressors import BaseCompressor
20
+ from compressed_tensors.config import CompressionFormat, SparsityCompressionConfig
21
+ from compressed_tensors.utils.safetensors_load import get_weight_mappings
22
+ from safetensors import safe_open
23
+ from safetensors.torch import save_file
24
+ from torch import Tensor
25
+
26
+
27
+ __all__ = [
28
+ "load_compressed",
29
+ "save_compressed",
30
+ "save_compressed_model",
31
+ ]
32
+
33
+
34
+ def save_compressed(
35
+ tensors: Dict[str, Tensor],
36
+ save_path: Union[str, Path],
37
+ compression_format: Optional[CompressionFormat] = None,
38
+ ):
39
+ """
40
+ Save compressed tensors to disk. If tensors are not compressed,
41
+ save them as is.
42
+
43
+ :param tensors: dictionary of tensors to compress
44
+ :param save_path: path to save compressed tensors
45
+ :param compression_format: compression format used for the tensors
46
+ :return: compression config, if tensors were compressed - None otherwise
47
+ """
48
+ if tensors is None or len(tensors) == 0:
49
+ raise ValueError("No tensors or empty tensors provided to compress")
50
+
51
+ # if no compression_format specified, default to `dense`
52
+ compression_format = compression_format or CompressionFormat.dense.value
53
+
54
+ if not (
55
+ compression_format in BaseCompressor.registered_names()
56
+ or compression_format in BaseCompressor.registered_aliases()
57
+ ):
58
+ raise ValueError(
59
+ f"Unknown compression format: {compression_format}. "
60
+ f"Must be one of {set(BaseCompressor.registered_names() + BaseCompressor.registered_aliases())}" # noqa E501
61
+ )
62
+
63
+ # compress
64
+ compressor = BaseCompressor.load_from_registry(compression_format)
65
+ # save compressed tensors
66
+ compressed_tensors = compressor.compress(tensors)
67
+ save_file(compressed_tensors, save_path)
68
+
69
+
70
+ def load_compressed(
71
+ compressed_tensors: Union[str, Path],
72
+ compression_config: SparsityCompressionConfig = None,
73
+ device: Optional[str] = "cpu",
74
+ ) -> Generator[Tuple[str, Tensor], None, None]:
75
+ """
76
+ Load compressed tensors from disk.
77
+ If tensors are not compressed, load them as is.
78
+
79
+ :param compressed_tensors: path to compressed tensors.
80
+ This can be a path to a file or a directory containing
81
+ one or multiple safetensor files (if multiple - in the format
82
+ assumed by huggingface)
83
+ :param compression_config: compression config to use for decompressing tensors.
84
+ :param device: device to move tensors to. If None, tensors are loaded on CPU.
85
+ :param return_dict: if True, return a dictionary of decompressed tensors
86
+ :return a generator that yields the name and tensor of the decompressed tensor
87
+ """
88
+ if compressed_tensors is None or not Path(compressed_tensors).exists():
89
+ raise ValueError("No compressed tensors provided to load")
90
+
91
+ if (
92
+ compression_config is None
93
+ or compression_config.format == CompressionFormat.dense.value
94
+ ):
95
+ # if no compression_config specified, or `dense` format specified,
96
+ # assume tensors are not compressed on disk
97
+ weight_mappings = get_weight_mappings(compressed_tensors)
98
+ for weight_name, file_with_weight_name in weight_mappings.items():
99
+ with safe_open(file_with_weight_name, framework="pt", device=device) as f:
100
+ weight = f.get_tensor(weight_name)
101
+ yield weight_name, weight
102
+ else:
103
+ # decompress tensors
104
+ compression_format = compression_config.format
105
+ compressor = BaseCompressor.load_from_registry(
106
+ compression_format, config=compression_config
107
+ )
108
+ yield from compressor.decompress(compressed_tensors, device=device)
109
+
110
+
111
+ def save_compressed_model(
112
+ model: torch.nn.Module,
113
+ filename: str,
114
+ compression_format: Optional[CompressionFormat] = None,
115
+ force_contiguous: bool = True,
116
+ ):
117
+ """
118
+ Wrapper around safetensors `save_model` helper function, which allows for
119
+ saving compressed model to disk.
120
+
121
+ Note: The model is assumed to have a
122
+ state_dict with unique entries
123
+
124
+ :param model: model to save on disk
125
+ :param filename: filename location to save the file
126
+ :param compression_format: compression format used for the model
127
+ :param force_contiguous: forcing the state_dict to be saved as contiguous tensors
128
+ """
129
+ state_dict = model.state_dict()
130
+ if force_contiguous:
131
+ state_dict = {k: v.contiguous() for k, v in state_dict.items()}
132
+ try:
133
+ save_compressed(state_dict, filename, compression_format=compression_format)
134
+ except ValueError as e:
135
+ msg = str(e)
136
+ msg += " Or use save_compressed_model(..., force_contiguous=True), read the docs for potential caveats." # noqa E501
137
+ raise ValueError(msg)
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # flake8: noqa
15
+
16
+
17
+ from .model_compressor import *
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (258 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/__pycache__/model_compressor.cpython-312.pyc ADDED
Binary file (30.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/model_compressors/model_compressor.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import logging
17
+ import operator
18
+ import os
19
+ import re
20
+ from contextlib import contextmanager
21
+ from copy import deepcopy
22
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, TypeVar, Union
23
+
24
+ import compressed_tensors
25
+ import torch
26
+ import transformers
27
+ from compressed_tensors.base import (
28
+ COMPRESSION_VERSION_NAME,
29
+ QUANTIZATION_CONFIG_NAME,
30
+ QUANTIZATION_METHOD_NAME,
31
+ SPARSITY_CONFIG_NAME,
32
+ )
33
+ from compressed_tensors.compressors.base import BaseCompressor
34
+ from compressed_tensors.compressors.sparse_compressors import DenseCompressor
35
+ from compressed_tensors.config import CompressionFormat, SparsityCompressionConfig
36
+ from compressed_tensors.quantization import (
37
+ DEFAULT_QUANTIZATION_METHOD,
38
+ QuantizationConfig,
39
+ QuantizationScheme,
40
+ QuantizationStatus,
41
+ apply_quantization_config,
42
+ load_pretrained_quantization_parameters,
43
+ )
44
+ from compressed_tensors.quantization.lifecycle import expand_target_names
45
+ from compressed_tensors.quantization.utils import (
46
+ is_module_quantized,
47
+ iter_named_leaf_modules,
48
+ )
49
+ from compressed_tensors.utils import (
50
+ align_module_device,
51
+ delete_offload_parameter,
52
+ get_execution_device,
53
+ get_offloaded_device,
54
+ get_safetensors_folder,
55
+ has_offloaded_params,
56
+ merge_names,
57
+ register_offload_parameter,
58
+ update_parameter_data,
59
+ )
60
+ from compressed_tensors.utils.helpers import (
61
+ fix_fsdp_module_name,
62
+ is_compressed_tensors_config,
63
+ )
64
+ from torch import Tensor
65
+ from torch.nn import Module
66
+ from tqdm import tqdm
67
+ from transformers import AutoConfig
68
+ from transformers.file_utils import CONFIG_NAME
69
+
70
+
71
+ if TYPE_CHECKING:
72
+ from compressed_tensors.compressors import BaseQuantizationCompressor
73
+
74
+
75
+ __all__ = ["ModelCompressor", "map_module_to_scheme"]
76
+
77
+ _LOGGER: logging.Logger = logging.getLogger(__name__)
78
+
79
+
80
+ if TYPE_CHECKING:
81
+ # dummy type if not available from transformers
82
+ CompressedTensorsConfig = TypeVar("CompressedTensorsConfig")
83
+
84
+
85
+ class ModelCompressor:
86
+ """
87
+ Handles compression and decompression of a model with a sparsity config and/or
88
+ quantization config.
89
+
90
+ Compression LifeCycle
91
+ - compressor = ModelCompressor.from_pretrained_model(model)
92
+ - compressed_state_dict = compressor.compress(model, state_dict)
93
+ - compressor.quantization_compressor.compress(model, state_dict)
94
+ - compressor.sparsity_compressor.compress(model, state_dict)
95
+ - model.save_pretrained(output_dir, state_dict=compressed_state_dict)
96
+ - compressor.update_config(output_dir)
97
+
98
+ Decompression LifeCycle
99
+ - compressor = ModelCompressor.from_pretrained(comp_model_path)
100
+ - model = AutoModel.from_pretrained(comp_model_path)
101
+ - compressor.decompress(comp_model_path, model)
102
+ - compressor.sparsity_compressor.decompress(comp_model_path, model)
103
+ - compressor.quantization_compressor.decompress(comp_model_path, model)
104
+
105
+ :param sparsity_config: config specifying sparsity compression parameters
106
+ :param quantization_config: config specifying quantization compression parameters
107
+ """
108
+
109
+ sparsity_config: Optional[SparsityCompressionConfig] = None
110
+ quantization_config: Optional[QuantizationConfig] = None
111
+
112
+ @classmethod
113
+ def from_pretrained(
114
+ cls,
115
+ pretrained_model_name_or_path: str,
116
+ **kwargs,
117
+ ) -> Optional["ModelCompressor"]:
118
+ """
119
+ Given a path to a model config, extract the sparsity and/or quantization
120
+ configs and load a ModelCompressor
121
+
122
+ :param pretrained_model_name_or_path: path to model config on disk or HF hub
123
+ :return: compressor for the configs, or None if model is not compressed
124
+ """
125
+ config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
126
+ compression_config = getattr(config, QUANTIZATION_CONFIG_NAME, None)
127
+ return cls.from_compression_config(compression_config)
128
+
129
+ @classmethod
130
+ def from_compression_config(
131
+ cls,
132
+ compression_config: Union[Dict[str, Any], "CompressedTensorsConfig"],
133
+ ):
134
+ """
135
+ :param compression_config:
136
+ A compression or quantization config
137
+
138
+ The type is one of the following:
139
+ 1. A Dict found under either "quantization_config" or "compression_config"
140
+ keys in the config.json
141
+ 2. A CompressedTensorsConfig found under key "quantization_config" in HF
142
+ model config
143
+ :return: compressor for the configs, or None if model is not compressed
144
+ """
145
+ if compression_config is None:
146
+ return None
147
+
148
+ sparsity_config = cls.parse_sparsity_config(compression_config)
149
+ quantization_config = cls.parse_quantization_config(compression_config)
150
+ if sparsity_config is None and quantization_config is None:
151
+ return None
152
+
153
+ if sparsity_config is not None:
154
+ format = sparsity_config.get("format")
155
+ sparsity_config = SparsityCompressionConfig.load_from_registry(
156
+ format, **sparsity_config
157
+ )
158
+ if quantization_config is not None:
159
+ quantization_config = QuantizationConfig.model_validate(quantization_config)
160
+
161
+ return cls(
162
+ sparsity_config=sparsity_config, quantization_config=quantization_config
163
+ )
164
+
165
+ @classmethod
166
+ def from_pretrained_model(
167
+ cls,
168
+ model: Module,
169
+ sparsity_config: Union[SparsityCompressionConfig, str, None] = None,
170
+ quantization_format: Optional[str] = None,
171
+ ) -> Optional["ModelCompressor"]:
172
+ """
173
+ Given a pytorch model and optional sparsity and/or quantization configs,
174
+ load the appropriate compressors
175
+
176
+ :param model: pytorch model to target for compression
177
+ :param sparsity_config: a filled in sparsity config or string corresponding
178
+ to a sparsity compression algorithm
179
+ :param quantization_format: string corresponding to a quantization compression
180
+ algorithm
181
+ :return: compressor for the configs, or None if model is not compressed
182
+ """
183
+ quantization_config = QuantizationConfig.from_pretrained(
184
+ model, format=quantization_format
185
+ )
186
+
187
+ if isinstance(sparsity_config, str): # we passed in a sparsity format
188
+ sparsity_config = SparsityCompressionConfig.load_from_registry(
189
+ sparsity_config
190
+ )
191
+
192
+ if sparsity_config is None and quantization_config is None:
193
+ return None
194
+
195
+ return cls(
196
+ sparsity_config=sparsity_config, quantization_config=quantization_config
197
+ )
198
+
199
+ @staticmethod
200
+ def parse_sparsity_config(
201
+ compression_config: Union[Dict[str, Any], "CompressedTensorsConfig"]
202
+ ) -> Union[Dict[str, Any], None]:
203
+ """
204
+ Parse sparsity config from quantization/compression config. Sparsity
205
+ config is nested inside q/c config
206
+
207
+ :param compression_config: quantization/compression config
208
+ :return: sparsity config
209
+ """
210
+ if compression_config is None:
211
+ return None
212
+
213
+ if is_compressed_tensors_config(compression_config):
214
+ s_config = compression_config.sparsity_config
215
+ return s_config.model_dump() if s_config is not None else None
216
+
217
+ return compression_config.get(SPARSITY_CONFIG_NAME, None)
218
+
219
+ @staticmethod
220
+ def parse_quantization_config(
221
+ compression_config: Union[Dict[str, Any], "CompressedTensorsConfig"]
222
+ ) -> Union[Dict[str, Any], None]:
223
+ """
224
+ Parse quantization config from quantization/compression config. The
225
+ quantization are all the fields that are not the sparsity config or
226
+ metadata fields
227
+
228
+ :param compression_config: quantization/compression config
229
+ :return: quantization config without sparsity config or metadata fields
230
+ """
231
+ if compression_config is None:
232
+ return None
233
+
234
+ if is_compressed_tensors_config(compression_config):
235
+ q_config = compression_config.quantization_config
236
+ return q_config.model_dump() if q_config is not None else None
237
+
238
+ quantization_config = deepcopy(compression_config)
239
+ quantization_config.pop(SPARSITY_CONFIG_NAME, None)
240
+
241
+ # some fields are required, even if a qconfig is not present
242
+ # pop them off and if nothing remains, then there is no qconfig
243
+ quant_method = quantization_config.pop(QUANTIZATION_METHOD_NAME, None)
244
+ _ = quantization_config.pop(COMPRESSION_VERSION_NAME, None)
245
+
246
+ if len(quantization_config) == 0:
247
+ return None
248
+
249
+ # replace popped off values
250
+ # note that version is discarded for now
251
+ if quant_method is not None:
252
+ quantization_config[QUANTIZATION_METHOD_NAME] = quant_method
253
+
254
+ return quantization_config
255
+
256
+ def __init__(
257
+ self,
258
+ sparsity_config: Optional[SparsityCompressionConfig] = None,
259
+ quantization_config: Optional[QuantizationConfig] = None,
260
+ ):
261
+ self.sparsity_config = sparsity_config
262
+ self.quantization_config = quantization_config
263
+ self.sparsity_compressor = None
264
+ self.quantization_compressor: Optional[
265
+ Union[BaseQuantizationCompressor, DenseCompressor]
266
+ ] = None
267
+
268
+ if sparsity_config is not None:
269
+ self.sparsity_compressor = BaseCompressor.load_from_registry(
270
+ sparsity_config.format, config=sparsity_config
271
+ )
272
+ if quantization_config is not None:
273
+ self.quantization_compressor = BaseCompressor.load_from_registry(
274
+ quantization_config.format, config=quantization_config
275
+ )
276
+
277
+ # ----- used by hf quantizer ----- #
278
+
279
+ def get_missing_module_keys(self, model: Module) -> List[str]:
280
+ """
281
+ Identifies the expected missing weight keys in the compressed state_dict.
282
+
283
+ When a model undergoes sparsity or quantization compression, certain
284
+ weight tensors may be absent from the checkpoint by virtue of compression.
285
+ This function determines which weight keys are missing based on the
286
+ applied compression techniques.
287
+
288
+ :param model: The PyTorch model to check for missing keys.
289
+ :return: A list of missing keys expected in the compressed state_dict.
290
+ """
291
+ missing_keys = set()
292
+
293
+ # Determine missing keys due to sparsity compression
294
+ if (
295
+ self.sparsity_compressor
296
+ and self.sparsity_config.format != CompressionFormat.dense.value
297
+ ):
298
+ sparse_targets = expand_target_names(
299
+ model=model,
300
+ targets=self.sparsity_config.targets,
301
+ ignore=self.sparsity_config.ignore,
302
+ )
303
+ missing_keys.update(
304
+ merge_names(target, "weight") for target in sparse_targets
305
+ )
306
+
307
+ # Determine missing keys due to pack quantization
308
+ if (
309
+ self.quantization_compressor
310
+ and self.quantization_config.format
311
+ == CompressionFormat.pack_quantized.value
312
+ ):
313
+ for scheme in self.quantization_config.config_groups.values():
314
+ quant_targets = expand_target_names(
315
+ model=model,
316
+ targets=scheme.targets,
317
+ ignore=self.quantization_config.ignore,
318
+ )
319
+ missing_keys.update(
320
+ merge_names(target, "weight") for target in quant_targets
321
+ )
322
+
323
+ return list(missing_keys)
324
+
325
+ def get_unexpected_file_keys(self, model: Module) -> List[str]:
326
+ """
327
+ Identifies extra keys introduced by the compression process in the
328
+ compressed state_dict that are not expected by the model graph.
329
+
330
+ During sparsity or quantization compression, additional metadata or
331
+ auxiliary parameters may be stored in the checkpoint, which do not
332
+ correspond to any parameter in the original model. These keys are
333
+ typically introduced to support the reconstruction of compressed weights.
334
+
335
+ For example, Sparse24Bitmask compression may introduce keys such as
336
+ 'compressed', 'bitmask', and 'shape' in the checkpoint, which are
337
+ not part of the original model parameters.
338
+
339
+ :param model: The PyTorch model to check for unexpected keys.
340
+ :return: A list of extra keys introduced by the compression process
341
+ that are not expected by the model.
342
+ """
343
+
344
+ unexpected_keys = set()
345
+
346
+ # Identify unexpected keys from sparsity compression
347
+ if (
348
+ self.sparsity_compressor
349
+ and self.sparsity_config.format != CompressionFormat.dense.value
350
+ ):
351
+ sparse_targets: Set[str] = expand_target_names(
352
+ model=model,
353
+ targets=self.sparsity_config.targets,
354
+ ignore=self.sparsity_config.ignore,
355
+ )
356
+ unexpected_keys.update(
357
+ merge_names(target, param)
358
+ for target in sparse_targets
359
+ for param in self.sparsity_compressor.compression_param_names
360
+ )
361
+
362
+ # Identify unexpected keys from quantization compression
363
+ if self.quantization_compressor:
364
+ for scheme in self.quantization_config.config_groups.values():
365
+ quant_targets: Set[str] = expand_target_names(
366
+ model=model,
367
+ targets=scheme.targets,
368
+ ignore=self.quantization_config.ignore,
369
+ )
370
+ unexpected_keys.update(
371
+ merge_names(target, param)
372
+ for target in quant_targets
373
+ for param in self.quantization_compressor.compression_param_names
374
+ if param != "weight"
375
+ )
376
+
377
+ return list(unexpected_keys)
378
+
379
+ # ----- model memory compression/decompression pathways ----- #
380
+
381
+ def compress_model(self, model: Module):
382
+ """
383
+ Compress a model in memory. Because the model structure is modified in place,
384
+ this method is more memory-efficient than `self.compress`
385
+
386
+ :param model: model containing parameters to compress
387
+ """
388
+ module_to_scheme = map_module_to_scheme(model)
389
+ sparse_compression_targets: Set[str] = expand_target_names(
390
+ model=model,
391
+ targets=self.sparsity_config.targets if self.sparsity_config else [],
392
+ ignore=self.sparsity_config.ignore if self.sparsity_config else [],
393
+ )
394
+
395
+ for prefix, module in tqdm(model.named_modules(), desc="Compressing model"):
396
+ if prefix in module_to_scheme or prefix in sparse_compression_targets:
397
+ # in the future, support compression on same device
398
+ with align_module_device(module, execution_device="cpu"):
399
+ state_dict = module.state_dict(prefix=f"{prefix}.")
400
+
401
+ # quantization first
402
+ if prefix in module_to_scheme:
403
+ state_dict = self.quantization_compressor.compress(
404
+ state_dict,
405
+ names_to_scheme=module_to_scheme,
406
+ show_progress=False,
407
+ )
408
+
409
+ # sparsity second
410
+ if prefix in sparse_compression_targets:
411
+ state_dict = self.sparsity_compressor.compress(
412
+ state_dict,
413
+ compression_targets=sparse_compression_targets,
414
+ show_progress=False,
415
+ )
416
+
417
+ # remove any existing parameters
418
+ exec_device = get_execution_device(module)
419
+ offload_device = get_offloaded_device(module)
420
+ for name, _ in list(module.named_parameters()):
421
+ delete_offload_parameter(module, name)
422
+
423
+ # replace with compressed parameters
424
+ for name, value in state_dict.items():
425
+ name = name.removeprefix(f"{prefix}.")
426
+ value = value.to(exec_device)
427
+ param = torch.nn.Parameter(value, requires_grad=False)
428
+ register_offload_parameter(module, name, param, offload_device)
429
+
430
+ module.quantization_status = QuantizationStatus.COMPRESSED
431
+
432
+ # TODO: consider sparse compression to also be compression
433
+ if (
434
+ self.quantization_config is not None
435
+ and self.quantization_config.format != CompressionFormat.dense.value
436
+ ):
437
+ self.quantization_config.quantization_status = QuantizationStatus.COMPRESSED
438
+
439
+ def decompress_model(self, model: Module):
440
+ """
441
+ Decompress a model in memory. Because the model structure is modified in place,
442
+ this method does not require loading some compression parameters from disk
443
+
444
+ :param model: model containing parameters to compress
445
+ """
446
+ module_to_scheme = map_module_to_scheme(model)
447
+ sparse_compression_targets: Set[str] = expand_target_names(
448
+ model=model,
449
+ targets=self.sparsity_config.targets if self.sparsity_config else [],
450
+ ignore=self.sparsity_config.ignore if self.sparsity_config else [],
451
+ )
452
+
453
+ for prefix, module in tqdm(model.named_modules(), desc="Decompressing model"):
454
+ if prefix in module_to_scheme or prefix in sparse_compression_targets:
455
+ # in the future, support decompression on same device
456
+ with align_module_device(module, execution_device="cpu"):
457
+ state_dict = module.state_dict(prefix=f"{prefix}.")
458
+
459
+ # sparsity first
460
+ if prefix in sparse_compression_targets:
461
+ # sparse_compression_targets are automatically inferred by this fn
462
+ generator = self.sparsity_compressor.decompress_from_state_dict(
463
+ state_dict,
464
+ )
465
+ # generates (param_path, param_val)
466
+ # of compressed and unused params
467
+ state_dict = {key: value for key, value in generator}
468
+
469
+ # quantization second
470
+ if prefix in module_to_scheme:
471
+ state_dict = (
472
+ self.quantization_compressor.decompress_module_from_state_dict(
473
+ prefix,
474
+ state_dict,
475
+ scheme=module_to_scheme[prefix],
476
+ )
477
+ )
478
+
479
+ # remove any existing parameters
480
+ exec_device = get_execution_device(module)
481
+ offload_device = get_offloaded_device(module)
482
+ for name, _ in list(module.named_parameters()):
483
+ delete_offload_parameter(module, name)
484
+
485
+ # replace with decompressed parameters
486
+ for name, value in state_dict.items():
487
+ name = name.removeprefix(f"{prefix}.")
488
+ value = value.to(exec_device)
489
+ param = torch.nn.Parameter(value, requires_grad=False)
490
+ register_offload_parameter(module, name, param, offload_device)
491
+
492
+ module.quantization_status = QuantizationStatus.FROZEN
493
+
494
+ # ----- state dict compression pathways ----- #
495
+
496
+ def compress(
497
+ self,
498
+ model: Module,
499
+ state_dict: Optional[Dict[str, Tensor]] = None,
500
+ show_progress: bool = False,
501
+ ) -> Dict[str, Tensor]:
502
+ """
503
+ Compresses a dense state dict or model with sparsity and/or quantization
504
+
505
+ :param model: uncompressed model to compress
506
+ :param state_dict: optional uncompressed state_dict to insert into model
507
+ :return: compressed state dict
508
+ """
509
+
510
+ if state_dict is None:
511
+ state_dict = model.state_dict()
512
+
513
+ if self.quantization_compressor is not None:
514
+ module_to_scheme = map_module_to_scheme(model)
515
+ state_dict = self.quantization_compressor.compress(
516
+ state_dict,
517
+ names_to_scheme=module_to_scheme,
518
+ show_progress=show_progress,
519
+ )
520
+
521
+ # TODO: consider sparse compression to also be compression
522
+ if self.quantization_config.format != CompressionFormat.dense.value:
523
+ self.quantization_config.quantization_status = (
524
+ QuantizationStatus.COMPRESSED
525
+ )
526
+
527
+ if self.sparsity_compressor is not None:
528
+ sparse_compression_targets: Set[str] = expand_target_names(
529
+ model=model,
530
+ targets=self.sparsity_config.targets,
531
+ ignore=self.sparsity_config.ignore,
532
+ )
533
+ state_dict = self.sparsity_compressor.compress(
534
+ state_dict,
535
+ compression_targets=sparse_compression_targets,
536
+ show_progress=show_progress,
537
+ )
538
+
539
+ # HACK: Override the dtype_byte_size function in transformers to
540
+ # support float8 types. Fix is posted upstream
541
+ # https://github.com/huggingface/transformers/pull/30488
542
+ transformers.modeling_utils.dtype_byte_size = new_dtype_byte_size
543
+
544
+ return state_dict
545
+
546
+ # ----- disk decompression pathways ----- #
547
+
548
+ def decompress(self, model_path: str, model: Module):
549
+ """
550
+ Overwrites the weights in model with weights decompressed from model_path
551
+
552
+ :param model_path: path to compressed weights
553
+ :param model: pytorch model to load decompressed weights into
554
+
555
+ Note: decompress makes use of both _replace_sparsity_weights and _replace_weights
556
+ The variations in these methods are a result of the subtle variations between the sparsity
557
+ and quantization compressors. Specifically, quantization compressors return not just the
558
+ decompressed weight, but the quantization parameters (e.g scales, zero_point) whereas sparsity
559
+ compressors only return the decompressed weight.
560
+
561
+ """
562
+ model_path = get_safetensors_folder(model_path)
563
+ sparse_decompressed = False
564
+
565
+ if (
566
+ self.sparsity_compressor is not None
567
+ and self.sparsity_config.format != CompressionFormat.dense.value
568
+ ):
569
+ params_to_ignore = None
570
+ if self.quantization_compressor is not None:
571
+ params_to_ignore = self.quantization_compressor.compression_param_names
572
+ # Sparse decompression is applied on the model_path
573
+ # The compressor will try and load any quantization parameters as well
574
+ # params_to_skip_load will skip over quantization params from being loaded
575
+ dense_gen = self.sparsity_compressor.decompress(
576
+ model_path, params_to_skip_load=params_to_ignore
577
+ )
578
+ self._replace_sparsity_weights(dense_gen, model)
579
+ setattr(model, SPARSITY_CONFIG_NAME, self.sparsity_compressor.config)
580
+ sparse_decompressed = True
581
+
582
+ if self.quantization_compressor is not None:
583
+ # Temporarily set quantization status to FROZEN to prevent
584
+ # quantization during apply_quantization_config. This ensures
585
+ # that the dtypes of the weights are not unintentionally updated.
586
+ # The status is restored after quantization params are loaded.
587
+
588
+ with override_quantization_status(
589
+ self.quantization_config, QuantizationStatus.FROZEN
590
+ ):
591
+
592
+ names_to_scheme = apply_quantization_config(
593
+ model, self.quantization_config
594
+ )
595
+ # Load activation scales/zp or any other quantization parameters
596
+ # Conditionally load the weight quantization parameters if we have a dense compressor
597
+ # Or if a sparsity compressor has already been applied
598
+ load_pretrained_quantization_parameters(
599
+ model,
600
+ model_path,
601
+ # TODO: all weight quantization params will be moved to the compressor in a follow-up
602
+ # including initialization
603
+ load_weight_quantization=(
604
+ sparse_decompressed
605
+ or isinstance(self.quantization_compressor, DenseCompressor)
606
+ ),
607
+ )
608
+
609
+ model_path_or_state_dict = (
610
+ model.state_dict() if sparse_decompressed else model_path
611
+ )
612
+
613
+ dense_gen = self.quantization_compressor.decompress(
614
+ model_path_or_state_dict, names_to_scheme=names_to_scheme
615
+ )
616
+ # TODO: all weight quantization params will be moved to the compressor
617
+ # to prevent duplicate parameter updates in update_parameter_data
618
+ self._replace_weights(dense_gen, model)
619
+
620
+ def freeze_quantization_status(module):
621
+ module.quantization_status = QuantizationStatus.FROZEN
622
+
623
+ model.apply(freeze_quantization_status)
624
+ setattr(model, QUANTIZATION_CONFIG_NAME, self.quantization_config)
625
+
626
+ def update_config(self, save_directory: str):
627
+ """
628
+ Update the model config located at save_directory with compression configs
629
+ for sparsity and/or quantization
630
+
631
+ :param save_directory: path to a folder containing a HF model config
632
+ """
633
+ if self.quantization_config is None and self.sparsity_config is None:
634
+ return
635
+
636
+ config_file_path = os.path.join(save_directory, CONFIG_NAME)
637
+ if not os.path.exists(config_file_path):
638
+ _LOGGER.warning(
639
+ f"Could not find a valid model config file in "
640
+ f"{save_directory}. Compression config will not be saved."
641
+ )
642
+ return
643
+
644
+ with open(config_file_path, "r") as config_file:
645
+ config_data = json.load(config_file)
646
+
647
+ # required metadata whenever a quantization or sparsity config is present
648
+ # overwrite previous config and version if already existing
649
+ config_data[QUANTIZATION_CONFIG_NAME] = {}
650
+ config_data[QUANTIZATION_CONFIG_NAME][
651
+ COMPRESSION_VERSION_NAME
652
+ ] = compressed_tensors.__version__
653
+ if self.quantization_config is not None:
654
+ self.quantization_config.quant_method = DEFAULT_QUANTIZATION_METHOD
655
+ else:
656
+ config_data[QUANTIZATION_CONFIG_NAME][
657
+ QUANTIZATION_METHOD_NAME
658
+ ] = DEFAULT_QUANTIZATION_METHOD
659
+
660
+ # quantization and sparsity configs
661
+ if self.quantization_config is not None:
662
+ quant_config_data = self.quantization_config.model_dump()
663
+ config_data[QUANTIZATION_CONFIG_NAME] = quant_config_data
664
+ if self.sparsity_config is not None:
665
+ sparsity_config_data = self.sparsity_config.model_dump()
666
+ config_data[QUANTIZATION_CONFIG_NAME][
667
+ SPARSITY_CONFIG_NAME
668
+ ] = sparsity_config_data
669
+
670
+ with open(config_file_path, "w") as config_file:
671
+ json.dump(config_data, config_file, indent=2, sort_keys=True)
672
+
673
+ def _replace_sparsity_weights(self, dense_weight_generator, model: Module):
674
+ """
675
+ Replace the weights of the model with the
676
+ provided dense weights.
677
+
678
+ This method iterates over the dense_weight_generator and
679
+ updates the corresponding weights in the model. If a parameter
680
+ name does not exist in the model, it will be skipped.
681
+
682
+ :param dense_weight_generator (generator): A generator that yields
683
+ tuples of (name, data), where 'name' is the parameter name and
684
+ 'data' is the updated param data
685
+ :param model: The model whose weights are to be updated.
686
+ """
687
+ for name, data in tqdm(dense_weight_generator, desc="Decompressing model"):
688
+
689
+ split_name = name.split(".")
690
+ prefix, param_name = ".".join(split_name[:-1]), split_name[-1]
691
+ module = operator.attrgetter(prefix)(model)
692
+
693
+ params_device = next(module.parameters()).device
694
+ device = "cpu" if has_offloaded_params(module) else params_device
695
+ delattr(module, param_name)
696
+ requires_grad = data.dtype in (torch.float16, torch.float32, torch.bfloat16)
697
+ param = torch.nn.Parameter(data.to(device), requires_grad=requires_grad)
698
+ register_offload_parameter(module, param_name, param)
699
+
700
+ def _replace_weights(self, dense_weight_generator, model: Module):
701
+ """
702
+ Replace the weights of the model with the
703
+ provided dense weights.
704
+
705
+ This method iterates over the dense_weight_generator and
706
+ updates the corresponding weights in the model. If a parameter
707
+ name does not exist in the model, it will be skipped.
708
+
709
+ :param dense_weight_generator (generator): A generator that yields
710
+ tuples of (name, data), where 'name' is the parameter name and
711
+ 'data' is the updated param data
712
+ :param model: The model whose weights are to be updated.
713
+ """
714
+
715
+ for mod_path, data in tqdm(dense_weight_generator, desc="Decompressing model"):
716
+ module = operator.attrgetter(mod_path)(model)
717
+
718
+ params_device = next(module.parameters()).device
719
+ device = "cpu" if has_offloaded_params(module) else params_device
720
+
721
+ for param_name, param_data in data.items():
722
+ if hasattr(module, param_name):
723
+ # If compressed, will have an incorrect dtype for transformers >4.49
724
+ # TODO: we can also just skip initialization of scales/zp if in decompression in init
725
+ # to be consistent with loading which happens later as well
726
+ # however, update_data does a good shape check - should be moved to the compressor
727
+ if param_name == "weight":
728
+ delattr(module, param_name)
729
+ requires_grad = param_data.dtype in (
730
+ torch.float16,
731
+ torch.float32,
732
+ torch.bfloat16,
733
+ )
734
+ param = torch.nn.Parameter(
735
+ param_data.to(device), requires_grad=requires_grad
736
+ )
737
+ register_offload_parameter(module, param_name, param)
738
+ else:
739
+ # Should already be registered to the correct device for
740
+ # for scales/zero-points
741
+ update_parameter_data(module, param_data, param_name)
742
+
743
+
744
+ def map_module_to_scheme(model: Module) -> Dict[str, QuantizationScheme]:
745
+ """
746
+ Returns a dictionary which maps quantized module names to their quantization schemes
747
+ """
748
+ return {
749
+ fix_fsdp_module_name(name): module.quantization_scheme
750
+ for name, module in iter_named_leaf_modules(model)
751
+ if is_module_quantized(module)
752
+ }
753
+
754
+
755
+ # HACK: Override the dtype_byte_size function in transformers to support float8 types
756
+ # Fix is posted upstream https://github.com/huggingface/transformers/pull/30488
757
+ def new_dtype_byte_size(dtype):
758
+ if dtype == torch.bool:
759
+ return 1 / 8
760
+ bit_search = re.search(r"[^\d](\d+)_?", str(dtype))
761
+ if bit_search is None:
762
+ raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
763
+ bit_size = int(bit_search.groups()[0])
764
+ return bit_size // 8
765
+
766
+
767
+ @contextmanager
768
+ def override_quantization_status(
769
+ config: QuantizationConfig, status: QuantizationStatus
770
+ ):
771
+ """
772
+ Within this context, the quantization status will be set to the
773
+ supplied status. After the context exits, the original status
774
+ will be restored.
775
+
776
+ :param config: the quantization config to override
777
+ :param status: the status to temporarily set
778
+ """
779
+ original_status = config.quantization_status
780
+ config.quantization_status = status
781
+ try:
782
+ yield
783
+ finally:
784
+ config.quantization_status = original_status
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # flake8: noqa
15
+
16
+ from .base import *
17
+ from .naive_quantized import *
18
+ from .nvfp4_quantized import *
19
+ from .pack_quantized import *
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (339 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/base.cpython-312.pyc ADDED
Binary file (10.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/naive_quantized.cpython-312.pyc ADDED
Binary file (5.87 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/nvfp4_quantized.cpython-312.pyc ADDED
Binary file (7.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/__pycache__/pack_quantized.cpython-312.pyc ADDED
Binary file (12.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/base.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Generator, Tuple, Union
18
+
19
+ import torch
20
+ from compressed_tensors.compressors.base import BaseCompressor
21
+ from compressed_tensors.quantization import QuantizationScheme, QuantizationStrategy
22
+ from compressed_tensors.utils import (
23
+ get_nested_mappings_from_state_dict,
24
+ get_nested_weight_mappings,
25
+ merge_names,
26
+ )
27
+ from compressed_tensors.utils.safetensors_load import match_param_name
28
+ from safetensors import safe_open
29
+ from torch import Tensor
30
+ from tqdm import tqdm
31
+
32
+
33
+ _LOGGER: logging.Logger = logging.getLogger(__name__)
34
+
35
+ __all__ = ["BaseQuantizationCompressor"]
36
+
37
+
38
+ class BaseQuantizationCompressor(BaseCompressor):
39
+ """
40
+ Base class representing a quant compression algorithm. Each child class should
41
+ implement compression_param_info, compress_weight and decompress_weight.
42
+
43
+ Compressors support compressing/decompressing a full module state dict or a single
44
+ quantized PyTorch leaf module.
45
+
46
+ Model Load Lifecycle (run_compressed=False):
47
+ - ModelCompressor.decompress()
48
+ - apply_quantization_config()
49
+ - BaseQuantizationCompressor.decompress()
50
+ - BaseQuantizationCompressor.decompress_weight()
51
+
52
+ Model Save Lifecycle:
53
+ - ModelCompressor.compress()
54
+ - BaseQuantizationCompressor.compress()
55
+ - BaseQuantizationCompressor.compress_weight()
56
+
57
+ Module Lifecycle (run_compressed=True):
58
+ - apply_quantization_config()
59
+ - compressed_module = CompressedLinear(module)
60
+ - initialize_module_for_quantization()
61
+ - BaseQuantizationCompressor.compression_param_info()
62
+ - register_parameters()
63
+ - compressed_module.forward()
64
+ - compressed_module.decompress()
65
+
66
+
67
+ :param config: config specifying compression parameters
68
+ """
69
+
70
+ def compress(
71
+ self,
72
+ model_state: Dict[str, Tensor],
73
+ names_to_scheme: Dict[str, QuantizationScheme],
74
+ show_progress: bool = False,
75
+ **kwargs,
76
+ ) -> Dict[str, Tensor]:
77
+ """
78
+ Compresses a dense state dict
79
+
80
+ :param model_state: state dict of uncompressed model
81
+ :param names_to_scheme: quantization args for each quantized weight, needed for
82
+ quantize function to calculate bit depth
83
+ :param show_progress: whether to show tqdm progress
84
+ :return: compressed state dict
85
+ """
86
+ uncompressed_names = list(model_state.keys())
87
+ compressed_dict = {}
88
+ save_device = "cpu"
89
+
90
+ # compress values
91
+ desc = "Compressing with quantization"
92
+ for name in tqdm(uncompressed_names, desc=desc, disable=(not show_progress)):
93
+ value = model_state[name]
94
+
95
+ # compress weights
96
+ if name.endswith("weight"):
97
+ prefix = name.removesuffix("weight")
98
+
99
+ # gather qparams
100
+ scale = model_state.get(prefix + "weight_scale", None)
101
+ g_idx = model_state.get(prefix + "weight_g_idx", None)
102
+ zp = model_state.get(prefix + "weight_zero_point", None)
103
+ global_scale = model_state.get(prefix + "weight_global_scale", None)
104
+
105
+ # is scale does not exist, then weight cannot be compressed
106
+ if scale is None:
107
+ compressed_dict[name] = value.to(save_device)
108
+ continue
109
+
110
+ # compress values on cpu (memory movement too expensive)
111
+ module_path = prefix[:-1] if prefix.endswith(".") else prefix
112
+ quant_args = names_to_scheme[module_path].weights
113
+ compressed_values = self.compress_weight(
114
+ weight=value,
115
+ scale=scale,
116
+ zero_point=zp,
117
+ global_scale=global_scale,
118
+ g_idx=g_idx,
119
+ quantization_args=quant_args,
120
+ device="cpu",
121
+ )
122
+
123
+ # update state dict
124
+ for key, value in compressed_values.items():
125
+ compressed_dict[prefix + key] = value.to(save_device)
126
+
127
+ else:
128
+ # omit saving zero points for symmetric or packed quantization
129
+ if name.endswith("zero_point") and self._skip_zp(name, names_to_scheme):
130
+ continue
131
+
132
+ # omit saving for g_idx if uninitialized
133
+ # TODO: does this case actually occur?
134
+ elif name.endswith("g_idx") and torch.any(value <= -1):
135
+ continue
136
+
137
+ compressed_dict[name] = value.to(save_device)
138
+
139
+ return compressed_dict
140
+
141
+ def _skip_zp(
142
+ self, name: str, names_to_scheme: Dict[str, QuantizationScheme]
143
+ ) -> bool:
144
+ from compressed_tensors.compressors import PackedQuantizationCompressor
145
+
146
+ module_name, zp_name = name.rsplit(".", 1) if "." in name else ("", name)
147
+ scheme = names_to_scheme[module_name]
148
+
149
+ if zp_name == "weight_zero_point":
150
+ args = scheme.weights
151
+ if zp_name == "input_zero_point":
152
+ args = scheme.input_activations
153
+ if zp_name == "output_zero_point":
154
+ args = scheme.output_activations
155
+
156
+ symmetric = args.symmetric
157
+ packable_strategies = [
158
+ QuantizationStrategy.GROUP.value,
159
+ QuantizationStrategy.CHANNEL.value,
160
+ ]
161
+ packed = (
162
+ isinstance(self, PackedQuantizationCompressor)
163
+ and args.strategy in packable_strategies
164
+ )
165
+
166
+ return symmetric or packed
167
+
168
+ def decompress(
169
+ self,
170
+ path_to_model_or_tensors: Union[str, Path, Dict[str, Any]],
171
+ names_to_scheme: Dict[str, QuantizationScheme],
172
+ device: str = "cpu",
173
+ ) -> Generator[Tuple[str, Tensor], None, None]:
174
+ """
175
+ Reads a compressed state dict located at path_to_model_or_tensors
176
+ and returns a generator for sequentially decompressing back to a
177
+ dense state dict
178
+ :param path_to_model_or_tensors: path to compressed safetensors model (directory
179
+ with one or more safetensors files) or compressed tensors file
180
+ :param names_to_scheme: quantization scheme for each quantized weight
181
+ :param device: optional device to load intermediate weights into (must be `str`,
182
+ not `torch.device`)
183
+ :return: compressed state dict
184
+ """
185
+ if isinstance(path_to_model_or_tensors, (str, Path)):
186
+ yield from self._decompress_from_path(
187
+ path_to_model_or_tensors, names_to_scheme, device
188
+ )
189
+
190
+ else:
191
+ yield from self.decompress_from_state_dict(
192
+ path_to_model_or_tensors, names_to_scheme
193
+ )
194
+
195
+ def _decompress_from_path(
196
+ self,
197
+ path_to_model: Union[str, Path, Dict[str, Any]],
198
+ names_to_scheme: Dict[str, QuantizationScheme],
199
+ device: str,
200
+ ):
201
+ weight_mappings = get_nested_weight_mappings(
202
+ path_to_model, self.compression_param_names
203
+ )
204
+ for module_path in weight_mappings.keys():
205
+ weight_data = {}
206
+ for param_name, safe_path in weight_mappings[module_path].items():
207
+ full_name = merge_names(module_path, param_name)
208
+ with safe_open(safe_path, framework="pt", device=device) as f:
209
+ weight_data[param_name] = f.get_tensor(full_name)
210
+ if "weight_scale" in weight_data:
211
+ quant_args = names_to_scheme[module_path].weights
212
+ decompressed = self.decompress_weight(
213
+ compressed_data=weight_data, quantization_args=quant_args
214
+ )
215
+ weight_data["weight"] = decompressed
216
+ yield module_path, weight_data
217
+
218
+ def decompress_from_state_dict(
219
+ self,
220
+ state_dict: Dict[str, torch.Tensor],
221
+ names_to_scheme: Dict[str, QuantizationScheme],
222
+ ) -> Generator[Tuple[str, Dict[str, torch.Tensor]], None, None]:
223
+ weight_mappings = get_nested_mappings_from_state_dict(
224
+ state_dict, self.compression_param_names
225
+ )
226
+ for module_path in weight_mappings.keys():
227
+ weight_data = weight_mappings[module_path].copy()
228
+
229
+ if "weight_scale" in weight_data:
230
+ quant_args = names_to_scheme[module_path].weights
231
+ decompressed = self.decompress_weight(
232
+ compressed_data=weight_data, quantization_args=quant_args
233
+ )
234
+ weight_data["weight"] = decompressed
235
+ yield module_path, weight_data
236
+
237
+ def decompress_module_from_state_dict(
238
+ self,
239
+ prefix: str,
240
+ state_dict: Dict[str, torch.Tensor],
241
+ scheme: QuantizationScheme,
242
+ ) -> Dict[str, torch.Tensor]:
243
+ """
244
+ Only used by in-memory decompression pathways to decompress the parameters of
245
+ one module
246
+
247
+ :param prefix: prefix of state_dict, typically the path to the module
248
+ :param state_dict: state dict containing module parameter values
249
+ :param scheme: quantization scheme of module to decompress
250
+ :return: state dict with weight decompressed if applicable
251
+ """
252
+ state_dict = {
253
+ key.removeprefix(f"{prefix}."): value for key, value in state_dict.items()
254
+ }
255
+
256
+ if "weight_scale" in state_dict:
257
+ state_dict["weight"] = self.decompress_weight(
258
+ compressed_data=state_dict, quantization_args=scheme.weights
259
+ )
260
+
261
+ state_dict = {f"{prefix}.{key}": value for key, value in state_dict.items()}
262
+
263
+ return state_dict
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/naive_quantized.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict, Optional, Tuple
16
+
17
+ import torch
18
+ from compressed_tensors.compressors.base import BaseCompressor
19
+ from compressed_tensors.compressors.quantized_compressors.base import (
20
+ BaseQuantizationCompressor,
21
+ )
22
+ from compressed_tensors.config import CompressionFormat
23
+ from compressed_tensors.quantization import QuantizationArgs
24
+ from compressed_tensors.quantization.lifecycle.forward import dequantize, quantize
25
+ from compressed_tensors.quantization.utils import can_quantize
26
+ from torch import Tensor
27
+
28
+
29
+ __all__ = [
30
+ "NaiveQuantizationCompressor",
31
+ "IntQuantizationCompressor",
32
+ "FloatQuantizationCompressor",
33
+ ]
34
+
35
+
36
+ @BaseCompressor.register(name=CompressionFormat.naive_quantized.value)
37
+ class NaiveQuantizationCompressor(BaseQuantizationCompressor):
38
+ """
39
+ Implements naive compression for quantized models. Weight of each
40
+ quantized layer is converted from its original float type to the closest Pytorch
41
+ type to the type specified by the layer's QuantizationArgs.
42
+ """
43
+
44
+ @property
45
+ def compression_param_names(self) -> Tuple[str]:
46
+ """
47
+ Returns a tuple of compression parameter names introduced by
48
+ the compressor during compression
49
+ """
50
+ return (
51
+ "weight",
52
+ "weight_scale",
53
+ "weight_zero_point",
54
+ "weight_g_idx",
55
+ )
56
+
57
+ def compression_param_info(
58
+ self,
59
+ weight_shape: torch.Size,
60
+ quantization_args: Optional[QuantizationArgs] = None,
61
+ ) -> Dict[str, Tuple[torch.Size, torch.dtype]]:
62
+ """
63
+ Creates a dictionary of expected shapes and dtypes for each compression
64
+ parameter used by the compressor
65
+
66
+ :param weight_shape: uncompressed weight shape
67
+ :param quantization_args: quantization parameters for the weight
68
+ :return: dictionary mapping compressed parameter names to shape and dtype
69
+ """
70
+ dtype = quantization_args.pytorch_dtype()
71
+ return {"weight": (weight_shape, dtype)}
72
+
73
+ def compress_weight(
74
+ self,
75
+ weight: Tensor,
76
+ scale: Tensor,
77
+ quantization_args: QuantizationArgs,
78
+ zero_point: Optional[Tensor] = None,
79
+ g_idx: Optional[torch.Tensor] = None,
80
+ device: Optional[torch.device] = None,
81
+ global_scale: Optional[torch.Tensor] = None,
82
+ ) -> Dict[str, torch.Tensor]:
83
+ """
84
+ Compresses a single uncompressed weight
85
+
86
+ :param weight: uncompressed weight tensor
87
+ :param scale: quantization scale for weight
88
+ :param quantization_args: quantization parameters for weight
89
+ :param zero_point: quantization zero point for weight
90
+ :param g_idx: optional mapping from column index to group index
91
+ :param device: optional device to move compressed output to
92
+ :return: dictionary of compressed weight data
93
+ """
94
+ if global_scale is not None:
95
+ raise ValueError(
96
+ "global_scale is not supported for the NaiveQuantizationCompressor"
97
+ )
98
+
99
+ if can_quantize(weight, quantization_args):
100
+ quantized_weight = quantize(
101
+ x=weight,
102
+ scale=scale,
103
+ zero_point=zero_point,
104
+ g_idx=g_idx,
105
+ args=quantization_args,
106
+ dtype=quantization_args.pytorch_dtype(),
107
+ )
108
+ else:
109
+ quantized_weight = weight
110
+
111
+ if device is not None:
112
+ quantized_weight = quantized_weight.to(device)
113
+
114
+ return {"weight": quantized_weight}
115
+
116
+ def decompress_weight(
117
+ self,
118
+ compressed_data: Dict[str, Tensor],
119
+ quantization_args: Optional[QuantizationArgs] = None,
120
+ ) -> torch.Tensor:
121
+ """
122
+ Decompresses a single compressed weight
123
+
124
+ :param compressed_data: dictionary of data needed for decompression
125
+ :param quantization_args: quantization parameters for the weight
126
+ :return: tensor of the decompressed weight
127
+ """
128
+ weight = compressed_data["weight"]
129
+ scale = compressed_data["weight_scale"]
130
+ zero_point = compressed_data.get("weight_zero_point", None)
131
+ g_idx = compressed_data.get("weight_g_idx", None)
132
+ decompressed_weight = dequantize(
133
+ x_q=weight, scale=scale, zero_point=zero_point, g_idx=g_idx
134
+ )
135
+
136
+ return decompressed_weight
137
+
138
+
139
+ @BaseCompressor.register(name=CompressionFormat.int_quantized.value)
140
+ class IntQuantizationCompressor(NaiveQuantizationCompressor):
141
+ """
142
+ Alias for integer quantized models
143
+ """
144
+
145
+ pass
146
+
147
+
148
+ @BaseCompressor.register(name=CompressionFormat.float_quantized.value)
149
+ class FloatQuantizationCompressor(NaiveQuantizationCompressor):
150
+ """
151
+ Alias for fp quantized models
152
+ """
153
+
154
+ pass
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/nvfp4_quantized.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Dict, Optional, Tuple
17
+
18
+ import numpy
19
+ import torch
20
+ from compressed_tensors.compressors.base import BaseCompressor
21
+ from compressed_tensors.compressors.quantized_compressors.base import (
22
+ BaseQuantizationCompressor,
23
+ )
24
+ from compressed_tensors.config import CompressionFormat
25
+ from compressed_tensors.quantization import QuantizationArgs
26
+ from compressed_tensors.quantization.lifecycle.forward import dequantize, quantize
27
+ from torch import Tensor
28
+
29
+
30
+ __all__ = ["pack_fp4_to_uint8", "unpack_fp4_from_uint8"]
31
+
32
+ FLOAT_TO_E2M1 = [
33
+ 0.0,
34
+ 0.5,
35
+ 1.0,
36
+ 1.5,
37
+ 2.0,
38
+ 3.0,
39
+ 4.0,
40
+ 6.0,
41
+ ]
42
+
43
+
44
+ @BaseCompressor.register(name=CompressionFormat.nvfp4_pack_quantized.value)
45
+ class NVFP4PackedCompressor(BaseQuantizationCompressor):
46
+ """
47
+ Implements compression of FP4 values. Weights of each quantized layer
48
+ are packed into uint8. Only supports symmetric weight compression for now.
49
+ """
50
+
51
+ @property
52
+ def compression_param_names(self) -> Tuple[str]:
53
+ """
54
+ Returns a tuple of compression parameter names introduced by
55
+ the compressor during compression
56
+ """
57
+ return (
58
+ "weight_packed",
59
+ "weight_scale",
60
+ "weight_zero_point",
61
+ "weight_global_scale",
62
+ )
63
+
64
+ def compress_weight(
65
+ self,
66
+ weight: Tensor,
67
+ scale: Tensor,
68
+ global_scale: Tensor,
69
+ quantization_args: QuantizationArgs,
70
+ device: Optional[torch.device] = None,
71
+ zero_point: Optional[torch.Tensor] = None,
72
+ g_idx: Optional[torch.Tensor] = None,
73
+ ) -> Dict[str, torch.Tensor]:
74
+
75
+ quantized_weight = quantize(
76
+ x=weight,
77
+ scale=scale,
78
+ global_scale=global_scale,
79
+ zero_point=zero_point,
80
+ args=quantization_args,
81
+ )
82
+ compressed_dict = {}
83
+ weight_packed = pack_fp4_to_uint8(quantized_weight)
84
+ if device is not None:
85
+ weight_packed = weight_packed.to(device)
86
+ compressed_dict["weight_packed"] = weight_packed
87
+ return compressed_dict
88
+
89
+ def decompress_weight(
90
+ self,
91
+ compressed_data: Dict[str, Tensor],
92
+ quantization_args: Optional[QuantizationArgs] = None,
93
+ ) -> torch.Tensor:
94
+
95
+ weight = compressed_data["weight_packed"]
96
+ scale = compressed_data["weight_scale"]
97
+ global_scale = compressed_data["weight_global_scale"]
98
+ m, n = weight.shape
99
+ # TODO: use a user provided dequant dtype
100
+ unpacked = unpack_fp4_from_uint8(weight, m, n * 2)
101
+ decompressed_weight = dequantize(
102
+ x_q=unpacked, scale=scale, global_scale=global_scale, dtype=unpacked.dtype
103
+ )
104
+
105
+ return decompressed_weight
106
+
107
+
108
+ def pack_fp4_to_uint8(x: torch.Tensor) -> torch.Tensor:
109
+ """
110
+ Packs a tensor with values in the fp4 range into uint8.
111
+ As there are 16 valid fp4 values, two fp4 values can be
112
+ packed into one uint8. Each fp4 value is mapped to its
113
+ particular index (e.g. 0.5 is mapped to index 1, 6.0 is mapped
114
+ to index 7) which is then represented using 4 bits. Consecutive
115
+ pairs of 4 bits are then packed into an uint8.
116
+
117
+ :param x: tensor to pack
118
+ returns: a packed tensor in uint8
119
+ """
120
+
121
+ m, n = x.shape
122
+ device = x.device
123
+
124
+ # Create lookup table for FP4 values to indices
125
+ # Map the absolute values to 0-7 indices
126
+ kE2M1 = torch.tensor(FLOAT_TO_E2M1, device=device, dtype=x.dtype)
127
+
128
+ # Find closest valid FP4 value index for each element
129
+ abs_x = torch.abs(x)
130
+ abs_indices = torch.zeros_like(abs_x, dtype=torch.long)
131
+ for i, val in enumerate(kE2M1):
132
+ abs_indices = torch.where(torch.isclose(abs_x, val), i, abs_indices)
133
+
134
+ # Apply sign bit (bit 3) to get final 4-bit representation
135
+ indices = abs_indices + (torch.signbit(x) << 3).to(torch.long)
136
+
137
+ # Reshape to prepare for packing pairs of values
138
+ indices = indices.reshape(-1)
139
+
140
+ # Handle odd length by padding if necessary
141
+ if indices.numel() % 2 != 0:
142
+ indices = torch.cat([indices, torch.zeros(1, dtype=torch.long, device=device)])
143
+
144
+ # Reshape to pair consecutive elements
145
+ indices = indices.reshape(-1, 2)
146
+
147
+ # Pack pairs of 4-bit values into 8-bit values
148
+ packed = (indices[:, 0] | (indices[:, 1] << 4)).to(torch.uint8)
149
+
150
+ return packed.reshape(m, n // 2)
151
+
152
+
153
+ kE2M1ToFloat = torch.tensor(
154
+ [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=torch.float32
155
+ )
156
+
157
+ # reference: : https://github.com/vllm-project/vllm/pull/16362
158
+ def unpack_fp4_from_uint8(
159
+ a: torch.Tensor, m: int, n: int, dtype: Optional[torch.dtype] = torch.bfloat16
160
+ ) -> torch.Tensor:
161
+ """
162
+ Unpacks uint8 values into fp4. Each uint8 consists of two fp4 values
163
+ (i.e. first four bits correspond to one fp4 value, last four corresond to a consecutive
164
+ fp4 value). The bits represent an index, which are mapped to an fp4 value.
165
+
166
+ :param a: tensor to unpack
167
+ :param m: original dim 0 size of the unpacked tensor
168
+ :param n: original dim 1 size of the unpacked tensor
169
+ :param dtype: dense dtype to cast the unpacked tensor to
170
+ """
171
+ assert a.dtype == torch.uint8
172
+
173
+ # Vectorized nibble processing
174
+ a_flat = a.flatten()
175
+ high = (a_flat & 0xF0) >> 4 # Upper nibbles
176
+ low = a_flat & 0x0F # Lower nibbles
177
+
178
+ # Combine nibbles for batch processing
179
+ combined = torch.stack((low, high), dim=1).flatten()
180
+
181
+ # Vectorized sign and magnitude extraction
182
+ signs = (combined & 0x08).to(torch.bool) # Sign bits
183
+ abs_vals = (combined & 0x07).to(torch.long) # Magnitude indices
184
+
185
+ # Device-aware lookup and sign application
186
+ kE2M1 = kE2M1ToFloat.to(device=a.device)
187
+ values = kE2M1[abs_vals] * torch.where(signs, -1.0, 1.0)
188
+
189
+ # Reshape to final form
190
+ return values.reshape(m, n).to(dtype=dtype)
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/quantized_compressors/pack_quantized.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ from typing import Dict, Literal, Optional, Tuple, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ from compressed_tensors.compressors.base import BaseCompressor
20
+ from compressed_tensors.compressors.quantized_compressors.base import (
21
+ BaseQuantizationCompressor,
22
+ )
23
+ from compressed_tensors.config import CompressionFormat
24
+ from compressed_tensors.quantization import QuantizationArgs, QuantizationStrategy
25
+ from compressed_tensors.quantization.lifecycle.forward import dequantize, quantize
26
+ from compressed_tensors.quantization.utils import can_quantize
27
+ from torch import Tensor
28
+
29
+
30
+ __all__ = ["PackedQuantizationCompressor", "pack_to_int32", "unpack_from_int32"]
31
+
32
+
33
+ @BaseCompressor.register(name=CompressionFormat.pack_quantized.value)
34
+ class PackedQuantizationCompressor(BaseQuantizationCompressor):
35
+ """
36
+ Compresses a quantized model by packing every eight 4-bit weights into an int32
37
+ """
38
+
39
+ @property
40
+ def compression_param_names(self) -> Tuple[str]:
41
+ """
42
+ Returns a tuple of compression parameter names introduced by
43
+ the compressor during compression
44
+ """
45
+ return (
46
+ "weight_packed",
47
+ "weight_scale",
48
+ "weight_zero_point",
49
+ "weight_g_idx",
50
+ "weight_shape",
51
+ )
52
+
53
+ def compression_param_info(
54
+ self,
55
+ weight_shape: torch.Size,
56
+ quantization_args: Optional[QuantizationArgs] = None,
57
+ ) -> Dict[str, Tuple[torch.Size, torch.dtype]]:
58
+ """
59
+ Creates a dictionary of expected shapes and dtypes for each compression
60
+ parameter used by the compressor
61
+
62
+ :param weight_shape: uncompressed weight shape
63
+ :param quantization_args: quantization parameters for the weight
64
+ :return: dictionary mapping compressed parameter names to shape and dtype
65
+ """
66
+ pack_factor = 32 // quantization_args.num_bits
67
+ packed_size = math.ceil(weight_shape[1] / pack_factor)
68
+ packed_size_zp = math.ceil(weight_shape[0] / pack_factor)
69
+ output = {
70
+ "weight_packed": (torch.Size((weight_shape[0], packed_size)), torch.int32),
71
+ "weight_shape": (torch.Size((2,)), torch.int32),
72
+ }
73
+ if not quantization_args.symmetric and quantization_args.strategy in [
74
+ QuantizationStrategy.GROUP.value,
75
+ QuantizationStrategy.CHANNEL.value,
76
+ ]:
77
+ zp_factor = (
78
+ quantization_args.group_size
79
+ if quantization_args.strategy == QuantizationStrategy.GROUP.value
80
+ else weight_shape[-1]
81
+ )
82
+
83
+ output["weight_zero_point"] = (
84
+ torch.Size((packed_size_zp, weight_shape[-1] // zp_factor)),
85
+ torch.int32,
86
+ )
87
+ return output
88
+
89
+ def compress_weight(
90
+ self,
91
+ weight: Tensor,
92
+ scale: Tensor,
93
+ quantization_args: QuantizationArgs,
94
+ zero_point: Optional[Tensor] = None,
95
+ g_idx: Optional[torch.Tensor] = None,
96
+ device: Optional[torch.device] = None,
97
+ global_scale: Optional[torch.Tensor] = None,
98
+ ) -> Dict[str, torch.Tensor]:
99
+ """
100
+ Compresses a single uncompressed weight
101
+
102
+ :param weight: uncompressed weight tensor
103
+ :param scale: quantization scale for weight
104
+ :param quantization_args: quantization parameters for weight
105
+ :param zero_point: quantization zero point for weight
106
+ :param g_idx: optional mapping from column index to group index
107
+ :param device: optional device to move compressed output to
108
+ :return: dictionary of compressed weight data
109
+ """
110
+ if global_scale is not None:
111
+ raise ValueError(
112
+ "global_scale is not supported for the PackQuantizationCompressor"
113
+ )
114
+
115
+ compressed_dict = {}
116
+ if can_quantize(weight, quantization_args):
117
+ quantized_weight = quantize(
118
+ x=weight,
119
+ scale=scale,
120
+ zero_point=zero_point,
121
+ g_idx=g_idx,
122
+ args=quantization_args,
123
+ dtype=torch.int8,
124
+ )
125
+ else:
126
+ quantized_weight = weight
127
+
128
+ packed_weight = pack_to_int32(quantized_weight, quantization_args.num_bits)
129
+
130
+ weight_shape = torch.tensor(weight.shape)
131
+ if device is not None:
132
+ packed_weight = packed_weight.to(device)
133
+ weight_shape = weight_shape.to(device)
134
+
135
+ compressed_dict["weight_shape"] = weight_shape
136
+ compressed_dict["weight_packed"] = packed_weight
137
+
138
+ # We typically don't compress zp; apart from when using the packed_compressor and when storing group/channel zp
139
+ if not quantization_args.symmetric and quantization_args.strategy in [
140
+ QuantizationStrategy.GROUP.value,
141
+ QuantizationStrategy.CHANNEL.value,
142
+ ]:
143
+ packed_zp = pack_to_int32(
144
+ zero_point, quantization_args.num_bits, packed_dim=0
145
+ )
146
+ compressed_dict["weight_zero_point"] = packed_zp
147
+ return compressed_dict
148
+
149
+ def decompress_weight(
150
+ self,
151
+ compressed_data: Dict[str, Tensor],
152
+ quantization_args: Optional[QuantizationArgs] = None,
153
+ ) -> torch.Tensor:
154
+ """
155
+ Decompresses a single compressed weight
156
+
157
+ :param compressed_data: dictionary of data needed for decompression
158
+ :param quantization_args: quantization parameters for the weight
159
+ :return: tensor of the decompressed weight
160
+ """
161
+ weight = compressed_data["weight_packed"]
162
+ scale = compressed_data["weight_scale"]
163
+ zero_point = compressed_data.get("weight_zero_point", None)
164
+ g_idx = compressed_data.get("weight_g_idx", None)
165
+ original_shape = torch.Size(compressed_data["weight_shape"])
166
+ num_bits = quantization_args.num_bits
167
+ unpacked = unpack_from_int32(weight, num_bits, original_shape)
168
+
169
+ # NOTE: this will fail decompression as we don't currently handle packed zp on decompression
170
+ if not quantization_args.symmetric and quantization_args.strategy in [
171
+ QuantizationStrategy.GROUP.value,
172
+ QuantizationStrategy.CHANNEL.value,
173
+ ]:
174
+ raise ValueError(
175
+ "Decompression of packed zero points is currently not supported"
176
+ )
177
+ assert zero_point is not None
178
+ original_zp_shape = (original_shape[0], scale.shape[-1])
179
+ zero_point = unpack_from_int32(
180
+ zero_point, num_bits, original_zp_shape, packed_dim=0
181
+ )
182
+
183
+ decompressed_weight = dequantize(
184
+ x_q=unpacked, scale=scale, zero_point=zero_point, g_idx=g_idx
185
+ )
186
+
187
+ return decompressed_weight
188
+
189
+
190
+ def pack_to_int32(
191
+ value: torch.Tensor,
192
+ num_bits: int,
193
+ packed_dim: Union[Literal[0], Literal[1]] = 1,
194
+ ) -> torch.Tensor:
195
+ """
196
+ Packs a tensor of quantized weights stored in int8 into int32s with padding
197
+
198
+ Pseudocode:
199
+ 1. Shift wrt num_bits to convert to unsigned. num_bits=8
200
+ [1,2] -> [129, 130]
201
+ 2. Pad to fill in 32 bits
202
+ [129, 130] -> [129, 130, 0, 0]
203
+ 3. convert to binary align in order
204
+ [129, 130, 0, 0] -> 00000000 00000000 10000010 10000001
205
+ 4. convert aligned binary to number
206
+ 00000000000000001000001010000001 -> 33409
207
+ 5. covert back to uint32
208
+ 33409 -> 33409
209
+
210
+ :param value: tensor to pack
211
+ :param num_bits: number of bits used to store underlying data, must be at least 1
212
+ :returns: packed int32 tensor
213
+ """
214
+ if value.dtype is not torch.int8:
215
+ raise ValueError("Tensor must be quantized to torch.int8 before packing")
216
+
217
+ if num_bits > 8:
218
+ raise ValueError("Packing is only supported for less than 8 bits")
219
+
220
+ if num_bits < 1:
221
+ raise ValueError(f"num_bits must be at least 1, got {num_bits}")
222
+
223
+ # convert to unsigned for packing
224
+ offset = 1 << (num_bits - 1)
225
+ value = (value + offset).to(torch.uint8)
226
+ value = value.cpu().numpy().astype(np.uint32)
227
+ pack_factor = 32 // num_bits
228
+
229
+ # pad input tensor and initialize packed output
230
+ packed_size = math.ceil(value.shape[packed_dim] / pack_factor)
231
+ padding = packed_size * pack_factor - value.shape[packed_dim]
232
+ value = np.pad(value, pad_width=[(0, 0), (0, padding)], constant_values=0)
233
+
234
+ # pack values
235
+ if packed_dim == 1:
236
+ packed = np.zeros((value.shape[0], packed_size), dtype=np.uint32)
237
+ for i in range(pack_factor):
238
+ packed |= value[:, i::pack_factor] << num_bits * i
239
+ else:
240
+ packed = np.zeros((packed_size, value.shape[1]), dtype=np.uint32)
241
+ for i in range(pack_factor):
242
+ packed |= value[i::pack_factor, :] << num_bits * i
243
+
244
+ # convert back to signed and torch
245
+ packed = np.ascontiguousarray(packed).view(np.int32)
246
+ return torch.from_numpy(packed)
247
+
248
+
249
+ def unpack_from_int32(
250
+ value: torch.Tensor,
251
+ num_bits: int,
252
+ shape: torch.Size,
253
+ packed_dim: Union[Literal[0], Literal[1]] = 1,
254
+ ) -> torch.Tensor:
255
+ """
256
+ Unpacks a tensor of packed int32 weights into individual int8s, maintaining the
257
+ original bit range.
258
+
259
+ Return tensors in int8
260
+
261
+ :param value: tensor to upack
262
+ :param num_bits: number of bits to unpack each data point into
263
+ :param shape: shape to unpack into, used to remove padding
264
+ :returns: unpacked int8 tensor
265
+ """
266
+ if value.dtype is not torch.int32:
267
+ raise ValueError(
268
+ f"Expected {torch.int32} but got {value.dtype}, Aborting unpack."
269
+ )
270
+
271
+ if num_bits > 8:
272
+ raise ValueError("Unpacking is only supported for less than 8 bits")
273
+
274
+ pack_factor = 32 // num_bits
275
+
276
+ # unpack
277
+ mask = (1 << num_bits) - 1
278
+
279
+ if packed_dim == 1:
280
+ unpacked = torch.zeros(
281
+ (value.shape[0], value.shape[1] * pack_factor),
282
+ device=value.device,
283
+ dtype=torch.int32,
284
+ )
285
+ for i in range(pack_factor):
286
+ unpacked[:, i::pack_factor] = (value >> (num_bits * i)) & mask
287
+
288
+ # remove padding
289
+ original_row_size = int(shape[1])
290
+ unpacked = unpacked[:, :original_row_size]
291
+ else:
292
+ unpacked = torch.zeros(
293
+ (value.shape[0] * pack_factor, value.shape[1]),
294
+ device=value.device,
295
+ dtype=torch.int32,
296
+ )
297
+ for i in range(pack_factor):
298
+ unpacked[i::pack_factor, :] = (value >> (num_bits * i)) & mask
299
+
300
+ # remove padding
301
+ original_row_size = int(shape[0])
302
+ unpacked = unpacked[:original_row_size, :]
303
+
304
+ # bits are packed in unsigned format, reformat to signed
305
+ # update the value range from unsigned to signed
306
+ offset = pow(2, num_bits) // 2
307
+ unpacked = (unpacked - offset).to(torch.int8)
308
+
309
+ return unpacked
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # flake8: noqa
15
+
16
+ from .base import *
17
+ from .dense import *
18
+ from .sparse_24_bitmask import *
19
+ from .sparse_bitmask import *
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (328 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/base.cpython-312.pyc ADDED
Binary file (8.65 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/dense.cpython-312.pyc ADDED
Binary file (3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/sparse_24_bitmask.cpython-312.pyc ADDED
Binary file (11.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/__pycache__/sparse_bitmask.cpython-312.pyc ADDED
Binary file (7.62 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/base.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ from typing import Dict, Generator, Optional, Set, Tuple
17
+
18
+ from compressed_tensors.compressors.base import BaseCompressor
19
+ from compressed_tensors.utils import (
20
+ get_nested_mappings_from_state_dict,
21
+ get_nested_weight_mappings,
22
+ merge_names,
23
+ )
24
+ from safetensors import safe_open
25
+ from torch import Tensor
26
+ from tqdm import tqdm
27
+
28
+
29
+ __all__ = ["BaseSparseCompressor"]
30
+
31
+ _LOGGER: logging.Logger = logging.getLogger(__name__)
32
+
33
+
34
+ class BaseSparseCompressor(BaseCompressor):
35
+ """
36
+ Base class representing a sparse compression algorithm. Each child class should
37
+ implement compression_param_names, compress_weight and decompress_weight;
38
+
39
+ Compressors support compressing/decompressing a full module state dict or a single
40
+ quantized PyTorch leaf module.
41
+
42
+ Model Load Lifecycle (run_compressed=False):
43
+ - ModelCompressor.decompress()
44
+ - apply_quantization_config()
45
+ - BaseSparseCompressor.decompress()
46
+ - BaseSparseCompressor.decompress_weight()
47
+
48
+ Model Save Lifecycle:
49
+ - ModelCompressor.compress()
50
+ - BaseSparseCompressor.compress()
51
+ - BaseSparseCompressor.compress_weight()
52
+
53
+ Module Lifecycle (run_compressed=True):
54
+ - apply_quantization_config()
55
+ - compressed_module = CompressedLinear(module)
56
+ - initialize_module_for_quantization()
57
+ - BaseSparseCompressor.compression_param_info()
58
+ - register_parameters()
59
+ - compressed_module.forward()
60
+ - compressed_module.decompress()
61
+
62
+
63
+ :param config: config specifying compression parameters
64
+ """
65
+
66
+ def compress(
67
+ self,
68
+ model_state: Dict[str, Tensor],
69
+ compression_targets: Optional[Set[str]] = None,
70
+ show_progress: bool = False,
71
+ ) -> Dict[str, Tensor]:
72
+ """
73
+ Compresses a dense state dict using bitmask compression
74
+
75
+ :param model_state: state dict of uncompressed model
76
+ :param compression_targets: optional set of layer prefixes to compress,
77
+ otherwise compress all layers (for backwards compatibility)
78
+ :return: compressed state dict
79
+ """
80
+ compressed_dict = {}
81
+ _LOGGER.debug(
82
+ f"Compressing model with {len(model_state)} parameterized layers..."
83
+ )
84
+ for name, value in tqdm(
85
+ model_state.items(),
86
+ desc="Compressing with sparsity",
87
+ disable=(not show_progress),
88
+ ):
89
+ if not self.should_compress(name, compression_targets):
90
+ compressed_dict[name] = value
91
+ continue
92
+ prefix = name
93
+ if prefix.endswith(".weight"):
94
+ prefix = prefix[: -(len(".weight"))]
95
+
96
+ compression_data = self.compress_weight(prefix, value)
97
+ for key in compression_data.keys():
98
+ if key in compressed_dict:
99
+ _LOGGER.warn(
100
+ f"Expected all compressed state_dict keys to be unique, but "
101
+ f"found an existing entry for {key}. The existing entry will "
102
+ "be replaced."
103
+ )
104
+
105
+ compressed_dict.update(compression_data)
106
+
107
+ return compressed_dict
108
+
109
+ def decompress(
110
+ self,
111
+ path_to_model_or_tensors: str,
112
+ device: str = "cpu",
113
+ params_to_skip_load: Optional[Tuple] = None,
114
+ **kwargs,
115
+ ) -> Generator[Tuple[str, Tensor], None, None]:
116
+ """
117
+ Reads a bitmask compressed state dict located
118
+ at path_to_model_or_tensors and returns a generator
119
+ for sequentially decompressing back to a dense state dict
120
+
121
+ :param model_path: path to compressed safetensors model (directory with
122
+ one or more safetensors files) or compressed tensors file
123
+ :param device: device to load decompressed weights onto
124
+ :param params_to_skip_load: a list of non-sparsity parameters (e.g quantization
125
+ parameters) that we want to skip loading. As the sparsity compresssor does
126
+ not handle quantized decompression, this should contain any quantization
127
+ parameters when decompressing stacked compressors. We want these parameters
128
+ to be handled by the quantization decompressor
129
+ :return: iterator for generating decompressed weights
130
+ """
131
+ weight_mappings, ignored_params = get_nested_weight_mappings(
132
+ path_to_model_or_tensors,
133
+ self.compression_param_names,
134
+ return_unmatched_params=True,
135
+ )
136
+ for module_path in weight_mappings.keys():
137
+ weight_data = {}
138
+ for param_name, safe_path in weight_mappings[module_path].items():
139
+ full_name = merge_names(module_path, param_name)
140
+ with safe_open(safe_path, framework="pt", device=device) as f:
141
+ weight_data[param_name] = f.get_tensor(full_name)
142
+
143
+ decompressed = self.decompress_weight(weight_data)
144
+ yield merge_names(module_path, "weight"), decompressed
145
+
146
+ for ignored_param_name, safe_path in ignored_params.items():
147
+ should_skip = False
148
+ if params_to_skip_load is not None:
149
+ for param_to_skip in params_to_skip_load:
150
+ if param_to_skip in ignored_param_name:
151
+ should_skip = True
152
+
153
+ if not should_skip:
154
+ with safe_open(safe_path, framework="pt", device=device) as f:
155
+ value = f.get_tensor(ignored_param_name)
156
+ yield ignored_param_name, value
157
+
158
+ def decompress_from_state_dict(
159
+ self,
160
+ state_dict: Dict[str, Tensor],
161
+ ) -> Generator[Tuple[str, Dict[str, Tensor]], None, None]:
162
+ """
163
+ Decompress the state dict of a module (or model)
164
+
165
+ Unlike `self.decompress`, this function does not need to explicitly skip params
166
+ via params_to_skip_load because it is more convenient for its only caller
167
+ (ModelCompressor.decompress_model) to retrieve all unused param keys
168
+
169
+ :param state_dict: state dict containing parameters to decompress
170
+ :return: Generator of (param_path, param_val)
171
+ """
172
+ weight_mappings, ignored_params = get_nested_mappings_from_state_dict(
173
+ state_dict, self.compression_param_names, return_unmatched_params=True
174
+ )
175
+
176
+ for module_path in weight_mappings.keys():
177
+ weight_data = {}
178
+ for param_name, param_value in weight_mappings[module_path].items():
179
+ weight_data[param_name] = param_value
180
+
181
+ decompressed = self.decompress_weight(weight_data)
182
+ yield merge_names(module_path, "weight"), decompressed
183
+
184
+ for ignored_param_path, ignored_param_value in ignored_params.items():
185
+ yield ignored_param_path, ignored_param_value
186
+
187
+ @staticmethod
188
+ def should_compress(name: str, expanded_targets: Optional[Set[str]] = None) -> bool:
189
+ """
190
+ Check if a parameter should be compressed.
191
+ Currently, this only returns True for weight parameters.
192
+
193
+ :param name: name of the parameter
194
+ :param expanded_targets: set of layer prefixes to compress
195
+ :return: whether or not the parameter should be compressed
196
+ """
197
+ if expanded_targets is None:
198
+ return name.endswith(".weight")
199
+
200
+ return (
201
+ name.endswith(".weight") and name[: -(len(".weight"))] in expanded_targets
202
+ )
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/dense.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING, Dict, Generator, Tuple
16
+
17
+ import torch
18
+ from compressed_tensors.compressors.base import BaseCompressor
19
+ from compressed_tensors.config import CompressionFormat
20
+ from torch import Tensor
21
+
22
+
23
+ if TYPE_CHECKING:
24
+ from compressed_tensors.quantization import QuantizationScheme
25
+
26
+
27
+ @BaseCompressor.register(name=CompressionFormat.dense.value)
28
+ class DenseCompressor(BaseCompressor):
29
+ """
30
+ Identity compressor for dense models, returns the original state_dict
31
+ """
32
+
33
+ @property
34
+ def compression_param_names(self) -> Tuple[str]:
35
+ """
36
+ Returns a tuple of compression parameter names introduced by
37
+ the compressor during compression
38
+ """
39
+ return ()
40
+
41
+ def compress(self, model_state: Dict[str, Tensor], **kwargs) -> Dict[str, Tensor]:
42
+ return model_state
43
+
44
+ def decompress(
45
+ self, path_to_model_or_tensors: str, device: str = "cpu", **kwargs
46
+ ) -> Generator[Tuple[str, Tensor], None, None]:
47
+ return iter([])
48
+
49
+ def decompress_from_state_dict(
50
+ self,
51
+ state_dict: Dict[str, Tensor],
52
+ ) -> Generator[Tuple[str, Dict[str, Tensor]], None, None]:
53
+ for key, value in state_dict.items():
54
+ yield key, value
55
+
56
+ def decompress_module_from_state_dict(
57
+ self,
58
+ prefix: str,
59
+ state_dict: Dict[str, torch.Tensor],
60
+ scheme: "QuantizationScheme",
61
+ ) -> Dict[str, torch.Tensor]:
62
+ """
63
+ This function is implemented as a workaround because of how
64
+ `ModelCompressor.quantization_compressor` can be set to either
65
+ an instance of `BaseQuantizationCompressor` or `DenseCompressor`.
66
+ """
67
+ return state_dict.copy()
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/sparse_24_bitmask.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Dict, Generator, List, Tuple, Union
17
+
18
+ import torch
19
+ from compressed_tensors.compressors.base import BaseCompressor
20
+ from compressed_tensors.compressors.sparse_compressors.base import BaseSparseCompressor
21
+ from compressed_tensors.config import CompressionFormat, SparsityStructure
22
+ from compressed_tensors.quantization import FP8_DTYPE
23
+ from compressed_tensors.utils import merge_names, pack_bitmasks, unpack_bitmasks
24
+ from torch import Tensor
25
+
26
+
27
+ __all__ = [
28
+ "Sparse24BitMaskCompressor",
29
+ "Sparse24BitMaskTensor",
30
+ "sparse24_bitmask_compress",
31
+ "sparse24_bitmask_decompress",
32
+ "get_24_bytemasks",
33
+ ]
34
+
35
+
36
+ @BaseCompressor.register(name=CompressionFormat.sparse_24_bitmask.value)
37
+ class Sparse24BitMaskCompressor(BaseSparseCompressor):
38
+ """
39
+ Compression for sparse models using bitmasks. Non-zero weights are stored in a 2d
40
+ values tensor, with their locations stored in a 2d bitmask
41
+ """
42
+
43
+ @property
44
+ def compression_param_names(self) -> Tuple[str]:
45
+ """
46
+ Returns a tuple of compression parameter names introduced by
47
+ the compressor during compression
48
+ """
49
+ return (
50
+ "shape",
51
+ "compressed",
52
+ "bitmask",
53
+ )
54
+
55
+ def compress_weight(self, name, value):
56
+ bitmask_tensor = Sparse24BitMaskTensor.from_dense(
57
+ value, self.config.sparsity_structure
58
+ )
59
+ bitmask_dict = bitmask_tensor.dict(name_prefix=name, device="cpu")
60
+ return bitmask_dict
61
+
62
+ def decompress_weight(self, weight_data):
63
+ data = Sparse24BitMaskTensor.from_compressed_data(**weight_data)
64
+ decompressed = data.decompress()
65
+ return decompressed
66
+
67
+
68
+ @dataclass
69
+ class Sparse24BitMaskTensor:
70
+ """
71
+ Owns compressions and decompression for a single 2:4 sparse
72
+ bitmask compressed tensor.
73
+
74
+ :param shape: shape of dense tensor
75
+ :param compressed: 2d tensor of non-zero values
76
+ :param bitmask: 2d bitmask of non-zero values
77
+ """
78
+
79
+ shape: List[int]
80
+ compressed: Tensor
81
+ bitmask: Tensor
82
+
83
+ @staticmethod
84
+ def from_dense(
85
+ tensor: Tensor,
86
+ sparsity_structure: Union[SparsityStructure, str] = SparsityStructure.TWO_FOUR,
87
+ ) -> "Sparse24BitMaskTensor":
88
+ """
89
+ :param tensor: dense tensor to compress
90
+ :return: instantiated compressed tensor
91
+ """
92
+ shape = list(tensor.shape)
93
+ compressed, bitmask = sparse24_bitmask_compress(
94
+ tensor.cpu(), sparsity_structure=sparsity_structure
95
+ )
96
+ return Sparse24BitMaskTensor(
97
+ shape=shape,
98
+ compressed=compressed,
99
+ bitmask=bitmask,
100
+ )
101
+
102
+ @staticmethod
103
+ def from_compressed_data(
104
+ shape: Union[List[int], Tensor], compressed: Tensor, bitmask: Tensor
105
+ ) -> "Sparse24BitMaskTensor":
106
+ """
107
+ :param shape: shape of the dense tensor (can be a list or a tensor)
108
+ :param compressed: 2d tensor of non-zero values
109
+ :param bitmask: 2d bitmask of non-zero values
110
+ :return: instantiated Sparse24BitMaskTensor
111
+ """
112
+ if isinstance(shape, list):
113
+ shape = torch.tensor(shape)
114
+ if isinstance(shape, torch.Tensor):
115
+ shape = shape.flatten().tolist()
116
+ return Sparse24BitMaskTensor(
117
+ shape=shape, compressed=compressed, bitmask=bitmask
118
+ )
119
+
120
+ def decompress(self) -> Tensor:
121
+ """
122
+ :return: reconstructed dense tensor
123
+ """
124
+ return sparse24_bitmask_decompress(self.compressed, self.bitmask, self.shape)
125
+
126
+ def curr_memory_size_bytes(self) -> int:
127
+ """
128
+ :return: size in bytes required to store compressed tensor on disk
129
+ """
130
+
131
+ def sizeof_tensor(a: Tensor) -> int:
132
+ return a.element_size() * a.nelement()
133
+
134
+ return sizeof_tensor(self.compressed) + sizeof_tensor(self.bitmask)
135
+
136
+ def dict(self, name_prefix: str, device: str = "cpu") -> Dict[str, Tensor]:
137
+ """
138
+ :param name_prefix: name of original tensor to store compressed weight as
139
+ :return: dict of compressed data for the stored weight
140
+ """
141
+ if name_prefix.endswith(".weight"):
142
+ name_prefix = name_prefix[: -len(".weight")]
143
+ return {
144
+ merge_names(name_prefix, "shape"): torch.tensor(
145
+ self.shape, device=device
146
+ ).reshape(-1, 1),
147
+ merge_names(name_prefix, "compressed"): self.compressed.to(device),
148
+ merge_names(name_prefix, "bitmask"): self.bitmask.to(device),
149
+ }
150
+
151
+ def __repr__(self) -> str:
152
+ return f"BitMaskTensor(shape={self.shape}, compressed=True)"
153
+
154
+
155
+ def sparse24_bitmask_compress(
156
+ tensor: Tensor,
157
+ sparsity_structure: Union[SparsityStructure, str] = SparsityStructure.TWO_FOUR,
158
+ ) -> Tuple[Tensor, Tensor, Tensor]:
159
+ """
160
+ Compresses a dense tensor using bitmask compression
161
+
162
+ :param tensor: dense 2D tensor to compress
163
+ :param sparsity_structure: structure of sparsity in the tensor, defaults
164
+ to unstructured, can also be set to `2:4`
165
+ :return: tuple of compressed data representing tensor
166
+ """
167
+ assert len(tensor.shape) == 2, "Only 2D tensors are supported"
168
+ assert (
169
+ SparsityStructure(sparsity_structure) == SparsityStructure.TWO_FOUR
170
+ ), "Only 2:4 sparsity is supported"
171
+
172
+ bytemasks = get_24_bytemasks(tensor=tensor)
173
+
174
+ if tensor.dtype == FP8_DTYPE:
175
+ # acces raw bytes of the tensor
176
+ tensor_view = tensor.view(torch.int8)
177
+ values = tensor_view[bytemasks]
178
+ values = values.view(FP8_DTYPE)
179
+ else:
180
+ values = tensor[bytemasks]
181
+
182
+ num_rows, num_cols = tensor.shape
183
+ compressed_values = values.reshape(num_rows, num_cols // 2)
184
+ bitmasks_packed = pack_bitmasks(bytemasks)
185
+ return compressed_values, bitmasks_packed
186
+
187
+
188
+ def sparse24_bitmask_decompress(
189
+ values: Tensor, bitmasks: Tensor, original_shape: torch.Size
190
+ ) -> Tensor:
191
+ """
192
+ Reconstructs a dense tensor from a compressed one
193
+
194
+ :param values: 1d tensor of non-zero values
195
+ :param bitmasks: 2d int8 tensor flagging locations of non-zero values in the
196
+ tensors original shape
197
+ :param original_shape: shape of the dense tensor
198
+ :return: decompressed dense tensor
199
+ """
200
+ bytemasks_unpacked = unpack_bitmasks(bitmasks, original_shape)
201
+
202
+ decompressed_tensor = torch.zeros(original_shape, dtype=values.dtype)
203
+ decompressed_tensor = decompressed_tensor.to(values.device)
204
+ values = values.flatten()
205
+ decompressed_tensor[bytemasks_unpacked] = values
206
+ return decompressed_tensor
207
+
208
+
209
+ def get_24_bytemasks(tensor):
210
+ """
211
+ Generate a 2:4 sparsity mask for the given tensor.
212
+
213
+ This function creates a mask where exactly 2 out of every 4 elements are
214
+ preserved based on their magnitudes. The preserved elements are the ones
215
+ with the highest absolute values in each group of 4 elements.
216
+
217
+ :param tensor: The input tensor for which the 2:4 sparsity mask is to be created.
218
+ The tensor can be of any shape but its total number of elements
219
+ must be a multiple of 4.
220
+ :return: A boolean tensor of the same shape as the input tensor, where `True`
221
+ indicates the preserved elements and `False` indicates the pruned elements.
222
+ :raises ValueError: If the total number of elements in the tensor is not a
223
+ multiple of 4.
224
+ """
225
+ original_dtype = tensor.dtype
226
+ if tensor.dtype == FP8_DTYPE:
227
+ tensor = tensor.view(torch.int8)
228
+ original_shape = tensor.shape
229
+ num_elements = tensor.numel()
230
+
231
+ if num_elements % 4 != 0:
232
+ raise ValueError("Tensor size must be a multiple of 4 for TWO_FOUR sparsity")
233
+
234
+ reshaped_tensor = tensor.view(-1, 4)
235
+ abs_tensor = reshaped_tensor.abs()
236
+ topk_indices = abs_tensor.topk(2, dim=1).indices
237
+ mask = torch.zeros_like(reshaped_tensor, dtype=torch.bool)
238
+ mask.scatter_(1, topk_indices, True)
239
+ mask = mask.view(original_shape)
240
+ tensor = tensor.view(original_dtype)
241
+
242
+ return mask
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_compressors/sparse_bitmask.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict, List, Tuple, Union
16
+
17
+ import torch
18
+ from compressed_tensors.compressors.base import BaseCompressor
19
+ from compressed_tensors.compressors.sparse_compressors.base import BaseSparseCompressor
20
+ from compressed_tensors.config import CompressionFormat
21
+ from compressed_tensors.quantization import FP8_DTYPE
22
+ from compressed_tensors.utils import merge_names, pack_bitmasks, unpack_bitmasks
23
+ from torch import Tensor
24
+
25
+
26
+ __all__ = [
27
+ "BitmaskCompressor",
28
+ "BitmaskTensor",
29
+ "bitmask_compress",
30
+ "bitmask_decompress",
31
+ ]
32
+
33
+
34
+ @BaseCompressor.register(name=CompressionFormat.sparse_bitmask.value)
35
+ class BitmaskCompressor(BaseSparseCompressor):
36
+ """
37
+ Compression for sparse models using bitmasks. Non-zero weights are stored in a 1d
38
+ values tensor, with their locations stored in a 2d bitmask
39
+ """
40
+
41
+ @property
42
+ def compression_param_names(self) -> Tuple[str]:
43
+ """
44
+ Returns a tuple of compression parameter names introduced by
45
+ the compressor during compression
46
+ """
47
+ return ("shape", "compressed", "bitmask", "row_offsets")
48
+
49
+ def compress_weight(self, name, value):
50
+ bitmask_tensor = BitmaskTensor.from_dense(value)
51
+ bitmask_dict = bitmask_tensor.dict(name_prefix=name, device="cpu")
52
+ return bitmask_dict
53
+
54
+ def decompress_weight(self, weight_data):
55
+ data = BitmaskTensor(**weight_data)
56
+ decompressed = data.decompress()
57
+ return decompressed
58
+
59
+
60
+ class BitmaskTensor:
61
+ """
62
+ Owns compressions and decompression for a single bitmask compressed tensor.
63
+ Adapted from: https://github.com/mgoin/torch_bitmask/tree/main
64
+
65
+ :param shape: shape of dense tensor
66
+ :compressed: flat tensor of non-zero values
67
+ :bitmask: 2d bitmask of non-zero values
68
+ :row_offsets: flat tensor indicating what index in values each dense row starts at
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ shape: Union[torch.Size, List],
74
+ compressed: Tensor,
75
+ bitmask: Tensor,
76
+ row_offsets: Tensor,
77
+ ):
78
+ self.shape = list(shape)
79
+ self.compressed = compressed
80
+ self.bitmask = bitmask
81
+ self.row_offsets = row_offsets
82
+
83
+ @staticmethod
84
+ def from_dense(tensor: Tensor) -> "BitmaskTensor":
85
+ """
86
+ :param tensor: dense tensor to compress
87
+ :return: instantiated compressed tensor
88
+ """
89
+ shape = tensor.shape
90
+ compressed, bitmask, row_offsets = bitmask_compress(tensor.cpu())
91
+ return BitmaskTensor(
92
+ shape=shape, compressed=compressed, bitmask=bitmask, row_offsets=row_offsets
93
+ )
94
+
95
+ def decompress(self) -> Tensor:
96
+ """
97
+ :return: reconstructed dense tensor
98
+ """
99
+ return bitmask_decompress(self.compressed, self.bitmask, self.shape)
100
+
101
+ def curr_memory_size_bytes(self):
102
+ """
103
+ :return: size in bytes required to store compressed tensor on disk
104
+ """
105
+
106
+ def sizeof_tensor(a):
107
+ return a.element_size() * a.nelement()
108
+
109
+ return (
110
+ sizeof_tensor(self.compressed)
111
+ + sizeof_tensor(self.bitmask)
112
+ + sizeof_tensor(self.row_offsets)
113
+ )
114
+
115
+ def dict(self, name_prefix: str, device: str = "cpu") -> Dict[str, Tensor]:
116
+ """
117
+ :name_prefix: name of original tensor to store compressed weight as
118
+ :return: dict of compressed data for the stored weight
119
+ """
120
+ return {
121
+ merge_names(name_prefix, "shape"): torch.tensor(self.shape, device=device),
122
+ merge_names(name_prefix, "compressed"): self.compressed.to(device),
123
+ merge_names(name_prefix, "bitmask"): self.bitmask.to(device),
124
+ merge_names(name_prefix, "row_offsets"): self.row_offsets.to(device),
125
+ }
126
+
127
+ def __repr__(self):
128
+ return f"BitmaskTensor(shape={self.shape}, compressed=True)"
129
+
130
+
131
+ def bitmask_compress(tensor: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
132
+ """
133
+ Compresses a dense tensor using bitmask compression
134
+
135
+ :param tensor: dense tensor to compress
136
+ :return: tuple of compressed data representing tensor
137
+ """
138
+ bytemasks = tensor != 0
139
+ row_counts = bytemasks.sum(dim=-1)
140
+ row_offsets = torch.cumsum(row_counts, 0) - row_counts
141
+ if tensor.dtype == FP8_DTYPE:
142
+ # acces raw bytes of the tensor
143
+ tensor_view = tensor.view(torch.int8)
144
+ values = tensor_view[bytemasks]
145
+ values = values.view(FP8_DTYPE)
146
+ else:
147
+ values = tensor[bytemasks]
148
+ bitmasks_packed = pack_bitmasks(bytemasks)
149
+ return values, bitmasks_packed, row_offsets
150
+
151
+
152
+ def bitmask_decompress(
153
+ values: Tensor, bitmasks: Tensor, original_shape: torch.Size
154
+ ) -> Tensor:
155
+ """
156
+ Reconstructs a dense tensor from a compressed one
157
+
158
+ :param values: 1d tensor of non-zero values
159
+ :param bitmasks: 2d int8 tensor flagging locations of non-zero values in the
160
+ tensors original shape
161
+ :param original_shape: shape of the dense tensor
162
+ :return: decompressed dense tensor
163
+ """
164
+ bytemasks_unpacked = unpack_bitmasks(bitmasks, original_shape)
165
+
166
+ decompressed_tensor = torch.zeros(original_shape, dtype=values.dtype)
167
+ decompressed_tensor[bytemasks_unpacked] = values
168
+
169
+ return decompressed_tensor
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # flake8: noqa
15
+
16
+ from .marlin_24 import Marlin24Compressor
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (286 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/__pycache__/marlin_24.cpython-312.pyc ADDED
Binary file (11.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/compressors/sparse_quantized_compressors/marlin_24.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ from typing import Dict, Generator, Tuple
17
+
18
+ import numpy as np
19
+ import torch
20
+ from compressed_tensors.compressors.base import BaseCompressor
21
+ from compressed_tensors.config import CompressionFormat
22
+ from compressed_tensors.quantization import (
23
+ QuantizationArgs,
24
+ QuantizationScheme,
25
+ QuantizationStrategy,
26
+ )
27
+ from compressed_tensors.quantization.lifecycle.forward import quantize
28
+ from compressed_tensors.utils import (
29
+ get_permutations_24,
30
+ is_quantization_param,
31
+ merge_names,
32
+ sparse_semi_structured_from_dense_cutlass,
33
+ tensor_follows_mask_structure,
34
+ )
35
+ from torch import Tensor
36
+ from tqdm import tqdm
37
+
38
+
39
+ _LOGGER: logging.Logger = logging.getLogger(__name__)
40
+
41
+
42
+ @BaseCompressor.register(name=CompressionFormat.marlin_24.value)
43
+ class Marlin24Compressor(BaseCompressor):
44
+ """
45
+ Compresses a quantized model with 2:4 sparsity structure for inference with the
46
+ Marlin24 kernel. Decompression is not implemented for this compressor.
47
+ """
48
+
49
+ @staticmethod
50
+ def validate_quant_compatability(
51
+ names_to_scheme: Dict[str, QuantizationScheme]
52
+ ) -> bool:
53
+ """
54
+ Checks if every quantized module in the model is compatible with Marlin24
55
+ compression. Quantization must be channel or group strategy with group_size
56
+ of 128. Only symmetric quantization is supported
57
+
58
+ :param names_to_scheme: dictionary of mapping module names to their
59
+ quantization schemes
60
+ :return: True if all modules are compatible with Marlin24 compression, raises
61
+ a ValueError otherwise
62
+ """
63
+ for name, scheme in names_to_scheme.items():
64
+ quant_args = scheme.weights
65
+ if quant_args is None:
66
+ raise ValueError(
67
+ "Marlin24 Compressor is only valid for weight quantization schemes"
68
+ )
69
+
70
+ strategy = quant_args.strategy
71
+ group_size = quant_args.group_size
72
+ symmetric = quant_args.symmetric
73
+ if (
74
+ strategy is not QuantizationStrategy.GROUP.value
75
+ and strategy is not QuantizationStrategy.CHANNEL.value
76
+ ):
77
+ raise ValueError(
78
+ f"Marlin24 Compressor is only valid for group and channel "
79
+ f"quantization strategies, got {strategy} in {name}"
80
+ )
81
+
82
+ if group_size is not None and group_size != 128:
83
+ raise ValueError(
84
+ f"Marlin24 Compressor is only valid for group size 128, "
85
+ f"got {group_size} in {name}"
86
+ )
87
+
88
+ if not symmetric:
89
+ raise ValueError(
90
+ f"Marlin24 Compressor is only valid for symmetric quantzation, "
91
+ f"got symmetric={symmetric} in {name}"
92
+ )
93
+
94
+ return True
95
+
96
+ @staticmethod
97
+ def validate_sparsity_structure(name: str, weight: Tensor) -> bool:
98
+ """
99
+ Checks if a tensor fits the required 2:4 sparsity structure
100
+
101
+ :param name: name of the tensor to check
102
+ :param weight: tensor to check for sparsity structure
103
+ :return: True if all rows match the 2:4 sparsity structure, raises
104
+ ValueError otherwise
105
+ """
106
+
107
+ if not tensor_follows_mask_structure(weight):
108
+ raise ValueError(
109
+ "Marlin24 Compressor is only compatible with weights that have "
110
+ f"a 2:4 sparsity structure. Found segments in {name} "
111
+ "that do not match the expected structure."
112
+ )
113
+
114
+ return True
115
+
116
+ @property
117
+ def compression_param_names(self) -> Tuple[str]:
118
+ """
119
+ Returns a tuple of compression parameter names introduced by
120
+ the compressor during compression
121
+ """
122
+ return ("weight_packed", "scale_packed", "meta")
123
+
124
+ def compress(
125
+ self,
126
+ model_state: Dict[str, Tensor],
127
+ names_to_scheme: Dict[str, QuantizationScheme],
128
+ show_progress: bool = False,
129
+ **kwargs,
130
+ ) -> Dict[str, Tensor]:
131
+ """
132
+ Compresses a quantized state_dict with 2:4 sparsity structure for inference
133
+ with the Marlin24 kernel
134
+
135
+ :param model_state: state dict of uncompressed model
136
+ :param names_to_scheme: quantization scheme for each quantized weight, needed
137
+ for quantize function to calculate bit depth
138
+ :param show_progress: whether to show tqdm progress
139
+ :return: compressed state dict
140
+ """
141
+ self.validate_quant_compatability(names_to_scheme)
142
+
143
+ compressed_dict = {}
144
+ weight_suffix = ".weight"
145
+ _LOGGER.debug(
146
+ f"Compressing model with {len(model_state)} parameterized layers..."
147
+ )
148
+
149
+ for name, value in tqdm(
150
+ model_state.items(), desc="Compressing model", disable=(not show_progress)
151
+ ):
152
+ if name.endswith(weight_suffix):
153
+ prefix = name[: -(len(weight_suffix))]
154
+ scale = model_state.get(merge_names(prefix, "weight_scale"), None)
155
+ zp = model_state.get(merge_names(prefix, "weight_zero_point"), None)
156
+ if scale is not None: # weight is quantized, compress it
157
+
158
+ # Marlin24 kernel requires float16 inputs
159
+ scale = scale.to(torch.float16)
160
+ value = value.to(torch.float16)
161
+
162
+ # quantize weight, keeping it as a float16 for now
163
+ quant_args = names_to_scheme[prefix].weights
164
+ value = quantize(
165
+ x=value, scale=scale, zero_point=zp, args=quant_args
166
+ )
167
+
168
+ # compress based on sparsity structure
169
+ self.validate_sparsity_structure(prefix, value)
170
+ value, meta = compress_weight_24(value)
171
+ meta = meta.cpu()
172
+
173
+ # Marlin24 kernel expects input dim first
174
+ value = value.t().contiguous().cpu()
175
+ scale = scale.t().contiguous().cpu()
176
+ og_weight_shape = value.shape
177
+
178
+ # Marlin24 kernel expects unsigned values, shift zero-point
179
+ value += (1 << quant_args.num_bits) // 2
180
+
181
+ # pack quantized weight and scale
182
+ value = pack_weight_24(value, quant_args)
183
+ packed_scale = pack_scales_24(scale, quant_args, og_weight_shape)
184
+ meta = meta.resize_(meta.shape[1] // 2, meta.shape[0] * 2)
185
+
186
+ # save compressed values
187
+ compressed_dict[merge_names(prefix, "scale_packed")] = packed_scale
188
+ compressed_dict[merge_names(prefix, "weight_packed")] = value
189
+ compressed_dict[merge_names(prefix, "meta")] = meta
190
+ continue
191
+
192
+ if not is_quantization_param(name):
193
+ # export unquantized parameters without modifying
194
+ compressed_dict[name] = value.to("cpu")
195
+
196
+ return compressed_dict
197
+
198
+ def decompress(
199
+ self, path_to_model_or_tensors: str, device: str = "cpu", **kwargs
200
+ ) -> Generator[Tuple[str, Tensor], None, None]:
201
+ raise NotImplementedError(
202
+ "Decompression is not implemented for the Marlin24 Compressor."
203
+ )
204
+
205
+
206
+ def compress_weight_24(weight: Tensor):
207
+ weight = weight.contiguous()
208
+ w_comp, meta = sparse_semi_structured_from_dense_cutlass(weight)
209
+ w_comp = w_comp.contiguous()
210
+ return w_comp, meta
211
+
212
+
213
+ def marlin_permute_weights(q_w, size_k, size_n, perm, tile):
214
+ assert q_w.shape == (size_k, size_n)
215
+ assert size_k % tile == 0, f"size_k = {size_k}, tile = {tile}"
216
+ assert size_n % tile == 0, f"size_k = {size_n}, tile = {tile}"
217
+
218
+ # Permute weights to 16x64 marlin tiles
219
+ q_w = q_w.reshape((size_k // tile, tile, size_n // tile, tile))
220
+ q_w = q_w.permute((0, 2, 1, 3))
221
+ q_w = q_w.reshape((size_k // tile, size_n * tile))
222
+
223
+ q_w = q_w.reshape((-1, perm.numel()))[:, perm].reshape(q_w.shape)
224
+
225
+ return q_w
226
+
227
+
228
+ def pack_weight_24(
229
+ weight: Tensor,
230
+ quantization_args: QuantizationArgs,
231
+ tile: int = 16,
232
+ ) -> torch.Tensor:
233
+ size_k = weight.shape[0]
234
+ size_n = weight.shape[1]
235
+ num_bits = quantization_args.num_bits
236
+ pack_factor = 32 // num_bits
237
+
238
+ # Reshuffle to marlin_24 format
239
+ perm, _, _ = get_permutations_24(num_bits)
240
+ q_w = marlin_permute_weights(weight, size_k, size_n, perm, tile)
241
+
242
+ q_w = q_w.cpu().numpy().astype(np.uint32)
243
+
244
+ q_packed = np.zeros((q_w.shape[0], q_w.shape[1] // pack_factor), dtype=np.uint32)
245
+ for i in range(pack_factor):
246
+ q_packed |= q_w[:, i::pack_factor] << num_bits * i
247
+
248
+ q_packed = torch.from_numpy(q_packed.astype(np.int32))
249
+
250
+ return q_packed
251
+
252
+
253
+ def pack_scales_24(
254
+ scales: torch.Tensor, quantization_args: QuantizationArgs, w_shape: torch.Size
255
+ ) -> torch.Tensor:
256
+ size_k = w_shape[0]
257
+ size_n = w_shape[1]
258
+ num_bits = quantization_args.num_bits
259
+
260
+ _, scale_perm_2_4, scale_perm_single_2_4 = get_permutations_24(num_bits)
261
+
262
+ if (
263
+ quantization_args.strategy == QuantizationStrategy.GROUP
264
+ and quantization_args.group_size < size_k
265
+ ):
266
+ scales = scales.reshape((-1, len(scale_perm_2_4)))[:, scale_perm_2_4]
267
+ else: # channelwise
268
+ scales = scales.reshape((-1, len(scale_perm_single_2_4)))[
269
+ :, scale_perm_single_2_4
270
+ ]
271
+ scales = scales.reshape((-1, size_n)).contiguous()
272
+
273
+ return scales
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # flake8: noqa
16
+ from .base import *
17
+ from .dense import *
18
+ from .sparse_24_bitmask import *
19
+ from .sparse_bitmask import *
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (304 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/base.cpython-312.pyc ADDED
Binary file (4.05 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/dense.cpython-312.pyc ADDED
Binary file (1.28 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/sparse_24_bitmask.cpython-312.pyc ADDED
Binary file (1.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/__pycache__/sparse_bitmask.cpython-312.pyc ADDED
Binary file (1.27 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/base.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from enum import Enum, unique
16
+ from typing import List, Optional
17
+
18
+ from compressed_tensors.registry import RegistryMixin
19
+ from pydantic import BaseModel
20
+
21
+
22
+ __all__ = ["SparsityCompressionConfig", "CompressionFormat", "SparsityStructure"]
23
+
24
+
25
+ @unique
26
+ class CompressionFormat(Enum):
27
+ dense = "dense"
28
+ sparse_bitmask = "sparse-bitmask"
29
+ sparse_24_bitmask = "sparse-24-bitmask"
30
+ int_quantized = "int-quantized"
31
+ float_quantized = "float-quantized"
32
+ naive_quantized = "naive-quantized"
33
+ pack_quantized = "pack-quantized"
34
+ marlin_24 = "marlin-24"
35
+ nvfp4_pack_quantized = "nvfp4-pack-quantized"
36
+
37
+
38
+ @unique
39
+ class SparsityStructure(Enum):
40
+ """
41
+ An enumeration to represent different sparsity structures.
42
+
43
+ Attributes
44
+ ----------
45
+ TWO_FOUR : str
46
+ Represents a 2:4 sparsity structure.
47
+ ZERO_ZERO : str
48
+ Represents a 0:0 sparsity structure.
49
+ UNSTRUCTURED : str
50
+ Represents an unstructured sparsity structure.
51
+
52
+ Examples
53
+ --------
54
+ >>> SparsityStructure('2:4')
55
+ <SparsityStructure.TWO_FOUR: '2:4'>
56
+
57
+ >>> SparsityStructure('unstructured')
58
+ <SparsityStructure.UNSTRUCTURED: 'unstructured'>
59
+
60
+ >>> SparsityStructure('2:4') == SparsityStructure.TWO_FOUR
61
+ True
62
+
63
+ >>> SparsityStructure('UNSTRUCTURED') == SparsityStructure.UNSTRUCTURED
64
+ True
65
+
66
+ >>> SparsityStructure(None) == SparsityStructure.UNSTRUCTURED
67
+ True
68
+
69
+ >>> SparsityStructure('invalid')
70
+ Traceback (most recent call last):
71
+ ...
72
+ ValueError: invalid is not a valid SparsityStructure
73
+ """
74
+
75
+ TWO_FOUR = "2:4"
76
+ UNSTRUCTURED = "unstructured"
77
+ ZERO_ZERO = "0:0"
78
+
79
+ def __new__(cls, value):
80
+ obj = object.__new__(cls)
81
+ obj._value_ = value.lower() if value is not None else value
82
+ return obj
83
+
84
+ @classmethod
85
+ def _missing_(cls, value):
86
+ # Handle None and case-insensitive values
87
+ if value is None:
88
+ return cls.UNSTRUCTURED
89
+ for member in cls:
90
+ if member.value == value.lower():
91
+ return member
92
+ raise ValueError(f"{value} is not a valid {cls.__name__}")
93
+
94
+
95
+ class SparsityCompressionConfig(RegistryMixin, BaseModel):
96
+ """
97
+ Base data class for storing sparsity compression parameters
98
+
99
+ :param format: name of compression format
100
+ :param targets: List of layer names or layer types that aren't sparse and should
101
+ be ignored during compression. By default, assume all layers are targeted
102
+ :param ignore: List of layer names (unique) to ignore from targets. Defaults to None
103
+ :param global_sparsity: average sparsity of the entire model
104
+ :param sparsity_structure: structure of the sparsity, such as
105
+ "unstructured", "2:4", "8:16" etc
106
+ """
107
+
108
+ format: str
109
+ targets: Optional[List[str]] = None
110
+ ignore: Optional[List[str]] = None
111
+ global_sparsity: Optional[float] = 0.0
112
+ sparsity_structure: Optional[str] = "unstructured"
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/dense.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ from compressed_tensors.config import CompressionFormat, SparsityCompressionConfig
18
+
19
+
20
+ __all__ = ["DenseSparsityConfig"]
21
+
22
+
23
+ @SparsityCompressionConfig.register(name=CompressionFormat.dense.value)
24
+ class DenseSparsityConfig(SparsityCompressionConfig):
25
+ """
26
+ Identity configuration for storing a sparse model in
27
+ an uncompressed dense format
28
+
29
+ :param global_sparsity: average sparsity of the entire model
30
+ :param sparsity_structure: structure of the sparsity, such as
31
+ "unstructured", "2:4", "8:16" etc
32
+ """
33
+
34
+ format: str = CompressionFormat.dense.value
35
+ global_sparsity: Optional[float] = 0.0
36
+ sparsity_structure: Optional[str] = "unstructured"
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/sparse_24_bitmask.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ from compressed_tensors.config import (
18
+ CompressionFormat,
19
+ SparsityCompressionConfig,
20
+ SparsityStructure,
21
+ )
22
+
23
+
24
+ __all__ = ["Sparse24BitMaskConfig"]
25
+
26
+
27
+ @SparsityCompressionConfig.register(name=CompressionFormat.sparse_24_bitmask.value)
28
+ class Sparse24BitMaskConfig(SparsityCompressionConfig):
29
+ """
30
+ Configuration for storing a 24 sparse model using
31
+ bytemask compression
32
+
33
+ :param global_sparsity: average sparsity of the entire model
34
+ :param sparsity_structure: structure of the sparsity, should always be
35
+ "2:4" for this compression format
36
+ """
37
+
38
+ format: str = CompressionFormat.sparse_24_bitmask.value
39
+ global_sparsity: Optional[float] = 0.0
40
+ sparsity_structure: Optional[str] = SparsityStructure.TWO_FOUR.value
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/config/sparse_bitmask.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ from compressed_tensors.config import CompressionFormat, SparsityCompressionConfig
18
+
19
+
20
+ __all__ = ["BitmaskConfig"]
21
+
22
+
23
+ @SparsityCompressionConfig.register(name=CompressionFormat.sparse_bitmask.value)
24
+ class BitmaskConfig(SparsityCompressionConfig):
25
+ """
26
+ Configuration for storing a sparse model using
27
+ bitmask compression
28
+
29
+ :param global_sparsity: average sparsity of the entire model
30
+ :param sparsity_structure: structure of the sparsity, such as
31
+ "unstructured", "2:4", "8:16" etc
32
+ """
33
+
34
+ format: str = CompressionFormat.sparse_bitmask.value
35
+ global_sparsity: Optional[float] = 0.0
36
+ sparsity_structure: Optional[str] = "unstructured"
tool_server/.venv/lib/python3.12/site-packages/compressed_tensors/linear/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing,
10
+ # software distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.