File size: 5,110 Bytes
3bbd5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""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()