cmvr-visual/inference/llm_services/runner.py

290 lines
14 KiB
Python
Raw Normal View History

"""One job, short-lived model processes; heavy libraries are imported only in stages.
Public entry point: python -m llm_services.runner --request job.json --result result.json
The worker owns the global queue/lock and the outer Linux process group.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
WORKSPACE = Path("/workspace")
TASKS = {"image.generate", "video.generate", "defect.generate", "audio.transcribe"}
def confined_path(value: Any, workspace: Path = WORKSPACE, *, exists: bool = False) -> Path:
if not isinstance(value, (str, Path)) or not str(value):
raise ValueError("A nonempty absolute local path is required")
candidate = Path(value)
if not candidate.is_absolute():
raise ValueError("Relative paths are not accepted")
root = workspace.resolve()
resolved = candidate.resolve()
if not resolved.is_relative_to(root):
raise ValueError("Path is outside /workspace")
if exists and not resolved.is_file():
raise ValueError("Input file does not exist or is not a regular file")
return resolved
def _integer(value: Any, name: str, minimum: int, maximum: int, multiple: int = 1) -> int:
if type(value) is not int or not minimum <= value <= maximum or value % multiple:
raise ValueError(f"{name} must be an integer in [{minimum}, {maximum}], multiple of {multiple}")
return value
def _number(value: Any, name: str, minimum: float, maximum: float) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{name} must be a finite number")
if not math.isfinite(value) or not minimum <= value <= maximum:
raise ValueError(f"{name} must be in [{minimum}, {maximum}]")
return float(value)
def validate_request(payload: Any, *, workspace: Path = WORKSPACE) -> dict[str, Any]:
if not isinstance(payload, dict) or not isinstance(payload.get("task_type"), str) or payload["task_type"] not in TASKS:
raise ValueError("Unsupported task_type")
task = payload["task_type"]
inputs, params = payload.get("input", {}), payload.get("parameters", {})
if not isinstance(inputs, dict) or not isinstance(params, dict):
raise ValueError("input and parameters must be objects")
output = confined_path(payload.get("output_dir"), workspace)
if not output.is_relative_to(workspace.resolve() / "outputs"):
raise ValueError("output_dir must be inside /workspace/outputs")
allowed_inputs = {"prompt", "negative_prompt"}
if task in {"video.generate", "defect.generate"}:
allowed_inputs.add("image_path")
if task == "audio.transcribe":
allowed_inputs = {"audio_path"}
if set(inputs) - allowed_inputs:
raise ValueError("Unknown input field")
inputs = dict(inputs)
if task != "audio.transcribe":
if not isinstance(inputs.get("prompt"), str) or not inputs["prompt"].strip():
raise ValueError("input.prompt is required")
if len(inputs["prompt"]) > 8000:
raise ValueError("prompt is too long")
negative = inputs.get("negative_prompt", "")
if not isinstance(negative, str) or len(negative) > 8000:
raise ValueError("negative_prompt must be a string of at most 8000 characters")
inputs["negative_prompt"] = negative
for name in ("image_path", "audio_path"):
if name in inputs:
inputs[name] = str(confined_path(inputs[name], workspace, exists=True))
required = "audio_path" if task == "audio.transcribe" else "image_path" if task == "defect.generate" else None
if required and required not in inputs:
raise ValueError(f"input.{required} is required")
if task == "audio.transcribe":
allowed = {"language", "max_audio_seconds"}
normalized = {"language": params.get("language", "zh"),
"max_audio_seconds": params.get("max_audio_seconds", 1800)}
# Whisper language tokens must never contain arbitrary prompt/control text.
language = normalized["language"]
if not isinstance(language, str) or language not in {
"zh", "en", "ja", "ko", "de", "fr", "es", "ru", "ar", "pt", "it", "auto"
}:
raise ValueError("Unsupported Whisper language; use a supported ISO code or auto")
_integer(normalized["max_audio_seconds"], "max_audio_seconds", 1, 1800)
else:
allowed = {"width", "height", "num_inference_steps", "seed", "guidance_scale", "negative_prompt"}
is_video = task == "video.generate"
normalized = {
"width": params.get("width", 1280 if is_video else 1024),
"height": params.get("height", 704 if is_video else 1024),
"num_inference_steps": params.get("num_inference_steps", 50),
"seed": params.get("seed", 42),
"guidance_scale": params.get("guidance_scale", 5.0 if is_video else 4.0 if task == "image.generate" else 7.5),
}
for key in ("width", "height"):
_integer(normalized[key], key, 256, 1280 if is_video else 2048, 32 if is_video else 16)
if normalized["width"] * normalized["height"] > (1280 * 704 if is_video else 2048 * 2048):
raise ValueError("Requested pixel area exceeds the service limit")
_integer(normalized["num_inference_steps"], "num_inference_steps", 1, 100)
_integer(normalized["seed"], "seed", 0, 2**32 - 1)
normalized["guidance_scale"] = _number(normalized["guidance_scale"], "guidance_scale", 1, 20)
if "negative_prompt" in params:
if not isinstance(params["negative_prompt"], str) or len(params["negative_prompt"]) > 8000:
raise ValueError("negative_prompt must be a bounded string")
inputs["negative_prompt"] = params["negative_prompt"]
if is_video:
allowed |= {"num_frames", "fps", "upscale", "upscale_width", "upscale_height", "tile_size"}
normalized.update(num_frames=params.get("num_frames", 121), fps=params.get("fps", 24),
upscale=params.get("upscale", True), upscale_width=params.get("upscale_width", 1920),
upscale_height=params.get("upscale_height", 1080), tile_size=params.get("tile_size", 128))
_integer(normalized["num_frames"], "num_frames", 5, 121)
if normalized["num_frames"] % 4 != 1:
raise ValueError("Wan num_frames must be 4n+1; long clips require a separate workflow")
if type(normalized["fps"]) is not int or normalized["fps"] != 24:
raise ValueError("This Wan checkpoint is served at 24fps")
if type(normalized["upscale"]) is not bool:
raise ValueError("upscale must be a boolean")
_integer(normalized["upscale_width"], "upscale_width", 256, 3840, 2)
_integer(normalized["upscale_height"], "upscale_height", 256, 2160, 2)
_integer(normalized["tile_size"], "tile_size", 64, 256, 16)
if task == "defect.generate":
allowed |= {"controlnet_conditioning_scale", "canny_low", "canny_high"}
normalized.update(controlnet_conditioning_scale=params.get("controlnet_conditioning_scale", 0.8),
canny_low=params.get("canny_low", 100), canny_high=params.get("canny_high", 200))
normalized["controlnet_conditioning_scale"] = _number(
normalized["controlnet_conditioning_scale"], "controlnet_conditioning_scale", 0, 2)
_integer(normalized["canny_low"], "canny_low", 0, 255)
_integer(normalized["canny_high"], "canny_high", 0, 255)
if normalized["canny_low"] >= normalized["canny_high"]:
raise ValueError("canny_low must be below canny_high")
if set(params) - allowed:
raise ValueError("Unknown task parameter(s): " + ", ".join(sorted(set(params) - allowed)))
return {"task_type": task, "input": inputs, "parameters": normalized, "output_dir": str(output)}
def stage_plan(request: dict[str, Any]) -> list[str]:
return ["model", "upscale"] if request["task_type"] == "video.generate" and request["parameters"]["upscale"] else ["model"]
def build_result(output_dir: Path, paths: list[Path], metadata: dict[str, Any]) -> dict[str, Any]:
output_dir = output_dir.resolve()
outputs = []
for path in paths:
resolved = Path(path).resolve()
if not resolved.is_relative_to(output_dir) or not resolved.is_file() or resolved.stat().st_size == 0:
raise ValueError("Adapter returned a missing, empty or out-of-job output")
outputs.append({"path": resolved.relative_to(output_dir).as_posix()})
if not outputs:
raise ValueError("Adapter produced no files")
return {"outputs": outputs, "metadata": metadata}
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + f".{os.getpid()}.tmp")
temporary.write_text(json.dumps(payload, ensure_ascii=False, allow_nan=False, indent=2), encoding="utf-8")
temporary.replace(path)
def _run_child(command: list[str], env: dict[str, str], log: Path, timeout: float) -> None:
"""Keep children in the worker's process group; clean up engine descendants.
psutil identities prevent PID reuse from targeting an unrelated process. The
external worker additionally kills the whole job group on cancel/timeout.
"""
import psutil
tracked: dict[int, Any] = {}
child = None
previous_handlers = {}
def cancel(signum, _frame):
raise InterruptedError(f"Runner received signal {signum}")
for signum in (signal.SIGTERM, signal.SIGINT):
previous_handlers[signum] = signal.signal(signum, cancel)
try:
with log.open("ab", buffering=0) as stream:
child = subprocess.Popen(command, env=env, stdout=stream, stderr=subprocess.STDOUT)
process = psutil.Process(child.pid)
tracked[child.pid] = process
started = time.monotonic()
while child.poll() is None:
try:
for descendant in process.children(recursive=True):
tracked[descendant.pid] = descendant
except psutil.NoSuchProcess:
pass
if time.monotonic() - started > timeout:
raise TimeoutError("Model stage exceeded its time budget")
time.sleep(0.2)
if child.returncode:
raise RuntimeError(f"Model stage exited with code {child.returncode}; see {log.name}")
finally:
live = []
for process in reversed(list(tracked.values())):
try:
if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
process.terminate()
live.append(process)
except psutil.NoSuchProcess:
pass
_, remaining = psutil.wait_procs(live, timeout=10)
for process in remaining:
try:
process.kill()
except psutil.NoSuchProcess:
pass
_, remaining = psutil.wait_procs(remaining, timeout=10)
for signum, handler in previous_handlers.items():
signal.signal(signum, handler)
if remaining:
raise RuntimeError("Model child processes could not be released; refusing next stage")
if child is not None:
child.wait(timeout=10)
def execute(request: dict[str, Any]) -> dict[str, Any]:
from . import adapters
output = Path(request["output_dir"])
output.mkdir(parents=True, exist_ok=True)
runtime = output / ".runtime"
if runtime.is_symlink() or not runtime.resolve().is_relative_to(output.resolve()):
raise ValueError("Job runtime directory must not be a symlink")
runtime.mkdir(exist_ok=True)
if any(runtime.iterdir()):
raise RuntimeError("Job runtime directory is not empty; use a new output_dir for each execution")
request_file = runtime / "request.json"
write_json(request_file, request)
env = adapters.budgeted_child_environment(runtime)
all_paths: list[Path] = []
budget, reserve = adapters.memory_policy()
metadata = {"stages": [], "allocator_budget_gib": budget, "reserve_gib": reserve,
"isolation": "allocator cap and NVML admission are not hardware isolation"}
for stage in stage_plan(request):
adapters.admit_gpu()
result_file = runtime / f"{stage}.json"
log_file = runtime / f"{stage}.log"
_run_child([sys.executable, "-m", "llm_services.runner", "--request", str(request_file),
"--result", str(result_file), "--stage", stage], env, log_file, 7200)
stage_result = json.loads(result_file.read_text(encoding="utf-8"))
paths = [output / item["path"] for item in stage_result["outputs"]]
# Revalidate child output before handing it to the API/queue.
build_result(output, paths, stage_result.get("metadata", {}))
metadata["final_output_indices"] = list(range(len(all_paths), len(all_paths) + len(paths)))
all_paths.extend(paths)
metadata["stages"].append(stage_result.get("metadata", {}))
return build_result(output, all_paths, metadata)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--request", required=True)
parser.add_argument("--result", required=True)
parser.add_argument("--stage", choices=("model", "upscale"), help=argparse.SUPPRESS)
args = parser.parse_args(argv)
result_path = None
try:
request_path = confined_path(args.request, exists=True)
result_path = confined_path(args.result)
request = validate_request(json.loads(request_path.read_text(encoding="utf-8")))
if args.stage:
from . import adapters
# Also set in this process; sitecustomize covers every spawned worker.
adapters.configure_gpu_budget()
paths, metadata = adapters.run_stage(request, args.stage)
result = build_result(Path(request["output_dir"]), paths, metadata)
else:
result = execute(request)
write_json(result_path, result)
return 0
except Exception as exc:
if result_path is not None:
write_json(result_path, {"outputs": [], "error": {"type": type(exc).__name__, "message": str(exc)},
"metadata": {"completed": False}})
print(f"Runner failed: {type(exc).__name__}: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())