"""Phase 2 zero-training measurement: fertility, boundary alignment, entropy profile, entropy trough depth, AdaMTP boundary-detection recall, and D_indep, for one condition. Run once per condition (L1, L2, L3, L4, L5, E1, E2), each pinned to a single physical GPU via CUDA_VISIBLE_DEVICES by the caller -- these are independent single-GPU jobs, no DDP, no model parallelism. See configs/phase2.yaml for the condition -> (model, text column, GPU) mapping and the reduced-sample-size rationale. """ import argparse import csv import logging import os os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID") import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import torch import yaml from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer from src.measure.boundary import _word_boundary_positions, compute_boundary_alignment from src.measure.boundary_detection import SentenceEntropyTrace, calibrate_tau, score_boundary_detection from src.measure.d_indep import d_indep_k2, d_indep_k3 from src.measure.entropy import boundary_token_positions_from_offsets, compute_entropy_profile, entropy_trough_depth from src.measure.fertility import compute_fertility from src.measure.model_handle import ModelHandle logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logging.getLogger("httpx").setLevel(logging.WARNING) logging.getLogger("huggingface_hub").setLevel(logging.WARNING) logger = logging.getLogger("phase2") def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--config", default="configs/phase2.yaml") p.add_argument("--condition", required=True, choices=["L1", "L2", "L3", "L4", "L5", "E1", "E2"]) p.add_argument("--out", required=True, help="per-condition output CSV path") return p.parse_args() def load_handle(model_cfg: dict, device: str) -> ModelHandle: is_seq2seq = model_cfg["kind"] == "seq2seq" tok = AutoTokenizer.from_pretrained(model_cfg["hf_id"]) cls = AutoModelForSeq2SeqLM if is_seq2seq else AutoModelForCausalLM model = cls.from_pretrained(model_cfg["hf_id"], dtype=torch.float32).to(device) model.eval() return ModelHandle(model, tok, device, is_seq2seq=is_seq2seq, is_byte_level=is_seq2seq) def load_sentences(cfg: dict, condition_cfg: dict, n: int, seed: int) -> list: import random path = cfg["english_control_csv"] if condition_cfg.get("source") == "english" else cfg["fertility_triples_csv"] rows = list(csv.DictReader(open(path, encoding="utf-8"))) col = condition_cfg["text_column"] texts = [r[col] for r in rows if r.get(col, "").strip()] rng = random.Random(seed) if len(texts) > n: texts = rng.sample(texts, n) return texts def run_condition(cfg: dict, condition: str, out_path: str) -> None: condition_cfg = cfg["conditions"][condition] model_cfg = cfg["models"][condition_cfg["model"]] device = "cuda:0" # process is already pinned to one physical GPU via CUDA_VISIBLE_DEVICES logger.info("condition=%s model=%s text_column=%s", condition, condition_cfg["model"], condition_cfg["text_column"]) handle = load_handle(model_cfg, device) sentences = load_sentences(cfg, condition_cfg, cfg["sentences_per_condition"], cfg["seed"]) logger.info("running on %d sentences", len(sentences)) fert = compute_fertility(handle, sentences) logger.info("fertility: mean=%.4f median=%.4f stdev=%.4f", fert.mean, fert.median, fert.stdev) generator = torch.Generator(device=device).manual_seed(cfg["seed"]) max_positions = cfg["max_positions_per_sentence"] max_horizon = cfg["max_horizon"] all_points = [] alignments = [] traces = [] d2_vals, d3_vals = [], [] for i, s in enumerate(sentences): tokenized = handle.encode(s) if tokenized.ids.shape[0] < 4: continue alignments.append(compute_boundary_alignment(handle, tokenized)) gold_pos = _word_boundary_positions(tokenized.text if not handle.is_byte_level else tokenized.text.encode("utf-8").decode("latin-1")) boundary_tok_pos = boundary_token_positions_from_offsets(tokenized, gold_pos) points = compute_entropy_profile(handle, tokenized, boundary_tok_pos, max_horizon=max_horizon, generator=generator, max_positions=max_positions) all_points.extend(points) h1 = sorted([p for p in points if p.horizon == 1], key=lambda p: p.position) if len(h1) >= 2: traces.append(SentenceEntropyTrace(entropies=[p.entropy for p in h1], is_boundary=[p.is_boundary for p in h1])) ids = tokenized.ids if ids.shape[0] > 3: prefix = ids[:2] d2_vals.append(d_indep_k2(handle, prefix)) d3_vals.append(d_indep_k3(handle, prefix, m=cfg["monte_carlo_samples"], generator=generator)) if (i + 1) % 10 == 0: logger.info(" %d/%d sentences processed", i + 1, len(sentences)) trough = entropy_trough_depth(all_points) mean_alignment = sum(alignments) / len(alignments) if alignments else float("nan") mean_d2 = sum(d2_vals) / len(d2_vals) if d2_vals else float("nan") mean_d3 = sum(d3_vals) / len(d3_vals) if d3_vals else float("nan") tau = calibrate_tau(traces, target_group_size=cfg["adamtp_target_group_size"]) if traces else float("nan") detection = score_boundary_detection(traces, tau) if traces and tau == tau else None logger.info("trough_depth=%.4f mean_alignment=%.4f d_indep_k2=%.4f d_indep_k3=%.4f", trough, mean_alignment, mean_d2, mean_d3) if detection: logger.info("adamtp tau=%.4f precision=%.4f recall=%.4f", detection.tau, detection.precision, detection.recall) rows_out = [ ("fertility_mean", fert.mean, len(fert.values)), ("fertility_median", fert.median, len(fert.values)), ("fertility_stdev", fert.stdev, len(fert.values)), ("boundary_alignment_fraction", mean_alignment, len(alignments)), ("entropy_trough_depth", trough, len(all_points)), ("d_indep_k2", mean_d2, len(d2_vals)), ("d_indep_k3", mean_d3, len(d3_vals)), ] if detection: rows_out += [ ("adamtp_tau", detection.tau, len(traces)), ("adamtp_precision", detection.precision, len(traces)), ("adamtp_recall", detection.recall, len(traces)), ] for horizon in range(1, max_horizon + 1): for tag, want_boundary in (("intraword", False), ("boundary", True)): vals = [p.entropy for p in all_points if p.horizon == horizon and p.is_boundary == want_boundary] if vals: rows_out.append((f"entropy_i{horizon}_{tag}", sum(vals) / len(vals), len(vals))) Path(out_path).parent.mkdir(parents=True, exist_ok=True) with open(out_path, "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["condition", "metric", "value", "n"]) for metric, value, n in rows_out: writer.writerow([condition, metric, value, n]) logger.info("wrote %s", out_path) def main() -> None: args = parse_args() with open(args.config, encoding="utf-8") as f: cfg = yaml.safe_load(f) logger.info("config: %s condition=%s", cfg, args.condition) run_condition(cfg, args.condition, args.out) if __name__ == "__main__": main()