Skip to content
38 changes: 33 additions & 5 deletions mstar/api_server/data_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import queue
import threading
import time
import traceback
from dataclasses import dataclass, field

import torch
Expand Down Expand Up @@ -47,6 +48,29 @@

logger = logging.getLogger(__name__)

# What decoders raise on a file they can't read (torchvision and torchcodec
# RuntimeError, PIL OSError); anything else from a loader is a server bug
_DECODE_ERRORS = (RuntimeError, OSError, EOFError)


def _raised_on_import(exc: BaseException) -> bool:
"""True when ``exc`` came out of a module being imported, e.g. torchcodec
on a host without FFmpeg: the install is broken, not the file."""
return any(f.f_code.co_name == "<module>" for f, _ in traceback.walk_tb(exc.__traceback__))


def _decode_input(load, filepath: str, device: str, modality: str):
"""Run a model's ``load_<modality>`` on one upload. A file that won't decode
becomes a ValueError, so the client gets a 400 instead of a 500."""
try:
return load(filepath, device)
except _DECODE_ERRORS as exc:
Comment thread
vasilevklart marked this conversation as resolved.
Resolved
# a missing upload was removed by our own cleanup
if not os.path.exists(filepath) or _raised_on_import(exc):
raise
detail = str(exc).replace(filepath, "the upload") # PIL names the server path
raise ValueError(f"could not decode the {modality} input: {detail}") from exc


def _video_frame_metadata(
tensor: torch.Tensor,
Expand Down Expand Up @@ -450,19 +474,19 @@ def _process_input(
for filepath in input.file_paths[modality]:
# ---- Image ----
if modality == "image":
out = self.model.load_image(filepath, self.device)
out = _decode_input(self.model.load_image, filepath, self.device, "image")
tensors[key].append(out.data)
input_metadata[key].append(out.metadata)

# ---- Audio ----
elif modality == "audio":
out = self.model.load_audio(filepath, self.device)
out = _decode_input(self.model.load_audio, filepath, self.device, "audio")
tensors[key].append(out.data)
input_metadata[key].append(out.metadata)

# ---- Video ----
elif modality == "video":
out = self.model.load_video(filepath, self.device)
out = _decode_input(self.model.load_video, filepath, self.device, "video")
tensors[key].append(out.data)
input_metadata[key].append(out.metadata)

Expand Down Expand Up @@ -608,7 +632,7 @@ def _summarize_inputs(input: PreprocessInput) -> list[InputInfo]:

def _fail_request(
self, request_id: str, exc: BaseException, stage: str, count: int = 1,
sequence: int | None = None,
sequence: int | None = None, status: int = 500,
):
"""Report a per-request data-worker failure to the API server.

Expand All @@ -620,9 +644,11 @@ def _fail_request(
``sequence`` is the output slot the failed tensor held. Its error chunk
takes that slot in the reorder buffer; put straight on ``out_queue`` it
would leave every later sequence held in ``pending`` until the TTL.

``status`` is 500 unless the caller knows the request itself was bad:
past intake, a ValueError is a server bug, not invalid input.
"""
logger.exception("%s failed for request %s", stage, request_id)
status = 400 if isinstance(exc, (ValueError, TypeError)) else 500
chunks = [
ResultChunk(
request_id=request_id,
Expand Down Expand Up @@ -944,6 +970,8 @@ def run(self):
# server timeout.
self._fail_request(
pre_input.request_id, exc, "preprocessing",
# intake rejects a request with ValueError/TypeError
status=400 if isinstance(exc, (ValueError, TypeError)) else 500,
)
# Never reached the conductor, so there are no remote
# readers to race: hard-drop the (possibly persisted)
Expand Down
42 changes: 32 additions & 10 deletions mstar/model/components/diffusion/image_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,35 @@ def deflate(index: int, part: bytes) -> bytes:
OUTPUT_FORMATS = ("png", "jpeg", "webp")


def _int_knob(kwargs: dict, name: str, default: int) -> int:
value = kwargs.get(name)
if value is None:
return default
try:
return int(value)
except (TypeError, ValueError, OverflowError):
raise ValueError(f"{name} must be an integer, got {value!r}") from None


def image_output_options(request_kwargs: dict | None = None) -> tuple[str, int | None, int | None]:
"""Parse the knobs :func:`encode_image` reads into ``(format, quality,
png_level)``; the one the format doesn't use is None. Models call this at
intake too, so a bad knob is a 400 before the GPU runs."""
kwargs = request_kwargs or {}
fmt = str(kwargs.get("output_format") or "png").lower()
if fmt == "jpg":
fmt = "jpeg"
if fmt not in OUTPUT_FORMATS:
raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {fmt!r}")
if fmt == "png":
level = _int_knob(kwargs, "png_compress_level", 1)
if not -1 <= level <= 9:
raise ValueError(f"png_compress_level must be -1 to 9, got {level}")
return fmt, None, level
quality = _int_knob(kwargs, "output_compression", 95 if fmt == "jpeg" else 80)
return fmt, max(0, min(100, quality)), None


def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> bytes:
"""Encode a uint8 ``[3, H, W]`` image for the client per the OpenAI images knobs.

Expand All @@ -154,23 +183,16 @@ def encode_image(image: torch.Tensor, request_kwargs: dict | None = None) -> byt
``png_compress_level`` (0-9, default 1) selects the zlib level of the fast writer.
Everything else decodes to the pixels the VAE produced (PNG losslessly).
"""
kwargs = request_kwargs or {}
fmt = str(kwargs.get("output_format") or "png").lower()
if fmt == "jpg":
fmt = "jpeg"
if fmt not in OUTPUT_FORMATS:
raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {fmt!r}")
fmt, quality, level = image_output_options(request_kwargs)
if fmt == "png":
return uint8_to_png(image, compress_level=int(kwargs.get("png_compress_level", 1)))
return uint8_to_png(image, compress_level=level)
from PIL import Image

if image.ndim == 4:
image = image[0]
quality = kwargs.get("output_compression")
quality = int(quality) if quality is not None else (95 if fmt == "jpeg" else 80)
buffer = io.BytesIO()
Image.fromarray(image.permute(1, 2, 0).contiguous().cpu().numpy(), mode="RGB").save(
buffer, format=fmt.upper(), quality=max(0, min(100, quality)),
buffer, format=fmt.upper(), quality=quality,
)
return buffer.getvalue()

Expand Down
4 changes: 4 additions & 0 deletions mstar/model/cosmos3/cosmos3_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from __future__ import annotations

import logging
import math
from pathlib import Path

import torch
Expand Down Expand Up @@ -1196,6 +1197,9 @@ def _resolve_gen_params(
1, int(mk.get("max_sequence_length", constants.DEFAULT_MAX_SEQUENCE_LENGTH))
),
}
# the packing divides by it, and postprocess muxes at it
if not math.isfinite(params["fps"]) or params["fps"] <= 0:
raise ValueError(f"Cosmos3 fps must be positive and finite; got {mk.get('fps')!r}.")
# Video-to-video: a non-action video input pins clean conditioning
# latent frames taken from the request video (reference recipe defaults:
# indexes (0, 1), keep "first", flow_shift 10.0). Validated here so a
Expand Down
7 changes: 7 additions & 0 deletions mstar/model/cosmos3/tests/test_serving.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ def test_gen_params_and_step_metadata() -> None:
assert sm["num_inference_steps"] == 7


@pytest.mark.parametrize("fps", [0, -24, float("nan"), float("inf")])
def test_gen_params_reject_a_bad_fps(fps) -> None:
model = Cosmos3Model(model_path_hf="unused", skip_weight_loading=True)
with pytest.raises(ValueError, match="fps must be positive"):
model._resolve_gen_params({"fps": fps}, ["text"], ["video"])


def test_dynamic_loop_check_stop_and_wasted_step() -> None:
"""The denoise loop stops at each request's own step count, and a step
dispatched one past that count is a no-op — so the loop's single speculative
Expand Down
3 changes: 2 additions & 1 deletion mstar/model/flux2_klein/flux2_klein_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION
from mstar.model.base import ForwardPassArgs, Model, TensorAndMetadata
from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES
from mstar.model.components.diffusion.image_io import encode_image
from mstar.model.components.diffusion.image_io import encode_image, image_output_options
from mstar.model.components.diffusion.lora import LoraSpec
from mstar.model.flux2_klein.config import (
DENOISE_LOOP,
Expand Down Expand Up @@ -317,6 +317,7 @@ def process_prompt(
raise ValueError(f"FLUX.2 klein only generates images; got output modality {output_modalities!r}")
if prompt is None or not prompt.strip():
raise ValueError("FLUX.2 klein requires a non-empty text prompt")
image_output_options(kwargs) # postprocess would fail it as a 500
images = (tensors or {}).get(IMAGE_INPUTS) or []
if "image" in input_modalities and not images:
raise ValueError("request declared an image input but no image arrived; editing needs the reference image")
Expand Down
5 changes: 3 additions & 2 deletions mstar/model/wan22/wan22_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import html
import io
import logging
import math
import os
import re
from fractions import Fraction
Expand Down Expand Up @@ -316,8 +317,8 @@ def _validate_generation_size(self, model_kwargs: dict) -> None:
fps = float(raw_fps)
except (TypeError, ValueError):
raise ValueError(f"Wan2.2 fps must be a number; got {raw_fps!r}.") from None
if fps <= 0:
raise ValueError(f"Wan2.2 fps must be positive; got {raw_fps!r}.")
if not math.isfinite(fps) or fps <= 0:
raise ValueError(f"Wan2.2 fps must be positive and finite; got {raw_fps!r}.")

def process_prompt(
self,
Expand Down
3 changes: 2 additions & 1 deletion mstar/model/z_image/z_image_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from mstar.graph.special_destinations import EMIT_TO_CLIENT, EMPTY_DESTINATION
from mstar.model.base import ForwardPassArgs, Model
from mstar.model.components.diffusion.decode_utils import VAE_DECODE_BATCH_SIZES
from mstar.model.components.diffusion.image_io import encode_image
from mstar.model.components.diffusion.image_io import encode_image, image_output_options
from mstar.model.submodule_base import NodeSubmodule
from mstar.model.z_image.config import DENOISE_LOOP, DIT_ATTN, Z_IMAGE_TURBO, ZImageConfig, resolve_snapshot_dir
from mstar.model.z_image.submodules import (
Expand Down Expand Up @@ -202,6 +202,7 @@ def process_prompt(
raise ValueError(f"Z-Image only generates images; got output modality {output_modalities!r}")
if prompt is None or not prompt.strip():
raise ValueError("Z-Image requires a non-empty text prompt")
image_output_options(kwargs) # postprocess would fail it as a 500
if "image" in input_modalities:
raise ValueError("Z-Image-Turbo is text-to-image only; reference images are not supported")
self._resolve_size(kwargs)
Expand Down
79 changes: 67 additions & 12 deletions test/modular/test_api_completion_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from mstar.api_server.data_worker import PreprocessWorker, PreprocessWorkerThread
from mstar.api_server.request_types import PreprocessInput
from mstar.graph.loop_indices import NestedLoopIndices
from mstar.model.base import Model


def _worker_with(output_loop_idxs):
Expand All @@ -39,14 +40,9 @@ def test_final_outputs_wait_for_registration_then_complete():
assert worker.received_final_chunks("r1", {"video_output": final}) is True


def test_preprocess_failure_emits_error_chunk():
"""A request rejected during preprocessing (e.g. an invalid model kwarg)
must produce an "error" chunk so the waiting client is released."""

class _RejectingModel:
def process_prompt(self, *args, **kwargs):
raise ValueError("bad knob")

def _preprocess_failure(model, file_paths=None):
"""Run one request through the preprocess loop and return its error chunk
and the rids force-cleaned."""
wt = PreprocessWorkerThread.__new__(PreprocessWorkerThread)
wt.in_queue = queue.Queue()
wt.out_queue = queue.Queue()
Expand All @@ -65,7 +61,7 @@ def process_prompt(self, *args, **kwargs):
has_inflight_reads=lambda rid: False,
get_ready_tensors=lambda: {},
)
wt.model = _RejectingModel()
wt.model = model
wt.device = "cpu"
wt.tensor_uuid_to_metadata_per_request = {}
wt.request_model_kwargs = {}
Expand All @@ -74,8 +70,9 @@ def process_prompt(self, *args, **kwargs):
wt._reads_done_sent = set()

wt.in_queue.put(PreprocessInput(
request_id="r1", text="x", file_paths=None,
input_modalities=["text"], output_modalities=["video"], model_kwargs={},
request_id="r1", text="x", file_paths=file_paths,
input_modalities=[*(file_paths or {}), "text"], output_modalities=["video"],
model_kwargs={},
))
thread = threading.Thread(target=wt.run, daemon=True)
thread.start()
Expand All @@ -84,9 +81,67 @@ def process_prompt(self, *args, **kwargs):
finally:
wt.stop_event.set()
thread.join(timeout=10)

assert chunk.request_id == "r1"
assert chunk.modality == "error"
return chunk, cleaned


def test_preprocess_failure_emits_error_chunk():
"""A request rejected during preprocessing (e.g. an invalid model kwarg)
must produce an "error" chunk so the waiting client is released."""

class _RejectingModel:
def process_prompt(self, *args, **kwargs):
raise ValueError("bad knob")

chunk, cleaned = _preprocess_failure(_RejectingModel())
assert b"bad knob" in chunk.data
assert chunk.metadata["status"] == 400
assert cleaned == ["r1"]


class _ImageModel:
def load_image(self, filepath, device):
return Model.load_image(self, filepath, device)


def test_an_upload_that_will_not_decode_is_a_400(tmp_path):
"""torchvision raises RuntimeError on a corrupt image, which used to be a 500."""
bad = tmp_path / "bad.png"
bad.write_bytes(b"not a png")
chunk, cleaned = _preprocess_failure(_ImageModel(), {"image": [str(bad)]})
assert b"could not decode the image input" in chunk.data
assert chunk.metadata["status"] == 400
assert cleaned == ["r1"]


def test_an_upload_our_cleanup_removed_is_a_500(tmp_path):
chunk, _ = _preprocess_failure(_ImageModel(), {"image": [str(tmp_path / "gone.png")]})
assert chunk.metadata["status"] == 500


def test_a_decoder_that_fails_to_import_is_a_500(tmp_path, monkeypatch):
"""torchcodec on a host without FFmpeg raises RuntimeError at import."""
(tmp_path / "broken_decoder.py").write_text('raise RuntimeError("could not load libdecoder")\n')
monkeypatch.syspath_prepend(str(tmp_path))

class _AudioModel:
def load_audio(self, filepath, device):
import broken_decoder # noqa: F401

clip = tmp_path / "clip.wav"
clip.write_bytes(b"RIFF")
chunk, _ = _preprocess_failure(_AudioModel(), {"audio": [str(clip)]})
assert b"could not load libdecoder" in chunk.data
assert chunk.metadata["status"] == 500


def test_a_bug_in_a_loader_is_a_500(tmp_path):
class _BuggyModel:
def load_video(self, filepath, device):
raise KeyError("average_fps")

clip = tmp_path / "clip.mp4"
clip.write_bytes(b"\x00")
chunk, _ = _preprocess_failure(_BuggyModel(), {"video": [str(clip)]})
assert chunk.metadata["status"] == 500
11 changes: 11 additions & 0 deletions test/modular/test_flux2_klein_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,17 @@ def test_process_prompt_rejects_bad_geometry(kwargs, message):
_make_model().process_prompt("a cat", ["text"], ["image"], **kwargs)


@pytest.mark.parametrize("kwargs,message", [
({"output_format": "gif"}, "output_format"),
({"output_format": "jpeg", "output_compression": "high"}, "output_compression"),
({"png_compress_level": 10}, "png_compress_level"),
])
def test_process_prompt_rejects_bad_output_knobs(kwargs, message):
"""encode_image reads them after the GPU work, where a raise is a 500."""
with pytest.raises(ValueError, match=message):
_make_model().process_prompt("a cat", ["text"], ["image"], **kwargs)


def test_process_prompt_rejects_missing_prompt_or_wrong_modality():
model = _make_model()
with pytest.raises(ValueError, match="text prompt"):
Expand Down
Loading
Loading