Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,35 @@ add_library(onebit_npu STATIC npu/full_elf.cpp npu/model.cpp npu/pack.cpp npu/pr
target_include_directories(onebit_npu PUBLIC npu)
target_link_libraries(onebit_npu PUBLIC nlohmann_json::nlohmann_json PRIVATE PkgConfig::PCRE2)

# ── Step 4: Laya router (docs/laya.md) ───────────────────────────────────
# The non-autoregressive decision scorer that picks where each request runs.
# Depends on onebit_npu only for its tokenizer.json reader; the scorer itself
# is device-independent (weights via model.safetensors, no Python at runtime).
add_library(onebit_laya STATIC laya/scorer.cpp laya/safetensors.cpp laya/route.cpp)
target_include_directories(onebit_laya PUBLIC laya)
target_link_libraries(onebit_laya PUBLIC onebit_npu)
# The engine binary gets `1bit route` and per-request routing through the scorer.
target_link_libraries(onebit PRIVATE onebit_laya)
target_compile_definitions(onebit PRIVATE ONEBIT_LAYA)

add_executable(laya_gate tests/laya_gate.cpp)
target_link_libraries(laya_gate PRIVATE onebit_laya nlohmann_json::nlohmann_json)
# Each pinned checkpoint gates against its own golden.json from the Python reference.
set(ONEBIT_LAYA_ROOT "" CACHE PATH "Root Laya checkpoint dir (model.safetensors + tokenizer/tokenizer.json)")
set(ONEBIT_LAYA_GOLDEN "" CACHE FILEPATH "golden.json for the root checkpoint")
set(ONEBIT_LAYA_TYPED_ROOT "" CACHE PATH "typed-decisions checkpoint dir")
set(ONEBIT_LAYA_TYPED_GOLDEN "" CACHE FILEPATH "golden.json for the typed-decisions checkpoint")
if(ONEBIT_LAYA_ROOT AND ONEBIT_LAYA_GOLDEN)
add_test(NAME laya_gate_root COMMAND laya_gate ${ONEBIT_LAYA_ROOT} ${ONEBIT_LAYA_GOLDEN})
endif()
if(ONEBIT_LAYA_TYPED_ROOT AND ONEBIT_LAYA_TYPED_GOLDEN)
add_test(NAME laya_gate_typed_decisions COMMAND laya_gate ${ONEBIT_LAYA_TYPED_ROOT} ${ONEBIT_LAYA_TYPED_GOLDEN})
endif()
set(ONEBIT_LAYA_ROUTE_MODEL "" CACHE PATH "Laya checkpoint dir for the per-request routing e2e test")
if(ONEBIT_LAYA_ROUTE_MODEL)
add_test(NAME laya_route_e2e COMMAND ${CMAKE_SOURCE_DIR}/tests/laya_route_e2e.sh $<TARGET_FILE:onebit> ${ONEBIT_LAYA_ROUTE_MODEL})
endif()

add_executable(npu_full_elf_test tests/npu_full_elf_test.cpp)
target_link_libraries(npu_full_elf_test PRIVATE onebit_npu)
add_test(NAME npu_full_elf_md5 COMMAND npu_full_elf_test)
Expand Down
60 changes: 60 additions & 0 deletions app/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
#include "private_route.h"
#include "unified.h"
#endif
#ifdef ONEBIT_LAYA
#include "route.h"
#include "scorer.h"
#endif
#include "serve.h"

#include <chrono>
Expand Down Expand Up @@ -66,6 +70,9 @@ void usage(FILE* out) {
" npu-run [options] generate on the NPU fast lane (npu-run --help)\n"
#endif
" comfy <workflow.json> run a ComfyUI workflow with ComfyUI.cpp (docs/comfyui.md)\n"
#ifdef ONEBIT_LAYA
" route [options] pick a device for a request via the Laya scorer\n"
#endif
" version print the version\n"
" help show this help\n");
#ifdef ONEBIT_NPU
Expand Down Expand Up @@ -180,6 +187,49 @@ int run_comfy(int argc, char** argv) {
::close(fd);
throw std::runtime_error("cannot run " + bin + ": " + std::strerror(err));
}
#ifdef ONEBIT_LAYA
// One request in, one device out: runs the Laya scorer's fixed routing question
// against the request state and prints the winning device (npu|hrx|vulkan|zinc).
int run_route(int argc, char** argv) {
std::string laya_model, state, devices_str = "npu,hrx,vulkan,zinc";
for (int i = 0; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string {
if (i + 1 >= argc) throw std::runtime_error(a + " needs a value");
return argv[++i];
};
if (a == "--laya-model") laya_model = next();
else if (a == "--state") state = next();
else if (a == "--devices") devices_str = next();
else if (a == "--help" || a == "-h") {
std::printf("usage: 1bit route --laya-model <dir> --state <text> [--devices npu,hrx,vulkan,zinc]\n"
" picks one of the devices for the request via the Laya scorer\n");
return 0;
} else throw std::runtime_error("unknown option " + a);
}
if (laya_model.empty()) throw std::runtime_error("--laya-model <dir> is required");
if (state.empty()) throw std::runtime_error("--state <text> is required");

std::vector<std::string> devices;
std::string cur;
for (std::istringstream ss(devices_str); std::getline(ss, cur, ',');)
if (!cur.empty()) devices.push_back(cur);
if (devices.empty()) throw std::runtime_error("--devices is empty");

onebit::laya::Scorer scorer;
if (!scorer.load(laya_model)) {
std::fprintf(stderr, "1bit route: %s\n", scorer.error().c_str());
return 1;
}
const std::string device = onebit::laya::route_device(scorer, state, devices);
if (device.empty()) {
std::fprintf(stderr, "1bit route: %s\n", scorer.error().c_str());
return 1;
}
std::printf("%s\n", device.c_str());
return 0;
}
#endif

} // namespace

Expand Down Expand Up @@ -234,6 +284,16 @@ int main(int argc, char** argv) {
return 127;
}
}
#ifdef ONEBIT_LAYA
if (cmd == "route") {
try {
return run_route(argc - 2, argv + 2);
} catch (const std::exception& e) {
std::fprintf(stderr, "1bit route: %s\n", e.what());
return 1;
}
}
#endif
if (cmd == "version" || cmd == "--version") {
std::printf("1bit %s\n", kVersion);
return 0;
Expand Down
138 changes: 133 additions & 5 deletions app/serve.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@
#ifdef ONEBIT_NPU
#include "unified.h"
#endif
#ifdef ONEBIT_LAYA
#include "route.h"
#include "scorer.h"
#endif

#include <httplib.h>
#include <nlohmann/json.hpp>
Expand Down Expand Up @@ -108,6 +112,7 @@ struct Options {
std::string embed, rerank; // RAG: an embedding model and a reranker, served beside the chat model
std::string role; // "embedding" or "reranking": the model itself is served in that role
std::vector<std::string> npu_opts; // --npu-opt KEY=VALUE, for a private NPU route
std::string laya_model; // --laya-model DIR: route each request by the Laya scorer (docs/laya.md)
};

// HRX dlopens the HSA runtime, and a distro libhsa rejects gfx1151's
Expand Down Expand Up @@ -452,9 +457,69 @@ Launch rag_launch(const Options& o, const std::string& model, const char* role,
return l;
}

// The devices a .gguf can run on, in the order the Laya router offers them. The NPU runs Q4NX
// model directories, not .gguf files (docs/npu.md), so it is not a candidate here; an NPU
// model directory routes to npu in run_serve.
const std::vector<std::string> kGgufDevices = {"vulkan", "hrx", "zinc"};

// The text the Laya scorer routes on: a completion's prompt, or a chat request's messages
// joined the way the request reads.
std::string request_state(const httplib::Request& req) {
json body;
try {
body = json::parse(req.body);
} catch (const std::exception&) {
return "";
}
if (body.contains("prompt") && body["prompt"].is_string()) return body["prompt"].get<std::string>();
std::string out;
if (body.contains("messages") && body["messages"].is_array())
for (const auto& m : body["messages"]) {
if (!m.is_object() || !m.contains("content")) continue;
auto add = [&](const std::string& t) {
if (t.empty()) return;
if (!out.empty()) out += "\n";
out += t;
};
const auto& c = m["content"];
if (c.is_string()) add(c.get<std::string>());
else if (c.is_array())
for (const auto& part : c)
if (part.is_object() && part.value("type", "") == "text") add(part.value("text", ""));
}
return out;
}

int serve_child(const Options& o) {
std::vector<Launch> backends;
if (o.adaptive) {
// --laya-model with --device auto: each request goes to the device the Laya scorer picks
// among the ones this build can run a .gguf on; a device's backend starts when it is
// first picked (one model is not loaded on every device at once)
const bool laya = !o.laya_model.empty() && o.device == "auto";
#ifdef ONEBIT_LAYA
std::unique_ptr<onebit::laya::Scorer> scorer;
std::vector<std::string> laya_devices;
if (laya) {
if (o.adaptive || !o.role.empty() || !o.prefill_device.empty() || o.lean)
throw std::runtime_error("--laya-model does not combine with --adaptive, --embedding/--reranking, --prefill-device or --lean");
scorer = std::make_unique<onebit::laya::Scorer>();
if (!scorer->load(o.laya_model)) throw std::runtime_error("laya: " + scorer->error());
for (const std::string& dev : kGgufDevices) {
try {
backends.push_back(launch_for(o, dev, free_port()));
laya_devices.push_back(dev);
} catch (const std::exception& e) {
std::fprintf(stderr, "1bit serve: laya: %s is not a candidate: %s\n", dev.c_str(), e.what());
}
}
if (backends.empty()) throw std::runtime_error("laya: no device in this build can run " + o.model);
}
#else
if (laya) throw std::runtime_error("--laya-model is not part of this build (-DONEBIT_LAYA=ON, docs/laya.md)");
#endif
if (laya) {
// the candidates are prepared above
} else if (o.adaptive) {
// Grows with the load: a lone request gets Vulkan (MTP if given, --adaptive-at slots,
// default 1); concurrent ones go to ROCm, which keeps scaling to 16 batched requests.
// MTP and batching live in separate backends: a server with MTP loaded batches at
Expand Down Expand Up @@ -489,7 +554,7 @@ int serve_child(const Options& o) {
} else {
backends.push_back(launch_for(o, o.device == "auto" ? "vulkan" : o.device, free_port()));
}
const std::string device = o.adaptive ? "vulkan+rocm" : backends[0].device;
const std::string device = laya ? "laya" : o.adaptive ? "vulkan+rocm" : backends[0].device;
const bool drop_model = backends[0].drop_model;
const std::string set_model = backends[0].set_model;

Expand All @@ -500,6 +565,7 @@ int serve_child(const Options& o) {

const std::string id = model_id(o);
std::atomic<bool> ready{false};

httplib::Server srv;
auto health = [&](const httplib::Request&, httplib::Response& res) {
res.status = ready ? 200 : 503;
Expand All @@ -514,6 +580,21 @@ int serve_child(const Options& o) {
res.set_content(json{{"object", "list"}, {"data", data}}.dump(), "application/json");
});
std::vector<std::unique_ptr<Child>> children;
// laya: the backends by index, started on first use (under start_mu; a start waits for
// the backend to be ready, up to 600 s)
std::vector<Child*> started(backends.size(), nullptr);
std::mutex start_mu;
auto ensure = [&](size_t i) -> bool {
std::lock_guard<std::mutex> lock(start_mu);
if (started[i]) return true;
const Launch& b = backends[i];
std::fprintf(stderr, "1bit serve: %s on %s (%s), picked by laya\n", id.c_str(), b.device.c_str(), b.argv[0].c_str());
auto c = std::make_unique<Child>(b.argv, b.env, b.port);
if (!c->wait_ready(std::chrono::seconds(600), g_stop)) return false;
started[i] = c.get();
children.push_back(std::move(c));
return true;
};
std::vector<std::atomic<int>> inflight(backends.size());
std::vector<std::atomic<long>> routed(backends.size());
std::mutex route_mu;
Expand All @@ -527,6 +608,27 @@ int serve_child(const Options& o) {
// choosing and reserving are one step, or a burst of requests all read "empty"
std::shared_ptr<InFlight> held;
size_t pick = 0;
#ifdef ONEBIT_LAYA
if (laya) {
const std::string dev = onebit::laya::route_device(*scorer, request_state(q), laya_devices);
const auto it = std::find(laya_devices.begin(), laya_devices.end(), dev);
if (it == laya_devices.end()) {
r.status = 502;
r.set_content(R"({"error":{"message":"laya routing failed"}})", "application/json");
return;
}
pick = size_t(it - laya_devices.begin());
if (!ensure(pick)) {
r.status = 503;
r.set_content(json{{"error", {{"message", backends[pick].device + " did not become ready"}}}}.dump(), "application/json");
return;
}
held = std::make_shared<InFlight>(&inflight[pick]);
++routed[pick];
forward(backends[pick].port, held, -1, id, backends[pick].drop_model, backends[pick].set_model, q, r);
return;
}
#endif
{
std::lock_guard<std::mutex> lock(route_mu);
if (backends.size() > 1 && inflight[0] >= o.adaptive_at) {
Expand All @@ -544,7 +646,8 @@ int serve_child(const Options& o) {
// The rest of llama-server's API, for the devices that run llama-server (Lemonade's
// llamacpp backend, which the onebit recipe inherits, forwards these to us). They go to
// the first backend; the NPU, ZINC and MLX answer 501.
const bool llama = device == "vulkan" || device == "hrx" || device == "rocm" || device == "vulkan+rocm";
const bool llama = device == "vulkan" || device == "hrx" || device == "rocm" || device == "vulkan+rocm" ||
(laya && backends[0].device == "vulkan");
auto unsupported = [&](const httplib::Request& q, httplib::Response& r) {
r.status = 501;
r.set_content(json{{"error", {{"message", q.path + " is not available on --device " + device},
Expand All @@ -556,6 +659,11 @@ int serve_child(const Options& o) {
r.set_content(R"({"error":{"message":"model is loading"}})", "application/json");
return;
}
if (laya && !ensure(0)) {
r.status = 503;
r.set_content(R"({"error":{"message":"backend did not become ready"}})", "application/json");
return;
}
relay(backends[0].port, q, r);
};
auto first_json = [&](const httplib::Request& q, httplib::Response& r) {
Expand All @@ -564,6 +672,11 @@ int serve_child(const Options& o) {
r.set_content(R"({"error":{"message":"model is loading"}})", "application/json");
return;
}
if (laya && !ensure(0)) {
r.status = 503;
r.set_content(R"({"error":{"message":"backend did not become ready"}})", "application/json");
return;
}
forward(backends[0].port, nullptr, -1, id, drop_model, set_model, q, r);
};
for (const char* path : {"/v1/responses", "/tokenize", "/detokenize", "/apply-template"})
Expand Down Expand Up @@ -621,7 +734,7 @@ int serve_child(const Options& o) {
sa.sa_handler = on_stop_signal;
::sigaction(SIGTERM, &sa, nullptr);
::sigaction(SIGINT, &sa, nullptr);
for (const auto& b : backends) {
for (const auto& b : laya ? std::vector<Launch>{} : backends) {
std::fprintf(stderr, "1bit serve: %s on %s (%s)\n", id.c_str(), b.device.c_str(), b.argv[0].c_str());
children.push_back(std::make_unique<Child>(b.argv, b.env, b.port));
}
Expand All @@ -637,8 +750,10 @@ int serve_child(const Options& o) {
}
}
ready = true;
std::fprintf(stderr, "1bit serve: ready on http://%s:%d\n", o.host.c_str(), o.port);
std::fprintf(stderr, "1bit serve: ready on http://%s:%d%s\n", o.host.c_str(), o.port,
laya ? " (laya routes each request; a device's backend starts when first picked)" : "");
auto all_alive = [&] {
std::lock_guard<std::mutex> lock(start_mu);
for (auto& c : children) if (!c->alive()) return false;
return true;
};
Expand All @@ -650,6 +765,7 @@ int serve_child(const Options& o) {
}
if (g_stop) {
std::fprintf(stderr, "1bit serve: stopping\n");
std::lock_guard<std::mutex> lock(start_mu);
for (auto& c : children) c->stop();
return 0;
}
Expand All @@ -670,6 +786,7 @@ void usage(FILE* out) {
" [--embed MODEL.gguf] [--rerank MODEL.gguf] RAG: /v1/embeddings and /v1/rerank\n"
" [--embedding | --reranking] serve the model itself as an embedding or reranking model\n"
" [--npu-opt KEY=VALUE ...] an option for a private NPU route (docs/npu.md)\n"
" [--laya-model DIR] with --device auto, the Laya scorer picks each request's device (docs/laya.md)\n"
" <model>: an NPU model directory (model.q4nx + npu/, or one a private NPU route serves),\n"
" a .gguf file, or with --device mlx a Hugging Face id (mlx-community/...)\n");
}
Expand Down Expand Up @@ -708,6 +825,7 @@ int run_serve(int argc, char** argv) {
else if (a == "--reranking") o.role = "reranking";
else if (a == "--rerank") o.rerank = next();
else if (a == "--npu-opt") o.npu_opts.push_back(next());
else if (a == "--laya-model") o.laya_model = next();
else if (a == "-h" || a == "--help") { usage(stdout); return 0; }
else throw std::runtime_error("unknown option " + a);
}
Expand All @@ -721,6 +839,16 @@ int run_serve(int argc, char** argv) {
npu::PrivateOptions opts;
for (const auto& kv : o.npu_opts) npu::parse_private_option(kv, opts);
if (const std::string why = npu_model_problem(o.model, opts); !why.empty()) throw std::runtime_error(why);
#ifdef ONEBIT_LAYA
// A Q4NX model directory runs on the NPU only; with --laya-model the router is still asked
// (with npu its only candidate), so every device the engine serves goes through Laya.
if (!o.laya_model.empty()) {
onebit::laya::Scorer scorer;
if (!scorer.load(o.laya_model)) throw std::runtime_error("laya: " + scorer.error());
const std::string dev = onebit::laya::route_device(scorer, o.model, {"npu"});
std::fprintf(stderr, "1bit serve: laya routes %s to %s (Q4NX model directory)\n", model_id(o).c_str(), dev.c_str());
}
#endif
// The NPU serves in process (unified.cpp).
std::vector<std::string> args = {"-m", o.model, "-p", std::to_string(o.port), "--host", o.host};
if (!o.alias.empty()) { args.push_back("--alias"); args.push_back(o.alias); }
Expand Down
Loading
Loading