inference-kernels / scripts /check_workload_inputs.py
DongyunZou's picture
Keep only kernels real inference uses; add SGLang baselines and KDA configs
5f5a41c verified
Raw History Blame
5.93 kB
"""Validate native schemas and every captured tensor's shape, dtype and hash."""
import argparse
import hashlib
import inspect
import json
from pathlib import Path
import torch
from safetensors.torch import load_file
from flashinfer_bench.data import TraceSet
from flashinfer_bench.data.validate import (
scan_dataset, check_layout, check_definition_content, check_workload_content,
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
args = parser.parse_args()
root = args.root.resolve()
torch.set_num_threads(8)
dataset = TraceSet.from_path(str(root))
rows = [json.loads(line) for line in (root / 'captures.jsonl').read_text().splitlines()]
receipts = {row['uuid']: row for row in rows}
assert len(rows) == len(receipts), 'Duplicate capture UUID'
index = scan_dataset(root)
report = dict(definitions=len(dataset.definitions), workloads=0, tensors=0,
missing_capture_definitions=[], dataset_checks={}, errors=[])
checked = {}
def tensor(descriptor, definition):
path = descriptor['path']
assert Path(path).parent == Path('blob/workloads') / definition, path
if path in checked:
return checked[path]
value = load_file(str(root / path))[descriptor['tensor_key']]
digest = hashlib.sha256(json.dumps([str(value.dtype), list(value.shape)]).encode())
digest.update(memoryview(value.reshape(-1).view(torch.uint8).numpy()))
if digest.hexdigest() != Path(path).stem:
raise ValueError(f'Content hash mismatch: {path}')
checked[path] = (tuple(value.shape), str(value.dtype))
return checked[path]
def inspect_descriptors(value, definition):
if isinstance(value, dict):
if value.get('type') == 'safetensors':
tensor(value, definition)
else:
for child in value.values():
inspect_descriptors(child, definition)
elif isinstance(value, list):
for child in value:
inspect_descriptors(child, definition)
ids = set()
for name, definition in dataset.definitions.items():
namespace = {}
exec(compile(definition.reference, name, 'exec'), namespace)
assert list(inspect.signature(namespace['run']).parameters) == list(definition.inputs)
traces = dataset.workloads.get(name, [])
if not traces:
report['missing_capture_definitions'].append(name)
continue
item = index.definitions[name]
checks = dict(layout=check_layout(root, name, item, index.workloads.get(name), [], []),
definition=check_definition_content(name, item, disable_gpu=True),
workload=check_workload_content(name, item.definition, index.workloads.get(name), root))
report['dataset_checks'][name] = {key: value.model_dump() for key, value in checks.items()}
for check in checks.values():
report['errors'].extend(message.message for message in check.messages if message.level == 'error')
for trace in traces:
workload = trace.workload
assert workload.uuid not in ids, 'Duplicate workload UUID'
ids.add(workload.uuid)
assert workload.uuid in receipts, 'Missing capture provenance'
receipt = receipts[workload.uuid]
assert receipt['definition'] == name, 'Capture definition mismatch'
assert receipt['axes'] == workload.axes, 'Capture axes mismatch'
validation = receipt['validation']
assert validation['uuid'] == workload.uuid and validation['definition'] == name
assert validation['axes'] == workload.axes and validation['status'] == 'passed'
axes = dict(definition.const_axes, **workload.axes)
assert set(workload.inputs) == set(definition.inputs)
for constraint in definition.constraints:
# A constraint may also read inputs, e.g. cu_seqlens[-1].
scope = dict(axes)
for key in set(compile(constraint, name, 'eval').co_names) & set(definition.inputs):
descriptor = workload.inputs[key].model_dump()
scope[key] = (descriptor['value'] if descriptor['type'] == 'scalar' else
load_file(str(root / descriptor['path']))[descriptor['tensor_key']])
assert eval(constraint, {'__builtins__': {}}, scope), constraint
for key, spec in definition.inputs.items():
descriptor = workload.inputs[key].model_dump()
if spec.shape is None:
assert descriptor['type'] == 'scalar', (name, key)
else:
assert descriptor['type'] == 'safetensors', (name, key)
shape, dtype = tensor(descriptor, name)
assert shape == tuple(axes[dim] if isinstance(dim, str) else dim for dim in spec.shape), (name, key)
assert dtype == 'torch.' + spec.dtype.value, (name, key)
inspect_descriptors(receipt, name)
report['workloads'] += 1
assert ids == set(receipts), 'Provenance and workload UUID sets differ'
assert set(checked) == {p.relative_to(root).as_posix()
for p in (root / 'blob').rglob('*.safetensors')}, 'Unreferenced tensor files'
report['tensors'] = len(checked)
(root / 'results').mkdir(exist_ok=True)
(root / 'results/workload_validation.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps({key: value for key, value in report.items() if key != 'dataset_checks'}, indent=2))
if report['errors']:
raise RuntimeError('Native dataset validation failed')
if __name__ == '__main__':
main()