Merge perf-PR group batch (f-145-pp-batch)
This commit is contained in:
commit
e8b1edbcb7
25 files changed
+2105
-130
No files matched your search
@@ -3495,7 +3495,7 @@ const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
|
||||
}
|
||||
if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
if (result != nullptr) ++reads_;
|
||||
if (result != nullptr) reads_.fetch_add(1, std::memory_order_relaxed);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -4895,7 +4895,7 @@ const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) {
|
||||
if (layer < 0 || expert < 0 || expert >= n_expert_) return nullptr;
|
||||
const int64_t idx = layer * n_expert_ + expert;
|
||||
if (idx < 0 || idx >= blobs_) return nullptr;
|
||||
++reads_;
|
||||
reads_.fetch_add(1, std::memory_order_relaxed);
|
||||
// Pointer arithmetic into resident memory. No fault, no copy, no mapping - which is the entire point of
|
||||
// this class over `FileExpertSource`.
|
||||
return base_ + arena_off(layer, expert);
|
||||
|
||||
+41
-8
@@ -1372,6 +1372,46 @@ bool MtpDrafter::prepare_prefill(std::string& err) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// STRATA_MTP_PREFILL_SYNC: the prompt pass's per-group loop (see MtpDrafter::prefill); HIP's default
|
||||
static bool prefill_per_group_sync() {
|
||||
static const bool v = [] {
|
||||
if (const char* e = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(e) != 0;
|
||||
#if defined(STRATA_USE_HIP)
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
|
||||
bool MtpDrafter::reserve_prefill(int64_t n, std::string& err) {
|
||||
const OnDevice on_device(device_);
|
||||
if (prefill_per_group_sync()) {
|
||||
for (int T = 1; T <= max_t_; ++T)
|
||||
if (!capture_prefill(T, err)) return false;
|
||||
return true;
|
||||
}
|
||||
if (!prepare_prefill(err)) return false;
|
||||
const int64_t per_row = 1 + 4 + g_->n_head;
|
||||
if (n <= 0) return true;
|
||||
// the records' pinned upload slots too (#1996's ring grows a slot at its first larger upload: a pinned free and
|
||||
// allocation, which take the driver's lock)
|
||||
if (!pf_ring_.reserve((size_t) (n * per_row) * sizeof(int32_t)))
|
||||
std::fprintf(stderr, "strata mtp: the prompt records' pinned upload slots could not be reserved (they grow at "
|
||||
"first use)\n");
|
||||
if (pf_cap_ >= n * per_row) return true;
|
||||
if (pf_dev_) cudaFree(pf_dev_);
|
||||
pf_dev_ = nullptr;
|
||||
pf_cap_ = 0;
|
||||
if (cudaMalloc((void**) &pf_dev_, (size_t) (n * per_row) * sizeof(int32_t)) != cudaSuccess) {
|
||||
err = "mtp prefill: the input records do not fit";
|
||||
return false;
|
||||
}
|
||||
pf_cap_ = n * per_row;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err,
|
||||
bool sync) {
|
||||
#if defined(STRATA_GPU_METAL)
|
||||
@@ -1393,14 +1433,7 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_
|
||||
// in hipGraphLaunch or the final sync until the watchdog ends the engine. R9700, full IQ3_XXS, --kv-resident
|
||||
// 32768, mixed load (chats, 32K and 7K prompts, deep follow-ups): E-4 hung in the first round on 2 of 2 tries,
|
||||
// the old loop ran 30 of 30 rounds clean, prompt speed unchanged.
|
||||
static const bool per_group_sync = [] {
|
||||
if (const char* v = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(v) != 0;
|
||||
#if defined(STRATA_USE_HIP)
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}();
|
||||
const bool per_group_sync = prefill_per_group_sync();
|
||||
const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp;
|
||||
if (!per_group_sync && n > 0) {
|
||||
if (pf_cap_ < n * per_row) {
|
||||
|
||||
+334
-66
@@ -58,6 +58,7 @@
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
@@ -412,6 +413,19 @@ const int64_t g_test_stall = [] {
|
||||
const char* e = std::getenv("STRATA_TEST_VERIFY_STALL");
|
||||
return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
|
||||
}();
|
||||
// The overlapped split's hand-off wait on the GPU is bounded: STRATA_SPLIT_WAIT_MS (default 30000, 0 = no bound).
|
||||
// The host's own per-layer wait (20 s, #267) normally ends a stalled window first; this bound is the backstop for
|
||||
// a host that is gone (a killed process must not leave a kernel spinning on its card).
|
||||
const unsigned long long g_split_wait_ns = [] {
|
||||
const char* e = std::getenv("STRATA_SPLIT_WAIT_MS");
|
||||
return (unsigned long long) (e != nullptr ? std::atoll(e) : 30000) * 1000000ull;
|
||||
}();
|
||||
// test hook: STRATA_TEST_HANDOFF_DROP=N - the writing stage's N-th window (1-based) leaves its hand-off flag down, as
|
||||
// if the publish were lost; the reading stage's bounded wait (or the host's) must then end the window cleanly.
|
||||
const int64_t g_test_drop = [] {
|
||||
const char* e = std::getenv("STRATA_TEST_HANDOFF_DROP");
|
||||
return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
|
||||
}();
|
||||
} // namespace
|
||||
|
||||
bool Verifier::release_gpu_waits(int timeout_ms) {
|
||||
@@ -420,7 +434,7 @@ bool Verifier::release_gpu_waits(int timeout_ms) {
|
||||
// the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here
|
||||
// reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but
|
||||
// wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises.
|
||||
for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_})
|
||||
for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_, hflag_in_h_}) // + an overlapped split's hand-off wait
|
||||
if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX;
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
_mm_sfence();
|
||||
@@ -557,8 +571,9 @@ Verifier::~Verifier() {
|
||||
for (cudaEvent_t e : df_join_)
|
||||
if (e) cudaEventDestroy(e);
|
||||
if (arena_) cudaFree(arena_);
|
||||
if (hcount_d_) cudaFree(hcount_d_);
|
||||
void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
|
||||
h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_};
|
||||
h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_};
|
||||
for (void* h : hosts)
|
||||
if (h) cudaFreeHost(h);
|
||||
}
|
||||
@@ -741,6 +756,13 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
|
||||
return false;
|
||||
}
|
||||
cudaMemset(arena_, 0, count.used);
|
||||
if (hflag_out_d_ != nullptr && hcount_d_ == nullptr) { // the overlapped split's hand-off counter
|
||||
if (cudaMalloc((void**) &hcount_d_, 64) != cudaSuccess) { err = "verify: hand-off counter allocation failed"; return false; }
|
||||
cudaMemset(hcount_d_, 0, 64);
|
||||
if (!mapped(64, (void**) &hdrop_h_, (void**) &hdrop_d_)) { err = "verify: hand-off test word allocation failed"; return false; }
|
||||
}
|
||||
if (hflag_in_d_ != nullptr && herr_h_ == nullptr &&
|
||||
!mapped(64, (void**) &herr_h_, (void**) &herr_d_)) { err = "verify: hand-off error word allocation failed"; return false; }
|
||||
if (g_trace && trace_h_ == nullptr) { // #649: the breadcrumbs, mapped so they read while the GPU hangs
|
||||
trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2;
|
||||
if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) {
|
||||
@@ -777,6 +799,25 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
|
||||
sink_.staging = (unsigned long long) staging_;
|
||||
sink_.staging_cap = kStagingBlobs;
|
||||
(void) TS;
|
||||
// STRATA_PIPED_CONCURRENT=1 (opt-in): a prompt can run on the same GPU while the batch windows run, so the windows'
|
||||
// streams get the device's highest priority (HIP: the default priority, as the drafter's)
|
||||
auto make_stream = [](cudaStream_t* s) -> cudaError_t {
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
static const bool hi = [] { // (STRATA_PIPED_CONCURRENT_PRIO=0: the default priority)
|
||||
const char* v = std::getenv("STRATA_PIPED_CONCURRENT");
|
||||
const char* p = std::getenv("STRATA_PIPED_CONCURRENT_PRIO");
|
||||
return v != nullptr && std::atoi(v) != 0 && (p == nullptr || std::atoi(p) != 0);
|
||||
}();
|
||||
int lo = 0, top = 0;
|
||||
if (hi) {
|
||||
if (cudaDeviceGetStreamPriorityRange(&lo, &top) == cudaSuccess &&
|
||||
cudaStreamCreateWithPriority(s, cudaStreamNonBlocking, top) == cudaSuccess)
|
||||
return cudaSuccess;
|
||||
cudaGetLastError(); // (only the failed priority call's error: the default path clears nothing)
|
||||
}
|
||||
#endif
|
||||
return cudaStreamCreateWithFlags(s, cudaStreamNonBlocking);
|
||||
};
|
||||
bool copy_made = false;
|
||||
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
// engine-latency, STRATA_COPY_HIP_PRIO=1 (opt-in): the copy stream at high priority, so it gets a hardware queue of
|
||||
@@ -790,13 +831,13 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
|
||||
(void) cudaGetLastError();
|
||||
}
|
||||
#endif
|
||||
if (!copy_made && cudaStreamCreateWithFlags(©_, cudaStreamNonBlocking) != cudaSuccess) {
|
||||
if (!copy_made && make_stream(©_) != cudaSuccess) {
|
||||
err = "verify: copy stream create failed";
|
||||
return false;
|
||||
}
|
||||
if (ext_stream_ != nullptr) cs_ = ext_stream_; // set_stream (pipelined windows): the stage's shared stream
|
||||
else if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) cs_ = nullptr;
|
||||
if (cs_ == nullptr || cudaStreamCreateWithFlags(&sh_cs_, cudaStreamNonBlocking) != cudaSuccess) {
|
||||
else if (make_stream(&cs_) != cudaSuccess) cs_ = nullptr;
|
||||
if (cs_ == nullptr || make_stream(&sh_cs_) != cudaSuccess) {
|
||||
err = "verify: stream create failed";
|
||||
return false;
|
||||
}
|
||||
@@ -989,6 +1030,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
const int64_t HB = Verifier::handoff_floats(g);
|
||||
if (lb_ > 0) {
|
||||
const float* hin = hand_in_ + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous
|
||||
// the overlapped split: this graph was launched before the previous stage finished - wait for its hand-off
|
||||
if (hflag_in_d_ != nullptr && !batch_rec_) wait_handoff(hflag_in_d_, 1u, herr_d_, g_split_wait_ns, cs);
|
||||
copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs);
|
||||
copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs);
|
||||
copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs);
|
||||
@@ -1279,6 +1322,24 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
}
|
||||
}
|
||||
// the recurrence from the untouched state over tokens [0, te); outputs only for this group's
|
||||
static const bool gdn_groups_on = [] { // STRATA_BATCH_GDN_GROUPS=1, all slots in one launch
|
||||
const char* v = std::getenv("STRATA_BATCH_GDN_GROUPS");
|
||||
return v != nullptr && std::atoi(v) != 0;
|
||||
}();
|
||||
if (batch_rec_ && gdn_groups_on && te - tb <= 8) {
|
||||
strata::kernels::GdnGroups gg;
|
||||
for (int t = tb; t < te;) {
|
||||
const int first = t;
|
||||
while (t < te && brow_[t] == brow_[first]) ++t;
|
||||
SessionState& sx = slot_ss(first);
|
||||
gg.state[gg.n] = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
|
||||
gg.first[gg.n] = first;
|
||||
gg.ntok[gg.n] = t - first;
|
||||
++gg.n;
|
||||
}
|
||||
strata::kernels::gdn_step_norm_groups(gg, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS,
|
||||
y_, (int) HK, (int) HV, false, cs);
|
||||
} else
|
||||
if (batch_rec_) { // each slot's recurrence over its own proposed-token group
|
||||
for (int t = tb; t < te;) {
|
||||
const int first = t;
|
||||
@@ -1553,6 +1614,35 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
bool streamed = false; // a streamed KV cache keeps the per-row resolve-then-attend order
|
||||
if (batch_rec_ && g_qsa_slots)
|
||||
for (int t = tb; t < te; ++t) streamed = streamed || slot_ss(t).qsa_states[qi].kv_mode == 1;
|
||||
// STRATA_BATCH_ATTN_ROWS=1: the window's rows in ONE launch per step - scores with each row's
|
||||
// own indexer keys, the top-k over all rows (row-independent), attention with each row's own pools -
|
||||
// instead of 3-4 one-row launches per row; the same per-row arithmetic. Not with KV streaming
|
||||
// (qsa_kv_resolve has work per slot then).
|
||||
static const bool attn_rows = [] {
|
||||
const char* v = std::getenv("STRATA_BATCH_ATTN_ROWS");
|
||||
return v != nullptr && std::atoi(v) != 0;
|
||||
}();
|
||||
bool rows_ok = batch_rec_ && attn_rows && te - tb <= strata::kernels::kAttnRowsMax;
|
||||
for (int t = tb; rows_ok && t < te; ++t) rows_ok = slot_ss(t).qsa_states[qi].kv_mode != 1;
|
||||
if (rows_ok) {
|
||||
const int n_rows = te - tb;
|
||||
strata::kernels::QsaScoreRows sr;
|
||||
strata::kernels::QsaAttnPoolsRows pr;
|
||||
sr.n = pr.n = n_rows;
|
||||
for (int t = tb; t < te; ++t) {
|
||||
const QsaState& sx = slot_ss(t).qsa_states[qi];
|
||||
sr.pooled[t - tb] = sx.idx_pooled;
|
||||
sr.dead[t - tb] = sx.idx_dead;
|
||||
pr.p[t - tb] = qsa_attn_pools(sx);
|
||||
}
|
||||
qsa_block_scores_rows(sr, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n_rows, max_blocks_, s,
|
||||
scores_ + (size_t) tb * max_blocks_, cs);
|
||||
qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n_rows, max_blocks_, cap_,
|
||||
s, sel_ + (size_t) tb * cap_, cs);
|
||||
qsa_decode_attn_batch_rows(qcur_ + tb * NH * HD, pr, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount,
|
||||
cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_,
|
||||
attn_ + tb * NH * HD, n_rows, cs);
|
||||
} else
|
||||
if (batch_rec_ && g_qsa_slots && !streamed) {
|
||||
// the rows' block scores, top-k and attention, up to 8 rows per launch. The rows only read
|
||||
// their slots' keys and K/V here and write their own scores/sel/scratch/attn rows, so running
|
||||
@@ -1927,6 +2017,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
}
|
||||
if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head
|
||||
float* hout = hand_out_ + (size_t) hrow0 * HB;
|
||||
if (hflag_out_d_ != nullptr && !batch_rec_) { // the overlapped split: payload + the next stage's flag
|
||||
handoff_publish(hout, R_, (int64_t) T * HC * N, bo_, (int64_t) T * N, inj2_, (int64_t) T * HC, hcount_d_,
|
||||
hflag_out_d_, cs, g_test_drop > 0 ? hdrop_d_ : nullptr); // the test word only with the hook on
|
||||
return true;
|
||||
}
|
||||
copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs);
|
||||
copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs);
|
||||
copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs);
|
||||
@@ -2357,7 +2452,12 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) {
|
||||
*(volatile uint32_t*) h_flag_ = 0;
|
||||
*(volatile uint32_t*) h_flagA_ = 0;
|
||||
*(volatile uint32_t*) h_flagB_ = 0;
|
||||
// the overlapped split: the next stage's graph is launched after this, and must see THIS window's raise
|
||||
if (hflag_out_h_ != nullptr) *(volatile uint32_t*) hflag_out_h_ = 0;
|
||||
if (herr_h_ != nullptr) *(volatile uint32_t*) herr_h_ = 0;
|
||||
if (hdrop_h_ != nullptr) *(volatile uint32_t*) hdrop_h_ = (g_test_drop > 0 && windows + 1 == g_test_drop) ? 1u : 0u;
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
_mm_sfence();
|
||||
last_t_ = T;
|
||||
last_pos0_ = pos0;
|
||||
for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t];
|
||||
@@ -2430,6 +2530,45 @@ bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Verifier::handoff_failed(std::string& err) const {
|
||||
if (herr_h_ == nullptr || *(const volatile uint32_t*) herr_h_ == 0) return false;
|
||||
err = "verify: layer split: the hand-off into layer " + std::to_string(lb_) + " did not arrive within " +
|
||||
std::to_string(g_split_wait_ns / 1000000ull) + " ms (STRATA_SPLIT_WAIT_MS); the window was not used. "
|
||||
"STRATA_SPLIT_OVERLAP=0 runs the serial order";
|
||||
trace_ev("HANDOFF-TIMEOUT", -1, lb_, (int64_t) (g_split_wait_ns / 1000000ull));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Verifier::chain_overlap() const {
|
||||
return next_ != nullptr && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr &&
|
||||
next_->hflag_in_h_ == hflag_out_h_ && next_->device_ != device_ && !next_->ple_stage();
|
||||
}
|
||||
|
||||
bool Verifier::prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string& err) {
|
||||
const OnDevice on_device(device_);
|
||||
prelaunched_ = 0;
|
||||
cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; // #871: the variant the previous stage refreshed
|
||||
if (T < 1 || T > max_t_ || exec_t == nullptr) { err = "verify: prelaunch before the window was captured"; return false; }
|
||||
if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
|
||||
if (pos0 + T > ss_->qsa_states[ss_->qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
|
||||
const Clock::time_point t0 = Clock::now();
|
||||
stage_inputs(T, tokens, pos0);
|
||||
if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8);
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
trace_ev("WINDOW-PRE", -1, -1, pos0 * 16 + T);
|
||||
ms_host += ms_since(t0);
|
||||
if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
|
||||
// 0.1.43: the same gate run() applies before it launches (the adaptive tier's copies land first)
|
||||
if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&
|
||||
!adapt_gate_wait((int32_t) g_->n_layers, err)) return false;
|
||||
const cudaError_t le = cudaGraphLaunch(exec_t, cs_);
|
||||
trace_ev("LAUNCHED", -1, -1, (int64_t) le);
|
||||
if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
|
||||
(void) cudaStreamQuery(cs_);
|
||||
prelaunched_ = T;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out,
|
||||
std::string& err) {
|
||||
#if defined(STRATA_GPU_METAL)
|
||||
@@ -2445,11 +2584,21 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
const ModelGeometry& g = *g_;
|
||||
SessionState& ss = *ss_;
|
||||
if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
|
||||
refresh_ar();
|
||||
// the overlapped split launched this stage's window already: keep the graph variant (#871) chosen for it then,
|
||||
// or this thread would serve the window as the other variant
|
||||
const bool pre = prelaunched_ == T;
|
||||
prelaunched_ = 0;
|
||||
if (!pre) refresh_ar();
|
||||
if (!capture(T, err) || !capture_commit(err)) return false;
|
||||
const bool chain = chain_overlap();
|
||||
if (chain) { // capture the next stage's window here, on this thread, so the helper only stages and launches
|
||||
const OnDevice on_next(next_->device_);
|
||||
next_->refresh_ar(); // #871: the variant its prelaunch and its run() will both use
|
||||
if (!next_->capture(T, err) || !next_->capture_commit(err)) return false;
|
||||
}
|
||||
VDBG("captured; staging\n");
|
||||
const Clock::time_point t0 = Clock::now();
|
||||
if (!staged_) stage_inputs(T, tokens, pos0);
|
||||
if (!pre && !staged_) stage_inputs(T, tokens, pos0);
|
||||
staged_ = false;
|
||||
const bool do_ple = ss.ple.ready() && ple_stage();
|
||||
uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS];
|
||||
@@ -2462,35 +2611,64 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
ss.ple.table->prefetch_rows(ple_rows + t * PLE_N_HEADS);
|
||||
}
|
||||
}
|
||||
if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
trace_ev("WINDOW", -1, -1, pos0 * 16 + T);
|
||||
ms_host += ms_since(t0);
|
||||
VDBG("staged; launching\n");
|
||||
if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
|
||||
// 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first
|
||||
if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&
|
||||
!adapt_gate_wait((int32_t) g.n_layers, err)) return false;
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
// A blocking instrumented launch cannot also serve the graph's CPU doorbells.
|
||||
static const bool threaded_launch = [] {
|
||||
const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH");
|
||||
return value != nullptr && value[0] == '1';
|
||||
}();
|
||||
HostGraphLaunch launch(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch,
|
||||
[this] { (void) release_gpu_waits(5000); });
|
||||
const cudaError_t le = launch.status();
|
||||
#else
|
||||
const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_);
|
||||
std::optional<HostGraphLaunch> launch_o; // (not set when the previous stage launched this window already)
|
||||
#endif
|
||||
trace_ev("LAUNCHED", -1, -1, (int64_t) le);
|
||||
if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
|
||||
if (!pre) {
|
||||
if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
trace_ev("WINDOW", -1, -1, pos0 * 16 + T);
|
||||
ms_host += ms_since(t0);
|
||||
VDBG("staged; launching\n");
|
||||
if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
|
||||
// 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first
|
||||
if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&
|
||||
!adapt_gate_wait((int32_t) g.n_layers, err)) return false;
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
(void) launch.query();
|
||||
// A blocking instrumented launch cannot also serve the graph's CPU doorbells.
|
||||
static const bool threaded_launch = [] {
|
||||
const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH");
|
||||
return value != nullptr && value[0] == '1';
|
||||
}();
|
||||
launch_o.emplace(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch,
|
||||
[this] { (void) release_gpu_waits(5000); });
|
||||
const cudaError_t le = launch_o->status();
|
||||
#else
|
||||
(void) cudaStreamQuery(cs_);
|
||||
const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_);
|
||||
#endif
|
||||
VDBG("launched\n");
|
||||
trace_ev("LAUNCHED", -1, -1, (int64_t) le);
|
||||
if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
(void) launch_o->query();
|
||||
#else
|
||||
(void) cudaStreamQuery(cs_);
|
||||
#endif
|
||||
VDBG("launched\n");
|
||||
}
|
||||
// The overlapped split: the next stage's window is staged and launched on a helper thread while this thread
|
||||
// serves this stage's layers; its graph waits on the GPU for this stage's hand-off flag. The guard joins the
|
||||
// helper on every return, and on an early return (an error after the launch) releases the next stage's GPU
|
||||
// waits so no spin kernel outlives the window (#267).
|
||||
struct NextLaunch {
|
||||
Verifier* next = nullptr;
|
||||
std::thread th;
|
||||
bool ok = true;
|
||||
bool handed = false;
|
||||
std::string err;
|
||||
bool join(std::string& e) {
|
||||
if (th.joinable()) th.join();
|
||||
if (!ok) e = err;
|
||||
return ok;
|
||||
}
|
||||
~NextLaunch() {
|
||||
if (th.joinable()) th.join();
|
||||
if (next != nullptr && !handed) (void) next->release_gpu_waits(5000);
|
||||
}
|
||||
} nl;
|
||||
if (chain) {
|
||||
nl.next = next_;
|
||||
nl.th = std::thread([&nl, T, tokens, pos0] { nl.ok = nl.next->prelaunch(T, tokens, pos0, nl.err); });
|
||||
}
|
||||
volatile uint32_t* const seq = h_seq_;
|
||||
volatile uint32_t* const flag = h_flag_;
|
||||
const int G = groups_[T] > 0 ? groups_[T] : 1;
|
||||
@@ -2524,7 +2702,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
if (now - last_flush > std::chrono::microseconds(2000)) {
|
||||
last_flush = now;
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
const cudaError_t q = launch.query();
|
||||
const cudaError_t q = launch_o ? launch_o->query() : cudaStreamQuery(cs_);
|
||||
#else
|
||||
const cudaError_t q = cudaStreamQuery(cs_);
|
||||
#endif
|
||||
@@ -2539,7 +2717,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
if (now - a > std::chrono::seconds(20)) {
|
||||
// #267: the caller ends the engine; no spin kernel may outlive it
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
trace_ev("TIMEOUT", k, l, (int64_t) launch.query());
|
||||
trace_ev("TIMEOUT", k, l, (int64_t) (launch_o ? launch_o->query() : cudaStreamQuery(cs_)));
|
||||
#else
|
||||
trace_ev("TIMEOUT", k, l, (int64_t) cudaStreamQuery(cs_));
|
||||
#endif
|
||||
@@ -2601,6 +2779,31 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
ms_pool += ms_since(b);
|
||||
}
|
||||
// (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own)
|
||||
if (chain) {
|
||||
// The overlapped split: no host sync between the stages. The next stage's GPU starts on this stage's flag;
|
||||
// this thread goes straight to serving the next stage's layers, and syncs this stage once the chain is done.
|
||||
if (!nl.join(err)) return false;
|
||||
nl.handed = true;
|
||||
++windows;
|
||||
const bool ok = next_->run(T, tokens, pos0, pool, next_user_, out, err);
|
||||
const OnDevice back(device_);
|
||||
const cudaError_t se = cudaStreamSynchronize(cs_);
|
||||
if (copy_used_) {
|
||||
cudaStreamSynchronize(copy_);
|
||||
copy_used_ = false;
|
||||
}
|
||||
if (!ok) return false;
|
||||
if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
|
||||
if (handoff_failed(err)) return false; // a middle stage of three or more: its own hand-in
|
||||
if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871, as below
|
||||
*(volatile uint32_t*) h_plan_err_ = 0;
|
||||
err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)";
|
||||
return false;
|
||||
}
|
||||
commit_pending_ = false;
|
||||
if (prof_on_ && G == 1) collect_profile();
|
||||
return true;
|
||||
}
|
||||
progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);
|
||||
// #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall
|
||||
// watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no
|
||||
@@ -2608,7 +2811,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
// itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver
|
||||
// beside the expert workers).
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
const cudaError_t launch_result = launch.finish();
|
||||
const cudaError_t launch_result = launch_o ? launch_o->finish() : cudaSuccess;
|
||||
if (launch_result != cudaSuccess) {
|
||||
err = std::string("verify: launch: ") + cudaGetErrorString(launch_result);
|
||||
return false;
|
||||
@@ -2618,6 +2821,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
||||
const cudaError_t se = cudaStreamSynchronize(cs_);
|
||||
trace_ev("SYNCED", -1, -1, (int64_t) se);
|
||||
if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
|
||||
if (handoff_failed(err)) return false; // a stale hand-off: nothing of this window is used
|
||||
if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole
|
||||
*(volatile uint32_t*) h_plan_err_ = 0;
|
||||
err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)";
|
||||
@@ -3014,6 +3218,15 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri
|
||||
if (!is_qsa_layer(g, l)) {
|
||||
const WeightRef* wnm = need(v, "ssm_norm.weight", err);
|
||||
if (!wnm) { ok = false; break; }
|
||||
// STRATA_BATCH_GDN_GROUPS=1: one-row groups (no --batch-mtp proposals) commit their recurrence
|
||||
// in one launch for all slots; the conv commits stay per slot
|
||||
static const bool gdn_groups_on = [] {
|
||||
const char* v = std::getenv("STRATA_BATCH_GDN_GROUPS");
|
||||
return v != nullptr && std::atoi(v) != 0;
|
||||
}();
|
||||
bool one_row = S <= 8;
|
||||
for (int t = 1; one_row && t < S; ++t) one_row = rows[t] != rows[t - 1];
|
||||
strata::kernels::GdnGroups gg;
|
||||
for (int t = 0; t < S;) {
|
||||
const int first = t;
|
||||
while (t < S && rows[t] == rows[first]) ++t;
|
||||
@@ -3023,6 +3236,14 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri
|
||||
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
|
||||
gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C,
|
||||
(int) C, keep, cs_);
|
||||
if (gdn_groups_on && one_row) {
|
||||
gg.state[gg.n] = state;
|
||||
gg.keep[gg.n] = keep;
|
||||
gg.first[gg.n] = first;
|
||||
gg.ntok[gg.n] = 1;
|
||||
++gg.n;
|
||||
continue;
|
||||
}
|
||||
gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C,
|
||||
gate_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,
|
||||
beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,
|
||||
@@ -3031,6 +3252,11 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri
|
||||
(int) HV, t - first, keep, cs_,
|
||||
t - first > 1 ? t - first : 0); // a 1-row group keeps the 0.1.39 kernel
|
||||
}
|
||||
if (gg.n > 0)
|
||||
gdn_step_norm_groups(gg, h_L_ + (size_t) gdn_index * MT * C, (int) C,
|
||||
gate_L_ + (size_t) gdn_index * MT * HV, beta_L_ + (size_t) gdn_index * MT * HV,
|
||||
z_, (const float*) wnm->data, EPS, y_dummy_, (int) g.ssm_k_heads, (int) HV, true,
|
||||
cs_);
|
||||
++gdn_index;
|
||||
} else {
|
||||
const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
|
||||
@@ -3399,52 +3625,38 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_
|
||||
sx.ple_prev[0] = sx.ple_prev[1];
|
||||
sx.ple_prev[1] = tokens[t];
|
||||
}
|
||||
b_running_ = true;
|
||||
b_k_ = 0;
|
||||
b_steps_ = le_ - lb_;
|
||||
b_last_ = Clock::now();
|
||||
ring_now();
|
||||
b_running_.store(true, std::memory_order_release); // last: an external server reads the rest after it
|
||||
return true;
|
||||
}
|
||||
|
||||
int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
|
||||
if (!b_running_) return 1;
|
||||
const OnDevice on_device(device_);
|
||||
int Verifier::batch_serve(PoolMultiFn pool, void* user) {
|
||||
if (!b_running_.load(std::memory_order_acquire)) return 1;
|
||||
volatile uint32_t* const seq = h_seq_;
|
||||
const int S = last_t_;
|
||||
// #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer,
|
||||
// so the poll is just "has the graph finished" - except the PLE flag, which the graph's first wait reads and
|
||||
// only the host can raise (the same raise run_slot_rows makes). Per-window (ar_on): with a loan in flight the
|
||||
// doorbell graph needs the per-layer service below.
|
||||
// except the PLE flag, which the graph's first wait reads and only the host can raise (the same raise
|
||||
// run_slot_rows makes). Per-window (ar_on): with a loan in flight the doorbell graph needs the per-layer service.
|
||||
if (ar_on() && ss_->ple.ready() && ple_stage()) {
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
_mm_sfence();
|
||||
*h_flag_ = 1;
|
||||
}
|
||||
while (!ar_on() && b_k_ < b_steps_) {
|
||||
const uint32_t want = (uint32_t) (b_k_ + 1);
|
||||
if (*seq < want) {
|
||||
const auto now = Clock::now();
|
||||
if (now - b_last_ > std::chrono::milliseconds(2)) {
|
||||
const cudaError_t q = cudaStreamQuery(cs_);
|
||||
if (q != cudaErrorNotReady && *seq < want) {
|
||||
err = "verify batch: layer " + std::to_string(lb_ + b_k_) + " never rang (" +
|
||||
(q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
|
||||
b_running_ = false;
|
||||
return -1;
|
||||
}
|
||||
if (now - b_last_ > std::chrono::seconds(20)) {
|
||||
err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) + released_note(release_gpu_waits(5000));
|
||||
b_running_ = false;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
for (;;) {
|
||||
// the window's row count is read after the served-layer count: with external serving the window this call
|
||||
// began on can have finished and the next one been launched meanwhile, and batch_launch writes its rows
|
||||
// (stage_batch) before it resets b_k_, so a count that is the new window's comes with the new rows
|
||||
const int64_t k = b_k_.load(std::memory_order_acquire);
|
||||
if (ar_on() || k >= b_steps_) break;
|
||||
const uint32_t want = (uint32_t) (k + 1);
|
||||
if (*seq < want) return 0;
|
||||
const int S = last_t_;
|
||||
const Clock::time_point b = Clock::now();
|
||||
cur_layer_ = want - 1;
|
||||
set_plan_slot(0);
|
||||
if (remote_opt_) remote_opt_->begin(h_w_, 0, S);
|
||||
if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + b_k_);
|
||||
if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + k);
|
||||
if (remote_opt_) remote_opt_->end();
|
||||
progress_tick();
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
@@ -3461,8 +3673,64 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
|
||||
}
|
||||
*(volatile uint32_t*) h_flag_ = want;
|
||||
ms_pool += ms_since(b);
|
||||
b_last_ = Clock::now();
|
||||
++b_k_;
|
||||
ring_now();
|
||||
b_k_.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
|
||||
if (!b_running_) return 1;
|
||||
// set_external_serve: another thread serves the doorbells (batch_serve) and this one only checks for a window that
|
||||
// will not finish, as below: its graph ended (or failed) with a layer still to ring, or no layer rang for 20 s.
|
||||
// The stream query can wait for the driver's lock while a read's call holds it; the doorbells go on meanwhile.
|
||||
// The served count is read before the query and the ring count after it: a layer served in between rang first.
|
||||
if (ext_serve_.load(std::memory_order_acquire) && !ar_on()) {
|
||||
const int64_t k = b_k_.load(std::memory_order_acquire);
|
||||
if (k < b_steps_) {
|
||||
const auto now = Clock::now();
|
||||
if (now - last_ring() <= std::chrono::milliseconds(2) || now - ext_checked_ < std::chrono::milliseconds(1))
|
||||
return 0;
|
||||
ext_checked_ = now; // (at most one query a millisecond: pump calls this in a loop)
|
||||
const OnDevice on_device(device_);
|
||||
const cudaError_t q = cudaStreamQuery(cs_);
|
||||
if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < (uint32_t) (k + 1)) {
|
||||
err = "verify batch: layer " + std::to_string(lb_ + k) + " never rang (" +
|
||||
(q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
|
||||
b_running_ = false;
|
||||
return -1;
|
||||
}
|
||||
if (now - last_ring() > std::chrono::seconds(20)) {
|
||||
err = "verify batch: timed out at layer " + std::to_string(lb_ + k) +
|
||||
released_note(release_gpu_waits(5000));
|
||||
b_running_ = false;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
const OnDevice on_device(device_);
|
||||
const int S = last_t_;
|
||||
// the layers that have rung so far (batch_serve); with one still to ring: did the graph finish without it, or
|
||||
// has it waited too long?
|
||||
if (!batch_serve(pool, user)) {
|
||||
const auto now = Clock::now();
|
||||
if (now - last_ring() > std::chrono::milliseconds(2)) {
|
||||
const cudaError_t q = cudaStreamQuery(cs_);
|
||||
if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < (uint32_t) (b_k_ + 1)) {
|
||||
err = "verify batch: layer " + std::to_string(lb_ + b_k_) + " never rang (" +
|
||||
(q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
|
||||
b_running_ = false;
|
||||
return -1;
|
||||
}
|
||||
if (now - last_ring() > std::chrono::seconds(20)) {
|
||||
err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) +
|
||||
released_note(release_gpu_waits(5000));
|
||||
b_running_ = false;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const cudaError_t q = cudaStreamQuery(cs_);
|
||||
if (q == cudaErrorNotReady) return 0;
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
// src/kernels/batch_rows_parity.cpp - the batch window's one-launch-for-all-rows kernels (#2234, STRATA_BATCH_ATTN_ROWS /
|
||||
// STRATA_BATCH_GDN_GROUPS) against the per-row launches they replace, bitwise (GPU, synthetic, no model).
|
||||
//
|
||||
// 1. qsa_block_scores_rows == qsa_block_scores, one call per row, each row with its OWN indexer keys;
|
||||
// 2. qsa_decode_attn_batch_rows == qsa_decode_attn_batch, one call per row, each row over its OWN K/V pools
|
||||
// (int8 codes + scales, and fp16);
|
||||
// 3. gdn_step_norm_groups == gdn_step_norm_multi, one call per slot group, in the window (all outputs, the state
|
||||
// untouched) and in the 1-row commit (the state written after `keep` tokens).
|
||||
// Every case compares with memcmp, not a tolerance. Usage: batch_rows_parity
|
||||
#include "strata/kernels/qsa.hpp"
|
||||
#include "strata/kernels/qsa_decode_attn.hpp"
|
||||
#include "strata/kernels/qsa_select.hpp"
|
||||
#include "strata/kernels/verify_kernels.hpp"
|
||||
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace k = strata::kernels;
|
||||
|
||||
namespace {
|
||||
void ck(cudaError_t e, const char* w) {
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
|
||||
}
|
||||
template <typename T> T* up(const std::vector<T>& h) {
|
||||
T* d = nullptr;
|
||||
ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
|
||||
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
|
||||
return d;
|
||||
}
|
||||
template <typename T> std::vector<T> down(const T* d, size_t n) {
|
||||
std::vector<T> h(n);
|
||||
ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download");
|
||||
return h;
|
||||
}
|
||||
uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
|
||||
|
||||
int bad = 0;
|
||||
void report(const char* what, bool same) {
|
||||
std::printf(" %-64s %s\n", what, same ? "bitwise" : "*** DIFFERS ***");
|
||||
if (!same) ++bad;
|
||||
}
|
||||
|
||||
// ---- 1. the block scores ----
|
||||
void scores_case(int rows) {
|
||||
const k::QsaShapes s = k::qsa_real_shapes();
|
||||
const int64_t max_blocks = 3000;
|
||||
std::mt19937 rng(11 + rows);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
k::QsaScoreRows sr;
|
||||
sr.n = rows;
|
||||
std::vector<const float*> pooled(rows), dead(rows);
|
||||
std::vector<float> q((size_t) rows * s.idx_n_head * s.idx_dim);
|
||||
for (auto& x : q) x = nd(rng);
|
||||
std::vector<int32_t> steps((size_t) rows * k::kStepCount);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
std::vector<float> p((size_t) max_blocks * s.idx_dim), d((size_t) s.idx_dim);
|
||||
for (auto& x : p) x = nd(rng);
|
||||
for (auto& x : d) x = nd(rng);
|
||||
pooled[r] = up(p);
|
||||
dead[r] = up(d);
|
||||
sr.pooled[r] = pooled[r];
|
||||
sr.dead[r] = dead[r];
|
||||
const int64_t pos = 700 + 997 * r + (r % 3) * 5; // different lengths, and an incomplete block at the tail
|
||||
steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) pos;
|
||||
steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) (pos + 1);
|
||||
steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
|
||||
steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
|
||||
}
|
||||
const float* d_q = up(q);
|
||||
const int32_t* d_steps = up(steps);
|
||||
float *d_rows = nullptr, *d_ref = nullptr;
|
||||
const size_t n = (size_t) rows * max_blocks;
|
||||
ck(cudaMalloc(&d_rows, n * 4), "malloc");
|
||||
ck(cudaMalloc(&d_ref, n * 4), "malloc");
|
||||
ck(cudaMemset(d_rows, 0, n * 4), "memset");
|
||||
ck(cudaMemset(d_ref, 0, n * 4), "memset");
|
||||
k::qsa_block_scores_rows(sr, d_q, d_steps, rows, max_blocks, s, d_rows, nullptr);
|
||||
for (int r = 0; r < rows; ++r)
|
||||
k::qsa_block_scores(pooled[r], dead[r], d_q + (size_t) r * s.idx_n_head * s.idx_dim, d_steps + (size_t) r * k::kStepCount, 1,
|
||||
max_blocks, s, d_ref + (size_t) r * max_blocks, nullptr);
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
const std::vector<float> a = down(d_rows, n), b = down(d_ref, n);
|
||||
char name[96];
|
||||
std::snprintf(name, sizeof name, "qsa_block_scores_rows, %d rows (own keys each)", rows);
|
||||
report(name, std::memcmp(a.data(), b.data(), n * 4) == 0);
|
||||
// the window selects with one top-k launch over all rows (row-independent) where the per-row path ran one per row
|
||||
const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);
|
||||
int32_t *i_rows = nullptr, *i_ref = nullptr;
|
||||
ck(cudaMalloc(&i_rows, (size_t) rows * cap * 4), "malloc");
|
||||
ck(cudaMalloc(&i_ref, (size_t) rows * cap * 4), "malloc");
|
||||
ck(cudaMemset(i_rows, 0, (size_t) rows * cap * 4), "memset");
|
||||
ck(cudaMemset(i_ref, 0, (size_t) rows * cap * 4), "memset");
|
||||
k::qsa_block_topk(d_ref, d_steps, rows, max_blocks, cap, s, i_rows, nullptr);
|
||||
for (int r = 0; r < rows; ++r)
|
||||
k::qsa_block_topk(d_ref + (size_t) r * max_blocks, d_steps + (size_t) r * k::kStepCount, 1, max_blocks, cap, s,
|
||||
i_ref + (size_t) r * cap, nullptr);
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
const std::vector<int32_t> ta = down(i_rows, (size_t) rows * cap), tb = down(i_ref, (size_t) rows * cap);
|
||||
bool tsame = true;
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
const int64_t w = steps[(size_t) r * k::kStepCount + k::kStepWidth];
|
||||
tsame = tsame && std::memcmp(ta.data() + (size_t) r * cap, tb.data() + (size_t) r * cap, (size_t) w * 4) == 0;
|
||||
}
|
||||
std::snprintf(name, sizeof name, "qsa_block_topk over %d rows == one call per row", rows);
|
||||
report(name, tsame);
|
||||
}
|
||||
|
||||
// ---- 2. the decode attention ----
|
||||
void attn_case(int rows, bool int8) {
|
||||
const k::QsaShapes s = k::qsa_real_shapes();
|
||||
const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
|
||||
const int64_t ctx_max = 5000, pages = (ctx_max + PS - 1) / PS, prow = pages * NKV * PS;
|
||||
const int64_t cap = k::qsa_selection_width(ctx_max, s);
|
||||
std::mt19937 rng(23 + rows + int8);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> code(-127, 127);
|
||||
std::uniform_real_distribution<float> sc(0.005f, 0.03f);
|
||||
k::QsaAttnPoolsRows pr;
|
||||
pr.n = rows;
|
||||
std::vector<float> q((size_t) rows * NH * HD);
|
||||
for (auto& x : q) x = nd(rng) * 2.0f;
|
||||
std::vector<int32_t> ids((size_t) rows * cap, 0), steps((size_t) rows * k::kStepCount, 0);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
k::QsaAttnPools& pl = pr.p[r];
|
||||
if (int8) {
|
||||
std::vector<int8_t> kq((size_t) prow * HD), vq((size_t) prow * HD);
|
||||
std::vector<uint16_t> ks((size_t) prow * (HD / 64)), vs(ks.size());
|
||||
for (auto& x : kq) x = (int8_t) code(rng);
|
||||
for (auto& x : vq) x = (int8_t) code(rng);
|
||||
for (auto& x : ks) x = f2h(sc(rng));
|
||||
for (auto& x : vs) x = f2h(sc(rng));
|
||||
pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs);
|
||||
} else {
|
||||
std::vector<uint16_t> kh((size_t) prow * HD), vh(kh.size());
|
||||
for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
|
||||
for (auto& x : vh) x = f2h(nd(rng));
|
||||
pl.k_pool = up(kh); pl.v_pool = up(vh);
|
||||
}
|
||||
std::vector<int32_t> table(pages);
|
||||
for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
|
||||
std::shuffle(table.begin(), table.end(), rng); // each row's pool has its own page order
|
||||
pl.page_table = up(table);
|
||||
const int64_t nkv = 900 + 641 * r + (r % 2) * 3;
|
||||
const int64_t w = k::qsa_selection_width(nkv, s);
|
||||
std::vector<int32_t> all((size_t) nkv);
|
||||
for (int64_t c = 0; c < nkv; ++c) all[c] = (int32_t) c;
|
||||
std::shuffle(all.begin(), all.end(), rng);
|
||||
std::sort(all.begin(), all.begin() + w);
|
||||
std::copy(all.begin(), all.begin() + w, ids.begin() + (size_t) r * cap);
|
||||
steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) (nkv - 1);
|
||||
steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) nkv;
|
||||
steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) (nkv / s.idx_block);
|
||||
steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) w;
|
||||
}
|
||||
const float* d_q = up(q);
|
||||
const int32_t* d_ids = up(ids);
|
||||
const int32_t* d_steps = up(steps);
|
||||
const int64_t scr = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s);
|
||||
float *scratch = nullptr, *d_rows = nullptr, *d_ref = nullptr;
|
||||
ck(cudaMalloc(&scratch, (size_t) rows * scr * 4), "malloc");
|
||||
const size_t n = (size_t) rows * NH * HD;
|
||||
ck(cudaMalloc(&d_rows, n * 4), "malloc");
|
||||
ck(cudaMalloc(&d_ref, n * 4), "malloc");
|
||||
ck(cudaMemset(d_rows, 0, n * 4), "memset");
|
||||
ck(cudaMemset(d_ref, 0, n * 4), "memset");
|
||||
k::qsa_decode_attn_batch_rows(d_q, pr, d_ids, d_steps, cap, s, scratch, d_rows, rows, nullptr);
|
||||
for (int r = 0; r < rows; ++r)
|
||||
k::qsa_decode_attn_batch(d_q + (size_t) r * NH * HD, pr.p[r], d_ids + (size_t) r * cap, d_steps + (size_t) r * k::kStepCount, cap,
|
||||
s, scratch + (size_t) r * scr, d_ref + (size_t) r * NH * HD, 1, nullptr);
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
const std::vector<float> a = down(d_rows, n), b = down(d_ref, n);
|
||||
char name[96];
|
||||
std::snprintf(name, sizeof name, "qsa_decode_attn_batch_rows, %d rows, %s pools (own pools each)", rows, int8 ? "int8" : "fp16");
|
||||
report(name, std::memcmp(a.data(), b.data(), n * 4) == 0);
|
||||
}
|
||||
|
||||
// ---- 3. the GDN recurrence ----
|
||||
void gdn_case(const std::vector<int>& ntok, bool commit) {
|
||||
const int S = 128, h_k = 16, h_v = 48; // the artifact's geometry
|
||||
const int qk = S * h_k, C = 2 * qk + S * h_v, vd = S * h_v;
|
||||
const float eps = 1e-6f;
|
||||
int T = 0;
|
||||
for (int n : ntok) T += n;
|
||||
const int G = (int) ntok.size();
|
||||
std::mt19937 rng(31 + T * 7 + G + commit);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::vector<float> h((size_t) T * C), gate((size_t) T * h_v), beta((size_t) T * h_v), z((size_t) T * vd), gamma(S);
|
||||
for (auto& v : h) v = nd(rng) * 0.1f;
|
||||
for (auto& v : gate) v = -(0.5f + 3.0f * (float) (rng() % 100) / 100.0f);
|
||||
for (auto& v : beta) v = (float) (rng() % 100) / 100.0f;
|
||||
for (auto& v : z) v = nd(rng);
|
||||
for (auto& v : gamma) v = 1.0f + 0.1f * nd(rng);
|
||||
const size_t st_n = (size_t) S * h_v * S;
|
||||
std::vector<std::vector<float>> st0(G);
|
||||
std::vector<float*> st_g(G), st_r(G);
|
||||
std::vector<int32_t*> keep(G);
|
||||
k::GdnGroups gg;
|
||||
gg.n = G;
|
||||
int first = 0;
|
||||
for (int i = 0; i < G; ++i) {
|
||||
st0[i].resize(st_n);
|
||||
for (auto& v : st0[i]) v = nd(rng) * 0.1f;
|
||||
st_g[i] = up(st0[i]);
|
||||
st_r[i] = up(st0[i]);
|
||||
const int32_t kp = commit ? ntok[i] : 0; // a commit group keeps all of its rows here
|
||||
keep[i] = up(std::vector<int32_t>{kp});
|
||||
gg.state[i] = st_g[i];
|
||||
gg.keep[i] = commit ? keep[i] : nullptr;
|
||||
gg.first[i] = first;
|
||||
gg.ntok[i] = ntok[i];
|
||||
first += ntok[i];
|
||||
}
|
||||
const float* d_h = up(h);
|
||||
const float* d_gate = up(gate);
|
||||
const float* d_beta = up(beta);
|
||||
const float* d_z = up(z);
|
||||
const float* d_gm = up(gamma);
|
||||
float *d_y = nullptr, *d_yr = nullptr;
|
||||
ck(cudaMalloc(&d_y, (size_t) T * vd * 4), "malloc");
|
||||
ck(cudaMalloc(&d_yr, (size_t) T * vd * 4), "malloc");
|
||||
ck(cudaMemset(d_y, 0, (size_t) T * vd * 4), "memset");
|
||||
ck(cudaMemset(d_yr, 0, (size_t) T * vd * 4), "memset");
|
||||
k::gdn_step_norm_groups(gg, d_h, C, d_gate, d_beta, d_z, d_gm, eps, d_y, h_k, h_v, commit, nullptr);
|
||||
for (int i = 0; i < G; ++i) {
|
||||
const int f = gg.first[i];
|
||||
// the engine's per-slot call: a window group runs its rows with all outputs; a commit group (1 row) keeps them
|
||||
k::gdn_step_norm_multi(st_r[i], d_h + (size_t) f * C, C, d_gate + (size_t) f * h_v, d_beta + (size_t) f * h_v,
|
||||
d_z + (size_t) f * vd, d_gm, eps, d_yr + (size_t) f * vd, h_k, h_v, ntok[i],
|
||||
commit ? keep[i] : nullptr, nullptr, 0);
|
||||
}
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
bool same = true;
|
||||
for (int i = 0; i < G; ++i) {
|
||||
const std::vector<float> a = down(st_g[i], st_n), b = down(st_r[i], st_n);
|
||||
same = same && std::memcmp(a.data(), b.data(), st_n * 4) == 0;
|
||||
if (!commit) same = same && std::memcmp(a.data(), st0[i].data(), st_n * 4) == 0; // a window leaves the state alone
|
||||
}
|
||||
if (!commit) {
|
||||
const std::vector<float> a = down(d_y, (size_t) T * vd), b = down(d_yr, (size_t) T * vd);
|
||||
same = same && std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
|
||||
}
|
||||
char name[96], rows[64] = "";
|
||||
for (int i = 0; i < G && i < 8; ++i) std::snprintf(rows + std::strlen(rows), sizeof rows - std::strlen(rows), "%s%d", i ? "," : "", ntok[i]);
|
||||
std::snprintf(name, sizeof name, "gdn_step_norm_groups %s, groups of %s rows", commit ? "commit" : "window", rows);
|
||||
report(name, same);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
std::printf("batch rows parity (#2234 kernels against the per-row launches)\n");
|
||||
for (int r : {1, 2, 4, 8}) scores_case(r);
|
||||
for (int r : {1, 3, 8}) {
|
||||
attn_case(r, true);
|
||||
attn_case(r, false);
|
||||
}
|
||||
gdn_case({1}, false);
|
||||
gdn_case({1, 1, 1, 1}, false);
|
||||
gdn_case({2, 2, 2, 2}, false);
|
||||
gdn_case({1, 3, 2, 1, 1}, false);
|
||||
gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, false);
|
||||
gdn_case({1}, true);
|
||||
gdn_case({1, 1, 1, 1}, true);
|
||||
gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, true);
|
||||
std::printf("%s\n", bad ? "batch_rows_parity: FAILED" : "batch_rows_parity: ok");
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
@@ -117,6 +117,8 @@ __device__ __forceinline__ int reduce12_head_of_lane(int lane) {
|
||||
}
|
||||
|
||||
// The chunk kernel's body; `p` is the query's KV pools (the call's one set, or blockIdx.z's slot's set).
|
||||
// (the body is a device function so the batch window's rows kernel below can run it over each query's own pools without
|
||||
// the default kernel's signature, or the function-pointer types the pre-sm_75 / HIP selections build, changing)
|
||||
template <int KV_MODE, bool LANE_CELL, bool QUERY_SWIZZLE, bool REDUCE12>
|
||||
__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids, const int32_t* __restrict__ step,
|
||||
@@ -309,6 +311,20 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float*
|
||||
part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
|
||||
}
|
||||
|
||||
// Batch windows: query blockIdx.z attends over its own slot's pools (rows.p[z]); the default kernel otherwise.
|
||||
template <int KV_MODE>
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_rows_kernel(const float* __restrict__ q, QsaAttnPoolsRows rows,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ step, int n_kv_heads,
|
||||
int page_size, float scale,
|
||||
float* __restrict__ part_acc,
|
||||
float* __restrict__ part_m,
|
||||
float* __restrict__ part_l, int n_chunks, int cap,
|
||||
long long scratch_stride) {
|
||||
attn_chunk_body<KV_MODE, false, false, false>(q, rows.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale,
|
||||
part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
|
||||
}
|
||||
|
||||
// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
|
||||
// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It
|
||||
// uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the
|
||||
@@ -966,6 +982,58 @@ bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const
|
||||
return true;
|
||||
}
|
||||
|
||||
void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, const int32_t* ids, const int32_t* steps,
|
||||
int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
|
||||
if (n_q <= 0) return;
|
||||
const QsaAttnPools& pools = rows.p[0];
|
||||
if (rows.n != n_q || n_q > kAttnRowsMax || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 ||
|
||||
!scratch || !ids || !steps) {
|
||||
std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n");
|
||||
std::exit(1);
|
||||
}
|
||||
const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
|
||||
: (pools.k_q != nullptr ? 1 : 0));
|
||||
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
|
||||
const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
|
||||
float* part_acc = scratch;
|
||||
float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
|
||||
float* part_l = part_m + (size_t) n_chunks * s.n_head;
|
||||
const float scale = 1.0f / sqrtf((float) HD);
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
// The plain kernel is what qsa_decode_attn_batch runs unless one of its variants is on (lane-cell scoring, the
|
||||
// pre-sm_75 / gfx103x kernel, the gfx906 swizzle): there each row goes through that call, one launch per row.
|
||||
static const bool lane_cell_rows = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
|
||||
bool per_row = lane_cell_rows;
|
||||
#if defined(STRATA_ATTN_PRE75_BUILT)
|
||||
per_row = per_row || pre75_attn();
|
||||
#endif
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
per_row = true;
|
||||
#endif
|
||||
if (per_row) {
|
||||
for (int64_t r = 0; r < n_q; ++r)
|
||||
qsa_decode_attn_batch(q + (size_t) r * s.n_head * HD, rows.p[r], ids + (size_t) r * cap,
|
||||
steps + (size_t) r * kStepCount, cap, s, scratch + (size_t) r * stride,
|
||||
attn + (size_t) r * s.n_head * HD, 1, stream);
|
||||
return;
|
||||
}
|
||||
#define STRATA_ATTN_ROWS(M) attn_chunk_rows_kernel<M><<<grid, THREADS, 0, st>>>(q, rows, ids, steps, (int) s.n_head_kv, \
|
||||
(int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
|
||||
if (kv_mode == 3) STRATA_ATTN_ROWS(3);
|
||||
else if (kv_mode == 2) STRATA_ATTN_ROWS(2);
|
||||
else if (kv_mode == 1) STRATA_ATTN_ROWS(1);
|
||||
else STRATA_ATTN_ROWS(0);
|
||||
#undef STRATA_ATTN_ROWS
|
||||
launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head,
|
||||
(unsigned) n_q, st);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "qsa_decode_attn_batch_rows: %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
|
||||
const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
|
||||
return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
|
||||
|
||||
@@ -835,7 +835,8 @@ __device__ __forceinline__ void block_scores_multi_body(const float* __restrict_
|
||||
const float* __restrict__ dead,
|
||||
const float* __restrict__ q_idx,
|
||||
const int32_t* __restrict__ steps, int nq, int64_t max_blocks,
|
||||
float* __restrict__ out, bool early_exit) {
|
||||
float* __restrict__ out, bool early_exit,
|
||||
const QsaScoreRows& srow) {
|
||||
__shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM];
|
||||
__shared__ int64_t s_nkv[MQ], s_nbid[MQ];
|
||||
if (!early_exit)
|
||||
@@ -858,12 +859,16 @@ __device__ __forceinline__ void block_scores_multi_body(const float* __restrict_
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
|
||||
for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
|
||||
const float4 kp = *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
|
||||
const float4 kd = *reinterpret_cast<const float4*>(dead + lane * 4);
|
||||
// srow.n > 0: each query reads its own sequence's keys; else one set of keys for every query
|
||||
const bool own = srow.n > 0;
|
||||
const float4 kp = own ? float4{} : *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
|
||||
const float4 kd = own ? float4{} : *reinterpret_cast<const float4*>(dead + lane * 4);
|
||||
for (int qi = 0; qi < nq; ++qi) {
|
||||
const int64_t n_bid = s_nbid[qi];
|
||||
if (b > n_bid) continue;
|
||||
const float4 k4 = (b == n_bid) ? kd : kp;
|
||||
const float4 k4 = !own ? ((b == n_bid) ? kd : kp)
|
||||
: (b == n_bid) ? *reinterpret_cast<const float4*>(srow.dead[qi] + lane * 4)
|
||||
: *reinterpret_cast<const float4*>(srow.pooled[qi] + b * IDX_DIM + lane * 4);
|
||||
const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
|
||||
float score = 0.0f;
|
||||
#pragma unroll
|
||||
@@ -887,8 +892,8 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co
|
||||
const float* __restrict__ q_idx,
|
||||
const int32_t* __restrict__ steps, int nq,
|
||||
int64_t max_blocks, float* __restrict__ out,
|
||||
bool early_exit) {
|
||||
block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit);
|
||||
bool early_exit, QsaScoreRows srow = {}) {
|
||||
block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit, srow);
|
||||
}
|
||||
|
||||
// Queries of different slots, each with its own indexer keys: blockIdx.y is the query, and its CTAs run exactly the
|
||||
@@ -910,7 +915,8 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(Sc
|
||||
for (unsigned i = 1; i < MQ; ++i)
|
||||
if (z == i) { pooled = keys.pooled[i]; dead = keys.dead[i]; }
|
||||
block_scores_multi_body(pooled, dead, q_idx + (size_t) z * IDX_HEADS * IDX_DIM,
|
||||
steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit);
|
||||
steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit,
|
||||
QsaScoreRows{});
|
||||
}
|
||||
|
||||
// QSAROWS (docs/QSAROWS.md, STRATA_QSA_ROWS=1): block_scores_multi_kernel's work for NQ <= 4 queries with less issue
|
||||
@@ -1284,6 +1290,20 @@ bool qsa_block_scores_rows(const float* pooled, const float* dead, const float*
|
||||
return true;
|
||||
}
|
||||
|
||||
void qsa_block_scores_rows(const QsaScoreRows& rows, const float* q_idx, const int32_t* steps, int64_t nq,
|
||||
int64_t max_blocks, const QsaShapes& s, float* scores, void* stream) {
|
||||
if (nq <= 0) return;
|
||||
if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > MQ || rows.n != nq) {
|
||||
std::fprintf(stderr, "qsa_block_scores_rows: unsupported geometry\n");
|
||||
std::exit(1);
|
||||
}
|
||||
static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
|
||||
block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(nullptr, nullptr, q_idx, steps, (int) nq,
|
||||
max_blocks, scores, early, rows);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_rows: %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
}
|
||||
|
||||
bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
|
||||
int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
|
||||
if (nq <= 0) return true;
|
||||
|
||||
@@ -291,7 +291,18 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re
|
||||
const float* __restrict__ gamma, float eps,
|
||||
float* __restrict__ y, int h_k, int h_v, int T,
|
||||
const int32_t* __restrict__ n_keep, int t_out_begin,
|
||||
GdnQ81* __restrict__ xq) {
|
||||
GdnQ81* __restrict__ xq, GdnGroups grp = {}) {
|
||||
if (grp.n > 0) { // group blockIdx.y - its slot's state and its rows of the window's buffers
|
||||
const int gi = blockIdx.y, f = grp.first[gi];
|
||||
state = grp.state[gi];
|
||||
hbuf += (size_t) f * C;
|
||||
gate += (size_t) f * h_v;
|
||||
beta += (size_t) f * h_v;
|
||||
z += (size_t) f * S * h_v;
|
||||
y += (size_t) f * S * h_v;
|
||||
T = grp.ntok[gi];
|
||||
n_keep = grp.keep[gi];
|
||||
}
|
||||
__shared__ float sk[2][S], sq[2][S];
|
||||
__shared__ float red_kv[RG][S];
|
||||
__shared__ float red_o[RG][S];
|
||||
@@ -1059,6 +1070,30 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet
|
||||
check("gdn_ab_multi");
|
||||
}
|
||||
|
||||
void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta,
|
||||
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit,
|
||||
void* stream) {
|
||||
if (groups.n < 1 || groups.n > 8 || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k) {
|
||||
std::fprintf(stderr, "gdn_step_norm_groups: invalid arguments\n");
|
||||
std::exit(1);
|
||||
}
|
||||
for (int i = 0; i < groups.n; ++i)
|
||||
if (!groups.state[i] || groups.ntok[i] < 1 || groups.ntok[i] > kVerifyMaxT || (commit && !groups.keep[i])) {
|
||||
std::fprintf(stderr, "gdn_step_norm_groups: invalid group %d\n", i);
|
||||
std::exit(1);
|
||||
}
|
||||
const dim3 g1((unsigned) h_v, (unsigned) groups.n), b1(S, RG);
|
||||
// the kernel gdn_step_norm_multi picks for these calls: a window's rows (all outputs, no keep) or a commit of
|
||||
// one-row groups (keep, t_out_begin 0)
|
||||
if (commit)
|
||||
gdn_step_norm_multi_kernel<false, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
|
||||
nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups);
|
||||
else
|
||||
gdn_step_norm_multi_kernel<true, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
|
||||
nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups);
|
||||
check("gdn_step_norm_groups");
|
||||
}
|
||||
|
||||
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
|
||||
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
|
||||
const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) {
|
||||
@@ -1121,8 +1156,78 @@ __global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t valu
|
||||
while (*flag < value) strata_spin_pause();
|
||||
__threadfence_system();
|
||||
}
|
||||
|
||||
// the GPU's clock in ns (the same sources as gpu_stamp_kernel)
|
||||
__device__ __forceinline__ unsigned long long strata_now_ns() {
|
||||
unsigned long long t;
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
t = wall_clock64() * 40ull;
|
||||
#elif defined(__HIPCC__)
|
||||
t = wall_clock64() * 10ull;
|
||||
#else
|
||||
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
|
||||
#endif
|
||||
return t;
|
||||
}
|
||||
|
||||
// the overlapped split's hand-off wait, bounded: spin until *flag >= value, or give up after timeout_ns (0: never),
|
||||
// marking *err = 1 (mapped) so the host fails the window instead of using a stale hand-off. The window's later
|
||||
// kernels still run (on whatever the hand-off buffer holds) so the graph completes and no stream is left hanging.
|
||||
__global__ void wait_handoff_kernel(const volatile uint32_t* flag, uint32_t value, uint32_t* err,
|
||||
unsigned long long timeout_ns) {
|
||||
const unsigned long long t0 = timeout_ns ? strata_now_ns() : 0ull;
|
||||
while (*flag < value) {
|
||||
strata_spin_pause();
|
||||
if (timeout_ns && strata_now_ns() - t0 > timeout_ns) {
|
||||
*(volatile uint32_t*) err = 1u;
|
||||
__threadfence_system();
|
||||
return;
|
||||
}
|
||||
}
|
||||
__threadfence_system();
|
||||
}
|
||||
|
||||
__global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, int64_t na, const float* __restrict__ b,
|
||||
int64_t nb, const float* __restrict__ c, int64_t nc, uint32_t* counter,
|
||||
uint32_t* flag, const volatile uint32_t* drop) {
|
||||
const int64_t n = na + nb + nc;
|
||||
volatile float* const out = dst;
|
||||
for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
|
||||
out[i] = i < na ? a[i] : i < na + nb ? b[i - na] : c[i - na - nb];
|
||||
__threadfence_system(); // this thread's stores reach host memory before the block counts itself done
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0) {
|
||||
const uint32_t prev = atomicAdd(counter, 1u);
|
||||
if (prev == gridDim.x - 1) { // every block's payload is out: raise the next stage's flag
|
||||
*(volatile uint32_t*) counter = 0u;
|
||||
__threadfence_system();
|
||||
if (drop == nullptr || *drop == 0u) { // test hook (STRATA_TEST_HANDOFF_DROP): a lost publish
|
||||
*(volatile uint32_t*) flag = 1u;
|
||||
__threadfence_system();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream) {
|
||||
wait_handoff_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, err, timeout_ns);
|
||||
check("wait_handoff");
|
||||
}
|
||||
|
||||
void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc,
|
||||
uint32_t* counter, uint32_t* flag, void* stream, const uint32_t* drop) {
|
||||
const int64_t n = na + nb + nc;
|
||||
if (n <= 0 || dst == nullptr || counter == nullptr || flag == nullptr) {
|
||||
std::fprintf(stderr, "handoff_publish: invalid arguments\n");
|
||||
std::exit(1);
|
||||
}
|
||||
const int64_t nb256 = (n + 255) / 256;
|
||||
const int blocks = (int) (nb256 < 64 ? nb256 : 64);
|
||||
handoff_publish_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(dst, a, na, b, nb, c, nc, counter, flag, drop);
|
||||
check("handoff_publish");
|
||||
}
|
||||
|
||||
namespace {
|
||||
// one thread per window entry: up to kVerifyMaxT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of
|
||||
// 7+ tokens lost its last entries)
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#endif
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
@@ -212,6 +213,8 @@ struct PleTable::Impl {
|
||||
strata::ngram::PleReader::Ticket ticket;
|
||||
bool pending = false;
|
||||
bool locked = false;
|
||||
// the table is shared by the prompt path and the decode windows; they can use it at once (one on a worker thread)
|
||||
std::recursive_mutex mu;
|
||||
uint32_t rows[PLE_N_HEADS] = {};
|
||||
uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {};
|
||||
static constexpr size_t kMaxPrefetch = 16;
|
||||
@@ -389,6 +392,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
|
||||
}
|
||||
|
||||
void PleTable::wait_prefetches() {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
|
||||
if (impl_->n_prefetch == 0) return;
|
||||
std::string dummy;
|
||||
for (size_t i = 0; i < impl_->n_prefetch; ++i) (void) impl_->reader.collect(impl_->prefetch_tickets[i], dummy);
|
||||
@@ -396,6 +400,7 @@ void PleTable::wait_prefetches() {
|
||||
}
|
||||
|
||||
void PleTable::prefetch_rows(const uint32_t* rows16) {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
|
||||
if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
|
||||
for (size_t i = 0; i < impl_->n_prefetch; ++i)
|
||||
if (std::memcmp(impl_->prefetch_keys[i], rows16, sizeof(uint32_t) * PLE_N_HEADS) == 0) return;
|
||||
@@ -444,6 +449,7 @@ uint64_t PleTable::rows() const { return impl_->n_rows; }
|
||||
uint64_t PleTable::bytes_read() const { return impl_->bytes_read; }
|
||||
|
||||
void PleTable::read_row(uint32_t row, float* out160) const {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
|
||||
if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
|
||||
uint8_t raw[PLE_ROW_BYTES_MAX];
|
||||
std::string err;
|
||||
@@ -465,6 +471,7 @@ void PleTable::read_row(uint32_t row, float* out160) const {
|
||||
}
|
||||
|
||||
bool PleTable::issue(const uint32_t* rows16) {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
|
||||
wait_prefetches();
|
||||
std::memcpy(impl_->rows, rows16, sizeof impl_->rows);
|
||||
if (impl_->mode == PleIo::Direct) {
|
||||
@@ -491,6 +498,7 @@ bool PleTable::issue(const uint32_t* rows16) {
|
||||
}
|
||||
|
||||
bool PleTable::collect(float* out2560, std::string& err) {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
|
||||
if (!impl_->pending) { err = "PleTable::collect without issue"; return false; }
|
||||
impl_->pending = false;
|
||||
if (impl_->mode == PleIo::Direct) {
|
||||
@@ -505,6 +513,7 @@ bool PleTable::collect(float* out2560, std::string& err) {
|
||||
}
|
||||
|
||||
bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err) {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
|
||||
if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; }
|
||||
const size_t n = n_tokens * (size_t) PLE_N_HEADS;
|
||||
if (impl_->mode == PleIo::Direct) {
|
||||
@@ -605,6 +614,7 @@ std::string PleTable::io_report() const {
|
||||
}
|
||||
|
||||
void PleTable::gather(const uint32_t* rows16, float* out2560) const {
|
||||
std::lock_guard<std::recursive_mutex> lk(impl_->mu); // issue + collect as one
|
||||
if (impl_->mode == PleIo::Direct) {
|
||||
// `gather` stays const for its existing callers; the reader's state is the table's I/O state.
|
||||
PleTable* self = const_cast<PleTable*>(this);
|
||||
|
||||
@@ -2352,8 +2352,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
std::future<bool> ple_next; // declared after everything it reads: an early return waits for it
|
||||
int ple_buf = 0;
|
||||
|
||||
if (hand_in_ == nullptr) stopped_at_ = -1;
|
||||
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
|
||||
if (should_stop && should_stop()) { err = "cancelled"; return false; }
|
||||
// the first stage: end the run before this chunk (every chunk before it is handed on; the caller's drain
|
||||
// waits for the later stages to read them)
|
||||
if (c0 > 0 && hand_in_ == nullptr && stop_at_chunk && stop_at_chunk()) {
|
||||
stopped_at_ = c0;
|
||||
break;
|
||||
}
|
||||
if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); }
|
||||
const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0;
|
||||
core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251
|
||||
@@ -4642,6 +4649,22 @@ bool Prefill::drain_pipeline(std::string& err) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Prefill::reserve_uploads(int64_t T) {
|
||||
bool ok = true;
|
||||
if (impl_ != nullptr && T > 0) {
|
||||
Impl& m = *impl_;
|
||||
const core::OnDevice on_device(m.device); // (the ring is the device's that is current at its first use)
|
||||
// a text chunk's largest pageable uploads through the ring: the routing tables (and their ids down, T x K
|
||||
// each); the PLE rows when they could not be pinned (T x N). A picture's rows are not covered.
|
||||
size_t bytes = (size_t) (T * K) * sizeof(int32_t);
|
||||
if (!m.ple_pageable[0].empty() || !m.ple_pageable[1].empty())
|
||||
bytes = std::max(bytes, (size_t) (T * N) * sizeof(float));
|
||||
ok = m.up_ring.reserve(bytes);
|
||||
}
|
||||
if (next_ != nullptr) ok = next_->reserve_uploads(T) && ok;
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
|
||||
#if defined(STRATA_GPU_METAL)
|
||||
{
|
||||
|
||||
+438
-34
@@ -8270,12 +8270,39 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
std::memset(hh, 0, hb);
|
||||
}
|
||||
// STRATA_SPLIT_OVERLAP=1 (opt-in; measured on 2x RX 7900 XTX only): a ready word per hand-off, raised by the
|
||||
// writing stage's GPU, so the next stage's window is launched early and the host never syncs between
|
||||
// stages (Verifier::set_handoff_flags). Not for --split-device 0 (both stages on one GPU).
|
||||
const bool overlap_asked = [] {
|
||||
const char* v = std::getenv("STRATA_SPLIT_OVERLAP");
|
||||
return v != nullptr && std::atoi(v) != 0;
|
||||
}();
|
||||
// --pipeline-windows (#859) runs its own overlapped loop with its own hand-offs: the two do not mix
|
||||
const bool overlap = overlap_asked && !split_same && o.pipeline_windows == 0;
|
||||
if (overlap_asked && o.pipeline_windows > 0)
|
||||
std::fprintf(stderr, "strata serve: STRATA_SPLIT_OVERLAP is off beside --pipeline-windows %d "
|
||||
"(that loop overlaps the stages itself)\n", o.pipeline_windows);
|
||||
std::vector<uint32_t*> hflag_h((size_t) n_stages - 1, nullptr), hflag_d((size_t) n_stages - 1, nullptr);
|
||||
if (overlap)
|
||||
for (size_t i = 0; i < hflag_h.size(); ++i) {
|
||||
if (cudaHostAlloc((void**) &hflag_h[i], 64, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess ||
|
||||
cudaHostGetDevicePointer((void**) &hflag_d[i], hflag_h[i], 0) != cudaSuccess) {
|
||||
std::fprintf(stderr, "strata serve: the layer-split hand-off flag allocation failed\n");
|
||||
return 1;
|
||||
}
|
||||
std::memset(hflag_h[i], 0, 64);
|
||||
}
|
||||
split_drive.base = &drive;
|
||||
split_drive.n = n_stages;
|
||||
for (int st = 0; st < n_stages; ++st) {
|
||||
stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1,
|
||||
st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr);
|
||||
if (hrows > strata::kernels::kVerifyMaxT) stage_ver(st).set_handoff_rows(hrows);
|
||||
if (overlap)
|
||||
stage_ver(st).set_handoff_flags(st == 0 ? nullptr : hflag_h[(size_t) st - 1],
|
||||
st == 0 ? nullptr : hflag_d[(size_t) st - 1],
|
||||
st + 1 < n_stages ? hflag_h[(size_t) st] : nullptr,
|
||||
st + 1 < n_stages ? hflag_d[(size_t) st] : nullptr);
|
||||
split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers;
|
||||
split_drive.cache_base[st] = drive.d.cache_base;
|
||||
split_drive.cache_slot_off[st] = drive.d.cache_slot_off;
|
||||
@@ -8316,7 +8343,8 @@ int main(int argc, char** argv) {
|
||||
for (int st = 1; st < n_stages; ++st)
|
||||
plan_s += ", " + std::to_string(split_at[(size_t) st - 1]) + "-" + std::to_string(split_drive.end[st] - 1) +
|
||||
" (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")";
|
||||
std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str());
|
||||
std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window%s\n", plan_s.c_str(),
|
||||
overlap ? " (overlapped: STRATA_SPLIT_OVERLAP=1)" : "");
|
||||
}
|
||||
// --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the
|
||||
// watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into
|
||||
@@ -10384,6 +10412,7 @@ int main(int argc, char** argv) {
|
||||
double bt_wait0 = 0, bt_pool0 = 0;
|
||||
int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0;
|
||||
int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0, bt_accepted = 0; // bt_accepted: --batch-mtp proposals taken
|
||||
int64_t pipe_rows = 0; // the pipelined groups' rows, never reset (bt_rows restarts when the slots go idle)
|
||||
// per stage (0 = CUDA0's verifier): the GPU-reach wait and pool time when the timed windows began; and the routed
|
||||
// (token, expert) entries the CPU and the PCIe share had served by then (bt_hits0 holds the VRAM entries)
|
||||
std::vector<double> bt_stage_wait0, bt_stage_pool0;
|
||||
@@ -10793,6 +10822,13 @@ int main(int argc, char** argv) {
|
||||
double line_drain_ms = 0.0, adm_drain_ms = 0.0;
|
||||
const char* rows_wait = nullptr; // what the next rows are timed from (rows_wait_t)
|
||||
Clock::time_point rows_wait_t{};
|
||||
// STRATA_PIPED_CONCURRENT (read_part): while a prompt is read on a thread of its own, the slots' doorbells are
|
||||
// served on another (conc_serving); between windows that thread waits on bell_cv and a launch wakes it (a
|
||||
// timed sleep is a whole timer tick on Windows, up to 15.6 ms, and the window's first layer would wait for it)
|
||||
bool conc_serving = false;
|
||||
std::mutex bell_mu;
|
||||
std::condition_variable bell_cv;
|
||||
std::atomic<bool> bell_waiting{false};
|
||||
// one turn: serve every running stage, hand finished groups on, start what can start
|
||||
auto pump = [&](bool may_start) -> bool {
|
||||
++pipe_tick;
|
||||
@@ -10832,6 +10868,7 @@ int main(int argc, char** argv) {
|
||||
std::printf("BT %d %d\n", gi * GS + t, (int) y);
|
||||
++sl.produced;
|
||||
++bt_rows;
|
||||
++pipe_rows;
|
||||
const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
|
||||
const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
|
||||
: sl.p + 2 > o.max_context ? "length" : nullptr;
|
||||
@@ -10887,6 +10924,12 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
G.inflight = true;
|
||||
G.stage = 0;
|
||||
// (with the doorbells on their own thread, a failure it set for a window that left this stage is
|
||||
// not cleared unseen)
|
||||
if (conc_serving && drive.d.failed) {
|
||||
std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed");
|
||||
return false;
|
||||
}
|
||||
drive.d.failed = false;
|
||||
apply_pending(false);
|
||||
}
|
||||
@@ -10897,6 +10940,13 @@ int main(int argc, char** argv) {
|
||||
return false;
|
||||
}
|
||||
stage_group[(size_t) k] = pick;
|
||||
if (conc_serving) { // the doorbell thread may be waiting between windows: the launch above is seen
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
if (bell_waiting.load(std::memory_order_relaxed)) {
|
||||
std::lock_guard<std::mutex> lk(bell_mu);
|
||||
bell_cv.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; }
|
||||
if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step
|
||||
@@ -10909,7 +10959,9 @@ int main(int argc, char** argv) {
|
||||
if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str());
|
||||
}
|
||||
bt_windows = bt_rows = 0;
|
||||
strata::core::progress().busy.store(false);
|
||||
// (not while a prompt is read in a request: its windows ran beside it, and the watchdog stays on for
|
||||
// the rest of the read, STRATA_PIPED_CONCURRENT; the request's end turns it off)
|
||||
if (!in_prompt_read) strata::core::progress().busy.store(false);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
@@ -12276,12 +12328,376 @@ int main(int argc, char** argv) {
|
||||
return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 8;
|
||||
}();
|
||||
const int64_t C = std::max<int64_t>(sp.chunk(), 1);
|
||||
const int64_t piece = strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks);
|
||||
// BYIELD <ys> with the read stopped at q (nothing in flight): the part read waits in slot ys and the
|
||||
// read ends with e = "yield" (true); false when it cannot give way there (the read goes on). Only
|
||||
// where the rest is read the same way after it (more than a chunk and more than a short read left),
|
||||
// text only, and into a slot that is not decoding.
|
||||
auto give_way = [&](int ys, int64_t q, std::string& err) -> bool {
|
||||
const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active &&
|
||||
(admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 &&
|
||||
b0 - q > std::max<int64_t>(C, o.short_read);
|
||||
std::string ye;
|
||||
const auto ty = Clock::now();
|
||||
std::vector<int32_t> pre(ids.begin(), ids.begin() + q);
|
||||
if (can && copy_to_slot(ys, pre, ye)) {
|
||||
BSlot& sl = bs[(size_t) ys];
|
||||
sl = BSlot{};
|
||||
sl.ids = std::move(pre);
|
||||
sl.cached = true;
|
||||
sl.partial = true;
|
||||
sl.partial_from0 = read_from == 0 || resumed_from0;
|
||||
sl.cvec = cvec_cached;
|
||||
for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read
|
||||
if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(),
|
||||
[](int32_t x, int64_t y) { return (int64_t) x == y; }))
|
||||
sl.checks.push_back(c);
|
||||
yielded_at = q;
|
||||
yielded_slot = ys;
|
||||
std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d "
|
||||
"holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys,
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - ty).count());
|
||||
err = "yield";
|
||||
return true;
|
||||
}
|
||||
if (can) bs[(size_t) ys].cached = false; // half written
|
||||
std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q,
|
||||
(long long) n, ye.empty() ? "" : ": ", ye.c_str());
|
||||
return false;
|
||||
};
|
||||
// Opt-in, experimental: STRATA_PIPED_CONCURRENT=1 reads the prompt on a thread of its own while
|
||||
// this thread keeps the slot groups decoding through the pipeline (pump), so they never stop for it
|
||||
// and the read has no drain inside it. The prompt and the windows use their own streams and memory
|
||||
// (the prompt's K/V goes to the main sessions, the slots' to theirs; the PLE table is locked), and
|
||||
// the adaptive tier stands still (its round landed before the read). The slots the prompt borrowed
|
||||
// were lent before this read with nothing in flight and are refilled after it, so the windows see
|
||||
// them missing and compute those experts on the CPU, as between pieces. A BYIELD ends the run at
|
||||
// its next chunk (Prefill::stop_at_chunk): the pipeline is drained there and the part read gives
|
||||
// way as below, or the read goes on from there.
|
||||
// Not where a read's thread allocates or frees (the idle stage's help, STRATA_PREFILL_HELP; the batched
|
||||
// draft K/V, STRATA_SPLIT_MTP_BATCH: a free waits for the device), where serving a doorbell makes a
|
||||
// CUDA call (--pcie-mode dma, the Foresight swap space STRATA_FS_SLOTS, the helper caches), and where
|
||||
// the expert source recycles the buffers it hands out (the GGUF in place, an unbuffered source, the
|
||||
// I/O read-ahead: one thread at a time). Pictures are read the usual way (their rows go up through
|
||||
// pinned slots of a size known only then).
|
||||
static const bool pr_conc = [&] {
|
||||
const char* v = std::getenv("STRATA_PIPED_CONCURRENT");
|
||||
if (v == nullptr || std::atoi(v) == 0) return false;
|
||||
auto env_on = [](const char* k) {
|
||||
const char* x = std::getenv(k);
|
||||
return x != nullptr && std::atoi(x) != 0;
|
||||
};
|
||||
strata::program::ConcurrentReadSetup s;
|
||||
s.prefill_help = env_on("STRATA_PREFILL_HELP");
|
||||
s.split_mtp_batch = env_on("STRATA_SPLIT_MTP_BATCH");
|
||||
s.fs_slots = env_on("STRATA_FS_SLOTS");
|
||||
s.pcie_dma = o.pcie_mode == "dma";
|
||||
// (--remote-expert-opt works only through a helper cache, so without one it does not count)
|
||||
s.helper_caches = prefill_src != srcp;
|
||||
for (int r = 0; r < 3; ++r) s.helper_caches |= o.expert_cache_remote[(size_t) r] > 0;
|
||||
s.staged_source = srcp == &src && src.stages_blobs();
|
||||
s.other_source = srcp != &src && srcp != &arena_src;
|
||||
if (const char* why = strata::program::concurrent_read_off(s)) {
|
||||
std::fprintf(stderr, "strata batch: STRATA_PIPED_CONCURRENT is off beside %s\n", why);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}();
|
||||
if (piped && pr_conc && req_imgs.empty()) { // (with no slot decoding it only watches for a BYIELD)
|
||||
// the drafter's prompt pass captures its graphs and grows its records at first use, and the
|
||||
// prompt path's pinned upload slots grow at their first larger upload: done here, with nothing in
|
||||
// flight (on the reader's thread a capture, an allocation or a free takes the driver's lock and
|
||||
// can wait for the device, #31)
|
||||
if (use_mtp && !mtp.reserve_prefill(C, e)) return false;
|
||||
if (!sp.reserve_uploads(C))
|
||||
std::fprintf(stderr, "strata batch: the prompt path's pinned upload slots could not be "
|
||||
"reserved (they grow at first use)\n");
|
||||
// where the read's thread and the doorbell thread run: on Linux a thread inherits its creator's
|
||||
// CPUs, and the host thread is pinned to the one core the pool leaves it, so both would share that
|
||||
// core with the host thread that pumps the windows - every window then waits its turn there for
|
||||
// the doorbell of each layer (4x RTX 5080, 4 stages: 6 rows/s during a read). They move off the
|
||||
// host's core and the pool workers' CPUs instead (--aux-cpus places them, when it is on).
|
||||
// STRATA_PIPED_CONCURRENT_UNPIN=0 keeps the inherited CPUs (an A/B); STRATA_TEST_CONC_ON_HOST_CPU=1
|
||||
// (Windows, a test) puts them on the host thread's CPUs first, as Linux does.
|
||||
static const bool conc_unpin = [] {
|
||||
const char* v = std::getenv("STRATA_PIPED_CONCURRENT_UNPIN");
|
||||
return v == nullptr || std::atoi(v) != 0;
|
||||
}();
|
||||
#if defined(_WIN32)
|
||||
static const bool conc_on_host = std::getenv("STRATA_TEST_CONC_ON_HOST_CPU") != nullptr;
|
||||
std::vector<ULONG> host_cpu_sets;
|
||||
if (conc_on_host) {
|
||||
const HANDLE self = GetCurrentThread();
|
||||
ULONG count = 0;
|
||||
if (GetThreadSelectedCpuSets(self, nullptr, 0, &count) ||
|
||||
GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
|
||||
host_cpu_sets.resize(count);
|
||||
if (count && !GetThreadSelectedCpuSets(self, host_cpu_sets.data(), count, &count))
|
||||
host_cpu_sets.clear();
|
||||
}
|
||||
static bool said = false;
|
||||
if (!said) {
|
||||
said = true;
|
||||
std::fprintf(stderr, "strata batch: test: the read's and the doorbell threads start on the "
|
||||
"host thread's %zu CPU set(s)%s\n", host_cpu_sets.size(),
|
||||
conc_unpin ? ", then leave them (the fix)"
|
||||
: " and stay there (as on Linux)");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// the threads that already inherited the host's core (the prompt path's copy threads, started by
|
||||
// the first prompt on the host thread) work during the read too: off that core as well (Linux)
|
||||
if (conc_unpin && !strata::aux_cpus::enabled())
|
||||
if (const int moved = strata::aux_cpus::release_host_inheritors(); moved > 0)
|
||||
std::fprintf(stderr, "strata batch: %d threads that ran on the host thread's core moved off "
|
||||
"it, for reads beside the slots\n", moved);
|
||||
auto conc_thread_cpus = [&] {
|
||||
strata::aux_cpus::pin_current_thread();
|
||||
#if defined(_WIN32)
|
||||
const HANDLE self = GetCurrentThread();
|
||||
if (conc_on_host && !host_cpu_sets.empty())
|
||||
SetThreadSelectedCpuSets(self, host_cpu_sets.data(), (ULONG) host_cpu_sets.size());
|
||||
if (conc_unpin && conc_on_host) SetThreadSelectedCpuSets(self, nullptr, 0);
|
||||
#else
|
||||
if (conc_unpin && !strata::aux_cpus::enabled()) (void) strata::aux_cpus::place_off_host();
|
||||
#endif
|
||||
};
|
||||
// the slots' doorbells are served on a thread of their own for the read, which makes no CUDA
|
||||
// call: a call here or on the read's threads can wait for the driver's lock while its holder
|
||||
// waits for the GPU (a free; a module the first kernel of a shape loads), and a window on that
|
||||
// GPU waits for its doorbell (#31). Ends (and hands the service back to pump) on every exit.
|
||||
struct Doorbells {
|
||||
std::atomic<bool> on{true};
|
||||
std::thread th;
|
||||
std::function<void()> wake, off;
|
||||
~Doorbells() {
|
||||
on.store(false, std::memory_order_release);
|
||||
if (wake) wake();
|
||||
if (th.joinable()) th.join();
|
||||
if (off) off();
|
||||
}
|
||||
} bells;
|
||||
for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(true);
|
||||
conc_serving = true;
|
||||
bells.off = [&] {
|
||||
for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(false);
|
||||
conc_serving = false;
|
||||
};
|
||||
bells.wake = [&] {
|
||||
std::lock_guard<std::mutex> lk(bell_mu);
|
||||
bell_cv.notify_one();
|
||||
};
|
||||
bells.th = std::thread([&] {
|
||||
conc_thread_cpus();
|
||||
auto any_busy = [&] {
|
||||
for (int k = 0; k < n_pipe; ++k)
|
||||
if (stage_verifier(k).batch_busy()) return true;
|
||||
return false;
|
||||
};
|
||||
while (bells.on.load(std::memory_order_acquire)) {
|
||||
bool busy = false;
|
||||
for (int k = 0; k < n_pipe; ++k) {
|
||||
auto& vk = stage_verifier(k);
|
||||
if (vk.batch_busy()) {
|
||||
busy = true;
|
||||
vk.batch_serve(win_pool_fn, win_pool_user);
|
||||
}
|
||||
}
|
||||
if (busy) continue;
|
||||
// STRATA_TEST_BELL_SLEEP_US=N (a test, an A/B of the wait below): sleep N us instead, as
|
||||
// the first form of this thread did (a whole timer tick on Windows)
|
||||
static const int test_sleep_us = [] {
|
||||
const char* t = std::getenv("STRATA_TEST_BELL_SLEEP_US");
|
||||
return t != nullptr ? std::max(0, std::atoi(t)) : 0;
|
||||
}();
|
||||
if (test_sleep_us > 0) {
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(test_sleep_us));
|
||||
continue;
|
||||
}
|
||||
// no window in flight: wait for pump's next launch (it notifies when this is set; the
|
||||
// fences pair the flag with batch_launch's running flag, so one of the two sides sees the
|
||||
// other), or for the end of the read
|
||||
std::unique_lock<std::mutex> lk(bell_mu);
|
||||
bell_waiting.store(true, std::memory_order_relaxed);
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
bell_cv.wait_for(lk, std::chrono::milliseconds(2),
|
||||
[&] { return !bells.on.load(std::memory_order_acquire) || any_busy(); });
|
||||
bell_waiting.store(false, std::memory_order_relaxed);
|
||||
}
|
||||
});
|
||||
for (int64_t q0 = a0; q0 < b0;) {
|
||||
const auto tc = Clock::now();
|
||||
const int64_t rows0 = pipe_rows;
|
||||
// per stage, for the read's log line: its windows and the host time that set them up (the
|
||||
// PLE gather included, which waits while the prompt holds the table) - both this thread's
|
||||
std::vector<std::pair<int64_t, double>> st0((size_t) n_pipe);
|
||||
for (int k = 0; k < n_pipe; ++k)
|
||||
st0[(size_t) k] = {stage_verifier(k).windows, stage_verifier(k).ms_host};
|
||||
std::atomic<bool> done{false};
|
||||
std::atomic<int> want_yield{-1};
|
||||
bool read_ok = true;
|
||||
std::string read_err;
|
||||
in_prompt_read = true;
|
||||
sp.stop_at_chunk = [&] { return want_yield.load(std::memory_order_acquire) >= 0; };
|
||||
std::thread reader([&] {
|
||||
conc_thread_cpus();
|
||||
try { // (an exception leaving a std::thread ends the process: a failed read instead)
|
||||
read_ok = sp.run(ids.data() + q0, b0 - q0, q0, read_err);
|
||||
} catch (const std::exception& x) {
|
||||
read_ok = false;
|
||||
read_err = std::string("the prompt read failed: ") + x.what();
|
||||
} catch (...) {
|
||||
read_ok = false;
|
||||
read_err = "the prompt read failed";
|
||||
}
|
||||
done.store(true, std::memory_order_release);
|
||||
{ std::lock_guard<std::mutex> lk(in_mu); } // (the loop below may be waiting on in_cv)
|
||||
in_cv.notify_all();
|
||||
});
|
||||
struct ReadEnd { // on every way out of this round (an exception too): the reader joined first
|
||||
std::thread& t;
|
||||
std::function<bool()>& hook;
|
||||
bool& reading;
|
||||
~ReadEnd() {
|
||||
if (t.joinable()) t.join();
|
||||
hook = nullptr;
|
||||
reading = false;
|
||||
}
|
||||
} read_end{reader, sp.stop_at_chunk, in_prompt_read};
|
||||
bool pump_ok = true;
|
||||
size_t seen = 0; // in_lines' length after the last look: a line that comes wakes the wait
|
||||
while (!done.load(std::memory_order_acquire)) {
|
||||
const bool decoding = pump_ok && (batch_on() || pipe_inflight());
|
||||
if (decoding) pump_ok = pump(true);
|
||||
std::unique_lock<std::mutex> lk(in_mu);
|
||||
if (!decoding) // nothing to pump: until the read ends or a line comes (both notify)
|
||||
in_cv.wait_for(lk, std::chrono::milliseconds(2), [&] {
|
||||
return done.load(std::memory_order_acquire) || in_lines.size() != seen;
|
||||
});
|
||||
// a BSTOP that came meanwhile ends its slot at its next window; a BYIELD ends the read at
|
||||
// its next chunk
|
||||
for (auto it = in_lines.begin(); it != in_lines.end();) {
|
||||
if (it->rfind("BSTOP ", 0) == 0) {
|
||||
const int b = std::atoi(it->c_str() + 6);
|
||||
if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;
|
||||
it = in_lines.erase(it);
|
||||
} else if (it->rfind("BYIELD ", 0) == 0 && want_yield.load() < 0) {
|
||||
want_yield.store(std::atoi(it->c_str() + 7), std::memory_order_release);
|
||||
it = in_lines.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
seen = in_lines.size();
|
||||
}
|
||||
reader.join(); // (a failed window leaves the read to finish: it is not stopped mid-run)
|
||||
sp.stop_at_chunk = nullptr;
|
||||
in_prompt_read = false;
|
||||
if (!pump_ok || !pipe_drain()) {
|
||||
batch_fatal = true;
|
||||
e = "a pipelined batch window failed";
|
||||
return false;
|
||||
}
|
||||
const int64_t q = read_ok && sp.stopped_at() >= 0 ? q0 + sp.stopped_at() : b0;
|
||||
const double read_ms = std::chrono::duration<double, std::milli>(Clock::now() - tc).count();
|
||||
std::string per;
|
||||
for (int k = 0; k < n_pipe; ++k) {
|
||||
const auto& v = stage_verifier(k);
|
||||
const int64_t w = v.windows - st0[(size_t) k].first;
|
||||
char b[96];
|
||||
const double host = w > 0 ? (v.ms_host - st0[(size_t) k].second) / (double) w : 0.0;
|
||||
std::snprintf(b, sizeof b, "%sstage %d: %lld windows, %.1f ms host each", k ? "; " : "",
|
||||
k + 1, (long long) w, host);
|
||||
per += b;
|
||||
}
|
||||
std::fprintf(stderr, "strata batch: read %lld tokens on a thread of its own in %.0f ms "
|
||||
"(concurrent, to %lld of %lld); the slots decoded %lld rows meanwhile "
|
||||
"(%.1f rows/s; %s)\n",
|
||||
(long long) (q - q0), read_ms, (long long) q, (long long) n,
|
||||
(long long) (pipe_rows - rows0),
|
||||
read_ms > 0.0 ? 1000.0 * (double) (pipe_rows - rows0) / read_ms : 0.0,
|
||||
per.c_str());
|
||||
if (!read_ok) {
|
||||
e = read_err;
|
||||
return false;
|
||||
}
|
||||
if (q < b0 && give_way(want_yield.load(), q, e)) return false;
|
||||
q0 = q; // done, or the give-way was not taken there: the rest goes on the same way
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Opt-in (#1906): on the pipelined slot groups a read goes in pieces of STRATA_PIPED_READ_PIECE tokens
|
||||
// (whole chunks). A piece's end has the pipeline drained, so a waiting shorter request can take
|
||||
// over there (BYIELD); with slots decoding, the groups then decode through the pipeline (pump) for
|
||||
// STRATA_BATCH_DECODE_SHARE x the piece's time, capped / floored by STRATA_PIPED_DECODE_MAX_MS /
|
||||
// _MIN_MS, and are drained (pipe_drain) before the next piece, as before any read. Unset: one run.
|
||||
static const int64_t pr_piece = [] {
|
||||
const char* v = std::getenv("STRATA_PIPED_READ_PIECE");
|
||||
return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 0;
|
||||
}();
|
||||
static const double pr_cap = [] {
|
||||
const char* v = std::getenv("STRATA_PIPED_DECODE_MAX_MS");
|
||||
return v != nullptr ? std::max(0.0, std::atof(v)) : 0.0;
|
||||
}();
|
||||
static const double pr_floor = [] {
|
||||
const char* v = std::getenv("STRATA_PIPED_DECODE_MIN_MS");
|
||||
return v != nullptr ? std::max(0.0, std::atof(v)) : 0.0;
|
||||
}();
|
||||
const bool pr_on = piped && pr_piece > 0;
|
||||
auto piece_now = [&]() -> int64_t {
|
||||
return pr_on ? strata::program::piped_read_piece(pr_piece, C)
|
||||
: strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C,
|
||||
yield_chunks);
|
||||
};
|
||||
// the slots decode through the pipeline for budget_ms, drained before the next read
|
||||
auto piped_decode = [&](double budget_ms, std::string& err) -> bool {
|
||||
const auto td = Clock::now();
|
||||
in_prompt_read = true;
|
||||
do {
|
||||
if (!pump(true)) {
|
||||
in_prompt_read = false; batch_fatal = true; err = "a pipelined batch window failed";
|
||||
return false;
|
||||
}
|
||||
} while (batch_on() &&
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - td).count() < budget_ms);
|
||||
if (!pipe_drain()) {
|
||||
in_prompt_read = false; batch_fatal = true; err = "a pipelined batch window failed";
|
||||
return false;
|
||||
}
|
||||
in_prompt_read = false;
|
||||
++il_parts;
|
||||
il_ms += std::chrono::duration<double, std::milli>(Clock::now() - td).count();
|
||||
return true;
|
||||
};
|
||||
// prompts arriving back to back: one decode budget before a read that follows a piecewise read
|
||||
static Clock::time_point pr_prev_end{};
|
||||
static bool pr_have_prev = false;
|
||||
static double pr_prev_piece_ms = 0.0; // the previous read's last full piece
|
||||
if (pr_on) {
|
||||
const double lead =
|
||||
pr_prev_piece_ms > 0.0
|
||||
? strata::program::piped_decode_budget_ms(pr_prev_piece_ms, decode_share, pr_cap, pr_floor)
|
||||
: (pr_cap > 0.0 ? pr_cap : std::max(pr_floor, 200.0));
|
||||
const double since =
|
||||
pr_have_prev ? std::chrono::duration<double, std::milli>(Clock::now() - pr_prev_end).count()
|
||||
: -1.0;
|
||||
if (strata::program::piped_read_lead_in(true, batch_on(), since, lead)) {
|
||||
const int64_t rows0 = pipe_rows;
|
||||
const auto tl = Clock::now();
|
||||
if (!piped_decode(lead, e)) return false;
|
||||
std::fprintf(stderr, "strata batch: a read right after a read: the slots decoded %lld rows in "
|
||||
"%.0f ms first\n", (long long) (pipe_rows - rows0),
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - tl).count());
|
||||
}
|
||||
}
|
||||
int64_t piece = piece_now();
|
||||
if (piece <= 0) return sp.run(ids.data() + a0, b0 - a0, a0, e);
|
||||
for (int64_t q = a0; q < b0;) {
|
||||
const int64_t r = std::min(b0, q + piece);
|
||||
const auto tq = Clock::now();
|
||||
if (!sp.run(ids.data() + q, r - q, q, e)) return false;
|
||||
const double piece_ms = std::chrono::duration<double, std::milli>(Clock::now() - tq).count();
|
||||
if (pr_on && r < b0) pr_prev_piece_ms = piece_ms;
|
||||
const int64_t piece_tokens = r - q;
|
||||
q = r;
|
||||
if (q >= b0) continue;
|
||||
int ys = -1;
|
||||
@@ -12300,38 +12716,25 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ys >= 0) {
|
||||
// only where the rest is read the same way after it (more than a chunk and more than a short
|
||||
// read left), text only, and into a slot that is not decoding
|
||||
const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active &&
|
||||
(admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 &&
|
||||
b0 - q > std::max<int64_t>(C, o.short_read);
|
||||
std::string ye;
|
||||
const auto ty = Clock::now();
|
||||
std::vector<int32_t> pre(ids.begin(), ids.begin() + q);
|
||||
if (can && copy_to_slot(ys, pre, ye)) {
|
||||
BSlot& sl = bs[(size_t) ys];
|
||||
sl = BSlot{};
|
||||
sl.ids = std::move(pre);
|
||||
sl.cached = true;
|
||||
sl.partial = true;
|
||||
sl.partial_from0 = read_from == 0 || resumed_from0;
|
||||
sl.cvec = cvec_cached;
|
||||
for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read
|
||||
if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(),
|
||||
[](int32_t x, int64_t y) { return (int64_t) x == y; }))
|
||||
sl.checks.push_back(c);
|
||||
yielded_at = q;
|
||||
yielded_slot = ys;
|
||||
std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d "
|
||||
"holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys,
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - ty).count());
|
||||
e = "yield";
|
||||
return false;
|
||||
if (ys >= 0 && give_way(ys, q, e)) return false;
|
||||
// (on the pipelined path a piece's end has the pipeline drained - nothing runs during a piece and
|
||||
// every decode budget ends in pipe_drain - so the part read can give way there as off the pipeline)
|
||||
if (pr_on) { // the pipelined pieces: the slots decode through the pipeline, then it is drained
|
||||
if (!batch_on()) {
|
||||
std::fprintf(stderr, "strata batch: piped read %lld tokens in %.0f ms (to %lld of %lld)\n",
|
||||
(long long) piece_tokens, piece_ms, (long long) q, (long long) n);
|
||||
continue;
|
||||
}
|
||||
if (can) bs[(size_t) ys].cached = false; // half written
|
||||
std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q,
|
||||
(long long) n, ye.empty() ? "" : ": ", ye.c_str());
|
||||
const double budget =
|
||||
strata::program::piped_decode_budget_ms(piece_ms, decode_share, pr_cap, pr_floor);
|
||||
const int64_t rows0 = pipe_rows;
|
||||
const auto td = Clock::now();
|
||||
if (!piped_decode(budget, e)) return false;
|
||||
std::fprintf(stderr, "strata batch: piped read %lld tokens in %.0f ms (to %lld of %lld), "
|
||||
"then the slots decoded %lld rows in %.0f ms\n", (long long) piece_tokens,
|
||||
piece_ms, (long long) q, (long long) n, (long long) (pipe_rows - rows0),
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - td).count());
|
||||
continue;
|
||||
}
|
||||
if (decode_share <= 0.0 || !batch_on()) continue;
|
||||
const double budget = decode_share * std::chrono::duration<double, std::milli>(Clock::now() - tq).count();
|
||||
@@ -12349,6 +12752,7 @@ int main(int argc, char** argv) {
|
||||
std::fflush(stderr);
|
||||
}
|
||||
}
|
||||
if (pr_on) { pr_prev_end = Clock::now(); pr_have_prev = true; } // for the next read's lead-in
|
||||
return true;
|
||||
};
|
||||
apply_pending(true);
|
||||
|
||||
Reference in new issue
Block a user