File size: 5,596 Bytes
e30ad40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Stage 03b (v32b): rank qualified layers by best_reduction desc.

A layer is "safe" (per Stage 03 calibration with new mono rule):
  - best_alpha = argmax(reduction) over non-trivial alphas
  - path from α=1.0 → best_alpha is monotonic non-decreasing
  - best_reduction >= min_reduction (= 1.0 default)

Stage 03b just:
  1. Filter to safe layers.
  2. Rank by best_reduction descending.
  3. Emit N_max = len(safe layers), full ranking and per-layer alpha.

Stage 04 sweeps top-K of the ranking for various K.
"""
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


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dimension", default="monitoring")
    ap.add_argument("--alpha-floor",   type=float, default=0.0)
    ap.add_argument("--alpha-ceiling", type=float, default=0.99)
    ap.add_argument("--output-suffix", type=str, default="")
    args = ap.parse_args()

    ensure_dirs(args.dimension)
    cfg = get_config(args.dimension)
    p = dim_paths(args.dimension)

    out_path = p.SELECTED_LAYERS
    if args.output_suffix:
        base, ext = os.path.splitext(p.SELECTED_LAYERS)
        out_path = f"{base}{args.output_suffix}{ext}"

    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}] (v32b): rank by best_reduction desc")
    log.info(f"  non_trivial_alphas = {cfg.NON_TRIVIAL_ALPHAS}")
    log.info(f"  alpha_floor        = {args.alpha_floor}")
    log.info(f"  alpha_ceiling      = {args.alpha_ceiling}")
    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", {})

    cands = []
    skip_reasons = {"not_safe": 0, "high_alpha": 0}
    for L_str, d in per_layer.items():
        L = int(L_str)
        if not d.get("safe"):
            log.info(f"  L{L}: SKIP (not safe — fail mono or red < min)")
            skip_reasons["not_safe"] += 1
            continue
        best_a   = float(d.get("best_alpha", 1.0))
        best_red = float(d.get("best_reduction", 0.0))
        mono     = bool(d.get("fully_monotonic", False))
        if best_a >= args.alpha_ceiling:
            log.info(f"  L{L}: SKIP (best_alpha={best_a:.2f} >= ceiling)")
            skip_reasons["high_alpha"] += 1
            continue

        # Per-alpha audit table
        sweep = d.get("sweep_detail", {})
        per_alpha_red = {}
        for a in cfg.NON_TRIVIAL_ALPHAS:
            key = f"{a:.2f}"
            cell = sweep.get(key) or {}
            per_alpha_red[key] = float(cell.get("avg_reduction", 0.0))

        eff_a = max(best_a, args.alpha_floor)
        cands.append({
            "layer":           L,
            "alpha":           eff_a,
            "raw_best_alpha":  best_a,
            "best_reduction":  best_red,
            "per_alpha_red":   per_alpha_red,
            "mean_alpha_red":  sum(per_alpha_red.values()) / max(1, len(per_alpha_red)),
            "fully_monotonic": mono,
        })

    log.info(f"  qualification: {len(cands)} / {len(per_layer)} kept")
    log.info(f"  skip reasons: {skip_reasons}")
    if not cands:
        log.error("No layers qualified."); sys.exit(2)

    # Rank by best_reduction descending (user's spec for v32b)
    ranking = sorted(cands, key=lambda x: -x["best_reduction"])
    selected = ranking[:]
    selected_sorted = sorted(selected, key=lambda x: x["layer"])

    log.info(f"  N_max = {len(selected)}")
    log.info(f"  QUALIFIED LAYERS (layer-id ascending):")
    cum_p = cum_r = 0.0
    for it in selected_sorted:
        cum_p += 1 - it["alpha"]
        cum_r += it["best_reduction"]
        per_a = it["per_alpha_red"]
        log.info(f"    L{it['layer']:>2}  alpha={it['alpha']:.2f}  "
                 f"best_red={it['best_reduction']:+.2f}  "
                 f"per_a={ {k:f'{v:+.1f}' for k,v in per_a.items()} }")
    log.info(f"  Cum best-reduction: {cum_r:.2f}")
    log.info(f"  Cum pressure (sum(1-α)): {cum_p:.2f}")
    if cum_p > 5.0:
        log.warning(f"  Cum pressure {cum_p:.2f} > 5.0 — collapse risk in stage 04")

    log.info(f"  RANKING (by best_reduction desc, ranking[0] = picked first in top-N):")
    for r_, it in enumerate(ranking):
        log.info(f"    rank{r_+1:>2}: L{it['layer']:>2}  "
                 f"best_red={it['best_reduction']:+.2f}  "
                 f"alpha={it['alpha']:.2f}")

    out = {
        "dimension": cfg.NAME,
        "selected_layers":      [it["layer"] for it in selected_sorted],
        "alpha_per_layer":      {str(it["layer"]): it["alpha"] for it in selected_sorted},
        "ranking":              [it["layer"] for it in ranking],
        "ranking_full":         ranking,
        "rank_by":              "best_reduction_desc",
        "n_qualified":          len(ranking),
        "cumulative_best_reduction": cum_r,
        "cumulative_pressure_at_best_alpha": cum_p,
        "skip_reasons":         skip_reasons,
        "policy": "v32b_best_reduction_desc",
        "policy_params": {
            "alpha_floor":   args.alpha_floor,
            "alpha_ceiling": args.alpha_ceiling,
        },
    }
    write_json(out, out_path)
    log.info(f"Saved -> {out_path}")
    log.info("Done.")


if __name__ == "__main__":
    main()