diff --git a/arch/common/rad_block_dspark_bf16.h b/arch/common/rad_block_dspark_bf16.h index 7f9d3896..2826dfeb 100644 --- a/arch/common/rad_block_dspark_bf16.h +++ b/arch/common/rad_block_dspark_bf16.h @@ -72,8 +72,9 @@ * prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1 * * `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the - * largest biased score, exactly the pinned reference's serial Markov walk. It does not prune to the - * base head's top K, use a joint-path heap, or apply the confidence head to logits. + * largest biased score, following the structure of the pinned reference's serial Markov walk. + * BF16 base logits, reduction order and tie behavior can differ from that reference. It does not + * prune to the base head's top K, use a joint-path heap, or apply confidence to logits. * * The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and * ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at diff --git a/docs/OPS.md b/docs/OPS.md index 18abd859..830f0a8f 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -3366,10 +3366,15 @@ candidates, and what enters the head from the trunk. |---|---|---| | `dflash_markov_greedy` | `M` `steps` `rank` `n_vocab` `anchor_stride`/opt `dtype` | `logits`, `anchor`, `pred`w, `succ`w → `tile_scores`, `tile_tokens`, `tokens` | -`dflash_markov_greedy` is the exact DSpark reference walk, not DFlash2's candidate-lattice selector. -For every position it adds `sum_r pred[previous,r] * succ[token,r]` to every vocabulary logit, -chooses the greatest biased score (ties to the lower token id), and uses that id as the next -predecessor. The explicit tile outputs are scratch for the device's vocabulary-wide reduction. +`dflash_markov_greedy` implements the DSpark full-vocabulary greedy walk, not DFlash2's +candidate-lattice selector. For every position it adds `sum_r pred[previous,r] * succ[token,r]` +to every vocabulary logit, chooses the greatest biased score (ties to the lower token id), and +uses that id as the next predecessor. The explicit tile outputs are scratch for the device's +vocabulary-wide reduction; their row pitches may differ. The current graph passes BF16 base logits, +whereas the pinned llama.cpp reference uses F32 logits, and the reduction orders also differ. +Its CPU argmax chooses the last equal maximum; its GPU reduction uses a backend-specific order. +This op's lower-id tie rule is not a claim of reference tie equivalence. Near-tie proposal +equivalence is therefore not established. ### DFlash2 diff --git a/libr4d/r4d_dflash_markov_bf16.hip b/libr4d/r4d_dflash_markov_bf16.hip index 4728972a..3605487a 100644 --- a/libr4d/r4d_dflash_markov_bf16.hip +++ b/libr4d/r4d_dflash_markov_bf16.hip @@ -1,6 +1,6 @@ // Full-vocabulary DSpark Markov greedy walk. Unlike dflash_select's candidate-lattice walk, this -// operation applies the learned bigram bias to every draft-head logit and greedily selects the -// largest biased score at each position, matching the pinned llama.cpp reference. +// operation applies the learned bigram bias to every BF16 draft-head logit and greedily selects +// the largest biased score. The pinned llama.cpp graph uses F32 base logits and may differ. #include #include #include "r4d_gdn_args.h" @@ -16,6 +16,13 @@ constexpr int kCandidatesPerTile = 64; constexpr int kCandidatesPerWarp = kCandidatesPerTile / kWarps; constexpr int kMaxRank = 512; +// The device computes element offsets in signed long; reject a row span that would overflow. +bool rows_fit(long long rows, long long pitch, long long width, int element_bytes) { + const long long limit = LLONG_MAX / element_bytes; + return rows > 0 && width > 0 && width <= limit && pitch >= width && + (rows == 1 || pitch <= (limit - (width - 1)) / (rows - 1)); +} + // One CTA scans 64 vocabulary rows, eight at a time (one warp per row). The rank reduction is // parallel across the warp and codebook loads remain contiguous. Each CTA writes its exact local // argmax; a second kernel reduces those tile winners before the next dependent position starts. @@ -23,7 +30,8 @@ __global__ __launch_bounds__(kThreads) void markov_score_tiles( const r4d_u16* __restrict__ logits, long logits_pitch, const int* __restrict__ anchor, long anchor_stride, const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, - float* __restrict__ tile_scores, int* __restrict__ tile_tokens, + float* __restrict__ tile_scores, long scores_pitch, + int* __restrict__ tile_tokens, long tokens_pitch, const int* __restrict__ out, long out_pitch, int step, int steps, int rank, int vocab, int n_tiles) { const int seq = blockIdx.y; @@ -80,13 +88,14 @@ __global__ __launch_bounds__(kThreads) void markov_score_tiles( best_token = token; } } - tile_scores[(long)seq * n_tiles + tile] = best; - tile_tokens[(long)seq * n_tiles + tile] = best_token; + tile_scores[(long)seq * scores_pitch + tile] = best; + tile_tokens[(long)seq * tokens_pitch + tile] = best_token; } } __global__ __launch_bounds__(kThreads) void markov_reduce_tiles( - const float* __restrict__ tile_scores, const int* __restrict__ tile_tokens, + const float* __restrict__ tile_scores, long scores_pitch, + const int* __restrict__ tile_tokens, long tokens_pitch, int* __restrict__ out, long out_pitch, int step, int n_tiles) { const int seq = blockIdx.x; const int tid = threadIdx.x; @@ -96,8 +105,8 @@ __global__ __launch_bounds__(kThreads) void markov_reduce_tiles( float best = -INFINITY; int best_token = INT_MAX; for (int tile = tid; tile < n_tiles; tile += kThreads) { - const float score = tile_scores[(long)seq * n_tiles + tile]; - const int token = tile_tokens[(long)seq * n_tiles + tile]; + const float score = tile_scores[(long)seq * scores_pitch + tile]; + const int token = tile_tokens[(long)seq * tokens_pitch + tile]; if (score > best || (score == best && token < best_token)) { best = score; best_token = token; @@ -121,17 +130,18 @@ __global__ __launch_bounds__(kThreads) void markov_reduce_tiles( } int markov_emit(const r4d_u16* logits, long logits_pitch, const int* anchor, long anchor_stride, - const r4d_u16* pred, const r4d_u16* succ, float* tile_scores, int* tile_tokens, - int* out, long out_pitch, int sequences, int steps, int rank, int vocab, + const r4d_u16* pred, const r4d_u16* succ, float* tile_scores, long scores_pitch, + int* tile_tokens, long tokens_pitch, int* out, long out_pitch, + int sequences, int steps, int rank, int vocab, int n_tiles, RadStream stream) { for (int step = 0; step < steps; ++step) { hipLaunchKernelGGL(markov_score_tiles, dim3(n_tiles, sequences), dim3(kThreads), 0, (hipStream_t)stream, logits, logits_pitch, anchor, anchor_stride, pred, - succ, tile_scores, tile_tokens, out, out_pitch, step, steps, rank, vocab, - n_tiles); + succ, tile_scores, scores_pitch, tile_tokens, tokens_pitch, out, out_pitch, + step, steps, rank, vocab, n_tiles); hipLaunchKernelGGL(markov_reduce_tiles, dim3(sequences), dim3(kThreads), 0, - (hipStream_t)stream, tile_scores, tile_tokens, out, out_pitch, step, - n_tiles); + (hipStream_t)stream, tile_scores, scores_pitch, tile_tokens, tokens_pitch, + out, out_pitch, step, n_tiles); } return (int)hipGetLastError(); } @@ -155,8 +165,8 @@ extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) const long long rank = r4d_geti_or(a, "rank", 0); const long long vocab = r4d_geti_or(a, "n_vocab", 0); const long long anchor_stride = r4d_geti_or(a, "anchor_stride", 1); - if (steps <= 0 || rank < kWave || rank > kMaxRank || rank % kWave || vocab <= 0 || - anchor_stride <= 0) + if (steps <= 0 || steps > INT_MAX || rank < kWave || rank > kMaxRank || rank % kWave || + vocab <= 0 || vocab > INT_MAX - kCandidatesPerTile || anchor_stride <= 0) return R4D_NO(RAD_E_INVAL); if (out->dtype != RAD_I32 || out->rank != 2 || out->shape[1] < steps) @@ -164,8 +174,12 @@ extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) const long long sequences = out->shape[0]; const long long out_pitch = r4d_row_pitch(out); const long long logits_pitch = r4d_row_pitch(logits); - if (sequences <= 0 || out_pitch < steps || logits->dtype != RAD_BF16 || logits->rank != 2 || - logits->shape[0] < sequences * steps || logits->shape[1] < vocab || logits_pitch < vocab) + // blockIdx.y is limited to 65535, and all kernel loop indices are int. + if (sequences <= 0 || sequences > 65535 || sequences > LLONG_MAX / steps || + (sequences - 1) > (LLONG_MAX - 1) / anchor_stride || + !rows_fit(sequences, out_pitch, steps, sizeof(int)) || logits->dtype != RAD_BF16 || + logits->rank != 2 || logits->shape[0] < sequences * steps || logits->shape[1] < vocab || + !rows_fit(sequences * steps, logits_pitch, vocab, sizeof(r4d_u16))) return R4D_NO(RAD_E_SHAPE); if (anchor->dtype != RAD_I32 || !r4d_contig(anchor) || @@ -179,13 +193,15 @@ extern "C" int r4d_rad_dflash_markov_greedy(const RadArgs* a, RadStream stream) if (scores->dtype != RAD_F32 || tokens->dtype != RAD_I32 || scores->rank != 2 || tokens->rank != 2 || scores->shape[0] < sequences || tokens->shape[0] < sequences || scores->shape[1] < n_tiles || tokens->shape[1] < n_tiles || - r4d_row_pitch(scores) < n_tiles || r4d_row_pitch(tokens) < n_tiles) + !rows_fit(sequences, r4d_row_pitch(scores), n_tiles, sizeof(float)) || + !rows_fit(sequences, r4d_row_pitch(tokens), n_tiles, sizeof(int))) return R4D_NO(RAD_E_SHAPE); return R4D_RAW(markov_emit((const r4d_u16*)logits->data, (long)logits_pitch, (const int*)anchor->data, (long)anchor_stride, (const r4d_u16*)pred->data, (const r4d_u16*)succ->data, - (float*)scores->data, (int*)tokens->data, (int*)out->data, + (float*)scores->data, (long)r4d_row_pitch(scores), + (int*)tokens->data, (long)r4d_row_pitch(tokens), (int*)out->data, (long)out_pitch, (int)sequences, (int)steps, (int)rank, (int)vocab, (int)n_tiles, stream)); } diff --git a/tests/dspark_device_test.cpp b/tests/dspark_device_test.cpp new file mode 100644 index 00000000..80d22105 --- /dev/null +++ b/tests/dspark_device_test.cpp @@ -0,0 +1,159 @@ +/* Focused device/CPU DSpark differential. Build with hipcc, then pass libr4d.so. + * This intentionally calls the real exported launchers, not the host SIMT emulator. + * See docs/DSPARK-VALIDATION-WIP.md for a scoped invocation and its limitations. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Fn = int (*)(const RadArgs*, RadStream); +static void check(bool b, const char* s) { if (!b) { std::fprintf(stderr, "FAIL %s\n", s); std::exit(1); } } +static void hipcheck(hipError_t e) { if (e != hipSuccess) { std::fprintf(stderr, "HIP: %s\n", hipGetErrorString(e)); std::exit(1); } } +static uint16_t bf(float f) { uint32_t x; std::memcpy(&x, &f, 4); x += 0x7fff + ((x >> 16) & 1); return x >> 16; } +static float fb(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; std::memcpy(&f, &x, 4); return f; } +template struct Device { + T* p = nullptr; size_t n; + explicit Device(const std::vector& v): n(v.size()) { hipcheck(hipMalloc(&p, n*sizeof(T))); hipcheck(hipMemcpy(p, v.data(), n*sizeof(T), hipMemcpyHostToDevice)); } + ~Device() { (void)hipFree(p); } + std::vector get() { std::vector v(n); hipcheck(hipMemcpy(v.data(), p, n*sizeof(T), hipMemcpyDeviceToHost)); return v; } +}; +static RadTensor t(void* p, int dt, std::initializer_list sh) { + RadTensor x{}; x.data=p; x.dtype=dt; x.rank=sh.size(); int i=0; for (auto d:sh) x.shape[i++]=d; rad_tensor_pack(&x); return x; +} +static RadParam pi(const char* k, long long v) { RadParam p{}; p.key=k; p.kind=RAD_P_INT; p.ival=v; return p; } +static RadParam ps(const char* k, const char* v) { RadParam p{}; p.key=k; p.kind=RAD_P_STR; p.sval=v; return p; } +static Fn symbol(void* h, const char* name) { auto f = reinterpret_cast(dlsym(h,name)); check(f != nullptr, name); return f; } + +static void markov(Fn fn, int R) { + constexpr int M=2, S=2, V=130, T=3, LP=137, SP=5, TP=7, OP=4; + std::vector l(M*S*LP,bf(0)), p(V*R,bf(0)), u(V*R,bf(0)); + for (int m=0;m anchor{1,-1,2,-1}, ti(M*TP,-777), out(M*OP,-777); + std::vector ts(M*SP,-777.f); + Device dl(l), dp(p), du(u); Device da(anchor), di(ti), dout(out); Device ds(ts); + RadTensor a[]={t(dl.p,RAD_BF16,{M*S,V}),t(da.p,RAD_I32,{M,2}),t(dp.p,RAD_BF16,{V,R}),t(du.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{M,T}),t(di.p,RAD_I32,{M,T}),t(dout.p,RAD_I32,{M,S})}; + a[0].stride[0]=LP; a[4].stride[0]=SP; a[5].stride[0]=TP; a[6].stride[0]=OP; + RadParam par[]={pi("M",M),pi("steps",S),pi("rank",R),pi("n_vocab",V),pi("anchor_stride",2),ps("dtype","bf16")}; + RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=6; + check(fn(&args,nullptr)==RAD_OK,"markov launch"); hipcheck(hipDeviceSynchronize()); + auto go=dout.get(); auto gs=ds.get(); auto gi=di.get(); + // Independent scalar oracle. Values are deliberately exactly representable so reduction order + // cannot explain a discrepancy. Sequential conditioning and tile winners are both checked. + for(int m=0;mbest) { best=score; winner=v; } + } + check(go[m*OP+s]==winner,"markov CPU winner"); prev=winner; + } + for(int tile=0;tilebest) {best=score; win=v;} + } + check(gs[m*SP+tile]==best && gi[m*TP+tile]==win,"markov pitched tile oracle"); + } + for(int i=T;i l{bf(1.001f),bf(1.002f)}, w(V*R,bf(0)); + std::vector anchor{0}, token{-1}, tile{-1}; std::vector score{-1}; + check(l[0]==l[1],"near tie quantizes identically"); + Device dl(l), dw(w); Device da(anchor), dt(tile), dout(token); Device ds(score); + RadTensor a[]={t(dl.p,RAD_BF16,{1,V}),t(da.p,RAD_I32,{1}),t(dw.p,RAD_BF16,{V,R}),t(dw.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{1,1}),t(dt.p,RAD_I32,{1,1}),t(dout.p,RAD_I32,{1,1})}; + RadParam par[]={pi("steps",1),pi("rank",R),pi("n_vocab",V),pi("anchor_stride",1)}; + RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=4; + check(fn(&args,nullptr)==RAD_OK,"near tie launch"); hipcheck(hipDeviceSynchronize()); + check(dout.get()[0]==0 && 1.002f>1.001f,"BF16/F32 near tie divergence"); + std::puts("near tie: F32 argmax=1, BF16 input argmax=0: PASS (synthetic)"); +} + +static void attention(Fn shared, Fn ordinary, int G, int ctx0, int ctx1, int causal) { + constexpr int M=2, Q=7, H=256, BS=16, W=513; + const int ctx[M]={ctx0,ctx1}, blocks=(std::max(ctx0,ctx1)+15)/16, nblocks=M*blocks; + std::vector q(M*Q*G*H,bf(0)), kv((size_t)nblocks*BS*2*H,bf(0)), out(M*Q*G*H,bf(0)); + std::vector bt(M*blocks), su{ctx0,ctx1}, cu{0,Q,2*Q}; + // Reverse physical pages: the oracle must consult block_table rather than logical positions. + for(int s=0;s dq(q), dk(kv), dout(out); Device db(bt), ds(su), dc(cu); + RadTensor a[]={t(dq.p,RAD_BF16,{M*Q,G,H}),t(dk.p,RAD_BF16,{nblocks,1,BS,2*H}), + t(db.p,RAD_I32,{M,blocks}),t(ds.p,RAD_I32,{M}),RadTensor{},RadTensor{}, + t(dc.p,RAD_I32,{M+1}),t(dout.p,RAD_BF16,{M*Q,G,H})}; + RadParam par[]={pi("q_len",Q),pi("head_dim",H),pi("gqa",G),pi("block_size",BS), + pi("causal",causal),pi("window",W),pi("n_head",G),pi("max_seqs",M), + ps("q_dtype","bf16"),ps("kv_dtype","bf16")}; + RadArgs args{}; args.t=a; args.n_t=8; args.p=par; args.n_p=10; + check(shared(&args,nullptr)==RAD_OK,"shared anchor attention launch"); hipcheck(hipDeviceSynchronize()); + auto got=dout.get(); std::vector expected(M*Q*G); + for(int s=0;s0.03) distinguished=true; + check(distinguished,"attention per-row window negative control"); + std::printf("attention gqa=%d ctx=%d,%d causal=%d shared oracle and negative control: PASS\n",G,ctx0,ctx1,causal); +} + +int main(int argc,char** argv) { + check(argc==2,"usage: dspark_device_test libr4d.so"); void* h=dlopen(argv[1],RTLD_NOW|RTLD_LOCAL); + if(!h) { std::fprintf(stderr,"dlopen: %s\n",dlerror()); return 1; } + Fn fn=symbol(h,"r4d_rad_dflash_markov_greedy"); + for(int r:{32,64,128,512}) markov(fn,r); + near_tie(fn); + for(int g:{1,2}) { + const char* shared=g==1?"r4d_rad_attn_anchor_window_h256_gqa1_bf16kv":"r4d_rad_attn_anchor_window_h256_gqa2_bf16kv"; + const char* ordinary=g==1?"r4d_rad_attn_window_h256_gqa1_bf16":"r4d_rad_attn_window_h256_gqa2_bf16"; + for(int causal:{0,1}) { + attention(symbol(h,shared),symbol(h,ordinary),g,520,1049,causal); + attention(symbol(h,shared),symbol(h,ordinary),g,521,1050,causal); + } + } + dlclose(h); std::puts("DSpark device differential: PASS"); +} diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 85209b97..62ed1ac3 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -9480,6 +9480,28 @@ TEST(dflash_markov_greedy_scans_full_vocab_and_keeps_sequences_independent) { CHECK_EQ(tile_scores.at(2), 0.0f); } +/* Independent pitches in the two scratch arrays are part of the tensor contract. Guard cells + * distinguish correct row addressing from treating both outputs as tightly packed. */ +TEST(dflash_markov_greedy_padded_scratch_rows) { + constexpr int V=130, R=32, M=2, tiles=3; + T logits(RAD_BF16, {M, V}), anchor(RAD_I32, {M}); anchor.n({1, 2}); + T pred(RAD_BF16, {V, R}), succ(RAD_BF16, {V, R}); + st_dt(RAD_BF16, pred.t.data, R, 1); st_dt(RAD_BF16, pred.t.data, 2*R+1, 1); + st_dt(RAD_BF16, succ.t.data, 129*R, 4); st_dt(RAD_BF16, succ.t.data, 80*R+1, 8); + T scores(RAD_F32, {M, 5}); scores.f(std::vector(10, -777)); + T tokens(RAD_I32, {M, 7}); tokens.n(std::vector(14, -777)); + scores.t.shape[1]=tiles; tokens.t.shape[1]=tiles; + T out(RAD_I32, {M, 1}); + A a; a.t(logits).t(anchor).t(pred).t(succ).t(scores).t(tokens).t(out) + .i("M", M).i("steps", 1).i("rank", R).i("n_vocab", V).s("dtype", "bf16"); + CHECK_OK(run("dflash_markov_greedy", a)); + CHECK_EQ(out.iat(0), 129); CHECK_EQ(out.iat(1), 80); + CHECK_EQ(tokens.iat(2), 129); CHECK_EQ(tokens.iat(7+1), 80); + CHECK_EQ(scores.at(2), 4); CHECK_EQ(scores.at(5+1), 8); + for (int i : {3,4,8,9}) CHECK_EQ(scores.at(i), -777); + for (int i : {3,4,5,6,10,11,12,13}) CHECK_EQ(tokens.iat(i), -777); +} + /* A one-row, one-layer DSpark oracle assembled from libref's ordinary ops. The literals check the * architecture-specific chain rather than only each primitive: each tap has its own RMS gain, * the normalized taps feed fc/h_norm then context K/V projections, context and draft K/V land in