diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 18305195..e43e2ac5 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -48,6 +48,7 @@ public: void set_prompt_len(int64_t n) { prompt_len_ = n; } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. void set_max_drafts(int k) { max_drafts_ = k; } + int max_t() const { return max_t_; } uint64_t vram_bytes() const { return vram_; } /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) const QsaState& kv_state() const { return st_; } @@ -62,8 +63,14 @@ public: const MtpDrafter* shared = nullptr); /// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host, - /// the token at position cell+1). Runs in batches of up to max_t rows. - bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err); + /// the token at position cell+1). Runs in batches of up to max_t rows. `sync` false: returns without waiting + /// for the drafter's stream (the caller orders on it: `stream()`). + bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err, + bool sync = true); + /// --pipeline-windows: capture the prefill graphs and size its input records for windows of up to max_t rows now, + /// so a later prefill(sync = false) of a window neither captures nor allocates (both wait for the device). + bool prepare_prefill(std::string& err); + cudaStream_t stream() const { return cs_; } /// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's /// argmaxes: row t pairs R_{p+t} with the token at p+t+1), then the draft chain from row `a` (the last @@ -86,6 +93,31 @@ public: void set_ple_session(SessionState* s) { ple_ss_ = s; } bool coupled() const { return coupled_active_; } + // ---- --pipeline-windows 2: the chain as one asynchronous launch (the round and its steps back to back, no host + // wait), its first `n_force` steps fed the given tokens instead of their own picks (teacher forcing: the drafts of + // a window already in flight), each output read once the event after its step has completed. + /// Before `load`: the round/step graphs get the forcing kernel (a no-op while its token is -1), and the drafter's + /// stream the highest priority (STRATA_MTP_PRIORITY=0: the default priority). + void set_force_capture(bool on) { force_on_ = on; } + /// The rows the next round reads (null: the bound `window_R`), copied into the bound buffer before the round. + void set_source_R(const float* rows) { src_R_ = rows; } + /// Capture the round graphs for T = 1..max_t and every step graph now (a capture syncs the drafter's stream). + bool prepare_chain(std::string& err); + /// The catch-up over T cells from `p` (as draft()), then `n_out` outputs from row `a`: output j is the chain's + /// own pick, and step j (1 <= j <= n_force) takes force[j - 1] as its input token instead of output j - 1. + /// `n_early`: an event after each of the first `n_early` outputs (chain_outputs_ready). + bool chain_launch(int T, const int32_t* tokens, int64_t p, int a, const int32_t* force, int n_force, int n_out, + int n_early, std::string& err); + /// 1: every output is in chain_tok()/chain_prob(); 0: still running; -1: an error. + int chain_poll(std::string& err); + /// How many of the chain's first outputs (up to `n_early`; all of them once the chain is done) have landed in + /// chain_tok()/chain_prob(); -1: an error. A window's size is often decided by its first outputs (a draft below + /// spec_min_p ends it), so the next launch need not wait for all of them. + int chain_outputs_ready(std::string& err); + bool chain_live() const { return chain_live_; } + const int32_t* chain_tok() const { return chain_tok_; } + const float* chain_prob() const { return chain_prob_; } + double ms_draft = 0, ms_prefill = 0; int64_t rounds = 0; @@ -133,6 +165,16 @@ private: int max_t_ = 0; int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) int max_drafts_ = 1 << 30; + // --pipeline-windows 2 (chain_launch) + bool stage_source_R(int T, std::string& err); ///< set_source_R's rows into the bound buffer + bool force_on_ = false, chain_live_ = false; + const float* src_R_ = nullptr; + int32_t *h_force_ = nullptr, *m_force_ = nullptr; ///< the forced tokens (mapped), -1 = the step's own pick + cudaEvent_t ev_chain_ = nullptr; + cudaEvent_t ev_step_[8] = {}; ///< after each of the first n_early outputs + int steps_seen_ = 0, chain_n_ = 0, chain_early_ = 0; + int32_t chain_tok_[8] = {}; + float chain_prob_[8] = {}; int64_t n_vocab_ = 0; uint64_t vram_ = 0; cudaStream_t cs_ = nullptr; diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 2efb7cf7..9c0e2b9c 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -85,6 +85,9 @@ void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst, int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs = nullptr, float* out_p = nullptr); +/// --pipeline-windows, the drafter's chain teacher forced: `*tok = force[j]` when force[j] >= 0 (`force` is mapped +/// host memory, read when the kernel runs), else `*tok` is left as it is. +void force_token(int32_t* tok, const int32_t* force, int j, void* stream); /// dst row i = src row ids[i] (row_bytes each, multiple of 16), for n rows. void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream); /// ids[t] = table[ids[t]] for n entries (a subset index back to a token id). diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index b8b83de3..285b45f4 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -130,7 +130,9 @@ MtpDrafter::~MtpDrafter() { if (head_logits_) cudaFree(head_logits_); if (owns_draft_head_ && dhead_) cudaFree(dhead_); if (owns_draft_head_ && dvocab_) cudaFree(dvocab_); - void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_}; + if (ev_chain_) cudaEventDestroy(ev_chain_); + for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e); + void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -268,8 +270,10 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) && mapped(64, (void**) &h_row_, (void**) &m_row_) && mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) && - mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_); + mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_) && + (!force_on_ || mapped(64, (void**) &h_force_, (void**) &m_force_)); if (!ok) { err = "mtp: mapped staging failed"; return false; } + if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1; auto carve = [&](Bump& b) { tok_ = b.take(T); step_ = b.take(R2 * 4); pos_ = b.take(R2 * NH); row_ = b.take(4); ident_ = b.take(T * (uint64_t) cap_); @@ -312,7 +316,17 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i; cudaMemcpy(ident_, id.data(), id.size() * 4, cudaMemcpyHostToDevice); } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } + // --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch + // on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default) + bool prio = false; +#if !defined(STRATA_USE_HIP) // (HIP: the default priority) + static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }(); + int prio_lo = 0, prio_hi = 0; + if (force_on_ && hi_prio && cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi) == cudaSuccess) + prio = cudaStreamCreateWithPriority(&cs_, cudaStreamNonBlocking, prio_hi) == cudaSuccess; + cudaGetLastError(); +#endif + if (!prio && cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } const double files_s = std::chrono::duration(std::chrono::steady_clock::now() - t_files).count(); if (shared != nullptr) { std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n", @@ -746,6 +760,7 @@ bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) { coupled_rec_ = false; } if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_); + if (ok && force_on_ && !coupled) force_token(tok_, m_force_, 0, cs_); // chain_launch: step 1's input return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err); } @@ -765,6 +780,7 @@ bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) { bool ok = record_forward(1, row, cs_, err); coupled_rec_ = false; if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_); + if (ok && force_on_ && !coupled) force_token(tok_, m_force_, j, cs_); // chain_launch: step j+1's input return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err); } @@ -778,7 +794,26 @@ void MtpDrafter::kv_restore(int64_t upto) { cudaStreamSynchronize(cs_); } -bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) { +bool MtpDrafter::prepare_prefill(std::string& err) { + const OnDevice on_device(device_); + const int64_t per_row = 1 + 4 + g_->n_head; + if (pf_cap_ < (int64_t) max_t_ * per_row) { + if (pf_dev_) cudaFree(pf_dev_); + pf_dev_ = nullptr; + pf_cap_ = 0; + if (cudaMalloc((void**) &pf_dev_, (size_t) (max_t_ * per_row) * sizeof(int32_t)) != cudaSuccess) { + err = "mtp prefill: the input records do not fit"; + return false; + } + pf_cap_ = max_t_ * per_row; + } + for (int T = 1; T <= max_t_; ++T) + if (!capture_prefill_dev(T, err)) return false; // (STRATA_MTP_PREFILL_SYNC's loop syncs anyway) + 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) { const OnDevice on_device(device_); const Clock::time_point t0 = Clock::now(); const int64_t HCN = g_->hc * g_->n_embd; @@ -848,6 +883,11 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_ return false; } } + if (!sync) { // the caller orders on stream(); the records are staged (a pageable copy returns once taken) + (void) cudaStreamQuery(cs_); + ms_prefill += ms_since(t0); + return true; + } if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; @@ -884,6 +924,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* float* probs, float min_p, int* n_drafts) { const OnDevice on_device(device_); if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; } + if (chain_live_) { err = "mtp: a pipelined chain is still in flight"; return false; } const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs if (!capture_round(T, cp, err)) return false; const int max_steps = std::min(max_t_ - 1, max_drafts_); @@ -908,7 +949,9 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* for (int j = 0; j < max_steps; ++j) ((volatile int32_t*) h_out_)[j] = -1; h_row_[0] = a; h_row_[1] = 0; + if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1; // the forcing kernels: no-ops here std::atomic_thread_fence(std::memory_order_seq_cst); + if (!stage_source_R(T, err)) return false; SessionState* const pss = ple_ss_ ? ple_ss_ : ss_; const bool do_ple = pss != nullptr && pss->ple.ready() && pss->ple.table != nullptr; @@ -1004,6 +1047,117 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* return true; } +bool MtpDrafter::stage_source_R(int T, std::string& err) { + if (src_R_ == nullptr || src_R_ == window_R_) return true; + if (cudaMemcpyAsync((void*) window_R_, src_R_, (size_t) T * (size_t) (g_->hc * g_->n_embd) * sizeof(float), + cudaMemcpyDeviceToDevice, cs_) != cudaSuccess) { + err = "mtp: staging the window's residual rows failed"; + return false; + } + return true; +} + +bool MtpDrafter::prepare_chain(std::string& err) { + const OnDevice on_device(device_); + if (!force_on_ || h_force_ == nullptr) { err = "mtp: chains need set_force_capture before load"; return false; } + for (int T = 1; T <= max_t_; ++T) + if (!capture_round(T, false, err)) return false; + for (int j = 1; j <= max_t_ - 2; ++j) + if (!capture_step(j, false, err)) return false; + if (ev_chain_ == nullptr && cudaEventCreateWithFlags(&ev_chain_, cudaEventDisableTiming) != cudaSuccess) { + err = "mtp: event creation failed"; + return false; + } + for (cudaEvent_t& e : ev_step_) + if (e == nullptr && cudaEventCreateWithFlags(&e, cudaEventDisableTiming) != cudaSuccess) { + err = "mtp: event creation failed"; + return false; + } + return true; +} + +bool MtpDrafter::chain_launch(int T, const int32_t* tokens, int64_t p, int a, const int32_t* force, int n_force, + int n_out, int n_early, std::string& err) { + const OnDevice on_device(device_); + if (chain_live_) { err = "mtp: a chain is already in flight"; return false; } + if (!force_on_ || ev_chain_ == nullptr) { err = "mtp: chains need prepare_chain"; return false; } + if (T < 1 || T > max_t_ || a < 0 || a >= T || n_out < 1 || n_out > max_t_ - 1 || n_force < 0 || n_force > n_out || + n_force > 16) { + err = "mtp: chain arguments out of range"; + return false; + } + if (round_exec_[T] == nullptr) { err = "mtp: chain graphs not prepared"; return false; } + for (int j = 1; j < n_out; ++j) + if (step_exec_[j] == nullptr) { err = "mtp: chain graphs not prepared"; return false; } + const Clock::time_point t0 = Clock::now(); + const int64_t NH = g_->n_head; + auto put = [&](int row, int64_t cell) { + h_step_[row * 4 + 0] = (int32_t) cell; + h_step_[row * 4 + 1] = (int32_t) (cell + 1); + h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); + h_step_[row * 4 + 3] = (int32_t) (cell + 1); + for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell; + }; + for (int t = 0; t < T; ++t) { + h_tok_[t] = tokens[t]; + put(t, p + t); + } + put(2 * max_t_ - 1, p + a); // output 0's cell + for (int j = 1; j < n_out; ++j) put(max_t_ + j - 1, p + a + j); // every step's cell, staged at once + for (int j = 0; j < 16; ++j) h_force_[j] = j < n_force ? force[j] : -1; + h_row_[0] = a; + h_row_[1] = 0; + std::atomic_thread_fence(std::memory_order_seq_cst); + if (!stage_source_R(T, err)) return false; + chain_early_ = std::max(0, std::min(n_early, n_out)); + bool ok = cudaGraphLaunch(round_exec_[T], cs_) == cudaSuccess; + if (ok && chain_early_ >= 1) ok = cudaEventRecord(ev_step_[0], cs_) == cudaSuccess; + for (int j = 1; ok && j < n_out; ++j) { + ok = cudaGraphLaunch(step_exec_[j], cs_) == cudaSuccess; + if (ok && j < chain_early_) ok = cudaEventRecord(ev_step_[j], cs_) == cudaSuccess; + } + if (!ok || cudaEventRecord(ev_chain_, cs_) != cudaSuccess) { + err = std::string("mtp chain: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + (void) cudaStreamQuery(cs_); // WDDM: submit now + steps_seen_ = 0; + chain_live_ = true; + chain_n_ = n_out; + ms_draft += ms_since(t0); + ++rounds; + return true; +} + +int MtpDrafter::chain_outputs_ready(std::string& err) { + if (!chain_live_) return chain_n_; + const OnDevice on_device(device_); + while (steps_seen_ < chain_early_) { + const cudaError_t q = cudaEventQuery(ev_step_[steps_seen_]); + if (q == cudaErrorNotReady) break; + if (q != cudaSuccess) { err = std::string("mtp chain: ") + cudaGetErrorString(q); return -1; } + chain_tok_[steps_seen_] = ((volatile int32_t*) h_out_)[steps_seen_]; + chain_prob_[steps_seen_] = ((volatile float*) h_prob_)[steps_seen_]; + ++steps_seen_; + } + return steps_seen_; +} + +int MtpDrafter::chain_poll(std::string& err) { + if (!chain_live_) return 1; + const OnDevice on_device(device_); + const cudaError_t q = cudaEventQuery(ev_chain_); + if (q == cudaErrorNotReady) return 0; + chain_live_ = false; + if (q != cudaSuccess) { err = std::string("mtp chain: ") + cudaGetErrorString(q); return -1; } + for (int j = 0; j < chain_n_; ++j) { + chain_tok_[j] = ((volatile int32_t*) h_out_)[j]; + chain_prob_[j] = ((volatile float*) h_prob_)[j]; + } + for (int j = chain_n_; j < 8; ++j) { chain_tok_[j] = 0; chain_prob_[j] = 0.0f; } + return 1; +} + bool MtpDrafter::draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, float* probs, float min_p, int* n_drafts) { const OnDevice on_device(device_); diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 02a8e1f6..dc029dbc 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -358,6 +358,12 @@ __global__ void dense_steps_kernel(const int32_t* __restrict__ cells, int n, int steps[i * 4 + 3] = c + 1; } +// --pipeline-windows: the drafter's chain, teacher forced (see force_token) +__global__ void force_token_kernel(int32_t* tok, const int32_t* force, int j) { + const int32_t f = ((const volatile int32_t*) force)[j]; + if (f >= 0) *tok = f; +} + } // namespace void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) { @@ -391,6 +397,11 @@ void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const check("mtp_select"); } +void force_token(int32_t* tok, const int32_t* force, int j, void* stream) { + force_token_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(tok, force, j); + check("force_token"); +} + void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) { cudaStream_t s = (cudaStream_t) stream; if (row_bytes % 16 == 0)