File size: 5,037 Bytes
d775561 | 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 | """
Stage 03b (v8b): select the layers to KEEP.
Keep a layer iff, over the calibration sub-sweep 0.7 -> 0.3 -> 0.0:
(a) the reflection reduction is monotonic (non-decreasing as alpha
drops from the 1.0 baseline down to 0.0, within `slack`), AND
(b) EVERY one of those three alpha reductions is STRICTLY > min_reduction.
i.e. starting from the alpha=1.0 baseline (reduction 0), reflection
"steps down" at every alpha and each step removes more than `min_reduction`
markers. No top-N truncation — every qualifying layer is kept.
Reads: calibration_monitoring.json (from stage 03, read-only)
Writes: selected_layers_monitoring.json
"""
import os, sys, argparse
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from configs import get_config
from configs.paths import LOG_DIR, dim_paths, ensure_dirs
from src.utils import read_json, write_json, setup_logger
DEFAULT_SLACK = 0.5
SUBSWEEP = ["0.70", "0.30", "0.00"] # 1.00 is the baseline (reduction 0)
def _red(sweep_detail, key):
d = sweep_detail.get(key)
return float(d["avg_reduction"]) if d else None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dimension", default="monitoring")
ap.add_argument("--slack", type=float, default=DEFAULT_SLACK,
help="Monotonicity slack (reduction may dip by up to this).")
ap.add_argument("--min-reduction", type=float, default=1.0,
help="Keep layer iff EVERY alpha reduction is STRICTLY > this.")
args = ap.parse_args()
ensure_dirs(args.dimension)
cfg = get_config(args.dimension)
p = dim_paths(args.dimension)
out_path = p.SELECTED_LAYERS
log = setup_logger("03b_select", os.path.join(LOG_DIR, f"03b_select_{cfg.NAME}.log"))
log.info("=" * 72)
log.info(f"Stage 03b [{cfg.NAME}] select KEEP layers")
log.info(f" criterion: monotonic over {SUBSWEEP} (slack={args.slack}) "
f"AND EVERY alpha reduction > {args.min_reduction}")
log.info(f" output -> {out_path}")
log.info("=" * 72)
if not os.path.exists(p.CALIBRATION):
log.error(f"missing {p.CALIBRATION} — run stage 03 first"); sys.exit(1)
calib = read_json(p.CALIBRATION)
per_layer = calib.get("calibration_per_layer", {})
log.info(f" layers in calibration: {len(per_layer)}")
cands = []
for L_str, d in per_layer.items():
L = int(L_str)
sd = d.get("sweep_detail", {})
reds = [_red(sd, k) for k in SUBSWEEP]
if any(r is None for r in reds):
log.info(f" L{L}: SKIP (missing sweep points)")
continue
mono = all(reds[i] >= reds[i - 1] - args.slack for i in range(1, len(reds)))
achievable = max(reds)
best_idx = max(range(len(reds)), key=lambda i: reds[i])
best_alpha = float(SUBSWEEP[best_idx])
if not mono:
log.info(f" L{L}: SKIP (not mono 0.7->0; reds={['%.2f' % r for r in reds]})")
continue
if not all(r > args.min_reduction for r in reds):
log.info(f" L{L}: SKIP (some alpha <= {args.min_reduction}; "
f"reds={['%.2f' % r for r in reds]})")
continue
cands.append({
"layer": L,
"alpha": best_alpha,
"achieved_red": achievable,
"reds_0p7_0p3_0p0": [round(r, 3) for r in reds],
"fully_monotonic": bool(d.get("fully_monotonic", False)),
"safe": bool(d.get("safe", False)),
})
if not cands:
log.error("No layers passed the 0.7->0 mono + every-alpha>min filter.")
sys.exit(2)
cands.sort(key=lambda x: x["layer"])
log.info(f" KEEP {len(cands)} layers:")
cum_r = 0.0
for it in cands:
cum_r += it["achieved_red"]
ff = "" if it["fully_monotonic"] else " [not-full-mono]"
log.info(f" L{it['layer']:>2} best_a={it['alpha']:.2f} "
f"red={it['achieved_red']:+.2f} "
f"reds(0.7/0.3/0)={it['reds_0p7_0p3_0p0']}{ff}")
log.info(f" cumulative achievable reduction: {cum_r:.2f}")
alpha_per_layer = {it["layer"]: it["alpha"] for it in cands}
out = {
"dimension": cfg.NAME,
"selected_layers": sorted(alpha_per_layer.keys()),
"alpha_per_layer": {str(L): v for L, v in alpha_per_layer.items()},
"work_alpha": 0.7,
"n_selected": len(alpha_per_layer),
"cumulative_reduction": cum_r,
"policy": "every_alpha_gt_min_and_monotonic_no_topn",
"policy_params": {
"subsweep": SUBSWEEP,
"slack": args.slack,
"min_reduction": args.min_reduction,
"rule": "EVERY alpha reduction > min AND monotonic from baseline",
},
"per_layer_diagnostics": cands,
}
write_json(out, out_path)
log.info(f"Saved {out_path} ({len(alpha_per_layer)} layers). Done.")
print("SELECTED_LAYERS =", sorted(alpha_per_layer.keys()))
print("OUTPUT =", out_path)
if __name__ == "__main__":
main()
|