diff --git a/engine/include/strata/poly/kernels.hpp b/engine/include/strata/poly/kernels.hpp index a13246f3f4..a3983f305a 100644 --- a/engine/include/strata/poly/kernels.hpp +++ b/engine/include/strata/poly/kernels.hpp @@ -302,6 +302,22 @@ struct ExpertBell { /// this one, or 0 when there is none). One block. CUDA only. void bell_ring(const void* const* slots, const int32_t* ids, const float* w, int n_used, int skip_from, int layer, const float* x, float* hx, int n, ExpertBell* bell, uint32_t* seq, void* stream); +/// bell_ring()'s arguments besides the picks, for route_ring(); uses: count_picks()'s counts (null: none). +struct BellRing { + const void* const* slots; + int32_t* uses; + int skip_from, layer; + const float* x; + float* hx; + int n; + ExpertBell* bell; + uint32_t* seq; +}; +/// route_rows() of one token into ids and w, count_picks() of its picks into r.uses and bell_ring() of them with +/// r's arguments, in one launch: the same bits as the three. CUDA only. +void route_ring(const float* logits, int n_expert, int n_used, int gate, float in_scale, const float* bias, + const float* escale, bool norm, float w_scale, int32_t* ids, float* w, const BellRing& r, + void* stream); /// Where seq[1] is a ring: wait until the bell's ack is that ring (or abort is set), then acc += hy (n floats). void bell_add(const ExpertBell* bell, const uint32_t* seq, const float* hy, float* acc, int n, void* stream); /// copy2() with a third run. CUDA and HIP only. diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 4360199699..e33086ca10 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -5582,20 +5582,31 @@ bool Engine::card_moe(int n) { // on the host, or its formats have no kernel for picks on the card. bool Engine::moe_card(Layer& L, int il, int n) { if (L.card == 0) return false; - if (!kernels::native_mmvq_ids_supported((int) L.gu_type) || !kernels::native_mmvq_ids_supported((int) L.u_type) || - !kernels::native_mmvq_ids_supported((int) L.d_type) || !route_card(il, n, d_ids_, d_wts_)) { + const int rr = n * n_used_; + const void* const* table = d_slots_ + (size_t) il * n_expert_; + [[maybe_unused]] const bool rings = bell_ && n == 1; + [[maybe_unused]] bool rung = false; // route_card_ring() has counted the picks and rung the bell + const bool kernels_for_picks = kernels::native_mmvq_ids_supported((int) L.gu_type) && + kernels::native_mmvq_ids_supported((int) L.u_type) && + kernels::native_mmvq_ids_supported((int) L.d_type); +#if !defined(STRATA_GPU_METAL) + // the doorbell: the misses to the host, a token's place under --tail-skip's + const BellRing ring{table, rings && !block_pass_ ? d_use_ + (size_t) il * n_expert_ : nullptr, + opt_.tail_skip > 0 ? opt_.tail_skip : n_used_, il, xn_, h_x_, n_embd_, h_bell_, d_bell_seq_}; + rung = kernels_for_picks && rings && route_card_ring(il, ring); +#endif + if (!kernels_for_picks || (!rung && !route_card(il, n, d_ids_, d_wts_))) { L.card = 0; return false; } L.card = 1; - const int rr = n * n_used_; - const void* const* table = d_slots_ + (size_t) il * n_expert_; - [[maybe_unused]] const bool rings = bell_ && n == 1; #if !defined(STRATA_GPU_METAL) - if (rings) { // the doorbell: the misses to the host, a token's place under --tail-skip's - if (!block_pass_) count_picks(d_ids_, rr, n_expert_, d_use_ + (size_t) il * n_expert_, st_); - bell_ring(table, d_ids_, d_wts_, n_used_, opt_.tail_skip > 0 ? opt_.tail_skip : n_used_, il, xn_, h_x_, n_embd_, - h_bell_, d_bell_seq_, st_); + if (rings) { + if (!rung) { + if (ring.uses) count_picks(d_ids_, rr, n_expert_, ring.uses, st_); + bell_ring(table, d_ids_, d_wts_, n_used_, ring.skip_from, il, xn_, h_x_, n_embd_, h_bell_, d_bell_seq_, + st_); + } table = d_zslots_ + (size_t) il * n_expert_; } else if (!all_cached()) { // card_far_: the experts it lacks, from the mirror into the staging buffer first far_plan(table, d_far_ + (size_t) il * n_expert_, d_ids_, rr, n_expert_, stage_, ahead_stride_, d_tab_, @@ -5628,7 +5639,7 @@ bool Engine::moe_card(Layer& L, int il, int n) { if (moe_sum_later(n)) moe_left_ = true; else moe_sum(d_, d_wts_, fo_, n_embd_, n_used_, n, st_); #if !defined(STRATA_GPU_METAL) - if (rings) bell_add(h_bell_, d_bell_seq_, h_cpu_, fo_, n_embd_, st_); // (bells(): no sum later then) + if (rings && !moe_left_) bell_add(h_bell_, d_bell_seq_, h_cpu_, fo_, n_embd_, st_); // (later: the family's) #endif return true; } diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e274541..3da5e3f2f2 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -567,6 +567,14 @@ class Engine { (void) il, (void) n, (void) ids, (void) w; return false; } +#if !defined(STRATA_GPU_METAL) + /// route_card() of one token into d_ids_ and d_wts_ with the doorbell's count_picks() and bell_ring() of its + /// picks (route_ring()), in one launch. False, with nothing launched: the three launches instead. + virtual bool route_card_ring(int il, const BellRing& ring) { + (void) il, (void) ring; + return false; + } +#endif /// The shared expert, into fo_. It runs on the GPU while the host routes. virtual void moe_shared(const Layer& L, int il, int n) = 0; /// False: run() launches moe_shared() as it is where it replays a layer's other launches (Layer::shared stays @@ -574,7 +582,8 @@ class Engine { virtual bool shared_recorded() const { return true; } /// True: moe_card() leaves the routed experts' sum (d_ weighted by d_wts_, onto fo_) of a call of n tokens to the /// family, which folds it into what follows (Inkling 2's layer_tail()), and sets moe_left_. The weights are then - /// still to be multiplied by moe_left_scale_[id] where that is set (expert_weights()'s product). + /// still to be multiplied by moe_left_scale_[id] where that is set (expert_weights()'s product), and with the + /// doorbell (bell_ and one token) the host's sum is then the family's to add too, as bell_add() adds it. virtual bool moe_sum_later(int n) const { (void) n; return false; diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index c20d374044..caf5be3823 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -1589,6 +1589,14 @@ void Inkling2::layer_tail(Layer&, int il, int n) { void Inkling2::tail_rows(int il, int n) { const Slot& S = slots_[(size_t) slot_of(il, pass_of(il))]; if (n == 1 && std::exchange(moe_left_, false)) { // moe_card() left the experts' sum here +#if !defined(STRATA_GPU_METAL) + if (bell_) { // and the doorbell's + ink_moe_bell_conv_add(d_, d_wts_, moe_left_scale_, d_ids_, n_used_, fo_, h_bell_, d_bell_seq_, h_cpu_, + past_f(run_slot(il, 0)), fp(blocks_[(size_t) il].f_conv), fc_, r_, 1.f, n_embd_, + taps_, st_); + return; + } +#endif ink_moe_conv_add(d_, d_wts_, moe_left_scale_, d_ids_, n_used_, fo_, past_f(run_slot(il, 0)), fp(blocks_[(size_t) il].f_conv), fc_, r_, 1.f, n_embd_, taps_, st_); return; @@ -1710,14 +1718,25 @@ void Inkling2::route_by(const float* logits, const float* bias, int* ids, float* } } -bool Inkling2::route_card(int il, int n, int32_t* ids, float* w) { +const float* Inkling2::card_bias(int il, int n) const { const Block& B = blocks_[(size_t) il]; const float* bias = B.probs_b_dev.p ? fp(B.probs_b_dev) : nullptr; // a few tokens (moe_card()) with --cache-bias pick by slots_moved()'s bias; a prompt batch as before if (cache_b_ && n < kStageRows) bias = cache_b_ + (size_t) il * n_expert_; - route_rows(rl_, n_expert_, n_used_, n, 1, 1.f, bias, nullptr, true, w_scale_, ids, w, st_); + return bias; +} + +bool Inkling2::route_card(int il, int n, int32_t* ids, float* w) { + route_rows(rl_, n_expert_, n_used_, n, 1, 1.f, card_bias(il, n), nullptr, true, w_scale_, ids, w, st_); + return true; +} + +#if !defined(STRATA_GPU_METAL) +bool Inkling2::route_card_ring(int il, const BellRing& ring) { + route_ring(rl_, n_expert_, n_used_, 1, 1.f, card_bias(il, 1), nullptr, true, w_scale_, d_ids_, d_wts_, ring, st_); return true; } +#endif // No shared expert: the routed experts' sum starts from nothing (where layer_tail() sums them, it starts there). void Inkling2::moe_shared(const Layer&, int, int n) { diff --git a/engine/src/poly/inkling2.cu b/engine/src/poly/inkling2.cu index cfe6c3d5f0..a08f25308a 100644 --- a/engine/src/poly/inkling2.cu +++ b/engine/src/poly/inkling2.cu @@ -901,20 +901,39 @@ __global__ void ink_conv_add_rows_kernel(const float* x, InkStateRows state, con norm, c); } +// BELL: ink_moe_bell_conv_add()'s, bell_add_kernel's wait and sum between the experts' sum and the convolution +template __global__ void ink_moe_conv_add_kernel(const float* x, const float* w, const float* __restrict__ scale, const int* ids, int n_used, float* fo, float* state, const float* __restrict__ cw, float* __restrict__ out, - float* acc, float a, int channels, int taps, float norm) { + float* acc, float a, int channels, int taps, float norm, + const ExpertBell* bell, const uint32_t* seq, const float* hy) { pdl_trigger(); // PDL (pdl.hpp): the launch after this one may start pdl_wait(); const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= channels) return; + if (!BELL && i >= channels) return; float s = 0.0f; - for (int k = 0; k < n_used; ++k) { + for (int k = 0; k < n_used && i < channels; ++k) { const float wk = scale ? w[k] * scale[ids[k]] : w[k]; // expert_weights_kernel's product s += wk * x[size_t(k) * channels + i]; } - fo[i] = 0.0f + s; // moe_sum() onto the zeros fo was + float f = 0.0f + s; // moe_sum() onto the zeros fo was + if (BELL) { + const uint32_t r = seq[1]; + if (r != 0) { + if (threadIdx.x == 0) + while (bell->ack != r && !bell->abort) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 + __nanosleep(500); +#endif + } + __syncthreads(); + __threadfence_system(); + if (i < channels) f = f + *(volatile const float*) (hy + i); + } + if (i >= channels) return; + } + fo[i] = f; const float y = conv_value(fo, state, cw, nullptr, channels, 1, taps, 0, i, norm); out[i] = y; conv_state_at(fo, state, channels, taps, 1, i); @@ -3001,11 +3020,22 @@ void ink_moe_conv_add(const float* x, const float* w, const float* scale, const void* stream) { if (taps < 2 || taps > 8) throw std::invalid_argument("ink_moe_conv_add: 2 to 8 taps"); const float norm = 1.0f / std::sqrt((float) (taps + 1)); - launch_pdl(ink_moe_conv_add_kernel, dim3(grid((size_t) channels, 256)), dim3(256), 0, cs(stream), x, w, scale, ids, - n_used, fo, state, cw, out, acc, a, channels, taps, norm); + launch_pdl(ink_moe_conv_add_kernel, dim3(grid((size_t) channels, 256)), dim3(256), 0, cs(stream), x, w, + scale, ids, n_used, fo, state, cw, out, acc, a, channels, taps, norm, (const ExpertBell*) nullptr, + (const uint32_t*) nullptr, (const float*) nullptr); launched("ink_moe_conv_add"); } +void ink_moe_bell_conv_add(const float* x, const float* w, const float* scale, const int* ids, int n_used, float* fo, + const ExpertBell* bell, const uint32_t* seq, const float* hy, float* state, const float* cw, + float* out, float* acc, float a, int channels, int taps, void* stream) { + if (taps < 2 || taps > 8) throw std::invalid_argument("ink_moe_bell_conv_add: 2 to 8 taps"); + const float norm = 1.0f / std::sqrt((float) (taps + 1)); + launch_pdl(ink_moe_conv_add_kernel, dim3(grid((size_t) channels, 256)), dim3(256), 0, cs(stream), x, w, + scale, ids, n_used, fo, state, cw, out, acc, a, channels, taps, norm, bell, seq, hy); + launched("ink_moe_bell_conv_add"); +} + #if defined(__HIPCC__) // HIP: ink_clips() as the launches its contract names (ink_clip(), ink_head_rms() and fp16 stores of its jobs), and // ink_qkv() as ink_conv() of K and V and then those; the fused kernels are not built there. ink_clips_kernel and diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 9b3b442939..6ef5014536 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -77,6 +77,9 @@ class Inkling2 final : public Engine { float* tmp) override; void slots_moved() override; bool route_card(int il, int n, int32_t* ids, float* w) override; +#if !defined(STRATA_GPU_METAL) + bool route_card_ring(int il, const BellRing& ring) override; +#endif void moe_shared(const Layer& L, int il, int n) override; private: @@ -140,9 +143,9 @@ class Inkling2 final : public Engine { bool control_ffn(const float* msg, const Ctrl& c, const Block& B, int row = 0); void guess_block(int32_t token) override; bool own_blocks() const override { return ds_file_ != nullptr; } - // only where moe_card() and layer_tail() are recorded together (whole_rec_), and not with the doorbell, whose - // experts' sum comes in after the card's - bool moe_sum_later(int n) const override { return n == 1 && whole_rec_ && !bell_; } + // only where moe_card() and layer_tail() are recorded together (whole_rec_); with the doorbell, layer_tail() + // adds the host's sum too + bool moe_sum_later(int n) const override { return n == 1 && whole_rec_; } bool bells() const override { return true; } #if defined(STRATA_USE_HIP) // the shared expert is one memset (moe_shared()), and a graph launch a layer for it cost an RX 9070 XT's host @@ -186,6 +189,8 @@ class Inkling2 final : public Engine { float w_scale_ = 0; float* cache_b_ = nullptr; ///< --cache-bias: each layer's pick bias for the card (slots_moved()) void route_by(const float* logits, const float* bias, int* ids, float* w, float* probs) const; + /// route_card()'s bias for layer il: the router's own, or for a few tokens with --cache-bias slots_moved()'s. + const float* card_bias(int il, int n) const; void cached_bias(const Layer& L, int il, float* b) const; uint32_t attn_type_ = 0; ///< --attn-requant's type for the attention's matrices; 0: the file's bool unsloth_ = false; ///< an "inkling2" file: block_count counts applications, the loop's names are Unsloth's diff --git a/engine/src/poly/inkling2_kernels.hpp b/engine/src/poly/inkling2_kernels.hpp index cccf9ca712..9a3e9d386b 100644 --- a/engine/src/poly/inkling2_kernels.hpp +++ b/engine/src/poly/inkling2_kernels.hpp @@ -99,6 +99,12 @@ void ink_conv_add_rows(const float* x, const InkStateRows& state, const float* w void ink_moe_conv_add(const float* x, const float* w, const float* scale, const int* ids, int n_used, float* fo, float* state, const float* cw, float* out, float* acc, float a, int channels, int taps, void* stream); +/// ink_moe_conv_add() with the doorbell's sum between the two: where seq[1] is a ring, the experts' sum waits for +/// the bell's answer and gets hy added (bell_add()'s), then the convolution. The same bits as moe_sum(), bell_add() +/// and ink_conv_add() in turn. CUDA only. +void ink_moe_bell_conv_add(const float* x, const float* w, const float* scale, const int* ids, int n_used, float* fo, + const ExpertBell* bell, const uint32_t* seq, const float* hy, float* state, const float* cw, + float* out, float* acc, float a, int channels, int taps, void* stream); /// Each head's `dim` values, times scale (null: none; [dim] a head), brought down to an L2 norm of at most `thr` /// (the norm has 1e-6 added), then times tau = 1 + alpha * log(max(1, (pos + row + 1) / floor)) when alpha > 0. diff --git a/engine/src/poly/inkling2_test.cu b/engine/src/poly/inkling2_test.cu index 7c26b0cf6c..1ffef533a3 100644 --- a/engine/src/poly/inkling2_test.cu +++ b/engine/src/poly/inkling2_test.cu @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -673,6 +674,161 @@ void case_moe_conv_add() { } } +#if !defined(__HIPCC__) +// Wait ms milliseconds on the host (spinning: would bring unistd.h's sync() beside the test's). +void wait_ms(int ms) { + const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); + while (std::chrono::steady_clock::now() < end) { + } +} + +// Pinned host memory of n T's, as the doorbell's bell and the token's input on the host are. +template +struct Pinned { + T* p = nullptr; + size_t n = 0; + explicit Pinned(size_t count) : n(count) { + ck(cudaMallocHost((void**) &p, n * sizeof(T)), "cudaMallocHost"); + std::memset((void*) p, 0, n * sizeof(T)); + } + Pinned(const Pinned&) = delete; + Pinned& operator=(const Pinned&) = delete; + ~Pinned() { (void) cudaFreeHost(p); } + std::vector bytes() const { + sync(); + return std::vector((const uint8_t*) p, (const uint8_t*) (p + n)); + } +}; + +// route_ring() against route_rows(), count_picks() and bell_ring() in turn: the same picks, weights, counts, bell +// and input on the host, for tokens with experts outside VRAM (some past --tail-skip's place) and without +void case_route_ring() { + const float w_scale = 2.5f; + const auto x = randv(kEmbd, 1.0f); + auto bias = randv(kExperts, 0.05f); + // experts 5 and 9: the largest bias, the same for both, so that with equal scores (below) their picks tie + // exactly at the top, and the lower expert goes first + bias[5] = bias[9] = *std::max_element(bias.begin(), bias.end()) + 0.1f; + std::vector slots(kExperts); + Dev dx(x), dbias(bias); + for (const int skip_from : {kUsed, 6}) { + for (const bool misses : {true, false}) { + for (int e = 0; e < kExperts; ++e) // a fake slot address: the kernels only test it for null + slots[(size_t) e] = misses && e % 3 == 0 ? nullptr : (void*) (uintptr_t) (4096 * (e + 1)); + Dev dslots(slots); + std::vector uses0(kExperts); + for (int e = 0; e < kExperts; ++e) uses0[(size_t) e] = (e * 7) % 5; + Dev uses_a(uses0), uses_b(uses0), ids_a(kUsed), ids_b(kUsed); + Dev w_a(kUsed), w_b(kUsed); + Dev seq_a(2), seq_b(2); + Pinned bell_a(1), bell_b(1); + Pinned hx_a(kEmbd), hx_b(kEmbd); + bool same = true, ties_ok = true; + int rings = 0; + for (int t = 0; t < 64 && same; ++t) { + auto lg = randv(kExperts, 2.0f); + if (t % 7 == 0) lg[5] = lg[9] = 9.f; // a tie at the top: the lower expert first + Dev dlg(lg); + route_rows(dlg, kExperts, kUsed, 1, 1, 1.f, dbias, nullptr, true, w_scale, ids_a, w_a, stream()); + count_picks(ids_a, kUsed, kExperts, uses_a, stream()); + bell_ring(dslots, ids_a, w_a, kUsed, skip_from, t, dx, hx_a.p, kEmbd, bell_a.p, seq_a, stream()); + const BellRing r{dslots, uses_b, skip_from, t, dx, hx_b.p, kEmbd, bell_b.p, seq_b}; + route_ring(dlg, kExperts, kUsed, 1, 1.f, dbias, nullptr, true, w_scale, ids_b, w_b, r, stream()); + const auto w1 = w_a.get(), w2 = w_b.get(); + same = ids_a.get() == ids_b.get() && std::memcmp(w1.data(), w2.data(), kUsed * sizeof(float)) == 0 && + uses_a.get() == uses_b.get() && seq_a.get() == seq_b.get() && bell_a.bytes() == bell_b.bytes() && + hx_a.bytes() == hx_b.bytes(); + rings += seq_b.get()[1] != 0; + if (t % 7 == 0) { // 5 and 9 tie at the top: both picked, 5 first + const auto id = ids_b.get(); + ties_ok = ties_ok && id[0] == 5 && id[1] == 9; + } + } + const std::string what = fmt("route_ring = route_rows + count_picks + bell_ring (skip from %d, %s)", + skip_from, misses ? "misses" : "all in VRAM"); + same_bits(what + ": picks", ids_a.get(), ids_b.get()); + same_bits(what + ": weights", w_a.get(), w_b.get()); + same_bits(what + ": counts", uses_a.get(), uses_b.get()); + same_bits(what + ": the bell", bell_a.bytes(), bell_b.bytes()); + same_bits(what + ": the input on the host", hx_a.bytes(), hx_b.bytes()); + same_bits(what + ": every token the same", std::vector{1}, std::vector{same ? 1 : 0}); + same_bits(what + ": a tie, the lower expert first", std::vector{1}, + std::vector{ties_ok ? 1 : 0}); + same_bits(what + ": rang where it should", std::vector{misses ? 1 : 0}, + std::vector{rings > 0 ? 1 : 0}); + } + } +} + +// ink_moe_bell_conv_add() against moe_shared()'s zeros, expert_weights(), moe_sum(), bell_add() and ink_conv_add() +// in turn (moe_card() and layer_tail() with the doorbell, one launch at a time): the same experts' sum, stream and +// state. Bells: no ring; a ring answered before the launch; one the host answers while the launch waits (hy is NaN +// until then, so a read before the answer shows); one the host aborts (the launch must end; its sums are spoiled). +// Widths of a whole number of blocks and not (the last block's threads past the width wait at the barrier too). +void case_moe_bell_conv_add() { + enum Bell { kNone, kBefore, kWhile, kAbort }; + const char* bell_name[] = {"no ring", "answered before", "answered while it waits", "aborted"}; + for (const int n : {kEmbd, 2200}) { + for (const bool scaled : {false, true}) { + for (const Bell how : {kNone, kBefore, kWhile, kAbort}) { + const auto x = randv((size_t) kUsed * n, 1.0f), w = randv(kUsed, 0.3f, 0.5f); + const auto escale = randv(kExperts, 0.2f, 1.0f), acc = randv(n, 1.0f), hy0 = randv(n, 0.5f); + const auto st = randv((size_t) (kTaps - 1) * n, 1.0f), cw = randv((size_t) n * kTaps, 0.5f); + std::vector ids(kUsed); + for (int k = 0; k < kUsed; ++k) ids[k] = (k * 37 + 5) % kExperts; + Pinned bell(1); + Pinned hy(n); + const bool late = how == kWhile || how == kAbort; + for (int i = 0; i < n; ++i) hy.p[i] = late ? NAN : hy0[(size_t) i]; + bell.p->ring = 41u; + bell.p->ack = late ? 40u : 41u; + Dev seq(std::vector{41u, how == kNone ? 0u : 41u}); + Dev dx(x), dw_a(w), dw_b(w), des(escale), acc_a(acc), acc_b(acc), st_a(st), st_b(st), dcw(cw); + Dev fo_a(std::vector(n, 1.0f)), fo_b(n), out_a(n), out_b(n); + Dev dids(ids); + const std::string what = fmt("ink_moe_bell_conv_add %d wide, %s, %s", n, scaled ? "scaled" : "plain", + bell_name[how]); + ink_moe_bell_conv_add(dx, dw_b, scaled ? des.p : nullptr, dids, kUsed, fo_b, bell.p, seq, hy.p, st_b, + dcw, out_b, acc_b, 1.f, n, kTaps, stream()); + if (late) { // the launch waits for the host: give it time, then answer (or give up) from here + wait_ms(50); + const bool waiting = cudaStreamQuery((cudaStream_t) stream()) == cudaErrorNotReady; + same_bits(what + ": waits for the host", std::vector{1}, std::vector{waiting ? 1 : 0}); + if (how == kWhile) { + for (int i = 0; i < n; ++i) hy.p[i] = hy0[(size_t) i]; + __atomic_thread_fence(__ATOMIC_RELEASE); // the sums before the answer + bell.p->ack = 41u; + } else { + bell.p->abort = 1u; + } + bool done = false; + for (int i = 0; i < 5000 && !done; ++i) { + done = cudaStreamQuery((cudaStream_t) stream()) != cudaErrorNotReady; + if (!done) wait_ms(1); + } + same_bits(what + ": ends after the answer", std::vector{1}, std::vector{done ? 1 : 0}); + if (!done) { // a launch that never ends: nothing after it can run + std::printf("ink_moe_bell_conv_add did not end FAIL\n"); + std::exit(1); + } + if (how == kAbort) continue; // the sums of an abort are spoiled, as the engine's call throws + } + bell.p->ack = 41u; // the five launches' bell_add: answered by now + ck(cudaMemsetAsync(fo_a, 0, n * sizeof(float), (cudaStream_t) stream()), "memset"); + if (scaled) expert_weights(dw_a, des, dids, kUsed, stream()); + moe_sum(dx, dw_a, fo_a, n, kUsed, 1, stream()); + bell_add(bell.p, seq, hy.p, fo_a, n, stream()); + ink_conv_add(fo_a, st_a, dcw, out_a, acc_a, nullptr, 1.f, 0, n, kTaps, stream()); + same_bits(what + " = the five launches: the experts' sum", fo_a.get(), fo_b.get()); + same_bits(what + " = the five launches: out", out_a.get(), out_b.get()); + same_bits(what + " = the five launches: the stream", acc_a.get(), acc_b.get()); + same_bits(what + " = the five launches: the state", st_a.get(), st_b.get()); + } + } + } +} +#endif + // ink_qkv(): a token's convolutions, clips, V's norm and the stores in one launch, against ink_conv_few() and // ink_clips() (the engine's path for a few tokens: the same bits) and against the reference; fp16 and FP8, a ring // and a full cache, the position by value and on the card @@ -1435,6 +1591,10 @@ const Case kCases[] = { {"conv", case_conv}, {"conv_acc", case_conv_acc}, {"moe_conv_add", case_moe_conv_add}, +#if !defined(__HIPCC__) + {"route_ring", case_route_ring}, + {"moe_bell_conv_add", case_moe_bell_conv_add}, +#endif {"qkv", case_qkv}, {"mix", case_mix}, {"norms", case_norms}, diff --git a/engine/src/poly/kernels.cu b/engine/src/poly/kernels.cu index 256f269c10..e6833535c1 100644 --- a/engine/src/poly/kernels.cu +++ b/engine/src/poly/kernels.cu @@ -1346,13 +1346,13 @@ __global__ void geglu_rows_kernel(const float* __restrict__ gate_up, float* __re constexpr int ROUTE_PER = 16; // experts a lane: up to 512 // The kernel takes PER experts a lane, the fewest that hold the model's: a slot past them is a -inf that changes no // pick and no sum, and walking all sixteen made a token's routing 3.5 us on an RTX 5090. +// route_kernel's routing of token `row` by a whole warp: false for a lane past n_used, else the lane's pick (the +// lane-th) in id and its weight in wt. template - -__global__ void route_kernel(const float* __restrict__ logits, int n_expert, int n_used, int rows, int gate, - float in_scale, const float* __restrict__ bias, const float* __restrict__ escale, - bool norm, float w_scale, int32_t* __restrict__ ids, float* __restrict__ w) { - const int row = (blockIdx.x * blockDim.x + threadIdx.x) / WARP, lane = threadIdx.x % WARP; - if (row >= rows) return; +__device__ __forceinline__ bool route_pick(const float* __restrict__ logits, int n_expert, int n_used, int row, + int gate, float in_scale, const float* __restrict__ bias, + const float* __restrict__ escale, bool norm, float w_scale, int lane, + int& id, float& wt) { const float* lg = logits + size_t(row) * n_expert; float p[PER], pick[PER]; float mx = -INFINITY; @@ -1418,12 +1418,27 @@ __global__ void route_kernel(const float* __restrict__ logits, int n_expert, int sum += pw; if (lane == j) mine = pw, my_id = at; } - if (lane >= n_used) return; + if (lane >= n_used) return false; float v = mine; if (norm) v /= fmaxf(sum, 6.103515625e-5f); // the floor ggml's MoE graph puts under the gate sum if (escale) v *= escale[my_id]; if (w_scale != 0.0f) v *= w_scale; - ids[size_t(row) * n_used + lane] = my_id; + id = my_id; + wt = v; + return true; +} + +template +__global__ void route_kernel(const float* __restrict__ logits, int n_expert, int n_used, int rows, int gate, + float in_scale, const float* __restrict__ bias, const float* __restrict__ escale, + bool norm, float w_scale, int32_t* __restrict__ ids, float* __restrict__ w) { + const int row = (blockIdx.x * blockDim.x + threadIdx.x) / WARP, lane = threadIdx.x % WARP; + if (row >= rows) return; + int id; + float v; + if (!route_pick(logits, n_expert, n_used, row, gate, in_scale, bias, escale, norm, w_scale, lane, id, v)) + return; + ids[size_t(row) * n_used + lane] = id; w[size_t(row) * n_used + lane] = v; } @@ -3969,9 +3984,11 @@ void far_pull(const FarFetch* fetch, const int* count, int most, size_t bytes, v throw std::runtime_error(std::string("far_pull: ") + cudaGetErrorString(e)); } -__global__ void bell_ring_kernel(const void* const* __restrict__ slots, const int32_t* __restrict__ ids, - const float* __restrict__ w, int n_used, int skip_from, int layer, - const float* __restrict__ x, float* hx, int n, ExpertBell* bell, uint32_t* seq) { +// bell_ring_kernel's work, for a block of the launch's threads +__device__ __forceinline__ void bell_ring_block(const void* const* __restrict__ slots, const int32_t* ids, + const float* w, int n_used, int skip_from, int layer, + const float* __restrict__ x, float* hx, int n, ExpertBell* bell, + uint32_t* seq) { __shared__ int jobs; if (threadIdx.x == 0) { int j = 0; @@ -4002,6 +4019,31 @@ __global__ void bell_ring_kernel(const void* const* __restrict__ slots, const in } } +__global__ void bell_ring_kernel(const void* const* __restrict__ slots, const int32_t* __restrict__ ids, + const float* __restrict__ w, int n_used, int skip_from, int layer, + const float* __restrict__ x, float* hx, int n, ExpertBell* bell, uint32_t* seq) { + bell_ring_block(slots, ids, w, n_used, skip_from, layer, x, hx, n, bell, seq); +} + +// route_ring(): the first warp routes the token, its lanes count their picks, then the block rings the bell with them +template +__global__ void route_ring_kernel(const float* __restrict__ logits, int n_expert, int n_used, int gate, + float in_scale, const float* __restrict__ bias, const float* __restrict__ escale, + bool norm, float w_scale, int32_t* ids, float* w, BellRing r) { + if (threadIdx.x < WARP) { + int id; + float v; + if (route_pick(logits, n_expert, n_used, 0, gate, in_scale, bias, escale, norm, w_scale, threadIdx.x, id, + v)) { + ids[threadIdx.x] = id; + w[threadIdx.x] = v; + if (r.uses && id >= 0 && id < n_expert) atomicAdd(&r.uses[id], 1); + } + } + __syncthreads(); // the picks are the block's + bell_ring_block(r.slots, ids, w, n_used, r.skip_from, r.layer, r.x, r.hx, r.n, r.bell, r.seq); +} + // One block: one thread asks the bell every half microsecond or so, the others sleep at the barrier (a spinning card // draws power that a laptop's CPU, computing the experts meanwhile, would rather have). __global__ void bell_add_kernel(const ExpertBell* bell, const uint32_t* __restrict__ seq, const float* hy, @@ -4026,6 +4068,23 @@ void bell_ring(const void* const* slots, const int32_t* ids, const float* w, int throw std::runtime_error(std::string("bell_ring: ") + cudaGetErrorString(e)); } +void route_ring(const float* logits, int n_expert, int n_used, int gate, float in_scale, const float* bias, + const float* escale, bool norm, float w_scale, int32_t* ids, float* w, const BellRing& r, + void* stream) { + if (n_expert > ROUTE_PER * WARP || n_used > WARP) + throw std::invalid_argument("route_ring: more than 512 experts, or more than 32 a token"); + const auto launch = [&](auto kernel) { + kernel<<<1, 256, 0, cs(stream)>>>(logits, n_expert, n_used, gate, in_scale, bias, escale, norm, w_scale, ids, + w, r); + }; + if (n_expert <= 2 * WARP) launch(route_ring_kernel<2>); + else if (n_expert <= 4 * WARP) launch(route_ring_kernel<4>); + else if (n_expert <= 8 * WARP) launch(route_ring_kernel<8>); + else launch(route_ring_kernel); + if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess) + throw std::runtime_error(std::string("route_ring: ") + cudaGetErrorString(e)); +} + void bell_add(const ExpertBell* bell, const uint32_t* seq, const float* hy, float* acc, int n, void* stream) { bell_add_kernel<<<1, 512, 0, cs(stream)>>>(bell, seq, hy, acc, n); if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess)