Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Container: one image per model (build arg), automatic pack download, card defaults for 128 GB, persistent kernel cache, positive switches

YanissAmzd17eb9a88a1d
diff --git a/.dockerignore b/.dockerignore
index 68a7200..dfe932d 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -4,3 +4,4 @@ build
*.safetensors
*.st
__pycache__
+doc/container.md
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 7964d17..1675670 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -1,5 +1,7 @@
# Kyojin server image for AMD Strix Halo (gfx1151). Works with docker and podman.
-# docker build -f docker/Dockerfile -t kyojin .
+# docker build -f docker/Dockerfile -t kyojin-qwen . # default model: qwen
+# docker build -f docker/Dockerfile --build-arg MODEL=glm -t kyojin-glm . # same layers, other baked defaults
+# docker build -f docker/Dockerfile --build-arg MODEL=mimo -t kyojin-mimo .
# Follows the README Quickstart: ROCm torch + rocm-sdk-devel from AMD's gfx1151 index, requirements.txt,
# `rocm-sdk init`, tools/strix_halo/env.sh, build.sh. The models are NOT in the image: mount them.
@@ -29,10 +31,13 @@ RUN pip install --pre torch rocm-sdk-devel --index-url https://rocm.nightlies.am
&& rm -rf build .rebuild.* .sdk-deps /root/.cache \
&& cd "$EXL3_ROCM_SDK" && rm -rf clients share/rocprofiler-sdk share/hipblaslt share/rocdecode share/rocsparse bin/*gtest* bin/*-test bin/*-bench bin/*-gemm-tune bin/*test*
ENV EXL3_ROCM_SDK=/opt/kyojin/.venv/lib/python3.12/site-packages/_rocm_sdk_devel
-ENV MODEL_DIR=/models PORT=8000 HOME=/root
-EXPOSE 8000
+# Last on purpose: the only layer that differs between the qwen, glm and mimo images. Defaults per model live in
+# docker/kyojin_args.py (context, sampling, hub repository); MODEL only picks which set the image starts with.
+ARG MODEL=qwen
+ENV KYOJIN_MODEL=$MODEL MODEL_DIR=/models PORT=8731 HOME=/root
+EXPOSE 8731
VOLUME ["/models"]
HEALTHCHECK --start-period=900s --interval=30s --timeout=5s --retries=3 \
- CMD curl -sf "http://127.0.0.1:${PORT}/health" >/dev/null || exit 1
+ CMD curl -sf "http://127.0.0.1:${KYOJIN_PORT:-$PORT}/health" >/dev/null || exit 1
STOPSIGNAL SIGTERM
ENTRYPOINT ["/opt/kyojin/docker/entrypoint.sh"]
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index d905b9e..5a4b4cb 100755
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -1,8 +1,10 @@
#!/bin/bash
-# Container entrypoint: configuration comes from environment variables (see doc/container.md).
+# Container entrypoint. Every setting is an optional environment variable (see doc/container.md): the image knows
+# its model (KYOJIN_MODEL), its defaults for a 128 GB machine, and it downloads a missing pack into /models.
# Arguments given to `docker run IMAGE <args>` are appended to the server command line.
set -u
-cd /opt/kyojin
+ROOT=${KYOJIN_ROOT:-/opt/kyojin}
+cd "$ROOT"
source tools/strix_halo/env.sh >/dev/null
case "${1:-}" in
@@ -10,18 +12,48 @@ case "${1:-}" in
check) exec bash tools/strix_halo/env.sh --check ;;
esac
-mapfile -d '' ARGS < <(python docker/kyojin_args.py --null) || true
+# Kernel cache (compiled HIP kernels, tuning tables, Triton): ~/.cache is empty in a fresh container and the first
+# start then takes 4 more minutes. Keep it across runs: a volume mounted on ~/.cache wins, else a hidden folder in
+# the writable models mount, else the container's own (lost with it). KYOJIN_CACHE_DIR forces a folder.
+CACHE_HOME=${HOME:-/root}/.cache
+CACHE_DIR=${KYOJIN_CACHE_DIR:-}
+if [ -z "$CACHE_DIR" ] && ! mountpoint -q "$CACHE_HOME" 2>/dev/null; then
+ MODELS=${KYOJIN_MODEL_DIR:-${MODEL_DIR:-/models}}
+ [ -d "$MODELS" ] && [ -w "$MODELS" ] && CACHE_DIR=$MODELS/.kyojin-cache
+fi
+if [ -n "$CACHE_DIR" ] && [ "$CACHE_DIR" != "$CACHE_HOME" ]; then
+ if mkdir -p "$CACHE_DIR" 2>/dev/null && { [ -L "$CACHE_HOME" ] || rmdir "$CACHE_HOME" 2>/dev/null || [ ! -e "$CACHE_HOME" ]; } \
+ && ln -sfn "$CACHE_DIR" "$CACHE_HOME"; then
+ echo "[kyojin] kernel cache: $CACHE_DIR" >&2
+ else
+ echo "[kyojin] kernel cache: cannot use $CACHE_DIR, using $CACHE_HOME (lost when the container is removed)" >&2
+ fi
+else
+ echo "[kyojin] kernel cache: $CACHE_HOME" >&2
+fi
+export TRITON_CACHE_DIR=${TRITON_CACHE_DIR:-$CACHE_HOME/triton}
+
+# Children run in the background so that this shell (PID 1) can forward SIGTERM: a bare PID 1 ignores it and docker
+# would wait for SIGKILL. SIGTERM, not SIGINT: a background job of a non-interactive shell starts with SIGINT ignored,
+# so python never sees it (measured: docker stop took the full timeout, exit 137). The trap is set before the
+# configuration step because that step can be a download of tens of GB.
+CHILD=""
+stop() { echo "[kyojin] signal received, stopping" >&2; [ -n "$CHILD" ] && kill -TERM "$CHILD" 2>/dev/null; STOPPED=1; }
+STOPPED=0
+trap stop TERM INT
+wait_child() { while kill -0 "$CHILD" 2>/dev/null; do wait "$CHILD" 2>/dev/null; done; wait "$CHILD" 2>/dev/null; return $?; }
+
+ARGFILE=$(mktemp)
+python docker/kyojin_args.py --null >"$ARGFILE" &
+CHILD=$!
+wait_child; RC=$?
+if [ "$RC" -ne 0 ] || [ "$STOPPED" = 1 ]; then rm -f "$ARGFILE"; [ "$STOPPED" = 1 ] && exit 143; exit "$RC"; fi
+mapfile -d '' ARGS <"$ARGFILE"; rm -f "$ARGFILE"
[ "${#ARGS[@]}" -gt 0 ] || exit 2
echo "[kyojin] python ${ARGS[*]} $*" >&2
-# Run the server as a child so this shell (PID 1) can forward SIGTERM. A bare PID 1 ignores SIGTERM and docker
-# would wait for SIGKILL. Forward SIGTERM, not SIGINT: a background job of a non-interactive shell starts with SIGINT
-# ignored, so python never sees it (measured: docker stop took the full timeout and ended in exit 137).
python "${ARGS[@]}" "$@" &
-PID=$!
-stop() { echo "[kyojin] signal received, stopping server" >&2; kill -TERM "$PID" 2>/dev/null; }
-trap stop TERM INT
-while kill -0 "$PID" 2>/dev/null; do wait "$PID" 2>/dev/null; done
-wait "$PID" 2>/dev/null; RC=$?
+CHILD=$!
+wait_child; RC=$?
echo "[kyojin] server exited with code $RC" >&2
exit "$RC"
diff --git a/docker/kyojin_args.py b/docker/kyojin_args.py
index a3fac6d..3b37319 100644
--- a/docker/kyojin_args.py
+++ b/docker/kyojin_args.py
@@ -1,13 +1,19 @@
#!/usr/bin/env python3
-"""Map KYOJIN_* environment variables to the argument list of one Kyojin server.
+"""Turn the container environment into the command line of one Kyojin server.
-Used by docker/entrypoint.sh. Run it directly to see the command a configuration produces:
+Used by docker/entrypoint.sh. Every variable is optional: the image bakes the model it serves (KYOJIN_MODEL), and
+each model has defaults for a 128 GB machine (context, sampling of the model card, hub repository). The only mount a
+user needs is /models. If no pack is there, it is downloaded from the hub into /models.
- KYOJIN_MODEL=qwen MODEL_DIR=/models/pack python docker/kyojin_args.py
+Run it directly to see the command a configuration produces (it downloads a missing pack):
+
+ KYOJIN_MODEL=qwen MODEL_DIR=/models python docker/kyojin_args.py
"""
+import contextlib
import json
import os
import shlex
+import shutil
import sys
from pathlib import Path
@@ -15,6 +21,17 @@ SERVERS = {"qwen": "tools/qwen/serve.py", "glm": "tools/glm/serve.py", "mimo": "
# model_type values found in the config.json of the published packs
TYPE_HINTS = (("qwen", "qwen"), ("glm", "glm"), ("mimo", "mimo"))
+# Per-model defaults. Context: the value of the README / model card quickstart (-c 131072), which leaves about
+# 14 GiB (Qwen) and 10 GiB (GLM) free on a 128 GB machine. Sampling: the values of the model cards.
+PROFILES = {
+ "qwen": {"repo": "yamz-labs/Qwen3.8-Flash-Next-EXL3-Yamz", "CONTEXT": "131072", "DEFAULT_TEMPERATURE": "1.0",
+ "DEFAULT_TOP_P": "0.95", "DEFAULT_TOP_K": "20", "DEFAULT_MIN_P": "0.0"},
+ "glm": {"repo": "yamz-labs/GLM-5.3-Flash-EXL3-Yamz", "CONTEXT": "131072", "DEFAULT_TEMPERATURE": "1.0",
+ "DEFAULT_TOP_P": "0.95"},
+ "mimo": {"repo": "yamz-labs/MiMo-V2.6-Flash-MOPD-EXL3-Yamz", "CONTEXT": "131072", "DEFAULT_TEMPERATURE": "1.0",
+ "DEFAULT_TOP_P": "0.95"},
+}
+
# env name -> (flag, {family: flag override or None when the family has no such option}, is_switch)
OPTIONS = {
"MODEL_ID": ("--model-id", {}, False),
@@ -30,28 +47,26 @@ OPTIONS = {
"NO_THINKING": ("--no-thinking", {"glm": None, "mimo": None}, True),
"NO_UNCENSOR": ("--no-uncensor", {"mimo": None}, True),
}
+# Positive switches: KYOJIN_ENABLE_X=1 keeps the feature on (the default), =0 is KYOJIN_NO_X=1.
+ENABLE_SWITCHES = {"ENABLE_VISION": "NO_VISION", "ENABLE_THINKING": "NO_THINKING", "ENABLE_UNCENSOR": "NO_UNCENSOR"}
TRUE = {"1", "true", "yes", "on"}
+FALSE = {"0", "false", "no", "off"}
+# Weight files of a pack are listed in this index when the pack is sharded
+INDEX = "model.safetensors.index.json"
class ConfigError(Exception):
pass
-def find_pack(model_dir: Path) -> Path:
- """MODEL_DIR is the pack itself, or a folder holding exactly one pack."""
- if (model_dir / "config.json").is_file():
- return model_dir
- packs = sorted(p.parent for p in model_dir.glob("*/config.json"))
- if len(packs) == 1:
- return packs[0]
- if not model_dir.is_dir():
- raise ConfigError(f"MODEL_DIR={model_dir} does not exist: mount the model folder (-v /path/to/pack:/models:ro)")
- if not packs:
- raise ConfigError(f"no config.json in MODEL_DIR={model_dir}: mount the model folder")
- raise ConfigError(f"MODEL_DIR={model_dir} holds {len(packs)} packs ({', '.join(p.name for p in packs)}): point MODEL_DIR at one")
+def log(msg: str) -> None:
+ print(f"[kyojin] {msg}", file=sys.stderr, flush=True)
-def detect_family(pack: Path) -> str:
+# ---------------------------------------------------------------- pack lookup
+
+def detect_family(pack: Path):
+ """Family named by config.json, or None when it names none of ours. Unreadable config.json is an error."""
try:
cfg = json.loads((pack / "config.json").read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
@@ -60,54 +75,206 @@ def detect_family(pack: Path) -> str:
for hint, family in TYPE_HINTS:
if hint in text:
return family
- raise ConfigError(f"cannot detect the model family from {pack}/config.json: set KYOJIN_MODEL=qwen|glm|mimo")
+ return None
+
+
+def missing_files(pack: Path) -> list:
+ """Weight files a pack should hold and does not. An unsharded pack needs at least one safetensors file."""
+ index = pack / INDEX
+ if index.is_file():
+ try:
+ names = sorted(set(json.loads(index.read_text(encoding="utf-8"))["weight_map"].values()))
+ except (OSError, ValueError, KeyError):
+ return [INDEX + " (unreadable)"]
+ return [n for n in names if not (pack / n).is_file()]
+ return [] if any(pack.glob("*.safetensors")) else ["*.safetensors"]
+
+
+def check_family(pack: Path, family: str) -> None:
+ found = detect_family(pack)
+ if found is not None and found != family:
+ raise ConfigError(f"{pack} is a {found} pack but this image serves {family}: use the {found} image, or set KYOJIN_MODEL={found}")
-def build(env) -> tuple:
+def local_pack(model_dir: Path, family: str, repo_name: str, repo_forced: bool):
+ """The pack folder to serve, or None when there is none (then it has to be downloaded)."""
+ if (model_dir / "config.json").is_file():
+ check_family(model_dir, family)
+ return model_dir
+ if (model_dir / repo_name / "config.json").is_file():
+ check_family(model_dir / repo_name, family)
+ return model_dir / repo_name
+ if repo_forced:
+ return None
+ # one /models folder can hold the packs of several models: take the one of this family
+ packs = [p.parent for p in sorted(model_dir.glob("*/config.json")) if detect_family(p.parent) == family]
+ if len(packs) > 1:
+ raise ConfigError(f"MODEL_DIR={model_dir} holds {len(packs)} {family} packs ({', '.join(p.name for p in packs)}): "
+ f"point MODEL_DIR at one, or set KYOJIN_HF_REPO to the one to use")
+ return packs[0] if packs else None
+
+
+class HubDownloader:
+ """Hub access, behind two methods so that tests can replace it."""
+
+ def size(self, repo: str):
+ from huggingface_hub import HfApi
+ info = HfApi().model_info(repo, files_metadata=True)
+ return sum(s.size or 0 for s in info.siblings)
+
+ def download(self, repo: str, dest: Path) -> None:
+ from huggingface_hub import snapshot_download
+ snapshot_download(repo_id=repo, local_dir=str(dest)) # resumes: finished files are kept, partial ones continue
+
+
+def fetch_pack(repo: str, dest: Path, hub, reason: str, env) -> None:
+ if env.get("KYOJIN_DOWNLOAD", "1").strip().lower() in FALSE:
+ raise ConfigError(f"{reason} and KYOJIN_DOWNLOAD=0 forbids the download: mount the pack at /models")
+ parent = dest.parent
+ if not parent.is_dir() or not os.access(parent, os.W_OK):
+ raise ConfigError(f"{reason}, but {parent} is not writable, so the pack cannot be downloaded: "
+ f"mount a writable /models (-v /path/to/models:/models) or mount the pack")
+ try:
+ total = hub.size(repo)
+ except Exception as e: # offline, private repo, unknown repo: say so before trying the real download
+ raise ConfigError(f"{reason}, and {repo} cannot be read on the hub ({type(e).__name__}: {e}). "
+ f"Set KYOJIN_HF_REPO to a valid repository, HF_TOKEN for a private one, or mount the pack")
+ gb = total / 1e9
+ dest.mkdir(parents=True, exist_ok=True)
+ free = shutil.disk_usage(parent).free
+ if free < total:
+ raise ConfigError(f"{reason}: {repo} needs {gb:.1f} GB and {parent} has {free / 1e9:.1f} GB free")
+ log(f"{reason}. Downloading {repo} ({gb:.1f} GB) into {dest}. This can take a long time; "
+ f"if it stops, start the container again and it resumes.")
+ try:
+ hub.download(repo, dest)
+ except Exception as e:
+ raise ConfigError(f"download of {repo} failed ({type(e).__name__}: {e}); start again to resume")
+ log(f"download of {repo} finished")
+
+
+def resolve_pack(model_dir: Path, family: str, env, hub=None) -> Path:
+ if not model_dir.is_dir():
+ raise ConfigError(f"MODEL_DIR={model_dir} does not exist: mount the model folder (-v /path/to/models:/models)")
+ profile = PROFILES[family]
+ forced = env.get("KYOJIN_HF_REPO", "").strip()
+ repo = forced or profile["repo"]
+ repo_name = repo.rstrip("/").split("/")[-1]
+ pack = local_pack(model_dir, family, repo_name, bool(forced))
+ hub = hub or HubDownloader()
+ if pack is None:
+ dest = model_dir / repo_name
+ fetch_pack(repo, dest, hub, f"no {family} pack found in {model_dir}", env)
+ pack = dest
+ else:
+ gone = missing_files(pack)
+ if gone:
+ fetch_pack(repo, pack, hub, f"the pack {pack} is incomplete ({len(gone)} file(s) missing, first: {gone[0]})", env)
+ gone = missing_files(pack)
+ if gone:
+ raise ConfigError(f"the pack {pack} is still incomplete after the download ({gone[0]} missing)")
+ return pack
+
+
+# ---------------------------------------------------------------- command line
+
+def flag_value(name: str, env, family: str):
+ """KYOJIN_<name> from the environment, else the default of the model."""
+ v = env.get("KYOJIN_" + name, "").strip()
+ return v if v else PROFILES[family].get(name, "")
+
+
+def bare(name: str, env, default: str) -> str:
+ """Names without prefix (PORT, HOST, CONTEXT, MODEL_DIR) also work as KYOJIN_<name>."""
+ for key in ("KYOJIN_" + name, name):
+ if env.get(key, "").strip():
+ return env[key].strip()
+ return default
+
+
+def parse_bool(name: str, env):
+ v = env.get("KYOJIN_" + name, "").strip().lower()
+ if not v:
+ return None
+ if v in TRUE:
+ return True
+ if v in FALSE:
+ return False
+ raise ConfigError(f"KYOJIN_{name}={v!r}: expected 1 or 0")
+
+
+def switches(env, family: str) -> tuple:
+ """Flags from NO_* and ENABLE_* (both spellings). Returns (flags, notes)."""
+ flags, notes = [], []
+ for enable, no in ENABLE_SWITCHES.items():
+ flag, overrides, _ = OPTIONS[no]
+ flag = overrides.get(family, flag)
+ off, on = parse_bool(no, env), parse_bool(enable, env)
+ disable = off is True or on is False
+ keep = on is True or off is False
+ if disable and keep:
+ raise ConfigError(f"KYOJIN_{no} and KYOJIN_{enable} contradict each other: set one of them")
+ if flag is None:
+ if disable:
+ raise ConfigError(f"KYOJIN_{no if off else enable} is not supported by the {family} server")
+ if on:
+ notes.append(f"KYOJIN_{enable}=1 ignored: the {family} server has no such option")
+ elif disable:
+ flags.append(flag)
+ return flags, notes
+
+
+def build(env, hub=None) -> tuple:
"""Return (argv, notes). argv starts after the interpreter: [server.py, flags...]."""
- get = lambda k, d="": env.get("KYOJIN_" + k, d).strip()
- model_dir = Path(env.get("MODEL_DIR", "/models")).expanduser()
- pack = find_pack(model_dir)
- family = get("MODEL", "auto").lower()
+ family = env.get("KYOJIN_MODEL", "").strip().lower() or "auto"
+ model_dir = Path(bare("MODEL_DIR", env, "/models")).expanduser()
if family == "auto":
- family = detect_family(pack)
+ # no model baked in: read it from a pack given as MODEL_DIR itself (or the only pack inside)
+ packs = [model_dir] if (model_dir / "config.json").is_file() else [p.parent for p in sorted(model_dir.glob("*/config.json"))]
+ found = {detect_family(p) for p in packs} - {None}
+ if len(found) != 1:
+ raise ConfigError("cannot tell the model family from the packs in MODEL_DIR: set KYOJIN_MODEL=qwen|glm|mimo")
+ family = found.pop()
if family not in SERVERS:
raise ConfigError(f"KYOJIN_MODEL={family!r}: expected qwen, glm, mimo or auto")
- argv = [SERVERS[family], "--model", str(pack), "--host", env.get("HOST", "0.0.0.0"), "--port", env.get("PORT", "8000")]
- if not env.get("PORT", "8000").isdigit():
- raise ConfigError(f"PORT={env['PORT']!r} is not a number")
- ctx = env.get("CONTEXT", "").strip()
- if ctx:
- if not ctx.isdigit() or int(ctx) <= 0:
- raise ConfigError(f"CONTEXT={ctx!r} must be a positive number of tokens")
- argv += ["-c", ctx]
+ port = bare("PORT", env, "8731")
+ if not port.isdigit():
+ raise ConfigError(f"PORT={port!r} is not a number")
+ ctx = bare("CONTEXT", env, PROFILES[family]["CONTEXT"])
+ if not ctx.isdigit() or int(ctx) <= 0:
+ raise ConfigError(f"CONTEXT={ctx!r} must be a positive number of tokens")
+ flags, notes = switches(env, family)
+ options = []
for name, (flag, overrides, is_switch) in OPTIONS.items():
- value = get(name)
+ if is_switch:
+ continue
+ value = flag_value(name, env, family)
if not value:
continue
flag = overrides.get(family, flag)
if flag is None:
raise ConfigError(f"KYOJIN_{name} is not supported by the {family} server")
- if is_switch:
- if value.lower() in TRUE:
- argv.append(flag)
- else:
- argv += [flag, value]
- argv += shlex.split(get("EXTRA_ARGS"))
- return argv, f"family={family} pack={pack}"
+ options += [flag, value]
+ pack = resolve_pack(model_dir, family, env, hub)
+ argv = [SERVERS[family], "--model", str(pack), "--host", bare("HOST", env, "0.0.0.0"), "--port", port, "-c", ctx]
+ argv += options + flags + shlex.split(env.get("KYOJIN_EXTRA_ARGS", ""))
+ return argv, notes + [f"family={family} pack={pack} context={ctx}"]
def main() -> int:
+ quiet_stdout = "--null" in sys.argv[1:]
try:
- argv, note = build(os.environ)
+ # anything printed by the hub client must not end up in the argument list read by the entrypoint
+ with contextlib.redirect_stdout(sys.stderr) if quiet_stdout else contextlib.nullcontext():
+ argv, notes = build(os.environ)
except ConfigError as e:
- print(f"[kyojin] configuration error: {e}", file=sys.stderr)
+ log(f"configuration error: {e}")
return 2
- if "--null" in sys.argv[1:]:
- sys.stderr.write(f"[kyojin] {note}\n")
+ for n in notes:
+ log(n)
+ if quiet_stdout:
sys.stdout.write("\0".join(argv) + "\0")
else:
- print(note)
print(" ".join(shlex.quote(a) for a in ["python"] + argv))
return 0
diff --git a/docker/test_entrypoint.sh b/docker/test_entrypoint.sh
new file mode 100644
index 0000000..741d913
--- /dev/null
+++ b/docker/test_entrypoint.sh
@@ -0,0 +1,95 @@
+#!/bin/bash
+# CPU test of every branch of docker/entrypoint.sh. No GPU, no model, no network: the server is a stub script.
+# Run: bash docker/test_entrypoint.sh (works on the host or inside the image: docker run --rm --entrypoint bash IMG docker/test_entrypoint.sh)
+set -u
+HERE=$(cd "$(dirname "$0")" && pwd)
+T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
+FAIL=0
+ok() { echo "ok $1"; }
+bad() { echo "FAIL $1"; FAIL=1; }
+check(){ if eval "$2"; then ok "$1"; else bad "$1"; fi; }
+
+# fake application root: env.sh, a stub server, and the real entrypoint + argument script
+R=$T/root; mkdir -p "$R/tools/strix_halo" "$R/tools/qwen" "$R/docker"
+cp "$HERE/entrypoint.sh" "$HERE/kyojin_args.py" "$R/docker/"
+cat >"$R/tools/strix_halo/env.sh" <<'EOF'
+[ "${1:-}" = "--check" ] && { echo ENV_CHECK_RAN; exit 0; }
+export KYOJIN_TEST_ENV_SOURCED=1
+EOF
+cat >"$R/tools/qwen/serve.py" <<'EOF'
+import os, signal, sys, time
+a = sys.argv[1:]
+print("STUB args:", " ".join(a), flush=True)
+print("STUB env: sourced=%s triton=%s" % (os.environ.get("KYOJIN_TEST_ENV_SOURCED"), os.environ.get("TRITON_CACHE_DIR")), flush=True)
+if "--rc" in a:
+ sys.exit(int(a[a.index("--rc") + 1]))
+if "--hang" in a:
+ time.sleep(60)
+EOF
+mkdir -p "$T/bin"; ln -s "$(command -v python3)" "$T/bin/python"
+export PATH="$T/bin:$PATH"
+PACK=$T/models/Qwen3.8-Flash-Next-EXL3-Yamz; mkdir -p "$PACK"
+echo '{"model_type":"qwen4_exp"}' >"$PACK/config.json"; echo w >"$PACK/model.safetensors"
+run() { # run NAME [env...] -- [args]: leaves $T/out.NAME and $T/rc.NAME
+ local n=$1; shift; local envs=()
+ while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift
+ env -i PATH="$PATH" HOME="$T/home.$n" KYOJIN_ROOT="$R" KYOJIN_MODEL=qwen MODEL_DIR="$T/models" "${envs[@]}" bash "$R/docker/entrypoint.sh" "$@" >"$T/out.$n" 2>&1
+ echo $? >"$T/rc.$n"
+}
+rc() { cat "$T/rc.$1"; }
+
+# 1 shell and check
+mkdir -p "$T/home.shell" "$T/home.check"
+run shell -- shell -c 'echo SHELL_OK'
+check "shell branch runs bash with the arguments" "grep -q SHELL_OK $T/out.shell && [ $(rc shell) = 0 ]"
+run check -- check
+check "check branch runs env.sh --check" "grep -q ENV_CHECK_RAN $T/out.check"
+
+# 2 normal start: arguments, appended args, env.sh sourced, Triton cache, exit code propagated
+mkdir -p "$T/home.run"
+run run -- --rc 7
+check "server gets model, context 131072, port 8731, sampling, then the appended args" \
+ "grep -q 'STUB args: --model $PACK --host 0.0.0.0 --port 8731 -c 131072 .*--default-temperature 1.0 .*--rc 7' $T/out.run"
+check "env.sh is sourced and TRITON_CACHE_DIR points into the cache" "grep -q \"sourced=1 triton=$T/home.run/.cache/triton\" $T/out.run"
+check "server exit code is the container exit code" "[ $(rc run) = 7 ] && grep -q 'server exited with code 7' $T/out.run"
+mkdir -p "$T/home.run0"; run run0 KYOJIN_CONTEXT=4096 -- --rc 0
+check "exit 0 and context override" "[ $(rc run0) = 0 ] && grep -q -- '-c 4096' $T/out.run0"
+
+# 3 configuration errors stop before any server starts
+mkdir -p "$T/home.err" "$T/empty"
+run err MODEL_DIR="$T/empty" KYOJIN_DOWNLOAD=0 -- --rc 0
+check "config error exits 2 and never starts the server" "[ $(rc err) = 2 ] && ! grep -q STUB $T/out.err && grep -q 'configuration error' $T/out.err"
+
+# 4 SIGTERM reaches the server and the exit code is the signal's
+mkdir -p "$T/home.term"
+env -i PATH="$PATH" HOME="$T/home.term" KYOJIN_ROOT="$R" KYOJIN_MODEL=qwen MODEL_DIR="$T/models" setsid bash "$R/docker/entrypoint.sh" --hang >"$T/out.term" 2>&1 &
+EP=$!
+for i in $(seq 1 50); do grep -q 'STUB env' "$T/out.term" 2>/dev/null && break; sleep 0.2; done
+S=$(date +%s.%N); kill -TERM "$EP"; wait "$EP"; RC=$?; E=$(python3 -c "import time;print(round(time.time()-$S,1))")
+check "SIGTERM stops the server (exit 143) in under 3 s (took ${E}s)" "[ $RC = 143 ] && python3 -c 'import sys;sys.exit(0 if $E<3 else 1)'"
+check "stop is logged" "grep -q 'signal received' $T/out.term"
+
+# 5 SIGTERM during the configuration step (a long download): stub the argument script with a sleeper
+R2=$T/root2; cp -r "$R" "$R2"; printf 'import time\ntime.sleep(60)\n' >"$R2/docker/kyojin_args.py"
+mkdir -p "$T/home.dl"
+env -i PATH="$PATH" HOME="$T/home.dl" KYOJIN_ROOT="$R2" KYOJIN_MODEL=qwen MODEL_DIR="$T/models" setsid bash "$R2/docker/entrypoint.sh" >"$T/out.dl" 2>&1 &
+EP=$!; sleep 1; S=$(date +%s.%N); kill -TERM "$EP"; wait "$EP"; RC=$?; E=$(python3 -c "import time;print(round(time.time()-$S,1))")
+check "SIGTERM during the download step exits 143 in under 3 s (took ${E}s)" "[ $RC = 143 ] && python3 -c 'import sys;sys.exit(0 if $E<3 else 1)'"
+
+# 6 kernel cache choice
+mkdir -p "$T/home.c1"; run c1 -- --rc 0
+check "writable models mount: cache is a hidden folder there, linked from ~/.cache" \
+ "[ -L $T/home.c1/.cache ] && [ \"\$(readlink $T/home.c1/.cache)\" = $T/models/.kyojin-cache ] && [ -d $T/models/.kyojin-cache ] && grep -q 'kernel cache: $T/models/.kyojin-cache' $T/out.c1"
+mkdir -p "$T/home.c2"; run c2 -- --rc 0
+check "second start reuses the same cache folder" "[ \"\$(readlink $T/home.c2/.cache)\" = $T/models/.kyojin-cache ]"
+mkdir -p "$T/home.c3"; run c3 KYOJIN_CACHE_DIR="$T/mycache" -- --rc 0
+check "KYOJIN_CACHE_DIR forces the folder" "[ \"\$(readlink $T/home.c3/.cache)\" = $T/mycache ] && [ -d $T/mycache ]"
+mkdir -p "$T/home.c4/.cache/old"; echo x >"$T/home.c4/.cache/old/f"; run c4 -- --rc 0
+check "a non-empty ~/.cache is kept and reported" "[ -d $T/home.c4/.cache/old ] && grep -q 'cannot use' $T/out.c4 && [ $(rc c4) = 0 ]"
+mkdir -p "$T/home.c5"; chmod 555 "$T/models"; run c5 -- --rc 0; chmod 755 "$T/models"
+check "read-only models mount: the container's own ~/.cache is used" "[ ! -L $T/home.c5/.cache ] && grep -q 'kernel cache: $T/home.c5/.cache' $T/out.c5 && [ $(rc c5) = 0 ]"
+mkdir -p "$T/home.c6/.cache" "$T/fakebin"; printf '#!/bin/sh\nexit 0\n' >"$T/fakebin/mountpoint"; chmod +x "$T/fakebin/mountpoint"
+PATH="$T/fakebin:$PATH" run c6 -- --rc 0
+check "a volume mounted on ~/.cache wins" "[ ! -L $T/home.c6/.cache ] && grep -q 'kernel cache: $T/home.c6/.cache' $T/out.c6"
+
+[ "$FAIL" = 0 ] && echo "ALL ENTRYPOINT TESTS PASSED" || { echo "SOME ENTRYPOINT TESTS FAILED"; exit 1; }
diff --git a/docker/test_kyojin_args.py b/docker/test_kyojin_args.py
index 79c8f4f..86cf619 100644
--- a/docker/test_kyojin_args.py
+++ b/docker/test_kyojin_args.py
@@ -1,4 +1,5 @@
-"""CPU tests for the env -> argument mapping. Run: python -m pytest docker/test_kyojin_args.py"""
+"""CPU tests for the env -> argument mapping, the pack lookup and the download. Run: python -m pytest docker/test_kyojin_args.py
+The hub is never contacted: a fake downloader stands in for it."""
import json
import sys
from pathlib import Path
@@ -8,88 +9,386 @@ import pytest
sys.path.insert(0, str(Path(__file__).parent))
import kyojin_args as ka
+TYPES = {"qwen": "qwen4_exp", "glm": "glm5_next", "mimo": "mimo_v2"}
-def pack(tmp_path, model_type, name="pack"):
+
+def pack(tmp_path, model_type, name="pack", files=("model.safetensors",)):
d = tmp_path / name
- d.mkdir()
+ d.mkdir(parents=True, exist_ok=True)
(d / "config.json").write_text(json.dumps({"model_type": model_type, "architectures": ["X"]}))
+ for f in files:
+ (d / f).write_text("w")
return d
-def test_defaults_and_autodetect(tmp_path):
+class FakeHub:
+ def __init__(self, size=1e9, fail=None, model_type="qwen4_exp", sharded=False):
+ self.calls, self.size_value, self.fail, self.model_type, self.sharded = [], size, fail, model_type, sharded
+
+ def size(self, repo):
+ self.calls.append(("size", repo))
+ if self.fail == "size":
+ raise OSError("offline")
+ return self.size_value
+
+ def download(self, repo, dest):
+ self.calls.append(("download", repo, Path(dest)))
+ if self.fail == "download":
+ raise OSError("connection reset")
+ dest = Path(dest)
+ dest.mkdir(parents=True, exist_ok=True)
+ (dest / "config.json").write_text(json.dumps({"model_type": self.model_type}))
+ if self.sharded:
+ (dest / ka.INDEX).write_text(json.dumps({"weight_map": {"a": "s1.safetensors", "b": "s2.safetensors"}}))
+ (dest / "s1.safetensors").write_text("w"); (dest / "s2.safetensors").write_text("w")
+ else:
+ (dest / "model.safetensors").write_text("w")
+
+
+def env_for(tmp_path, family="qwen", **extra):
+ return {"KYOJIN_MODEL": family, "MODEL_DIR": str(tmp_path), **extra}
+
+
+# ---- defaults per model (the card values)
+
+def test_qwen_defaults_for_128gb(tmp_path):
p = pack(tmp_path, "qwen4_exp")
- argv, _ = ka.build({"MODEL_DIR": str(p)})
- assert argv == ["tools/qwen/serve.py", "--model", str(p), "--host", "0.0.0.0", "--port", "8000"]
+ argv, _ = ka.build(env_for(tmp_path))
+ assert argv[:9] == ["tools/qwen/serve.py", "--model", str(p), "--host", "0.0.0.0", "--port", "8731", "-c", "131072"]
+ for flag, v in (("--default-temperature", "1.0"), ("--default-top-p", "0.95"), ("--default-top-k", "20"), ("--default-min-p", "0.0")):
+ assert argv[argv.index(flag) + 1] == v
+ assert "--no-vision" not in argv and "--no-thinking" not in argv
[email protected]("mt,server", [("glm5_next", "glm"), ("mimo_v2", "mimo"), ("qwen4_exp", "qwen")])
-def test_detect(tmp_path, mt, server):
- argv, _ = ka.build({"MODEL_DIR": str(pack(tmp_path, mt))})
- assert argv[0] == f"tools/{server}/serve.py"
[email protected]("family", ["glm", "mimo"])
+def test_glm_mimo_defaults(tmp_path, family):
+ pack(tmp_path, TYPES[family])
+ argv, _ = ka.build(env_for(tmp_path, family))
+ assert argv[0] == f"tools/{family}/serve.py" and argv[argv.index("-c") + 1] == "131072"
+ assert argv[argv.index("--default-temperature") + 1] == "1.0" and argv[argv.index("--default-top-p") + 1] == "0.95"
+ assert "--default-top-k" not in argv and "--default-min-p" not in argv
-def test_explicit_model_overrides_detection(tmp_path):
- argv, _ = ka.build({"MODEL_DIR": str(pack(tmp_path, "qwen4_exp")), "KYOJIN_MODEL": "GLM"})
- assert argv[0] == "tools/glm/serve.py"
[email protected]("family", ka.SERVERS)
+def test_profile_complete_and_flags_exist_in_servers(family):
+ """Each flag emitted for a family, from the profile or from an option, must be an add_argument of that server."""
+ root = Path(__file__).parent.parent
+ src = (root / ka.SERVERS[family]).read_text()
+ prof = ka.PROFILES[family]
+ assert prof["repo"].startswith("yamz-labs/") and prof["CONTEXT"].isdigit()
+ for env_name, (flag, over, _) in ka.OPTIONS.items():
+ f = over.get(family, flag)
+ if f is not None:
+ assert f'"{f}"' in src, f"{family} server has no {f}"
+ assert '"-c"' in src
+ for name in prof:
+ if name.startswith("DEFAULT_"):
+ flag, over, _ = ka.OPTIONS[name]
+ assert over.get(family, flag) is not None, f"{family} profile sets {name} but the server lacks it"
-def test_parent_folder_with_one_pack(tmp_path):
- p = pack(tmp_path, "mimo_v2")
- argv, _ = ka.build({"MODEL_DIR": str(tmp_path)})
- assert argv[2] == str(p)
+# ---- model selection
+
+def test_baked_model_used_even_if_pack_is_other_family(tmp_path):
+ p = pack(tmp_path, "glm5_next")
+ with pytest.raises(ka.ConfigError, match="glm pack but this image serves qwen"):
+ ka.build(env_for(tmp_path, MODEL_DIR=str(p)))
+ q = pack(tmp_path, "glm5_next", "Qwen3.8-Flash-Next-EXL3-Yamz") # named like the qwen repo, but a glm pack
+ with pytest.raises(ka.ConfigError, match="glm pack but this image serves qwen"):
+ ka.build(env_for(tmp_path))
-def test_parent_folder_with_two_packs(tmp_path):
+def test_auto_detects_from_the_only_pack(tmp_path):
+ pack(tmp_path, "mimo_v2")
+ argv, _ = ka.build({"KYOJIN_MODEL": "auto", "MODEL_DIR": str(tmp_path)})
+ assert argv[0] == "tools/mimo/serve.py"
+ argv, _ = ka.build({"MODEL_DIR": str(tmp_path)}) # unset = auto
+ assert argv[0] == "tools/mimo/serve.py"
+
+
+def test_auto_cannot_decide(tmp_path):
pack(tmp_path, "mimo_v2", "a"); pack(tmp_path, "qwen4_exp", "b")
- with pytest.raises(ka.ConfigError, match="2 packs"):
+ with pytest.raises(ka.ConfigError, match="set KYOJIN_MODEL"):
ka.build({"MODEL_DIR": str(tmp_path)})
+ with pytest.raises(ka.ConfigError, match="set KYOJIN_MODEL"):
+ ka.build({"MODEL_DIR": str(tmp_path / "empty-nonexistent")})
-def test_port_context_options(tmp_path):
+def test_unknown_family(tmp_path):
+ with pytest.raises(ka.ConfigError, match="expected qwen"):
+ ka.build(env_for(tmp_path, "llama"))
+
+
+def test_explicit_model_case_insensitive(tmp_path):
+ pack(tmp_path, "glm5_next")
+ argv, _ = ka.build(env_for(tmp_path, "GLM"))
+ assert argv[0] == "tools/glm/serve.py"
+
+
+# ---- pack lookup
+
+def test_pack_is_model_dir_itself(tmp_path):
p = pack(tmp_path, "qwen4_exp")
- argv, _ = ka.build({"MODEL_DIR": str(p), "PORT": "9000", "HOST": "127.0.0.1", "CONTEXT": "32768",
- "KYOJIN_DEFAULT_TEMPERATURE": "0.6", "KYOJIN_NO_VISION": "1", "KYOJIN_DRAFT_TOKENS": "2",
- "KYOJIN_REASONING_EFFORT": "low", "KYOJIN_NO_THINKING": "0"})
- assert argv[3:7] == ["127.0.0.1", "--port", "9000", "-c"] or "-c" in argv
+ argv, _ = ka.build({"KYOJIN_MODEL": "qwen", "MODEL_DIR": str(p)})
+ assert argv[2] == str(p)
+
+
+def test_pack_named_after_the_repo_wins(tmp_path):
+ pack(tmp_path, "qwen4_exp", "other")
+ p = pack(tmp_path, "qwen4_exp", "Qwen3.8-Flash-Next-EXL3-Yamz")
+ argv, _ = ka.build(env_for(tmp_path))
+ assert argv[2] == str(p)
+
+
+def test_shared_models_folder_picks_own_family(tmp_path):
+ pack(tmp_path, "glm5_next", "g"); q = pack(tmp_path, "qwen4_exp", "q"); pack(tmp_path, "mimo_v2", "m")
+ hub = FakeHub()
+ argv, _ = ka.build(env_for(tmp_path, "qwen"), hub)
+ assert argv[2] == str(q) and hub.calls == []
+
+
+def test_two_packs_of_the_family(tmp_path):
+ pack(tmp_path, "qwen4_exp", "a"); pack(tmp_path, "qwen4_exp", "b")
+ with pytest.raises(ka.ConfigError, match="2 qwen packs"):
+ ka.build(env_for(tmp_path), FakeHub())
+
+
+def test_missing_model_dir(tmp_path):
+ with pytest.raises(ka.ConfigError, match="does not exist"):
+ ka.build(env_for(tmp_path, MODEL_DIR=str(tmp_path / "nope")))
+
+
+def test_unreadable_config(tmp_path):
+ d = tmp_path / "p"; d.mkdir(); (d / "config.json").write_text("{not json")
+ with pytest.raises(ka.ConfigError, match="cannot read"):
+ ka.build(env_for(tmp_path, MODEL_DIR=str(d)))
+
+
+def test_pack_with_unknown_model_type_is_accepted_when_family_is_set(tmp_path):
+ p = pack(tmp_path, "gpt2")
+ argv, _ = ka.build(env_for(tmp_path, MODEL_DIR=str(p)))
+ assert argv[2] == str(p)
+
+
+# ---- download
+
+def test_download_when_no_pack(tmp_path):
+ hub = FakeHub(sharded=True)
+ argv, notes = ka.build(env_for(tmp_path), hub)
+ dest = tmp_path / "Qwen3.8-Flash-Next-EXL3-Yamz"
+ assert hub.calls == [("size", "yamz-labs/Qwen3.8-Flash-Next-EXL3-Yamz"), ("download", "yamz-labs/Qwen3.8-Flash-Next-EXL3-Yamz", dest)]
+ assert argv[2] == str(dest)
+
+
[email protected]("family,repo", [("glm", "yamz-labs/GLM-5.3-Flash-EXL3-Yamz"), ("mimo", "yamz-labs/MiMo-V2.6-Flash-MOPD-EXL3-Yamz")])
+def test_download_repo_per_model(tmp_path, family, repo):
+ hub = FakeHub(model_type=TYPES[family])
+ ka.build(env_for(tmp_path, family), hub)
+ assert hub.calls[0] == ("size", repo)
+
+
+def test_download_repo_override(tmp_path):
+ hub = FakeHub()
+ argv, _ = ka.build(env_for(tmp_path, KYOJIN_HF_REPO="someone/My-Pack"), hub)
+ assert hub.calls[1] == ("download", "someone/My-Pack", tmp_path / "My-Pack") and argv[2] == str(tmp_path / "My-Pack")
+
+
+def test_forced_repo_ignores_other_packs_in_folder(tmp_path):
+ pack(tmp_path, "qwen4_exp", "old")
+ hub = FakeHub()
+ argv, _ = ka.build(env_for(tmp_path, KYOJIN_HF_REPO="someone/My-Pack"), hub)
+ assert argv[2] == str(tmp_path / "My-Pack")
+
+
+def test_log_line_with_size_comes_before_the_download(tmp_path, capsys):
+ ka.build(env_for(tmp_path), FakeHub(size=1.5e9))
+ err = capsys.readouterr().err
+ assert "Downloading yamz-labs/Qwen3.8-Flash-Next-EXL3-Yamz (1.5 GB)" in err and "resumes" in err
+
+
+def test_incomplete_pack_resumes(tmp_path):
+ d = tmp_path / "Qwen3.8-Flash-Next-EXL3-Yamz"; d.mkdir()
+ (d / "config.json").write_text(json.dumps({"model_type": "qwen4_exp"}))
+ (d / ka.INDEX).write_text(json.dumps({"weight_map": {"a": "s1.safetensors", "b": "s2.safetensors"}}))
+ (d / "s1.safetensors").write_text("w")
+ hub = FakeHub(sharded=True)
+ argv, _ = ka.build(env_for(tmp_path), hub)
+ assert hub.calls[1] == ("download", "yamz-labs/Qwen3.8-Flash-Next-EXL3-Yamz", d) and (d / "s2.safetensors").exists()
+
+
+def test_complete_sharded_pack_does_not_touch_the_hub(tmp_path):
+ d = pack(tmp_path, "qwen4_exp", files=("s1.safetensors",))
+ (d / ka.INDEX).write_text(json.dumps({"weight_map": {"a": "s1.safetensors"}}))
+ hub = FakeHub()
+ ka.build(env_for(tmp_path), hub)
+ assert hub.calls == []
+
+
+def test_pack_without_weights_is_incomplete(tmp_path):
+ pack(tmp_path, "qwen4_exp", files=())
+ hub = FakeHub()
+ ka.build(env_for(tmp_path), hub)
+ assert [c[0] for c in hub.calls] == ["size", "download"]
+
+
+def test_unreadable_index_is_incomplete(tmp_path):
+ d = pack(tmp_path, "qwen4_exp"); (d / ka.INDEX).write_text("nope")
+ assert ka.missing_files(d)[0].startswith(ka.INDEX)
+
+
+def test_download_forbidden(tmp_path):
+ hub = FakeHub()
+ with pytest.raises(ka.ConfigError, match="KYOJIN_DOWNLOAD=0"):
+ ka.build(env_for(tmp_path, KYOJIN_DOWNLOAD="0"), hub)
+ assert hub.calls == []
+
+
+def test_download_into_read_only_mount(tmp_path):
+ ro = tmp_path / "ro"; ro.mkdir(); ro.chmod(0o555)
+ try:
+ with pytest.raises(ka.ConfigError, match="not writable"):
+ ka.build(env_for(tmp_path, MODEL_DIR=str(ro)), FakeHub())
+ finally:
+ ro.chmod(0o755)
+
+
+def test_hub_unreachable_is_a_clear_error(tmp_path):
+ with pytest.raises(ka.ConfigError, match="cannot be read on the hub"):
+ ka.build(env_for(tmp_path), FakeHub(fail="size"))
+
+
+def test_download_failure_says_how_to_resume(tmp_path):
+ with pytest.raises(ka.ConfigError, match="start again to resume"):
+ ka.build(env_for(tmp_path), FakeHub(fail="download"))
+
+
+def test_not_enough_disk(tmp_path):
+ with pytest.raises(ka.ConfigError, match="GB free"):
+ ka.build(env_for(tmp_path), FakeHub(size=1e18))
+
+
+def test_download_that_leaves_pack_incomplete(tmp_path):
+ class Half(FakeHub):
+ def download(self, repo, dest):
+ super().download(repo, dest)
+ (Path(dest) / ka.INDEX).write_text(json.dumps({"weight_map": {"a": "gone.safetensors"}}))
+ with pytest.raises(ka.ConfigError, match="still incomplete"):
+ ka.build(env_for(tmp_path), Half())
+
+
+def test_hub_downloader_is_lazy():
+ ka.HubDownloader() # building it must not import or contact the hub
+
+
+# ---- options
+
+def test_port_context_options(tmp_path):
+ pack(tmp_path, "qwen4_exp")
+ argv, _ = ka.build(env_for(tmp_path, PORT="9000", HOST="127.0.0.1", CONTEXT="32768", KYOJIN_DEFAULT_TEMPERATURE="0.6",
+ KYOJIN_NO_VISION="1", KYOJIN_DRAFT_TOKENS="2", KYOJIN_REASONING_EFFORT="low", KYOJIN_NO_THINKING="0"))
assert argv[argv.index("--port") + 1] == "9000" and argv[argv.index("--host") + 1] == "127.0.0.1"
assert argv[argv.index("-c") + 1] == "32768"
assert "--no-vision" in argv and "--no-thinking" not in argv
assert argv[argv.index("--ndt") + 1] == "2" and argv[argv.index("--default-temperature") + 1] == "0.6"
+ assert argv.count("--default-temperature") == 1
+
+
+def test_prefixed_aliases(tmp_path):
+ pack(tmp_path, "qwen4_exp")
+ argv, _ = ka.build(env_for(tmp_path, KYOJIN_PORT="9100", KYOJIN_CONTEXT="4096", KYOJIN_HOST="::1", PORT="1", CONTEXT="2"))
+ assert argv[argv.index("--port") + 1] == "9100" and argv[argv.index("-c") + 1] == "4096" and argv[argv.index("--host") + 1] == "::1"
+
+
+def test_prefixed_model_dir(tmp_path):
+ p = pack(tmp_path, "qwen4_exp")
+ argv, _ = ka.build({"KYOJIN_MODEL": "qwen", "KYOJIN_MODEL_DIR": str(p)})
+ assert argv[2] == str(p)
def test_glm_draft_flag_name(tmp_path):
- argv, _ = ka.build({"MODEL_DIR": str(pack(tmp_path, "glm5_next")), "KYOJIN_DRAFT_TOKENS": "3"})
+ pack(tmp_path, "glm5_next")
+ argv, _ = ka.build(env_for(tmp_path, "glm", KYOJIN_DRAFT_TOKENS="3"))
assert argv[argv.index("--num-draft") + 1] == "3" and "--ndt" not in argv
def test_unsupported_option_is_an_error(tmp_path):
+ pack(tmp_path, "glm5_next")
+ with pytest.raises(ka.ConfigError, match="not supported by the glm"):
+ ka.build(env_for(tmp_path, "glm", KYOJIN_NO_VISION="1"))
with pytest.raises(ka.ConfigError, match="not supported by the glm"):
- ka.build({"MODEL_DIR": str(pack(tmp_path, "glm5_next")), "KYOJIN_NO_VISION": "1"})
+ ka.build(env_for(tmp_path, "glm", KYOJIN_DEFAULT_TOP_K="40"))
def test_extra_args_passthrough_keeps_quotes(tmp_path):
- argv, _ = ka.build({"MODEL_DIR": str(pack(tmp_path, "qwen4_exp")),
- "KYOJIN_EXTRA_ARGS": "--default-max-tokens 512 --model-id 'my model'"})
+ pack(tmp_path, "qwen4_exp")
+ argv, _ = ka.build(env_for(tmp_path, KYOJIN_EXTRA_ARGS="--default-max-tokens 512 --model-id 'my model'"))
assert argv[-4:] == ["--default-max-tokens", "512", "--model-id", "my model"]
[email protected]("env,msg", [({"CONTEXT": "abc"}, "CONTEXT"), ({"PORT": "x"}, "PORT"), ({"KYOJIN_MODEL": "llama"}, "expected")])
[email protected]("env,msg", [({"CONTEXT": "abc"}, "CONTEXT"), ({"CONTEXT": "0"}, "CONTEXT"), ({"PORT": "x"}, "PORT"),
+ ({"KYOJIN_NO_VISION": "maybe"}, "expected 1 or 0")])
def test_bad_values(tmp_path, env, msg):
+ pack(tmp_path, "qwen4_exp")
with pytest.raises(ka.ConfigError, match=msg):
- ka.build({"MODEL_DIR": str(pack(tmp_path, "qwen4_exp")), **env})
+ ka.build(env_for(tmp_path, **env))
-def test_missing_model_dir(tmp_path):
- with pytest.raises(ka.ConfigError, match="does not exist"):
- ka.build({"MODEL_DIR": str(tmp_path / "nope")})
+# ---- positive switches
[email protected]("env,flags", [
+ ({}, []),
+ ({"KYOJIN_ENABLE_VISION": "1"}, []),
+ ({"KYOJIN_ENABLE_VISION": "0"}, ["--no-vision"]),
+ ({"KYOJIN_ENABLE_VISION": "false"}, ["--no-vision"]),
+ ({"KYOJIN_NO_VISION": "1"}, ["--no-vision"]),
+ ({"KYOJIN_NO_VISION": "0"}, []),
+ ({"KYOJIN_ENABLE_THINKING": "0"}, ["--no-thinking"]),
+ ({"KYOJIN_ENABLE_UNCENSOR": "0"}, ["--no-uncensor"]),
+ ({"KYOJIN_ENABLE_VISION": "1", "KYOJIN_NO_VISION": "0"}, []),
+ ({"KYOJIN_ENABLE_VISION": "0", "KYOJIN_NO_VISION": "1"}, ["--no-vision"]),
+])
+def test_qwen_switches(tmp_path, env, flags):
+ pack(tmp_path, "qwen4_exp")
+ argv, _ = ka.build(env_for(tmp_path, **env))
+ assert [f for f in ("--no-vision", "--no-thinking", "--no-uncensor") if f in argv] == flags
-def test_every_flag_exists_in_the_servers():
- """Each flag emitted for a family must be an add_argument of that server."""
- root = Path(__file__).parent.parent
- for family, script in ka.SERVERS.items():
- src = (root / script).read_text()
- for env_name, (flag, over, _) in ka.OPTIONS.items():
- f = over.get(family, flag)
- if f is not None:
- assert f'"{f}"' in src, f"{family} server has no {f}"
+
[email protected]("env", [{"KYOJIN_ENABLE_VISION": "1", "KYOJIN_NO_VISION": "1"}, {"KYOJIN_ENABLE_VISION": "0", "KYOJIN_NO_VISION": "0"}])
+def test_contradicting_switches(tmp_path, env):
+ pack(tmp_path, "qwen4_exp")
+ with pytest.raises(ka.ConfigError, match="contradict"):
+ ka.build(env_for(tmp_path, **env))
+
+
+def test_enable_vision_is_ignored_where_the_server_has_none(tmp_path):
+ """His llama-swap line sets KYOJIN_ENABLE_VISION=1 for every model; GLM and MiMo have no vision tower."""
+ pack(tmp_path, "glm5_next")
+ argv, notes = ka.build(env_for(tmp_path, "glm", KYOJIN_ENABLE_VISION="1"))
+ assert "--no-vision" not in argv and any("ignored" in n for n in notes)
+ with pytest.raises(ka.ConfigError, match="not supported by the glm"):
+ ka.build(env_for(tmp_path, "glm", KYOJIN_ENABLE_VISION="0"))
+
+
+# ---- command line of the script
+
+def test_cli_null_output_and_errors(tmp_path, monkeypatch, capsys):
+ pack(tmp_path, "qwen4_exp")
+ monkeypatch.setattr(sys, "argv", ["x", "--null"])
+ for k, v in env_for(tmp_path).items():
+ monkeypatch.setenv(k, v)
+ assert ka.main() == 0
+ cap = capsys.readouterr()
+ assert cap.out.split("\0")[0] == "tools/qwen/serve.py" and cap.out.endswith("\0") and "family=qwen" in cap.err
+ monkeypatch.setenv("CONTEXT", "x")
+ assert ka.main() == 2
+ cap = capsys.readouterr()
+ assert cap.out == "" and "configuration error" in cap.err
+
+
+def test_cli_plain_output(tmp_path, monkeypatch, capsys):
+ pack(tmp_path, "qwen4_exp")
+ monkeypatch.setattr(sys, "argv", ["x"])
+ for k, v in env_for(tmp_path).items():
+ monkeypatch.setenv(k, v)
+ assert ka.main() == 0
+ assert capsys.readouterr().out.startswith("python tools/qwen/serve.py --model ")