"""Blocker B: is L5's entropy trough depth an artifact of how ByT5 is driven? Phase 2 predicted entropy trough depth would separate L1 from L5 most sharply; measured, they were nearly identical (0.790 vs 0.809). The leading suspect is that ByT5 was driven with the prefix mirrored into its bidirectional encoder, so it saw the prefix in a way L1-L4's causal models never do -- which would systematically deflate its conditional entropies. This runs L5's entropy profile in both driving modes over the same sentences. If trough depth moves materially, the Phase 2 number was an architecture artifact; if it does not, the failed prediction is a real property of the ladder needing a different explanation. """ import argparse import csv import json 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 from src.measure.entropy import ( POSITION_STRATEGY_FIRST, POSITION_STRATEGY_SPREAD, boundary_token_positions_from_offsets, compute_entropy_profile, entropy_trough_depth, ) from src.measure.model_handle import SEQ2SEQ_MODE_CAUSAL, SEQ2SEQ_MODE_MIRRORED, 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("phase2b_b") MIN_TOKENS = 4 def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--config", default="configs/phase2b.yaml") p.add_argument("--out", required=True) p.add_argument("--limit", type=int, default=None) p.add_argument("--max-horizon", type=int, default=None, help="override; trough depth only needs 1") p.add_argument( "--model", default=None, help="models key; defaults to blocker_b.model. Causal models ignore the driving-mode axis.", ) p.add_argument("--text-column", default=None) p.add_argument( "--texts-csv", default=None, help="source CSV for sentences; defaults to the Hindi fertility triples. " "The English control conditions (E1/E2) live in a separate file.", ) p.add_argument( "--strategies", default=f"{POSITION_STRATEGY_FIRST},{POSITION_STRATEGY_SPREAD}", help="comma-separated position strategies to evaluate", ) return p.parse_args() def profile_in_mode(handle: ModelHandle, texts: list, cfg: dict, mode: str, position_strategy: str) -> dict: """Entropy profile and trough depth over texts under one (driving mode, position strategy) pair.""" handle.seq2seq_mode = mode device = handle.device generator = torch.Generator(device=device).manual_seed(cfg["seed"]) all_points = [] for i, text in enumerate(texts): tokenized = handle.encode(text) if tokenized.ids.shape[0] < MIN_TOKENS: continue # byte-level offsets are byte indices, so boundary detection has to # run on the byte string to line up with them; character offsets # otherwise reference = tokenized.text.encode("utf-8").decode("latin-1") if handle.is_byte_level else tokenized.text gold = _word_boundary_positions(reference) boundary_pos = boundary_token_positions_from_offsets(tokenized, gold) all_points.extend( compute_entropy_profile( handle, tokenized, boundary_pos, max_horizon=cfg["max_horizon"], generator=generator, max_positions=cfg["max_positions_per_sentence"], position_strategy=position_strategy, ) ) if (i + 1) % 25 == 0: logger.info(" [%s/%s] %d/%d sentences", mode, position_strategy, i + 1, len(texts)) trough = entropy_trough_depth(all_points) by_horizon = {} for horizon in range(1, cfg["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: by_horizon[f"entropy_i{horizon}_{tag}"] = sum(vals) / len(vals) h1_intra = [p.entropy for p in all_points if p.horizon == 1 and not p.is_boundary] h1_bound = [p.entropy for p in all_points if p.horizon == 1 and p.is_boundary] logger.info( "[%s/%s] trough_depth=%.4f n_points=%d n_h1_intra=%d n_h1_boundary=%d", mode, position_strategy, trough, len(all_points), len(h1_intra), len(h1_bound), ) return { "mode": mode, "position_strategy": position_strategy, "entropy_trough_depth": trough, "n_points": len(all_points), "h1_intraword_values": h1_intra, "h1_boundary_values": h1_bound, "by_horizon": by_horizon, } def main() -> None: args = parse_args() with open(args.config, encoding="utf-8") as f: cfg = yaml.safe_load(f) logger.info("config: %s", cfg) b_cfg = cfg["blocker_b"] model_key = args.model or b_cfg["model"] model_cfg = cfg["models"][model_key] text_column = args.text_column or b_cfg["text_column"] device = "cuda:0" if args.max_horizon is not None: cfg["max_horizon"] = args.max_horizon n = args.limit if args.limit is not None else cfg["blocker_b_sentences"] texts_csv = args.texts_csv or cfg["fertility_triples_csv"] rows = list(csv.DictReader(open(texts_csv, encoding="utf-8"))) import random rng = random.Random(cfg["seed"]) if len(rows) > n: rows = rng.sample(rows, n) texts = [r[text_column] for r in rows if r[text_column].strip()] logger.info("blocker B: model=%s column=%s n=%d max_horizon=%d", model_key, text_column, len(texts), cfg["max_horizon"]) 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).eval() handle = ModelHandle(model, tok, device, is_seq2seq=is_seq2seq, is_byte_level=is_seq2seq) # driving mode x position-selection strategy. The position strategy is on # this grid because the leading-positions cap turned out to leave # byte-level boundary positions unsampled, a second candidate explanation # for the Phase 2 trough-depth result that must be separated from the # architecture one rather than confounded with it. Causal models have no # encoder to starve, so the mode axis collapses to one level for them. modes = (SEQ2SEQ_MODE_MIRRORED, SEQ2SEQ_MODE_CAUSAL) if is_seq2seq else (SEQ2SEQ_MODE_MIRRORED,) strategies = [s.strip() for s in args.strategies.split(",") if s.strip()] results = {} for mode in modes: for strategy in strategies: results[f"{mode}__{strategy}"] = profile_in_mode(handle, texts, cfg, mode, strategy) Path(args.out).parent.mkdir(parents=True, exist_ok=True) with open(args.out, "w", encoding="utf-8") as f: json.dump(results, f) logger.info("wrote %s", args.out) if __name__ == "__main__": main()