Isolate AMD NPU vocoder compiler crash and validate 2D rewrite
This commit is contained in:
1 parent
df8f02376d
commit
a1866083a0
38 files changed
+1203
-4
No files matched your search
@@ -0,0 +1,192 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract a pinned Code2Wav ONNX prefix and probe AMD VitisAI compilation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for block in iter(lambda: source.read(8 << 20), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def write_report(path: Path, report: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def extract(args: argparse.Namespace) -> None:
|
||||
import onnx
|
||||
|
||||
source_hash = sha256(args.source)
|
||||
if source_hash != args.expected_source_sha256:
|
||||
raise ValueError("source ONNX hash changed")
|
||||
source = onnx.load(args.source)
|
||||
if not 1 <= args.cut <= len(source.graph.node):
|
||||
raise ValueError("cut must be a one-based node ordinal")
|
||||
terminal = source.graph.node[args.cut - 1]
|
||||
output_name = terminal.output[0]
|
||||
if not output_name:
|
||||
raise ValueError("selected node has an empty first output")
|
||||
inputs = args.input_tensor or [item.name for item in source.graph.input]
|
||||
candidate = onnx.utils.Extractor(source).extract_model(inputs, [output_name])
|
||||
onnx.checker.check_model(candidate)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
onnx.save(candidate, args.output)
|
||||
report = {
|
||||
"scope": "compiler bisection component, not a vocoder waveform or TTS stream",
|
||||
"source_sha256": source_hash,
|
||||
"source_node_count": len(source.graph.node),
|
||||
"cut_one_based": args.cut,
|
||||
"terminal_node": terminal.name,
|
||||
"terminal_op": terminal.op_type,
|
||||
"terminal_output": output_name,
|
||||
"boundary_inputs": inputs,
|
||||
"extracted_node_count": len(candidate.graph.node),
|
||||
"extracted_ops": dict(Counter(node.op_type for node in candidate.graph.node)),
|
||||
"output_type": str(candidate.graph.output[0].type),
|
||||
"candidate_file": str(args.output.resolve()),
|
||||
"candidate_bytes": args.output.stat().st_size,
|
||||
"candidate_sha256": sha256(args.output),
|
||||
}
|
||||
write_report(args.report, report)
|
||||
print(json.dumps({key: report[key] for key in
|
||||
("cut_one_based", "extracted_node_count", "candidate_sha256")}))
|
||||
|
||||
|
||||
def probe(args: argparse.Namespace) -> None:
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
|
||||
report = json.loads(args.extraction_report.read_text(encoding="utf-8"))
|
||||
expected_model_hash = report.get("candidate_sha256", report.get("rewritten_sha256"))
|
||||
if sha256(args.model) != expected_model_hash:
|
||||
raise ValueError("candidate ONNX hash changed")
|
||||
if args.synthetic_input:
|
||||
fixture_hash = None
|
||||
quantized = None
|
||||
else:
|
||||
if args.fixture is None or args.expected_fixture_sha256 is None:
|
||||
raise ValueError("fixture and expected hash are required for real input")
|
||||
if sha256(args.fixture) != args.expected_fixture_sha256:
|
||||
raise ValueError("fixture hash changed")
|
||||
with np.load(args.fixture, allow_pickle=False) as source:
|
||||
quantized = np.ascontiguousarray(source["quantized"])
|
||||
if quantized.shape != (1, 512, 74) or quantized.dtype != np.float32:
|
||||
raise ValueError("fixture shape/dtype changed")
|
||||
fixture_hash = args.expected_fixture_sha256
|
||||
report.update({
|
||||
"os": platform.platform(),
|
||||
"onnxruntime_version": ort.__version__,
|
||||
"fixture_sha256": fixture_hash,
|
||||
"input_provenance": "synthetic fixed-seed normal" if args.synthetic_input else "pinned real-weight vocoder fixture",
|
||||
"status": "started",
|
||||
})
|
||||
write_report(args.report, report)
|
||||
cpu = ort.InferenceSession(str(args.model), providers=["CPUExecutionProvider"])
|
||||
cpu_input = cpu.get_inputs()[0]
|
||||
if args.synthetic_input:
|
||||
shape = cpu_input.shape
|
||||
if any(not isinstance(size, int) or size <= 0 for size in shape):
|
||||
raise ValueError("synthetic input requires a fully static tensor shape")
|
||||
quantized = np.random.default_rng(42).standard_normal(shape).astype(np.float32)
|
||||
started = time.perf_counter()
|
||||
cpu_output = cpu.run(None, {cpu_input.name: quantized})[0]
|
||||
report.update({
|
||||
"cpu_output_shape": list(cpu_output.shape),
|
||||
"cpu_output_finite": bool(np.isfinite(cpu_output).all()),
|
||||
"cpu_inference_s": time.perf_counter() - started,
|
||||
"status": "cpu_component_pass",
|
||||
})
|
||||
write_report(args.report, report)
|
||||
if not report["cpu_output_finite"]:
|
||||
raise ValueError("CPU prefix output is nonfinite")
|
||||
if args.cpu_only:
|
||||
return
|
||||
|
||||
ep_dir = args.ep_dir.resolve(strict=True)
|
||||
os.environ["PATH"] = str(ep_dir) + os.pathsep + os.environ.get("PATH", "")
|
||||
if hasattr(os, "add_dll_directory"):
|
||||
os.add_dll_directory(str(ep_dir))
|
||||
ort.register_execution_provider_library(
|
||||
"vitisai", str(ep_dir / "onnxruntime_vitisai_ep.dll"))
|
||||
devices = [device for device in ort.get_ep_devices()
|
||||
if device.ep_name == "vitisai" and str(device.device.type).endswith("NPU")]
|
||||
report["vitisai_npu_device_count"] = len(devices)
|
||||
report["status"] = "vitisai_session_creation_started"
|
||||
write_report(args.report, report)
|
||||
if not devices:
|
||||
raise RuntimeError("VitisAI EP did not expose an NPU device")
|
||||
options = ort.SessionOptions()
|
||||
options.add_provider_for_devices(devices, {})
|
||||
options.enable_profiling = True
|
||||
options.profile_file_prefix = str(args.profile_prefix)
|
||||
started = time.perf_counter()
|
||||
session = ort.InferenceSession(str(args.model), sess_options=options)
|
||||
report["vitisai_session_create_s"] = time.perf_counter() - started
|
||||
report["status"] = "vitisai_session_created"
|
||||
write_report(args.report, report)
|
||||
started = time.perf_counter()
|
||||
actual = session.run(None, {cpu_input.name: quantized})[0]
|
||||
report["vitisai_inference_s"] = time.perf_counter() - started
|
||||
if actual.shape != cpu_output.shape:
|
||||
raise ValueError("VitisAI prefix output shape changed")
|
||||
report["vitisai_output_finite"] = bool(np.isfinite(actual).all())
|
||||
report["relative_l2_vs_cpu"] = float(
|
||||
np.linalg.norm((actual - cpu_output).astype(np.float64))
|
||||
/ max(np.linalg.norm(cpu_output.astype(np.float64)), 1e-12))
|
||||
profile_path = Path(session.end_profiling())
|
||||
report["profile_file"] = str(profile_path)
|
||||
events = json.loads(profile_path.read_text(encoding="utf-8"))
|
||||
providers = [(event.get("args") or {}).get("provider") for event in events
|
||||
if event.get("cat") == "Node"]
|
||||
report["node_providers"] = dict(Counter(providers))
|
||||
report["status"] = (
|
||||
"npu_component_numeric_pass"
|
||||
if providers.count("vitisai") > 0
|
||||
and report["vitisai_output_finite"]
|
||||
and report["relative_l2_vs_cpu"] <= 0.01
|
||||
else "component_not_qualified"
|
||||
)
|
||||
write_report(args.report, report)
|
||||
print(json.dumps({"status": report["status"],
|
||||
"relative_l2_vs_cpu": report["relative_l2_vs_cpu"]}))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
extraction = subparsers.add_parser("extract")
|
||||
extraction.add_argument("--source", type=Path, required=True)
|
||||
extraction.add_argument("--expected-source-sha256", required=True)
|
||||
extraction.add_argument("--cut", type=int, required=True)
|
||||
extraction.add_argument("--input-tensor", action="append")
|
||||
extraction.add_argument("--output", type=Path, required=True)
|
||||
extraction.add_argument("--report", type=Path, required=True)
|
||||
execution = subparsers.add_parser("probe")
|
||||
execution.add_argument("--model", type=Path, required=True)
|
||||
execution.add_argument("--extraction-report", type=Path, required=True)
|
||||
execution.add_argument("--fixture", type=Path)
|
||||
execution.add_argument("--expected-fixture-sha256")
|
||||
execution.add_argument("--synthetic-input", action="store_true")
|
||||
execution.add_argument("--ep-dir", type=Path, required=True)
|
||||
execution.add_argument("--report", type=Path, required=True)
|
||||
execution.add_argument("--profile-prefix", type=Path, required=True)
|
||||
execution.add_argument("--cpu-only", action="store_true")
|
||||
args = parser.parse_args()
|
||||
(extract if args.command == "extract" else probe)(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -105,9 +105,10 @@ def main() -> None:
|
||||
if (not report["cpu_vs_retained_reference"]["finite"]
|
||||
or report["cpu_vs_retained_reference"]["relative_l2"] > 1e-4):
|
||||
raise ValueError("current ONNX CPU output differs from the retained reference")
|
||||
report["status"] = "cpu_reference_pass"
|
||||
args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
del cpu
|
||||
if args.cpu_only:
|
||||
report["status"] = "cpu_reference_pass"
|
||||
return
|
||||
|
||||
ep_dir = args.ep_dir.resolve(strict=True)
|
||||
@@ -124,6 +125,8 @@ def main() -> None:
|
||||
options.add_provider_for_devices(devices, {})
|
||||
options.enable_profiling = True
|
||||
options.profile_file_prefix = str(args.profile_prefix)
|
||||
report["status"] = "vitisai_session_creation_started"
|
||||
args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
npu_started = time.perf_counter()
|
||||
npu = ort.InferenceSession(str(args.model), sess_options=options)
|
||||
report["npu_load_s"] = time.perf_counter() - npu_started
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rewrite ONNX ConvTranspose1d as equivalent size-one-height ConvTranspose2d."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for block in iter(lambda: source.read(8 << 20), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source", type=Path, required=True)
|
||||
parser.add_argument("--expected-source-sha256", required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--report", type=Path, required=True)
|
||||
parser.add_argument("--fixture", type=Path)
|
||||
parser.add_argument("--expected-fixture-sha256")
|
||||
args = parser.parse_args()
|
||||
|
||||
import numpy as np
|
||||
import onnx
|
||||
import onnxruntime as ort
|
||||
|
||||
source_hash = sha256(args.source)
|
||||
if source_hash != args.expected_source_sha256:
|
||||
raise ValueError("source ONNX hash changed")
|
||||
model = onnx.load(args.source)
|
||||
weights = {initializer.name: initializer for initializer in model.graph.initializer}
|
||||
existing_names = {
|
||||
name
|
||||
for node in model.graph.node
|
||||
for name in (*node.input, *node.output)
|
||||
if name
|
||||
} | set(weights)
|
||||
axes_name = "__edge_convtranspose2d_axis2"
|
||||
if axes_name in existing_names:
|
||||
raise ValueError("rewrite tensor name collision")
|
||||
axes = onnx.helper.make_tensor(axes_name, onnx.TensorProto.INT64, [1], [2])
|
||||
model.graph.initializer.append(axes)
|
||||
|
||||
rewritten = []
|
||||
replacements = []
|
||||
for node in model.graph.node:
|
||||
if node.op_type != "ConvTranspose":
|
||||
replacements.append(node)
|
||||
continue
|
||||
attributes = {
|
||||
attr.name: onnx.helper.get_attribute_value(attr)
|
||||
for attr in node.attribute
|
||||
}
|
||||
kernel_shape = list(attributes.get("kernel_shape", []))
|
||||
if len(kernel_shape) != 1:
|
||||
replacements.append(node)
|
||||
continue
|
||||
if len(node.input) < 2 or len(node.output) != 1:
|
||||
raise ValueError("unexpected ConvTranspose input/output contract")
|
||||
weight = weights.get(node.input[1])
|
||||
if weight is None or len(weight.dims) != 3:
|
||||
raise ValueError("ConvTranspose1d weight is not an embedded rank-three initializer")
|
||||
original_dims = list(weight.dims)
|
||||
if original_dims[2] != kernel_shape[0]:
|
||||
raise ValueError("weight kernel shape changed")
|
||||
input_2d = node.input[0] + "__edge_2d"
|
||||
output_2d = node.output[0] + "__edge_2d"
|
||||
if input_2d in existing_names or output_2d in existing_names:
|
||||
raise ValueError("rewrite tensor name collision")
|
||||
existing_names.update((input_2d, output_2d))
|
||||
attributes["kernel_shape"] = [1, kernel_shape[0]]
|
||||
for name in ("strides", "dilations", "output_padding"):
|
||||
if name in attributes:
|
||||
attributes[name] = [1 if name != "output_padding" else 0, *attributes[name]]
|
||||
if "pads" in attributes:
|
||||
before, after = attributes["pads"]
|
||||
attributes["pads"] = [0, before, 0, after]
|
||||
del weight.dims[:]
|
||||
weight.dims.extend([original_dims[0], original_dims[1], 1, original_dims[2]])
|
||||
replacements.extend([
|
||||
onnx.helper.make_node(
|
||||
"Unsqueeze", [node.input[0], axes_name], [input_2d],
|
||||
name=node.name + "__edge_unsqueeze"),
|
||||
onnx.helper.make_node(
|
||||
"ConvTranspose", [input_2d, *node.input[1:]], [output_2d],
|
||||
name=node.name + "__edge_2d", **attributes),
|
||||
onnx.helper.make_node(
|
||||
"Squeeze", [output_2d, axes_name], list(node.output),
|
||||
name=node.name + "__edge_squeeze"),
|
||||
])
|
||||
rewritten.append({
|
||||
"node_name": node.name,
|
||||
"weight_name": node.input[1],
|
||||
"original_weight_dims": original_dims,
|
||||
"new_weight_dims": list(weight.dims),
|
||||
})
|
||||
if not rewritten:
|
||||
raise ValueError("source has no rank-one ConvTranspose to rewrite")
|
||||
del model.graph.node[:]
|
||||
model.graph.node.extend(replacements)
|
||||
onnx.checker.check_model(model)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
onnx.save(model, args.output)
|
||||
|
||||
source_session = ort.InferenceSession(str(args.source), providers=["CPUExecutionProvider"])
|
||||
rewritten_session = ort.InferenceSession(str(args.output), providers=["CPUExecutionProvider"])
|
||||
source_input = source_session.get_inputs()[0]
|
||||
rewritten_input = rewritten_session.get_inputs()[0]
|
||||
if source_input.shape != rewritten_input.shape:
|
||||
raise ValueError("rewritten graph changed input shape")
|
||||
if args.fixture is None:
|
||||
shape = source_input.shape
|
||||
if any(not isinstance(size, int) or size <= 0 for size in shape):
|
||||
raise ValueError("synthetic control requires static input shape")
|
||||
data = np.random.default_rng(42).standard_normal(shape).astype(np.float32)
|
||||
input_provenance = "synthetic fixed-seed normal"
|
||||
fixture_hash = None
|
||||
else:
|
||||
if args.expected_fixture_sha256 is None:
|
||||
raise ValueError("fixture hash required")
|
||||
fixture_hash = sha256(args.fixture)
|
||||
if fixture_hash != args.expected_fixture_sha256:
|
||||
raise ValueError("fixture hash changed")
|
||||
with np.load(args.fixture, allow_pickle=False) as fixture:
|
||||
if fixture.files != ["quantized"]:
|
||||
raise ValueError("fixture schema changed")
|
||||
data = np.ascontiguousarray(fixture["quantized"])
|
||||
input_provenance = "pinned real-weight vocoder fixture"
|
||||
expected = source_session.run(None, {source_input.name: data})[0]
|
||||
actual = rewritten_session.run(None, {rewritten_input.name: data})[0]
|
||||
if expected.shape != actual.shape:
|
||||
raise ValueError("rewritten graph changed output shape")
|
||||
error = actual.astype(np.float64) - expected.astype(np.float64)
|
||||
relative_l2 = float(
|
||||
np.linalg.norm(error) /
|
||||
max(np.linalg.norm(expected.astype(np.float64)), 1e-12))
|
||||
report = {
|
||||
"source_sha256": source_hash,
|
||||
"source_file": str(args.source.resolve()),
|
||||
"rewritten_sha256": sha256(args.output),
|
||||
"rewritten_file": str(args.output.resolve()),
|
||||
"fixture_sha256": fixture_hash,
|
||||
"input_provenance": input_provenance,
|
||||
"rewritten_nodes": rewritten,
|
||||
"input_shape": list(data.shape),
|
||||
"output_shape": list(actual.shape),
|
||||
"cpu_finite": bool(np.isfinite(actual).all()),
|
||||
"cpu_relative_l2_vs_source": relative_l2,
|
||||
"cpu_maximum_absolute_error": float(np.max(np.abs(error))),
|
||||
"status": "cpu_rewrite_parity_pass" if relative_l2 <= 1e-5 else "cpu_rewrite_parity_failed",
|
||||
}
|
||||
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({"status": report["status"], "rewritten_nodes": len(rewritten),
|
||||
"cpu_relative_l2_vs_source": relative_l2}))
|
||||
if report["status"] != "cpu_rewrite_parity_pass":
|
||||
raise ValueError("rewritten graph changed CPU output")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user