Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions engine/include/strata/poly/kernels.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -285,25 +285,28 @@ void far_pull(const FarFetch* fetch, const int* count, int most, size_t bytes, v
/// v0.2.19's Inkling hybrid mode (engine/src/inkling2/cuda/ink_hybrid.cuh): the card rings it with the experts it
/// lacks and goes on with its own, the host computes those and answers, and the card waits for the answer only where
/// it adds their sum. Its fields are each a cache line from the others'.
constexpr int kBellJobs = 32;
constexpr int kBellJobs = 128;
struct ExpertBell {
volatile uint32_t ring; ///< the card's rings so far; a new value is a new job
uint32_t pad0[15];
volatile uint32_t ack; ///< the ring the host has answered
uint32_t pad1[15];
volatile uint32_t abort; ///< the host gave up: every wait ends at once
uint32_t pad2[15];
int32_t layer, n; ///< the job: layer and how many experts
int32_t layer, n, rows; ///< the job: layer, how many experts, and how many token rows
int32_t e[kBellJobs]; ///< their ids
int32_t row[kBellJobs]; ///< each job's token row (0..rows-1)
float w[kBellJobs]; ///< their router weights
};
/// One token's picks ids[0..n_used) with weights w at layer `layer`: the ones whose slots[] entry is null, at a place
/// under skip_from, go into the bell, x (n floats) into hx, and the bell rings (seq[0] counts the rings; seq[1] is
/// this one, or 0 when there is none). One block. CUDA and HIP.
/// Picks ids[0..rows*n_used) with weights w at layer `layer`: the ones whose slots[] entry is null, at a place
/// under skip_from, go into the bell, x (rows*n floats) into hx, and the bell rings (seq[0] counts the rings;
/// seq[1] is this one, or 0 when there is none). One block. CUDA and HIP.
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);
const float* x, float* hx, int n, ExpertBell* bell, uint32_t* seq, void* stream, int rows = 1);
/// 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);
/// Pokes bell->ack = seq from a CUDA/HIP stream after its preceding D2H writes are visible to the peer.
void bell_ack(ExpertBell* bell, uint32_t seq, void* stream);
/// copy2() with a third run. CUDA and HIP only.
void copy3(const void* x0, void* y0, int n0, const void* x1, void* y1, int n1, const void* x2, void* y2, int n2,
void* stream);
Expand Down
72 changes: 55 additions & 17 deletions engine/src/poly/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5595,7 +5595,7 @@ bool Engine::card_moe(int n) {
const bool bell = bell_on(n);
if (!(card_routes() || bell) || !d_slots_ || n * n_used_ > card_rows() || opt_.dump) return false;
#if !defined(STRATA_GPU_METAL)
if (ecard_) return false; // --expert-gpu: the host routes, and hands the second card its experts (moe())
if (ecard_ && !bell) return false;
#endif
const bool mirrored = !all_cached() && !bell; // with the doorbell the misses are the host's, not the mirror's
const auto far_of = [&](int il, int e) -> void* {
Expand Down Expand Up @@ -5657,12 +5657,12 @@ bool Engine::moe_card(Layer& L, int il, int n) {
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;
[[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 (rings) { // the doorbell: the misses to the host / second card, 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_);
h_bell_, d_bell_seq_, st_, n);
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_,
Expand Down Expand Up @@ -5702,7 +5702,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) bell_add(h_bell_, d_bell_seq_, h_cpu_, fo_, n * n_embd_, st_); // (bells(): no sum later then)
#endif
return true;
}
Expand All @@ -5712,7 +5712,8 @@ bool Engine::bell_on(int n) const {
(void) n;
return false;
#else
return n == 1 && h_bell_ && !all_cached() && !card_far_ && !pool_ && !split_ && !block_pass_ && !opt_.dump;
return (n == 1 || (ecard_ && n >= 1 && n <= kCpuRows)) && h_bell_ && !all_cached() && !card_far_ &&
(!pool_ || ecard_) && !split_ && !block_pass_ && !opt_.dump;
#endif
}

Expand Down Expand Up @@ -5755,14 +5756,17 @@ void Engine::bell_serve() {
if (r != bell_seen_) {
std::atomic_thread_fence(std::memory_order_acquire);
bell_seen_ = r;
bool async_ack = false;
try {
bell_job();
async_ack = bell_job(r);
} catch (...) {
bell_unwind(); // the card's waits end; what it adds is spoiled, and the call throws
throw;
}
std::atomic_thread_fence(std::memory_order_release);
h_bell_->ack = r;
if (!async_ack) {
std::atomic_thread_fence(std::memory_order_release);
h_bell_->ack = r;
}
moved = Clock::now();
continue;
}
Expand All @@ -5788,25 +5792,59 @@ void Engine::bell_unwind() {
#endif
}

void Engine::bell_job() {
bool Engine::bell_job(uint32_t seq) {
const int il = h_bell_->layer, n = std::min<int>(h_bell_->n, kBellJobs);
const int rows = std::max(1, h_bell_->rows);
const Layer& L = layers_[(size_t) il];
CpuExpert host[kBellJobs];
int n_host = 0;
#if !defined(STRATA_GPU_METAL)
ExpertCard::Job card2[kBellJobs];
int n_far = 0;
#endif
for (int j = 0; j < n; ++j) {
const size_t e = (size_t) h_bell_->e[j];
const int row = h_bell_->row[j];
const float w = L.h_s_down.empty() ? h_bell_->w[j] : h_bell_->w[j] * L.h_s_down[e]; // NVFP4's down scale
#if !defined(STRATA_GPU_METAL)
if (const uint8_t* s = ecard_ ? ecard_->slot(il, (int) e) : nullptr) {
card2[n_far++] = {s, w, row, (int) e};
continue;
}
#endif
const float gs = L.h_s_gate.empty() ? 1.f : L.h_s_gate[e], us = L.h_s_up.empty() ? 1.f : L.h_s_up[e];
if (const uint8_t* m = mirror(il, (int) e))
host[j] = {m, m + L.gu_bytes, m + L.gu2(), w, 0, gs, us};
host[n_host++] = {m, m + L.gu_bytes, m + L.gu2(), w, row, gs, us};
else
host[j] = {L.exp_gate + e * L.gu_stride, L.exp_up + e * L.u_stride, L.exp_down + e * L.d_bytes, w, 0, gs, us};
host[n_host++] = {L.exp_gate + e * L.gu_stride, L.exp_up + e * L.u_stride, L.exp_down + e * L.d_bytes, w,
row, gs, us};
}
#if !defined(STRATA_GPU_METAL)
if (n_far > 0 && n_host == 0) {
ecard_->start(L, il, h_x_, rows, card2, n_far, clamp_exp_[(size_t) il], gelu_, situ_beta_, situ_lb_, h_cpu_,
h_bell_, seq);
return true;
}
if (n_far > 0)
ecard_->start(L, il, h_x_, rows, card2, n_far, clamp_exp_[(size_t) il], gelu_, situ_beta_, situ_lb_);
#else
(void) seq;
#endif
const Clock::time_point t0 = Clock::now();
cpu_experts(*workers_, host, n, 1, (int) L.gu_type, (int) L.u_type, (int) L.d_type, n_embd_, n_ff_exp_, h_x_,
clamp_exp_[(size_t) il], gelu_, h_cpu_, nullptr, nullptr, nullptr, situ_beta_, situ_lb_);
stats_.cpu_ms += ms_since(t0);
stats_.cpu_experts += n;
stats_.gpu_experts -= n; // run() counted every pick of the token as the card's
if (n_host > 0) {
if (pool_) pool_take(L, il, host, n_host);
cpu_experts(*workers_, host, n_host, rows, (int) L.gu_type, (int) L.u_type, (int) L.d_type, n_embd_, n_ff_exp_,
h_x_, clamp_exp_[(size_t) il], gelu_, h_cpu_, nullptr, nullptr, nullptr, situ_beta_, situ_lb_);
stats_.cpu_ms += ms_since(t0);
stats_.cpu_experts += n_host;
stats_.gpu_experts -= n_host; // run() counted every pick of the token as the card's
} else {
std::memset(h_cpu_, 0, (size_t) rows * n_embd_ * sizeof(float));
}
#if !defined(STRATA_GPU_METAL)
if (n_far > 0) ecard_->finish_into(h_cpu_);
#endif
return false;
}

// m experts from the mapped file into the staging buffer: gate and up of each back to back from the start, the
Expand Down
2 changes: 1 addition & 1 deletion engine/src/poly/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1235,7 +1235,7 @@ class Engine {
bool picks_like_alone() const;
bool picks_like_alone(const Layer& L) const;
void bell_serve();
void bell_job();
bool bell_job(uint32_t seq);
void bell_unwind();
uint8_t* stage_ = nullptr; ///< experts that are not cached, on their way through VRAM
uint8_t* h_stage_[2] = {}; ///< pinned; filled in turn
Expand Down
14 changes: 11 additions & 3 deletions engine/src/poly/expert_card.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ void ExpertCard::scales(int il, const std::vector<float>& gate, const std::vecto
// What Engine::moe()'s launch does with the first card's cached experts, on this card: the rows' inputs quantized,
// gate and up, the activation, its quantization, down, then each output times its weight into its token's row.
void ExpertCard::start(const Layer& L, int il, const float* x, int m, const Job* jobs, int n, float limit, bool gelu,
float situ_beta, float situ_lb) {
float situ_beta, float situ_lb, float* dst_rows, void* bell, uint32_t seq) {
OnDevice on(device_);
if (pending_) { // a call that ended in an exception (the CPU's experts) left its work: it is dropped
ck(cudaStreamSynchronize((cudaStream_t) stream_), "--expert-gpu experts");
Expand Down Expand Up @@ -159,8 +159,16 @@ void ExpertCard::start(const Layer& L, int il, const float* x, int m, const Job*
if (q == kSumRows - 1 || i0 + j == n - 1) add_scaled(sum, q + 1, n_embd_, st);
}
}
ck(cudaMemcpyAsync(out_, acc_, (size_t) m * row * sizeof(float), cudaMemcpyDeviceToHost, st), "--expert-gpu output");
pending_ = m;
if (dst_rows) {
ck(cudaMemcpyAsync(dst_rows, acc_, (size_t) m * row * sizeof(float), cudaMemcpyDeviceToHost, st),
"--expert-gpu output");
if (bell) bell_ack((ExpertBell*) bell, seq, st);
pending_ = 0;
} else {
ck(cudaMemcpyAsync(out_, acc_, (size_t) m * row * sizeof(float), cudaMemcpyDeviceToHost, st),
"--expert-gpu output");
pending_ = m;
}
}

void ExpertCard::finish_into(float* rows) {
Expand Down
5 changes: 3 additions & 2 deletions engine/src/poly/expert_card.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,10 @@ class ExpertCard {

/// Starts n jobs of layer il for m rows: x is the rows' expert input (n_embd floats a row, pinned host memory, as
/// the CPU's experts read it). The activation is the layer's: SiTU when situ_beta > 0, else GELU when gelu, else
/// SwiGLU clamped at limit. finish_into() waits for it.
/// SwiGLU clamped at limit. When dst_rows is non-null, copies acc_ directly to dst_rows on stream_ and, if bell
/// is non-null, signals bell->ack = seq from the GPU stream (no finish_into() needed). Otherwise finish_into() waits.
void start(const Layer& L, int il, const float* x, int m, const Job* jobs, int n, float limit, bool gelu,
float situ_beta, float situ_lb);
float situ_beta, float situ_lb, float* dst_rows = nullptr, void* bell = nullptr, uint32_t seq = 0);
/// Waits for start()'s work and adds its sums to `rows` (m rows of n_embd floats, host memory).
void finish_into(float* rows);

Expand Down
37 changes: 28 additions & 9 deletions engine/src/poly/kernels.cu
Original file line number Diff line number Diff line change
Expand Up @@ -3972,29 +3972,37 @@ void far_pull(const FarFetch* fetch, const int* count, int most, size_t bytes, v

__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) {
const float* __restrict__ x, float* hx, int n, int rows, ExpertBell* bell,
uint32_t* seq) {
__shared__ int jobs;
if (threadIdx.x == 0) {
int j = 0;
for (int k = 0; k < n_used && j < kBellJobs; ++k)
if (!slots[ids[k]] && k < skip_from) {
bell->e[j] = ids[k];
bell->w[j] = w[k];
++j;
for (int t = 0; t < rows && j < kBellJobs; ++t) {
for (int u = 0; u < n_used && j < kBellJobs; ++u) {
const int k = t * n_used + u;
if (!slots[ids[k]] && u < skip_from) {
bell->e[j] = ids[k];
bell->row[j] = t;
bell->w[j] = w[k];
++j;
}
}
}
jobs = j;
}
__syncthreads();
if (jobs == 0) {
if (threadIdx.x == 0) seq[1] = 0;
return;
}
for (int i = threadIdx.x; i < n; i += blockDim.x) hx[i] = x[i];
const int total = rows * n;
for (int i = threadIdx.x; i < total; i += blockDim.x) hx[i] = x[i];
__threadfence_system(); // the input and the jobs are the host's before the ring (bell_poke())
__syncthreads();
if (threadIdx.x == 0) {
bell->layer = layer;
bell->n = jobs;
bell->rows = rows;
__threadfence_system();
const uint32_t s = ++seq[0];
bell_poke(&bell->ring, s);
Expand All @@ -4015,18 +4023,29 @@ __global__ void bell_add_kernel(const ExpertBell* bell, const uint32_t* __restri
}

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_kernel<<<1, 256, 0, cs(stream)>>>(slots, ids, w, n_used, skip_from, layer, x, hx, n, bell, seq);
const float* x, float* hx, int n, ExpertBell* bell, uint32_t* seq, void* stream, int rows) {
bell_ring_kernel<<<1, 256, 0, cs(stream)>>>(slots, ids, w, n_used, skip_from, layer, x, hx, n, rows, bell, seq);
if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess)
throw std::runtime_error(std::string("bell_ring: ") + cudaGetErrorString(e));
}

__global__ void bell_ack_kernel(ExpertBell* bell, uint32_t seq) {
__threadfence_system();
bell_poke(&bell->ack, seq);
}

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)
throw std::runtime_error(std::string("bell_add: ") + cudaGetErrorString(e));
}

void bell_ack(ExpertBell* bell, uint32_t seq, void* stream) {
bell_ack_kernel<<<1, 1, 0, cs(stream)>>>(bell, seq);
if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess)
throw std::runtime_error(std::string("bell_ack: ") + cudaGetErrorString(e));
}

void copy3(const void* x0, void* y0, int n0, const void* x1, void* y1, int n1, const void* x2, void* y2, int n2,
void* stream) {
copy3_kernel<<<grid(n0 + n1 + n2, 256), 256, 0, cs(stream)>>>((const uint32_t*) x0, (uint32_t*) y0, n0,
Expand Down
Loading