cmvr-visual/inference/llm_services/runner.py

378 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""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
from .reference_profiles import get_profile
from .video_profiles import is_h3
WORKSPACE = Path("/workspace")
from .dialogue import KEYS as DIALOGUE_TASKS, LATENTSYNC_PREVIEW, SYNC
TASKS = {*DIALOGUE_TASKS, "image.generate", "image.reference.generate", "video.generate", "video.people.analyze", "video.replace", "defect.generate", "audio.transcribe"}
class StageProcessFailed(RuntimeError):
"""仅表示模型子进程非零退出;不能覆盖清理失败或超时。"""
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")
if task in DIALOGUE_TASKS:
from .dialogue.protocol import validate
inputs, params = validate(task, inputs, params, workspace)
return {"task_type":task,"input":inputs,"parameters":params,"output_dir":str(output)}
if task in {"video.people.analyze", "video.replace"}:
from .video_edit.protocol import validate
inputs, params = validate(task, inputs, params, workspace)
return {"task_type": task, "input": inputs, "parameters": params, "output_dir": str(output)}
legacy_profile = None
if task == 'video.generate':
from .video_profiles import H3_PROFILES, LEGACY_PROFILE, normalize_h3
if params.get('profile') in H3_PROFILES:
inputs, params = normalize_h3(inputs, params, workspace)
return {'task_type': task, 'input': inputs, 'parameters': params, 'output_dir': str(output)}
if 'profile' in params:
if params['profile'] != LEGACY_PROFILE:
raise ValueError('Unknown video generation profile')
legacy_profile = params['profile']
params = {key: value for key, value in params.items() if key != 'profile'}
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 task == "image.reference.generate":
allowed_inputs.add("image_paths")
if set(inputs) - allowed_inputs:
raise ValueError("Unknown input field")
inputs = dict(inputs)
reference = get_profile(params.get("profile")) if task == "image.reference.generate" else None
if reference:
paths = inputs.get("image_paths")
if not isinstance(paths, list) or not 1 <= len(paths) <= reference.max_images:
raise ValueError("Reference task requires the complete ordered image_paths list within profile limit")
inputs["image_paths"] = [str(confined_path(path, workspace, exists=True)) for path in paths]
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),
}
if reference:
allowed |= {"profile", "true_cfg_scale", "max_sequence_length"}
normalized.update(profile=reference.name, width=params.get("width", 1280),
height=params.get("height", 704), num_inference_steps=params.get("num_inference_steps", 40),
guidance_scale=params.get("guidance_scale", 1.0),
true_cfg_scale=_number(params.get("true_cfg_scale", 4.0), "true_cfg_scale", 1, 20),
max_sequence_length=_integer(params.get("max_sequence_length", 1024),
"max_sequence_length", 1, reference.max_sequence_length))
if (normalized["width"], normalized["height"]) not in {(1280, 704), (704, 1280), (1024, 1024)}:
raise ValueError("Reference frame size must be 1280x704, 704x1280 or 1024x1024")
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, 361)
if normalized["num_frames"] % 4 != 1:
raise ValueError("Wan num_frames must be 4n+1 (up to 361 frames, about 15 seconds at 24fps)")
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)))
if legacy_profile:
normalized['profile'] = legacy_profile
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 StageProcessFailed(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
from .video_profiles import is_native_av, is_tp2
if request['task_type'] == 'video.generate' and is_tp2(request['parameters']):
# 双卡有独立bootstrap和阶段屏障,不能进入单卡sitecustomize。
from .h3_tp2 import run
paths, metadata = run(request)
if is_native_av(request['parameters']):
# TP2绕过通用stage循环,必须在这个出口声明视频和完整原声均为最终产物。
output = Path(request['output_dir']).resolve()
expected = [output / 'video_raw.mp4', output / 'audio_native.wav']
indices = metadata.get('final_output_indices', [0, 1])
if ([Path(path).resolve() for path in paths] != expected
or not isinstance(indices, list) or indices != [0, 1]
or any(type(i) is not int for i in indices)):
raise ValueError('Native TP2 must return the final MP4 and full WAV at indices 0,1')
metadata = {**metadata, 'final_output_indices': [0, 1]}
return build_result(Path(request['output_dir']), paths, metadata)
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)
if request["task_type"] == SYNC and request["parameters"].get("profile") == LATENTSYNC_PREVIEW:
from .dialogue.latentsync_preview import cache_environment
env.update(cache_environment(WORKSPACE / "models" / LATENTSYNC_PREVIEW))
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"
# 仅放宽H3生成子进程;worker仍按已持久化的job预算限制整个执行。
stage_timeout = (21600 if request["task_type"] == "video.generate"
and stage == "model" and is_h3(request["parameters"]) else 7200)
try:
_run_child([sys.executable, "-m", "llm_services.runner", "--request", str(request_file),
"--result", str(result_file), "--stage", stage], env, log_file, stage_timeout)
except StageProcessFailed:
# 子进程释放完毕后传递明确的抢占类型;不能把让卡变为永久失败。
# 其他失败继续沿用原异常,不能凭缺失/损坏清单自动重试GPU任务。
try:
report = json.loads(result_file.read_text(encoding='utf-8'))
except (OSError, ValueError, AttributeError):
report = {}
failure = report.get('error', {}) if isinstance(report, dict) else {}
details = report.get('metadata', {}) if isinstance(report, dict) else {}
if (isinstance(report, dict) and report.get('outputs') == []
and isinstance(details, dict) and details.get('completed') is False
and isinstance(failure, dict) and failure.get('type') == 'GpuPreempted'
and isinstance(failure.get('message'), str) and failure['message'].strip()):
raise adapters.GpuPreempted(failure['message'][:2000]) from None
raise
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", {}))
if (request["task_type"] in {*DIALOGUE_TASKS, "video.people.analyze", "video.replace"}
or request['task_type'] == 'video.generate' and is_native_av(request['parameters'])):
metadata.update(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())