Download provenance/scripts/export_spark.py from webbrain-one/webbrain-compass-tiny-xs-v3-onnx: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/webbrain-one/webbrain-compass-tiny-xs-v3-onnx/resolve/main/provenance/scripts/export_spark.py
- Command line
-
hf download hf://webbrain-one/webbrain-compass-tiny-xs-v3-onnx/provenance/scripts/export_spark.py
-
curl -L -o export_spark.py https://huggingface.co/webbrain-one/webbrain-compass-tiny-xs-v3-onnx/resolve/main/provenance/scripts/export_spark.py
12.1 kB
| """Spark-native cached ONNX export; no architecture remapping or retraining.""" | |
| import argparse | |
| import hashlib | |
| import importlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import sys | |
| import time | |
| SOURCE = Path(__file__).parents[1] / 'spark_x25_17b_webbrain_compass_v3' | |
| sys.path.insert(0, str(SOURCE)) | |
| from prepare import sha, write_json | |
| from train import gpu_guard | |
| import torch | |
| ROOT = Path(r'D:\webbrain-training\compass-tiny-v3-spark-x25-20260926\onnx-v3') | |
| MODEL = ROOT.parent / 'release-compat-v3' | |
| CFG = json.loads((SOURCE / 'train-config.json').read_text()) | |
| def event(stage, **fields): | |
| record = {'stage': stage, 'unixTime': time.time(), **fields} | |
| with (ROOT / 'events.jsonl').open('a', encoding='utf-8') as f: | |
| f.write(json.dumps(record) + '\n') | |
| f.flush() | |
| os.fsync(f.fileno()) | |
| print(json.dumps(record), flush=True) | |
| class TensorCache: | |
| def __init__(self, past): | |
| self.past = past | |
| self.present = [] | |
| def update(self, k, v, layer_idx, cache_kwargs): | |
| k = torch.cat((self.past[2 * layer_idx], k), dim=2) | |
| v = torch.cat((self.past[2 * layer_idx + 1], v), dim=2) | |
| self.present.extend((k, v)) | |
| return k, v | |
| class CachedSpark(torch.nn.Module): | |
| """Use original decoder layers, norms, gates and RoPE; tensor-only cache.""" | |
| def __init__(self, model): | |
| super().__init__() | |
| self.native = model | |
| self.helpers = importlib.import_module(model.__class__.__module__) | |
| self.config = model.config | |
| def forward(self, input_ids, position_ids, *past): | |
| c = self.config | |
| hidden = self.native.model.embedding(input_ids).float() | |
| cache = TensorCache(past) | |
| keys = torch.arange(past[0].shape[2] + input_ids.shape[1], device=input_ids.device) | |
| queries = position_ids.reshape(-1) | |
| causal = queries[:, None] >= keys[None, :] | |
| sliding = causal & (keys[None, :] > queries[:, None] - c.sliding_window) | |
| dtype = self.native.model.embedding.weight.dtype | |
| masks = {name: torch.where(allowed, 0., torch.finfo(dtype).min).to(dtype)[None, None] | |
| for name, allowed in [('full_attention', causal), ('sliding_attention', sliding)]} | |
| ropes = {} | |
| for layer_type in ['full_attention', 'sliding_attention']: | |
| ropes[layer_type] = self.helpers.compute_rope_cos_sin(queries, c.head_dim, c.get_rope_theta(layer_type), | |
| c.get_partial_rotary_factor(layer_type), device=input_ids.device) | |
| for layer in self.native.model.layers: | |
| hidden = layer(hidden, position_embeddings=ropes[layer.layer_type], | |
| attention_mask=masks[layer.layer_type], past_key_values=cache, | |
| cache_position=queries, position_ids=position_ids) | |
| hidden = self.native.model.norm(hidden).to(dtype)[:, -1:, :] | |
| logits = torch.nn.functional.linear(hidden, self.native.model.embedding.weight).float() | |
| return (logits, *cache.present) | |
| def empty_past(c, device='cpu'): | |
| return [torch.empty(1, c.num_key_value_heads, 0, c.head_dim, dtype=torch.float16, device=device) | |
| for _ in range(2 * c.num_hidden_layers)] | |
| def make_contract(): | |
| ROOT.mkdir(exist_ok=True) | |
| proof = json.loads((MODEL / 'provenance/release-validation.json').read_text()) | |
| assert proof['passed'] and proof['cachedGenerationPassed'] | |
| inventory = [{'path': p.relative_to(MODEL).as_posix(), 'sha256': sha(p), 'bytes': p.stat().st_size} | |
| for p in MODEL.glob('*') if p.is_file() and p.suffix in ('.json', '.safetensors', '.py', '.jinja')] | |
| plan = {'source': str(MODEL), 'sourceFiles': inventory, 'exportScriptSha256': sha(__file__), | |
| 'sourcePrecision': 'BF16', 'firstTarget': 'FP16 ONNX, FP32 residual/norm/RoPE/softmax', | |
| 'cache': '28 pairs of [1,2,past_length,256] FP16 tensors; full storage, exact SW512 mask', | |
| 'lastTokenLogitsOnly': True, 'nativeArchitectureChanged': False, | |
| 'gates': {'relativeRmsMax': .02, 'cosineMin': .999, 'finiteRequired': True, | |
| 'prefillAndCachedDecodeRequired': True, 'browserWebgpuRequired': True}, | |
| 'fixtureSelection': 'Fixed plain, native-tool, and 513-token sliding-boundary prompts before ONNX results'} | |
| target = ROOT / 'contract.json' | |
| if target.exists(): | |
| assert json.loads(target.read_text()) == plan, 'Frozen ONNX contract drift' | |
| else: | |
| write_json(target, plan) | |
| def reference(): | |
| make_contract() | |
| gpu_guard(CFG) | |
| from transformers import AutoTokenizer | |
| import runtime | |
| torch.set_num_threads(8) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL, local_files_only=True) | |
| model = runtime.load_native(str(MODEL), dtype=torch.bfloat16, device_map={'': 0}).eval() | |
| tools = [{'type': 'function', 'function': {'name': 'open_url', 'description': 'Open a URL in the browser.', | |
| 'parameters': {'type': 'object', 'properties': {'url': {'type': 'string'}}, 'required': ['url']}}}] | |
| prompts = [ | |
| {'name': 'plain', 'messages': [{'role': 'user', 'content': 'In one sentence, what does a browser do?'}], 'tools': None}, | |
| {'name': 'native_tool', 'messages': [{'role': 'system', 'content': 'Use the provided tool when asked to open a page.'}, | |
| {'role': 'user', 'content': 'Open https://example.com with open_url.'}], 'tools': tools}, | |
| {'name': 'sliding_boundary_513', 'messages': [{'role': 'user', 'content': 'Reference facts: ' + 'browser web page. ' * 180 + ' Summarize briefly.'}], 'tools': None}, | |
| ] | |
| fixtures = [] | |
| (ROOT / 'reference').mkdir(exist_ok=True) | |
| import numpy as np | |
| for case in prompts: | |
| encoded = tokenizer.apply_chat_template(case['messages'], tools=case['tools'], enable_thinking=False, | |
| add_generation_prompt=True, tokenize=True, return_tensors='pt', return_dict=True) | |
| ids = encoded['input_ids'][0].tolist() | |
| if case['name'] == 'sliding_boundary_513': | |
| ids = ids[:513] | |
| assert len(ids) > 0 | |
| tensors = torch.tensor([ids], device='cuda') | |
| # Full-storage cache preserves simple ABI; native mask semantics unchanged. | |
| from transformers.cache_utils import DynamicCache | |
| cache = DynamicCache(config=None) | |
| chosen = [] | |
| for step in range(4): | |
| with torch.no_grad(): | |
| result = model(input_ids=tensors, past_key_values=cache, use_cache=True, logits_to_keep=1) | |
| logits = result.logits[0, -1].float().cpu().numpy() | |
| np.save(ROOT / 'reference' / f'{case["name"]}-{step}.npy', logits) | |
| token = int(logits.argmax()) | |
| chosen.append(token) | |
| tensors = torch.tensor([[token]], device='cuda') | |
| fixtures.append({**case, 'inputIds': ids, 'teacherTokens': chosen}) | |
| event('bf16_fixture_recorded', name=case['name'], promptTokens=len(ids)) | |
| write_json(ROOT / 'fixtures.json', fixtures) | |
| event('reference_complete', fixtures=len(fixtures)) | |
| def export(): | |
| make_contract() | |
| import runtime | |
| import onnx | |
| torch.set_num_threads(8) | |
| model = runtime.load_native(str(MODEL), dtype=torch.float16, device_map={'': 'cpu'}).eval() | |
| wrapper = CachedSpark(model).eval() | |
| c = model.config | |
| ids = torch.tensor([[1, 321, 765, 24, 44, 2, 23, 26]], dtype=torch.int64) | |
| pos = torch.arange(2, 10)[None] | |
| past = [torch.zeros(1, c.num_key_value_heads, 2, c.head_dim, dtype=torch.float16) | |
| for _ in range(2 * c.num_hidden_layers)] | |
| inputs = ['input_ids', 'position_ids'] + [f'past_key_values.{i}.{kind}' for i in range(c.num_hidden_layers) for kind in ('key', 'value')] | |
| outputs = ['logits'] + [f'present.{i}.{kind}' for i in range(c.num_hidden_layers) for kind in ('key', 'value')] | |
| axes = {'input_ids': {1: 'sequence_length'}, 'position_ids': {1: 'sequence_length'}} | |
| axes.update({n: {2: 'past_sequence_length'} for n in inputs[2:]}) | |
| axes.update({n: {2: 'total_sequence_length'} for n in outputs[1:]}) | |
| raw = ROOT / 'raw' | |
| raw.mkdir(exist_ok=False) | |
| event('torch_onnx_export_started') | |
| with torch.no_grad(): | |
| torch.onnx.export(wrapper, (ids, pos, *past), str(raw / 'model.onnx'), input_names=inputs, | |
| output_names=outputs, dynamic_axes=axes, opset_version=17, dynamo=False, | |
| do_constant_folding=True, external_data=True) | |
| event('torch_onnx_export_finished') | |
| bundle = ROOT / 'bundle' | |
| graph_dir = bundle / 'onnx' | |
| graph_dir.mkdir(parents=True) | |
| graph = onnx.load(raw / 'model.onnx') | |
| onnx.save_model(graph, graph_dir / 'model_fp16.onnx', save_as_external_data=True, | |
| all_tensors_to_one_file=True, location='model_fp16.onnx_data', size_threshold=1024) | |
| onnx.checker.check_model(str(graph_dir / 'model_fp16.onnx')) | |
| for name in ['config.json', 'tokenizer.json', 'tokenizer_config.json', 'generation_config.json', | |
| 'special_tokens_map.json', 'chat_template.jinja', 'LICENSE']: | |
| if (MODEL / name).exists(): | |
| shutil.copy2(MODEL / name, bundle / name) | |
| write_json(ROOT / 'graph-abi.json', {'inputs': inputs, 'outputs': outputs, 'numLayers': c.num_hidden_layers, | |
| 'numKvHeads': c.num_key_value_heads, 'headDim': c.head_dim, 'vocabSize': c.vocab_size, | |
| 'dtype': 'float16', 'weights': 'FP16', 'residualNormRopeSoftmax': 'FP32', 'contextTested': None}) | |
| event('export_complete', graphBytes=(graph_dir / 'model_fp16.onnx').stat().st_size, | |
| weightsBytes=(graph_dir / 'model_fp16.onnx_data').stat().st_size) | |
| def validate(): | |
| import numpy as np | |
| import onnxruntime as ort | |
| make_contract() | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = 8 | |
| options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL | |
| session = ort.InferenceSession(str(ROOT / 'bundle/onnx/model_fp16.onnx'), options, providers=['CPUExecutionProvider']) | |
| abi = json.loads((ROOT / 'graph-abi.json').read_text()) | |
| checks = [] | |
| for case in json.loads((ROOT / 'fixtures.json').read_text()): | |
| ids = case['inputIds'] | |
| past = [np.empty((1, abi['numKvHeads'], 0, abi['headDim']), dtype=np.float16) for _ in range(2 * abi['numLayers'])] | |
| seen = 0 | |
| for step in range(4): | |
| feeds = {'input_ids': np.array([ids], dtype=np.int64), 'position_ids': np.arange(seen, seen + len(ids), dtype=np.int64)[None]} | |
| feeds.update(dict(zip(abi['inputs'][2:], past))) | |
| result = session.run(None, feeds) | |
| got = result[0][0, -1].astype(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))) | |
| finite = bool(np.isfinite(got).all() and all(np.isfinite(p).all() for p in result[1:])) | |
| record = {'case': case['name'], 'step': step, 'relativeRms': relative, 'cosine': cosine, | |
| 'finite': finite, 'bf16Argmax': int(expected.argmax()), 'onnxArgmax': int(got.argmax())} | |
| checks.append(record) | |
| event('onnx_numerical_case', **record) | |
| seen += len(ids) | |
| ids = [case['teacherTokens'][step]] | |
| past = result[1:] | |
| passed = all(c['finite'] and c['relativeRms'] <= .02 and c['cosine'] >= .999 for c in checks) | |
| write_json(ROOT / 'numerical-validation.json', {'passed': passed, 'checks': checks, 'precision': 'FP16 ONNX versus BF16', | |
| 'thresholds': {'relativeRmsMax': .02, 'cosineMin': .999}, 'runtime': ort.__version__}) | |
| if not passed: | |
| raise RuntimeError('ONNX numerical validation failed; do not publish') | |
| event('numerical_validation_passed') | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('stage', choices=['reference', 'export', 'validate']) | |
| args = parser.parse_args() | |
| {'reference': reference, 'export': export, 'validate': validate}[args.stage]() | |