Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

setup: bring an engine already here up to date with make before using it; coli logs says where a foreground server prints (#1852)

JustVugg3ece386880ed
diff --git a/README.it.md b/README.it.md
index fec4ada5..d4d08cad 100644
--- a/README.it.md
+++ b/README.it.md
@@ -129,7 +129,8 @@ Cosa fa ogni passo, nel dettaglio: [docs/quickstart.md](docs/quickstart.md#the-o
| `the ... build failed`, per esempio `Unsupported gpu architecture` quando il CUDA toolkit installato non supporta più la scheda | l'installazione controlla prima il toolkit rispetto alla scheda e sceglie Vulkan da sé, spiegando perché; se una compilazione fallisce ancora, offre la prossima (Vulkan, poi la CPU). `./start-here.sh --backend vulkan` forza Vulkan; `--no-gpu` resta sulla CPU |
| `needs N GB free for the download` | `--dir` con una cartella su un disco più grande |
| su WSL, la cartella del modello è sotto `/mnt/c` | tienila sul disco Linux (il predefinito, `~/colibri-models`): `/mnt/c` è molte volte più lento |
-| qualsiasi altra cosa | `c/coli logs -n 50` mostra il log del server e `c/coli logs --install` quello dell'installazione; apri una [issue](https://github.com/JustVugg/colibri/issues) con le ultime righe stampate dall'installazione |
+| hai aggiornato il checkout (`git pull`) | rilancia `./start-here.sh`: ricompila il motore se i sorgenti sono cambiati, poi lo avvia |
+| qualsiasi altra cosa | `c/coli logs -n 50` mostra il log del server avviato in background (quello avviato in primo piano scrive nel suo terminale) e `c/coli logs --install` quello dell'installazione; apri una [issue](https://github.com/JustVugg/colibri/issues) con le ultime righe stampate dall'installazione |
### Lascia che sia il tuo assistente AI a installarlo
diff --git a/README.ja.md b/README.ja.md
index 997f419f..d6b607b8 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -97,7 +97,8 @@ Starting colibri
| `the ... build failed`。たとえば、インストールされている CUDA ツールキットがそのカードをもうサポートしていないときの `Unsupported gpu architecture` | セットアップはまずツールキットをカードと照らし合わせてチェックし、自分で Vulkan を選びます(理由も表示します)。それでもビルドが失敗する場合は次の選択肢(Vulkan、その次に CPU)を提示します。`./start-here.sh --backend vulkan` は Vulkan を強制します。`--no-gpu` なら CPU のままです |
| `needs N GB free for the download` | `--dir` で、より大きなディスク上のフォルダーを指定する |
| WSL で、モデルのフォルダーが `/mnt/c` の下にある | Linux 側のディスク(デフォルトの `~/colibri-models`)に置く:`/mnt/c` は何倍も遅くなります |
-| それ以外 | `c/coli logs -n 50` でサーバーのログを、`c/coli logs --install` でセットアップのログを表示できます。セットアップが最後に表示した数行を添えて [issue](https://github.com/JustVugg/colibri/issues) を作成してください |
+| チェックアウトを更新した(`git pull`) | `./start-here.sh` をもう一度実行してください。ソースが変わっていればエンジンを再ビルドしてから起動します |
+| それ以外 | `c/coli logs -n 50` でバックグラウンドで起動したサーバーのログを(フォアグラウンドで起動したサーバーは自分のターミナルに出力します)、`c/coli logs --install` でセットアップのログを表示できます。セットアップが最後に表示した数行を添えて [issue](https://github.com/JustVugg/colibri/issues) を作成してください |
### AI アシスタントにセットアップしてもらう
diff --git a/README.md b/README.md
index e0040f92..6fc0f46f 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,8 @@ What each step does, in detail: [docs/quickstart.md](docs/quickstart.md#the-one-
| `the ... build failed`, for example `Unsupported gpu architecture` when the installed CUDA toolkit no longer supports the card | the setup checks the toolkit against the card first and picks Vulkan by itself, saying why; if a build still fails it offers the next one (Vulkan, then the CPU). `./start-here.sh --backend vulkan` forces Vulkan; `--no-gpu` stays on the CPU |
| `needs N GB free for the download` | `--dir` with a folder on a bigger disk |
| on WSL, the model folder is under `/mnt/c` | keep it on the Linux disk (the default, `~/colibri-models`): `/mnt/c` is many times slower |
-| anything else | `c/coli logs -n 50` shows the server log and `c/coli logs --install` the setup's; open an [issue](https://github.com/JustVugg/colibri/issues) with the last lines the setup printed |
+| you updated the checkout (`git pull`) | run `./start-here.sh` again: it rebuilds the engine when the sources changed, then starts it |
+| anything else | `c/coli logs -n 50` shows the log of a server started in the background (one started in the foreground prints to its own terminal) and `c/coli logs --install` the setup's; open an [issue](https://github.com/JustVugg/colibri/issues) with the last lines the setup printed |
### Let your AI assistant set it up
diff --git a/README.zh-CN.md b/README.zh-CN.md
index c5bf00a4..c7b7968c 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -97,7 +97,8 @@ Starting colibri
| `the ... build failed`,例如已安装的 CUDA toolkit 不再支持这张显卡时出现的 `Unsupported gpu architecture` | 安装程序会先把 toolkit 和显卡对照检查,自行选择 Vulkan,并说明原因;如果编译仍然失败,它会提供下一个选项(先 Vulkan,再 CPU)。`./start-here.sh --backend vulkan` 强制使用 Vulkan;`--no-gpu` 则只使用 CPU |
| `needs N GB free for the download` | 用 `--dir` 指定一个更大磁盘上的文件夹 |
| 在 WSL 中,模型文件夹位于 `/mnt/c` 下 | 把它放在 Linux 磁盘上(即默认的 `~/colibri-models`):`/mnt/c` 要慢很多倍 |
-| 其他情况 | `c/coli logs -n 50` 显示服务器日志,`c/coli logs --install` 显示安装程序的日志;提交一个 [issue](https://github.com/JustVugg/colibri/issues),附上安装程序最后打印的几行 |
+| 更新了代码(`git pull`) | 重新运行 `./start-here.sh`:如果源代码有变化,它会先重新编译引擎,再启动 |
+| 其他情况 | `c/coli logs -n 50` 显示后台启动的服务器的日志(前台启动的服务器输出在它自己的终端里),`c/coli logs --install` 显示安装程序的日志;提交一个 [issue](https://github.com/JustVugg/colibri/issues),附上安装程序最后打印的几行 |
### 让 AI 助手帮你安装
diff --git a/README.zh-TW.md b/README.zh-TW.md
index ad44f532..60cfe15b 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -123,7 +123,8 @@ Starting colibri
| `the ... build failed`,例如已安裝的 CUDA toolkit 不再支援這張顯示卡時出現的 `Unsupported gpu architecture` | 安裝程式會先把 toolkit 和顯示卡對照檢查,自行選擇 Vulkan,並說明原因;如果建置仍然失敗,它會提供下一個選項(先 Vulkan,再 CPU)。`./start-here.sh --backend vulkan` 會強制使用 Vulkan;`--no-gpu` 則留在 CPU 上 |
| `needs N GB free for the download` | 用 `--dir` 指定一個位於較大硬碟上的資料夾 |
| 在 WSL 上,模型資料夾位於 `/mnt/c` 底下 | 把它放在 Linux 磁碟上(預設的 `~/colibri-models`):`/mnt/c` 慢上好幾倍 |
-| 其他任何問題 | `c/coli logs -n 50` 會顯示伺服器日誌,`c/coli logs --install` 則顯示安裝程式的日誌;請附上安裝程式最後印出的幾行,開一個 [issue](https://github.com/JustVugg/colibri/issues) |
+| 更新了程式碼(`git pull`) | 重新執行 `./start-here.sh`:如果原始碼有變動,它會先重新編譯引擎,再啟動 |
+| 其他任何問題 | `c/coli logs -n 50` 會顯示在背景啟動的伺服器日誌(在前景啟動的伺服器會輸出到它自己的終端機),`c/coli logs --install` 則顯示安裝程式的日誌;請附上安裝程式最後印出的幾行,開一個 [issue](https://github.com/JustVugg/colibri/issues) |
### 讓你的 AI 助手幫你安裝
diff --git a/c/setup_flow.py b/c/setup_flow.py
index 08d4c3d9..67943c89 100644
--- a/c/setup_flow.py
+++ b/c/setup_flow.py
@@ -639,11 +639,17 @@ def build_log_name(backend):
return f"build-{backend}"
-def build_engine(family, backend, tc, out=print, make_args=()):
+def build_engine(family, backend, tc, out=print, make_args=(), update=False):
+ """make the engine; `update` for one already here (refresh_engine), where make
+ redoes only what changed since it was built."""
cmd, cwd, env = make_command(family, backend, tc, make_args)
shown = [a for a in cmd if a == family.build_target or re.match(r"^[A-Z_]+=", a)]
log_file = log_path(build_log_name(backend))
- out(f" building: make {' '.join(shown)} (a few minutes; log: {log_file})")
+ if update:
+ out(f" updating: make {' '.join(shown)} (only what changed since the last build; "
+ f"log: {log_file})")
+ else:
+ out(f" building: make {' '.join(shown)} (a few minutes; log: {log_file})")
write_state("build", engine=family.engine_artifact, backend=backend)
with open(_ensure_log(build_log_name(backend)), "w", encoding="utf-8", errors="replace") as log:
process = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE,
@@ -848,8 +854,10 @@ def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):
if os.path.exists(local):
have = binary_backend(local)
if decision["backend"] == "cpu" or have == decision["backend"]:
+ make_args = decision.get("make_args", ()) if have == decision["backend"] else ()
+ source = refresh_engine(family, have, tc, local, out=out, make_args=make_args)
return {"launcher_dir": HERE, "engine": local, "backend": decision["backend"],
- "source": "present"}
+ "source": source}
if not tc.get("can_build"):
out(f" the {family.engine_artifact} engine here is a {have} build; "
f"keeping it, since nothing here can rebuild it")
@@ -880,6 +888,61 @@ def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):
return {"launcher_dir": runtime, "engine": engine, "backend": "cpu", "source": f"release {tag}"}
+# What the toolchain needs to build each kind of engine (toolchain()).
+CAN_BUILD = {"cpu": "can_build", "vulkan": "can_build_vulkan", "cuda": "can_build_cuda"}
+
+
+def refresh_engine(family, backend, tc, path, out=print, make_args=()):
+ """An engine already here, brought up to date with the sources before it is
+ used: make redoes what changed since it was built, and nothing when nothing
+ did (about 0.02 s). Without this a checkout updated with `git pull` kept its
+ old engine, since one with the right backend was found and used as it was,
+ and the new code never ran (#1852). It is rebuilt as the kind it is (`backend`,
+ from binary_backend), so a Vulkan engine used for the CPU stays a Vulkan one.
+ With no toolchain for that kind, or when the rebuild fails, the engine that
+ was here stays, the failure with a line. Returns "present" or "rebuilt"."""
+ if not tc.get(CAN_BUILD.get(backend, "can_build")):
+ return "present"
+ before = os.stat(path).st_mtime_ns
+ try:
+ build_engine(family, backend, tc, out=out, make_args=make_args, update=True)
+ except BuildError as error:
+ if not os.path.exists(path):
+ raise
+ out(f" could not update it (log: {error.log}); "
+ f"keeping the {family.engine_artifact} engine that was here")
+ return "present"
+ if os.stat(path).st_mtime_ns == before:
+ out(" up to date")
+ return "present"
+ out(" rebuilt: the sources changed since the last build")
+ return "rebuilt"
+
+
+def refresh_configured(cfg, out=print, tc=None):
+ """The configured engine, brought up to date before a start (refresh_engine).
+ A rerun of the setup, or `coli start`, used to start the engine as it was, so
+ after a `git pull` the old code kept running (#1852). Only an engine built in
+ this checkout: a prebuilt one from a release archive has no sources here. Not
+ while a server runs: it keeps the engine it started with. Returns
+ refresh_engine's answer, or None when there was nothing to check."""
+ try:
+ family = family_by_id(cfg.get("family"))
+ except Exception:
+ return None
+ engine = cfg.get("engine") or ""
+ if (not os.path.isfile(engine)
+ or os.path.abspath(engine) != os.path.abspath(engine_path(HERE, family))):
+ return None
+ if server_status(cfg)["state"] != "stopped":
+ return None
+ tc = tc or toolchain()
+ have = binary_backend(engine)
+ # The CUDA variables the setup built it with: they come from the cards it kept.
+ make_args = cuda_make_args(family, tc, cfg.get("nvidia") or []) if have == "cuda" else ()
+ return refresh_engine(family, have, tc, engine, out=out, make_args=make_args)
+
+
def resolve_with_fallback(ui, family, entry, decision, tc, hw, requested, failed=()):
"""resolve_engine, and when a build fails the next backend that can work
instead of a stop: CUDA, then Vulkan, then the CPU (choose_backend again,
@@ -1140,6 +1203,7 @@ def start_server(cfg, *, background=False, open_browser=True, out=print, wait=5.
out(" stop: press Ctrl+C here (or close this window)\n")
sys.stdout.flush() # ours before the server's, when the output is a file
process = subprocess.Popen(cmd, env=env)
+ note_foreground_start(process.pid, cmd)
try:
return process.wait()
except KeyboardInterrupt:
@@ -1182,6 +1246,21 @@ def start_server(cfg, *, background=False, open_browser=True, out=print, wait=5.
return status
+def note_foreground_start(pid, cmd):
+ """A server in the foreground prints to its terminal, not to serve.log; say so
+ in the log, so that `coli logs` (often run from another terminal) points there
+ instead of showing an older background run's lines as if they were this one's
+ (#1852). Best effort: a log that cannot be written changes nothing else."""
+ try:
+ with open(_ensure_log("serve"), "a", encoding="utf-8", errors="replace") as handle:
+ handle.write(f"\n--- start {time.strftime('%Y-%m-%d %H:%M:%S')} in the foreground "
+ f"(pid {pid}): {' '.join(cmd)}\n"
+ f"--- its output goes to the terminal that started it, not to this log; "
+ f"`coli start --background` writes it here\n")
+ except OSError:
+ pass
+
+
def spawn_detached(cmd, **kwargs):
"""Start a process that outlives this call, and reap it when it exits.
@@ -1553,6 +1632,7 @@ def cmd_setup(a, ui=None):
ui.say("The GPU packages are installed now: rebuilding the engine for the GPU.\n")
else:
ui.say(f"Already set up: {describe_existing(cfg)}")
+ refresh_configured(cfg, out=ui.say)
return _finish(ui, cfg, a)
# A setup that stopped half way (pending), or a finished one whose engine or
# files went missing (ready, but not runnable): continue with the same choice.
@@ -1712,6 +1792,7 @@ def cmd_start(a):
cfg = load_config()
if not cfg or not config_ready(cfg):
raise SetupError("nothing is set up yet (or the setup did not finish): run `coli setup`")
+ refresh_configured(cfg, out=(lambda *_: None) if getattr(a, "json", False) else print)
if getattr(a, "json", False):
print(json.dumps(start_server(cfg, background=True, open_browser=not a.no_browser,
out=lambda *_: None), indent=2))
@@ -1788,6 +1869,17 @@ def cmd_logs(a):
text = tail_file(path, a.lines)
if not text:
print(f"no {name} log yet ({path})")
+ cfg = load_config() if name == "serve" else None
+ try:
+ status = server_status(cfg) if cfg and cfg.get("port") else None
+ except (OSError, ValueError, KeyError):
+ status = None
+ if status and status["state"] != "stopped":
+ # Started some other way (`coli serve` in a terminal): its output is there.
+ print(f"colibri is running ({status['state']}"
+ + (f", pid {status['pid']}" if status.get("pid") else "")
+ + "), started in the foreground: its output is in the terminal that "
+ "started it; `coli start --background` writes it to this log instead")
return 1
print(text)
return 0
diff --git a/c/tests/test_setup_flow.py b/c/tests/test_setup_flow.py
index 5baa29b6..eb9bdef4 100644
--- a/c/tests/test_setup_flow.py
+++ b/c/tests/test_setup_flow.py
@@ -581,20 +581,76 @@ class EngineResolution(HomeTestCase):
path.write_bytes(b"\x7fELF" + content)
self.assertEqual(setup_flow.binary_backend(str(path)), expected)
- def test_present_engine_with_the_right_backend_is_not_rebuilt(self):
- for os_name, loader in (("linux", b"libvulkan.so.1"), ("win32", b"vulkan-1.dll")):
- with self.subTest(os=os_name), modeled(os_name), \
- tempfile.TemporaryDirectory() as engines:
- Path(engines, engine_name(os_name)).write_bytes(loader)
- decision = {"backend": "vulkan", "missing": []}
- with mock.patch.object(setup_flow, "HERE", engines), \
- mock.patch.object(setup_flow, "build_engine") as build:
- info = setup_flow.resolve_engine(family_by_id("qwen36"), None, decision, TC_ALL,
- out=lambda *_: None)
- build.assert_not_called()
- self.assertEqual(info["source"], "present")
+ def resolve_present(self, os_name, make, tc=TC_ALL, content=b"libvulkan.so.1"):
+ """resolve_engine with an engine already here and `make` standing in for
+ build_engine; returns (info, the build mock, what it said)."""
+ said = []
+ with modeled(os_name), tempfile.TemporaryDirectory() as engines:
+ path = Path(engines, engine_name(os_name))
+ path.write_bytes(content)
+ os.utime(path, ns=(1_000_000_000, 1_000_000_000))
+ with mock.patch.object(setup_flow, "HERE", engines), \
+ mock.patch.object(setup_flow, "build_engine",
+ side_effect=lambda *a, **k: make(path, *a, **k)) as build:
+ info = setup_flow.resolve_engine(family_by_id("qwen36"), None,
+ {"backend": "vulkan", "missing": []}, tc,
+ out=said.append)
+ return info, build, "\n".join(said)
+
+ def test_present_engine_is_brought_up_to_date_with_make(self):
+ # #1852: an engine with the right backend used to be taken as it was, so after
+ # a `git pull` the old engine kept running. make now redoes what changed.
+ for os_name in ("linux", "win32"):
+ with self.subTest(os=os_name):
+ info, build, said = self.resolve_present(os_name, lambda path, *a, **k: str(path))
+ build.assert_called_once()
+ self.assertEqual(build.call_args.args[1], "vulkan")
+ self.assertTrue(build.call_args.kwargs["update"])
+ self.assertEqual(info["source"], "present") # make had nothing to do
+ self.assertIn("up to date", said)
self.assertEqual(os.path.basename(info["engine"]), engine_name(os_name))
+ def test_changed_sources_rebuild_the_present_engine(self):
+ def make(path, *a, **k):
+ path.write_bytes(b"libvulkan.so.1 newer")
+ return str(path)
+ info, build, said = self.resolve_present("linux", make)
+ self.assertEqual(info["source"], "rebuilt")
+ self.assertIn("rebuilt: the sources changed since the last build", said)
+
+ def test_a_failed_update_keeps_the_engine_that_was_here(self):
+ def make(path, family, backend, tc, out=print, make_args=(), update=False):
+ raise setup_flow.BuildError("the qwen36 VULKAN build failed", backend, "/logs/build.log")
+ info, build, said = self.resolve_present("linux", make)
+ self.assertEqual(info["source"], "present")
+ self.assertEqual(info["backend"], "vulkan")
+ self.assertIn("could not update it (log: /logs/build.log); keeping the qwen36 engine", said)
+
+ def test_a_failed_update_that_removed_the_engine_is_a_failed_build(self):
+ def make(path, family, backend, tc, out=print, make_args=(), update=False):
+ path.unlink()
+ raise setup_flow.BuildError("the qwen36 VULKAN build failed", backend, "/logs/build.log")
+ with self.assertRaises(setup_flow.BuildError):
+ self.resolve_present("linux", make)
+
+ def test_no_toolchain_for_the_engine_kind_keeps_it_as_it_is(self):
+ no_vulkan = dict(TC_ALL, vulkan_headers=False, glslc=None, can_build_vulkan=False)
+ info, build, said = self.resolve_present("linux", lambda path, *a, **k: str(path), tc=no_vulkan)
+ build.assert_not_called()
+ self.assertEqual(info["source"], "present")
+
+ def test_a_gpu_engine_used_for_the_cpu_is_updated_as_the_gpu_build_it_is(self):
+ said = []
+ with modeled("linux"), tempfile.TemporaryDirectory() as engines:
+ Path(engines, "qwen36").write_bytes(b"libvulkan.so.1")
+ with mock.patch.object(setup_flow, "HERE", engines), \
+ mock.patch.object(setup_flow, "build_engine") as build:
+ info = setup_flow.resolve_engine(family_by_id("qwen36"), None,
+ {"backend": "cpu", "missing": []}, TC_ALL,
+ out=said.append)
+ self.assertEqual(build.call_args.args[1], "vulkan") # not rebuilt as a CPU engine
+ self.assertEqual(info["backend"], "cpu")
+
def test_an_engine_without_the_exe_suffix_is_not_the_windows_engine(self):
Path(self.tmp.name, "qwen36").write_bytes(b"vulkan-1.dll")
with modeled("win32"), mock.patch.object(setup_flow, "HERE", self.tmp.name), \
@@ -801,7 +857,14 @@ class WholeSetup(HomeTestCase):
mock.patch.object(setup_flow, "toolchain", return_value=TC_ALL),
mock.patch.object(setup_flow, "plan_summary",
return_value=("dense part 0.0 GB in RAM", [])),
- mock.patch.object(setup_download.time, "sleep")):
+ mock.patch.object(setup_download.time, "sleep"),
+ # No colibri runs (whatever this machine has on port 8000), so a
+ # rerun checks its engine; make has nothing to do, the engine here
+ # stays as it is. A test that builds patches build_engine again inside.
+ mock.patch.object(setup_flow, "server_status",
+ return_value={"state": "stopped", "pid": None}),
+ mock.patch.object(setup_flow, "build_engine",
+ side_effect=lambda family, *a, **k: os.path.join(self.engines, "qwen36"))):
patcher.start()
self.addCleanup(patcher.stop)
@@ -835,7 +898,26 @@ class WholeSetup(HomeTestCase):
self.assertEqual(code, 0, text)
self.assertIn("Already set up: Tiny test model", text)
self.assertEqual(len(self.hub.requests), before)
- build.assert_not_called()
+ build.assert_called_once() # make, with nothing to redo
+ self.assertTrue(build.call_args.kwargs["update"])
+
+ def test_a_rerun_after_a_pull_rebuilds_the_engine_it_starts(self):
+ code, text = self.run_setup(pick="tiny")
+ self.assertEqual(code, 0, text)
+ engine = Path(self.engines, "qwen36")
+ os.utime(engine, ns=(1_000_000_000, 1_000_000_000))
+
+ def make(family, backend, tc, out=print, make_args=(), update=False):
+ self.assertEqual((backend, update), ("vulkan", True))
+ engine.write_bytes(b"\x7fELF libvulkan.so.1 with the pulled sources")
+ return str(engine)
+
+ with mock.patch.object(setup_flow, "build_engine", side_effect=make):
+ code, text = self.run_setup()
+ self.assertEqual(code, 0, text)
+ self.assertIn("Already set up: Tiny test model", text)
+ self.assertIn("rebuilt: the sources changed since the last build", text)
+ self.assertIn(b"pulled sources", engine.read_bytes())
def test_interrupted_download_continues_on_rerun(self):
real = setup_download.download_repo
@@ -883,7 +965,7 @@ class WholeSetup(HomeTestCase):
os.remove(os.path.join(self.engines, "qwen36"))
shard_fetches = sum("/cdn/" in r["path"] for r in self.hub.requests)
- def rebuild(family, backend, tc, out=print, make_args=()):
+ def rebuild(family, backend, tc, out=print, make_args=(), update=False):
Path(self.engines, "qwen36").write_bytes(b"libvulkan.so.1")
return os.path.join(self.engines, "qwen36")
@@ -909,7 +991,7 @@ class WholeSetup(HomeTestCase):
code, text = self.run_setup()
self.assertIn("Already set up", text)
- def rebuild(family, backend, tc, out=print, make_args=()):
+ def rebuild(family, backend, tc, out=print, make_args=(), update=False):
self.assertEqual(backend, "vulkan")
Path(self.engines, "qwen36").write_bytes(b"libvulkan.so.1")
return os.path.join(self.engines, "qwen36")
@@ -924,11 +1006,15 @@ class WholeSetup(HomeTestCase):
def failing_build(self, *broken):
"""build_engine as a mock: the backends in `broken` fail the way make
- does (BuildError with their log), the others write a matching engine."""
+ does (BuildError with their log), the others write a matching engine.
+ `calls` lists the builds; updating an engine already here (refresh_engine)
+ is make with nothing to do, and not a build."""
loaders = {"cuda": b"libcudart.so.12", "vulkan": b"libvulkan.so.1", "cpu": b"plain"}
calls = []
- def build(family, backend, tc, out=print, make_args=()):
+ def build(family, backend, tc, out=print, make_args=(), update=False):
+ if update:
+ return os.path.join(self.engines, "qwen36")
calls.append(backend)
log = setup_flow.log_path(setup_flow.build_log_name(backend))
if backend in broken:
@@ -1223,6 +1309,96 @@ class ServerControl(HomeTestCase):
self.port = moved["port"] # cleanup stops this one
+class ForegroundLogs(HomeTestCase):
+ """#1852: the server the setup starts in the foreground prints to its terminal,
+ and `coli logs` (from another terminal) said only "no serve log yet"."""
+
+ def logs(self):
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out):
+ code = setup_flow.cmd_logs(argparse.Namespace(install=False, lines=100))
+ return code, out.getvalue()
+
+ def test_a_foreground_start_leaves_a_line_saying_where_its_output_is(self):
+ Path(setup_flow._ensure_log("serve")).write_text("an older background run's lines\n")
+ setup_flow.note_foreground_start(4242, ["python3", "coli", "web", "--port", "8000"])
+ code, text = self.logs()
+ self.assertEqual(code, 0)
+ last = text.strip().splitlines()[-2:]
+ self.assertIn("in the foreground (pid 4242): python3 coli web --port 8000", last[0])
+ self.assertIn("its output goes to the terminal that started it", last[1])
+ self.assertIn("`coli start --background` writes it here", last[1])
+
+ def test_no_log_but_a_running_server_says_where_to_look(self):
+ setup_flow.save_config({"status": "ready", "port": 8000, "host": "127.0.0.1"})
+ with mock.patch.object(setup_flow, "server_status",
+ return_value={"state": "ready", "pid": 18985}):
+ code, text = self.logs()
+ self.assertEqual(code, 1)
+ self.assertIn("no serve log yet", text)
+ self.assertIn("colibri is running (ready, pid 18985), started in the foreground: "
+ "its output is in the terminal that started it", text)
+
+ def test_no_log_and_nothing_running_says_only_that(self):
+ setup_flow.save_config({"status": "ready", "port": 8000, "host": "127.0.0.1"})
+ with mock.patch.object(setup_flow, "server_status", return_value={"state": "stopped", "pid": None}):
+ code, text = self.logs()
+ self.assertEqual(code, 1)
+ self.assertEqual(text.strip().splitlines()[-1].startswith("no serve log yet"), True)
+ self.assertNotIn("running", text)
+
+
+class ConfiguredRefresh(HomeTestCase):
+ """refresh_configured: the engine a ready setup starts, checked against the sources."""
+
+ def setUp(self):
+ super().setUp()
+ self.engines = os.path.join(self.tmp.name, "c")
+ os.makedirs(self.engines)
+ self.engine = Path(self.engines, "qwen36")
+ self.engine.write_bytes(b"\x7fELF libvulkan.so.1")
+ for patcher in (modeled("linux"), mock.patch.object(setup_flow, "HERE", self.engines)):
+ patcher.__enter__()
+ self.addCleanup(patcher.__exit__, None, None, None)
+ self.cfg = {"family": "qwen36", "engine": str(self.engine), "port": 8000, "host": "127.0.0.1"}
+
+ def refresh(self, state="stopped", cfg=None):
+ with mock.patch.object(setup_flow, "server_status", return_value={"state": state, "pid": None}), \
+ mock.patch.object(setup_flow, "build_engine", return_value=str(self.engine)) as build:
+ result = setup_flow.refresh_configured(cfg or self.cfg, out=lambda *_: None, tc=TC_ALL)
+ return result, build
+
+ def test_a_stopped_server_gets_its_engine_checked(self):
+ result, build = self.refresh()
+ self.assertEqual(result, "present")
+ self.assertEqual(build.call_args.args[1], "vulkan")
+
+ def test_a_running_server_keeps_the_engine_it_started_with(self):
+ for state in ("ready", "loading"):
+ result, build = self.refresh(state)
+ self.assertIsNone(result)
+ build.assert_not_called()
+
+ def test_a_prebuilt_engine_from_a_release_is_left_alone(self):
+ elsewhere = Path(self.tmp.name, "release", "qwen36")
+ elsewhere.parent.mkdir()
+ elsewhere.write_bytes(b"plain")
+ result, build = self.refresh(cfg=dict(self.cfg, engine=str(elsewhere)))
+ self.assertIsNone(result)
+ build.assert_not_called()
+
+ def test_a_cuda_engine_is_updated_with_the_variables_for_its_cards(self):
+ self.engine.write_bytes(b"\x7fELF libcudart.so.12")
+ cfg = dict(self.cfg, nvidia=[{"name": "Tesla V100-SXM2-16GB", "compute_cap": "7.0"}])
+ tc = dict(TC_ALL, cuda_version="11.8")
+ with mock.patch.object(setup_flow, "server_status", return_value={"state": "stopped", "pid": None}), \
+ mock.patch.object(setup_flow, "build_engine", return_value=str(self.engine)) as build:
+ setup_flow.refresh_configured(cfg, out=lambda *_: None, tc=tc)
+ self.assertEqual(build.call_args.args[1], "cuda")
+ self.assertEqual(build.call_args.kwargs["make_args"],
+ setup_flow.cuda_make_args(family_by_id("qwen36"), tc, cfg["nvidia"]))
+
+
class CommandLine(HomeTestCase):
def coli(self, *args):
return subprocess.run([sys.executable, str(C_DIR / "coli"), *args], capture_output=True,
diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md
index 25e0ccb6..72bbcf2b 100644
--- a/docs/AI_SETUP.md
+++ b/docs/AI_SETUP.md
@@ -243,7 +243,7 @@ next free port and the configuration is updated; read the URLs from
```bash
python3 c/coli status # human-readable; --json for the fields above
-python3 c/coli logs -n 50 # server log of a background start
+python3 c/coli logs -n 50 # server log of a background start (a foreground one prints to its terminal)
python3 c/coli logs --install # log of a detached install
python3 c/coli stop # stops the configured server and its engine
```
@@ -251,7 +251,9 @@ python3 c/coli stop # stops the configured server and its engine
`coli stop` without `--port` stops the server the setup configured. Rerunning
`python3 c/coli setup` later starts the configured server directly (in the
foreground; add `--background --no-browser` for a detached start), with no
-download and no build.
+download. Before it starts, `make` brings the engine up to date with the sources:
+nothing to do (a fraction of a second) unless they changed, as after a `git pull`,
+and then only what changed is rebuilt. `coli start` does the same.
## Files
diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md
index 9348447a..f482427f 100644
--- a/docs/SETTINGS.md
+++ b/docs/SETTINGS.md
@@ -29,7 +29,7 @@ Flags may also be given **after** the subcommand. Most flags map onto an engine
| `serve` | Start the OpenAI-compatible HTTP server. |
| `web` | `serve`, then open the dashboard in the browser. |
| `stop` | Shut down a running `coli serve` and its engine (default port: the one `coli setup` configured, else `8000`). |
-| `setup` | One step: detect the hardware, recommend a model, build or fetch the engine (Vulkan/CUDA when usable), download with resume, write the run configuration, start. A rerun starts directly. See [AI_SETUP.md](AI_SETUP.md). |
+| `setup` | One step: detect the hardware, recommend a model, build or fetch the engine (Vulkan/CUDA when usable), download with resume, write the run configuration, start. A rerun starts directly, once `make` has brought the engine up to date with the sources (a rebuild only when they changed, as after `git pull`). See [AI_SETUP.md](AI_SETUP.md). |
| `start` | Start what `coli setup` configured (`--background`, `--no-browser`, `--json`). |
| `status` | What is set up, install progress, server state, URLs, API model id, tok/s of the last answer (`--json`). |
| `logs` | Tail of the background server log (`-n N`, `--install` for the install log). |