File size: 5,930 Bytes
65e1c10 86b22af 65e1c10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | """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()
|