"""Grade /app/prediction.json against ground truth. Writes reward.json (all values numeric). v49 (D10 fix): - A malformed entry (missing/non-numeric score, non-dict, non-int index, NaN/Inf) counts as a missing prediction for that index (abs_err = 100.0) instead of zeroing the entire task. - A duplicate index keeps the first entry encountered. """ import json, math, sys pred_path, gt_path, out_path = sys.argv[1:4] gt = json.load(open(gt_path)) targets = gt['targets'] res = {'reward': 0.0, 'valid': 0, 'n_targets': len(targets)} try: p = json.load(open(pred_path)) if not isinstance(p, dict) or not isinstance(p.get('predictions'), list): raise ValueError('predictions must be a list') preds = {} for x in p['predictions']: if not isinstance(x, dict) or 'index' not in x or isinstance(x['index'], bool): continue try: idx = int(x['index']) except (TypeError, ValueError): continue if idx in preds: continue raw_s = x.get('score') if raw_s is None or isinstance(raw_s, bool): preds[idx] = None continue try: v = float(raw_s) preds[idx] = v if math.isfinite(v) else None except (TypeError, ValueError): preds[idx] = None try: # keep a copy next to the reward (the verifier logs dir is downloaded to the host) json.dump({'predictions': [{'index': k, 'score': v} for k, v in preds.items() if v is not None], 'rationale': str(p.get('rationale', ''))[:4000]}, open(out_path.rsplit('/', 1)[0] + '/prediction.json', 'w')) except Exception: pass errs = [] for k, t in enumerate(targets): v = preds.get(int(t['index'])) if v is None or not math.isfinite(v): e = 100.0 else: e = abs(max(0.0, min(100.0, v)) - t['score']) errs.append(e) res[f'abs_err_{k}'] = e res['mae'] = sum(errs) / len(errs) res['reward'] = sum(max(0.0, 1 - e / 10) for e in errs) / len(errs) res['valid'] = 1 except Exception as ex: # missing or malformed top-level prediction.json print('invalid prediction:', ex, file=sys.stderr) json.dump(res, open(out_path, 'w'))