okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
9c143c403
main
1void quantize_q8_K_avx1(const float* x, void* vy, int64_t k) { 2 block_q8_K* y = (block_q8_K*) vy; 3 const int64_t nb = k / QK_K; 4 const __m128 absm = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)); 5 const __m128 magic = _mm_set1_ps(12582912.f); 6 const __m128i mant = _mm_set1_epi32(0x007fffff), off = _mm_set1_epi32(0x00400000); 7 const __m128i c127 = _mm_set1_epi32(127); 8 for (int64_t i = 0; i < nb; ++i, x += QK_K) { 9 __m128 m = _mm_setzero_ps(); 10 for (int j = 0; j < QK_K; j += 4) m = _mm_max_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), m); 11 __m128 h = _mm_max_ps(m, _mm_movehl_ps(m, m)); 12 h = _mm_max_ss(h, _mm_movehdup_ps(h)); 13 const float amax = _mm_cvtss_f32(h); 14 if (!amax) { 15 y[i].d = 0; 16 std::memset(y[i].qs, 0, QK_K); 17 continue; 18 } 19 float mx = 0.f; 20 const __m128 va = _mm_set1_ps(amax); 21 for (int j = 0; j < QK_K; j += 4) { 22 const int msk = _mm_movemask_ps(_mm_cmpeq_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), va)); 23 if (msk) { 24 int b = 0; 25 while (!((msk >> b) & 1)) ++b; 26 mx = x[j + b]; 27 break; 28 } 29 } 30 const float iscale = -127.f / mx; 31 const __m128 vis = _mm_set1_ps(iscale); 32 for (int j = 0; j < QK_K; j += 16) { 33 __m128i v[4]; 34 for (int q = 0; q < 4; ++q) { 35 __m128 p = _mm_mul_ps(vis, _mm_loadu_ps(x + j + 4 * q)); 36#if defined(__GNUC__) && !defined(__clang__) 37 // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference 38 // rounds the product before the add, so the product must stay a separate value (no FMA under 39 // -mavx, but the barrier keeps the contract if the file is ever built with a newer floor) 40 __asm__("" : "+x"(p)); 41#endif 42 const __m128 t = _mm_add_ps(p, magic); 43 v[q] = _mm_min_epi32(_mm_sub_epi32(_mm_and_si128(_mm_castps_si128(t), mant), off), c127); 44 // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those 45 // bytes: the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes 46 v[q] = _mm_srai_epi32(_mm_slli_epi32(v[q], 24), 24); 47 } 48 __m128i s = _mm_add_epi32(_mm_add_epi32(v[0], v[1]), _mm_add_epi32(v[2], v[3])); 49 s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0x4E)); 50 s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0xB1)); 51 y[i].bsums[j / 16] = (int16_t) _mm_cvtsi128_si32(s); 52 _mm_storeu_si128((__m128i*) (y[i].qs + j), 53 _mm_packs_epi16(_mm_packs_epi32(v[0], v[1]), _mm_packs_epi32(v[2], v[3]))); 54 } 55 y[i].d = 1 / iscale; 56 } 57}