MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / legacy-c / debug_layer.c
| 1 | /* debug_layer.c — Print first layer intermediate values for debugging. |
| 2 | * Compile: gcc -O0 -g -mavx2 -mfma -mf16c -fopenmp -shared -fPIC \ |
| 3 | * -o debug_layer.so debug_layer.c -lm |
| 4 | */ |
| 5 | #include <stdio.h> |
| 6 | #include <stdint.h> |
| 7 | #include <string.h> |
| 8 | #include <math.h> |
| 9 | #include <immintrin.h> |
| 10 | #include <omp.h> |
| 11 | |
| 12 | #define Q4_0_BS 18 |
| 13 | |
| 14 | static inline float f16_to_f32(uint16_t h) { return _cvtsh_ss(h); } |
| 15 | static inline float hsum_ps(__m256 v) { |
| 16 | __m128 l=_mm256_castps256_ps128(v),h=_mm256_extractf128_ps(v,1); |
| 17 | l=_mm_add_ps(l,h);l=_mm_hadd_ps(l,l);l=_mm_hadd_ps(l,l);return _mm_cvtss_f32(l); |
| 18 | } |
| 19 | |
| 20 | void test_q4_matmul(const uint8_t *W, const float *x, float *out, |
| 21 | int n_rows, int n_cols, int layer, const char *name) { |
| 22 | int bp=n_cols/32; |
| 23 | #pragma omp parallel for schedule(static) |
| 24 | for(int r=0;r<n_rows;r++){ |
| 25 | __m256 s0=_mm256_setzero_ps(),s1=_mm256_setzero_ps(); |
| 26 | for(int b=0;b<bp;b++){ |
| 27 | const uint8_t *p=W+((size_t)r*bp+b)*Q4_0_BS; |
| 28 | float sc=f16_to_f32((uint16_t)p[0]|((uint16_t)p[1]<<8)); |
| 29 | __m256 sv=_mm256_set1_ps(sc); |
| 30 | __m128i nb=_mm_loadu_si128((const __m128i*)(p+2)); |
| 31 | __m128i lo=_mm_and_si128(nb,_mm_set1_epi8(15)); |
| 32 | __m128i hi=_mm_and_si128(_mm_srli_epi16(_mm_and_si128(nb,_mm_set1_epi8((char)0xF0)),4),_mm_set1_epi8(15)); |
| 33 | __m128i ls=_mm_sub_epi8(lo,_mm_set1_epi8(8)),hs=_mm_sub_epi8(hi,_mm_set1_epi8(8)); |
| 34 | __m256 v0=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(ls))); |
| 35 | __m256 v1=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(_mm_shuffle_epi32(ls,0x4e)))); |
| 36 | __m256 v2=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(hs))); |
| 37 | __m256 v3=_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm_cvtepi8_epi16(_mm_shuffle_epi32(hs,0x4e)))); |
| 38 | v0=_mm256_mul_ps(v0,sv);v1=_mm256_mul_ps(v1,sv);v2=_mm256_mul_ps(v2,sv);v3=_mm256_mul_ps(v3,sv); |
| 39 | int o=b*32; |
| 40 | s0=_mm256_fmadd_ps(v0,_mm256_loadu_ps(x+o),s0); s0=_mm256_fmadd_ps(v1,_mm256_loadu_ps(x+o+8),s0); |
| 41 | s1=_mm256_fmadd_ps(v2,_mm256_loadu_ps(x+o+16),s1); s1=_mm256_fmadd_ps(v3,_mm256_loadu_ps(x+o+24),s1); |
| 42 | } |
| 43 | out[r]=hsum_ps(_mm256_add_ps(s0,s1)); |
| 44 | } |
| 45 | /* Print first 5 values */ |
| 46 | printf("Layer %d %s [0:5]: %.4f %.4f %.4f %.4f %.4f\n", |
| 47 | layer, name, out[0], out[1], out[2], out[3], out[4]); |
| 48 | } |