KrokoMusci-OpenASR / preflight_model.py
Banafo's picture
Add KrokoMusci Open ASR H200 benchmark
7966eff verified
Raw History Blame Contribute Delete
20.8 kB
"""CPU validation of the Kroko ONNX distribution contract.
Requires fast-gpu-asr 0.2.0 waveform graphs (including its custom operators),
not arbitrary Icefall exports. No source checkpoint is loaded. config.json is
used to locate and validate every runtime asset.
"""
import hashlib
import json
import math
import os
import re
import shutil
import tempfile
from pathlib import Path, PurePosixPath
FORMAT = "kroko-fast-gpu-asr-onnx-v1"
FAST_GPU_ASR_VERSION = "0.2.0"
MODEL_SUBFOLDER = "fast-gpu-asr"
ASSET_NAMES = {"encoder", "decoder", "predictor_contexts", "tokenizer"}
PROFILE_NAMES = ("min_audio_seconds", "opt_audio_seconds", "max_audio_seconds")
INT32_MAX = (1 << 31) - 1
ZIPFORMER_PLUGIN_OPS = frozenset({
"zipformer_attention_value", "zipformer_convolution", "zipformer_downsample",
"zipformer_feature_extractor", "zipformer_output_assembly",
"zipformer_relative_attention", "zipformer_upsample_bypass",
})
_VALIDATION_PLUGIN_DOMAIN = "fast_gpu_asr_plugins"
def safe_relative(name):
"""Restrict Hub paths and ONNX external-data locations to literal paths."""
if (not isinstance(name, str) or not name or "\\" in name
or any(c in name for c in (":", "\x00", "*", "?", "[", "]"))
or any(part in ("", ".", "..") for part in name.split("/"))
or PurePosixPath(name).is_absolute()):
raise ValueError(f"Unsafe repository-relative path: {name!r}")
if PurePosixPath(name).suffix.lower() in {".pt", ".pth", ".pkl", ".pickle"}:
raise ValueError("Published assets must not contain PyTorch/pickle files")
return name
def _positive_int(value, name, maximum=INT32_MAX):
if type(value) is not int or not 1 <= value <= maximum:
raise ValueError(f"{name} must be a positive integer <= {maximum}")
def _finite_float(value, name):
if type(value) not in (float, int) or not math.isfinite(value):
raise ValueError(f"{name} must be a finite number")
return float(value)
def validate_config(config):
"""Validate the JSON contract without importing CUDA-dependent packages."""
if type(config) is not dict or config.get("format") != FORMAT:
raise ValueError(f"config.json format must be {FORMAT}")
if config.get("fast_gpu_asr_version") != FAST_GPU_ASR_VERSION:
raise ValueError(f"ONNX package must target fast-gpu-asr {FAST_GPU_ASR_VERSION}")
if not isinstance(config.get("language"), str) or not re.fullmatch(
r"[a-z]{2,3}(?:-[A-Za-z0-9]+)*", config["language"]
):
raise ValueError("config.json requires a language code, for example en")
assets, files = config.get("assets"), config.get("files")
if type(assets) is not dict or set(assets) != ASSET_NAMES:
raise ValueError(f"assets must define exactly {sorted(ASSET_NAMES)}")
if type(files) is not dict or not files:
raise ValueError("files must contain the asset SHA256/bytes manifest")
for name, info in files.items():
safe_relative(name)
if name == "config.json" or type(info) is not dict:
raise ValueError("The asset manifest excludes config.json itself")
if set(info) != {"sha256", "bytes"} or not re.fullmatch(r"[0-9a-f]{64}", str(info.get("sha256", ""))):
raise ValueError(f"Invalid SHA256/bytes entry for {name}")
_positive_int(info.get("bytes"), f"{name} bytes", maximum=1 << 44)
for kind, name in assets.items():
safe_relative(name)
if name not in files:
raise ValueError(f"Asset absent from files manifest: {name}")
suffix = {"encoder": ".onnx", "decoder": ".onnx",
"predictor_contexts": ".npy", "tokenizer": ".model"}[kind]
if not name.endswith(suffix):
raise ValueError(f"{kind} must be a {suffix} asset")
if len(set(assets.values())) != len(assets):
raise ValueError("Each asset must have a distinct path")
runtime, export = config.get("runtime_config"), config.get("export")
if type(runtime) is not dict or type(export) is not dict:
raise ValueError("runtime_config and export must be objects")
if runtime.get("model_type") != "zipformer_asr" or runtime.get(
"decoder_type"
) != "transducer_modified_beam_search":
raise ValueError("Expected the fast-gpu-asr Zipformer RNN-T beam-search runtime")
encoder, decoder = runtime.get("audio_encoder_params"), runtime.get("decoder_params")
if type(encoder) is not dict or type(decoder) is not dict:
raise ValueError("Missing encoder/decoder runtime settings")
if encoder.get("use_ctc") is not False:
raise ValueError("The public ONNX package must disable CTC")
for name in ("model_samplerate", "vocab_size"):
_positive_int(runtime.get(name), name)
if runtime["model_samplerate"] != 16000:
raise ValueError("This evaluation adapter requires model_samplerate=16000")
for name in ("feature_dim", "frame_shift_ms", "subsampling_factor", "pos_emb_max_len", "output_dim"):
_positive_int(encoder.get(name), name)
for name in ("beam", "context_size", "decoder_dim", "joiner_dim"):
_positive_int(decoder.get(name), name)
if decoder["context_size"] > 2:
raise ValueError("This release requires context_size 1 or 2")
if decoder["beam"] > runtime["vocab_size"]:
raise ValueError("Beam must not exceed vocabulary size")
if encoder["output_dim"] != decoder["joiner_dim"]:
raise ValueError("Encoder output and joiner dimensions must match")
for name in ("encoder_dims", "num_encoder_layers", "downsampling_factors", "feedforward_dims"):
values = encoder.get(name)
if type(values) is not list or len(values) != 6:
raise ValueError(f"{name} must contain six positive integers")
for value in values:
_positive_int(value, name)
dims = encoder["encoder_dims"]
if not dims[0] <= dims[1] <= dims[2] <= dims[3] >= dims[4] >= dims[5]:
raise ValueError("Invalid Zipformer encoder dimension progression")
blank = runtime.get("blank_id")
if type(blank) is not int or not 0 <= blank < runtime["vocab_size"]:
raise ValueError("Invalid blank_id")
padding = encoder.get("right_padding_samples")
if type(padding) is not int or not 0 <= padding <= INT32_MAX:
raise ValueError("Invalid right_padding_samples")
_positive_int(export.get("batch_size"), "batch_size")
if export.get("beam") != decoder["beam"]:
raise ValueError("Export beam does not match the runtime")
penalty = _finite_float(export.get("blank_penalty"), "blank_penalty")
if abs(penalty) > 3.4028234663852886e38 or penalty != decoder.get("blank_penalty"):
raise ValueError("Export blank_penalty does not match the runtime")
for name in ("encoder_precision", "decoder_precision"):
if export.get(name) not in {"fp16", "fp32", "bf16"}:
raise ValueError(f"Invalid {name}")
durations = tuple(_finite_float(export.get(n), n) for n in PROFILE_NAMES)
if not 0 < durations[0] <= durations[1] <= durations[2]:
raise ValueError("Expected 0 < min <= opt <= max audio seconds")
for name, value in zip(PROFILE_NAMES, durations):
if encoder.get(name) != value:
raise ValueError(f"Export {name} does not match the runtime")
max_samples = round(durations[-1] * runtime["model_samplerate"]) + padding
if max_samples > INT32_MAX or round(durations[0] * runtime["model_samplerate"]) < 1:
raise ValueError("Audio profile exceeds supported sample indexing")
if (runtime["vocab_size"] + 1) ** decoder["context_size"] * decoder["joiner_dim"] > INT32_MAX:
raise ValueError("Predictor lookup exceeds signed 32-bit indexing")
if export["batch_size"] * decoder["beam"] * max(runtime["vocab_size"], decoder["joiner_dim"]) > INT32_MAX:
raise ValueError("Decoder tensors exceed signed 32-bit indexing")
return config
def read_config(path):
if path.stat().st_size > 1024 * 1024:
raise ValueError("config.json exceeds the one MiB metadata limit")
def invalid_constant(value):
raise ValueError(f"Non-finite JSON number: {value}")
return validate_config(json.loads(path.read_text(), parse_constant=invalid_constant))
def file_receipt(path):
with path.open("rb") as handle:
digest = hashlib.file_digest(handle, "sha256").hexdigest()
return {"sha256": digest, "bytes": path.stat().st_size}
def _all_messages(message, message_class):
"""Walk protobuf children, including nested graphs and local functions."""
if isinstance(message, message_class):
yield message
for descriptor, value in message.ListFields():
if descriptor.type == descriptor.TYPE_MESSAGE:
if descriptor.is_repeated:
for child in value:
yield from _all_messages(child, message_class)
else:
yield from _all_messages(value, message_class)
def _check_onnx_model(path, model):
"""Check standard ONNX structure while recognizing the upstream TRT plugins.
fast-gpu-asr 0.2.0 emits its TensorRT plugins in ONNX's default domain.
check_custom_domain=False alone therefore still asks ONNX for nonexistent
standard schemas. Move only the seven known, namespace-verified operators
to a private domain in a validation copy. The published graph remains
unchanged, and TensorRT must validate the plugin operations on the GPU.
"""
import onnx
plugins = [node for node in _all_messages(model, onnx.NodeProto)
if not node.domain and node.op_type in ZIPFORMER_PLUGIN_OPS]
if not plugins:
onnx.checker.check_model(str(path), check_custom_domain=False)
return
for node in plugins:
namespaces = [attribute for attribute in node.attribute
if attribute.name == "plugin_namespace"]
if (len(namespaces) != 1 or namespaces[0].type != onnx.AttributeProto.STRING
or namespaces[0].s != b"fast_gpu_asr"):
raise ValueError(f"Unexpected TensorRT plugin namespace for {node.op_type}")
validation_model = onnx.ModelProto()
validation_model.CopyFrom(model)
for node in _all_messages(validation_model, onnx.NodeProto):
if not node.domain and node.op_type in ZIPFORMER_PLUGIN_OPS:
node.domain = _VALIDATION_PLUGIN_DOMAIN
# Functions have their own opset imports. Add the validation domain to all
# scopes so the same checks apply if an exporter nests plugin operations.
for scope in (validation_model, *validation_model.functions):
existing = [item for item in scope.opset_import
if item.domain == _VALIDATION_PLUGIN_DOMAIN]
if existing:
raise ValueError("Reserved ONNX validation domain already present")
scope.opset_import.append(onnx.helper.make_opsetid(_VALIDATION_PLUGIN_DOMAIN, 1))
# Keep the copy beside the graph: external-data locations and offsets must
# resolve against the same regular files, without loading/copying weights.
with tempfile.NamedTemporaryFile(dir=Path(path).parent,
prefix=".onnx-validation-", suffix=".onnx",
delete=False) as handle:
temporary = Path(handle.name)
try:
temporary.write_bytes(validation_model.SerializeToString())
onnx.checker.check_model(str(temporary), check_custom_domain=False)
finally:
temporary.unlink(missing_ok=True)
def validate_graph(path, name, config, root):
import onnx
graph = onnx.load(str(path), load_external_data=False)
external_files = set()
for tensor in _all_messages(graph, onnx.TensorProto):
if tensor.data_location != onnx.TensorProto.EXTERNAL:
if tensor.external_data:
raise ValueError("Unexpected ONNX external-data metadata")
continue
metadata = {item.key: item.value for item in tensor.external_data}
if len(metadata) != len(tensor.external_data) or not set(metadata) <= {"location", "offset", "length", "checksum"}:
raise ValueError("Unsupported ONNX external-data metadata")
location = safe_relative(metadata.get("location"))
relative = safe_relative(str(PurePosixPath(name).parent / location))
if relative not in config["files"]:
raise ValueError(f"ONNX external data absent from manifest: {relative}")
size = (root / relative).stat().st_size
for field in ("offset", "length"):
if field in metadata and not re.fullmatch(r"[0-9]+", metadata[field]):
raise ValueError(f"Invalid ONNX external-data {field}")
offset = int(metadata.get("offset", "0"))
length = int(metadata.get("length", str(size - offset)))
if offset < 0 or length < 0 or offset + length > size:
raise ValueError("ONNX external-data slice exceeds the declared file")
external_files.add(relative)
# Path-based checking supports models larger than 2 GB via external data.
# Plugin semantics are additionally validated by TensorRT on the target GPU.
_check_onnx_model(path, graph)
if graph.training_info:
raise ValueError("Inference graph must not contain ONNX training state")
def specs(values):
result = {}
for value in values:
tensor_type = value.type.tensor_type
result[value.name] = {
"dtype": tensor_type.elem_type,
"shape": [dim.dim_value if dim.HasField("dim_value") else None
for dim in tensor_type.shape.dim],
}
return result
inputs, outputs = specs(graph.graph.input), specs(graph.graph.output)
batch, runtime = config["export"]["batch_size"], config["runtime_config"]
joiner = runtime["decoder_params"]["joiner_dim"]
def require(values, key, shape, dtypes):
if key not in values or values[key]["shape"] != shape or values[key]["dtype"] not in dtypes:
raise ValueError(f"Incompatible ONNX tensor {key}: expected shape {shape}, dtype {dtypes}")
if name == config["assets"]["encoder"]:
if set(inputs) != {"audio", "audio_lengths"} or set(outputs) != {"encoder_output", "encoder_output_lengths"}:
raise ValueError("Encoder ONNX input/output names do not match fast-gpu-asr")
require(inputs, "audio", [batch, None], {onnx.TensorProto.FLOAT})
require(inputs, "audio_lengths", [batch], {onnx.TensorProto.INT64})
require(outputs, "encoder_output", [batch, None, joiner], {onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16, onnx.TensorProto.BFLOAT16})
require(outputs, "encoder_output_lengths", [batch], {onnx.TensorProto.INT32})
else:
capacity = batch * config["export"]["beam"]
dtype = {"fp32": onnx.TensorProto.FLOAT, "fp16": onnx.TensorProto.FLOAT16,
"bf16": onnx.TensorProto.BFLOAT16}[config["export"]["decoder_precision"]]
if set(inputs) != {"decoder_input", "encoder_output"} or set(outputs) != {"tokens_log_prob"}:
raise ValueError("Decoder ONNX input/output names do not match fast-gpu-asr")
for key in inputs:
require(inputs, key, [capacity, joiner], {dtype})
require(outputs, "tokens_log_prob", [capacity, runtime["vocab_size"]], {onnx.TensorProto.FLOAT})
return {"inputs": inputs, "outputs": outputs}, external_files
def validate_contexts(path, config):
import numpy as np
contexts = np.load(path, mmap_mode="r", allow_pickle=False)
runtime = config["runtime_config"]
decoder = runtime["decoder_params"]
shape = ((runtime["vocab_size"] + 1) ** decoder["context_size"], decoder["joiner_dim"])
precision = config["export"]["decoder_precision"]
dtype = {"fp16": np.dtype("<f2"), "fp32": np.dtype("<f4"), "bf16": np.dtype("<u2")}[precision]
if not isinstance(contexts, np.ndarray) or contexts.shape != shape or contexts.dtype != dtype or not contexts.flags.c_contiguous:
raise ValueError(f"Predictor NPY must be C-contiguous {dtype} with shape {shape}")
for start in range(0, len(contexts), 8192):
chunk = contexts[start:start + 8192]
finite = ((chunk & 0x7F80) != 0x7F80).all() if precision == "bf16" else np.isfinite(chunk).all()
if not finite:
raise ValueError("Predictor NPY contains non-finite values")
return {"shape": list(shape), "dtype": str(dtype), "precision": precision}
def validate_tokenizer(path, config):
import sentencepiece as spm
tokenizer = spm.SentencePieceProcessor(model_file=str(path))
vocab = tokenizer.vocab_size()
if tokenizer.unk_id() == vocab - 1:
vocab -= 1
runtime = config["runtime_config"]
blank = tokenizer.piece_to_id("<blk>")
if vocab != runtime["vocab_size"] or blank != runtime["blank_id"] or tokenizer.id_to_piece(blank) != "<blk>":
raise ValueError("Tokenizer vocabulary/blank ID does not match the ONNX package")
def validate_directory(root, config=None):
"""Return a public-safe receipt after hashing and checking every asset."""
root = Path(root)
config = read_config(root / "config.json") if config is None else validate_config(config)
files = {"config.json": file_receipt(root / "config.json")}
for name, expected in config["files"].items():
path = root / name
if not path.is_file():
raise ValueError(f"Missing release asset: {name}")
files[name] = file_receipt(path)
if files[name] != expected:
raise ValueError(f"Release asset digest/size mismatch: {name}")
graphs, dependencies = {}, set(config["assets"].values())
for kind in ("encoder", "decoder"):
name = config["assets"][kind]
graphs[kind], external = validate_graph(root / name, name, config, root)
dependencies.update(external)
if dependencies != set(config["files"]):
raise ValueError("Manifest contains files unused by the inference assets")
contexts = validate_contexts(root / config["assets"]["predictor_contexts"], config)
validate_tokenizer(root / config["assets"]["tokenizer"], config)
return {"format": FORMAT, "language": config["language"],
"model_samplerate": config["runtime_config"]["model_samplerate"],
"fast_gpu_asr_version": FAST_GPU_ASR_VERSION, "export": config["export"],
"files": files, "graphs": graphs, "predictor_contexts": contexts}
def _materialize_hub_links(root, names):
"""ONNX's external-data checker rejects symlinks and multiply linked files.
The Hub's local_dir mode normally creates regular files already. Handle any
older cache links with atomic private copies, never modifying their targets.
Call only inside the dedicated release-cache lock, not the shared Hub cache.
"""
for name in names:
path = root / name
if not path.is_symlink() and path.stat().st_nlink == 1:
continue
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=".materializing-", delete=False) as file:
temporary = Path(file.name)
try:
shutil.copyfile(path, temporary)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def download_release(model_id, revision):
from filelock import FileLock
from huggingface_hub import hf_hub_download, snapshot_download
if not re.fullmatch(r"[0-9a-f]{40}", revision):
raise ValueError("Use the immutable Hub commit SHA for --model-revision")
config_path = Path(hf_hub_download(model_id, "config.json", subfolder=MODEL_SUBFOLDER,
revision=revision))
config = read_config(config_path)
names = ["config.json", *config["files"]]
cache = Path(os.environ.get("KROKO_ONNX_CACHE", str(Path(tempfile.gettempdir()) / "kroko-onnx-model-cache")))
cache.mkdir(parents=True, exist_ok=True)
key = hashlib.sha256(f"{model_id}@{revision}/{MODEL_SUBFOLDER}".encode()).hexdigest()
# Stable local_dir avoids Hub snapshot symlinks for external ONNX weights,
# and avoids copying multi-GB assets again for every dataset subprocess.
with FileLock(str(cache / f"{key}.lock")):
snapshot = Path(snapshot_download(model_id, revision=revision, local_dir=cache / key,
allow_patterns=[f"{MODEL_SUBFOLDER}/{name}" for name in names]))
root = snapshot / MODEL_SUBFOLDER
_materialize_hub_links(root, names)
receipt = validate_directory(root, config)
receipt.update(model_id=model_id, revision=revision, model_subfolder=MODEL_SUBFOLDER)
return root, config, receipt
def check_release(model_id, revision):
return download_release(model_id, revision)[2]