okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0a9381336
main
1// src/quant/internal.hpp - block layouts and helpers shared by the layer's own sources (never included by a public header). 2// 3// Block structs and codebooks come from third_party/strata-ggml/strata-quant-common.h (ours since 1B; llama.cpp's ggml-common.h at the pin). 4// It is included here in its C declaration flavour: the anonymous unions of the K-quant blocks (`d`/`dmin`/`dm`) are then plain members in C++ too 5// (GCC, Clang and MSVC accept them). A source that needs the codebook tables (the i-quant grids, kvalues_iq4nl, ...) defines STRATA_QUANT_TABLES 6// before this header; they are `static const` tables per translation unit. 7#pragma once 8 9#define GGML_COMMON_DECL_C 10#ifdef STRATA_QUANT_TABLES 11#define GGML_COMMON_IMPL_C 12#endif 13#include "strata-quant-common.h" 14 15#include <cmath> 16#include <cstdint> 17#include <cstring> 18 19#include "strata/quant/fp16.hpp" 20#include "strata/quant/types.hpp" 21 22#if defined(_MSC_VER ) 23#define STRATA_RESTRICT __restrict 24#else 25#define STRATA_RESTRICT __restrict__ 26#endif 27 28namespace strata::quant { 29 30 31/// ggml's ue4m3 (NVFP4 sub-block scales) decoder, halved as ggml does: a 256-entry table (the NVFP4 dots decode four scales a block, and the ldexp form made them 32/// five times slower than ggml's table lookup). The values are those of the formula in ue4m3_formula. 33inline float ue4m3_formula (uint8_t x ) { 34if (x == 0 || x == 0x7F )return 0.0f ; 35const int exp = (x >>3 )& 0xF ; 36const int man = x & 0x7 ; 37const float raw = exp == 0 ? std::ldexp ((float )man ,-9 ) : std::ldexp (1.0f + (float )man /8.0f ,exp - 7 ); 38return raw * 0.5f ; 39} 40struct Ue4m3Table { 41float v [256 ]; 42Ue4m3Table () { 43for (int i = 0 ;i < 256 ;++ i )v [i ]= ue4m3_formula ((uint8_t )i ); 44 } 45}; 46inline const Ue4m3Table g_ue4m3_table ;// built before main (ggml's ggml_table_f32_ue4m3 is a plain global table too); nothing decodes a scale during static initialization 47inline float ue4m3_to_fp32 (uint8_t x ) {return g_ue4m3_table .v [x ]; } 48/// ggml's e8m0 (MXFP4) decoder, halved as ggml does. 49inline float e8m0_to_fp32_half (uint8_t x ) { 50const uint32_t bits = x < 2 ? (0x00200000u <<x ) : (uint32_t ) (x - 1 ) <<23 ; 51return f32_from_bits (bits ); 52} 53 54/// ggml's nearest_int: round half to even through the 2^23 + 2^22 magic number (|v| <= 4194303). 55inline int nearest_int (float v ) { 56const float val = v + 12582912.f ; 57int i ; 58 std::memcpy (& i ,& val ,sizeof i ); 59return (i & 0x007fffff )- 0x00400000 ; 60} 61 62}// namespace strata::quant