Profile Spark BF16 on fork branch and audit S25 short vocoder

This commit is contained in:
tzhouam committed 2026-09-24 13:37:57 +08:00
1 parent 8978302a1b
commit 68e0fd7cad
51 files changed
+38444 -6

No files matched your search

@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Audit a two-frame Code2Wav S25 candidate against its local CPU export."""
from __future__ import annotations
import argparse
import hashlib
import json
import math
from collections import Counter
from pathlib import Path
import numpy as np
def sha256(path: Path) -> str:
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def waveform(path: Path, name: str) -> 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}")
return value
def compare(reference: np.ndarray, observed: np.ndarray) -> dict:
a = reference.astype(np.float64).ravel()
b = observed.astype(np.float64).ravel()
delta = float(np.linalg.norm(a - b))
norm = float(np.linalg.norm(a))
return {
"relative_l2": delta / norm,
"snr_db": 20 * math.log10(norm / delta) if delta else None,
"max_abs": float(np.max(np.abs(a - b))),
"reference_rms": float(np.sqrt(np.mean(a * a))),
"output_rms": float(np.sqrt(np.mean(b * b))),
"output_saturated_fraction_abs_ge_0_999": float(np.mean(np.abs(b) >= 0.999)),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
for name in ("export-report", "upload-report", "dataset-report", "fixture",
"cpu-output", "eager-output", "compile-report", "inference-report",
"device-output", "output-report"):
parser.add_argument(f"--{name}", type=Path, required=True)
parser.add_argument("--profile-report", type=Path)
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()
export = json.loads(args.export_report.read_text())
upload = json.loads(args.upload_report.read_text())
dataset = json.loads(args.dataset_report.read_text())
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 (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["sample_count"] != 1
or sha256(args.fixture) != dataset["fixture_sha256"]):
raise ValueError("hosted input is not the retained short-window fixture")
if (inference["status"] != "SUCCESS"
or inference["model_id"] != compile_job["target_model_id"]
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")
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")
report = {
"scope": "one two-frame Qwen3-TTS vocoder component on hosted S25; no complete stream",
"status": "component_inference_numeric_measured",
"device": inference["device"],
"source_model_id": compile_job["source_model_id"],
"target_model_id": compile_job["target_model_id"],
"input_dataset_id": dataset["dataset_id"],
"jobs": {"compile": compile_job["job_id"], "inference": inference["job_id"]},
"route": {"compile_options": compile_job["options"], "run_options": inference["options"]},
"files": {name: {"bytes": path.stat().st_size, "sha256": sha256(path)}
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),
"eager_cpu_vs_device": compare(eager, hosted),
"limits": [
"One fixed two-frame 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.",
],
}
if profile is not None:
if (profile["status"] != "SUCCESS"
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"]}):
raise ValueError("placement profile did not use the audited device/artifact")
execution = profile["profile"]
samples = execution["execution_summary"]["all_inference_times"]
if not samples or any(not isinstance(t, int) or t <= 0 for t in samples):
raise ValueError("placement profile has no valid timing samples")
units = Counter(row.get("compute_unit") for row in execution["execution_detail"])
if not units:
raise ValueError("placement profile has no node placement detail")
ordered = sorted(samples)
report["jobs"]["profile"] = profile["job_id"]
report["profile"] = {
"sample_count": len(samples),
"min_us": ordered[0],
"nearest_rank_p50_us": ordered[math.ceil(0.5 * len(samples)) - 1],
"nearest_rank_p95_us": ordered[math.ceil(0.95 * len(samples)) - 1],
"reported_peak_memory_bytes": execution["execution_summary"]["estimated_inference_peak_memory"],
"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"
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")
print(json.dumps({"status": report["status"],
"comparison": report["ort_cpu_vs_device"],
"profile": report.get("profile")}, indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,191 @@
#!/usr/bin/env python3
"""Export and numerically gate a shorter 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.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import time
from pathlib import Path
import numpy as np
import onnx
import onnxruntime as ort
import torch
from torch import nn
from vllm_omni.edge.decoder_export import load_code2wav_decoder
class QuantizedWindowDecoder(nn.Module):
"""The existing decoder after RVQ lookup, with an explicit context window."""
def __init__(self, decoder: nn.Module, chunk_frames: int) -> None:
super().__init__()
self.decoder = decoder
self.chunk_frames = chunk_frames
self.hop = int(decoder.total_upsample)
def forward(self, quantized: torch.Tensor) -> torch.Tensor:
decoder = self.decoder
hidden = decoder.pre_conv(quantized).transpose(1, 2)
hidden = decoder.pre_transformer(inputs_embeds=hidden).last_hidden_state
hidden = hidden.permute(0, 2, 1)
for blocks in decoder.upsample:
for block in blocks:
hidden = block(hidden)
for block in decoder.decoder:
hidden = block(hidden)
return hidden.clamp(-1, 1).reshape(1, -1)[:, -self.chunk_frames * self.hop :]
def sha256(path: Path) -> str:
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def compare(reference: np.ndarray, output: np.ndarray) -> dict:
a = reference.astype(np.float64).ravel()
b = output.astype(np.float64).ravel()
error = float(np.linalg.norm(a - b))
norm = float(np.linalg.norm(a))
return {
"relative_l2": error / norm,
"snr_db": 20 * math.log10(norm / error) if error else None,
"max_abs": float(np.max(np.abs(a - b))),
"reference_rms": float(np.sqrt(np.mean(a * a))),
"output_rms": float(np.sqrt(np.mean(b * b))),
}
def strip_export_guards(path: Path) -> None:
graph = onnx.load(str(path))
nodes = graph.graph.node
producers = {out: node for node in nodes for out in node.output}
rename: dict[str, str] = {}
for node in list(nodes):
if node.op_type != "Where" or node.input[0] not in producers:
continue
guard = producers[node.input[0]]
if guard.op_type != "IsNaN":
continue
source = guard.input[0]
if source not in node.input[1:]:
continue
rename[node.output[0]] = source
nodes.remove(node)
nodes.remove(guard)
for node in nodes:
for index, value in enumerate(node.input):
if value in rename:
node.input[index] = rename[value]
if node.op_type == "Reshape":
for attribute in node.attribute:
if attribute.name == "allowzero":
attribute.i = 0
for value in graph.graph.output:
if value.name in rename:
value.name = rename[value.name]
onnx.save(graph, str(path))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
for name in ("model", "fixture", "long-reference", "onnx-output", "fixture-output",
"eager-output", "ort-output", "report"):
parser.add_argument(f"--{name}", type=Path, required=True)
parser.add_argument("--chunk-frames", type=int, default=2)
parser.add_argument("--context-frames", type=int, default=72)
args = parser.parse_args()
if args.chunk_frames <= 0 or args.context_frames != 72 or args.chunk_frames > 25:
raise ValueError("this fixture supports 72 history frames and 1-25 new frames")
with np.load(args.fixture, allow_pickle=False) as source:
if source.files != ["quantized"]:
raise ValueError("unexpected retained fixture")
full_input = np.asarray(source["quantized"])
if full_input.shape != (1, 512, 97) or full_input.dtype != np.float32:
raise ValueError("retained vocoder fixture differs from expected shape/dtype")
short_input = np.ascontiguousarray(full_input[:, :, : args.context_frames + args.chunk_frames])
if not np.isfinite(short_input).all():
raise ValueError("fixture contains nonfinite values")
decoder = load_code2wav_decoder(str(args.model))
model = QuantizedWindowDecoder(decoder, args.chunk_frames).eval()
with torch.inference_mode():
eager = model(torch.from_numpy(short_input)).detach().numpy()
expected_shape = (1, args.chunk_frames * model.hop)
if eager.shape != expected_shape or not np.isfinite(eager).all():
raise ValueError("eager short-window output violates contract")
args.onnx_output.parent.mkdir(parents=True, exist_ok=True)
started = time.perf_counter()
program = torch.onnx.export(
model, (torch.from_numpy(short_input),),
input_names=["quantized"], output_names=["wav"],
opset_version=17, dynamo=True, optimize=True,
)
program.save(str(args.onnx_output))
strip_export_guards(args.onnx_output)
export_s = time.perf_counter() - started
exported_model = onnx.load(str(args.onnx_output), load_external_data=False)
options = ort.SessionOptions()
options.intra_op_num_threads = 4
session = ort.InferenceSession(str(args.onnx_output), sess_options=options,
providers=["CPUExecutionProvider"])
observed = np.asarray(session.run(["wav"], {"quantized": short_input})[0])
if observed.shape != expected_shape or not np.isfinite(observed).all():
raise ValueError("ORT short-window output violates contract")
with np.load(args.long_reference, allow_pickle=False) as reference:
if reference.files != ["wav"] or reference["wav"].shape != (1, 48000):
raise ValueError("long-window reference differs from retained CPU output")
long_prefix = np.asarray(reference["wav"][:, : expected_shape[1]])
for path, key, value in (
(args.fixture_output, "quantized", short_input),
(args.eager_output, "wav", eager),
(args.ort_output, "wav", observed),
):
path.parent.mkdir(parents=True, exist_ok=True)
np.savez_compressed(path, **{key: value})
report = {
"scope": "one synthetic first short vocoder window; no device execution or complete TTS stream",
"model_snapshot": str(args.model.resolve()),
"model_snapshot_revision": args.model.resolve().name,
"model_weight_sha256": sha256(args.model / "speech_tokenizer" / "model.safetensors"),
"torch_version": torch.__version__,
"onnx_version": onnx.__version__,
"onnxruntime_version": ort.__version__,
"actual_opsets": {entry.domain or "ai.onnx": entry.version
for entry in exported_model.opset_import},
"source_fixture_sha256": sha256(args.fixture),
"long_cpu_reference_sha256": sha256(args.long_reference),
"context_frames": args.context_frames,
"chunk_frames": args.chunk_frames,
"input_shape": list(short_input.shape),
"output_shape": list(expected_shape),
"export_s_not_inference": export_s,
"onnx_sha256": sha256(args.onnx_output),
"short_fixture_sha256": sha256(args.fixture_output),
"eager_output_sha256": sha256(args.eager_output),
"ort_output_sha256": sha256(args.ort_output),
"ort_vs_eager": compare(eager, observed),
"short_eager_vs_25_frame_prefix": compare(long_prefix, eager),
"limits": [
"The short-window graph still requires its prior 72 quantized frames from a model adapter.",
"Prefix agreement is tested on one retained synthetic fixture, not a speech-quality set.",
"CPU export parity does not establish target compilation, placement or memory admission.",
],
}
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"ort_vs_eager": report["ort_vs_eager"],
"short_vs_long": report["short_eager_vs_25_frame_prefix"]}, indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Profile the pinned two-frame Code2Wav ONNX artifact on local ORT CPU."""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import platform
import sys
import time
from pathlib import Path
import numpy as np
import onnxruntime as ort
import psutil
def sha256(path: Path) -> str:
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def rank(values: list[float], fraction: float) -> float:
ordered = sorted(values)
return ordered[math.ceil(fraction * len(ordered)) - 1]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
for name in ("export-report", "model", "fixture", "reference-output", "report"):
parser.add_argument(f"--{name}", type=Path, required=True)
parser.add_argument("--threads", type=int, default=4)
parser.add_argument("--warmups", type=int, default=1)
parser.add_argument("--repeats", type=int, default=20)
args = parser.parse_args()
if args.threads < 1 or args.warmups < 1 or args.repeats < 20:
raise ValueError("expected positive threads and at least one warmup / 20 samples")
export = json.loads(args.export_report.read_text())
if (sha256(args.model) != export["onnx_sha256"]
or sha256(args.fixture) != export["short_fixture_sha256"]
or sha256(args.reference_output) != export["ort_output_sha256"]):
raise ValueError("model, fixture or reference differs from the audited export")
with np.load(args.fixture, allow_pickle=False) as data:
if data.files != ["quantized"]:
raise ValueError("unexpected fixture schema")
x = np.asarray(data["quantized"])
with np.load(args.reference_output, allow_pickle=False) as data:
if data.files != ["wav"]:
raise ValueError("unexpected reference schema")
reference = np.asarray(data["wav"])
if x.shape != (1, 512, 74) or x.dtype != np.float32 or reference.shape != (1, 3840):
raise ValueError("short-window tensor contract differs")
options = ort.SessionOptions()
options.intra_op_num_threads = args.threads
started = time.perf_counter()
session = ort.InferenceSession(str(args.model), sess_options=options,
providers=["CPUExecutionProvider"])
load_s = time.perf_counter() - started
if session.get_providers() != ["CPUExecutionProvider"]:
raise RuntimeError("the profile did not use ORT CPU")
process = psutil.Process()
loaded_rss = process.memory_info().rss
samples: list[float] = []
for index in range(args.warmups + args.repeats):
started = time.perf_counter()
output = np.asarray(session.run(["wav"], {"quantized": x})[0])
elapsed = time.perf_counter() - started
if output.shape != reference.shape or not np.isfinite(output).all():
raise ValueError("profile output violates waveform contract")
relative_l2 = float(np.linalg.norm((output - reference).astype(np.float64))
/ np.linalg.norm(reference.astype(np.float64)))
if relative_l2 > 1e-6:
raise ValueError(f"profile output drifted from its own CPU reference: {relative_l2}")
if index >= args.warmups:
samples.append(elapsed)
report = {
"scope": "one fixed two-frame Code2Wav component on HX370 WSL ORT CPU; no complete TTS stream",
"status": "component_cpu_profiled",
"platform": platform.platform(),
"cpu": next((line.split(":", 1)[1].strip()
for line in Path("/proc/cpuinfo").read_text().splitlines()
if line.startswith("model name")), platform.processor()),
"python_version": sys.version.split()[0],
"checkpoint_revision": export["model_snapshot_revision"],
"power_condition": "not recorded",
"ort_version": ort.__version__,
"provider": session.get_providers(),
"threads": args.threads,
"model_sha256": export["onnx_sha256"],
"fixture_sha256": export["short_fixture_sha256"],
"load_s": load_s,
"rss_after_load_bytes": loaded_rss,
"warmups": args.warmups,
"sample_count": len(samples),
"samples_s": samples,
"nearest_rank_p50_s": rank(samples, 0.5),
"nearest_rank_p95_s": rank(samples, 0.95),
"audio_duration_s": 3840 / 24000,
"median_component_rtf": rank(samples, 0.5) / (3840 / 24000),
"limits": [
"The input is one retained synthetic window, and no talker or predictor ran.",
"This host CPU timing cannot be transplanted to the S25 or another SoC.",
],
}
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({k: report[k] for k in
("sample_count", "nearest_rank_p50_s", "nearest_rank_p95_s",
"median_component_rtf")}, indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Profile serial complete Spark BF16 text requests through the Omni CPU stage."""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import math
import time
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 rank(values: list[float], fraction: float) -> float:
ordered = sorted(values)
return ordered[math.ceil(fraction * len(ordered)) - 1]
async def profile(args: argparse.Namespace) -> dict:
plan = plan_text_session(
str(args.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("the pinned Spark BF16 run was not admitted on CPU")
name, prompt = acceptance_prompts()[0]
runs = []
async with LocalTextEngine(plan) as engine:
for index in range(args.warmups + args.repeats):
session = engine.open_session()
started = time.perf_counter()
request_id, stream = await engine.submit(
session, prompt, max_tokens=args.max_tokens,
temperature=0.0, ignore_eos=True,
)
async for _ in stream:
pass
wall_s = time.perf_counter() - started
record = engine.records[request_id]
if record.error or record.cancelled or not record.finished or record.output_tokens != args.max_tokens:
raise RuntimeError(f"request {index} did not complete the specified text workload")
digest = hashlib.sha256(json.dumps(record.output_token_ids).encode()).hexdigest()
runs.append({
"kind": "warmup" if index < args.warmups else "measured",
"prompt_name": name,
"prompt_tokens": record.prompt_tokens,
"output_tokens": record.output_tokens,
"token_ids_sha256": digest,
"wall_s": wall_s,
"ttft_s": record.ttft_s,
"decode_tok_per_s": record.decode_tok_per_s,
"stream": stream.stats(),
})
engine.close_session(session.session_id)
placement = engine.report_placement()
usage = engine.report_usage()
load_s = engine.load_seconds
measured = runs[args.warmups:]
if len({row["token_ids_sha256"] for row in runs}) != 1:
raise RuntimeError("serial greedy requests produced different token sequences")
report = {
"scope": "Spark-X2.5-1.7B dense BF16 complete text requests through Omni on WSL HX370 CPU",
"status": "scoped_e2e_profiled",
"model": str(args.model.resolve()),
"runtime": runtime_versions().to_dict(),
"plan": plan.to_dict(),
"placement": placement,
"usage": usage,
"load_s_not_request_timing": load_s,
"warmup_count": args.warmups,
"measured_count": args.repeats,
"max_new_tokens": args.max_tokens,
"runs": runs,
"nearest_rank_p50_wall_s": rank([r["wall_s"] for r in measured], 0.5),
"nearest_rank_p95_wall_s": rank([r["wall_s"] for r in measured], 0.95),
"nearest_rank_p50_ttft_s": rank([r["ttft_s"] for r in measured], 0.5),
"nearest_rank_p95_ttft_s": rank([r["ttft_s"] for r in measured], 0.95),
"limits": [
"One short prompt and one concurrency level; the acceptance and parity suites are separate evidence.",
"The host power condition was not controlled or recorded as a sustained thermal test.",
],
}
return report
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--report", type=Path, required=True)
parser.add_argument("--warmups", type=int, default=1)
parser.add_argument("--repeats", type=int, default=20)
parser.add_argument("--max-tokens", type=int, default=64)
args = parser.parse_args()
if args.warmups < 1 or args.repeats < 20 or args.max_tokens < 1:
parser.error("expected at least one warmup, 20 measured requests and positive token count")
report = asyncio.run(profile(args))
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({key: report[key] for key in (
"status", "measured_count", "nearest_rank_p50_wall_s", "nearest_rank_p95_wall_s",
"nearest_rank_p50_ttft_s", "nearest_rank_p95_ttft_s",
)}, indent=2))
if __name__ == "__main__":
main()