okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bb930bc8b
main
1// Standalone HIP INT8 QSA query-LDS-swizzle component probe. 2// Adapted from the cell-probability probe; input generation and full-byte dump are unchanged. 3// Build/link in the project with strata_kernels + hip::host (or its HIP runtime target). 4// Usage: gfx906_qsa_query_swizzle_probe [nq=32] [ctx=65536] [reps=20] [output.bin] [--masked-pages] 5// Output path may instead be supplied by STRATA_QSA_PROBE_OUT. It is required. 6// Run candidate environment settings in SEPARATE processes: the dispatcher caches them. 7// No prompt-attention entry point, architecture skip, model loading, or repository writes. 8#include "strata/kernels/qsa.hpp" 9#include "strata/kernels/qsa_decode_attn.hpp" 10 11#include <hip/hip_runtime.h> 12 13#include <algorithm> 14#include <cerrno> 15#include <cmath> 16#include <cstdint> 17#include <cstdio> 18#include <cstdlib> 19#include <cstring> 20#include <exception> 21#include <limits> 22#include <numeric> 23#include <vector> 24 25namespace k= strata::kernels; 26namespace { 27constexpr int64_t kBatch = 32 ; 28constexpr size_t kGuard = 64 ; 29constexpr uint64_t kSeed = 0x7161736150524f42ull ; 30 31[[noreturn ]]void fail (const char * why ) { 32 std::fprintf (stderr ,"qsa_query_swizzle_probe: %s\n" ,why ); 33 std::exit (2 ); 34} 35void ck (hipError_t e ,const char * what ) { 36if (e != hipSuccess ) { 37 std::fprintf (stderr ,"%s: %s\n" ,what ,hipGetErrorString (e )); 38 std::exit (2 ); 39 } 40} 41#define HIP_CHECK (x ) ck((x), #x) 42 43// Fixed integer generator and exact binary fractions avoid library-dependent 44// normal distributions and never inspect the candidate environment setting. 45struct Rng { 46uint64_t state = kSeed ; 47uint32_t next () { 48state ^=state >>12 ; 49state ^=state <<25 ; 50state ^=state >>27 ; 51return uint32_t ((state * 2685821657736338717ull ) >>32 ); 52 } 53size_t below (size_t n ) {return size_t (next ()) %n ; } 54template < class T > void shuffle (std::vector < T >& v ) { 55for (size_t n = v .size ();n > 1 ;-- n ) std::swap (v [n - 1 ],v [below (n )]); 56 } 57}; 58 59template < class T > struct Device { 60T * p = nullptr ; 61explicit Device (size_t n ) {HIP_CHECK (hipMalloc (reinterpret_cast < void **> (& p ),n * sizeof (T ))); } 62explicit Device (const std::vector < T >& v ) :Device (v .size ()) { 63HIP_CHECK (hipMemcpy (p ,v .data (),v .size ()* sizeof (T ),hipMemcpyHostToDevice )); 64 } 65 ~Device () {if (p ) (void )hipFree (p ); } 66Device (const Device & )= delete ; 67Device & operator= (const Device & )= delete ; 68}; 69 70uint64_t hash_bytes (uint64_t hash ,const void * ptr ,size_t bytes ) { 71const auto * p = static_cast < const unsigned char *> (ptr ); 72for (size_t i = 0 ;i < bytes ;++ i )hash = (hash ^p [i ])* 1099511628211ull ; 73return hash ; 74} 75template < class T > void hash_vector (uint64_t & hash ,const std::vector < T >& v ) { 76hash = hash_bytes (hash ,v .data (),v .size ()* sizeof (T )); 77} 78int64_t positive (const char * text ) { 79errno = 0 ; 80char * end = nullptr ; 81const long long n = std::strtoll (text ,& end ,10 ); 82if (errno || end == text || * end || n <=0 || n > INT32_MAX ) 83fail ("nq, ctx, and reps must be positive int32 values" ); 84return int64_t (n ); 85} 86const char * env (const char * name ) { 87const char * value = std::getenv (name ); 88return value ?value :"<unset>" ; 89} 90 91std::vector < float > read_checked (const Device < float >& storage ,size_t count ) { 92 std::vector < float > host (count + 2 * kGuard ); 93HIP_CHECK (hipMemcpy (host .data (),storage .p ,host .size ()* sizeof (float ),hipMemcpyDeviceToHost )); 94for (size_t i = 0 ;i < host .size ();++ i ) { 95if (i >=kGuard && i < kGuard + count ) { 96if (!std::isfinite (host [i ])) { 97 std::fprintf (stderr ,"nonfinite or unwritten output at float %zu\n" ,i - kGuard ); 98fail ("output check failed" ); 99 } 100 }else { 101uint32_t bits ; 102 std::memcpy (& bits ,& host [i ],sizeof (bits )); 103if (bits != UINT32_MAX )fail ("output guard changed" ); 104 } 105 } 106return std::vector < float > (host .begin ()+ kGuard ,host .begin ()+ kGuard + count ); 107} 108 109int run (int64_t nq ,int64_t ctx ,int reps ,const char * output ,bool masked ) { 110if (ctx < nq )fail ("ctx must be >= nq (query positions are ctx-nq through ctx-1)" ); 111const char * lane = std::getenv ("STRATA_ATTN_LANECELL" ); 112if (lane && lane [0 ]== '1' )fail ("unset STRATA_ATTN_LANECELL or set it to 0 for this probe" ); 113 static_assert(sizeof (float )== 4 && std::numeric_limits < float > ::is_iec559 , 114"probe requires IEEE binary32 output" ); 115const k::QsaShapes s = k::qsa_real_shapes (); 116// Match prefill.cpp: use the model's actual 4-cell page layout. 117if (s .n_head != 24 || s .n_head_kv != 2 || s .head_dim != 256 || s .page_size != 4 ) 118fail ("unexpected model geometry" ); 119const int64_t hd = s .head_dim ,nh = s .n_head ,nkvh = s .n_head_kv ,ps = s .page_size ; 120const int64_t pages = (ctx + ps - 1 ) /ps ,rows = pages * nkvh * ps ; 121const int64_t cap = k::qsa_selection_width (ctx ,s ); 122const size_t count = size_t (nq )* size_t (nh * hd ); 123Rng rng ; 124 std::vector < int8_t > kq (size_t (rows * hd )),vq (kq .size ()); 125 std::vector < uint16_t > ks (size_t (rows * (hd /64 ))),vs (ks .size ()); 126for (auto * v : {& kq ,& vq }) 127for (auto & x :* v )x = int8_t (int (rng .next () %255 )- 127 ); 128// Positive finite binary16 scales, directly encoded: [2^-8, 2^-5). 129for (auto * v : {& ks ,& vs }) 130for (auto & x :* v )x = uint16_t (0x1c00u + rng .next () %0x0c00u ); 131 std::vector < int32_t > table (size_t (pages ),0 ); 132 std::iota (table .begin (),table .end (),0 ); 133rng .shuffle (table ); 134const auto physical = table ; 135if (masked ) 136for (int64_t page = 1 ;page < pages ;page += 3 )table [size_t (page )]= -1 ; 137 138// The decode kernel reads ids[c0+t] only for t<n_here, and returns before 139// reading IDs for empty chunks. Unused row slots are nevertheless zeroed; 140// a final 64-cell initialized guard also avoids an exact allocation end. 141// cap remains the actual row stride; no per-row padding is passed as cap. 142 std::vector < int32_t > ids (size_t (nq * cap )+ kGuard ,0 ); 143 std::vector < int32_t > steps (size_t (nq * k::kStepCount ),0 ); 144 std::vector < float > query (count ); 145for (auto & x :query )x = float (int (rng .next () %4096 )- 2048 )* (1.0f /1024.0f ); 146 std::vector < int32_t > old_cells ; 147for (int64_t i = 0 ;i < nq ;++ i ) { 148const int64_t pos = ctx - nq + i ,nkv = pos + 1 ; 149const int64_t width = k::qsa_selection_width (nkv ,s ); 150 k::qsa_step_fill (steps .data ()+ i * k::kStepCount ,pos ,s ); 151int32_t * sel = ids .data ()+ i * cap ; 152if (width == nkv ) { 153 std::iota (sel ,sel + width ,0 ); 154 }else { 155// Same selection pattern as qsa_prompt_attn_parity: a recent 156// 512-cell window plus a sorted older set drifting ~3% per query. 157constexpr int64_t recent = 512 ; 158const int64_t older = width - recent ; 159if (int64_t (old_cells .size ())!= older ) { 160 std::vector < int32_t > all (size_t (nkv - recent ),0 ); 161 std::iota (all .begin (),all .end (),0 ); 162rng .shuffle (all ); 163old_cells .assign (all .begin (),all .begin ()+ older ); 164 }else { 165for (int64_t r = 0 ;r < older /32 ;++ r ) { 166const int32_t cell = int32_t (rng .below (size_t (nkv - recent ))); 167if (std::find (old_cells .begin (),old_cells .end (),cell )== old_cells .end ()) 168old_cells [rng .below (size_t (older ))]= cell ; 169 } 170 } 171 std::copy (old_cells .begin (),old_cells .end (),sel ); 172 std::iota (sel + older ,sel + width ,int32_t (nkv - recent )); 173 std::sort (sel ,sel + width ); 174 } 175bool valid_page = false; 176for (int64_t c = 0 ;c < width ;++ c ) { 177if (sel [c ]< 0 || sel [c ] >=nkv || (c && sel [c - 1 ] >=sel [c ])) 178fail ("selection must be unique, sorted, and causal" ); 179valid_page |=table [size_t (sel [c ] /ps )] >=0 ; 180 } 181// Restore a selected logical page if necessary, never allow an 182// all-masked query to make a vacuous zero-output equality check pass. 183if (!valid_page ) { 184const size_t page = size_t (sel [0 ] /ps ); 185table [page ]= physical [page ]; 186 } 187 } 188size_t masked_selected = 0 ; 189for (int64_t i = 0 ;i < nq ;++ i ) 190for (int32_t c = 0 ;c < steps [size_t (i * k::kStepCount + k::kStepWidth )];++ c ) 191masked_selected += table [size_t (ids [size_t (i * cap + c )] /ps )]< 0 ; 192uint64_t input_hash = 14695981039346656037ull ; 193hash_vector (input_hash ,kq );hash_vector (input_hash ,vq ); 194hash_vector (input_hash ,ks );hash_vector (input_hash ,vs ); 195hash_vector (input_hash ,table );hash_vector (input_hash ,ids ); 196hash_vector (input_hash ,steps );hash_vector (input_hash ,query ); 197 198Device < int8_t > dk (kq ),dv (vq ); 199Device < uint16_t > dks (ks ),dvs (vs ); 200Device < int32_t > dtable (table ),dids (ids ),dsteps (steps ); 201Device < float > dq (query ),dout (count + 2 * kGuard ); 202const uint64_t stride = k::qsa_decode_attn_scratch_floats (cap ,s ); 203Device < float > scratch (size_t (std::min (kBatch ,nq ))* size_t (stride )); 204 k::QsaAttnPools pools ; 205pools .k_q = dk .p ;pools .v_q = dv .p ;pools .k_scale = dks .p ;pools .v_scale = dvs .p ; 206pools .page_table = dtable .p ; 207HIP_CHECK (hipMemset (dout .p ,0xff , (count + 2 * kGuard )* sizeof (float ))); 208HIP_CHECK (hipMemset (scratch .p ,0xff ,size_t (std::min (kBatch ,nq ))* size_t (stride )* sizeof (float ))); 209auto launch = [& ] { 210for (int64_t t = 0 ;t < nq ;t += kBatch ) 211 k::qsa_decode_attn_batch (dq .p + t * nh * hd ,pools ,dids .p + t * cap , 212dsteps .p + t * k::kStepCount ,cap ,s ,scratch .p ,dout .p + kGuard + t * nh * hd , 213 std::min (kBatch ,nq - t ),nullptr ); 214HIP_CHECK (hipGetLastError ()); 215 }; 216launch (); 217HIP_CHECK (hipDeviceSynchronize ()); 218const auto first = read_checked (dout ,count ); 219constexpr int warmups = 3 ; 220for (int i = 0 ;i < warmups ;++ i )launch (); 221HIP_CHECK (hipDeviceSynchronize ()); 222hipEvent_t begin = nullptr ,end = nullptr ; 223HIP_CHECK (hipEventCreate (& begin ));HIP_CHECK (hipEventCreate (& end )); 224 std::vector < float > times (size_t (reps ),0.0f ); 225for (int i = 0 ;i < reps ;++ i ) { 226// Excluded from event duration; the last timed invocation must also 227// overwrite every logical output element instead of inheriting it. 228HIP_CHECK (hipMemsetAsync (dout .p + kGuard ,0xff ,count * sizeof (float ),nullptr )); 229HIP_CHECK (hipEventRecord (begin ,nullptr )); 230launch (); 231HIP_CHECK (hipEventRecord (end ,nullptr )); 232HIP_CHECK (hipEventSynchronize (end )); 233HIP_CHECK (hipEventElapsedTime (& times [size_t (i )],begin ,end )); 234 } 235const auto result = read_checked (dout ,count ); 236if (std::memcmp (first .data (),result .data (),count * sizeof (float ))!= 0 ) 237fail ("first and final invocation differ byte-for-byte within this process" ); 238const uint64_t output_hash = hash_bytes (14695981039346656037ull ,result .data (),count * sizeof (float )); 239 std::FILE * file = std::fopen (output ,"wb" ); 240if (!file )fail ("cannot open output file" ); 241const size_t written = std::fwrite (result .data (),sizeof (float ),count ,file ); 242const int close_status = std::fclose (file ); 243if (written != count || close_status != 0 )fail ("cannot write complete output file" ); 244 std::sort (times .begin (),times .end ()); 245const float median = reps %2 ?times [size_t (reps /2 )] 246 :0.5f * (times [size_t (reps /2 - 1 )]+ times [size_t (reps /2 )]); 247int device = 0 ; 248hipDeviceProp_t prop {}; 249HIP_CHECK (hipGetDevice (& device ));HIP_CHECK (hipGetDeviceProperties (& prop ,device )); 250 std::printf ("device=%s arch=%s nq=%lld ctx=%lld cap=%lld page_size=%lld batch=%lld reps=%d warmups=%d\n" , 251prop .name ,prop .gcnArchName , (long long )nq , (long long )ctx , (long long )cap , 252 (long long )ps , (long long )kBatch ,reps ,warmups ); 253 std::printf ("QUERY_SWIZZLE=%s LANECELL=%s seed=%016llx masked_pages=%zu masked_selected=%zu\n" , 254env ("STRATA_GFX906_ATTN_QUERY_SWIZZLE" ),env ("STRATA_ATTN_LANECELL" ), (unsigned long long )kSeed , 255size_t (std::count (table .begin (),table .end (),-1 )),masked_selected ); 256 std::printf ("INPUT_FNV1A64=%016llx OUTPUT_FNV1A64=%016llx output_floats=%zu output_bytes=%zu\n" , 257 (unsigned long long )input_hash , (unsigned long long )output_hash ,count ,count * sizeof (float )); 258 std::printf ("PASS finite_written_guards_and_repeat median_ms=%.6f min_ms=%.6f max_ms=%.6f us_per_query=%.6f output=%s\n" , 259median ,times .front (),times .back (),double (median )* 1000.0 /double (nq ),output ); 260HIP_CHECK (hipEventDestroy (begin ));HIP_CHECK (hipEventDestroy (end )); 261return 0 ; 262} 263}// namespace 264 265int main (int argc ,char ** argv ) { 266try { 267 std::vector < const char *> args ; 268bool masked = false; 269for (int i = 1 ;i < argc ;++ i ) { 270if (std::strcmp (argv [i ],"--masked-pages" )== 0 )masked = true; 271else args .push_back (argv [i ]); 272 } 273if (args .size ()> 4 )fail ("usage: probe [nq] [ctx] [reps] [output.bin] [--masked-pages]" ); 274const int64_t nq = args .size ()> 0 ?positive (args [0 ]) :32 ; 275const int64_t ctx = args .size ()> 1 ?positive (args [1 ]) :65536 ; 276const int reps = args .size ()> 2 ?int (positive (args [2 ])) :20 ; 277const char * output = args .size ()> 3 ?args [3 ] : std::getenv ("STRATA_QSA_PROBE_OUT" ); 278if (!output || !* output )fail ("pass output.bin as fourth positional argument or set STRATA_QSA_PROBE_OUT" ); 279return run (nq ,ctx ,reps ,output ,masked ); 280 }catch (const std::exception & e ) { 281 std::fprintf (stderr ,"qsa_query_swizzle_probe: %s\n" ,e .what ()); 282return 2 ; 283 } 284}