Skip to content

serve --pm: the served model is the Project Manager, delegating to expert models Lemonade runs - #321

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/pm
Oct 6, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/pm

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

ZAYA1-8B becomes the engine's Project Manager. Owner direction (2026-10-05):

"zaya1-8b is made for reasoning, zaya1-8b-1bit needs to be the router for all models, find an expert llm
and load it, i.e. I ask zaya about coding, they dispatch an agent to do the code work on their behalf.
zaya1-8b-1bit is the Project Manager for 1bit engine."

1bit serve --pm [--pm-experts FILE] [--lemonade-url URL]: the resident model keeps every conversation and
POST /v1/chat/completions runs a tool loop (app/pm.cpp) instead of a plain forward. The PM gets a system
prompt and two tools, experts() and delegate(expert, task, context). A delegate call becomes one OpenAI
chat request to Lemonade for the expert's catalog id; Lemonade loads the expert (it keeps two LLMs at once,
so one expert runs beside the PM); the expert's answer is the tool result, cut at pm.max_result_bytes. At most
pm.max_rounds (4) rounds, the last without tools. Final answer streams as SSE when the client asked for a stream.
Lemonade down, or an expert error, becomes a tool result that says so and the PM answers alone. One log line per
delegation. Tool calls are read from llama-server's tool_calls or from ZAYA's own <zyphra_tool_call> text.

config/pm-experts.json ships built in (like recipes.json):

expert catalog id domain
code (default) Qwen2.5-Coder-7B-Instruct-1bit programming — light, 4.7 GB
code-heavy Qwen3-Coder-30B-A3B-Instruct-1bit large refactors, agentic coding
reasoning Qwen3.8-27B-1bit long reasoning, mathematics, analysis
agentic gpt-oss-20b-mxfp4-1bit tool-heavy workflows

General chat is the PM's own. --pm-experts FILE replaces the built-in list.

Measured, on Strix Halo (real run, not a mock)

1bit serve -m zaya1-8b-Q4_K_M.gguf --alias ZAYA1-8B-PM --pm --lemonade-url http://127.0.0.1:38725,
with Lemonade (our fork, 2026.42.0~1654.d7703e06) holding the catalog:

1bit serve: pm: ZAYA1-8B-PM is the project manager; experts through http://127.0.0.1:38725:
  code=Qwen2.5-Coder-7B-Instruct-1bit, code-heavy=Qwen3-Coder-30B-A3B-Instruct-1bit,
  reasoning=Qwen3.8-27B-1bit, agentic=gpt-oss-20b-mxfp4-1bit (config/pm-experts.json, 4 rounds max)

[a1] wall 40.2s rounds=2 delegations=[('code','Qwen2.5-Coder-7B-Instruct-1bit', 22084, True)] content_chars=3146 has_code=True
[a2] wall 36.2s rounds=2 delegations=[('code','Qwen2.5-Coder-7B-Instruct-1bit', 18985, True)] content_chars=3492 has_code=True
[a3] wall 30.4s rounds=2 delegations=[('code','Qwen2.5-Coder-7B-Instruct-1bit', 16021, True)] content_chars=2813 has_code=True
[a-stream] wall 23.9s delegations=[('code','Qwen2.5-Coder-7B-Instruct-1bit', ...)] content_chars=2463 has_code=True
[b] general question: wall 1.1s rounds=1 delegations=[]            <- PM answers alone, no expert loaded

and Lemonade's own /api/v1/health confirms the expert it was asked for is resident beside the PM:

{"backend_alive": true, "backend_health": "ready", "backend_url": "http://127.0.0.1:8001/v1",
 "checkpoint": "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF:qwen2.5-coder-7b-instruct-q4_k_m.gguf",
 "loaded": true, "model_name": "Qwen2.5-Coder-7B-Instruct-1bit", "pid": 824277,
 "recipe": "onebit", "slot_pool": "standard/llm", "status": "ready"}

The expert's llama-server runs on HRX (--device HRX0 -ngl 99) at ~47 t/s decode for the coder.

Tests

tests/pm_route.sh — ctest pm_route, no GPU, mock llama-server + mock Lemonade (27/27 pass):
both tool-call forms, no delegation on a general question, streaming SSE, Lemonade unreachable,
an erroring expert, the round cap, /v1/completions untouched, refusals (--pm with --laya,
an experts file without ids). tools/copyright.py --check passes.

Notes

  • Not to be merged: the release is on hold until the owner calls it.
  • Requires the Lemonade fork's onebit recipe with the PM option (ZAYA1-8B-PM-1bit, recipe option
    onebit_pm) — that catalog branch is the companion PR in the lemonade fork.
  • The engine never holds an API key: Lemonade decides auth/bind/port/UX and owns model loading.

@github-actions

github-actions Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit e8283a7)

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Memory Leak in SSE Streaming

The stream_final function in app/pm.cpp creates a shared pointer to a vector of strings (chunks) and a shared pointer to a size_t (cursor) to manage the streaming of SSE chunks. If an error occurs during streaming, the function may not properly clean up these shared pointers, potentially leading to a memory leak. The cleanup logic relies on the content_provider callback to eventually release the memory, but there's no explicit mechanism to handle errors during streaming.

void stream_final(httplib::Response& res, const std::string& id, const std::string& model, const json& message,
                  const std::string& finish) {
    json tpl = {{"id", id}, {"object", "chat.completion.chunk"}, {"created", now_s()}, {"model", model}};
    auto chunks = std::make_shared<std::vector<std::string>>();
    auto push = [&](json delta, json fin) {
        json c = tpl;
        c["choices"] = json::array({{{"index", 0}, {"delta", std::move(delta)}, {"finish_reason", std::move(fin)}}});
        chunks->push_back("data: " + c.dump() + "\n\n");
    };
    push({{"role", "assistant"}, {"content", ""}}, nullptr);
    auto pieces = [&](const char* field, const std::string& text) {
        // pieces of about 48 bytes, split at ASCII spaces so a UTF-8 sequence is never cut
        size_t i = 0;
        while (i < text.size()) {
            size_t j = std::min(text.size(), i + 48);
            if (j < text.size()) {
                const size_t sp = text.rfind(' ', j);
                if (sp != std::string::npos && sp > i) j = sp + 1;
                else
                    while (j < text.size() && (static_cast<unsigned char>(text[j]) & 0xC0) == 0x80) ++j;
            }
            push({{field, text.substr(i, j - i)}}, nullptr);
            i = j;
        }
    };
    if (message.contains("reasoning_content") && message["reasoning_content"].is_string())
        pieces("reasoning_content", message["reasoning_content"].get<std::string>());
    pieces("content", content_text(message.value("content", json())));
    push(json::object(), finish);
    chunks->push_back("data: [DONE]\n\n");
    auto cursor = std::make_shared<size_t>(0);
    res.set_chunked_content_provider("text/event-stream", [chunks, cursor](size_t, httplib::DataSink& sink) {
        while (*cursor < chunks->size()) {
            const std::string& d = (*chunks)[*cursor];
            if (!sink.write(d.data(), d.size())) return false;
            ++*cursor;
        }
        sink.done();
        return true;
    });
}
Possible Race Condition in Delegation Logging

The log vector in run_delegate function is accessed by multiple threads without synchronization. If multiple delegations occur simultaneously, there could be a race condition when pushing new Delegation objects into the log vector, potentially leading to data corruption or undefined behavior.

std::string run_delegate(const Config& cfg, const json& args, std::vector<Delegation>& log) {
    const std::string key = json_string(args.value("expert", json()));
    const std::string task = json_string(args.value("task", json()));
    const std::string context = json_string(args.value("context", json()));
    const Expert* e = nullptr;
    expert_or(cfg, key, e);
    Delegation d;
    d.expert = key;
    if (!e) {
        std::string keys;
        for (const auto& x : cfg.experts) keys += (keys.empty() ? "" : ", ") + x.key;
        log.push_back(d);
        std::fprintf(stderr, "1bit serve: pm: delegate %s: unknown expert (task %zu chars)\n", key.c_str(), task.size());
        return "delegation failed: there is no expert '" + key + "'. The experts are: " + (keys.empty() ? "(none)" : keys) +
               ". Answer the user yourself.";
    }
    d.id = e->id;
    if (task.empty()) {
        log.push_back(d);
        return "delegation failed: delegate() needs a task. Call it again with the full brief in `task`.";
    }
    json messages = json::array();
    messages.push_back({{"role", "system"},
                        {"content", "You are the " + e->domain + " expert of the 1bit engine's team. The Project Manager "
                                    "sends you one task; answer it completely and directly, code included. Your answer is relayed "
                                    "to the user as it is."}});
    messages.push_back({{"role", "user"}, {"content", context.empty() ? task : task + "\n\nContext:\n" + context}});
    json req = {{"model", e->id}, {"messages", messages}, {"stream", false}};
    if (e->max_tokens > 0) req["max_tokens"] = e->max_tokens;

    const auto t0 = std::chrono::steady_clock::now();
    auto elapsed = [&] { return long(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count()); };
    auto fail = [&](const std::string& why) {
        d.ms = elapsed();
        log.push_back(d);
        std::fprintf(stderr, "1bit serve: pm: delegate %s -> %s (task %zu chars) %ld ms failed: %s\n", key.c_str(),
                     e->id.c_str(), task.size(), d.ms, why.c_str());
        return "delegation to " + e->id + " failed: " + why + ". Tell the user the expert was not available and answer yourself.";
    };
    httplib::Client cli(cfg.lemonade_url);
    if (!cli.is_valid()) return fail("--lemonade-url " + cfg.lemonade_url + " is not a usable http:// URL");
    cli.set_connection_timeout(5);
    cli.set_read_timeout(cfg.delegate_timeout_s);
    cli.set_write_timeout(60);
    auto r = cli.Post(cfg.chat_path, req.dump(), "application/json");
    if (!r) return fail("Lemonade at " + cfg.lemonade_url + " did not answer (" + httplib::to_string(r.error()) + ")");
    json out;
    try {
        out = json::parse(r->body);
    } catch (const std::exception&) {
        return fail("Lemonade answered HTTP " + std::to_string(r->status) + " with a body that is not JSON");
    }
    if (r->status != 200) {
        std::string msg = out.is_object() && out.contains("error") ? json_string(out["error"].is_object() ? out["error"].value("message", json()) : out["error"]) : "";
        return fail("Lemonade answered HTTP " + std::to_string(r->status) + (msg.empty() ? "" : " (" + msg + ")"));
    }
    std::string answer;
    try {
        const json& m = out.at("choices").at(0).at("message");
        answer = content_text(m.value("content", json()));
        if (answer.empty() && m.contains("reasoning_content")) answer = json_string(m["reasoning_content"]);
    } catch (const std::exception&) {
        return fail("Lemonade's reply had no choices[0].message");
    }
    if (answer.empty()) return fail("the expert returned an empty answer");
    d.ms = elapsed();
    d.ok = true;
    log.push_back(d);
    bool cut = false;
    answer = cut_utf8(answer, cfg.max_result_bytes, &cut);
    std::fprintf(stderr, "1bit serve: pm: delegate %s -> %s (task %zu chars) %ld ms ok, %zu bytes%s\n", key.c_str(),
                 e->id.c_str(), task.size(), d.ms, answer.size(), cut ? " (cut)" : "");
    if (cut) answer += "\n[the expert's answer was cut at " + std::to_string(cfg.max_result_bytes) + " bytes]";
    return answer;
}
Incorrect Error Handling in PM Mode

In serve_child, when --pm is enabled, the code checks for conflicts with --laya and --embedding/--reranking, but it does not validate that the model specified with -m is actually a valid Project Manager model. This could lead to unexpected behavior if a non-PM model is used with --pm.

// --pm (docs/pm.md): the model is the Project Manager. Its chat completions run the tool loop
// in app/pm.cpp against the one backend; the experts are Lemonade's models, reached by URL.
pm::Config pm_cfg;
if (o.pm) {
    if (o.laya_auto || !o.laya_model.empty())
        throw std::runtime_error("--pm does not combine with --laya: the Project Manager routes among models, Laya among devices");
    if (!o.role.empty()) throw std::runtime_error("--pm does not combine with --embedding/--reranking");
    pm_cfg = pm::load_config(o.pm_experts, o.lemonade_url);
}
Potential Integer Overflow in UTF-8 Cutting

The cut_utf8 function in app/pm.cpp uses size_t for the input string size and the cut limit, but it does not check for potential integer overflow when performing operations like s.resize(end) or when calculating end. If the input string is extremely large, this could lead to unexpected behavior or crashes.

std::string cut_utf8(std::string s, size_t n, bool* cut) {
    *cut = false;
    if (s.size() <= n) return s;
    size_t end = n;
    while (end > 0 && (static_cast<unsigned char>(s[end]) & 0xC0) == 0x80) --end;
    s.resize(end);
    *cut = true;
    return s;
}
Insecure HTTP Client Usage

The httplib::Client used in run_delegate function is initialized with a plain http:// URL without any TLS configuration. This is insecure and could expose the system to man-in-the-middle attacks if the Lemonade server is not running on localhost. The documentation in docs/pm.md already mentions this limitation, but it's worth noting that this is a security concern.

httplib::Client cli(cfg.lemonade_url);

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 0aaf823

bong-water-water-bong and others added 2 commits October 5, 2026 18:45
…pert models Lemonade runs

`1bit serve --pm [--pm-experts FILE] [--lemonade-url URL]`: the resident model (ZAYA1-8B) keeps
every conversation; POST /v1/chat/completions runs a tool loop (app/pm.cpp) instead of a plain
forward. The PM gets a system prompt and two tools, experts() and delegate(expert, task, context).
A delegate call is one OpenAI chat request to Lemonade for the expert's catalog id (Lemonade loads
it; one expert runs beside the PM within its two-LLM limit); the expert's answer is the tool result,
cut at pm.max_result_bytes; the loop runs at most pm.max_rounds (4), the last round without tools.
The final answer streams as SSE when the client asked for a stream. Lemonade down or an expert
error becomes a tool result that says so, and the PM answers alone; one log line per delegation.
Tool calls are read from llama-server's tool_calls or from ZAYA's own <zyphra_tool_call> text.

config/pm-experts.json (built in, like recipes.json): code -> Qwen2.5-Coder-7B-Instruct-1bit
(the light default), code-heavy -> Qwen3-Coder-30B-A3B-Instruct-1bit, reasoning -> Qwen3.8-27B-1bit,
agentic -> gpt-oss-20b-mxfp4-1bit; general chat is the PM's own.

tests/pm_route.sh (ctest pm_route, no GPU): mock llama-server + mock Lemonade; both tool-call forms,
no delegation on a general question, streaming, Lemonade unreachable, an erroring expert, the round
cap, /v1/completions untouched, refusals.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…pm.md

`1bit serve --pm` (app/pm.cpp) makes the served model the Project Manager: it answers
general conversation itself and delegates to expert models Lemonade loads beside it.
Documented in docs/pm.md, with the README status line and the `--pm` entry in the
serve.md usage block and option list.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit e8283a7

@bong-water-water-bong
bong-water-water-bong merged commit 7406feb into main Oct 6, 2026
6 of 7 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/pm branch October 6, 2026 03:58
bong-water-water-bong pushed a commit that referenced this pull request Nov 12, 2026
…twice (engine #2137)

+ llama.cpp #322: the fused conv4 prefill shares the weight copy prefill already reads
+ llama.cpp #321 (engine #2150 test) and the attention accumulator bound test

docs/hrx.md: the 27B paragraph gets the #322 measurement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 12, 2026
…ng or short prompt (#2137) (#2241)

* Bump llama.cpp (hrx) 4107043c1 -> 228e1f652: the 27B holds no weight twice (engine #2137)

+ llama.cpp #322: the fused conv4 prefill shares the weight copy prefill already reads
+ llama.cpp #321 (engine #2150 test) and the attention accumulator bound test

docs/hrx.md: the 27B paragraph gets the #322 measurement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Bump llama.cpp (hrx) 228e1f652 -> 962507f8e: a short prompt holds no weight twice either (#2137)

llama.cpp #324: at 6 to 8 tokens the few-token kernels leave a weight prefill
reads packed to the packed kernels (Qwen3-4B 611 -> 398 device copies on a
6- or 8-word prompt). llama.cpp #325: a tied weight stays on the few-token
kernel. docs/hrx.md records the copies and the rate cost at those sizes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant