diff --git a/abi/rad_builder.h b/abi/rad_builder.h index eee2f213..2e18b8bb 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -671,6 +671,17 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); * embedding-only or encoder-only plugin declares none. */ int rad_declare_logits(RadBuilder* b, rad_buf logits); +/* Scored steps (RadBatch::score_only). A plugin whose lm_head is the bf16 table `table` + * ([n_vocab, n_embd], e.g. a tied embedding, whatever encoding the head itself is read at) and + * whose final-normed rows land in `hidden` ([rows, n_embd] bf16, row k the step's k-th sampled row, + * as the lm_head reads them) declares both here. On a step where every sampled row is a scored row + * the core sets RadBatch::score_only, the plugin issues everything but the lm_head, and the core + * reads the hidden rows and the candidates' table rows back and takes the dot products on the host + * in f64: the logits a scored request returns, at no head read on the card (half a gigabyte a step + * at a 128K bf16 vocabulary). Optional; one rank only (the core ignores it at --tp > 1). + * Additive export; RAD_ABI_VERSION does not move. */ +int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table); + /* Which buffer holds this step's pooled vectors, what an embedding model returns instead of * logits. Row s is sequence s's whole input pooled into one vector, with whatever pooling the * model was trained with (a mean, the last token, a CLS row). The core reads rows [0, n_seq) back diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index fb4bc5bf..ee1c4d5f 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -295,6 +295,16 @@ typedef struct RadBatch { * position tables per grid) reads them here; they live as long as the pass. */ const int32_t* enc_seg_h; const int32_t* enc_seg_w; + + /* ================================================ scored steps */ + + /* Non-zero when every row the sampler wants is a scored row (a /v1/systemone question: the raw + * logits at a few candidate ids, the sampled token discarded) and the program declared where + * the core finds the hidden rows and the head (rad_declare_scores). The plugin then skips its + * lm_head and leaves `rad_declare_scores`' hidden buffer holding the gathered, final-normed + * rows; the core computes the candidates' logits itself. Zero on every other step, and always + * for a program that declared no scores. Appended; an older plugin never sees it set. */ + int32_t score_only; } RadBatch; /* What a generator pass carries beside the step batch's own fields, which keep their meanings: diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 7bc985a3..68757100 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -123,6 +123,7 @@ public: int op_declared (const char* op) const; int decl_name_map(const RadNameMap* m); int declare_logits(rad_buf b); + int declare_scores(rad_buf hidden, rad_weight table); int declare_pooled(rad_buf b); int declare_drafter(const RadDrafterDecl* d); int drafter_shared_kv(int pos_offset); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 67724102..c88c4c88 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1134,6 +1134,30 @@ int Builder::decl_name_map(const RadNameMap* m) { /* The buffer the core samples from. A second call is refused rather than winning: a target and * its drafter declaring into one builder (spec ยง10) both have logits, and keeping the second would * sample the draft distribution. The drafter's logits are reached through its scope. */ +int Builder::declare_scores(rad_buf hidden, rad_weight table) { + if (finished_) { err(RAD_E_STATE, "declare_scores after declare finished"); return RAD_E_STATE; } + if (hidden == RAD_NULL_HANDLE || (size_t)hidden >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_scores: %u is not a declared buffer", (unsigned)hidden); + return RAD_E_INVAL; + } + if (table == RAD_NULL_HANDLE || (size_t)table >= prog_.weights.size()) { + err(RAD_E_INVAL, "declare_scores: %u is not a declared weight", (unsigned)table); + return RAD_E_INVAL; + } + const RadBufDecl& h = prog_.buffers[hidden].decl; + const auto& w = prog_.weights[table]; + if (h.dtype != RAD_BF16 || h.rank != 2 || w.decl.dtype != RAD_BF16 || w.decl.rank != 2 || + w.decl.shape[1] != h.shape[1]) { + err(RAD_E_INVAL, "declare_scores: the hidden rows ('%s') and the table ('%s') must be bf16 " + "[rows, n_embd] and [n_vocab, n_embd]", prog_.buffers[hidden].name.c_str(), + w.name.c_str()); + return RAD_E_INVAL; + } + prog_.score_hidden = hidden; + prog_.score_table = table; + return RAD_OK; +} + int Builder::declare_logits(rad_buf b) { if (finished_) { err(RAD_E_STATE, "declare_logits after declare finished"); return RAD_E_STATE; } if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) { @@ -2630,6 +2654,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) { return B(b)->declare_logits(logits); } +int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_scores(hidden, table); +} + int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { if (!b) return RAD_E_INVAL; return B(b)->declare_pooled(pooled); diff --git a/core/engine.cpp b/core/engine.cpp index b2c84939..d4e5a0dd 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1198,6 +1198,8 @@ int Engine::save_checkpoints() { * row is copied (512 KB at a 128K vocabulary), which is cheaper than one copy per id. */ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { score_rows_.clear(); + score_only_ = false; + score_ids_.clear(); if (embedding_) return RAD_OK; for (size_t i = 0; i < plan.e.size(); ++i) { const Request* r = plan.e[i].req; @@ -1206,16 +1208,35 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { } if (score_rows_.empty()) return RAD_OK; const int64_t n = (int64_t)score_rows_.size(); + + /* A scored step reads back the hidden rows and the candidates' table rows instead of whole + * logits rows (BatchBuilder set the flag on the same facts). */ + const RadBatch* b0 = sched_.batch_for(0); + score_only_ = b0 && b0->score_only; + if (score_only_) { + const Program& p = ranks_[0]->program; + score_embd_ = p.buffers[p.score_hidden].decl.shape[1]; + for (const auto& sr : score_rows_) + for (int32_t t : sr.second->tokens) score_ids_.push_back(t); + std::sort(score_ids_.begin(), score_ids_.end()); + score_ids_.erase(std::unique(score_ids_.begin(), score_ids_.end()), score_ids_.end()); + } for (auto& rk : ranks_) { - if (n <= rk->score_rows_cap) continue; + const int64_t width = rk->sampler.config().n_vocab_local; + /* In floats: n logits rows, or the bf16 hidden and table rows of a scored step. */ + int64_t rows = n; + if (score_only_) { + const int64_t need = ((n + (int64_t)score_ids_.size()) * score_embd_ + 1) / 2; + rows = std::max(rows, (need + width - 1) / width); + } + if (rows <= rk->score_rows_cap) continue; if (ranks_.size() > 1) RAD_TRY(rad_dev_set(rk->device)); if (rk->score_host) rad_dev_free(rk->score_host, RAD_MEM_HOST_PINNED); - const int64_t width = rk->sampler.config().n_vocab_local; rk->score_host = static_cast( - rad_dev_alloc(n * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED)); - rk->score_rows_cap = rk->score_host ? n : 0; + rad_dev_alloc(rows * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED)); + rk->score_rows_cap = rk->score_host ? rows : 0; if (!rk->score_host) { - RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)n); + RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)rows); return RAD_E_NOMEM; } } @@ -1225,8 +1246,27 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { int Engine::issue_scored_rows(Rank& r) { const int64_t width = r.sampler.config().n_vocab_local; - const char* logits = static_cast(r.ctx.buf_ptr(r.program.logits_buf)); + char* const logits = static_cast(r.ctx.buf_ptr(r.program.logits_buf)); if (!logits || !r.score_host) return RAD_E_STATE; + if (score_only_) { + /* The plugin left the hidden rows and ran no lm_head: read back each scored row's hidden + * state and the table rows its candidates name, then zero the logits rows the sampler is + * about to read, so the token it draws (and the caller discards) is drawn from defined + * values. One rank (BatchBuilder). */ + const int64_t rb = score_embd_ * (int64_t)sizeof(uint16_t); + const char* hid = static_cast(r.ctx.buf_ptr(r.program.score_hidden)); + const char* tab = static_cast(r.ctx.weight_ptr(r.program.score_table)); + if (!hid || !tab) return RAD_E_STATE; + char* host = reinterpret_cast(r.score_host); + const int64_t n = (int64_t)score_rows_.size(); + for (int64_t k = 0; k < n; ++k) + RAD_TRY(rad_memcpy_async(host + k * rb, hid + (int64_t)score_rows_[(size_t)k].first * rb, + rb, r.ctx.stream())); + for (size_t j = 0; j < score_ids_.size(); ++j) + RAD_TRY(rad_memcpy_async(host + (n + (int64_t)j) * rb, tab + (int64_t)score_ids_[j] * rb, + rb, r.ctx.stream())); + return rad_memset_async(logits, 0, n * width * (int64_t)sizeof(float), r.ctx.stream()); + } for (size_t k = 0; k < score_rows_.size(); ++k) RAD_TRY(rad_memcpy_async(r.score_host + (int64_t)k * width, logits + (int64_t)score_rows_[k].first * width * 4, @@ -1234,6 +1274,18 @@ int Engine::issue_scored_rows(Rank& r) { return RAD_OK; } +/* A scored step's logits: the dot product of a row's hidden state with each candidate's table row, + * bf16 operands widened exactly and summed in f64, then rounded once to f32. */ +static float score_dot(const uint16_t* h, const uint16_t* w, int64_t n) { + double acc = 0.0; + for (int64_t i = 0; i < n; ++i) { + const float a = __builtin_bit_cast(float, (uint32_t)h[i] << 16); + const float b = __builtin_bit_cast(float, (uint32_t)w[i] << 16); + acc += (double)a * (double)b; + } + return (float)acc; +} + int Engine::collect_scored_rows() { if (score_rows_.empty()) return RAD_OK; /* collect_step's wait fences rank 0's stream; every other rank's copies are fenced here. */ @@ -1242,6 +1294,23 @@ int Engine::collect_scored_rows() { RAD_TRY(rad_stream_sync(ranks_[i]->ctx.stream())); } if (ranks_.size() > 1) RAD_TRY(rad_dev_set(ranks_[0]->device)); + if (score_only_) { + const uint16_t* host = reinterpret_cast(ranks_[0]->score_host); + const int64_t n = (int64_t)score_rows_.size(); + for (int64_t k = 0; k < n; ++k) { + TokenScores& ts = *score_rows_[(size_t)k].second; + ts.logits.assign(ts.tokens.size(), 0.0f); + for (size_t j = 0; j < ts.tokens.size(); ++j) { + const auto it = std::lower_bound(score_ids_.begin(), score_ids_.end(), ts.tokens[j]); + const int64_t c = it - score_ids_.begin(); + ts.logits[j] = score_dot(host + k * score_embd_, host + (n + c) * score_embd_, + score_embd_); + } + } + score_rows_.clear(); + score_only_ = false; + return RAD_OK; + } for (size_t k = 0; k < score_rows_.size(); ++k) { TokenScores& ts = *score_rows_[k].second; ts.logits.assign(ts.tokens.size(), 0.0f); diff --git a/core/engine.h b/core/engine.h index b10743c4..e9038283 100644 --- a/core/engine.h +++ b/core/engine.h @@ -315,6 +315,12 @@ private: * Written by the scheduler thread while the ranks are parked, read by them during the step, * consumed by collect_step. */ std::vector> score_rows_; + /* A scored step (RadBatch::score_only): the plugin ran no lm_head, and the candidates' logits + * come from the hidden rows and the head table's rows at `score_ids_` (every scored row's + * candidates, sorted and unique), both read back into `score_host`. */ + bool score_only_ = false; + std::vector score_ids_; + int64_t score_embd_ = 0; int stage_scored_rows(const StepPlan& plan, const StepOut& so); int issue_scored_rows(Rank& r); int collect_scored_rows(); diff --git a/core/rad_core.h b/core/rad_core.h index ed994742..0e911d94 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -367,6 +367,10 @@ public: * encoder-only or embedding-only plugin does; the engine refuses to serve such a program at * startup. */ rad_buf logits_buf = 0; + /* Scored steps (rad_declare_scores): the final-normed hidden rows and the bf16 head table. + * Zero when the plugin declared none. */ + rad_buf score_hidden = 0; + rad_weight score_table = 0; /* The step's pooled vectors (rad_declare_pooled): set only by an embedding program, which has * no logits buffer. */ rad_buf pooled_buf = 0; diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 968c4a25..aa3b1fb5 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -929,7 +929,7 @@ int Ctx::lane_join(int from, int to) { * field added to RadBatch changes its size: decide whether the key must read it, then update the * size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded * (below). */ -static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360, +static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 368, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); @@ -953,7 +953,7 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { mix((uint64_t)b->n_checkpoints); mix((uint64_t)b->n_seq_decode); mix((uint64_t)b->n_tok_decode); mix((uint64_t)b->max_q_len_decode); mix((uint64_t)b->max_q_len_prefill); mix((uint64_t)b->n_draft_out); mix((uint64_t)b->n_ahead); - mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); + mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); mix((uint64_t)b->score_only); ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids); ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted); ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids); diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 05220592..9e067f8a 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -1149,6 +1149,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, mm_ev_live_ = true; } + /* A scored step (RadBatch::score_only): every sampled row is a scored request's first row, on + * one rank, in a program that told the core where its hidden rows and head table are. */ + int32_t score_only = 0; + if (n_out > 0 && n_dout == 0 && !plan.draft_pass && ranks_.size() == 1 && + prog_->score_hidden != RAD_NULL_HANDLE && prog_->score_table != RAD_NULL_HANDLE) { + score_only = 1; + for (const StepEntry& e : plan.e) { + if (!e.produces_token) continue; + if (!e.req || !e.req->token_scores || !e.req->output.empty() || e.n_spec > 0) { + score_only = 0; + break; + } + } + } + /* ---------------------------------------------------------- the batch, one per rank */ for (size_t r = 0; r < ranks_.size(); ++r) { void* const base = s.dev[r]; @@ -1164,6 +1179,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, B.seq_ids = on_rank(base, b0, s.d_sid); B.n_out = n_out; B.out_ids = n_out ? on_rank(base, b0, s.d_out) : nullptr; + B.score_only = score_only; B.n_draft_out = n_dout; B.draft_out_ids = n_dout ? on_rank(base, b0, s.d_dout) : nullptr; B.q_lens = on_rank(base, b0, s.d_q); diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 39020139..de39f321 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -2103,6 +2103,12 @@ const RadBatch* Scheduler::step_next_locked() { * that cannot rewind decides at commit whether the next step may speculate; one that can, * or no grammar, keeps its answer. */ if (!e.produces_token || !r.speculation_fixed) return nullptr; + /* A SCORED row (Request::token_scores, a /v1/systemone question) that the step in flight + * brings to max_tokens gets no step issued ahead: it would run a whole forward pass for a + * request that finishes at the commit, and max_tokens=1 pays a decode step after its + * prefill. Scored rows only -- every other decode keeps the step of overlap it had. */ + if (r.token_scores && r.max_tokens > 0 && + (int64_t)r.output.size() + 1 >= r.max_tokens) return nullptr; /* The furthest context the row can reach: every position this step verifies committed, * counted from the last commit rather than this step's own bound (which would add a diff --git a/core/server/server.cpp b/core/server/server.cpp index 702387f6..2dbab68c 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -1858,6 +1858,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) { release(n); metrics_.observe_http(200); return HttpResponse::json_body(200, json_dump(json{ + { "model", opt_.model_id }, { "answers", std::move(answers) }, { "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } })); } diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index e862eece..5a7bb715 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -84,6 +84,7 @@ ABI_FIELD(RadBatch, vgen_b) ABI_FIELD(RadBatch, control_vector) ABI_FIELD(RadBatch, enc_seg_h) ABI_FIELD(RadBatch, enc_seg_w) +ABI_FIELD(RadBatch, score_only) ABI_STRUCT(RadBufDecl) ABI_FIELD(RadBufDecl, dtype) ABI_FIELD(RadBufDecl, rank) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 59a9fabd..5ddeb56e 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -80,6 +80,7 @@ { "RadBatch", "control_vector", 336, 4 }, { "RadBatch", "enc_seg_h", 344, 8 }, { "RadBatch", "enc_seg_w", 352, 8 }, +{ "RadBatch", "score_only", 360, 4 }, { "RadBufDecl", "", 0, 80 }, { "RadBufDecl", "dtype", 0, 4 }, { "RadBufDecl", "rank", 4, 4 }, diff --git a/tests/arch_fakes.h b/tests/arch_fakes.h index 6a49d182..4911b6e6 100644 --- a/tests/arch_fakes.h +++ b/tests/arch_fakes.h @@ -86,6 +86,8 @@ struct RecJoin { size_t at = 0; int from = 0, to = 0; }; using namespace rad_fake; struct RadBuilder { + rad_buf score_hidden = 0; /* rad_declare_scores */ + rad_weight score_table = 0; std::vector weights; std::vector bufs; std::vector ops; @@ -289,6 +291,14 @@ extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { return RAD_OK; } +/* Scored steps' hidden rows and head table, recorded for the tests. */ +extern "C" int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table) { + if (!b || !hidden || !table) return RAD_E_INVAL; + b->score_hidden = hidden; + b->score_table = table; + return RAD_OK; +} + /* An embedding program names its pooled output instead of logits; a program declares one. */ extern "C" int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { if (!b || !pooled || b->logits) return RAD_E_INVAL; diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 93d317c7..7b8d95fd 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -5843,6 +5843,46 @@ TEST(a_request_finishing_under_a_step_issued_ahead_keeps_its_blocks_for_that_ste CHECK_EQ((int)f.sch.find(a)->output.size(), 2); /* the step ahead emitted nothing */ } +/* A SCORED row (Request::token_scores) the step in flight brings to max_tokens gets no step issued + * ahead: it would be a forward pass for a request that finishes at the commit. The step after the + * commit is planned as usual, and a decode that is not scored keeps its step of overlap. */ +TEST(no_step_is_issued_ahead_for_a_scored_request_the_step_in_flight_finishes) { + Fixture f; + f.build(/*blocks=*/20, /*states=*/64); + CHECK_OK(f.start()); + const int64_t before = f.kv.free_blocks(0); + auto r = f.request(40, /*max_tokens=*/2); + r->speculation_fixed = true; + r->token_scores = std::make_shared(); + r->token_scores->tokens = { 1, 2 }; + const uint64_t a = f.add(std::move(r)); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(); + REQUIRE(f.sch.step() != nullptr); + CHECK(f.sch.step_next() == nullptr); + f.commit_plain(); /* the second token: finished */ + CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished); + CHECK_EQ(f.kv.free_blocks(0), before); + CHECK_EQ((int)f.sch.find(a)->output.size(), 2); + CHECK(f.sch.step() == nullptr); +} + +/* The same row without token_scores is an ordinary decode: the step ahead is issued, as upstream. */ +TEST(a_non_scored_row_keeps_the_step_issued_ahead) { + Fixture f; + f.build(/*blocks=*/20, /*states=*/64); + CHECK_OK(f.start()); + auto r = f.request(40, /*max_tokens=*/2); + r->speculation_fixed = true; + const uint64_t a = f.add(std::move(r)); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(); + REQUIRE(f.sch.step() != nullptr); + CHECK(f.sch.step_next() != nullptr); + f.commit_plain(); + CHECK_EQ((int)f.sch.find(a)->output.size(), 2); +} + /* ================================================================== terminal paths */ /* A lone request that outgrows the whole pool fails with the reason the client sees and gives its * blocks back; nothing is preempted, since there is nobody to preempt and preempting itself would diff --git a/tests/systemone_test.cpp b/tests/systemone_test.cpp index 776ed0ac..fd9acde8 100644 --- a/tests/systemone_test.cpp +++ b/tests/systemone_test.cpp @@ -326,6 +326,7 @@ TEST(the_endpoint_answers_only_for_a_declared_d1) { if (!*type) { CHECK_EQ(res.status, 501); continue; } REQUIRE(res.status == 200); const json j = json::parse(res.body); + CHECK_EQ(j["model"].get(), "d1"); CHECK_NEAR(j["answers"]["q"]["noul"].get(), 0.75, 1e-6); CHECK_EQ(j["answers"]["c"]["choice"].get(), "one"); CHECK_EQ(j["usage"]["output_tokens"].get(), 0);