File size: 4,069 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
"""Additional fixed 8192-token cache-boundary test; independent BF16 reference."""
import json
import argparse
import os
from pathlib import Path
import subprocess
import sys
import urllib.request
import numpy as np
import torch

ROOT = Path(r'D:\webbrain-training\compass-tiny-v3-spark-x25-20260926\onnx-v3')
sys.path.insert(0, str(Path(__file__).parents[1] / 'spark_x25_17b_webbrain_compass_v3'))
import runtime


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--length', type=int, default=8192)
    args = parser.parse_args()
    assert args.length in (4096, 8192)
    uuid = 'GPU-6d908ed7-d2e6-1c70-8a1e-28754a8cbfae'
    assert os.environ.get('CUDA_VISIBLE_DEVICES') == uuid
    free = int(subprocess.check_output(['nvidia-smi', '-i', uuid, '--query-gpu=memory.free', '--format=csv,noheader,nounits'], text=True).strip())
    assert free > 20000, 'Not enough GPU0 headroom; leave other processes untouched'
    folder = ROOT / f'context-{args.length}-v1'
    folder.mkdir(exist_ok=False)
    from transformers import AutoTokenizer
    from transformers.cache_utils import DynamicCache
    tokenizer = AutoTokenizer.from_pretrained(ROOT.parent / 'release-compat-v3', local_files_only=True)
    # Artificial numerical probe, not a selected/modified training or benchmark row.
    ids = tokenizer('Browser reference facts: ' + 'website tab navigation page content. ' * 3000, add_special_tokens=False)['input_ids'][:args.length-3]
    assert len(ids) == args.length-3
    fixture = {'name': f'context_{args.length}', 'inputIds': ids, 'teacherTokens': []}
    (folder / 'selection.json').write_text(json.dumps({'inputIds': ids, 'rule': f'Fixed synthetic {args.length-3}-token prefill plus three decode tokens, chosen before results; 4K is a separately tested deployment cap, not removal of the failed 8K check'}), encoding='utf-8')
    torch.set_num_threads(8)
    torch.backends.cuda.matmul.allow_tf32 = False
    model = runtime.load_native(str(ROOT.parent / 'release-compat-v3'), dtype=torch.bfloat16, device_map={'': 0}).eval()
    cache = DynamicCache(config=None)
    tensors = torch.tensor([ids], device='cuda')
    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(folder / f'bf16-{step}.npy', logits)
        token = int(logits.argmax())
        fixture['teacherTokens'].append(token)
        tensors = torch.tensor([[token]], device='cuda')
        print(json.dumps({'referenceStep': step, 'finite': bool(np.isfinite(logits).all())}), flush=True)
    del model, cache, result
    torch.cuda.empty_cache()
    request = urllib.request.Request('http://127.0.0.1:8561/infer', data=json.dumps(fixture).encode(), headers={'Content-Type': 'application/json'})
    with urllib.request.urlopen(request, timeout=600) as response:
        actual = json.load(response)
    checks = []
    for step, values in enumerate(actual['logits']):
        expected = np.load(folder / f'bf16-{step}.npy').astype(np.float64)
        got = np.array(values, dtype=np.float64)
        checks.append({'step': step, 'relativeRms': 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()), 'argmaxMatched': bool(got.argmax()==expected.argmax())})
    passed = all(c['finite'] and c['relativeRms'] <= .02 and c['cosine'] >= .999 for c in checks)
    report = {'passed': passed, 'prefillTokens': args.length-3, 'finalCacheTokens': args.length, 'checks': checks,
              'thresholds': {'relativeRmsMax': .02, 'cosineMin': .999}, 'gpu': actual['gpuInfo']}
    (folder / 'validation.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
    print(json.dumps(report), flush=True)
    assert passed, 'Long-context WebGPU numerical validation failed'


if __name__ == '__main__':
    main()