diff --git a/core/lora/config.h b/core/lora/config.h new file mode 100644 index 00000000..924ee32b --- /dev/null +++ b/core/lora/config.h @@ -0,0 +1,36 @@ +/* lora/config.h -- what runtime LoRA was started with (--lora, --max-loras, --max-lora-rank, + * --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager + * (what may be loaded into them) and by nothing else. + * + * OFF UNLESS ASKED FOR: with no adapter named and no --max-loras, `enabled()` is false, declare + * appends nothing, the program has no pool and no extra op, and the engine computes exactly what it + * computed before this file existed. */ +#pragma once +#include +#include +#include +#include + +namespace rad { + +struct LoraConfig { + /* NAME=PATH pairs to load at startup, in the order given. */ + std::vector> adapters; + /* Adapter slots resident at once. 0 with adapters named means "as many as were named". */ + int max_loras = 0; + /* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */ + int max_rank = 16; + /* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for. Empty: + * the union of the startup adapters' target_modules, or -- with no startup adapter -- every + * LoRA-capable trunk linear (`all_linear`). */ + std::set targets; + bool all_linear = false; + + bool enabled() const { return max_loras > 0 || !adapters.empty(); } + int slots() const { + const int named = (int)adapters.size(); + return max_loras > 0 ? (max_loras > named ? max_loras : named) : named; + } +}; + +} /* namespace rad */ diff --git a/core/rad_core.h b/core/rad_core.h index c88036f7..a67e9f92 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -264,6 +264,12 @@ struct OpInfo { const RadOpSchema* schema = nullptr; int32_t index = 0; /* position in the declared order */ bool issued = false; /* did the run phase ever issue it */ + /* RUNTIME LoRA (core/lora/). `anchor`: an op the CORE appended after the plugin's declare and + * issues inside another op's issue -- its buffers are that op's, so buffer liveness is judged + * at the anchor's position, not at this op's own (which is past every plugin op). -1 for every + * plugin op. `lora_site`: on a targeted gemm, its row in Program::lora_sites; -1 otherwise. */ + int32_t anchor = -1; + int32_t lora_site = -1; }; struct KVGroupInfo { @@ -289,6 +295,30 @@ inline int64_t conv_window_entries(const RadKVGroupDecl& d, int64_t n_spec) { return (d.conv_width > 0 ? d.conv_width - 1 : 0) + (n_spec > 0 ? n_spec : 0); } +/* ONE TARGETED GEMM OF A RUNTIME-LoRA PROGRAM (core/lora/), as the issue path needs it: the two ops + * the core appended for it, where in the gemm's own operand list its activation and output are, + * and the buffers the appended ops read. Built once at declare; issue reads it and nothing else. */ +struct LoraIssueSite { + uint32_t gemm = 0, shrink = 0, expand = 0; /* op handles */ + int8_t opd_a = -1, opd_a_scale = -1, opd_y = -1; /* positions in the GEMM's schema */ + uint32_t a_dtype = 0, y_dtype = 0; /* what the appended ops were declared for */ + int32_t pool = -1; /* index into Program::lora_pools */ + int32_t t = -1; /* index into Program::lora_t */ + int64_t R = 0, K = 0, N = 0; +}; +/* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale + * [S, N] f32 -- PERSIST buffers, so the arena plan (and with it the KV budget) holds them. */ +struct LoraPool { + std::string weight; + rad_buf a = 0, b = 0, scale = 0; + int64_t R = 0, K = 0, N = 0, S = 0; +}; +/* The f32 intermediate t = A.x of one rank capacity R, one per lane (lane 1 runs beside lane 0). */ +struct LoraScratch { + int64_t R = 0; + rad_buf lane[2] = { 0, 0 }; +}; + /* Everything declare produced. The core owns it; the plugin only ever sees handles into it. */ class Program { public: @@ -310,6 +340,12 @@ public: * no logits buffer. */ rad_buf pooled_buf = 0; + /* RUNTIME LoRA (core/lora/), empty unless the engine was started with adapters enabled. */ + std::vector lora_sites; + std::vector lora_pools; + std::vector lora_t; + rad_buf lora_slot_buf = 0; /* RAD_BUF_DERIVED "lora_slot", [max_tok] i32 */ + /* The declared draft head (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when none, the * normal case: the engine then speculates with the scheduler's prompt-lookup drafter or not at * all. `drafter_name` is a copy because RadDrafterDecl::name points into plugin storage. */ @@ -538,6 +574,11 @@ struct TokenScores { struct Request { uint64_t id = 0; + /* THE RUNTIME LoRA ADAPTER this request is served with (core/lora/): its slot in the adapter + * pools, -1 for the base model, and the uid of the load that slot held when the request was + * admitted -- the prefix cache keys on the uid, so a reload under the same name starts cold. */ + int32_t lora_slot = -1; + uint64_t lora_uid = 0; std::vector prompt; std::vector output; SamplingParams sp; diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index aca7f695..13fe02fc 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -316,6 +316,7 @@ int Ctx::bind_ops() { /* Matched by name once here, not on the issue path; see OpPlan::billed. */ p.billed = (oi.op == "all_reduce"); p.collective = p.billed; + p.lora_site = oi.lora_site; for (const Band& b : oi.bands) band_table_.push_back(b.hi); diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index e6fb9015..847eb01f 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -86,6 +86,8 @@ struct OpPlan { /* The conventional all_reduce, whose `n` is the message's element count, so its link bytes * can be counted (ar_bytes) apart from the expert mover's. */ bool billed = false; + /* RUNTIME LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */ + int32_t lora_site = -1; }; /* ------------------------------------------------------------------ routing handoff */ @@ -345,6 +347,7 @@ private: int bind_buffers(); int bind_weights(); int bind_ops(); + int issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n); int bind_routing(); int bind_profiling(); int check_domain(rad_op h, int domain) const; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 71c09b4e..59f35f28 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -395,7 +395,11 @@ static long g_iss_n = 0; * after_op runs on the op's stream, where "every reader of this weight is behind us" can be * recorded. */ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { - if (!staging_) return issue_body(h, opd, n_opd, n); + if (!staging_) { + const int rc = issue_body(h, opd, n_opd, n); + if (rc < 0 || (size_t)h >= plans_.size() || plans_[h].lora_site < 0) return rc; + return issue_lora(h, opd, n_opd, n); + } if (step_status_ < 0) return step_status_; bool resync = false; const int sb = stager_->before_op(h, cur_stream(), &resync); @@ -407,9 +411,74 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { const int sa = stager_->after_op(h, cur_stream()); if (sa < 0) return abort_step_msg(h, sa, "the weight stager could not release this op's weights"); + if ((size_t)h < plans_.size() && plans_[h].lora_site >= 0) return issue_lora(h, opd, n_opd, n); return rc; } +/* RUNTIME LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the + * same stream, over the same rows, through the ordinary issue path (bands, tape, hazards). + * + * t = A[slot] . x lora_shrink, x = the gemm's own activation operand(s) + * y += scale . B[slot] . t lora_expand, y = the gemm's own output operand + * + * Here and only here: a row-parallel gemm's y is this rank's PARTIAL sum and the plugin reduces it + * after this returns, so the delta rides the same reduction (B.A.x is linear in x's shards). Only + * the trunk pass: a draft pass runs the drafter's weights, an encoder pass the tower's. A base row + * (slot -1) is not touched by either kernel, so a step with no adapter rows computes exactly what + * the same step without LoRA does. */ +int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { + if (!batch_ || batch_->draft_pass != 0 || batch_->enc != 0 || batch_->gen != 0) return RAD_OK; + const OpPlan& p = plans_[h]; + const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site]; + if (n == RAD_N_BATCH) n = batch_->n_tok; + if (n <= 0) return RAD_OK; + if (op_domain_[h].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE) + return abort_step_msg(h, RAD_E_UNSUPPORTED, + "a LoRA-targeted gemm was placed on the host; its adapter delta has " + "no host path, so the step would compute the base model's output"); + if (s.opd_a < 0 || s.opd_a >= n_opd || s.opd_y < 0 || s.opd_y >= n_opd) + return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm was issued with fewer operands " + "than its schema names"); + const RadOperand& ya = opd[s.opd_y]; + const RadOperand& xa = opd[s.opd_a]; + if (ya.kind != RAD_OPK_BUF || xa.kind != RAD_OPK_BUF || + (size_t)ya.handle >= program_->buffers.size() || (size_t)xa.handle >= program_->buffers.size()) + return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the gemm's activation or output is " + "not a declared buffer"); + /* THE ROWS THE GEMM WROTE ARE ROWS OF THE STEP'S TOKENS starting at r0, so the slot array is + * read from r0 too. A row slice offsets by whole rows of the buffer's declared width; a column + * slice offsets by less than one row. Anything else is a view this code cannot place. */ + const RadBufDecl& yd = program_->buffers[ya.handle].decl; + const RadBufDecl& xd = program_->buffers[xa.handle].decl; + if (yd.dtype != s.y_dtype || xd.dtype != s.a_dtype) + return abort_step_msg(h, RAD_E_STATE, + fmt("LoRA site: declared for activation %s / output %s, issued with " + "%s / %s", rad_dtype_name(s.a_dtype), rad_dtype_name(s.y_dtype), + rad_dtype_name(xd.dtype), rad_dtype_name(yd.dtype))); + const int64_t yw = yd.rank >= 2 ? yd.shape[yd.rank - 1] : 0; + if (yw <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output has no width"); + if (ya.cols == 0 && ya.offset % yw != 0) + return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a " + "row, so its token rows cannot be told"); + const int64_t r0 = ya.offset / yw; + if (r0 < 0 || r0 + n > batch_->n_tok) + return abort_step_msg(h, RAD_E_STATE, + fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step", + (long long)r0, (long long)(r0 + n), (long long)batch_->n_tok)); + const LoraPool& pool = program_->lora_pools[(size_t)s.pool]; + const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0]; + const RadOperand slot = RAD_B_N(program_->lora_slot_buf, r0, n); + const RadOperand tv = RAD_B_N(t, 0, n); + const RadOperand sh[5] = { xa, + s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale] + : RAD_NONE, + slot, RAD_B(pool.a), tv }; + int rc = issue_body((rad_op)s.shrink, sh, 5, n); + if (rc < 0) return rc; + const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), ya }; + return issue_body((rad_op)s.expand, ex, 5, n); +} + int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { const auto t_iss0 = g_dbg_issue ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; @@ -512,8 +581,10 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { * depends on the plan's packing. */ { const BufferInfo& bi = program_->buffers[bh]; - if (bi.first_def >= 0 && - ((int32_t)h < bi.first_def || (int32_t)h > bi.last_use)) + /* A core-appended op (runtime LoRA) is judged at the op it rides on: it touches + * that op's activation and output inside that op's issue, never after it. */ + const int32_t at = p.info && p.info->anchor >= 0 ? p.info->anchor : (int32_t)h; + if (bi.first_def >= 0 && (at < bi.first_def || at > bi.last_use)) return abort_step_msg(h, RAD_E_STATE, fmt("operand %d names buffer '%s', which this op never " "declared: the plan gives it ops %d..%d and this is " diff --git a/core/sched/derive.cpp b/core/sched/derive.cpp index 2b7a6d97..ca077c4e 100644 --- a/core/sched/derive.cpp +++ b/core/sched/derive.cpp @@ -1,6 +1,7 @@ /* derive.cpp -- the derivation table, one row per name. */ #include "derive.h" +#include "rad_core.h" #include @@ -81,6 +82,24 @@ static int d_state_chunk_seq(const DeriveInput& in, int32_t* out, int64_t cap, i return chunk_walk(in, out, cap, n_out); } +/* ------------------------------------------------------------------ lora_slot */ +/* [n_tok] -- the runtime LoRA adapter slot each token's row is multiplied with, -1 for the base + * model (core/lora/). A sequence's slot is its request's, fixed when the request was admitted, so + * every row of one sequence carries the same value and a step mixing adapters needs nothing but + * this array: the LoRA kernels read the slot of each row they touch and leave a -1 row alone. */ +static int d_lora_slot(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + if (in.n_tok > cap || !in.plan || (int64_t)in.plan->e.size() < in.n_seq) return RAD_E_FULL; + for (int64_t i = 0; i < in.n_seq; ++i) { + const Request* r = in.plan->e[(size_t)i].req; + const int32_t slot = r ? r->lora_slot : -1; + const int64_t b = in.cu_seqlens[i], e = in.cu_seqlens[i + 1]; + if (b < 0 || e < b || e > in.n_tok) return RAD_E_STATE; + for (int64_t k = b; k < e; ++k) out[k] = slot; + } + *n_out = in.n_tok; + return RAD_OK; +} + /* ------------------------------------------------------------------ the table */ static const DeriveRow g_rows[] = { { "seq_start_index", d_seq_start_index, @@ -91,6 +110,8 @@ static const DeriveRow g_rows[] = { "[n_chunks+1] token indices bounding each linear-state chunk; never crosses a sequence" }, { "state_chunk_seq", d_state_chunk_seq, "[n_chunks] the sequence each chunk belongs to" }, + { "lora_slot", d_lora_slot, + "[n_tok] the runtime LoRA adapter slot of each token's sequence, -1 for the base model" }, }; int derive_index(const char* name) {