Audit S24 vocoder routes and Spark restart; prepare pinned S25 export

This commit is contained in:
tzhouam committed 2026-09-24 14:27:11 +08:00
1 parent 68e0fd7cad
commit 203039e054
59 files changed
+18865 -30

No files matched your search

@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Audit a two-frame Code2Wav S25 candidate against its local CPU export."""
"""Audit a fixed-window Code2Wav candidate against its local CPU export."""
from __future__ import annotations
@@ -18,13 +18,13 @@ def sha256(path: Path) -> str:
return hashlib.file_digest(stream, "sha256").hexdigest()
def waveform(path: Path, name: str) -> np.ndarray:
def waveform(path: Path, name: str, expected_shape: tuple[int, int]) -> np.ndarray:
with np.load(path, allow_pickle=False) as data:
if data.files != [name]:
raise ValueError(f"{path}: expected one output named {name}")
value = np.asarray(data[name])
if value.shape != (1, 3840) or value.dtype != np.float32 or not np.isfinite(value).all():
raise ValueError(f"{path}: expected finite float32[1,3840], got {value.shape}/{value.dtype}")
if value.shape != expected_shape or value.dtype != np.float32 or not np.isfinite(value).all():
raise ValueError(f"{path}: expected finite float32{expected_shape}, got {value.shape}/{value.dtype}")
return value
@@ -50,6 +50,7 @@ def main() -> None:
"device-output", "output-report"):
parser.add_argument(f"--{name}", type=Path, required=True)
parser.add_argument("--profile-report", type=Path)
parser.add_argument("--expected-device", default="Samsung Galaxy S25")
parser.add_argument("--expected-compile-options", default="--target_runtime qnn_dlc --qnn_options default_graph_htp_precision=FLOAT16")
parser.add_argument("--expected-run-options", default="--compute_unit npu")
args = parser.parse_args()
@@ -59,15 +60,17 @@ def main() -> None:
compile_job = json.loads(args.compile_report.read_text())
inference = json.loads(args.inference_report.read_text())
profile = json.loads(args.profile_report.read_text()) if args.profile_report else None
if export["context_frames"] != 72 or export["chunk_frames"] != 2:
raise ValueError("export differs from the tested two-frame window")
if (export["context_frames"] != 72 or not 1 <= export["chunk_frames"] <= 25
or export["input_shape"] != [1, 512, 72 + export["chunk_frames"]]
or export["output_shape"] != [1, 1920 * export["chunk_frames"]]):
raise ValueError("export differs from the tested fixed-window contract")
if (upload["source_sha256"] != export["onnx_sha256"]
or compile_job["source_model_id"] != upload["source_model_id"]
or compile_job["status"] != "SUCCESS"
or compile_job["options"] != args.expected_compile_options):
raise ValueError("compile does not use the verified short-window artifact")
if (dataset["fixture_sha256"] != export["short_fixture_sha256"]
or dataset["input_shape"] != [1, 512, 74]
or dataset["input_shape"] != export["input_shape"]
or dataset["sample_count"] != 1
or sha256(args.fixture) != dataset["fixture_sha256"]):
raise ValueError("hosted input is not the retained short-window fixture")
@@ -76,17 +79,21 @@ def main() -> None:
or inference["input_dataset_id"] != dataset["dataset_id"]
or inference["options"] != args.expected_run_options
or inference["device"] != compile_job["device"]
or inference["device"]["name"] != "Samsung Galaxy S25"):
raise ValueError("inference differs from the exact S25 target/fixture/route")
or inference["device"]["name"] != args.expected_device):
raise ValueError("inference differs from the exact target/fixture/route")
if (sha256(args.cpu_output) != export["ort_output_sha256"]
or sha256(args.eager_output) != export["eager_output_sha256"]):
raise ValueError("local CPU outputs differ from export parity evidence")
cpu = waveform(args.cpu_output, "wav")
eager = waveform(args.eager_output, "wav")
hosted = waveform(args.device_output, "output_0__0")
expected_shape = tuple(export["output_shape"])
cpu = waveform(args.cpu_output, "wav", expected_shape)
eager = waveform(args.eager_output, "wav", expected_shape)
hosted = waveform(args.device_output, "output_0__0", expected_shape)
cpu_comparison = compare(cpu, hosted)
gross_numeric_failure = (cpu_comparison["relative_l2"] >= 1.0
or cpu_comparison["output_saturated_fraction_abs_ge_0_999"] >= 0.1)
report = {
"scope": "one two-frame Qwen3-TTS vocoder component on hosted S25; no complete stream",
"status": "component_inference_numeric_measured",
"scope": f"one {export['chunk_frames']}-frame Qwen3-TTS vocoder component on hosted {args.expected_device}; no complete stream",
"status": "component_gross_numeric_failure" if gross_numeric_failure else "component_inference_numeric_measured",
"device": inference["device"],
"source_model_id": compile_job["source_model_id"],
"target_model_id": compile_job["target_model_id"],
@@ -97,10 +104,14 @@ def main() -> None:
for name, path in {"fixture": args.fixture, "ort_cpu": args.cpu_output,
"eager_cpu": args.eager_output,
"device_output": args.device_output}.items()},
"ort_cpu_vs_device": compare(cpu, hosted),
"ort_cpu_vs_device": cpu_comparison,
"eager_cpu_vs_device": compare(eager, hosted),
"gross_numeric_failure_screen": {
"failed": gross_numeric_failure,
"criteria": "relative L2 >= 1.0 or fraction |sample| >= 0.999 at least 0.1; this is not a speech-quality acceptance threshold",
},
"limits": [
"One fixed two-frame waveform has no listening-quality tolerance.",
"One fixed-window waveform has no listening-quality tolerance.",
"The 72-frame input history, talker, predictor and stage handoff did not run on the device.",
"No persistent state, admission, cancellation or complete TTS stream was tested.",
],
@@ -110,7 +121,7 @@ def main() -> None:
or profile["model_id"] != inference["model_id"]
or profile["device"] != inference["device"]
or profile["options"] != inference["options"]
or profile["shapes"] != {"quantized": [[1, 512, 74], "float32"]}):
or profile["shapes"] != {"quantized": [export["input_shape"], "float32"]}):
raise ValueError("placement profile did not use the audited device/artifact")
execution = profile["profile"]
samples = execution["execution_summary"]["all_inference_times"]
@@ -130,7 +141,8 @@ def main() -> None:
"compute_unit_row_counts": dict(units),
"profile_input": "Workbench generated input with audited tensor shape; the waveform inference used the retained fixture",
}
report["status"] = "component_inference_numeric_and_placement_measured"
report["status"] = ("component_gross_numeric_failure_with_placement_profile"
if gross_numeric_failure else "component_inference_numeric_and_placement_measured")
else:
report["limits"].append("Requested accelerator execution is not verified node placement without a profile.")
args.output_report.write_text(json.dumps(report, indent=2) + "\n")
@@ -93,6 +93,8 @@ def main() -> None:
raise RuntimeError("job did not use the exact requested device")
if inference.get("options") != args.run_options or (profile is not None and profile.get("options") != args.run_options):
raise RuntimeError("inference/profile requested different compute options")
if profile is not None and profile.get("shapes") != {"quantized": [[1, 512, 97], "float32"]}:
raise RuntimeError("profile did not use the pinned 97-frame input contract")
files = {
name: {"bytes": path.stat().st_size, "sha256": sha256(path)}
for name, path in {
@@ -116,6 +118,7 @@ def main() -> None:
cpu = read_output(args.cpu_output, "wav")
s25 = read_output(args.s25_output, "output_0__0")
output = read_output(args.device_output, "output_0__0")
same_s25_output = args.s25_output.resolve() == args.device_output.resolve()
report = {
"scope": "one Qwen3-TTS code2wav 48,000-sample component on one retained fixture; no complete TTS stream",
"status": "component_executed_quality_unqualified" if profile is not None else "component_inference_numeric_measured",
@@ -128,7 +131,9 @@ def main() -> None:
"requested_run_options": args.run_options,
"files": files,
"cpu_source_vs_device": compare(cpu, output),
"s25_gpu_vs_device": compare(s25, output),
"s25_gpu_vs_device": None if same_s25_output else compare(s25, output),
"s25_comparison_note": ("same retained S25 output; no independent device comparison"
if same_s25_output else "independent hosted output comparison"),
"limits": [
"Historical source export does not attest its exact checkpoint revision.",
"This fixed component waveform has no listening or task-quality tolerance.",
@@ -152,6 +157,7 @@ def main() -> None:
"reported_estimated_inference_time_us": execution["execution_summary"]["estimated_inference_time"],
"reported_peak_memory_bytes": execution["execution_summary"]["estimated_inference_peak_memory"],
"compute_unit_row_counts": dict(units),
"profile_input": "Workbench generated input with pinned tensor shape; waveform inference used the retained fixture",
}
else:
report["limits"].append("Requested compute unit is not verified node placement without a device profile.")
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
"""Export and numerically gate a shorter Qwen3-TTS Code2Wav window.
"""Export and numerically gate a fixed Qwen3-TTS Code2Wav window.
The retained 25-frame graph takes 72 context frames plus 25 new frames. This
experiment keeps the same decoder and 72-frame history while reducing the new
chunk to two frames, before any device compilation or performance claim.
The retained reference graph takes 72 context frames plus 25 new frames.
This experiment keeps the same decoder and 72-frame history while selecting
1-25 new frames, before any device compilation or performance claim.
"""
from __future__ import annotations
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Compare a pinned eager 25-frame Code2Wav decoder with retained ONNX CPU."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
import torch
from benchmarks.edge_harness.experiments.export_qwen_tts_vocoder_short_chunk import (
QuantizedWindowDecoder,
compare,
sha256,
)
from vllm_omni.edge.decoder_export import load_code2wav_decoder
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
for name in ("checkpoint", "source-onnx", "fixture", "ort-output", "manifest", "report"):
parser.add_argument(f"--{name}", type=Path, required=True)
args = parser.parse_args()
manifest = json.loads(args.manifest.read_text())
for key, path in (("vocoder_source_onnx", args.source_onnx),
("vocoder_fixture", args.fixture),
("vocoder_ort_cpu_output", args.ort_output)):
if sha256(path) != manifest["files"][key]["sha256"]:
raise ValueError(f"{key} differs from the retained historical artifact")
with np.load(args.fixture, allow_pickle=False) as data:
if data.files != ["quantized"]:
raise ValueError("unexpected fixture schema")
quantized = np.asarray(data["quantized"])
with np.load(args.ort_output, allow_pickle=False) as data:
if data.files != ["wav"]:
raise ValueError("unexpected output schema")
reference = np.asarray(data["wav"])
if (quantized.shape != (1, 512, 97) or quantized.dtype != np.float32
or reference.shape != (1, 48000) or reference.dtype != np.float32):
raise ValueError("historical tensor contract changed")
torch.set_num_threads(4)
decoder = QuantizedWindowDecoder(load_code2wav_decoder(str(args.checkpoint)), 25).eval()
with torch.inference_mode():
eager = decoder(torch.from_numpy(quantized)).detach().numpy()
if eager.shape != reference.shape or not np.isfinite(eager).all():
raise ValueError("eager output violates finite 48,000-sample contract")
report = {
"scope": "one synthetic 25-frame Code2Wav waveform parity check; no device stream",
"pinned_checkpoint_revision": args.checkpoint.resolve().name,
"pinned_decoder_weight_sha256": sha256(args.checkpoint / "speech_tokenizer" / "model.safetensors"),
"source_onnx_sha256": sha256(args.source_onnx),
"fixture_sha256": sha256(args.fixture),
"ort_output_sha256": sha256(args.ort_output),
"eager_output_bytes_sha256": hashlib.sha256(eager.tobytes()).hexdigest(),
"torch_version": torch.__version__,
"eager_vs_historical_onnx_cpu": compare(reference, eager),
"limits": [
"Numerical agreement on one fixture cannot prove the historical ONNX export's exact checkpoint revision.",
"One synthetic latent window cannot establish listening quality or multi-chunk history.",
],
}
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report["eager_vs_historical_onnx_cpu"], indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Check whether shorter Code2Wav history preserves a pinned two-frame output.
This is a one-fixture numerical screen for smaller target graphs, not an audio
quality or device-performance result.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from benchmarks.edge_harness.experiments.export_qwen_tts_vocoder_short_chunk import (
QuantizedWindowDecoder,
compare,
sha256,
)
from vllm_omni.edge.decoder_export import load_code2wav_decoder
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--source-fixture", type=Path, required=True)
parser.add_argument("--long-reference", type=Path, required=True)
parser.add_argument("--export-report", type=Path, required=True)
parser.add_argument("--report", type=Path, required=True)
args = parser.parse_args()
export = json.loads(args.export_report.read_text())
if (sha256(args.source_fixture) != export["source_fixture_sha256"]
or sha256(args.long_reference) != export["long_cpu_reference_sha256"]
or sha256(args.model / "speech_tokenizer" / "model.safetensors")
!= export["model_weight_sha256"]):
raise ValueError("fixture, reference or checkpoint differs from the export")
with np.load(args.source_fixture, allow_pickle=False) as data:
if data.files != ["quantized"]:
raise ValueError("unexpected fixture schema")
full_input = np.asarray(data["quantized"])
with np.load(args.long_reference, allow_pickle=False) as data:
if data.files != ["wav"]:
raise ValueError("unexpected reference schema")
long_output = np.asarray(data["wav"])
if (full_input.shape != (1, 512, 97) or full_input.dtype != np.float32
or long_output.shape != (1, 48000)):
raise ValueError("reference tensor shape changed")
torch.set_num_threads(4)
model = QuantizedWindowDecoder(load_code2wav_decoder(str(args.model)), 2).eval()
reference = long_output[:, :3840]
rows = []
baseline = None
for history in (72, 64, 48, 32, 24, 16, 8):
window = np.ascontiguousarray(full_input[:, :, 72 - history:74])
with torch.inference_mode():
output = model(torch.from_numpy(window)).detach().numpy()
if output.shape != (1, 3840) or not np.isfinite(output).all():
raise ValueError(f"{history}-frame history violated waveform contract")
if baseline is None:
baseline = output
rows.append({
"history_frames": history,
"input_shape": list(window.shape),
"vs_72_history": compare(baseline, output),
"vs_25_frame_reference_prefix": compare(reference, output),
})
report = {
"scope": "one synthetic two-frame Code2Wav window; local CPU numerical screen only",
"checkpoint_revision": export["model_snapshot_revision"],
"checkpoint_weight_sha256": export["model_weight_sha256"],
"source_fixture_sha256": export["source_fixture_sha256"],
"long_reference_sha256": export["long_cpu_reference_sha256"],
"torch_version": torch.__version__,
"rows": rows,
"limits": [
"One synthetic first window cannot establish multi-chunk history or speech quality.",
"No smaller-history graph was exported, compiled or executed on a device.",
"CPU forward timing was not measured as a performance profile.",
],
}
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps([{"history_frames": x["history_frames"],
"relative_l2": x["vs_72_history"]["relative_l2"]}
for x in rows], indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Verify Spark BF16 can generate again after an in-flight Omni cancellation."""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
from pathlib import Path
from vllm_omni.edge.local.engine import LocalTextEngine
from vllm_omni.edge.local.manifest import runtime_versions
from vllm_omni.edge.local.plan import plan_text_session
from vllm_omni.edge.local.prompts import acceptance_prompts
def token_digest(ids: list[int]) -> str:
return hashlib.sha256(json.dumps(ids).encode()).hexdigest()
async def run(model: Path) -> dict:
plan = plan_text_session(
str(model), max_model_len=4096, max_num_seqs=1,
max_num_batched_tokens=2048, enforce_eager=True,
)
if not plan.admitted or plan.selected is None or plan.selected.device_id != "cpu":
raise RuntimeError("pinned BF16 CPU plan was not admitted")
name, prompt = acceptance_prompts()[0]
requests = []
async with LocalTextEngine(plan) as engine:
session = engine.open_session()
async def generate(label: str, active_session: object) -> list[int]:
rid, stream = await engine.submit(
active_session, prompt, max_tokens=128, temperature=0.0, ignore_eos=True,
)
async for _ in stream:
pass
record = engine.records[rid]
if record.error or record.cancelled or not record.finished or record.output_tokens != 128:
raise RuntimeError(f"{label} did not finish the specified text workload")
ids = list(record.output_token_ids)
requests.append({"label": label, "request_id": rid,
"session_id": active_session.session_id,
"epoch": record.epoch, "output_tokens": len(ids),
"token_ids_sha256": token_digest(ids),
"ttft_s": record.ttft_s,
"stream": stream.stats()})
return ids
baseline = await generate("before_cancel", session)
rid, stream = await engine.submit(
session, prompt, max_tokens=4096, temperature=0.0, ignore_eos=True,
)
token_events = 0
async for event in stream:
if event.kind == "token":
token_events += 1
if token_events >= 8:
break
cancel = await engine.cancel(rid)
late_events = []
while True:
try:
event = await asyncio.wait_for(stream.get(), timeout=1.0)
except asyncio.TimeoutError:
break
if event is None:
break
late_events.append(event.to_dict())
cancel["token_events_before_cancel"] = token_events
cancel["late_events"] = late_events
try:
stale_rid, _ = await engine.submit(
session, prompt, max_tokens=128, temperature=0.0, ignore_eos=True,
)
except RuntimeError as exc:
stale_error = str(exc)
stale_rejected = "stale" in stale_error and "open a new session" in stale_error
else:
await engine.cancel(stale_rid)
stale_error = "old session was unexpectedly accepted"
stale_rejected = False
engine.close_session(session.session_id)
fresh_session = engine.open_session()
new_session = await generate("new_session_after_cancel", fresh_session)
engine.close_session(fresh_session.session_id)
placement = engine.report_placement()
usage = engine.report_usage()
load_s = engine.load_seconds
passed = (bool(cancel.get("aborted_in_backend"))
and cancel.get("inflight_after") == 0
and not late_events
and stale_rejected
and baseline == new_session)
return {
"scope": "Spark 1.7B BF16 128-token WSL CPU text restart after cancellation",
"status": "restart_after_cancel_pass" if passed else "restart_after_cancel_fail",
"prompt_name": name,
"runtime": runtime_versions().to_dict(),
"plan": plan.to_dict(),
"placement": placement,
"usage": usage,
"load_s_not_request_timing": load_s,
"requests": requests,
"cancel": cancel,
"stale_handle_rejected": stale_rejected,
"stale_handle_error": stale_error,
"exact_token_sequence_agreement": baseline == new_session,
"limits": [
"One prompt, 128 output tokens, one engine instance and one cancellation depth.",
"The retired session is rejected by design; restart uses a fresh session handle.",
"No concurrent traffic or sustained power/thermal behavior was tested.",
],
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--report", type=Path, required=True)
args = parser.parse_args()
report = asyncio.run(run(args.model))
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"status": report["status"],
"cancel_before": report["cancel"]["token_events_before_cancel"],
"late_events": len(report["cancel"]["late_events"]),
"stale_handle_rejected": report["stale_handle_rejected"],
"exact": report["exact_token_sequence_agreement"]}, indent=2))
if report["status"] != "restart_after_cancel_pass":
raise SystemExit(1)
if __name__ == "__main__":
main()