void quantize_q8_K_avx2(const float* x, void* vy, int64_t k) { block_q8_K* y = (block_q8_K*) vy; const int64_t nb = k / QK_K; const __m256 absm = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)); const __m256 magic = _mm256_set1_ps(12582912.f); const __m256i mant = _mm256_set1_epi32(0x007fffff), off = _mm256_set1_epi32(0x00400000); const __m256i c127 = _mm256_set1_epi32(127); const __m256i perm = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7); for (int64_t i = 0; i < nb; ++i, x += QK_K) { __m256 m = _mm256_setzero_ps(); for (int j = 0; j < QK_K; j += 8) m = _mm256_max_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), m); __m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1)); h = _mm_max_ps(h, _mm_movehl_ps(h, h)); h = _mm_max_ss(h, _mm_movehdup_ps(h)); const float amax = _mm_cvtss_f32(h); if (!amax) { y[i].d = 0; std::memset(y[i].qs, 0, QK_K); continue; } float mx = 0.f; const __m256 va = _mm256_set1_ps(amax); for (int j = 0; j < QK_K; j += 8) { const int msk = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), va, _CMP_EQ_OQ)); if (msk) { int b = 0; while (!((msk >> b) & 1)) ++b; mx = x[j + b]; break; } } const float iscale = -127.f / mx; const __m256 vis = _mm256_set1_ps(iscale); for (int j = 0; j < QK_K; j += 32) { __m256i v[4]; for (int q = 0; q < 4; ++q) { __m256 p = _mm256_mul_ps(vis, _mm256_loadu_ps(x + j + 8 * q)); #if defined(__GNUC__) && !defined(__clang__) // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference rounds // the product before the add, so the product must stay a separate value __asm__("" : "+x"(p)); #endif const __m256 t = _mm256_add_ps(p, magic); v[q] = _mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(t), mant), off), c127); // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those bytes: // the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes v[q] = _mm256_srai_epi32(_mm256_slli_epi32(v[q], 24), 24); } for (int q = 0; q < 2; ++q) { // two 16-value sums const __m256i s = _mm256_add_epi32(v[2 * q], v[2 * q + 1]); __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(s), _mm256_extracti128_si256(s, 1)); s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4E)); s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1)); y[i].bsums[j / 16 + q] = (int16_t) _mm_cvtsi128_si32(s4); } const __m256i p16a = _mm256_packs_epi32(v[0], v[1]), p16b = _mm256_packs_epi32(v[2], v[3]); const __m256i p8 = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(p16a, p16b), perm); _mm256_storeu_si256((__m256i*) (y[i].qs + j), p8); } y[i].d = 1 / iscale; } }