okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
9258e4086
main
1// metal/include/metal_compat/cuda_bf16.h - the handful of CUDA bf16/fp8 names the dsv41 sources use, on Metal. 2// 3// Only what the engine touches (found by compiling src/dsv41/*.cu against this directory, 2026-10-23): the storage typedef 4// and four conversions. On a Mac the bf16 storage is a uint16_t and the conversion is the standard round-to-nearest-even 5// truncation CUDA's __float2bfloat16_rn does; fp8 is E4M3 with the same rounding. 6#pragma once 7 8#include "cuda_fp16.h" // __half_raw, which the fp8 conversions return 9#include <cstdint> 10#include <cstring> 11 12typedef uint16_t __nv_bfloat16 ; 13typedef uint16_t __nv_bfloat162 ; 14typedef uint8_t __nv_fp8_storage_t ; 15 16static inline uint16_t strata_f32_to_bf16_rn (float f ) { 17uint32_t u ; 18std ::memcpy (& u ,& f ,sizeof u ); 19if ((u & 0x7fffffffu )> 0x7f800000u )return (uint16_t ) ((u >>16 ) |0x0040u );// NaN keeps a payload 20uint32_t r = (u + 0x7fffu + ((u >>16 )& 1u )) >>16 ; 21return (uint16_t )r ; 22} 23 24static inline __nv_bfloat16 __float2bfloat16_rn (float f ) {return strata_f32_to_bf16_rn (f ); } 25static inline uint16_t __bfloat16_as_ushort (__nv_bfloat16 v ) {return v ; } 26 27// E4M3 (no infinities, max 448), round to nearest even - the inverse of the half conversion the engine also uses 28static inline __nv_fp8_storage_t __nv_cvt_float_to_fp8 (float f ,int ,int ) { 29if (f != f )return 0x7f ; 30float a = f < 0 ?- f :f ; 31int sign = f < 0 ?0x80 :0 ; 32if (a == 0.0f )return (__nv_fp8_storage_t )sign ; 33if (a >=448.0f )return (__nv_fp8_storage_t ) (sign |0x7e ); 34int e = 0 ; 35while (a >=2.0f ) {a *=0.5f ;++ e ; } 36while (a < 1.0f ) {a *=2.0f ;-- e ; } 37// a in [1,2): 3 mantissa bits, bias 7 38float scaled = (a - 1.0f )* 8.0f ; 39int m = (int ) (scaled + 0.5f ); 40int biased = e + 7 ; 41if (m == 8 ) {m = 0 ;++ biased ; } 42if (biased <=0 )return (__nv_fp8_storage_t )sign ;// subnormal -> zero here 43if (biased >=15 )return (__nv_fp8_storage_t ) (sign |0x7e );// clamp to 448 44return (__nv_fp8_storage_t ) (sign | (biased <<3 ) |m ); 45} 46static inline uint16_t __nv_cvt_fp8_to_halfraw (__nv_fp8_storage_t v ,int ) { 47// half (IEEE binary16) from E4M3: the engine only reads these back for the vision tower's tables 48const int sign = (v & 0x80 ) ?0x8000 :0 ; 49const int e = (v >>3 )& 0xf ,m = v & 0x7 ; 50if (e == 0 && m == 0 )return (uint16_t )sign ; 51int he ,hm ; 52if (e == 0 ) {he = 0 ;hm = m <<7 ; } 53else {he = e - 7 + 15 ;hm = m <<7 ; } 54return (uint16_t ) (sign | (he <<10 ) |hm ); 55} 56 57// the conversion modes __nv_cvt_float_to_fp8 / __nv_cvt_fp8_to_halfraw take (CUDA spells them as an enum) 58enum __nv_fp8_interpretation_t {__NV_E4M3 = 0 ,__NV_E5M2 = 1 }; 59enum __nv_saturation_t {__NV_NOSAT = 0 ,__NV_SATFINITE = 1 };