cmvr-visual/inference/llm_services/adapters.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

467 lines
24 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.

"""Pinned-runtime model adapters. No heavyweight import at module import time.
API provenance (v0.32.0): vllm-project/vllm-omni examples/offline_inference/
text_to_{image,video}; diffusion/offloader/config.py; vllm examples/generate/
multimodal/audio_language_offline.py. Each adapter runs in a disposable process.
"""
from __future__ import annotations
import gc
import json
import math
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Any
from .reference_profiles import get_profile
GIB = 2**30
MODELS = {
"image.generate": "/workspace/models/qwen-image",
"image.reference.generate": "/workspace/models/qwen-image-edit-2511",
"video.generate": "/workspace/models/wan2.2-ti2v-5b",
"defect.generate": "/workspace/models/sdxl-base",
"audio.transcribe": "/workspace/models/whisper-large-v3-turbo",
}
class GpuPreempted(RuntimeError):
"""Keep a stage's yield decision in its result manifest across snapshots."""
def memory_policy() -> tuple[float, float]:
try:
budget = float(os.environ.get("LLM_GPU_BUDGET_GIB", "68"))
reserve = float(os.environ.get("LLM_GPU_RESERVE_GIB", "8"))
except ValueError as exc:
raise RuntimeError("GPU budget/reserve must be finite GiB values") from exc
if not math.isfinite(budget) or not 1 <= budget <= 72 or not math.isfinite(reserve) or not 1 <= reserve <= 16:
raise RuntimeError("GPU budget must be 1..72GiB and reserve must be 1..16GiB")
return budget, reserve
def memory_fraction(total_bytes: int) -> float:
budget, reserve = memory_policy()
if total_bytes < (budget + reserve) * GIB:
raise RuntimeError("GPU total memory is smaller than the configured budget plus reserve")
return budget * GIB / total_bytes
def check_memory_admission(free_bytes: int, total_bytes: int) -> None:
memory_fraction(total_bytes)
budget, reserve = memory_policy()
if free_bytes > total_bytes or free_bytes < (budget + reserve) * GIB:
raise RuntimeError(f"GPU admission rejected: need {budget + reserve:g}GiB free ({budget:g}GiB allocator + {reserve:g}GiB reserve)")
def admit_gpu() -> dict[str, int]:
# Recheck host ownership at every stage, including the transition from
# video generation to enhancement. CUDA visibility alone is not priority.
if os.environ.get("LLM_GPU_STATUS_PATH"):
from .gpu_policy import GpuPolicy
policy = GpuPolicy.from_env()
reason = policy.should_yield({"uuid": os.environ.get("LLM_GPU_UUID")})
if reason:
raise GpuPreempted(f"GPU policy requires yielding: {reason}")
import pynvml
pynvml.nvmlInit()
try:
uuid = os.environ.get("LLM_GPU_UUID")
handle = (pynvml.nvmlDeviceGetHandleByUUID(uuid) if uuid else
pynvml.nvmlDeviceGetHandleByIndex(int(os.environ.get("LLM_NVML_GPU_INDEX", "2"))))
memory = pynvml.nvmlDeviceGetMemoryInfo(handle)
check_memory_admission(memory.free, memory.total)
return {"free_bytes": memory.free, "total_bytes": memory.total}
finally:
pynvml.nvmlShutdown()
def configure_gpu_budget() -> None:
import torch
if not torch.cuda.is_available() or torch.cuda.device_count() != 1:
raise RuntimeError("Runner requires exactly one visible CUDA device, mapped to its selected GPU")
total = torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(memory_fraction(total), device=0)
torch.set_num_threads(min(int(os.environ.get('OMP_NUM_THREADS', '8')), os.cpu_count() or 1))
def rpc_base_path() -> Path:
"""vLLM 0.32 reads VLLM_RPC_BASE_PATH before appending a 36-byte UUID.
Keep ordinary temporary files in the job directory, but IPC sockets need a
short base for Linux's 107-byte AF_UNIX pathname limit. Never recursively
delete this directory: another process owns its own UUID socket files.
"""
path = Path(tempfile.gettempdir()) / "llm-rpc" if os.name == "nt" else Path("/workspace/.tmp")
if path.is_symlink():
raise RuntimeError("RPC base directory must not be a symlink")
path.mkdir(mode=0o700, parents=True, exist_ok=True)
path = path.resolve()
if os.name != "nt" and not path.is_relative_to(Path("/workspace").resolve()):
raise RuntimeError("RPC base directory escapes /workspace")
if len(os.fsencode(str(path))) + 1 + 36 >= 107:
raise RuntimeError("RPC base directory is too long for AF_UNIX sockets")
return path
def budgeted_child_environment(runtime: Path) -> dict[str, str]:
"""Task-private bootstrap is inherited by Python spawn workers, not installed globally."""
bootstrap = runtime / "bootstrap"
bootstrap.mkdir()
(bootstrap / "sitecustomize.py").write_text(
"import os, sys\n"
"try:\n"
" from llm_services.adapters import configure_gpu_budget\n"
" configure_gpu_budget()\n"
"except BaseException as exc:\n"
" sys.stderr.write('GPU allocator bootstrap failed: %s\\n' % exc)\n"
" sys.stderr.flush()\n"
" os._exit(78)\n", encoding="utf-8")
env = dict(os.environ)
env.setdefault('OMP_NUM_THREADS', '8')
project = str(Path(__file__).resolve().parent.parent)
env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(bootstrap), project, env.get("PYTHONPATH"))))
temporary = runtime / "tmp"
temporary.mkdir()
env.update(VLLM_WORKER_MULTIPROC_METHOD="spawn", TOKENIZERS_PARALLELISM="false",
VLLM_RPC_BASE_PATH=str(rpc_base_path()),
HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_HOME="/workspace/.cache/huggingface",
XDG_CACHE_HOME="/workspace/.cache", TORCH_HOME="/workspace/.cache/torch",
VLLM_CACHE_ROOT="/workspace/.cache/vllm", TRITON_CACHE_DIR="/workspace/.cache/triton",
TORCH_EXTENSIONS_DIR="/workspace/.cache/torch_extensions", CUDA_CACHE_PATH="/workspace/.cache/cuda",
NUMBA_CACHE_DIR="/workspace/.cache/numba", TMPDIR=str(temporary), TMP=str(temporary), TEMP=str(temporary))
return env
def omni_engine_kwargs(model: str) -> dict[str, Any]:
# Public 0.32 mapping. Module mode swaps encoders/DiT for the dedicated 68GiB
# budget; operator can select layer mode if a workload needs a smaller peak.
mode = os.environ.get("LLM_DIFFUSION_OFFLOAD_MODE", "module")
if mode not in {"module", "layer"}:
raise RuntimeError("LLM_DIFFUSION_OFFLOAD_MODE must be module or layer")
return {"model": model, "dtype": "bfloat16", "tensor_parallel_size": 1,
"diffusion_offload_config": {"mode": mode, "components": ["dit", "text_encoder"],
"pin_memory": True},
"vae_use_tiling": True, "vae_use_slicing": True, "enforce_eager": True,
"cache_backend": "none", "max_num_seqs": 1}
def _new_file(output: Path, name: str) -> Path:
destination = output / name
if not destination.resolve().is_relative_to(output.resolve()):
raise ValueError("Adapter output path escapes the job output directory")
if destination.exists() or destination.is_symlink():
raise RuntimeError(f"Refusing to reuse an existing output: {name}")
return destination
def _require_model(model: str) -> str:
from .runner import confined_path
directory = confined_path(model)
if not directory.is_dir():
raise RuntimeError(f"Model directory is not ready: {directory.name}")
manifest = directory / ".deployment-manifest.json"
if not manifest.is_file() or not json.loads(manifest.read_text(encoding="utf-8")).get("files"):
raise RuntimeError(f"Model download and verification are not complete: {directory.name}")
return str(directory)
def reference_omni_inputs(request, tokenizer):
"""Token预算使用0.32实际模板和占位符基线,绝不截断用户文本。"""
p, inputs = request["parameters"], request["input"]
profile = get_profile(p["profile"])
paths = inputs.get("image_paths")
if not isinstance(paths, list) or not 1 <= len(paths) <= profile.max_images:
raise ValueError("Reference generation requires all ordered image paths")
# 与官方EditPlus _get_qwen_prompt_embeds相同的text-only预算口径。
template = ("<|im_start|>system\nDescribe the key features of the input image "
"(color, shape, size, texture, objects, background), then explain how the user's "
"text instruction should alter or modify the image. Generate a new image that meets "
"the user's requirements while maintaining consistency with the original input where "
"appropriate.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n")
placeholders = "".join(f"Picture {i + 1}: <|vision_start|><|image_pad|><|vision_end|>" for i in range(len(paths)))
baseline = len(tokenizer.encode(template.format(placeholders), truncation=False))
counts = {}
for name in ("prompt", "negative_prompt"):
text = inputs.get(name, "")
counts[name] = max(0, len(tokenizer.encode(template.format(placeholders + text), truncation=False)) - baseline)
if counts[name] > p["max_sequence_length"]:
raise ValueError(f"Reference {name} token budget exceeded: {counts[name]} > {p['max_sequence_length']}")
prompt = {"prompt": inputs["prompt"], "negative_prompt": inputs.get("negative_prompt", ""),
"modalities": ["image"], "multi_modal_data": {"image": list(paths)}}
sampling = {name: p[name] for name in ("height", "width", "seed", "num_inference_steps",
"guidance_scale", "true_cfg_scale", "max_sequence_length")}
sampling.update(num_outputs_per_prompt=1, output_type="pil")
return prompt, sampling
def _omni_generate(request: dict[str, Any]) -> tuple[list[Path], dict[str, Any]]:
import numpy as np
import torch
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.diffusion.utils.image_output import extract_images_from_outputs
p, inputs, task = request["parameters"], request["input"], request["task_type"]
output = Path(request["output_dir"])
reference = get_profile(p["profile"]) if task == "image.reference.generate" else None
model = _require_model(reference.directory if reference else MODELS[task])
reference_inputs = None
if reference:
# 先检查真实tokenizer和模型manifest,再构造GPU引擎。
manifest = json.loads((Path(model) / ".deployment-manifest.json").read_text(encoding="utf-8"))
if manifest.get("repo") != reference.repo or manifest.get("revision") != reference.revision:
raise RuntimeError("Reference checkpoint manifest differs from explicit profile")
from transformers import Qwen2Tokenizer
tokenizer = Qwen2Tokenizer.from_pretrained(model, subfolder="tokenizer", local_files_only=True)
reference_inputs = reference_omni_inputs(request, tokenizer)
kwargs = omni_engine_kwargs(model)
if task == "video.generate":
kwargs["flow_shift"] = 5.0
engine = None
try:
engine = Omni(**kwargs)
prompt = {"prompt": inputs["prompt"], "negative_prompt": inputs["negative_prompt"],
"modalities": ["video" if task == "video.generate" else "image"]}
if "image_path" in inputs:
# Wan0.32 preprocessor accepts a checked local path or a PIL image.
prompt["multi_modal_data"] = {"image": inputs["image_path"]}
sampling = {"height": p["height"], "width": p["width"], "seed": p["seed"],
"num_inference_steps": p["num_inference_steps"], "num_outputs_per_prompt": 1,
"guidance_scale": p["guidance_scale"]}
if reference:
prompt, sampling = reference_inputs
elif task == "image.generate":
sampling["true_cfg_scale"] = p["guidance_scale"]
sampling["output_type"] = "pil"
else:
sampling.update(num_frames=p["num_frames"], fps=p["fps"], output_type="np", return_frames=True)
results = engine.generate(prompt, sampling_params_list=OmniDiffusionSamplingParams(**sampling), use_tqdm=False)
if not results:
raise RuntimeError("Omni returned no result")
if task in {"image.generate", "image.reference.generate"}:
from PIL import Image
images = extract_images_from_outputs(results)
if not images:
images = getattr(results[0], "images", None)
if not images:
raise RuntimeError("Omni returned no image")
image = images[0]
if isinstance(image, np.ndarray):
array = np.clip(image * 255 if np.issubdtype(image.dtype, np.floating) else image, 0, 255).astype("uint8")
image = Image.fromarray(array)
target = _new_file(output, "image.png")
image.save(target)
else:
from diffusers.utils import export_to_video
frames = _video_frames(results, torch, np)
if len(frames) != p["num_frames"]:
raise RuntimeError(f"Wan frame count mismatch: expected {p['num_frames']}, got {len(frames)}")
target = _new_file(output, "video_raw.mp4")
export_to_video(frames, str(target), fps=p["fps"], macro_block_size=1)
return [target], {"engine": "vllm-omni", "model": model, "stage": "generation",
"parameters": p, "cpu_offload": kwargs["diffusion_offload_config"]}
finally:
if engine is not None:
engine.close()
def _video_frames(results, torch, np):
"""Normalize Wan's documented OmniRequestOutput.images video payload to THWC."""
frames = getattr(results[0], "images", None)
if frames is None or (isinstance(frames, list) and not frames):
raise RuntimeError("Omni returned no video frames")
if isinstance(frames, list) and len(frames) == 1:
if isinstance(frames[0], dict):
item = frames[0]
frames = item.get("frames") if item.get("frames") is not None else item.get("video")
elif isinstance(frames[0], (list, tuple)):
frames = frames[0]
elif hasattr(frames[0], "ndim") and frames[0].ndim >= 4:
frames = frames[0]
if isinstance(frames, torch.Tensor):
frames = frames.detach().cpu().float().numpy()
if isinstance(frames, np.ndarray):
if frames.ndim == 5:
frames = frames[0]
if frames.ndim == 4 and frames.shape[0] in (3, 4) and frames.shape[-1] not in (3, 4):
frames = frames.transpose(1, 2, 3, 0)
frames = list(frames)
normalized = []
for frame in frames:
if isinstance(frame, torch.Tensor):
frame = frame.detach().cpu().float().numpy()
frame = np.asarray(frame)
if frame.ndim == 3 and frame.shape[0] in (3, 4) and frame.shape[-1] not in (3, 4):
frame = frame.transpose(1, 2, 0)
if frame.ndim != 3 or frame.shape[-1] not in (3, 4):
raise RuntimeError("Unexpected Wan frame shape")
if np.issubdtype(frame.dtype, np.integer):
frame = frame.astype(np.float32) / 255
# Wan's np postprocessor emits [0,1], never infer signed ranges from
# image minima (an all-dark frame could otherwise be misclassified).
normalized.append(np.clip(frame[..., :3], 0, 1))
return normalized
def _defect_generate(request):
import cv2
import numpy as np
import torch
from PIL import Image
from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline
p, inputs = request["parameters"], request["input"]
output = Path(request["output_dir"])
with Image.open(inputs["image_path"]) as source:
source = source.convert("RGB").resize((p["width"], p["height"]), Image.Resampling.LANCZOS)
edges = cv2.Canny(np.asarray(source), p["canny_low"], p["canny_high"])
control_image = Image.fromarray(np.repeat(edges[..., None], 3, axis=2))
control_path = _new_file(output, "control_canny.png")
control_image.save(control_path)
control = ControlNetModel.from_pretrained(_require_model("/workspace/models/controlnet-canny-sdxl"),
variant="fp16", torch_dtype=torch.float16, use_safetensors=True, local_files_only=True)
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(_require_model(MODELS["defect.generate"]),
controlnet=control, variant="fp16", torch_dtype=torch.float16, use_safetensors=True,
local_files_only=True, add_watermarker=False)
pipeline.enable_model_cpu_offload(gpu_id=0)
# Diffusers 0.40 moved these controls to AutoencoderMixin on the VAE.
pipeline.vae.enable_tiling()
pipeline.vae.enable_slicing()
try:
with torch.inference_mode():
result = pipeline(prompt=inputs["prompt"], negative_prompt=inputs["negative_prompt"],
image=control_image, width=p["width"], height=p["height"],
num_inference_steps=p["num_inference_steps"], guidance_scale=p["guidance_scale"],
controlnet_conditioning_scale=p["controlnet_conditioning_scale"],
generator=torch.Generator("cpu").manual_seed(p["seed"])).images[0]
target = _new_file(output, "defect.png")
result.save(target)
return [target, control_path], {"engine": "diffusers", "model": MODELS["defect.generate"],
"controlnet": "/workspace/models/controlnet-canny-sdxl", "parameters": p,
"stage": "sdxl_controlnet", "interpretation": "Canny-conditioned synthetic image; no defect ground-truth mask"}
finally:
pipeline.maybe_free_model_hooks()
del pipeline, control
gc.collect()
torch.cuda.empty_cache()
def whisper_generation_limit(prompt_tokens: int, max_model_len: int = 448) -> int:
# Leave eight positions for any renderer-added decoder prefix/EOS. Never
# depend on the scheduler silently shortening a fixed max_tokens=400.
available = max_model_len - prompt_tokens - 8
if type(prompt_tokens) is not int or prompt_tokens < 0 or available < 1:
raise ValueError("Whisper decoder prompt leaves no safe generation budget")
return min(400, available)
def _transcribe(request):
import numpy as np
from vllm import LLM, SamplingParams
p, output = request["parameters"], Path(request["output_dir"])
source = request["input"]["audio_path"]
# Bound decoding independently of client-supplied metadata; +1 detects truncation.
decoded = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", source, "-t",
str(p["max_audio_seconds"] + 1), "-ac", "1", "-ar", "16000", "-f", "f32le", "pipe:1"],
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300)
audio = np.frombuffer(decoded.stdout, dtype="<f4").copy()
if audio.size == 0 or audio.size > p["max_audio_seconds"] * 16000:
raise ValueError("Audio is empty or exceeds max_audio_seconds")
language = "" if p["language"] == "auto" else f"<|{p['language']}|>"
prompt = f"<|startoftranscript|>{language}<|transcribe|><|notimestamps|>" if language else "<|startoftranscript|>"
# 448 is Whisper's decoder context. A 30s chunk is its maximum acoustic window.
model = LLM(model=_require_model(MODELS["audio.transcribe"]), max_model_len=448,
# The audio encoder has 1500 tokens despite the decoder's 448 limit.
max_num_seqs=1, max_num_batched_tokens=2048, limit_mm_per_prompt={"audio": 1},
gpu_memory_utilization=0.10, enforce_eager=True, tensor_parallel_size=1, dtype="float16",
trust_remote_code=False)
prompt_ids = model.get_tokenizer().encode(prompt, add_special_tokens=False)
generation_limit = whisper_generation_limit(len(prompt_ids))
segments = []
for start in range(0, audio.size, 30 * 16000):
chunk = audio[start:start + 30 * 16000]
results = model.generate({"prompt": prompt, "multi_modal_data": {"audio": (chunk, 16000)}},
sampling_params=SamplingParams(temperature=0, max_tokens=generation_limit), use_tqdm=False)
if not results or not results[0].outputs:
raise RuntimeError("Whisper returned no transcript")
segments.append({"start": start / 16000, "end": (start + len(chunk)) / 16000,
"text": results[0].outputs[0].text.strip(),
"truncated": results[0].outputs[0].finish_reason == "length"})
text = "\n".join(segment["text"] for segment in segments)
transcript = _new_file(output, "transcript.txt")
transcript.write_text(text + "\n", encoding="utf-8")
details = _new_file(output, "transcript.json")
details.write_text(json.dumps({"text": text, "language": p["language"], "segments": segments,
"duration": audio.size / 16000}, ensure_ascii=False, indent=2), encoding="utf-8")
return [transcript, details], {"engine": "vllm", "model": MODELS["audio.transcribe"],
"stage": "transcription", "chunk_seconds": 30,
"max_generation_tokens": generation_limit,
"truncated_segments": sum(segment["truncated"] for segment in segments),
"timestamps": "chunk boundaries, not word alignment", "parameters": p}
def _upscale(request):
import cv2
import imageio.v2 as imageio
import numpy as np
import torch
from .realesrgan_arch import make_rrdbnet, tiled_upscale
from .runner import confined_path
p, output = request["parameters"], Path(request["output_dir"])
source = confined_path(output / "video_raw.mp4", exists=True)
weight_file = confined_path("/workspace/models/realesrgan/RealESRGAN_x4plus.pth", exists=True)
network = make_rrdbnet(torch)
weights = torch.load(str(weight_file), map_location="cpu", weights_only=True)
network.load_state_dict(weights.get("params_ema", weights.get("params", weights)), strict=True)
network = network.eval().half().to("cuda:0")
capture = cv2.VideoCapture(str(source))
target = _new_file(output, "video_upscaled.mp4")
frames = 0
try:
with imageio.get_writer(str(target), fps=p["fps"], codec="libx264", quality=8,
macro_block_size=1, ffmpeg_log_level="error") as writer:
while True:
ok, frame = capture.read()
if not ok:
break
# RealESRGAN weights consume RGB normalized to [0,1].
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
restored = tiled_upscale(rgb, network, torch, np, p["tile_size"])
height, width = restored.shape[:2]
scale = min(p["upscale_width"] / width, p["upscale_height"] / height)
resized = cv2.resize(restored, (round(width * scale), round(height * scale)), interpolation=cv2.INTER_LANCZOS4)
canvas = np.zeros((p["upscale_height"], p["upscale_width"], 3), dtype=np.uint8)
y = (canvas.shape[0] - resized.shape[0]) // 2
x = (canvas.shape[1] - resized.shape[1]) // 2
canvas[y:y + resized.shape[0], x:x + resized.shape[1]] = resized
writer.append_data(canvas)
frames += 1
finally:
capture.release()
del network
torch.cuda.empty_cache()
if frames != p["num_frames"]:
raise RuntimeError(f"RealESRGAN decoded {frames} frames; expected {p['num_frames']}")
return [target], {"engine": "pytorch", "model": str(weight_file), "stage": "realesrgan",
"frames": frames, "resolution": [p["upscale_width"], p["upscale_height"]],
"fit": "aspect-preserving letterbox", "tile_size": p["tile_size"], "tile_pad": 10}
def run_stage(request: dict[str, Any], stage: str):
if request["task_type"] in {"video.people.analyze", "video.replace"}:
from .video_edit.runtime import run
return run(request)
if stage == "upscale":
if request["task_type"] != "video.generate" or not request["parameters"]["upscale"]:
raise ValueError("Upscale stage requires a video job with upscale enabled")
return _upscale(request)
if stage != "model":
raise ValueError("Unknown stage")
if request["task_type"] in {"image.generate", "image.reference.generate", "video.generate"}:
return _omni_generate(request)
if request["task_type"] == "defect.generate":
return _defect_generate(request)
if request["task_type"] == "audio.transcribe":
return _transcribe(request)
raise ValueError("Unknown task")