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: 11 additions & 0 deletions config/qwen3_reranker.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<|im_start|>system
Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".<|im_end|>
<|im_start|>user
<Instruct>: {{ instruction | default(instruct | default(messages | selectattr("role", "eq", "system") | map(attribute="content") | first | default("Given a web search query, retrieve relevant passages that answer the query", true), true), true) }}
<Query>: {{ messages | selectattr("role", "eq", "query") | map(attribute="content") | first }}
<Document>: {{ messages | selectattr("role", "eq", "document") | map(attribute="content") | first }}<|im_end|>
<|im_start|>assistant
<think>

</think>

14 changes: 9 additions & 5 deletions docs/CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,9 @@ entries.
## Kimi CLI

`~/.kimi-code/config.toml`, partly generated: `default_model = "servedeck/main"`, one
`[providers.servedeck]`, one `[models."servedeck/<key>"]` per registry model plus
`servedeck/main`, and `[thinking] enabled = true`.
`[providers.servedeck]`, one `[models."servedeck/<key>"]` per registry chat model plus
`servedeck/main`, and `[thinking] enabled = true`. A pooling model (an embedder or a reranker; see
[Configuration](CONFIGURATION.md)) gets no table, and a table written for one before is retired.

Capabilities are derived from the registry — `tool_use` for a tool parser, `thinking` +
`always_thinking` for a reasoning parser, `image_in` when `vision` is true. `servedeck/main`
Expand Down Expand Up @@ -225,9 +226,12 @@ policies, it dies the moment `servedeck switch` changes the card, and it is invi
ats-optimizer's own service, binds `0.0.0.0` rather than loopback, and servedeck never
touches it; `models.toml` validation rejects 8000 and 8010 as model ports outright.

What the gateway does not speak today: **no `/v1/embeddings`** — the request is forwarded and
the engine 404s `{"detail":"Not Found"}`, because a generation model registers no embeddings
route (verified live 2026-09-18), and nothing on this box serves embeddings. **`/v1/messages`
What the gateway does not speak today: **`/v1/embeddings` from a chat model** — the request is
forwarded and the engine 404s `{"detail":"Not Found"}`, because a generation model registers no
embeddings route (verified live 2026-09-18). The one model here that serves embeddings is the
knowledge base's `Qwen3-Embedding-8B` (a pooling model on :8021, started on demand), which no
client config lists; the hub calls its port directly, and a request through the gateway that
names it was not checked live. **`/v1/messages`
exists but is undocumented and unverified** — the engine registers it (with
`/v1/messages/count_tokens`) and the catch-all forwards it, but no client here uses it, no
policy is written for its shape, and a GET returns 405 from upstream. **No Ollama surface**,
Expand Down
2 changes: 1 addition & 1 deletion docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fails, rather than systemd refusing three modules later.
| `build` | string | yes | — | A key in `[builds]`. |
| `ctx` | int \| `"native"` | yes | — | `"native"` resolves to the checkpoint's own `max_position_embeddings` from the local hub cache (never fetched). An int pins a validated ceiling below it — GLM is `327680` because its context here is bounded by VRAM headroom, not by the checkpoint's 1,048,576. |
| `aliases` | list of strings | no | `[]` | Every name a client has ever used. Appended to `--served-model-name` and advertised in `GET /v1/models`. |
| `flags` | list of strings | no | `[]` | Appended verbatim to the argv after the computed flags. |
| `flags` | list of strings | no | `[]` | Appended verbatim to the argv after the computed flags. `--runner pooling` or `--convert embed\|classify\|reward` (with a space or `=`) makes the model a pooling model, an embedder or a reranker, which `servedeck wire` keeps out of every client config. |
| `env` | table of strings | no | `{}` | The model's own environment, merged over `[defaults.env]`. |
| `presets` | table of tables | no | `{}` | See below. |
| `vram_mib` | int | residents only | — | The resident's VRAM budget, from which its utilisation is derived. |
Expand Down
44 changes: 44 additions & 0 deletions models.toml
Original file line number Diff line number Diff line change
Expand Up @@ -630,3 +630,47 @@ flags = [

[models.lfm2.tools]
parser = "lfm2"

# --------------------------------------------------------------------------------
# Knowledge base (kcc kb, 2026-10-29): the embedder and reranker that the hub's data/kb/retrieval.json names, the pair
# the hub's model-size grid chose (KB design, 2026-10-29). Pooling models on stock032 (vLLM 0.32.0), each on its own
# loopback port, started on demand; `servedeck wire` keeps them out of every client config (--runner pooling). When
# they are down, a pack uses the hub's CPU embedder (bge-m3 on :8031, the fallback_embed of retrieval.json), then words
# and the graph. The reranker reads vLLM v0.32.0's qwen3_reranker.jinja (sha256 e1ee98e6...), kept in this repo as
# config/qwen3_reranker.jinja; its flag names the control plane's copy, the checkout servedeck.service runs from.
# Opt-in, like lfm2: at utils 0.21 and 0.12 the pair holds about 32,304 MiB, so a main model that wants most of the
# card refuses to start beside them (not_enough_vram).
# --------------------------------------------------------------------------------
# Qwen/Qwen3-Embedding-8B, apache-2.0, 15.1 GB BF16, 4,096 dims, last-token pooling.
[models.kb-emb-qwen3-8b]
id = "Qwen3-Embedding-8B"
repo = "Qwen/Qwen3-Embedding-8B"
slot = "resident"
vram_mib = 21000 # estimated budget; util floor2(21000/97887) = 0.21: 15.1 GB weights + activations + KV
port = 8021
build = "stock032"
ctx = 8192 # not native (40,960): claims and questions are short
flags = [
"--runner", "pooling",
"--dtype", "bfloat16",
"--max-num-seqs", "64",
"--max-num-batched-tokens", "16384",
]

# Qwen/Qwen3-Reranker-4B, apache-2.0, 8.04 GB BF16, scored through the sequence-classification view, as vLLM documents.
[models.kb-rr-qwen3-4b]
id = "Qwen3-Reranker-4B"
repo = "Qwen/Qwen3-Reranker-4B"
slot = "resident"
vram_mib = 12000 # estimated budget; util 0.12: 8.04 GB weights + activations
port = 8029
build = "stock032"
ctx = 8192 # native 40,960
flags = [
"--runner", "pooling",
"--dtype", "bfloat16",
"--max-num-seqs", "64",
"--max-num-batched-tokens", "16384",
"--hf-overrides", "{\"architectures\": [\"Qwen3ForSequenceClassification\"], \"classifier_from_token\": [\"no\", \"yes\"], \"is_original_qwen3_reranker\": true}",
"--chat-template", "/home/pctablet505/Projects/servedeck/config/qwen3_reranker.jinja",
]
4 changes: 4 additions & 0 deletions servedeck/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
# since Flash-Next was removed; served from the stock build. Its own label,
# not "stock": the map must stay 1:1 for _reverse_arch_backends().
"Qwen3_5MoeForConditionalGeneration": "ornith",
# Qwen/Qwen3-Embedding-8B and Qwen/Qwen3-Reranker-4B config.json (2026-11-21),
# the knowledge base's pooling pair; served from the stock032 build with
# --runner pooling. Its own label: the map must stay 1:1.
"Qwen3ForCausalLM": "qwen3",
}

def arch_backends() -> dict[str, str]:
Expand Down
38 changes: 31 additions & 7 deletions servedeck/wire.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,29 @@
_DEFAULT_MAX_OUTPUT_TOKENS = 4096


#: ``--convert`` values with which vLLM serves a generation checkpoint as a pooling model.
_POOLING_CONVERTS = frozenset({"embed", "classify", "reward"})


def _flag_value(flags: tuple[str, ...], name: str) -> str | None:
"""The value ``flags`` give to ``name``, written ``name value`` or ``name=value``; the last one wins, as in argparse.
None when the flag is absent."""
value = None
for i, arg in enumerate(flags):
if arg == name and i + 1 < len(flags):
value = flags[i + 1]
elif arg.startswith(name + "="):
value = arg[len(name) + 1:]
return value


def _chats(m: _models.Model) -> bool:
"""Whether a client can chat with the model. A pooling model (an embedder or a reranker, served with
``--runner pooling`` or ``--convert embed|classify|reward``, in either spelling) answers /v1/embeddings or
/v1/rerank and never chat completions, so no client config lists it."""
return _flag_value(m.flags, "--runner") != "pooling" and _flag_value(m.flags, "--convert") not in _POOLING_CONVERTS


def _vscode_entry(served_name: str, m: _models.Model, ctx: int) -> dict[str, Any]:
max_out = m.max_output_tokens if m.max_output_tokens is not None else _DEFAULT_MAX_OUTPUT_TOKENS
return {
Expand Down Expand Up @@ -142,7 +165,7 @@ def render_vscode(
entries.append(_vscode_entry(_MAIN_ROUTE, narrowest, ctx))
for m in registry.models.values():
ctx = resolve_ctx(m)
if ctx <= 0:
if ctx <= 0 or not _chats(m):
continue
entries.append(_vscode_entry(m.id, m, ctx))
for preset_name in m.presets:
Expand Down Expand Up @@ -437,11 +460,12 @@ def render_kimi(
kimi-code provider, other models, oauth, services) is left untouched."""
resolved = {key: resolve_ctx(m) for key, m in registry.models.items()}
main_models = [m for m in registry.models.values() if m.slot == "main" and resolved[m.key] > 0]
# Retire only tables for models that left the registry. A model whose
# context is unknown right now (weights not in the hub cache, a disk not
# mounted) keeps its table: it is still a registry model, and dropping it
# would make the client forget a model that comes back on the next apply.
wanted_headers = {f'[models."servedeck/{key}"]' for key in registry.models}
# Retire only tables for models that left the registry, or that no client
# can chat with (a pooling model). A model whose context is unknown right
# now (weights not in the hub cache, a disk not mounted) keeps its table:
# it is still a registry model, and dropping it would make the client
# forget a model that comes back on the next apply.
wanted_headers = {f'[models."servedeck/{key}"]' for key, m in registry.models.items() if _chats(m)}
wanted_headers.add(f'[models."servedeck/{_MAIN_ROUTE}"]')

text = _remove_sections(
Expand All @@ -454,7 +478,7 @@ def render_kimi(
)
for key, m in registry.models.items():
ctx = resolved[key]
if ctx <= 0:
if ctx <= 0 or not _chats(m):
continue
data = {
"provider": "servedeck",
Expand Down
13 changes: 13 additions & 0 deletions tests/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,10 +412,23 @@ def test_known_archs_map_is_exactly_the_two_documented_entries() -> None:
"Glm5NextForConditionalGeneration": "glm53",
"Lfm2ForCausalLM": "stock",
"Qwen3_5MoeForConditionalGeneration": "ornith",
"Qwen3ForCausalLM": "qwen3",
}
assert len(set(KNOWN_ARCHS.values())) == len(KNOWN_ARCHS), "map must stay 1:1"


def test_the_knowledge_base_pooling_checkpoints_are_servable(tmp_path: Path) -> None:
"""The KB's embedder and reranker are Qwen3ForCausalLM checkpoints. Unmapped, `doctor` failed both weights rows and
the dashboard offered neither, although both were complete in the hub cache."""
config = {"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3", "max_position_embeddings": 40960,
"num_hidden_layers": 36, "num_key_value_heads": 8, "head_dim": 128}
for repo in ("models--Qwen--Qwen3-Embedding-8B", "models--Qwen--Qwen3-Reranker-4B"):
_make_repo(tmp_path, repo, config=config, safetensors={"model-1.safetensors": GIB})
entries = discover_models(tmp_path)
assert [(e.repo_id, e.servable, e.reason) for e in entries] == [
("Qwen/Qwen3-Embedding-8B", True, None), ("Qwen/Qwen3-Reranker-4B", True, None)]


def test_arch_map_is_the_built_in_map_and_nothing_layers_over_it() -> None:
"""v1 let `[backends.<name>].architectures` in servedeck.toml extend this
map, because a model could not be launched until its architecture was
Expand Down
2 changes: 1 addition & 1 deletion tests/test_doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def get(url: str, timeout: float) -> httpx.Response:
def test_check_registry_ok_on_real_models_toml():
r = doctor.check_registry(REPO_ROOT / "models.toml")
assert r.ok is True
assert "7 model(s)" in r.detail
assert "9 model(s)" in r.detail


def test_check_registry_fails_on_bad_file(tmp_path):
Expand Down
15 changes: 14 additions & 1 deletion tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,8 @@ def test_the_agent_profile_admits_a_browser_sessions_screenshots():
def test_real_models_toml_loads():
"""The repo-root models.toml (the actual deliverable) must load and validate."""
reg = models.load(REPO_ROOT / "models.toml")
assert set(reg.models) == {"qwen27b", "flashnext", "flashnext-batch", "fp4local", "glm53", "lfm2", "ornith"}
assert set(reg.models) == {"qwen27b", "flashnext", "flashnext-batch", "fp4local", "glm53", "lfm2", "ornith",
"kb-emb-qwen3-8b", "kb-rr-qwen3-4b"}
assert reg.gpu.total_mib == 97887
assert reg.gpu.margin_mib == 1024
assert reg.defaults_env == {
Expand All @@ -261,6 +262,18 @@ def test_real_models_toml_loads():
}


def test_the_kb_reranker_chat_template_is_a_file_this_repo_keeps():
"""The reranker's --chat-template names config/qwen3_reranker.jinja in the control plane's checkout: servedeck.service
runs from ~/Projects/servedeck and reads that checkout's models.toml, so the file must ship in the same commit. It is
vLLM v0.32.0's examples/pooling/score/template/qwen3_reranker.jinja, byte for byte."""
import hashlib

flags = models.load(REPO_ROOT / "models.toml").models["kb-rr-qwen3-4b"].flags
assert flags[flags.index("--chat-template") + 1] == "/home/pctablet505/Projects/servedeck/config/qwen3_reranker.jinja"
assert hashlib.sha256((REPO_ROOT / "config" / "qwen3_reranker.jinja").read_bytes()).hexdigest() == (
"e1ee98e69aab7b2da366edf1c50efcef37e34b4a0c50fb816336213e68d9047a")


# --------------------------------------------------------------------------- #
# Validation — one failing fixture per rule
# --------------------------------------------------------------------------- #
Expand Down
48 changes: 46 additions & 2 deletions tests/test_wire.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ def resolve_ctx(registry):
)


def _pooling(m: models.Model) -> bool:
"""Served with `--runner pooling`: an embedder or a reranker, which answers no chat completions."""
return "--runner" in m.flags and m.flags[m.flags.index("--runner") + 1] == "pooling"


# --------------------------------------------------------------------------- #
# VS Code
# --------------------------------------------------------------------------- #
Expand All @@ -54,14 +59,53 @@ def test_vscode_empty_existing_creates_group(registry, resolve_ctx):
assert data[0]["apiType"] == "chat-completions"
ids = [e["id"] for e in data[0]["models"]]
# The slot first (the stable pick), then one per id and per preset:
# 1 + 7 base ids + 3 glm53 presets = 11.
# 1 + 7 chat ids + 3 glm53 presets = 11; the KB embedder and reranker are pooling models, never listed.
assert ids[0] == "main", "the entry that survives a switch is the obvious pick"
assert ids.count("Qwen3.8-27B-NVFP4") == 1
assert ids.count("Ornith-1.5-122B-NVFP4") == 1
assert "glm53-flash-low" in ids and "glm53-flash-high" in ids and "glm53-flash-max" in ids
assert len(ids) == 11


def test_no_client_lists_a_pooling_model(registry, resolve_ctx):
"""An embedder or a reranker (`--runner pooling`) answers /v1/embeddings or /v1/rerank, never chat completions: neither
VS Code nor Kimi lists one, and a Kimi table written for one before is retired."""
pooling = {key: m.id for key, m in registry.models.items() if _pooling(m)}
assert pooling == {"kb-emb-qwen3-8b": "Qwen3-Embedding-8B", "kb-rr-qwen3-4b": "Qwen3-Reranker-4B"}
assert all(resolve_ctx(registry.models[key]) > 0 for key in pooling) # a known context: only the runner keeps them out
vscode = [e["id"] for e in json.loads(wire.render_vscode(registry, "", resolve_ctx=resolve_ctx))[0]["models"]]
stale = "".join(f'{wire._OWNED_COMMENT}\n[models."servedeck/{key}"]\nprovider = "servedeck"\nmodel = "{name}"\n\n'
for key, name in pooling.items()) # tables an earlier `servedeck wire` wrote
kimi = wire.render_kimi(registry, stale, resolve_ctx=resolve_ctx)
assert set(pooling.values()).isdisjoint(vscode), vscode
assert all(f'servedeck/{key}"' not in kimi and name not in kimi for key, name in pooling.items()), kimi


@pytest.mark.parametrize("extra, chats", [
(("--runner", "pooling"), False),
(("--runner=pooling",), False),
(("--convert", "embed"), False),
(("--convert=classify",), False),
(("--convert", "reward"), False),
(("--runner", "generate"), True),
(("--runner=generate",), True),
(("--convert", "none"), True),
(("--runner", "pooling", "--runner", "generate"), True), # the last one wins, as vLLM's argparse reads it
])
def test_a_model_is_wired_unless_its_flags_make_it_a_pooling_model(registry, resolve_ctx, extra, chats):
"""vLLM serves a pooling model for `--runner pooling` or `--convert embed|classify|reward`, written with a space or
with `=`; any other runner chats. A resident chat model given each set of flags is in the VS Code and Kimi configs
exactly when it chats."""
import dataclasses

lfm2 = registry.models["lfm2"]
changed = dataclasses.replace(lfm2, flags=lfm2.flags + extra)
reg = dataclasses.replace(registry, models={**registry.models, "lfm2": changed})
vscode = [e["id"] for e in json.loads(wire.render_vscode(reg, "", resolve_ctx=resolve_ctx))[0]["models"]]
kimi = wire.render_kimi(reg, "", resolve_ctx=resolve_ctx)
assert (lfm2.id in vscode, 'servedeck/lfm2"' in kimi) == (chats, chats)


def test_vscode_entry_fields(registry, resolve_ctx):
out = wire.render_vscode(registry, "", resolve_ctx=resolve_ctx)
data = json.loads(out)
Expand Down Expand Up @@ -441,7 +485,7 @@ def test_wire_leaves_out_a_model_whose_weights_are_not_downloaded(tmp_path, monk
client. Now each such model is left out, and the rest are written."""
monkeypatch.setenv("SERVEDECK_HF_HUB_DIR", str(tmp_path)) # nothing downloaded
native = [m for m in registry.models.values() if not isinstance(m.ctx, int)]
pinned = [m for m in registry.models.values() if isinstance(m.ctx, int)]
pinned = [m for m in registry.models.values() if isinstance(m.ctx, int) and not _pooling(m)] # chat models: a pooling model is never wired
assert native and pinned # the registry exercises both kinds

resolver = wire.make_default_ctx_resolver(registry)
Expand Down