code-switch-mtp / scripts /phase2b_blocker_a.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
5.11 kB
"""Blocker A: one cell of the (model x script) factorial probing the L1 D_indep anomaly.
Phase 2 found L1 (Sarvam-1, Devanagari) had the lowest fertility but the
highest D_indep among subword conditions -- the opposite of what a
fertility-driven account predicts. L1 was also the only condition run on
Sarvam-1, so model identity and script were perfectly confounded. This
script measures one cell of the 2x2 that separates them; run all four cells
over the same paired sentence subset and aggregate with
scripts/phase2b_aggregate.py.
Emits per-sentence values, not just means: the question is whether the
effect survives sampling noise, which needs the raw distribution.
"""
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, AutoTokenizer
from src.measure.d_indep import d_indep_k2, d_indep_k3
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("phase2b_a")
MIN_TOKENS_FOR_D_INDEP = 4
PREFIX_LEN = 2
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase2b.yaml")
p.add_argument("--cell", required=True, help="key in blocker_a_cells")
p.add_argument("--out", required=True, help="per-cell JSON output path")
p.add_argument("--limit", type=int, default=None, help="override sentence count (for calibration runs)")
return p.parse_args()
def paired_sentence_indices(csv_path: str, n: int, seed: int) -> list:
"""Row indices shared by every cell, so cross-cell differences are within-sentence.
Sampling indices (not texts) is what makes the design paired: each cell
then reads its own text column from the same rows.
"""
import random
with open(csv_path, encoding="utf-8") as f:
total = sum(1 for _ in csv.DictReader(f))
rng = random.Random(seed)
idx = list(range(total))
if total > n:
idx = sorted(rng.sample(idx, n))
return idx
def load_texts(csv_path: str, column: str, indices: list) -> list:
rows = list(csv.DictReader(open(csv_path, encoding="utf-8")))
return [rows[i][column] for i in indices]
def run_cell(cfg: dict, cell: str, out_path: str, limit: int = None) -> None:
cell_cfg = cfg["blocker_a_cells"][cell]
model_cfg = cfg["models"][cell_cfg["model"]]
device = "cuda:0" # already pinned to one physical GPU via CUDA_VISIBLE_DEVICES
n = limit if limit is not None else cfg["blocker_a_sentences"]
indices = paired_sentence_indices(cfg["fertility_triples_csv"], n, cfg["seed"])
texts = load_texts(cfg["fertility_triples_csv"], cell_cfg["text_column"], indices)
logger.info("cell=%s model=%s column=%s n_sentences=%d", cell, cell_cfg["model"], cell_cfg["text_column"], len(texts))
tok = AutoTokenizer.from_pretrained(model_cfg["hf_id"])
model = AutoModelForCausalLM.from_pretrained(model_cfg["hf_id"], dtype=torch.float32).to(device).eval()
handle = ModelHandle(model, tok, device, is_seq2seq=False, is_byte_level=False)
generator = torch.Generator(device=device).manual_seed(cfg["seed"])
m = cfg["monte_carlo_samples"]
# NaN placeholders keep every list index aligned to the shared sentence
# subset, which the paired aggregation depends on.
fertility, d2, d3 = [], [], []
for i, text in enumerate(texts):
tokenized = handle.encode(text)
ids = tokenized.ids
n_words = len(text.split())
fertility.append(ids.shape[0] / n_words if n_words else float("nan"))
if ids.shape[0] >= MIN_TOKENS_FOR_D_INDEP:
prefix = ids[:PREFIX_LEN]
d2.append(d_indep_k2(handle, prefix))
d3.append(d_indep_k3(handle, prefix, m=m, generator=generator))
else:
d2.append(float("nan"))
d3.append(float("nan"))
if (i + 1) % 50 == 0:
logger.info(" %d/%d sentences", i + 1, len(texts))
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as f:
json.dump(
{
"cell": cell,
"model": cell_cfg["model"],
"text_column": cell_cfg["text_column"],
"sentence_indices": indices,
"fertility": fertility,
"d_indep_k2": d2,
"d_indep_k3": d3,
},
f,
)
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 cell=%s", cfg, args.cell)
run_cell(cfg, args.cell, args.out, limit=args.limit)
if __name__ == "__main__":
main()