okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1// src/kernels/gdn_chunk_parity.cpp - v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence 2// and a host reference (GPU, synthetic, no model). 3// 4// The chunked path (src/prefill/gdn_chunk.cu) computes the SAME recurrence in a different summation order: 5// a 64-token chunk becomes one triangular solve and a batch of matmuls instead of 64 sequential rank-1 steps. 6// That is FP32-level, NOT bit-exact - the precedent is qsa_prompt_attn.hpp. So this test does not ask for 7// equality; it measures the error of both GPU paths against a double-precision transcription of the same 8// recurrence (`ref/gdn.py`'s, as re-pinned by gdn_parity) and asserts bounds: 9// 10// 1. the recurrence vs the host reference: the FP32 floor of the old path, 11// 2. the chunked path vs the host reference: the number that matters for the model, 12// 3. chunked vs recurrence directly: the observable switch STRATA_GDN_CHUNK flips. 13// 14// Both GPU paths go through the REAL dispatch (`gdn_recurrence`), A/B'd with the env switch, so the tail 15// (< 64 tokens) and the output norm are part of what is compared - the recurrence kernels' raw FP32 output for 16// the kernel comparisons (0.1.38's gdn_out_norm_kernel leaves it in place and writes only the FP16 copy), and 17// the norm's FP16 output once against the host reference's normalized values. 18#include "strata/prefill/gdn_chunk.hpp" 19#include "strata/prefill/kernels.hpp" 20 21#include <cuda_runtime.h> 22#include <cuda_fp16.h> 23 24#include <cmath> 25#include <cstdio> 26#include <cstdlib> 27#include <cstring> 28#include <limits> 29#include <string> 30#include <vector> 31 32#if defined(_WIN32 )// MSVC has no setenv / unsetenv 33#define setenv (k ,v ,o ) _putenv_s((k), (v)) 34#define unsetenv (k ) _putenv_s((k), "") 35#endif 36 37namespace { 38 39constexpr int S = 128 ,HK = 16 ,HV = 48 ,C = 10240 ; 40 41void check (cudaError_t e ,const char * what ) { 42if (e != cudaSuccess ) { 43 std::fprintf (stderr ,"%s: %s\n" ,what ,cudaGetErrorString (e )); 44 std::exit (1 ); 45 } 46} 47 48// the FP16 store's value back as FP32, for the one normalized-output comparison 49float half_to_float (uint16_t u ) { 50__half h ; 51 std::memcpy (& h ,& u ,2 ); 52return __half2float (h ); 53} 54 55// deterministic LCG - the same inputs on every machine and every run 56struct Rng { 57uint64_t s ; 58explicit Rng (uint64_t seed ) :s (seed ) {} 59float uni () { 60s = s * 6364136223846793005ULL + 1442695040888963407ULL ; 61return (float ) ((s >>40 )* (1.0 /16777216.0 )); 62 } 63}; 64 65/// The GDN chunk as a double-precision transcription of the recurrence in strata/kernels/gdn.hpp: the state 66/// (S, h_v, S) f32 layout, decay BEFORE the rank-1 update, modulo head pairing. `yraw_out` is the raw output 67/// the recurrence kernels leave for gdn_out_norm_kernel; `y_out` is the norm's value, formed exactly as 68/// gdn_out_norm_kernel forms it (sqrt(S) in the oc scale, +eps on the SCALED squared norm). 69void ref_full (const std::vector < float >& st0 ,const std::vector < float >& h ,const std::vector < float >& gate , 70const std::vector < float >& beta ,const std::vector < float >& z ,const std::vector < float >& gamma , 71float eps ,int64_t T , std::vector < float >& yraw_out , std::vector < float >& y_out , 72 std::vector < float >& st_out ) { 73 std::vector < double > st ((size_t )S * HV * S ); 74for (size_t i = 0 ;i < st .size ();++ i )st [i ]= (double )st0 [i ]; 75y_out .assign ((size_t )T * HV * S ,0.0f ); 76yraw_out .assign ((size_t )T * HV * S ,0.0f ); 77 std::vector < double > o (S ); 78for (int64_t t = 0 ;t < T ;++ t ) { 79for (int hh = 0 ;hh < HV ;++ hh ) { 80const int qh = hh %HK ; 81const double dec = std::exp ((double )gate [(size_t )t * HV + hh ]); 82const double b = (double )beta [(size_t )t * HV + hh ]; 83for (int j = 0 ;j < S ;++ j ) { 84double sk = 0.0 ; 85for (int i = 0 ;i < S ;++ i )sk += st [((size_t )i * HV + hh )* S + j ]* (double )h [(size_t )t * C + HK * S + qh * S + i ]; 86const double d = ((double )h [(size_t )t * C + 2 * HK * S + hh * S + j ]- dec * sk )* b ; 87for (int i = 0 ;i < S ;++ i ) { 88double & w = st [((size_t )i * HV + hh )* S + j ]; 89w = dec * w + (double )h [(size_t )t * C + HK * S + qh * S + i ]* d ; 90 } 91double dot = 0.0 ; 92for (int i = 0 ;i < S ;++ i )dot += st [((size_t )i * HV + hh )* S + j ]* (double )h [(size_t )t * C + qh * S + i ]; 93o [j ]= dot / std::sqrt ((double )S );// the oc scale of gdn_rec_cols_kernel 94 } 95double ss = 0.0 ; 96for (int j = 0 ;j < S ;++ j )ss += o [j ]* o [j ]; 97const double rs = 1.0 / std::sqrt (ss / (double )S + (double )eps ); 98for (int j = 0 ;j < S ;++ j ) { 99yraw_out [((size_t )t * HV + hh )* S + j ]= (float )o [j ]; 100const double sig = 1.0 / (1.0 + std::exp (- (double )z [(size_t )t * HV * S + hh * S + j ])); 101y_out [((size_t )t * HV + hh )* S + j ]= (float ) (o [j ]* rs * (double )gamma [j ]* sig ); 102 } 103 } 104 } 105st_out .resize (st .size ()); 106for (size_t i = 0 ;i < st .size ();++ i )st_out [i ]= (float )st [i ]; 107} 108 109struct Err { 110float abs_ = 0 ,rel_ = 0 ; 111void see (float a ,float b ) { 112const float d = std::fabs (a - b ); 113const float m = std::fabs (b ); 114// a NaN or inf anywhere is a hard error: an unordered comparison would otherwise leave the max at 0 115if (!std::isfinite (a )|| !std::isfinite (b )) { 116abs_ = rel_ = std::numeric_limits < float > ::infinity (); 117return ; 118 } 119if (d > abs_ )abs_ = d ; 120const float r = d / (m + 1e-4f ); 121if (r > rel_ )rel_ = r ; 122 } 123}; 124 125int failures = 0 ; 126 127void expect (const char * what ,const Err & e ,float bound_abs ,float bound_rel ) { 128const bool ok = e .rel_ <=bound_rel && e .abs_ <=bound_abs ; 129 std::printf (" %-38s max abs %.3e max rel %.3e (bounds abs %.1e rel %.1e) %s\n" ,what ,e .abs_ ,e .rel_ , 130bound_abs ,bound_rel ,ok ?"ok" :"FAIL" ); 131if (!ok )++ failures ; 132} 133 134void run_case (int64_t T ,uint64_t seed ) { 135 std::printf ("T = %lld%s\n" , (long long )T , (T %64 ) ?" (tail: T % 64 != 0)" :"" ); 136Rng rng (seed ); 137 std::vector < float > h ((size_t )T * C ),gate ((size_t )T * HV ),beta ((size_t )T * HV ),z ((size_t )T * HV * S ), 138gamma (S ),st0 ((size_t )S * HV * S ); 139for (int64_t t = 0 ;t < T ;++ t ) { 140for (int qh = 0 ;qh < HK ;++ qh ) {// q and k: L2-normalised rows, as gdn_conv leaves them 141for (int part = 0 ;part < 2 ;++ part ) { 142double ss = 0 ; 143float row [S ]; 144for (int i = 0 ;i < S ;++ i ) { 145row [i ]= rng .uni ()- 0.5f ; 146ss += (double )row [i ]* row [i ]; 147 } 148const float nrm = (float ) (1.0 / std::sqrt (ss + 1e-5 )); 149for (int i = 0 ;i < S ;++ i )h [(size_t )t * C + (part ?HK * S :0 )+ qh * S + i ]= row [i ]* nrm ; 150 } 151 } 152for (int hh = 0 ;hh < HV ;++ hh ) { 153for (int j = 0 ;j < S ;++ j )// v: O(1) rows 154h [(size_t )t * C + 2 * HK * S + hh * S + j ]= rng .uni ()- 0.5f ; 155gate [(size_t )t * HV + hh ]= -0.02f - 0.3f * rng .uni (); 156beta [(size_t )t * HV + hh ]= 1.0f / (1.0f + std::exp (- (4.0f * rng .uni ()- 2.0f ))); 157for (int j = 0 ;j < S ;++ j )z [((size_t )t * HV + hh )* S + j ]= 2.0f * rng .uni ()- 1.0f ; 158 } 159 } 160for (int j = 0 ;j < S ;++ j )gamma [j ]= 0.5f + 2.0f * rng .uni (); 161for (size_t i = 0 ;i < st0 .size ();++ i )st0 [i ]= 0.1f * (rng .uni ()- 0.5f ); 162const float eps = 1e-5f ; 163 164 std::vector < float > y_ref ,yraw_ref ,st_ref ; 165ref_full (st0 ,h ,gate ,beta ,z ,gamma ,eps ,T ,yraw_ref ,y_ref ,st_ref ); 166 167float * d_st = nullptr ,* d_h = nullptr ,* d_g = nullptr ,* d_b = nullptr ,* d_z = nullptr ,* d_ga = nullptr , 168* d_y = nullptr ,* d_st0 = nullptr ; 169uint16_t * d_y16 = nullptr ; 170check (cudaMalloc (& d_st ,st0 .size ()* 4 ),"malloc" ); 171check (cudaMalloc (& d_st0 ,st0 .size ()* 4 ),"malloc" ); 172check (cudaMalloc (& d_h ,h .size ()* 4 ),"malloc" ); 173check (cudaMalloc (& d_g ,gate .size ()* 4 ),"malloc" ); 174check (cudaMalloc (& d_b ,beta .size ()* 4 ),"malloc" ); 175check (cudaMalloc (& d_z ,z .size ()* 4 ),"malloc" ); 176check (cudaMalloc (& d_ga ,gamma .size ()* 4 ),"malloc" ); 177check (cudaMalloc (& d_y ,y_ref .size ()* 4 ),"malloc" ); 178check (cudaMalloc (& d_y16 ,y_ref .size ()* 2 ),"malloc" ); 179check (cudaMemcpy (d_st0 ,st0 .data (),st0 .size ()* 4 ,cudaMemcpyHostToDevice ),"H2D" ); 180check (cudaMemcpy (d_h ,h .data (),h .size ()* 4 ,cudaMemcpyHostToDevice ),"H2D" ); 181check (cudaMemcpy (d_g ,gate .data (),gate .size ()* 4 ,cudaMemcpyHostToDevice ),"H2D" ); 182check (cudaMemcpy (d_b ,beta .data (),beta .size ()* 4 ,cudaMemcpyHostToDevice ),"H2D" ); 183check (cudaMemcpy (d_z ,z .data (),z .size ()* 4 ,cudaMemcpyHostToDevice ),"H2D" ); 184check (cudaMemcpy (d_ga ,gamma .data (),gamma .size ()* 4 ,cudaMemcpyHostToDevice ),"H2D" ); 185 186 std::vector < float > y_gpu (y_ref .size ()),st_gpu (st0 .size ()); 187 std::vector < float > y_rec (y_ref .size ()),st_rec (st0 .size ()),y_warp (y_ref .size ()),st_warp (st0 .size ()), 188y_fast (y_ref .size ()),st_fast (st0 .size ()),y_fma (y_ref .size ()),st_fma (st0 .size ()); 189auto run = [& ](const char * chunk ,const char * warp , std::vector < float >& y , std::vector < float >& st , 190 std::vector < float >* y16f = nullptr ) { 191setenv ("STRATA_GDN_CHUNK" ,chunk ,1 ); 192setenv ("STRATA_GDN_REC_WARP" ,warp ,1 ); 193check (cudaMemcpy (d_st ,d_st0 ,st0 .size ()* 4 ,cudaMemcpyDeviceToDevice ),"D2D" ); 194 strata::prefill::gdn_recurrence (d_st ,d_h ,d_g ,d_b ,d_z ,d_ga ,eps ,d_y ,d_y16 ,T ,nullptr ); 195check (cudaDeviceSynchronize (),"sync" ); 196check (cudaMemcpy (y .data (),d_y ,y .size ()* 4 ,cudaMemcpyDeviceToHost ),"D2H" ); 197check (cudaMemcpy (st .data (),d_st ,st .size ()* 4 ,cudaMemcpyDeviceToHost ),"D2H" ); 198if (y16f != nullptr ) { 199 std::vector < uint16_t > h16 (y .size ()); 200check (cudaMemcpy (h16 .data (),d_y16 ,h16 .size ()* 2 ,cudaMemcpyDeviceToHost ),"D2H" ); 201y16f -> resize (y .size ()); 202for (size_t i = 0 ;i < y .size ();++ i ) (* y16f )[i ]= half_to_float (h16 [i ]); 203 } 204 }; 205 std::vector < float > y16_rec ; 206run ("0" ,"0" ,y_rec ,st_rec ,& y16_rec );// the old pipelined recurrence (+ the norm's FP16 output) 207run ("0" ,"1" ,y_warp ,st_warp );// the sync-free warp recurrence - must be BIT-EXACT vs the above 208run ("0" ,"2" ,y_fast ,st_fast );// the chain-split recurrence (the V100 default) 209run ("1" ,"0" ,y_gpu ,st_gpu );// the chunked path's wmma variant 210run ("2" ,"0" ,y_fma ,st_fma );// the chunked path's FP32 FMA variant 211 212size_t bits = 0 ; 213for (size_t i = 0 ;i < y_ref .size ();++ i ) 214if (std::memcmp (& y_rec [i ],& y_warp [i ],4 )!= 0 )++ bits ; 215for (size_t i = 0 ;i < st_ref .size ();++ i ) 216if (std::memcmp (& st_rec [i ],& st_warp [i ],4 )!= 0 )++ bits ; 217 std::printf (" %-38s %s\n" ,"warp recurrence vs pipelined (bits)" ,bits ?"FAIL" :"bit-exact" ); 218if (bits )++ failures ; 219 220Err e_yr ,e_y ,e_yf ,e_ym ,e_yc ,e_yn ,e_sr ,e_s ,e_sf ,e_sm ,e_sc ; 221for (size_t i = 0 ;i < y_ref .size ();++ i ) { 222e_yr .see (y_rec [i ],yraw_ref [i ]); 223e_yf .see (y_fast [i ],yraw_ref [i ]); 224e_ym .see (y_fma [i ],yraw_ref [i ]); 225e_y .see (y_gpu [i ],yraw_ref [i ]); 226e_yc .see (y_gpu [i ],y_rec [i ]); 227e_yn .see (y16_rec [i ],y_ref [i ]); 228 } 229for (size_t i = 0 ;i < st_ref .size ();++ i ) { 230e_sr .see (st_rec [i ],st_ref [i ]); 231e_sf .see (st_fast [i ],st_ref [i ]); 232e_sm .see (st_fma [i ],st_ref [i ]); 233e_s .see (st_gpu [i ],st_ref [i ]); 234e_sc .see (st_gpu [i ],st_rec [i ]); 235 } 236// The bounds are the measured errors of this build on the V100 with ~3x margin (rel uses a 1e-4 floor on 237// the reference magnitude). The recurrence is the FP32 floor; the FMA chunked path reorders the sums 238// (FP32-level, not bit-exact - qsa_prompt_attn.hpp's precedent); the wmma chunked path additionally 239// stages q/k/v and the state through FP16 (the reference's f32 -> f16 staging), which is the error level 240// llama.cpp-v100's FlashQLA sm70 path ships with. The y rows compared here are the recurrence kernels' 241// raw output (0.1.38's norm keeps its FP32 store out); the last line reads the norm's FP16 copy instead. 242expect ("recurrence vs host ref (y)" ,e_yr ,5e-6f ,1e-2f ); 243expect ("chain-split recurrence (y)" ,e_yf ,1e-5f ,2e-2f ); 244expect ("chunked FMA vs host ref (y)" ,e_ym ,1e-5f ,2e-2f ); 245expect ("chunked wmma vs host ref (y)" ,e_y ,6e-3f ,5e1f ); 246expect ("chunked wmma vs recurrence (y)" ,e_yc ,6e-3f ,5e1f ); 247expect ("output norm (FP16) vs host ref (y)" ,e_yn ,8e-3f ,5e-2f ); 248expect ("recurrence vs host ref (state)" ,e_sr ,1e-7f ,5e-4f ); 249expect ("chain-split recurrence (state)" ,e_sf ,5e-7f ,2e-3f ); 250expect ("chunked FMA vs host ref (state)" ,e_sm ,5e-7f ,2e-3f ); 251expect ("chunked wmma vs host ref (state)" ,e_s ,3e-4f ,2e0f ); 252expect ("chunked wmma vs recurrence (state)" ,e_sc ,3e-4f ,2e0f ); 253 254cudaFree (d_st );cudaFree (d_st0 );cudaFree (d_h );cudaFree (d_g );cudaFree (d_b );cudaFree (d_z ); 255cudaFree (d_ga );cudaFree (d_y );cudaFree (d_y16 ); 256} 257 258}// namespace 259 260int main (int argc ,char ** argv ) { 261bool selftest = false; 262for (int i = 1 ;i < argc ;++ i ) { 263if (std::strcmp (argv [i ],"--selftest" )== 0 )selftest = true; 264else { std::fprintf (stderr ,"usage: gdn_chunk_parity [--selftest]\n" );return 2 ; } 265 } 266 { 267// the kkt stage needs 2*64*129 floats (66 KB) of dynamic shared memory: a card whose opt-in limit is lower 268// (Pascal: 48 KB) cannot launch it, and the engine dispatch never selects the chunked path there 269int dev = 0 ,smem = 0 ; 270cudaGetDevice (& dev ); 271cudaDeviceGetAttribute (& smem ,cudaDevAttrMaxSharedMemoryPerBlockOptin ,dev ); 272if (smem < 2 * 64 * 129 * 4 ) { 273 std::printf ("gdn_chunk_parity: the card's shared-memory opt-in (%d B) is below the kkt stage's need, skipped\n" ,smem ); 274return 77 ; 275 } 276 } 277if (!strata::prefill::gdn_chunk_available ()) 278 std::printf ("note: not a V100 (cc 7.0) - the parity still runs; the engine dispatch keeps the recurrence\n" ); 279run_case (64 ,1 ); 280run_case (128 ,2 ); 281run_case (200 ,3 );// tail: T % 64 = 8 282run_case (320 ,4 ); 283 std::printf ("\ngdn_chunk: %d failures\n" ,failures ); 284if (selftest && failures == 0 ) std::printf ("gdn_chunk_parity OK\n" ); 285return failures ?1 :0 ; 286}