"""Generate one self-contained ablation copy of foldsrunner_newest_segformer.py per experiment. The ORIGINAL script is never modified. Each generated copy (ablations/.py): * hardcodes the repo root so it can live in this subfolder, * uses its own MODEL_NAME -> outputs go to a separate runs/ subtree, * trains ONLY strategy 3 and reuses the EXISTING frozen strategy-2 base checkpoint via STRATEGY2_SPECIFIC_CHECKPOINT, * bakes in exactly one ablation (code edit and/or dedicated param JSON). Run: python ablations/_generate_ablations.py Re-runnable and idempotent. Asserts every anchor is found exactly once so a stale anchor fails loudly instead of producing a broken copy. """ from __future__ import annotations import json from pathlib import Path REPO = Path(__file__).resolve().parent.parent ORIG = REPO / "foldsrunner_newest_segformer.py" OUT_DIR = REPO / "ablations" PARAM_DIR = REPO / "param_segformer" BASE_PARAM = PARAM_DIR / "best_params_strat3.json" BASE_CKPT_REL = ( "runs/Segformer_B0_revamped_nt_2/repeated_holdout/stratified_holdout_v1/" "phase_001/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt" ) src_original = ORIG.read_text(encoding="utf-8") base_params = json.loads(BASE_PARAM.read_text(encoding="utf-8")) # -------------------------------------------------------------------------- # Anchors (must each appear exactly once in the original). # -------------------------------------------------------------------------- MANUAL_HPARAMS_ANCHOR = ( 'MANUAL_HPARAMS_IF_OPTUNA_OFF: dict[str, str] = {\n' ' "2:100": "param_segformer/best_params_strat2.json",\n' ' "3:100": "param_segformer/best_params_strat3.json",\n' '}' ) RL_LOSS_ANCHOR = ( " rl_loss = rl_loss_scale * (actor_loss_tensor + critic_loss_weight * critic_loss_tensor)" ) FRS_ANCHOR = ( " def forward_refinement_state(\n" " self,\n" " base_features: torch.Tensor,\n" " current_mask: torch.Tensor,\n" " decoder_prob: torch.Tensor,\n" " mc_variance: torch.Tensor,\n" " pred_entropy: torch.Tensor,\n" " encoder_features: list[torch.Tensor] | None = None,\n" " ) -> torch.Tensor:\n" " boundary = _differentiable_boundary(current_mask, kernel_size=3)\n" " conditioning = torch.cat(\n" " [\n" " decoder_prob.to(dtype=base_features.dtype),\n" " current_mask.to(dtype=base_features.dtype),\n" " boundary.to(dtype=base_features.dtype),\n" " mc_variance.to(dtype=base_features.dtype),\n" " pred_entropy.to(dtype=base_features.dtype),\n" " ],\n" " dim=1,\n" " )\n" " fused = self.refinement_adapter(torch.cat([base_features, conditioning], dim=1))\n" " if encoder_features is not None:\n" " ms_feat = self.multi_scale_refine(encoder_features, output_size=fused.shape[-2:])\n" " fused = fused + ms_feat\n" " return self.sam.forward_features(fused)" ) def assert_once(text: str, anchor: str, label: str) -> None: n = text.count(anchor) if n != 1: raise SystemExit(f"[generator] anchor {label!r} found {n} times (expected 1). Aborting.") for anchor, label in [ (MANUAL_HPARAMS_ANCHOR, "MANUAL_HPARAMS"), (RL_LOSS_ANCHOR, "RL_LOSS"), (FRS_ANCHOR, "FORWARD_REFINEMENT_STATE"), ]: assert_once(src_original, anchor, label) def build_frs(*, boundary=True, mcvar=True, predentropy=True, multiscale=True, sam=True, tag="") -> str: """Rebuild the SMP forward_refinement_state; defaults reproduce the original byte-for-byte.""" def chan(expr): keep, gained = expr return f" {gained}," if keep else f" {gained} * 0.0," boundary_line = " boundary.to(dtype=base_features.dtype)" + ("," if boundary else " * 0.0,") mcvar_line = " mc_variance.to(dtype=base_features.dtype)" + ("," if mcvar else " * 0.0,") pe_line = " pred_entropy.to(dtype=base_features.dtype)" + ("," if predentropy else " * 0.0,") if multiscale: ms_block = ( " if encoder_features is not None:\n" " ms_feat = self.multi_scale_refine(encoder_features, output_size=fused.shape[-2:])\n" " fused = fused + ms_feat\n" ) else: ms_block = " # ABLATION: multi-scale residual branch disabled\n" sam_return = " return self.sam.forward_features(fused)" if sam else " return fused # ABLATION: SAM disabled" return ( " def forward_refinement_state(\n" " self,\n" " base_features: torch.Tensor,\n" " current_mask: torch.Tensor,\n" " decoder_prob: torch.Tensor,\n" " mc_variance: torch.Tensor,\n" " pred_entropy: torch.Tensor,\n" " encoder_features: list[torch.Tensor] | None = None,\n" " ) -> torch.Tensor:\n" " boundary = _differentiable_boundary(current_mask, kernel_size=3)\n" " conditioning = torch.cat(\n" " [\n" " decoder_prob.to(dtype=base_features.dtype),\n" " current_mask.to(dtype=base_features.dtype),\n" f"{boundary_line}\n" f"{mcvar_line}\n" f"{pe_line}\n" " ],\n" " dim=1,\n" " )\n" " fused = self.refinement_adapter(torch.cat([base_features, conditioning], dim=1))\n" f"{ms_block}" f"{sam_return}" ) # Safety: default build must equal the original method exactly. if build_frs() != FRS_ANCHOR: raise SystemExit("[generator] build_frs() default does not reproduce the original method. Aborting.") RL_ACTOR_ONLY = " rl_loss = rl_loss_scale * (actor_loss_tensor + 0.0 * critic_loss_tensor)" RL_DISABLED = " rl_loss = rl_loss_scale * (0.0 * actor_loss_tensor + 0.0 * critic_loss_tensor) # ABLATION: RL off" # -------------------------------------------------------------------------- # Variant specification table. # frs : kwargs for build_frs (None -> keep original) # rl : replacement for the rl_loss line (None -> keep original) # params : dict of param overrides written to a dedicated JSON (None -> baseline JSON) # -------------------------------------------------------------------------- VARIANTS = [ dict(name="abl_ab0_control", model="Segformer_B0_AB0_control", desc="Baseline control (no ablation) under the ablation harness / fresh MODEL_NAME."), dict(name="abl_ab1_no_critic", model="Segformer_B0_AB1_no_critic", desc="AB-1: critic loss removed (value head kept, contributes no gradient).", rl=RL_ACTOR_ONLY), # AB-2 rollout length (hyperparameter only). dict(name="abl_ab2_tmax1", model="Segformer_B0_AB2_tmax1", desc="AB-2: Tmax=1.", params={"tmax": 1}), dict(name="abl_ab2_tmax2", model="Segformer_B0_AB2_tmax2", desc="AB-2: Tmax=2.", params={"tmax": 2}), dict(name="abl_ab2_tmax4", model="Segformer_B0_AB2_tmax4", desc="AB-2: Tmax=4.", params={"tmax": 4}), dict(name="abl_ab2_tmax6", model="Segformer_B0_AB2_tmax6", desc="AB-2: Tmax=6.", params={"tmax": 6}), dict(name="abl_ab2_tmax10", model="Segformer_B0_AB2_tmax10", desc="AB-2: Tmax=10.", params={"tmax": 10}), # AB-3 reward decomposition (hyperparameter only). dict(name="abl_ab3_r1_only", model="Segformer_B0_AB3_r1_only", desc="AB-3: r1 (progress) only; BIoU reward weight = 0.", params={"strategy3_r1_progress_weight": 1.0, "biou_reward_weight": 0.0}), dict(name="abl_ab3_r3_only", model="Segformer_B0_AB3_r3_only", desc="AB-3: r3 (differentiable BIoU) only; progress weight = 0.", params={"strategy3_r1_progress_weight": 0.0, "biou_reward_weight": 1.0}), # AB-4 reward vs auxiliary supervised loss. dict(name="abl_ab4_reward_only", model="Segformer_B0_AB4_reward_only", desc="AB-4: reward only; auxiliary supervised loss disabled.", params={"strategy3_aux_ce_weight": 0.0}), dict(name="abl_ab4_aux_only", model="Segformer_B0_AB4_aux_only", desc="AB-4: aux supervised loss only; RL (actor+critic) disabled, aux active from epoch 1.", rl=RL_DISABLED, params={"strategy3_aux_ce_weight": 0.4, "strategy3_aux_ce_anneal_start_epoch": 1, "strategy3_aux_ce_anneal_epochs": 0, "strategy3_aux_ce_floor_fraction": 1.0}), # AB-5 uncertainty state channels. dict(name="abl_ab5_no_mcvar", model="Segformer_B0_AB5_no_mcvar", desc="AB-5a: mc_variance channel zeroed.", frs=dict(mcvar=False)), dict(name="abl_ab5_no_predentropy", model="Segformer_B0_AB5_no_predentropy", desc="AB-5b: pred_entropy channel zeroed.", frs=dict(predentropy=False)), dict(name="abl_ab5_no_uncertainty", model="Segformer_B0_AB5_no_uncertainty", desc="AB-5c: both uncertainty channels zeroed and MC dropout disabled (compute recovery).", frs=dict(mcvar=False, predentropy=False), params={"strategy3_mc_dropout_enabled": False}), # AB-6 / AB-7 architecture. dict(name="abl_ab6_no_multiscale", model="Segformer_B0_AB6_no_multiscale", desc="AB-6: multi-scale residual branch disabled.", frs=dict(multiscale=False)), dict(name="abl_ab7_no_sam", model="Segformer_B0_AB7_no_sam", desc="AB-7: self-attention module replaced by identity.", frs=dict(sam=False)), # AB-8 minimal state. dict(name="abl_ab8_minimal_state", model="Segformer_B0_AB8_minimal_state", desc="AB-8: minimal conditioning [P, M_t]; boundary + both uncertainty channels zeroed.", frs=dict(boundary=False, mcvar=False, predentropy=False)), dict(name="abl_ab8_no_boundary", model="Segformer_B0_AB8_no_boundary", desc="AB-8b: boundary channel zeroed.", frs=dict(boundary=False)), ] PROJECT_DIR_NEW = ( 'PROJECT_DIR = Path(__file__).resolve().parent.parent ' '# ABLATION: repo root (this copy lives in ablations/)' ) def harness_block(model_name: str, param_json_rel: str) -> str: return ( MANUAL_HPARAMS_ANCHOR + "\n\n" + "# ===================== ABLATION HARNESS OVERRIDE =====================\n" + "# Auto-generated. Outputs go to a separate MODEL_NAME subtree; strategy 3\n" + "# only; the frozen strategy-2 base is reused from the original run tree.\n" + f'MODEL_NAME = "{model_name}"\n' + "STRATEGIES = [3]\n" + 'STRATEGY2_CHECKPOINT_MODE = "specific"\n' + 'STRATEGY2_SPECIFIC_CHECKPOINT = {1: str(PROJECT_DIR / ' + f'"{BASE_CKPT_REL}")}}\n' + "MANUAL_HPARAMS_IF_OPTUNA_OFF = {**MANUAL_HPARAMS_IF_OPTUNA_OFF, " + f'"3:100": "{param_json_rel}"}}\n' + "# =====================================================================" ) def replace_project_dir(text: str) -> str: lines = text.split("\n") hits = [i for i, ln in enumerate(lines) if ln.startswith("PROJECT_DIR = Path(__file__).resolve().parent")] if len(hits) != 1: raise SystemExit(f"[generator] PROJECT_DIR line found {len(hits)} times (expected 1).") lines[hits[0]] = PROJECT_DIR_NEW return "\n".join(lines) manifest = [] for v in VARIANTS: text = src_original # 1) hardcode repo root text = replace_project_dir(text) # 2) param JSON (dedicated file if overrides, else baseline) if v.get("params"): merged = {**base_params, **v["params"]} pj_rel = f"param_segformer/{v['name']}.json" (PARAM_DIR / f"{v['name']}.json").write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8") else: pj_rel = "param_segformer/best_params_strat3.json" # 3) harness override (MODEL_NAME, STRATEGIES=[3], base checkpoint, param repoint) text = text.replace(MANUAL_HPARAMS_ANCHOR, harness_block(v["model"], pj_rel), 1) # 4) code edits if v.get("frs"): text = text.replace(FRS_ANCHOR, build_frs(**v["frs"]), 1) if v.get("rl"): text = text.replace(RL_LOSS_ANCHOR, v["rl"], 1) out_path = OUT_DIR / f"{v['name']}.py" out_path.write_text(text, encoding="utf-8") manifest.append({"name": v["name"], "model_name": v["model"], "description": v["desc"], "param_json": pj_rel, "script": f"ablations/{v['name']}.py"}) (OUT_DIR / "ablation_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") print(f"[generator] wrote {len(manifest)} ablation scripts to {OUT_DIR}") for m in manifest: print(f" {m['name']:28s} -> MODEL_NAME={m['model_name']}")