import json
from pathlib import Path
import numpy as np
import onnxruntime as ort

root = Path('/tmp/codex/ltb1021/20260909-gpu-preprocess')
# FP16 engine 대조 사전 허용치. 결과를 보고 완화하지 않는다.
tolerances = {'dets': (0.005, 0.01), 'labels': (0.05, 0.01)}
options = ort.SessionOptions()
options.intra_op_num_threads = 2
options.inter_op_num_threads = 1
session = ort.InferenceSession('/data/contextra/models/rfdetr-medium.onnx', options,
                              providers=['CPUExecutionProvider'])
x = np.fromfile(root/'input.bin', dtype=np.float32).reshape(1,3,576,576)
outputs = session.run(['dets','labels'], {'input':x})
for name, value in zip(['dets','labels'], outputs):
    np.save(root/(name+'_reference.npy'),value)
result = {}
for name, reference in zip(['dets','labels'],outputs):
    actual = np.fromfile(root/(name+'.bin'),dtype=np.float32).reshape(reference.shape)
    atol,rtol = tolerances[name]
    delta = np.abs(actual-reference)
    passed = bool(np.isfinite(reference).all() and np.isfinite(actual).all()
                  and np.allclose(actual, reference, atol=atol, rtol=rtol))
    result[name] = {'shape':list(reference.shape), 'max_abs':float(delta.max()),
                    'mean_abs':float(delta.mean()), 'atol':atol,'rtol':rtol,'pass':passed}
actual_boxes = np.fromfile(root/'dets.bin',dtype=np.float32).reshape(300,4)
dist = np.max(np.abs(outputs[0][0,:,None,:]-actual_boxes[None,:,:]),axis=-1)
nearest = dist.argmin(axis=1)
diagnostic = {'unique_nearest_queries': int(np.unique(nearest).size),
              'max_nearest_box_abs':float(dist.min(axis=1).max()),
              'note':'nearest-box diagnostic only; not bijective parity or acceptance'}
(root/'query_diagnostic.json').write_text(json.dumps(diagnostic,indent=2))
(root/'comparison.json').write_text(json.dumps(result,indent=2))
print(json.dumps(diagnostic))
print(json.dumps(result,indent=2))
raise SystemExit(0 if all(v['pass'] for v in result.values()) else 1)
