Benchmark data statistics for each stage of omni models (#3628)
Signed-off-by: ZacheryAU <70869627+ZacheryAU@users.noreply.github.com>
This commit is contained in:
1 parent
e10aca30ec
commit
bfc7cedcf1
28 files changed
+2297
-152
No files matched your search
@@ -261,6 +261,7 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
data_parallel_rank: int | None = None,
|
||||
reasoning_ended: bool | None = None,
|
||||
reasoning_parser_kwargs: dict[str, Any] | None = None,
|
||||
arrival_time: float | None = None,
|
||||
) -> AsyncGenerator[OmniRequestOutput, None]:
|
||||
"""Generate outputs for the given prompt(s) asynchronously.
|
||||
|
||||
@@ -334,11 +335,12 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
)
|
||||
|
||||
# Track per-request metrics
|
||||
wall_start_ts = time.time()
|
||||
wall_start_ts = float(arrival_time) if arrival_time is not None else time.time()
|
||||
req_start_ts: dict[str, float] = {}
|
||||
|
||||
# Determine the final stage for E2E stats
|
||||
final_stage_id_for_e2e = self._compute_final_stage_id(output_modalities)
|
||||
final_output_stage_ids = self._compute_final_output_stage_ids(output_modalities) or [final_stage_id_for_e2e]
|
||||
|
||||
metrics = OrchestratorMetrics(
|
||||
self.num_stages,
|
||||
@@ -372,6 +374,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
input_stream=prompt,
|
||||
sampling_params_list=req_sp_list,
|
||||
final_stage_id=final_stage_id_for_e2e,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
arrival_time=wall_start_ts,
|
||||
)
|
||||
else:
|
||||
await self.engine.add_request_async(
|
||||
@@ -379,6 +383,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
prompt=prompt,
|
||||
sampling_params_list=req_sp_list,
|
||||
final_stage_id=final_stage_id_for_e2e,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
arrival_time=wall_start_ts,
|
||||
)
|
||||
submit_ts = time.time()
|
||||
req_state.metrics.stage_first_ts[0] = submit_ts
|
||||
@@ -421,6 +427,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
input_stream: AsyncGenerator[StreamingInput, None],
|
||||
sampling_params_list: Sequence[OmniSamplingParams],
|
||||
final_stage_id: int,
|
||||
final_output_stage_ids: Sequence[int],
|
||||
arrival_time: float,
|
||||
) -> asyncio.Task:
|
||||
"""Submit a streaming input generator as incremental stage-0 updates."""
|
||||
if not sampling_params_list:
|
||||
@@ -456,6 +464,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
prompt_text=prompt_text,
|
||||
sampling_params_list=chunk_sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
arrival_time=arrival_time,
|
||||
resumable=True,
|
||||
)
|
||||
has_submitted_first_chunk = True
|
||||
@@ -466,6 +476,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
prompt_text=prompt_text,
|
||||
sampling_params_list=chunk_sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
arrival_time=arrival_time,
|
||||
resumable=True,
|
||||
)
|
||||
except (asyncio.CancelledError, GeneratorExit):
|
||||
@@ -492,6 +504,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
prompt_text=None,
|
||||
sampling_params_list=final_sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
arrival_time=arrival_time,
|
||||
resumable=False,
|
||||
)
|
||||
else:
|
||||
@@ -501,6 +515,8 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
prompt_text=None,
|
||||
sampling_params_list=final_sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
arrival_time=arrival_time,
|
||||
resumable=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -131,6 +131,31 @@ def add_seed_tts_cli_args(parser: argparse.ArgumentParser) -> None:
|
||||
)
|
||||
|
||||
|
||||
def add_omni_benchmark_cli_args(parser: argparse.ArgumentParser) -> None:
|
||||
"""Add vLLM-Omni specific serving benchmark options."""
|
||||
group = parser.add_argument_group("vLLM-Omni Multi-stage Benchmark Options")
|
||||
group.add_argument(
|
||||
"--print-stage",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help=(
|
||||
"Print per-stage benchmark metrics for --omni serving when stage metrics are returned by the server. "
|
||||
"Disabled by default. The latency sections follow --percentile-metrics by modality: "
|
||||
"ttft/tpot/itl control text stages, ttfc/tpoc/icl control internal stream stages, "
|
||||
"and tpop controls both text TPOP and internal stream TPOP."
|
||||
),
|
||||
)
|
||||
group.add_argument(
|
||||
"--image-edits-bot-task",
|
||||
type=str,
|
||||
default="think",
|
||||
help=(
|
||||
"Default bot_task form field for --backend openai-image-edits-omni "
|
||||
'(/v1/images/edits). Use --extra-body \'{"bot_task":"..."}\' to override per run.'
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
_OMNI_BENCH_DATASET_CHOICES = (
|
||||
"daily-omni",
|
||||
"seed-tts",
|
||||
@@ -173,16 +198,39 @@ class OmniBenchmarkServingSubcommand(OmniBenchmarkSubcommandBase):
|
||||
# Add Daily-Omni specific arguments
|
||||
add_daily_omni_cli_args(parser)
|
||||
add_seed_tts_cli_args(parser)
|
||||
add_omni_benchmark_cli_args(parser)
|
||||
|
||||
for action in parser._actions:
|
||||
if action.dest == "dataset_name" and action.choices is not None:
|
||||
extra = [
|
||||
c
|
||||
for c in (
|
||||
"daily-omni",
|
||||
"seed-tts",
|
||||
"seed-tts-text",
|
||||
"seed-tts-design",
|
||||
"ttsd",
|
||||
"sound-effect",
|
||||
)
|
||||
if c not in action.choices
|
||||
]
|
||||
if extra:
|
||||
action.choices = list(action.choices) + extra
|
||||
if action.dest == "backend" and action.choices is not None:
|
||||
extra = [c for c in ("openai-image-edits-omni",) if c not in action.choices]
|
||||
if extra:
|
||||
action.choices = list(action.choices) + extra
|
||||
_extend_omni_dataset_name_choices(parser)
|
||||
|
||||
# Update help messages for omni-specific features
|
||||
for action in parser._actions:
|
||||
if action.dest == "percentile_metrics":
|
||||
action.help = (
|
||||
"Comma-separated list of selected metrics to report percentiles."
|
||||
"This argument specifies the metrics to report percentiles."
|
||||
'Allowed metric names are "ttft", "tpot", "itl", "e2el", "audio_ttfp", "audio_rtf". '
|
||||
"Comma-separated list of selected metrics to report percentiles. "
|
||||
'For text metrics, "ttft", "tpot", and "itl" affect the global benchmark and text '
|
||||
'stage metrics. "tpop" also requests text TPOT/TPOP globally and per stage, and internal '
|
||||
'stream TPOP. "ttfc", "tpoc", and "icl" only affect internal stream stage metrics. '
|
||||
'Audio metrics include "audio_ttfp", "audio_rtf", "audio_duration", and "audio_underrun".'
|
||||
)
|
||||
if action.dest == "random_mm_limit_mm_per_prompt":
|
||||
action.help = (
|
||||
@@ -216,4 +264,9 @@ class OmniBenchmarkServingSubcommand(OmniBenchmarkSubcommandBase):
|
||||
os.environ["SEED_TTS_WER_EVAL"] = "1"
|
||||
if getattr(args, "seed_tts_wer_save_items", False):
|
||||
os.environ["SEED_TTS_WER_SAVE_ITEMS"] = "1"
|
||||
image_edits_bot_task = getattr(args, "image_edits_bot_task", None)
|
||||
if image_edits_bot_task is not None:
|
||||
extra_body = dict(getattr(args, "extra_body", None) or {})
|
||||
extra_body.setdefault("bot_task", image_edits_bot_task)
|
||||
args.extra_body = extra_body
|
||||
main(args)
|
||||
@@ -121,6 +121,7 @@ class Omni(OmniBase):
|
||||
for req_id, prompt in zip(request_ids, request_prompts):
|
||||
prompt_modalities = prompt.get("modalities", None) if isinstance(prompt, dict) else None
|
||||
final_stage_id = self._compute_final_stage_id(prompt_modalities)
|
||||
final_output_stage_ids = self._compute_final_output_stage_ids(prompt_modalities) or [final_stage_id]
|
||||
req_final_stage_ids[req_id] = final_stage_id
|
||||
|
||||
metrics = OrchestratorMetrics(
|
||||
@@ -145,6 +146,7 @@ class Omni(OmniBase):
|
||||
prompt=prompt,
|
||||
sampling_params_list=req_sp_list,
|
||||
final_stage_id=final_stage_id,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
)
|
||||
submit_ts = time.time()
|
||||
req_state.metrics.stage_first_ts[0] = submit_ts
|
||||
|
||||
@@ -22,7 +22,7 @@ from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
|
||||
from vllm_omni.entrypoints.utils import coerce_param_message_types, get_final_stage_id_for_e2e
|
||||
from vllm_omni.metrics.modality import OmniModalityMetrics, observe_modality_at_finalize
|
||||
from vllm_omni.metrics.prometheus import OmniPrometheusMetrics
|
||||
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
|
||||
from vllm_omni.metrics.stats import OrchestratorAggregator
|
||||
from vllm_omni.metrics.transfer import OmniTransferMetrics
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
@@ -189,6 +189,7 @@ class OmniBase(PDDisaggregationMixin):
|
||||
self.async_chunk = bool(getattr(self.engine, "async_chunk", False))
|
||||
|
||||
self.request_states: dict[str, ClientRequestState] = {}
|
||||
self._consumed_metric_messages: dict[str, set[int]] = {}
|
||||
self.prom_metrics = OmniPrometheusMetrics(model_name=model, log_stats=log_stats)
|
||||
self.mod_metrics = OmniModalityMetrics(model_name=model, log_stats=log_stats)
|
||||
|
||||
@@ -308,6 +309,7 @@ class OmniBase(PDDisaggregationMixin):
|
||||
)
|
||||
finally:
|
||||
self.request_states.pop(request_id, None)
|
||||
self._consumed_metric_messages.pop(request_id, None)
|
||||
# Republish gauges so any stale value left by the per-stage
|
||||
# publish in _process_single_result (which runs while the request
|
||||
# is still in self.request_states) is corrected after the pop.
|
||||
@@ -326,6 +328,17 @@ class OmniBase(PDDisaggregationMixin):
|
||||
self._stage_meta_list,
|
||||
)
|
||||
|
||||
def _compute_final_output_stage_ids(self, output_modalities: list[str] | None) -> list[int]:
|
||||
requested_modalities = output_modalities or self.output_modalities
|
||||
requested_modalities = [m for m in requested_modalities if m in self.output_modalities]
|
||||
if not requested_modalities:
|
||||
requested_modalities = self.output_modalities
|
||||
return [
|
||||
sid
|
||||
for sid, stage in enumerate(self._stage_meta_list)
|
||||
if getattr(stage, "final_output", False) and stage.final_output_type in requested_modalities
|
||||
]
|
||||
|
||||
def _process_stage_metrics_message(self, msg: StageMetricsMessage) -> None:
|
||||
req_id = msg.request_id
|
||||
req_state = self.request_states.get(req_id)
|
||||
@@ -333,7 +346,8 @@ class OmniBase(PDDisaggregationMixin):
|
||||
return
|
||||
_m = msg.metrics
|
||||
stage_id = msg.stage_id
|
||||
req_state.metrics.on_stage_metrics(stage_id, req_id, _m)
|
||||
stage_meta = self.engine.get_stage_metadata(stage_id)
|
||||
req_state.metrics.on_stage_metrics(stage_id, req_id, _m, stage_meta.final_output_type)
|
||||
submit_ts = msg.stage_submit_ts
|
||||
now = time.time()
|
||||
if req_state.metrics.stage_first_ts[stage_id] is None:
|
||||
@@ -378,6 +392,20 @@ class OmniBase(PDDisaggregationMixin):
|
||||
|
||||
req_state.stage_id = stage_id
|
||||
|
||||
if msg.metrics is not None and not msg.finished and req_state.metrics is not None:
|
||||
stage_meta = self.engine.get_stage_metadata(stage_id)
|
||||
output_type = getattr(msg.engine_outputs, "final_output_type", stage_meta.final_output_type)
|
||||
msg_id = id(msg)
|
||||
consumed = self._consumed_metric_messages.setdefault(req_id, set())
|
||||
if msg_id not in consumed:
|
||||
req_state.metrics.on_stage_metrics(stage_id, req_id, msg.metrics, output_type)
|
||||
submit_ts = msg.stage_submit_ts
|
||||
now = time.time()
|
||||
if req_state.metrics.stage_first_ts[stage_id] is None:
|
||||
req_state.metrics.stage_first_ts[stage_id] = submit_ts if submit_ts is not None else now
|
||||
req_state.metrics.stage_last_ts[stage_id] = max(req_state.metrics.stage_last_ts[stage_id] or 0.0, now)
|
||||
consumed.add(msg_id)
|
||||
|
||||
return False, req_id, stage_id, req_state
|
||||
|
||||
def _check_engine_output_error(
|
||||
@@ -415,7 +443,7 @@ class OmniBase(PDDisaggregationMixin):
|
||||
self,
|
||||
result: OutputMessage,
|
||||
stage_id: int,
|
||||
metrics: OrchestratorMetrics,
|
||||
metrics: OrchestratorAggregator,
|
||||
req_start_ts: dict[str, float],
|
||||
wall_start_ts: float,
|
||||
final_stage_id_for_e2e: int,
|
||||
@@ -457,10 +485,11 @@ class OmniBase(PDDisaggregationMixin):
|
||||
metrics.stage_last_ts[stage_id] = max(metrics.stage_last_ts[stage_id] or 0.0, now)
|
||||
|
||||
_m = result.metrics
|
||||
if finished and _m is not None:
|
||||
metrics.on_stage_metrics(stage_id, req_id, _m)
|
||||
|
||||
stage_meta = self.engine.get_stage_metadata(stage_id)
|
||||
output_type = getattr(engine_outputs, "final_output_type", stage_meta.final_output_type)
|
||||
if finished and _m is not None:
|
||||
metrics.on_stage_metrics(stage_id, req_id, _m, output_type)
|
||||
|
||||
if not stage_meta.final_output:
|
||||
return None
|
||||
|
||||
@@ -510,6 +539,31 @@ class OmniBase(PDDisaggregationMixin):
|
||||
self.prom_metrics.set_waiting(max(0, total - running))
|
||||
|
||||
images = getattr(engine_outputs, "images", []) if output_type == "image" else []
|
||||
response_metrics: dict[str, Any] = {}
|
||||
stage_metrics: dict[str, dict[str, Any]] = {}
|
||||
rid_key = str(req_id)
|
||||
for evt in metrics.stage_events.get(rid_key, []):
|
||||
if evt.stage_id is None:
|
||||
continue
|
||||
sid = int(evt.stage_id)
|
||||
evt_stage_meta = self.engine.get_stage_metadata(sid)
|
||||
evt_output_type = evt.final_output_type
|
||||
if not evt_output_type:
|
||||
evt_output_type = evt_stage_meta.final_output_type
|
||||
stage_name = evt_stage_meta.model_stage
|
||||
sid_key = str(sid)
|
||||
stage_metrics[sid_key] = OrchestratorAggregator._merge_stage_metric_event(stage_metrics.get(sid_key), evt)
|
||||
stage_metrics[sid_key]["stage_name"] = stage_name or f"stage_{sid}"
|
||||
stage_metrics[sid_key]["final_output_type"] = evt_output_type
|
||||
if stage_metrics:
|
||||
response_metrics["stage_metrics"] = stage_metrics
|
||||
current_stage_metrics = stage_metrics.get(str(stage_id))
|
||||
if current_stage_metrics is not None:
|
||||
response_metrics["stage_id"] = current_stage_metrics["stage_id"]
|
||||
response_metrics["final_output_type"] = current_stage_metrics["final_output_type"]
|
||||
if current_stage_metrics["final_output_type"] == "text":
|
||||
response_metrics["num_tokens_in"] = current_stage_metrics["num_tokens_in"]
|
||||
response_metrics["num_tokens_out"] = current_stage_metrics["num_tokens_out"]
|
||||
return OmniRequestOutput(
|
||||
request_id=req_id or "",
|
||||
stage_id=stage_id,
|
||||
@@ -521,6 +575,7 @@ class OmniBase(PDDisaggregationMixin):
|
||||
trajectory_log_probs=getattr(engine_outputs, "trajectory_log_probs", None),
|
||||
trajectory_decoded=getattr(engine_outputs, "trajectory_decoded", None),
|
||||
_custom_output=getattr(engine_outputs, "_custom_output", {}),
|
||||
metrics=response_metrics,
|
||||
stage_durations=stage_durations,
|
||||
peak_memory_mb=peak_memory_mb,
|
||||
)
|
||||
|
||||
@@ -29,6 +29,7 @@ from PIL import Image
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.datastructures import State
|
||||
from starlette.routing import Route
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.anthropic.serving import AnthropicServingMessages
|
||||
from vllm.entrypoints.chat_utils import load_chat_template
|
||||
@@ -445,6 +446,7 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
|
||||
# OMNI: Pass supported_tasks to build_app (required by upstream vLLM)
|
||||
app = build_openai_app(args, supported_tasks)
|
||||
|
||||
# OMNI: Remove upstream routes that we override with omni-specific handlers
|
||||
_remove_route_from_app(app, "/v1/chat/completions", {"POST"})
|
||||
_remove_route_from_app(app, "/v1/models", {"GET"}) # Remove upstream /v1/models to use omni's handler
|
||||
@@ -477,8 +479,29 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
vllm_config.parallel_config._api_process_rank,
|
||||
listen_address,
|
||||
)
|
||||
|
||||
class _TimestampMiddleware:
|
||||
"""Pure-ASGI outermost wrapper that stamps HTTP request arrival time.
|
||||
|
||||
Wraps the fully-built Starlette app as an outer ASGI layer so no
|
||||
Starlette internals (user_middleware, middleware_stack, etc.) are
|
||||
touched. Websocket and lifespan scopes pass through unchanged.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: ASGIApp) -> None:
|
||||
self._inner = inner
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._inner, name)
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] == "http":
|
||||
scope.setdefault("state", {})
|
||||
scope["state"]["request_timestamp"] = time.time()
|
||||
await self._inner(scope, receive, send)
|
||||
|
||||
shutdown_task = await serve_http(
|
||||
app,
|
||||
_TimestampMiddleware(app),
|
||||
sock=sock,
|
||||
enable_ssl_refresh=args.enable_ssl_refresh,
|
||||
host=args.host,
|
||||
@@ -1592,6 +1615,7 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
Raises:
|
||||
HTTPException: For validation errors, missing engine, or generation failures
|
||||
"""
|
||||
request_timestamp = float(getattr(raw_request.state, "request_timestamp", time.time()))
|
||||
# Get engine client (AsyncOmni) from app state
|
||||
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
|
||||
|
||||
@@ -1654,6 +1678,7 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
extra_body=extra_body,
|
||||
request_id=f"img_gen-{random_uuid()}",
|
||||
raw_request=raw_request,
|
||||
arrival_time=request_timestamp,
|
||||
)
|
||||
if isinstance(generation_result, ErrorResponse):
|
||||
return JSONResponse(
|
||||
@@ -1736,6 +1761,7 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
stage_configs=stage_configs,
|
||||
prompt=prompt,
|
||||
request_id=request_id,
|
||||
arrival_time=request_timestamp,
|
||||
)
|
||||
|
||||
if result is None:
|
||||
@@ -1826,12 +1852,14 @@ async def edit_images(
|
||||
bot_task: str | None = Form(None),
|
||||
sys_type: str | None = Form(None),
|
||||
system_prompt: str | None = Form(None),
|
||||
return_stage_metrics: bool | None = Form(None),
|
||||
) -> ImageGenerationResponse:
|
||||
"""
|
||||
OpenAI-compatible image edit endpoint.
|
||||
"""
|
||||
|
||||
# 1. get engine and model
|
||||
request_timestamp = float(getattr(raw_request.state, "request_timestamp", time.time()))
|
||||
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
|
||||
if model is not None and model != model_name:
|
||||
raise HTTPException(
|
||||
@@ -2050,6 +2078,8 @@ async def edit_images(
|
||||
extra_body["sys_type"] = sys_type
|
||||
if system_prompt is not None:
|
||||
extra_body["system_prompt"] = system_prompt
|
||||
if return_stage_metrics is not None:
|
||||
extra_body["return_stage_metrics"] = return_stage_metrics
|
||||
|
||||
prompt_text = prompt.get("prompt", "")
|
||||
generation_result = await chat_handler.generate_diffusion_images(
|
||||
@@ -2057,6 +2087,7 @@ async def edit_images(
|
||||
extra_body=extra_body,
|
||||
reference_images=ref_b64_list,
|
||||
request_id=request_id,
|
||||
arrival_time=request_timestamp,
|
||||
stream=stream,
|
||||
model=model_name,
|
||||
output_format=output_format,
|
||||
|
||||
@@ -193,6 +193,10 @@ class ImageEditARDeltaChunk(BaseModel):
|
||||
index: int = Field(default=0, description="Completion index for the AR stage output")
|
||||
created: int = Field(..., description="Unix timestamp of when the stream was created")
|
||||
model: str = Field(..., description="Model used for the image edit request")
|
||||
metrics: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
description="Optional vLLM-Omni per-stage metrics snapshot for benchmark clients.",
|
||||
)
|
||||
|
||||
|
||||
class ImageEditImageChunk(BaseModel):
|
||||
@@ -205,6 +209,10 @@ class ImageEditImageChunk(BaseModel):
|
||||
size: str = Field(..., description="The generated image size")
|
||||
created: int = Field(..., description="Unix timestamp of when the stream was created")
|
||||
model: str = Field(..., description="Model used for the image edit request")
|
||||
metrics: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
description="Optional vLLM-Omni per-stage metrics snapshot for benchmark clients.",
|
||||
)
|
||||
|
||||
|
||||
class ImageEditStreamError(BaseModel):
|
||||
|
||||
@@ -216,6 +216,27 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
self._supported_speakers = set()
|
||||
return self._supported_speakers
|
||||
|
||||
@staticmethod
|
||||
def _truthy_extra_body_flag(request: Any, key: str) -> bool:
|
||||
if isinstance(request, dict):
|
||||
extra_body = request
|
||||
model_extra = {}
|
||||
else:
|
||||
extra_body = getattr(request, "extra_body", None) or {}
|
||||
model_extra = getattr(request, "model_extra", None) or {}
|
||||
value = extra_body.get(key, model_extra.get(key))
|
||||
if isinstance(value, str):
|
||||
return value.lower() in {"1", "true", "yes", "on"}
|
||||
return bool(value)
|
||||
|
||||
@classmethod
|
||||
def _filter_stage_metrics_detail(cls, metrics: dict[str, Any] | None, request: Any) -> dict[str, Any] | None:
|
||||
if not metrics:
|
||||
return metrics
|
||||
if cls._truthy_extra_body_flag(request, "return_stage_metrics"):
|
||||
return metrics
|
||||
return None
|
||||
|
||||
async def create_chat_completion(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
@@ -244,6 +265,10 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
if self._diffusion_mode:
|
||||
return await self._create_diffusion_chat_completion(request, raw_request)
|
||||
|
||||
request_timestamp = time.time()
|
||||
if raw_request is not None:
|
||||
request_timestamp = float(getattr(raw_request.state, "request_timestamp", request_timestamp))
|
||||
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
logger.error("Error with model %s", error_check_ret)
|
||||
@@ -555,6 +580,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
request_id=request_id,
|
||||
sampling_params_list=sampling_params_list,
|
||||
output_modalities=output_modalities,
|
||||
arrival_time=request_timestamp,
|
||||
)
|
||||
|
||||
generators.append(generator)
|
||||
@@ -1624,7 +1650,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
choices=[choice_data],
|
||||
model=model_name,
|
||||
modality=final_output_type,
|
||||
metrics=omni_res.metrics,
|
||||
metrics=self._filter_stage_metrics_detail(omni_res.metrics, request),
|
||||
)
|
||||
|
||||
# handle usage stats if requested & if continuous
|
||||
@@ -1705,6 +1731,48 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
choices=choices_data,
|
||||
model=model_name,
|
||||
modality=final_output_type,
|
||||
metrics=self._filter_stage_metrics_detail(omni_res.metrics, request),
|
||||
)
|
||||
chunk.usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=0,
|
||||
total_tokens=num_prompt_tokens,
|
||||
)
|
||||
data = chunk.model_dump_json(exclude_unset=True)
|
||||
yield f"data: {data}\n\n"
|
||||
|
||||
elif final_output_type == "image":
|
||||
role = self.get_chat_request_role(request)
|
||||
choices_data = []
|
||||
for choice in self._create_image_choice(omni_res, role, request, stream=True):
|
||||
delta = DeltaMessage.model_construct(role=role)
|
||||
object.__setattr__(delta, "content", choice.message.content)
|
||||
if hasattr(delta, "__pydantic_fields_set__"):
|
||||
delta.__pydantic_fields_set__.add("content")
|
||||
stream_choice = ChatCompletionResponseStreamChoice(
|
||||
index=choice.index,
|
||||
delta=delta,
|
||||
logprobs=None,
|
||||
finish_reason=choice.finish_reason,
|
||||
stop_reason=choice.stop_reason,
|
||||
)
|
||||
if stream_choice.finish_reason is not None:
|
||||
modality_finished[stream_choice.index].add("image")
|
||||
if modality_seen[stream_choice.index] < set(request.modalities) or not all(
|
||||
m in modality_finished[stream_choice.index] for m in modality_seen[stream_choice.index]
|
||||
):
|
||||
stream_choice.finish_reason = None
|
||||
else:
|
||||
stop_reason_emitted[stream_choice.index] = True
|
||||
choices_data.append(stream_choice)
|
||||
chunk = OmniChatCompletionStreamResponse(
|
||||
id=request_id,
|
||||
object=chunk_object_type,
|
||||
created=created_time,
|
||||
choices=choices_data,
|
||||
model=model_name,
|
||||
modality=final_output_type,
|
||||
metrics=self._filter_stage_metrics_detail(omni_res.metrics, request),
|
||||
)
|
||||
# NOTE: Currently usage is only set the text stages to align with the behavior
|
||||
# of the full generator. TODO (Alex): Add support for usage on all stages for
|
||||
@@ -1772,7 +1840,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
choices=[],
|
||||
model=model_name,
|
||||
usage=final_usage,
|
||||
metrics=last_metrics,
|
||||
metrics=self._filter_stage_metrics_detail(last_metrics, request),
|
||||
)
|
||||
final_usage_data = final_usage_chunk.model_dump_json(exclude_unset=True, exclude_none=True)
|
||||
yield f"data: {final_usage_data}\n\n"
|
||||
@@ -1926,6 +1994,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
response_metrics.update(extra)
|
||||
choices.extend(choices_data)
|
||||
|
||||
response_metrics = self._filter_stage_metrics_detail(response_metrics, request)
|
||||
|
||||
# Compute prompt_text for non-streaming response (upstream #42052)
|
||||
prompt_text = (
|
||||
getattr(final_res, "prompt", None)
|
||||
@@ -2248,6 +2318,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# omits "sr" and runs at 24kHz; Ming-flash-omni surfaces a 44.1kHz
|
||||
# AudioVAE rate via multimodal_output["sr"].
|
||||
sr_raw = mm_output.get("sr")
|
||||
if isinstance(sr_raw, (list, tuple)):
|
||||
sr_raw = next((item for item in sr_raw if item is not None), None)
|
||||
if sr_raw is None:
|
||||
sample_rate = 24000
|
||||
elif hasattr(sr_raw, "item"):
|
||||
@@ -2696,6 +2768,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
extra_body: dict[str, Any] | None = None,
|
||||
reference_images: list[str] | None = None,
|
||||
request_id: str | None = None,
|
||||
arrival_time: float | None = None,
|
||||
stream: bool = False,
|
||||
model: str | None = None,
|
||||
output_format: str = "png",
|
||||
@@ -2717,6 +2790,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
engine, gen_prompt, gen_params, pil_images = prepared
|
||||
if extra_body is None:
|
||||
extra_body = {}
|
||||
return_stage_metrics = self._truthy_extra_body_flag(extra_body, "return_stage_metrics")
|
||||
|
||||
if isinstance(engine, AsyncOmni):
|
||||
diffusion_engine = cast(AsyncOmni, engine)
|
||||
@@ -2755,6 +2829,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
prompt=engine_prompt,
|
||||
sampling_params_list=sampling_params_list,
|
||||
request_id=request_id,
|
||||
arrival_time=arrival_time,
|
||||
)
|
||||
if stream:
|
||||
return self._stream_diffusion_image_chunks(
|
||||
@@ -2763,6 +2838,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
output_format=output_format,
|
||||
output_compression=output_compression,
|
||||
size=size,
|
||||
return_stage_metrics=return_stage_metrics,
|
||||
raw_request=raw_request,
|
||||
)
|
||||
|
||||
@@ -2818,6 +2894,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
output_format: str,
|
||||
output_compression: int,
|
||||
size: str,
|
||||
return_stage_metrics: bool,
|
||||
raw_request: Request | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Yield image edit SSE chunks from multi-stage diffusion outputs."""
|
||||
@@ -2827,6 +2904,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
async for output in result_generator:
|
||||
final_output_type = getattr(output, "final_output_type", None)
|
||||
stage_id = getattr(output, "stage_id", None)
|
||||
metrics = getattr(output, "metrics", None) if return_stage_metrics else None
|
||||
if final_output_type == "text" and stage_id == 0:
|
||||
request_output = output.request_output
|
||||
for completion in request_output.outputs:
|
||||
@@ -2838,6 +2916,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
index=completion.index,
|
||||
created=created,
|
||||
model=model,
|
||||
metrics=metrics,
|
||||
)
|
||||
yield f"data: {chunk.model_dump_json()}\n\n"
|
||||
elif final_output_type == "image":
|
||||
@@ -2861,6 +2940,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
size=size,
|
||||
created=created,
|
||||
model=model,
|
||||
metrics=metrics,
|
||||
)
|
||||
yield f"data: {chunk.model_dump_json()}\n\n"
|
||||
emitted_image = True
|
||||
|
||||
Reference in new issue
Block a user