| 1 | // Adapted from |
| 2 | // https://github.com/sgl-project/sglang/blob/main/python/sglang/kernels/aot/csrc/cpu/store_cache.cpp |
| 3 | // |
| 4 | // DeepSeek-V4 fused Q RMSNorm+RoPE / KV RoPE+UE8M0-quant+paged-cache-insert |
| 5 | // kernel for the fp8_ds_mla cache layout. Not a port of upstream's |
| 6 | // `set_k_and_s_cpu`/`quant_to_nope_fp8_rope_bf16_pack_cpu` -- their |
| 7 | // pool_kv/pool_score signature doesn't apply to vLLM's layout. This is the |
| 8 | // CPU counterpart to vLLM's own CUDA kernel |
| 9 | // (`fused_deepseek_v4_qnorm_rope_kv_insert_kernel.cu`); see |
| 10 | // `DeepseekV4Attention._fused_qnorm_rope_kv_insert_cpu` (attention.py) for |
| 11 | // the eager reference this replaces. |
| 12 | // |
| 13 | // clang-format off |
| 14 | |
| 15 | #include <algorithm> |
| 16 | #include <cmath> |
| 17 | #include <vector> |
| 18 | |
| 19 | #include "common.h" |
| 20 | #include "vec.h" |
| 21 | |
| 22 | #if !defined(CPU_CAPABILITY_AVX512) |
| 23 | static_assert(false, |
| 24 | "store_cache.cpp is only ever compiled into the AVX512+AMX-flagged " |
| 25 | "_C target (see cmake/cpu_extension.cmake's VLLM_EXT_SRC_SGL) and " |
| 26 | "relies on that unconditionally -- CPU_CAPABILITY_AVX512 must be " |
| 27 | "defined here."); |
| 28 | #endif |
| 29 | |
| 30 | namespace { |
| 31 | |
| 32 | constexpr int64_t kRopeDim = 64; |
| 33 | constexpr int64_t kQuantBlock = 64; |
| 34 | constexpr float kFp8Max = 448.0f; |
| 35 | constexpr float kFp8Min = -448.0f; |
| 36 | constexpr float kQuantEps = 1e-4f; |
| 37 | |
| 38 | inline void apply_gptj_rope_inplace(float* __restrict__ x, const float* __restrict__ cos, const float* __restrict__ sin, int64_t half_dim) { |
| 39 | for (int64_t i = 0; i < half_dim; ++i) { |
| 40 | const float e = x[2 * i]; |
| 41 | const float o = x[2 * i + 1]; |
| 42 | x[2 * i] = e * cos[i] - o * sin[i]; |
| 43 | x[2 * i + 1] = e * sin[i] + o * cos[i]; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // AVX512 tile-quantization, adapted verbatim from SGLang's |
| 48 | // `store_cache.cpp` (`quant_to_nope_fp8_rope_bf16_pack_cpu`'s |
| 49 | // `cvt_fp32x16_to_fp8x16`/`quantize_tile_avx512`): per-64-element tile, |
| 50 | // computes the UE8M0 power-of-two scale and quantizes to fp8_e4m3fn with |
| 51 | // RNE rounding via bit manipulation instead of a per-element scalar |
| 52 | // `at::Float8_e4m3fn` cast. Subnormal-magnitude fp8 lanes are flushed to |
| 53 | // zero (matches SGLang's own convention, `cvt_fp32x16_to_fp8x16`) -- |
| 54 | // vLLM's own AVX512 dequant of this cache (`flash_mla.cpp`'s |
| 55 | // `CVT_FP8_TO_BF16_EXT`) doesn't reconstruct exact subnormal magnitudes |
| 56 | // either way, so there is nothing to preserve by rounding them exactly on |
| 57 | // the write side. |
| 58 | #if defined(CPU_CAPABILITY_AVX512) |
| 59 | |
| 60 | // Vectorized float32x16 -> fp8_e4m3fn x16 using AVX512 bit manipulation. |
| 61 | // Implements RNE (round-to-nearest-even). Flushes subnormal fp8 to zero. |
| 62 | // fp8_e4m3fn: sign(1), exp(4, bias=7), mant(3), no inf/nan special values. |
| 63 | // Normal: exp_field in [1..15], value = 2^(exp-7) * (1 + mant/8) |
| 64 | // Input assumed clamped to [-448, 448]. |
| 65 | inline __m128i cvt_fp32x16_to_fp8x16(__m512 input) { |
| 66 | __m512i bits = _mm512_castps_si512(input); |
| 67 | |
| 68 | // Extract sign -> bit 7 of fp8 byte |
| 69 | __m512i signs = _mm512_srli_epi32(_mm512_and_si512(bits, _mm512_set1_epi32(0x80000000)), 24); |
| 70 | |
| 71 | // Absolute value bits |
| 72 | __m512i abs_bits = _mm512_and_si512(bits, _mm512_set1_epi32(0x7FFFFFFF)); |
| 73 | |
| 74 | // Float32 biased exponent |
| 75 | __m512i f32_exp = _mm512_srli_epi32(abs_bits, 23); |
| 76 | |
| 77 | // Float32 mantissa (23 bits) |
| 78 | __m512i f32_mant = _mm512_and_si512(abs_bits, _mm512_set1_epi32(0x7FFFFF)); |
| 79 | |
| 80 | // fp8_exp = f32_exp - 120 (rebias from 127 to 7) |
| 81 | __m512i fp8_exp = _mm512_sub_epi32(f32_exp, _mm512_set1_epi32(120)); |
| 82 | |
| 83 | // Top 3 mantissa bits |
| 84 | __m512i mant3 = _mm512_srli_epi32(f32_mant, 20); |
| 85 | |
| 86 | // RNE rounding: round_bit = bit 19, sticky = bits[18:0] |
| 87 | __m512i round_bit = _mm512_and_si512(_mm512_srli_epi32(f32_mant, 19), _mm512_set1_epi32(1)); |
| 88 | __m512i sticky_bits = _mm512_and_si512(f32_mant, _mm512_set1_epi32(0x7FFFF)); |
| 89 | __mmask16 has_sticky = _mm512_cmpneq_epi32_mask(sticky_bits, _mm512_setzero_si512()); |
| 90 | |
| 91 | // Round up if round_bit AND (sticky OR lsb_of_mant3) |
| 92 | __m512i lsb = _mm512_and_si512(mant3, _mm512_set1_epi32(1)); |
| 93 | __m512i sticky_or_lsb = _mm512_or_si512(_mm512_maskz_mov_epi32(has_sticky, _mm512_set1_epi32(1)), lsb); |
| 94 | __m512i do_round = _mm512_and_si512(round_bit, sticky_or_lsb); |
| 95 | mant3 = _mm512_add_epi32(mant3, do_round); |
| 96 | |
| 97 | // Mantissa overflow (mant3 == 8) -> increment exponent, zero mantissa |
| 98 | __mmask16 mant_ovf = _mm512_cmpeq_epi32_mask(mant3, _mm512_set1_epi32(8)); |
| 99 | mant3 = _mm512_mask_mov_epi32(mant3, mant_ovf, _mm512_setzero_si512()); |
| 100 | fp8_exp = _mm512_mask_add_epi32(fp8_exp, mant_ovf, fp8_exp, _mm512_set1_epi32(1)); |
| 101 | |
| 102 | // Clamp exponent: max 15 |
| 103 | fp8_exp = _mm512_min_epi32(fp8_exp, _mm512_set1_epi32(15)); |
| 104 | |
| 105 | // Result: (fp8_exp << 3) | mant3 |
| 106 | __m512i result = _mm512_or_si512(_mm512_slli_epi32(fp8_exp, 3), mant3); |
| 107 | |
| 108 | // Flush to zero: if f32_exp < 121 (would be subnormal in fp8), output 0 |
| 109 | __mmask16 is_subnormal_or_zero = _mm512_cmplt_epi32_mask(f32_exp, _mm512_set1_epi32(121)); |
| 110 | result = _mm512_mask_mov_epi32(result, is_subnormal_or_zero, _mm512_setzero_si512()); |
| 111 | |
| 112 | // Add sign |
| 113 | result = _mm512_or_si512(result, signs); |
| 114 | |
| 115 | // Pack 16 x i32 -> 16 x i8 |
| 116 | return _mm512_cvtepi32_epi8(result); |
| 117 | } |
| 118 | |
| 119 | // Process one tile (64 bf16 values): find amax, compute scale, quantize to fp8. |
| 120 | inline uint8_t quantize_tile_avx512(const at::BFloat16* __restrict__ src, uint8_t* __restrict__ dst) { |
| 121 | // Load 64 bf16 -> 4 x 16 floats |
| 122 | __m256i bf16_0 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src)); |
| 123 | __m256i bf16_1 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src + 16)); |
| 124 | __m256i bf16_2 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src + 32)); |
| 125 | __m256i bf16_3 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src + 48)); |
| 126 | |
| 127 | __m512 f0 = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(bf16_0), 16)); |
| 128 | __m512 f1 = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(bf16_1), 16)); |
| 129 | __m512 f2 = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(bf16_2), 16)); |
| 130 | __m512 f3 = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(bf16_3), 16)); |
| 131 | |
| 132 | // Absolute values |
| 133 | const __m512i abs_mask_i = _mm512_set1_epi32(0x7FFFFFFF); |
| 134 | __m512 abs0 = _mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(f0), abs_mask_i)); |
| 135 | __m512 abs1 = _mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(f1), abs_mask_i)); |
| 136 | __m512 abs2 = _mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(f2), abs_mask_i)); |
| 137 | __m512 abs3 = _mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(f3), abs_mask_i)); |
| 138 | |
| 139 | // Horizontal max |
| 140 | __m512 max01 = _mm512_max_ps(abs0, abs1); |
| 141 | __m512 max23 = _mm512_max_ps(abs2, abs3); |
| 142 | __m512 max0123 = _mm512_max_ps(max01, max23); |
| 143 | float amax = _mm512_reduce_max_ps(max0123); |
| 144 | |
| 145 | // Scale computation |
| 146 | float scale = std::max(amax / kFp8Max, kQuantEps); |
| 147 | float ceil_log2 = std::ceil(std::log2(scale)); |
| 148 | float scale_pow2 = std::exp2(ceil_log2); |
| 149 | float scale_inv = 1.0f / scale_pow2; |
| 150 | |
| 151 | int exponent = static_cast<int>(ceil_log2); |
| 152 | uint8_t scale_uint8 = static_cast<uint8_t>(exponent + 127); |
| 153 | |
| 154 | // Scale all values |
| 155 | __m512 vinv = _mm512_set1_ps(scale_inv); |
| 156 | __m512 s0 = _mm512_mul_ps(f0, vinv); |
| 157 | __m512 s1 = _mm512_mul_ps(f1, vinv); |
| 158 | __m512 s2 = _mm512_mul_ps(f2, vinv); |
| 159 | __m512 s3 = _mm512_mul_ps(f3, vinv); |
| 160 | |
| 161 | // Clamp |
| 162 | __m512 vmax = _mm512_set1_ps(kFp8Max); |
| 163 | __m512 vmin = _mm512_set1_ps(kFp8Min); |
| 164 | s0 = _mm512_max_ps(_mm512_min_ps(s0, vmax), vmin); |
| 165 | s1 = _mm512_max_ps(_mm512_min_ps(s1, vmax), vmin); |
| 166 | s2 = _mm512_max_ps(_mm512_min_ps(s2, vmax), vmin); |
| 167 | s3 = _mm512_max_ps(_mm512_min_ps(s3, vmax), vmin); |
| 168 | |
| 169 | // Vectorized float -> fp8 conversion (16 values at a time) |
| 170 | __m128i fp8_0 = cvt_fp32x16_to_fp8x16(s0); |
| 171 | __m128i fp8_1 = cvt_fp32x16_to_fp8x16(s1); |
| 172 | __m128i fp8_2 = cvt_fp32x16_to_fp8x16(s2); |
| 173 | __m128i fp8_3 = cvt_fp32x16_to_fp8x16(s3); |
| 174 | |
| 175 | _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), fp8_0); |
| 176 | _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 16), fp8_1); |
| 177 | _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 32), fp8_2); |
| 178 | _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + 48), fp8_3); |
| 179 | |
| 180 | return scale_uint8; |
| 181 | } |
| 182 | |
| 183 | #endif // CPU_CAPABILITY_AVX512 |
| 184 | |
| 185 | template <typename scalar_t> |
| 186 | static void qnorm_rope_kv_insert_impl( |
| 187 | scalar_t* __restrict__ q_out, // [num_tokens_full, q_head_padded, head_dim] |
| 188 | uint8_t* __restrict__ cache, // [num_blocks, cache_row_stride] bytes |
| 189 | const scalar_t* __restrict__ q, // [num_tokens_full, num_heads_q, head_dim] |
| 190 | const scalar_t* __restrict__ kv, // [>=num_tokens_insert, head_dim] |
| 191 | const int64_t* __restrict__ positions, // [num_tokens_full] |
| 192 | const int64_t* __restrict__ slot_mapping, // [num_tokens_insert] |
| 193 | const float* __restrict__ cos_sin_cache, // [max_pos, rope_dim] (first half cos, second half sin) |
| 194 | int64_t num_tokens_full, |
| 195 | int64_t num_heads_q, |
| 196 | int64_t q_head_padded, |
| 197 | int64_t head_dim, |
| 198 | int64_t nope_dim, |
| 199 | int64_t num_quant_blocks, |
| 200 | int64_t token_data_bytes, |
| 201 | int64_t scale_bytes_per_token, |
| 202 | int64_t num_tokens_insert, |
| 203 | int64_t cache_block_size, |
| 204 | int64_t cache_row_stride, |
| 205 | float eps) { |
| 206 | const int64_t rope_half = kRopeDim / 2; |
| 207 | |
| 208 | // Q: per-head weight-free RMSNorm + GPT-J RoPE on the last rope_dim dims. |
| 209 | at::parallel_for(0, num_tokens_full * num_heads_q, 0, [&](int64_t begin, int64_t end) { |
| 210 | std::vector<float> buf(head_dim); |
| 211 | for (int64_t idx = begin; idx < end; ++idx) { |
| 212 | const int64_t t = idx / num_heads_q; |
| 213 | const int64_t h = idx % num_heads_q; |
| 214 | const scalar_t* q_th = q + (t * num_heads_q + h) * head_dim; |
| 215 | |
| 216 | float sq_sum = 0.f; |
| 217 | for (int64_t i = 0; i < head_dim; ++i) { |
| 218 | const float v = static_cast<float>(q_th[i]); |
| 219 | buf[i] = v; |
| 220 | sq_sum += v * v; |
| 221 | } |
| 222 | const float inv_rms = 1.0f / std::sqrt(sq_sum / static_cast<float>(head_dim) + eps); |
| 223 | for (int64_t i = 0; i < head_dim; ++i) |
| 224 | buf[i] *= inv_rms; |
| 225 | |
| 226 | const int64_t pos = positions[t]; |
| 227 | const float* cos = cos_sin_cache + pos * kRopeDim; |
| 228 | const float* sin = cos + rope_half; |
| 229 | apply_gptj_rope_inplace(buf.data() + nope_dim, cos, sin, rope_half); |
| 230 | |
| 231 | scalar_t* out_th = q_out + (t * q_head_padded + h) * head_dim; |
| 232 | for (int64_t i = 0; i < head_dim; ++i) |
| 233 | out_th[i] = static_cast<scalar_t>(buf[i]); |
| 234 | } |
| 235 | }); |
| 236 | |
| 237 | // KV: GPT-J RoPE (no RMSNorm) + bf16 round-trip + UE8M0 FP8 quant + paged insert. |
| 238 | at::parallel_for(0, num_tokens_insert, 0, [&](int64_t begin, int64_t end) { |
| 239 | std::vector<float> buf(head_dim); |
| 240 | std::vector<at::BFloat16> nope_bf16(nope_dim); |
| 241 | for (int64_t t = begin; t < end; ++t) { |
| 242 | const int64_t slot_id = slot_mapping[t]; |
| 243 | if (slot_id < 0) continue; |
| 244 | |
| 245 | const scalar_t* kv_t = kv + t * head_dim; |
| 246 | for (int64_t i = 0; i < head_dim; ++i) |
| 247 | buf[i] = static_cast<float>(kv_t[i]); |
| 248 | |
| 249 | const int64_t pos = positions[t]; |
| 250 | const float* cos = cos_sin_cache + pos * kRopeDim; |
| 251 | const float* sin = cos + rope_half; |
| 252 | apply_gptj_rope_inplace(buf.data() + nope_dim, cos, sin, rope_half); |
| 253 | |
| 254 | // bf16 round-trip, matching the CUDA kernel's double convert. |
| 255 | for (int64_t i = 0; i < head_dim; ++i) |
| 256 | buf[i] = static_cast<float>(at::BFloat16(buf[i])); |
| 257 | for (int64_t i = 0; i < nope_dim; ++i) |
| 258 | nope_bf16[i] = at::BFloat16(buf[i]); |
| 259 | |
| 260 | const int64_t block_idx = slot_id / cache_block_size; |
| 261 | const int64_t pos_in_block = slot_id % cache_block_size; |
| 262 | uint8_t* const block_base = cache + block_idx * cache_row_stride; |
| 263 | uint8_t* const token_fp8_ptr = block_base + pos_in_block * token_data_bytes; |
| 264 | uint8_t* const token_bf16_ptr = token_fp8_ptr + nope_dim; |
| 265 | uint8_t* const token_scale_ptr = |
| 266 | block_base + cache_block_size * token_data_bytes + pos_in_block * scale_bytes_per_token; |
| 267 | |
| 268 | // AVX512 tile-quantization (SGLang's `quantize_tile_avx512`), one |
| 269 | // 64-wide tile per iteration. |
| 270 | for (int64_t qb = 0; qb < num_quant_blocks; ++qb) { |
| 271 | const at::BFloat16* tile_src = nope_bf16.data() + qb * kQuantBlock; |
| 272 | uint8_t* tile_dst = token_fp8_ptr + qb * kQuantBlock; |
| 273 | token_scale_ptr[qb] = quantize_tile_avx512(tile_src, tile_dst); |
| 274 | } |
| 275 | token_scale_ptr[num_quant_blocks] = 0; |
| 276 | |
| 277 | auto* out_rope = reinterpret_cast<at::BFloat16*>(token_bf16_ptr); |
| 278 | for (int64_t i = 0; i < kRopeDim; ++i) |
| 279 | out_rope[i] = at::BFloat16(buf[nope_dim + i]); |
| 280 | } |
| 281 | }); |
| 282 | } |
| 283 | |
| 284 | } // anonymous namespace |
| 285 | |
| 286 | at::Tensor fused_qnorm_rope_kv_insert_cpu( |
| 287 | at::Tensor& q, |
| 288 | at::Tensor& kv, |
| 289 | at::Tensor& positions, |
| 290 | at::Tensor& swa_kv_cache_2d, |
| 291 | at::Tensor& slot_mapping, |
| 292 | at::Tensor& cos_sin_cache, |
| 293 | int64_t q_head_padded, |
| 294 | double eps, |
| 295 | int64_t cache_block_size) { |
| 296 | TORCH_CHECK( |
| 297 | q.dim() == 3 && (q.scalar_type() == at::kBFloat16 || q.scalar_type() == at::kHalf), |
| 298 | "fused_qnorm_rope_kv_insert_cpu: q must be bf16/fp16 [num_tokens, num_heads_q, head_dim]"); |
| 299 | TORCH_CHECK(kv.dim() == 2 && kv.scalar_type() == q.scalar_type(), "fused_qnorm_rope_kv_insert_cpu: kv dtype must match q"); |
| 300 | TORCH_CHECK(positions.scalar_type() == at::kLong, "fused_qnorm_rope_kv_insert_cpu: positions must be int64"); |
| 301 | TORCH_CHECK(slot_mapping.scalar_type() == at::kLong, "fused_qnorm_rope_kv_insert_cpu: slot_mapping must be int64"); |
| 302 | TORCH_CHECK( |
| 303 | swa_kv_cache_2d.dim() == 2 && swa_kv_cache_2d.scalar_type() == at::kByte, |
| 304 | "fused_qnorm_rope_kv_insert_cpu: swa_kv_cache_2d must be a 2D uint8 tensor"); |
| 305 | TORCH_CHECK( |
| 306 | q.device().is_cpu() && kv.device().is_cpu() && positions.device().is_cpu() && slot_mapping.device().is_cpu() && |
| 307 | swa_kv_cache_2d.device().is_cpu() && cos_sin_cache.device().is_cpu(), |
| 308 | "fused_qnorm_rope_kv_insert_cpu: all inputs must be CPU tensors"); |
| 309 | |
| 310 | const int64_t num_tokens_full = q.size(0); |
| 311 | const int64_t num_heads_q = q.size(1); |
| 312 | const int64_t head_dim = q.size(2); |
| 313 | const int64_t nope_dim = head_dim - kRopeDim; |
| 314 | TORCH_CHECK(nope_dim > 0 && nope_dim % kQuantBlock == 0, "fused_qnorm_rope_kv_insert_cpu: unexpected head_dim"); |
| 315 | const int64_t num_quant_blocks = nope_dim / kQuantBlock; |
| 316 | const int64_t scale_bytes_per_token = num_quant_blocks + 1; |
| 317 | const int64_t token_data_bytes = nope_dim + kRopeDim * 2; |
| 318 | |
| 319 | TORCH_CHECK(q_head_padded >= num_heads_q, "fused_qnorm_rope_kv_insert_cpu: q_head_padded must be >= num_heads_q"); |
| 320 | TORCH_CHECK(kv.size(1) == head_dim, "fused_qnorm_rope_kv_insert_cpu: kv head_dim must match q"); |
| 321 | TORCH_CHECK(positions.numel() == num_tokens_full, "fused_qnorm_rope_kv_insert_cpu: positions must have num_tokens_full entries"); |
| 322 | |
| 323 | const int64_t num_tokens_insert = slot_mapping.size(0); |
| 324 | TORCH_CHECK(kv.size(0) >= num_tokens_insert, "fused_qnorm_rope_kv_insert_cpu: kv must have >= num_tokens_insert rows"); |
| 325 | TORCH_CHECK(cache_block_size > 0, "fused_qnorm_rope_kv_insert_cpu: cache_block_size must be positive"); |
| 326 | TORCH_CHECK( |
| 327 | cos_sin_cache.scalar_type() == at::kFloat && cos_sin_cache.is_contiguous(), |
| 328 | "fused_qnorm_rope_kv_insert_cpu: cos_sin_cache must be float32 and " |
| 329 | "contiguous (convert once in Python)"); |
| 330 | TORCH_CHECK( |
| 331 | q.is_contiguous() && kv.is_contiguous() && positions.is_contiguous() && slot_mapping.is_contiguous(), |
| 332 | "fused_qnorm_rope_kv_insert_cpu: q/kv/positions/slot_mapping must be contiguous"); |
| 333 | |
| 334 | // swa_kv_cache_2d is mutated in place; index via its real row stride |
| 335 | // rather than assuming it equals cache_block_size * (token_data_bytes + |
| 336 | // scale_bytes_per_token) -- a paged/pooled buffer's row stride is not |
| 337 | // guaranteed to match the logical per-block byte count. |
| 338 | const int64_t cache_row_stride = swa_kv_cache_2d.stride(0); |
| 339 | |
| 340 | auto q_out = at::zeros({num_tokens_full, q_head_padded, head_dim}, q.options()); |
| 341 | |
| 342 | AT_DISPATCH_REDUCED_FLOATING_TYPES(q.scalar_type(), "fused_qnorm_rope_kv_insert_cpu", [&] { |
| 343 | qnorm_rope_kv_insert_impl<scalar_t>( |
| 344 | q_out.data_ptr<scalar_t>(), |
| 345 | swa_kv_cache_2d.data_ptr<uint8_t>(), |
| 346 | q.data_ptr<scalar_t>(), |
| 347 | kv.data_ptr<scalar_t>(), |
| 348 | positions.data_ptr<int64_t>(), |
| 349 | slot_mapping.data_ptr<int64_t>(), |
| 350 | cos_sin_cache.data_ptr<float>(), |
| 351 | num_tokens_full, |
| 352 | num_heads_q, |
| 353 | q_head_padded, |
| 354 | head_dim, |
| 355 | nope_dim, |
| 356 | num_quant_blocks, |
| 357 | token_data_bytes, |
| 358 | scale_bytes_per_token, |
| 359 | num_tokens_insert, |
| 360 | cache_block_size, |
| 361 | cache_row_stride, |
| 362 | static_cast<float>(eps)); |
| 363 | }); |
| 364 | |
| 365 | return q_out; |
| 366 | } |
| 367 | |
| 368 | // vLLM-native: inverse GPT-J RoPE for `_o_proj`'s output de-rotation (undoes |
| 369 | // the query's own rotation on the attention output before the low-rank |
| 370 | // wo_a/wo_b projection -- see the math writeup in cpu_sparse.py's `_o_proj`). |
| 371 | // Upstream needs this same step (`fused_rope_inplace(..., inverse=True)` in |
| 372 | // `deepseek_v4.py`) but only has a CUDA-JIT implementation, no CPU kernel -- |
| 373 | // this fills that gap rather than porting one. Replaces the eager reference |
| 374 | // in `DeepseekV4CPUAttention._o_proj` (cpu_sparse.py). Uses the same |
| 375 | // half-half `[cos...|sin...]` cache layout as `apply_gptj_rope_inplace` |
| 376 | // above (not upstream's interleaved `[c0,s0,c1,s1,...]` layout). |
| 377 | // |
| 378 | // AVX512 path: NoPE dtype-convert copy uses `vec.h`'s `load_float_vec` |
| 379 | // (16-wide bf16/fp16 -> fp32). The interleaved (even,odd) rotation widens |
| 380 | // 32 raw elements to fp32 via `load_float_vec2`, round-trips them through |
| 381 | // an aligned scratch buffer, then gathers/scatters the even/odd lanes -- |
| 382 | // same technique as `indexer.cpp`'s Q-side RoPE, since `cos`/`sin` here |
| 383 | // are two contiguous halves rather than per-pair-interleaved. |
| 384 | at::Tensor inverse_gptj_rope_o_proj_cpu( |
| 385 | at::Tensor& o, // [num_tokens, num_heads, head_dim] |
| 386 | at::Tensor& positions, // [num_tokens] |
| 387 | at::Tensor& cos_sin_cache, // [max_pos, rope_dim] (first half cos, second half sin) |
| 388 | int64_t rope_dim) { |
| 389 | TORCH_CHECK(o.dim() == 3, "inverse_gptj_rope_o_proj_cpu: o must be 3D [num_tokens, num_heads, head_dim]"); |
| 390 | TORCH_CHECK(positions.scalar_type() == at::kLong, "inverse_gptj_rope_o_proj_cpu: positions must be int64"); |
| 391 | TORCH_CHECK( |
| 392 | o.device().is_cpu() && positions.device().is_cpu() && cos_sin_cache.device().is_cpu(), |
| 393 | "inverse_gptj_rope_o_proj_cpu: all inputs must be CPU tensors"); |
| 394 | |
| 395 | const int64_t num_tokens = o.size(0); |
| 396 | const int64_t num_heads = o.size(1); |
| 397 | const int64_t head_dim = o.size(2); |
| 398 | const int64_t nope_dim = head_dim - rope_dim; |
| 399 | const int64_t half_dim = rope_dim / 2; |
| 400 | TORCH_CHECK(nope_dim >= 0, "inverse_gptj_rope_o_proj_cpu: rope_dim must not exceed head_dim"); |
| 401 | // Only ever called with head_dim=512, rope_dim=64 (DeepseekV4CPUAttention's |
| 402 | // _o_proj); the AVX512 loops below process 16 elements/pairs per iteration |
| 403 | // with no scalar remainder, so require both to divide evenly. |
| 404 | TORCH_CHECK(nope_dim % 16 == 0 && half_dim % 16 == 0, |
| 405 | "inverse_gptj_rope_o_proj_cpu: head_dim-rope_dim and rope_dim/2 must be multiples of 16"); |
| 406 | TORCH_CHECK( |
| 407 | cos_sin_cache.scalar_type() == at::kFloat && cos_sin_cache.is_contiguous(), |
| 408 | "inverse_gptj_rope_o_proj_cpu: cos_sin_cache must be float32 and " |
| 409 | "contiguous (convert once in Python)"); |
| 410 | TORCH_CHECK(o.is_contiguous() && positions.is_contiguous(), |
| 411 | "inverse_gptj_rope_o_proj_cpu: o/positions must be contiguous"); |
| 412 | |
| 413 | auto out = at::empty({num_tokens, num_heads, head_dim}, o.options().dtype(at::kFloat)); |
| 414 | |
| 415 | AT_DISPATCH_REDUCED_FLOATING_TYPES(o.scalar_type(), "inverse_gptj_rope_o_proj_cpu", [&] { |
| 416 | const scalar_t* o_ptr = o.data_ptr<scalar_t>(); |
| 417 | float* out_ptr = out.data_ptr<float>(); |
| 418 | const int64_t* pos_ptr = positions.data_ptr<int64_t>(); |
| 419 | const float* cos_sin_ptr = cos_sin_cache.data_ptr<float>(); |
| 420 | |
| 421 | at::parallel_for(0, num_tokens * num_heads, 0, [&](int64_t begin, int64_t end) { |
| 422 | for (int64_t idx = begin; idx < end; ++idx) { |
| 423 | const int64_t t = idx / num_heads; |
| 424 | const int64_t h = idx % num_heads; |
| 425 | const scalar_t* src = o_ptr + (t * num_heads + h) * head_dim; |
| 426 | float* dst = out_ptr + (t * num_heads + h) * head_dim; |
| 427 | |
| 428 | // head_dim=512, rope_dim=64 in practice (checked above), so |
| 429 | // nope_dim/half_dim are always multiples of 16 -- no scalar |
| 430 | // remainder needed. |
| 431 | for (int64_t i = 0; i < nope_dim; i += 16) { |
| 432 | load_float_vec<scalar_t>(src + i).store(dst + i); |
| 433 | } |
| 434 | |
| 435 | const int64_t pos = pos_ptr[t]; |
| 436 | const float* cos = cos_sin_ptr + pos * rope_dim; |
| 437 | const float* sin = cos + half_dim; |
| 438 | |
| 439 | { |
| 440 | // Permute-based (no gather/scatter), adapted from SGLang's |
| 441 | // `rope.cpp` (`apply_rotary_emb_row`) the same way as |
| 442 | // compressor.cpp's `apply_gptj_rope_inplace`: `_mm512_permute_ps` |
| 443 | // swaps each pair's (even, odd) lanes in one shuffle, and cos/sin |
| 444 | // -- loaded as 8 contiguous values -- are duplicated pairwise via |
| 445 | // `_mm512_permutexvar_ps` to align with that layout, since our |
| 446 | // cos/sin are two separate flat arrays rather than SGLang's |
| 447 | // pre-interleaved freqs. Two batches of 8 pairs per iteration |
| 448 | // (matching `load_float_vec2`'s 16+16-lane split). |
| 449 | const __m512i dup_idx = _mm512_set_epi32(7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0, 0); |
| 450 | // Inverse GPT-J rotation negates the sin broadcast on the odd |
| 451 | // (imag) lane of each pair; the even (real) lane keeps sin's sign. |
| 452 | const __m512 sign_mask = _mm512_castsi512_ps(_mm512_set_epi32( |
| 453 | (int)0x80000000, 0, (int)0x80000000, 0, (int)0x80000000, 0, (int)0x80000000, 0, |
| 454 | (int)0x80000000, 0, (int)0x80000000, 0, (int)0x80000000, 0, (int)0x80000000, 0)); |
| 455 | for (int64_t j = 0; j < half_dim; j += 16) { |
| 456 | const scalar_t* rsrc = src + nope_dim + 2 * j; |
| 457 | at::vec::Vectorized<float> x0, x1; |
| 458 | std::tie(x0, x1) = load_float_vec2(rsrc); |
| 459 | float* rdst = dst + nope_dim + 2 * j; |
| 460 | |
| 461 | __m512 xv0 = x0; |
| 462 | __m512 cos_b0 = _mm512_permutexvar_ps(dup_idx, _mm512_castps256_ps512(_mm256_loadu_ps(cos + j))); |
| 463 | __m512 sin_b0 = _mm512_permutexvar_ps(dup_idx, _mm512_castps256_ps512(_mm256_loadu_ps(sin + j))); |
| 464 | __m512 out0 = _mm512_fmadd_ps( |
| 465 | xv0, cos_b0, _mm512_mul_ps(_mm512_permute_ps(xv0, 0xB1), _mm512_xor_ps(sin_b0, sign_mask))); |
| 466 | _mm512_storeu_ps(rdst, out0); |
| 467 | |
| 468 | __m512 xv1 = x1; |
| 469 | __m512 cos_b1 = _mm512_permutexvar_ps(dup_idx, _mm512_castps256_ps512(_mm256_loadu_ps(cos + j + 8))); |
| 470 | __m512 sin_b1 = _mm512_permutexvar_ps(dup_idx, _mm512_castps256_ps512(_mm256_loadu_ps(sin + j + 8))); |
| 471 | __m512 out1 = _mm512_fmadd_ps( |
| 472 | xv1, cos_b1, _mm512_mul_ps(_mm512_permute_ps(xv1, 0xB1), _mm512_xor_ps(sin_b1, sign_mask))); |
| 473 | _mm512_storeu_ps(rdst + 16, out1); |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | }); |
| 478 | }); |
| 479 | |
| 480 | return out; |
| 481 | } |