Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Keep MTP drafting in concurrent batch slots

rkcth8cfb3fd7ccfa
diff --git a/docs/BATCHING.md b/docs/BATCHING.md
index 7672dcc58..47597779b 100644
--- a/docs/BATCHING.md
+++ b/docs/BATCHING.md
@@ -19,6 +19,13 @@ asked, with a note when it is more than setup would recommend.
"parallel": 2
```
+On one GPU with MTP enabled, set `MULTI_CONCURRENCY=TRUE` in the server's
+environment to let batch slots use one MTP proposal each. It is opt-in; without
+it, the batch behavior described below is unchanged. The grouped path has only
+been tested on an AMD R9700. It needs additional VRAM per slot for draft state
+and buffers, so check the engine's free-memory log before using it on a smaller
+card. It has not been validated on NVIDIA or with a layer split.
+
With a layer split, the engine options go into the config's `args`:
```
@@ -28,12 +35,12 @@ With a layer split, the engine options go into the config's `args`:
| Option | What it does |
| --- | --- |
-| `"parallel": N` / `--batch N` / `--slots N` (2..8) | up to N conversations decoded together; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. |
+| `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. |
| `--batch-groups G` | with a layer split: the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. |
| `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. |
-The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots (a
-window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads
+The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by
+default (a window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads
the count the engine reports (`INFO batch_slots=N`), and `GET /v1/status` says it (`concurrency.serving`).
### What a slot costs, and what setup recommends
@@ -57,7 +64,8 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske
- **One request alone** runs on the usual solo path (verify windows with MTP drafts): the fastest single stream.
- **When a second request arrives**, the first is stopped (`STOP`) and continues in a batch slot with its prompt
plus what it generated so far - the engine's prompt cache holds exactly that, so nothing is read again - and the
- new request is admitted next to it. A request in a slot decodes **without MTP drafts** (one token per window).
+ new request is admitted next to it. By default, a request in a slot decodes **without MTP drafts** (one token per window).
+ With `MULTI_CONCURRENCY=TRUE`, each slot verifies one MTP proposal alongside its current token.
- **A request left alone in a slot** (the others finished, nobody waits) goes back to the solo path: the slot is
stopped, the engine copies its sessions back and decodes with MTP drafts again (at most twice per request; with
`--prompt-cache 0` it stays in the slot; `STRATA_PARALLEL_SOLO=0` turns it off). The draft layer's own K/V was
@@ -113,8 +121,9 @@ counter-based draw (Philox(seed, position)).
## Limits (for now)
-- Batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo path keeps
- its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone).
+- By default, batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo
+ path keeps its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone).
+- Grouped MTP currently uses one proposal per slot and requires one GPU; it does not support a layer split.
- Repetition / frequency / presence penalties are not applied in batch windows.
- A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk
boundary, and not for pictures.
diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp
index bfb6ee0f5..18305195f 100644
--- a/include/strata/core/mtp.hpp
+++ b/include/strata/core/mtp.hpp
@@ -43,7 +43,7 @@ public:
/// Loads `rt_dir` (from tools/mtp_rt.py) and allocates the layer's K/V and buffers for up to `max_t` rows.
/// Call before the VRAM expert tier is sized: this takes ~0.9 GB.
bool load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
- int64_t window = 32768);
+ int64_t window = 32768, const MtpDrafter* shared = nullptr);
/// The prompt's length: prefill() skips the cells the attention window can never reach again.
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.
@@ -58,7 +58,8 @@ public:
/// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this.
uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const;
/// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each).
- bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err);
+ bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err,
+ 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.
@@ -145,6 +146,9 @@ private:
std::vector<Tensor> tensors_;
uint8_t* dense_ = nullptr;
uint8_t* experts_ = nullptr;
+ // Slot drafters borrow immutable weights and head; each still owns its state and scratch.
+ bool owns_weights_ = true;
+ bool owns_draft_head_ = true;
void* state_arena_ = nullptr;
QsaState st_;
void* arena_ = nullptr;
diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp
index 51c5972f0..c76b92498 100644
--- a/include/strata/core/verify.hpp
+++ b/include/strata/core/verify.hpp
@@ -149,8 +149,11 @@ public:
/// listed are not touched, so an idle slot keeps its state (a finished conversation it may continue later).
bool run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user,
int32_t* out, std::string& err);
- /// Keep every row of the last batch window: each slot's state advances by its one token.
+ /// Keep every row of the last batch window.
bool commit_slots(std::string& err);
+ /// Commit an accepted prefix in each contiguous slot group of the last window. `keep` has
+ /// one entry per slot (indexed by slot ID), each in 1..that slot's group length.
+ bool commit_slot_prefixes(const int* keep, std::string& err);
// ---- The stages of a layer split as a PIPELINE. A batch window over the slot GROUP
// [base, base + S) is launched on ONE stage with its commit right behind it on the stage's stream (a batch window
@@ -221,14 +224,18 @@ private:
int row_base_ = 0; ///< ... its hand-off rows start here (a pipeline group's own rows)
int brow_[8] = {}; ///< ... and row t is slot brow_[t]
bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group)
- std::map<uint64_t, cudaGraphExec_t> exec_bm_, commit_bm_; ///< key: batch_key(rows, S, hand-off base)
+ std::map<std::vector<int>, cudaGraphExec_t> exec_bm_, commit_bm_; ///< full row layout avoids slot-ID collisions
int last_rows_[8] = {}; ///< the slots of the last batch window's rows
- uint64_t bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs
- return batch_key(rows, S, hbase) | (ar_off_ ? (1ull << 63) : 0ull);
+ std::vector<int> bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs
+ std::vector<int> k = batch_key(rows, S, hbase);
+ k.push_back(ar_off_ ? 1 : 0);
+ return k;
}
- static uint64_t batch_key(const int* rows, int S, int hbase) {
- uint64_t k = (uint64_t) hbase << 40 | (uint64_t) S << 32;
- for (int t = 0; t < S; ++t) k |= (uint64_t) (rows[t] & 15) << (4 * t);
+ static std::vector<int> batch_key(const int* rows, int S, int hbase) {
+ std::vector<int> k;
+ k.reserve((size_t) S + 1);
+ k.push_back(hbase);
+ for (int t = 0; t < S; ++t) k.push_back(rows[t]);
return k;
}
// batch_launch / batch_poll
diff --git a/serve/server.py b/serve/server.py
index e755e00bb..be4ddc925 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -1612,7 +1612,7 @@ def engine_args(cfg: dict) -> list[str]:
return learned_profile_args(cfg, args)
-PARALLEL_MAX = 8 # the engine's batch window holds at most 8 rows (kVerifyMaxT)
+PARALLEL_MAX = 8 # normal batch mode; grouped MTP waves more slots through eight-row windows
def parallel_args(cfg: dict, args: list[str]) -> list[str]:
@@ -1630,7 +1630,7 @@ def parallel_args(cfg: dict, args: list[str]) -> list[str]:
return []
if n <= 1:
return []
- if n > PARALLEL_MAX:
+ if n > PARALLEL_MAX and os.environ.get("MULTI_CONCURRENCY") != "TRUE":
print(f'[strata] "parallel": {n} - the engine runs at most {PARALLEL_MAX} requests together; it will use '
f"{PARALLEL_MAX}", flush=True)
return ["--batch", str(n)]
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index e9953e300..b8b83de34 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -123,13 +123,13 @@ MtpDrafter::~MtpDrafter() {
if (h_cparams_) cudaFreeHost(h_cparams_);
if (h_chist_) cudaFreeHost(h_chist_);
if (cs_) cudaStreamDestroy(cs_);
- if (dense_) cudaFree(dense_);
- if (experts_) cudaFree(experts_);
+ if (owns_weights_ && dense_) cudaFree(dense_);
+ if (owns_weights_ && experts_) cudaFree(experts_);
if (state_arena_) cudaFree(state_arena_);
if (arena_) cudaFree(arena_);
if (head_logits_) cudaFree(head_logits_);
- if (dhead_) cudaFree(dhead_);
- if (dvocab_) cudaFree(dvocab_);
+ 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_};
for (void* h : hosts) if (h) cudaFreeHost(h);
}
@@ -148,7 +148,7 @@ const void* MtpDrafter::q8(const char* name) const {
}
bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
- int64_t window) {
+ int64_t window, const MtpDrafter* shared) {
cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there
g_ = &g;
ss_ = &ss;
@@ -156,11 +156,23 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
max_t_ = max_t;
rt_dir_ = rt_dir;
if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT) { err = "mtp: max_t out of range"; return false; }
+ if (shared != nullptr) {
+ if (shared->device_ != device_ || shared->g_ != &g || shared->dense_ == nullptr ||
+ shared->experts_ == nullptr || shared->rt_dir_ != rt_dir) {
+ err = "mtp: incompatible shared weights";
+ return false;
+ }
+ dense_ = shared->dense_;
+ experts_ = shared->experts_;
+ tensors_ = shared->tensors_;
+ owns_weights_ = false;
+ owns_draft_head_ = false;
+ }
// Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting
// them apart from the rest of the stage is what makes the next regression visible.
const auto t_files = std::chrono::steady_clock::now();
// ---- the index and the dense weights
- {
+ if (shared == nullptr) {
std::ifstream idx(rt_dir + "/dense.txt");
if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; }
std::string line;
@@ -187,7 +199,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
vram_ += blob.size();
}
// ---- the 512 routed experts, one blob each
- {
+ if (shared == nullptr) {
const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
// Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under
// MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes.
@@ -302,17 +314,22 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
}
if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; }
const double files_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_files).count();
- std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",
- (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,
- (double) tensors_.back().off / 1048576.0, files_s,
- files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /
- 1048576.0 / files_s : 0.0);
+ if (shared != nullptr) {
+ std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n",
+ (double) vram_ / 1048576.0);
+ } else {
+ std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",
+ (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,
+ (double) tensors_.back().off / 1048576.0, files_s,
+ files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /
+ 1048576.0 / files_s : 0.0);
+ }
return true;
}
uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {
uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);
- if (dhead_ == nullptr) {
+ if (dhead_ == nullptr && owns_draft_head_) {
if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {
std::fseek(f, 0, SEEK_END);
const long size = std::ftell(f);
@@ -420,7 +437,8 @@ void draft_head_hint(int64_t n_tokens, int64_t row_bytes) {
}
} // namespace
-bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) {
+bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err,
+ const MtpDrafter* shared) {
const OnDevice on_device(device_);
wt_ = &wt;
head_ = head;
@@ -434,8 +452,19 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float
err = "mtp: the draft logits do not fit";
return false;
}
+ if (shared != nullptr) {
+ if (shared->head_ != head || shared->device_ != device_ ||
+ shared->n_vocab_ != n_vocab_) {
+ err = "mtp: incompatible shared draft head";
+ return false;
+ }
+ dhead_ = shared->dhead_;
+ dvocab_ = shared->dvocab_;
+ n_dvocab_ = shared->n_dvocab_;
+ owns_draft_head_ = false;
+ }
// the draft head's token subset, when tools/draft_vocab.py wrote one
- if (dhead_ == nullptr) {
+ if (dhead_ == nullptr && shared == nullptr) {
std::vector<uint8_t> raw;
if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
n_dvocab_ = (int64_t) (raw.size() / 4);
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index 8db8f0086..4e76f995b 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -724,13 +724,15 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
native_quantize_q8_1(xm, xq_, (int) N, n, cs);
native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs);
stamp(l, 2, grp);
- if (batch_rec_) { // each row from its own slot's conv history, one row each
- for (int t = tb; t < te; ++t) {
- SessionState& sx = slot_ss(t);
+ if (batch_rec_) { // contiguous rows may be proposals for the same slot
+ for (int t = tb; t < te;) {
+ const int first = t;
+ while (t < te && brow_[t] == brow_[first]) ++t;
+ SessionState& sx = slot_ss(first);
const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats +
(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
- gdn_conv_l2_multi(cx, qkv + (size_t) t * C, (const float*) wc->data, hb + (size_t) t * C, (int) C,
- (int) (2 * HK), EPS, 1, cs, 0);
+ gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data,
+ hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0);
}
} else
gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb);
@@ -742,13 +744,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs);
stamp(l, 5, grp);
// the recurrence from the untouched state over tokens [0, te); outputs only for this group's
- if (batch_rec_) { // each row's recurrence from its own slot's state, one token
- for (int t = tb; t < te; ++t) {
- SessionState& sx = slot_ss(t);
+ if (batch_rec_) { // each slot's recurrence over its own proposed-token group
+ for (int t = tb; t < te;) {
+ const int first = t;
+ while (t < te && brow_[t] == brow_[first]) ++t;
+ SessionState& sx = slot_ss(first);
float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
- gdn_step_norm_multi(stx, hb + (size_t) t * C, (int) C, gate + (size_t) t * HV, beta + (size_t) t * HV,
- z_ + (size_t) t * ZV, (const float*) wnm->data, EPS, y_ + (size_t) t * ZV,
- (int) HK, (int) HV, 1, nullptr, cs, 0);
+ gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV,
+ beta + (size_t) first * HV, z_ + (size_t) first * ZV,
+ (const float*) wnm->data, EPS, y_ + (size_t) first * ZV,
+ (int) HK, (int) HV, t - first, nullptr, cs, 0);
}
} else
gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
@@ -795,10 +800,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
}
stamp(l, 8, grp);
- if (batch_rec_) { // every slot's indexer tail, restored by its commit
+ if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row
for (int t = tb; t < te; ++t)
- copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, slot_ss(t).qsa_states[qi].idx_tail,
- TS, cs);
+ if (t == tb || brow_[t] != brow_[t - 1])
+ copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS,
+ slot_ss(t).qsa_states[qi].idx_tail, TS, cs);
} else
if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);
for (int t = tb; t < te; ++t) {
@@ -1776,8 +1782,8 @@ bool Verifier::wait_commit(std::string& err) {
bool Verifier::init_slots(const std::vector<SessionState*>& slots, std::string& err) {
const OnDevice on_device(device_);
if (g_ == nullptr || ss_ == nullptr) { err = "verify: init_slots before init"; return false; }
- if (slots.empty() || (int) slots.size() > max_t_) {
- err = "verify: init_slots needs 1.." + std::to_string(max_t_) + " sessions";
+ if (slots.empty()) {
+ err = "verify: init_slots needs at least one session";
return false;
}
for (SessionState* x : slots) {
@@ -1843,7 +1849,7 @@ bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err
}
bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::string& err) {
- cudaGraphExec_t& cex = commit_bm_[batch_key(rows, S, hbase)];
+ cudaGraphExec_t& cex = commit_bm_[bkey(rows, S, hbase)];
if (cex != nullptr) return true;
using namespace strata::kernels;
const ModelGeometry& g = *g_;
@@ -1861,7 +1867,8 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri
bool ok = true;
try {
for (int t = 0; t < S; ++t)
- copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_);
+ if (t == 0 || rows[t] != rows[t - 1])
+ copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_);
int64_t qsa_index = 0, gdn_index = 0;
for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
for (int64_t l = lb_; l < le_ && ok; ++l) {
@@ -1869,36 +1876,49 @@ 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; }
- for (int t = 0; t < S; ++t) {
- SessionState& sx = *slots_[(size_t) rows[t]];
- const int32_t* keep = commitb_ + (size_t) rows[t] * CB;
+ for (int t = 0; t < S;) {
+ const int first = t;
+ while (t < S && rows[t] == rows[first]) ++t;
+ SessionState& sx = *slots_[(size_t) rows[first]];
+ const int32_t* keep = commitb_ + (size_t) rows[first] * CB;
float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats;
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) t * C, (int) C, keep, cs_);
- gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) t * C, (int) C,
- gate_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV,
- beta_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV, z_ + (size_t) t * ZV,
- (const float*) wnm->data, EPS, y_dummy_ + (size_t) t * ZV, (int) g.ssm_k_heads,
- (int) HV, 1, keep, cs_);
+ gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C,
+ (int) C, keep, cs_);
+ 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,
+ z_ + (size_t) first * ZV, (const float*) wnm->data, EPS,
+ y_dummy_ + (size_t) first * ZV, (int) g.ssm_k_heads,
+ (int) HV, t - first, keep, cs_, t - first);
}
++gdn_index;
} else {
const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
if (!wikn) { ok = false; break; }
- for (int t = 0; t < S; ++t) {
- const QsaState& st = slots_[(size_t) rows[t]]->qsa_states[qsa_index];
- copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[t] * nQ + qsa_index) * TS, TS, cs_);
+ for (int t = 0; t < S;) {
+ const int first = t;
+ while (t < S && rows[t] == rows[first]) ++t;
+ const QsaState& st = slots_[(size_t) rows[first]]->qsa_states[qsa_index];
+ copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[first] * nQ + qsa_index) * TS,
+ TS, cs_);
const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
- native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commitb_ + (size_t) rows[t] * CB + 2,
- 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_);
+ for (int u = first; u < t; ++u)
+ native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + u) * ID,
+ commitb_ + (size_t) rows[first] * CB + 2 + (u - first),
+ 0, (const float*) wikn->data, EPS, ib, s, st.max_cells,
+ rope_scaling(), cs_);
}
++qsa_index;
}
}
if (ok && ss_->ple.ready() && ple_stage())
- for (int t = 0; t < S; ++t)
- copy_indexed(slots_[(size_t) rows[t]]->ple_hist, hist_snap_ + (size_t) t * HS, HS,
- commitb_ + (size_t) rows[t] * CB + 1, HS, cs_);
+ for (int t = 0; t < S;) {
+ const int first = t;
+ while (t < S && rows[t] == rows[first]) ++t;
+ copy_indexed(slots_[(size_t) rows[first]]->ple_hist, hist_snap_ + (size_t) first * HS,
+ HS, commitb_ + (size_t) rows[first] * CB + 1, HS, cs_);
+ }
} catch (const std::exception& e) {
err = std::string("verify batch commit: ") + e.what();
ok = false;
@@ -1921,14 +1941,29 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri
bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos,
std::string& err) {
using namespace strata::kernels;
- if (S < 1 || S > max_t_ || hbase < 0 || hbase + S > (int) slots_.size()) {
+ if (S < 1 || S > max_t_ || hbase < 0 ||
+ (next_ != nullptr && hbase + S > (int) slots_.size())) {
err = "verify: batch rows out of range (init_slots)";
return false;
}
for (int t = 0; t < S; ++t) {
- bool dup = false;
- for (int u = 0; u < t; ++u) dup = dup || rows[u] == rows[t];
- if (rows[t] < 0 || rows[t] >= (int) slots_.size() || dup) { err = "verify: a batch row's slot is out of range or twice"; return false; }
+ if (rows[t] < 0 || rows[t] >= (int) slots_.size()) {
+ err = "verify: a batch row's slot is out of range";
+ return false;
+ }
+ for (int u = 0; u < t - 1; ++u)
+ if (rows[u] == rows[t] && rows[t - 1] != rows[t]) {
+ err = "verify: a slot's proposed rows must be contiguous";
+ return false;
+ }
+ if (t > 0 && rows[t] == rows[t - 1] && pos[t] != pos[t - 1] + 1) {
+ err = "verify: proposed rows must have consecutive positions";
+ return false;
+ }
+ if (t > 0 && rows[t] == rows[t - 1] && next_ != nullptr) {
+ err = "verify: grouped slot rows do not support a layer split yet";
+ return false;
+ }
}
if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
const ModelGeometry& g = *g_;
@@ -1938,6 +1973,24 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok
return false;
}
refresh_ar();
+ // Slot rotation creates new layouts; bound the captured graph pairs.
+ const auto key = bkey(rows, S, hbase);
+ constexpr size_t graph_limit = 32;
+ if (exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= graph_limit) {
+ if (cudaStreamSynchronize(cs_) != cudaSuccess) {
+ err = "verify: synchronizing before batch graph eviction failed";
+ return false;
+ }
+ auto old = exec_bm_.begin();
+ const auto old_key = old->first;
+ if (old->second) cudaGraphExecDestroy(old->second);
+ exec_bm_.erase(old);
+ auto commit_old = commit_bm_.find(old_key);
+ if (commit_old != commit_bm_.end()) {
+ if (commit_old->second) cudaGraphExecDestroy(commit_old->second);
+ commit_bm_.erase(commit_old);
+ }
+ }
if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false;
const Clock::time_point t0 = Clock::now();
const QsaShapes s = shapes_of(g);
@@ -1955,18 +2008,25 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok
for (int t = 0; t < S; ++t) {
const SessionState& sx = *slots_[(size_t) rows[t]];
int32_t prev[2] = {sx.ple_prev[0], sx.ple_prev[1]};
+ if (t > 0 && rows[t] == rows[t - 1]) {
+ prev[0] = t > 1 && rows[t - 2] == rows[t] ? tokens[t - 2] : sx.ple_prev[1];
+ prev[1] = tokens[t - 1];
+ }
ngram_rows(&tokens[t], prev, 1, ss_->ple.consts, ple_rows + t * PLE_N_HEADS);
}
if (!ss_->ple.table->gather_batch(ple_rows, (size_t) S, h_ple_, err)) return false;
}
- // the commit's rows (a batch window keeps every row): [1, 0, position, -1 ..] per slot
+ // Each slot owns a contiguous group. The default commit keeps all its rows; speculative
+ // decoding may change the prefix length after comparing the draft with these picks.
const int64_t CB = 2 + max_t_;
- for (int t = 0; t < S; ++t) {
- int32_t* c = h_commitb_ + (size_t) rows[t] * CB;
- c[0] = 1;
- c[1] = 0;
- c[2] = (int32_t) pos[t];
- for (int64_t j = 3; j < CB; ++j) c[j] = -1;
+ for (int t = 0; t < S;) {
+ const int first = t;
+ while (t < S && rows[t] == rows[first]) ++t;
+ int32_t* c = h_commitb_ + (size_t) rows[first] * CB;
+ c[0] = t - first;
+ c[1] = t - first - 1;
+ for (int64_t j = 0; j < max_t_; ++j)
+ c[2 + j] = j < t - first ? (int32_t) pos[first + j] : -1;
}
*(volatile uint32_t*) h_seq_ = 0;
*(volatile uint32_t*) h_flag_ = 0;
@@ -2085,23 +2145,49 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons
}
bool Verifier::commit_slots(std::string& err) {
+ std::vector<int> keep(slots_.size(), 0);
+ for (int t = 0; t < last_t_; ++t) ++keep[(size_t) last_rows_[t]];
+ return commit_slot_prefixes(keep.data(), err);
+}
+
+bool Verifier::commit_slot_prefixes(const int* keep, std::string& err) {
const OnDevice on_device(device_);
if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; }
const int S = last_t_;
const Clock::time_point t0 = Clock::now();
+ const int64_t CB = 2 + max_t_;
+ // One prefix per slot: rejected draft rows must not enter recurrent state.
+ for (int t = 0; t < S;) {
+ const int first = t;
+ while (t < S && last_rows_[t] == last_rows_[first]) ++t;
+ const int n = keep[last_rows_[first]];
+ if (n < 1 || n > t - first) {
+ err = "verify: accepted prefix is outside its slot group";
+ return false;
+ }
+ int32_t* c = h_commitb_ + (size_t) last_rows_[first] * CB;
+ c[0] = n;
+ c[1] = n - 1;
+ for (int j = 0; j < max_t_; ++j)
+ c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1;
+ }
std::atomic_thread_fence(std::memory_order_seq_cst);
- const cudaError_t le = cudaGraphLaunch(commit_bm_[batch_key(last_rows_, S, row_base_)], cs_);
+ const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_);
if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; }
const cudaError_t se = cudaStreamSynchronize(cs_);
if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; }
if (ple_stage())
- for (int t = 0; t < S; ++t) {
- SessionState& sx = *slots_[(size_t) last_rows_[t]];
- sx.ple_prev[0] = sx.ple_prev[1];
- sx.ple_prev[1] = last_tokens_[t];
+ for (int t = 0; t < S;) {
+ const int first = t;
+ while (t < S && last_rows_[t] == last_rows_[first]) ++t;
+ SessionState& sx = *slots_[(size_t) last_rows_[first]];
+ for (int u = first; u < first + keep[last_rows_[first]]; ++u) {
+ sx.ple_prev[0] = sx.ple_prev[1];
+ sx.ple_prev[1] = last_tokens_[u];
+ }
}
ms_commit += ms_since(t0);
- return next_ == nullptr || next_->commit_slots(err);
+ return next_ == nullptr || next_->commit_slot_prefixes(keep, err);
}
bool Verifier::sample_rows(int S, std::string& err) {
@@ -2126,7 +2212,7 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_
for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t;
if (!stage_batch(rows, S, base, tokens, pos, err)) return false;
cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_);
- if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[batch_key(rows, S, base)], cs_); // right behind it: every row is kept
+ if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_); // right behind it: every row is kept
if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; }
(void) cudaStreamQuery(cs_);
if (ple_stage()) // the host's side of the commit (the hash's last two tokens)
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 907a23c6b..2aa845ebf 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -651,7 +651,8 @@ void usage() {
" --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n"
" default 512), so the command `VRAM <reserve_mib>` (the server's POST /v1/vram) can\n"
" give VRAM back to other programs between requests and take it back later\n"
- " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8),\n"
+ " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n"
+ " normally; MULTI_CONCURRENCY=TRUE waves more through eight-row windows),\n"
" each slot with its own session (VRAM like the main one); docs/BATCHING.md\n"
" --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n"
" --trim-stage-weights an explicit --layer-split: each GPU loads only its own layers' dense weights\n"
@@ -2961,6 +2962,8 @@ int main(int argc, char** argv) {
// slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room.
// Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the
// engine still starts and serves one request at a time.
+ const char* multi_concurrency = std::getenv("MULTI_CONCURRENCY");
+ const bool batch_mtp_requested = multi_concurrency != nullptr && std::strcmp(multi_concurrency, "TRUE") == 0;
std::vector<std::vector<std::unique_ptr<strata::core::SessionState>>> bslot_ss;
if (o.batch != 0) {
const int cap = strata::kernels::kVerifyMaxT;
@@ -2969,7 +2972,7 @@ int main(int argc, char** argv) {
if (off != nullptr) {
std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off);
o.batch = 0;
- } else if (o.batch > cap) {
+ } else if (o.batch > cap && !batch_mtp_requested) {
std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d "
"slots\n", o.batch, cap, cap);
o.batch = cap;
@@ -3033,6 +3036,12 @@ int main(int argc, char** argv) {
// Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts.
// In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages.
strata::core::MtpDrafter mtp;
+ const bool batch_mtp = batch_mtp_requested;
+ if (batch_mtp && (o.batch < 2 || o.mtp.empty() || multi_gpu)) {
+ std::fprintf(stderr, "strata generate: MULTI_CONCURRENCY=TRUE needs at least two slots, --mtp and one GPU\n");
+ return 2;
+ }
+ std::vector<std::unique_ptr<strata::core::MtpDrafter>> slot_mtp;
if (!o.mtp.empty()) {
if (o.spec < 2) {
std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
@@ -3046,6 +3055,19 @@ int main(int argc, char** argv) {
const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1);
if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; }
mtp.set_ple_session(&ss);
+ if (batch_mtp) {
+ for (int b = 0; b < o.batch; ++b) {
+ auto d = std::make_unique<strata::core::MtpDrafter>();
+ if (!d->load(o.mtp, draft_geometry, *bslot_ss[0][(size_t) b], o.spec, err, o.mtp_window, &mtp)) {
+ std::fprintf(stderr, "strata generate: batch MTP slot %d: %s%s\n", b, err.c_str(),
+ vram_free_note().c_str());
+ return 1;
+ }
+ d->set_max_drafts(1); // the first candidate verifies one proposal per slot
+ d->set_ple_session(bslot_ss[0][(size_t) b].get());
+ slot_mtp.push_back(std::move(d));
+ }
+ }
}
// THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so
// everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after
@@ -3244,8 +3266,10 @@ int main(int argc, char** argv) {
const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
// the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them
// ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199)
- const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())
- ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;
+ int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())
+ ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;
+ for (const auto& d : slot_mtp)
+ mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab);
const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind;
const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
int64_t slots = ((int64_t) free_b - reserve) / blob;
@@ -5177,11 +5201,31 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str());
}
ver.set_remote_expert_opt(remote_opt.get());
- if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err) ||
+ if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr,
+ batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) ||
!mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, ver.final_R_all(), err)) {
std::fprintf(stderr, "strata serve: %s\n", err.c_str());
return 1;
}
+ auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); };
+ std::vector<std::unique_ptr<float, decltype(free_slot_mtp_rows)>> slot_mtp_rows;
+ if (batch_mtp) {
+ for (int b = 0; b < o.batch; ++b) {
+ float* r = nullptr;
+ const size_t bytes = (size_t) o.spec * (size_t) g.hc * (size_t) g.n_embd * sizeof(float);
+ if (cudaMalloc((void**) &r, bytes) != cudaSuccess) {
+ std::fprintf(stderr, "strata serve: batch MTP slot %d residual buffer does not fit%s\n",
+ b, vram_free_note().c_str());
+ return 1;
+ }
+ slot_mtp_rows.emplace_back(r, free_slot_mtp_rows);
+ if (!slot_mtp[(size_t) b]->bind(wt, &native_head, r, err, &mtp)) {
+ std::fprintf(stderr, "strata serve: batch MTP slot %d: %s%s\n", b, err.c_str(),
+ vram_free_note().c_str());
+ return 1;
+ }
+ }
+ }
// each stage's verifier gets its stage's slot sessions
if (o.batch > 0) {
for (size_t k = 0; k < bslot_ss.size(); ++k) {
@@ -5944,6 +5988,8 @@ int main(int argc, char** argv) {
struct BSlot {
bool active = false, stop = false;
int32_t x = 0; ///< the token the next window feeds (not yet in the slot's state)
+ std::array<int32_t, strata::kernels::kVerifyMaxT> draft{}; ///< the slot's next MTP proposal
+ bool draft_ready = false;
int64_t p = 0; ///< its position
int64_t produced = 0, max_new = 0;
Clock::time_point t0;
@@ -6002,6 +6048,18 @@ int main(int argc, char** argv) {
}
if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; }
}
+ if (batch_mtp) {
+ // Admission first builds the solo draft KV; copy it into the slot before drafting.
+ static const strata::core::ModelGeometry draft_g{};
+ strata::core::ConversationKv image;
+ if (!mtp.idle(e) || !slot_mtp[(size_t) b]->idle(e) ||
+ !strata::core::conversation_kv_save(image, mtp.kv_state(), draft_g, upto, false, e) ||
+ !strata::core::conversation_kv_restore(image, slot_mtp[(size_t) b]->kv_state(),
+ draft_g, upto, false, e) ||
+ cudaDeviceSynchronize() != cudaSuccess)
+ return false;
+ slot_mtp[(size_t) b]->set_prompt_len(upto);
+ }
return true;
};
// slot b's sessions -> the main ones (the reverse of copy_to_slot): a request that continues the
@@ -6035,6 +6093,18 @@ int main(int argc, char** argv) {
}
if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; }
}
+ if (batch_mtp) {
+ // A returning solo request resumes from its slot's draft KV.
+ static const strata::core::ModelGeometry draft_g{};
+ strata::core::ConversationKv image;
+ if (!slot_mtp[(size_t) b]->idle(e) || !mtp.idle(e) ||
+ !strata::core::conversation_kv_save(image, slot_mtp[(size_t) b]->kv_state(),
+ draft_g, upto, false, e) ||
+ !strata::core::conversation_kv_restore(image, mtp.kv_state(), draft_g, upto, false, e) ||
+ cudaDeviceSynchronize() != cudaSuccess)
+ return false;
+ mtp.set_prompt_len(upto);
+ }
return true;
};
// one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched,
@@ -6044,13 +6114,32 @@ int main(int argc, char** argv) {
int rows[strata::kernels::kVerifyMaxT] = {};
int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {};
int64_t pos[strata::kernels::kVerifyMaxT] = {};
- for (int b = 0; b < (int) bs.size() && S < strata::kernels::kVerifyMaxT; ++b)
+ int first[strata::kernels::kVerifyMaxT] = {}, active[strata::kernels::kVerifyMaxT] = {};
+ static size_t next_slot = 0;
+ // Each MTP slot uses two rows; rotate slots when more than four are active.
+ int A = 0;
+ for (size_t offset = 0; offset < bs.size() && S + (batch_mtp ? 2 : 1) <= strata::kernels::kVerifyMaxT; ++offset) {
+ const int b = (int) ((next_slot + offset) % bs.size());
if (bs[(size_t) b].active) {
+ first[A] = S;
+ active[A++] = b;
rows[S] = b;
tok[S] = bs[(size_t) b].x;
pos[S] = bs[(size_t) b].p;
++S;
+ if (batch_mtp) {
+ rows[S] = b;
+ if (!bs[(size_t) b].draft_ready) {
+ err = "batch MTP: a live slot has no draft";
+ return false;
+ }
+ tok[S] = bs[(size_t) b].draft[0];
+ pos[S] = bs[(size_t) b].p + 1;
+ ++S;
+ }
}
+ }
+ if (batch_mtp && A > 0) next_slot = ((size_t) active[A - 1] + 1) % bs.size();
if (S == 0) return true;
const bool was_busy = strata::core::progress().busy.load();
strata::core::progress().busy.store(true);
@@ -6069,7 +6158,16 @@ int main(int argc, char** argv) {
return false;
}
const Clock::time_point w1 = Clock::now();
- if (!ver.commit_slots(err)) {
+ // Accept the proposal only when the target picked it and there is room to emit both tokens.
+ std::vector<int> keep(bs.size(), 0);
+ for (int a = 0; a < A; ++a) {
+ const int b = active[a], i = first[a];
+ const BSlot& sl = bs[(size_t) b];
+ const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i]) != o.eos_ids.end();
+ keep[b] = batch_mtp && outb[i] == tok[i + 1] && !eos && !sl.stop &&
+ sl.produced + 2 <= sl.max_new && sl.p + 3 <= o.max_context ? 2 : 1;
+ }
+ if (!(batch_mtp ? ver.commit_slot_prefixes(keep.data(), err) : ver.commit_slots(err))) {
std::printf("ERR %s\n", err.c_str());
return false;
}
@@ -6078,26 +6176,40 @@ int main(int argc, char** argv) {
bt_run += msd(w0, w1);
bt_commit += msd(w1, w2);
++bt_windows;
- bt_rows += S;
- for (int t = 0; t < S; ++t) {
- const int b = rows[t];
+ for (int a = 0; a < A; ++a) bt_rows += keep[active[a]];
+ for (int t = 0; t < A; ++t) {
+ const int b = active[t];
BSlot& sl = bs[(size_t) b];
- const int32_t y = outb[t];
- sl.ids.push_back(sl.x); // the window fed it: the slot's sessions hold it now
- std::printf("BT %d %d\n", b, (int) y);
- ++sl.produced;
- 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;
- if (fin != nullptr) {
- const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
- std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms);
- sl.active = false;
- sl.cached = o.prompt_cache > 0 && !sl.img; // its sessions hold sl.ids for the next turn
- } else {
+ for (int j = 0; j < keep[b]; ++j) {
+ const int32_t y = outb[first[t] + j];
+ sl.ids.push_back(tok[first[t] + j]);
+ std::printf("BT %d %d\n", b, (int) y);
+ ++sl.produced;
+ 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;
+ if (fin != nullptr) {
+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
+ std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms);
+ sl.active = false;
+ sl.cached = o.prompt_cache > 0 && !sl.img;
+ break;
+ }
sl.x = y;
sl.p += 1;
}
+ if (batch_mtp && sl.active) {
+ const size_t stride = (size_t) g.hc * (size_t) g.n_embd;
+ if (cudaMemcpy(slot_mtp_rows[(size_t) b].get(),
+ ver.final_R_all() + (size_t) first[t] * stride,
+ 2 * stride * sizeof(float), cudaMemcpyDeviceToDevice) != cudaSuccess ||
+ !slot_mtp[(size_t) b]->draft(2, outb + first[t], pos[first[t]], keep[b] - 1,
+ sl.draft.data(), err)) {
+ std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str());
+ return false;
+ }
+ sl.draft_ready = true;
+ }
}
std::fflush(stdout);
bt_emit += msd(w2, Clock::now());
@@ -7445,6 +7557,15 @@ int main(int argc, char** argv) {
sl.max_new = admit_max_new;
sl.t0 = Clock::now();
sl.ids = live;
+ if (batch_mtp) {
+ if (!slot_mtp[(size_t) admit_slot]->draft_first(1, ver.final_R_all(), sl.x,
+ sl.p - 1, sl.draft.data(), err)) {
+ std::fprintf(stderr, "strata batch: MTP admission for slot %d failed: %s\n",
+ admit_slot, err.c_str());
+ return 1;
+ }
+ sl.draft_ready = true;
+ }
sl.cvec = cvec_cached;
sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached
const ConvCheckpoint* best = nullptr;