okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6aae30348
main
1// src/prefill/kv_host_dma_parity.cpp - the prompt path's K/V append under KV streaming, both ways (GPU, synthetic, no model): 2// (a) the append kernel writes the host copy itself (STRATA_KV_HOST_DMA=0), 3// (b) the append writes the staging pool and the VRAM slots only, then kv_unstage_to_host copies the chunk's blocks 4// from the staging pool to the host copy by DMA on the same stream (the CUDA default, core/kv_host_dma.hpp). 5// Per format (fp16, int8 + scales, q4_0) a 4,048-cell context is appended in four chunks whose starts are not block 6// aligned (0, 999, 1000, 3045; one chunk of a single cell), each chunk staged from the host copy first as the prompt 7// path does. After every chunk, before any host-side wait on the append's stream, a reader on ANOTHER stream that waits 8// for an event recorded right after the append reads the host copy back; then the host copies, the read-backs and the 9// VRAM slot pools of (a) and (b) must be byte-equal over every cell written so far. The staging pools start as junk, 10// the host copies as zeros, so a block that was not copied, or a copy that ran before its append, shows up. 11// 12// kv_host_dma_parity [--device N] exit 0: every case equal; 1: a difference; 77: no GPU 13#include "strata/kernels/kv_q4.hpp" 14#include "strata/kernels/kv_q8.hpp" 15#include "strata/kernels/kv_stream.hpp" 16#include "strata/kernels/qsa.hpp" 17#include "strata/kernels/qsa_decode_attn.hpp" 18#include "strata/prefill/kernels.hpp" 19 20#include <cuda_runtime.h> 21 22#include <algorithm> 23#include <cstdint> 24#include <cstdio> 25#include <cstdlib> 26#include <cstring> 27#include <random> 28#include <string> 29#include <vector> 30 31namespace k= strata::kernels; 32 33namespace { 34bool ck (cudaError_t e ,const char * what ) { 35if (e != cudaSuccess ) { 36 std::fprintf (stderr ,"kv_host_dma_parity: %s: %s\n" ,what ,cudaGetErrorString (e )); 37return false; 38 } 39return true; 40} 41 42// One array of a pool: bytes per (cell, head) row. 43struct Arr { 44size_t row = 0 ; 45}; 46 47struct Pools {// one set of arrays (fp16: 2, int8: 4, q4: 2), each [n_pages][2][page_size] rows 48 std::vector < uint8_t *> a ; 49}; 50 51k::KvHostPools as_host (const Pools & p ,int fmt ) { 52 k::KvHostPools h ; 53if (fmt == k::kKvF16 ) {h .k_pool = (uint16_t * )p .a [0 ];h .v_pool = (uint16_t * )p .a [1 ]; } 54else if (fmt == k::kKvInt8 ) {h .k_q = (int8_t * )p .a [0 ];h .v_q = (int8_t * )p .a [1 ];h .k_scale = (uint16_t * )p .a [2 ];h .v_scale = (uint16_t * )p .a [3 ]; } 55else {h .k_q4 = p .a [0 ];h .v_q4 = p .a [1 ]; } 56return h ; 57} 58 59k::QsaAttnPools as_attn (const Pools & p ,int fmt ) { 60const k::KvHostPools h = as_host (p ,fmt ); 61 k::QsaAttnPools q ; 62q .k_pool = h .k_pool ;q .v_pool = h .v_pool ;q .k_q = h .k_q ;q .v_q = h .v_q ;q .k_scale = h .k_scale ;q .v_scale = h .v_scale ; 63q .k_q4 = h .k_q4 ;q .v_q4 = h .v_q4 ; 64return q ; 65} 66 67std::vector < Arr > arrays_of (int fmt ,const k::QsaShapes & s ) { 68if (fmt == k::kKvF16 )return {{(size_t )s .head_dim * 2 }, {(size_t )s .head_dim * 2 }}; 69if (fmt == k::kKvInt8 ) { 70const size_t sc = (size_t ) (s .head_dim / k::KV_Q8_GROUP )* 2 ; 71return {{(size_t )s .head_dim }, {(size_t )s .head_dim }, {sc }, {sc }}; 72 } 73const size_t q4 = (size_t ) k::kv_q4_bytes_per_head ((int )s .head_dim ); 74return {{q4 }, {q4 }}; 75} 76 77const char * fmt_name (int fmt ) {return fmt == k::kKvF16 ?"fp16" :fmt == k::kKvInt8 ?"int8" :"q4_0" ; } 78 79int run_format (int fmt ) { 80 k::QsaShapes s = k::qsa_real_shapes (); 81const int64_t ps = s .page_size ,nkv = s .n_head_kv ,hd = s .head_dim ; 82const int64_t n_cells = 4096 ,n_pages = n_cells /ps ,rows = n_pages * nkv * ps ; 83const std::vector < Arr > arrs = arrays_of (fmt ,s ); 84const int na = (int )arrs .size (); 85// the VRAM slots: one slot per resident page; about a third of the pages are not resident (-1) 86 std::mt19937 rng (1234u + (unsigned )fmt ); 87 std::vector < int32_t > table ((size_t )n_pages ); 88 { 89 std::vector < int32_t > perm ((size_t )n_pages ); 90for (int64_t i = 0 ;i < n_pages ;++ i )perm [(size_t )i ]= (int32_t )i ; 91 std::shuffle (perm .begin (),perm .end (),rng ); 92for (int64_t i = 0 ;i < n_pages ;++ i )table [(size_t )i ]= (rng () %3 == 0 ) ?-1 :perm [(size_t )i ]; 93 } 94int32_t * d_table = nullptr ; 95if (!ck (cudaMalloc (& d_table ,table .size ()* 4 ),"table" )|| 96 !ck (cudaMemcpy (d_table ,table .data (),table .size ()* 4 ,cudaMemcpyHostToDevice ),"table up" ))return 2 ; 97// per path (0 = kernel stores, 1 = DMA): host copy (pinned, mapped), staging pool, slot pool, read-back buffer 98Pools host [2 ],host_dev [2 ],stage [2 ],slots [2 ],back [2 ]; 99for (int w = 0 ;w < 2 ;++ w ) { 100for (int i = 0 ;i < na ;++ i ) { 101const size_t bytes = (size_t )rows * arrs [(size_t )i ].row ; 102uint8_t * h = nullptr ,* hd_ptr = nullptr ,* st = nullptr ,* sl = nullptr ,* bk = nullptr ; 103if (!ck (cudaHostAlloc ((void ** )& h ,bytes ,cudaHostAllocMapped |cudaHostAllocPortable ),"host copy" )|| 104 !ck (cudaHostGetDevicePointer ((void ** )& hd_ptr ,h ,0 ),"host device pointer" )|| 105 !ck (cudaMalloc (& st ,bytes ),"stage" )|| !ck (cudaMalloc (& sl ,bytes ),"slots" )|| !ck (cudaMalloc (& bk ,bytes ),"back" )) 106return 2 ; 107 std::memset (h ,0 ,bytes ); 108ck (cudaMemset (st ,0xA5 ,bytes ),"stage junk" ); 109ck (cudaMemset (sl ,0x5A ,bytes ),"slots junk" ); 110ck (cudaMemset (bk ,0x00 ,bytes ),"back zero" ); 111host [w ].a .push_back (h );host_dev [w ].a .push_back (hd_ptr );stage [w ].a .push_back (st );slots [w ].a .push_back (sl ); 112back [w ].a .push_back (bk ); 113 } 114 } 115cudaStream_t cs = nullptr ,rd = nullptr ; 116cudaEvent_t ev = nullptr ; 117if (!ck (cudaStreamCreateWithFlags (& cs ,cudaStreamNonBlocking ),"stream" )|| 118 !ck (cudaStreamCreateWithFlags (& rd ,cudaStreamNonBlocking ),"reader stream" )|| 119 !ck (cudaEventCreateWithFlags (& ev ,cudaEventDisableTiming ),"event" ))return 2 ; 120const int64_t chunks [4 ][2 ]= {{0 ,999 }, {999 ,1 }, {1000 ,2045 }, {3045 ,1003 }}; 121 std::normal_distribution < float > nd (0.0f ,1.0f ); 122float * dK = nullptr ,* dV = nullptr ; 123if (!ck (cudaMalloc (& dK , (size_t )2045 * nkv * hd * 4 ),"K" )|| !ck (cudaMalloc (& dV , (size_t )2045 * nkv * hd * 4 ),"V" ))return 2 ; 124int bad = 0 ; 125for (const auto & c :chunks ) { 126const int64_t p0 = c [0 ],T = c [1 ],end = p0 + T ; 127 std::vector < float > K ((size_t ) (T * nkv * hd )),V (K .size ()); 128for (auto & x :K )x = nd (rng )* 3.0f ; 129for (auto & x :V )x = nd (rng )* 3.0f ; 130ck (cudaMemcpy (dK ,K .data (),K .size ()* 4 ,cudaMemcpyHostToDevice ),"K up" ); 131ck (cudaMemcpy (dV ,V .data (),V .size ()* 4 ,cudaMemcpyHostToDevice ),"V up" ); 132// the uploads and the junk fills run on the legacy stream, which the two non-blocking streams do not wait for 133if (!ck (cudaDeviceSynchronize (),"uploads" ))return 2 ; 134for (int w = 0 ;w < 2 ;++ w ) { 135const k::KvHostPools hp = as_host (host_dev [w ],fmt ),sp = as_host (stage [w ],fmt ),lp = as_host (slots [w ],fmt ); 136// the prompt path: this layer's cells [0, p0) from the host copy into the staging pool first 137 k::kv_stage_from_host (as_attn (stage [w ],fmt ),hp ,fmt , (p0 + ps - 1 ) /ps ,s ,cs ); 138const k::KvHostPools * host_w = w == 0 ?& hp :nullptr ; 139if (fmt == k::kKvQ4 ) 140 k::kv_append_q4 (lp .k_q4 ,lp .v_q4 ,d_table ,p0 ,T ,dK ,dV ,s ,cs ,host_w ,& sp ); 141else 142 strata::prefill::kv_append (dK ,dV ,T ,p0 ,d_table ,ps ,fmt == k::kKvF16 ?lp .k_pool :nullptr , 143fmt == k::kKvF16 ?lp .v_pool :nullptr ,lp .k_q ,lp .v_q ,lp .k_scale ,lp .v_scale , 144cs ,host_w ,& sp ); 145if (w == 1 ) k::kv_unstage_to_host (as_attn (stage [w ],fmt ),hp ,fmt ,p0 /ps , (end + ps - 1 ) /ps ,s ,cs ); 146// a reader on another stream, ordered only by an event recorded right after the append's calls 147ck (cudaEventRecord (ev ,cs ),"event record" ); 148ck (cudaStreamWaitEvent (rd ,ev ,0 ),"reader wait" ); 149for (int i = 0 ;i < na ;++ i ) { 150const size_t bytes = (size_t ) ((end + ps - 1 ) /ps )* nkv * ps * arrs [(size_t )i ].row ; 151ck (cudaMemcpyAsync (back [w ].a [(size_t )i ],host_dev [w ].a [(size_t )i ],bytes ,cudaMemcpyDefault ,rd ),"read back" ); 152 } 153if (!ck (cudaStreamSynchronize (rd ),"reader sync" ))return 2 ; 154 } 155if (!ck (cudaDeviceSynchronize (),"sync" )|| !ck (cudaGetLastError (),"kernels" ))return 2 ; 156// compare every written cell: host copies (host side), read-backs, and the whole slot pools 157 std::vector < uint8_t > b0 ,b1 ; 158for (int i = 0 ;i < na ;++ i ) { 159const size_t rb = arrs [(size_t )i ].row ,bytes = (size_t )rows * rb ; 160b0 .resize (bytes );b1 .resize (bytes ); 161ck (cudaMemcpy (b0 .data (),back [0 ].a [(size_t )i ],bytes ,cudaMemcpyDeviceToHost ),"back0" ); 162ck (cudaMemcpy (b1 .data (),back [1 ].a [(size_t )i ],bytes ,cudaMemcpyDeviceToHost ),"back1" ); 163int64_t d_host = 0 ,d_back = 0 ,d_zero = 0 ; 164for (int64_t pos = 0 ;pos < end ;++ pos ) 165for (int64_t h = 0 ;h < nkv ;++ h ) { 166const size_t r = (size_t ) (((pos /ps )* nkv + h )* ps + pos %ps )* rb ; 167if (std::memcmp (host [0 ].a [(size_t )i ]+ r ,host [1 ].a [(size_t )i ]+ r ,rb )!= 0 )++ d_host ; 168if (std::memcmp (b0 .data ()+ r ,b1 .data ()+ r ,rb )!= 0 )++ d_back ; 169if (std::memcmp (b0 .data ()+ r ,host [0 ].a [(size_t )i ]+ r ,rb )!= 0 )++ d_back ; 170bool zero = true;// a written row of a nonzero input is never all zero: catches a missing copy 171for (size_t j = 0 ;j < rb ;++ j )zero = zero && host [1 ].a [(size_t )i ][r + j ]== 0 ; 172if (zero )++ d_zero ; 173 } 174ck (cudaMemcpy (b0 .data (),slots [0 ].a [(size_t )i ],bytes ,cudaMemcpyDeviceToHost ),"slots0" ); 175ck (cudaMemcpy (b1 .data (),slots [1 ].a [(size_t )i ],bytes ,cudaMemcpyDeviceToHost ),"slots1" ); 176const bool slots_eq = std::memcmp (b0 .data (),b1 .data (),bytes )== 0 ; 177const bool ok = d_host == 0 && d_back == 0 && d_zero == 0 && slots_eq ; 178 std::printf ("%s chunk p0 %lld T %lld array %d: host rows differing %lld, read-back rows differing %lld, " 179"all-zero rows %lld, slot pools %s: %s\n" ,fmt_name (fmt ), (long long )p0 , (long long )T ,i , 180 (long long )d_host , (long long )d_back , (long long )d_zero ,slots_eq ?"equal" :"DIFFER" , 181ok ?"ok" :"FAIL" ); 182if (!ok )++ bad ; 183 } 184 } 185cudaFree (dK );cudaFree (dV );cudaFree (d_table ); 186for (int w = 0 ;w < 2 ;++ w ) 187for (int i = 0 ;i < na ;++ i ) { 188cudaFreeHost (host [w ].a [(size_t )i ]);cudaFree (stage [w ].a [(size_t )i ]);cudaFree (slots [w ].a [(size_t )i ]); 189cudaFree (back [w ].a [(size_t )i ]); 190 } 191cudaEventDestroy (ev );cudaStreamDestroy (cs );cudaStreamDestroy (rd ); 192return bad == 0 ?0 :1 ; 193} 194}// namespace 195 196int main (int argc ,char ** argv ) { 197int dev = 0 ; 198for (int i = 1 ;i + 1 < argc ;++ i ) 199if (std::string (argv [i ])== "--device" )dev = std::atoi (argv [i + 1 ]); 200int n = 0 ; 201if (cudaGetDeviceCount (& n )!= cudaSuccess || n <=dev ) { 202 std::printf ("kv_host_dma_parity: no GPU: skipped\n" ); 203return 77 ; 204 } 205if (!ck (cudaSetDevice (dev ),"device" ))return 2 ; 206cudaDeviceProp p {}; 207cudaGetDeviceProperties (& p ,dev ); 208 std::printf ("kv_host_dma_parity: device %d %s (sm_%d%d)\n" ,dev ,p .name ,p .major ,p .minor ); 209int rc = 0 ; 210for (int fmt : {(int ) k::kKvF16 , (int ) k::kKvInt8 , (int ) k::kKvQ4 }) { 211const int r = run_format (fmt ); 212if (r != 0 )rc = r > rc ?r :rc ; 213 } 214 std::printf ("kv_host_dma_parity: %s\n" ,rc == 0 ?"ok (both ways byte-equal)" :"FAILED" ); 215return rc ; 216}