| 1 | // Adapted from |
| 2 | // https://github.com/sgl-project/sglang/tree/main/sgl-kernel/csrc/cpu |
| 3 | |
| 4 | // clang-format off |
| 5 | |
| 6 | #include <torch/all.h> |
| 7 | |
| 8 | #include "gemm.h" |
| 9 | #include "vec.h" |
| 10 | |
| 11 | namespace { |
| 12 | |
| 13 | #define BLOCK_N block_size_n() |
| 14 | #define BLOCK_M 128 |
| 15 | |
| 16 | template <bool sym_quant_act> |
| 17 | struct ActDtype; |
| 18 | template <> |
| 19 | struct ActDtype<true> { |
| 20 | using type = int8_t; |
| 21 | }; |
| 22 | template <> |
| 23 | struct ActDtype<false> { |
| 24 | using type = uint8_t; |
| 25 | }; |
| 26 | |
| 27 | #if defined(CPU_CAPABILITY_AVX512) |
| 28 | struct alignas(32) m256i_wrapper { |
| 29 | __m256i data; |
| 30 | }; |
| 31 | |
| 32 | inline std::array<m256i_wrapper, 2> load_zps_4vnni(const int8_t* __restrict__ zps) { |
| 33 | // broadcast 01234567 to |
| 34 | // 01234567012345670123456701234567 |
| 35 | __m256i vzps_low = _mm256_set1_epi64x(*reinterpret_cast<const long*>(zps)); |
| 36 | __m256i vzps_high = _mm256_set1_epi64x(*reinterpret_cast<const long*>(zps + 8)); |
| 37 | // shuffle from |
| 38 | // 01234567012345670123456701234567 |
| 39 | // to |
| 40 | // 00001111222233334444555566667777 |
| 41 | __m256i shuffle_mask = |
| 42 | _mm256_set_epi8(7, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0); |
| 43 | vzps_low = _mm256_shuffle_epi8(vzps_low, shuffle_mask); |
| 44 | vzps_high = _mm256_shuffle_epi8(vzps_high, shuffle_mask); |
| 45 | m256i_wrapper vzps_low_wp, vzps_high_wp; |
| 46 | vzps_low_wp.data = vzps_low; |
| 47 | vzps_high_wp.data = vzps_high; |
| 48 | return {vzps_low_wp, vzps_high_wp}; |
| 49 | } |
| 50 | |
| 51 | inline std::array<m256i_wrapper, 2> load_uint4_as_int8(const uint8_t* __restrict__ qB) { |
| 52 | __m256i packed = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(qB)); |
| 53 | const __m256i low_mask = _mm256_set1_epi8(0x0f); |
| 54 | __m256i high = _mm256_srli_epi16(packed, 4); |
| 55 | high = _mm256_and_si256(high, low_mask); |
| 56 | __m256i low = _mm256_and_si256(packed, low_mask); |
| 57 | m256i_wrapper low_wp, high_wp; |
| 58 | low_wp.data = low; |
| 59 | high_wp.data = high; |
| 60 | return {low_wp, high_wp}; |
| 61 | } |
| 62 | |
| 63 | template <int64_t N, int64_t ldb> |
| 64 | void _dequant_weight_zp_only(const uint8_t* __restrict__ B, int8_t* dqB, const int8_t* __restrict__ qzeros, int64_t K) { |
| 65 | // unpack weight int8 -> two int4 |
| 66 | // subtract zero point |
| 67 | // B shape = [K, ldb] = [K, N / 2], actual shape = [K / 4, N / 2, 4] |
| 68 | // dqB shape = [K, N], actual shape = [K / 4, N, 4] |
| 69 | #pragma GCC unroll 2 |
| 70 | for (int n = 0; n < N; n += 16) { |
| 71 | auto [zps_low_wp, zps_high_wp] = load_zps_4vnni(&qzeros[n]); |
| 72 | auto zps_low = zps_low_wp.data; |
| 73 | auto zps_high = zps_high_wp.data; |
| 74 | for (int k = 0; k < K; k += 4) { |
| 75 | auto [vb_low_wp, vb_high_wp] = load_uint4_as_int8(B + ldb * k + n / 2 * 4); |
| 76 | auto vb_low = vb_low_wp.data; |
| 77 | auto vb_high = vb_high_wp.data; |
| 78 | vb_high = _mm256_sub_epi8(vb_high, zps_high); |
| 79 | vb_low = _mm256_sub_epi8(vb_low, zps_low); |
| 80 | // store vb to B |
| 81 | _mm256_storeu_si256(reinterpret_cast<__m256i_u*>(dqB + N * k + n * 4), vb_low); |
| 82 | _mm256_storeu_si256(reinterpret_cast<__m256i_u*>(dqB + N * k + (n + 8) * 4), vb_high); |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | template <bool accum, int64_t N, bool sym_quant_act> |
| 88 | void _dequant_and_store( |
| 89 | float* __restrict__ output, |
| 90 | const int32_t* __restrict__ input, |
| 91 | const float* __restrict__ scale_a, |
| 92 | const int32_t* __restrict__ zp_a, |
| 93 | const float* __restrict__ scale_b, |
| 94 | const int32_t* __restrict__ comp_b, |
| 95 | int M, |
| 96 | int ldi, |
| 97 | int ldo, |
| 98 | int ldsa = 1) { |
| 99 | for (int m = 0; m < M; ++m) { |
| 100 | float a_scale = *(scale_a + m * ldsa); |
| 101 | __m512 va_scale = _mm512_set1_ps(a_scale); |
| 102 | int32_t a_zp; |
| 103 | __m512i va_zp; |
| 104 | if constexpr (!sym_quant_act) { |
| 105 | a_zp = *(zp_a + m * ldsa); |
| 106 | va_zp = _mm512_set1_epi32(a_zp); |
| 107 | } |
| 108 | int n = 0; |
| 109 | #pragma GCC unroll 2 |
| 110 | for (; n < N; n += 16) { |
| 111 | __m512i vc = _mm512_loadu_si512(input + m * ldi + n); |
| 112 | if constexpr (!sym_quant_act) { |
| 113 | __m512i vb_comp = _mm512_loadu_si512(comp_b + n); |
| 114 | vc = _mm512_sub_epi32(vc, _mm512_mullo_epi32(vb_comp, va_zp)); |
| 115 | } |
| 116 | __m512 vc_f = _mm512_cvtepi32_ps(vc); |
| 117 | __m512 vc_f_mul = _mm512_mul_ps(vc_f, va_scale); |
| 118 | __m512 vb_s = _mm512_loadu_ps(scale_b + n); |
| 119 | vc_f_mul = _mm512_mul_ps(vc_f_mul, vb_s); |
| 120 | if constexpr (accum) { |
| 121 | __m512 vo = _mm512_loadu_ps(output + m * ldo + n); |
| 122 | _mm512_storeu_ps(output + m * ldo + n, _mm512_add_ps(vo, vc_f_mul)); |
| 123 | } else { |
| 124 | _mm512_storeu_ps(output + m * ldo + n, vc_f_mul); |
| 125 | } |
| 126 | } |
| 127 | for (; n < N; ++n) { |
| 128 | float dq_val; |
| 129 | if constexpr (sym_quant_act) { |
| 130 | dq_val = (float)input[m * ldi + n] * a_scale * scale_b[n]; |
| 131 | } else { |
| 132 | dq_val = (float)(input[m * ldi + n] - a_zp * comp_b[n]) * a_scale * scale_b[n]; |
| 133 | } |
| 134 | if constexpr (accum) { |
| 135 | output[m * ldo + n] += dq_val; |
| 136 | } else { |
| 137 | output[m * ldo + n] = dq_val; |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | #else |
| 144 | template <int64_t N, int64_t ldb> |
| 145 | void _dequant_weight_zp_only(const uint8_t* B, int8_t* dqB, const int8_t* qzeros, int64_t K) { |
| 146 | // B shape = [K, N / 2] |
| 147 | // dqB shape = [K, N] |
| 148 | for (int k = 0; k < K; ++k) { |
| 149 | for (int n = 0; n < N / 2; ++n) { |
| 150 | int32_t b = (int32_t)B[k * ldb + n]; |
| 151 | dqB[k * N + n * 2] = (b & 0xf) - qzeros[n]; |
| 152 | dqB[k * N + n * 2 + 1] = (b >> 4) - qzeros[n]; |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | #endif |
| 157 | |
| 158 | #if defined(CPU_CAPABILITY_AVX512) |
| 159 | inline __m512i combine_m256i(__m256i a, __m256i b) { |
| 160 | __m512i c = _mm512_castsi256_si512(a); |
| 161 | return _mm512_inserti64x4(c, b, 1); |
| 162 | } |
| 163 | |
| 164 | inline __m512i combine_m256i(std::array<m256i_wrapper, 2> two_256) { |
| 165 | return combine_m256i(two_256[0].data, two_256[1].data); |
| 166 | } |
| 167 | |
| 168 | // negate elements in a according to b's sign |
| 169 | static inline __m512i _mm512_sign_epi8(__m512i a, __m512i b) { |
| 170 | __m512i zero = _mm512_setzero_si512(); |
| 171 | __mmask64 blt0 = _mm512_movepi8_mask(b); |
| 172 | return _mm512_mask_sub_epi8(a, blt0, zero, a); |
| 173 | } |
| 174 | |
| 175 | template <int64_t M, int64_t N, int64_t ldb, bool sym_quant_act> |
| 176 | void _dequant_gemm_accum_small_M( |
| 177 | float* __restrict__ C, |
| 178 | const uint8_t* A, |
| 179 | const float* scales_a, |
| 180 | const int32_t* qzeros_a, |
| 181 | const uint8_t* B, |
| 182 | const float* scales_b, |
| 183 | const int8_t* qzeros_b, |
| 184 | int64_t K, |
| 185 | int64_t lda, |
| 186 | int64_t ldc) { |
| 187 | // if sym_quant_act is true, A pointer type is passed in as uint8_t* but actually int8_t*. |
| 188 | |
| 189 | constexpr int COLS = N / 16; |
| 190 | // Computing compensation is faster than loading it for small M |
| 191 | // because it's memory bound. |
| 192 | __m512i ones = _mm512_set1_epi8(1); // used for computing compensation |
| 193 | __m512i va; |
| 194 | __m512i vb[COLS]; |
| 195 | __m512i vc[M * COLS]; |
| 196 | __m512 vscales[COLS]; |
| 197 | __m512i vzps[COLS]; |
| 198 | __m512i vcompensate[COLS]; |
| 199 | |
| 200 | // Load scales and zps |
| 201 | Unroll<COLS>{}([&](auto i) { |
| 202 | vscales[i] = _mm512_loadu_ps(scales_b + i * 16); |
| 203 | vzps[i] = combine_m256i(load_zps_4vnni(qzeros_b + i * 16)); |
| 204 | if constexpr (!sym_quant_act) { |
| 205 | vcompensate[i] = _mm512_setzero_epi32(); |
| 206 | } |
| 207 | }); |
| 208 | Unroll<M * COLS>{}([&](auto i) { vc[i] = _mm512_setzero_epi32(); }); |
| 209 | |
| 210 | auto compute = [&](auto i, int k) { |
| 211 | constexpr const int row = i / COLS; |
| 212 | constexpr const int col = i % COLS; |
| 213 | |
| 214 | if constexpr (col == 0) { |
| 215 | va = _mm512_set1_epi32(*(int32_t*)(A + row * lda + k)); |
| 216 | } |
| 217 | |
| 218 | if constexpr (row == 0) { |
| 219 | int B_offset = k * ldb + col * 16 * 2; |
| 220 | vb[col] = combine_m256i(load_uint4_as_int8(B + B_offset)); |
| 221 | vb[col] = _mm512_sub_epi8(vb[col], vzps[col]); |
| 222 | if constexpr (!sym_quant_act) { |
| 223 | vcompensate[col] = _mm512_dpbusd_epi32(vcompensate[col], ones, vb[col]); |
| 224 | } |
| 225 | _mm_prefetch(B + B_offset + 128 * ldb, _MM_HINT_T0); |
| 226 | } |
| 227 | if constexpr (sym_quant_act) { |
| 228 | auto vsb = _mm512_sign_epi8(vb[col], va); |
| 229 | auto vabsa = _mm512_sign_epi8(va, va); |
| 230 | vc[i] = _mm512_dpbusds_epi32(vc[i], vabsa, vsb); |
| 231 | } else { |
| 232 | vc[i] = _mm512_dpbusd_epi32(vc[i], va, vb[col]); |
| 233 | } |
| 234 | }; |
| 235 | |
| 236 | // Accumulate along k |
| 237 | constexpr const int unroll = 4; |
| 238 | int k = 0; |
| 239 | for (; k < K / 4 / unroll; k++) { |
| 240 | Unroll<unroll>{}([&](auto i) { Unroll<M * COLS>{}(compute, 4 * (k * unroll + i)); }); |
| 241 | } |
| 242 | k *= 4 * unroll; |
| 243 | for (; k < K; k += 4) { |
| 244 | Unroll<M * COLS>{}(compute, k); |
| 245 | } |
| 246 | |
| 247 | // Store to C |
| 248 | auto store = [&](auto i) { |
| 249 | constexpr const int row = i / COLS; |
| 250 | constexpr const int col = i % COLS; |
| 251 | // compute (qC - compensate * zp_a) * scale_a * scale_b |
| 252 | __m512 vc_float; |
| 253 | if constexpr (!sym_quant_act) { |
| 254 | vc[i] = _mm512_sub_epi32(vc[i], _mm512_mullo_epi32(vcompensate[col], _mm512_set1_epi32(*(qzeros_a + row)))); |
| 255 | } |
| 256 | vc_float = _mm512_cvtepi32_ps(vc[i]); |
| 257 | vc_float = _mm512_mul_ps(vc_float, _mm512_set1_ps(*(scales_a + row))); |
| 258 | |
| 259 | vc_float = _mm512_mul_ps(vc_float, vscales[col]); |
| 260 | auto vc_old = _mm512_loadu_ps(C + row * ldc + col * 16); |
| 261 | vc_float = _mm512_add_ps(vc_float, vc_old); |
| 262 | _mm512_storeu_ps(C + row * ldc + col * 16, vc_float); |
| 263 | }; |
| 264 | Unroll<M * COLS>{}(store); |
| 265 | } |
| 266 | |
| 267 | #define CALL_DEQUANT_GEMM_ACCUM_SMALL_M(M) \ |
| 268 | _dequant_gemm_accum_small_M<M, N, ldb, sym_quant_act>(C, A, scales_a, qzeros_a, B, scales_b, qzeros_b, K, lda, ldc); |
| 269 | #endif |
| 270 | |
| 271 | template <int64_t N, int64_t ldb> |
| 272 | inline int32_t load_uint4_vnni(const uint8_t* __restrict__ B, int64_t k, int64_t n) { |
| 273 | // B is packed as [_block_k / 4, N / 2, 4] for VNNI4. Each byte stores two |
| 274 | // columns from adjacent 8-column groups for one K lane. |
| 275 | constexpr int64_t n_group_size = 8; |
| 276 | constexpr int64_t vnni_size = 4; |
| 277 | static_assert(N % (2 * n_group_size) == 0); |
| 278 | |
| 279 | int64_t n_group = n / n_group_size; |
| 280 | int64_t ni = n % n_group_size; |
| 281 | int64_t ki = k % vnni_size; |
| 282 | int64_t k_base = k - ki; |
| 283 | int64_t packed_n = (n_group / 2) * n_group_size + ni; |
| 284 | uint8_t packed = B[k_base * ldb + packed_n * vnni_size + ki]; |
| 285 | return (n_group % 2 == 0) ? (packed & 0x0f) : ((packed >> 4) & 0x0f); |
| 286 | } |
| 287 | |
| 288 | #if defined(CPU_CAPABILITY_RVV) |
| 289 | template <int64_t N, int64_t ldb, int group> |
| 290 | inline fixed_i8x8_t load_uint4_as_int8_rvv(const uint8_t* __restrict__ B, int64_t k) { |
| 291 | constexpr int64_t n_group_size = 8; |
| 292 | constexpr int64_t vnni_size = 4; |
| 293 | static_assert(N == 32); |
| 294 | static_assert(ldb == N / 2); |
| 295 | static_assert(group >= 0 && group < N / n_group_size); |
| 296 | |
| 297 | // Unpack: gather 8 packed int4 values from the VNNI4 layout. |
| 298 | const int64_t ki = k % vnni_size; |
| 299 | const int64_t k_base = k - ki; |
| 300 | constexpr int64_t packed_group = group / 2; |
| 301 | const uint8_t* packed_ptr = B + k_base * ldb + packed_group * n_group_size * vnni_size + ki; |
| 302 | |
| 303 | fixed_u8x8_t packed = RVVI(__riscv_vlse8_v_u8, LMUL_64)(packed_ptr, vnni_size, n_group_size); |
| 304 | if constexpr (group % 2 == 1) { |
| 305 | packed = RVVI(__riscv_vsrl_vx_u8, LMUL_64)(packed, 4, n_group_size); |
| 306 | } |
| 307 | fixed_u8x8_t nibbles = RVVI(__riscv_vand_vx_u8, LMUL_64)(packed, 0x0f, n_group_size); |
| 308 | return RVVI4(__riscv_vreinterpret_v_u8, LMUL_64, _i8, LMUL_64)(nibbles); |
| 309 | } |
| 310 | |
| 311 | inline fixed_i32x8_t gemm_accum_uint8_int8_rvv(fixed_i32x8_t acc, uint8_t a, fixed_i8x8_t b) { |
| 312 | constexpr int64_t vl = 8; |
| 313 | fixed_i16x8_t b_i16 = RVVI(__riscv_vsext_vf2_i16, LMUL_128)(b, vl); |
| 314 | return RVVI(__riscv_vwmacc_vx_i32, LMUL_256)(acc, static_cast<int16_t>(a), b_i16, vl); |
| 315 | } |
| 316 | |
| 317 | template <int64_t N, int64_t ldb, int group> |
| 318 | inline fixed_i32x8_t gemm_accum_uint4_rvv( |
| 319 | fixed_i32x8_t acc, |
| 320 | const uint8_t* __restrict__ B, |
| 321 | const int8_t* __restrict__ qzeros_b, |
| 322 | uint8_t a, |
| 323 | int64_t k) { |
| 324 | constexpr int64_t n_group_size = 8; |
| 325 | fixed_i8x8_t b = load_uint4_as_int8_rvv<N, ldb, group>(B, k); |
| 326 | fixed_i8x8_t qzeros = |
| 327 | RVVI(__riscv_vle8_v_i8, LMUL_64)(qzeros_b + group * n_group_size, n_group_size); |
| 328 | b = RVVI(__riscv_vsub_vv_i8, LMUL_64)(b, qzeros, n_group_size); |
| 329 | return gemm_accum_uint8_int8_rvv(acc, a, b); |
| 330 | } |
| 331 | |
| 332 | template <int group> |
| 333 | inline void _dequant_and_store_rvv( |
| 334 | float* __restrict__ C, |
| 335 | fixed_i32x8_t acc, |
| 336 | const float* __restrict__ scales_a, |
| 337 | const int32_t* __restrict__ qzeros_a, |
| 338 | const float* __restrict__ scales_b, |
| 339 | const int32_t* __restrict__ compensation, |
| 340 | int64_t m, |
| 341 | int64_t ldc) { |
| 342 | constexpr int64_t n_group_size = 8; |
| 343 | constexpr int64_t n = group * n_group_size; |
| 344 | constexpr int64_t vl = n_group_size; |
| 345 | |
| 346 | // Dequant compensation: remove activation zero-point contribution. |
| 347 | fixed_i32x8_t comp = RVVI(__riscv_vle32_v_i32, LMUL_256)(compensation + n, vl); |
| 348 | fixed_i32x8_t zp_comp = RVVI(__riscv_vmul_vx_i32, LMUL_256)(comp, qzeros_a[m], vl); |
| 349 | acc = RVVI(__riscv_vsub_vv_i32, LMUL_256)(acc, zp_comp, vl); |
| 350 | |
| 351 | // Scale: convert int32 accumulators to fp32 and apply activation/weight scales. |
| 352 | fixed_fp32x8_t acc_f = RVVI(__riscv_vfcvt_f_x_v_f32, LMUL_256)(acc, vl); |
| 353 | acc_f = RVVI(__riscv_vfmul_vf_f32, LMUL_256)(acc_f, scales_a[m], vl); |
| 354 | fixed_fp32x8_t scale_b = RVVI(__riscv_vle32_v_f32, LMUL_256)(scales_b + n, vl); |
| 355 | acc_f = RVVI(__riscv_vfmul_vv_f32, LMUL_256)(acc_f, scale_b, vl); |
| 356 | |
| 357 | // Store: accumulate into the float scratch buffer that already holds bias/zero. |
| 358 | float* c_ptr = C + m * ldc + n; |
| 359 | fixed_fp32x8_t c_old = RVVI(__riscv_vle32_v_f32, LMUL_256)(c_ptr, vl); |
| 360 | fixed_fp32x8_t c_new = RVVI(__riscv_vfadd_vv_f32, LMUL_256)(c_old, acc_f, vl); |
| 361 | RVVI(__riscv_vse32_v_f32, LMUL_256)(c_ptr, c_new, vl); |
| 362 | } |
| 363 | |
| 364 | template <int64_t N, int64_t ldb> |
| 365 | void _dequant_gemm_accum_rvv( |
| 366 | float* __restrict__ C, |
| 367 | const uint8_t* __restrict__ A, |
| 368 | const float* __restrict__ scales_a, |
| 369 | const int32_t* __restrict__ qzeros_a, |
| 370 | const uint8_t* __restrict__ B, |
| 371 | const float* __restrict__ scales_b, |
| 372 | const int8_t* __restrict__ qzeros_b, |
| 373 | const int32_t* __restrict__ compensation, |
| 374 | int64_t M, |
| 375 | int64_t K, |
| 376 | int64_t lda, |
| 377 | int64_t ldc) { |
| 378 | static_assert(N == 32); |
| 379 | static_assert(ldb == N / 2); |
| 380 | constexpr int64_t vl = 8; |
| 381 | |
| 382 | // Accumulate one C row over the 32-column block. |
| 383 | for (int64_t m = 0; m < M; ++m) { |
| 384 | fixed_i32x8_t acc0 = RVVI(__riscv_vmv_v_x_i32, LMUL_256)(0, vl); |
| 385 | fixed_i32x8_t acc1 = RVVI(__riscv_vmv_v_x_i32, LMUL_256)(0, vl); |
| 386 | fixed_i32x8_t acc2 = RVVI(__riscv_vmv_v_x_i32, LMUL_256)(0, vl); |
| 387 | fixed_i32x8_t acc3 = RVVI(__riscv_vmv_v_x_i32, LMUL_256)(0, vl); |
| 388 | // A[m][k] @ B[k][0:32] -> acc[m][0:32] |
| 389 | for (int64_t k = 0; k < K; ++k) { |
| 390 | // GEMM K step: one scalar activation updates four 8-column RVV tiles. |
| 391 | const uint8_t a = A[m * lda + k]; |
| 392 | acc0 = gemm_accum_uint4_rvv<N, ldb, 0>(acc0, B, qzeros_b, a, k); |
| 393 | acc1 = gemm_accum_uint4_rvv<N, ldb, 1>(acc1, B, qzeros_b, a, k); |
| 394 | acc2 = gemm_accum_uint4_rvv<N, ldb, 2>(acc2, B, qzeros_b, a, k); |
| 395 | acc3 = gemm_accum_uint4_rvv<N, ldb, 3>(acc3, B, qzeros_b, a, k); |
| 396 | } |
| 397 | |
| 398 | // Dequant/scale/store each 8-column group back into C. |
| 399 | _dequant_and_store_rvv<0>(C, acc0, scales_a, qzeros_a, scales_b, compensation, m, ldc); |
| 400 | _dequant_and_store_rvv<1>(C, acc1, scales_a, qzeros_a, scales_b, compensation, m, ldc); |
| 401 | _dequant_and_store_rvv<2>(C, acc2, scales_a, qzeros_a, scales_b, compensation, m, ldc); |
| 402 | _dequant_and_store_rvv<3>(C, acc3, scales_a, qzeros_a, scales_b, compensation, m, ldc); |
| 403 | } |
| 404 | } |
| 405 | #endif |
| 406 | |
| 407 | template <int64_t N, int64_t ldb, bool sym_quant_act> |
| 408 | void _dequant_gemm_accum( |
| 409 | float* C, |
| 410 | const uint8_t* A, |
| 411 | const float* scales_a, |
| 412 | const int32_t* qzeros_a, |
| 413 | const uint8_t* B, |
| 414 | const float* scales_b, |
| 415 | const int8_t* qzeros_b, |
| 416 | const int32_t* compensation, |
| 417 | int8_t* dqB, |
| 418 | int64_t M, |
| 419 | int64_t K, |
| 420 | int64_t lda, |
| 421 | int64_t ldc, |
| 422 | bool use_brgemm) { |
| 423 | // Compute GEMM int8 * int8 -> int32 |
| 424 | // dequant result to float by applying scales/qzeros |
| 425 | #if defined(CPU_CAPABILITY_AVX512) |
| 426 | if (!use_brgemm) { |
| 427 | switch (M) { |
| 428 | case 1: |
| 429 | CALL_DEQUANT_GEMM_ACCUM_SMALL_M(1); |
| 430 | break; |
| 431 | case 2: |
| 432 | CALL_DEQUANT_GEMM_ACCUM_SMALL_M(2); |
| 433 | break; |
| 434 | case 3: |
| 435 | CALL_DEQUANT_GEMM_ACCUM_SMALL_M(3); |
| 436 | break; |
| 437 | case 4: |
| 438 | CALL_DEQUANT_GEMM_ACCUM_SMALL_M(4); |
| 439 | break; |
| 440 | default: |
| 441 | TORCH_CHECK(false, "tinygemm_kernel: unexpected M for AVX path!"); |
| 442 | } |
| 443 | return; |
| 444 | } |
| 445 | |
| 446 | _dequant_weight_zp_only<N, ldb>(B, dqB, qzeros_b, K); |
| 447 | using Tin = typename ActDtype<sym_quant_act>::type; |
| 448 | Tin* A_ptr = (Tin*)A; |
| 449 | if (use_brgemm) { |
| 450 | int32_t C_i32[M * N]; |
| 451 | at::native::cpublas::brgemm( |
| 452 | M, N, K, lda, N /*ldb*/, N /*ldc*/, false /* add_C */, A_ptr, dqB, C_i32, true /* is_vnni */); |
| 453 | _mm_prefetch(B + N * K / 2, _MM_HINT_T0); |
| 454 | _mm_prefetch(A + K, _MM_HINT_T0); |
| 455 | _dequant_and_store<true, N, sym_quant_act>( |
| 456 | C, C_i32, scales_a, qzeros_a, scales_b, compensation, M, N /*ldi*/, ldc, 1 /*ldsa*/); |
| 457 | } else |
| 458 | #elif defined(CPU_CAPABILITY_RVV) |
| 459 | if constexpr (!sym_quant_act && N == BLOCK_N && ldb == BLOCK_N / 2) { |
| 460 | _dequant_gemm_accum_rvv<N, ldb>(C, A, scales_a, qzeros_a, B, scales_b, qzeros_b, compensation, M, K, lda, ldc); |
| 461 | return; |
| 462 | } else |
| 463 | #endif |
| 464 | { |
| 465 | for (int64_t m = 0; m < M; ++m) { |
| 466 | for (int64_t n = 0; n < N; ++n) { |
| 467 | int32_t acc = 0; |
| 468 | for (int64_t k = 0; k < K; ++k) { |
| 469 | int32_t b = load_uint4_vnni<N, ldb>(B, k, n) - qzeros_b[n]; |
| 470 | if constexpr (sym_quant_act) { |
| 471 | const int8_t* A_s8 = reinterpret_cast<const int8_t*>(A); |
| 472 | acc += static_cast<int32_t>(A_s8[m * lda + k]) * b; |
| 473 | } else { |
| 474 | acc += static_cast<int32_t>(A[m * lda + k]) * b; |
| 475 | } |
| 476 | } |
| 477 | if constexpr (!sym_quant_act) { |
| 478 | acc -= qzeros_a[m] * compensation[n]; |
| 479 | } |
| 480 | C[m * ldc + n] += static_cast<float>(acc) * scales_a[m] * scales_b[n]; |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | template <int64_t N> |
| 487 | inline void copy_bias(const float* bias_ptr, float* y_buf, int64_t m) { |
| 488 | if (bias_ptr) { |
| 489 | for (int i = 0; i < m; ++i) { |
| 490 | int j = 0; |
| 491 | #if defined(CPU_CAPABILITY_AVX512) |
| 492 | #pragma GCC unroll 2 |
| 493 | for (; j < N; j += 16) { |
| 494 | __m512 bias_vec = _mm512_loadu_ps(bias_ptr + j); |
| 495 | _mm512_storeu_ps(y_buf + i * N + j, bias_vec); |
| 496 | } |
| 497 | #endif |
| 498 | for (; j < N; ++j) { |
| 499 | y_buf[i * N + j] = bias_ptr[j]; |
| 500 | } |
| 501 | } |
| 502 | } else { // initialize to zero |
| 503 | for (int i = 0; i < m; ++i) { |
| 504 | int j = 0; |
| 505 | #if defined(CPU_CAPABILITY_AVX512) |
| 506 | #pragma GCC unroll 2 |
| 507 | for (; j < N; j += 16) { |
| 508 | __m512 zero_vec = _mm512_setzero_ps(); |
| 509 | _mm512_storeu_ps(y_buf + i * N + j, zero_vec); |
| 510 | } |
| 511 | #endif |
| 512 | for (; j < N; ++j) { |
| 513 | y_buf[i * N + j] = 0; |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | template <typename out_dtype, int64_t N> |
| 520 | inline void store_out(const float* y_buf, out_dtype* c_ptr, int64_t m, /* int64_t n, */ int64_t lda) { |
| 521 | for (int i = 0; i < m; ++i) { |
| 522 | int j = 0; |
| 523 | if constexpr (std::is_same<out_dtype, float>::value) { |
| 524 | #if defined(CPU_CAPABILITY_AVX512) |
| 525 | #pragma GCC unroll 2 |
| 526 | for (; j < N; j += 16) { |
| 527 | __m512 y_vec = _mm512_loadu_ps(y_buf + i * N + j); |
| 528 | _mm512_storeu_ps(c_ptr + i * lda + j, y_vec); |
| 529 | } |
| 530 | #endif |
| 531 | for (; j < N; ++j) { |
| 532 | c_ptr[i * lda + j] = y_buf[i * N + j]; |
| 533 | } |
| 534 | } else if constexpr (std::is_same<out_dtype, at::BFloat16>::value) { |
| 535 | #if defined(CPU_CAPABILITY_AVX512) |
| 536 | #pragma GCC unroll 2 |
| 537 | for (; j < N; j += 16) { |
| 538 | __m512 y_vec = _mm512_loadu_ps(y_buf + i * N + j); |
| 539 | __m256i y_bf16_vec = at::vec::cvtfp32_bf16(y_vec); |
| 540 | _mm256_storeu_si256(reinterpret_cast<__m256i*>(c_ptr + i * lda + j), y_bf16_vec); |
| 541 | } |
| 542 | #endif |
| 543 | for (; j < N; ++j) { |
| 544 | c_ptr[i * lda + j] = at::BFloat16(y_buf[i * N + j]); |
| 545 | } |
| 546 | } else if constexpr (std::is_same<out_dtype, at::Half>::value) { |
| 547 | #if defined(CPU_CAPABILITY_AVX512) |
| 548 | #pragma GCC unroll 2 |
| 549 | for (; j < N; j += 16) { |
| 550 | __m512 y_vec = _mm512_loadu_ps(y_buf + i * N + j); |
| 551 | __m256i y_fp16_vec = at::vec::cvtfp32_fp16(y_vec); |
| 552 | _mm256_storeu_si256(reinterpret_cast<__m256i*>(c_ptr + i * lda + j), y_fp16_vec); |
| 553 | } |
| 554 | #endif |
| 555 | for (; j < N; ++j) { |
| 556 | c_ptr[i * lda + j] = at::Half(y_buf[i * N + j]); |
| 557 | } |
| 558 | } else { |
| 559 | TORCH_CHECK(false, "Unsupported output dtype"); |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | void fill_val_stub(int32_t* __restrict__ output, int32_t value, int64_t size) { |
| 565 | using iVec = at::vec::Vectorized<int32_t>; |
| 566 | constexpr int VecSize = iVec::size(); |
| 567 | const iVec fill_val_vec = iVec(value); |
| 568 | int64_t d; |
| 569 | #pragma GCC unroll 4 |
| 570 | for (d = 0; d <= size - VecSize; d += VecSize) { |
| 571 | fill_val_vec.store(output + d); |
| 572 | } |
| 573 | for (; d < size; ++d) { |
| 574 | output[d] = value; |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | template <typename act_dtype, typename out_dtype, bool sym_quant_act> |
| 579 | void _da8w4_linear_impl( |
| 580 | act_dtype* __restrict__ input, |
| 581 | const float* __restrict__ input_scales, |
| 582 | const int32_t* __restrict__ input_qzeros, |
| 583 | const uint8_t* __restrict__ weight, |
| 584 | const float* __restrict__ weight_scales, |
| 585 | const int8_t* __restrict__ weight_qzeros, |
| 586 | const float* __restrict__ bias, |
| 587 | out_dtype* __restrict__ output, |
| 588 | float* __restrict__ output_temp, |
| 589 | int8_t* __restrict__ dequant_weight_temp, |
| 590 | int64_t M, |
| 591 | int64_t N, |
| 592 | int64_t K, |
| 593 | int64_t num_groups) { |
| 594 | // weight + compensation shape = [Nc, Kc, BLOCK_N * _block_k / 2 + BLOCK_N*sizeof(int32_t)] |
| 595 | // scales/qzeros shape = [Nc, G, BLOCK_N] |
| 596 | const bool use_brgemm = can_use_brgemm<int8_t>(M); |
| 597 | int64_t block_m = [&]() -> long { |
| 598 | if (M <= 48) { |
| 599 | return M; |
| 600 | } else if (M < 64) { |
| 601 | return 32; |
| 602 | } else if (M < 96) { |
| 603 | return 64; |
| 604 | } else { |
| 605 | return 128; |
| 606 | } |
| 607 | }(); |
| 608 | int64_t Mc = div_up(M, block_m); |
| 609 | bool parallel_on_M = M > 128; |
| 610 | int64_t Nc = N / BLOCK_N; |
| 611 | int64_t num_blocks = parallel_on_M ? Mc * Nc : Nc; |
| 612 | int64_t group_size = div_up(K, num_groups); |
| 613 | int64_t _block_k = get_4bit_block_k_size(group_size); |
| 614 | int64_t Kc = K / _block_k; |
| 615 | int64_t block_per_group = group_size / _block_k; |
| 616 | |
| 617 | at::parallel_for(0, num_blocks, 1, [&](int64_t begin, int64_t end) { |
| 618 | int tid = get_thread_num(); |
| 619 | float* C_tmp = output_temp + tid * block_m * BLOCK_N; |
| 620 | int8_t* dqB_tmp = dequant_weight_temp + tid * _block_k * BLOCK_N; |
| 621 | for (const auto i : c10::irange(begin, end)) { |
| 622 | int64_t mc = parallel_on_M ? i / Nc : 0; |
| 623 | int64_t nc = parallel_on_M ? i % Nc : i; |
| 624 | int64_t mc_end = parallel_on_M ? mc + 1 : Mc; |
| 625 | |
| 626 | for (int mci = mc; mci < mc_end; ++mci) { |
| 627 | int64_t m_size = mci * block_m + block_m > M ? M - mci * block_m : block_m; |
| 628 | // copy bias to y_buf if bias is not None |
| 629 | auto bias_data = bias ? bias + nc * BLOCK_N : nullptr; |
| 630 | copy_bias<BLOCK_N>(bias_data, C_tmp, m_size); |
| 631 | for (int kci = 0; kci < Kc; ++kci) { |
| 632 | int32_t* compensation_ptr = |
| 633 | sym_quant_act |
| 634 | ? nullptr |
| 635 | : (int32_t*)(void*)(weight + (nc * Kc + kci) * (BLOCK_N * (_block_k / 2 + sizeof(int32_t))) + |
| 636 | _block_k * BLOCK_N / 2) /*Bcomp*/; |
| 637 | _dequant_gemm_accum<BLOCK_N, BLOCK_N / 2, sym_quant_act>( |
| 638 | /*C*/ C_tmp, |
| 639 | /*A*/ (uint8_t*)input + mci * block_m * K + kci * _block_k, |
| 640 | /*scales_a*/ input_scales + mci * block_m, |
| 641 | /*qzeros_a*/ input_qzeros + mci * block_m, |
| 642 | /*B*/ weight + (nc * Kc + kci) * (BLOCK_N * (_block_k / 2 + sizeof(int32_t))), |
| 643 | /*scales_b*/ weight_scales + nc * BLOCK_N * num_groups + kci / block_per_group * BLOCK_N, |
| 644 | /*qzeros_b*/ weight_qzeros + nc * BLOCK_N * num_groups + kci / block_per_group * BLOCK_N, |
| 645 | /*Bcomp*/ compensation_ptr, |
| 646 | /*dqB_tmp*/ dqB_tmp, |
| 647 | /*M*/ m_size, |
| 648 | /*K*/ _block_k, |
| 649 | /*lda*/ K, |
| 650 | /*ldc*/ BLOCK_N, |
| 651 | /*use_brgemm*/ use_brgemm); |
| 652 | } |
| 653 | // store y_buf to output with dtype conversion |
| 654 | store_out<out_dtype, BLOCK_N>(C_tmp, output + mci * block_m * N + nc * BLOCK_N, m_size, N /*lda*/); |
| 655 | } |
| 656 | } |
| 657 | #if defined(CPU_CAPABILITY_AVX512) |
| 658 | if (use_brgemm) { |
| 659 | at::native::cpublas::brgemm_release(); |
| 660 | } |
| 661 | #endif |
| 662 | }); |
| 663 | } |
| 664 | |
| 665 | } // anonymous namespace |
| 666 | |
| 667 | /* |
| 668 | return: packed_weight, packed_scales, packed_qzeros |
| 669 | */ |
| 670 | std::tuple<at::Tensor, at::Tensor, at::Tensor> convert_int4_weight_packed_with_compensation( |
| 671 | const at::Tensor& weight, const at::Tensor& scales, const at::Tensor& qzeros) { |
| 672 | // weight shape = [N, K] |
| 673 | // scales shape = [N, G] |
| 674 | // qzeros shape = [N, G] |
| 675 | TORCH_CHECK(weight.dim() == 2, "DA8W4 CPU: Weight should be a 2D tensor for packing"); |
| 676 | TORCH_CHECK(weight.size(1) % 2 == 0, "DA8W4 CPU: Weight should have even number of columns for packing"); |
| 677 | |
| 678 | auto new_scales = scales; |
| 679 | auto new_qzeros = qzeros; |
| 680 | if (new_scales.dim() == 1) { |
| 681 | new_scales.unsqueeze_(1); |
| 682 | } |
| 683 | new_scales = new_scales.to(at::kFloat); |
| 684 | if (new_qzeros.dim() == 1) { |
| 685 | new_qzeros.unsqueeze_(1); |
| 686 | } |
| 687 | new_qzeros = new_qzeros.to(at::kChar); |
| 688 | int64_t N = weight.size(0); |
| 689 | int64_t K = weight.size(1); |
| 690 | int64_t G = scales.size(1); |
| 691 | int64_t group_size = K / G; |
| 692 | int64_t _block_k = get_4bit_block_k_size(group_size); |
| 693 | constexpr int block_n = block_size_n(); |
| 694 | int64_t Nc = N / block_n; |
| 695 | int64_t Kc = K / _block_k; |
| 696 | |
| 697 | // Reorder weight to [N/block_n, K/_block_k, _block_k, block_n] |
| 698 | // Reorder scales/qzeros to [N/block_n, G, block_n] |
| 699 | // weight + compensation shape = [Nc, Kc, block_n * _block_k / 2 + block_n*sizeof(int32_t)] |
| 700 | // scales/qzeros shape = [Nc, G, block_n] |
| 701 | auto weight_view = weight.view({Nc, block_n, Kc, _block_k}); |
| 702 | at::Tensor weight_reordered = weight_view.permute({0, 2, 3, 1}).contiguous(); |
| 703 | at::Tensor blocked_weight; |
| 704 | at::Tensor blocked_scales = new_scales.view({Nc, block_n, G}).permute({0, 2, 1}).contiguous(); |
| 705 | at::Tensor blocked_qzeros = new_qzeros.view({Nc, block_n, G}).permute({0, 2, 1}).contiguous(); |
| 706 | // Compensation = Σ(k)(W[k][n] - ZP[n]) for each block. |
| 707 | auto weight_sub_qzero = weight.view({Nc, block_n, G, -1}).to(at::kInt) - new_qzeros.view({Nc, block_n, G, -1}); |
| 708 | weight_sub_qzero = weight_sub_qzero.view({Nc, block_n, Kc, _block_k}); |
| 709 | at::Tensor compensation = weight_sub_qzero.sum(-1); |
| 710 | compensation = compensation.permute({0, 2, 1}).contiguous().to(at::kInt); |
| 711 | int64_t buffer_size_nbytes = _block_k * block_n / 2 + block_n * sizeof(int32_t); |
| 712 | blocked_weight = at::empty({Nc, Kc, buffer_size_nbytes}, weight.options()); |
| 713 | |
| 714 | auto weight_ptr = weight_reordered.data_ptr<uint8_t>(); |
| 715 | auto compensation_ptr = compensation.data_ptr<int32_t>(); |
| 716 | auto blocked_weight_ptr = blocked_weight.data_ptr<uint8_t>(); |
| 717 | int64_t num_blocks = Nc * Kc; |
| 718 | at::parallel_for(0, num_blocks, 1, [&](int64_t begin, int64_t end) { |
| 719 | for (const auto i : c10::irange(begin, end)) { |
| 720 | auto in_ptr = weight_ptr + i * _block_k * block_n; |
| 721 | auto out_ptr = blocked_weight_ptr + i * block_n * (_block_k / 2 + sizeof(int32_t)); |
| 722 | int32_t* comp_in_prt = compensation_ptr + i * block_n; |
| 723 | int32_t* comp_out_prt = (int32_t*)(void*)(blocked_weight_ptr + i * block_n * (_block_k / 2 + sizeof(int32_t)) + |
| 724 | _block_k * block_n / 2); |
| 725 | // Reorder weight block to VNNI4 and pack two lanes along N |
| 726 | // N=16 viewed as two lanes: a0, ...a7, b0, ...b7 |
| 727 | // pack two lanes: [a0, b0], ..., [a7, b7] |
| 728 | // plain shape = [_block_k, block_n] |
| 729 | // packed shape = [_block_k / 4, block_n / 2, 4] viewed as [_block_k, block_n / 2] |
| 730 | constexpr int n_group_size = 8; |
| 731 | constexpr int vnni_size = 4; |
| 732 | constexpr int n_group = block_n / n_group_size; // 4 |
| 733 | for (int nb = 0; nb < n_group; nb += 2) { |
| 734 | for (int k = 0; k < _block_k; k += vnni_size) { |
| 735 | for (int ni = 0; ni < n_group_size; ++ni) { |
| 736 | for (int ki = 0; ki < vnni_size; ++ki) { |
| 737 | int src_idx_1 = nb * n_group_size + ni + (k + ki) * block_n; |
| 738 | int src_idx_2 = (nb + 1) * n_group_size + ni + (k + ki) * block_n; |
| 739 | int dst_idx = (nb / 2 * n_group_size + ni) * vnni_size + k * block_n / 2 + ki; |
| 740 | uint8_t src_1 = *(in_ptr + src_idx_1); |
| 741 | uint8_t src_2 = *(in_ptr + src_idx_2); |
| 742 | uint8_t dst = (src_1 & 0x0f) | ((src_2 & 0x0f) << 4); |
| 743 | *(out_ptr + dst_idx) = dst; |
| 744 | } |
| 745 | } |
| 746 | } |
| 747 | } |
| 748 | // compensation [block_n] |
| 749 | for (int nb = 0; nb < block_n; nb++) { |
| 750 | *(comp_out_prt + nb) = *(comp_in_prt + nb); |
| 751 | } |
| 752 | } |
| 753 | }); |
| 754 | |
| 755 | return std::make_tuple(std::move(blocked_weight), std::move(blocked_scales), std::move(blocked_qzeros)); |
| 756 | } |
| 757 | |
| 758 | std::tuple<at::Tensor, at::Tensor> unpack_4bit_to_32bit_signed(const at::Tensor& qweight, const at::Tensor& qzeros) { |
| 759 | TORCH_CHECK(qweight.scalar_type() == at::kInt, "qweight must be int32"); |
| 760 | TORCH_CHECK(qzeros.scalar_type() == at::kInt, "qzeros must be int32"); |
| 761 | const auto W0 = qweight.size(0); |
| 762 | const auto W1 = qweight.size(1); |
| 763 | const auto Z0 = qzeros.size(0); |
| 764 | const auto Z1 = qzeros.size(1); |
| 765 | |
| 766 | // unpacked_weights: (W0 * 8, W1), int8 |
| 767 | auto unpacked_weights = at::zeros({W0 * 8, W1}, at::TensorOptions().dtype(at::kChar)); |
| 768 | // unpacked_zeros: (Z0, Z1 * 8), int8 |
| 769 | auto unpacked_zeros = at::zeros({Z0, Z1 * 8}, at::TensorOptions().dtype(at::kChar)); |
| 770 | |
| 771 | const int32_t* qw_ptr = qweight.data_ptr<int32_t>(); |
| 772 | const int32_t* qz_ptr = qzeros.data_ptr<int32_t>(); |
| 773 | int8_t* uw_ptr = unpacked_weights.data_ptr<int8_t>(); |
| 774 | int8_t* uz_ptr = unpacked_zeros.data_ptr<int8_t>(); |
| 775 | |
| 776 | // ---- unpack qweight ---- |
| 777 | for (int64_t row = 0; row < W0 * 8; ++row) { |
| 778 | const int i = row & 7; // row % 8 |
| 779 | const int src_row = row >> 3; // row // 8 |
| 780 | const int shift = 4 * i; |
| 781 | for (int64_t col = 0; col < W1; ++col) { |
| 782 | int32_t v = qw_ptr[src_row * W1 + col]; |
| 783 | uw_ptr[row * W1 + col] = static_cast<int8_t>((v >> shift) & 0xF); |
| 784 | } |
| 785 | } |
| 786 | // ---- unpack qzeros ---- |
| 787 | for (int64_t col = 0; col < Z1 * 8; ++col) { |
| 788 | const int i = col & 7; |
| 789 | const int src_col = col >> 3; |
| 790 | const int shift = 4 * i; |
| 791 | |
| 792 | for (int64_t row = 0; row < Z0; ++row) { |
| 793 | int32_t v = qz_ptr[row * Z1 + src_col]; |
| 794 | uz_ptr[row * (Z1 * 8) + col] = static_cast<int8_t>((v >> shift) & 0xF); |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | return std::make_tuple(unpacked_weights, unpacked_zeros + 1); |
| 799 | } |
| 800 | |
| 801 | std::tuple<at::Tensor, at::Tensor> |
| 802 | autogptq_to_int4pack(const at::Tensor& qweight_tensor, const at::Tensor& qzeros_tensor) { |
| 803 | TORCH_CHECK(qweight_tensor.scalar_type() == at::kInt, "qweight_tensor must be int32"); |
| 804 | TORCH_CHECK(qzeros_tensor.scalar_type() == at::kInt, "qzeros_tensor must be int32"); |
| 805 | TORCH_CHECK(qweight_tensor.is_cpu(), "CPU only implementation"); |
| 806 | if (qweight_tensor.dim() == 3) { |
| 807 | const int64_t B = qweight_tensor.size(0); |
| 808 | std::vector<at::Tensor> qweight_list; |
| 809 | std::vector<at::Tensor> qzeros_list; |
| 810 | qweight_list.reserve(B); |
| 811 | qzeros_list.reserve(B); |
| 812 | for (int64_t i = 0; i < B; ++i) { |
| 813 | auto outputs = unpack_4bit_to_32bit_signed(qweight_tensor[i], qzeros_tensor[i]); |
| 814 | at::Tensor unpacked_qweight = std::get<0>(outputs); |
| 815 | at::Tensor unpacked_qzeros = std::get<1>(outputs); |
| 816 | qweight_list.push_back(unpacked_qweight.transpose(0, 1).contiguous().to(at::kByte)); |
| 817 | qzeros_list.push_back(unpacked_qzeros.contiguous().to(at::kByte)); |
| 818 | } |
| 819 | return std::make_tuple(at::stack(qweight_list).detach(), at::stack(qzeros_list).detach()); |
| 820 | } |
| 821 | auto outputs = unpack_4bit_to_32bit_signed(qweight_tensor, qzeros_tensor); |
| 822 | at::Tensor unpacked_qweight = std::get<0>(outputs); |
| 823 | at::Tensor unpacked_qzeros = std::get<1>(outputs); |
| 824 | at::Tensor return_qweight = unpacked_qweight.transpose(0, 1).contiguous().to(at::kByte); |
| 825 | at::Tensor return_qzeros = unpacked_qzeros.contiguous().to(at::kByte); |
| 826 | return std::make_tuple(return_qweight, return_qzeros); |
| 827 | } |
| 828 | |
| 829 | std::tuple<at::Tensor, at::Tensor> int4pack(at::Tensor qweight, at::Tensor qzeros, int64_t quant_method_4bit) { |
| 830 | if (quant_method_4bit == CPUQuantAlgo::AWQ) { |
| 831 | // autoawq unpacking |
| 832 | qweight = qweight.contiguous(); |
| 833 | qzeros = qzeros.contiguous(); |
| 834 | // bitshifts: [0, 4, 1, 5, 2, 6, 3, 7] * 4 |
| 835 | auto bitshifts = at::tensor({0, 4, 1, 5, 2, 6, 3, 7}, at::kInt) * 4; |
| 836 | auto qweight_unsq = qweight.unsqueeze(-1); // [..., K, N/8, 1] |
| 837 | auto unpacked = (at::bitwise_right_shift(qweight_unsq, bitshifts) & 0xF).contiguous(); |
| 838 | auto qweight_final = unpacked.flatten(-2).transpose(-1, -2).to(at::kByte).clone(); |
| 839 | auto qzeros_unsq = qzeros.unsqueeze(-1); |
| 840 | auto qzeros_unpacked = (at::bitwise_right_shift(qzeros_unsq, bitshifts) & 0xF).contiguous(); |
| 841 | auto qzeros_final = qzeros_unpacked.flatten(-2).to(at::kByte).clone(); |
| 842 | return std::make_tuple(qweight_final, qzeros_final); |
| 843 | } else if (quant_method_4bit == CPUQuantAlgo::GPTQ) { |
| 844 | // autogptq unpacking |
| 845 | auto outputs = autogptq_to_int4pack(qweight, qzeros); |
| 846 | at::Tensor unpacked_qweight = std::get<0>(outputs); |
| 847 | at::Tensor unpacked_qzeros = std::get<1>(outputs); |
| 848 | return std::make_tuple(unpacked_qweight, unpacked_qzeros); |
| 849 | } else { |
| 850 | TORCH_CHECK(false, "CPU int4 pack only support AWQ or GPTQ..."); |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | std::tuple<at::Tensor, at::Tensor, at::Tensor> convert_weight_packed_scale_zp( |
| 855 | at::Tensor qweight, // awq: (*, K, N / 8) || gptq: (*, K / 8, N) , int32 |
| 856 | at::Tensor qzeros, // awq: (*, K / group_size, N / 8) || gptq: (*, K / group_size, N / 8) , int32 |
| 857 | at::Tensor scales, // awq: (*, K / group_size, N) || gptq: (*, K / group_size, N) , bfloat16 |
| 858 | int64_t quant_method_4bit) { |
| 859 | at::Tensor _qweight; |
| 860 | at::Tensor _qzeros; |
| 861 | |
| 862 | auto res = int4pack(qweight, qzeros, quant_method_4bit); |
| 863 | _qweight = std::get<0>(res); |
| 864 | _qzeros = std::get<1>(res); |
| 865 | |
| 866 | auto _scales = scales; |
| 867 | _qzeros = _qzeros.transpose(-2, -1).contiguous(); // .T |
| 868 | _scales = _scales.transpose(-2, -1).contiguous(); |
| 869 | if (_qweight.dim() == 3) { // Dim=3 for MOE packing, TODO: refine a unified loop |
| 870 | int64_t E = _qweight.size(0); |
| 871 | int64_t K = _qweight.size(2); |
| 872 | int64_t G = _scales.size(2); |
| 873 | int64_t group_size = K / G; |
| 874 | int64_t _block_k = get_4bit_block_k_size(group_size); |
| 875 | int64_t block_n = block_size_n(); |
| 876 | int64_t Nc = _qweight.size(1) / block_n; |
| 877 | int64_t Kc = K / _block_k; |
| 878 | int64_t buffer_size_nbytes = _block_k * block_n / 2 + block_n * sizeof(int32_t); |
| 879 | auto blocked_weight = at::empty({E, Nc, Kc, buffer_size_nbytes}, _qweight.options()); |
| 880 | auto blocked_scales = at::empty({E, Nc, G, block_n}, _scales.options()).to(at::kFloat); |
| 881 | auto blocked_qzeros = at::empty({E, Nc, G, block_n}, _qzeros.options()).to(at::kChar); |
| 882 | for (int i = 0; i < _qweight.size(0); i++) { |
| 883 | auto res_ = convert_int4_weight_packed_with_compensation(_qweight[i], _scales[i], _qzeros[i]); |
| 884 | blocked_weight[i] = std::get<0>(res_); |
| 885 | blocked_scales[i] = std::get<1>(res_); |
| 886 | blocked_qzeros[i] = std::get<2>(res_); |
| 887 | } |
| 888 | _qweight = blocked_weight; |
| 889 | _scales = blocked_scales; |
| 890 | _qzeros = blocked_qzeros; |
| 891 | } else { |
| 892 | auto res_ = convert_int4_weight_packed_with_compensation(_qweight, _scales, _qzeros); |
| 893 | _qweight = std::get<0>(res_); |
| 894 | _scales = std::get<1>(res_); |
| 895 | _qzeros = std::get<2>(res_); |
| 896 | } |
| 897 | |
| 898 | return std::make_tuple(_qweight, _qzeros, _scales); |
| 899 | } |
| 900 | |
| 901 | at::Tensor int4_scaled_mm_cpu_with_quant( |
| 902 | const at::Tensor& input, |
| 903 | const at::Tensor& weight, |
| 904 | const at::Tensor& weight_scales, |
| 905 | const at::Tensor& weight_qzeros, |
| 906 | const std::optional<at::Tensor>& bias, |
| 907 | at::ScalarType output_dtype) { |
| 908 | int64_t M_a = input.size(0); |
| 909 | int64_t K_a = input.size(1); |
| 910 | int64_t lda = input.stride(0); |
| 911 | |
| 912 | const auto st = input.scalar_type(); |
| 913 | TORCH_CHECK( |
| 914 | st == at::kBFloat16 || st == at::kHalf, "int4_scaled_mm_cpu_with_quant: expect A to be bfloat16 or half."); |
| 915 | |
| 916 | constexpr bool sym_quant_act = false; // TODO: add sym quant path |
| 917 | using Tin = typename ActDtype<sym_quant_act>::type; |
| 918 | int64_t act_buffer_size = /* act quant */ M_a * K_a + |
| 919 | /* act scale */ M_a * sizeof(float) + |
| 920 | /* act zp */ M_a * sizeof(int32_t); |
| 921 | auto act_buffer = at::empty({act_buffer_size}, input.options().dtype(at::kByte)); |
| 922 | // asym path, activation quants into uint8_t |
| 923 | auto Aq_data = act_buffer.data_ptr<uint8_t>(); |
| 924 | auto As_data = reinterpret_cast<float*>(Aq_data + M_a * K_a); |
| 925 | auto Azp_data = reinterpret_cast<int32_t*>(As_data + M_a); |
| 926 | fill_val_stub(Azp_data, 128, M_a); // sym_a s8s8 is unified to u8s8 with compensation (128) |
| 927 | |
| 928 | auto out_sizes = input.sizes().vec(); |
| 929 | int64_t N = weight_scales.size(0) * weight_scales.size(-1); |
| 930 | out_sizes.back() = N; |
| 931 | auto output = at::empty(out_sizes, input.options()); |
| 932 | // weight + compensation shape = [Nc, Kc, BLOCK_N * _block_k / 2 + BLOCK_N*sizeof(int32_t)] |
| 933 | // scales/qzeros shape = [Nc, G, BLOCK_N] |
| 934 | int64_t Nc = weight.size(0); |
| 935 | int64_t Kc = weight.size(1); |
| 936 | int64_t _block_k = K_a / Kc; |
| 937 | TORCH_CHECK(N == Nc * BLOCK_N, "DA8W4: weight and input shapes mismatch"); |
| 938 | // scales/qzeros shape = [Nc, G, BLOCK_N] |
| 939 | int64_t num_groups = weight_scales.size(1); |
| 940 | |
| 941 | const uint8_t* b_ptr = weight.data_ptr<uint8_t>(); |
| 942 | const float* b_scales_ptr = weight_scales.data_ptr<float>(); |
| 943 | const int8_t* b_qzeros_ptr = weight_qzeros.data_ptr<int8_t>(); |
| 944 | const float* bias_ptr = bias.has_value() ? bias.value().data_ptr<float>() : nullptr; |
| 945 | int num_threads = at::get_num_threads(); |
| 946 | int64_t temp_buffer_size = /* output temp */ num_threads * BLOCK_M * BLOCK_N * sizeof(float) + |
| 947 | /* weight dequant temp */ num_threads * _block_k * BLOCK_N; |
| 948 | auto c_temp_buffer = at::empty({temp_buffer_size}, input.options().dtype(at::kChar)); |
| 949 | float* c_temp_ptr = (float*)((void*)(c_temp_buffer.data_ptr<int8_t>())); |
| 950 | int8_t* dqB_temp_ptr = (int8_t*)((void*)(c_temp_ptr + num_threads * BLOCK_M * BLOCK_N)); |
| 951 | |
| 952 | #define LAUNCH_DA8W4_LINEAR_WITH_QUANT_IMPL(sym_quant_act) \ |
| 953 | AT_DISPATCH_FLOATING_TYPES_AND2( \ |
| 954 | at::ScalarType::BFloat16, at::ScalarType::Half, output_dtype, "int4_scaled_mm_cpu_with_quant", [&] { \ |
| 955 | const scalar_t* __restrict__ A_data = input.data_ptr<scalar_t>(); \ |
| 956 | scalar_t* __restrict__ c_ptr = output.data_ptr<scalar_t>(); \ |
| 957 | at::parallel_for(0, M_a, 0, [&](int64_t begin, int64_t end) { \ |
| 958 | for (int64_t m = begin; m < end; ++m) { \ |
| 959 | quantize_row_int8<scalar_t>(Aq_data + m * K_a, As_data[m], A_data + m * lda, K_a); \ |
| 960 | } \ |
| 961 | }); \ |
| 962 | _da8w4_linear_impl<Tin, scalar_t, sym_quant_act>( \ |
| 963 | Aq_data, \ |
| 964 | As_data, \ |
| 965 | Azp_data, \ |
| 966 | b_ptr, \ |
| 967 | b_scales_ptr, \ |
| 968 | b_qzeros_ptr, \ |
| 969 | bias_ptr, \ |
| 970 | c_ptr, \ |
| 971 | c_temp_ptr, \ |
| 972 | dqB_temp_ptr, \ |
| 973 | M_a, \ |
| 974 | N, \ |
| 975 | K_a, \ |
| 976 | num_groups); \ |
| 977 | }); |
| 978 | |
| 979 | LAUNCH_DA8W4_LINEAR_WITH_QUANT_IMPL(sym_quant_act); |
| 980 | |
| 981 | return output; |
| 982 | } |
| 983 | template <typename scalar_t> |
| 984 | inline void copy_stub(scalar_t* __restrict__ out, const float* __restrict__ input, int64_t size) { |
| 985 | using Vec = at::vec::Vectorized<scalar_t>; |
| 986 | using fVec = at::vec::Vectorized<float>; |
| 987 | // no remainder |
| 988 | #pragma GCC unroll 4 |
| 989 | for (int64_t d = 0; d < size; d += Vec::size()) { |
| 990 | fVec x0 = fVec::loadu(input + d); |
| 991 | fVec x1 = fVec::loadu(input + d + fVec::size()); |
| 992 | Vec res = convert_from_float_ext<scalar_t>(x0, x1); |
| 993 | res.store(out + d); |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | template <typename scalar_t> |
| 998 | void tinygemm_kernel( |
| 999 | scalar_t* C, |
| 1000 | float* C_temp, |
| 1001 | const uint8_t* A, |
| 1002 | const float* scales_a, |
| 1003 | const int32_t* qzeros_a, |
| 1004 | const uint8_t* B, |
| 1005 | const float* scales_b, |
| 1006 | const int8_t* qzeros_b, |
| 1007 | const int32_t* compensation, |
| 1008 | int8_t* dqB_tmp, |
| 1009 | int64_t M, |
| 1010 | int64_t K, |
| 1011 | int64_t lda, |
| 1012 | int64_t ldc_f, |
| 1013 | int64_t ldc_s, |
| 1014 | bool store_out, |
| 1015 | bool use_brgemm) { |
| 1016 | // TODO: add sym quant act, now only asym |
| 1017 | _dequant_gemm_accum<BLOCK_N, BLOCK_N / 2, false>( |
| 1018 | C_temp, A, scales_a, qzeros_a, B, scales_b, qzeros_b, compensation, dqB_tmp, M, K, lda, ldc_f, use_brgemm); |
| 1019 | if (store_out) { |
| 1020 | // copy from Ctmp to C |
| 1021 | for (int64_t m = 0; m < M; ++m) { |
| 1022 | copy_stub<scalar_t>(C + m * ldc_s, C_temp + m * ldc_f, BLOCK_N); |
| 1023 | } |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | #define INSTANTIATE_TINYGEMM_TEMPLATE(TYPE) \ |
| 1028 | template void tinygemm_kernel<TYPE>( \ |
| 1029 | TYPE * C, \ |
| 1030 | float* C_temp, \ |
| 1031 | const uint8_t* A, \ |
| 1032 | const float* scales_a, \ |
| 1033 | const int32_t* qzeros_a, \ |
| 1034 | const uint8_t* B, \ |
| 1035 | const float* scales_b, \ |
| 1036 | const int8_t* qzeros_b, \ |
| 1037 | const int32_t* compensation, \ |
| 1038 | int8_t* dqB_tmp, \ |
| 1039 | int64_t M, \ |
| 1040 | int64_t K, \ |
| 1041 | int64_t lda, \ |
| 1042 | int64_t ldc_f, \ |
| 1043 | int64_t ldc_s, \ |
| 1044 | bool store_out, \ |
| 1045 | bool use_brgemm) |
| 1046 | |
| 1047 | INSTANTIATE_TINYGEMM_TEMPLATE(at::BFloat16); |
| 1048 | INSTANTIATE_TINYGEMM_TEMPLATE(at::Half); |
| 1049 | |
| 1050 | // int4 gemm dispatch api register |
| 1051 | at::Tensor int4_scaled_mm_cpu( |
| 1052 | at::Tensor& x, at::Tensor& w, at::Tensor& w_zeros, at::Tensor& w_scales, std::optional<at::Tensor> bias) { |
| 1053 | return int4_scaled_mm_cpu_with_quant(x, w, w_scales, w_zeros, bias, x.scalar_type()); |
| 1054 | } |