core: runtime LoRA declare, startup adapters, model routing and a per-adapter prefix key

--lora NAME=PATH, --max-loras, --max-lora-rank, --lora-target-modules. Off unless
named: no site, no pool, no op, and every prefix hash is what it was.
This commit is contained in:
baKon committed 2026-10-16 20:52:09 -05:00
1 parent 86cbc59063
commit ba406ace1b
18 files changed
+684 -4

No files matched your search

+11
View File
@@ -159,6 +159,16 @@ public:
* an io_uring ring, which must not stop a sandboxed conversion. */
void set_instances(bool on) { instances_ = on; }
/* RUNTIME LoRA (core/lora/): the HF module leaves an adapter may target. Set before the
* plugin declares, so a FUSED GEMM over a targeted weight -- a GEMM no adapter delta can ride
* on, the gated gate_up fold -- is declined as it is declared and the plugin emits the unfused
* chain it already has for a library without the fused kernel. Null: nothing is declined. */
void set_lora_targets(const std::set<std::string>* t) { lora_targets_ = t; }
/* The read and write sets an op declared (rad_op_reads / rad_op_writes), for the LoRA declare,
* which needs the dtypes of the activation and the output a targeted GEMM was declared over. */
const std::vector<rad_buf>& op_read_set (rad_op h) const { return op_bufs_[h].reads; }
const std::vector<rad_buf>& op_write_set(rad_op h) const { return op_bufs_[h].writes; }
Program& program() { return prog_; }
const Program& program() const { return prog_; }
@@ -199,6 +209,7 @@ private:
/* Parallel to prog_.ops: the buffers each op declared it reads and writes. */
struct OpBufUse { std::vector<rad_buf> reads, writes; };
std::vector<OpBufUse> op_bufs_;
const std::set<std::string>* lora_targets_ = nullptr;
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
* bound when their bytes are in use, so they are live for the whole program. */
+28
View File
@@ -9,6 +9,7 @@
* which makes fusion a selection rather than a compiler pass (spec §2.3).
*/
#include "rad_build.h"
#include "lora/lora.h"
#include "../device/device.h"
#include <algorithm>
@@ -702,6 +703,33 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
}
}
/* RUNTIME LoRA: A FUSED GEMM OVER A TARGETED WEIGHT IS DECLINED. Every `gemm_*` op other than
* the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue --
* the gated fold quantises the SiLU product in place -- so the delta has no y to land in. The
* op is recorded resolved to nothing, exactly as a library without the kernel would leave it,
* and the plugin falls back to the unfused chain it emits for that library. The decision reads
* only the weight's own declaration and name map, so the sizing declare makes the same one. */
bool lora_declined = false;
if (lora_targets_ && n_w > 0 && oi.op.rfind("gemm_", 0) == 0 && oi.op != "gemm_nt" &&
oi.op != "gemm_nt_bias" && oi.op != "gemm_nt_q" && oi.op != "gemm_nt_q_bias") {
for (int i = 0; i < n_w && !lora_declined; ++i)
if (w[i] > 0 && w[i] < prog_.weights.size() &&
lora::weight_targeted(prog_, w[i], *lora_targets_))
lora_declined = true;
}
if (lora_declined) {
Band none;
none.hi = oi.ranged_key.empty() ? INT64_MAX : oi.range_hi;
for (int d = 0; d < RAD_N_DOMAINS; ++d)
none.miss[d] = "declined: its weight is a runtime-LoRA target, and a fused GEMM has no "
"output for the adapter's delta (the plugin runs the unfused chain)";
oi.bands.assign(1, none);
prog_.ops.push_back(std::move(oi));
op_bufs_.emplace_back();
return RAD_NULL_HANDLE;
}
if (ref_) {
const size_t at = prog_.ops.size();
if (at >= ref_->ops.size() || ref_->ops[at].op != oi.op)
+16 -1
View File
@@ -4,6 +4,7 @@
*/
#include "build/startup.h"
#include "build/rad_build.h"
#include "lora/declare.h"
#include "format/tunecache.h"
#include "plugin/registry.h"
@@ -340,7 +341,8 @@ std::vector<std::string> CheckpointSources::refused() const {
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
const Program* ref, const WeightSourceFn& sources, bool instances) {
const Program* ref, const WeightSourceFn& sources, bool instances,
const LoraDeclare* lora) {
if (!out) return RAD_E_INVAL;
Registry& r = rad_tools_registry();
@@ -355,6 +357,8 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
if (ref) b.set_reference(ref);
if (sources) b.set_sources(sources);
b.set_instances(instances);
const bool with_lora = lora && lora->cfg && lora->cfg->enabled();
if (with_lora) b.set_lora_targets(&lora->targets);
int s = ap->arch_declare(&b, &meta, &ctx);
if (s < 0) {
@@ -363,6 +367,17 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
return s;
}
/* RUNTIME LoRA, after the plugin and before the sampler: the sites read the plugin's finished
* graph, and the appended ops go through the same resolution as everything else. */
if (with_lora) {
b.set_lora_targets(nullptr);
s = lora_declare(b, *lora);
if (s < 0) {
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
return s;
}
}
/* The sampler declares into the same builder before finish(). An unresolved sampler op is not
* a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a
* negative return here is structural. Skipped for embedding programs and image generators,
+1 -1
View File
@@ -108,7 +108,7 @@ int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
const RadBuildCtx& ctx, Program* out,
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
const Program* ref = nullptr, const WeightSourceFn& sources = {},
bool instances = true);
bool instances = true, const struct LoraDeclare* lora = nullptr);
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
* declare. */
+49
View File
@@ -97,6 +97,17 @@ static const Flag g_flags[] = {
" or host memory (default 3600). 0 keeps it until the memory\n"
" is wanted" },
{ "--lora", "ADAPTER", "NAME=PATH: serve a PEFT LoRA adapter beside the base model,\n"
" as model NAME (repeatable). The base stays as it is; each\n"
" request picks its adapter by `model`"},
{ "--max-loras", "N", "adapter slots resident at once (default: the number of\n"
" --lora). Each slot holds one adapter's A/B on the card"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n"
" adapter is zero-padded, a larger one refused"},
{ "--lora-target-modules", "LIST", "comma-separated HF module names adapters may target\n"
" (q_proj,k_proj,...). Default: what the --lora adapters\n"
" target. Needed with --max-loras and no --lora"},
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
" set cannot change under the heat engine. The sampler is\n"
@@ -489,6 +500,33 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--prefix-cache-mib")) { if (!num(0, INT32_MAX, &c->prefix_cache_mib)) return RAD_E_INVAL; }
else if (S("--prefix-cache-ttl")) { if (!num(0, INT32_MAX, &c->prefix_cache_ttl)) return RAD_E_INVAL; }
else if (S("--lora")) {
if (!(v = need(i))) return RAD_E_INVAL;
const char* eq = std::strchr(v, '=');
if (!eq || eq == v || !eq[1]) {
RAD_ERR("--lora wants NAME=PATH, got '%s'", v);
return RAD_E_INVAL;
}
c->lora.adapters.emplace_back(std::string(v, eq), std::string(eq + 1));
}
else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; }
else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; }
else if (S("--lora-target-modules")) {
if (!(v = need(i))) return RAD_E_INVAL;
c->lora.targets.clear();
std::string cur;
for (const char* q = v;; ++q) {
if (*q == ',' || !*q) {
if (!cur.empty()) c->lora.targets.insert(cur);
cur.clear();
if (!*q) break;
} else if (*q != ' ') cur += *q;
}
if (c->lora.targets.empty()) {
RAD_ERR("--lora-target-modules names no module");
return RAD_E_INVAL;
}
}
/* The prefix cache has no disk tier; the removed flags name their replacements. */
else if (S("--prefix-cache-host-mib")) {
RAD_ERR("--prefix-cache-host-mib was renamed: use --prefix-cache-mib");
@@ -902,6 +940,17 @@ const ShowRow kShow[] = {
return c.prefix_cache_mib ? num(c.prefix_cache_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-ttl", [](const Config& c) {
return c.prefix_cache_ttl ? num(c.prefix_cache_ttl) + " s" : std::string("0 (never)"); } },
{ "--lora", [](const Config& c) {
std::string o;
for (const auto& [n, p] : c.lora.adapters) o += (o.empty() ? "" : ", ") + n + "=" + p;
return o.empty() ? std::string("none") : o; } },
{ "--max-loras", [](const Config& c) {
return c.lora.enabled() ? num(c.lora.slots()) : std::string("0 (off)"); } },
{ "--max-lora-rank", [](const Config& c) { return num(c.lora.max_rank); } },
{ "--lora-target-modules", [](const Config& c) {
std::string o;
for (const std::string& t : c.lora.targets) o += (o.empty() ? "" : ",") + t;
return o.empty() ? std::string(c.lora.enabled() ? "the adapters' own" : "-") : o; } },
{ "--placement", [](const Config& c) { return c.placement; } },
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
+6
View File
@@ -2076,6 +2076,12 @@ int Engine::run_server() {
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); };
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
o.diagnostics_json = [this] { return diagnostics_json(); };
if (cfg_.lora.enabled()) {
o.lora_resolve = [this](const std::string& m, int32_t* slot, uint64_t* uid) {
return lora_resolve(m, slot, uid);
};
o.lora_names = [this] { return lora_names(); };
}
/* Media, when the program declared an encoder. The processor's geometry comes from the
* container and the encoder states its own; patch width and merge must agree, checked here
+16
View File
@@ -19,6 +19,7 @@
*/
#pragma once
#include "rad_core.h"
#include <set>
#include "build/startup.h"
#include "diag/diag.h"
#include "mem/hostarena.h"
@@ -133,6 +134,21 @@ private:
int apply_rope_scaling();
int declare();
int plan();
/* RUNTIME LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded
* into slots after every rank's Ctx is bound, and a request's `model` names one. */
int lora_targets();
int lora_start();
public:
int lora_load(const std::string& name, const std::string& dir, std::string* err);
/* RAD_OK with the slot and the uid of its load, RAD_E_NOTFOUND for a name no slot holds. */
int lora_resolve(const std::string& name, int32_t* slot, uint64_t* uid) const;
std::vector<std::string> lora_names() const;
private:
struct LoraSlotState { std::string name, dir; uint64_t uid = 0; };
std::vector<LoraSlotState> lora_slots_;
uint64_t lora_next_uid_ = 1;
mutable std::mutex lora_mu_;
std::set<std::string> lora_targets_;
/* Resolves --embedding-placement, --vision-tower-placement and --ngram-placement into Config
* before the card is split (engine_bringup.cpp describes how auto chooses). `wfs` is every
* rank's footprint, read for its towers. `host_late` is the pinned host memory startup
+16 -2
View File
@@ -853,6 +853,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
}
int Engine::declare() {
RAD_TRY(lora_targets());
/* KL mode measures the trunk (core/kld.h): a drafter writes no scored rows and a prefix hit
* would skip positions the reference holds, so both are off, and an explicit depth is refused
* rather than ignored. The tower stays off the card; the corpus is text. */
@@ -977,11 +978,16 @@ int Engine::declare() {
return;
}
const RadBuildCtx bc = build_ctx(ri, cfg_.max_tok);
LoraDeclare ld;
ld.cfg = &cfg_.lora;
ld.targets = lora_targets_;
ld.sites_out = &r->lora_sites;
st[(size_t)ri] = rad_tools_declare(plugins_, meta_, bc, &r->program,
[this, ri](RadBuilder* bb, int64_t lw) {
return declare_sampler(ri, bb, lw);
},
nullptr, sources());
nullptr, sources(), true,
cfg_.lora.enabled() ? &ld : nullptr);
});
}
/* A message is a step's bf16 residual rows, so the floor is a row count: a decode step has
@@ -1149,12 +1155,16 @@ void Engine::probe_arena_levels() {
RadBuildCtx bc = build_ctx(r.index, want[l]);
bc.shape_probe = 1;
Program probe;
LoraDeclare ld;
ld.cfg = &cfg_.lora;
ld.targets = lora_targets_;
const int st = rad_tools_declare(plugins_, meta_, bc, &probe,
[this, &r](RadBuilder* bb, int64_t lw) {
return declare_sampler(r.index, bb, lw,
true);
},
&r.program, sources());
&r.program, sources(), true,
cfg_.lora.enabled() ? &ld : nullptr);
if (st < 0) why[k] = fmt("the sizing declare failed: %s", rad_strerror(st));
else if (plan_level(r.program, probe, want[l], &got[k], &why[k]) >= 0)
ok[k] = 1;
@@ -3129,6 +3139,10 @@ int Engine::start() {
}
}
/* RUNTIME LoRA: the startup adapters, copied into their slots now that every rank's pools have
* an address and before any step can read them. */
RAD_TRY(lora_start());
/* ---- the loan: the cache's idle blocks, lent to the expert slab in place -----------------
*
* Here because it needs the cache's carve (the addresses) and the mover's compute stream
+230
View File
@@ -0,0 +1,230 @@
/* engine_lora.cpp -- runtime LoRA on the engine side: which modules adapters may target (fixed
* before declare), and loading an adapter into a slot of every rank's pools.
*
* A LOAD IS: pack the adapter for each rank (lora::load_adapter, host only), refuse a module no
* rank placed, copy each rank's bytes into the slot on a stream of its own, wait, and only then
* publish the name. A request can name the adapter only after the publish, so no step ever reads
* a slot while it is being written; a slot no published adapter holds is never referenced. */
#include "engine_priv.h"
#include "lora/lora.h"
#include <nlohmann/json.hpp>
#include <cstring>
#include <fstream>
#include <sstream>
namespace rad {
namespace {
/* adapter_config.json's target_modules as leaf names. PEFT also accepts a regex string and
* "all-linear"; neither names leaves this engine can check before declare, so both are refused
* with the flag that does. */
int read_targets(const std::string& dir, std::set<std::string>* out, std::string* err) {
const std::string path = dir + "/adapter_config.json";
std::ifstream f(path);
if (!f) { *err = "cannot read " + path; return RAD_E_NOTFOUND; }
nlohmann::json j;
try { f >> j; } catch (const std::exception& e) {
*err = path + ": " + e.what();
return RAD_E_INVAL;
}
const auto it = j.find("target_modules");
if (it == j.end() || it->is_null()) { *err = path + " names no target_modules"; return RAD_E_INVAL; }
if (it->is_string()) {
*err = path + ": target_modules is '" + it->get<std::string>() +
"', not a list of module names; give them with --lora-target-modules";
return RAD_E_UNSUPPORTED;
}
if (!it->is_array()) { *err = path + ": target_modules is not a list"; return RAD_E_INVAL; }
for (const auto& m : *it) {
if (!m.is_string()) { *err = path + ": a target_modules entry is not a string"; return RAD_E_INVAL; }
std::string s = m.get<std::string>();
const size_t dot = s.rfind('.');
if (dot != std::string::npos) s = s.substr(dot + 1);
if (!s.empty()) out->insert(s);
}
return RAD_OK;
}
} /* namespace */
int Engine::lora_targets() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_targets_ = cfg_.lora.targets;
if (lora_targets_.empty()) {
if (cfg_.lora.adapters.empty()) {
RAD_ERR("lora: --max-loras with no --lora names no module an adapter may target; give "
"them with --lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
}
for (const auto& [name, dir] : cfg_.lora.adapters) {
std::string err;
const int s = read_targets(dir, &lora_targets_, &err);
if (s < 0) {
RAD_ERR("lora: adapter '%s': %s", name.c_str(), err.c_str());
return s;
}
}
}
std::set<std::string> seen;
for (const auto& [name, dir] : cfg_.lora.adapters) {
if (!seen.insert(name).second) {
RAD_ERR("lora: two adapters are named '%s'", name.c_str());
return RAD_E_INVAL;
}
}
lora_slots_.assign((size_t)cfg_.lora.slots(), LoraSlotState{});
return RAD_OK;
}
int Engine::lora_start() {
if (!cfg_.lora.enabled()) return RAD_OK;
size_t n_sites = 0;
for (const auto& r : ranks_) n_sites += r->program.lora_sites.size();
if (n_sites == 0) {
std::string t;
for (const std::string& x : lora_targets_) t += (t.empty() ? "" : ",") + x;
RAD_ERR("lora: no GEMM of this model multiplies a weight of the targeted modules (%s)",
t.c_str());
return RAD_E_UNSUPPORTED;
}
{
const Program& P = ranks_[0]->program;
int64_t slot_bytes = 0;
for (const LoraPool& p : P.lora_pools) slot_bytes += 2 * p.R * p.K + 2 * p.N * p.R + 4 * p.N;
std::string t;
for (const std::string& x : lora_targets_) t += (t.empty() ? "" : ",") + x;
RAD_INFO("lora: %zu GEMMs over %zu weights carry adapters on rank 0 (%s); %d slots of rank "
"%d, %s a slot, %s on the card", P.lora_sites.size(), P.lora_pools.size(), t.c_str(),
cfg_.lora.slots(), cfg_.lora.max_rank, humanb(slot_bytes).c_str(),
humanb(slot_bytes * cfg_.lora.slots()).c_str());
}
for (const auto& [name, dir] : cfg_.lora.adapters) {
std::string err;
const int s = lora_load(name, dir, &err);
if (s < 0) {
RAD_ERR("lora: adapter '%s' (%s): %s", name.c_str(), dir.c_str(), err.c_str());
return s;
}
}
return RAD_OK;
}
int Engine::lora_load(const std::string& name, const std::string& dir, std::string* err) {
std::lock_guard<std::mutex> lk(lora_mu_);
if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; }
if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; }
int slot = -1;
for (size_t i = 0; i < lora_slots_.size(); ++i) {
if (lora_slots_[i].uid != 0 && lora_slots_[i].name == name) {
*err = "an adapter named '" + name + "' is already loaded";
return RAD_E_INVAL;
}
if (slot < 0 && lora_slots_[i].uid == 0) slot = (int)i;
}
if (slot < 0) {
*err = fmt("all %zu adapter slots are in use (--max-loras)", lora_slots_.size());
return RAD_E_FULL;
}
/* ---- pack, per rank (host only) */
std::vector<lora::AdapterInfo> infos(ranks_.size());
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.max_rank, &infos[ri],
&packed[ri], err);
if (s < 0) {
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
return s;
}
}
{
const int s = lora::check_placed(infos, err, &ranks_[0]->program, &lora_targets_);
if (s < 0) return s;
}
/* ---- copy, per rank, on a stream of its own (the compute stream may be recording a pass) */
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
Rank& r = *ranks_[ri];
const Program& P = r.program;
if (packed[ri].size() != P.lora_pools.size()) {
*err = fmt("rank %zu: the adapter was packed for %zu pools, the program has %zu", ri,
packed[ri].size(), P.lora_pools.size());
return RAD_E_STATE;
}
if (rad_dev_set(r.device) < 0) { *err = fmt("rank %zu: cannot bind its device", ri); return RAD_E_DEVICE; }
RadStream st{};
if (rad_stream_create(&st, 0) < 0) { *err = fmt("rank %zu: no copy stream", ri); return RAD_E_DEVICE; }
int rc = RAD_OK;
for (size_t p = 0; p < P.lora_pools.size() && rc >= 0; ++p) {
const LoraPool& lp = P.lora_pools[p];
const lora::PackedSite& ps = packed[ri][p];
const int64_t ab = 2 * lp.R * lp.K, bb = 2 * lp.N * lp.R, sb = 4 * lp.N;
char* da = (char*)P.buffers[lp.a].ptr;
char* db = (char*)P.buffers[lp.b].ptr;
char* ds = (char*)P.buffers[lp.scale].ptr;
if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; }
da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb;
/* A pool this adapter does not touch is ZEROED, not left: the bytes are whatever the
* last adapter in the slot or the arena held, and a scale of 0 times a NaN is a NaN. */
if (ps.empty) {
if (rad_memset_async(da, 0, ab, st) < 0 || rad_memset_async(db, 0, bb, st) < 0 ||
rad_memset_async(ds, 0, sb, st) < 0)
rc = RAD_E_DEVICE;
continue;
}
if ((int64_t)ps.a.size() * 2 != ab || (int64_t)ps.b.size() * 2 != bb ||
(int64_t)ps.scale.size() * 4 != sb) {
*err = fmt("rank %zu: pool '%s' was packed as %zu/%zu/%zu elements, its slot holds "
"%lld/%lld/%lld", ri, lp.weight.c_str(), ps.a.size(), ps.b.size(),
ps.scale.size(), (long long)(ab / 2), (long long)(bb / 2), (long long)(sb / 4));
rc = RAD_E_STATE;
break;
}
if (rad_memcpy_async(da, ps.a.data(), ab, st) < 0 ||
rad_memcpy_async(db, ps.b.data(), bb, st) < 0 ||
rad_memcpy_async(ds, ps.scale.data(), sb, st) < 0)
rc = RAD_E_DEVICE;
}
const int sy = rad_stream_sync(st);
rad_stream_destroy(st);
if (rc >= 0 && sy < 0) rc = RAD_E_DEVICE;
if (rc < 0) {
if (err->empty()) *err = fmt("rank %zu: the copy into slot %d failed", ri, slot);
return rc;
}
}
LoraSlotState& ls = lora_slots_[(size_t)slot];
ls.name = name;
ls.dir = dir;
ls.uid = lora_next_uid_++;
const lora::AdapterInfo& a = infos[0];
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
return RAD_OK;
}
int Engine::lora_resolve(const std::string& name, int32_t* slot, uint64_t* uid) const {
std::lock_guard<std::mutex> lk(lora_mu_);
for (size_t i = 0; i < lora_slots_.size(); ++i)
if (lora_slots_[i].uid != 0 && lora_slots_[i].name == name) {
*slot = (int32_t)i;
*uid = lora_slots_[i].uid;
return RAD_OK;
}
return RAD_E_NOTFOUND;
}
std::vector<std::string> Engine::lora_names() const {
std::lock_guard<std::mutex> lk(lora_mu_);
std::vector<std::string> out;
for (const LoraSlotState& s : lora_slots_)
if (s.uid != 0) out.push_back(s.name);
return out;
}
} /* namespace rad */
+4
View File
@@ -17,6 +17,7 @@
#include "mem/kvtier.h"
#include "runtime/tierexec.h"
#include "build/rad_build.h"
#include "lora/declare.h"
#include "place/heat.h"
#include "place/planner.h"
#include "place/mover.h"
@@ -33,6 +34,9 @@ struct Engine::Rank {
int index = 0;
int device = 0;
Program program; /* declare runs once per rank: dimensions are already divided */
/* RUNTIME LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's
* modules to this rank's slot bytes. Empty with LoRA off. */
std::vector<lora::Site> lora_sites;
Plan plan;
Pools pools;
Mover mover;
+225
View File
@@ -0,0 +1,225 @@
/* lora/declare.cpp -- see declare.h. */
#include "lora/declare.h"
#include "build/rad_build.h"
#include "rad_internal.h"
#include <cstring>
#include <map>
#include <string>
namespace rad {
namespace {
std::string join(const lora::TargetSet& t) {
std::string s;
for (const std::string& x : t) s += (s.empty() ? "" : ",") + x;
return s.empty() ? std::string("(none)") : s;
}
int opd_index(const OpInfo& o, const char* name) {
if (!o.schema || !o.schema->operands) return -1;
for (int k = 0; k < o.schema->n_operands; ++k)
if (o.schema->operands[k].name && std::strcmp(o.schema->operands[k].name, name) == 0) return k;
return -1;
}
bool is_coded(uint32_t dt) {
return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_I8;
}
rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32_t rank,
const int64_t* shape, int kind = RAD_BUF_PERSIST, const char* derive = nullptr) {
RadBufDecl d{};
d.dtype = dtype;
d.rank = rank;
for (uint32_t i = 0; i < rank; ++i) d.shape[i] = shape[i];
d.kind = kind;
d.domain = RAD_DOMAIN_DEVICE;
d.derive = derive;
return b.decl_buffer(name.c_str(), &d);
}
} /* namespace */
int lora_declare(Builder& b, const LoraDeclare& d) {
if (!d.cfg || !d.cfg->enabled()) return RAD_OK;
Program& P = b.program();
const int S = d.cfg->slots();
const int max_rank = d.cfg->max_rank;
const int64_t max_tok = P.ctx.max_tok;
if (S <= 0 || max_rank <= 0 || max_tok <= 0) {
RAD_ERR("lora: %d slots of rank %d over steps of %lld tokens is not a configuration", S,
max_rank, (long long)max_tok);
return RAD_E_INVAL;
}
/* EVERY READER OF A TARGETED WEIGHT CARRIES THE DELTA, OR STARTUP REFUSES. A targeted weight
* that some op multiplies without the adapter is a model that is the base in one place and the
* adapter in another, and the text it writes is wrong in a way no test of the targeted GEMM
* would show. */
std::vector<lora::UnsupportedUse> bad;
int s = lora::find_unsupported_uses(P, d.targets, &bad);
if (s < 0) return s;
if (!bad.empty()) {
for (const lora::UnsupportedUse& u : bad)
RAD_ERR("lora: weight '%s' (%s) is read by op %u '%s', which cannot carry an adapter: %s",
u.weight.c_str(), u.module.c_str(), u.op_index, u.op.c_str(), u.why.c_str());
RAD_ERR("lora: narrow --lora-target-modules (now %s) to modules every reader of which is a "
"plain GEMM", join(d.targets).c_str());
return RAD_E_UNSUPPORTED;
}
std::vector<lora::Site> sites;
std::vector<std::string> pool_weights;
std::string err;
s = lora::build_sites(P, d.targets, max_rank, &sites, &err, &pool_weights);
if (s < 0) {
RAD_ERR("lora: %s", err.c_str());
return s;
}
/* ---- the pools: one per targeted weight, [S, R, K] / [S, N, R] bf16 and [S, N] f32 */
P.lora_pools.clear();
P.lora_pools.resize(pool_weights.size());
for (size_t p = 0; p < pool_weights.size(); ++p) {
const lora::Site* first = nullptr;
for (const lora::Site& x : sites)
if (x.pool == (int32_t)p) { first = &x; break; }
if (!first) {
RAD_ERR("lora: pool %zu ('%s') has no site", p, pool_weights[p].c_str());
return RAD_E_STATE;
}
for (const lora::Site& x : sites)
if (x.pool == (int32_t)p && (x.R != first->R || x.K_r != first->K_r || x.N_r != first->N_r)) {
RAD_ERR("lora: two GEMMs over '%s' disagree about its geometry (R %lld/%lld, K %lld/%lld, "
"N %lld/%lld)", pool_weights[p].c_str(), (long long)x.R, (long long)first->R,
(long long)x.K_r, (long long)first->K_r, (long long)x.N_r,
(long long)first->N_r);
return RAD_E_STATE;
}
LoraPool& lp = P.lora_pools[p];
lp.weight = pool_weights[p];
lp.R = first->R; lp.K = first->K_r; lp.N = first->N_r; lp.S = S;
const int64_t sa[3] = { S, lp.R, lp.K }, sb[3] = { S, lp.N, lp.R }, ss[2] = { S, lp.N };
lp.a = decl_persist(b, "lora." + lp.weight + ".a", RAD_BF16, 3, sa);
lp.b = decl_persist(b, "lora." + lp.weight + ".b", RAD_BF16, 3, sb);
lp.scale = decl_persist(b, "lora." + lp.weight + ".scale", RAD_F32, 2, ss);
if (!lp.a || !lp.b || !lp.scale) {
RAD_ERR("lora: could not declare the pools of '%s'", lp.weight.c_str());
return RAD_E_STATE;
}
}
/* ---- t = A.x, one f32 plane per capacity R and lane. PERSIST and not TRANSIENT: the ops that
* use it are issued inside the GEMM's issue, at the GEMM's position, while the buffer plan would
* place a transient by the appended ops' own position at the end of the program -- and share
* its bytes with whatever is live there. */
std::map<int64_t, int32_t> t_by_r;
P.lora_t.clear();
for (const lora::Site& x : sites) {
if (t_by_r.count(x.R)) continue;
LoraScratch sc;
sc.R = x.R;
const int64_t sh[2] = { max_tok, x.R };
for (int l = 0; l < 2; ++l) {
sc.lane[l] = decl_persist(b, fmt("lora.t.r%lld.lane%d", (long long)x.R, l), RAD_F32, 2, sh);
if (!sc.lane[l]) return RAD_E_STATE;
}
t_by_r[x.R] = (int32_t)P.lora_t.size();
P.lora_t.push_back(sc);
}
/* ---- the per-token slot, derived by the core each step (core/sched/derive.cpp) */
{
const int64_t sh[1] = { max_tok };
P.lora_slot_buf = decl_persist(b, "lora.slot", RAD_I32, 1, sh, RAD_BUF_DERIVED, "lora_slot");
if (!P.lora_slot_buf) {
RAD_ERR("lora: could not declare the per-token slot buffer");
return RAD_E_STATE;
}
}
/* ---- the two ops behind each targeted GEMM */
P.lora_sites.clear();
int n_refused = 0;
for (lora::Site& x : sites) {
const uint32_t gh = x.gemm;
if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE;
if (!b.op_resolved(gh)) continue; /* never handed to the plugin, so never issued */
/* Copied out first: decl_op below appends to P.ops and moves every OpInfo. */
const OpInfo& g = P.ops[gh];
const std::string gop = g.op;
const std::string rkey = g.ranged_key;
const int64_t lo = g.range_lo, hi = g.range_hi;
long long gk = 0, gn = 0, gg = 0;
const bool has_k = g.base.get_i("K", &gk), has_n = g.base.get_i("N", &gn);
const bool has_group = g.base.get_i("group", &gg) && gg > 0;
const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y");
const std::vector<rad_buf> reads = b.op_read_set(gh), writes = b.op_write_set(gh);
auto refuse = [&](const std::string& why) {
RAD_ERR("lora: op %u '%s' over '%s': %s", gh, gop.c_str(), x.weight.c_str(), why.c_str());
++n_refused;
};
if (rkey != "M") { refuse("its row count is not the ranged parameter M"); continue; }
if (!has_k || !has_n || gk != x.K_r || gn != x.N_r) {
refuse(fmt("declared K %lld, N %lld; the weight's per-rank slice is K %lld, N %lld", gk, gn,
(long long)x.K_r, (long long)x.N_r));
continue;
}
if (oa < 0 || oy < 0) { refuse("its schema names no `a` or no `y` operand"); continue; }
if (reads.empty() || writes.empty()) {
refuse("it declared no read or write set (rad_op_reads / rad_op_writes), so the dtypes "
"of its activation and output are not known at declare");
continue;
}
const uint32_t a_dt = P.buffers[reads[0]].decl.dtype;
const uint32_t y_dt = P.buffers[writes[0]].decl.dtype;
const bool coded = is_coded(a_dt);
if (coded && oas < 0) { refuse("a coded activation and no `a_scale` operand"); continue; }
RadParam sp[6];
int n_sp = 0;
sp[n_sp++] = RAD_RANGE("M", lo, hi);
sp[n_sp++] = RAD_INT("K", x.K_r);
sp[n_sp++] = RAD_INT("R", x.R);
sp[n_sp++] = RAD_INT("S", S);
if (coded && has_group) sp[n_sp++] = RAD_INT("group", gg);
sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt));
const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0);
const RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
const rad_op he = b.decl_op("lora_expand", ep, 5, nullptr, 0);
if (!hs || !he) {
refuse(fmt("no kernel resolves lora_%s for an activation of %s and an output of %s",
!hs ? "shrink" : "expand", rad_dtype_name(a_dt), rad_dtype_name(y_dt)));
continue;
}
LoraIssueSite is;
is.gemm = gh; is.shrink = hs; is.expand = he;
is.opd_a = (int8_t)oa;
is.opd_a_scale = (int8_t)(coded ? oas : -1);
is.opd_y = (int8_t)oy;
is.a_dtype = a_dt; is.y_dtype = y_dt;
is.pool = x.pool;
is.t = t_by_r[x.R];
is.R = x.R; is.K = x.K_r; is.N = x.N_r;
P.ops[hs].anchor = (int32_t)gh;
P.ops[he].anchor = (int32_t)gh;
P.ops[gh].lora_site = (int32_t)P.lora_sites.size();
P.lora_sites.push_back(is);
x.lora_shrink = hs; x.lora_expand = he;
const LoraPool& lp = P.lora_pools[(size_t)x.pool];
x.pool_a = lp.a; x.pool_b = lp.b; x.pool_scale = lp.scale;
}
if (n_refused) return RAD_E_UNSUPPORTED;
if (d.sites_out) *d.sites_out = std::move(sites);
return RAD_OK;
}
} /* namespace rad */
+28
View File
@@ -0,0 +1,28 @@
/* lora/declare.h -- the runtime-LoRA half of declare: after the architecture plugin has declared
* its program, build the sites (lora.h), declare the adapter pools and the two ops each targeted
* GEMM is followed by, and record what the issue path needs (Program::lora_sites).
*
* Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, on the real
* declare AND on every sizing declare -- identically, because a sizing declare must produce the
* same op list (rad_builder.cpp checks it op by op). */
#pragma once
#include "lora/config.h"
#include "lora/lora.h"
#include <vector>
namespace rad {
class Builder;
struct LoraDeclare {
const LoraConfig* cfg = nullptr;
lora::TargetSet targets;
/* The real declare's sites, for the adapter loader; null on a sizing declare. */
std::vector<lora::Site>* sites_out = nullptr;
};
/* RAD_OK, or a negative code after RAD_ERR lines naming every refusal. */
int lora_declare(Builder& b, const LoraDeclare& d);
} /* namespace rad */
+2
View File
@@ -6,6 +6,7 @@
*/
#pragma once
#include "rad_internal.h"
#include "lora/config.h"
#include <map>
#include <memory>
@@ -665,6 +666,7 @@ enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
struct Config {
std::string model; /* path to the .rad, or a Hugging Face repo id (hf_model.h) */
LoraConfig lora; /* --lora, --max-loras, --max-lora-rank, --lora-target-modules */
std::string download_dir; /* where a repo id is fetched to; empty = the XDG cache */
std::string radiance_home;
std::vector<std::string> kernel_hierarchy; /* ordered; first wins */
+12
View File
@@ -461,6 +461,18 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
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;
/* ...and the activation must be the SAME rows: shrink reads x's row m and expand writes y's
* row m with one slot, so a GEMM whose two views start at different tokens cannot be followed. */
{
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output "
"views do not start at the same token row");
}
if (op_domain_[s.shrink].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE ||
op_domain_[s.expand].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE)
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed off "
"the device the gemm runs on");
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",
+12
View File
@@ -284,6 +284,18 @@ struct KVBinding final : IKVManager {
* and segment: the same picture at the same place hits, two pictures never alias. */
inline void media_keys(const Request& r, std::vector<MMContentKey>* out) {
out->clear();
/* THE RUNTIME LoRA ADAPTER IS PART OF EVERY BLOCK'S KEY. KV written under an adapter is not
* the base's, so it rides into the chain as one span over the whole sequence, keyed by the
* adapter's load uid -- every block overlaps it, and with uid 0 (the base) there is no span and
* every hash is what it was before adapters existed. The uid, never the name: a reload under
* the same name is new weights and must start cold. */
if (r.lora_uid != 0) {
MMContentKey k;
k.tok_begin = 0;
k.tok_end = INT32_MAX;
k.hash = (r.lora_uid * 0x9e3779b97f4a7c15ull) ^ 0x4c6f5241ull; /* "LoRA" */
out->push_back(k);
}
if (!r.media) return;
const mm::PromptMedia& pm = *r.media;
for (const mm::RopeLayout::Run& run : pm.rope.runs) {
+22
View File
@@ -388,6 +388,26 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
}
}
/* RUNTIME LoRA: `model` picks the adapter. The served model's own name, or no name, is the
* base; with adapters enabled anything else must be a loaded adapter -- a typo served by the
* base would answer as the wrong model and say nothing. */
int32_t lora_slot = -1;
uint64_t lora_uid = 0;
if (opt_.lora_resolve && !r.model.empty() && r.model != opt_.model_id) {
if (opt_.lora_resolve(r.model, &lora_slot, &lora_uid) != RAD_OK) {
std::string names = opt_.model_id;
if (opt_.lora_names)
for (const std::string& n : opt_.lora_names()) names += ", " + n;
ApiError e;
e.status = 404;
e.type = "not_found_error";
e.param = "model";
e.message = "no such model or adapter: " + r.model + " (served: " + names + ")";
*err = e;
return RAD_E_NOTFOUND;
}
}
int idx = 0;
std::vector<Request> rqs;
rqs.reserve(r.prompts.size() * (size_t)r.n);
@@ -422,6 +442,8 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
rq.stream = r.stream;
rq.media = r.prompts[p].media;
rq.session_label = r.session_label;
rq.lora_slot = lora_slot;
rq.lora_uid = lora_uid;
rq.sink = g.sink.get();
rqs.push_back(std::move(rq));
gens->push_back(std::move(g));
+4
View File
@@ -119,6 +119,10 @@ struct ServerOptions {
* clock only mean something under load: queried during a long prefill, it tells a link parked
* below its maximum from one at rest. */
std::function<std::string()> diagnostics_json;
/* RUNTIME LoRA (Engine::lora_resolve): a request's `model` naming a loaded adapter gets that
* adapter's slot and load uid. Unset with LoRA off, and then any `model` is served by the base. */
std::function<int(const std::string&, int32_t*, uint64_t*)> lora_resolve;
std::function<std::vector<std::string>()> lora_names;
std::string api_key;
bool cors = true;
+2
View File
@@ -410,6 +410,8 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--kld-record", { "/r", "--kld-corpus", "/c.jsonl" } }, { "--kld-ref", { "/r" } },
{ "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } },
{ "--kld-out", { "/o.json", "--kld-ref", "/r" } },
{ "--lora", { "a=/adapters/a" } }, { "--max-loras", { "2" } },
{ "--max-lora-rank", { "32" } }, { "--lora-target-modules", { "q_proj,v_proj" } },
};
return v;
}