File size: 8,367 Bytes
5f4e9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
231
232
233
234
235
"""CSV → jsonl splits + axiom rewrite + coverage report. No model imports."""

from __future__ import annotations

import argparse
import csv
import json
import random
import sys
from collections import Counter
from pathlib import Path

from .axioms import match_cot, rewrite_cot_assistant

TEXT_CSV = Path("Physics_Dataset/Physics_Dataset_no_image.csv")
IMAGE_CSV = Path("Physics_Dataset/Physics_dataset_with_image.csv")
IMAGE_DIR = Path("Physics_Dataset/Image")
DEFAULT_OUT = Path("data/physics_sft")
SPLIT_SEED = 42
TRAIN_RATIO = 0.90
VAL_RATIO = 0.05


def repo_root_from_here() -> Path:
    here = Path(__file__).resolve()
    for parent in here.parents:
        if (parent / "Physics_Dataset").is_dir() and (parent / "CLAUDE.md").exists():
            return parent
    return Path.cwd()


def load_csv(path: Path) -> list[dict[str, str]]:
    with path.open(newline="", encoding="utf-8") as handle:
        return list(csv.DictReader(handle))


def is_empty_answer(value: str | None) -> bool:
    return not (value or "").strip()


def resolve_image_path(id_image: str, image_dir: Path) -> Path:
    candidate = image_dir / id_image
    if candidate.is_file():
        return candidate
    raise FileNotFoundError(f"Missing diagram for id_image={id_image!r}: {candidate}")


def split_keys(keys: list[str], seed: int) -> dict[str, str]:
    rng = random.Random(seed)
    ordered = list(keys)
    rng.shuffle(ordered)
    n = len(ordered)
    n_val = max(1, int(round(n * VAL_RATIO))) if n >= 3 else (1 if n >= 2 else 0)
    n_test = max(1, int(round(n * VAL_RATIO))) if n >= 3 else (1 if n >= 3 else 0)
    if n_val + n_test >= n:
        n_val = 1 if n >= 3 else 0
        n_test = 1 if n >= 3 else 0
    n_train = n - n_val - n_test
    assignment: dict[str, str] = {}
    for i, key in enumerate(ordered):
        if i < n_train:
            assignment[key] = "train"
        elif i < n_train + n_val:
            assignment[key] = "val"
        else:
            assignment[key] = "test"
    return assignment


def record_from_row(
    row: dict[str, str],
    *,
    has_image: bool,
    image_path: str | None,
) -> dict:
    assistant, axiom_ids = rewrite_cot_assistant(row.get("cot") or "", row.get("answer") or "", row.get("unit") or "")
    return {
        "id": row["id"],
        "has_image": has_image,
        "image_path": image_path,
        "question": row.get("question") or "",
        "axiom_ids": axiom_ids,
        "assistant": assistant,
    }


def write_jsonl(path: Path, rows: list[dict]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")


def coverage_report(records: list[dict]) -> dict:
    hist: Counter[str] = Counter()
    n_with = 0
    for rec in records:
        ids = rec.get("axiom_ids") or []
        if ids:
            n_with += 1
        for axiom_id in ids:
            hist[axiom_id] += 1
    n = len(records)
    n_zero = n - n_with
    return {
        "n_rows": n,
        "n_with_axiom": n_with,
        "n_without_axiom": n_zero,
        "pct_with_axiom": round(100.0 * n_with / n, 2) if n else 0.0,
        "pct_without_axiom": round(100.0 * n_zero / n, 2) if n else 0.0,
        "axiom_histogram": dict(hist.most_common()),
    }


def print_coverage(report: dict) -> None:
    print("=== axiom matcher coverage ===")
    print(f"rows                 {report['n_rows']}")
    print(f">=1 axiom            {report['n_with_axiom']}  ({report['pct_with_axiom']}%)")
    print(f"0 axioms             {report['n_without_axiom']}  ({report['pct_without_axiom']}%)")
    print("histogram:")
    for axiom_id, count in report["axiom_histogram"].items():
        print(f"  {axiom_id:8} {count}")


def build_records(root: Path) -> tuple[list[dict], list[str], dict]:
    text_rows = load_csv(root / TEXT_CSV)
    image_rows = load_csv(root / IMAGE_CSV)
    image_dir = root / IMAGE_DIR

    dropped: list[str] = []
    records: list[dict] = []

    for row in text_rows:
        if is_empty_answer(row.get("answer")):
            dropped.append(row["id"])
            continue
        rec = record_from_row(row, has_image=False, image_path=None)
        rec["_split_key"] = row["id"]
        rec["_split_kind"] = "text"
        records.append(rec)

    for row in image_rows:
        if is_empty_answer(row.get("answer")):
            dropped.append(row["id"])
            continue
        resolved = resolve_image_path(row["id_image"], image_dir)
        rel = resolved.relative_to(root).as_posix()
        rec = record_from_row(row, has_image=True, image_path=rel)
        rec["_id_image"] = row["id_image"]
        rec["_split_key"] = row["id_image"]
        rec["_split_kind"] = "image"
        records.append(rec)

    return records, dropped, {
        "n_text_csv": len(text_rows),
        "n_image_csv": len(image_rows),
    }


def assign_splits(records: list[dict], seed: int) -> dict:
    text_keys = sorted({r["_split_key"] for r in records if r["_split_kind"] == "text"})
    image_keys = sorted({r["_split_key"] for r in records if r["_split_kind"] == "image"})
    text_map = split_keys(text_keys, seed)
    image_map = split_keys(image_keys, seed + 1)
    manifest = {"seed": seed, "text": {"train": [], "val": [], "test": []}, "image": {"train": [], "val": [], "test": []}}
    for rec in records:
        if rec["_split_kind"] == "text":
            split = text_map[rec["_split_key"]]
            rec["split"] = split
            manifest["text"][split].append(rec["id"])
        else:
            split = image_map[rec["_split_key"]]
            rec["split"] = split
            manifest["image"][split].append({"id": rec["id"], "id_image": rec["_id_image"]})
    return manifest


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Prepare physics SFT jsonl splits.")
    parser.add_argument("--root", type=Path, default=None)
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    parser.add_argument("--seed", type=int, default=SPLIT_SEED)
    args = parser.parse_args(argv)

    root = (args.root or repo_root_from_here()).resolve()
    out = args.out if args.out.is_absolute() else root / args.out
    out.mkdir(parents=True, exist_ok=True)

    records, dropped, counts = build_records(root)
    print(f"dropped empty-answer ids ({len(dropped)}): {dropped}")
    print(f"csv text={counts['n_text_csv']} image={counts['n_image_csv']}")

    manifest = assign_splits(records, args.seed)
    splits: dict[str, list[dict]] = {"train": [], "val": [], "test": []}
    for rec in records:
        splits[rec["split"]].append(rec)

    clean_splits: dict[str, list[dict]] = {}
    for name, rows in splits.items():
        cleaned = []
        for rec in rows:
            cleaned.append(
                {
                    "id": rec["id"],
                    "has_image": rec["has_image"],
                    "image_path": rec["image_path"],
                    "question": rec["question"],
                    "axiom_ids": rec["axiom_ids"],
                    "assistant": rec["assistant"],
                }
            )
        clean_splits[name] = cleaned
        write_jsonl(out / f"{name}.jsonl", cleaned)

    report = coverage_report([rec for recs in clean_splits.values() for rec in recs])
    (out / "coverage.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (out / "split_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (out / "dropped_ids.json").write_text(json.dumps(dropped, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

    print_coverage(report)
    print("=== split sizes ===")
    for name, rows in clean_splits.items():
        n_img = sum(1 for r in rows if r["has_image"])
        n_txt = len(rows) - n_img
        max_chars = max((len(r["assistant"]) for r in rows), default=0)
        print(f"{name:5} n={len(rows):5}  text={n_txt:4}  image={n_img:4}  max_assistant_chars={max_chars}")
    if report["pct_with_axiom"] < 25.0:
        print("WARNING: >=1 axiom coverage is under 25%. Loosen matcher rules before training.", file=sys.stderr)
        return 2
    return 0


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