Files
leleka/scripts/cuda-qsa-oracle/main.cu
T

174 lines
14 KiB
Plaintext

// Independent test caller: candidate PTX is never an expected-value oracle.
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <string>
#include <vector>
extern "C" void oracle_norm(const float*,const float*,float*,int,int,cudaStream_t);
extern "C" void oracle_gate(const float*,const float*,float*,cudaStream_t);
extern "C" void oracle_rope(const float*,float*,int,int,const int*,cudaStream_t);
extern "C" void oracle_index(const float*,const float*,const int*,float*,float*,float*,int*,cudaStream_t);
extern "C" void oracle_scores(const float*,const float*,const float*,const int*,int64_t,float*,cudaStream_t);
extern "C" void oracle_topk(const float*,const int*,int64_t,int*,cudaStream_t);
extern "C" void oracle_pack(const float*,const float*,uint16_t*,uint16_t*,const int*,cudaStream_t);
extern "C" void oracle_attention(const float*,const uint16_t*,const uint16_t*,const int*,float*,cudaStream_t);
static std::string output;
static std::string retained;
static uint64_t words=0;
static unsigned cases=0;
static void rt(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));}
static void drv(CUresult e){if(e!=CUDA_SUCCESS){const char*s=nullptr;cuGetErrorString(e,&s);throw std::runtime_error(s?s:"driver failure");}}
template<class T> struct Buffer {
T*p=nullptr;size_t n;
explicit Buffer(size_t count):n(count){rt(cudaMalloc(&p,n*sizeof(T)));rt(cudaMemset(p,0,n*sizeof(T)));}
explicit Buffer(const std::vector<T>&v):Buffer(v.size()){set(v);}
~Buffer(){if(p)cudaFree(p);}
void set(const std::vector<T>&v){if(v.size()!=n)throw std::runtime_error("fixture extent");rt(cudaMemcpy(p,v.data(),n*sizeof(T),cudaMemcpyHostToDevice));}
std::vector<T> get(){std::vector<T>v(n);rt(cudaMemcpy(v.data(),p,n*sizeof(T),cudaMemcpyDeviceToHost));return v;}
Buffer(const Buffer&)=delete;
};
static void raw(const std::string&name,const void*p,size_t n){std::ofstream f(output+"/"+name,std::ios::binary);f.write(static_cast<const char*>(p),n);if(!f)throw std::runtime_error("proof write");}
template<class T> static void exact(const std::string&name,const std::vector<T>&want,const std::vector<T>&got){
raw(name+".want",want.data(),want.size()*sizeof(T));raw(name+".got",got.data(),got.size()*sizeof(T));
if(want.size()!=got.size())throw std::runtime_error(name+": extent");
for(size_t i=0;i<want.size();++i)if(std::memcmp(&want[i],&got[i],sizeof(T))){
std::fprintf(stderr,"FAIL %s index=%zu\n",name.c_str(),i);throw std::runtime_error("exact bits differ");}
words+=want.size();++cases;std::printf("PASS %s exact_words=%zu\n",name.c_str(),want.size());
}
static std::vector<float> values(size_t n,int salt){std::vector<float>v(n);for(size_t i=0;i<n;++i)v[i]=float(int((i*37+salt*13)%127)-63)/64.0f;return v;}
static std::vector<float> norm_weights(size_t n){std::vector<float>v(n);for(size_t i=0;i<n;++i)v[i]=float(int(i%13)+8)/16.0f;return v;}
static std::vector<int> step(unsigned p){return {int(p),int(p+1),int((p+1)/4),int(std::min(p+1,2051u))};}
static cudaStream_t stream;
static CUmodule modules[4];
static void launch(int m,const char*name,unsigned gx,unsigned gy,unsigned bx,unsigned shared,std::vector<void*>args){
CUfunction f;drv(cuModuleGetFunction(&f,modules[m],name));
drv(cuLaunchKernel(f,gx,gy,1,bx,1,1,shared,reinterpret_cast<CUstream>(stream),args.data(),nullptr));
rt(cudaStreamSynchronize(stream));
}
static void norms(){for(int mode=0;mode<3;++mode){int c=mode==2?128:256,n=mode==0?24:mode==1?2:4;
Buffer<float>x(values(c*n,mode+1)),g(norm_weights(c)),w(c*n),y(c*n);
oracle_norm(x.p,g.p,w.p,c,n,stream);rt(cudaStreamSynchronize(stream));
const char*names[]={"leleka_qsa_norm_q","leleka_qsa_norm_k","leleka_qsa_norm_index_q"};
launch(0,names[mode],n,1,256,0,{&x.p,&g.p,&y.p});exact(std::string("norm_")+std::to_string(mode),w.get(),y.get());
}}
static void ropes(bool repair=false){for(int mode=0;mode<3;++mode){int c=mode==2?128:256,n=mode==0?24:mode==1?2:4;
const char*names[]={"leleka_qsa_rope_q","leleka_qsa_rope_k","leleka_qsa_rope_index_q"};
for(unsigned p:{0u,1u,4u,7u,262143u}){
if(repair&&mode==0&&p==0)continue; // Exact Q position0 proof is already retained.
auto input=values(c*n,mode+4);Buffer<float>x(input),w(c*n),y(c*n);Buffer<int>positions(std::vector<int>(n,int(p)));
oracle_rope(x.p,w.p,c,n,positions.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,names[mode],1,n,128,0,{&x.p,&p,&y.p});auto got=y.get();
exact("rope_"+std::to_string(mode)+"_"+std::to_string(p),w.get(),got);
for(int row=0;row<n;++row)for(int d=64;d<c;++d)if(std::memcmp(&input[row*c+d],&got[row*c+d],4))throw std::runtime_error("partial RoPE suffix changed");
}}}
static void split_pack(){
auto full=values(12288,8);Buffer<float>x(full),q(6144),g(6144);
launch(0,"leleka_qsa_split_q_gate",24,1,256,0,{&x.p,&q.p,&g.p});
std::vector<float>wq(6144),wg(6144);for(int h=0;h<24;++h)for(int d=0;d<256;++d){wq[h*256+d]=full[h*512+d];wg[h*256+d]=full[h*512+256+d];}
exact("split_q",wq,q.get());exact("split_gate",wg,g.get());
const uint32_t bits[]={0,0x80000000u,0x3f800000u,0x3f801000u,0x3f803000u,0xbf801000u,0x33800000u,0x33000000u,0x477fe000u,0xc77fe000u};
const uint16_t half[]={0,0x8000,0x3c00,0x3c00,0x3c02,0xbc00,1,0,0x7bff,0xfbff};
std::vector<float>kv(512);std::vector<uint16_t>want(512);for(int i=0;i<512;++i){std::memcpy(&kv[i],&bits[i%10],4);want[i]=half[i%10];}
Buffer<float>k(kv),v(kv);Buffer<uint16_t>kh(512),vh(512),wk(512),wv(512);Buffer<int>st(step(0));
oracle_pack(k.p,v.p,wk.p,wv.p,st.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,"leleka_qsa_pack_kv",2,1,256,0,{&k.p,&v.p,&kh.p,&vh.p});
exact("pack_original_k",wk.get(),kh.get());exact("pack_literal_k",want,kh.get());exact("pack_original_v",wv.get(),vh.get());
}
static void indexer(){
Buffer<float>g(norm_weights(128)),tail(384),dead(128),pool(384);Buffer<int>bpos(1);
std::vector<float>prior(512,0.0f);
for(unsigned p=0;p<8;++p){auto input=values(128,p+9);Buffer<float>x(input),old(prior),next(640);Buffer<int>position(std::vector<int>{int(p)});
oracle_index(x.p,g.p,position.p,tail.p,dead.p,pool.p,bpos.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,"leleka_qsa_index_append",1,1,256,0,{&x.p,&g.p,&old.p,&next.p,&p});
auto got=next.get(),wt=tail.get(),wd=dead.get(),wp=pool.get();std::vector<float>want=wt;want.insert(want.end(),wd.begin(),wd.end());
size_t row=p==0?0:p%4==3?p/4+0:(p+1)/4;
want.insert(want.end(),wp.begin()+row*128,wp.begin()+(row+1)*128);
exact("index_append_"+std::to_string(p),want,got);prior.assign(got.begin(),got.begin()+512);
}}
static std::vector<float> retained_words(const std::string&name){
std::vector<float>v(640);std::ifstream f(retained+"/"+name,std::ios::binary);
f.read(reinterpret_cast<char*>(v.data()),2560);if(!f||f.peek()!=std::ifstream::traits_type::eof())throw std::runtime_error("retained fixture extent");return v;
}
static void repaired_indexer(){
// Restore the independently proven prior at6; no operator0..6 is relaunched.
auto previous=retained_words("index_append_6.want"),first_block=retained_words("index_append_3.want");
std::vector<float>old(previous.begin(),previous.begin()+512),tail_words(old.begin(),old.begin()+384),dead_words(old.begin()+384,old.end()),pool_words(384,0);
std::copy(first_block.begin()+512,first_block.end(),pool_words.begin());std::copy(dead_words.begin(),dead_words.end(),pool_words.begin()+128);
Buffer<float>g(norm_weights(128)),tail(tail_words),dead(dead_words),pool(pool_words),x(values(128,16)),prior(old),next(640);
Buffer<int>bpos(1),position(std::vector<int>{7});unsigned p=7;
oracle_index(x.p,g.p,position.p,tail.p,dead.p,pool.p,bpos.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,"leleka_qsa_index_append",1,1,256,0,{&x.p,&g.p,&prior.p,&next.p,&p});
auto want=tail.get(),wd=dead.get(),wp=pool.get();want.insert(want.end(),wd.begin(),wd.end());want.insert(want.end(),wp.begin()+128,wp.begin()+256);
exact("index_append_7_repaired",want,next.get());
}
static std::vector<int> cpu_ids(const std::vector<float>&scores,unsigned n){
std::vector<int>ids(n);std::iota(ids.begin(),ids.end(),0);
std::stable_sort(ids.begin(),ids.end(),[&](int a,int b){float x=scores[a/4],y=scores[b/4];return x==y?a<b:x>y;});
ids.resize(std::min(n,2051u));std::sort(ids.begin(),ids.end());return ids;
}
static void selection(){for(unsigned n:{1u,4u,7u,2051u,2052u,2053u,4096u,262144u}){unsigned p=n-1;size_t blocks=n/4+1;
Buffer<float>k(values(blocks*128,3)),dead(values(128,7)),q(values(512,19)),w(blocks),y(blocks);Buffer<int>st(step(p)),wid(2051),id(2051);
oracle_scores(k.p,dead.p,q.p,st.p,blocks,w.p,stream);rt(cudaStreamSynchronize(stream));
launch(1,"leleka_qsa_block_scores",256,1,256,0,{&k.p,&dead.p,&q.p,&y.p,&p});auto scores=y.get();
exact("scores_"+std::to_string(n),w.get(),scores);
oracle_topk(w.p,st.p,blocks,wid.p,stream);rt(cudaStreamSynchronize(stream));
launch(1,"leleka_qsa_block_topk",1,1,256,0,{&y.p,&id.p,&p});auto got=id.get(),want=wid.get();got.resize(std::min(n,2051u));want.resize(got.size());
exact("topk_source_"+std::to_string(n),want,got);exact("topk_independent_"+std::to_string(n),cpu_ids(scores,n),got);
// Literal all-equal block scores force lowest-ID ties even at the truncation boundary.
std::vector<float>ties(blocks,0.0f);y.set(ties);launch(1,"leleka_qsa_block_topk",1,1,256,0,{&y.p,&id.p,&p});got=id.get();got.resize(std::min(n,2051u));
std::vector<int>literal(got.size());std::iota(literal.begin(),literal.end(),0);exact("topk_literal_tie_"+std::to_string(n),literal,got);
}}
static double half_double(uint16_t x){return double(__half2float(__ushort_as_half(x)));}
static void attention(){for(unsigned width:{1u,7u,257u,2051u}){
auto query=values(6144,11);std::vector<uint16_t>k(size_t(width)*512),v(k.size());
const uint16_t kb[]={0x0000,0x3400,0xb800,0x3a00,0xbc00,0x3800};
const uint16_t vb[]={0x3c00,0xbc00,0x4000,0xb800,0x3400,0x4200};
for(size_t i=0;i<k.size();++i){k[i]=kb[(i*7+i/256)%6];v[i]=vb[(i*11+i/512)%6];}
if(width==1){for(int d=0;d<256;++d){v[d]=0x4200;v[256+d]=0xc700;}}
Buffer<float>q(query),w(6144),y(6144);Buffer<uint16_t>dk(k),dv(v);Buffer<int>st(step(width-1));
oracle_attention(q.p,dk.p,dv.p,st.p,w.p,stream);rt(cudaStreamSynchronize(stream));
launch(2,"leleka_qsa_attend",24,1,256,(2051+32)*4,{&q.p,&dk.p,&dv.p,&y.p,&width});auto got=y.get();exact("attention_source_"+std::to_string(width),w.get(),got);
std::vector<double>reference(6144),scores(width);
for(int h=0;h<24;++h){int kv=h/12;
for(unsigned j=0;j<width;++j){double dot=0;for(int d=0;d<256;++d)dot+=half_double(k[(size_t(j)*2+kv)*256+d])*double(query[h*256+d]);scores[j]=dot/16.0;}
double maximum=*std::max_element(scores.begin(),scores.end()),den=0;for(double&s:scores){s=std::exp(s-maximum);den+=s;}for(double&s:scores)s/=den;
for(int d=0;d<256;++d){double a=0;for(unsigned j=0;j<width;++j)a+=scores[j]*half_double(v[(size_t(j)*2+kv)*256+d]);reference[h*256+d]=a;}
}
raw("attention_double_"+std::to_string(width)+".want",reference.data(),reference.size()*8);
double diff=0,mag=0;for(size_t i=0;i<got.size();++i){if(!std::isfinite(got[i]))throw std::runtime_error("nonfinite attention");diff+=std::abs(reference[i]-double(got[i]));mag+=std::abs(reference[i]);}
double rel=diff/(mag==0?1:mag);std::printf("DOUBLE attention width=%u relL1=%.17g limit=1e-5\n",width,rel);if(rel>1e-5)throw std::runtime_error("attention double tolerance");++cases;
}}
static void gate(){
const float literals[]={-1000,-100,-1,-0.0f,0.0f,1,100,1000};auto a=values(6144,21);std::vector<float>gate(6144),full(12288,777);
for(int h=0;h<24;++h)for(int d=0;d<256;++d){float x=literals[(h+d)%8];gate[h*256+d]=x;full[h*512+256+d]=x;}
Buffer<float>x(a),g(gate),f(full),w(6144),y(6144);
oracle_gate(x.p,f.p,w.p,stream);rt(cudaStreamSynchronize(stream));launch(3,"leleka_qsa_gate_f32",24,1,256,0,{&x.p,&g.p,&y.p});exact("gate_native_f32_saturation",w.get(),y.get());
}
static void invalid(){
auto a=values(6144,2);a[0]=std::numeric_limits<float>::quiet_NaN();Buffer<float>x(a),g(norm_weights(256)),y(6144);
launch(0,"leleka_qsa_norm_q",24,1,256,0,{&x.p,&g.p,&y.p});auto out=y.get();for(int d=0;d<256;++d)if(!std::isnan(out[d]))throw std::runtime_error("norm NaN hidden");++cases;std::puts("PASS invalid_norm_row_nan");
auto gate=values(6144,3);gate[19]=std::numeric_limits<float>::infinity();Buffer<float>gg(gate);
launch(3,"leleka_qsa_gate_f32",24,1,256,0,{&x.p,&gg.p,&y.p});out=y.get();if(!std::isnan(out[0])||!std::isnan(out[19]))throw std::runtime_error("gate invalid hidden");++cases;std::puts("PASS invalid_gate_nan_inf");
}
int main(int argc,char**argv){try{
if(argc<3||argc>5)throw std::runtime_error("Usage: qsa_oracle ASSET_DIRECTORY PRIVATE_OUTPUT_DIRECTORY [group [RETAINED_PROOF_DIRECTORY]]");output=argv[2];std::string group=argc>=4?argv[3]:"all";
if(group=="repair"){if(argc!=5)throw std::runtime_error("repair requires retained prior-proof directory");retained=argv[4];}
rt(cudaSetDevice(0));rt(cudaFree(nullptr));drv(cuInit(0));rt(cudaStreamCreate(&stream));
const char*asset[]={"qwen_qsa_native.ptx","qwen_qsa_select.ptx","qwen_qsa_attention.ptx","qwen_qsa_attention_native.ptx"};
for(int i=0;i<4;++i)drv(cuModuleLoad(&modules[i],(std::string(argv[1])+"/"+asset[i]).c_str()));
cudaDeviceProp prop;rt(cudaGetDeviceProperties(&prop,0));int driver=0;rt(cudaDriverGetVersion(&driver));std::printf("DEVICE %s cc=%d.%d driver=%d\n",prop.name,prop.major,prop.minor,driver);
auto enabled=[&](const char*s){return group=="all"||group==s;};
if(enabled("norm"))norms();if(enabled("rope"))ropes();if(enabled("pack"))split_pack();if(enabled("index"))indexer();if(enabled("select"))selection();if(enabled("attention"))attention();if(enabled("gate"))gate();if(enabled("invalid"))invalid();
if(group=="repair"){ropes(true);repaired_indexer();}
for(auto m:modules)drv(cuModuleUnload(m));rt(cudaStreamDestroy(stream));std::printf("RESULT PASS cases=%u exact_words=%llu\n",cases,(unsigned long long)words);return 0;
}catch(const std::exception&e){std::fprintf(stderr,"RESULT FAIL %s\n",e.what());return 1;}}