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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ jobs:
- name: Configure
run: cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc-15 -DCMAKE_CXX_COMPILER=g++-15
- name: Build
run: cmake --build build --target onebit npu_full_elf_test npu_pack_test npu_q4nx_test npu_lax_test tokenizer_test -j
run: cmake --build build --target onebit npu_full_elf_test npu_pack_test npu_q4nx_test npu_lax_test tokenizer_test think_split_test -j
- name: Test
run: ctest --test-dir build --output-on-failure
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ target_link_libraries(onebit PRIVATE nlohmann_json::nlohmann_json httplib::httpl

# Runs everywhere, CI included: serve's proxy against a fake backend.
add_test(NAME smoke_serve COMMAND ${CMAKE_SOURCE_DIR}/tests/smoke_serve.sh $<TARGET_FILE:onebit>)
# The NPU route's <think> split into reasoning_content (app/think_split.h); header only, runs in CI.
add_executable(think_split_test tests/think_split_test.cpp)
target_include_directories(think_split_test PRIVATE app)
add_test(NAME think_split COMMAND think_split_test)

# ── `1bit serve` end to end (docs/serve.md) ───────────────────────────────
# Needs a GGUF (e.g. Qwen3-0.6B Q4_K_M); tests each device this build has.
Expand Down
76 changes: 76 additions & 0 deletions app/think_split.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// 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.
#pragma once

#include <algorithm>
#include <string>

namespace onebit {

// Splits a thinking model's output as llama-server does (reasoning_format "auto"): the text
// inside <think>...</think> is reasoning_content, the rest content. Tags may arrive split across
// tokens, so a possible partial tag is held back; the think block is only entered before any
// content, and whitespace around the block is dropped.
struct ThinkSplit {
bool in_think;
bool content_started = false;
bool reasoning_started = false;
std::string buf;
explicit ThinkSplit(bool opened) : in_think(opened) {}

template <class Emit> // Emit(bool reasoning, const std::string& text)
void feed(const std::string& t, Emit&& emit) {
buf += t;
for (;;) {
const std::string tag = in_think ? "</think>" : "<think>";
const size_t p = buf.find(tag);
const bool opens = p != std::string::npos && !in_think && !content_started &&
buf.find_first_not_of(" \t\r\n") >= p; // only whitespace before it
if (p != std::string::npos && (in_think || opens)) {
out(buf.substr(0, p), emit);
buf.erase(0, p + tag.size());
in_think = !in_think;
continue;
}
// hold back the longest suffix that could start the tag
size_t keep = 0;
for (size_t k = std::min(tag.size() - 1, buf.size()); k > 0; --k)
if (buf.compare(buf.size() - k, k, tag, 0, k) == 0) { keep = k; break; }
out(buf.substr(0, buf.size() - keep), emit);
buf.erase(0, buf.size() - keep);
return;
}
}
template <class Emit>
void flush(Emit&& emit) {
out(buf, emit);
buf.clear();
}

private:
template <class Emit>
void out(std::string text, Emit& emit) {
bool& started = in_think ? reasoning_started : content_started;
if (!started) {
const size_t b = text.find_first_not_of(" \t\r\n");
if (b == std::string::npos) return;
text.erase(0, b);
started = true;
}
if (!text.empty()) emit(in_think, text);
}
};

} // namespace onebit
38 changes: 29 additions & 9 deletions app/unified.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
// prompt's prefix (--snapshots, npu/lax_turns.h): a chat follow-up re-feeds only the turns
// after the one its history last diverged in. It starts over otherwise.
#include "unified.h"
#include "think_split.h"

#include "generate.h"
#include "lax.h"
Expand Down Expand Up @@ -153,11 +154,14 @@ void handle_generate(Engine& e, const httplib::Request& req, httplib::Response&
return;
}
std::string prompt;
bool split_reasoning = false, think_opened = false;
try {
bool thinking = true;
if (body.contains("chat_template_kwargs") && body["chat_template_kwargs"].is_object())
thinking = body["chat_template_kwargs"].value("enable_thinking", true);
prompt = chat ? chatml(body.at("messages"), thinking, e.open_think) : body.at("prompt").get<std::string>();
split_reasoning = chat && thinking && body.value("reasoning_format", std::string("auto")) != "none";
think_opened = thinking && e.open_think;
} catch (const std::exception& ex) {
res.status = 400;
res.set_content(json{{"error", {{"message", std::string("bad request: ") + ex.what()}}}}.dump(), "application/json");
Expand Down Expand Up @@ -199,9 +203,12 @@ void handle_generate(Engine& e, const httplib::Request& req, httplib::Response&
};
// By value: for a stream, httplib calls the content provider after this
// handler has returned.
auto chunk = [id, object, created, model = e.id, chat](const std::string& text, const json& finish) {
auto chunk = [id, object, created, model = e.id, chat](const std::string& text, const json& finish,
bool reasoning = false) {
json c{{"id", id}, {"object", object}, {"created", created}, {"model", model}};
c["choices"] = json::array({chat ? json{{"index", 0}, {"delta", {{"content", text}}}, {"finish_reason", finish}}
c["choices"] = json::array({chat ? json{{"index", 0},
{"delta", {{reasoning ? "reasoning_content" : "content", text}}},
{"finish_reason", finish}}
: json{{"index", 0}, {"text", text}, {"finish_reason", finish}}});
return "data: " + c.dump() + "\n\n";
};
Expand All @@ -223,12 +230,21 @@ void handle_generate(Engine& e, const httplib::Request& req, httplib::Response&

if (stream) {
res.set_chunked_content_provider("text/event-stream", [run, chunk, usage, timings, stream_usage, id, object, created,
split_reasoning, think_opened,
model = e.id](size_t, httplib::DataSink& sink) mutable {
try {
ThinkSplit split(think_opened);
bool ok = true;
auto emit = [&](bool reasoning, const std::string& t) {
const std::string c = chunk(t, nullptr, reasoning);
ok = ok && sink.write(c.data(), c.size());
};
auto [r, n_prompt, n_cached, cache] = run([&](const std::string& t) {
const std::string c = chunk(t, nullptr);
return sink.write(c.data(), c.size());
if (split_reasoning) split.feed(t, emit);
else emit(false, t);
return ok;
});
if (split_reasoning) split.flush(emit);
std::string end = chunk("", r.stopped_at_eos ? "stop" : "length");
if (stream_usage) {
const json u{{"id", id}, {"object", object},
Expand All @@ -249,16 +265,20 @@ void handle_generate(Engine& e, const httplib::Request& req, httplib::Response&
return;
}
try {
std::string text;
std::string text, reasoning;
ThinkSplit split(think_opened);
auto emit = [&](bool r, const std::string& t) { (r ? reasoning : text) += t; };
auto [r, n_prompt, n_cached, cache] = run([&](const std::string& t) {
text += t;
if (split_reasoning) split.feed(t, emit);
else text += t;
return true;
});
if (split_reasoning) split.flush(emit);
json out{{"id", id}, {"object", object}, {"created", created}, {"model", e.id}};
const char* finish = r.stopped_at_eos ? "stop" : "length";
out["choices"] = json::array({chat ? json{{"index", 0},
{"message", {{"role", "assistant"}, {"content", text}}},
{"finish_reason", finish}}
json message{{"role", "assistant"}, {"content", text}};
if (!reasoning.empty()) message["reasoning_content"] = reasoning;
out["choices"] = json::array({chat ? json{{"index", 0}, {"message", message}, {"finish_reason", finish}}
: json{{"index", 0}, {"text", text}, {"finish_reason", finish}}});
out["usage"] = usage(r, n_prompt, n_cached);
out["timings"] = timings(r, cache);
Expand Down
2 changes: 1 addition & 1 deletion docs/lemonade.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ What "fully embedded" still needs, measured on Strix Halo. The runs use the pinn
repo, the recipe hands `1bit serve` the directory, and the engine runs it on its own lax
kernels as full ELFs (16.0 tok/s). Still open:
- the smaller NPU models: their lane kernels are captured, not built from source;
- `reasoning_content`: the NPU route returns the thinking inside `content`;
- ~~`reasoning_content`~~: done (#73), the NPU route splits the thinking out as llama-server does;
- models in our own Hugging Face repos. (engine + fork)
7. **Beyond the LLM suite:**
- image generation: `1bit comfy` behind Lemonade's image endpoint;
Expand Down
2 changes: 1 addition & 1 deletion docs/serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ One model per process:
|---|---|
| `GET /health`, `GET /v1/health` | 503 while the model loads, then 200 |
| `GET /v1/models` | the one model (`--alias`, else the file or directory name) |
| `POST /v1/chat/completions` | streamed (SSE) or not |
| `POST /v1/chat/completions` | streamed (SSE) or not; a thinking model's `<think>` block comes back as `reasoning_content` (`"reasoning_format": "none"` keeps it in `content`) |
| `POST /v1/completions` | |
| `POST /v1/embeddings` | with `--embed` (RAG) |
| `POST /v1/rerank` | with `--rerank` (RAG) |
Expand Down
45 changes: 45 additions & 0 deletions tests/think_split_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// 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.
//
// ThinkSplit (app/think_split.h): the NPU route's reasoning_content split.
#include "think_split.h"

#include <cstdio>
#include <string>
#include <vector>

struct R { std::string c, r; };
R run(bool opened, std::vector<std::string> parts) {
onebit::ThinkSplit s(opened); R out;
auto emit=[&](bool reasoning, const std::string& t){ (reasoning?out.r:out.c)+=t; };
for (auto& p: parts) s.feed(p, emit);
s.flush(emit); return out;
}
int fails=0;
void check(const char* name, R got, const char* c, const char* r){
bool ok = got.c==c && got.r==r; fails += !ok;
std::printf("%s %s: content=[%s] reasoning=[%s]\n", ok?"PASS":"FAIL", name, got.c.c_str(), got.r.c_str());
}
int main(){
check("tags whole", run(false,{"<think>\nplan</think>\n\nParis"}), "Paris", "plan");
check("tags split", run(false,{"<th","ink>pl","an</th","ink>","\n\nPar","is"}), "Paris", "plan");
check("opened by template", run(true,{"plan it\n","</think>","\n\nParis"}), "Paris", "plan it\n");
check("no think", run(false,{"Par","is"}), "Paris", "");
check("literal tag after content", run(false,{"use <think> tags"}), "use <think> tags", "");
check("unfinished think", run(false,{"<think>still going"}), "", "still going");
return fails;
}


Loading