galqiwi commited on
Commit
0154673
·
1 Parent(s): 1e532e9

feat: HIGGS quantization kernels for HF Kernel Hub

Browse files

Dequantize (codebook lookup), quantize fp16, quantize bf16.
Ported from github.com/galqiwi/higgs-kernels.
Source only - build/ to be generated with nix run .#build-and-copy

.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ *.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
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.
README.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # higgs-kernels
2
+
3
+ CUDA kernels for [HIGGS](https://arxiv.org/abs/2410.20939) quantization, packaged for the [Hugging Face Kernel Hub](https://huggingface.co/docs/kernels).
4
+
5
+ Extracted from [galqiwi/higgs-kernels](https://github.com/galqiwi/higgs-kernels).
6
+
7
+ ## Kernels
8
+
9
+ - `higgs_dequantize_2_256` - codebook lookup: uint8 indices -> 2D fp16/bf16 vectors
10
+ - `higgs_quantize_2_256_f16` - nearest codebook entry search (fp16)
11
+ - `higgs_quantize_2_256_bf16` - nearest codebook entry search (bf16)
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ from kernels import get_kernel
17
+
18
+ higgs = get_kernel("galqiwi/higgs-kernels")
19
+
20
+ out = higgs.higgs_dequantize_2_256_kernel(x_uint8, grid_256x2)
21
+ indices = higgs.higgs_quantize_2_256_kernel(x_fp16_Nx2, grid_256x2, grid_norms_256)
22
+ ```
23
+
24
+ ## Grid data
25
+
26
+ Pre-trained codebook included in `grids.safetensors` (256x2, key `"2_256"`).
27
+
28
+ ```python
29
+ from kernels import get_kernel
30
+ higgs = get_kernel("galqiwi/higgs-kernels")
31
+ grid = higgs.load_optimal_grid_2_256(device="cuda", dtype=torch.float16)
32
+ ```
33
+
34
+ ## License
35
+
36
+ Apache-2.0
build.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [general]
2
+ name = "higgs-kernels"
3
+ universal = false
4
+
5
+ [torch]
6
+ src = [
7
+ "torch-ext/torch_binding.cpp",
8
+ "torch-ext/torch_binding.h",
9
+ ]
10
+
11
+ [kernel.dequant]
12
+ backend = "cuda"
13
+ depends = ["torch"]
14
+ src = ["csrc/dequant.cu"]
15
+
16
+ [kernel.quant_f16]
17
+ backend = "cuda"
18
+ depends = ["torch"]
19
+ src = ["csrc/quant_f16.cu"]
20
+
21
+ [kernel.quant_bf16]
22
+ backend = "cuda"
23
+ depends = ["torch"]
24
+ src = ["csrc/quant_bf16.cu"]
csrc/dequant.cu ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cstdint>
2
+ #include <cuda.h>
3
+ #include <cuda_runtime.h>
4
+ #include <cuda_fp16.h>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <c10/cuda/CUDAException.h>
7
+
8
+ // Each thread processes 4 indices: loads 4 bytes (uint32), stores 16 bytes (uint4)
9
+ static constexpr int ELEMENTS_PER_THREAD = 4;
10
+
11
+ static __global__ void higgs_dequantize_2_256_ptr_cuda_portable_kernel(
12
+ const uint8_t* __restrict__ x,
13
+ const uint32_t* __restrict__ grid_packed,
14
+ uint32_t* __restrict__ out_packed,
15
+ long long out_dim) {
16
+ __shared__ uint32_t s_grid[256];
17
+
18
+ // Load codebook to shared memory
19
+ for (int idx = threadIdx.x; idx < 256; idx += blockDim.x) {
20
+ s_grid[idx] = grid_packed[idx];
21
+ }
22
+ __syncthreads();
23
+
24
+ // Each thread processes 4 indices
25
+ long long base_idx = (static_cast<long long>(blockIdx.x) * blockDim.x + threadIdx.x) * ELEMENTS_PER_THREAD;
26
+
27
+ if (base_idx >= out_dim) return;
28
+
29
+ // Check if we have a full 4 elements to process
30
+ if (base_idx + ELEMENTS_PER_THREAD <= out_dim) {
31
+ // Vectorized load: load 4 uint8 indices as uint32 (4 bytes)
32
+ uint32_t indices_packed = *reinterpret_cast<const uint32_t*>(&x[base_idx]);
33
+
34
+ // Extract individual bytes
35
+ uint8_t idx0 = indices_packed & 0xFF;
36
+ uint8_t idx1 = (indices_packed >> 8) & 0xFF;
37
+ uint8_t idx2 = (indices_packed >> 16) & 0xFF;
38
+ uint8_t idx3 = (indices_packed >> 24) & 0xFF;
39
+
40
+ // Lookup all 4 values
41
+ uint32_t val0 = s_grid[idx0];
42
+ uint32_t val1 = s_grid[idx1];
43
+ uint32_t val2 = s_grid[idx2];
44
+ uint32_t val3 = s_grid[idx3];
45
+
46
+ // Vectorized store: write 4 uint32 values as uint4 (16 bytes)
47
+ uint4 result = make_uint4(val0, val1, val2, val3);
48
+ *reinterpret_cast<uint4*>(&out_packed[base_idx]) = result;
49
+ } else {
50
+ // Handle remainder (less than 4 elements at the end)
51
+ for (long long i = base_idx; i < out_dim; i++) {
52
+ out_packed[i] = s_grid[x[i]];
53
+ }
54
+ }
55
+ }
56
+
57
+ extern "C" void higgs_dequantize_2_256_ptr_cuda_portable(
58
+ uint64_t x_ptr,
59
+ uint64_t grid_ptr,
60
+ uint64_t out_ptr,
61
+ int64_t out_dim) {
62
+ const uint8_t* x = reinterpret_cast<const uint8_t*>(x_ptr);
63
+ const uint32_t* grid_packed = reinterpret_cast<const uint32_t*>(grid_ptr);
64
+ uint32_t* out_packed = reinterpret_cast<uint32_t*>(out_ptr);
65
+
66
+ constexpr int threads_per_block = 256;
67
+ constexpr int elements_per_block = threads_per_block * ELEMENTS_PER_THREAD;
68
+ int blocks = static_cast<int>((out_dim + elements_per_block - 1) / elements_per_block);
69
+
70
+ auto stream = at::cuda::getCurrentCUDAStream();
71
+ higgs_dequantize_2_256_ptr_cuda_portable_kernel<<<blocks, threads_per_block, 0, stream.stream()>>>(
72
+ x, grid_packed, out_packed, static_cast<long long>(out_dim));
73
+
74
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
75
+ }
csrc/quant_bf16.cu ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cuda_runtime.h>
2
+ #include <math_constants.h>
3
+ #include <cstdint>
4
+ #include <limits>
5
+ #include <ATen/cuda/CUDAContext.h>
6
+ #include <c10/cuda/CUDAException.h>
7
+
8
+ static constexpr int kCodebookSize = 256;
9
+ static constexpr int kInDim = 2;
10
+
11
+ __device__ __forceinline__ float bf16_to_fp32(uint16_t v) {
12
+ uint32_t u = static_cast<uint32_t>(v) << 16;
13
+ return __uint_as_float(u);
14
+ }
15
+ __device__ __forceinline__ uint16_t fp32_to_bf16_rne(float f) {
16
+ uint32_t x = __float_as_uint(f);
17
+ uint32_t lsb = (x >> 16) & 1U;
18
+ uint32_t rounding_bias = 0x00007FFFU + lsb;
19
+ x += rounding_bias;
20
+ return static_cast<uint16_t>(x >> 16);
21
+ }
22
+
23
+ __device__ __forceinline__ uint16_t bf16_mul(uint16_t a_bf16, uint16_t b_bf16) {
24
+ float a = bf16_to_fp32(a_bf16);
25
+ float b = bf16_to_fp32(b_bf16);
26
+ return fp32_to_bf16_rne(a * b);
27
+ }
28
+
29
+ __global__ void higgs_quantize_2_256_ptr_bf16_cuda_portable_kernel(
30
+ const uint16_t* __restrict__ x,
31
+ const uint16_t* __restrict__ grid,
32
+ const uint16_t* __restrict__ grid_norms,
33
+ unsigned char* __restrict__ out,
34
+ int64_t out_dim)
35
+ {
36
+ __shared__ float s_grid[kCodebookSize][kInDim];
37
+ __shared__ uint16_t s_norms_bf16[kCodebookSize];
38
+
39
+ for (int idx = threadIdx.x; idx < kCodebookSize * kInDim; idx += blockDim.x) {
40
+ int r = idx / kInDim;
41
+ int c = idx % kInDim;
42
+ s_grid[r][c] = bf16_to_fp32(grid[r * kInDim + c]);
43
+ }
44
+ for (int idx = threadIdx.x; idx < kCodebookSize; idx += blockDim.x) {
45
+ s_norms_bf16[idx] = grid_norms[idx];
46
+ }
47
+ __syncthreads();
48
+
49
+ int64_t row = blockIdx.x * blockDim.x + threadIdx.x;
50
+ if (row >= out_dim) return;
51
+
52
+ const uint16_t two_bf16 = fp32_to_bf16_rne(2.0f);
53
+
54
+ uint16_t x0_b = x[row * kInDim + 0];
55
+ uint16_t x1_b = x[row * kInDim + 1];
56
+ float x0 = bf16_to_fp32(x0_b);
57
+ float x1 = bf16_to_fp32(x1_b);
58
+
59
+ float best_score = -CUDART_INF_F;
60
+ unsigned int best_index = 0u;
61
+
62
+ #pragma unroll 8
63
+ for (int c = 0; c < kCodebookSize; ++c) {
64
+ float g0 = s_grid[c][0];
65
+ float g1 = s_grid[c][1];
66
+ float dot_fp32 = x0 * g0 + x1 * g1;
67
+ uint16_t dot_bf16 = fp32_to_bf16_rne(dot_fp32);
68
+
69
+ uint16_t twice_dot_bf16 = bf16_mul(dot_bf16, two_bf16);
70
+ float twice_dot = bf16_to_fp32(twice_dot_bf16);
71
+
72
+ uint16_t grid_norm_bf16 = s_norms_bf16[c];
73
+ float score = bf16_to_fp32(fp32_to_bf16_rne(twice_dot - bf16_to_fp32(grid_norm_bf16)));
74
+
75
+ if (score > best_score) {
76
+ best_score = score;
77
+ best_index = static_cast<unsigned int>(c);
78
+ }
79
+ }
80
+
81
+ out[row] = static_cast<unsigned char>(best_index);
82
+ }
83
+
84
+ extern "C" void higgs_quantize_2_256_ptr_bf16_cuda_portable(
85
+ uint64_t x_ptr,
86
+ uint64_t grid_ptr,
87
+ uint64_t grid_norms_ptr,
88
+ uint64_t out_ptr,
89
+ int64_t out_dim)
90
+ {
91
+ const uint16_t* x = reinterpret_cast<const uint16_t*>(x_ptr);
92
+ const uint16_t* grid = reinterpret_cast<const uint16_t*>(grid_ptr);
93
+ const uint16_t* grid_norms = reinterpret_cast<const uint16_t*>(grid_norms_ptr);
94
+ unsigned char* out = reinterpret_cast<unsigned char*>(out_ptr);
95
+
96
+ int threads = 256;
97
+ int blocks = static_cast<int>((out_dim + threads - 1) / threads);
98
+
99
+ auto stream = at::cuda::getCurrentCUDAStream();
100
+ higgs_quantize_2_256_ptr_bf16_cuda_portable_kernel<<<blocks, threads, 0, stream>>>(x, grid, grid_norms, out, out_dim);
101
+
102
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
103
+ }
csrc/quant_f16.cu ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cuda_fp16.h>
2
+ #include <stdint.h>
3
+ #include <float.h>
4
+ #include <ATen/cuda/CUDAContext.h>
5
+ #include <c10/cuda/CUDAException.h>
6
+
7
+ static constexpr int codebookSize = 256;
8
+ static constexpr int codebookDim = 2;
9
+
10
+ static __global__ void higgs_quantize_2_256_ptr_f16_cuda_portable_kernel(
11
+ const __half* __restrict__ x,
12
+ const __half* __restrict__ grid,
13
+ const __half* __restrict__ grid_norms,
14
+ uint8_t* __restrict__ out,
15
+ int64_t out_dim)
16
+ {
17
+ __shared__ float s_grid[codebookSize][codebookDim];
18
+ __shared__ __half s_norms[codebookSize];
19
+
20
+ for (int idx = threadIdx.x; idx < codebookSize * codebookDim; idx += blockDim.x) {
21
+ int r = idx / codebookDim;
22
+ int c = idx % codebookDim;
23
+ s_grid[r][c] = __half2float(grid[r * codebookDim + c]);
24
+ }
25
+ for (int idx = threadIdx.x; idx < codebookSize; idx += blockDim.x) {
26
+ s_norms[idx] = grid_norms[idx];
27
+ }
28
+ __syncthreads();
29
+
30
+ int64_t row = static_cast<int64_t>(blockIdx.x) * blockDim.x + threadIdx.x;
31
+ if (row >= out_dim) return;
32
+
33
+ const __half two_h = __float2half(2.0f);
34
+
35
+ const __half x0_h = x[row * codebookDim + 0];
36
+ const __half x1_h = x[row * codebookDim + 1];
37
+
38
+ float best_score = -FLT_MAX;
39
+ uint8_t best_index = 0;
40
+
41
+ #pragma unroll 8
42
+ for (int c = 0; c < codebookSize; ++c) {
43
+ const float g0 = s_grid[c][0];
44
+ const float g1 = s_grid[c][1];
45
+ const float dot_f = __half2float(x0_h) * g0 + __half2float(x1_h) * g1;
46
+ const __half dot_h = __float2half_rn(dot_f);
47
+ const __half twice_dot_h = __hmul(dot_h, two_h);
48
+ const __half score_h = __hsub(twice_dot_h, s_norms[c]);
49
+ const float score_f = __half2float(score_h);
50
+ if (score_f > best_score) {
51
+ best_score = score_f;
52
+ best_index = static_cast<uint8_t>(c);
53
+ }
54
+ }
55
+
56
+ out[row] = best_index;
57
+ }
58
+
59
+ extern "C" void higgs_quantize_2_256_ptr_f16_cuda_portable(
60
+ uint64_t x_ptr,
61
+ uint64_t grid_ptr,
62
+ uint64_t grid_norms_ptr,
63
+ uint64_t out_ptr,
64
+ int64_t out_dim)
65
+ {
66
+ const __half* x = reinterpret_cast<const __half*>(x_ptr);
67
+ const __half* grid = reinterpret_cast<const __half*>(grid_ptr);
68
+ const __half* grid_norms = reinterpret_cast<const __half*>(grid_norms_ptr);
69
+ uint8_t* out = reinterpret_cast<uint8_t*>(out_ptr);
70
+
71
+ const int threads = 256;
72
+ const int blocks = static_cast<int>((out_dim + threads - 1) / threads);
73
+
74
+ auto stream = at::cuda::getCurrentCUDAStream();
75
+ higgs_quantize_2_256_ptr_f16_cuda_portable_kernel<<<blocks, threads, 0, stream>>>(x, grid, grid_norms, out, out_dim);
76
+
77
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
78
+ }
flake.nix ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ description = "CUDA kernels for HIGGS quantization";
3
+
4
+ inputs = {
5
+ kernel-builder.url = "github:huggingface/kernels";
6
+ };
7
+
8
+ outputs =
9
+ {
10
+ self,
11
+ kernel-builder,
12
+ }:
13
+ kernel-builder.lib.genKernelFlakeOutputs {
14
+ inherit self;
15
+ path = ./.;
16
+ };
17
+ }
torch-ext/higgs_kernels/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import functools
3
+
4
+ import torch
5
+ from ._ops import ops
6
+
7
+ import safetensors.torch
8
+
9
+ PKG_PATH = os.path.dirname(os.path.realpath(__file__))
10
+
11
+
12
+ @functools.cache
13
+ def load_optimal_grid_2_256(device="cpu", dtype=torch.float16):
14
+ return safetensors.torch.load_file(
15
+ os.path.join(PKG_PATH, "grids.safetensors"), device=device
16
+ )["2_256"].to(dtype)
17
+
18
+
19
+ def higgs_dequantize_2_256_kernel(x, grid):
20
+ x = x.contiguous()
21
+ grid = grid.contiguous()
22
+
23
+ assert grid.device == x.device
24
+ assert "cuda" in str(x.device)
25
+
26
+ assert grid.dtype in (torch.float16, torch.bfloat16)
27
+ assert grid.shape == (256, 2)
28
+
29
+ assert x.dtype == torch.uint8
30
+ (out_dim,) = x.shape
31
+ assert out_dim > 0
32
+
33
+ assert x.data_ptr() % 4 == 0, "Input tensor must be 4-byte aligned for vectorized loads"
34
+
35
+ out = torch.zeros((out_dim, 2), dtype=grid.dtype, device=grid.device)
36
+
37
+ assert out.data_ptr() % 16 == 0, "Output tensor must be 16-byte aligned for vectorized stores"
38
+
39
+ ops.higgs_dequantize_2_256(x, grid, out)
40
+
41
+ return out
42
+
43
+
44
+ def higgs_quantize_2_256_kernel(x, grid, grid_norms):
45
+ assert x.dtype == grid.dtype == grid_norms.dtype
46
+ assert x.device == grid.device == grid_norms.device
47
+ assert "cuda" in str(x.device)
48
+
49
+ assert x.dtype in (torch.bfloat16, torch.float16)
50
+
51
+ assert grid.shape == (256, 2), grid.shape
52
+ assert grid_norms.shape == (256,), grid_norms.shape
53
+
54
+ out_dim, in_dim = x.shape
55
+ assert in_dim == 2
56
+ assert out_dim > 0
57
+
58
+ out = torch.empty((out_dim,), dtype=torch.uint8, device=x.device)
59
+
60
+ if x.dtype == torch.bfloat16:
61
+ ops.higgs_quantize_2_256_bf16(x, grid, grid_norms, out)
62
+ else:
63
+ ops.higgs_quantize_2_256_f16(x, grid, grid_norms, out)
64
+
65
+ return out
torch-ext/higgs_kernels/grids.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e27a5baf702063e559681cf89465bad78562ddeb54bc3782b760c87332382488
3
+ size 2128
torch-ext/torch_binding.cpp ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <torch/library.h>
2
+
3
+ #include "registration.h"
4
+ #include "torch_binding.h"
5
+
6
+ extern "C" void higgs_dequantize_2_256_ptr_cuda_portable(uint64_t x_ptr,
7
+ uint64_t grid_ptr,
8
+ uint64_t out_ptr,
9
+ int64_t out_dim);
10
+
11
+ extern "C" void higgs_quantize_2_256_ptr_f16_cuda_portable(
12
+ uint64_t x_ptr, uint64_t grid_ptr, uint64_t grid_norms_ptr,
13
+ uint64_t out_ptr, int64_t out_dim);
14
+
15
+ extern "C" void higgs_quantize_2_256_ptr_bf16_cuda_portable(
16
+ uint64_t x_ptr, uint64_t grid_ptr, uint64_t grid_norms_ptr,
17
+ uint64_t out_ptr, int64_t out_dim);
18
+
19
+ void higgs_dequantize_2_256(torch::Tensor x, torch::Tensor grid,
20
+ torch::Tensor out) {
21
+ int64_t out_dim = x.size(0);
22
+ higgs_dequantize_2_256_ptr_cuda_portable(
23
+ reinterpret_cast<uint64_t>(x.data_ptr()),
24
+ reinterpret_cast<uint64_t>(grid.data_ptr()),
25
+ reinterpret_cast<uint64_t>(out.data_ptr()), out_dim);
26
+ }
27
+
28
+ void higgs_quantize_2_256_f16(torch::Tensor x, torch::Tensor grid,
29
+ torch::Tensor grid_norms, torch::Tensor out) {
30
+ int64_t out_dim = x.size(0);
31
+ higgs_quantize_2_256_ptr_f16_cuda_portable(
32
+ reinterpret_cast<uint64_t>(x.data_ptr()),
33
+ reinterpret_cast<uint64_t>(grid.data_ptr()),
34
+ reinterpret_cast<uint64_t>(grid_norms.data_ptr()),
35
+ reinterpret_cast<uint64_t>(out.data_ptr()), out_dim);
36
+ }
37
+
38
+ void higgs_quantize_2_256_bf16(torch::Tensor x, torch::Tensor grid,
39
+ torch::Tensor grid_norms, torch::Tensor out) {
40
+ int64_t out_dim = x.size(0);
41
+ higgs_quantize_2_256_ptr_bf16_cuda_portable(
42
+ reinterpret_cast<uint64_t>(x.data_ptr()),
43
+ reinterpret_cast<uint64_t>(grid.data_ptr()),
44
+ reinterpret_cast<uint64_t>(grid_norms.data_ptr()),
45
+ reinterpret_cast<uint64_t>(out.data_ptr()), out_dim);
46
+ }
47
+
48
+ TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, ops) {
49
+ ops.def(
50
+ "higgs_dequantize_2_256(Tensor x, Tensor grid, Tensor! out) -> ()");
51
+ ops.impl("higgs_dequantize_2_256", torch::kCUDA, &higgs_dequantize_2_256);
52
+
53
+ ops.def("higgs_quantize_2_256_f16(Tensor x, Tensor grid, Tensor "
54
+ "grid_norms, Tensor! out) -> ()");
55
+ ops.impl("higgs_quantize_2_256_f16", torch::kCUDA,
56
+ &higgs_quantize_2_256_f16);
57
+
58
+ ops.def("higgs_quantize_2_256_bf16(Tensor x, Tensor grid, Tensor "
59
+ "grid_norms, Tensor! out) -> ()");
60
+ ops.impl("higgs_quantize_2_256_bf16", torch::kCUDA,
61
+ &higgs_quantize_2_256_bf16);
62
+ }
63
+
64
+ REGISTER_EXTENSION(TORCH_EXTENSION_NAME)
torch-ext/torch_binding.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/types.h>
4
+
5
+ void higgs_dequantize_2_256(torch::Tensor x, torch::Tensor grid,
6
+ torch::Tensor out);
7
+
8
+ void higgs_quantize_2_256_f16(torch::Tensor x, torch::Tensor grid,
9
+ torch::Tensor grid_norms, torch::Tensor out);
10
+
11
+ void higgs_quantize_2_256_bf16(torch::Tensor x, torch::Tensor grid,
12
+ torch::Tensor grid_norms, torch::Tensor out);