"""Same frozen logit thresholds in real Chrome/WebGPU; exact tokenizer check.""" import hashlib import argparse import json from pathlib import Path import time import urllib.request import numpy as np ROOT = Path(r'D:\webbrain-training\compass-tiny-v3-spark-x25-20260926\onnx-v3') URL = 'http://127.0.0.1:8561' def post(route, payload): request = urllib.request.Request(URL + route, data=json.dumps(payload).encode(), headers={'Content-Type': 'application/json'}) with urllib.request.urlopen(request, timeout=600) as response: return json.load(response) def main(): global ROOT parser = argparse.ArgumentParser() parser.add_argument('--root', type=Path, default=ROOT) parser.add_argument('--run-tag', default='browser-v5') args = parser.parse_args() ROOT = args.root assert json.loads((ROOT / 'numerical-validation.json').read_text())['passed'] ready = json.loads((ROOT / args.run_tag / 'ready.json').read_text()) assert ready['ready'] and ready['gpuInfo']['architecture'] == 'blackwell' checks, templates, smoke = [], [], [] cases = json.loads((ROOT / 'fixtures.json').read_text()) # The reference recorder used insertion-ordered tools, but write_json sorted # all dictionary keys on disk. Restore the declared original fixture order; # never modify saved token IDs or model outputs to obtain a match. for case in cases: if case['name'] == 'native_tool': original = {'type': 'function', 'function': {'name': 'open_url', 'description': 'Open a URL in the browser.', 'parameters': {'type': 'object', 'properties': {'url': {'type': 'string'}}, 'required': ['url']}}} assert original == case['tools'][0] case['tools'] = [original] for case in cases: if case['name'] != 'sliding_boundary_513': template = post('/template', {'messages': case['messages'], 'tools': case['tools']}) same = template['ids'] == case['inputIds'] templates.append({'case': case['name'], 'tokenIdsIdentical': same}) if not same: raise RuntimeError('JS/Python native-tokenizer mismatch') result = post('/infer', case) for step, values in enumerate(result['logits']): got = np.array(values, dtype=np.float64) expected = np.load(ROOT / 'reference' / f'{case["name"]}-{step}.npy').astype(np.float64) relative = float(np.linalg.norm(got - expected) / np.linalg.norm(expected)) cosine = float(np.dot(got, expected) / (np.linalg.norm(got) * np.linalg.norm(expected))) check = {'case': case['name'], 'step': step, 'relativeRms': relative, 'cosine': cosine, 'finite': bool(np.isfinite(got).all()), 'bf16Argmax': int(expected.argmax()), 'webgpuArgmax': int(got.argmax())} checks.append(check) print(json.dumps(check), flush=True) for case in cases[:2]: start = time.monotonic() output = post('/v1/chat/completions', {'model': 'webbrain-compass-tiny-v3-onnx-fp16', 'messages': case['messages'], 'tools': case['tools'], 'max_tokens': 96, 'temperature': 0, 'stream': False}) smoke.append({'case': case['name'], 'seconds': time.monotonic() - start, 'result': output}) print(json.dumps({'generationSmoke': smoke[-1]}), flush=True) passed = all(c['finite'] and c['relativeRms'] <= .02 and c['cosine'] >= .999 for c in checks) report = {'passed': passed, 'checks': checks, 'templates': templates, 'generationSmoke': smoke, 'thresholds': {'relativeRmsMax': .02, 'cosineMin': .999}, 'browser': ready['browser'], 'runtime': ready['runtime'], 'gpu': ready['gpuInfo'], 'precision': ready['precision'], 'cloudFallback': False, 'interpretation': 'Runtime/numerical smoke only; not an agent benchmark'} with (ROOT / 'browser-validation.json').open('x', encoding='utf-8') as f: json.dump(report, f, indent=2) if not passed: raise RuntimeError('Real WebGPU numerical validation failed; do not publish') print(json.dumps({'passed': True, 'cases': len(checks), 'maximumRelativeRms': max(c['relativeRms'] for c in checks)}), flush=True) if __name__ == '__main__': main()