Skip to content
Open
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
4 changes: 4 additions & 0 deletions docs/adding-a-gpu-vendor.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,10 @@ VRAM policy that has to be rethought rather than parameterised. That is a port,
and it should be opened as one — with the unified-memory question answered
first, because everything else follows from it.

Until that port exists, an inference server on such a machine can already be
used from a console on a supported one: a hand-written proxy entry, described
in [remote-models.md](remote-models.md).

## Where to look in the code

| Question | File |
Expand Down
95 changes: 95 additions & 0 deletions docs/remote-models.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Models on another machine

The console starts and supervises the engines it knows (llama.cpp, vLLM,
SGLang) on the cards of this machine. A model served by a machine it does
not run — a Mac running [Yunshu](https://github.com/YuhuanStudio/Yunshu),
a second box, a friend's server — can still be used through the console's
`/v1` by writing one entry into llama-swap's `config.yaml` by hand. The
console preserves hand-written entries when it writes the file
(`internal/llamaswap` reads and writes it without losing what a person
wrote), and as of the change this document ships with it never frees or waits on ComfyUI
to "make room" for such an entry, and never polls it as llama-server.

## The entry

llama-swap requires a `cmd` on every entry, so the entry hangs its
lifecycle on a placeholder and points its `proxy` at the other machine:

```yaml
models:
mac-qwen:
name: Qwen3.4B on the Mac
cmd: sleep 3600
proxy: http://192.168.1.30:8000
useModelName: Qwen3-4B-MLX-4bit
checkEndpoint: /v1/models
ttl: 0
aliases:
- qwen-mac
```

`proxy` is where every `/v1` request for this id goes; `checkEndpoint`
is what llama-swap probes before forwarding (use `none` to skip it);
`useModelName` is what the server is sent in the `model` field, which
servers that validate it (vLLM, SGLang, Yunshu's single-model mode)
otherwise refuse; the placeholder process is what llama-swap starts,
health-checks and kills on unload, which is why `ttl: 0` is the plain
reading — there is nothing to time out. The console recognises an entry
as remote when its `proxy` is explicit, names something other than a
loopback address, and contains no `${PORT}` or macro; that is what keeps
it out of the card and VRAM arithmetic.

Measured on llama-swap v273 (container image `cpu`, built 2026-11-15)
against a real Mac running Yunshu 0.1.8.dev4 with
`lmstudio-community/Qwen3-4B-MLX-4bit`, through a console on a Linux
box: `GET /v1/models` listed the id and a request by its alias answered
from the Mac; chat answered streaming and not, as did the legacy
`/v1/completions`, Anthropic `/v1/messages` with `count_tokens`, and a
tool-call round trip; unloading the entry killed the placeholder and the
next request health-checked and answered again. Two console accounts
were tried against it — the member was refused the model editor and its
API key worked on `/v1`, while an administrator's key got 403 on `/api`.
The Models page was refreshed for two minutes and the Mac saw nothing.
On the ComfyUI question this was not a GPU machine and ComfyUI was not
running, so the eviction guard is tested by unit tests only there.

## What works and what does not

- Works: the console's `/v1/chat/completions` and `/v1/messages`, the
chat panel, API keys, the model id appearing in `/v1/models`.
- Not managed: the console never installs, sizes, benchmarks, quantises
or GPU-places it. It is grouped under its own 遠端模型 engine rather
than mistaken for llama.cpp, and the load/unload buttons act on the
placeholder and the forwarding side only, never on the other machine.
- No credential: a model entry cannot send an `Authorization` header.
Serve the remote endpoint on a network you trust (LAN, Tailscale), or
bring your own tunnel. llama-swap's `peers` can reach a machine behind
NAT over a tailcat:// key; that is llama-swap's own feature, not the
console's.
- One llama-swap quirk to know: because the placeholder "loads" instantly
and never dies on its own, the Models page shows the entry as loaded
once anything has referenced it until llama-swap is told to unload it.
- Bench works -- over the network. A run against one of these drives the
same /v1 path every client uses, so it times the whole way: the other
machine's speed plus the link between. It does not touch the other
machine's GPU directly, and it still takes its usual turn of pausing
/v1 and unloading the models sharing the llama-swap.

## Why this is not "an engine", and how it joins the model list anyway

`internal/providers/engines/README.md` explains the engine record: an
image, a launcher, cards. A server on another machine has none of those
to manage, which is why it is a kind of model and not a row on the
Engines page -- but it is not filed under llama.cpp either: the Models
page gives it its own group, 遠端模型, so the list says where the
weights are rather than implying they are here.

The Models page can add and edit these itself: 新增模型 → 模型來源 →
遠端服務器 asks for the server's URL and the name the server is sent,
and writes the placeholder, proxy, `useModelName` and health check as
above; editing such an entry reads the same fields back. The
hand-written form remains the way to reach what the form does not ask
for -- aliases, a custom `checkEndpoint`, timeouts -- and the MLX
section of `docs/adding-a-gpu-vendor.md` points here because until
that port exists, this is how a server on another platform joins the
machine.
10 changes: 10 additions & 0 deletions internal/api/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ type ModelSpec struct {
// card it pre-allocates.
Quantization string `json:"quantization"`
GpuMemoryUtilization float64 `json:"gpu_memory_utilization"`
// Endpoint makes the entry a server on another machine (docs/remote-
// models.md): the URL /v1 requests go to. UpstreamName is the model
// name that server is sent, which the ones that check it (vLLM, SGLang,
// Yunshu's single-model mode) otherwise refuse the entry's id against.
Endpoint string `json:"endpoint"`
UpstreamName string `json:"upstream_name"`
}

// ModelSpecOut is a configured entry parsed back into the editor's fields.
Expand All @@ -48,6 +54,10 @@ type ModelSpecOut struct {
Group *string `json:"group"`
Sampling map[string]any `json:"sampling"`
Extra string `json:"extra"`
// Endpoint and UpstreamName are set for a remote entry (the Provider is
// then "remote"): the server's URL and the name it is sent.
Endpoint string `json:"endpoint"`
UpstreamName string `json:"upstream_name"`
}

type ModelFile struct {
Expand Down
7 changes: 7 additions & 0 deletions internal/httpapi/comfy.go
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,13 @@ func (s *Server) makeRoom(ctx gocontext.Context, modelID string) (int, string) {
// An aliased name is a different string for a model that may already be
// loaded; resolved so every Codex request does not look like a cold load.
modelID = s.Config.CanonicalModel(modelID)
// An entry that names a server on another machine (docs/remote-models.md)
// is nobody's load on this one: without this a request to it would free
// -- or wait on -- every ComfyUI on the machine for a model that needs
// no card at all.
if s.Config.RemoteProxy(modelID) != "" {
return 0, ""
}
for _, entry := range s.LlamaSwap.Running(ctx) {
if m, _ := entry["model"].(string); m == modelID {
return 0, ""
Expand Down
22 changes: 22 additions & 0 deletions internal/httpapi/comfy_room_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ import (
"github.com/NoobBandi/TenkStack/internal/store/storetest"
)

// A model served by another machine (docs/remote-models.md) needs no card
// here, so the guard in makeRoom returns before anything that could free
// or wait on ComfyUI: with no probe wired up at all, asking for room for
// a remote model answering cleanly is the point of this test, since the
// unguarded path reaches the nil probe.
func TestMakeRoomSkipsRemote(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yaml")
os.WriteFile(path, []byte(`models:
mac:
cmd: sleep 3600
proxy: http://192.168.1.30:8000
aliases:
- mac-alias
`), 0o644)
s := &Server{Config: llamaswap.NewStore(path)}
for _, id := range []string{"mac", "mac-alias"} {
if status, detail := s.makeRoom(context.Background(), id); status != 0 || detail != "" {
t.Errorf("makeRoom(%s): %d %s", id, status, detail)
}
}
}

// busyB70s is the two cards as they were on 2026-10-10 20:13: card 1 with
// 9.4 GiB of idle ComfyUI on it.
type busyB70s struct{ twoB70s }
Expand Down
33 changes: 27 additions & 6 deletions internal/httpapi/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"net/http"
"net/url"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -41,8 +42,9 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) {
for id, entry := range byID {
proxy, _ := entry["proxy"].(string)
// /props and /slots are llama-server's; another provider answers
// 404 twice a poll, which is noise in its log for nothing.
if proxy == "" || formOf(providerOf[id]) != providers.FormLlama {
// 404 twice a poll, which is noise in its log for nothing. So does
// a server on another machine, which is not llama-server either.
if proxy == "" || s.Config.RemoteProxy(id) != "" || formOf(providerOf[id]) != providers.FormLlama {
continue
}
wg.Add(1)
Expand Down Expand Up @@ -118,6 +120,14 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) {
if p := providers.Get(providerOf[id]); p != nil && p.Tools {
caps.Tools = true
}
// The servers people host elsewhere -- vLLM, SGLang, llama.cpp, an
// engine like Yunshu -- all carry tools once started with them, and
// the console cannot ask a server it does not start. Assuming true
// keeps the chat panel's switch available; a remote without tools
// answers with the error, which the panel already shows.
if providerOf[id] == llamaswap.RemoteKey {
caps.Tools = true
}
if live != nil {
caps.Source = "live"
caps.Vision, _ = modalities["vision"].(bool)
Expand All @@ -133,13 +143,18 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) {
row["capabilities"] = caps
// Which inference engine starts the entry, so the list can be
// grouped by it; an entry named by hand is llama.cpp.
// A server on another machine answers for its own engine, not for
// llama.cpp's; grouping it under llama.cpp would be a lie the Models
// page tells about where the weights are.
key := providerOf[id]
if key == "" {
key = providers.DefaultProvider().Key
}
row["provider"] = key
if p := providers.Get(key); p != nil {
row["provider_name"] = p.Name
} else if key == llamaswap.RemoteKey {
row["provider_name"] = "遠端模型"
}
out = append(out, row)
}
Expand Down Expand Up @@ -231,15 +246,21 @@ func (s *Server) createModel(w http.ResponseWriter, r *http.Request) {
return
}
spec := api.ModelSpec{CtxSize: 16384, NGpuLayers: 99, TTL: 900, Group: strp("large")}
if _, has := raw["model_file"]; !has {
fail(w, http.StatusUnprocessableEntity, "model_file is required")
return
}
body, _ := json.Marshal(raw)
if err := json.Unmarshal(body, &spec); err != nil || spec.ID == "" {
fail(w, http.StatusUnprocessableEntity, "id is required")
return
}
if spec.Endpoint != "" {
u, err := url.Parse(spec.Endpoint)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
fail(w, http.StatusUnprocessableEntity, "endpoint 必須是完整的 http(s) URL")
return
}
} else if spec.ModelFile == "" {
fail(w, http.StatusUnprocessableEntity, "model_file is required")
return
}
chosen, present := chosenDevices(spec.Device)
env := s.deviceEnv(r, chosen)
var managed map[string]bool
Expand Down
55 changes: 55 additions & 0 deletions internal/llamaswap/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,39 @@ func (s *Store) Upsert(ctx context.Context, spec api.ModelSpec, env map[string]s
}
entry.Set("name", Str(name))
entry.Set("description", Str(spec.Description))
// Was this the remote form before the write? Only then are its keys
// the console's to remove when an entry moves back to a local
// server; a hand-written proxy for a fixed local port stays alone,
// being somebody else's arrangement.
wasRemote := remoteProxyURL(entry) != ""
// Remote: the console writing the form docs/remote-models.md
// describes. Nothing here concerns a card or a container: the
// placeholder is what llama-swap starts, health-checks and kills;
// proxy is where requests go; useModelName is the name a server that
// checks its model field (vLLM, SGLang, Yunshu) expects, the entry's
// id otherwise.
if spec.Endpoint != "" {
entry.Set("cmd", Literal("# served elsewhere; this only anchors llama-swap's lifecycle\n"+RemoteCmd+"\n"))
entry.Set("proxy", Str(spec.Endpoint))
up := spec.UpstreamName
if up == "" {
up = spec.ID
}
entry.Set("useModelName", Str(up))
entry.Set("checkEndpoint", Str("/health"))
entry.Set("ttl", Int(0))
entry.Delete("cmdStop")
entry.Delete("env")
// No group: a server elsewhere occupies no card here, and group
// membership is what the eviction policy reads.
syncGroupMembership(c, spec.ID, nil)
return nil
}
if wasRemote {
entry.Delete("proxy")
entry.Delete("useModelName")
entry.Delete("checkEndpoint")
}
if wrapper == "" {
wrapper = WrapperIn(Scalar(entry.Get("cmd")))
}
Expand Down Expand Up @@ -539,6 +572,13 @@ func (m *Models) ProviderKeys() map[string]string {
}
for _, e := range entries {
p, _, _ := ProviderOf(e.cmd)
if remoteProxyURL(e.spec) != "" {
// Read as remote by the same rule RemoteProxy applies, so the
// Models page groups it where makeRoom and readModels already
// treat it.
out[e.id] = RemoteKey
continue
}
out[e.id] = p.Key
}
return out
Expand Down Expand Up @@ -1053,6 +1093,21 @@ func (m *Models) ReadSpec(modelID string) *api.ModelSpecOut {
if e == nil || e.spec == nil {
return nil
}
if proxy := remoteProxyURL(e.spec); proxy != "" {
out := &api.ModelSpecOut{
ID: modelID, Provider: RemoteKey, Endpoint: proxy,
UpstreamName: Scalar(e.spec.Get("useModelName")),
Name: Scalar(e.spec.Get("name")),
Description: Scalar(e.spec.Get("description")),
}
if out.Name == "" {
out.Name = modelID
}
if ttl := e.spec.Get("ttl"); ttl != nil && ttl.Kind == yaml.ScalarNode {
out.TTL, _ = strconv.Atoi(ttl.Value)
}
return out
}
p, _, _ := ProviderOf(e.cmd)
patterns, owns := argPatterns, managed
if p.Form == providers.FormServer {
Expand Down
Loading