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
11 changes: 10 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,14 @@ FetchContent_Declare(httplib
GIT_TAG fe332fa06bac76a1c6d402c08f414052999347da) # v0.47.0
FetchContent_MakeAvailable(json httplib)

add_executable(onebit app/main.cpp app/serve.cpp app/recipes.cpp app/pm.cpp app/route_serve.cpp app/laya_checkpoint.cpp)
# config/laya-first.json (the routing table, docs/laya-first.md §4) is compiled in like
# config/recipes.json; `1bit laya-first --laya-first FILE` replaces it at run time.
file(READ ${CMAKE_SOURCE_DIR}/config/laya-first.json ONEBIT_LAYA_FIRST_JSON)
file(WRITE ${CMAKE_BINARY_DIR}/generated/laya_first_default.h
"// generated from config/laya-first.json by CMakeLists.txt\n#pragma once\n"
"static const char kDefaultLayaFirstJson[] = R\"ONEBITLAYAFIRST(${ONEBIT_LAYA_FIRST_JSON})ONEBITLAYAFIRST\";\n")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${CMAKE_SOURCE_DIR}/config/laya-first.json)
add_executable(onebit app/main.cpp app/serve.cpp app/recipes.cpp app/pm.cpp app/route_serve.cpp app/laya_checkpoint.cpp app/laya_first.cpp)
# config/recipes.json (tuned llama-server settings per model and route, docs/recipes.md) is
# compiled in as serve's default recipes; --recipes replaces them at run time.
file(READ ${CMAKE_SOURCE_DIR}/config/recipes.json ONEBIT_RECIPES_JSON)
Expand Down Expand Up @@ -173,6 +180,8 @@ add_test(NAME pm_route COMMAND ${CMAKE_SOURCE_DIR}/tests/pm_route.sh $<TARGET_FI
add_test(NAME bench_selftest COMMAND ${CMAKE_SOURCE_DIR}/tests/bench_selftest.sh $<TARGET_FILE:onebit>)
add_test(NAME prism_route COMMAND ${CMAKE_SOURCE_DIR}/tests/prism_route.sh $<TARGET_FILE:onebit>)
add_test(NAME laya_gguf_route COMMAND ${CMAKE_SOURCE_DIR}/tests/laya_gguf_route.sh $<TARGET_FILE:onebit>)
# The routing table that ships and the collection.router policy it desugars into (docs/laya-first.md §4).
add_test(NAME laya_first COMMAND ${CMAKE_SOURCE_DIR}/tests/laya_first.sh $<TARGET_FILE:onebit>)
add_test(NAME mem_admit_route COMMAND ${CMAKE_SOURCE_DIR}/tests/mem_admit_route.sh $<TARGET_FILE:onebit>)
# engine#315: what --hrx-cwsr-placement puts in an HRX backend's environment (app/hrx_cwsr.h); fake backend, no GPU.
add_test(NAME hrx_cwsr_route COMMAND ${CMAKE_SOURCE_DIR}/tests/hrx_cwsr_route.sh $<TARGET_FILE:onebit>)
Expand Down
215 changes: 215 additions & 0 deletions app/laya_first.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
// Copyright 2026 bong-water-water-bong
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "laya_first.h"

#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>

#include <nlohmann/json.hpp>

#include "laya_checkpoint.h" // laya_home(): the same ${XDG_DATA_HOME:-~/.local/share}/1bit root
#include "laya_first_default.h" // kDefaultLayaFirstJson, from config/laya-first.json

namespace onebit {
namespace {

using json = nlohmann::ordered_json;

// The classes Laya answers, in the order the policy declares its rules (docs/laya-first.md §4).
const std::vector<std::string>& classes() {
static const std::vector<std::string> order = {"short", "prose", "code", "long_doc"};
return order;
}

const std::vector<std::string>& devices() {
static const std::vector<std::string> known = {"hrx", "npu", "hybrid", "auto"};
return known;
}

bool contains(const std::vector<std::string>& v, const std::string& s) {
for (const auto& item : v)
if (item == s) return true;
return false;
}

std::string read_file(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("cannot read " + path);
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}

// The table: --laya-first FILE, else the installed <laya home dir>/laya-first.json, else the copy
// compiled in from config/laya-first.json (the same pattern as config/recipes.json and
// config/pm-experts.json).
std::string load_table(const std::string& given) {
namespace fs = std::filesystem;
if (!given.empty()) return read_file(given);
const std::string installed = laya_home("") + "/laya-first.json";
if (fs::exists(installed)) return read_file(installed);
return kDefaultLayaFirstJson;
}

// Everything the table promises must be checkable here rather than discovered by a user whose
// request landed on a class with a typo'd device.
void validate(const json& table) {
if (!table.is_object()) throw std::runtime_error("the table must be a JSON object");
if (table.value("version", "") != "1")
throw std::runtime_error("version must be \"1\"");
if (!table.contains("classes") || !table["classes"].is_object() || table["classes"].empty())
throw std::runtime_error("classes must be a non-empty object");
for (const auto& name : classes()) {
if (!table["classes"].contains(name))
throw std::runtime_error("classes is missing '" + name + "' (Laya names exactly these)");
}
for (auto it = table["classes"].begin(); it != table["classes"].end(); ++it) {
const std::string name = it.key();
const json& cls = it.value();
if (!contains(classes(), name))
throw std::runtime_error("classes.'" + name + "' is not a Laya class (short, prose, code, long_doc)");
if (!cls.is_object()) throw std::runtime_error("classes.'" + name + "' must be an object");
for (const char* key : {"model", "hf_repo", "device"}) {
if (!cls.contains(key) || !cls[key].is_string() || cls[key].get<std::string>().empty())
throw std::runtime_error("classes.'" + name + "'.model/hf_repo/device are required strings");
}
const std::string device = cls["device"].get<std::string>();
if (!contains(devices(), device))
throw std::runtime_error("classes.'" + name + "'.device '" + device +
"' is not one of hrx, npu, hybrid, auto");
if (!cls.contains("ctx") || !cls["ctx"].is_number_integer() || cls["ctx"].get<long>() <= 0)
throw std::runtime_error("classes.'" + name + "'.ctx must be a positive integer");
if (cls.contains("on_busy")) {
const json& busy = cls["on_busy"];
if (!busy.is_object() || !busy.contains("device") || !busy["device"].is_string())
throw std::runtime_error("classes.'" + name + "'.on_busy.device is required");
if (!contains(devices(), busy["device"].get<std::string>()))
throw std::runtime_error("classes.'" + name + "'.on_busy.device is not one of hrx, npu, hybrid, auto");
}
}
if (table.contains("scorer")) {
const json& scorer = table["scorer"];
if (!scorer.is_object() || !scorer.contains("hf_repo") || !scorer.contains("file"))
throw std::runtime_error("scorer must name hf_repo and file");
}
const std::string default_model = table.value("default_model", "");
if (default_model.empty())
throw std::runtime_error("default_model is required (the model a cold, unroutable request uses)");
bool known = false;
for (auto it = table["classes"].begin(); it != table["classes"].end(); ++it)
if (it.value().value("model", "") == default_model) known = true;
if (!known)
throw std::runtime_error("default_model '" + default_model + "' is not one of the classes' models");
}

// The floor a class rule needs. NOT 0.0: the classifier reports only the class Laya chose, so every
// other label scores exactly 0.0, and a band with `min_score: 0.0` matches `0.0 >= 0.0` - which makes
// the FIRST class rule swallow every request (measured against a live lemond: a `short` prompt routed
// to the `code` model). A floor strictly above zero is what turns the band into "Laya chose this class",
// and it still cannot drop a real decision, because Laya's confidence for a chosen class is never 0.
constexpr double kClassFloor = 0.01;

// The policy Lemonade already understands: one rule per class, `route_to` that class's model.
// The floor is deliberately low - Laya's calibrated confidence for `code` is about 0.44, so the band's
// default of 0.5 would drop the very decisions this table exists to route - but it is not zero, for the
// reason on kClassFloor above.
json desugar(const json& table) {
json components = json::array();
json rules = json::array();
for (const auto& name : classes()) {
const json& cls = table["classes"][name];
const std::string model = cls["model"].get<std::string>();
components.push_back(model);
rules.push_back(json{{"id", "laya-" + name},
{"match", json{{"classifier", "laya"}, {"label", name}, {"min_score", kClassFloor}}},
{"route_to", model}});
}
// The `laya` classifier entry itself: labels are the four classes, which is also what makes a
// typo in a rule's `label` a parse error rather than a rule that never matches.
json classifier = json{{"id", "laya"}, {"type", "laya"}, {"labels", classes()}};

// `user.` is not decoration: Lemonade refuses to register a definition that is not under it
// ("Registered model definitions must use a non-empty `user.*` name") - measured against a live
// lemond while exercising the release-check row, which is why the name the row looks for changed.
return json{{"version", "1"},
{"model_name", "user.Laya-First"},
{"recipe", "collection.router"},
{"components", components},
{"routing",
json{{"candidates", components},
{"default_model", table["default_model"]},
{"classifiers", json::array({classifier})},
{"rules", rules}}}};
}

void usage(std::FILE* out) {
std::fprintf(out,
"usage: 1bit laya-first [--laya-first FILE] [--policy FILE] [--check] [--json]\n"
" Reads the Laya-first routing table (config/laya-first.json, compiled in;\n"
" --laya-first FILE replaces it, else ${XDG_DATA_HOME:-~/.local/share}/1bit/laya-first.json\n"
" when it exists) and prints the collection.router policy it desugars into:\n"
" one rule per class (short, prose, code, long_doc), route_to that class's model.\n"
" --policy FILE write the policy there instead of stdout\n"
" --check validate the table only; exit 0 when it is usable\n");
}

} // namespace

int run_laya_first(int argc, char** argv) {
std::string table_path, policy_out;
bool check = false;
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-first") table_path = next();
else if (a == "--policy") policy_out = next();
else if (a == "--check") check = true;
else if (a == "--json") continue; // the output is JSON; accepted for symmetry with `route`
else if (a == "--help" || a == "-h") {
usage(stdout);
return 0;
} else throw std::runtime_error("unknown option " + a);
}

const json table = json::parse(load_table(table_path), nullptr, /*allow_exceptions=*/false);
if (table.is_discarded()) throw std::runtime_error("the table is not valid JSON");
validate(table);
if (check) {
std::fprintf(stderr, "1bit laya-first: %zu classes, default %s\n", classes().size(),
table["default_model"].get<std::string>().c_str());
return 0;
}

const std::string policy = desugar(table).dump(2) + "\n";
if (policy_out.empty()) {
std::fwrite(policy.data(), 1, policy.size(), stdout);
return 0;
}
std::ofstream out(policy_out, std::ios::trunc);
if (!out) throw std::runtime_error("cannot write " + policy_out);
out << policy;
if (!out) throw std::runtime_error("cannot write " + policy_out);
std::fprintf(stderr, "1bit laya-first: policy written to %s\n", policy_out.c_str());
return 0;
}

} // namespace onebit
27 changes: 27 additions & 0 deletions app/laya_first.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2026 bong-water-water-bong
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// `1bit laya-first`: the routing table that ships (docs/laya-first.md §4) and the
// `collection.router` policy it desugars into. The table is the product surface — class ->
// {model, hf_repo, file, device, ctx} — and the policy is the mechanism Lemonade already
// understands (one rule per class, `route_to` that class's model), so the engine, the validate
// endpoint and the decision format are untouched.
#pragma once

namespace onebit {

int run_laya_first(int argc, char** argv);

} // namespace onebit
9 changes: 9 additions & 0 deletions app/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ int onebit_ort_run_main(int argc, char** argv);
#endif
#ifdef ONEBIT_LAYA
#include "laya_checkpoint.h"
#include "laya_first.h"
#include "policy.h"
#include "route.h"
#include "route_serve.h"
Expand Down Expand Up @@ -306,6 +307,14 @@ int main(int argc, char** argv) {
}
}
#endif
if (cmd == "laya-first") {
try {
return onebit::run_laya_first(argc - 2, argv + 2);
} catch (const std::exception& e) {
std::fprintf(stderr, "1bit laya-first: %s\n", e.what());
return 1;
}
}
#ifdef ONEBIT_LAYA
if (cmd == "route") {
try {
Expand Down
43 changes: 43 additions & 0 deletions config/laya-first.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"version": "1",
"scorer": {
"hf_repo": "mys/laya-typed-decisions-GGUF",
"file": "laya_typed_decisions_q8_0.gguf",
"device": "hrx"
},
"pull_budget_s": 600,
"default_model": "Qwen3-0.6B-1bit",
"classes": {
"short": {
"model": "Qwen3-0.6B-1bit",
"hf_repo": "1bit-MONSTER/Qwen3-0.6B-GGUF",
"file": "Qwen3-0.6B-Q8_0.gguf",
"device": "hrx",
"ctx": 8192
},
"prose": {
"model": "ZAYA1-8B-1bit",
"hf_repo": "1bit-MONSTER/ZAYA1-8B-GGUF",
"file": "zaya1-8b-Q4_K_M.gguf",
"device": "hrx",
"ctx": 16384
},
"code": {
"model": "Qwen3-Coder-30B-A3B-Instruct-1bit",
"hf_repo": "1bit-MONSTER/Qwen3-Coder-30B-A3B-Instruct-GGUF",
"file": "Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf",
"device": "hrx",
"ctx": 32768
},
"long_doc": {
"model": "Qwen3.8-27B-1bit",
"hf_repo": "1bit-MONSTER/Qwen3.8-27B-UD-Q4_K_XL-MTP",
"file": "Qwen3.8-27B-UD-Q4_K_XL.gguf",
"device": "hrx",
"ctx": 65536,
"extra_files": [
"MTP/mtp-Qwen3.8-27B-Q4_0.gguf"
]
}
}
}
Loading
Loading