File size: 8,789 Bytes
02443ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from __future__ import annotations

import argparse
from collections import defaultdict
import hashlib
import json
from pathlib import Path
import sys


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from anima_style_probe.factor_interventions import (  # noqa: E402
    FACTORS,
    INTERVENTION_VERSION,
    LEVELS,
    TRAIN_FAMILIES,
    VALIDATION_FAMILIES,
)


def stable_int(*values: object) -> int:
    text = "|".join(map(str, values))
    return int.from_bytes(hashlib.blake2b(text.encode(), digest_size=8).digest(), "little")


def read_records(paths: list[Path]) -> list[dict]:
    records: list[dict] = []
    seen: set[str] = set()
    for path in paths:
        payload = json.loads(path.read_text(encoding="utf-8"))
        for row in payload["records"]:
            record_id = str(row["record_id"])
            if record_id in seen:
                raise RuntimeError(f"duplicate packed record: {record_id}")
            seen.add(record_id)
            records.append(row)
    return records


def intensity_for(key: object) -> tuple[str, int]:
    value = stable_int("intensity", key) % 10
    level = "weak" if value < 4 else "medium" if value < 8 else "strong"
    sign = 1 if stable_int("sign", key) % 2 else -1
    return level, sign


def intervention_row(
    source: dict,
    factor: str,
    family: str,
    level: str,
    sign: int,
    *,
    anchor_kind: str,
    repeat_of: str | None = None,
    validation: bool = False,
) -> dict:
    suffix = f"{factor}-{family}-{level}-{'p' if sign > 0 else 'n'}"
    if repeat_of is not None:
        suffix += "-repeat"
    intervention_id = f"{source['record_id']}__{suffix}"
    return {
        "record_id": intervention_id,
        "source_record_id": source["record_id"],
        "style_id": source["style_id"],
        "source": source["source"],
        "split": "validation" if validation else "train",
        "shard": source["shard"],
        "factor": factor,
        "factor_index": FACTORS.index(factor),
        "family": family,
        "level": level,
        "sign": sign,
        "signed_intensity": sign * LEVELS[level],
        "operation_seed": stable_int("operation", intervention_id) & ((1 << 63) - 1),
        "transform_version": INTERVENTION_VERSION,
        "anchor_kind": anchor_kind,
        "repeat_of": repeat_of,
        "panel": False,
        "anima_pilot": False,
    }


def build_training(records: list[dict]) -> list[dict]:
    by_style: dict[str, list[dict]] = defaultdict(list)
    for row in records:
        by_style[str(row["style_id"])].append(row)
    if len(by_style) != 8_000:
        raise RuntimeError(f"expected 8,000 train identities, found {len(by_style)}")

    output: list[dict] = []
    for style_id, rows in sorted(by_style.items()):
        if len(rows) != 40:
            raise RuntimeError(f"{style_id} has {len(rows)} optimization records, expected 40")
        ordered = sorted(rows, key=lambda row: stable_int("anchor", row["record_id"]))
        shared = ordered[0]
        specific = iter(ordered[1:9])
        factor_rows: dict[str, list[dict]] = defaultdict(list)
        for factor in FACTORS:
            families = list(TRAIN_FAMILIES[factor])
            rotation = stable_int("family", style_id, factor) % len(families)
            families = families[rotation:] + families[:rotation]
            anchors = [shared, next(specific), next(specific)]
            for index, (source, family) in enumerate(zip(anchors, families, strict=True)):
                level, sign = intensity_for((style_id, factor, family))
                row = intervention_row(
                    source,
                    factor,
                    family,
                    level,
                    sign,
                    anchor_kind="shared" if index == 0 else "factor_specific",
                )
                output.append(row)
                factor_rows[factor].append(row)

        repeat_factor = FACTORS[stable_int("repeat-factor", style_id) % len(FACTORS)]
        base = factor_rows[repeat_factor][stable_int("repeat-row", style_id) % 3]
        second_level = {"weak": "medium", "medium": "strong", "strong": "medium"}[base["level"]]
        source = next(row for row in rows if row["record_id"] == base["source_record_id"])
        output.append(
            intervention_row(
                source,
                base["factor"],
                base["family"],
                second_level,
                base["sign"],
                anchor_kind="intensity_repeat",
                repeat_of=base["record_id"],
            )
        )

    if len(output) != 104_000:
        raise RuntimeError(f"expected 104,000 train variants, found {len(output)}")

    by_stratum: dict[tuple[str, str], list[dict]] = defaultdict(list)
    for row in output:
        if row["anchor_kind"] != "intensity_repeat":
            by_stratum[(row["source"], row["factor"])].append(row)
    for rows in by_stratum.values():
        for row in sorted(rows, key=lambda item: stable_int("panel", item["record_id"]))[:128]:
            row["panel"] = True
    if sum(row["panel"] for row in output) != 1_024:
        raise RuntimeError("failed to build balanced 1,024-record panel")
    return output


def build_validation(records: list[dict]) -> list[dict]:
    by_source_style: dict[str, dict[str, list[dict]]] = defaultdict(lambda: defaultdict(list))
    for row in records:
        if row.get("split") == "validation":
            by_source_style[row["source"]][row["style_id"]].append(row)
    output: list[dict] = []
    for source in ("synthetic", "human"):
        styles = sorted(
            by_source_style[source], key=lambda style: stable_int("validation-style", style)
        )[:256]
        if len(styles) != 256:
            raise RuntimeError(f"{source} has only {len(styles)} unseen validation identities")
        for style_id in styles:
            base = min(
                by_source_style[source][style_id],
                key=lambda row: stable_int("validation-record", row["record_id"]),
            )
            for factor in FACTORS:
                family = VALIDATION_FAMILIES[factor]
                sign = 1 if stable_int("validation-sign", style_id, factor) % 2 else -1
                for level in ("weak", "strong"):
                    output.append(
                        intervention_row(
                            base,
                            factor,
                            family,
                            level,
                            sign,
                            anchor_kind="validation_intensity",
                            validation=True,
                        )
                    )
    if len(output) != 4_096:
        raise RuntimeError(f"expected 4,096 validation variants, found {len(output)}")
    for row in output:
        row["anima_pilot"] = True
    return output


def main() -> int:
    parser = argparse.ArgumentParser(description="Build the factor-intervention subset manifest.")
    parser.add_argument("--packed-root", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    train_paths = sorted(args.packed_root.glob("train-rank*/features-*.json"))
    validation_paths = sorted(args.packed_root.glob("validation-*/features-*.json"))
    if not train_paths or not validation_paths:
        raise FileNotFoundError("packed train or validation metadata is missing")
    train = build_training(read_records(train_paths))
    validation = build_validation(read_records(validation_paths))
    rows = train + validation
    if len({row["record_id"] for row in rows}) != len(rows):
        raise RuntimeError("duplicate intervention record IDs")

    args.output.parent.mkdir(parents=True, exist_ok=True)
    temporary = args.output.with_suffix(args.output.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8", newline="\n") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
    temporary.replace(args.output)
    summary = {
        "status": "complete",
        "train_variants": len(train),
        "validation_variants": len(validation),
        "unique_train_anchors": len({row["source_record_id"] for row in train}),
        "panel": sum(row["panel"] for row in train),
        "anima_pilot": sum(row["anima_pilot"] for row in validation),
        "transform_version": INTERVENTION_VERSION,
        "output": str(args.output),
    }
    args.output.with_suffix(".summary.json").write_text(
        json.dumps(summary, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps(summary, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())