#!/usr/bin/env python """Real-data reproduction of ORCA (arXiv 2410.13735, Table 3) on blog / fb1 / fb2. Pipeline per run (seeded by run_id): 1. load cached dataset, optional y preproc ('logz' on the FULL data), split 500 explore / 500 calib / 1000 test / rest = train; 2. fit a fresh quantile-forest QRF on train (quantile-forest package); 3. sample K=20 conditional draws per row via the paper's stated interface (Appendix E.1: QRF quantile grid 1%..99%): ONE batched predict on a 99-level grid -> (n, 99) per-row quantile curves; ONE u_k ~ U(0,1) per sample index k SHARED across all rows; the draw for (row, k) is the row's grid curve interpolated at u_k (grid-inversion sampling). 4. methods, all sharing the SAME QRF object and the SAME splits: - orca: m-NN density ranking (k_neighbor=5) -> residual matrix -> stage-2 MILP over per-rank levels (compact HiGHS/scipy formulation, replaces the repo's OR-Tools CP-SAT) -> stage-3 split-conformal rescale (ported from orca/optimize.py + orca/conformal.py); - pcp: cal_type='uniform' min-k score, single radius t (pcp/pcp.py); - cqr: QRF q05/q95 read off the same 99-level grid, score max(q05-y, y-q95), interval [q05-t, q95+t]; 5. append one CSV row per (dataset, run, method). Seed-stream choice (documented per spec): each run uses ONE numpy Generator seeded with seed0 + run_id; it is consumed in a fixed order -- split, then explore draws, calib draws, test draws. ORCA and PCP SHARE the same drawn samples within a run (the calib/test sample matrices are drawn once per run and passed to both methods), so the ORCA-vs-PCP comparison is paired; CQR uses no draws. """ from __future__ import annotations import argparse import glob import io import math import os import shutil import sys import time import urllib.request import zipfile import numpy as np import pandas as pd from scipy.optimize import Bounds, LinearConstraint, milp # --------------------------------------------------------------------------- # # Config # --------------------------------------------------------------------------- # N_EXPLORE = 500 N_CALIB = 500 N_TEST = 1000 K = 20 K_NEIGHBOR = 5 # ceil(sqrt(20)); NOT the repo default ceil(K/3) ALPHA = 0.10 Q_GRID = np.arange(0.01, 1.0, 0.01) # shared 99-level quantile grid (paper App. E.1) MILP_TIME_LIMIT = 120.0 # seconds; falls back to greedy warm start on timeout DATA_DIR = os.environ.get("ORCA_REPRO_DATA", "/work/orca_repro/data") BLOG_URL = "https://archive.ics.uci.edu/static/public/304/blogfeedback.zip" BLOG_FALLBACK = ("https://raw.githubusercontent.com/scikit-learn-contrib/MAPIE/" "master/examples/data/blogData_train.csv.gz") FB_URL = "https://archive.ics.uci.edu/ml/machine-learning-databases/00363/Dataset.zip" BLOG_SHAPE = (52397, 281) FB1_SHAPE = (40949, 54) FB2_SHAPE = (81312, 54) # --------------------------------------------------------------------------- # # Data loading (cached) # --------------------------------------------------------------------------- # def _download(url: str, dest: str) -> None: print(f"[data] downloading {url} -> {dest}", flush=True) t0 = time.time() urllib.request.urlretrieve(url, dest) print(f"[data] done in {time.time() - t0:.1f}s ({os.path.getsize(dest)} bytes)", flush=True) def ensure_blog(data_dir: str) -> str: """Return path to blogData_train.csv (52397 x 281, no header).""" os.makedirs(data_dir, exist_ok=True) out = os.path.join(data_dir, "blogData_train.csv") if os.path.exists(out): return out zpath = os.path.join(data_dir, "blogfeedback.zip") if not os.path.exists(zpath): try: _download(BLOG_URL, zpath) except Exception as exc: # noqa: BLE001 print(f"[data] primary blog URL failed ({exc}); trying fallback", flush=True) gzpath = os.path.join(data_dir, "blogData_train.csv.gz") _download(BLOG_FALLBACK, gzpath) import gzip with gzip.open(gzpath, "rb") as fin, open(out, "wb") as fout: fout.write(fin.read()) return out with zipfile.ZipFile(zpath) as zf: zf.extractall(data_dir) if not os.path.exists(out): raise FileNotFoundError("blogData_train.csv not found after extraction") return out def ensure_fb(data_dir: str, variant: int) -> str: """Return path to Features_Variant_{1,2}.csv (no header).""" os.makedirs(data_dir, exist_ok=True) out = os.path.join(data_dir, f"Features_Variant_{variant}.csv") if os.path.exists(out): return out zpath = os.path.join(data_dir, "Dataset.zip") if not os.path.exists(zpath): _download(FB_URL, zpath) with zipfile.ZipFile(zpath) as zf: zf.extractall(data_dir) if not os.path.exists(out): # the UCI Dataset.zip nests files under Dataset/Training/ -- search # recursively and copy to the flat expected path hits = glob.glob(os.path.join(data_dir, "**", f"Features_Variant_{variant}.csv"), recursive=True) if hits: shutil.copyfile(hits[0], out) else: raise FileNotFoundError( f"Features_Variant_{variant}.csv not found under {data_dir} after extraction") return out def load_dataset(dataset: str, data_dir: str = DATA_DIR): if dataset == "blog": path = ensure_blog(data_dir) arr = np.loadtxt(path, delimiter=",") expected = BLOG_SHAPE X, y = arr[:, :280], arr[:, 280] elif dataset in ("fb1", "fb2"): path = ensure_fb(data_dir, variant=1 if dataset == "fb1" else 2) arr = np.loadtxt(path, delimiter=",") expected = FB1_SHAPE if dataset == "fb1" else FB2_SHAPE X, y = arr[:, :53], arr[:, 53] else: raise ValueError(f"unknown dataset {dataset!r}") assert arr.shape == expected, f"{dataset}: got shape {arr.shape}, expected {expected}" return X, y # --------------------------------------------------------------------------- # # QRF sampling: quantile-grid inversion (port of orca/models.py) # --------------------------------------------------------------------------- # def fit_qrf(X_train, y_train, seed: int, n_jobs: int = 2, leaf_mode: str = "leaf"): """leaf_mode='leaf': min_samples_leaf=50 (original config). leaf_mode='split': min_samples_split=50 with default min_samples_leaf=1 (the ORCA paper text says 'minimum of 50 samples per node split', which is ambiguous between the two; see --leaf_mode).""" from quantile_forest import RandomForestQuantileRegressor if leaf_mode == "leaf": model = RandomForestQuantileRegressor( n_estimators=100, min_samples_leaf=50, random_state=seed, n_jobs=n_jobs ) elif leaf_mode == "split": model = RandomForestQuantileRegressor( n_estimators=100, min_samples_split=50, random_state=seed, n_jobs=n_jobs ) else: raise ValueError(f"bad leaf_mode: {leaf_mode}") model.fit(X_train, y_train) return model def _invert_quantile_grid(q: np.ndarray, grid: np.ndarray, us: np.ndarray) -> np.ndarray: """Row-wise quantile curves q (n, L) on a sorted ascending level grid (L,), evaluated at levels us (n_sample,) -> (n, n_sample). Piecewise-linear interpolation per the shared-quantile interface: u <= grid[0] -> column 0; u >= grid[-1] -> column -1; else linear between the bracketing grid columns. The columns are the same for every row, so the whole batch is two gathers + a weighted blend.""" q = np.asarray(q, dtype=float).reshape(len(q), len(grid)) out = np.empty((q.shape[0], len(us)), dtype=float) for k, u in enumerate(np.asarray(us, dtype=float)): if u <= grid[0]: out[:, k] = q[:, 0] elif u >= grid[-1]: out[:, k] = q[:, -1] else: hi = int(np.searchsorted(grid, u, side="right")) lo = hi - 1 w = (u - grid[lo]) / (grid[hi] - grid[lo]) out[:, k] = (1.0 - w) * q[:, lo] + w * q[:, hi] return out def draw_samples(model, X, n_sample: int, rng, shared: bool = True) -> np.ndarray: """K conditional draws per row via the paper's QRF interface (Appendix E.1: a quantile grid from 1% to 99%). ONE batched predict call on the 99-level grid gives each row's full quantile curve q (n, 99); ONE u_k ~ U(0,1) is drawn per sample index k and SHARED across rows (the shared quantile draw setting); the draw for (row, k) is that row's curve interpolated at u_k. Interpolating the grid gives CONTINUOUS samples -- the scalar-quantile predict returns exact order statistics of the raw counts (integer tie mass), which flattens conformal scores; the grid interface is what the paper's pipeline actually evaluates. Returns (n, n_sample, 1).""" X = np.asarray(X) n = len(X) grid = np.arange(0.01, 1.0, 0.01) q = np.asarray(model.predict(X, quantiles=list(grid))).reshape(n, len(grid)) if not shared: # DIAG VARIANT: independent draws -- one u ~ U(0,1) per (row, k) us = rng.random((n, n_sample)) hi_idx = np.clip(np.searchsorted(grid, us, side="right"), 1, len(grid) - 1) lo_idx = hi_idx - 1 w = np.clip((us - grid[lo_idx]) / (grid[hi_idx] - grid[lo_idx]), 0.0, 1.0) rows_idx = np.arange(n)[:, None] out = (1.0 - w) * q[rows_idx, lo_idx] + w * q[rows_idx, hi_idx] return out[:, :, None] us = rng.random(n_sample) # one shared u per sample index return _invert_quantile_grid(q, grid, us)[:, :, None] # --------------------------------------------------------------------------- # # Density ranking + residuals (port of orca/sampling.py, d=1) # --------------------------------------------------------------------------- # def rank_samples_by_density(Y_hat: np.ndarray, k_neighbor: int = K_NEIGHBOR) -> np.ndarray: """Rank each row's samples densest-first (mean distance to the k nearest neighbours within the cloud, self-distance 0 included). Returns (n, K, 1). Vectorised equivalent of orca/sampling.py:rank_samples_by_density.""" Y_hat = np.asarray(Y_hat, dtype=float) assert Y_hat.ndim == 3 and Y_hat.shape[2] == 1, Y_hat.shape S = Y_hat[:, :, 0] # (n, K) pairwise = np.abs(S[:, :, None] - S[:, None, :]) # (n, K, K) proxy = np.sort(pairwise, axis=2)[:, :, : k_neighbor + 1].mean(axis=2) idx = np.argsort(proxy, axis=1, kind="stable") ranked = np.take_along_axis(S, idx, axis=1) return ranked[:, :, None] def residual_matrix(Y_true: np.ndarray, Y_samples: np.ndarray) -> np.ndarray: """E[i, r] = |y_i - sample_{i,r}| (d=1).""" return np.abs(np.asarray(Y_samples, dtype=float)[:, :, 0] - np.asarray(Y_true, dtype=float).reshape(-1, 1)) # --------------------------------------------------------------------------- # # Conformal quantile (port of orca/conformal.py) # --------------------------------------------------------------------------- # def conformal_quantile(scores, alpha: float) -> float: """ceil((1 - alpha) * (m + 1))-th smallest score, capped at the largest.""" s = np.sort(np.asarray(scores, dtype=float)) m = s.shape[0] if m == 0: raise ValueError("empty score set") k = int(math.ceil((1.0 - alpha) * (m + 1))) return float(s[int(np.clip(k, 1, m)) - 1]) # --------------------------------------------------------------------------- # # Stage 2: coverage allocation. The repo uses OR-Tools CP-SAT # (orca/optimize.py:solve_orca_milp); ortools is unavailable here, so we use # the compact MILP over per-rank levels solved by scipy.optimize.milp / HiGHS: # binary z_{r,l} (monotone z_{r,l} >= z_{r,l+1}), # y_i <= sum_r z_{r, l_min(i,r)}, l_min(i,r) = smallest l with E_(l),r >= E_{i,r}, # cost = sum_r (threshold_r)^d (d=1), encoded as level increments, # sum_i y_i >= ceil(n1 * (1 - alpha)). # The repo's greedy warm start + threshold tightening are ported verbatim and # used as the fallback when HiGHS hits the time limit without a feasible point. # --------------------------------------------------------------------------- # def build_levels(E: np.ndarray): """Per-rank sorted unique residual values (orca/optimize.py:build_levels, with_zero=False).""" return [np.unique(E[:, r]) for r in range(E.shape[1])] def coverage_count(E, thresholds) -> int: return int((np.asarray(E) <= np.asarray(thresholds)[None, :]).any(axis=1).sum()) def coverage_target(n: int, alpha: float) -> int: return int(min(n, math.ceil((n + 1) * (1.0 - alpha)))) def _proxy_objective(thresholds, d: int) -> float: return float(np.sum(np.asarray(thresholds, dtype=float) ** d)) def tighten_thresholds(E, alpha, thresholds, levels): """Port of orca/optimize.py:tighten_thresholds (demote each rank as far as the quota allows).""" E = np.asarray(E, dtype=float) n, K_ = E.shape target = coverage_target(n, alpha) thr = np.asarray(thresholds, dtype=float).copy() for r in range(K_): lv = levels[r] while True: idx = int(np.searchsorted(lv, thr[r], side="right")) - 1 if idx <= 0: break old = thr[r] thr[r] = lv[idx - 1] if coverage_count(E, thr) >= target: continue thr[r] = old break return thr def greedy_warm_start(E, alpha, d: int = 1): """Port of orca/optimize.py:greedy_warm_start (with_zero=False).""" import heapq E = np.asarray(E, dtype=float) n, K_ = E.shape levels = build_levels(E) cover = [(E[:, r][:, None] <= levels[r][None, :]) for r in range(K_)] inc_cost = [np.diff(lv ** d, prepend=lv[0] ** d) for lv in levels] thresholds = np.array([lv[0] for lv in levels], dtype=float) covered = np.zeros(n, dtype=bool) for r in range(K_): covered |= E[:, r] <= thresholds[r] target = coverage_target(n, alpha) heap, counter = [], 0 for r in range(K_): if len(levels[r]) > 1: gain = int((~covered & cover[r][:, 1]).sum()) heapq.heappush(heap, (float(inc_cost[r][1]) / max(1, gain), counter, r, 1)) counter += 1 while covered.sum() < target and heap: ratio, _, r, ell = heapq.heappop(heap) gain = int((~covered & cover[r][:, ell]).sum()) ratio_now = float(inc_cost[r][ell]) / max(1, gain) if abs(ratio_now - ratio) > 1e-12: heapq.heappush(heap, (ratio_now, counter, r, ell)) counter += 1 continue thresholds[r] = levels[r][ell] covered |= cover[r][:, ell] if ell + 1 < len(levels[r]): nxt = ell + 1 g2 = int((~covered & cover[r][:, nxt]).sum()) heapq.heappush(heap, (float(inc_cost[r][nxt]) / max(1, g2), counter, r, nxt)) counter += 1 # 2-exchange refinement (single demote/promote pass loop, as in the repo) improved = True while improved: improved = False current_obj = _proxy_objective(thresholds, d) for r in range(K_): lv_r = levels[r] idx_r = int(np.searchsorted(lv_r, thresholds[r], side="right")) - 1 if idx_r <= 0: continue thr_r_old = thresholds[r] thresholds[r] = lv_r[idx_r - 1] for s in range(K_): if s == r: continue lv_s = levels[s] idx_s = int(np.searchsorted(lv_s, thresholds[s], side="right")) - 1 if idx_s + 1 >= len(lv_s): continue thr_s_old = thresholds[s] thresholds[s] = lv_s[idx_s + 1] if coverage_count(E, thresholds) >= target: new_obj = _proxy_objective(thresholds, d) if new_obj + 1e-12 < current_obj: improved = True current_obj = new_obj break thresholds[s] = thr_s_old if not improved: thresholds[r] = thr_r_old else: break return thresholds def solve_orca_milp(E: np.ndarray, alpha: float, d: int = 1, time_limit: float = MILP_TIME_LIMIT, stage2: str = "milp"): """Compact level-MILP via scipy.optimize.milp (HiGHS). Mirrors the repo's CP-SAT solve_orca_milp: greedy warm start + tighten + threshold readout. stage2='greedy' skips HiGHS and uses the ported greedy_warm_start directly (measured MILP wall time on fb1: 0.15s, so 'milp' stays the default).""" import scipy.sparse as sp E = np.asarray(E, dtype=float) n, K_ = E.shape assert d == 1, "real-data reproduction is d=1" target = coverage_target(n, alpha) levels = build_levels(E) n_levels = [len(lv) for lv in levels] if stage2 == "greedy": thresholds = tighten_thresholds(E, alpha, greedy_warm_start(E, alpha, d), levels) beta_hat = 1.0 - (E <= thresholds[None, :]).sum(axis=0) / (n + 1) return thresholds, beta_hat, {"status": "greedy", "milp_sec": 0.0} if stage2 != "milp": raise ValueError(f"unknown stage2 {stage2!r}") # variable layout: z[(r, l)] then y[i] z_offset = np.cumsum([0] + n_levels) # z_offset[r] = start index of rank r nz = int(z_offset[-1]) n_var = nz + n y_offset = nz # objective: level increments within each rank (prefix sum = threshold^1) c = np.zeros(n_var) for r in range(K_): lv = levels[r] c[z_offset[r]: z_offset[r] + len(lv)] = np.diff(lv, prepend=0.0) # monotonicity z_{r,l} - z_{r,l+1} >= 0 mono_rows, mono_cols = [], [] r_idx, lo_idx, hi_idx, mono_data = [], [], [], [] row = 0 for r in range(K_): for l in range(n_levels[r] - 1): r_idx += [row, row] lo_idx += [z_offset[r] + l, z_offset[r] + l + 1] mono_data += [1.0, -1.0] row += 1 mono = sp.csr_matrix( (mono_data, (r_idx, lo_idx)), shape=(row, n_var)) mono_con = LinearConstraint(mono, lb=0.0, ub=np.inf) # coverage: y_i <= sum_r z_{r, l_min(i,r)} -> sum_r z - y_i >= 0 cov_rows, cov_cols, cov_data = [], [], [] row = 0 for i in range(n): for r in range(K_): l_min = int(np.searchsorted(levels[r], E[i, r], side="left")) cov_rows.append(row) cov_cols.append(z_offset[r] + l_min) cov_data.append(1.0) cov_rows.append(row) cov_cols.append(y_offset + i) cov_data.append(-1.0) row += 1 cov = sp.csr_matrix((cov_data, (cov_rows, cov_cols)), shape=(n, n_var)) cov_con = LinearConstraint(cov, lb=0.0, ub=np.inf) # quota: sum_i y_i >= target quota = sp.csr_matrix( (np.ones(n), (np.zeros(n, dtype=int), y_offset + np.arange(n))), shape=(1, n_var)) quota_con = LinearConstraint(quota, lb=float(target), ub=np.inf) integrality = np.zeros(n_var) integrality[:nz] = 1 t0 = time.time() res = milp( c=c, constraints=[mono_con, cov_con, quota_con], integrality=integrality, bounds=Bounds(np.zeros(n_var), np.ones(n_var)), options={"time_limit": time_limit, "mip_rel_gap": 0.01, "presolve": True}, ) solve_sec = time.time() - t0 z_sol = np.round(np.asarray(res.x[:nz])) if res.x is not None else None if z_sol is None: # no incumbent within the budget: fall back to the greedy warm start thresholds = greedy_warm_start(E, alpha, d) details = {"status": "greedy-fallback", "milp_sec": solve_sec} else: thresholds = np.empty(K_) for r in range(K_): active = np.nonzero(z_sol[z_offset[r]: z_offset[r] + n_levels[r]])[0] thresholds[r] = levels[r][active[-1]] details = {"status": str(res.status), "milp_sec": solve_sec} # repo applies tighten_thresholds to the solver output candidate = tighten_thresholds(E, alpha, thresholds, levels) if coverage_count(E, candidate) >= target: thresholds = candidate details["tighten_applied"] = "yes" else: details["tighten_applied"] = "no_quota_lost" # per-rank empirical miscoverage (repo's _beta_hat) counts = (E <= thresholds[None, :]).sum(axis=0) beta_hat = 1.0 - counts / (n + 1) return thresholds, beta_hat, details # --------------------------------------------------------------------------- # # Interval merging (replaces PCP's sympy Interval/Union) # --------------------------------------------------------------------------- # def merged_total_length(lo: np.ndarray, hi: np.ndarray) -> float: """Total length of the union of [lo_k, hi_k] after merging overlaps.""" order = np.argsort(lo, kind="stable") lo, hi = lo[order], hi[order] total, cur_hi = 0.0, None for a, b in zip(lo, hi): if cur_hi is None or b > cur_hi: total += (b - max(a, cur_hi)) if cur_hi is not None else (b - a) cur_hi = b return float(total) def covered_by_intervals(y: float, lo: np.ndarray, hi: np.ndarray) -> bool: return bool(((lo <= y) & (y <= hi)).any()) def clip_region_size(eff: np.ndarray, span: float) -> np.ndarray: """SIZE METRIC, aligned with official orca/metrics.py:region_size: the merged-union region length is CLIPPED to the span (max - min) of the observed responses. The official docstring says "clip to the range of observed responses" but no script states which rows count; to avoid test leakage we clip to the span of train + explore + calib y EXCLUDING test rows (computed once per run in one_run as span_clipped).""" return np.minimum(np.asarray(eff, dtype=float), float(span)) # --------------------------------------------------------------------------- # # Methods # --------------------------------------------------------------------------- # def run_orca(model, y_explore, y_calib, y_test, X_explore, X_calib, X_test, rng, span_clipped, stage2="milp", S_cal=None, S_te=None, shared_draws=True, k_neighbor=K_NEIGHBOR): """ORCA method. If S_cal/S_te are given they are the SHARED per-run sample matrices (drawn once in one_run, also used by PCP -> paired comparison).""" t0 = time.time() S_exp = draw_samples(model, X_explore, K, rng, shared=shared_draws) ranked_exp = rank_samples_by_density(S_exp, k_neighbor) E_explore = residual_matrix(y_explore, ranked_exp) # (n1, K) assert E_explore.shape == (len(y_explore), K) thresholds, beta_hat, milp_details = solve_orca_milp( E_explore, ALPHA, d=1, stage2=stage2) # A zero threshold (zero radius) for a rank is legitimate: that ball has # measure 0. The MILP can legitimately emit 0.0/tiny levels for low-density # ranks, so require only non-negativity and finiteness. assert np.all(thresholds >= 0) and np.all(np.isfinite(thresholds)) # stage 3: split-conformal rescale on calibration residuals if S_cal is None: S_cal = draw_samples(model, X_calib, K, rng, shared=shared_draws) ranked_cal = rank_samples_by_density(S_cal, k_neighbor) E_calib = residual_matrix(y_calib, ranked_cal) # Guard against Q_r == 0 (threshold 0): such a rank covers a point only if # E_{i,r} == 0 exactly (ratio 0); otherwise the ratio is +inf and the rank # is skipped by the min below. A zero-radius ball also contributes nothing # to the test-set union/efficiency (degenerate [x, x] interval, length 0). Q = thresholds[None, :] with np.errstate(divide="ignore", invalid="ignore"): ratios_pos = np.where(Q > 0, E_calib / np.where(Q > 0, Q, 1.0), np.inf) ratios = np.where(Q > 0, ratios_pos, np.where(E_calib == 0, 0.0, np.inf)) scores = ratios.min(axis=1) t_alpha = conformal_quantile(scores, ALPHA) assert np.isfinite(t_alpha) radii = t_alpha * thresholds # (K,) # test if S_te is None: S_te = draw_samples(model, X_test, K, rng, shared=shared_draws) ranked_te = rank_samples_by_density(S_te, k_neighbor)[:, :, 0] # (n_test, K) lo = ranked_te - radii[None, :] hi = ranked_te + radii[None, :] # zero-radius ranks yield degenerate intervals of length 0: harmless in the # merged union and in coverage (they only ever match an exact sample value). eff = np.array([merged_total_length(l, h) for l, h in zip(lo, hi)]) cov = np.array([covered_by_intervals(y, l, h) for y, l, h in zip(y_test, lo, hi)]) eff = clip_region_size(eff, span_clipped) # clip to observed span (no test rows) return { "coverage": float(cov.mean()), "eff": float(eff.mean()), "threshold_t": float(t_alpha), "seconds": time.time() - t0, "n_explore": len(y_explore), "n_calib": len(y_calib), "milp_status": milp_details["status"], "stage2_sec": float(milp_details.get("milp_sec", 0.0)), "proxy_objective": float(_proxy_objective(thresholds, 1)), "tighten_applied": milp_details.get("tighten_applied", "n/a"), } def run_pcp(model, y_calib, y_test, X_calib, X_test, rng, span_clipped, S_cal=None, S_te=None, pcp_threshold="interp", shared_draws=True): """Port of pcp/pcp.py, cal_type='uniform': score = min_k |y - sample_k|, single radius t; test set = union of [s_k - t, s_k + t]. If S_cal/S_te are given they are the SHARED per-run sample matrices (drawn once in one_run); otherwise they are drawn here.""" t0 = time.time() if S_cal is None: S_cal = draw_samples(model, X_calib, K, rng, # (n_cal, K, 1) shared=shared_draws) E_calib = residual_matrix(y_calib, S_cal) # (n_cal, K) scores = E_calib.min(axis=1) # min over k # PCP threshold fidelity: the ORCA paper used the PCP authors' public # implementation (Zhendong-Wang/Probabilistic-Conformal-Prediction, # pcp/pcp.py, cal_type='uniform'), which calibrates with the INTERPOLATED # quantile torch.quantile(scores, 1-alpha) -- NOT the conformal # ceil((n+1)(1-alpha))-th order statistic. 'interp' reproduces that # (np.quantile linear = torch.quantile default); 'ceil' is the # split-conformal order statistic used by ORCA/CQR. if pcp_threshold == "interp": t = float(np.quantile(scores, 1 - ALPHA, method="linear")) elif pcp_threshold == "ceil": t = conformal_quantile(scores, ALPHA) else: raise ValueError(f"bad pcp_threshold: {pcp_threshold}") assert np.isfinite(t) if S_te is None: S_te = draw_samples(model, X_test, K, rng)[:, :, 0] else: S_te = np.asarray(S_te) if S_te.ndim == 3: # shared per-run matrix is (n, K, 1) S_te = S_te[:, :, 0] lo, hi = S_te - t, S_te + t eff = np.array([merged_total_length(l, h) for l, h in zip(lo, hi)]) cov = np.array([covered_by_intervals(y, l, h) for y, l, h in zip(y_test, lo, hi)]) return { "coverage": float(cov.mean()), "eff": float(eff.mean()), "threshold_t": float(t), "seconds": time.time() - t0, "n_explore": 0, "n_calib": len(y_calib), "pcp_threshold": pcp_threshold, } def cqr_quantiles(model, X, levels=(0.05, 0.95)) -> np.ndarray: """CQR's conditional quantiles through the SAME 99-level grid interface as the sampler (paper Appendix E.1): ONE batched grid predict -> (n, 99) per-row curves, then the two requested levels are read off the grid with the same piecewise-linear rule as _invert_quantile_grid. Keeps the CQR quantiles continuous (no integer order-statistic ties). Returns (n, 2) with columns [q_lo, q_hi].""" X = np.asarray(X) n = len(X) grid = np.arange(0.01, 1.0, 0.01) q = np.asarray(model.predict(X, quantiles=list(grid))).reshape(n, len(grid)) return _invert_quantile_grid(q, grid, levels) def run_cqr(model, y_calib, y_test, X_calib, X_test, span_clipped=None): """CQR baseline (Romano, Patterson, Candes 2019), exactly as in the textbook: E_i = max(q_lo(X_i) - y_i, y_i - q_hi(X_i)) with NO clamp to 0 -- scores may be NEGATIVE; the threshold t is the ceil((n+1)(1-alpha))-th order statistic of the raw scores and can itself be negative (the interval is still [q_lo - t, q_hi + t]). DIAGNOSTICS (per spec): assert np.all(q05 <= q95); record the fraction of calib scores <= 0 (frac_neg_scores, diagnostic ONLY -- it does not feed the threshold) and the mean CQR interval length BEFORE conformal inflation.""" t0 = time.time() q_c = cqr_quantiles(model, X_calib) # (n_calib, 2) grid-interpolated q05_c, q95_c = q_c[:, 0], q_c[:, 1] assert np.all(q05_c <= q95_c), "CQR: q05 > q95 on calib" E_calib = np.maximum(q05_c - y_calib, y_calib - q95_c) frac_nonpos = float(np.mean(E_calib <= 0)) # diagnostic mean_len_before = float(np.mean(q95_c - q05_c)) # mean interval len pre-inflation t = conformal_quantile(E_calib, ALPHA) assert np.isfinite(t) q_t = cqr_quantiles(model, X_test) # (n_test, 2) grid-interpolated q05_t, q95_t = q_t[:, 0], q_t[:, 1] assert np.all(q05_t <= q95_t), "CQR: q05 > q95 on test" eff = float(np.mean(q95_t - q05_t)) if span_clipped is not None: eff = min(eff, float(span_clipped)) # same size metric as ORCA/PCP cov = float(np.mean((y_test >= q05_t - t) & (y_test <= q95_t + t))) return { "coverage": cov, "eff": eff, "threshold_t": float(t), "seconds": time.time() - t0, "n_explore": 0, "n_calib": len(y_calib), "frac_neg_scores": frac_nonpos, "mean_len_before_inflation": mean_len_before, } # --------------------------------------------------------------------------- # # One run # --------------------------------------------------------------------------- # def one_run(dataset: str, X: np.ndarray, y_full: np.ndarray, run_id: int, seed0: int, methods, preproc: str, stage2: str = "milp", leaf_mode: str = "leaf", pcp_threshold: str = "interp", shared_draws: bool = True, k_neighbor: int = K_NEIGHBOR) -> list: seed = seed0 + run_id rng = np.random.default_rng(seed) # -- split (seeded by run_id) -- perm = rng.permutation(len(y_full)) i_explore = perm[:N_EXPLORE] i_calib = perm[N_EXPLORE: N_EXPLORE + N_CALIB] i_test = perm[N_EXPLORE + N_CALIB: N_EXPLORE + N_CALIB + N_TEST] i_train = perm[N_EXPLORE + N_CALIB + N_TEST:] assert len(set(i_explore) | set(i_calib) | set(i_test)) == N_EXPLORE + N_CALIB + N_TEST y = y_full if preproc == "logz": # y transform on the FULL dataset before splitting, then z-score y = np.log1p(y - y.min() + 1.0) X_train, X_explore, X_calib, X_test = (X[i_train], X[i_explore], X[i_calib], X[i_test]) y_train, y_explore, y_calib, y_test = (y[i_train], y[i_explore], y[i_calib], y[i_test]) # -- z-score X with train stats (both preprocs); z-score y for logz -- mu_x, sd_x = X_train.mean(axis=0), X_train.std(axis=0) sd_x[sd_x == 0] = 1.0 Z = lambda A: (A - mu_x) / sd_x # noqa: E731 X_train, X_explore, X_calib, X_test = map( Z, (X_train, X_explore, X_calib, X_test)) if preproc == "logz": mu_y, sd_y = y_train.mean(), y_train.std() y_train = (y_train - mu_y) / sd_y y_explore = (y_explore - mu_y) / sd_y y_calib = (y_calib - mu_y) / sd_y y_test = (y_test - mu_y) / sd_y # -- fresh QRF every run -- t0 = time.time() model = fit_qrf(X_train, y_train, seed=seed, leaf_mode=leaf_mode) qrf_sec = time.time() - t0 print(f"[run {run_id}] QRF fit: {qrf_sec:.1f}s " f"(train n={len(y_train)})", flush=True) # SIZE METRIC: span (max - min) of observed responses EXCLUDING test rows # (train + explore + calib y); see clip_region_size. span_clipped = float(np.concatenate( [y_train, y_explore, y_calib]).max() - np.concatenate([y_train, y_explore, y_calib]).min()) # SHARED sample matrices for ORCA and PCP (paired comparison): the calib # and test draws are made once per run from the single rng stream and # handed to both methods, so they see identical draws. t_share = time.time() if shared_draws: S_cal_shared = draw_samples(model, X_calib, K, rng) S_te_shared = draw_samples(model, X_test, K, rng) else: # DIAG VARIANT shared_draws=0: methods draw per-(row, k) internally S_cal_shared = S_te_shared = None t_shared_sec = time.time() - t_share stage2_sec = 0.0 tighten_applied = "" rows = [] if "orca" in methods: res = run_orca(model, y_explore, y_calib, y_test, X_explore, X_calib, X_test, rng, span_clipped=span_clipped, stage2=stage2, S_cal=S_cal_shared, S_te=S_te_shared, shared_draws=shared_draws, k_neighbor=k_neighbor) res["milp"] = res.pop("milp_status", "") stage2_sec = res.get("stage2_sec", 0.0) tighten_applied = res.get("tighten_applied", "") rows.append(("orca", res)) if "pcp" in methods: res = run_pcp(model, y_calib, y_test, X_calib, X_test, rng, span_clipped=span_clipped, S_cal=S_cal_shared, S_te=S_te_shared, pcp_threshold=pcp_threshold, shared_draws=shared_draws) res["milp"] = "" rows.append(("pcp", res)) if "cqr" in methods: res = run_cqr(model, y_calib, y_test, X_calib, X_test, span_clipped=span_clipped) res["milp"] = "" rows.append(("cqr", res)) out = [] for method, res in rows: out.append({ "dataset": dataset, "run_id": run_id, "method": method, "coverage": res["coverage"], "eff": res["eff"], "n_test": len(y_test), "seconds": res["seconds"], "preproc": preproc, "threshold_t": res["threshold_t"], "n_explore": res["n_explore"], "n_calib": res["n_calib"], "stage2_seconds": round(stage2_sec, 4), "proxy_objective": round(res.get("proxy_objective", float("nan")), 6) if method == "orca" else "", "milp": res["milp"], "tighten_applied": tighten_applied if method == "orca" else "", "frac_neg_scores": round(res.get("frac_neg_scores", float("nan")), 4) if method == "cqr" else "", "leaf_mode": leaf_mode, "pcp_threshold": res.get("pcp_threshold", ""), "mean_len_before_inflation": round(res.get("mean_len_before_inflation", float("nan")), 4) if method == "cqr" else "", "span_clipped": round(span_clipped, 6), "shared_draws": int(shared_draws), "k_neighbor": k_neighbor, }) print(f"[run {run_id}] {method}: cov={res['coverage']:.3f} " f"eff={res['eff']:.3f} t={res['threshold_t']:.3f} " f"stage2_sec={stage2_sec:.2f} " f"Qsum={res.get('proxy_objective', float('nan')):.3f} " f"fracneg={res.get('frac_neg_scores', float('nan')):.3f} " f"tighten={tighten_applied or '-'} " f"sec={res['seconds']:.1f}", flush=True) print(f"[run {run_id}] QRF fit sec={qrf_sec:.1f} shared-sampling sec={t_shared_sec:.1f}", flush=True) return out # --------------------------------------------------------------------------- # # Main # --------------------------------------------------------------------------- # def main(): _trackio = None # trackio.init reads TRACKIO_SPACE_ID from the environment itself os.environ.setdefault("TRACKIO_SPACE_ID", "Devya27/orca-table3-repro-trackio") if os.environ.get("TRACKIO_SPACE_ID"): try: import trackio trackio.init(project="orca-table3-repro", space_id=os.environ["TRACKIO_SPACE_ID"]) _trackio = trackio print("[trackio] dashboard initialised", flush=True) except Exception as exc: # noqa: BLE001 print(f"[trackio] init failed (continuing without): {exc}", flush=True) # hf_jobs uv runs the script with no argv; allow config via ORCA_ARGS if os.environ.get("ORCA_ARGS"): sys.argv += os.environ["ORCA_ARGS"].split() ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--dataset", required=True, choices=["blog", "fb1", "fb2"]) ap.add_argument("--runs", type=int, default=1) ap.add_argument("--methods", default="orca,pcp,cqr") ap.add_argument("--preproc", default="raw", choices=["raw", "logz"]) ap.add_argument("--out", required=True) ap.add_argument("--seed0", type=int, default=0) ap.add_argument("--stage2", default="milp", choices=["milp", "greedy"], help="stage-2 solver: milp (HiGHS, default; 0.15s on fb1) " "or greedy (greedy_warm_start + tighten)") ap.add_argument("--data-dir", default=DATA_DIR) ap.add_argument("--leaf_mode", default="split", choices=["leaf", "split"], help="QRF config: 'leaf' = min_samples_leaf=50 (current); " "'split' = min_samples_split=50, default leaf=1") ap.add_argument("--shared_draws", type=int, default=1, choices=[0, 1], help="1 = shared u per sample index k (paper default); " "0 = independent u per (row, k) [diag variant a]") ap.add_argument("--k_neighbor", type=int, default=5, choices=[5, 7], help="m for density ranking: 5 = ceil(sqrt(K)) (paper " "default); 7 = ceil(K/3) (official repo default)") ap.add_argument("--pcp_threshold", default="interp", choices=["interp", "ceil"], help="PCP calibration: 'interp' = np.quantile linear " "(torch.quantile, the PCP repo); 'ceil' = the " "conformal ceil((n+1)(1-alpha)) order statistic") args = ap.parse_args() methods = [m.strip() for m in args.methods.split(",") if m.strip()] for m in methods: assert m in ("orca", "pcp", "cqr"), m X, y = load_dataset(args.dataset, args.data_dir) print(f"[data] {args.dataset}: X{X.shape} y{y.shape} " f"leaf_mode={args.leaf_mode} pcp_threshold={args.pcp_threshold}", flush=True) header = ["dataset", "run_id", "method", "coverage", "eff", "n_test", "seconds", "preproc", "threshold_t", "n_explore", "n_calib", "stage2_seconds", "proxy_objective", "milp", "tighten_applied", "frac_neg_scores", "mean_len_before_inflation", "span_clipped", "leaf_mode", "pcp_threshold", "shared_draws", "k_neighbor"] write_header = not os.path.exists(args.out) all_rows = [] for run_id in range(args.runs): rows = one_run(args.dataset, X, y, run_id, args.seed0, methods, args.preproc, stage2=args.stage2, leaf_mode=args.leaf_mode, pcp_threshold=args.pcp_threshold, shared_draws=bool(args.shared_draws), k_neighbor=args.k_neighbor) all_rows.extend(rows) df = pd.DataFrame(rows, columns=header) df.to_csv(args.out, mode="a", header=write_header, index=False) write_header = False # live dashboard (one point per run per method) if os.environ.get("TRACKIO_SPACE_ID") and _trackio is not None: metrics = {} for method, gdf in df.groupby("method"): last = gdf.iloc[-1] metrics[f"{method}/coverage"] = float(last["coverage"]) metrics[f"{method}/eff"] = float(last["eff"]) try: _trackio.log(metrics, step=run_id) except Exception as exc: # noqa: BLE001 print(f"[trackio] log failed: {exc}", flush=True) # summary table: mean +- SE per method df = pd.DataFrame(all_rows, columns=header) print("\n=== summary (mean +- SE over runs) ===", flush=True) print(f"{'method':8s} {'coverage':>16s} {'eff':>16s}") for method, g in df.groupby("method"): cov_m, cov_s = g["coverage"].mean(), g["coverage"].sem() eff_m, eff_s = g["eff"].mean(), g["eff"].sem() print(f"{method:8s} {cov_m:.4f} +- {cov_s:.4f} " f"{eff_m:>16.4f} +- {eff_s:.4f}") total = df.groupby("method")["seconds"].sum() + df["seconds"].sum() * 0 print(f"\n[total] method seconds: {dict(total.round(1))}", flush=True) print(f"[out] rows appended to {args.out}", flush=True) if _trackio is not None: try: _trackio.finish() except Exception: # noqa: BLE001 pass if os.environ.get("ORCA_UPLOAD_REPO", "Devya27/orca-table3-repro"): try: from huggingface_hub import HfApi HfApi().upload_file( path_or_fileobj=args.out, path_in_repo=f"results/{args.dataset}.csv", repo_id=os.environ.get("ORCA_UPLOAD_REPO", "Devya27/orca-table3-repro"), repo_type="dataset", ) print(f"[upload] {args.out} -> results/{args.dataset}.csv " f"in {os.environ['ORCA_UPLOAD_REPO']}", flush=True) except Exception as exc: # noqa: BLE001 print(f"[upload] FAILED: {exc}", flush=True) if __name__ == "__main__": main()