From 383544f073c027823372d3958c482dd81f2ebd88 Mon Sep 17 00:00:00 2001 From: baKon Date: Fri, 16 Oct 2026 03:29:19 -0500 Subject: [PATCH] server: adapters on /v1/models, load/unload_lora_adapter, and a hold that keeps an adapter loaded while a request uses it --- core/engine.cpp | 10 ++++-- core/engine.h | 16 ++++++++-- core/engine_lora.cpp | 46 ++++++++++++++++++++++++--- core/server/oai.cpp | 9 ++++++ core/server/oai.h | 5 +++ core/server/server.cpp | 67 ++++++++++++++++++++++++++++++++++++--- core/server/server.h | 6 +++- core/server/server_priv.h | 2 ++ 8 files changed, 146 insertions(+), 15 deletions(-) diff --git a/core/engine.cpp b/core/engine.cpp index 6e7ff5f0..61069e86 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -396,6 +396,7 @@ int Engine::step_loop() { * readback (Scheduler::step_next). */ const RadBatch* ahead = nullptr; while (!stopping_.load(std::memory_order_acquire)) { + lora_epoch_.fetch_add(1, std::memory_order_acq_rel); phase_t_ = std::chrono::steady_clock::now(); /* Encode media for waiting requests while nothing is in flight. The scheduler issues no * step ahead while a request waits, and a request with unencoded media waits. */ @@ -2077,10 +2078,15 @@ int Engine::run_server() { /* 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_acquire = [this](const std::string& m, int32_t* slot, uint64_t* uid, + std::shared_ptr* hold) { + return lora_acquire(m, slot, uid, hold); }; o.lora_names = [this] { return lora_names(); }; + o.lora_load = [this](const std::string& n, const std::string& d, std::string* e) { + return lora_load(n, d, e); + }; + o.lora_unload = [this](const std::string& n, std::string* e) { return lora_unload(n, e); }; } /* Media, when the program declared an encoder. The processor's geometry comes from the diff --git a/core/engine.h b/core/engine.h index 7206fac3..1b1a2158 100644 --- a/core/engine.h +++ b/core/engine.h @@ -19,6 +19,7 @@ */ #pragma once #include "rad_core.h" +#include #include #include "build/startup.h" #include "diag/diag.h" @@ -140,15 +141,24 @@ private: 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; + /* Unpublish an adapter. Refused (RAD_E_STATE) while a request holds it; its slot is reused + * only once the step loop has gone round three times since, so no step still on the card can + * read bytes a later load is writing (the next step is issued before the last is read back). */ + int lora_unload(const std::string& name, std::string* err); + /* RAD_OK with the slot, the uid of its load and a HOLD -- the adapter cannot be unloaded while + * the hold lives (the server keeps it in the request's Generation, which outlives the request + * in the scheduler). RAD_E_NOTFOUND for a name no slot holds. */ + int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid, + std::shared_ptr* hold); std::vector lora_names() const; private: - struct LoraSlotState { std::string name, dir; uint64_t uid = 0; }; + struct LoraSlotState { std::string name, dir; uint64_t uid = 0; bool used = false; uint64_t freed_at = 0; }; std::vector lora_slots_; uint64_t lora_next_uid_ = 1; + std::map lora_refs_; mutable std::mutex lora_mu_; std::set lora_targets_; + std::atomic lora_epoch_{0}; /* step-loop iterations, for slot reuse */ /* 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 diff --git a/core/engine_lora.cpp b/core/engine_lora.cpp index 2e4b038c..8fb06e9d 100644 --- a/core/engine_lora.cpp +++ b/core/engine_lora.cpp @@ -117,15 +117,22 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri 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; + bool cooling = false; + const uint64_t now = lora_epoch_.load(std::memory_order_acquire); for (size_t i = 0; i < lora_slots_.size(); ++i) { - if (lora_slots_[i].uid != 0 && lora_slots_[i].name == name) { + const LoraSlotState& x = lora_slots_[i]; + if (x.uid != 0 && x.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 (x.uid != 0 || slot >= 0) continue; + if (x.used && now < x.freed_at + 3) { cooling = true; continue; } + slot = (int)i; } if (slot < 0) { - *err = fmt("all %zu adapter slots are in use (--max-loras)", lora_slots_.size()); + *err = cooling ? std::string("the free slot was unloaded a moment ago and a step on the card " + "may still read it; retry") + : fmt("all %zu adapter slots are in use (--max-loras)", lora_slots_.size()); return RAD_E_FULL; } @@ -201,6 +208,7 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri ls.name = name; ls.dir = dir; ls.uid = lora_next_uid_++; + ls.used = true; 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)" : "", @@ -208,17 +216,45 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri return RAD_OK; } -int Engine::lora_resolve(const std::string& name, int32_t* slot, uint64_t* uid) const { +int Engine::lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid, + std::shared_ptr* hold) { std::lock_guard lk(lora_mu_); for (size_t i = 0; i < lora_slots_.size(); ++i) if (lora_slots_[i].uid != 0 && lora_slots_[i].name == name) { + const uint64_t u = lora_slots_[i].uid; *slot = (int32_t)i; - *uid = lora_slots_[i].uid; + *uid = u; + ++lora_refs_[u]; + *hold = std::shared_ptr(nullptr, [this, u](void*) { + std::lock_guard g(lora_mu_); + auto it = lora_refs_.find(u); + if (it != lora_refs_.end() && --it->second <= 0) lora_refs_.erase(it); + }); return RAD_OK; } return RAD_E_NOTFOUND; } +int Engine::lora_unload(const std::string& name, std::string* err) { + std::lock_guard lk(lora_mu_); + for (LoraSlotState& x : lora_slots_) { + if (x.uid == 0 || x.name != name) continue; + auto it = lora_refs_.find(x.uid); + if (it != lora_refs_.end() && it->second > 0) { + *err = fmt("%d request%s still use%s '%s'", it->second, it->second == 1 ? "" : "s", + it->second == 1 ? "s" : "", name.c_str()); + return RAD_E_STATE; + } + RAD_INFO("lora: '%s' unloaded (uid %llu)", name.c_str(), (unsigned long long)x.uid); + x.uid = 0; + x.name.clear(); + x.freed_at = lora_epoch_.load(std::memory_order_acquire); + return RAD_OK; + } + *err = "no adapter named '" + name + "' is loaded"; + return RAD_E_NOTFOUND; +} + std::vector Engine::lora_names() const { std::lock_guard lk(lora_mu_); std::vector out; diff --git a/core/server/oai.cpp b/core/server/oai.cpp index fde2682e..49429f9b 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -2684,6 +2684,7 @@ static json model_card(const ModelCard& c) { m["owned_by"] = "radiance"; if (c.max_model_len > 0) m["max_model_len"] = c.max_model_len; if (!c.root.empty()) m["root"] = c.root; + if (!c.parent.empty()) m["parent"] = c.parent; if (!c.capabilities.empty()) { json caps = json::parse(c.capabilities, nullptr, false); if (!caps.is_discarded() && caps.is_object()) m["capabilities"] = std::move(caps); @@ -2698,6 +2699,14 @@ std::string models_body(const ModelCard& c) { return o.dump(); } +std::string models_body(const std::vector& cards) { + json o; + o["object"] = "list"; + o["data"] = json::array(); + for (const ModelCard& c : cards) o["data"].push_back(model_card(c)); + return o.dump(); +} + std::string model_body(const ModelCard& c) { return model_card(c).dump(); } diff --git a/core/server/oai.h b/core/server/oai.h index 29689452..4ea77023 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -392,9 +392,14 @@ struct ModelCard { * OpenAI's model object has no such field. A JSON object as text, spliced in verbatim; empty * leaves it out. */ std::string capabilities; + /* A runtime LoRA adapter's card names the model it runs on, vLLM's `parent`. Empty for the + * served model itself, which then carries no such field. */ + std::string parent; }; /* The list, for GET /v1/models. */ std::string models_body(const ModelCard& m); +/* ...with the runtime LoRA adapters after the served model. */ +std::string models_body(const std::vector& cards); /* The entry itself, for GET /v1/models/:id: OpenAI's retrieve answers the model object, not a * list of one, and its SDK reads `id` off the top level. */ std::string model_body(const ModelCard& m); diff --git a/core/server/server.cpp b/core/server/server.cpp index 2787531c..a237313c 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -112,6 +112,8 @@ void Server::register_routes() { }); router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); }); router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); }); + router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); }); + router_.post("/v1/unload_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, false); }); /* The same routes without /v1, as llama-server answers them, for clients whose base URL is * the bare host. */ router_.post("/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); }); @@ -393,8 +395,9 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr * 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::shared_ptr lora_hold; + if (opt_.lora_acquire && !r.model.empty() && r.model != opt_.model_id) { + if (opt_.lora_acquire(r.model, &lora_slot, &lora_uid, &lora_hold) != RAD_OK) { std::string names = opt_.model_id; if (opt_.lora_names) for (const std::string& n : opt_.lora_names()) names += ", " + n; @@ -444,6 +447,7 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr rq.session_label = r.session_label; rq.lora_slot = lora_slot; rq.lora_uid = lora_uid; + g.lora_hold = lora_hold; rq.sink = g.sink.get(); rqs.push_back(std::move(rq)); gens->push_back(std::move(g)); @@ -1771,7 +1775,11 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) { HttpResponse Server::handle_models(const HttpRequest& req) { const std::string id = req.param("id"); - if (!id.empty() && id != opt_.model_id) { + /* RUNTIME LoRA: each loaded adapter is a model of its own, whose parent is the served one. */ + std::vector adapters; + if (opt_.lora_names) adapters = opt_.lora_names(); + const bool is_adapter = !id.empty() && std::find(adapters.begin(), adapters.end(), id) != adapters.end(); + if (!id.empty() && id != opt_.model_id && !is_adapter) { ApiError e; e.status = 404; e.type = "not_found_error"; @@ -1786,7 +1794,58 @@ HttpResponse Server::handle_models(const HttpRequest& req) { c.root = opt_.model_path; c.capabilities = capabilities().dump(); metrics_.observe_http(200); - return HttpResponse::json_body(200, id.empty() ? models_body(c) : model_body(c)); + std::vector cards{ c }; + for (const std::string& a : adapters) { + ModelCard ac = c; + ac.id = a; + ac.parent = opt_.model_id; + cards.push_back(ac); + if (is_adapter && a == id) return HttpResponse::json_body(200, model_body(ac)); + } + return HttpResponse::json_body(200, id.empty() ? models_body(cards) : model_body(c)); +} + +/* RUNTIME LoRA ADMIN, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"} + * to unload. The path is read on THIS machine, so without --api-key only a loopback client may ask + * -- the rule /diagnostics follows. */ +HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) { + using json = nlohmann::json; + auto fail = [&](int status, const char* type, const std::string& msg) { + ApiError e; + e.status = status; + e.type = type; + e.message = msg; + return error_response(e, req.peer); + }; + if (!opt_.lora_load || !opt_.lora_unload) + return fail(404, "not_found_error", "this server was started without runtime LoRA (--lora or " + "--max-loras)"); + if (opt_.api_key.empty() && !req.peer_is_loopback()) + return fail(403, "permission_error", "loading an adapter reads a path on this machine, and a " + "server started without --api-key takes it only from a " + "loopback client"); + const json j = json::parse(req.body, nullptr, false); + if (j.is_discarded() || !j.is_object() || !j.contains("lora_name") || !j["lora_name"].is_string()) + return fail(400, "invalid_request_error", "the body must be a JSON object with lora_name"); + const std::string name = j["lora_name"].get(); + if (name.empty() || name == opt_.model_id) + return fail(400, "invalid_request_error", "lora_name must be non-empty and not the served model's name"); + std::string err; + int s; + if (load) { + if (!j.contains("lora_path") || !j["lora_path"].is_string()) + return fail(400, "invalid_request_error", "load_lora_adapter needs lora_path"); + s = opt_.lora_load(name, j["lora_path"].get(), &err); + } else { + s = opt_.lora_unload(name, &err); + } + if (s == RAD_E_NOTFOUND) return fail(404, "not_found_error", err); + if (s == RAD_E_STATE) return fail(409, "conflict_error", err); + if (s == RAD_E_FULL) return fail(503, "service_unavailable", err); + if (s < 0) return fail(400, "invalid_request_error", err.empty() ? std::string(rad_strerror(s)) : err); + metrics_.observe_http(200); + return HttpResponse::json_body(200, json{ { "status", "ok" }, { "lora_name", name }, + { "action", load ? "loaded" : "unloaded" } }.dump()); } HttpResponse Server::handle_metrics(const HttpRequest&) { diff --git a/core/server/server.h b/core/server/server.h index bbdf43fe..328744c9 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -121,8 +121,11 @@ struct ServerOptions { std::function 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 lora_resolve; + std::function*)> lora_acquire; std::function()> lora_names; + /* POST /v1/load_lora_adapter and /v1/unload_lora_adapter (vLLM's names and bodies). */ + std::function lora_load; + std::function lora_unload; std::string api_key; bool cors = true; @@ -233,6 +236,7 @@ private: HttpResponse handle_tokenizer_info(const HttpRequest& req); HttpResponse handle_server_info(const HttpRequest& req); HttpResponse handle_diagnostics(const HttpRequest& req); + HttpResponse handle_lora_admin(const HttpRequest& req, bool load); /* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning * efforts), shared by /server_info's `capabilities` and the model entry so they agree. */ json capabilities() const; diff --git a/core/server/server_priv.h b/core/server/server_priv.h index a695db40..b4122cfa 100644 --- a/core/server/server_priv.h +++ b/core/server/server_priv.h @@ -18,6 +18,8 @@ namespace server { struct Server::Generation { std::shared_ptr sink; + /* The runtime LoRA adapter this choice runs with, held so it cannot be unloaded under it. */ + std::shared_ptr lora_hold; std::unique_ptr detok; std::unique_ptr delta; /* chat streaming only, in the request's API shape */ uint64_t id = 0;