File size: 7,242 Bytes
ae877b5 | 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 | #!/usr/bin/env python
"""Diagnostics for ORCA's conformal rescale t on fb2 (raw preproc, stage2=milp,
shared draws, seed 0 run):
a. MILP threshold vector Q_r (20 values, 3 decimals), count of ~0 entries,
proxy objective, exploration coverage after tighten (target ~0.902);
b. calib scores S = min_r E_cal,r / Q_r -> quantiles at
[0.5, 0.8, 0.85, 0.9, 0.95], fraction S <= 1.0 (unrescaled-set calib
coverage), and t (451st order statistic);
c. same fraction S <= 1.0 for the EXPLORE set;
d. unique-coverage concentration: for each rank r, the number of exploration
points covered by rank r and NO other rank; top 5 reported.
Defaults unchanged; no side effects on run_realdata.py's config.
"""
from __future__ import annotations
import argparse
import math
import numpy as np
from run_realdata import (
ALPHA, K, N_CALIB, N_EXPLORE, N_TEST, build_levels, coverage_count,
coverage_target, draw_samples, fit_qrf, load_dataset, rank_samples_by_density,
residual_matrix, solve_orca_milp, _proxy_objective, tighten_thresholds,
conformal_quantile,
)
QUANTILES = [0.5, 0.8, 0.85, 0.9, 0.95]
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--dataset", default="fb2", choices=["blog", "fb1", "fb2"])
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--preproc", default="raw", choices=["raw", "logz"])
ap.add_argument("--stage2", default="milp", choices=["milp", "greedy"])
ap.add_argument("--k_neighbor", type=int, default=5)
ap.add_argument("--shared_draws", type=int, default=1, choices=[0, 1])
ap.add_argument("--leaf_mode", default="split", choices=["leaf", "split"])
ap.add_argument("--data-dir", default="/work/orca_repro/data")
args = ap.parse_args()
seed = args.seed
rng = np.random.default_rng(seed)
X, y_full = load_dataset(args.dataset, args.data_dir)
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:]
y = y_full
if args.preproc == "logz":
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])
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 args.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
import time
t0 = time.time()
model = fit_qrf(X_train, y_train, seed=seed, leaf_mode=args.leaf_mode)
print(f"[diag] QRF fit {time.time() - t0:.1f}s", flush=True)
shared = bool(args.shared_draws)
# EXPLORE draws + ranked residuals (fresh draws in run_orca too; but shared
# mode still uses fresh draws for explore because only calib/test are shared)
S_exp = draw_samples(model, X_explore, K, rng, shared=shared)
ranked_exp = rank_samples_by_density(S_exp, args.k_neighbor)
E_explore = residual_matrix(y_explore, ranked_exp)
# stage-2 solver
import time as _t
_t0 = _t.time()
thresholds, beta_hat, details = solve_orca_milp(
E_explore, ALPHA, d=1, stage2=args.stage2)
print(f"[diag] stage2 ({args.stage2}) {(_t.time() - _t0):.2f}s "
f"status={details['status']} tighten={details.get('tighten_applied')}",
flush=True)
# (a) threshold vector
Q_r = np.asarray(thresholds, dtype=float)
n_zero = int((Q_r < 1e-8).sum())
proxy_obj = _proxy_objective(Q_r, 1)
cov_explore_milp = coverage_count(E_explore, Q_r) / len(y_explore)
print("\n=== (a) MILP thresholds Q_r (ranks 1..20) ===", flush=True)
print("Q_r = [" + ", ".join(f"{v:.3f}" for v in Q_r) + "]", flush=True)
print(f"count ~0 (Q_r < 1e-8): {n_zero} / {K}", flush=True)
print(f"proxy objective (sum Q_r): {proxy_obj:.4f}", flush=True)
print(f"exploration coverage after tighten: {cov_explore_milp:.4f} "
f"(target {coverage_target(len(y_explore), ALPHA)} / {len(y_explore)} = "
f"{coverage_target(len(y_explore), ALPHA) / len(y_explore):.4f})", flush=True)
# (b) calib scores S = min_r E_cal,r / Q_r
S_cal = draw_samples(model, X_calib, K, rng, shared=shared)
ranked_cal = rank_samples_by_density(S_cal, args.k_neighbor)
E_calib = residual_matrix(y_calib, ranked_cal)
ratios_cal = np.divide(E_calib, Q_r[None, :],
out=np.full(E_calib.shape, np.inf),
where=Q_r[None, :] > 0)
scores_cal = ratios_cal.min(axis=1)
print("\n=== (b) CALIB scores S = min_r E_cal,r / Q_r ===", flush=True)
qvals = np.quantile(scores_cal, QUANTILES)
for q, v in zip(QUANTILES, qvals):
print(f" S quantile {q:.2f}: {v:.4f}", flush=True)
frac_cal_le1 = float((scores_cal <= 1.0).mean())
t_alpha = conformal_quantile(scores_cal, ALPHA)
print(f"frac calib S <= 1.0 (unrescaled-set calib coverage): {frac_cal_le1:.4f}",
flush=True)
print(f"t (451st order statistic of calib S): {t_alpha:.4f}", flush=True)
# (c) explore scores
ratios_exp = np.divide(E_explore, Q_r[None, :],
out=np.full(E_explore.shape, np.inf),
where=Q_r[None, :] > 0)
scores_exp = ratios_exp.min(axis=1)
frac_exp_le1 = float((scores_exp <= 1.0).mean())
print("\n=== (c) EXPLORE scores S = min_r E_exp,r / Q_r ===", flush=True)
print(f"frac explore S <= 1.0 (unrescaled-set explore coverage): "
f"{frac_exp_le1:.4f}", flush=True)
print(f"explore - calib unrescaled-set coverage gap: "
f"{frac_exp_le1 - frac_cal_le1:+.4f}", flush=True)
# (d) unique-coverage concentration on the exploration set
covered_mask = E_explore <= Q_r[None, :] # (n_explore, K)
any_cov = covered_mask.any(axis=1)
counts_per_rank = covered_mask.sum(axis=0)
unique_counts = np.zeros(K, dtype=int)
for r in range(K):
others = np.delete(covered_mask, r, axis=1).any(axis=1)
unique_counts[r] = int((covered_mask[:, r] & ~others).sum())
order = np.argsort(unique_counts)[::-1]
print("\n=== (d) unique-coverage concentration (explore) ===", flush=True)
print("total covered by >=1 rank:", int(any_cov.sum()), flush=True)
print("points covered by exactly 1 rank:",
int(unique_counts.sum()), flush=True)
print("top 5 ranks by uniquely-covered points:", flush=True)
for r in order[:5]:
print(f" rank {r + 1}: {unique_counts[r]} unique / "
f"{int(counts_per_rank[r])} total covered by this rank", flush=True)
print("unique_counts (ranks 1..20):", unique_counts.tolist(), flush=True)
if __name__ == "__main__":
main()
|