chiruan commited on
Commit
b78f36e
·
verified ·
1 Parent(s): 084666a

Upload DeepSeek-R1-Distill-Qwen-1.5B W4A8KV4 checkpoint and runtime

Browse files

Complete 28-layer BF16 fake-quant checkpoint, tokenizer, required transform state, licenses, vLLM runtime and file checksums.

.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LICENSE-Apache-2.0 ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
LICENSE-Quantized-Reasoning-Models ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ruikangliu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
NOTICE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DeepSeek-R1-Distill-Qwen-1.5B QuaRot W4A8KV4
2
+
3
+ Base model: DeepSeek-R1-Distill-Qwen-1.5B, Copyright (c) 2023 DeepSeek, MIT.
4
+ Quantized-Reasoning-Models: Copyright (c) 2025 ruikangliu, MIT.
5
+ https://github.com/ruikangliu/Quantized-Reasoning-Models
6
+ vLLM/Qwen/Transformers-derived adapter copyright notices are retained in source; Apache 2.0.
7
+ QuaRot: https://github.com/spcl/QuaRot, Apache 2.0.
8
+
9
+ Local modifications: quantization and inference adaptations for this Qwen2 checkpoint.
10
+ Packaging modifications: imports relocated; unrelated optional KV backend imports
11
+ replaced by unsupported-operation guards for the scalar FlatQuant package.
12
+ The included generation entrypoint and package initializers were added for loading.
13
+ These packages do not imply an official upstream quantized model release.
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model: deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
4
+ base_model_relation: quantized
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - qwen2
8
+ - quarot
9
+ - fake-quantization
10
+ - w4a8kv4
11
+ - custom-code
12
+ - safetensors
13
+ ---
14
+
15
+ # DeepSeek-R1-Distill-Qwen-1.5B · QuaRot · W4A8KV4
16
+
17
+ Complete 28-layer quantized checkpoint from run `20260915T034854Z`, exported
18
+ on 2026-09-15. Base model:
19
+ [deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B).
20
+
21
+ **This is a BF16 fake-quant checkpoint.** W4A8KV4 denotes 4-bit weights,
22
+ 8-bit activations and 4-bit keys/values in the quantize-dequantize numerical
23
+ simulation. Weights are stored as BF16 values in safetensors, approximately
24
+ 3.55 GB. This repository does not provide packed INT4 weights or INT4 kernels.
25
+
26
+ 中文:这是 W4A8KV4 伪量化模型,权重以 BF16 保存。请使用随附的 vLLM
27
+ 自定义加载代码,以启用激活和 KV 量化及所需变换。
28
+
29
+ ## Calibration and format
30
+
31
+ Hadamard rotations (seed 0), GPTQ, WikiText-2, 128 samples × 2048 tokens; activation clip 0.9 and K/V clip 0.95. The checkpoint selects the local Qwen2 `legacy` QuaRot implementation.
32
+
33
+ Weights use per-channel symmetric quantization; activations use per-token
34
+ asymmetric quantization. K/V use asymmetric quantization with group size 128.
35
+ Tensor parallelism is 1. Full details are in `config.json`.
36
+
37
+ Online Hadamard rotations and A/K/V quantization are provided by the bundled QuaRot runtime.
38
+
39
+ ## Load and generate
40
+
41
+ Use Python 3.11, PyTorch 2.7.0, Transformers 4.51.3 and vLLM 0.9.0.
42
+ Install a vLLM/PyTorch build that supports your GPU. The environment used to
43
+ evaluate this checkpoint has CUDA 12.8 and a local vLLM 0.9.0 build for RTX
44
+ 5090 (SM 12.0). An incompatible vLLM wheel cannot run that GPU.
45
+
46
+ ```bash
47
+ hf download chiruan/DeepSeek-R1-Distill-Qwen-1.5B-QuaRot-W4A8KV4 --local-dir ./DeepSeek-R1-Distill-Qwen-1.5B-QuaRot-W4A8KV4
48
+ cd DeepSeek-R1-Distill-Qwen-1.5B-QuaRot-W4A8KV4
49
+ python -m pip install -r requirements.txt
50
+ python generate.py --model . --prompt "What is 7 * 8?" --max-new-tokens 128
51
+ ```
52
+
53
+ The included script registers `Qwen2QuaRotForCausalLM` and runs the bundled
54
+ adapter. Stock Transformers or vLLM loading alone does not install this
55
+ checkpoint's custom numerical operations. Use a local downloaded directory;
56
+ all model files and auxiliary state must remain together.
57
+
58
+ For QuaRot, the optional `fast_hadamard_transform` CUDA extension accelerates
59
+ online rotations; the bundled helper also has a PyTorch fallback.
60
+
61
+ ## Validation and provenance
62
+
63
+ The completed source run passed full checkpoint export and short prefill /
64
+ cached-decode checks with a 32768-token context configuration. That check does
65
+ not establish quality on a full 32K-token input. Benchmark evaluation was still
66
+ in progress when the upload was prepared; no unfinished score is claimed here.
67
+
68
+ The bundled vLLM adapter comes from the frozen source used in that run.
69
+ Imports were relocated into a standalone package. For FlatQuant, unrelated
70
+ optional KV backends were replaced by explicit unsupported-operation guards;
71
+ the scalar KV path used by this checkpoint is retained. File provenance and
72
+ changes are recorded in `runtime-provenance.json`; file integrity hashes are
73
+ in `SHA256SUMS`.
74
+
75
+ ## License
76
+
77
+ The base model uses [MIT](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B/blob/main/LICENSE),
78
+ included in `LICENSE`. Quantized-Reasoning-Models utilities retain their MIT
79
+ license. The vLLM/Qwen-derived adapters and QuaRot-related code retain Apache
80
+ 2.0 licensing. Both license texts and attribution are included; see `NOTICE`.
SHA256SUMS ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 1c8f573e830ca9b3ebfeb7ace1823146e22b66f99ee223840e7637c9e745e1c7 LICENSE
2
+ 832dd9e00a68dd83b3c3fb9f5588dad7dcf337a0db50f7d9483f310cd292e92e LICENSE-Apache-2.0
3
+ 5d08e7234cb56095f50a3a7ac7bcc5698870ef6aedffb16a6c79f8d412fa2864 LICENSE-Quantized-Reasoning-Models
4
+ cf0031b591fd38db93c941dc6533ab80a0e778ec9a2f1c966b6f84532d6954f8 NOTICE
5
+ fea4eefa1b17cec5427f640fa2e5d6dff38520280b7465dac7ed0c46b0a4bb41 README.md
6
+ 30ac55e118af2854dc57f4abd9469ebb816c9fdebf9ed711f1db40101c49f821 config.json
7
+ b6a9b3b3bace39e2979f0811034af3053a9af67797682bb52c206df0321bf957 generate.py
8
+ ef0e5b193e84dd2a48757aa55088ab0d148dce48849ab2d8be1fc73d4bb85795 generation_config.json
9
+ 661e4d3a689113b2c9898bf8bae1462b248b2993d3f6c9c37876d6674f818e48 model.safetensors
10
+ 7fcb7dced6e18c9c4a583ced8e67c1f9feced201684cd346cd83fb1845fb6957 r1_quant_runtime/__init__.py
11
+ 921489754ec76c191d06980d1e14c4d775090cdbd0f7ca307a6ab41e9e01a0de r1_quant_runtime/model.py
12
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 r1_quant_runtime/utils/__init__.py
13
+ 2ac96df145e404b488115c087bc0f8bef56f00c3e9cbc325d309faf1565f7015 r1_quant_runtime/utils/fake_quant_utils.py
14
+ ff633fb9debddff5185e9eb3c6d7ce52d2afbe0edb87e2044977d87cefac5162 r1_quant_runtime/utils/hadamard_ops.py
15
+ 0bfcb099762a7bf7cb7d32646de3f293d60a0834e5474330b4897945236927f0 r1_quant_runtime/utils/hadamard_utils.py
16
+ 4f28cf06aca626ee045693328d0ee8f4dc31297293360e6e0f787c460b3b3cea requirements.txt
17
+ 9fbdec7d95117368cac8eb3b788d93efd90f0e6c3821e1454ea0455ce14dea3a runtime-provenance.json
18
+ 59cda48bbe8bab9d61ffb410e6e3c07b6d98bff73cee7c88ff8b51f95f21ab1c special_tokens_map.json
19
+ e20ddafc659ba90242154b55275402edeca0715e5dbb30f56815a4ce081f4893 tokenizer.json
20
+ 92a23085bfbd6862f4868df0db8404d8f18f6393225ec5b2bbef0bd1630111fa tokenizer_config.json
config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "architectures": [
4
+ "Qwen2QuaRotForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "eos_token_id": 151643,
9
+ "fake_quant_config": {
10
+ "a_asym": true,
11
+ "a_bits": 8,
12
+ "a_clip_ratio": 0.9,
13
+ "a_groupsize": -1,
14
+ "k_asym": true,
15
+ "k_bits": 4,
16
+ "k_clip_ratio": 0.95,
17
+ "k_groupsize": 128,
18
+ "quant_scope": "all",
19
+ "quarot_impl": "legacy",
20
+ "quarot_impl_version": 1,
21
+ "rotation_mode": "hadamard",
22
+ "rotation_seed": 0,
23
+ "tp": 1,
24
+ "v_asym": true,
25
+ "v_bits": 4,
26
+ "v_clip_ratio": 0.95,
27
+ "v_groupsize": 128,
28
+ "w_bits": 4,
29
+ "w_clip": true,
30
+ "w_groupsize": -1,
31
+ "weight_method": "gptq"
32
+ },
33
+ "hidden_act": "silu",
34
+ "hidden_size": 1536,
35
+ "initializer_range": 0.02,
36
+ "intermediate_size": 8960,
37
+ "max_position_embeddings": 131072,
38
+ "max_window_layers": 21,
39
+ "model_type": "qwen2",
40
+ "num_attention_heads": 12,
41
+ "num_hidden_layers": 28,
42
+ "num_key_value_heads": 2,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": null,
45
+ "rope_theta": 10000,
46
+ "sliding_window": 4096,
47
+ "tie_word_embeddings": false,
48
+ "torch_dtype": "bfloat16",
49
+ "transformers_version": "4.51.3",
50
+ "use_cache": true,
51
+ "use_mrope": false,
52
+ "use_sliding_window": false,
53
+ "vocab_size": 151936
54
+ }
generate.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-device vLLM inference with the checkpoint's custom quantized runtime."""
2
+ import argparse
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+
7
+ from r1_quant_runtime import register
8
+
9
+ # Spawned workers import this entrypoint before loading the model architecture.
10
+ register()
11
+
12
+
13
+ def main():
14
+ from transformers import AutoTokenizer
15
+ from vllm import LLM, SamplingParams
16
+ parser = argparse.ArgumentParser(description=__doc__)
17
+ parser.add_argument('--model', default=str(Path(__file__).resolve().parent))
18
+ parser.add_argument('--prompt', default='What is 7 * 8?')
19
+ parser.add_argument('--max-new-tokens', type=int, default=128)
20
+ parser.add_argument('--context-length', type=int, default=32768)
21
+ parser.add_argument('--gpu-memory-utilization', type=float, default=0.85)
22
+ parser.add_argument('--num-gpu-blocks', type=int, default=None)
23
+ parser.add_argument('--smoke-test', action='store_true')
24
+ args = parser.parse_args()
25
+ path = Path(args.model).resolve()
26
+ config = json.loads((path / 'config.json').read_text())
27
+ q = config['fake_quant_config']
28
+ if q.get('kv_vq') is not None or q.get('oscar') is not None:
29
+ raise ValueError('This package supports only its scalar W4A8KV4 checkpoint.')
30
+ if [q[k + '_bits'] for k in ('w', 'a', 'k', 'v')] != [4, 8, 4, 4] or q.get('tp', 1) != 1:
31
+ raise ValueError('Expected a W4A8KV4, TP=1 checkpoint.')
32
+ llm = LLM(model=str(path), dtype='bfloat16', tensor_parallel_size=1,
33
+ max_model_len=args.context_length, max_num_seqs=2,
34
+ max_num_batched_tokens=min(512, args.context_length),
35
+ gpu_memory_utilization=args.gpu_memory_utilization,
36
+ num_gpu_blocks_override=args.num_gpu_blocks,
37
+ enforce_eager=True, compilation_config=0,
38
+ enable_prefix_caching=False, seed=42)
39
+ if args.smoke_test:
40
+ requests = [{'prompt_token_ids': [3, 4, 5, 6]}, {'prompt_token_ids': [7, 8]}]
41
+ outputs = llm.generate(requests, SamplingParams(temperature=0, max_tokens=4,
42
+ ignore_eos=True, logprobs=1, prompt_logprobs=1), use_tqdm=False)
43
+ results = []
44
+ for item in outputs:
45
+ out = item.outputs[0]
46
+ assert len(out.token_ids) == 4
47
+ assert len(item.prompt_logprobs) == len(item.prompt_token_ids)
48
+ assert all(math.isfinite(scores[token].logprob) for token, scores in zip(out.token_ids, out.logprobs))
49
+ assert all(math.isfinite(scores[token].logprob) for token, scores in zip(item.prompt_token_ids[1:], item.prompt_logprobs[1:]))
50
+ results.append({'prompt': list(item.prompt_token_ids), 'generated': list(out.token_ids)})
51
+ print(json.dumps({'passed': True, 'check': 'full checkpoint prefill and cached decode', 'results': results}), flush=True)
52
+ else:
53
+ tokenizer = AutoTokenizer.from_pretrained(str(path), local_files_only=True)
54
+ prompt = tokenizer.apply_chat_template([{'role': 'user', 'content': args.prompt}],
55
+ tokenize=False, add_generation_prompt=True)
56
+ outputs = llm.generate([prompt], SamplingParams(temperature=0.6, top_p=0.95,
57
+ top_k=-1, max_tokens=args.max_new_tokens), use_tqdm=False)
58
+ print(outputs[0].outputs[0].text)
59
+
60
+
61
+ if __name__ == '__main__':
62
+ main()
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151646,
4
+ "do_sample": true,
5
+ "eos_token_id": 151643,
6
+ "temperature": 0.6,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.51.3"
9
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:661e4d3a689113b2c9898bf8bae1462b248b2993d3f6c9c37876d6674f818e48
3
+ size 3554214752
r1_quant_runtime/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Register the custom architecture required by this model."""
2
+ def register():
3
+ from vllm import ModelRegistry
4
+ ModelRegistry.register_model('Qwen2QuaRotForCausalLM', "r1_quant_runtime.model:Qwen2QuaRotForCausalLM")
r1_quant_runtime/model.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Packaging modification: imports adapted for this standalone checkpoint.
2
+ # Adapted from
3
+ # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/qwen2/modeling_qwen2.py
4
+ # Copyright 2024 The Qwen team.
5
+ # Copyright 2023 The vLLM team.
6
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
7
+ #
8
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
9
+ # and OPT implementations in this library. It has been modified from its
10
+ # original forms to accommodate minor architectural differences compared
11
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
12
+ #
13
+ # Licensed under the Apache License, Version 2.0 (the "License");
14
+ # you may not use this file except in compliance with the License.
15
+ # You may obtain a copy of the License at
16
+ #
17
+ # http://www.apache.org/licenses/LICENSE-2.0
18
+ #
19
+ # Unless required by applicable law or agreed to in writing, software
20
+ # distributed under the License is distributed on an "AS IS" BASIS,
21
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
+ # See the License for the specific language governing permissions and
23
+ # limitations under the License.
24
+ """Inference-only Qwen2 model compatible with HuggingFace weights."""
25
+ import math
26
+ import inspect
27
+ from typing import Iterable, List, Optional, Set, Tuple, Union
28
+
29
+ import torch
30
+ from torch import nn
31
+ from transformers import Qwen2Config
32
+ from .utils import hadamard_ops as fast_hadamard_transform
33
+
34
+ from vllm.attention import Attention, AttentionMetadata, AttentionType
35
+ from vllm.compilation.decorators import support_torch_compile
36
+ from vllm.config import CacheConfig, VllmConfig
37
+ from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
38
+ from vllm.logger import init_logger
39
+ from vllm.model_executor.layers.activation import SiluAndMul
40
+ from vllm.model_executor.layers.layernorm import RMSNorm
41
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
42
+ QKVParallelLinear,
43
+ RowParallelLinear)
44
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
45
+ from vllm.model_executor.layers.pooler import Pooler, PoolingType
46
+ from vllm.model_executor.layers.quantization import QuantizationConfig
47
+ from vllm.model_executor.layers.rotary_embedding import get_rope
48
+ from vllm.model_executor.layers.sampler import SamplerOutput, get_sampler
49
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
50
+ ParallelLMHead, VocabParallelEmbedding)
51
+ from vllm.model_executor.model_loader.weight_utils import (
52
+ default_weight_loader, maybe_remap_kv_scale_name)
53
+ from vllm.model_executor.pooling_metadata import PoolingMetadata
54
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
55
+ from vllm.sequence import IntermediateTensors, PoolerOutput
56
+
57
+ from vllm.model_executor.models.interfaces import SupportsLoRA, SupportsPP
58
+ from vllm.model_executor.models.utils import (AutoWeightsLoader, PPMissingLayer, WeightsMapper,
59
+ is_pp_missing_parameter,
60
+ make_empty_intermediate_tensors_factory, make_layers,
61
+ maybe_prefix)
62
+
63
+ from .utils.fake_quant_utils import ActivationQuantizer
64
+ from .utils import hadamard_utils
65
+
66
+ logger = init_logger(__name__)
67
+
68
+ # vLLM 0.9 carries cache tensors and metadata in its forward context.
69
+ _CONTEXT_ATTENTION = "kv_cache" not in inspect.signature(Attention.forward).parameters
70
+
71
+
72
+ class Qwen2MLP(nn.Module):
73
+
74
+ def __init__(
75
+ self,
76
+ hidden_size: int,
77
+ intermediate_size: int,
78
+ hidden_act: str,
79
+ fake_quant_config: dict,
80
+ quant_config: Optional[QuantizationConfig] = None,
81
+ prefix: str = "",
82
+ ) -> None:
83
+ super().__init__()
84
+ self.gate_up_proj = MergedColumnParallelLinear(
85
+ hidden_size,
86
+ [intermediate_size] * 2,
87
+ bias=False,
88
+ quant_config=quant_config,
89
+ prefix=f"{prefix}.gate_up_proj",
90
+ )
91
+ self.down_proj = RowParallelLinear(
92
+ intermediate_size,
93
+ hidden_size,
94
+ bias=False,
95
+ quant_config=quant_config,
96
+ prefix=f"{prefix}.down_proj",
97
+ )
98
+ if hidden_act != "silu":
99
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
100
+ "Only silu is supported for now.")
101
+ self.act_fn = SiluAndMul()
102
+
103
+ # fake quantization for activations
104
+ self.gate_up_quant = ActivationQuantizer(bits=fake_quant_config["a_bits"], sym=not fake_quant_config["a_asym"],
105
+ lac=False, groupsize=-1, clip_ratio=fake_quant_config["a_clip_ratio"])
106
+ self.down_quant = ActivationQuantizer(bits=fake_quant_config["a_bits"], sym=not fake_quant_config["a_asym"],
107
+ lac=False, groupsize=-1, clip_ratio=fake_quant_config["a_clip_ratio"])
108
+
109
+ # hadamard transformation
110
+ self.down_hadK, self.down_K = hadamard_utils.get_hadK(intermediate_size // self.down_proj.tp_size)
111
+
112
+ def forward(self, x):
113
+ x = self.gate_up_quant(x)
114
+ gate_up, _ = self.gate_up_proj(x)
115
+ x = self.act_fn(gate_up)
116
+ x = hadamard_utils.matmul_hadU_cuda(x, self.down_hadK, self.down_K)
117
+ x = self.down_quant(x)
118
+ x, _ = self.down_proj(x)
119
+ return x
120
+
121
+
122
+ class Qwen2Attention(nn.Module):
123
+
124
+ def __init__(self,
125
+ hidden_size: int,
126
+ num_heads: int,
127
+ num_kv_heads: int,
128
+ max_position: int = 4096 * 32,
129
+ rope_theta: float = 10000,
130
+ fake_quant_config: dict = None,
131
+ cache_config: Optional[CacheConfig] = None,
132
+ quant_config: Optional[QuantizationConfig] = None,
133
+ rope_scaling: Optional[Tuple] = None,
134
+ prefix: str = "",
135
+ attn_type: str = AttentionType.DECODER) -> None:
136
+ super().__init__()
137
+ self.hidden_size = hidden_size
138
+ tp_size = get_tensor_model_parallel_world_size()
139
+ self.total_num_heads = num_heads
140
+ assert self.total_num_heads % tp_size == 0
141
+ self.num_heads = self.total_num_heads // tp_size
142
+ self.total_num_kv_heads = num_kv_heads
143
+ if self.total_num_kv_heads >= tp_size:
144
+ # Number of KV heads is greater than TP size, so we partition
145
+ # the KV heads across multiple tensor parallel GPUs.
146
+ assert self.total_num_kv_heads % tp_size == 0
147
+ else:
148
+ # Number of KV heads is less than TP size, so we replicate
149
+ # the KV heads across multiple tensor parallel GPUs.
150
+ assert tp_size % self.total_num_kv_heads == 0
151
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
152
+ self.head_dim = hidden_size // self.total_num_heads
153
+ self.q_size = self.num_heads * self.head_dim
154
+ self.kv_size = self.num_kv_heads * self.head_dim
155
+ self.scaling = self.head_dim**-0.5
156
+ self.rope_theta = rope_theta
157
+
158
+ self.qkv_proj = QKVParallelLinear(
159
+ hidden_size,
160
+ self.head_dim,
161
+ self.total_num_heads,
162
+ self.total_num_kv_heads,
163
+ bias=True,
164
+ quant_config=quant_config,
165
+ prefix=f"{prefix}.qkv_proj",
166
+ )
167
+ self.o_proj = RowParallelLinear(
168
+ self.total_num_heads * self.head_dim,
169
+ hidden_size,
170
+ bias=False,
171
+ quant_config=quant_config,
172
+ prefix=f"{prefix}.o_proj",
173
+ )
174
+
175
+ self.rotary_emb = get_rope(
176
+ self.head_dim,
177
+ rotary_dim=self.head_dim,
178
+ max_position=max_position,
179
+ base=self.rope_theta,
180
+ rope_scaling=rope_scaling,
181
+ )
182
+ self.attn = Attention(self.num_heads,
183
+ self.head_dim,
184
+ self.scaling,
185
+ num_kv_heads=self.num_kv_heads,
186
+ cache_config=cache_config,
187
+ quant_config=quant_config,
188
+ prefix=f"{prefix}.attn",
189
+ attn_type=attn_type)
190
+
191
+ # fake quantization for activations
192
+ self.qkv_quant = ActivationQuantizer(bits=fake_quant_config["a_bits"], sym=not fake_quant_config["a_asym"],
193
+ lac=False, groupsize=-1, clip_ratio=fake_quant_config["a_clip_ratio"])
194
+ self.o_quant = ActivationQuantizer(bits=fake_quant_config["a_bits"], sym=not fake_quant_config["a_asym"],
195
+ lac=False, groupsize=-1, clip_ratio=fake_quant_config["a_clip_ratio"])
196
+ self.k_cache_quant = ActivationQuantizer(bits=fake_quant_config["k_bits"], sym=not fake_quant_config["k_asym"],
197
+ lac=False, groupsize=fake_quant_config["k_groupsize"], clip_ratio=fake_quant_config["k_clip_ratio"])
198
+ self.v_cache_quant = ActivationQuantizer(bits=fake_quant_config["v_bits"], sym=not fake_quant_config["v_asym"],
199
+ lac=False, groupsize=fake_quant_config["v_groupsize"], clip_ratio=fake_quant_config["v_clip_ratio"])
200
+
201
+ # TP=1 folds a full hidden-width rotation into o_proj. The V
202
+ # projection supplies its within-head part; complete it across heads
203
+ # after attention. For TP>1 the export uses within-head rotation only.
204
+ self.o_online_had = tp_size == 1
205
+ o_hadK, self.o_K = hadamard_utils.get_hadK(self.num_heads) if self.o_online_had else (None, 1)
206
+ self.register_buffer("o_hadK", o_hadK, persistent=False)
207
+
208
+ def forward(
209
+ self,
210
+ positions: torch.Tensor,
211
+ hidden_states: torch.Tensor,
212
+ kv_cache: Optional[torch.Tensor] = None,
213
+ attn_metadata: Optional[AttentionMetadata] = None,
214
+ ) -> torch.Tensor:
215
+ hidden_states = self.qkv_quant(hidden_states)
216
+ qkv, _ = self.qkv_proj(hidden_states)
217
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
218
+ q, k = self.rotary_emb(positions, q, k)
219
+ q, k = self.qk_had_trans(q, k)
220
+ k = self.k_cache_quant(k)
221
+ v = self.v_cache_quant(v)
222
+ if _CONTEXT_ATTENTION:
223
+ attn_output = self.attn(q, k, v)
224
+ else:
225
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
226
+ if self.o_online_had:
227
+ attn_output = self.o_had_trans(attn_output)
228
+ attn_output = self.o_quant(attn_output)
229
+ output, _ = self.o_proj(attn_output)
230
+ return output
231
+
232
+ def o_had_trans(self, x):
233
+ shape = x.shape
234
+ heads_last = x.reshape(-1, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
235
+ rotated = hadamard_utils.matmul_hadU_cuda(heads_last, self.o_hadK, self.o_K)
236
+ return rotated.transpose(1, 2).reshape(shape)
237
+
238
+ def qk_had_trans(self, q, k):
239
+ init_q_shape, init_k_shape = q.shape, k.shape
240
+ dtype = q.dtype
241
+ q = q.reshape(-1, self.head_dim)
242
+ k = k.reshape(-1, self.head_dim)
243
+ q = fast_hadamard_transform.hadamard_transform(q.float(), scale=1/math.sqrt(q.shape[-1])).to(dtype)
244
+ k = fast_hadamard_transform.hadamard_transform(k.float(), scale=1/math.sqrt(k.shape[-1])).to(dtype)
245
+ q = q.reshape(*init_q_shape)
246
+ k = k.reshape(*init_k_shape)
247
+ return q, k
248
+
249
+
250
+ class Qwen2DecoderLayer(nn.Module):
251
+
252
+ def __init__(
253
+ self,
254
+ config: Qwen2Config,
255
+ cache_config: Optional[CacheConfig] = None,
256
+ quant_config: Optional[QuantizationConfig] = None,
257
+ prefix: str = "",
258
+ ) -> None:
259
+ super().__init__()
260
+ self.hidden_size = config.hidden_size
261
+ # Requires transformers > 4.32.0
262
+ rope_theta = getattr(config, "rope_theta", 1000000)
263
+ rope_scaling = getattr(config, "rope_scaling", None)
264
+
265
+ # By default, Qwen2 uses causal attention as it is a decoder-only model.
266
+ # You can override the HF config with `is_causal=False` to enable
267
+ # bidirectional attention, which is used in some embedding models
268
+ # (e.g. Alibaba-NLP/gte-Qwen2-7B-instruct)
269
+ if getattr(config, "is_causal", True):
270
+ attn_type = AttentionType.DECODER
271
+ else:
272
+ attn_type = AttentionType.ENCODER_ONLY
273
+
274
+ self.self_attn = Qwen2Attention(
275
+ hidden_size=self.hidden_size,
276
+ num_heads=config.num_attention_heads,
277
+ max_position=config.max_position_embeddings,
278
+ num_kv_heads=config.num_key_value_heads,
279
+ rope_theta=rope_theta,
280
+ cache_config=cache_config,
281
+ fake_quant_config=config.fake_quant_config,
282
+ quant_config=quant_config,
283
+ rope_scaling=rope_scaling,
284
+ prefix=f"{prefix}.self_attn",
285
+ attn_type=attn_type,
286
+ )
287
+ self.mlp = Qwen2MLP(
288
+ hidden_size=self.hidden_size,
289
+ intermediate_size=config.intermediate_size,
290
+ hidden_act=config.hidden_act,
291
+ fake_quant_config=config.fake_quant_config,
292
+ quant_config=quant_config,
293
+ prefix=f"{prefix}.mlp",
294
+ )
295
+ self.input_layernorm = RMSNorm(config.hidden_size,
296
+ eps=config.rms_norm_eps)
297
+ self.post_attention_layernorm = RMSNorm(config.hidden_size,
298
+ eps=config.rms_norm_eps)
299
+
300
+ def forward(
301
+ self,
302
+ positions: torch.Tensor,
303
+ hidden_states: torch.Tensor,
304
+ kv_cache: torch.Tensor,
305
+ attn_metadata: AttentionMetadata,
306
+ residual: Optional[torch.Tensor],
307
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
308
+ # Self Attention
309
+ if residual is None:
310
+ residual = hidden_states
311
+ hidden_states = self.input_layernorm(hidden_states)
312
+ else:
313
+ hidden_states, residual = self.input_layernorm(
314
+ hidden_states, residual)
315
+ hidden_states = self.self_attn(
316
+ positions=positions,
317
+ hidden_states=hidden_states,
318
+ kv_cache=kv_cache,
319
+ attn_metadata=attn_metadata,
320
+ )
321
+
322
+ # Fully Connected
323
+ hidden_states, residual = self.post_attention_layernorm(
324
+ hidden_states, residual)
325
+ hidden_states = self.mlp(hidden_states)
326
+ return hidden_states, residual
327
+
328
+
329
+ @support_torch_compile(
330
+ dynamic_arg_dims={
331
+ "input_ids": 0,
332
+ # positions is of shape (3, seq_len) if mrope is enabled for qwen2-vl,
333
+ # otherwise (seq_len, ).
334
+ "positions": -1,
335
+ "intermediate_tensors": 0,
336
+ "inputs_embeds": 0,
337
+ })
338
+ class Qwen2Model(nn.Module):
339
+
340
+ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
341
+ super().__init__()
342
+
343
+ config = vllm_config.model_config.hf_config
344
+ cache_config = vllm_config.cache_config
345
+ quant_config = vllm_config.quant_config
346
+
347
+ # TODO (@robertgshaw2): see if this can be moved out
348
+ if (cache_config.sliding_window is not None
349
+ and hasattr(config, "max_window_layers")):
350
+ raise ValueError("Sliding window for some but all layers is not "
351
+ "supported. This model uses sliding window "
352
+ "but `max_window_layers` = {} is less than "
353
+ "`num_hidden_layers` = {}. Please open an issue "
354
+ "to discuss this feature.".format(
355
+ config.max_window_layers,
356
+ config.num_hidden_layers,
357
+ ))
358
+
359
+ self.config = config
360
+ self.quant_config = quant_config
361
+ self.padding_idx = config.pad_token_id
362
+ self.vocab_size = config.vocab_size
363
+
364
+ if get_pp_group().is_first_rank or (config.tie_word_embeddings
365
+ and get_pp_group().is_last_rank):
366
+ self.embed_tokens = VocabParallelEmbedding(
367
+ config.vocab_size,
368
+ config.hidden_size,
369
+ quant_config=quant_config,
370
+ prefix=f"{prefix}.embed_tokens",
371
+ )
372
+ else:
373
+ self.embed_tokens = PPMissingLayer()
374
+
375
+ self.start_layer, self.end_layer, self.layers = make_layers(
376
+ config.num_hidden_layers,
377
+ lambda prefix: Qwen2DecoderLayer(config=config,
378
+ cache_config=cache_config,
379
+ quant_config=quant_config,
380
+ prefix=prefix),
381
+ prefix=f"{prefix}.layers",
382
+ )
383
+
384
+ self.make_empty_intermediate_tensors = (
385
+ make_empty_intermediate_tensors_factory(
386
+ ["hidden_states", "residual"], config.hidden_size))
387
+ if get_pp_group().is_last_rank:
388
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
389
+ else:
390
+ self.norm = PPMissingLayer()
391
+
392
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
393
+ return self.embed_tokens(input_ids)
394
+
395
+ def forward(
396
+ self,
397
+ input_ids: torch.Tensor,
398
+ positions: torch.Tensor,
399
+ kv_caches: Optional[List[torch.Tensor]] = None,
400
+ attn_metadata: Optional[AttentionMetadata] = None,
401
+ intermediate_tensors: Optional[IntermediateTensors] = None,
402
+ inputs_embeds: Optional[torch.Tensor] = None,
403
+ ) -> Union[torch.Tensor, IntermediateTensors]:
404
+ if get_pp_group().is_first_rank:
405
+ if inputs_embeds is not None:
406
+ hidden_states = inputs_embeds
407
+ else:
408
+ hidden_states = self.get_input_embeddings(input_ids)
409
+ residual = None
410
+ else:
411
+ assert intermediate_tensors is not None
412
+ hidden_states = intermediate_tensors["hidden_states"]
413
+ residual = intermediate_tensors["residual"]
414
+ for i in range(self.start_layer, self.end_layer):
415
+ layer = self.layers[i]
416
+ hidden_states, residual = layer(
417
+ positions,
418
+ hidden_states,
419
+ kv_caches[i - self.start_layer] if kv_caches is not None else None,
420
+ attn_metadata,
421
+ residual,
422
+ )
423
+ if not get_pp_group().is_last_rank:
424
+ return IntermediateTensors({
425
+ "hidden_states": hidden_states,
426
+ "residual": residual
427
+ })
428
+ hidden_states, _ = self.norm(hidden_states, residual)
429
+ return hidden_states
430
+
431
+ def load_weights(self, weights: Iterable[Tuple[str,
432
+ torch.Tensor]]) -> Set[str]:
433
+ stacked_params_mapping = [
434
+ # (param_name, shard_name, shard_id)
435
+ ("qkv_proj", "q_proj", "q"),
436
+ ("qkv_proj", "k_proj", "k"),
437
+ ("qkv_proj", "v_proj", "v"),
438
+ ("gate_up_proj", "gate_proj", 0),
439
+ ("gate_up_proj", "up_proj", 1),
440
+ ]
441
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
442
+ loaded_params: Set[str] = set()
443
+ for name, loaded_weight in weights:
444
+ if "rotary_emb.inv_freq" in name:
445
+ continue
446
+ if (self.quant_config is not None and
447
+ (scale_name := self.quant_config.get_cache_scale(name))):
448
+ # Loading kv cache quantization scales
449
+ param = params_dict[scale_name]
450
+ weight_loader = getattr(param, "weight_loader",
451
+ default_weight_loader)
452
+ loaded_weight = (loaded_weight if loaded_weight.dim() == 0 else
453
+ loaded_weight[0])
454
+ weight_loader(param, loaded_weight)
455
+ loaded_params.add(scale_name)
456
+ continue
457
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
458
+ if weight_name not in name:
459
+ continue
460
+ name = name.replace(weight_name, param_name)
461
+ # Skip loading extra bias for GPTQ models.
462
+ if name.endswith(".bias") and name not in params_dict:
463
+ continue
464
+ if is_pp_missing_parameter(name, self):
465
+ continue
466
+ param = params_dict[name]
467
+ weight_loader = param.weight_loader
468
+ weight_loader(param, loaded_weight, shard_id)
469
+ break
470
+ else:
471
+ # Skip loading extra bias for GPTQ models.
472
+ if name.endswith(".bias") and name not in params_dict:
473
+ continue
474
+ # Remapping the name of FP8 kv-scale.
475
+ name = maybe_remap_kv_scale_name(name, params_dict)
476
+ if name is None:
477
+ continue
478
+ if is_pp_missing_parameter(name, self):
479
+ continue
480
+ param = params_dict[name]
481
+ weight_loader = getattr(param, "weight_loader",
482
+ default_weight_loader)
483
+ weight_loader(param, loaded_weight)
484
+ loaded_params.add(name)
485
+ return loaded_params
486
+
487
+
488
+ class Qwen2QuaRotForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
489
+ packed_modules_mapping = {
490
+ "qkv_proj": [
491
+ "q_proj",
492
+ "k_proj",
493
+ "v_proj",
494
+ ],
495
+ "gate_up_proj": [
496
+ "gate_proj",
497
+ "up_proj",
498
+ ],
499
+ }
500
+
501
+ # LoRA specific attributes
502
+ supported_lora_modules = [
503
+ "qkv_proj",
504
+ "o_proj",
505
+ "gate_up_proj",
506
+ "down_proj",
507
+ ]
508
+ embedding_modules = {}
509
+ embedding_padding_modules = []
510
+
511
+ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
512
+ super().__init__()
513
+ config = vllm_config.model_config.hf_config
514
+ quant_config = vllm_config.quant_config
515
+ lora_config = vllm_config.lora_config
516
+
517
+ self.config = config
518
+ self.lora_config = lora_config
519
+
520
+ self.quant_config = quant_config
521
+ self.model = Qwen2Model(vllm_config=vllm_config,
522
+ prefix=maybe_prefix(prefix, "model"))
523
+
524
+ if get_pp_group().is_last_rank:
525
+ if config.tie_word_embeddings:
526
+ self.lm_head = self.model.embed_tokens
527
+ else:
528
+ self.lm_head = ParallelLMHead(config.vocab_size,
529
+ config.hidden_size,
530
+ quant_config=quant_config,
531
+ prefix=maybe_prefix(
532
+ prefix, "lm_head"))
533
+ else:
534
+ self.lm_head = PPMissingLayer()
535
+
536
+ self.logits_processor = LogitsProcessor(config.vocab_size)
537
+ self.sampler = get_sampler()
538
+
539
+ self.make_empty_intermediate_tensors = (
540
+ self.model.make_empty_intermediate_tensors)
541
+
542
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
543
+ return self.model.get_input_embeddings(input_ids)
544
+
545
+ def forward(
546
+ self,
547
+ input_ids: torch.Tensor,
548
+ positions: torch.Tensor,
549
+ kv_caches: Optional[List[torch.Tensor]] = None,
550
+ attn_metadata: Optional[AttentionMetadata] = None,
551
+ intermediate_tensors: Optional[IntermediateTensors] = None,
552
+ inputs_embeds: Optional[torch.Tensor] = None,
553
+ ) -> Union[torch.Tensor, IntermediateTensors]:
554
+ hidden_states = self.model(input_ids, positions, kv_caches,
555
+ attn_metadata, intermediate_tensors,
556
+ inputs_embeds)
557
+ return hidden_states
558
+
559
+ def compute_logits(
560
+ self,
561
+ hidden_states: torch.Tensor,
562
+ sampling_metadata: SamplingMetadata,
563
+ ) -> Optional[torch.Tensor]:
564
+ logits = self.logits_processor(self.lm_head, hidden_states,
565
+ sampling_metadata)
566
+ return logits
567
+
568
+ def sample(
569
+ self,
570
+ logits: torch.Tensor,
571
+ sampling_metadata: SamplingMetadata,
572
+ ) -> Optional[SamplerOutput]:
573
+ next_tokens = self.sampler(logits, sampling_metadata)
574
+ return next_tokens
575
+
576
+ def load_weights(self, weights: Iterable[Tuple[str,
577
+ torch.Tensor]]) -> Set[str]:
578
+ loader = AutoWeightsLoader(
579
+ self,
580
+ skip_prefixes=(["lm_head."]
581
+ if self.config.tie_word_embeddings else None),
582
+ )
583
+ return loader.load_weights(weights)
584
+
585
+
586
+ class Qwen2EmbeddingModel(nn.Module, SupportsLoRA, SupportsPP):
587
+ packed_modules_mapping = {
588
+ "qkv_proj": [
589
+ "q_proj",
590
+ "k_proj",
591
+ "v_proj",
592
+ ],
593
+ "gate_up_proj": [
594
+ "gate_proj",
595
+ "up_proj",
596
+ ],
597
+ }
598
+
599
+ # LoRA specific attributes
600
+ supported_lora_modules = [
601
+ "qkv_proj",
602
+ "o_proj",
603
+ "gate_up_proj",
604
+ "down_proj",
605
+ ]
606
+ embedding_modules = {}
607
+ embedding_padding_modules = []
608
+
609
+ hf_to_vllm_mapper = WeightsMapper(orig_to_new_prefix={"model.": ""})
610
+
611
+ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
612
+ super().__init__()
613
+ config = vllm_config.model_config.hf_config
614
+ quant_config = vllm_config.quant_config
615
+ lora_config = vllm_config.lora_config
616
+ pooler_config = vllm_config.model_config.pooler_config
617
+
618
+ self.config = config
619
+ self.lora_config = lora_config
620
+
621
+ self.quant_config = quant_config
622
+ self.model = Qwen2Model(vllm_config=vllm_config,
623
+ prefix=maybe_prefix(prefix, "model"))
624
+
625
+ # TODO: Replace this model class with as_embedding_model(
626
+ # Qwen2ForCausalLM) after changing the default pooling method
627
+ if pooler_config.pooling_type is None:
628
+ logger.warning(
629
+ "This embedding model will default to last-token pooling in "
630
+ "an upcoming version. To avoid breaking changes, you should "
631
+ "pass `--override-pooler-config '{\"pooling_type\": \"MEAN\"}'`"
632
+ " explicitly.")
633
+
634
+ self._pooler = Pooler.from_config_with_defaults(
635
+ pooler_config,
636
+ pooling_type=PoolingType.MEAN,
637
+ normalize=True,
638
+ softmax=False)
639
+
640
+ def forward(
641
+ self,
642
+ input_ids: torch.Tensor,
643
+ positions: torch.Tensor,
644
+ kv_caches: Optional[List[torch.Tensor]] = None,
645
+ attn_metadata: Optional[AttentionMetadata] = None,
646
+ intermediate_tensors: Optional[IntermediateTensors] = None,
647
+ ) -> torch.Tensor:
648
+ return self.model(input_ids, positions, kv_caches, attn_metadata,
649
+ intermediate_tensors)
650
+
651
+ def pooler(
652
+ self,
653
+ hidden_states: torch.Tensor,
654
+ pooling_metadata: PoolingMetadata,
655
+ ) -> Optional[PoolerOutput]:
656
+ return self._pooler(hidden_states, pooling_metadata)
657
+
658
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
659
+ weights = self.hf_to_vllm_mapper.apply(weights)
660
+ weights = ((name, data) for name, data in weights
661
+ if not name.startswith("lm_head."))
662
+ self.model.load_weights(weights)
r1_quant_runtime/utils/__init__.py ADDED
File without changes
r1_quant_runtime/utils/fake_quant_utils.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ def round_ste(x: torch.Tensor):
4
+ """
5
+ Implement Straight-Through Estimator for rounding operation.
6
+ """
7
+ return (x.round() - x).detach() + x
8
+
9
+
10
+ def format_scale(scale: torch.Tensor, scale_format: str):
11
+ if scale_format == "fp32":
12
+ return scale
13
+ if scale_format != "ue8m0":
14
+ raise ValueError(f"Unsupported scale format: {scale_format}")
15
+ safe_scale = scale.float().clamp_min(torch.finfo(torch.float32).tiny)
16
+ return torch.pow(2.0, torch.ceil(torch.log2(safe_scale))).to(scale.dtype)
17
+
18
+
19
+ def _sync_tensor_parallel_extrema(xmax, xmin):
20
+ """Return extrema over all TP shards using one two-scalar collective."""
21
+ from vllm.distributed import (
22
+ get_tensor_model_parallel_world_size,
23
+ tensor_model_parallel_all_gather,
24
+ )
25
+
26
+ world_size = get_tensor_model_parallel_world_size()
27
+ if world_size == 1:
28
+ return xmax, xmin
29
+ local = torch.stack((xmax.reshape(-1)[0], xmin.reshape(-1)[0]))
30
+ gathered = tensor_model_parallel_all_gather(local, dim=0).reshape(
31
+ world_size, 2
32
+ )
33
+ return (
34
+ gathered[:, 0].amax().reshape_as(xmax),
35
+ gathered[:, 1].amin().reshape_as(xmin),
36
+ )
37
+
38
+
39
+ def get_qmin_qmax(bits, sym):
40
+ if sym:
41
+ q_max = torch.tensor(2 ** (bits - 1) - 1)
42
+ q_min = -q_max -1
43
+ else:
44
+ q_max, q_min = torch.tensor(2 ** bits - 1), 0
45
+ return q_max, q_min
46
+
47
+
48
+ def sym_quant(x, scale, maxq):
49
+ scale = scale.to(x.device)
50
+ q = torch.clamp(round_ste(x / scale), -(maxq + 1), maxq)
51
+ return q, scale
52
+
53
+
54
+ def sym_dequant(q, scale):
55
+ return scale * q
56
+
57
+
58
+ def sym_quant_dequant(x, scale, maxq):
59
+ return sym_dequant(*sym_quant(x, scale, maxq))
60
+
61
+
62
+ def asym_quant(x, scale, zero, maxq):
63
+ scale = scale.to(x.device)
64
+ zero = zero.to(x.device)
65
+ q = torch.clamp(round_ste(x / scale) + zero, 0, maxq)
66
+ return q, scale, zero
67
+
68
+
69
+ def asym_dequant(q, scale, zero):
70
+ return scale * (q - zero)
71
+
72
+
73
+ def asym_quant_dequant(x, scale, zero, maxq):
74
+ return asym_dequant(*asym_quant(x, scale, zero, maxq))
75
+
76
+
77
+ class ActivationQuantizer(torch.nn.Module):
78
+ """Runtime activation fake quantizer matching the calibration semantics."""
79
+ def __init__(
80
+ self,
81
+ bits,
82
+ sym=False,
83
+ lac=False,
84
+ groupsize=-1,
85
+ num_groups=None,
86
+ clip_ratio=None,
87
+ granularity="per_token",
88
+ scale_format="fp32",
89
+ sync_tensor_parallel=False,
90
+ ):
91
+ super(ActivationQuantizer, self).__init__()
92
+ self.bits = bits
93
+ self.q_max, self.q_min = get_qmin_qmax(bits, sym)
94
+ self.sym = sym
95
+ self.groupsize = groupsize
96
+ self.num_groups = num_groups
97
+ self.granularity = granularity
98
+ self.scale_format = scale_format
99
+ self.sync_tensor_parallel = sync_tensor_parallel
100
+ if self.granularity not in {"per_token", "per_tensor"}:
101
+ raise ValueError(
102
+ f"Unsupported activation granularity: {self.granularity}"
103
+ )
104
+ if self.scale_format not in {"fp32", "ue8m0"}:
105
+ raise ValueError(f"Unsupported scale format: {self.scale_format}")
106
+ if self.granularity == "per_tensor" and self.num_groups not in (None, 1):
107
+ raise ValueError("Per-tensor activation quantization uses one group")
108
+ if self.granularity == "per_tensor" and self.groupsize != -1:
109
+ raise ValueError("Per-tensor activation quantization uses groupsize=-1")
110
+ if self.groupsize == 0 or self.groupsize < -1:
111
+ raise ValueError("Activation groupsize must be -1 or positive")
112
+ if (
113
+ self.groupsize > 0
114
+ and self.num_groups is not None
115
+ and self.num_groups <= 0
116
+ ):
117
+ raise ValueError("Grouped activation quantization needs num_groups > 0")
118
+ if self.granularity == "per_tensor" or self.groupsize == -1:
119
+ self.num_groups = 1 if self.num_groups is None else self.num_groups
120
+ if self.sync_tensor_parallel and self.granularity != "per_tensor":
121
+ raise ValueError("TP extrema synchronization requires per-tensor A quantization")
122
+ self.lac = lac
123
+ self._clip_ratio = clip_ratio
124
+ if self.lac:
125
+ init_value = 4.
126
+ self.sigmoid = torch.nn.Sigmoid()
127
+ self.clip_factor_a_max = torch.nn.Parameter(
128
+ torch.ones((self.num_groups or 1, )) * init_value,
129
+ requires_grad=True,
130
+ )
131
+ self.clip_factor_a_min = torch.nn.Parameter(
132
+ torch.ones((self.num_groups or 1, )) * init_value,
133
+ requires_grad=True,
134
+ )
135
+
136
+ self.enable = True
137
+
138
+ def forward(self, x, scale=None, zero=None):
139
+ if self.bits == 16 or (not self.enable):
140
+ return x
141
+ init_shape = x.shape
142
+ if self.granularity == "per_tensor":
143
+ x = x.reshape(1, 1, -1)
144
+ else:
145
+ if self.groupsize > 0:
146
+ if init_shape[-1] % self.groupsize:
147
+ raise ValueError(
148
+ f"Activation width {init_shape[-1]} is not divisible "
149
+ f"by group size {self.groupsize}"
150
+ )
151
+ inferred_num_groups = init_shape[-1] // self.groupsize
152
+ if (
153
+ self.num_groups is not None
154
+ and self.num_groups != inferred_num_groups
155
+ ):
156
+ raise ValueError(
157
+ f"Activation width {init_shape[-1]} does not match "
158
+ f"{self.num_groups} groups of {self.groupsize}"
159
+ )
160
+ num_groups = inferred_num_groups
161
+ else:
162
+ num_groups = self.num_groups
163
+ x = x.reshape(
164
+ -1,
165
+ num_groups,
166
+ init_shape[-1] if self.groupsize == -1 else self.groupsize,
167
+ )
168
+ fq_x = self.fake_quant(x, scale, zero)
169
+ return fq_x.reshape(*init_shape)
170
+
171
+ def fake_quant(self, x, scale=None, zero=None):
172
+ x_dtype = x.dtype
173
+ if scale is None or zero is None:
174
+ scale, zero = self.get_scale_zero(x)
175
+ if self.sym:
176
+ return sym_quant_dequant(x, scale, self.q_max.to(x)).to(x_dtype)
177
+ else:
178
+ return asym_quant_dequant(x, scale, zero, self.q_max.to(x)).to(x_dtype) # TODO
179
+
180
+ def get_scale_zero(self, x):
181
+ q_max = self.q_max.to(x)
182
+ init_shape = x.shape
183
+ xmax, xmin = x.amax(-1, keepdim=True), x.amin(-1, keepdim=True)
184
+ tmp = torch.zeros_like(xmax)
185
+ xmax, xmin = torch.maximum(xmax, tmp), torch.minimum(xmin, tmp)
186
+ if self.sync_tensor_parallel:
187
+ xmax, xmin = _sync_tensor_parallel_extrema(xmax, xmin)
188
+ # # if self.groupsize > 0:
189
+ # # assert x.shape[-1] % self.groupsize == 0
190
+ # # x = x.reshape((-1, self.groupsize))
191
+ # # # TODO: add padding
192
+ if self.lac:
193
+ clip_shape = (1, self.clip_factor_a_max.numel(), 1)
194
+ xmax = xmax * self.sigmoid(self.clip_factor_a_max).reshape(
195
+ clip_shape
196
+ )
197
+ xmin = xmin * self.sigmoid(self.clip_factor_a_min).reshape(
198
+ clip_shape
199
+ )
200
+ elif self._clip_ratio is not None:
201
+ xmax = xmax * self._clip_ratio
202
+ xmin = xmin * self._clip_ratio
203
+ if self.sym:
204
+ xmax = torch.maximum(torch.abs(xmin), xmax)
205
+ tmp = xmax == 0
206
+ scale = (xmax / q_max)
207
+ scale[tmp] = 1
208
+ scale = format_scale(scale, self.scale_format)
209
+ if self.granularity != "per_tensor":
210
+ scale = scale.repeat(1, 1, x.shape[-1]).reshape(init_shape)
211
+ zero = torch.zeros_like(scale)
212
+ else:
213
+ tmp = (xmin == 0) & (xmax == 0)
214
+ xmin[tmp] = -1
215
+ xmax[tmp] = +1
216
+ scale = (xmax - xmin) / q_max
217
+ scale = format_scale(scale, self.scale_format)
218
+ zero = torch.round(-xmin / scale)
219
+
220
+ if self.granularity != "per_tensor":
221
+ scale = scale.repeat(1, 1, x.shape[-1]).reshape(init_shape)
222
+ zero = zero.repeat(1, 1, x.shape[-1]).reshape(init_shape)
223
+
224
+ return scale, zero
225
+
226
+
227
+ class WeightQuantizer(torch.nn.Module):
228
+ '''From GPTQ Repo'''
229
+
230
+ def __init__(self, shape=1):
231
+ super(WeightQuantizer, self).__init__()
232
+ self.register_buffer('maxq', torch.tensor(0))
233
+ self.register_buffer('scale', torch.zeros(shape))
234
+ self.register_buffer('zero', torch.zeros(shape))
235
+
236
+ self.enable = True
237
+
238
+ def configure(
239
+ self,
240
+ bits, perchannel=False, sym=True,
241
+ mse=False, norm=2.4, grid=100, maxshrink=.8
242
+ ):
243
+ self.bits = bits
244
+ self.perchannel = perchannel
245
+ self.sym = sym
246
+ self.mse = mse
247
+ self.norm = norm
248
+ self.grid = grid
249
+ self.maxshrink = maxshrink
250
+ if sym:
251
+ self.maxq = torch.tensor(2**(bits-1)-1)
252
+ else:
253
+ self.maxq = torch.tensor(2**bits - 1)
254
+
255
+ def find_params(self, x):
256
+ if self.bits == 16 or (not self.enable):
257
+ return
258
+ dev = x.device
259
+ self.maxq = self.maxq.to(dev)
260
+
261
+ shape = x.shape
262
+ if self.perchannel:
263
+ x = x.flatten(1)
264
+ else:
265
+ x = x.flatten().unsqueeze(0)
266
+
267
+ tmp = torch.zeros(x.shape[0], device=dev)
268
+ xmin = torch.minimum(x.min(1)[0], tmp)
269
+ xmax = torch.maximum(x.max(1)[0], tmp)
270
+
271
+ if self.sym:
272
+ xmax = torch.maximum(torch.abs(xmin), xmax).clamp(min=1e-5)
273
+ self.scale = xmax / self.maxq
274
+ self.zero = torch.zeros_like(self.scale)
275
+ else:
276
+ tmp = (xmin == 0) & (xmax == 0)
277
+ xmin[tmp] = -1
278
+ xmax[tmp] = +1
279
+ self.scale = (xmax - xmin).clamp(min=1e-5) / self.maxq
280
+ self.zero = torch.round(-xmin / self.scale)
281
+
282
+ if self.mse:
283
+ best = torch.full([x.shape[0]], float('inf'), device=dev)
284
+ for i in range(int(self.maxshrink * self.grid)):
285
+ p = 1 - i / self.grid
286
+ xmin1 = p * xmin
287
+ xmax1 = p * xmax
288
+
289
+ if self.sym:
290
+ scale1 = xmax1 / self.maxq
291
+ zero1 = torch.zeros_like(scale1)
292
+ q = sym_quant_dequant(x, scale1.unsqueeze(1), self.maxq)
293
+ else:
294
+
295
+ scale1 = (xmax1 - xmin1) / self.maxq
296
+ zero1 = torch.round(-xmin1 / scale1)
297
+ q = asym_quant_dequant(x, scale1.unsqueeze(1), zero1.unsqueeze(1), self.maxq)
298
+
299
+ q -= x
300
+ q.abs_()
301
+ q.pow_(self.norm)
302
+ err = torch.sum(q, 1)
303
+ tmp = err < best
304
+ if torch.any(tmp):
305
+ best[tmp] = err[tmp]
306
+ self.scale[tmp] = scale1[tmp]
307
+ self.zero[tmp] = zero1[tmp]
308
+ if not self.perchannel:
309
+
310
+ tmp = shape[0]
311
+ self.scale = self.scale.repeat(tmp)
312
+ self.zero = self.zero.repeat(tmp)
313
+
314
+ shape = [-1] + [1] * (len(shape) - 1)
315
+ self.scale = self.scale.reshape(shape)
316
+ self.zero = self.zero.reshape(shape)
317
+ return
318
+
319
+ def quantize(self, x):
320
+ x_dtype = x.dtype
321
+ if self.enable and self.ready() and self.bits < 16:
322
+ if self.sym:
323
+ return sym_quant_dequant(x, self.scale, self.maxq).to(x_dtype)
324
+ return asym_quant_dequant(x, self.scale, self.zero, self.maxq).to(x_dtype)
325
+ return x
326
+
327
+ def forward(self, x):
328
+ return self.quantize(x)
329
+
330
+ def enabled(self):
331
+ return self.maxq > 0
332
+
333
+ def ready(self):
334
+ return torch.all(self.scale != 0)
335
+
336
+
337
+ def set_quantizer_state(model, enable=True):
338
+ for m in model.modules():
339
+ if isinstance(m, (WeightQuantizer, ActivationQuantizer)):
340
+ m.enable = enable
341
+ return model
342
+
343
+
344
+ def set_weight_quantizer_state(model, enable=True):
345
+ for m in model.modules():
346
+ if isinstance(m, WeightQuantizer):
347
+ m.enable = enable
348
+ return model
349
+
350
+
351
+ def set_act_quantizer_state(model, enable=True):
352
+ for m in model.modules():
353
+ if isinstance(m, ActivationQuantizer):
354
+ m.enable = enable
355
+ return model
r1_quant_runtime/utils/hadamard_ops.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Power-of-two Walsh-Hadamard transform with an optional CUDA extension."""
2
+ import warnings
3
+
4
+ import torch
5
+
6
+ try:
7
+ from fast_hadamard_transform import hadamard_transform as _cuda_hadamard
8
+ except ImportError:
9
+ _cuda_hadamard = None
10
+ warnings.warn(
11
+ "fast_hadamard_transform is not installed. The online rotations fall back "
12
+ "to a Walsh-Hadamard matmul, which costs an extra kernel per rotation and "
13
+ "slows quantized decoding down. Install the extension for the fast path.",
14
+ RuntimeWarning)
15
+
16
+ _MATRIX_CACHE = {}
17
+
18
+
19
+ def _hadamard_matrix(n, device, dtype):
20
+ """Sylvester-ordered H_n, the same ordering as the butterfly recursion."""
21
+ key = (n, device, dtype)
22
+ matrix = _MATRIX_CACHE.get(key)
23
+ if matrix is None:
24
+ matrix = torch.ones(1, 1, device=device, dtype=dtype)
25
+ while matrix.shape[0] < n:
26
+ matrix = torch.cat((torch.cat((matrix, matrix), dim=1),
27
+ torch.cat((matrix, -matrix), dim=1)), dim=0)
28
+ _MATRIX_CACHE[key] = matrix
29
+ return matrix
30
+
31
+
32
+ def hadamard_transform(x, scale=1.0):
33
+ n = x.shape[-1]
34
+ if n <= 0 or n & (n - 1):
35
+ raise ValueError(f"Walsh-Hadamard dimension must be a power of two: {n}")
36
+ if _cuda_hadamard is not None and x.is_cuda:
37
+ return _cuda_hadamard(x.contiguous(), scale=float(scale))
38
+ dtype = x.dtype
39
+ work = x.float() if dtype in (torch.float16, torch.bfloat16) else x
40
+ # H is symmetric, so `work @ H` is the same transform the butterfly below
41
+ # computes, in one kernel instead of log2(n). TF32 would round the ±1
42
+ # products of an FP32 source, so that mode keeps the exact recursion.
43
+ if work.is_cuda and not torch.backends.cuda.matmul.allow_tf32:
44
+ work = work @ _hadamard_matrix(n, work.device, work.dtype)
45
+ return (work * scale).to(dtype)
46
+ shape = work.shape
47
+ width = 1
48
+ while width < n:
49
+ blocks = work.reshape(*shape[:-1], -1, 2, width)
50
+ left, right = blocks.unbind(-2)
51
+ work = torch.stack((left + right, left - right), dim=-2).reshape(shape)
52
+ width *= 2
53
+ return (work * scale).to(dtype)
r1_quant_runtime/utils/hadamard_utils.py ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch==2.7.0
2
+ transformers==4.51.3
3
+ vllm==0.9.0
4
+ safetensors>=0.4.3
5
+ numpy>=1.26,<2
6
+ scipy>=1.11
7
+ huggingface_hub>=0.30,<1.0
runtime-provenance.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "r1_quant_runtime/model.py": {
3
+ "original_relative_path": "vllm_custom/model_executor/fake_quantized_models/qwen2_quarot.py",
4
+ "original_sha256": "82727ba2547342fcc75d177dc035db9e7cf28046c75e4c6bd3a05a7d3beb391f",
5
+ "packaged_sha256": "921489754ec76c191d06980d1e14c4d775090cdbd0f7ca307a6ab41e9e01a0de",
6
+ "changes": [
7
+ "Imports relocated into the standalone r1_quant_runtime package."
8
+ ]
9
+ },
10
+ "r1_quant_runtime/utils/fake_quant_utils.py": {
11
+ "original_relative_path": "vllm_custom/model_executor/layers/quantization/utils/fake_quant_utils.py",
12
+ "original_sha256": "2ac96df145e404b488115c087bc0f8bef56f00c3e9cbc325d309faf1565f7015",
13
+ "packaged_sha256": "2ac96df145e404b488115c087bc0f8bef56f00c3e9cbc325d309faf1565f7015",
14
+ "changes": []
15
+ },
16
+ "r1_quant_runtime/utils/hadamard_ops.py": {
17
+ "original_relative_path": "methods/utils/hadamard_ops.py",
18
+ "original_sha256": "ff633fb9debddff5185e9eb3c6d7ce52d2afbe0edb87e2044977d87cefac5162",
19
+ "packaged_sha256": "ff633fb9debddff5185e9eb3c6d7ce52d2afbe0edb87e2044977d87cefac5162",
20
+ "changes": []
21
+ },
22
+ "r1_quant_runtime/utils/hadamard_utils.py": {
23
+ "original_relative_path": "methods/utils/hadamard_utils.py",
24
+ "original_sha256": "0bfcb099762a7bf7cb7d32646de3f293d60a0834e5474330b4897945236927f0",
25
+ "packaged_sha256": "0bfcb099762a7bf7cb7d32646de3f293d60a0834e5474330b4897945236927f0",
26
+ "changes": []
27
+ }
28
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin▁of▁sentence|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end▁of▁sentence|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|end▁of▁sentence|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e20ddafc659ba90242154b55275402edeca0715e5dbb30f56815a4ce081f4893
3
+ size 11422778
tokenizer_config.json ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "151643": {
7
+ "content": "<|end▁of▁sentence|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "151644": {
15
+ "content": "<|User|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": false
21
+ },
22
+ "151645": {
23
+ "content": "<|Assistant|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "151646": {
31
+ "content": "<|begin▁of▁sentence|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "151647": {
39
+ "content": "<|EOT|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": false
45
+ },
46
+ "151648": {
47
+ "content": "<think>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": false
53
+ },
54
+ "151649": {
55
+ "content": "</think>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": false
61
+ },
62
+ "151650": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "151651": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "151652": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "151653": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "151654": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "151655": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "151656": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "151657": {
119
+ "content": "<tool_call>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "151658": {
127
+ "content": "</tool_call>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "151659": {
135
+ "content": "<|fim_prefix|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "151660": {
143
+ "content": "<|fim_middle|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "151661": {
151
+ "content": "<|fim_suffix|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "151662": {
159
+ "content": "<|fim_pad|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "151663": {
167
+ "content": "<|repo_name|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "151664": {
175
+ "content": "<|file_sep|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ }
182
+ },
183
+ "bos_token": "<|begin▁of▁sentence|>",
184
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='') %}{%- for message in messages %}{%- if message['role'] == 'system' %}{% set ns.system_prompt = message['content'] %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin��>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|><think>\\n'}}{% endif %}",
185
+ "clean_up_tokenization_spaces": false,
186
+ "eos_token": "<|end▁of▁sentence|>",
187
+ "extra_special_tokens": {},
188
+ "legacy": true,
189
+ "model_max_length": 16384,
190
+ "pad_token": "<|end▁of▁sentence|>",
191
+ "sp_model_kwargs": {},
192
+ "tokenizer_class": "LlamaTokenizerFast",
193
+ "unk_token": null,
194
+ "use_default_system_prompt": false
195
+ }