File size: 12,095 Bytes
c5cfd97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""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]()