Gregory-L commited on
Commit
0ed5275
·
verified ·
1 Parent(s): 76258e9

serve --to vllm|sglang: real deploy targets (launch detached, readiness, stop)

Browse files

deploy/openai_server_push.py: launch_openai_server serves a LoRA natively over
the base (vLLM --enable-lora --lora-modules, SGLang --enable-lora --lora-paths)
or merged (--merge, merge_lora_adapter); builds the exact argv; launches in its
own session with server.log / server.pid / launch.json under
out/runs/<run>/serve/<to>/; polls /v1/models (+ vLLM /health) until the tag is
listed; optionally swaps mindX's fallback (provider vllm|sglang).
stop_openai_server SIGTERMs the process group and verifies it is gone. CPU
hosts get bfloat16, VLLM_CPU_KVCACHE_SPACE, SGLang --device cpu; quantized
checkpoints and tensor_parallel > 1 are refused without a GPU; a missing server
is reported with its install hint. Results never raise.

CLI: --dry-run, --stop, --merge, --host, --port, --dtype, --server-bin,
--server-arg, --ready-timeout, --cpu-kvcache-gib. Gradio Serve room offers
sglang. Docs: docs/serve.md (flag provenance), cli.md, README, NAV, CHANGELOG,
llm.txt. Tests: 21 new (Popen/which monkeypatched, httpx MockTransport).

Co-Authored-By: Professor Codephreak <codephreak@pythai.net>

made with luv.pythai.net

README.md CHANGED
@@ -93,6 +93,15 @@ GPU steps (`bench` without `--dry-run`, `train`, `quantize`, `serve`) require
93
  an AMD MI300X with ROCm 7.2.1; run inside `rocm/primus:v26.2`. The full
94
  operator checklist lives in [`HANDOFF.md`](docs/HANDOFF.md).
95
 
 
 
 
 
 
 
 
 
 
96
  ## bankml (verified CPU engine)
97
 
98
  [bankml](https://github.com/cryptoAGI/bankml) is a zero-dependency Rust runtime, token-identical to
@@ -138,6 +147,7 @@ scripts/ dev helpers
138
  | [`docs/coach.md`](docs/coach.md) | Interactive `/coach/` web UI bundled in the operator. |
139
  | [`docs/dcoach.md`](docs/dcoach.md) | The dcoach proof loop — prove a CPU model recalls its training; decentralized-training fit. |
140
  | [`docs/cli.md`](docs/cli.md) | Every `mindxtrain` verb with synopsis, options, exit codes. |
 
141
  | [`docs/bankml.md`](docs/bankml.md) | bankml as serve target, operator backend and receipt-auditable imprint probe — what it takes and what it refuses. [bankml on GitHub](https://github.com/cryptoAGI/bankml). |
142
  | [`docs/yaml_schema.md`](docs/yaml_schema.md) | Every field of the 10-section `XTrainConfig`. |
143
  | [`docs/benchmarks.md`](docs/benchmarks.md) | Target metrics + the 7-cell framework comparison. |
 
93
  an AMD MI300X with ROCm 7.2.1; run inside `rocm/primus:v26.2`. The full
94
  operator checklist lives in [`HANDOFF.md`](docs/HANDOFF.md).
95
 
96
+ ## Serving on vLLM / SGLang
97
+
98
+ `mindxtrain serve run.yaml --to vllm` (or `--to sglang`) launches the OpenAI-compatible server on
99
+ the trained run — the LoRA served natively over the base, or merged with `--merge` — detached, with
100
+ its log and pid under `out/runs/<run>/serve/<to>/`, and returns once `/v1/models` lists the tag.
101
+ `--dry-run` prints the exact argv; `--stop` ends it; `--register-as-fallback` hands it to mindX.
102
+ On a host without a GPU it uses the CPU backends and refuses configs that need a GPU, with the
103
+ reason. vLLM: `uv sync --extra serve`; SGLang: install it yourself. Full page: [`docs/serve.md`](docs/serve.md).
104
+
105
  ## bankml (verified CPU engine)
106
 
107
  [bankml](https://github.com/cryptoAGI/bankml) is a zero-dependency Rust runtime, token-identical to
 
147
  | [`docs/coach.md`](docs/coach.md) | Interactive `/coach/` web UI bundled in the operator. |
148
  | [`docs/dcoach.md`](docs/dcoach.md) | The dcoach proof loop — prove a CPU model recalls its training; decentralized-training fit. |
149
  | [`docs/cli.md`](docs/cli.md) | Every `mindxtrain` verb with synopsis, options, exit codes. |
150
+ | [`docs/serve.md`](docs/serve.md) | `serve --to vllm\|sglang`: native-LoRA or merged launch, readiness, stop, CPU vs GPU, and where every flag was verified. |
151
  | [`docs/bankml.md`](docs/bankml.md) | bankml as serve target, operator backend and receipt-auditable imprint probe — what it takes and what it refuses. [bankml on GitHub](https://github.com/cryptoAGI/bankml). |
152
  | [`docs/yaml_schema.md`](docs/yaml_schema.md) | Every field of the 10-section `XTrainConfig`. |
153
  | [`docs/benchmarks.md`](docs/benchmarks.md) | Target metrics + the 7-cell framework comparison. |
docs/CHANGELOG.md CHANGED
@@ -28,6 +28,20 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
28
  **not comparable** with the canonical 1.3-penalty gate.
29
  - MEI `InferenceEngineIdent.name` accepts `"bankml"`; the Gradio Serve room offers `bankml`.
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  ### Changed
32
 
33
  - `ui/console.py` omits penalty / mirostat options left at the engine's own default, so bankml
 
28
  **not comparable** with the canonical 1.3-penalty gate.
29
  - MEI `InferenceEngineIdent.name` accepts `"bankml"`; the Gradio Serve room offers `bankml`.
30
 
31
+ - **`serve --to vllm|sglang` are real deploy targets** ([`docs/serve.md`](serve.md)), no longer
32
+ print-only. `deploy/openai_server_push.py`: `launch_openai_server` serves a LoRA natively over
33
+ the base (vLLM `--enable-lora --lora-modules`, SGLang `--enable-lora --lora-paths`) or merged
34
+ (`--merge`, `merge_lora_adapter`), launches detached (own session; `server.log`, `server.pid`,
35
+ `launch.json` under `out/runs/<run>/serve/<to>/`), waits for `/v1/models` (+ vLLM `/health`),
36
+ and optionally swaps mindX's fallback (`provider="vllm"|"sglang"`); `stop_openai_server` SIGTERMs
37
+ the process group and verifies it is gone. CPU hosts get bfloat16, `VLLM_CPU_KVCACHE_SPACE`,
38
+ SGLang `--device cpu`; quantized checkpoints and `tensor_parallel > 1` are refused without a
39
+ GPU; a missing server is reported with its install hint. Every outcome is a
40
+ `ServerLaunchResult` / `ServerStopResult`. New CLI options: `--dry-run`, `--stop`, `--merge`,
41
+ `--host`, `--port`, `--dtype`, `--server-bin`, `--server-arg`, `--ready-timeout`,
42
+ `--cpu-kvcache-gib`. The Gradio Serve room offers `sglang`. vLLM / SGLang are reached as a
43
+ subprocess and over HTTP only.
44
+
45
  ### Changed
46
 
47
  - `ui/console.py` omits penalty / mirostat options left at the engine's own default, so bankml
docs/NAV.md CHANGED
@@ -123,6 +123,10 @@ The interactive `/coach/` operator UI: create-script, live-training diagnostics,
123
  - [How mindXtrain fits decentralized training](dcoach.md#how-mindxtrain-fits-decentralized-training)
124
  - [Why this matters](dcoach.md#why-this-matters)
125
 
 
 
 
 
126
  ### [bankml — the verified CPU engine](bankml.md)
127
  [bankml](https://github.com/cryptoAGI/bankml) as serve target, operator backend and receipt-auditable imprint probe.
128
  - [What bankml runs, and what it refuses](bankml.md#what-bankml-runs-and-what-it-refuses)
 
123
  - [How mindXtrain fits decentralized training](dcoach.md#how-mindxtrain-fits-decentralized-training)
124
  - [Why this matters](dcoach.md#why-this-matters)
125
 
126
+ ### [Serving on vLLM and SGLang](serve.md)
127
+
128
+ - [What runs](serve.md#what-runs) · [CPU and GPU](serve.md#cpu-and-gpu) · [Exit codes](serve.md#exit-codes) · [Where each flag comes from](serve.md#where-each-flag-comes-from)
129
+
130
  ### [bankml — the verified CPU engine](bankml.md)
131
  [bankml](https://github.com/cryptoAGI/bankml) as serve target, operator backend and receipt-auditable imprint probe.
132
  - [What bankml runs, and what it refuses](bankml.md#what-bankml-runs-and-what-it-refuses)
docs/cli.md CHANGED
@@ -131,19 +131,24 @@ Requires the `amd-quark` package — typically only available inside the
131
  `rocm/primus:v26.2` container or per
132
  [Quark docs](https://quark.docs.amd.com/).
133
 
134
- ## `serve` — print the vLLM-ROCm launch command
135
 
136
  ```
137
- mindxtrain serve <config.yaml> [--checkpoint <path>]
 
 
 
138
  ```
139
 
140
- Builds the `vllm serve` argv from `cfg.serve` and prints it. We deliberately
141
- don't `exec` — the user pipes it into their own orchestrator (or
142
- `ops/compose/compose_dev.yaml`).
143
-
144
- The chat-template parsers map per `serve.reasoning_parser` (`qwen3` for Qwen3,
145
- `deepseek_r1` for DeepSeek-style) and `serve.tool_call_parser` (`hermes`,
146
- `qwen3_coder`).
 
 
147
 
148
  ### `serve --to ollama` / `--to bankml`
149
 
@@ -225,7 +230,7 @@ $ uv run mindxtrain receipt out/runs/<run_id>/manifest.json --config run.yaml
225
  | `dataset prep` | `mindxtrain.cli.main.dataset_prep` + `mindxtrain.data.{curate,filter,tokenize,pack}` |
226
  | `eval` | `mindxtrain.cli.main.eval_` + `mindxtrain.eval.harness.run_lm_eval` |
227
  | `quantize` | `mindxtrain.cli.main.quantize` + `mindxtrain.deploy.quark.quark_fp8` |
228
- | `serve` | `mindxtrain.cli.main.serve` + `mindxtrain.deploy.vllm_launcher.build_vllm_command` |
229
  | `serve --to bankml` | `mindxtrain.cli.main._serve_bankml` + `mindxtrain.deploy.bankml_push.push_to_bankml` |
230
  | `imprint-bankml` | `mindxtrain.cli.main.imprint_bankml` + `mindxtrain.eval.imprint_bankml.imprint_via_bankml` |
231
  | `publish` | `mindxtrain.cli.main.publish` + `mindxtrain.storage.{hf_hub,lighthouse}` + `mindxtrain.deploy.api_client` |
 
131
  `rocm/primus:v26.2` container or per
132
  [Quark docs](https://quark.docs.amd.com/).
133
 
134
+ ## `serve` — launch vLLM / SGLang (default `--to vllm`)
135
 
136
  ```
137
+ mindxtrain serve <config.yaml> [--to vllm|sglang] [--checkpoint <path>] [--tag NAME] [--merge]
138
+ [--host 127.0.0.1] [--port N] [--dtype auto] [--server-bin PATH]
139
+ [--server-arg ARG ...] [--ready-timeout 600] [--cpu-kvcache-gib 4]
140
+ [--register-as-fallback] [--dry-run | --stop]
141
  ```
142
 
143
+ Launches `vllm serve` / `python -m sglang.launch_server` detached (log, pid and `launch.json` under
144
+ `out/runs/<run>/serve/<to>/`), serving a LoRA natively over the base (`--merge` merges it first),
145
+ waits until `/v1/models` lists the tag (and vLLM's `/health` is 200), and with
146
+ `--register-as-fallback` swaps mindX's fallback model to it. `--dry-run` prints the exact argv and
147
+ runs nothing; `--stop` sends SIGTERM to the recorded server's process group and verifies it is
148
+ gone. On a GPU-less host the CPU backends are used (bfloat16, `VLLM_CPU_KVCACHE_SPACE`,
149
+ SGLang `--device cpu`); a quantized checkpoint or `tensor_parallel > 1` is refused there. Exit
150
+ codes: 1 checkpoint missing · 2 refused (server missing, GPU needed, already running) · 3 merge
151
+ failed / exited early / error · 4 not ready in time (left running). Full page: [serve.md](serve.md).
152
 
153
  ### `serve --to ollama` / `--to bankml`
154
 
 
230
  | `dataset prep` | `mindxtrain.cli.main.dataset_prep` + `mindxtrain.data.{curate,filter,tokenize,pack}` |
231
  | `eval` | `mindxtrain.cli.main.eval_` + `mindxtrain.eval.harness.run_lm_eval` |
232
  | `quantize` | `mindxtrain.cli.main.quantize` + `mindxtrain.deploy.quark.quark_fp8` |
233
+ | `serve --to vllm\|sglang` | `mindxtrain.cli.main._serve_openai_server` + `mindxtrain.deploy.openai_server_push.launch_openai_server` |
234
  | `serve --to bankml` | `mindxtrain.cli.main._serve_bankml` + `mindxtrain.deploy.bankml_push.push_to_bankml` |
235
  | `imprint-bankml` | `mindxtrain.cli.main.imprint_bankml` + `mindxtrain.eval.imprint_bankml.imprint_via_bankml` |
236
  | `publish` | `mindxtrain.cli.main.publish` + `mindxtrain.storage.{hf_hub,lighthouse}` + `mindxtrain.deploy.api_client` |
docs/serve.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Serving on vLLM and SGLang
2
+
3
+ `mindxtrain serve <config.yaml> --to vllm|sglang` launches an OpenAI-compatible server on the
4
+ trained checkpoint, waits until it answers, and can hand it to mindX as the fallback model. It sits
5
+ beside `--to ollama` (merge + `ollama create`) and `--to bankml` (merge + `bankml create`, see
6
+ [bankml.md](bankml.md)). Code: `mindxtrain/deploy/openai_server_push.py`.
7
+
8
+ vLLM and SGLang are reached **only** as a subprocess and over HTTP — neither is imported by
9
+ mindXtrain (clean-room policy). SGLang's presence is checked with `importlib.util.find_spec`,
10
+ which does not import it.
11
+
12
+ ```
13
+ mindxtrain serve run.yaml --to vllm [--tag NAME] [--checkpoint DIR] [--merge] [--host 127.0.0.1]
14
+ [--port N] [--dtype auto] [--server-bin PATH]
15
+ [--server-arg ARG ...] [--ready-timeout 600]
16
+ [--cpu-kvcache-gib 4] [--register-as-fallback]
17
+ mindxtrain serve run.yaml --to sglang ...same options...
18
+ mindxtrain serve run.yaml --to vllm --dry-run # print the argv (and env); run nothing
19
+ mindxtrain serve run.yaml --to vllm --stop # SIGTERM the recorded server, verify it is gone
20
+ ```
21
+
22
+ ## What runs
23
+
24
+ 1. **Checkpoint.** `--checkpoint`, else `out/runs/<run>/quantized/` when the config quantizes and
25
+ that directory exists, else `out/runs/<run>/checkpoint/`.
26
+ 2. **LoRA, native or merged.** A directory with `adapter_config.json` is a LoRA. By default it is
27
+ served **natively over the base** (no merge):
28
+ - vLLM: `--enable-lora --lora-modules <tag>=<adapter> --max-lora-rank R` (R = the adapter's `r`
29
+ rounded up to a vLLM choice: 1, 8, 16, 32, 64, 128, 256, 320, 512). The base is served as
30
+ `<tag>-base`; the adapter is listed on `/v1/models` as `<tag>`, which is the client's `model`.
31
+ - SGLang: `--enable-lora --lora-paths <tag>=<adapter> --max-lora-rank r`. The base is served as
32
+ `<tag>-base`; a client selects the adapter with `model: "<tag>-base:<tag>"`.
33
+
34
+ `--merge` folds the adapter in first (`merge_lora_adapter`, needs `uv sync --extra ml`) and
35
+ serves the merged directory as `<tag>`.
36
+ 3. **argv.** vLLM: `vllm serve <model> --served-model-name … --host --port --dtype
37
+ --max-model-len <serve.max_model_len> --tensor-parallel-size <serve.tensor_parallel>
38
+ [--quantization fp8|mxfp4|gptq]`. SGLang: `python -m sglang.launch_server --model-path …
39
+ --served-model-name … --host --port --dtype --context-length <serve.max_model_len>
40
+ --tp <serve.tensor_parallel>` plus `--device cpu` on CPU or `--mem-fraction-static 0.85` on GPU.
41
+ Anything else goes through `--server-arg`, verbatim (e.g. `--server-arg=--enforce-eager`).
42
+ 4. **Detached.** The server runs in its own session; stdout+stderr go to
43
+ `out/runs/<run>/serve/<to>/server.log`, its pid to `server.pid`, and the argv/env/time to
44
+ `launch.json`. It outlives the CLI.
45
+ 5. **Ready.** `/v1/models` is polled (and, for vLLM, `/health` must be 200) until the expected
46
+ name is listed, the process exits, or `--ready-timeout` passes. On a timeout the server is
47
+ **left running** (big models load slowly) — watch the log or `--stop` it.
48
+ 6. **mindX.** With `--register-as-fallback`, mindX's fallback model is swapped to
49
+ `{provider: "vllm"|"sglang", model: <client model>}` (best-effort, as for Ollama).
50
+
51
+ ## CPU and GPU
52
+
53
+ With no `/dev/kfd` (ROCm) or `/dev/nvidia0` the CPU backends are used: `--dtype auto` becomes
54
+ `bfloat16` (the vLLM CPU guide's recommendation; float16 is unstable or unsupported on CPU), vLLM
55
+ gets `VLLM_CPU_KVCACHE_SPACE=<--cpu-kvcache-gib>` unless the environment already sets it (other
56
+ CPU knobs such as `VLLM_CPU_OMP_THREADS_BIND` pass through from your env), and SGLang gets
57
+ `--device cpu`. A config that needs a GPU is **refused** on such a host, with the reason: an FP8 /
58
+ MXFP4 / GPTQ checkpoint, or `serve.tensor_parallel > 1`. Neither upstream documents LoRA on CPU;
59
+ if your build rejects it, use `--merge`.
60
+
61
+ ## Installing the servers
62
+
63
+ - vLLM: `uv sync --extra serve` (GPU / ROCm). CPU-only per the
64
+ [vLLM CPU guide](https://docs.vllm.ai/en/latest/getting_started/installation/cpu.html), e.g.
65
+ `uv pip install vllm --torch-backend cpu`. Or point `--server-bin` at a `vllm` elsewhere.
66
+ - SGLang is not a mindXtrain extra: install it into the interpreter that will run it
67
+ (`uv pip install sglang`, [docs.sglang.io](https://docs.sglang.io)) and pass that interpreter as
68
+ `--server-bin` if it is not this one.
69
+
70
+ ## Exit codes
71
+
72
+ `0` ready / dry run / stopped / not running · `1` checkpoint missing · `2` refused: server missing,
73
+ GPU needed, already running · `3` merge failed, server exited early, stop failed, error ·
74
+ `4` not ready before `--ready-timeout` (still running).
75
+
76
+ ## Where each flag comes from
77
+
78
+ vLLM: the [`vllm serve` CLI reference](https://docs.vllm.ai/en/latest/cli/serve.html)
79
+ (`--served-model-name`, `--host`, `--port`, `--dtype`, `--max-model-len`, `--tensor-parallel-size`,
80
+ `--quantization`, `--enable-lora`, `--lora-modules`, `--max-lora-rank` and its choices), the
81
+ [LoRA page](https://docs.vllm.ai/en/latest/features/lora.html) (`name=path`, adapters on
82
+ `/v1/models`), the [CPU installation page](https://docs.vllm.ai/en/latest/getting_started/installation/cpu.html)
83
+ (`VLLM_CPU_KVCACHE_SPACE`, bfloat16), and [online serving](https://docs.vllm.ai/en/latest/serving/online_serving/)
84
+ (`/health`, `/v1/models`). SGLang: [Server Arguments](https://docs.sglang.io/advanced_features/server_arguments.html)
85
+ (`--model-path`, `--served-model-name`, `--host`, `--port`, `--dtype`, `--context-length`,
86
+ `--device`, `--tp`, `--mem-fraction-static`, `--enable-lora`, `--lora-paths`, `--max-lora-rank`)
87
+ and the [LoRA page](https://docs.sglang.io/advanced_features/lora.html) (`base:adapter` model
88
+ syntax). Checked against the docs current on 2026-10-02 (`uv.lock` resolves vLLM 0.20.1); no
89
+ server was installed or launched to write this.
llm.txt CHANGED
@@ -88,6 +88,11 @@ Its scores are tagged `<scorer>/bankml-greedy` and are **not comparable** with t
88
  them. Backends the operator knows: `openai_compat`, `ollama`, `vllm`, `bankml` — see `docs/bankml.md`;
89
  a bankml HTTP 400 is a `BankmlRefusal` with its reason, and is never retried with altered parameters.
90
 
 
 
 
 
 
91
  ## The teaching artifacts
92
 
93
  Published beside the weights at `PYTHAI/mindXtrain39`, and mirrored in mindX at
 
88
  them. Backends the operator knows: `openai_compat`, `ollama`, `vllm`, `bankml` — see `docs/bankml.md`;
89
  a bankml HTTP 400 is a `BankmlRefusal` with its reason, and is never retried with altered parameters.
90
 
91
+ Serve targets: `mindxtrain serve run.yaml --to ollama|bankml|vllm|sglang`. `vllm` / `sglang` launch the
92
+ OpenAI-compatible server detached (LoRA native over the base by default, `--merge` to merge; log + pid
93
+ under `out/runs/<run>/serve/<to>/`), return once `/v1/models` lists the tag, `--dry-run` prints the
94
+ argv, `--stop` ends it; GPU-only configs are refused on a CPU host — see `docs/serve.md`.
95
+
96
  ## The teaching artifacts
97
 
98
  Published beside the weights at `PYTHAI/mindXtrain39`, and mirrored in mindX at
mindxtrain/cli/main.py CHANGED
@@ -302,6 +302,98 @@ def quantize(
302
  console.print(f"[green]quantized:[/green] {path}")
303
 
304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  def _serve_bankml(
306
  cfg: XTrainConfig,
307
  checkpoint: Path | None,
@@ -376,15 +468,59 @@ def serve(
376
  checkpoint: Path = typer.Option(None, "--checkpoint", "-c"),
377
  to: str = typer.Option(
378
  "vllm", "--to",
379
- help="Serve target: vllm (default, builds vllm-rocm launch cmd), "
380
- "sglang (builds sglang-rocm launch cmd), "
381
  "ollama (merges LoRA + calls `ollama create`), or "
382
  "bankml (merges LoRA + calls `bankml create`; the verified CPU engine, "
383
  "https://github.com/cryptoAGI/bankml).",
384
  ),
385
  tag: str = typer.Option(
386
  None, "--tag",
387
- help="Model tag for `--to ollama|bankml`. Defaults to run_name when omitted.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  ),
389
  ollama_bin: str = typer.Option(
390
  None, "--ollama-bin",
@@ -402,7 +538,7 @@ def serve(
402
  register_as_fallback: bool = typer.Option(
403
  False, "--register-as-fallback",
404
  help=(
405
- "After --to ollama succeeds, PATCH the new tag into mindX as "
406
  "the local-fallback model (PATCH /v1/config/fallback-model). "
407
  "Best-effort — a failure logs but does NOT fail the push."
408
  ),
@@ -418,8 +554,13 @@ def serve(
418
  ) -> None:
419
  """Serve the trained checkpoint locally.
420
 
421
- `--to vllm` (default) prints a vllm-rocm launch command against the
422
- quantized checkpoint — wire it into your orchestrator.
 
 
 
 
 
423
 
424
  `--to ollama` runs the local-learning loop: merges the LoRA adapter
425
  into the base weights, writes an ollama Modelfile, and calls
@@ -481,23 +622,12 @@ def serve(
481
  console.print(f"[red]unknown serve target:[/red] {to}")
482
  raise typer.Exit(code=2)
483
 
484
- ckpt = checkpoint or Path("./out/runs") / cfg.meta.run_name / "quantized"
485
- if not ckpt.exists():
486
- console.print(f"[red]quantized checkpoint not found:[/red] {ckpt}")
487
- raise typer.Exit(code=1)
488
-
489
- if to == "sglang":
490
- from mindxtrain.deploy.sglang_rocm import build_sglang_command
491
-
492
- cmd = build_sglang_command(cfg.serve, ckpt)
493
- console.print(f"[green]sglang cmd:[/green] {' '.join(cmd)}")
494
- return
495
-
496
- from mindxtrain.deploy.vllm_launcher import build_vllm_command
497
-
498
- cmd = build_vllm_command(cfg.serve, ckpt, cfg.quantize)
499
- console.print(f"[green]vllm cmd:[/green] {' '.join(cmd)}")
500
- # Caller can pipe the cmd into their orchestrator; we don't exec by default.
501
 
502
 
503
  # ---- dataset prep ---------------------------------------------------------
 
302
  console.print(f"[green]quantized:[/green] {path}")
303
 
304
 
305
+ def _serve_openai_server(
306
+ cfg: XTrainConfig,
307
+ flavour: str,
308
+ checkpoint: Path | None,
309
+ *,
310
+ tag: str | None,
311
+ stop: bool,
312
+ dry_run: bool,
313
+ merge: bool,
314
+ host: str,
315
+ port: int | None,
316
+ dtype: str,
317
+ server_bin: str | None,
318
+ server_args: list[str],
319
+ ready_timeout: float,
320
+ cpu_kvcache_gib: int,
321
+ register_as_fallback: bool,
322
+ mindx_base_url: str | None,
323
+ ) -> None:
324
+ """`serve --to vllm|sglang`: launch detached, wait for /v1/models, or `--stop` it."""
325
+ from mindxtrain.deploy.openai_server_push import (
326
+ VLLM_QUANTIZATION,
327
+ launch_openai_server,
328
+ stop_openai_server,
329
+ )
330
+
331
+ fl = "vllm" if flavour == "vllm" else "sglang"
332
+ run_dir = Path("./out/runs") / cfg.meta.run_name
333
+ if stop:
334
+ res = stop_openai_server(fl, run_dir)
335
+ colour = "green" if res.ok else "red"
336
+ console.print(f"[{colour}]{fl} {res.status}[/{colour}] "
337
+ f"{('pid ' + str(res.pid)) if res.pid else ''} {res.reason}".rstrip())
338
+ raise typer.Exit(code=0 if res.ok else 3)
339
+
340
+ quantized = run_dir / "quantized"
341
+ if checkpoint is None:
342
+ use_quant = (cfg.quantize.enabled and cfg.quantize.scheme != "none"
343
+ and quantized.exists())
344
+ checkpoint = quantized if use_quant else run_dir / "checkpoint"
345
+ if not checkpoint.exists():
346
+ console.print(f"[red]checkpoint not found:[/red] {checkpoint}")
347
+ raise typer.Exit(code=1)
348
+ is_adapter = (checkpoint / "adapter_config.json").exists()
349
+ is_quant = checkpoint.resolve() == quantized.resolve() or checkpoint.name == "quantized"
350
+ quant = VLLM_QUANTIZATION.get(cfg.quantize.scheme) if is_quant else None
351
+
352
+ result = launch_openai_server(
353
+ fl,
354
+ base_model=cfg.model.name,
355
+ tag=tag or cfg.meta.run_name,
356
+ run_dir=run_dir,
357
+ adapter_dir=checkpoint if is_adapter else None,
358
+ model_dir=None if is_adapter else checkpoint,
359
+ merge=merge,
360
+ host=host,
361
+ port=port or cfg.serve.port,
362
+ dtype=dtype, # type: ignore[arg-type]
363
+ max_model_len=cfg.serve.max_model_len,
364
+ tensor_parallel=cfg.serve.tensor_parallel,
365
+ quantization=quant,
366
+ cpu_kvcache_gib=cpu_kvcache_gib,
367
+ extra_args=tuple(server_args),
368
+ server_bin=server_bin,
369
+ dry_run=dry_run,
370
+ ready_timeout_s=ready_timeout,
371
+ register_with_mindx=register_as_fallback,
372
+ mindx_base_url=mindx_base_url,
373
+ sink=lambda line: console.print(line, markup=False, highlight=False),
374
+ )
375
+ if result.status == "dry_run":
376
+ console.print(f"[green]{fl} cmd:[/green] {' '.join(result.argv)}",
377
+ highlight=False, soft_wrap=True)
378
+ return
379
+ if not result.ok:
380
+ console.print(f"[red]serve --to {fl} {result.status}:[/red] {result.reason}",
381
+ highlight=False, soft_wrap=True)
382
+ refused = ("refused", "missing", "no_gpu", "already_running")
383
+ raise typer.Exit(code=2 if result.status in refused
384
+ else 4 if result.status == "timeout" else 3)
385
+ console.print(f"[green]{fl} ready:[/green] model {result.client_model!r} at "
386
+ f"{result.base_url}/v1 (pid {result.pid}, log {result.log_path})",
387
+ highlight=False)
388
+ console.print(f"stop it: mindxtrain serve <config.yaml> --to {fl} --stop")
389
+ if result.mindx_fallback_swap:
390
+ console.print(
391
+ f"[green]mindX fallback swapped:[/green] "
392
+ f"{result.mindx_fallback_swap.get('previous', '?')} -> "
393
+ f"{result.mindx_fallback_swap.get('current', '?')}",
394
+ )
395
+
396
+
397
  def _serve_bankml(
398
  cfg: XTrainConfig,
399
  checkpoint: Path | None,
 
468
  checkpoint: Path = typer.Option(None, "--checkpoint", "-c"),
469
  to: str = typer.Option(
470
  "vllm", "--to",
471
+ help="Serve target: vllm (default; launches `vllm serve` detached and waits for "
472
+ "/v1/models), sglang (launches `python -m sglang.launch_server` the same way), "
473
  "ollama (merges LoRA + calls `ollama create`), or "
474
  "bankml (merges LoRA + calls `bankml create`; the verified CPU engine, "
475
  "https://github.com/cryptoAGI/bankml).",
476
  ),
477
  tag: str = typer.Option(
478
  None, "--tag",
479
+ help="Model tag (Ollama/bankml tag; vLLM/SGLang served or LoRA name). "
480
+ "Defaults to run_name when omitted.",
481
+ ),
482
+ dry_run: bool = typer.Option(
483
+ False, "--dry-run",
484
+ help="`--to vllm|sglang`: print the exact launch argv (and env) and do nothing.",
485
+ ),
486
+ stop: bool = typer.Option(
487
+ False, "--stop",
488
+ help="`--to vllm|sglang`: SIGTERM the server recorded in "
489
+ "out/runs/<run>/serve/<to>/server.pid and verify it is gone.",
490
+ ),
491
+ merge: bool = typer.Option(
492
+ False, "--merge",
493
+ help="`--to vllm|sglang`: merge the LoRA into the base first (needs `uv sync --extra ml`) "
494
+ "instead of serving base + adapter natively (the default; no merge).",
495
+ ),
496
+ host: str = typer.Option(
497
+ "127.0.0.1", "--host", help="`--to vllm|sglang`: bind address (loopback by default).",
498
+ ),
499
+ port: int = typer.Option(
500
+ None, "--port", help="`--to vllm|sglang`: port; defaults to serve.port in the config.",
501
+ ),
502
+ dtype: str = typer.Option(
503
+ "auto", "--dtype",
504
+ help="`--to vllm|sglang`: auto|half|float16|bfloat16|float|float32. "
505
+ "auto becomes bfloat16 on a GPU-less host (the CPU backends' recommendation).",
506
+ ),
507
+ server_bin: str = typer.Option(
508
+ None, "--server-bin",
509
+ help="`--to vllm`: the vllm executable; `--to sglang`: a Python interpreter with "
510
+ "sglang installed. Defaults: `vllm` on PATH / this interpreter.",
511
+ ),
512
+ server_arg: list[str] = typer.Option(
513
+ None, "--server-arg",
514
+ help="`--to vllm|sglang`: an extra argument passed verbatim to the server "
515
+ "(repeatable), e.g. --server-arg=--enforce-eager.",
516
+ ),
517
+ ready_timeout: float = typer.Option(
518
+ 600.0, "--ready-timeout",
519
+ help="`--to vllm|sglang`: seconds to wait for /v1/models to list the tag.",
520
+ ),
521
+ cpu_kvcache_gib: int = typer.Option(
522
+ 4, "--cpu-kvcache-gib",
523
+ help="`--to vllm` on CPU: VLLM_CPU_KVCACHE_SPACE in GiB, unless already set in the env.",
524
  ),
525
  ollama_bin: str = typer.Option(
526
  None, "--ollama-bin",
 
538
  register_as_fallback: bool = typer.Option(
539
  False, "--register-as-fallback",
540
  help=(
541
+ "After --to ollama|bankml|vllm|sglang succeeds, PATCH the new tag into mindX as "
542
  "the local-fallback model (PATCH /v1/config/fallback-model). "
543
  "Best-effort — a failure logs but does NOT fail the push."
544
  ),
 
554
  ) -> None:
555
  """Serve the trained checkpoint locally.
556
 
557
+ `--to vllm` (default) / `--to sglang` launch an OpenAI-compatible server
558
+ detached (log + pid under out/runs/<run>/serve/<to>/), serving the LoRA
559
+ natively over the base (or the merged weights with `--merge`, or the
560
+ quantized checkpoint when one exists), wait until `/v1/models` lists the
561
+ tag, and optionally swap mindX's fallback model to it. `--dry-run` prints
562
+ the argv; `--stop` ends the server. A GPU-less host uses the CPU backends;
563
+ a config that needs a GPU is refused with the reason.
564
 
565
  `--to ollama` runs the local-learning loop: merges the LoRA adapter
566
  into the base weights, writes an ollama Modelfile, and calls
 
622
  console.print(f"[red]unknown serve target:[/red] {to}")
623
  raise typer.Exit(code=2)
624
 
625
+ _serve_openai_server(
626
+ cfg, to, checkpoint, tag=tag, stop=stop, dry_run=dry_run, merge=merge, host=host,
627
+ port=port, dtype=dtype, server_bin=server_bin, server_args=server_arg or [],
628
+ ready_timeout=ready_timeout, cpu_kvcache_gib=cpu_kvcache_gib,
629
+ register_as_fallback=register_as_fallback, mindx_base_url=mindx_base_url,
630
+ )
 
 
 
 
 
 
 
 
 
 
 
631
 
632
 
633
  # ---- dataset prep ---------------------------------------------------------
mindxtrain/deploy/openai_server_push.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serve a trained model on vLLM or SGLang — an OpenAI-compatible server, launched and watched.
2
+
3
+ `launch_openai_server` is the vLLM / SGLang twin of `ollama_push.push_to_ollama` and
4
+ `bankml_push.push_to_bankml`: resolve the launcher → build the exact argv → start it detached
5
+ (own session, log file and pid file under the run dir) → poll until the tag answers on
6
+ `/v1/models` (and `/health` for vLLM) → optionally swap mindX's fallback model to it.
7
+ `stop_openai_server` reads the pid file, sends SIGTERM to the server's process group and
8
+ verifies it is gone.
9
+
10
+ Two ways to serve a LoRA, chosen per call:
11
+
12
+ - **native (default — no merge):** the base model plus the adapter, as the server loads it.
13
+ vLLM: `--enable-lora --lora-modules <tag>=<adapter> --max-lora-rank R`; the adapter is listed
14
+ on `/v1/models` under `<tag>`. SGLang: `--enable-lora --lora-paths <tag>=<adapter>
15
+ --max-lora-rank R`; a client selects it as `model: "<served-name>:<tag>"`.
16
+ - **merged (`merge=True`):** `merge_lora_adapter` folds the adapter into the base weights
17
+ (`uv sync --extra ml`) and the merged directory is served under `<tag>`.
18
+
19
+ On a host without a GPU the CPU backends are used: vLLM's CPU build reads
20
+ `VLLM_CPU_KVCACHE_SPACE` (GiB; set here unless the environment already sets it) and wants
21
+ `--dtype bfloat16`; SGLang takes `--device cpu`. A config that needs a GPU (an FP8 / MXFP4 /
22
+ GPTQ checkpoint, or tensor parallel > 1) is refused on a GPU-less host, with the reason.
23
+
24
+ Every flag below is from the upstream server-argument docs (vLLM `vllm serve` CLI reference and
25
+ LoRA / CPU-installation pages; SGLang "Server Arguments" and LoRA pages). Anything else a site
26
+ needs goes through `extra_args`, verbatim — this module does not guess at flags.
27
+
28
+ Clean-room: vLLM and SGLang are reached only as a subprocess and over HTTP. Neither is imported
29
+ here (SGLang's presence is checked with `importlib.util.find_spec`, which does not import it).
30
+
31
+ Every public function returns a result; nothing here raises past `ServerLaunchResult` /
32
+ `ServerStopResult`.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import importlib.util
38
+ import json
39
+ import os
40
+ import shutil
41
+ import signal
42
+ import subprocess
43
+ import sys
44
+ import time
45
+ from collections.abc import Callable
46
+ from dataclasses import dataclass, field
47
+ from datetime import UTC, datetime
48
+ from pathlib import Path
49
+ from typing import Any, Literal
50
+
51
+ import httpx
52
+ from pydantic import BaseModel, ConfigDict, Field
53
+
54
+ Flavour = Literal["vllm", "sglang"]
55
+ Dtype = Literal["auto", "half", "float16", "bfloat16", "float", "float32"]
56
+
57
+ VLLM_INSTALL_HINT = (
58
+ "install vLLM with `uv sync --extra serve` (GPU / ROCm), or CPU-only per "
59
+ "https://docs.vllm.ai/en/latest/getting_started/installation/cpu.html "
60
+ "(e.g. `uv pip install vllm --torch-backend cpu`); or pass --server-bin"
61
+ )
62
+ SGLANG_INSTALL_HINT = (
63
+ "SGLang is not a mindXtrain extra; install it into the interpreter that will run it "
64
+ "(`uv pip install sglang`, see https://docs.sglang.io) or pass --server-bin <python>"
65
+ )
66
+
67
+ # vLLM `--max-lora-rank` choices (vllm serve CLI reference); SGLang takes any int (default 16).
68
+ VLLM_LORA_RANKS: tuple[int, ...] = (1, 8, 16, 32, 64, 128, 256, 320, 512)
69
+
70
+ # `quantize.scheme` → vLLM `--quantization` (as vllm_launcher.build_vllm_command maps it).
71
+ VLLM_QUANTIZATION: dict[str, str] = {"quark_fp8": "fp8", "quark_mxfp4": "mxfp4",
72
+ "gptq_rocm": "gptq"}
73
+
74
+ LaunchStatus = Literal[
75
+ "ready", "dry_run", "refused", "missing", "no_gpu", "merge_failed", "already_running",
76
+ "exited", "timeout", "error",
77
+ ]
78
+ StopStatus = Literal["stopped", "not_running", "still_running", "error"]
79
+
80
+
81
+ class OpenAIServerSpec(BaseModel):
82
+ """What to serve and how. `build_argv` / `build_env` turn it into the exact launch."""
83
+
84
+ model_config = ConfigDict(extra="forbid", frozen=True)
85
+
86
+ flavour: Flavour
87
+ model: str = Field(min_length=1, description="Model dir or HF repo id (the base, for LoRA).")
88
+ tag: str = Field(min_length=1, description="The name clients use (served name or LoRA name).")
89
+ lora_path: str | None = Field(default=None, description="Adapter dir served natively.")
90
+ lora_rank: int | None = Field(default=None, ge=1, description="Adapter rank (`r`).")
91
+ host: str = "127.0.0.1"
92
+ port: int = Field(default=8000, ge=1024, le=65535)
93
+ dtype: Dtype = "auto"
94
+ max_model_len: int = Field(default=8192, ge=512)
95
+ tensor_parallel: int = Field(default=1, ge=1)
96
+ quantization: str | None = None
97
+ cpu: bool = False
98
+ cpu_kvcache_gib: int = Field(default=4, ge=1)
99
+ extra_args: tuple[str, ...] = ()
100
+
101
+ @property
102
+ def served_name(self) -> str:
103
+ """The name the base (or merged) model is served under."""
104
+ return f"{self.tag}-base" if self.lora_path else self.tag
105
+
106
+ @property
107
+ def client_model(self) -> str:
108
+ """What an OpenAI client puts in `model` to reach the tag."""
109
+ if self.lora_path and self.flavour == "sglang":
110
+ return f"{self.served_name}:{self.tag}"
111
+ return self.tag
112
+
113
+ @property
114
+ def base_url(self) -> str:
115
+ return f"http://{self.host}:{self.port}"
116
+
117
+
118
+ def _vllm_rank(r: int) -> int:
119
+ return next((c for c in VLLM_LORA_RANKS if c >= r), VLLM_LORA_RANKS[-1])
120
+
121
+
122
+ def default_launcher(flavour: Flavour) -> list[str]:
123
+ """The launcher prefix assumed when none is resolved (used by dry runs)."""
124
+ if flavour == "vllm":
125
+ return ["vllm"]
126
+ return [sys.executable, "-m", "sglang.launch_server"]
127
+
128
+
129
+ def build_argv(spec: OpenAIServerSpec, launcher: list[str] | None = None) -> list[str]:
130
+ """The exact argv for `spec`. `launcher` is `["vllm"]` or `[python, "-m", "sglang.launch_server"]`."""
131
+ prefix = list(launcher or default_launcher(spec.flavour))
132
+ dtype = "bfloat16" if (spec.cpu and spec.dtype == "auto") else spec.dtype
133
+ if spec.flavour == "vllm":
134
+ argv = [*prefix, "serve", spec.model,
135
+ "--served-model-name", spec.served_name,
136
+ "--host", spec.host, "--port", str(spec.port),
137
+ "--dtype", dtype,
138
+ "--max-model-len", str(spec.max_model_len),
139
+ "--tensor-parallel-size", str(spec.tensor_parallel)]
140
+ if spec.quantization:
141
+ argv += ["--quantization", spec.quantization]
142
+ if spec.lora_path:
143
+ argv += ["--enable-lora", "--lora-modules", f"{spec.tag}={spec.lora_path}",
144
+ "--max-lora-rank", str(_vllm_rank(spec.lora_rank or 16))]
145
+ else:
146
+ argv = [*prefix, "--model-path", spec.model,
147
+ "--served-model-name", spec.served_name,
148
+ "--host", spec.host, "--port", str(spec.port),
149
+ "--dtype", dtype,
150
+ "--context-length", str(spec.max_model_len),
151
+ "--tp", str(spec.tensor_parallel)]
152
+ if spec.cpu:
153
+ argv += ["--device", "cpu"]
154
+ else:
155
+ argv += ["--mem-fraction-static", "0.85"]
156
+ if spec.lora_path:
157
+ argv += ["--enable-lora", "--lora-paths", f"{spec.tag}={spec.lora_path}",
158
+ "--max-lora-rank", str(spec.lora_rank or 16)]
159
+ return [*argv, *spec.extra_args]
160
+
161
+
162
+ def build_env(spec: OpenAIServerSpec, base_env: dict[str, str] | None = None) -> dict[str, str]:
163
+ """Environment variables this launch adds (the CPU backend's), without overriding the caller's."""
164
+ env = dict(os.environ if base_env is None else base_env)
165
+ added: dict[str, str] = {}
166
+ if spec.cpu and spec.flavour == "vllm" and "VLLM_CPU_KVCACHE_SPACE" not in env:
167
+ added["VLLM_CPU_KVCACHE_SPACE"] = str(spec.cpu_kvcache_gib)
168
+ return added
169
+
170
+
171
+ def gpu_refusal(spec: OpenAIServerSpec) -> str | None:
172
+ """None when `spec` can run without a GPU; else why it cannot."""
173
+ if spec.quantization:
174
+ return (f"the checkpoint is {spec.quantization}-quantized, which {spec.flavour} serves "
175
+ "on a GPU only — serve the unquantized checkpoint (--checkpoint .../checkpoint)")
176
+ if spec.tensor_parallel > 1:
177
+ return f"tensor_parallel={spec.tensor_parallel} needs that many GPUs"
178
+ return None
179
+
180
+
181
+ def detect_gpu() -> str | None:
182
+ """A GPU this host exposes (ROCm `/dev/kfd`, NVIDIA `/dev/nvidia0`), or None."""
183
+ for dev, name in (("/dev/kfd", "rocm"), ("/dev/nvidia0", "cuda")):
184
+ if Path(dev).exists():
185
+ return name
186
+ return None
187
+
188
+
189
+ def adapter_rank(adapter_dir: Path) -> int | None:
190
+ """The LoRA rank `r` from `adapter_config.json`, or None."""
191
+ try:
192
+ r = json.loads((Path(adapter_dir) / "adapter_config.json").read_text("utf-8")).get("r")
193
+ except (OSError, ValueError):
194
+ return None
195
+ return int(r) if isinstance(r, int) and r > 0 else None
196
+
197
+
198
+ def resolve_launcher(flavour: Flavour, server_bin: str | None = None) -> tuple[list[str] | None, str]:
199
+ """(launcher argv prefix, "") or (None, reason with the install hint). Never raises.
200
+
201
+ vLLM: `server_bin` or `vllm` on PATH. SGLang: `server_bin` is a Python interpreter that has
202
+ `sglang` (checked in a subprocess), else this interpreter when `find_spec("sglang")` finds it.
203
+ """
204
+ if flavour == "vllm":
205
+ binary = server_bin or shutil.which("vllm")
206
+ if not binary or not (shutil.which(binary) or Path(binary).is_file()):
207
+ return None, f"`vllm` not found on PATH — {VLLM_INSTALL_HINT}"
208
+ return [binary], ""
209
+ if server_bin:
210
+ probe = "import importlib.util,sys; sys.exit(importlib.util.find_spec('sglang') is None)"
211
+ try:
212
+ rc = subprocess.run([server_bin, "-c", probe], capture_output=True, timeout=60,
213
+ check=False).returncode
214
+ except (OSError, subprocess.SubprocessError) as exc:
215
+ return None, f"cannot run {server_bin}: {exc} — {SGLANG_INSTALL_HINT}"
216
+ if rc != 0:
217
+ return None, f"{server_bin} has no `sglang` package — {SGLANG_INSTALL_HINT}"
218
+ return [server_bin, "-m", "sglang.launch_server"], ""
219
+ try:
220
+ found = importlib.util.find_spec("sglang") is not None
221
+ except (ImportError, ValueError):
222
+ found = False
223
+ if not found:
224
+ return None, f"`sglang` is not importable from {sys.executable} — {SGLANG_INSTALL_HINT}"
225
+ return [sys.executable, "-m", "sglang.launch_server"], ""
226
+
227
+
228
+ def server_dir(run_dir: Path, flavour: Flavour) -> Path:
229
+ """Where the log, pid file and launch record live: `<run_dir>/serve/<flavour>/`."""
230
+ return Path(run_dir) / "serve" / flavour
231
+
232
+
233
+ def _alive(pid: int) -> bool:
234
+ try:
235
+ os.kill(pid, 0)
236
+ except ProcessLookupError:
237
+ return False
238
+ except PermissionError:
239
+ return True
240
+ # A zombie still answers kill(0); /proc says whether it is really running.
241
+ try:
242
+ stat = Path(f"/proc/{pid}/stat").read_text()
243
+ return stat.rsplit(")", 1)[1].split()[0] != "Z"
244
+ except (OSError, IndexError):
245
+ return True
246
+
247
+
248
+ def _read_pid(pid_file: Path) -> int | None:
249
+ try:
250
+ return int(pid_file.read_text().strip())
251
+ except (OSError, ValueError):
252
+ return None
253
+
254
+
255
+ def _tail(path: Path, n: int = 2000) -> str:
256
+ try:
257
+ return path.read_text(encoding="utf-8", errors="replace")[-n:]
258
+ except OSError:
259
+ return ""
260
+
261
+
262
+ # ---- results ------------------------------------------------------------------------------
263
+
264
+
265
+ @dataclass(frozen=True)
266
+ class ServerLaunchResult:
267
+ """Outcome of `launch_openai_server`. `ready` (or `dry_run`) is success."""
268
+
269
+ status: LaunchStatus
270
+ flavour: Flavour
271
+ tag: str
272
+ reason: str = ""
273
+ argv: tuple[str, ...] = ()
274
+ env: dict[str, str] = field(default_factory=dict)
275
+ pid: int | None = None
276
+ base_url: str = ""
277
+ client_model: str = ""
278
+ models: tuple[str, ...] = ()
279
+ log_path: Path | None = None
280
+ pid_file: Path | None = None
281
+ merged_dir: Path | None = None
282
+ mindx_fallback_swap: dict[str, str] | None = None
283
+ log: tuple[str, ...] = ()
284
+
285
+ @property
286
+ def ok(self) -> bool:
287
+ return self.status in ("ready", "dry_run")
288
+
289
+
290
+ @dataclass(frozen=True)
291
+ class ServerStopResult:
292
+ status: StopStatus
293
+ flavour: Flavour
294
+ pid: int | None = None
295
+ reason: str = ""
296
+
297
+ @property
298
+ def ok(self) -> bool:
299
+ return self.status in ("stopped", "not_running")
300
+
301
+
302
+ # ---- readiness ----------------------------------------------------------------------------
303
+
304
+
305
+ def wait_ready(
306
+ spec: OpenAIServerSpec,
307
+ *,
308
+ timeout_s: float,
309
+ poll_interval_s: float = 2.0,
310
+ proc: Any = None,
311
+ http_client: httpx.Client | None = None,
312
+ sleep: Callable[[float], None] = time.sleep,
313
+ ) -> tuple[str, tuple[str, ...]]:
314
+ """Poll until `/v1/models` lists the expected id (and vLLM's `/health` is 200).
315
+
316
+ Returns ("ready" | "exited" | "timeout", model ids last seen). The expected id is the tag
317
+ for vLLM (served or LoRA name) and the served name for SGLang.
318
+ """
319
+ expect = spec.tag if spec.flavour == "vllm" else spec.served_name
320
+ client = http_client or httpx.Client(timeout=5.0)
321
+ seen: tuple[str, ...] = ()
322
+ deadline = time.monotonic() + timeout_s
323
+ try:
324
+ while True:
325
+ if proc is not None and proc.poll() is not None:
326
+ return "exited", seen
327
+ try:
328
+ healthy = True
329
+ if spec.flavour == "vllm":
330
+ healthy = client.get(f"{spec.base_url}/health").status_code == 200
331
+ if healthy:
332
+ resp = client.get(f"{spec.base_url}/v1/models")
333
+ if resp.status_code == 200:
334
+ data = resp.json().get("data") or []
335
+ seen = tuple(str(m.get("id")) for m in data if isinstance(m, dict))
336
+ if expect in seen:
337
+ return "ready", seen
338
+ except (httpx.HTTPError, ValueError, AttributeError):
339
+ pass
340
+ if time.monotonic() >= deadline:
341
+ return "timeout", seen
342
+ sleep(poll_interval_s)
343
+ finally:
344
+ if http_client is None:
345
+ client.close()
346
+
347
+
348
+ # ---- launch / stop ------------------------------------------------------------------------
349
+
350
+
351
+ def launch_openai_server(
352
+ flavour: Flavour,
353
+ *,
354
+ base_model: str,
355
+ tag: str,
356
+ run_dir: Path,
357
+ adapter_dir: Path | None = None,
358
+ model_dir: Path | None = None,
359
+ merge: bool = False,
360
+ host: str = "127.0.0.1",
361
+ port: int = 8000,
362
+ dtype: Dtype = "auto",
363
+ max_model_len: int = 8192,
364
+ tensor_parallel: int = 1,
365
+ quantization: str | None = None,
366
+ cpu: bool | None = None,
367
+ cpu_kvcache_gib: int = 4,
368
+ extra_args: tuple[str, ...] | list[str] = (),
369
+ server_bin: str | None = None,
370
+ dry_run: bool = False,
371
+ ready_timeout_s: float = 600.0,
372
+ poll_interval_s: float = 2.0,
373
+ register_with_mindx: bool = False,
374
+ mindx_base_url: str | None = None,
375
+ http_client: httpx.Client | None = None,
376
+ sleep: Callable[[float], None] = time.sleep,
377
+ sink: Callable[[str], None] | None = None,
378
+ ) -> ServerLaunchResult:
379
+ """Launch vLLM / SGLang on a trained checkpoint, detached, and wait for it to answer.
380
+
381
+ Give exactly one of `adapter_dir` (a PEFT LoRA over `base_model`; served natively unless
382
+ `merge`) or `model_dir` (a full model directory — merged or quantized). `cpu=None` decides
383
+ from `detect_gpu()`. `dry_run` builds and returns the argv and touches nothing.
384
+
385
+ The server runs in its own session with stdout+stderr in `<run_dir>/serve/<flavour>/
386
+ server.log` and its pid in `server.pid`; it outlives this call (stop it with
387
+ `stop_openai_server`). On `timeout` it is left running — big models load slowly.
388
+ """
389
+ lines: list[str] = []
390
+
391
+ def emit(line: str) -> None:
392
+ lines.append(line)
393
+ if sink:
394
+ sink(line)
395
+
396
+ def done(status: LaunchStatus, **kw: Any) -> ServerLaunchResult:
397
+ return ServerLaunchResult(status=status, flavour=flavour, tag=tag, log=tuple(lines), **kw)
398
+
399
+ try:
400
+ if (adapter_dir is None) == (model_dir is None):
401
+ return done("error", reason="give exactly one of adapter_dir or model_dir")
402
+ gpu = detect_gpu() if cpu is None else (None if cpu else "given")
403
+ on_cpu = gpu is None
404
+ sdir = server_dir(run_dir, flavour)
405
+ lora = None if (adapter_dir is None or merge) else Path(adapter_dir)
406
+ spec = OpenAIServerSpec(
407
+ flavour=flavour,
408
+ model=base_model if lora else str(model_dir or sdir / "merged"),
409
+ tag=tag, lora_path=str(lora.resolve()) if lora else None,
410
+ lora_rank=adapter_rank(lora) if lora else None,
411
+ host=host, port=port, dtype=dtype, max_model_len=max_model_len,
412
+ tensor_parallel=tensor_parallel,
413
+ quantization=quantization if flavour == "vllm" else None,
414
+ cpu=on_cpu, cpu_kvcache_gib=cpu_kvcache_gib, extra_args=tuple(extra_args),
415
+ )
416
+ needs_gpu = gpu_refusal(spec) if on_cpu else None
417
+ if flavour == "sglang" and quantization and on_cpu:
418
+ needs_gpu = (f"the checkpoint is {quantization}-quantized, which sglang serves on a "
419
+ "GPU only — serve the unquantized checkpoint (--checkpoint .../checkpoint)")
420
+
421
+ if dry_run:
422
+ launcher, why = resolve_launcher(flavour, server_bin)
423
+ argv = build_argv(spec, launcher)
424
+ env = build_env(spec)
425
+ if merge and adapter_dir is not None:
426
+ emit(f"[serve-{flavour}] would merge {adapter_dir} into {sdir / 'merged'} first")
427
+ for note in (why, needs_gpu and f"needs a GPU: {needs_gpu}"):
428
+ if note:
429
+ emit(f"[serve-{flavour}] note: {note}")
430
+ if env:
431
+ emit(f"[serve-{flavour}] env: " + " ".join(f"{k}={v}" for k, v in env.items()))
432
+ return done("dry_run", argv=tuple(argv), env=env, base_url=spec.base_url,
433
+ client_model=spec.client_model, reason=why or (needs_gpu or ""))
434
+
435
+ if needs_gpu:
436
+ return done("no_gpu", reason=f"no GPU on this host and {needs_gpu}")
437
+ launcher, why = resolve_launcher(flavour, server_bin)
438
+ if launcher is None:
439
+ return done("missing", reason=why)
440
+
441
+ pid_file, log_path = sdir / "server.pid", sdir / "server.log"
442
+ old = _read_pid(pid_file)
443
+ if old is not None and _alive(old):
444
+ return done("already_running", pid=old, pid_file=pid_file, log_path=log_path,
445
+ reason=(f"{flavour} already running as pid {old} ({pid_file}); "
446
+ f"stop it first (`serve --to {flavour} --stop`)"))
447
+
448
+ merged: Path | None = None
449
+ if merge and adapter_dir is not None:
450
+ try:
451
+ from mindxtrain.deploy.ollama_push import merge_lora_adapter
452
+
453
+ merged = merge_lora_adapter(base_model, Path(adapter_dir), sdir / "merged",
454
+ sink=emit)
455
+ except ImportError as exc:
456
+ return done("merge_failed", reason=f"{exc} — merging needs `uv sync --extra ml`")
457
+ except Exception as exc: # a merge failure is a result, not a crash
458
+ return done("merge_failed", reason=f"{type(exc).__name__}: {exc}")
459
+ spec = spec.model_copy(update={"model": str(merged)})
460
+ elif model_dir is not None and not Path(model_dir).is_dir():
461
+ return done("error", reason=f"model_dir {model_dir} is not a directory")
462
+
463
+ argv = build_argv(spec, launcher)
464
+ added = build_env(spec)
465
+ sdir.mkdir(parents=True, exist_ok=True)
466
+ emit(f"[serve-{flavour}] $ {' '.join(argv)}")
467
+ with log_path.open("ab") as logf:
468
+ proc = subprocess.Popen(argv, stdout=logf, stderr=subprocess.STDOUT,
469
+ stdin=subprocess.DEVNULL, start_new_session=True,
470
+ env={**os.environ, **added})
471
+ pid_file.write_text(f"{proc.pid}\n", encoding="utf-8")
472
+ (sdir / "launch.json").write_text(json.dumps({
473
+ "flavour": flavour, "tag": tag, "pid": proc.pid, "argv": argv, "env": added,
474
+ "base_url": spec.base_url, "client_model": spec.client_model,
475
+ "started_at": datetime.now(tz=UTC).isoformat(),
476
+ }, indent=1), encoding="utf-8")
477
+ emit(f"[serve-{flavour}] pid {proc.pid}, log {log_path}; waiting for {spec.base_url}")
478
+
479
+ state, models = wait_ready(spec, timeout_s=ready_timeout_s,
480
+ poll_interval_s=poll_interval_s, proc=proc,
481
+ http_client=http_client, sleep=sleep)
482
+ common: dict[str, Any] = dict(argv=tuple(argv), env=added, pid=proc.pid,
483
+ base_url=spec.base_url, client_model=spec.client_model,
484
+ models=models, log_path=log_path, pid_file=pid_file,
485
+ merged_dir=merged)
486
+ if state == "exited":
487
+ pid_file.unlink(missing_ok=True)
488
+ return done("exited", reason=(f"{flavour} exited with code {proc.poll()} before "
489
+ f"answering; log tail:\n{_tail(log_path, 1200)}"),
490
+ **common)
491
+ if state == "timeout":
492
+ return done("timeout", reason=(
493
+ f"{spec.base_url} did not list {spec.client_model!r} within {ready_timeout_s:g}s "
494
+ f"(seen: {', '.join(models) or 'nothing'}); still running as pid {proc.pid} — "
495
+ f"watch {log_path}, or `serve --to {flavour} --stop`"), **common)
496
+
497
+ swap: dict[str, str] | None = None
498
+ if register_with_mindx:
499
+ try:
500
+ from mindxtrain.deploy.api_client import swap_mindx_fallback_model
501
+
502
+ swap = swap_mindx_fallback_model(provider=flavour, model=spec.client_model,
503
+ api_url=mindx_base_url)
504
+ emit(f"[serve-{flavour}] mindX swap: {swap.get('previous', '?')} -> "
505
+ f"{swap.get('current', '?')}")
506
+ except Exception as exc: # best-effort, as push_to_ollama
507
+ emit(f"[serve-{flavour}] mindX registration failed (server still up): {exc}")
508
+ emit(f"[serve-{flavour}] ready: {spec.client_model} at {spec.base_url}/v1")
509
+ common["mindx_fallback_swap"] = swap
510
+ return done("ready", **common)
511
+ except Exception as exc: # never past the result
512
+ return done("error", reason=f"{type(exc).__name__}: {exc}")
513
+
514
+
515
+ def stop_openai_server(
516
+ flavour: Flavour,
517
+ run_dir: Path,
518
+ *,
519
+ timeout_s: float = 30.0,
520
+ poll_interval_s: float = 0.5,
521
+ sleep: Callable[[float], None] = time.sleep,
522
+ ) -> ServerStopResult:
523
+ """SIGTERM the server recorded in `<run_dir>/serve/<flavour>/server.pid` (its whole process
524
+ group — it was started in its own session) and verify it is gone. Never raises."""
525
+ pid_file = server_dir(run_dir, flavour) / "server.pid"
526
+ try:
527
+ pid = _read_pid(pid_file)
528
+ if pid is None:
529
+ return ServerStopResult("not_running", flavour, reason=f"no pid file at {pid_file}")
530
+ if not _alive(pid):
531
+ pid_file.unlink(missing_ok=True)
532
+ return ServerStopResult("not_running", flavour, pid,
533
+ reason=f"pid {pid} was not running (stale pid file removed)")
534
+ try:
535
+ os.killpg(pid, signal.SIGTERM)
536
+ except (ProcessLookupError, PermissionError):
537
+ os.kill(pid, signal.SIGTERM)
538
+ deadline = time.monotonic() + timeout_s
539
+ while _alive(pid):
540
+ if time.monotonic() >= deadline:
541
+ return ServerStopResult("still_running", flavour, pid, reason=(
542
+ f"pid {pid} still alive {timeout_s:g}s after SIGTERM; "
543
+ f"`kill -KILL -{pid}` ends its group"))
544
+ sleep(poll_interval_s)
545
+ pid_file.unlink(missing_ok=True)
546
+ return ServerStopResult("stopped", flavour, pid)
547
+ except Exception as exc:
548
+ return ServerStopResult("error", flavour, reason=f"{type(exc).__name__}: {exc}")
549
+
550
+
551
+ __all__ = [
552
+ "VLLM_LORA_RANKS",
553
+ "VLLM_QUANTIZATION",
554
+ "OpenAIServerSpec",
555
+ "ServerLaunchResult",
556
+ "ServerStopResult",
557
+ "adapter_rank",
558
+ "build_argv",
559
+ "build_env",
560
+ "default_launcher",
561
+ "detect_gpu",
562
+ "gpu_refusal",
563
+ "launch_openai_server",
564
+ "resolve_launcher",
565
+ "server_dir",
566
+ "stop_openai_server",
567
+ "wait_ready",
568
+ ]
mindxtrain/ui/app.py CHANGED
@@ -241,7 +241,7 @@ def build() -> gr.Blocks:
241
  with gr.Row():
242
  s_cfg = gr.Textbox(value="run.yaml", label="config", scale=2)
243
  s_ckpt = gr.Textbox(value="", label="checkpoint", scale=2)
244
- s_to = gr.Radio(["ollama", "bankml", "vllm"], value="ollama", label="to", scale=1)
245
  s_tag = gr.Textbox(value="", label="tag", scale=1)
246
  s_btn = gr.Button("serve", variant="primary", scale=1)
247
  with gr.Group(visible=False) as adv_serve:
 
241
  with gr.Row():
242
  s_cfg = gr.Textbox(value="run.yaml", label="config", scale=2)
243
  s_ckpt = gr.Textbox(value="", label="checkpoint", scale=2)
244
+ s_to = gr.Radio(["ollama", "bankml", "vllm", "sglang"], value="ollama", label="to", scale=1)
245
  s_tag = gr.Textbox(value="", label="tag", scale=1)
246
  s_btn = gr.Button("serve", variant="primary", scale=1)
247
  with gr.Group(visible=False) as adv_serve:
tests/test_cli_smoke.py CHANGED
@@ -100,7 +100,7 @@ def test_receipt_detects_checkpoint_tamper(tmp_path, monkeypatch):
100
  assert result.exit_code == 2, result.stdout
101
 
102
 
103
- def test_serve_to_sglang_prints_command(tmp_path, monkeypatch):
104
  from mindxtrain.config.loader import load_config, render_recipe
105
 
106
  monkeypatch.chdir(tmp_path)
@@ -110,7 +110,7 @@ def test_serve_to_sglang_prints_command(tmp_path, monkeypatch):
110
  quant = tmp_path / "out" / "runs" / cfg.meta.run_name / "quantized"
111
  quant.mkdir(parents=True)
112
 
113
- result = runner.invoke(app, ["serve", str(recipe), "--to", "sglang"])
114
  assert result.exit_code == 0, result.stdout
115
  assert "sglang cmd" in result.stdout
116
  assert "sglang.launch_server" in result.stdout
 
100
  assert result.exit_code == 2, result.stdout
101
 
102
 
103
+ def test_serve_to_sglang_dry_run_prints_command(tmp_path, monkeypatch):
104
  from mindxtrain.config.loader import load_config, render_recipe
105
 
106
  monkeypatch.chdir(tmp_path)
 
110
  quant = tmp_path / "out" / "runs" / cfg.meta.run_name / "quantized"
111
  quant.mkdir(parents=True)
112
 
113
+ result = runner.invoke(app, ["serve", str(recipe), "--to", "sglang", "--dry-run"])
114
  assert result.exit_code == 0, result.stdout
115
  assert "sglang cmd" in result.stdout
116
  assert "sglang.launch_server" in result.stdout
tests/test_openai_server_push.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """launch_openai_server / stop_openai_server: argv, readiness, refusals, stop — no real server.
2
+
3
+ subprocess.Popen, shutil.which and the GPU probe are monkeypatched; readiness is answered by an
4
+ httpx MockTransport. Nothing here installs or imports vLLM or SGLang.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import signal
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import httpx
16
+ import pytest
17
+ from typer.testing import CliRunner
18
+
19
+ from mindxtrain.deploy import openai_server_push as OS
20
+
21
+
22
+ class FakeProc:
23
+ def __init__(self, pid: int = 4242, exit_code: int | None = None) -> None:
24
+ self.pid = pid
25
+ self._exit = exit_code
26
+
27
+ def poll(self) -> int | None:
28
+ return self._exit
29
+
30
+
31
+ class PopenRecorder:
32
+ def __init__(self, exit_code: int | None = None) -> None:
33
+ self.calls: list[dict[str, Any]] = []
34
+ self.exit_code = exit_code
35
+
36
+ def __call__(self, argv: list[str], **kw: Any) -> FakeProc:
37
+ self.calls.append({"argv": argv, **kw})
38
+ return FakeProc(exit_code=self.exit_code)
39
+
40
+
41
+ def _client(models: list[str], *, health: int = 200, seen: list[str] | None = None) -> httpx.Client:
42
+ def handler(req: httpx.Request) -> httpx.Response:
43
+ if seen is not None:
44
+ seen.append(req.url.path)
45
+ if req.url.path == "/health":
46
+ return httpx.Response(health)
47
+ if req.url.path == "/v1/models":
48
+ return httpx.Response(200, json={"object": "list",
49
+ "data": [{"id": m} for m in models]})
50
+ return httpx.Response(404)
51
+
52
+ return httpx.Client(transport=httpx.MockTransport(handler))
53
+
54
+
55
+ def _adapter(tmp: Path, r: int = 8) -> Path:
56
+ d = tmp / "out" / "runs" / "run" / "checkpoint"
57
+ d.mkdir(parents=True)
58
+ (d / "adapter_config.json").write_text(json.dumps({"r": r}))
59
+ return d
60
+
61
+
62
+ @pytest.fixture
63
+ def env(monkeypatch: pytest.MonkeyPatch) -> PopenRecorder:
64
+ rec = PopenRecorder()
65
+ monkeypatch.setattr(OS.subprocess, "Popen", rec)
66
+ monkeypatch.setattr(OS.shutil, "which", lambda name: f"/usr/bin/{name}")
67
+ monkeypatch.setattr(OS, "detect_gpu", lambda: None)
68
+ monkeypatch.delenv("VLLM_CPU_KVCACHE_SPACE", raising=False)
69
+ return rec
70
+
71
+
72
+ def _launch(tmp: Path, flavour: OS.Flavour = "vllm", **kw: Any) -> OS.ServerLaunchResult:
73
+ adapter = kw.pop("adapter_dir", None) or _adapter(tmp, kw.pop("rank", 8))
74
+ base: dict[str, Any] = dict(base_model="HuggingFaceTB/SmolLM2-135M", tag="mindx-gen9",
75
+ run_dir=adapter.parent, adapter_dir=adapter, port=8123,
76
+ ready_timeout_s=1.0, poll_interval_s=0.0, sleep=lambda _s: None)
77
+ base.update(kw)
78
+ return OS.launch_openai_server(flavour, **base)
79
+
80
+
81
+ # ---- argv ----------------------------------------------------------------------------------
82
+
83
+
84
+ def test_vllm_native_lora_argv_on_cpu(tmp_path: Path, env: PopenRecorder) -> None:
85
+ res = _launch(tmp_path, rank=24, http_client=_client(["mindx-gen9-base", "mindx-gen9"]))
86
+ assert res.status == "ready", res.reason
87
+ argv = env.calls[0]["argv"]
88
+ assert argv[:3] == ["/usr/bin/vllm", "serve", "HuggingFaceTB/SmolLM2-135M"]
89
+ s = " ".join(argv)
90
+ assert "--served-model-name mindx-gen9-base" in s
91
+ assert "--host 127.0.0.1 --port 8123" in s
92
+ assert "--dtype bfloat16" in s # auto → bfloat16 on CPU
93
+ assert "--max-model-len 8192" in s
94
+ assert "--enable-lora --lora-modules mindx-gen9=" in s
95
+ assert argv[argv.index("--max-lora-rank") + 1] == "32" # 24 rounded up to a vLLM choice
96
+ assert env.calls[0]["start_new_session"] is True
97
+ assert env.calls[0]["env"]["VLLM_CPU_KVCACHE_SPACE"] == "4"
98
+ assert res.env == {"VLLM_CPU_KVCACHE_SPACE": "4"}
99
+ assert res.client_model == "mindx-gen9"
100
+ assert res.pid_file is not None and res.pid_file.read_text().strip() == "4242"
101
+ launch = json.loads((res.pid_file.parent / "launch.json").read_text())
102
+ assert launch["argv"] == argv
103
+
104
+
105
+ def test_sglang_native_lora_argv_on_cpu(tmp_path: Path, env: PopenRecorder,
106
+ monkeypatch: pytest.MonkeyPatch) -> None:
107
+ monkeypatch.setattr(OS.importlib.util, "find_spec", lambda name: object())
108
+ res = _launch(tmp_path, "sglang", http_client=_client(["mindx-gen9-base"]))
109
+ assert res.status == "ready", res.reason
110
+ argv = env.calls[0]["argv"]
111
+ assert argv[1:3] == ["-m", "sglang.launch_server"]
112
+ s = " ".join(argv)
113
+ assert "--model-path HuggingFaceTB/SmolLM2-135M" in s
114
+ assert "--context-length 8192" in s and "--tp 1" in s
115
+ assert "--device cpu" in s and "--mem-fraction-static" not in s
116
+ assert "--enable-lora --lora-paths mindx-gen9=" in s
117
+ assert argv[argv.index("--max-lora-rank") + 1] == "8"
118
+ assert res.client_model == "mindx-gen9-base:mindx-gen9"
119
+ assert res.env == {}
120
+
121
+
122
+ def test_extra_args_and_gpu_quantized_full_model(tmp_path: Path, env: PopenRecorder,
123
+ monkeypatch: pytest.MonkeyPatch) -> None:
124
+ monkeypatch.setattr(OS, "detect_gpu", lambda: "rocm")
125
+ qdir = tmp_path / "quantized"
126
+ qdir.mkdir()
127
+ res = OS.launch_openai_server(
128
+ "vllm", base_model="Qwen/Qwen3-8B", tag="q8", run_dir=tmp_path, model_dir=qdir,
129
+ quantization="fp8", extra_args=["--enforce-eager"], ready_timeout_s=1.0,
130
+ poll_interval_s=0.0, sleep=lambda _s: None, http_client=_client(["q8"]))
131
+ assert res.status == "ready", res.reason
132
+ argv = env.calls[0]["argv"]
133
+ assert argv[2] == str(qdir) and "--enable-lora" not in argv
134
+ assert argv[argv.index("--quantization") + 1] == "fp8"
135
+ assert argv[argv.index("--dtype") + 1] == "auto"
136
+ assert argv[-1] == "--enforce-eager"
137
+ assert res.env == {} # no CPU env on a GPU host
138
+
139
+
140
+ # ---- readiness ---------------------------------------------------------------------------
141
+
142
+
143
+ def test_ready_polls_health_and_models_and_swaps_mindx(tmp_path: Path, env: PopenRecorder,
144
+ monkeypatch: pytest.MonkeyPatch) -> None:
145
+ from mindxtrain.deploy import api_client
146
+
147
+ swapped: dict[str, Any] = {}
148
+
149
+ def fake_swap(**kw: Any) -> dict[str, str]:
150
+ swapped.update(kw)
151
+ return {"previous": "old", "current": kw["model"]}
152
+
153
+ monkeypatch.setattr(api_client, "swap_mindx_fallback_model", fake_swap)
154
+ paths: list[str] = []
155
+ res = _launch(tmp_path, http_client=_client(["mindx-gen9"], seen=paths),
156
+ register_with_mindx=True, mindx_base_url="http://mindx.test")
157
+ assert res.status == "ready"
158
+ assert paths[:2] == ["/health", "/v1/models"]
159
+ assert swapped == {"provider": "vllm", "model": "mindx-gen9", "api_url": "http://mindx.test"}
160
+ assert res.mindx_fallback_swap == {"previous": "old", "current": "mindx-gen9"}
161
+
162
+
163
+ def test_timeout_leaves_server_running(tmp_path: Path, env: PopenRecorder) -> None:
164
+ res = _launch(tmp_path, ready_timeout_s=0.0, http_client=_client(["something-else"]))
165
+ assert res.status == "timeout"
166
+ assert "something-else" in res.reason and "--stop" in res.reason
167
+ assert res.pid == 4242 and res.pid_file is not None and res.pid_file.exists()
168
+
169
+
170
+ def test_unhealthy_vllm_never_ready(tmp_path: Path, env: PopenRecorder) -> None:
171
+ res = _launch(tmp_path, ready_timeout_s=0.0, http_client=_client(["mindx-gen9"], health=503))
172
+ assert res.status == "timeout"
173
+
174
+
175
+ def test_exited_early_reports_log_tail(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
176
+ env: PopenRecorder) -> None:
177
+ env.exit_code = 1
178
+ res = _launch(tmp_path, http_client=_client([]))
179
+ assert res.status == "exited" and "code 1" in res.reason
180
+ assert res.pid_file is not None and not res.pid_file.exists()
181
+
182
+
183
+ # ---- refusals ------------------------------------------------------------------------------
184
+
185
+
186
+ def test_missing_vllm_binary(tmp_path: Path, env: PopenRecorder,
187
+ monkeypatch: pytest.MonkeyPatch) -> None:
188
+ monkeypatch.setattr(OS.shutil, "which", lambda name: None)
189
+ res = _launch(tmp_path)
190
+ assert res.status == "missing" and not res.ok
191
+ assert "uv sync --extra serve" in res.reason
192
+ assert env.calls == []
193
+
194
+
195
+ def test_missing_sglang(tmp_path: Path, env: PopenRecorder,
196
+ monkeypatch: pytest.MonkeyPatch) -> None:
197
+ monkeypatch.setattr(OS.importlib.util, "find_spec", lambda name: None)
198
+ res = _launch(tmp_path, "sglang")
199
+ assert res.status == "missing" and "uv pip install sglang" in res.reason
200
+ assert env.calls == []
201
+
202
+
203
+ def test_gpu_config_refused_without_gpu(tmp_path: Path, env: PopenRecorder) -> None:
204
+ qdir = tmp_path / "quantized"
205
+ qdir.mkdir()
206
+ for flavour in ("vllm", "sglang"):
207
+ res = OS.launch_openai_server(flavour, base_model="b", tag="t", run_dir=tmp_path, # type: ignore[arg-type]
208
+ model_dir=qdir, quantization="fp8")
209
+ assert res.status == "no_gpu" and "GPU" in res.reason
210
+ tp = _launch(tmp_path, tensor_parallel=2)
211
+ assert tp.status == "no_gpu" and "tensor_parallel=2" in tp.reason
212
+ assert env.calls == []
213
+
214
+
215
+ def test_already_running(tmp_path: Path, env: PopenRecorder) -> None:
216
+ adapter = _adapter(tmp_path)
217
+ sdir = OS.server_dir(adapter.parent, "vllm")
218
+ sdir.mkdir(parents=True)
219
+ (sdir / "server.pid").write_text(str(os.getpid()))
220
+ res = _launch(tmp_path, adapter_dir=adapter)
221
+ assert res.status == "already_running" and res.pid == os.getpid()
222
+ assert env.calls == []
223
+
224
+
225
+ def test_merge_failure_is_a_result(tmp_path: Path, env: PopenRecorder,
226
+ monkeypatch: pytest.MonkeyPatch) -> None:
227
+ from mindxtrain.deploy import ollama_push
228
+
229
+ def boom(*_a: Any, **_k: Any) -> Path:
230
+ raise ImportError("needs peft")
231
+
232
+ monkeypatch.setattr(ollama_push, "merge_lora_adapter", boom)
233
+ res = _launch(tmp_path, merge=True)
234
+ assert res.status == "merge_failed" and "uv sync --extra ml" in res.reason
235
+
236
+
237
+ def test_merge_serves_merged_dir(tmp_path: Path, env: PopenRecorder,
238
+ monkeypatch: pytest.MonkeyPatch) -> None:
239
+ from mindxtrain.deploy import ollama_push
240
+
241
+ def fake_merge(base: str, adapter: Path, out: Path, **_k: Any) -> Path:
242
+ out.mkdir(parents=True)
243
+ return out
244
+
245
+ monkeypatch.setattr(ollama_push, "merge_lora_adapter", fake_merge)
246
+ res = _launch(tmp_path, merge=True, http_client=_client(["mindx-gen9"]))
247
+ assert res.status == "ready", res.reason
248
+ argv = env.calls[0]["argv"]
249
+ assert argv[2].endswith("serve/vllm/merged") and "--enable-lora" not in argv
250
+ assert argv[argv.index("--served-model-name") + 1] == "mindx-gen9"
251
+
252
+
253
+ def test_bad_inputs_never_raise(tmp_path: Path, env: PopenRecorder) -> None:
254
+ res = OS.launch_openai_server("vllm", base_model="b", tag="t", run_dir=tmp_path)
255
+ assert res.status == "error"
256
+ res = OS.launch_openai_server("vllm", base_model="b", tag="t", run_dir=tmp_path,
257
+ model_dir=tmp_path / "nope", ready_timeout_s=0.0)
258
+ assert res.status == "error" and "not a directory" in res.reason
259
+
260
+
261
+ # ---- dry run ---------------------------------------------------------------------------------
262
+
263
+
264
+ def test_dry_run_builds_argv_and_does_nothing(tmp_path: Path, env: PopenRecorder,
265
+ monkeypatch: pytest.MonkeyPatch) -> None:
266
+ monkeypatch.setattr(OS.shutil, "which", lambda name: None) # even with no vllm installed
267
+ res = _launch(tmp_path, dry_run=True)
268
+ assert res.status == "dry_run" and res.ok
269
+ assert res.argv[:2] == ("vllm", "serve")
270
+ assert "uv sync --extra serve" in res.reason
271
+ assert env.calls == []
272
+ assert not (tmp_path / "out" / "runs" / "run" / "serve").exists()
273
+
274
+
275
+ # ---- stop ------------------------------------------------------------------------------------
276
+
277
+
278
+ def _pidfile(tmp_path: Path, pid: int) -> Path:
279
+ sdir = OS.server_dir(tmp_path, "vllm")
280
+ sdir.mkdir(parents=True)
281
+ (sdir / "server.pid").write_text(f"{pid}\n")
282
+ return sdir / "server.pid"
283
+
284
+
285
+ def test_stop_sigterms_group_and_verifies(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
286
+ pf = _pidfile(tmp_path, 777)
287
+ alive = {"v": True}
288
+ sent: list[tuple[int, int]] = []
289
+
290
+ def killpg(pid: int, sig: int) -> None:
291
+ sent.append((pid, sig))
292
+ alive["v"] = False
293
+
294
+ monkeypatch.setattr(OS, "_alive", lambda pid: alive["v"])
295
+ monkeypatch.setattr(OS.os, "killpg", killpg)
296
+ res = OS.stop_openai_server("vllm", tmp_path, sleep=lambda _s: None)
297
+ assert res.status == "stopped" and res.pid == 777
298
+ assert sent == [(777, signal.SIGTERM)]
299
+ assert not pf.exists()
300
+
301
+
302
+ def test_stop_still_running(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
303
+ pf = _pidfile(tmp_path, 778)
304
+ monkeypatch.setattr(OS, "_alive", lambda pid: True)
305
+ monkeypatch.setattr(OS.os, "killpg", lambda pid, sig: None)
306
+ res = OS.stop_openai_server("vllm", tmp_path, timeout_s=0.0, sleep=lambda _s: None)
307
+ assert res.status == "still_running" and not res.ok
308
+ assert pf.exists()
309
+
310
+
311
+ def test_stop_without_pidfile_or_stale(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
312
+ assert OS.stop_openai_server("sglang", tmp_path).status == "not_running"
313
+ pf = _pidfile(tmp_path, 779)
314
+ monkeypatch.setattr(OS, "_alive", lambda pid: False)
315
+ res = OS.stop_openai_server("vllm", tmp_path)
316
+ assert res.status == "not_running" and not pf.exists()
317
+
318
+
319
+ # ---- CLI -------------------------------------------------------------------------------------
320
+
321
+
322
+ def _recipe(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:
323
+ from mindxtrain.config.loader import load_config, render_recipe
324
+
325
+ monkeypatch.chdir(tmp_path)
326
+ recipe = tmp_path / "run.yaml"
327
+ recipe.write_text(render_recipe("qwen3_8b_sft_lora"))
328
+ run_dir = tmp_path / "out" / "runs" / load_config(recipe).meta.run_name
329
+ ckpt = run_dir / "checkpoint"
330
+ ckpt.mkdir(parents=True)
331
+ (ckpt / "adapter_config.json").write_text(json.dumps({"r": 16}))
332
+ return recipe, run_dir
333
+
334
+
335
+ def test_cli_dry_run_vllm_prefers_adapter_without_quantized(
336
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: PopenRecorder) -> None:
337
+ from mindxtrain.cli.main import app
338
+
339
+ recipe, _ = _recipe(tmp_path, monkeypatch)
340
+ out = CliRunner().invoke(app, ["serve", str(recipe), "--to", "vllm", "--dry-run",
341
+ "--tag", "t1", "--port", "8124"])
342
+ assert out.exit_code == 0, out.stdout
343
+ assert "vllm cmd" in out.stdout and "--lora-modules" in out.stdout
344
+ assert "--port 8124" in out.stdout
345
+ assert env.calls == []
346
+
347
+
348
+ def test_cli_missing_binary_exits_2(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
349
+ env: PopenRecorder) -> None:
350
+ from mindxtrain.cli.main import app
351
+
352
+ monkeypatch.setattr(OS.shutil, "which", lambda name: None)
353
+ recipe, _ = _recipe(tmp_path, monkeypatch)
354
+ out = CliRunner().invoke(app, ["serve", str(recipe), "--to", "vllm"])
355
+ assert out.exit_code == 2, out.stdout
356
+ assert "missing" in out.stdout and "uv sync --extra serve" in out.stdout
357
+
358
+
359
+ def test_cli_stop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
360
+ from mindxtrain.cli.main import app
361
+
362
+ recipe, _ = _recipe(tmp_path, monkeypatch)
363
+ out = CliRunner().invoke(app, ["serve", str(recipe), "--to", "sglang", "--stop"])
364
+ assert out.exit_code == 0, out.stdout
365
+ assert "not_running" in out.stdout