Download examples/run_examples.py from susun-123/kern-kernels: direct link, hf CLI and curl.
- Browser
- Download file 3.94 kB
-
https://huggingface.co/datasets/susun-123/kern-kernels/resolve/main/examples/run_examples.py
- Command line
-
hf download hf://datasets/susun-123/kern-kernels/examples/run_examples.py
-
curl -L -o run_examples.py https://huggingface.co/datasets/susun-123/kern-kernels/resolve/main/examples/run_examples.py
3.94 kB
| #!/usr/bin/env python3 | |
| """Run all three downloaded JSON examples against FlashInfer, without weights.""" | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import subprocess | |
| import tempfile | |
| import flashinfer | |
| import torch | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--runner', type=Path, required=True) | |
| parser.add_argument('--cubins', type=Path, required=True) | |
| parser.add_argument('--gpu', type=int, default=0) | |
| parser.add_argument('--output', type=Path, default=Path('example-results.json')) | |
| args = parser.parse_args() | |
| torch.cuda.set_device(args.gpu) | |
| torch.set_grad_enabled(False) | |
| torch.manual_seed(20260907) | |
| directory = Path(__file__).resolve().parent | |
| results = [] | |
| for name, qlen in [('decode', 1), ('prefill', 129), ('verify', 8)]: | |
| manifest_path = directory / f'{name}.json' | |
| manifest = json.loads(manifest_path.read_text()) | |
| q = torch.randn(manifest['buffers']['q']['shape'], device='cuda', dtype=torch.bfloat16) | |
| kv = torch.randn(22, 2, 64, 4, 2, 256, device='cuda', dtype=torch.bfloat16) | |
| table = torch.randperm(22, device='cuda', dtype=torch.int32).view(2, 11) | |
| seq = torch.tensor([385, 641], device='cuda', dtype=torch.int32) | |
| cuq = torch.arange(3, device='cuda', dtype=torch.int32) * qlen | |
| cuk = torch.tensor([0, 385, 1026], device='cuda', dtype=torch.int32) | |
| workspace = torch.zeros(256 * 1024 * 1024, device='cuda', dtype=torch.uint8) | |
| common = dict(query=q[:2 * qlen], kv_cache=(kv[:, 1, :, :, 0], kv[:, 1, :, :, 1]), | |
| workspace_buffer=workspace, block_tables=table, seq_lens=seq, | |
| bmm1_scale=1 / 16, bmm2_scale=1., kv_layout='NHD', enable_pdl=False) | |
| if name == 'decode': | |
| expected = flashinfer.decode.trtllm_batch_decode_with_kv_cache( | |
| **common, max_seq_len=641, backend='trtllm-gen') | |
| else: | |
| expected = flashinfer.prefill.trtllm_batch_context_with_kv_cache( | |
| **common, max_q_len=qlen, max_kv_len=641, batch_size=2, | |
| cum_seq_lens_q=cuq, cum_seq_lens_kv=cuk, causal=True) | |
| expected = expected.cpu().float() | |
| with tempfile.TemporaryDirectory() as tmp: | |
| tmp = Path(tmp) | |
| cmd = [str(args.runner.resolve()), '--gpu', str(args.gpu), | |
| '--manifest', str(manifest_path), '--cubins', str(args.cubins.resolve()), | |
| '--env', 'seqs=2', '--env', f'tokens={2 * qlen}', '--graph', '--iters', '9', | |
| '--out', f'out={tmp}/out.bin'] | |
| for key, tensor in dict(q=q, kv=kv, table=table, seq=seq, cuq=cuq).items(): | |
| (tmp / f'{key}.bin').write_bytes(tensor.contiguous().view(torch.uint8).cpu().numpy().tobytes()) | |
| cmd += ['--in', f'{key}={tmp}/{key}.bin'] | |
| completed = subprocess.run(cmd, capture_output=True, text=True, timeout=120) | |
| if completed.returncode: | |
| raise RuntimeError(completed.stderr) | |
| data = bytearray((tmp / 'out.bin').read_bytes()) | |
| actual = torch.frombuffer(data, dtype=torch.bfloat16)[:2 * qlen * 24 * 256].reshape_as(expected).float() | |
| delta = actual - expected | |
| relative_l2 = (delta.norm() / expected.norm().clamp_min(1e-12)).item() | |
| max_abs = delta.abs().max().item() | |
| passed = bool(torch.isfinite(actual).all()) and relative_l2 < .02 and max_abs < .02 | |
| row = dict(example=name, batch=2, query_tokens=qlen, passed=passed, | |
| bit_exact=torch.equal(actual, expected), relative_l2=relative_l2, max_abs=max_abs) | |
| print(json.dumps(row), flush=True) | |
| results.append(row) | |
| if not passed: | |
| raise AssertionError(row) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(results, indent=2) + '\n') | |
| if __name__ == '__main__': | |
| main() | |