diff --git a/.gitignore b/.gitignore index 79a8d98..0234e2e 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,13 @@ __pycache__/ !mlperf-data/mlperf-*.csv !mlperf-data/summaries/*.csv !datasets/summaries/*.csv +!manual_runs/scripts/vllm-omni/templates/*.csv +# Populated local datasets and builder outputs contain deployment/MLflow IDs; keep them out of git. +datasets/omni/consolidated_dashboard_omni.csv +datasets/omni/consolidated_dashboard_omni.csv.* +datasets/omni/consolidated_dashboard_omni_legacy.csv +datasets/omni/consolidated_dashboard_omni_legacy.csv.* +datasets/omni/logs/ vllm-cpu-perf-eval/ # Ignore large original dataset files in datasets/ (pkl, parquet, npy) diff --git a/README.md b/README.md index b7c8d22..18b8963 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # AI Inference Performance Dashboard -A comprehensive performance analysis dashboard for AI inference benchmarks including RHAIIS (Red Hat AI Inference Server), LLM-D (disaggregated LLM inference), and MLPerf submissions. This dashboard provides interactive visualizations and analysis of AI model performance across different accelerators, versions, and configurations. +A comprehensive performance analysis dashboard for AI inference benchmarks including RHAIIS (Red Hat AI Inference Server), LLM-D (disaggregated LLM inference), vLLM-Omni (speech-in, speech-out, and text), and MLPerf submissions. This dashboard provides interactive visualizations and analysis of AI model performance across different accelerators, versions, and configurations. ## Features @@ -24,6 +24,14 @@ A comprehensive performance analysis dashboard for AI inference benchmarks inclu - **Performance Plots**: Interactive visualizations with multiple Y-axis metric options - **Runtime Configuration Tracking**: View server configurations and deployment parameters +### Omni Dashboard + +- **Speech, ASR, and text views**: Filter one consolidated CSV by modality, task type, load generator, model, runtime, accelerator, and concurrency +- **Speech-out metrics**: Audio TTFP, RTF, underrun, audio throughput, and streaming continuity +- **ASR metrics**: WER, RTFx, transcription throughput, and input-audio duration +- **Text metrics**: TTFT, TPOT, ITL, E2EL, and token throughput +- **Extensible schema**: One row per benchmark point; modality-inapplicable fields may be blank, and future metrics live in `extra_json` + ### MLPerf Dashboard - **Multi-Version Support**: Compare MLPerf v5.0 and v5.1 submissions @@ -270,6 +278,28 @@ When you have code changes: 2. **Consolidate data**: Merge new results with existing CSV file +## Omni Data Management + +The Omni dashboard reads `datasets/omni/consolidated_dashboard_omni.csv` locally, or the `S3_KEY_OMNI` object when `S3_BUCKET` is set. Header-only templates are included: + +- `manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_template.csv` +- `manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_tts_template.csv` + +Build the staged 77-column TTS CSV: + +```bash +python manual_runs/scripts/vllm-omni/build_omni_tts_csv.py \ + --recipe-root ~/omni-perf-benchmark-recipe \ + --output datasets/omni/consolidated_dashboard_omni.csv +``` + +The older 165-column converter +(`manual_runs/scripts/vllm-omni/build_consolidated_omni_csv.py`) remains for the +legacy schema/template. + +See `docs/omni-dashboard.md` for the schema, units, dashboard sections, and +configuration. + ## MLPerf Data Management ### MLPerf CSV Files @@ -369,14 +399,15 @@ See [tests/README.md](tests/README.md) for detailed test documentation. The dashboard can load CSV data directly from an AWS S3 bucket instead of local files. This is useful for production deployments where data is updated externally. -| Variable | Description | Default | -| ----------------------- | ----------------------------------------- | ---------------------------- | -| `S3_BUCKET` | S3 bucket name (enables S3 mode when set) | _(none)_ | -| `S3_KEY` | Path to RHAIIS CSV in bucket | `consolidated_dashboard.csv` | -| `S3_KEY_LLMD` | Path to LLM-D CSV in bucket | `llmd-dashboard.csv` | -| `S3_REGION` | AWS region | `us-east-1` | -| `AWS_ACCESS_KEY_ID` | AWS access key (for private buckets) | _(none)_ | -| `AWS_SECRET_ACCESS_KEY` | AWS secret key (for private buckets) | _(none)_ | +| Variable | Description | Default | +| ----------------------- | ----------------------------------------- | --------------------------------- | +| `S3_BUCKET` | S3 bucket name (enables S3 mode when set) | _(none)_ | +| `S3_KEY` | Path to RHAIIS CSV in bucket | `consolidated_dashboard.csv` | +| `S3_KEY_LLMD` | Path to LLM-D CSV in bucket | `llmd-dashboard.csv` | +| `S3_KEY_OMNI` | Path to Omni CSV in bucket | `consolidated_dashboard_omni.csv` | +| `S3_REGION` | AWS region | `us-east-1` | +| `AWS_ACCESS_KEY_ID` | AWS access key (for private buckets) | _(none)_ | +| `AWS_SECRET_ACCESS_KEY` | AWS secret key (for private buckets) | _(none)_ | **Behavior:** @@ -393,6 +424,7 @@ export AWS_SECRET_ACCESS_KEY='your-secret' export S3_BUCKET='your-s3-bucket' export S3_KEY='location of the consolidated-dashboard.csv file in the bucket' export S3_KEY_LLMD='location of the llmd-dashboard.csv file in the bucket' +export S3_KEY_OMNI='location of the consolidated_dashboard_omni.csv file in the bucket' export S3_REGION='us-east-1' # Run the dashboard diff --git a/dashboard.py b/dashboard.py index f62443d..960fd7d 100644 --- a/dashboard.py +++ b/dashboard.py @@ -160,6 +160,15 @@ def _render_methodology_note(versions): CPU_AVAILABLE = False print("Warning: cpu_dashboard module not found. vLLM CPU view will be disabled.") +# Import Omni dashboard +try: + from omni_dashboard import render_omni_dashboard + + OMNI_AVAILABLE = True +except ImportError: + OMNI_AVAILABLE = False + print("Warning: omni_dashboard module not found. Omni view will be disabled.") + # Configure logging to stdout for container logs logging.basicConfig( level=logging.INFO, @@ -173,6 +182,7 @@ def _render_methodology_note(versions): S3_KEY = os.environ.get("S3_KEY", "consolidated_dashboard.csv") S3_KEY_LLMD = os.environ.get("S3_KEY_LLMD", "llmd-dashboard.csv") S3_KEY_CPU = os.environ.get("S3_KEY_CPU", "cpu_dashboard.csv") +S3_KEY_OMNI = os.environ.get("S3_KEY_OMNI", "consolidated_dashboard_omni.csv") S3_REGION = os.environ.get("S3_REGION", "us-east-1") AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") @@ -180,6 +190,7 @@ def _render_methodology_note(versions): S3_LOGS_PREFIX = os.environ.get("S3_LOGS_PREFIX", "logs/") MLFLOW_BASE_URL = os.environ.get("MLFLOW_BASE_URL", "") MLFLOW_WORKSPACE = os.environ.get("MLFLOW_WORKSPACE", "forge-rhaiis") +DEFAULT_DASHBOARD_VIEW = os.environ.get("DEFAULT_DASHBOARD_VIEW", "RHAIIS Dashboard") # ── Overview version configuration (single source of truth) ────── @@ -12404,12 +12415,16 @@ def render_sidebar_header(): view_options.append("LLM-D Dashboard") if CPU_AVAILABLE: view_options.append("vLLM CPU Dashboard") + if OMNI_AVAILABLE: + view_options.append("Omni Dashboard") if len(view_options) > 1: # Pre-populate the widget key so we never need the `index` # param (which can conflict with the key and eat the first click). if "dashboard_view_selector" not in st.session_state: - current_view = st.session_state.get("selected_view", "RHAIIS Dashboard") + current_view = st.session_state.get( + "selected_view", DEFAULT_DASHBOARD_VIEW + ) st.session_state.dashboard_view_selector = ( current_view if current_view in view_options else view_options[0] ) @@ -12466,6 +12481,7 @@ def render_confidentiality_notice(): "MLPerf Dashboard", "LLM-D Dashboard", "vLLM CPU Dashboard", + "Omni Dashboard", ]: st.session_state.selected_view = view_from_url st.session_state.dashboard_view_selector = view_from_url @@ -12609,6 +12625,11 @@ def render_confidentiality_notice(): render_cpu_dashboard("cpu_dashboard.csv") st.stop() # Stop execution here, don't load RHAIIS data +# If Omni view is selected, render Omni dashboard and exit +if OMNI_AVAILABLE and selected_view == "Omni Dashboard": + render_omni_dashboard("datasets/omni/consolidated_dashboard_omni.csv") + st.stop() # Stop execution here, don't load RHAIIS data + # Otherwise, continue with RHAIIS dashboard DATA_FILE = "consolidated_dashboard.csv" diff --git a/deploy/openshift-deployment-staging.yaml b/deploy/openshift-deployment-staging.yaml index c7c41f7..27611b5 100644 --- a/deploy/openshift-deployment-staging.yaml +++ b/deploy/openshift-deployment-staging.yaml @@ -56,6 +56,8 @@ spec: value: "the location of the llmd-dashboard.csv file" - name: S3_KEY_CPU value: "the location of the cpu_dashboard.csv file" + - name: S3_KEY_OMNI + value: "staging/omni-dashboard/omni_dashboard.csv" - name: S3_REGION value: "the region of your bucket" # S3 Configuration for logs diff --git a/docs/omni-dashboard.md b/docs/omni-dashboard.md new file mode 100644 index 0000000..72b5830 --- /dev/null +++ b/docs/omni-dashboard.md @@ -0,0 +1,106 @@ +# Omni Dashboard + +The Omni view covers speech-out (TTS) benchmarking for vLLM-Omni. The current staged rollout is TTS-only — Qwen3-TTS and OmniVoice, streaming and non-streaming, WAV and PCM. ASR, chat-completions TTS, and realtime endpoints are not in the staged CSV yet. + +The dashboard is a view over the benchmark data; it does not change collection. + +## Data flow + +``` +benchmark runner → local result JSON + logs → MLflow + ↓ + build_omni_tts_csv.py + ↓ + consolidated_dashboard_omni.csv + ↓ + dashboard (local file or S3) +``` + +- MLflow stores the run hierarchy and artifacts. The dashboard uses it for **View Logs** and run hyperlinks, not for benchmark metrics. +- The dashboard reads the CSV from `datasets/omni/consolidated_dashboard_omni.csv`, or from S3 when `S3_BUCKET` is set. +- New benchmark runs do not appear automatically. Rebuild the CSV and, when using S3, upload the new object. + +## CSV schema + +The staged schema is **77 columns**. The canonical header is in `manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_tts_template.csv`; the populated CSV is not committed. + +| Group | Contents | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Identity | `run_key`, `run_name`, `timestamp_utc`, `cluster`, `deployment_uuid`, `mlflow_run_id`, `source_file` | +| Model/runtime | `model`, `runtime_version`, `image_tag`, `accelerator`, `gpu_count`, `tp`, `runtime_args` | +| Task/protocol | `modality`, `input_modality`, `output_modality`, `task_type`, `recipe`, `experiment_phase`, `benchmark_tool`, `load_generator`, `api_endpoint`, `benchmark_backend`, `benchmark_mode`, `response_format`, `tokenizer_override`, `status` | +| Workload | `dataset`, `locale`, `num_prompts`, `request_rate`, `concurrency`, `measured_concurrency`, `short_window` | +| Outcome | `duration_s`, `successful_requests`, `errored_requests`, `e2el_ms_{mean,median,p95,p99}`, `request_throughput_rps` | +| Stage/system | `stage_0/1_ttft_ms_{p50,p95}`, `stage_0/1_gen_time_ms_{p50,p95}`, `transfer_tx_ms_{p50,p95}` | +| Audio output | `audio_ttfp_ms_*`, `audio_rtf_*`, `audio_duration_s_*`, `audio_underrun_s_*`, `audio_throughput_x`, `audio_output_duration_s_total`, `audio_frames_total`, `audio_sample_rate_hz`, `audio_continuity_ok_rate`, plus format/coverage fields | +| Extra | `notes` | + +Notes: + +- `recipe` is the deployment configuration (`default`, `b8`). Source metadata still calls it `profile`. +- `num_prompts` is **N**, the measured requests per benchmark point, excluding warmups and burn-in. +- `short_window` is true when the measured duration is below 30 s. +- Stage columns are blank when the bench JSON has no stage durations. +- The legacy 165-column template (`manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_template.csv`) remains for the older converter. The staged dashboard uses the 77-column template. + +## Build + +```bash +python3 manual_runs/scripts/vllm-omni/build_omni_tts_csv.py \ + --recipe-root ~/omni-perf-benchmark-recipe \ + --output datasets/omni/consolidated_dashboard_omni.csv +``` + +Optional: `--mlflow-runs-json` accepts a saved MLflow runs/search response to fill `mlflow_run_id` for runs not present in local metadata. The builder reads the 3.5 legacy CSV/JSONs, the 3.6 base CI/saturation JSONs, and the Athena matrix cells. + +## Dashboard sections + +- **Overview** — summary tiles and coverage. +- **Performance Plots** — concurrency on a log2 axis with ticks at the actual ladder; Y-axis includes throughput, audio TTFP/RTF/underrun, audio throughput, and request count (N); Streaming, Response format, and 3.5 legacy toggles; hover shows N, format, UUID, and resolved runtime args; repeated deployments use distinct line styles. +- **Compare Versions** — matches on model, task, dataset, concurrency, load generator, TP, accelerator, and response format; recipe is shown in labels. +- **View Logs** — one entry per deployment; the vLLM server log is the default source, with a per-concurrency bench-log selector; MLflow/local/S3 fallbacks. +- **Filtered Data** — curated default columns, MLflow and Grafana links, "show all columns", and CSV download. + +Filters and compare selections persist in URL query parameters. + +## Configuration + +S3 (CSV and logs): + +```bash +export S3_BUCKET='' +export S3_KEY_OMNI='/omni_dashboard.csv' +export S3_REGION='us-east-1' +export S3_LOGS_BUCKET='' # optional, for View Logs +export S3_LOGS_PREFIX='logs/' # optional +``` + +The CSV is cached for 5 minutes. AWS credentials use the standard provider chain (environment variables, shared config, or instance role). Set `S3_ANONYMOUS=true` only for a public bucket. + +Observability links (optional; no URLs are committed): + +```bash +export MLFLOW_TRACKING_URI='' +export MLFLOW_BASE_URL='' +export MLFLOW_WORKSPACE='' +export OMNI_MLFLOW_EXPERIMENT_ID='' +export GRAFANA_BASE_URL='' +export OMNI_GRAFANA_DASHBOARD_UID='' +``` + +If an observability variable is unset, the corresponding link is blank. + +## Caveats + +- **Voxtral streaming WAV** is unsupported: the first audio chunk lacks sample-rate metadata. Use streaming PCM, non-streaming WAV, or wait for the upstream fix. +- **Do not compare across workloads directly.** 3.5 legacy uses N=100 and c1–c25; the 3.6 matrix uses N=1000 and c1–c128. Compare only at the same model/version, N, concurrency, streaming mode, response format, and 24 kHz sample rate. +- **OmniVoice is single-stage.** Its underrun is 0 by construction, not a streaming win; use TTFP ≈ E2EL when discussing it. +- **Stage metrics** are blank unless the run emits stage durations. + +## Tests + +```bash +python3 -m pytest -o addopts="" -q +``` + +The data CSV, backups, and logs are intentionally not versioned; only the templates and converter are. diff --git a/manual_runs/scripts/vllm-omni/README.md b/manual_runs/scripts/vllm-omni/README.md new file mode 100644 index 0000000..764d6f1 --- /dev/null +++ b/manual_runs/scripts/vllm-omni/README.md @@ -0,0 +1,78 @@ +# vLLM-Omni Manual Runs + +Scripts for turning manual vLLM-Omni benchmark artifacts into the Omni +dashboard CSV. + +## Scripts + +| Script | Purpose | +| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `build_omni_tts_csv.py` | Build the staged 77-column TTS dashboard CSV from the 3.5 legacy, 3.6 base, and 3.6 Athena results. | +| `build_consolidated_omni_csv.py` | Build the older 165-column consolidated schema used by the legacy converter. | +| `extract_mlflow_runs.py` | Optional MLflow export/backfill helper. Writes `runs.json` so the CSV builder can attach MLflow links when the benchmark files have no run ID. | + +The dashboard reads the finished CSV; it does not import these scripts. + +## Manual workflow + +```text +1. vllm bench serve -> result JSONs (no MLflow ID) +2. export_athena_csv.py -> raw benchmark CSV (no MLflow ID) +3. log_to_mlflow.py -> MLflow runs (IDs live only in MLflow) +4. extract_mlflow_runs.py -> runs.json (IDs copied locally) +5. build_omni_tts_csv.py -> dashboard CSV (IDs joined into rows) +6. dashboard / S3 -> MLflow links + logs +``` + +`extract_mlflow_runs.py` is kept as executable documentation for the manual +backfill step. Future runs can avoid it by writing the ID mapping during the +MLflow upload step. + +## Build the staged TTS CSV + +```bash +python3 manual_runs/scripts/vllm-omni/build_omni_tts_csv.py \ + --recipe-root ~/omni-perf-benchmark-recipe \ + --output datasets/omni/consolidated_dashboard_omni.csv +``` + +Optional MLflow backfill: + +```bash +export MLFLOW_TRACKING_URI='' +export MLFLOW_WORKSPACE='' +export MLFLOW_TRACKING_USERNAME='' +export MLFLOW_TRACKING_PASSWORD='' + +python3 manual_runs/scripts/vllm-omni/extract_mlflow_runs.py \ + --experiment-id \ + --name-regex '' \ + --artifact-pattern 'results/*.json' \ + --artifact-pattern 'logs/*.log' \ + --output-dir ~/Downloads/mlflow-extract + +python3 manual_runs/scripts/vllm-omni/build_omni_tts_csv.py \ + --recipe-root ~/omni-perf-benchmark-recipe \ + --mlflow-runs-json ~/Downloads/mlflow-extract/runs.json \ + --output datasets/omni/consolidated_dashboard_omni.csv +``` + +## Build the legacy schema + +```bash +python3 manual_runs/scripts/vllm-omni/build_consolidated_omni_csv.py \ + --omni-json path/to/omni-json/ \ + --legacy-csv path/to/legacy-benchmark_results.csv \ + --output datasets/omni/consolidated_dashboard_omni_legacy.csv +``` + +Add `--metadata-json PATH` when you have defaults or pattern overrides to supply. + +See `docs/omni-dashboard.md` for the schema, dashboard sections, and deployment +configuration. + +## Requirements + +- Python 3.9+ +- `mlflow` only for `extract_mlflow_runs.py` +- `pandas`/`streamlit` only for running the dashboard diff --git a/manual_runs/scripts/vllm-omni/build_consolidated_omni_csv.py b/manual_runs/scripts/vllm-omni/build_consolidated_omni_csv.py new file mode 100644 index 0000000..f547028 --- /dev/null +++ b/manual_runs/scripts/vllm-omni/build_consolidated_omni_csv.py @@ -0,0 +1,966 @@ +#!/usr/bin/env python3 +"""Build the consolidated Omni benchmark dashboard CSV. + +One row per benchmark point (model + runtime + task + dataset + concurrency/ +request-rate + repetition). Blanks are allowed for modality-inapplicable +fields; the dashboard should filter on modality/task_type. + +Usage: + python3 manual_runs/scripts/vllm-omni/build_consolidated_omni_csv.py \ + [--metadata-json PATH] \ + --omni-json path/to/omni-json/ \ + --legacy-csv path/to/legacy-benchmark_results.csv \ + --output datasets/omni/consolidated_dashboard_omni_legacy.csv + +Future metrics go in `extra_json` until promoted to a first-class column. +""" + +import argparse +import csv +import datetime as dt +import fnmatch +import glob +import hashlib +import json +import os +import re +from collections import Counter + +SCHEMA_VERSION = "1.0" + +CORE_COLUMNS = [ + "schema_version", + "source_format", + "timestamp_utc", + "run_name", + "benchmark_run_id", + "repetition", + "mlflow_run_id", + "mlflow_parent_run_id", + "mlflow_experiment_id", + "cluster", + "namespace", + "deployment_uuid", + "deployment_pod_name", + "grafana_dashboard_uid", + "model", + "model_revision", + "runtime", + "runtime_version", + "vllm_version", + "vllm_omni_version", + "image_tag", + "image_digest", + "accelerator", + "gpu_count", + "tp", + "pp", + "dp", + "modality", + "input_modality", + "output_modality", + "task_type", + "benchmark_tool", + "benchmark_tool_version", + "load_generator", + "dataset", + "dataset_path", + "dataset_split", + "locale", + "num_prompts", + "num_utterances", + "request_rate", + "concurrency", + "measured_concurrency", + "num_warmups", + "turns", + "prefix_tokens", + "prefix_count", + "prefix_caching", + "spec_decoding", + "request_type", + "extra_body_json", + "runtime_args", + "env_vars_json", + "max_num_seqs", + "max_num_batched_tokens", + "duration_s", + "successful_requests", + "errored_requests", + "benchmark_start_ms", + "benchmark_end_ms", +] + +TEXT_COLUMNS = [ + "prompt_tokens_requested", + "output_tokens_requested", + "prompt_tokens_total", + "output_tokens_total", + "prompt_tokens_mean", + "prompt_tokens_p99", + "output_tokens_mean", + "output_tokens_p99", + "ttft_ms_mean", + "ttft_ms_median", + "ttft_ms_std", + "ttft_ms_p25", + "ttft_ms_p50", + "ttft_ms_p75", + "ttft_ms_p90", + "ttft_ms_p95", + "ttft_ms_p99", + "tpot_ms_mean", + "tpot_ms_median", + "tpot_ms_std", + "tpot_ms_p50", + "tpot_ms_p95", + "tpot_ms_p99", + "itl_ms_mean", + "itl_ms_median", + "itl_ms_std", + "itl_ms_p50", + "itl_ms_p95", + "itl_ms_p99", + "e2el_ms_mean", + "e2el_ms_median", + "e2el_ms_std", + "e2el_ms_p25", + "e2el_ms_p50", + "e2el_ms_p75", + "e2el_ms_p90", + "e2el_ms_p95", + "e2el_ms_p99", + "e2el_ms_min", + "e2el_ms_max", + "request_throughput_rps", + "output_token_throughput", + "total_token_throughput", +] + +SPEECH_COLUMNS = [ + "audio_ttfp_ms_mean", + "audio_ttfp_ms_median", + "audio_ttfp_ms_std", + "audio_ttfp_ms_p25", + "audio_ttfp_ms_p50", + "audio_ttfp_ms_p75", + "audio_ttfp_ms_p90", + "audio_ttfp_ms_p95", + "audio_ttfp_ms_p99", + "audio_rtf_mean", + "audio_rtf_median", + "audio_rtf_std", + "audio_rtf_p25", + "audio_rtf_p50", + "audio_rtf_p75", + "audio_rtf_p90", + "audio_rtf_p95", + "audio_rtf_p99", + "audio_duration_s_mean", + "audio_duration_s_median", + "audio_duration_s_p50", + "audio_duration_s_p95", + "audio_duration_s_p99", + "audio_underrun_s_mean", + "audio_underrun_s_median", + "audio_underrun_s_p50", + "audio_underrun_s_p95", + "audio_underrun_s_p99", + "audio_throughput_x", + "audio_output_duration_s_total", + "audio_frames_total", + "audio_sample_rate_hz", + "audio_continuity_ok_rate", +] + +ASR_COLUMNS = [ + "wer", + "wer_ci_lower", + "wer_ci_upper", + "rtfx", + "transcription_throughput_utterances_s", + "audio_input_duration_s_total", + "normalization", + "language", +] + +STAGE_COLUMNS = [ + "stage_0_ttft_ms_p50", + "stage_0_ttft_ms_p95", + "stage_1_ttft_ms_p50", + "stage_1_ttft_ms_p95", + "stage_0_gen_time_ms_p50", + "stage_0_gen_time_ms_p95", + "stage_1_gen_time_ms_p50", + "stage_1_gen_time_ms_p95", + "transfer_tx_ms_p50", + "transfer_tx_ms_p95", + "stage_metrics_json", + "gpu_util_mean", + "gpu_util_p95", + "gpu_mem_used_mean_mb", + "gpu_power_mean_w", + "gpu_temp_max_c", +] + +EXTRA_COLUMNS = [ + "quality_metric", + "quality_value", + "extra_json", + "notes", + "source_file", +] + +CANONICAL_COLUMNS = ( + CORE_COLUMNS + + TEXT_COLUMNS + + SPEECH_COLUMNS + + ASR_COLUMNS + + STAGE_COLUMNS + + EXTRA_COLUMNS +) + +RAW_LIST_KEYS = { + "ttfts", + "tpots", + "itls", + "e2els", + "generated_texts", + "errors", + "audio_ttfps", + "audio_durations", + "audio_frames", + "stage_gen_times_ms", + "postprocess_times_ms", + "serving_time_to_first_outputs_ms", + "time_per_output_units_ms", + "inter_output_latencies_ms", +} + +STATS = ( + "mean", + "median", + "std", + "p25", + "p50", + "p75", + "p90", + "p95", + "p99", + "min", + "max", +) +PERCENTILE_SETS = { + "audio_ttfp_ms": "audio_ttfp_ms", + "audio_rtf": "audio_rtf", + "audio_duration_s": "audio_duration_s", + "audio_underrun_s": "audio_underrun_s", + "e2el_ms": "e2el_ms", + "ttft_ms": "ttft_ms", + "tpot_ms": "tpot_ms", + "itl_ms": "itl_ms", +} + + +def sget(d, *keys, default=""): + """Return the first non-empty value for a set of keys.""" + for k in keys: + v = d.get(k) + if v is not None and v != "": + return v + return default + + +def fnum(v): + """Format a value for CSV output.""" + if v is None or v == "": + return "" + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, float) and v != v: # NaN + return "" + return str(v) + + +def jdump(v): + """Serialize a value as compact JSON, or an empty string.""" + if v is None or v == "" or v == {} or v == []: + return "" + return json.dumps(v, sort_keys=True, separators=(",", ":"), default=str) + + +def parse_timestamp(value, fallback_path): + """Normalize a timestamp or use the file mtime.""" + if value: + value = str(value) + for fmt in ( + "%Y%m%d-%H%M%S", + "%Y-%m-%dT%H:%M:%SZ", + "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%d %H:%M:%S", + ): + try: + parsed = dt.datetime.strptime(value, fmt) + return parsed.replace(tzinfo=dt.timezone.utc).isoformat() + except ValueError: + pass + return value + try: + mtime = os.path.getmtime(fallback_path) + return dt.datetime.fromtimestamp(mtime, tz=dt.timezone.utc).isoformat() + except OSError: + return "" + + +def relpath(path): + """Return a repository-relative path.""" + return os.path.relpath(os.path.abspath(path), os.getcwd()).replace(os.sep, "/") + + +def load_metadata(path): + """Load converter metadata from JSON.""" + if not path: + return {} + with open(path) as f: + return json.load(f) + + +def match_meta(metadata, rel): + """Merge defaults with the first matching pattern.""" + meta = dict(metadata.get("defaults", {})) + pattern_meta = {} + for pattern in metadata.get("patterns", []): + glob_pat = pattern.get("glob", "") + if glob_pat and fnmatch.fnmatch(rel, glob_pat): + pattern_meta = dict(pattern) + break + for k, v in pattern_meta.items(): + if k not in ( + "glob", + "run_name_template", + "mlflow_run_id_by_concurrency", + "bench_log_dir", + ): + meta[k] = v + meta["run_name_template"] = pattern_meta.get("run_name_template", "") + meta["mlflow_run_id_by_concurrency"] = pattern_meta.get( + "mlflow_run_id_by_concurrency", {} + ) + meta["bench_log_dir"] = pattern_meta.get("bench_log_dir", "") + meta["_pattern"] = pattern_meta + return meta + + +def apply_meta(row, meta, source, concurrency, stem): + """Fill blank row fields from metadata.""" + for k, v in meta.items(): + if k.startswith("_") or k in ( + "run_name_template", + "mlflow_run_id_by_concurrency", + "bench_log_dir", + ): + continue + if k in row and row[k] == "": + row[k] = v + template = meta.get("run_name_template") + if template: + row["run_name"] = template.format( + concurrency=concurrency, + stem=stem, + model=sget(source, "model_id", "model", default=row.get("model", "")), + task_type=row.get("task_type", ""), + ) + elif not row.get("run_name"): + row["run_name"] = stem + if concurrency != "": + by_conc = meta.get("mlflow_run_id_by_concurrency", {}) + if str(concurrency) in by_conc: + row["mlflow_run_id"] = by_conc[str(concurrency)] + row["benchmark_run_id"] = row.get("benchmark_run_id") or row["run_name"] + + +def map_stats(row, prefix, source, src_prefix): + """Copy a metric's statistics from the source record.""" + for stat in STATS: + v = source.get(f"{stat}_{src_prefix}") + col = f"{prefix}_{stat}" + if v is not None and col in row: + row[col] = fnum(v) + + +def continuity_rate(meta, stem): + """Extract the last streaming continuity rate from a log.""" + log_dir = meta.get("bench_log_dir", "") + if not log_dir: + return "" + path = os.path.join(log_dir, stem + ".log") + if not os.path.isfile(path): + return "" + try: + with open(path, errors="replace") as handle: + text = handle.read() + except OSError: + return "" + matches = re.findall(r"Streaming continuity OK rate:\s*([0-9.]+)%", text) + if not matches: + return "" + return fnum(float(matches[-1]) / 100.0) + + +def build_omni_row(path, metadata): + """Build a canonical row from a vLLM-Omni bench JSON.""" + stem = os.path.splitext(os.path.basename(path))[0] + rel = relpath(path) + meta = match_meta(metadata, rel) + with open(path) as f: + d = json.load(f) + + model = sget(d, "model_id", "model", default=meta.get("model", "")) + conc = sget(d, "max_concurrency", "concurrency", default="") + try: + conc_int = int(float(conc)) if conc != "" else "" + except (TypeError, ValueError): + conc_int = "" + if not model or conc_int == "": + raise ValueError(f"{rel}: missing model_id or max_concurrency") + + row = dict.fromkeys(CANONICAL_COLUMNS, "") + row["schema_version"] = meta.get("schema_version", SCHEMA_VERSION) + row["source_format"] = meta.get("source_format", "vllm-omni-bench-json") + row["source_file"] = rel + row["model"] = model + row["concurrency"] = conc_int + row["repetition"] = meta.get("repetition", "1") + row["num_prompts"] = fnum(d.get("num_prompts", "")) + row["request_rate"] = fnum(d.get("request_rate", "")) + row["duration_s"] = fnum(d.get("duration", "")) + row["successful_requests"] = fnum( + sget(d, "completed", "successful_requests", default="") + ) + row["errored_requests"] = fnum(sget(d, "failed", "errored_requests", default="")) + row["request_throughput_rps"] = fnum(d.get("request_throughput", "")) + row["output_token_throughput"] = fnum(d.get("output_throughput", "")) + row["total_token_throughput"] = fnum(d.get("total_token_throughput", "")) + row["prompt_tokens_total"] = fnum(d.get("total_input_tokens", "")) + row["output_tokens_total"] = fnum(d.get("total_output_tokens", "")) + row["audio_throughput_x"] = fnum(d.get("audio_throughput", "")) + row["audio_output_duration_s_total"] = fnum(d.get("total_audio_duration_s", "")) + row["audio_frames_total"] = fnum(d.get("total_audio_frames", "")) + row["audio_sample_rate_hz"] = fnum(meta.get("audio_sample_rate_hz", "")) + + map_stats(row, "audio_ttfp_ms", d, "audio_ttfp_ms") + map_stats(row, "audio_rtf", d, "audio_rtf") + map_stats(row, "audio_duration_s", d, "audio_duration_s") + map_stats(row, "audio_underrun_s", d, "audio_underrun_s") + map_stats(row, "e2el_ms", d, "e2el_ms") + map_stats(row, "ttft_ms", d, "ttft_ms") + map_stats(row, "tpot_ms", d, "tpot_ms") + map_stats(row, "itl_ms", d, "itl_ms") + + stage = { + "mean": d.get("stage_durations_mean"), + "p50": d.get("stage_durations_p50"), + "p99": d.get("stage_durations_p99"), + } + if any(stage.values()): + row["stage_metrics_json"] = jdump(stage) + + continuity = continuity_rate(meta, stem) + if continuity != "": + row["audio_continuity_ok_rate"] = continuity + + apply_meta(row, meta, d, conc_int, stem) + row["load_generator"] = ( + row.get("load_generator") + or meta.get("load_generator") + or row.get("benchmark_tool") + or "vllm-omni-bench-serve" + ) + row["timestamp_utc"] = row.get("timestamp_utc") or parse_timestamp( + d.get("date"), path + ) + row["audio_sample_rate_hz"] = row.get("audio_sample_rate_hz") or fnum( + meta.get("audio_sample_rate_hz", "") + ) + + consumed = { + "model_id", + "model", + "max_concurrency", + "concurrency", + "num_prompts", + "request_rate", + "duration", + "completed", + "failed", + "successful_requests", + "errored_requests", + "request_throughput", + "output_throughput", + "total_token_throughput", + "total_input_tokens", + "total_output_tokens", + "audio_throughput", + "total_audio_duration_s", + "total_audio_frames", + "stage_durations_mean", + "stage_durations_p50", + "stage_durations_p99", + } + for src_prefix in PERCENTILE_SETS: + for stat in STATS: + consumed.add(f"{stat}_{src_prefix}") + extra = {k: v for k, v in d.items() if k not in consumed and k not in RAW_LIST_KEYS} + row["extra_json"] = jdump(extra) + row["notes"] = meta.get("notes", "") + return row + + +def normalize_task(task): + """Normalize legacy task names.""" + task = (task or "").strip().lower() + return {"custom_voice": "default_voice"}.get(task, task) + + +def _legacy_measurement_fingerprint(row): + """Return a stable fingerprint of legacy measurement fields.""" + fields = [ + "tp", + "accelerator", + "runtime_args", + "timestamp_utc", + "num_prompts", + "request_rate", + "duration_s", + "successful_requests", + "errored_requests", + "request_throughput_rps", + "audio_throughput_x", + "audio_output_duration_s_total", + "audio_sample_rate_hz", + "e2el_ms_min", + "e2el_ms_max", + ] + for prefix in ( + "audio_rtf", + "audio_ttfp_ms", + "e2el_ms", + "ttft_ms", + "audio_duration_s", + "audio_underrun_s", + ): + for stat in ("mean", "median", "std", "p25", "p50", "p75", "p90", "p95", "p99"): + fields.append(f"{prefix}_{stat}") + payload = "|".join(f"{field}={row.get(field, '')}" for field in fields) + return hashlib.sha1(payload.encode("utf-8"), usedforsecurity=False).hexdigest()[:12] + + +def build_legacy_row(r, path, metadata): + """Build a canonical row from the 3.5 CSV.""" + defaults = metadata.get("legacy_defaults", {}) + row = dict.fromkeys(CANONICAL_COLUMNS, "") + row.update({k: v for k, v in defaults.items() if k in row}) + row["schema_version"] = defaults.get("schema_version", SCHEMA_VERSION) + row["source_format"] = "legacy-3.5-csv" + row["source_file"] = relpath(path) + row["timestamp_utc"] = r.get("timestamp", "") + row["repetition"] = "1" + row["model"] = r.get("model", "") + row["runtime_version"] = r.get("version", "") + row["tp"] = fnum(r.get("tp", "")) + row["accelerator"] = r.get("accelerator", "") + row["image_tag"] = r.get("image_tag", "") + row["modality"] = "audio" + row["input_modality"] = "text" + row["output_modality"] = "audio" + legacy_task = r.get("task_type", "") + row["task_type"] = normalize_task(legacy_task) + row["benchmark_tool"] = defaults.get("benchmark_tool", "vllm-omni-bench-serve") + row["load_generator"] = defaults.get("load_generator", row["benchmark_tool"]) + row["runtime_args"] = r.get("runtime_args", "") + row["concurrency"] = fnum(r.get("concurrency", "")) + row["num_prompts"] = fnum(r.get("num_prompts", "")) + row["request_rate"] = fnum(r.get("request_rate", "")) + row["duration_s"] = fnum(r.get("total_duration_s", "")) + row["successful_requests"] = fnum(r.get("successful_requests", "")) + row["errored_requests"] = fnum(r.get("errored_requests", "")) + row["request_throughput_rps"] = fnum(r.get("request_throughput", "")) + row["audio_throughput_x"] = fnum(r.get("audio_throughput", "")) + row["audio_output_duration_s_total"] = fnum(r.get("audio_duration_total", "")) + row["audio_sample_rate_hz"] = fnum(defaults.get("audio_sample_rate_hz", "")) + + for stat in ("mean", "median", "std", "p25", "p50", "p75", "p90", "p95", "p99"): + row[f"audio_rtf_{stat}"] = fnum(r.get(f"audio_rtf_{stat}", "")) + row[f"audio_ttfp_ms_{stat}"] = fnum(r.get(f"audio_ttfp_{stat}", "")) + row[f"e2el_ms_{stat}"] = fnum(r.get(f"e2el_{stat}", "")) + row[f"ttft_ms_{stat}"] = fnum(r.get(f"ttft_{stat}", "")) + row["e2el_ms_min"] = fnum(r.get("e2el_min", "")) + row["e2el_ms_max"] = fnum(r.get("e2el_max", "")) + for stat in ("mean", "median", "p50", "p95", "p99"): + row[f"audio_duration_s_{stat}"] = fnum(r.get(f"audio_duration_{stat}", "")) + row[f"audio_underrun_s_{stat}"] = fnum(r.get(f"audio_underrun_{stat}", "")) + row["audio_duration_s_mean"] = fnum( + r.get("audio_duration_mean", row["audio_duration_s_mean"]) + ) + row["audio_duration_s_median"] = fnum( + r.get("audio_duration_median", row["audio_duration_s_median"]) + ) + row["audio_duration_s_p99"] = fnum( + r.get("audio_duration_p99", row["audio_duration_s_p99"]) + ) + row["audio_underrun_s_mean"] = fnum( + r.get("audio_underrun_mean", row["audio_underrun_s_mean"]) + ) + row["audio_underrun_s_median"] = fnum( + r.get("audio_underrun_median", row["audio_underrun_s_median"]) + ) + row["audio_underrun_s_p99"] = fnum( + r.get("audio_underrun_p99", row["audio_underrun_s_p99"]) + ) + + if legacy_task == "voice_clone": + row["extra_body_json"] = '{"task_type":"Base"}' + elif legacy_task == "custom_voice": + row["extra_body_json"] = '{"task_type":"CustomVoice"}' + elif legacy_task == "voice_design": + row["extra_body_json"] = '{"task_type":"VoiceDesign"}' + row["prefix_caching"] = defaults.get("prefix_caching", "false") + base_run_name = f"legacy-3.5-{row['model']}-{row['task_type']}-{row['runtime_version']}-c{row['concurrency']}" + json_file = r.get("json_file", "") + if json_file: + row["run_name"] = base_run_name + row["benchmark_run_id"] = json_file + else: + row["run_name"] = f"{base_run_name}-{_legacy_measurement_fingerprint(row)}" + row["benchmark_run_id"] = row["run_name"] + row["notes"] = defaults.get("notes", "Imported from legacy benchmark CSV") + row["extra_json"] = jdump( + { + "legacy_task_type": legacy_task, + "legacy_modality": r.get("modality", ""), + "legacy_version": r.get("version", ""), + "json_file": r.get("json_file", ""), + "legacy_benchmark_tool": r.get("benchmark_tool", ""), + } + ) + return row + + +ASR_ALIASES = { + "model": ("model", "model_id", "model_name"), + "runtime": ("runtime", "engine"), + "runtime_version": ("runtime_version", "version", "image_version"), + "image_tag": ("image_tag", "image"), + "accelerator": ("accelerator", "gpu_model", "gpu"), + "tp": ("tp", "tensor_parallel_size"), + "dataset": ("dataset", "dataset_name"), + "dataset_split": ("dataset_split", "split"), + "language": ("language", "lang"), + "num_utterances": ("num_utterances", "num_prompts", "num_requests", "count"), + "wer": ("wer", "WER", "word_error_rate"), + "wer_ci_lower": ("wer_ci_lower", "wer_ci_low", "wer_ci_lower_95"), + "wer_ci_upper": ("wer_ci_upper", "wer_ci_high", "wer_ci_upper_95"), + "rtfx": ("rtfx", "RTFx", "RTFX", "rtf_x"), + "transcription_throughput_utterances_s": ( + "transcription_throughput_utterances_s", + "utterances_per_s", + "throughput_utterances_s", + "transcription_throughput", + ), + "audio_input_duration_s_total": ( + "audio_input_duration_s_total", + "audio_duration_total_s", + "total_audio_duration_s", + "audio_seconds", + ), + "normalization": ("normalization", "normalizer", "text_normalization"), + "timestamp_utc": ("timestamp_utc", "timestamp", "date"), + "cluster": ("cluster", "cluster_name"), + "namespace": ("namespace",), + "deployment_uuid": ("deployment_uuid", "uuid"), + "mlflow_run_id": ("mlflow_run_id", "run_id"), + "mlflow_experiment_id": ("mlflow_experiment_id", "experiment_id"), + "benchmark_tool": ("benchmark_tool", "tool"), + "benchmark_tool_version": ("benchmark_tool_version", "tool_version"), + "load_generator": ("load_generator", "generator", "load_tool"), + "duration_s": ("duration_s", "total_duration_s", "duration"), +} + + +def pick(row, aliases): + """Return the first non-empty value from aliases.""" + for key in aliases: + if key in row and row[key] not in (None, ""): + return row[key] + return "" + + +def _asr_identity_suffix(row): + """Return a stable fingerprint for ASR rows without an MLflow run id.""" + fields = ( + "timestamp_utc", + "wer", + "wer_ci_lower", + "wer_ci_upper", + "rtfx", + "num_utterances", + "duration_s", + "audio_input_duration_s_total", + ) + payload = "|".join(f"{field}={row.get(field, '')}" for field in fields) + return hashlib.sha1(payload.encode("utf-8"), usedforsecurity=False).hexdigest()[:12] + + +def build_asr_row(r, path, metadata): + """Build a canonical row from ASR results.""" + defaults = metadata.get("asr_defaults", {}) + model = pick(r, ASR_ALIASES["model"]) + wer = pick(r, ASR_ALIASES["wer"]) + if not model or wer == "": + raise ValueError(f"{relpath(path)}: ASR row missing model or wer") + row = dict.fromkeys(CANONICAL_COLUMNS, "") + row.update({k: v for k, v in defaults.items() if k in row}) + + def _value(alias, field): + value = pick(r, ASR_ALIASES[alias]) + return value if value not in (None, "") else row.get(field, "") + + row["schema_version"] = defaults.get("schema_version", SCHEMA_VERSION) + row["source_format"] = "asr-csv" + row["source_file"] = relpath(path) + row["timestamp_utc"] = _value("timestamp_utc", "timestamp_utc") + row["repetition"] = "1" + row["model"] = model + row["runtime"] = _value("runtime", "runtime") or defaults.get("runtime", "vllm") + row["runtime_version"] = _value("runtime_version", "runtime_version") + row["image_tag"] = _value("image_tag", "image_tag") + row["accelerator"] = _value("accelerator", "accelerator") + row["tp"] = fnum(_value("tp", "tp")) + row["modality"] = "audio" + row["input_modality"] = "audio" + row["output_modality"] = "text" + row["task_type"] = "asr_transcription" + row["benchmark_tool"] = _value("benchmark_tool", "benchmark_tool") or defaults.get( + "benchmark_tool", "" + ) + row["benchmark_tool_version"] = _value( + "benchmark_tool_version", "benchmark_tool_version" + ) + row["load_generator"] = ( + pick(r, ASR_ALIASES["load_generator"]) or row.get("load_generator") or "offline" + ) + row["dataset"] = _value("dataset", "dataset") + row["dataset_split"] = _value("dataset_split", "dataset_split") + row["language"] = _value("language", "language") + row["num_utterances"] = fnum(_value("num_utterances", "num_utterances")) + row["wer"] = fnum(wer) + row["wer_ci_lower"] = fnum(_value("wer_ci_lower", "wer_ci_lower")) + row["wer_ci_upper"] = fnum(_value("wer_ci_upper", "wer_ci_upper")) + row["rtfx"] = fnum(_value("rtfx", "rtfx")) + row["transcription_throughput_utterances_s"] = fnum( + _value( + "transcription_throughput_utterances_s", + "transcription_throughput_utterances_s", + ) + ) + row["audio_input_duration_s_total"] = fnum( + _value("audio_input_duration_s_total", "audio_input_duration_s_total") + ) + row["normalization"] = _value("normalization", "normalization") + row["duration_s"] = fnum(_value("duration_s", "duration_s")) + row["successful_requests"] = row["num_utterances"] + row["cluster"] = _value("cluster", "cluster") + row["namespace"] = _value("namespace", "namespace") + row["deployment_uuid"] = _value("deployment_uuid", "deployment_uuid") + row["mlflow_run_id"] = _value("mlflow_run_id", "mlflow_run_id") + row["mlflow_experiment_id"] = _value("mlflow_experiment_id", "mlflow_experiment_id") + row["quality_metric"] = "wer" + row["quality_value"] = fnum(wer) + suffix = row["mlflow_run_id"] or _asr_identity_suffix(row) + suffix = re.sub(r"[^A-Za-z0-9_.:-]+", "-", str(suffix)).strip("-") + row["run_name"] = f"asr-{model}-{row['dataset']}-{row['language']}-{suffix}" + row["benchmark_run_id"] = row["run_name"] + row["notes"] = defaults.get("notes", "Imported from ASR results") + row["extra_json"] = jdump( + {k: v for k, v in r.items() if k not in CANONICAL_COLUMNS} + ) + return row + + +def expand_inputs(paths, include_calibration): + """Expand file, directory, and glob inputs.""" + files = [] + for path in paths: + if os.path.isdir(path): + files.extend(sorted(glob.glob(os.path.join(path, "*.json")))) + elif any(ch in path for ch in "*?["): + files.extend(sorted(glob.glob(path))) + else: + files.append(path) + if not include_calibration: + files = [f for f in files if "calibration" not in os.path.basename(f).lower()] + return files + + +def csv_value(v): + """Normalize a value for CSV output.""" + if isinstance(v, bool): + return "true" if v else "false" + return "" if v is None else v + + +def main(): + """Build the consolidated CSV and print a summary.""" + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument( + "--omni-json", + action="append", + default=[], + metavar="PATH", + help="vLLM-Omni bench JSON file/dir/glob (repeatable)", + ) + ap.add_argument( + "--legacy-csv", default="", help="Existing legacy benchmark_results.csv" + ) + ap.add_argument( + "--asr-csv", action="append", default=[], help="ASR results CSV (repeatable)" + ) + ap.add_argument( + "--asr-json", action="append", default=[], help="ASR results JSON (repeatable)" + ) + ap.add_argument( + "--metadata-json", default="", help="Metadata defaults/pattern overrides" + ) + ap.add_argument( + "--output", default="datasets/omni/consolidated_dashboard_omni_legacy.csv" + ) + ap.add_argument( + "--template", + default="manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_template.csv", + ) + ap.add_argument("--include-calibration", action="store_true") + ap.add_argument( + "--strict", + action="store_true", + help="Exit nonzero if required fields are blank", + ) + args = ap.parse_args() + + metadata = load_metadata(args.metadata_json) + rows, errors = [], [] + + for path in expand_inputs(args.omni_json, args.include_calibration): + try: + rows.append(build_omni_row(path, metadata)) + except Exception as exc: + errors.append(str(exc)) + + if args.legacy_csv: + with open(args.legacy_csv, newline="") as f: + for r in csv.DictReader(f): + try: + rows.append(build_legacy_row(r, args.legacy_csv, metadata)) + except Exception as exc: + errors.append(str(exc)) + + asr_paths = list(args.asr_csv) + for path in args.asr_json: + if os.path.isdir(path): + asr_paths.extend(sorted(glob.glob(os.path.join(path, "*.json")))) + else: + asr_paths.append(path) + for path in asr_paths: + try: + if path.lower().endswith(".csv"): + with open(path, newline="") as f: + for r in csv.DictReader(f): + try: + rows.append(build_asr_row(r, path, metadata)) + except Exception as exc: + errors.append(f"{path}: {exc}") + else: + with open(path) as f: + data = json.load(f) + records = data if isinstance(data, list) else [data] + for r in records: + try: + rows.append(build_asr_row(r, path, metadata)) + except Exception as exc: + errors.append(f"{path}: {exc}") + except Exception as exc: + errors.append(f"{path}: {exc}") + + deduped, seen = [], {} + for row in rows: + key = ( + row.get("model", ""), + row.get("task_type", ""), + row.get("runtime_version", ""), + row.get("dataset", ""), + row.get("concurrency", ""), + row.get("request_rate", ""), + row.get("run_name", ""), + row.get("benchmark_run_id", ""), + row.get("repetition", ""), + ) + if key in seen: + errors.append(f"duplicate row kept last: {key}") + seen[key] = row + deduped = list(seen.values()) + + def sort_key(row): + try: + conc = int(float(row.get("concurrency") or 0)) + except ValueError: + conc = 0 + return ( + row.get("timestamp_utc", ""), + row.get("model", ""), + row.get("task_type", ""), + conc, + ) + + deduped.sort(key=sort_key) + + required_blank = Counter() + for row in deduped: + required = ["model", "task_type", "benchmark_tool", "load_generator"] + if row.get("task_type") != "asr_transcription": + required.append("concurrency") + for col in required: + if not row.get(col): + required_blank[col] += 1 + if args.strict and required_blank: + raise SystemExit(2) + + for path in (args.output, args.template): + parent = os.path.dirname(path) + if parent: + os.makedirs(parent, exist_ok=True) + with open(args.output, "w", newline="") as f: + writer = csv.DictWriter( + f, fieldnames=CANONICAL_COLUMNS, extrasaction="ignore", lineterminator="\n" + ) + writer.writeheader() + for row in deduped: + writer.writerow({k: csv_value(row.get(k, "")) for k in CANONICAL_COLUMNS}) + with open(args.template, "w", newline="") as f: + csv.DictWriter( + f, fieldnames=CANONICAL_COLUMNS, lineterminator="\n" + ).writeheader() + + summary = { + "rows": len(deduped), + "by_modality": dict(Counter(r.get("modality", "") for r in deduped)), + "by_task": dict(Counter(r.get("task_type", "") for r in deduped)), + "by_source_format": dict(Counter(r.get("source_format", "") for r in deduped)), + "required_blank": dict(required_blank), + "errors": errors[:20], + "output": args.output, + "template": args.template, + } + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/manual_runs/scripts/vllm-omni/build_omni_tts_csv.py b/manual_runs/scripts/vllm-omni/build_omni_tts_csv.py new file mode 100644 index 0000000..1d080f6 --- /dev/null +++ b/manual_runs/scripts/vllm-omni/build_omni_tts_csv.py @@ -0,0 +1,1106 @@ +#!/usr/bin/env python3 +"""Build the staged Omni TTS dashboard CSV (Qwen3-TTS only). + +Reads benchmark artifacts from the read-only recipe checkout and writes the +77-column schema documented in docs/omni-dashboard.md. + +Groups: + 1. 3.5 legacy -- results/3.5/benchmark_results.csv + raw JSON per json_file + 2. 3.6 base -- results/3.6/ci/*.json + results/3.6/qwen3-tts-base-36ga/saturation/saturation_c*.json + 3. 3.6 Athena -- results/athena/benchmark_results.csv Qwen3-TTS CustomVoice rows + +Usage: + python3 manual_runs/scripts/vllm-omni/build_omni_tts_csv.py [--recipe-root PATH] [--output PATH] + [--template PATH] [--mlflow-runs-json PATH] + +Defaults: + recipe root ~/omni-perf-benchmark-recipe + output /datasets/omni/consolidated_dashboard_omni.csv + template /manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_tts_template.csv + +--mlflow-runs-json is optional. Pass a saved MLflow runs/search response to +fill run IDs that are not present in the local metadata files. + +Standard library only. The recipe checkout is never modified. +""" + +import csv +import datetime +import glob +import json +import os +import re +import sys + +DEFAULT_RECIPE_ROOT = os.path.expanduser("~/omni-perf-benchmark-recipe") + +TEMPLATE_REL = os.path.join( + "manual_runs", + "scripts", + "vllm-omni", + "templates", + "consolidated_dashboard_omni_tts_template.csv", +) +OUTPUT_REL = os.path.join("datasets", "omni", "consolidated_dashboard_omni.csv") + +Q35_DIR = os.path.join("results", "3.5") +Q35_CSV = os.path.join(Q35_DIR, "benchmark_results.csv") +Q36_CI_JSON = os.path.join("results", "3.6", "ci", "ci_qwen3_tts_base_c1.json") +Q36_SAT_GLOB = os.path.join( + "results", "3.6", "qwen3-tts-base-36ga", "saturation", "saturation_c*.json" +) +Q36_META = os.path.join("results", "3.6", "consolidated_dashboard_omni_metadata.json") +ATHENA_CSV = os.path.join("results", "athena", "benchmark_results.csv") +ATHENA_META = os.path.join( + "results", "athena", "customvoice-36ga", "consolidated_metadata.json" +) + +QWEN_TTS_PREFIX = "Qwen/Qwen3-TTS-" + +DEFAULT_LOAD_GENERATOR = "vllm-omni-bench-serve" +DEFAULT_AUDIO_SAMPLE_RATE = "24000" +DEFAULT_GPU_MEM = '{"0":0.3,"1":0.3}' + +# Raw bench JSON field -> dashboard column. +D_METRICS = { + "e2el_ms_mean": "mean_e2el_ms", + "e2el_ms_median": "median_e2el_ms", + "e2el_ms_p95": "p95_e2el_ms", + "e2el_ms_p99": "p99_e2el_ms", + "request_throughput_rps": "request_throughput", + "audio_ttfp_ms_mean": "mean_audio_ttfp_ms", + "audio_ttfp_ms_median": "median_audio_ttfp_ms", + "audio_ttfp_ms_p95": "p95_audio_ttfp_ms", + "audio_ttfp_ms_p99": "p99_audio_ttfp_ms", + "audio_rtf_mean": "mean_audio_rtf", + "audio_rtf_median": "median_audio_rtf", + "audio_rtf_p95": "p95_audio_rtf", + "audio_rtf_p99": "p99_audio_rtf", + "audio_duration_s_mean": "mean_audio_duration_s", + "audio_duration_s_median": "median_audio_duration_s", + "audio_duration_s_p95": "p95_audio_duration_s", + "audio_duration_s_p99": "p99_audio_duration_s", + "audio_underrun_s_mean": "mean_audio_underrun_s", + "audio_underrun_s_median": "median_audio_underrun_s", + "audio_underrun_s_p95": "p95_audio_underrun_s", + "audio_underrun_s_p99": "p99_audio_underrun_s", + "audio_throughput_x": "audio_throughput", + "audio_output_duration_s_total": "total_audio_duration_s", + "num_prompts": "num_prompts", + "request_rate": "request_rate", + "duration_s": "duration", + "successful_requests": "completed", + "errored_requests": "failed", +} + +# Source-CSV fallback names for the 3.5 legacy CSV. +R35_METRICS = { + "e2el_ms_mean": "e2el_mean", + "e2el_ms_median": "e2el_median", + "e2el_ms_p95": "e2el_p95", + "e2el_ms_p99": "e2el_p99", + "request_throughput_rps": "request_throughput", + "audio_ttfp_ms_mean": "audio_ttfp_mean", + "audio_ttfp_ms_median": "audio_ttfp_median", + "audio_ttfp_ms_p95": "audio_ttfp_p95", + "audio_ttfp_ms_p99": "audio_ttfp_p99", + "audio_rtf_mean": "audio_rtf_mean", + "audio_rtf_median": "audio_rtf_median", + "audio_rtf_p95": "audio_rtf_p95", + "audio_rtf_p99": "audio_rtf_p99", + "audio_duration_s_mean": "audio_duration_mean", + "audio_duration_s_median": "audio_duration_median", + "audio_duration_s_p95": "audio_duration_p95", + "audio_duration_s_p99": "audio_duration_p99", + "audio_underrun_s_mean": "audio_underrun_mean", + "audio_underrun_s_median": "audio_underrun_median", + "audio_underrun_s_p95": "audio_underrun_p95", + "audio_underrun_s_p99": "audio_underrun_p99", + "audio_throughput_x": "audio_throughput", + "audio_output_duration_s_total": "audio_duration_total", + "num_prompts": "num_prompts", + "request_rate": "request_rate", + "duration_s": "total_duration_s", + "successful_requests": "successful_requests", + "errored_requests": "errored_requests", +} + +# Source-CSV fallback names for the Athena CSV. +RATH_METRICS = { + "e2el_ms_mean": "e2el_ms_mean", + "e2el_ms_median": "e2el_ms_median", + "e2el_ms_p95": "e2el_ms_p95", + "e2el_ms_p99": "e2el_ms_p99", + "request_throughput_rps": "request_throughput", + "audio_ttfp_ms_mean": "audio_ttfp_ms_mean", + "audio_ttfp_ms_median": "audio_ttfp_ms_median", + "audio_ttfp_ms_p95": "audio_ttfp_ms_p95", + "audio_ttfp_ms_p99": "audio_ttfp_ms_p99", + "audio_rtf_mean": "audio_rtf_mean", + "audio_rtf_median": "audio_rtf_median", + "audio_rtf_p95": "audio_rtf_p95", + "audio_rtf_p99": "audio_rtf_p99", + "audio_underrun_s_mean": "audio_underrun_s_mean", + "audio_underrun_s_median": "audio_underrun_s_median", + "audio_underrun_s_p95": "audio_underrun_s_p95", + "audio_underrun_s_p99": "audio_underrun_s_p99", + "audio_throughput_x": "audio_throughput", + "num_prompts": "num_prompts", + "request_rate": "request_rate", + "duration_s": "duration_s", + "successful_requests": "completed", + "errored_requests": "failed", +} + +REQUIRED_COLUMNS = [ + "model", + "task_type", + "benchmark_tool", + "load_generator", + "concurrency", + "accelerator", + "runtime_version", + "dataset", + "modality", + "input_modality", + "output_modality", +] + + +# --------------------------------------------------------------------------- +# Generic helpers +# --------------------------------------------------------------------------- + + +def as_text(value): + """Render a JSON/CSV value as the CSV string used by the dashboard.""" + if value is None: + return "" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, float): + if value != value: # NaN + return "" + if value == float("inf"): + return "inf" + if value == float("-inf"): + return "-inf" + return repr(value) + if isinstance(value, int): + return str(value) + return str(value).strip() + + +def pick(*values): + """First value that is not None and not an empty string (0/false are valid).""" + for value in values: + if value is None: + continue + if isinstance(value, str) and value == "": + continue + return value + return "" + + +def load_json(path): + """Load a JSON file, returning an empty dict on failure.""" + if not path or not os.path.isfile(path): + return {} + try: + with open(path, encoding="utf-8") as handle: + return json.load(handle) + except (OSError, ValueError): + return {} + + +def read_csv_rows(path): + """Read a CSV file into a list of dictionaries.""" + if not os.path.isfile(path): + return [] + with open(path, encoding="utf-8", newline="") as handle: + return list(csv.DictReader(handle)) + + +def load_mlflow_index(path): + """Index MLflow runs by run name and by (deployment_uuid, concurrency).""" + if not path: + return {} + data = load_json(path) + runs = data.get("runs", []) if isinstance(data, dict) else data + by_name = {} + by_uuid_concurrency = {} + + def _pairs(value): + if isinstance(value, dict): + return value + if isinstance(value, list): + return { + item.get("key"): item.get("value") + for item in value + if isinstance(item, dict) + } + return {} + + for run in runs or []: + info = run.get("info") or {} + run_data = run.get("data") or {} + tags = _pairs(run_data.get("tags")) + params = _pairs(run_data.get("params")) + run_id = as_text(info.get("run_id")) + if not run_id: + continue + name = as_text(tags.get("mlflow.runName")) + deployment_uuid = as_text( + pick(tags.get("deployment_uuid"), params.get("deployment_uuid")) + ) + concurrency = concurrency_str( + pick(tags.get("concurrency"), params.get("max_concurrency")) + ) + if name: + by_name.setdefault(name, []).append((deployment_uuid, run_id)) + if deployment_uuid and concurrency: + by_uuid_concurrency[(deployment_uuid, concurrency)] = run_id + return {"by_name": by_name, "by_uuid_concurrency": by_uuid_concurrency} + + +def mlflow_run_id_for(mlflow_index, run_name, deployment_uuid, concurrency): + """Look up a run id from the optional MLflow cache.""" + if not mlflow_index: + return "" + run_id = mlflow_index.get("by_uuid_concurrency", {}).get( + (deployment_uuid, concurrency), "" + ) + if run_id: + return run_id + candidates = [ + candidate_run_id + for candidate_deployment, candidate_run_id in mlflow_index.get( + "by_name", {} + ).get(run_name, []) + if not deployment_uuid + or not candidate_deployment + or candidate_deployment == deployment_uuid + ] + return candidates[0] if len(candidates) == 1 else "" + + +def slug(text): + """Deterministic lowercase slug: non-alphanumerics collapse to '-'.""" + return re.sub(r"[^a-z0-9]+", "-", as_text(text).lower()).strip("-") + + +def concurrency_str(value): + """Canonical integer-looking concurrency string.""" + text = as_text(value) + if text == "": + return "" + try: + number = float(text) + except ValueError: + return text + if number.is_integer(): + return str(int(number)) + return text + + +def normalize_task_type(value): + """Normalize legacy task names to the dashboard names.""" + text = as_text(value) + if text == "custom_voice": + return "default_voice" + return text + + +def map_endpoint(value): + """Map a bench backend name to its HTTP endpoint.""" + text = as_text(value) + mapping = {"openai-audio-speech": "/v1/audio/speech"} + if text in mapping: + return mapping[text] + if text.startswith("/"): + return text + return "" + + +def short_window_flag(duration_text): + """Return true when a run is shorter than the steady-state window.""" + try: + return "true" if float(duration_text) < 30 else "false" + except (TypeError, ValueError): + return "" + + +def normalize_timestamp(value, fallback_path): + """Normalize YYYYMMDD-HHMMSS or ISO-8601 input to ISO-8601 UTC.""" + text = as_text(value) + if text: + if re.fullmatch(r"\d{8}-\d{6}", text): + try: + parsed = datetime.datetime.strptime(text, "%Y%m%d-%H%M%S") + parsed = parsed.replace(tzinfo=datetime.timezone.utc) + return parsed.strftime("%Y-%m-%dT%H:%M:%SZ") + except ValueError: + pass + try: + parsed = datetime.datetime.fromisoformat(text.replace("Z", "+00:00")) + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=datetime.timezone.utc) + parsed = parsed.astimezone(datetime.timezone.utc) + return parsed.strftime("%Y-%m-%dT%H:%M:%SZ") + except ValueError: + pass + if fallback_path and os.path.isfile(fallback_path): + parsed = datetime.datetime.fromtimestamp( + os.path.getmtime(fallback_path), datetime.timezone.utc + ) + return parsed.strftime("%Y-%m-%dT%H:%M:%SZ") + return text + + +def strip_image_digest(image): + """Return an image reference without its sha256 digest.""" + return re.split(r"@sha256:", as_text(image), maxsplit=1)[0] + + +def response_format_from_extra_body(extra_body): + """Return response_format from an extra-body JSON object or string.""" + if isinstance(extra_body, str): + if not extra_body.strip(): + return "" + try: + extra_body = json.loads(extra_body) + except ValueError: + return "" + if not isinstance(extra_body, dict): + return "" + return as_text(extra_body.get("response_format")) + + +def compose_runtime_args(gpu_mem, max_seqs, max_batched): + """Render the resolved deployment args for the dashboard hover.""" + parts = [] + for label, value in ( + ("gpu-mem", gpu_mem), + ("max-seqs", max_seqs), + ("max-batched-tokens", max_batched), + ): + text = as_text(value).strip() + if text: + parts.append(f"{label}={text}") + return "; ".join(parts) + + +def find_log(json_path, extra_log_dir=""): + """Cell log: same directory as the JSON, then a metadata bench_log_dir.""" + stem = os.path.splitext(os.path.basename(json_path))[0] + candidates = [os.path.join(os.path.dirname(json_path), stem + ".log")] + if extra_log_dir: + candidates.append(os.path.join(extra_log_dir, stem + ".log")) + for candidate in candidates: + if os.path.isfile(candidate): + return candidate + return "" + + +def continuity_ok_rate(log_path): + """Last 'Streaming continuity OK rate: X%' line divided by 100.""" + if not log_path: + return "" + last = None + try: + with open(log_path, encoding="utf-8", errors="replace") as handle: + for line in handle: + match = re.search( + r"Streaming continuity OK rate:\s*([0-9]+(?:\.[0-9]+)?)\s*%", + line, + ) + if match: + last = match.group(1) + except OSError: + return "" + if last is None: + return "" + return as_text(float(last) / 100.0) + + +def stage_value(mapping, index): + """Return a stage value by index or natural key order.""" + if not isinstance(mapping, dict) or not mapping: + return "" + for key in (str(index), index): + if key in mapping: + return as_text(mapping[key]) + + # Fall back to the first/second stage by natural key order. + def sort_key(key): + try: + return (0, int(key)) + except (TypeError, ValueError): + return (1, str(key)) + + keys = sorted(mapping.keys(), key=sort_key) + if index < len(keys): + return as_text(mapping[keys[index]]) + return "" + + +def apply_stages(row, data): + """Populate the stage p50 columns; p95 stays blank for the current schema.""" + row["stage_0_ttft_ms_p50"] = "" + row["stage_0_ttft_ms_p95"] = "" + row["stage_1_ttft_ms_p50"] = "" + row["stage_1_ttft_ms_p95"] = "" + row["transfer_tx_ms_p50"] = "" + row["transfer_tx_ms_p95"] = "" + + p50 = data.get("stage_durations_p50") + if not isinstance(p50, dict) or not p50: + return + row["stage_0_ttft_ms_p50"] = stage_value(p50, 0) + row["stage_1_ttft_ms_p50"] = stage_value(p50, 1) + for key, value in p50.items(): + lowered = str(key).lower() + if "transfer" in lowered or lowered in ("tx", "stage_gap", "gap"): + row["transfer_tx_ms_p50"] = as_text(value) + break + + +def apply_metrics(row, data, source_row, group): + """Copy outcome metrics from the bench JSON or source CSV.""" + fallback = R35_METRICS if group == "3.5" else RATH_METRICS + for column, data_key in D_METRICS.items(): + source_key = fallback.get(column) if source_row else None + value = pick( + data.get(data_key), + source_row.get(source_key) if source_key else None, + ) + row[column] = as_text(value) + + +def apply_audio_output(row, data, group, log_path, sample_rate, response_format): + """Populate audio-output format and coverage fields.""" + row["audio_frames_total"] = ( + "" if group == "3.5" else as_text(data.get("total_audio_frames")) + ) + row["audio_sample_rate_hz"] = as_text(sample_rate) + row["audio_continuity_ok_rate"] = continuity_ok_rate(log_path) + row["num_audio_ttfp_samples"] = ( + "" if group == "3.5" else as_text(data.get("num_audio_ttfp_samples")) + ) + row["num_audio_rtf_samples"] = ( + "" if group == "3.5" else as_text(data.get("num_audio_rtf_samples")) + ) + row["missing_audio_duration_count"] = as_text( + data.get("missing_audio_duration_count") + ) + row["audio_channels"] = "1" + row["audio_bits_per_sample"] = "16" + row["audio_codec"] = ( + "pcm_s16le" if as_text(response_format).lower() in ("wav", "pcm") else "" + ) + row["audio_underrun_threshold_s"] = "0.1" + + +def build_notes(group, response_format_inferred, short_window): + """Build the short notes string for a row.""" + notes = [] + if response_format_inferred: + notes.append("response_format inferred") + if short_window == "true": + notes.append("short_window") + return "; ".join(notes) + + +def new_row(header): + """Create an empty row with the canonical columns.""" + return dict.fromkeys(header, "") + + +def match_pattern(patterns, recipe_root, absolute_path): + """Return the metadata pattern whose glob contains this source file.""" + normalized = os.path.normpath(absolute_path) + for pattern in patterns or []: + pattern_glob = pattern.get("glob", "") + if not pattern_glob: + continue + matches = glob.glob(os.path.join(recipe_root, pattern_glob)) + if any(os.path.normpath(match) == normalized for match in matches): + return pattern + return {} + + +def dataset_for_task(task_type): + """Return the default dataset for a task type.""" + if task_type == "voice_clone": + return "seed-tts" + if task_type == "default_voice": + return "seed-tts-text" + return "" + + +def locale_for(dataset, task_type): + """Return the locale filter for a dataset and task.""" + if dataset == "seed-tts" and task_type == "voice_clone": + return "en" + return "" + + +def tokenizer_override(model, tokenizer_id): + """Return whether the bench tokenizer differs from the model.""" + model_text = as_text(model) + tokenizer_text = as_text(tokenizer_id) + if model_text and tokenizer_text and model_text != tokenizer_text: + return "true" + return "false" + + +# --------------------------------------------------------------------------- +# Group 1: 3.5 legacy +# --------------------------------------------------------------------------- + + +def build_35(recipe_root, header): + """Build rows from the 3.5 legacy CSV and raw JSONs.""" + rows = [] + for source_row in read_csv_rows(os.path.join(recipe_root, Q35_CSV)): + model = as_text(source_row.get("model")) + if not model.startswith(QWEN_TTS_PREFIX): + continue + + json_file = as_text(source_row.get("json_file")) + relative_path = os.path.normpath(os.path.join(Q35_DIR, json_file)) + json_path = os.path.join(recipe_root, relative_path) + data = load_json(json_path) + + task_type = normalize_task_type(source_row.get("task_type")) + runtime_version = as_text(source_row.get("version")) + concurrency = concurrency_str( + pick(data.get("max_concurrency"), source_row.get("concurrency")) + ) + profile = "default" + phase = "legacy" + + row = new_row(header) + row["run_key"] = "__".join( + [ + slug(model), + runtime_version, + profile, + task_type, + "c" + concurrency, + phase, + ] + ) + row["run_name"] = ( + f"legacy-3.5-{model}-{task_type}-{runtime_version}-c{concurrency}" + ) + row["timestamp_utc"] = normalize_timestamp( + source_row.get("timestamp"), json_path + ) + row["cluster"] = "hera" + row["deployment_uuid"] = "" + row["mlflow_run_id"] = "" + row["source_file"] = relative_path + + row["model"] = as_text(pick(data.get("model_id"), model)) + row["runtime_version"] = runtime_version + row["image_tag"] = as_text(source_row.get("image_tag")) + row["accelerator"] = as_text(source_row.get("accelerator")) + # The doc records 1 GPU / TP=1 for every current Qwen3-TTS row; the + # legacy CSV only carries TP. + row["gpu_count"] = "1" + row["tp"] = as_text(pick(source_row.get("tp"), "1")) + + row["modality"] = "audio" + row["input_modality"] = "text" + row["output_modality"] = "audio" + row["task_type"] = task_type + row["recipe"] = profile + row["experiment_phase"] = phase + row["benchmark_tool"] = as_text(source_row.get("benchmark_tool")) + row["load_generator"] = DEFAULT_LOAD_GENERATOR + row["api_endpoint"] = map_endpoint(data.get("endpoint_type")) + row["benchmark_mode"] = "streaming" + # 3.5 has no response_format in bench JSON; WAV is the server default. + row["response_format"] = "wav" + row["tokenizer_override"] = tokenizer_override(model, data.get("tokenizer_id")) + row["status"] = "valid" + row["runtime_args"] = as_text(source_row.get("runtime_args")) + + dataset = dataset_for_task(task_type) + row["dataset"] = dataset + row["locale"] = locale_for(dataset, task_type) + row["concurrency"] = concurrency + row["measured_concurrency"] = as_text(data.get("max_concurrent_requests")) + + apply_metrics(row, data, source_row, "3.5") + row["short_window"] = short_window_flag(row["duration_s"]) + apply_stages(row, data) + row["notes"] = build_notes("3.5", True, row["short_window"]) + apply_audio_output( + row, data, "3.5", "", DEFAULT_AUDIO_SAMPLE_RATE, row["response_format"] + ) + rows.append(row) + return rows + + +# --------------------------------------------------------------------------- +# Group 2: 3.6 base (CI + saturation) +# --------------------------------------------------------------------------- + + +def build_36(recipe_root, header): + """Build rows from the 3.6 base CI and saturation JSONs.""" + metadata = load_json(os.path.join(recipe_root, Q36_META)) + defaults = metadata.get("defaults", {}) + patterns = metadata.get("patterns", []) + + source_paths = [] + ci_path = os.path.join(recipe_root, Q36_CI_JSON) + if os.path.isfile(ci_path): + source_paths.append(ci_path) + source_paths.extend(sorted(glob.glob(os.path.join(recipe_root, Q36_SAT_GLOB)))) + + rows = [] + for json_path in source_paths: + data = load_json(json_path) + relative_path = os.path.normpath(os.path.relpath(json_path, recipe_root)) + pattern = match_pattern(patterns, recipe_root, json_path) + + concurrency = concurrency_str( + pick(data.get("max_concurrency"), defaults.get("concurrency")) + ) + phase = "ci" if "/ci/" in relative_path.replace(os.sep, "/") else "saturation" + profile = "default" + + model = as_text(pick(data.get("model_id"), defaults.get("model"))) + runtime_version = as_text(defaults.get("runtime_version")) + task_type = normalize_task_type(defaults.get("task_type")) + if not task_type: + task_type = "voice_clone" + + run_name_template = as_text(pattern.get("run_name_template")) + if run_name_template: + try: + run_name = run_name_template.format(concurrency=concurrency) + except (KeyError, IndexError, ValueError): + run_name = run_name_template + else: + run_name = f"qwen3-tts-base-36ga_saturation_c{concurrency}" + + mlflow_run_id = as_text(pattern.get("mlflow_run_id")) + if not mlflow_run_id: + by_concurrency = pattern.get("mlflow_run_id_by_concurrency") or {} + mlflow_run_id = as_text(by_concurrency.get(concurrency)) + + extra_body = defaults.get("extra_body_json") + response_format = response_format_from_extra_body(extra_body) + response_format_inferred = not response_format + if not response_format: + response_format = "wav" + + log_dir = as_text(pattern.get("bench_log_dir")) + log_path = find_log( + json_path, os.path.join(recipe_root, log_dir) if log_dir else "" + ) + sample_rate = pick( + defaults.get("audio_sample_rate_hz"), DEFAULT_AUDIO_SAMPLE_RATE + ) + + row = new_row(header) + row["run_key"] = "__".join( + [ + slug(model), + runtime_version, + profile, + task_type, + "c" + concurrency, + phase, + ] + ) + row["run_name"] = run_name + row["timestamp_utc"] = normalize_timestamp(data.get("date"), json_path) + row["cluster"] = "hera" + row["deployment_uuid"] = as_text(pattern.get("deployment_uuid")) + row["mlflow_run_id"] = mlflow_run_id + row["source_file"] = relative_path + + row["model"] = model + row["runtime_version"] = runtime_version + row["image_tag"] = as_text(defaults.get("image_tag")) + row["accelerator"] = as_text(defaults.get("accelerator")) + row["gpu_count"] = as_text(pick(defaults.get("gpu_count"), "1")) + row["tp"] = as_text(pick(defaults.get("tp"), "1")) + + row["modality"] = "audio" + row["input_modality"] = "text" + row["output_modality"] = "audio" + row["task_type"] = task_type + row["recipe"] = profile + row["experiment_phase"] = phase + row["benchmark_tool"] = as_text( + pick(defaults.get("benchmark_tool"), "vllm-omni-bench-serve") + ) + row["load_generator"] = as_text( + pick(defaults.get("load_generator"), DEFAULT_LOAD_GENERATOR) + ) + row["api_endpoint"] = map_endpoint(data.get("endpoint_type")) + row["benchmark_mode"] = "streaming" + row["response_format"] = response_format + row["tokenizer_override"] = tokenizer_override(model, data.get("tokenizer_id")) + row["status"] = "valid" + row["runtime_args"] = compose_runtime_args( + pick(defaults.get("gpu_memory_utilization"), DEFAULT_GPU_MEM), + defaults.get("max_num_seqs"), + defaults.get("max_num_batched_tokens"), + ) + + dataset = as_text(pick(defaults.get("dataset"), dataset_for_task(task_type))) + row["dataset"] = dataset + row["locale"] = as_text( + pick(defaults.get("locale"), locale_for(dataset, task_type)) + ) + row["concurrency"] = concurrency + row["measured_concurrency"] = as_text(data.get("max_concurrent_requests")) + + apply_metrics(row, data, None, "3.6") + row["short_window"] = short_window_flag(row["duration_s"]) + apply_stages(row, data) + row["notes"] = build_notes("3.6", response_format_inferred, row["short_window"]) + apply_audio_output( + row, data, "3.6", log_path, sample_rate, row["response_format"] + ) + rows.append(row) + return rows + + +# --------------------------------------------------------------------------- +# Group 3: 3.6 Athena +# --------------------------------------------------------------------------- + + +def build_athena(recipe_root, header, mlflow_index=None): + """Build rows from the Athena matrix CSV and cell artifacts.""" + metadata = load_json(os.path.join(recipe_root, ATHENA_META)) + defaults = metadata.get("defaults", {}) + patterns = metadata.get("patterns", []) + + rows = [] + for source_row in read_csv_rows(os.path.join(recipe_root, ATHENA_CSV)): + model = as_text(source_row.get("model")) + if not model.startswith(QWEN_TTS_PREFIX): + continue + + relative_path = os.path.normpath(as_text(source_row.get("source_file"))) + json_path = os.path.join(recipe_root, relative_path) + data = load_json(json_path) + json_dir = os.path.dirname(json_path) + cell_meta = load_json(os.path.join(json_dir, "cell_meta.json")) + run_meta = load_json(os.path.join(json_dir, "run_meta.json")) + + run_config = run_meta.get("config") or {} + model_config = run_config.get("model") or {} + benchmark_config = run_config.get("benchmark") or {} + + task_type = normalize_task_type( + pick(cell_meta.get("task_type"), source_row.get("task_type")) + ) + runtime_version = as_text( + pick(cell_meta.get("version"), source_row.get("version")) + ) + profile = as_text(pick(cell_meta.get("profile"), source_row.get("profile"))) + concurrency = concurrency_str( + pick(data.get("max_concurrency"), source_row.get("concurrency")) + ) + phase = "matrix" + + run_dir = os.path.basename(os.path.dirname(os.path.dirname(relative_path))) + run_name = f"{run_dir}-{profile}_c{concurrency}" + + model_id = as_text( + pick(data.get("model_id"), source_row.get("model"), cell_meta.get("model")) + ) + + pattern = match_pattern(patterns, recipe_root, json_path) + mlflow_run_id = "" + by_concurrency = pattern.get("mlflow_run_id_by_concurrency") or {} + if by_concurrency: + mlflow_run_id = as_text(by_concurrency.get(concurrency)) + if not mlflow_run_id: + mlflow_run_id = as_text(pattern.get("mlflow_run_id")) + deployment_uuid = as_text( + pick(cell_meta.get("deployment_uuid"), run_meta.get("deployment_uuid")) + ) + if not mlflow_run_id: + mlflow_run_id = mlflow_run_id_for( + mlflow_index, run_name, deployment_uuid, concurrency + ) + + response_format = response_format_from_extra_body(cell_meta.get("extra_body")) + if not response_format: + response_format = response_format_from_extra_body( + benchmark_config.get("extra_body") + ) + response_format_inferred = not response_format + if not response_format: + response_format = "wav" + + dataset = as_text(pick(cell_meta.get("dataset"), source_row.get("dataset"))) + sample_rate = pick( + defaults.get("audio_sample_rate_hz"), DEFAULT_AUDIO_SAMPLE_RATE + ) + log_path = find_log(json_path) + + row = new_row(header) + row["run_key"] = "__".join( + [ + slug(model_id), + runtime_version, + profile, + task_type, + "c" + concurrency, + phase, + ] + ) + row["run_name"] = run_name + row["timestamp_utc"] = normalize_timestamp( + pick(run_meta.get("started_at"), data.get("date")), json_path + ) + row["cluster"] = "athena" + row["deployment_uuid"] = deployment_uuid + row["mlflow_run_id"] = mlflow_run_id + row["source_file"] = relative_path + + row["model"] = model_id + row["runtime_version"] = runtime_version + row["image_tag"] = strip_image_digest(cell_meta.get("image")) + row["accelerator"] = as_text(cell_meta.get("gpu_model")) + row["gpu_count"] = as_text(pick(cell_meta.get("gpu_count"), "1")) + row["tp"] = as_text(pick(model_config.get("tp"), "1")) + + row["modality"] = "audio" + row["input_modality"] = "text" + row["output_modality"] = "audio" + row["task_type"] = task_type + row["recipe"] = profile + row["experiment_phase"] = phase + row["benchmark_tool"] = as_text( + pick(defaults.get("benchmark_tool"), "vllm-omni-bench-serve") + ) + row["load_generator"] = as_text( + pick(defaults.get("load_generator"), DEFAULT_LOAD_GENERATOR) + ) + row["api_endpoint"] = map_endpoint(data.get("endpoint_type")) + row["benchmark_mode"] = "streaming" + row["response_format"] = response_format + row["tokenizer_override"] = tokenizer_override( + model_id, data.get("tokenizer_id") + ) + row["runtime_args"] = compose_runtime_args( + pick( + model_config.get("gpu_memory_utilization"), + DEFAULT_GPU_MEM if runtime_version == "vllm-omni-3.6.0-ga" else "", + ), + pick(cell_meta.get("max_num_seqs"), model_config.get("max_num_seqs")), + pick( + cell_meta.get("max_num_batched_tokens"), + model_config.get("max_num_batched_tokens"), + ), + ) + # Every included Athena point has completed == num_prompts and failed == 0. + row["status"] = "valid" + + row["dataset"] = dataset + row["locale"] = locale_for(dataset, task_type) + row["concurrency"] = concurrency + row["measured_concurrency"] = as_text(data.get("max_concurrent_requests")) + + apply_metrics(row, data, source_row, "athena") + row["short_window"] = short_window_flag(row["duration_s"]) + apply_stages(row, data) + row["notes"] = build_notes( + "athena", response_format_inferred, row["short_window"] + ) + apply_audio_output( + row, data, "athena", log_path, sample_rate, row["response_format"] + ) + rows.append(row) + return rows + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +def dashboard_repo_root(): + """Return the dashboard repository root.""" + path = os.path.dirname(os.path.abspath(__file__)) + while True: + if os.path.isdir(os.path.join(path, "manual_runs", "scripts")): + return path + parent = os.path.dirname(path) + if parent == path: + return os.getcwd() + path = parent + + +def usage(): + """Return the CLI usage text.""" + return __doc__.strip() + + +def parse_args(argv): + """Parse command-line arguments into paths.""" + recipe_root = DEFAULT_RECIPE_ROOT + output = "" + template = "" + mlflow_runs_json = "" + + index = 1 + while index < len(argv): + argument = argv[index] + if argument in ("-h", "--help"): + print(usage()) + raise SystemExit(0) + + name = argument + value = None + if argument.startswith("--") and "=" in argument: + name, value = argument.split("=", 1) + elif argument in ( + "--recipe-root", + "--output", + "--template", + "--mlflow-runs-json", + ): + if index + 1 >= len(argv): + raise SystemExit(f"Missing value for {argument}") + value = argv[index + 1] + index += 1 + else: + raise SystemExit(f"Unknown argument: {argument}") + + if name == "--recipe-root": + recipe_root = value + elif name == "--output": + output = value + elif name == "--template": + template = value + elif name == "--mlflow-runs-json": + mlflow_runs_json = value + else: + raise SystemExit(f"Unknown argument: {name}") + index += 1 + + repo_root = dashboard_repo_root() + if not output: + output = os.path.join(repo_root, OUTPUT_REL) + if not template: + template = os.path.join(repo_root, TEMPLATE_REL) + + return ( + os.path.abspath(os.path.expanduser(recipe_root)), + os.path.abspath(os.path.expanduser(output)), + os.path.abspath(os.path.expanduser(template)), + ( + os.path.abspath(os.path.expanduser(mlflow_runs_json)) + if mlflow_runs_json + else "" + ), + ) + + +def read_header(template_path): + """Read the canonical header from the template CSV.""" + if not os.path.isfile(template_path): + raise SystemExit(f"Template not found: {template_path}") + with open(template_path, encoding="utf-8", newline="") as handle: + reader = csv.reader(handle) + header = next(reader, None) + if not header: + raise SystemExit(f"Template has no header: {template_path}") + return header + + +def main(argv): + """Build the CSV and print a validation summary.""" + recipe_root, output_path, template_path, mlflow_runs_json = parse_args(argv) + header = read_header(template_path) + if len(header) != 77: + raise SystemExit( + f"Template must have 77 columns, found {len(header)}: {template_path}" + ) + + mlflow_index = load_mlflow_index(mlflow_runs_json) + legacy_rows = build_35(recipe_root, header) + base_rows = build_36(recipe_root, header) + athena_rows = build_athena(recipe_root, header, mlflow_index) + rows = legacy_rows + base_rows + athena_rows + if not rows: + raise SystemExit( + f"No benchmark rows found under {recipe_root}. Check --recipe-root." + ) + + for row in rows: + if "Voxtral" in row.get("model", "") or "OmniVoice" in row.get("model", ""): + raise SystemExit( + "Out-of-scope model leaked into output: {}".format(row.get("model")) + ) + + seen = {} + resolved_collisions = 0 + for row in rows: + key = row.get("run_key", "") + if key in seen: + suffix = "__".join( + value + for value in ( + slug(row.get("deployment_uuid")), + slug(row.get("response_format")), + slug(row.get("run_name")), + ) + if value + ) + candidate = f"{key}__{suffix}" if suffix else key + if candidate in seen: + raise SystemExit(f"Duplicate run_key values: {key} and {candidate}") + row["run_key"] = candidate + key = candidate + resolved_collisions += 1 + seen[key] = row + + missing_required = [] + for row in rows: + for column in REQUIRED_COLUMNS: + if not row.get(column): + missing_required.append((row.get("run_key", ""), column)) + if missing_required: + raise SystemExit( + f"Required dashboard columns are blank: {missing_required[:10]}" + ) + + output_dir = os.path.dirname(output_path) + if output_dir and not os.path.isdir(output_dir): + os.makedirs(output_dir) + + with open(output_path, "w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter( + handle, fieldnames=header, extrasaction="ignore", restval="" + ) + writer.writeheader() + for row in rows: + writer.writerow({column: row.get(column, "") for column in header}) + + print(f"3.5 legacy rows: {len(legacy_rows)}") + print(f"3.6 base rows: {len(base_rows)}") + print(f"3.6 Athena rows: {len(athena_rows)}") + print(f"total rows: {len(rows)}") + print(f"columns: {len(header)}") + print(f"resolved run_key collisions:{resolved_collisions}") + print(f"written: {output_path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/manual_runs/scripts/vllm-omni/extract_mlflow_runs.py b/manual_runs/scripts/vllm-omni/extract_mlflow_runs.py new file mode 100644 index 0000000..ebbb072 --- /dev/null +++ b/manual_runs/scripts/vllm-omni/extract_mlflow_runs.py @@ -0,0 +1,391 @@ +#!/usr/bin/env python3 +"""Extract MLflow runs and selected artifacts into a local folder. + +Examples: + export MLFLOW_TRACKING_URI=https://mlflow.example.com + export MLFLOW_WORKSPACE=my-workspace + export MLFLOW_TRACKING_USERNAME=... + export MLFLOW_TRACKING_PASSWORD=... + + python manual_runs/scripts/vllm-omni/extract_mlflow_runs.py \ + --experiment-id \ + --name-regex '^my-benchmark-run_.*_c[0-9]+$' \ + --artifact-pattern 'results/*.json' \ + --artifact-pattern 'logs/*.log' \ + --output-dir ~/Downloads/mlflow-runs + +Outputs: + /runs.json Full MLflow run records + /runs_summary.csv Flattened params, metrics, and tags + /manifest.json Selection, downloads, and errors + /artifacts// Downloaded artifacts, paths preserved +""" + +from __future__ import annotations + +import argparse +import csv +import fnmatch +import json +import os +import re +import shutil +import sys +import tempfile +from datetime import datetime, timezone +from pathlib import Path + +import urllib3 + +DEFAULT_TRACKING_URI = os.environ.get("MLFLOW_TRACKING_URI", "") +DEFAULT_WORKSPACE = os.environ.get("MLFLOW_WORKSPACE", "") +DEFAULT_ARTIFACT_PATTERNS = ["results/*"] + + +def utc_now() -> str: + """Return the current UTC time as an ISO 8601 string.""" + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def ms_to_utc(value: int | None) -> str: + """Convert milliseconds since epoch to an ISO 8601 UTC string.""" + if not value: + return "" + return datetime.fromtimestamp(value / 1000, tz=timezone.utc).isoformat( + timespec="seconds" + ) + + +def safe_dirname(run_name: str, run_id: str) -> str: + """Return a filesystem-safe directory name.""" + name = re.sub(r"[^A-Za-z0-9._-]+", "_", run_name or "run").strip("._") + return f"{name[:120] or 'run'}__{run_id[:8]}" + + +def matches_any(path: str, patterns: list[str]) -> bool: + """Return whether a value matches any regex or glob pattern.""" + return any(fnmatch.fnmatch(path, pattern) for pattern in patterns) + + +def flatten_run(run) -> dict: + """Flatten an MLflow run record into scalar columns.""" + row = { + "run_id": run.info.run_id, + "run_name": run.info.run_name or "", + "status": run.info.status, + "experiment_id": run.info.experiment_id, + "start_time_utc": ms_to_utc(run.info.start_time), + "end_time_utc": ms_to_utc(run.info.end_time), + "artifact_uri": run.info.artifact_uri, + } + for key, value in (run.data.params or {}).items(): + row[f"param.{key}"] = value + for key, value in (run.data.metrics or {}).items(): + row[f"metric.{key}"] = value + for key, value in (run.data.tags or {}).items(): + row[f"tag.{key}"] = value + return row + + +def walk_artifacts(client, run_id: str, path: str = ""): + """Yield artifact paths below an MLflow artifact directory.""" + for item in client.list_artifacts(run_id, path): + if item.is_dir: + yield from walk_artifacts(client, run_id, item.path) + else: + yield item + + +def select_runs(client, args): + """Select runs matching the CLI filters.""" + if args.run_id: + runs = [client.get_run(run_id) for run_id in args.run_id] + else: + filter_parts = [] + if args.status: + filter_parts.append(f"attributes.status = '{args.status}'") + runs = client.search_runs( + [args.experiment_id], + filter_string=" and ".join(filter_parts), + max_results=args.max_results, + order_by=[args.order_by], + ) + + if args.name_regex: + pattern = re.compile(args.name_regex) + runs = [run for run in runs if pattern.search(run.info.run_name or "")] + + if args.limit: + runs = runs[: args.limit] + + return runs + + +def print_summary(runs) -> None: + """Print a short selection summary.""" + if not runs: + return + print(f"{'run_name':<64} {'status':<10} {'c':>4} {'req/s':>9} {'p95 RTF':>9}") + print("-" * 100) + for run in runs: + params = run.data.params or {} + metrics = run.data.metrics or {} + c = params.get("max_concurrency", "") + rps = metrics.get("request_throughput") + rtf = metrics.get("p95_audio_rtf") + rps_text = f"{rps:.3f}" if isinstance(rps, (int, float)) else "" + rtf_text = f"{rtf:.4f}" if isinstance(rtf, (int, float)) else "" + print( + f"{(run.info.run_name or '')[:64]:<64} {run.info.status:<10} " + f"{str(c):>4} {rps_text:>9} {rtf_text:>9}" + ) + + +def main() -> int: + """Run the MLflow artifact extraction CLI.""" + parser = argparse.ArgumentParser( + description="Extract MLflow runs, metrics, and selected artifacts." + ) + parser.add_argument("--experiment-id", default=None) + parser.add_argument("--tracking-uri", default=DEFAULT_TRACKING_URI) + parser.add_argument("--workspace", default=DEFAULT_WORKSPACE) + parser.add_argument("--run-id", action="append", help="Extract specific run ID(s).") + parser.add_argument("--name-regex", help="Only runs whose name matches this regex.") + parser.add_argument( + "--status", choices=["RUNNING", "SCHEDULED", "FINISHED", "FAILED", "KILLED"] + ) + parser.add_argument( + "--order-by", + default="attributes.start_time DESC", + help="MLflow order_by clause.", + ) + parser.add_argument("--max-results", type=int, default=500) + parser.add_argument("--limit", type=int, help="Cap the number of selected runs.") + parser.add_argument( + "--artifact-pattern", + action="append", + dest="artifact_patterns", + help=f"Glob for artifact paths. Default: {DEFAULT_ARTIFACT_PATTERNS}. Repeatable.", + ) + parser.add_argument( + "--max-artifact-mb", + type=float, + default=25.0, + help="Skip individual artifacts larger than this size (default: 25).", + ) + parser.add_argument( + "--skip-artifacts", action="store_true", help="Write run metadata only." + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Select and list artifacts without writing.", + ) + parser.add_argument( + "--insecure", + action="store_true", + default=os.environ.get("MLFLOW_TRACKING_INSECURE_TLS", "").lower() + in ("1", "true", "yes"), + help="Disable TLS verification.", + ) + parser.add_argument( + "--output-dir", + default=None, + help="Destination (default: mlflow_extracts/_).", + ) + args = parser.parse_args() + + if not args.tracking_uri: + parser.error("Set --tracking-uri or MLFLOW_TRACKING_URI.") + if not args.run_id and not args.experiment_id: + parser.error("Set --experiment-id when not using --run-id.") + + os.environ["MLFLOW_TRACKING_URI"] = args.tracking_uri + if args.workspace: + os.environ["MLFLOW_WORKSPACE"] = args.workspace + if args.insecure: + os.environ["MLFLOW_TRACKING_INSECURE_TLS"] = "true" + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + os.environ.setdefault("MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR", "false") + + try: + from mlflow.tracking import MlflowClient + except ImportError: + print( + "mlflow is not installed. Install it with: pip install mlflow", + file=sys.stderr, + ) + return 2 + + username = os.environ.get("MLFLOW_TRACKING_USERNAME") + password = os.environ.get("MLFLOW_TRACKING_PASSWORD") + if bool(username) != bool(password): + print( + "Set both MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD, or neither.", + file=sys.stderr, + ) + return 2 + + client = MlflowClient(tracking_uri=args.tracking_uri) + try: + runs = select_runs(client, args) + except Exception as exc: + message = str(exc) + hint = "" + if "401" in message or "403" in message or "Unauthorized" in message: + hint = ( + " Check MLFLOW_TRACKING_USERNAME/PASSWORD and MLFLOW_WORKSPACE " + f"(current workspace: {args.workspace or 'unset'})." + ) + print(f"MLflow query failed: {message}.{hint}", file=sys.stderr) + return 1 + + if not runs: + print("No runs matched the selection.", file=sys.stderr) + return 1 + + if args.dry_run: + print_summary(runs) + patterns = args.artifact_patterns or DEFAULT_ARTIFACT_PATTERNS + for run in runs: + files = [ + item + for item in walk_artifacts(client, run.info.run_id) + if matches_any(item.path, patterns) + ] + print(f"\n{run.info.run_name} ({run.info.run_id})") + for item in files: + size = ( + f"{item.file_size} B" + if item.file_size is not None + else "size unknown" + ) + print(f" {item.path} ({size})") + return 0 + + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + output_dir = Path( + args.output_dir or f"mlflow_extracts/{args.experiment_id}_{stamp}" + ).expanduser() + output_dir.mkdir(parents=True, exist_ok=True) + + runs_payload = [] + for run in runs: + payload = run.to_dictionary() if hasattr(run, "to_dictionary") else {} + runs_payload.append(payload) + (output_dir / "runs.json").write_text(json.dumps(runs_payload, indent=2)) + + rows = [flatten_run(run) for run in runs] + fieldnames = list(rows[0].keys()) + extra = sorted( + {key for row in rows for key in row if key not in fieldnames}, + key=lambda key: (not key.startswith("param."), key), + ) + fieldnames.extend(extra) + with (output_dir / "runs_summary.csv").open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + patterns = args.artifact_patterns or DEFAULT_ARTIFACT_PATTERNS + manifest = { + "generated_at_utc": utc_now(), + "tracking_uri": args.tracking_uri, + "workspace": args.workspace, + "experiment_id": args.experiment_id, + "selection": { + "run_ids": args.run_id, + "name_regex": args.name_regex, + "status": args.status, + "order_by": args.order_by, + "max_results": args.max_results, + "limit": args.limit, + "artifact_patterns": patterns, + }, + "run_count": len(runs), + "runs": [], + "errors": [], + } + + for run in runs: + run_dir = ( + output_dir + / "artifacts" + / safe_dirname(run.info.run_name or "", run.info.run_id) + ) + run_entry = { + "run_id": run.info.run_id, + "run_name": run.info.run_name or "", + "status": run.info.status, + "artifact_dir": str(run_dir.relative_to(output_dir)), + "downloaded": [], + "skipped": [], + "errors": [], + } + + if not args.skip_artifacts: + try: + files = [ + item + for item in walk_artifacts(client, run.info.run_id) + if matches_any(item.path, patterns) + ] + except Exception as exc: + run_entry["errors"].append(f"list artifacts: {exc}") + manifest["errors"].append(f"{run.info.run_id}: list artifacts: {exc}") + files = [] + + for item in files: + if ( + item.file_size is not None + and args.max_artifact_mb + and item.file_size > args.max_artifact_mb * 1024 * 1024 + ): + run_entry["skipped"].append( + { + "path": item.path, + "size_bytes": item.file_size, + "reason": f"larger than {args.max_artifact_mb} MB", + } + ) + continue + try: + with tempfile.TemporaryDirectory() as tmp: + local = Path( + client.download_artifacts(run.info.run_id, item.path, tmp) + ) + target = run_dir / item.path + target.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(local), str(target)) + run_entry["downloaded"].append( + { + "path": item.path, + "local_path": str(target.relative_to(output_dir)), + "size_bytes": target.stat().st_size, + } + ) + except Exception as exc: + message = f"{item.path}: {exc}" + run_entry["errors"].append(message) + manifest["errors"].append(f"{run.info.run_id}: {message}") + + manifest["runs"].append(run_entry) + + (output_dir / "manifest.json").write_text(json.dumps(manifest, indent=2)) + + print_summary(runs) + downloaded = sum(len(entry["downloaded"]) for entry in manifest["runs"]) + skipped = sum(len(entry["skipped"]) for entry in manifest["runs"]) + errors = len(manifest["errors"]) + print( + f"\nWrote {len(runs)} runs, {downloaded} artifacts, {skipped} skipped, " + f"{errors} errors to {output_dir}" + ) + if errors: + print("See manifest.json for error details.", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_template.csv b/manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_template.csv new file mode 100644 index 0000000..74f1891 --- /dev/null +++ b/manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_template.csv @@ -0,0 +1 @@ +schema_version,source_format,timestamp_utc,run_name,benchmark_run_id,repetition,mlflow_run_id,mlflow_parent_run_id,mlflow_experiment_id,cluster,namespace,deployment_uuid,deployment_pod_name,grafana_dashboard_uid,model,model_revision,runtime,runtime_version,vllm_version,vllm_omni_version,image_tag,image_digest,accelerator,gpu_count,tp,pp,dp,modality,input_modality,output_modality,task_type,benchmark_tool,benchmark_tool_version,load_generator,dataset,dataset_path,dataset_split,locale,num_prompts,num_utterances,request_rate,concurrency,measured_concurrency,num_warmups,turns,prefix_tokens,prefix_count,prefix_caching,spec_decoding,request_type,extra_body_json,runtime_args,env_vars_json,max_num_seqs,max_num_batched_tokens,duration_s,successful_requests,errored_requests,benchmark_start_ms,benchmark_end_ms,prompt_tokens_requested,output_tokens_requested,prompt_tokens_total,output_tokens_total,prompt_tokens_mean,prompt_tokens_p99,output_tokens_mean,output_tokens_p99,ttft_ms_mean,ttft_ms_median,ttft_ms_std,ttft_ms_p25,ttft_ms_p50,ttft_ms_p75,ttft_ms_p90,ttft_ms_p95,ttft_ms_p99,tpot_ms_mean,tpot_ms_median,tpot_ms_std,tpot_ms_p50,tpot_ms_p95,tpot_ms_p99,itl_ms_mean,itl_ms_median,itl_ms_std,itl_ms_p50,itl_ms_p95,itl_ms_p99,e2el_ms_mean,e2el_ms_median,e2el_ms_std,e2el_ms_p25,e2el_ms_p50,e2el_ms_p75,e2el_ms_p90,e2el_ms_p95,e2el_ms_p99,e2el_ms_min,e2el_ms_max,request_throughput_rps,output_token_throughput,total_token_throughput,audio_ttfp_ms_mean,audio_ttfp_ms_median,audio_ttfp_ms_std,audio_ttfp_ms_p25,audio_ttfp_ms_p50,audio_ttfp_ms_p75,audio_ttfp_ms_p90,audio_ttfp_ms_p95,audio_ttfp_ms_p99,audio_rtf_mean,audio_rtf_median,audio_rtf_std,audio_rtf_p25,audio_rtf_p50,audio_rtf_p75,audio_rtf_p90,audio_rtf_p95,audio_rtf_p99,audio_duration_s_mean,audio_duration_s_median,audio_duration_s_p50,audio_duration_s_p95,audio_duration_s_p99,audio_underrun_s_mean,audio_underrun_s_median,audio_underrun_s_p50,audio_underrun_s_p95,audio_underrun_s_p99,audio_throughput_x,audio_output_duration_s_total,audio_frames_total,audio_sample_rate_hz,audio_continuity_ok_rate,wer,wer_ci_lower,wer_ci_upper,rtfx,transcription_throughput_utterances_s,audio_input_duration_s_total,normalization,language,stage_0_ttft_ms_p50,stage_0_ttft_ms_p95,stage_1_ttft_ms_p50,stage_1_ttft_ms_p95,stage_0_gen_time_ms_p50,stage_0_gen_time_ms_p95,stage_1_gen_time_ms_p50,stage_1_gen_time_ms_p95,transfer_tx_ms_p50,transfer_tx_ms_p95,stage_metrics_json,gpu_util_mean,gpu_util_p95,gpu_mem_used_mean_mb,gpu_power_mean_w,gpu_temp_max_c,quality_metric,quality_value,extra_json,notes,source_file diff --git a/manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_tts_template.csv b/manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_tts_template.csv new file mode 100644 index 0000000..d2eb05f --- /dev/null +++ b/manual_runs/scripts/vllm-omni/templates/consolidated_dashboard_omni_tts_template.csv @@ -0,0 +1 @@ +run_key,run_name,timestamp_utc,cluster,deployment_uuid,mlflow_run_id,source_file,model,runtime_version,image_tag,accelerator,gpu_count,tp,modality,input_modality,output_modality,task_type,recipe,runtime_args,experiment_phase,benchmark_tool,load_generator,api_endpoint,benchmark_mode,response_format,tokenizer_override,status,dataset,locale,num_prompts,request_rate,concurrency,measured_concurrency,short_window,duration_s,successful_requests,errored_requests,e2el_ms_mean,e2el_ms_median,e2el_ms_p95,e2el_ms_p99,request_throughput_rps,stage_0_ttft_ms_p50,stage_0_ttft_ms_p95,stage_1_ttft_ms_p50,stage_1_ttft_ms_p95,transfer_tx_ms_p50,transfer_tx_ms_p95,notes,audio_ttfp_ms_mean,audio_ttfp_ms_median,audio_ttfp_ms_p95,audio_ttfp_ms_p99,audio_rtf_mean,audio_rtf_median,audio_rtf_p95,audio_rtf_p99,audio_duration_s_mean,audio_duration_s_median,audio_duration_s_p95,audio_duration_s_p99,audio_underrun_s_mean,audio_underrun_s_median,audio_underrun_s_p95,audio_underrun_s_p99,audio_throughput_x,audio_output_duration_s_total,audio_frames_total,audio_sample_rate_hz,audio_continuity_ok_rate,num_audio_ttfp_samples,num_audio_rtf_samples,missing_audio_duration_count,audio_channels,audio_bits_per_sample,audio_codec,audio_underrun_threshold_s diff --git a/omni_dashboard.py b/omni_dashboard.py new file mode 100644 index 0000000..b156e43 --- /dev/null +++ b/omni_dashboard.py @@ -0,0 +1,2613 @@ +# mypy: ignore-errors +"""vLLM-Omni Performance Dashboard Module. + +Loads the consolidated Omni benchmark CSV (text, speech-out, and ASR) and +renders modality-aware performance and quality views. The module follows the +same S3/local-CSV loading pattern as ``llmd_dashboard.py`` and keeps the +RHAIIS sidebar navigation shell. +""" + +import hashlib +import logging +import os +import re +import sys +import tempfile +from pathlib import Path +from typing import Optional + +import numpy as np +import pandas as pd +import plotly.express as px +import plotly.io as pio +import streamlit as st + +from dashboard_taxonomy import ( + MARKER_SYMBOLS, + add_trace_metadata, + deterministic_color_map, +) + +if "plotly_white_light" not in pio.templates: + pio.templates["plotly_white_light"] = pio.templates["plotly_white"] +pio.templates.default = "plotly_white_light" + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + handlers=[logging.StreamHandler(sys.stdout)], +) +logger = logging.getLogger(__name__) + +# S3 configuration (same env convention as the main dashboard) +S3_BUCKET = os.environ.get("S3_BUCKET") +S3_KEY_OMNI = os.environ.get("S3_KEY_OMNI", "consolidated_dashboard_omni.csv") +S3_REGION = os.environ.get("S3_REGION", "us-east-1") + +MLFLOW_TRACKING_URI = os.environ.get("MLFLOW_TRACKING_URI", "") +MLFLOW_BASE_URL = os.environ.get("MLFLOW_BASE_URL", MLFLOW_TRACKING_URI) +MLFLOW_WORKSPACE = os.environ.get("MLFLOW_WORKSPACE", "") +OMNI_MLFLOW_EXPERIMENT_ID = os.environ.get("OMNI_MLFLOW_EXPERIMENT_ID", "") +MLFLOW_LOG_ARTIFACT_PREFIX = os.environ.get("MLFLOW_LOG_ARTIFACT_PREFIX", "logs") +MAX_LOG_DISPLAY_CHARS = 2_000_000 +OMNI_LOG_DIR = os.environ.get("OMNI_LOG_DIR", "datasets/omni/logs") +S3_LOGS_BUCKET = os.environ.get("S3_LOGS_BUCKET", "") +S3_LOGS_PREFIX = os.environ.get("S3_LOGS_PREFIX", "logs/") + +GRAFANA_BASE_URL = os.environ.get("GRAFANA_BASE_URL", "") +OMNI_GRAFANA_DASHBOARD_UID = os.environ.get("OMNI_GRAFANA_DASHBOARD_UID", "") + +NUMERIC_COLUMNS = [ + "concurrency", + "measured_concurrency", + "num_prompts", + "num_utterances", + "tp", + "pp", + "dp", + "gpu_count", + "request_throughput_rps", + "output_token_throughput", + "total_token_throughput", + "audio_throughput_x", + "audio_rtf_mean", + "audio_rtf_median", + "audio_rtf_p95", + "audio_rtf_p99", + "audio_ttfp_ms_mean", + "audio_ttfp_ms_median", + "audio_ttfp_ms_p95", + "audio_ttfp_ms_p99", + "audio_underrun_s_mean", + "audio_underrun_s_median", + "audio_underrun_s_p95", + "audio_underrun_s_p99", + "audio_continuity_ok_rate", + "ttft_ms_mean", + "ttft_ms_median", + "ttft_ms_p95", + "ttft_ms_p99", + "tpot_ms_mean", + "tpot_ms_median", + "tpot_ms_p95", + "tpot_ms_p99", + "itl_ms_mean", + "itl_ms_median", + "itl_ms_p95", + "itl_ms_p99", + "e2el_ms_mean", + "e2el_ms_median", + "e2el_ms_p95", + "e2el_ms_p99", + "wer", + "rtfx", + "transcription_throughput_utterances_s", + "audio_input_duration_s_total", + "audio_output_duration_s_total", +] + +LOAD_GENERATORS = { + "guidellm", + "vllm-omni-bench-serve", + "vllm-bench-serve", + "locust", + "k6", +} + +TASK_TYPE_LABELS = { + "voice_clone": "TTS - Voice Clone", + "default_voice": "TTS - Default Voice", + "voice_design": "TTS - Voice Design", + "asr_transcription": "ASR / STT - Transcription", + "text_to_text": "Text - Text generation", +} + +TASK_TYPE_ORDER = [ + "voice_clone", + "default_voice", + "voice_design", + "asr_transcription", + "text_to_text", +] + +TASK_HELP = ( + "- **TTS - Voice Clone**: clone a reference voice from an audio sample.\n" + "- **TTS - Default Voice**: synthesize with a preset or automatic voice.\n" + "- **TTS - Voice Design**: synthesize from a voice description.\n" + "- **ASR / STT - Transcription**: transcribe audio to text.\n" + "- **Text - Text generation**: text-to-text generation." +) + +DATASET_HELP = ( + "- **seed-tts**: reference audio + transcript; voice cloning (Base models).\n" + "- **seed-tts-text**: text-only prompts; preset or automatic voice " + "(CustomVoice, OmniVoice, Voxtral).\n" + "- **seed-tts-design**: voice description + text; voice-design models.\n" + "- **(unspecified)**: legacy rows that did not record a dataset." +) + + +def _task_label(value: str) -> str: + return TASK_TYPE_LABELS.get(str(value), str(value)) + + +def _omni_legend_label(row: pd.Series) -> str: + tp = row.get("TP") + if pd.notna(tp): + tp_text = f"TP={int(tp) if float(tp).is_integer() else tp}" + else: + tp_text = "TP=N/A" + recipe = str(row.get("recipe") or "default").strip() + if recipe.lower() == "b8": + recipe = "B8" + return " | ".join( + [ + str(row.get("model_short") or row.get("model") or "?"), + str(row.get("runtime_version") or "?"), + _task_label(row.get("task_type")), + str(row.get("dataset") or "?"), + recipe, + tp_text, + ] + ) + + +PLOT_CUSTOM_DATA = [ + "accelerator", + "model_short", + "runtime_version", + "task_label", + "dataset", + "concurrency", + "num_prompts", + "deployment_uuid_hover", + "runtime_args_hover", + "response_format_label", +] + +# Default Filtered Data view. The full row stays available via the CSV download +# and the "Show all columns" toggle. +OMNI_DISPLAY_COLUMNS = [ + "model", + "runtime_version", + "mlflow_link", + "grafana_metrics_link", + "recipe", + "task_type", + "dataset", + "response_format", + "concurrency", + "num_prompts", + "audio_ttfp_ms_p95", + "audio_rtf_p95", + "audio_underrun_s_p95", + "audio_throughput_x", + "e2el_ms_p95", + "duration_s", + "successful_requests", + "errored_requests", + "status", +] + + +def _display_frame(frame: pd.DataFrame) -> pd.DataFrame: + columns = [column for column in OMNI_DISPLAY_COLUMNS if column in frame.columns] + return frame[columns] if columns else frame + + +def _mlflow_link(row: pd.Series): + run_id = str(row.get("mlflow_run_id") or "").strip() + if ( + not run_id + or run_id.lower() in ("nan", "none") + or not MLFLOW_BASE_URL + or not OMNI_MLFLOW_EXPERIMENT_ID + ): + return "" + return ( + f"{MLFLOW_BASE_URL}/#/experiments/{OMNI_MLFLOW_EXPERIMENT_ID}" + f"/runs/{run_id}/artifacts?workspace={MLFLOW_WORKSPACE}" + ) + + +def _grafana_metrics_link(row: pd.Series): + if not GRAFANA_BASE_URL or not OMNI_GRAFANA_DASHBOARD_UID: + return "" + uuid = str(row.get("deployment_uuid") or "").strip() + if not uuid or uuid.lower() in ("nan", "none"): + return "" + timestamp = pd.to_datetime(row.get("timestamp_utc"), errors="coerce", utc=True) + duration = pd.to_numeric(row.get("duration_s"), errors="coerce") + if pd.isna(timestamp) or pd.isna(duration): + return "" + start_ms = int(timestamp.timestamp() * 1000) - 600_000 + end_ms = start_ms + int(float(duration) * 1000) + 300_000 + return ( + f"{GRAFANA_BASE_URL}/d/{OMNI_GRAFANA_DASHBOARD_UID}/" + f"{OMNI_GRAFANA_DASHBOARD_UID}" + f"?orgId=1&from={start_ms}&to={end_ms}&timezone=browser" + f"&var-deployment_uuid={uuid}&var-deployment_pod_name=$__all" + f"&var-rate_interval=1m" + ) + + +def _blank_nan(frame: pd.DataFrame) -> pd.DataFrame: + """Render missing numeric cells as blanks instead of 'None'.""" + display = frame.copy() + for column in display.columns: + if pd.api.types.is_float_dtype(display[column]): + display[column] = display[column].map( + lambda value: "" if pd.isna(value) else str(value) + ) + return display + + +def _link_column_config(frame: pd.DataFrame): + config = {} + if "mlflow_link" in frame.columns: + config["mlflow_link"] = st.column_config.LinkColumn( + "MLflow", help="Open this run in MLflow", display_text="View Run 🧪" + ) + if "grafana_metrics_link" in frame.columns: + config["grafana_metrics_link"] = st.column_config.LinkColumn( + "Grafana Metrics", + help="Open this run in Grafana", + display_text="View Metrics 📊", + ) + return config or None + + +OMNI_METRICS = { + "Request throughput (req/s)": "request_throughput_rps", + "Audio throughput (audio-s/s)": "audio_throughput_x", + "Output token throughput (tok/s)": "output_token_throughput", + "Total token throughput (tok/s)": "total_token_throughput", + "Audio RTF mean": "audio_rtf_mean", + "Audio RTF P95": "audio_rtf_p95", + "Audio TTFP mean (ms)": "audio_ttfp_ms_mean", + "Audio TTFP P95 (ms)": "audio_ttfp_ms_p95", + "Audio underrun mean (s)": "audio_underrun_s_mean", + "Audio underrun P95 (s)": "audio_underrun_s_p95", + "TTFT median (ms)": "ttft_ms_median", + "TPOT median (ms)": "tpot_ms_median", + "ITL median (ms)": "itl_ms_median", + "End-to-end median (ms)": "e2el_ms_median", + "WER": "wer", + "RTFx": "rtfx", + "Transcription throughput (utt/s)": "transcription_throughput_utterances_s", + "Requests sent (N)": "num_prompts", +} + + +def _available_metrics(frame: pd.DataFrame) -> dict: + return { + label: column + for label, column in OMNI_METRICS.items() + if column in frame.columns and frame[column].notna().any() + } + + +def _resolve_benchmark_mode(available_modes: set, preferred_streaming: bool) -> tuple: + """Pick streaming/non-streaming from the modes present in the filtered data.""" + has_streaming = "streaming" in available_modes + has_non_streaming = "non_streaming" in available_modes + if has_streaming and not has_non_streaming: + return "streaming", True + if has_non_streaming and not has_streaming: + return "non_streaming", False + if has_streaming and has_non_streaming: + if preferred_streaming: + return "streaming", True + return "non_streaming", False + return "", bool(preferred_streaming) + + +COMPARE_STATISTICS = ["Mean", "Median", "P95", "P99"] + +COMPARE_METRIC_FAMILIES = { + "Request throughput": { + "short": "Req/s", + "direction": "higher", + "column": "request_throughput_rps", + }, + "Audio throughput": { + "short": "Audio tput", + "direction": "higher", + "column": "audio_throughput_x", + }, + "Output token throughput": { + "short": "Out tok/s", + "direction": "higher", + "column": "output_token_throughput", + }, + "Total token throughput": { + "short": "Total tok/s", + "direction": "higher", + "column": "total_token_throughput", + }, + "Audio RTF": { + "short": "RTF", + "direction": "lower", + "columns": { + "Mean": "audio_rtf_mean", + "Median": "audio_rtf_median", + "P95": "audio_rtf_p95", + "P99": "audio_rtf_p99", + }, + }, + "Audio TTFP": { + "short": "TTFP", + "direction": "lower", + "columns": { + "Mean": "audio_ttfp_ms_mean", + "Median": "audio_ttfp_ms_median", + "P95": "audio_ttfp_ms_p95", + "P99": "audio_ttfp_ms_p99", + }, + }, + "Audio underrun": { + "short": "Underrun", + "direction": "lower", + "columns": { + "Mean": "audio_underrun_s_mean", + "Median": "audio_underrun_s_median", + "P95": "audio_underrun_s_p95", + "P99": "audio_underrun_s_p99", + }, + }, + "TTFT": { + "short": "TTFT", + "direction": "lower", + "columns": { + "Mean": "ttft_ms_mean", + "Median": "ttft_ms_median", + "P95": "ttft_ms_p95", + "P99": "ttft_ms_p99", + }, + }, + "TPOT": { + "short": "TPOT", + "direction": "lower", + "columns": { + "Mean": "tpot_ms_mean", + "Median": "tpot_ms_median", + "P95": "tpot_ms_p95", + "P99": "tpot_ms_p99", + }, + }, + "ITL": { + "short": "ITL", + "direction": "lower", + "columns": { + "Mean": "itl_ms_mean", + "Median": "itl_ms_median", + "P95": "itl_ms_p95", + "P99": "itl_ms_p99", + }, + }, + "End-to-end latency": { + "short": "E2EL", + "direction": "lower", + "columns": { + "Mean": "e2el_ms_mean", + "Median": "e2el_ms_median", + "P95": "e2el_ms_p95", + "P99": "e2el_ms_p99", + }, + }, + "WER": {"short": "WER", "direction": "lower", "column": "wer"}, + "RTFx": {"short": "RTFx", "direction": "higher", "column": "rtfx"}, + "Transcription throughput": { + "short": "STT utt/s", + "direction": "higher", + "column": "transcription_throughput_utterances_s", + }, +} + +COMPARE_SUMMARY_FAMILIES = [ + "Request throughput", + "Audio throughput", + "Audio RTF", + "Audio TTFP", + "Audio underrun", + "TTFT", + "TPOT", + "End-to-end latency", + "WER", + "RTFx", + "Transcription throughput", +] + +COMPARE_KEYS = [ + "model", + "task_type", + "dataset", + "concurrency_label", + "load_generator", + "tp", + "accelerator", + "response_format", + "recipe", + "num_prompts", + "benchmark_mode", +] +COMPARE_FLAT_THRESHOLD_PCT = 1.0 + +OMNI_NAV_GROUPS = [ + ("Dashboard", ["🏠 Overview"]), + ("Performance Analysis", ["📊 Performance Plots", "⚖️ Compare Versions"]), + ("Tools", ["📋 View Logs", "📄 Filtered Data"]), +] + + +def _s3_client(region: str): + """Return an S3 client using the normal AWS credential chain.""" + import boto3 + from botocore import UNSIGNED + from botocore.config import Config + + if os.environ.get("S3_ANONYMOUS", "").strip().lower() in ("1", "true", "yes"): + return boto3.client( + "s3", region_name=region, config=Config(signature_version=UNSIGNED) + ) + return boto3.client("s3", region_name=region) + + +def _read_csv_from_s3(bucket: str, key: str, region: str = "us-east-1") -> pd.DataFrame: + client = _s3_client(region) + obj = client.get_object(Bucket=bucket, Key=key) + return pd.read_csv(obj["Body"], low_memory=False) + + +def _normalise(df: pd.DataFrame) -> pd.DataFrame: + df = df.copy() + for col in df.select_dtypes(include=["object"]).columns: + df[col] = df[col].astype(str).str.strip() + df.loc[df[col].isin(["", "nan", "None", "NaN"]), col] = np.nan + + for col in NUMERIC_COLUMNS: + if col not in df.columns: + df[col] = np.nan + df[col] = pd.to_numeric(df[col], errors="coerce") + + if "load_generator" not in df.columns: + df["load_generator"] = np.nan + if "benchmark_tool" not in df.columns: + df["benchmark_tool"] = np.nan + df["load_generator"] = df["load_generator"].fillna("").astype(str) + tool = df["benchmark_tool"].fillna("").astype(str).str.lower() + fallback = tool.where(tool.isin(LOAD_GENERATORS), "offline") + df["load_generator"] = df["load_generator"].where( + df["load_generator"] != "", fallback + ) + + for col in ( + "modality", + "input_modality", + "output_modality", + "task_type", + "model", + "runtime_version", + "accelerator", + ): + if col not in df.columns: + df[col] = "unknown" + df[col] = df[col].fillna("unknown") + + if "recipe" not in df.columns and "profile" in df.columns: + df["recipe"] = df["profile"] + for column, default in ( + ("recipe", "default"), + ("experiment_phase", ""), + ("runtime_args", ""), + ("response_format", ""), + ("image_tag", ""), + ("tokenizer_override", "false"), + ): + if column not in df.columns: + df[column] = default + df[column] = df[column].fillna(default) + + if "dataset" not in df.columns: + df["dataset"] = np.nan + df["dataset_filter"] = df["dataset"].fillna("(unspecified)").astype(str).str.strip() + df.loc[ + df["dataset_filter"].isin(["", "nan", "None", "unknown"]), + "dataset_filter", + ] = "(unspecified)" + + def _conc_label(value): + if pd.isna(value): + return "n/a" + value = float(value) + return str(int(value)) if value.is_integer() else str(value) + + df["concurrency_label"] = df["concurrency"].apply(_conc_label) + df["series"] = ( + df["model"].astype(str) + + " | " + + df["runtime_version"].astype(str) + + " | " + + df["load_generator"].astype(str) + ) + df["mlflow_link"] = df.apply(_mlflow_link, axis=1) + df["grafana_metrics_link"] = df.apply(_grafana_metrics_link, axis=1) + return df + + +@st.cache_data(ttl=300) +def load_omni_data(file_path: str) -> Optional[pd.DataFrame]: + """Load the Omni CSV from S3 when configured, otherwise from file_path.""" + try: + if S3_BUCKET: + try: + df = _read_csv_from_s3(S3_BUCKET, S3_KEY_OMNI, S3_REGION) + logger.info("Loaded Omni data from s3://%s/%s", S3_BUCKET, S3_KEY_OMNI) + except Exception as s3_error: + logger.warning( + "S3 load failed (%s); falling back to %s", s3_error, file_path + ) + df = pd.read_csv(file_path, low_memory=False) + else: + df = pd.read_csv(file_path, low_memory=False) + return _normalise(df) + except FileNotFoundError: + st.error(f"Omni data file not found: {file_path}") + return None + except Exception as exc: + st.error(f"Error loading Omni data from {file_path}: {exc}") + return None + + +def _values(frame: pd.DataFrame, column: str) -> list: + if column not in frame.columns: + return [] + return sorted( + value + for value in frame[column].dropna().unique() + if str(value).strip() not in ("", "unknown", "nan", "None") + ) + + +def _multiselect( + label: str, options: list, key: str, param_key: Optional[str] = None +) -> list: + if not options: + return [] + if param_key: + return _persistent_multiselect(label, options, key, param_key) + return st.multiselect(label, options, default=options, key=key) + + +def _persistent_multiselect( + label: str, + options: list, + key: str, + param_key: Optional[str] = None, + help_text: Optional[str] = None, +) -> list: + if not options: + return [] + if param_key: + _seed_filter_state(key, options, param_key) + elif key not in st.session_state: + st.session_state[key] = options + current = st.session_state.get(key, []) + valid = [value for value in current if value in options] + if current and not valid: + valid = options + st.session_state[key] = valid + selected = st.multiselect(label, options, key=key, help=help_text) + if param_key: + _persist_filter(param_key, selected, options) + return selected + + +def _select_all_models_multiselect( + label: str, options: list, key: str, param_key: Optional[str] = None +) -> list: + if not options: + return [] + select_all_key = f"{key}_select_all" + if param_key: + _seed_filter_state(key, options, param_key) + elif key not in st.session_state: + st.session_state[key] = options + current = st.session_state.get(key, []) + valid = [model for model in current if model in options] + if current and not valid: + valid = options + st.session_state[key] = valid + if select_all_key not in st.session_state: + st.session_state[select_all_key] = set(st.session_state[key]) == set(options) + elif st.session_state.get(select_all_key): + st.session_state[key] = options + + def _sync_select_all(): + st.session_state[select_all_key] = set(st.session_state.get(key, [])) == set( + options + ) + + def _apply_select_all(): + if st.session_state.get(select_all_key): + st.session_state[key] = options + + selected = st.multiselect( + label, + options, + key=key, + on_change=_sync_select_all, + ) + if param_key: + _persist_filter(param_key, selected, options) + st.checkbox( + "Select All Models", + key=select_all_key, + on_change=_apply_select_all, + ) + return selected + + +def _selection_key(prefix: str, *groups) -> str: + signature = "|".join( + ",".join(str(value) for value in sorted(group)) for group in groups + ) + return f"{prefix}_{signature}" + + +def _main_filters(df: pd.DataFrame) -> pd.DataFrame: + """RHAIIS-style filter band in the main content.""" + st.subheader("Filter Your Data") + st.caption( + "Empty selections mean all. Changing an upstream filter resets " + "downstream selections so the chart reflects the new scope." + ) + + filter_col1, filter_col2, filter_col3, filter_col4, filter_col5 = st.columns( + [1.5, 1.8, 1.3, 2.7, 1] + ) + + with filter_col1: + accelerators = _persistent_multiselect( + "1️⃣ Select Accelerator(s)", + _values(df, "accelerator"), + "omni_accelerator", + "omni_accels", + ) + accelerator_sig = _selection_signature(accelerators) + filtered = df + if accelerators: + filtered = filtered[filtered["accelerator"].isin(accelerators)] + + task_values = sorted( + _values(filtered, "task_type"), + key=lambda task: ( + TASK_TYPE_ORDER.index(task) + if task in TASK_TYPE_ORDER + else len(TASK_TYPE_ORDER), + str(task), + ), + ) + task_options = [(task, _task_label(task)) for task in task_values] + task_labels = [label for _, label in task_options] + task_key = "omni_task" + _cascade_reset(task_key, "omni_tasks", accelerator_sig) + _seed_filter_state(task_key, task_labels, "omni_tasks") + current_tasks = st.session_state.get(task_key, []) + valid_tasks = [label for label in current_tasks if label in task_labels] + if current_tasks and not valid_tasks: + valid_tasks = task_labels + st.session_state[task_key] = valid_tasks + with filter_col2: + selected_task_labels = st.multiselect( + "2️⃣ Select Task(s)", + task_labels, + key=task_key, + help=TASK_HELP, + ) + _persist_filter("omni_tasks", selected_task_labels, task_labels) + task_sig = _selection_signature(selected_task_labels) + selected_tasks = [ + task for task, label in task_options if label in selected_task_labels + ] + if selected_tasks: + filtered = filtered[filtered["task_type"].isin(selected_tasks)] + + dataset_options = _values(filtered, "dataset_filter") + _cascade_reset( + "omni_dataset", + "omni_datasets", + (accelerator_sig, task_sig), + ) + datasets = _persistent_multiselect( + "3️⃣ Select Dataset(s)", + dataset_options, + "omni_dataset", + "omni_datasets", + help_text=DATASET_HELP, + ) + if datasets: + filtered = filtered[filtered["dataset_filter"].isin(datasets)] + dataset_sig = _selection_signature(datasets) + + with filter_col3: + _cascade_reset( + "omni_version", + "omni_versions", + (accelerator_sig, task_sig, dataset_sig), + ) + versions = _persistent_multiselect( + "4️⃣ Select Version(s)", + _values(filtered, "runtime_version"), + "omni_version", + "omni_versions", + ) + if versions: + filtered = filtered[filtered["runtime_version"].isin(versions)] + version_sig = _selection_signature(versions) + + with filter_col4: + _cascade_reset( + "omni_load_generator", + "omni_loadgens", + (accelerator_sig, task_sig, dataset_sig, version_sig), + ) + generators = _persistent_multiselect( + "5️⃣ Select Load Generator(s)", + _values(filtered, "load_generator"), + "omni_load_generator", + "omni_loadgens", + ) + if generators: + filtered = filtered[filtered["load_generator"].isin(generators)] + loadgen_sig = _selection_signature(generators) + model_options = _values(filtered, "model") + _cascade_reset( + "omni_model", + "omni_models", + (accelerator_sig, task_sig, dataset_sig, version_sig, loadgen_sig), + ) + models = _select_all_models_multiselect( + "6️⃣ Select Model(s)", + model_options, + "omni_model", + "omni_models", + ) + if models: + filtered = filtered[filtered["model"].isin(models)] + model_sig = _selection_signature(models) + + with filter_col5: + _cascade_reset( + "omni_tp", + "omni_tp_sizes", + ( + accelerator_sig, + task_sig, + dataset_sig, + version_sig, + loadgen_sig, + model_sig, + ), + ) + tps = _persistent_multiselect( + "7️⃣ Select TP Size(s)", + _values(filtered, "tp"), + "omni_tp", + "omni_tp_sizes", + ) + if tps: + filtered = filtered[filtered["tp"].isin(tps)] + + if filtered.empty: + st.warning( + "No rows match the current filters. Broaden a selection or clear a filter." + ) + return filtered + + +def _query_first(key: str) -> Optional[str]: + value = st.query_params.get(key) + if isinstance(value, list): + return value[0] if value else None + return value + + +def _url_filter_values(param_key: str) -> Optional[list]: + raw = _query_first(param_key) + if not raw: + return None + return [value for value in str(raw).split(",") if value] + + +def _seed_filter_state(key: str, options: list, param_key: str) -> None: + """Restore a widget selection from the URL on first render/refresh.""" + if key in st.session_state: + return + url_values = _url_filter_values(param_key) + if url_values: + valid = [value for value in url_values if value in options] + st.session_state[key] = valid or options + else: + st.session_state[key] = options + + +def _selection_signature(values: list) -> tuple: + return tuple(sorted(str(value) for value in values)) + + +def _cascade_reset(key: str, param_key: str, upstream_signature: tuple) -> None: + """Reset a child filter when an upstream selection changes. + + Empty selections still mean "all", so clearing a parent broadens the data. + Resetting the children makes that broadening visible instead of leaving a + stale child selection in place. + """ + state_key = f"{key}__cascade" + previous = st.session_state.get(state_key) + if previous is None: + st.session_state[state_key] = upstream_signature + return + if previous == upstream_signature: + return + st.session_state[state_key] = upstream_signature + st.session_state.pop(key, None) + st.session_state.pop(f"{key}_select_all", None) + if param_key in st.query_params: + del st.query_params[param_key] + + +def _persist_filter(param_key: str, values: list, options: list) -> None: + """Mirror a selection into the URL; omit the param when everything is selected.""" + selected = [str(value) for value in values] + option_values = [str(value) for value in options] + if not selected or set(selected) == set(option_values): + if param_key in st.query_params: + del st.query_params[param_key] + return + if _url_filter_values(param_key) != selected: + st.query_params[param_key] = ",".join(selected) + + +def _render_sidebar_nav() -> str: + """Render the same grouped navigation shell used by RHAIIS.""" + valid_sections = [ + section for _, sections in OMNI_NAV_GROUPS for section in sections + ] + if "omni_active_section" not in st.session_state: + requested = _query_first("section") + st.session_state.omni_active_section = ( + requested if requested in valid_sections else "🏠 Overview" + ) + with st.sidebar: + for group_name, sections in OMNI_NAV_GROUPS: + st.markdown( + f'', unsafe_allow_html=True + ) + for section in sections: + active = section == st.session_state.omni_active_section + if st.button( + section, + key=f"omni_nav_{section}", + use_container_width=True, + type="primary" if active else "secondary", + ): + st.session_state.omni_active_section = section + st.query_params["section"] = section + st.rerun() + st.query_params["section"] = st.session_state.omni_active_section + return st.session_state.omni_active_section + + +def _log_run_label(row: pd.Series) -> str: + parts = [ + str(row.get("run_name") or row.get("deployment_uuid") or "run"), + str(row.get("model") or ""), + str(row.get("runtime_version") or ""), + ] + concurrency = str(row.get("concurrency_label") or "") + if concurrency and concurrency not in ("nan", "n/a"): + parts.append(f"c={concurrency}") + return " | ".join(part for part in parts if part and part != "nan") + + +def _log_rank(path: str, concurrency: str) -> tuple: + name = Path(path).name.lower() + score = 0 + if "full" in name: + score += 100 + elif "server" in name: + score += 95 + elif "startup" in name: + score += 80 + elif "saturation" in name or "bench" in name or re.search(r"_c\d+(?:\D|$)", name): + score += 60 + if ( + concurrency not in ("", "nan", "n/a") + and f"saturation_c{concurrency}.log" in name + ): + score += 10 + return (-score, name) + + +@st.cache_data(ttl=300, show_spinner=False) +def _list_mlflow_logs(run_id: str, prefix: str, tracking_uri: str) -> list: + from mlflow.tracking import MlflowClient + + client = MlflowClient(tracking_uri=tracking_uri) + + def _walk(path: str): + for item in client.list_artifacts(run_id, path): + if item.is_dir: + yield from _walk(item.path) + elif item.path.endswith(".log"): + yield item.path + + return list(_walk(prefix)) + + +def _mlflow_log_candidates(row: pd.Series) -> tuple: + run_id = str(row.get("mlflow_run_id") or "").strip() + if not run_id or run_id.lower() == "nan": + return [], [] + if not MLFLOW_TRACKING_URI: + return [], [ + "MLflow is not configured; set MLFLOW_TRACKING_URI to load run artifacts." + ] + try: + paths = _list_mlflow_logs( + run_id, MLFLOW_LOG_ARTIFACT_PREFIX, MLFLOW_TRACKING_URI + ) + if not paths and MLFLOW_LOG_ARTIFACT_PREFIX: + paths = _list_mlflow_logs(run_id, "", MLFLOW_TRACKING_URI) + except Exception as exc: + return [], [f"MLflow: {exc}"] + return [ + { + "source": "mlflow", + "identifier": run_id, + "path": path, + } + for path in paths + ], [] + + +def _local_log_candidates(row: pd.Series) -> tuple: + if not OMNI_LOG_DIR: + return [], [] + root = Path(OMNI_LOG_DIR).expanduser() + if not root.is_dir(): + return [], [] + tokens = [] + for key in ("run_name", "mlflow_run_id", "deployment_uuid"): + value = str(row.get(key) or "").strip() + if not value or value.lower() == "nan": + continue + tokens.append(value) + if key == "mlflow_run_id" and len(value) >= 8: + tokens.append(value[:8]) + tokens = sorted(set(tokens)) + if not tokens: + return [], [] + + def _matches(path: Path) -> bool: + parts = path.parts + name = path.name + for token in tokens: + if token in parts: + return True + if re.search(rf"(? tuple: + uuid = str(row.get("deployment_uuid") or "").strip() + if not S3_LOGS_BUCKET or not uuid or uuid.lower() == "nan": + return [], [] + key = f"{S3_LOGS_PREFIX}{uuid}.log" + return [ + { + "source": "s3", + "identifier": uuid, + "path": key, + } + ], [] + + +def _log_candidates(row: pd.Series) -> tuple: + candidates = [] + errors = [] + for finder in (_mlflow_log_candidates, _local_log_candidates, _s3_log_candidates): + found, failure = finder(row) + candidates.extend(found) + errors.extend(failure) + concurrency = str(row.get("concurrency_label") or "") + candidates.sort(key=lambda item: _log_rank(item["path"], concurrency)) + return candidates, errors + + +def _fetch_log( + source: str, + identifier: str, + path: str, + tracking_uri: str = "", + s3_bucket: str = "", + s3_region: str = "us-east-1", +) -> str: + if source == "mlflow": + from mlflow.tracking import MlflowClient + + client = MlflowClient(tracking_uri=tracking_uri) + with tempfile.TemporaryDirectory() as tmp: + local = Path(client.download_artifacts(identifier, path, tmp)) + return local.read_text(encoding="utf-8", errors="replace") + + if source == "local": + return Path(path).read_text(encoding="utf-8", errors="replace") + + if source == "s3": + client = _s3_client(s3_region) + response = client.get_object(Bucket=s3_bucket, Key=path) + return response["Body"].read().decode("utf-8", errors="replace") + + raise ValueError(f"Unknown log source: {source}") + + +def _log_deployment_key(row: pd.Series) -> str: + """Group concurrency children under one deployment/configuration.""" + uuid = str(row.get("deployment_uuid") or "").strip() + if uuid and uuid.lower() not in ("nan", "none"): + return "uuid:" + uuid + return "config:" + "|".join( + str(row.get(key) or "").strip() + for key in ("model", "runtime_version", "recipe", "task_type", "dataset") + ) + + +def _log_deployment_label(row: pd.Series) -> str: + model = str(row.get("model") or "?").split("/")[-1] + parts = [ + model, + str(row.get("runtime_version") or "").strip(), + str(row.get("recipe") or "").strip(), + _task_label(row.get("task_type")), + str(row.get("dataset") or "").strip(), + ] + return " | ".join(part for part in parts if part and part not in ("nan", "unknown")) + + +def _prefer_log_candidates( + candidates: list, preferred_names: list, fallback: bool = True +) -> list: + """Prefer an exact artifact filename, then a delimited stem match.""" + for name in preferred_names: + exact = [c for c in candidates if Path(c["path"]).name == name] + if exact: + return exact + for name in preferred_names: + stem = Path(name).stem + pattern = re.compile(rf"(?:^|[_.-]){re.escape(stem)}(?:[_.-]|$)") + loose = [c for c in candidates if pattern.search(Path(c["path"]).name)] + if loose: + return loose + return candidates if fallback else [] + + +def _group_has_mlflow(group: pd.DataFrame) -> bool: + if "mlflow_run_id" not in group.columns: + return False + return group["mlflow_run_id"].fillna("").astype(str).str.strip().ne("").any() + + +def _group_is_matrix(group: pd.DataFrame) -> bool: + if "experiment_phase" not in group.columns: + return False + return ( + group["experiment_phase"].fillna("").astype(str).str.strip().eq("matrix").any() + ) + + +def _view_logs(df: pd.DataFrame): + st.subheader("📋 View Logs") + + if not MLFLOW_TRACKING_URI: + st.caption( + "MLflow is not configured; set MLFLOW_TRACKING_URI to load run artifacts." + ) + + if "run_name" not in df.columns: + st.info("No run_name column is available in the data.") + return + + logs_df = df.dropna(subset=["run_name"]).copy() + if logs_df.empty: + st.info("No runs with a run name are available in the current filters.") + return + + logs_df["_concurrency"] = pd.to_numeric(logs_df["concurrency"], errors="coerce") + logs_df["_deployment_key"] = logs_df.apply(_log_deployment_key, axis=1) + + grouped = [] + for key, group in logs_df.groupby("_deployment_key", sort=False): + group = group.sort_values("_concurrency") + grouped.append( + { + "key": key, + "label": _log_deployment_label(group.iloc[0]), + "group": group, + } + ) + label_counts = {} + for item in grouped: + label_counts[item["label"]] = label_counts.get(item["label"], 0) + 1 + for item in grouped: + if label_counts[item["label"]] > 1: + first = item["group"].iloc[0] + uuid = str(first.get("deployment_uuid") or "").strip() + suffix = ( + uuid[:8] + if uuid and uuid.lower() not in ("nan", "none") + else str(first.get("run_name") or "")[:24] + ) + item["label"] = f"{item['label']} | {suffix}" + grouped.sort( + key=lambda item: ( + 0 + if _group_has_mlflow(item["group"]) and _group_is_matrix(item["group"]) + else 1, + 0 if "qwen" in str(item["group"].iloc[0].get("model") or "").lower() else 1, + item["label"], + ) + ) + + options = [item["key"] for item in grouped] + labels = {item["key"]: item["label"] for item in grouped} + if st.session_state.get("omni_log_deployment") not in options: + st.session_state["omni_log_deployment"] = options[0] + selected_key = st.selectbox( + "Select a deployment:", + options, + format_func=lambda key: labels[key], + key="omni_log_deployment", + help="One entry per deployment/configuration. Server and bench logs are selected below.", + ) + item = next(item for item in grouped if item["key"] == selected_key) + group = item["group"] + label = item["label"] + + concurrency_values = sorted( + { + int(value) + for value in group["_concurrency"].dropna() + if float(value).is_integer() + } + ) + source_options = ["Server log (vLLM)"] + [ + f"Bench log — c{value}" for value in concurrency_values + ] + if st.session_state.get("omni_log_source") not in source_options: + st.session_state["omni_log_source"] = source_options[0] + source = st.radio( + "Log source:", + source_options, + horizontal=True, + key="omni_log_source", + help="The vLLM server log is per deployment; bench logs are per concurrency.", + ) + + errors = [] + candidates = [] + if source == "Server log (vLLM)": + rows_to_try = [] + c1 = group[group["_concurrency"] == 1] + if not c1.empty: + rows_to_try.append(c1.iloc[0]) + for _, candidate_row in group.iterrows(): + if c1.empty or candidate_row["run_name"] != c1.iloc[0]["run_name"]: + rows_to_try.append(candidate_row) + for candidate_row in rows_to_try: + row_candidates, row_errors = _log_candidates(candidate_row) + matches = [ + candidate + for candidate in row_candidates + if Path(candidate["path"]).name == "server.log" + ] + if matches: + candidates = matches + errors = row_errors + break + if row_candidates and not candidates: + candidates = row_candidates + errors = row_errors + candidates = _prefer_log_candidates(candidates, ["server.log"]) + if candidates and not any( + Path(candidate["path"]).name == "server.log" for candidate in candidates + ): + st.caption( + "Server log not found for this deployment; showing the available log instead." + ) + else: + concurrency_by_source = { + f"Bench log — c{value}": value for value in concurrency_values + } + concurrency = concurrency_by_source[source] + target_rows = group[group["_concurrency"] == concurrency] + if target_rows.empty: + st.warning(f"No run found for concurrency {concurrency}.") + return + row = target_rows.iloc[0] + candidates, errors = _log_candidates(row) + candidates = _prefer_log_candidates( + candidates, + [f"cell_c{concurrency}.log", f"saturation_c{concurrency}.log"], + fallback=False, + ) + if not candidates: + st.warning(f"No bench log found for c{concurrency}.") + return + + if not candidates: + st.warning("Log not available for this deployment.") + if errors: + st.caption(errors[0]) + return + + result_key = f"{selected_key}|{source}" + safe_key = re.sub(r"[^A-Za-z0-9_.-]+", "_", result_key)[:100] + if st.button("🔍 Fetch Log", type="primary", key=f"omni_fetch_log_{safe_key}"): + result = {"run": result_key, "content": None, "error": None} + for candidate in candidates: + try: + result["content"] = _fetch_log( + candidate["source"], + candidate["identifier"], + candidate["path"], + MLFLOW_TRACKING_URI, + S3_LOGS_BUCKET, + S3_REGION, + ) + result["error"] = None + break + except Exception as exc: + result["error"] = str(exc) + st.session_state["omni_log_result"] = result + + cached = st.session_state.get("omni_log_result") + if not cached or cached.get("run") != result_key: + return + + if cached.get("error"): + st.warning(f"Log not available for this deployment: {cached['error']}") + return + + content = cached.get("content") or "" + st.success(f"Log loaded for {label} — {source}") + display_content = content + if len(content) > MAX_LOG_DISPLAY_CHARS: + display_content = content[-MAX_LOG_DISPLAY_CHARS:] + st.caption( + f"Showing the last {MAX_LOG_DISPLAY_CHARS // 1_000_000} MB of " + f"{len(content) / 1_000_000:.1f} MB. Download the full log below." + ) + st.text_area( + "Log output", + value=display_content, + height=600, + disabled=True, + key=f"omni_log_full_{safe_key}", + ) + st.download_button( + "⬇️ Download Full Log", + data=content, + file_name=f"{safe_key}.log", + mime="text/plain", + key=f"omni_download_log_{safe_key}", + ) + + +def _overview(df: pd.DataFrame): + rows, models = len(df), df["model"].nunique() + col1, col2, col3, col4 = st.columns(4) + col1.metric("Benchmark rows", rows) + col2.metric("Models", models) + best_rps = df["request_throughput_rps"].max() + col3.metric( + "Best request throughput", + f"{best_rps:.2f} req/s" if pd.notna(best_rps) else "n/a", + ) + best_audio = df["audio_throughput_x"].max() + col4.metric( + "Best audio throughput", f"{best_audio:.2f}x" if pd.notna(best_audio) else "n/a" + ) + st.subheader("Coverage") + coverage = ( + df.groupby(["modality", "task_type", "load_generator"], dropna=False) + .agg(rows=("model", "size"), models=("model", "nunique")) + .reset_index() + .sort_values(["modality", "task_type"]) + ) + st.dataframe(coverage, use_container_width=True, hide_index=True) + + +def _performance_plots(df: pd.DataFrame): + st.subheader("📊 Performance Plots") + st.markdown( + "💡 **Tip:** Click on the full screen view (⛶) of the graph to get a detailed view." + ) + + mode_values = set() + if "benchmark_mode" in df.columns: + mode_values = { + str(value).strip().lower() + for value in df["benchmark_mode"].dropna().unique() + if str(value).strip() + } + mode_key = "omni_perf_streaming" + pref_key = "omni_perf_streaming_pref" + if pref_key not in st.session_state: + preferred_streaming = True + streaming_param = _query_first("omni_streaming") + if streaming_param in ("0", "false", "off"): + preferred_streaming = False + elif streaming_param in ("1", "true", "on"): + preferred_streaming = True + st.session_state[pref_key] = preferred_streaming + st.session_state[mode_key] = preferred_streaming + preferred_streaming = st.session_state.get(pref_key, True) + selected_mode, toggle_default = _resolve_benchmark_mode( + mode_values, preferred_streaming + ) + st.session_state[mode_key] = ( + toggle_default if selected_mode else preferred_streaming + ) + + x_label = "Concurrency" + x_axis = "concurrency" + metrics = _available_metrics(df) + if not metrics: + st.warning("No metrics with data are available for the current filters.") + return + format_values = set() + if "response_format" in df.columns: + format_values = { + str(value).strip().lower() + for value in df["response_format"].dropna().unique() + if str(value).strip() + } + format_options = ["all"] + [ + value + for value in ("wav", "pcm", "mp3", "flac", "opus") + if value in format_values + ] + format_key = "omni_perf_response_format" + format_param = _query_first("omni_response_format") + preferred_format = st.session_state.get(format_key, format_param or "all") + if preferred_format not in format_options: + preferred_format = "all" if "all" in format_options else format_options[0] + col1, col2, col3, col4, col5 = st.columns([1.5, 0.9, 0.8, 1.0, 1.0]) + with col1: + y_label = st.selectbox("Select Y-Axis", list(metrics), key="omni_perf_y_axis") + + def _remember_streaming_preference(): + if "streaming" in mode_values and "non_streaming" in mode_values: + st.session_state[pref_key] = st.session_state.get( + mode_key, preferred_streaming + ) + + with col3: + streaming_on = st.toggle( + "Streaming", + key=mode_key, + on_change=_remember_streaming_preference, + help="Show streaming results (on) or non-streaming results (off).", + ) + with col4: + response_format = st.selectbox( + "Response format", + format_options, + index=format_options.index(preferred_format), + format_func=lambda value: "All" if value == "all" else value.upper(), + key=format_key, + help=( + "WAV and PCM are only comparable at the same model/version, N, " + "concurrency, streaming mode, and 24 kHz sample rate. WAV is PCM " + "plus a header; format handling can add overhead." + ), + ) + with col5: + include_legacy = st.toggle( + "Include 3.5 legacy (N=100)", + value=False, + key="omni_perf_include_legacy", + help="3.5 legacy runs used N=100; the 3.6 matrix uses N=1000.", + ) + if response_format != "all": + if _query_first("omni_response_format") != response_format: + st.query_params["omni_response_format"] = response_format + elif "omni_response_format" in st.query_params: + del st.query_params["omni_response_format"] + if "streaming" in mode_values and "non_streaming" in mode_values: + desired_param = "1" if streaming_on else "0" + if _query_first("omni_streaming") != desired_param: + st.query_params["omni_streaming"] = desired_param + elif "omni_streaming" in st.query_params: + del st.query_params["omni_streaming"] + y_axis = metrics[y_label] + + sub = df.dropna(subset=[x_axis, y_axis]).copy() + if not include_legacy and "experiment_phase" in sub.columns: + sub = sub[sub["experiment_phase"] != "legacy"].copy() + if "experiment_phase" in sub.columns: + # CI smoke runs are one-off c1 validation points, not comparison data. + sub = sub[sub["experiment_phase"] != "ci"].copy() + if mode_values: + active_mode = "streaming" if streaming_on else "non_streaming" + if active_mode not in mode_values: + active_mode, _ = _resolve_benchmark_mode(mode_values, streaming_on) + if active_mode: + sub = sub[ + sub["benchmark_mode"].astype(str).str.lower() == active_mode + ].copy() + if response_format != "all" and "response_format" in sub.columns: + sub = sub[ + sub["response_format"].astype(str).str.lower() == response_format + ].copy() + if x_axis == "concurrency": + sub["concurrency"] = pd.to_numeric(sub["concurrency"], errors="coerce") + sub = sub.dropna(subset=["concurrency"]) + concurrency_values = sorted( + {float(value) for value in sub["concurrency"].dropna()} + ) + if concurrency_values: + with col2: + if ( + "omni_perf_max_concurrency" in st.session_state + and st.session_state["omni_perf_max_concurrency"] + not in concurrency_values + ): + st.session_state.pop("omni_perf_max_concurrency") + max_conc = st.selectbox( + "Show concurrency up to", + concurrency_values, + index=len(concurrency_values) - 1, + key="omni_perf_max_concurrency", + format_func=lambda value: ( + str(int(value)) if float(value).is_integer() else str(value) + ), + ) + sub = sub[sub["concurrency"] <= max_conc] + + st.caption( + "N = measured requests per benchmark point (warmups and the 500-request " + "burn-in excluded). 3.5 legacy: N=100; 3.6 Athena matrix: N=1000; " + "3.6 base: N=10 (CI) and N=100/128/256 (saturation). " + "Hover a point for its N, or select 'Requests sent (N)' as the Y-axis." + ) + if "wav" in format_values and "pcm" in format_values: + st.caption( + "Comparing WAV vs PCM: match model/version, N, concurrency, streaming " + "mode, and 24 kHz sample rate. WAV is PCM plus a header, but format " + "handling can add overhead; report RTF and audio throughput alongside req/s." + ) + + if sub.empty: + st.info(f"No data available for '{y_label}' with these filters.") + return + + if "underrun" in str(y_axis).lower() and "model" in sub.columns: + models_in_view = sub["model"].dropna().astype(str).str.lower() + if models_in_view.str.contains("omnivoice").any(): + st.warning( + "**OmniVoice underrun is 0 by construction — not a streaming win.** " + "OmniVoice is a single-stage diffusion model that emits the whole " + "waveform in one audio chunk. Underrun measures gaps between " + "streamed chunks, so a single-chunk response can never register a " + "deficit, even when RTF > 1. This is expected behavior, not " + "missing or incorrect data. For OmniVoice, read TTFP ≈ E2EL (no " + "incremental audio) instead; underrun is meaningful only for " + "incrementally streaming two-stage models like Qwen3-TTS." + ) + + # One trace per deployment. Configurations share a color; a non-default + # profile is dashed, and repeated deployments are dotted/dash-dot with + # CI repeats faded, matching the RHAIIS duplicate-run treatment. + sub["model_short"] = sub["model"].astype(str).str.split("/").str[-1] + sub["version"] = sub["runtime_version"] + sub["TP"] = pd.to_numeric(sub["tp"], errors="coerce") + sub["uuid"] = sub["deployment_uuid"].fillna("").astype(str).str.strip() + sub["run_identifier"] = ( + sub["accelerator"].fillna("?").astype(str) + + " | " + + sub["model_short"] + + " | " + + sub["recipe"].fillna("?").astype(str) + + " | " + + sub["runtime_version"].fillna("?").astype(str) + + " | " + + sub["task_type"].fillna("?").astype(str) + + " | " + + sub["dataset"].fillna("?").astype(str) + + " | " + + sub["response_format"].fillna("").astype(str).str.lower() + ) + sub["runtime_args"] = sub["runtime_args"].fillna("").astype(str) + sub["task_label"] = sub["task_type"].map(_task_label) + sub["deployment_uuid_hover"] = sub["deployment_uuid"].fillna("").astype(str) + sub["runtime_args_hover"] = sub["runtime_args"].str.replace( + "; ", "
", regex=False + ) + sub["response_format_label"] = ( + sub["response_format"].fillna("").astype(str).str.upper() + ) + sub = add_trace_metadata( + sub, + series_column="run_identifier", + legend_options={ + "include_accelerator": True, + "include_model": True, + "include_profile": True, + "include_label": False, + "include_tp": True, + "include_dp": False, + }, + ) + is_non_default_recipe = ( + sub["recipe"].fillna("").astype(str).str.lower().ne("default") + ) + sub.loc[is_non_default_recipe & sub["line_style"].eq("solid"), "line_style"] = ( + "dash" + ) + sub.loc[is_non_default_recipe & sub["line_style"].eq("dot"), "line_style"] = ( + "dashdot" + ) + repeated = sub["line_style"].isin(["dot", "dashdot"]) & sub["uuid"].ne("") + sub.loc[repeated, "line_opacity"] = 1.0 + sub["legend_label"] = sub.apply(_omni_legend_label, axis=1) + + default_color_map = deterministic_color_map(sub["run_identifier"]) + default_shape_map = dict.fromkeys(sorted(sub["run_identifier"].unique()), "circle") + custom_colors = dict(st.session_state.get("omni_perf_custom_colors", {})) + custom_shapes = { + key: value + for key, value in st.session_state.get("omni_perf_custom_shapes", {}).items() + if value in MARKER_SYMBOLS + } + customizable_series = sorted(sub["run_identifier"].unique()) + + fig = px.line( + sub.sort_values([x_axis, "trace_label"]), + x=x_axis, + y=y_axis, + color="trace_label", + markers=True, + title=f"{y_label} vs {x_label}", + labels={x_axis: x_label, y_axis: y_label, "trace_label": "Run"}, + custom_data=PLOT_CUSTOM_DATA, + template="plotly_white_light", + category_orders={"trace_label": sub["trace_label"].unique().tolist()}, + ) + for trace in fig.data: + trace_rows = sub[sub["trace_label"] == trace.name] + if trace_rows.empty: + continue + first = trace_rows.iloc[0] + color = custom_colors.get( + first["run_identifier"], default_color_map[first["run_identifier"]] + ) + trace.meta = first["trace_label"] + trace.name = first["legend_label"] + trace.line.color = color + trace.line.dash = first["line_style"] + trace.line.width = 2 + trace.marker.size = 10 + trace.marker.symbol = custom_shapes.get( + first["run_identifier"], default_shape_map[first["run_identifier"]] + ) + trace.marker.color = color + trace.marker.line = {"width": 1, "color": "white"} + trace.opacity = float(first["line_opacity"]) + trace.legendgroup = first["run_identifier"] + format_line = ( + "Format: %{customdata[9]}
" if first.get("response_format") else "" + ) + uuid_line = ( + "UUID: %{customdata[7]}
" if first.get("deployment_uuid_hover") else "" + ) + runtime_line = ( + "Runtime args:
%{customdata[8]}
" if first.get("runtime_args") else "" + ) + trace.hovertemplate = ( + f"{x_label}: %{{x}}
" + f"{y_label}: %{{y}}
" + "Accelerator: %{customdata[0]}
" + "Model: %{customdata[1]}
" + "Version: %{customdata[2]}
" + "Task: %{customdata[3]}
" + "Dataset: %{customdata[4]}
" + "Requests: %{customdata[6]}
" + + format_line + + uuid_line + + runtime_line + + "" + ) + fig.update_layout( + hovermode="closest", + hoverdistance=60, + legend_title_text=( + "Run Details (Accelerator | Model | Version | Task | Dataset | TP)" + ), + legend={"font": {"size": 12}, "itemwidth": 42}, + height=560, + margin={"l": 80, "r": 320, "t": 110, "b": 60}, + title={ + "font": {"size": 18}, + "x": 0.02, + "xanchor": "left", + "y": 0.94, + "yanchor": "top", + }, + ) + concurrency_ticks = sorted( + { + int(value) + for value in sub["concurrency"].dropna().unique() + if float(value).is_integer() + } + ) + if concurrency_ticks: + fig.update_xaxes( + type="log", + tickmode="array", + tickvals=concurrency_ticks, + ticktext=[str(value) for value in concurrency_ticks], + title_text="Concurrency (log scale)", + ) + + def _merge_plot_selection(): + points = st.session_state["omni_perf_chart"]["selection"]["points"] + merged = set(st.session_state.get("omni_perf_lines", [])) + for point in points or []: + curve = ( + point.get("curve_number", point.get("curveNumber")) + if isinstance(point, dict) + else None + ) + if curve is not None and 0 <= curve < len(fig.data): + merged.add(fig.data[curve].meta or fig.data[curve].name) + st.session_state["omni_perf_lines"] = sorted(merged) + + def _clear_comparison(): + st.session_state["omni_perf_lines"] = [] + + st.plotly_chart( + fig, + use_container_width=True, + theme=None, + key="omni_perf_chart", + on_select=_merge_plot_selection, + selection_mode=("points", "box", "lasso"), + ) + st.caption( + "Click points, or box/lasso-select an area, to add lines to the comparison. " + "Dashed = non-default configuration; dotted/dash-dot = repeated deployment; " + "faded dots = exact repeats. You can also choose lines below." + ) + + trace_labels = ( + sub.drop_duplicates("trace_label") + .set_index("trace_label")["legend_label"] + .to_dict() + ) + series_options = sorted(sub["trace_label"].unique()) + if "omni_perf_lines" in st.session_state: + st.session_state["omni_perf_lines"] = [ + line + for line in st.session_state["omni_perf_lines"] + if line in series_options + ] + selected_lines = st.multiselect( + "Plot lines to compare", + series_options, + key="omni_perf_lines", + format_func=lambda key: trace_labels.get(key, key), + ) + + st.subheader("📄 Filtered Data for Plot Lines") + st.caption("The table shows the source rows for the selected plot lines.") + if selected_lines: + selected_view = _blank_nan( + _display_frame(sub[sub["trace_label"].isin(selected_lines)]) + ) + st.dataframe( + selected_view, + use_container_width=True, + hide_index=True, + column_config=_link_column_config(selected_view), + ) + if st.button( + "Clear comparison", key="omni_perf_clear", on_click=_clear_comparison + ): + pass + else: + st.caption("No plot lines selected.") + + if customizable_series: + with st.expander("🎨 Customize", expanded=False): + st.caption( + "Choose a color and marker shape for a configuration. Repeated " + "deployments keep dotted (or dash-dot) lines." + ) + series_labels = { + key: sub.loc[sub["run_identifier"] == key, "legend_label"] + .iloc[0] + .split(" | run ", 1)[0] + for key in customizable_series + } + selected_series = st.selectbox( + "Configuration", + customizable_series, + format_func=lambda key: series_labels[key], + key="omni_perf_customize_series", + ) + color_key = ( + "omni_perf_color_" + + hashlib.sha1( + selected_series.encode(), usedforsecurity=False + ).hexdigest()[:10] + ) + shape_key = ( + "omni_perf_shape_" + + hashlib.sha1( + selected_series.encode(), usedforsecurity=False + ).hexdigest()[:10] + ) + + def _save_custom_color(series=selected_series, key=color_key): + updated = dict(st.session_state.get("omni_perf_custom_colors", {})) + updated[series] = st.session_state[key] + st.session_state["omni_perf_custom_colors"] = updated + + def _save_custom_shape(series=selected_series, key=shape_key): + updated = dict(st.session_state.get("omni_perf_custom_shapes", {})) + updated[series] = st.session_state[key] + st.session_state["omni_perf_custom_shapes"] = updated + + st.color_picker( + "Line color", + custom_colors.get(selected_series, default_color_map[selected_series]), + key=color_key, + on_change=_save_custom_color, + ) + current_shape = custom_shapes.get(selected_series, "circle") + st.selectbox( + "Marker shape", + MARKER_SYMBOLS, + index=( + MARKER_SYMBOLS.index(current_shape) + if current_shape in MARKER_SYMBOLS + else 0 + ), + key=shape_key, + on_change=_save_custom_shape, + ) + + +def _concurrency_sort(value: str) -> tuple: + try: + return (0, float(value)) + except (TypeError, ValueError): + return (1, str(value)) + + +def _natural_key(value: str) -> list: + return [ + (0, int(part)) if part.isdigit() else (1, part.lower()) + for part in re.split(r"(\d+)", str(value)) + ] + + +def _version_order(df: pd.DataFrame) -> list: + versions = _values(df, "runtime_version") + if "timestamp_utc" in df.columns and versions: + timestamps = pd.to_datetime(df["timestamp_utc"], errors="coerce", utc=True) + if timestamps.notna().any(): + latest = ( + df.assign(_ts=timestamps) + .dropna(subset=["_ts"]) + .groupby("runtime_version")["_ts"] + .max() + .sort_values(kind="stable") + ) + ordered = [version for version in latest.index if version in versions] + ordered.extend(version for version in versions if version not in ordered) + return ordered + return sorted(versions, key=_natural_key) + + +def _common_prefix_length(left: str, right: str) -> int: + length = 0 + for left_char, right_char in zip(str(left), str(right)): + if left_char != right_char: + break + length += 1 + return length + + +def _compare_defaults(versions: list) -> tuple: + candidate = versions[-1] + baseline = max( + versions[:-1], + key=lambda version: ( + _common_prefix_length(version, candidate), + versions.index(version), + ), + ) + return baseline, candidate + + +def _comparison_keys(base_df: pd.DataFrame, comparison_df: pd.DataFrame) -> list: + """Return workload keys that can safely distinguish version comparisons. + + A key is included when either side has populated values. If both sides are + entirely blank, the key carries no signal and is skipped. Rows missing an + included key are excluded from the comparison rather than matched to a + known workload. + """ + keys = [] + for key in COMPARE_KEYS: + if key not in base_df.columns or key not in comparison_df.columns: + continue + + def _has_values(frame: pd.DataFrame, key: str = key) -> bool: + values = frame[key].dropna().astype(str).str.strip().str.lower() + return bool(values[~values.isin(["", "nan", "none", "n/a"])].any()) + + if _has_values(base_df) or _has_values(comparison_df): + keys.append(key) + return keys + + +def _comparison_table( + base_df: pd.DataFrame, + comparison_df: pd.DataFrame, + metric: str, + direction: str, +) -> pd.DataFrame: + if "task_type" not in base_df.columns or "task_type" not in comparison_df.columns: + return _comparison_table_for_task( + base_df, + comparison_df, + metric, + direction, + _comparison_keys(base_df, comparison_df), + ) + + tasks = sorted( + set(base_df["task_type"].dropna()) | set(comparison_df["task_type"].dropna()) + ) + frames = [] + for task in tasks: + task_base = base_df[base_df["task_type"] == task] + task_comparison = comparison_df[comparison_df["task_type"] == task] + if task_base.empty or task_comparison.empty: + continue + detail = _comparison_table_for_task( + task_base, + task_comparison, + metric, + direction, + _comparison_keys(task_base, task_comparison), + ) + if not detail.empty: + frames.append(detail) + if not frames: + return pd.DataFrame() + return pd.concat(frames, ignore_index=True) + + +def _comparison_table_for_task( + base_df: pd.DataFrame, + comparison_df: pd.DataFrame, + metric: str, + direction: str, + keys: list, +) -> pd.DataFrame: + base = base_df.dropna(subset=[metric]).copy() + comparison = comparison_df.dropna(subset=[metric]).copy() + if base.empty or comparison.empty: + return pd.DataFrame() + + def _prepare(frame: pd.DataFrame) -> pd.DataFrame: + prepared = frame[keys + [metric]].copy() + for key in keys: + prepared[key] = _normalize_key(prepared[key]) + if keys: + prepared = prepared[~prepared[keys].eq("n/a").any(axis=1)] + if prepared.empty: + return prepared + prepared["_key"] = prepared[keys].astype(str).agg(" | ".join, axis=1) + return prepared + + def _normalize_key(series: pd.Series) -> pd.Series: + def _one(value) -> str: + try: + if pd.isna(value): + return "n/a" + except (TypeError, ValueError): + pass + text = str(value).strip() + if text.lower() in ("", "nan", "none", "n/a", ""): + return "n/a" + try: + numeric = float(text) + except (TypeError, ValueError): + return text + return str(int(numeric)) if numeric.is_integer() else text + + return series.map(_one) + + base_prepared = _prepare(base) + comparison_prepared = _prepare(comparison) + if base_prepared.empty or comparison_prepared.empty: + return pd.DataFrame() + aggregations = {metric: "mean", **dict.fromkeys(keys, "first")} + base_grouped = base_prepared.groupby("_key", as_index=False).agg(aggregations) + comparison_grouped = comparison_prepared.groupby("_key", as_index=False).agg( + aggregations + ) + merged = base_grouped.merge( + comparison_grouped, on="_key", suffixes=("_baseline", "_comparison") + ) + merged["baseline"] = merged.pop(f"{metric}_baseline") + merged["comparison"] = merged.pop(f"{metric}_comparison") + for key in keys: + merged[key] = merged.pop(f"{key}_baseline") + comparison_column = f"{key}_comparison" + if comparison_column in merged.columns: + merged.pop(comparison_column) + merged = merged.dropna(subset=["baseline", "comparison"]) + + denominator = merged["baseline"].abs() + merged["delta_pct"] = np.where( + denominator > 0, + (merged["comparison"] - merged["baseline"]) / denominator * 100, + np.nan, + ) + + def _verdict(delta): + if pd.isna(delta): + return "n/a" + if abs(delta) < COMPARE_FLAT_THRESHOLD_PCT: + return "Flat" + if direction == "higher": + return "Better" if delta > 0 else "Worse" + return "Better" if delta < 0 else "Worse" + + merged["verdict"] = merged["delta_pct"].apply(_verdict) + concurrency_label = ( + merged["concurrency_label"].astype(str) + if "concurrency_label" in merged.columns + else pd.Series("n/a", index=merged.index) + ) + merged["label"] = ( + merged["model"].astype(str).str.split("/").str[-1] + + " | " + + merged["task_type"].astype(str) + + " | c=" + + concurrency_label + ) + if "load_generator" in merged.columns and merged["load_generator"].nunique() > 1: + merged["label"] += " | " + merged["load_generator"].astype(str) + if "concurrency_label" in merged.columns: + merged["_concurrency_sort"] = pd.to_numeric( + merged["concurrency_label"], errors="coerce" + ).fillna(9999) + else: + merged["_concurrency_sort"] = 9999 + sort_columns = ["model", "task_type", "_concurrency_sort"] + if "load_generator" in merged.columns: + sort_columns.append("load_generator") + merged = merged.sort_values(sort_columns).drop(columns=["_concurrency_sort"]) + return merged + + +def _family_statistics( + family: str, base_df: pd.DataFrame, comparison_df: pd.DataFrame +) -> list: + config = COMPARE_METRIC_FAMILIES[family] + if "columns" not in config: + return [] + return [ + statistic + for statistic in COMPARE_STATISTICS + if ( + config["columns"].get(statistic) + and base_df[config["columns"][statistic]].notna().any() + and comparison_df[config["columns"][statistic]].notna().any() + ) + ] + + +def _summary_statistics(base_df: pd.DataFrame, comparison_df: pd.DataFrame) -> list: + statistics = [] + for statistic in COMPARE_STATISTICS: + for family in COMPARE_SUMMARY_FAMILIES: + config = COMPARE_METRIC_FAMILIES[family] + if "columns" not in config: + continue + column = config["columns"].get(statistic) + if ( + column + and base_df[column].notna().any() + and comparison_df[column].notna().any() + ): + statistics.append(statistic) + break + return statistics + + +def _default_compare_statistic( + base_df: pd.DataFrame, + comparison_df: pd.DataFrame, + statistics: list, +) -> Optional[str]: + if not statistics: + return None + tasks = set(base_df["task_type"].dropna().astype(str)) + if tasks & {"voice_clone", "default_voice", "voice_design"}: + family = "Audio RTF" + elif tasks and tasks <= {"text_to_text"}: + family = "TTFT" + else: + family = None + if family: + available = _family_statistics(family, base_df, comparison_df) + if "P95" in available: + return "P95" + if "Mean" in available: + return "Mean" + if available: + return available[0] + if "P95" in statistics: + return "P95" + if "Mean" in statistics: + return "Mean" + return statistics[0] + + +def _aggregate_delta(detail: pd.DataFrame) -> float: + deltas = detail["delta_pct"].dropna() / 100.0 + if deltas.empty: + return np.nan + factors = 1 + deltas + if (factors > 0).all(): + return (float(np.prod(factors)) ** (1 / len(factors)) - 1) * 100 + return float(deltas.mean() * 100) + + +def _model_comparison_summary( + base_df: pd.DataFrame, + comparison_df: pd.DataFrame, + statistic: Optional[str], +) -> pd.DataFrame: + core_group_keys = [ + "model", + "task_type", + "load_generator", + "tp", + "accelerator", + "recipe", + ] + metric_columns = [] + for family in COMPARE_SUMMARY_FAMILIES: + config = COMPARE_METRIC_FAMILIES[family] + if "columns" in config: + column = config["columns"].get(statistic) + if ( + not column + or not base_df[column].notna().any() + or not comparison_df[column].notna().any() + ): + continue + header = f"{config['short']} {statistic}" + else: + column = config["column"] + if ( + not base_df[column].notna().any() + or not comparison_df[column].notna().any() + ): + continue + header = config["short"] + metric_columns.append((header, column, config["direction"])) + if not metric_columns: + return pd.DataFrame() + + groups = {} + cells = {} + for header, column, direction in metric_columns: + detail = _comparison_table(base_df, comparison_df, column, direction) + if detail.empty: + continue + group_keys = [key for key in core_group_keys if key in detail.columns] + detail["_group"] = ( + detail[group_keys].agg(" | ".join, axis=1) if group_keys else "all" + ) + for group, subset in detail.groupby("_group", sort=False): + if group not in groups: + meta = subset.iloc[0] + groups[group] = {key: meta[key] for key in group_keys} + delta = _aggregate_delta(subset) + if pd.isna(delta): + cells[(group, header)] = "⚪ N/A" + elif abs(delta) < COMPARE_FLAT_THRESHOLD_PCT: + cells[(group, header)] = f"🟡 {delta:+.1f}%" + elif (direction == "higher" and delta > 0) or ( + direction == "lower" and delta < 0 + ): + cells[(group, header)] = f"🟢 {delta:+.1f}%" + else: + cells[(group, header)] = f"🔴 {delta:+.1f}%" + + rows = [] + for group, meta in groups.items(): + model = str(meta.get("model", "")).split("/")[-1] + tp = str(meta.get("tp", "")).strip() + if tp and tp != "n/a": + model += f" (TP={tp})" + row = {"Model": model} + if "task_type" in meta: + row["Task"] = _task_label(meta["task_type"]) + if "load_generator" in meta: + row["Load generator"] = meta["load_generator"] + if "accelerator" in meta: + row["GPU"] = meta["accelerator"] + if "recipe" in meta: + row["Recipe"] = meta["recipe"] + for header, _, _ in metric_columns: + row[header] = cells.get((group, header), "⚪ N/A") + rows.append(row) + + summary = pd.DataFrame(rows) + for column in ("Load generator", "GPU"): + if column in summary.columns and summary[column].nunique(dropna=False) <= 1: + summary = summary.drop(columns=[column]) + return summary + + +def _compare_versions(df: pd.DataFrame): + st.subheader("⚖️ Compare Versions") + st.markdown( + "💡 **Compare the same model, task, dataset, and concurrency across two runtime versions.**" + ) + + versions = _version_order(df) + if len(versions) < 2: + st.warning("Need at least two runtime versions in the data to compare.") + return + + default_baseline, default_candidate = _compare_defaults(versions) + if not st.session_state.get("omni_compare_url_loaded"): + st.session_state.omni_compare_url_pending = { + "baseline": _query_first("cv_base"), + "candidate": _query_first("cv_comp"), + "tasks": _query_first("cv_tasks"), + "loadgen": _query_first("cv_loadgen"), + "models": _query_first("cv_models"), + "stat": _query_first("cv_stat"), + } + st.session_state.omni_compare_url_loaded = True + pending = st.session_state.get("omni_compare_url_pending", {}) + if pending.get("baseline") in versions: + st.session_state["omni_compare_baseline"] = pending["baseline"] + if pending.get("candidate") in versions: + st.session_state["omni_compare_candidate"] = pending["candidate"] + for key in ("omni_compare_baseline", "omni_compare_candidate"): + if st.session_state.get(key) not in versions: + st.session_state.pop(key, None) + st.session_state.setdefault("omni_compare_baseline", default_baseline) + st.session_state.setdefault("omni_compare_candidate", default_candidate) + + col1, swap_col, col2 = st.columns([4, 0.5, 4]) + with col1: + baseline = st.selectbox( + "Select Version 1 (Baseline)", + versions, + key="omni_compare_baseline", + ) + + def _swap_versions(): + baseline_value = st.session_state.get("omni_compare_baseline") + candidate_value = st.session_state.get("omni_compare_candidate") + st.session_state["omni_compare_baseline"] = candidate_value + st.session_state["omni_compare_candidate"] = baseline_value + + with swap_col: + st.markdown("
", unsafe_allow_html=True) + st.button( + "⇄", + key="omni_compare_swap", + help="Swap versions", + on_click=_swap_versions, + ) + with col2: + candidate = st.selectbox( + "Select Version 2 (Comparison)", + versions, + key="omni_compare_candidate", + ) + + if baseline == candidate: + st.warning("Select two different versions to compare.") + return + + base_all = df[df["runtime_version"] == baseline].copy() + comparison_all = df[df["runtime_version"] == candidate].copy() + + common_tasks = sorted( + set(base_all["task_type"].dropna()) & set(comparison_all["task_type"].dropna()), + key=lambda task: ( + TASK_TYPE_ORDER.index(task) + if task in TASK_TYPE_ORDER + else len(TASK_TYPE_ORDER), + str(task), + ), + ) + if not common_tasks: + st.warning(f"No common tasks found between {baseline} and {candidate}.") + return + task_options = [(task, _task_label(task)) for task in common_tasks] + task_labels = [label for _, label in task_options] + task_key = _selection_key("omni_compare_tasks", baseline, candidate) + if task_key in st.session_state: + st.session_state[task_key] = [ + label for label in st.session_state[task_key] if label in task_labels + ] + pending_tasks = [ + task for task in (pending.get("tasks") or "").split(",") if task in common_tasks + ] + pending_task_labels = [_task_label(task) for task in pending_tasks] + if pending_task_labels and task_key not in st.session_state: + st.session_state[task_key] = pending_task_labels + + col_task, col_loadgen, col_models, col_stat = st.columns([2, 2, 2, 1.3]) + with col_task: + selected_task_labels = st.multiselect( + "Tasks", + task_labels, + default=task_labels, + key=task_key, + help=TASK_HELP, + ) + if not selected_task_labels: + st.info("Select at least one task type.") + return + selected_tasks = [ + task for task, label in task_options if label in selected_task_labels + ] + + base_tasks = base_all[base_all["task_type"].isin(selected_tasks)] + comparison_tasks = comparison_all[comparison_all["task_type"].isin(selected_tasks)] + + def _load_generators(frame: pd.DataFrame) -> set: + values = frame["load_generator"].dropna().astype(str).str.strip() + return set(values[~values.str.lower().isin(["", "nan", "none", "unknown"])]) + + load_generators = sorted( + _load_generators(base_tasks) & _load_generators(comparison_tasks), + key=lambda value: (value == "offline", str(value)), + ) + if not load_generators: + st.warning("No common load generators found for the selected tasks.") + return + tts_tasks = {"voice_clone", "default_voice", "voice_design"} + if "vllm-omni-bench-serve" in load_generators and tts_tasks & set(selected_tasks): + preferred_load_generator = "vllm-omni-bench-serve" + elif "guidellm" in load_generators: + preferred_load_generator = "guidellm" + else: + preferred_load_generator = load_generators[0] + loadgen_key = _selection_key( + "omni_compare_loadgen", baseline, candidate, selected_tasks + ) + if st.session_state.get(loadgen_key) not in load_generators: + st.session_state.pop(loadgen_key, None) + if ( + pending.get("loadgen") in load_generators + and loadgen_key not in st.session_state + ): + st.session_state[loadgen_key] = pending["loadgen"] + with col_loadgen: + load_generator = st.selectbox( + "Load generator", + load_generators, + index=load_generators.index(preferred_load_generator), + key=loadgen_key, + help=( + "Only one load generator is compared at a time. GuideLLM, " + "vLLM-Omni bench serve, and offline results are never mixed." + ), + ) + + base_load = base_tasks[base_tasks["load_generator"] == load_generator] + comparison_load = comparison_tasks[ + comparison_tasks["load_generator"] == load_generator + ] + common_models = sorted( + set(base_load["model"].dropna()) & set(comparison_load["model"].dropna()) + ) + if not common_models: + st.warning( + f"No common models found between {baseline} and {candidate} for " + f"the selected tasks and {load_generator}." + ) + return + + model_key = _selection_key( + "omni_compare_models", + baseline, + candidate, + selected_tasks, + [load_generator], + ) + if model_key in st.session_state: + st.session_state[model_key] = [ + model for model in st.session_state[model_key] if model in common_models + ] + pending_models = [ + model + for model in (pending.get("models") or "").split(",") + if model in common_models + ] + if pending_models and model_key not in st.session_state: + st.session_state[model_key] = pending_models + + with col_models: + models = _select_all_models_multiselect( + "Models", + common_models, + model_key, + ) + if not models: + st.info("Select at least one model.") + return + + base = base_load[base_load["model"].isin(models)] + comparison = comparison_load[comparison_load["model"].isin(models)] + + summary_statistics = _summary_statistics(base, comparison) + statistic = None + if summary_statistics: + preferred_statistic = _default_compare_statistic( + base, comparison, summary_statistics + ) + stat_key = _selection_key( + "omni_compare_stat", + baseline, + candidate, + selected_tasks, + models, + [load_generator], + ) + if st.session_state.get(stat_key) not in summary_statistics: + st.session_state.pop(stat_key, None) + if ( + pending.get("stat") in summary_statistics + and stat_key not in st.session_state + ): + st.session_state[stat_key] = pending["stat"] + with col_stat: + statistic = st.selectbox( + "Statistic", + summary_statistics, + index=summary_statistics.index(preferred_statistic), + key=stat_key, + help=( + "Mean, Median, P95, or P99 where available. Throughput, " + "WER, RTFx, and transcription throughput are single values." + ), + ) + else: + with col_stat: + st.caption("Statistic: single value") + st.session_state.pop("omni_compare_url_pending", None) + + base_concurrency = set(base["concurrency_label"].dropna().astype(str)) + comparison_concurrency = set(comparison["concurrency_label"].dropna().astype(str)) + common_concurrency = sorted( + base_concurrency & comparison_concurrency, key=_concurrency_sort + ) + if not common_concurrency: + st.warning("No common concurrency levels found for both versions.") + return + st.caption("Using all common concurrency levels: " + ", ".join(common_concurrency)) + base = base[base["concurrency_label"].astype(str).isin(common_concurrency)] + comparison = comparison[ + comparison["concurrency_label"].astype(str).isin(common_concurrency) + ] + + context_parts = [] + for key, label in ( + ("accelerator", "GPU"), + ("task_type", "Task"), + ("dataset", "Dataset"), + ("load_generator", "Load gen"), + ): + if key in base.columns and key in comparison.columns: + raw_values = pd.concat([base[key], comparison[key]]).astype(str).str.strip() + normalized = raw_values.str.lower() + if normalized.isin(["", "nan", "none", "n/a"]).any(): + continue + if raw_values.nunique() == 1: + value = raw_values.iloc[0] + context_parts.append( + f"{label}: {_task_label(value) if key == 'task_type' else value}" + ) + + title_col, popover_col = st.columns([5, 1]) + with title_col: + st.markdown( + "### " + + (" | ".join(context_parts) if context_parts else "Version comparison") + ) + with popover_col: + with st.popover("ℹ️ How are these calculated?"): + st.markdown( + "**Matching:** rows are matched on model, task, concurrency, load " + "generator, TP, accelerator, and dataset when both versions provide it.\n\n" + "**Delta:** percent change of the comparison version relative to the " + "baseline.\n\n" + "**Summary:** each cell is the geometric mean of the per-concurrency " + "deltas for that model/configuration.\n\n" + "**Statistic:** Mean, Median, P95, or P99 where available. Throughput, " + "WER, RTFx, and transcription throughput are single values.\n\n" + "**Verdicts:** 🟢 Better, 🟡 Flat (±1%), 🔴 Worse. Verdicts account for " + "metric direction: for lower-is-better metrics, a negative delta is better." + ) + st.markdown(f"**Comparing:** {baseline} vs {candidate}") + st.caption( + "Each version/model/configuration is matched on common concurrency levels. " + "Summary cells use the geometric mean of per-concurrency deltas. Only the " + "selected load generator is used; results from different load generators " + "are never mixed. " + + ( + f"Statistic: {statistic} where available." + if statistic + else "Statistic: single values only." + ) + ) + + summary = _model_comparison_summary(base, comparison, statistic) + st.subheader("Version comparison summary") + if summary.empty: + st.info( + "No metric pairs are available for these versions and concurrency levels." + ) + return + st.dataframe(summary, use_container_width=True, hide_index=True) + if ( + "Model" in summary.columns + and summary["Model"].astype(str).str.contains("OmniVoice", case=False).any() + and any("Underrun" in str(column) for column in summary.columns) + ): + st.caption( + "OmniVoice underrun is 0 by construction: it is a single-stage " + "diffusion model that delivers audio in one chunk, so the inter-chunk " + "underrun metric cannot register a deficit. Flat/N/A underrun deltas " + "for OmniVoice are not a streaming result; use TTFP ≈ E2EL instead." + ) + st.caption( + "🟢 Better · 🟡 Flat (±1%) · 🔴 Worse. Cells use the geometric mean of " + "per-concurrency deltas for the selected statistic. Statistic changes apply " + "to RTF, TTFP, underrun, TTFT, TPOT, and end-to-end latency; throughput, WER, " + "RTFx, and transcription throughput are single values. Verdicts account for " + "metric direction, so a negative delta is better for lower-is-better metrics." + ) + st.download_button( + "Download comparison summary CSV", + data=summary.to_csv(index=False).encode("utf-8"), + file_name="omni_version_comparison.csv", + mime="text/csv", + ) + st.query_params["cv_base"] = baseline + st.query_params["cv_comp"] = candidate + st.query_params["cv_tasks"] = ",".join(selected_tasks) + st.query_params["cv_loadgen"] = load_generator + st.query_params["cv_models"] = ",".join(models) + st.query_params["cv_stat"] = statistic or "" + + +def _filtered_data(df: pd.DataFrame): + st.subheader("📄 Filtered Data") + show_all = st.toggle("Show all columns", value=False, key="omni_filtered_show_all") + view = _blank_nan(df if show_all else _display_frame(df)) + st.dataframe( + view, + use_container_width=True, + hide_index=True, + column_config=_link_column_config(view), + ) + st.download_button( + "Download filtered CSV", + data=df.to_csv(index=False).encode("utf-8"), + file_name="consolidated_dashboard_omni_filtered.csv", + mime="text/csv", + ) + + +def _render_section(section: str, df: pd.DataFrame): + if section == "🏠 Overview": + _overview(df) + elif section == "📊 Performance Plots": + filtered = _main_filters(df) + if filtered.empty: + st.warning("No rows match the current filters.") + return + _performance_plots(filtered) + elif section == "⚖️ Compare Versions": + _compare_versions(df) + elif section == "📄 Filtered Data": + filtered = _main_filters(df) + if filtered.empty: + st.warning("No rows match the current filters.") + return + _filtered_data(filtered) + elif section == "📋 View Logs": + filtered = _main_filters(df) + if filtered.empty: + st.warning("No rows match the current filters.") + return + _view_logs(filtered) + + +def render_omni_dashboard( + csv_path: str = "datasets/omni/consolidated_dashboard_omni.csv", +): + """Render the Omni dashboard shell and the selected section.""" + csv_path = os.environ.get("OMNI_CSV_PATH", csv_path) + st.header("vLLM-Omni Performance") + st.caption( + "Speech-out (TTS) benchmarks. Use Performance Plots to study model " + "performance across versions and review throughput, TTFP, RTF, " + "underrun, and audio throughput." + ) + section = _render_sidebar_nav() + df = load_omni_data(csv_path) + if df is None or df.empty: + st.warning("No Omni benchmark data is available.") + return + _render_section(section, df) diff --git a/pyproject.toml b/pyproject.toml index 1b5f6e9..7d890f6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ license = "MIT" readme = "README.md" requires-python = ">=3.9" dependencies = [ - "streamlit>=1.28.0", + "streamlit>=1.35.0", "pandas>=2.0.0", "plotly>=5.15.0", "numpy>=1.24.0", diff --git a/tests/test_omni_comparison.py b/tests/test_omni_comparison.py new file mode 100644 index 0000000..c53e28d --- /dev/null +++ b/tests/test_omni_comparison.py @@ -0,0 +1,94 @@ +"""Tests for Omni version-comparison workload matching.""" + +import pandas as pd + +from omni_dashboard import _comparison_keys, _comparison_table_for_task + + +def _frame(num_prompts, modes, throughput): + rows = len(num_prompts) + return pd.DataFrame( + { + "model": ["example/tts-1b"] * rows, + "task_type": ["default_voice"] * rows, + "concurrency_label": [1] * rows, + "load_generator": ["vllm-omni-bench-serve"] * rows, + "num_prompts": num_prompts, + "benchmark_mode": modes, + "request_throughput_rps": throughput, + } + ) + + +def test_key_is_included_when_only_one_side_has_values(): + base = _frame([100, None], [None, None], [1.0, 9.0]) + comparison = _frame([None], [None], [3.0]) + + keys = _comparison_keys(base, comparison) + + assert "num_prompts" in keys + assert "benchmark_mode" not in keys + + +def test_unknown_num_prompts_does_not_match_known_value(): + base = _frame([100, None], ["streaming", "streaming"], [1.0, 9.0]) + comparison = _frame([100], ["streaming"], [2.0]) + keys = _comparison_keys(base, comparison) + + table = _comparison_table_for_task( + base, comparison, "request_throughput_rps", "higher", keys + ) + + assert len(table) == 1 + assert table.iloc[0]["baseline"] == 1.0 + assert table.iloc[0]["comparison"] == 2.0 + + +def test_different_num_prompts_do_not_match(): + base = _frame([100], ["streaming"], [1.0]) + comparison = _frame([1000], ["streaming"], [2.0]) + keys = _comparison_keys(base, comparison) + + table = _comparison_table_for_task( + base, comparison, "request_throughput_rps", "higher", keys + ) + + assert table.empty + + +def test_different_benchmark_modes_do_not_match(): + base = _frame([100], ["streaming"], [1.0]) + comparison = _frame([100], ["non-streaming"], [2.0]) + keys = _comparison_keys(base, comparison) + + table = _comparison_table_for_task( + base, comparison, "request_throughput_rps", "higher", keys + ) + + assert table.empty + + +def test_all_unknown_keys_return_empty_instead_of_raising(): + base = _frame([None], ["streaming"], [1.0]) + comparison = _frame([100], ["streaming"], [2.0]) + keys = _comparison_keys(base, comparison) + + table = _comparison_table_for_task( + base, comparison, "request_throughput_rps", "higher", keys + ) + + assert table.empty + + +def test_pd_na_key_is_treated_as_unknown(): + base = _frame([100, None], ["streaming", "streaming"], [1.0, 9.0]) + base["num_prompts"] = pd.array([100, pd.NA], dtype="Int64") + comparison = _frame([100], ["streaming"], [2.0]) + keys = _comparison_keys(base, comparison) + + table = _comparison_table_for_task( + base, comparison, "request_throughput_rps", "higher", keys + ) + + assert len(table) == 1 + assert table.iloc[0]["baseline"] == 1.0 diff --git a/tests/test_omni_csv.py b/tests/test_omni_csv.py new file mode 100644 index 0000000..9e62106 --- /dev/null +++ b/tests/test_omni_csv.py @@ -0,0 +1,479 @@ +"""Tests for the consolidated Omni dashboard CSV schemas and converter.""" + +import csv +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +TEMPLATES_DIR = ROOT / "manual_runs" / "scripts" / "vllm-omni" / "templates" +TEMPLATE = TEMPLATES_DIR / "consolidated_dashboard_omni_template.csv" +TTS_TEMPLATE = TEMPLATES_DIR / "consolidated_dashboard_omni_tts_template.csv" +CONVERTER = ( + ROOT / "manual_runs" / "scripts" / "vllm-omni" / "build_consolidated_omni_csv.py" +) + +REQUIRED = {"model", "task_type", "benchmark_tool", "load_generator"} + + +def _metadata_file(tmp_path): + path = tmp_path / "metadata.json" + path.write_text( + json.dumps( + { + "defaults": { + "source_format": "vllm-omni-bench-json", + "runtime": "vllm-omni", + "benchmark_tool": "vllm-omni-bench-serve", + "load_generator": "vllm-omni-bench-serve", + "task_type": "voice_clone", + "dataset": "seed-tts", + "modality": "audio", + "input_modality": "text", + "output_modality": "audio", + "audio_sample_rate_hz": 24000, + "gpu_count": 1, + "tp": 1, + } + } + ) + ) + return path + + +def _read_csv(path): + with path.open(newline="") as handle: + return list(csv.DictReader(handle)) + + +def _header(path): + with path.open(newline="") as handle: + return next(csv.reader(handle)) + + +def test_legacy_template_schema(): + header = _header(TEMPLATE) + assert len(header) == 165 + assert len(set(header)) == 165 + assert "gpu_model" not in header + assert REQUIRED.issubset(header) + assert "extra_json" in header + assert "stage_metrics_json" in header + + +def test_tts_template_schema(): + header = _header(TTS_TEMPLATE) + assert len(header) == 77 + assert len(set(header)) == 77 + assert REQUIRED.issubset(header) + assert "recipe" in header + assert "profile" not in header + for column in ( + "run_key", + "num_prompts", + "response_format", + "audio_ttfp_ms_p95", + "audio_rtf_p95", + "audio_underrun_s_p95", + ): + assert column in header + + +def test_converter_smoke(tmp_path): + result = { + "model_id": "example/tts-1b", + "max_concurrency": 1, + "num_prompts": 2, + "request_throughput": 1.0, + "completed": 2, + "failed": 0, + "mean_audio_rtf": 0.1, + "mean_audio_ttfp_ms": 100.0, + "audio_throughput": 10.0, + "total_audio_duration_s": 4.0, + "total_audio_frames": 96000, + } + json_path = tmp_path / "result.json" + json_path.write_text(json.dumps(result)) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--omni-json", + str(json_path), + "--metadata-json", + str(_metadata_file(tmp_path)), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 1 + row = rows[0] + assert row["model"] == "example/tts-1b" + assert row["load_generator"] == "vllm-omni-bench-serve" + assert row["task_type"] == "voice_clone" + assert row["concurrency"] == "1" + assert row["model"] and row["benchmark_tool"] + assert len(_header(template)) == 165 + + +def test_asr_distinct_measurements_without_run_id(tmp_path): + input_csv = tmp_path / "asr.csv" + input_csv.write_text( + "model,wer,timestamp_utc,dataset,language,benchmark_tool,load_generator\n" + "example/asr-1b,10.0,2026-01-01T00:00:00Z,librispeech,en,asr-bench,asr-bench\n" + "example/asr-1b,12.0,2026-01-01T00:00:00Z,librispeech,en,asr-bench,asr-bench\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--asr-csv", + str(input_csv), + "--metadata-json", + str(_metadata_file(tmp_path)), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 2 + assert len({row["run_name"] for row in rows}) == 2 + + +def test_asr_exact_replays_still_deduplicate(tmp_path): + input_csv = tmp_path / "asr.csv" + input_csv.write_text( + "model,wer,timestamp_utc,dataset,language,benchmark_tool,load_generator\n" + "example/asr-1b,10.0,2026-01-01T00:00:00Z,librispeech,en,asr-bench,asr-bench\n" + "example/asr-1b,10.0,2026-01-01T00:00:00Z,librispeech,en,asr-bench,asr-bench\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--asr-csv", + str(input_csv), + "--metadata-json", + str(_metadata_file(tmp_path)), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 1 + assert rows[0]["run_name"].startswith("asr-example/asr-1b-librispeech-en-") + + +def test_legacy_distinct_measurements_without_json_file(tmp_path): + legacy_csv = tmp_path / "legacy.csv" + legacy_csv.write_text( + "model,version,concurrency,request_rate,task_type,request_throughput\n" + "example/tts-1b,v1,1,inf,voice_clone,1.0\n" + "example/tts-1b,v1,1,inf,voice_clone,2.0\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--legacy-csv", + str(legacy_csv), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 2 + assert len({row["run_name"] for row in rows}) == 2 + + +def test_legacy_latency_percentile_distinguishes_rows(tmp_path): + legacy_csv = tmp_path / "legacy.csv" + legacy_csv.write_text( + "model,version,concurrency,request_rate,task_type,audio_ttfp_p95\n" + "example/tts-1b,v1,1,inf,voice_clone,100\n" + "example/tts-1b,v1,1,inf,voice_clone,200\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--legacy-csv", + str(legacy_csv), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 2 + assert len({row["run_name"] for row in rows}) == 2 + + +def test_legacy_exact_replays_without_json_file_deduplicate(tmp_path): + legacy_csv = tmp_path / "legacy.csv" + legacy_csv.write_text( + "model,version,concurrency,request_rate,task_type,request_throughput\n" + "example/tts-1b,v1,1,inf,voice_clone,1.0\n" + "example/tts-1b,v1,1,inf,voice_clone,1.0\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--legacy-csv", + str(legacy_csv), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 1 + + +def _asr_metadata_file(tmp_path): + path = tmp_path / "asr-metadata.json" + path.write_text( + json.dumps( + { + "asr_defaults": { + "runtime_version": "asr-runtime-v1", + "dataset": "librispeech", + "cluster": "hera", + "benchmark_tool": "asr-bench", + "load_generator": "asr-bench", + } + } + ) + ) + return path + + +def test_legacy_distinct_json_files_are_preserved(tmp_path): + legacy_csv = tmp_path / "legacy.csv" + legacy_csv.write_text( + "model,version,concurrency,request_rate,json_file,task_type\n" + "example/tts-1b,v1,1,inf,a.json,voice_clone\n" + "example/tts-1b,v1,1,inf,b.json,voice_clone\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--legacy-csv", + str(legacy_csv), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 2 + assert {row["benchmark_run_id"] for row in rows} == {"a.json", "b.json"} + + +def test_asr_defaults_survive_missing_source_columns(tmp_path): + input_csv = tmp_path / "asr.csv" + input_csv.write_text("model,wer\nexample/asr-1b,10.0\n") + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--asr-csv", + str(input_csv), + "--metadata-json", + str(_asr_metadata_file(tmp_path)), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + row = _read_csv(output)[0] + assert row["runtime_version"] == "asr-runtime-v1" + assert row["dataset"] == "librispeech" + assert row["cluster"] == "hera" + + +def test_asr_offline_run_is_not_labeled_as_benchmark_tool(tmp_path): + input_csv = tmp_path / "asr.csv" + input_csv.write_text("model,wer,benchmark_tool\nexample/asr-1b,10.0,asr-bench\n") + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--asr-csv", + str(input_csv), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + row = _read_csv(output)[0] + assert row["benchmark_tool"] == "asr-bench" + assert row["load_generator"] == "offline" + + +def test_legacy_configuration_distinguishes_rows(tmp_path): + legacy_csv = tmp_path / "legacy.csv" + legacy_csv.write_text( + "model,version,concurrency,request_rate,task_type,request_throughput,tp\n" + "example/tts-1b,v1,1,inf,voice_clone,1.0,1\n" + "example/tts-1b,v1,1,inf,voice_clone,1.0,2\n" + ) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--legacy-csv", + str(legacy_csv), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + rows = _read_csv(output) + assert len(rows) == 2 + assert len({row["run_name"] for row in rows}) == 2 + + +def test_asr_numeric_zero_is_not_replaced_by_default(tmp_path): + input_json = tmp_path / "asr.json" + input_json.write_text( + json.dumps( + { + "model": "example/asr-1b", + "wer": 10.0, + "wer_ci_lower": 0, + "wer_ci_upper": 2, + } + ) + ) + metadata = tmp_path / "metadata.json" + metadata.write_text(json.dumps({"asr_defaults": {"wer_ci_lower": 2}})) + output = tmp_path / "consolidated.csv" + template = tmp_path / "template.csv" + + subprocess.run( + [ + sys.executable, + str(CONVERTER), + "--asr-json", + str(input_json), + "--metadata-json", + str(metadata), + "--output", + str(output), + "--template", + str(template), + ], + check=True, + cwd=ROOT, + capture_output=True, + text=True, + ) + + row = _read_csv(output)[0] + assert row["wer_ci_lower"] == "0" + + +if __name__ == "__main__": + pytest.main([__file__]) diff --git a/tests/test_omni_filter_persistence.py b/tests/test_omni_filter_persistence.py new file mode 100644 index 0000000..61a9cb2 --- /dev/null +++ b/tests/test_omni_filter_persistence.py @@ -0,0 +1,70 @@ +"""Regression tests for Omni filter persistence. + +Guards the bug where changing an upstream filter (for example Version) +reset downstream selections such as Model back to "all", which looked +like the filter was being ignored. +""" + +from pathlib import Path + +import pytest +from streamlit.testing.v1 import AppTest + +HARNESS = """ +import sys +sys.path.insert(0, {repo!r}) +import streamlit as st +from omni_dashboard import _persistent_multiselect, _select_all_models_multiselect + +MODE = st.radio("mode", ["wide", "narrow"], key="mode") +OPTIONS = {{ + "wide": ["m1", "m2", "m3", "m4"], + "narrow": ["m1", "m3"], +}}[MODE] +KIND = st.radio("kind", ["plain", "select_all"], key="kind") +if KIND == "plain": + sel = _persistent_multiselect("Model(s)", OPTIONS, "omni_model") +else: + sel = _select_all_models_multiselect("Model(s)", OPTIONS, "omni_model") +st.write("selected", list(sel)) +""" + + +def make_app(tmp_path: Path, kind: str) -> AppTest: + repo = Path(__file__).resolve().parents[1] + script = tmp_path / "harness.py" + script.write_text(HARNESS.format(repo=str(repo))) + at = AppTest.from_file(str(script), default_timeout=30) + at.run() + at.radio(key="kind").set_value(kind).run() + return at + + +@pytest.mark.parametrize("kind", ["plain", "select_all"]) +def test_selection_survives_upstream_change(tmp_path, kind): + at = make_app(tmp_path, kind) + at.multiselect[0].set_value(["m1", "m2"]).run() + assert at.multiselect[0].value == ["m1", "m2"] + + at.radio(key="mode").set_value("wide").run() + assert at.multiselect[0].value == ["m1", "m2"], ( + "changing an upstream filter must not reset downstream selections" + ) + + +@pytest.mark.parametrize("kind", ["plain", "select_all"]) +def test_only_invalid_values_are_pruned(tmp_path, kind): + at = make_app(tmp_path, kind) + at.multiselect[0].set_value(["m1", "m2"]).run() + + at.radio(key="mode").set_value("narrow").run() + assert at.multiselect[0].value == ["m1"] + + +@pytest.mark.parametrize("kind", ["plain", "select_all"]) +def test_falls_back_to_all_when_nothing_is_valid(tmp_path, kind): + at = make_app(tmp_path, kind) + at.multiselect[0].set_value(["m4"]).run() + + at.radio(key="mode").set_value("narrow").run() + assert at.multiselect[0].value == ["m1", "m3"] diff --git a/tests/test_omni_mlflow_lookup.py b/tests/test_omni_mlflow_lookup.py new file mode 100644 index 0000000..39e60c3 --- /dev/null +++ b/tests/test_omni_mlflow_lookup.py @@ -0,0 +1,57 @@ +"""Tests for the optional MLflow run-id lookup used by the Omni TTS builder.""" + +import importlib.util +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +BUILDER = ROOT / "manual_runs" / "scripts" / "vllm-omni" / "build_omni_tts_csv.py" + + +def _builder_module(): + spec = importlib.util.spec_from_file_location("build_omni_tts_csv", BUILDER) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_builder_repo_root(): + module = _builder_module() + assert Path(module.dashboard_repo_root()) == ROOT + + +def test_deployment_lookup_precedes_duplicate_run_name(tmp_path): + runs = { + "runs": [ + { + "info": {"run_id": "run-a"}, + "data": { + "tags": { + "mlflow.runName": "same-name", + "deployment_uuid": "deployment-a", + "concurrency": "1", + }, + "params": {}, + }, + }, + { + "info": {"run_id": "run-b"}, + "data": { + "tags": { + "mlflow.runName": "same-name", + "deployment_uuid": "deployment-b", + "concurrency": "1", + }, + "params": {}, + }, + }, + ] + } + path = tmp_path / "runs.json" + path.write_text(json.dumps(runs)) + module = _builder_module() + index = module.load_mlflow_index(str(path)) + + assert module.mlflow_run_id_for(index, "same-name", "deployment-a", "1") == "run-a" + assert module.mlflow_run_id_for(index, "same-name", "deployment-b", "1") == "run-b" + assert module.mlflow_run_id_for(index, "same-name", "deployment-c", "1") == "" diff --git a/tests/test_omni_streaming_preference.py b/tests/test_omni_streaming_preference.py new file mode 100644 index 0000000..b3d2b93 --- /dev/null +++ b/tests/test_omni_streaming_preference.py @@ -0,0 +1,77 @@ +"""Regression test for Omni streaming-preference persistence.""" + +from pathlib import Path + +from streamlit.testing.v1 import AppTest + +HARNESS = """ +import sys + +sys.path.insert(0, {repo!r}) + +import pandas as pd +import streamlit as st + +from omni_dashboard import _performance_plots + + +def make_df(): + base = {{ + "accelerator": "H200", + "model": "Qwen/Qwen3-TTS-12Hz-1.7B-Base", + "runtime_version": "vllm-omni-3.6.0-ga", + "tp": 1, + "recipe": "default", + "task_type": "voice_clone", + "dataset": "seed-tts", + "response_format": "wav", + "runtime_args": "", + "experiment_phase": "matrix", + "concurrency": 1, + "num_prompts": 1000, + }} + return pd.DataFrame( + [ + {{ + **base, + "benchmark_mode": "streaming", + "deployment_uuid": "uuid-streaming", + "request_throughput_rps": 1.0, + }}, + {{ + **base, + "benchmark_mode": "non_streaming", + "deployment_uuid": "uuid-nonstreaming", + "request_throughput_rps": 2.0, + }}, + ] + ) + + +mode = st.radio("mode", ["both", "streaming_only"], key="mode") +df = make_df() +if mode == "streaming_only": + df = df[df["benchmark_mode"] == "streaming"] +_performance_plots(df) +""" + + +def test_streaming_preference_survives_single_mode_filter(tmp_path): + repo = Path(__file__).resolve().parents[1] + script = tmp_path / "harness.py" + script.write_text(HARNESS.format(repo=str(repo))) + at = AppTest.from_file(str(script), default_timeout=30) + at.run() + assert not at.exception + assert at.toggle(key="omni_perf_streaming").value is True + + at.toggle(key="omni_perf_streaming").set_value(False).run() + assert at.toggle(key="omni_perf_streaming").value is False + + at.radio(key="mode").set_value("streaming_only").run() + assert at.toggle(key="omni_perf_streaming").value is True + assert at.session_state["omni_perf_streaming_pref"] is False + + at.radio(key="mode").set_value("both").run() + assert at.toggle(key="omni_perf_streaming").value is False + assert not at.exception