8b / scripts /03_calibrate.py
JulianHJR's picture
Add files using upload-large-folder tool
d775561 verified
Raw
History Blame Contribute Delete
8.12 kB
"""
Stage 03 (v8b): Per-layer alpha sweep + monotonicity gate.
Sweep over THREE alphas {0.0, 0.3, 0.7} for each kept layer. For each
alpha and each "active" calibration problem, run inference with the
direction at that alpha and compute the reduction in reflection-marker
count vs. the baseline (alpha = 1.0).
Calibration problems = the LAST CALIBRATION_N_TEST (=15) problems of
RAW_COTS_PATH, regenerated at baseline.
Detector here is the regex-based BehaviorDetector (configs/monitoring.py
PATTERNS) — the EVALUATION instrument only; the direction itself was
learned without it.
A layer is KEPT (safe) if some alpha < 1.0 reduces reflection by >=
min_reduction while staying within side-effect budget.
Resume: per-layer JSON cache (one file per layer) + baseline cache.
"""
import argparse, json, os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import torch
from tqdm import tqdm
from configs import get_config
from configs.paths import RAW_COTS_PATH, LOG_DIR, dim_paths, ensure_dirs
from src.calibration import calibrate_all_layers
from src.detectors import BehaviorDetector
from src.interventions import generate_plain
from src.utils import (
build_chat_prompt, get_device, load_model_and_tokenizer,
read_jsonl, setup_logger, write_json, think_segment,
)
MIN_REDUCTION = 1.0
def get_problem(item):
for k in ("problem", "question", "query", "Problem"):
if k in item and item[k]:
return item[k]
return ""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dimension", default="monitoring")
ap.add_argument("--n-test", type=int, default=None)
ap.add_argument("--active-threshold", type=int, default=None)
ap.add_argument("--side-effect-rate", type=float, default=None)
ap.add_argument("--gen-max-tokens", type=int, default=None)
ap.add_argument("--min-reduction", type=float, default=MIN_REDUCTION)
ap.add_argument("--force", action="store_true", help="Wipe caches and recompute.")
args = ap.parse_args()
ensure_dirs(args.dimension)
cfg = get_config(args.dimension)
p = dim_paths(args.dimension)
n_test = args.n_test or cfg.CALIBRATION_N_TEST
active_threshold = (args.active_threshold
if args.active_threshold is not None
else cfg.CALIBRATION_ACTIVE_THRESHOLD)
side_rate = (args.side_effect_rate
if args.side_effect_rate is not None
else cfg.CALIBRATION_SIDE_EFFECT_RATE)
gen_max = args.gen_max_tokens or cfg.GEN_MAX_NEW_TOKENS
severe_repetition = float(getattr(cfg, "SEVERE_REPETITION", 0.3))
log = setup_logger("03_calibrate",
os.path.join(LOG_DIR, f"03_calibrate_{cfg.NAME}.log"))
log.info("=" * 70)
log.info(f"Stage 03 [{cfg.NAME}] (v8b) "
f"n_test={n_test} active_thr={active_threshold} side_rate={side_rate}")
log.info(f" alphas={cfg.NON_TRIVIAL_ALPHAS} min_reduction={args.min_reduction}")
log.info(f" severe_repetition_skip={severe_repetition} (layer abandoned early if any alpha/case loops)")
log.info("=" * 70)
if not os.path.exists(p.DIRECTIONS):
log.error(f"missing {p.DIRECTIONS} — run stage 02 first"); sys.exit(1)
blob = torch.load(p.DIRECTIONS, map_location="cpu", weights_only=False)
directions = {int(k): v for k, v in blob["directions"].items()}
only_env = os.environ.get("CALIB_ONLY_LAYERS", "").strip()
if only_env:
wanted = {int(x) for x in only_env.replace(",", " ").split()}
directions = {L: v for L, v in directions.items() if int(L) in wanted}
log.info(f"CALIB_ONLY_LAYERS active: {sorted(wanted)}")
if not directions:
log.error("No directions left for calibration after CALIB_ONLY_LAYERS filter.")
sys.exit(2)
log.info(f"Loaded {len(directions)} layers: {sorted(directions.keys())}")
if args.force:
for f_ in [p.CALIB_BASELINE]:
if os.path.exists(f_):
os.remove(f_)
import shutil
if os.path.isdir(p.CALIB_PER_LAYER):
shutil.rmtree(p.CALIB_PER_LAYER)
log.info("[force] caches cleared")
raw = read_jsonl(RAW_COTS_PATH)
problems = [get_problem(it) for it in raw if get_problem(it)]
test_items = problems[-n_test:]
log.info(f" calibration problems: {len(test_items)}")
device = get_device()
log.info("Loading model...")
model, tokenizer = load_model_and_tokenizer(device=device)
detector = BehaviorDetector(cfg)
samples = None
if os.path.exists(p.CALIB_BASELINE):
try:
with open(p.CALIB_BASELINE) as f_:
cached = json.load(f_)
reuse_any = os.environ.get("REUSE_CALIB_BASELINE", "0") == "1"
ok_strict = (cached.get("n_test") == n_test
and cached.get("gen_max") == gen_max
and cached.get("active_threshold") == active_threshold
and len(cached.get("samples", [])) == n_test)
if ok_strict or (reuse_any and len(cached.get("samples", [])) > 0):
samples = cached["samples"]
log.info(f" [resume] loaded {len(samples)} baselines from cache"
f" (reuse_any={reuse_any}, strict={ok_strict})")
except Exception as e:
log.warning(f" [resume] baseline cache unreadable ({e}); recomputing")
if samples is None:
samples = []
for prob in tqdm(test_items, desc=" baselines"):
prompt = build_chat_prompt(tokenizer, prob, enable_thinking=True)
text = generate_plain(model, tokenizer, prompt, device,
max_new_tokens=gen_max)
n = detector.detect(think_segment(text))["total"]
samples.append({
"prompt": prompt,
"behavior_count": int(n),
"baseline_text": text,
"problem": prob,
})
blob2 = {
"n_test": n_test, "gen_max": gen_max,
"active_threshold": active_threshold, "samples": samples,
}
tmp = p.CALIB_BASELINE + ".tmp"
with open(tmp, "w", encoding="utf-8") as f_:
json.dump(blob2, f_, indent=2, ensure_ascii=False)
os.replace(tmp, p.CALIB_BASELINE)
log.info(" baseline cache saved")
active = [s for s in samples if s["behavior_count"] >= active_threshold]
inactive = [s for s in samples if s["behavior_count"] < active_threshold]
log.info(f" active={len(active)} inactive={len(inactive)}")
log.info(f" baseline counts: {[s['behavior_count'] for s in samples]}")
if not active:
log.error("No active samples. Lower active_threshold or raise gen_max_tokens.")
sys.exit(3)
results = calibrate_all_layers(
model, tokenizer, directions, list(cfg.NON_TRIVIAL_ALPHAS), device,
active, inactive, detector,
side_effect_rate=side_rate, min_reduction=args.min_reduction,
gen_max_tokens=gen_max, logger=log,
per_layer_dir=p.CALIB_PER_LAYER,
severe_repetition=severe_repetition,
)
kept = [L for L, r in results.items() if r["safe"]]
best_alpha_per_layer = {int(L): float(results[L]["best_alpha"]) for L in kept}
log.info(f"KEEP layers: {sorted(kept)}")
log.info(f"best_alpha_per_layer: {best_alpha_per_layer}")
save = {
"dimension": cfg.NAME,
"n_test": n_test,
"active_threshold": active_threshold,
"side_effect_rate": side_rate,
"min_reduction": args.min_reduction,
"severe_repetition": severe_repetition,
"n_active": len(active),
"n_inactive": len(inactive),
"baseline_counts": [s["behavior_count"] for s in samples],
"calibration_per_layer": {str(L): r for L, r in results.items()},
"kept_layers": sorted(kept),
"best_alpha_per_layer": {str(L): v for L, v in best_alpha_per_layer.items()},
}
write_json(save, p.CALIBRATION)
log.info(f"Saved {p.CALIBRATION}. Done.")
if __name__ == "__main__":
main()