File size: 10,782 Bytes
2cc13ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import copy
import json
from collections import Counter, defaultdict
from pathlib import Path

from sklearn.model_selection import train_test_split


ROOT = Path("/root/knowledgegrapheval/type_prediction_dataset")
ARTIFACTS_DIR = ROOT / "artifacts"
INPUT_PATH = ROOT / "type_predictor_data.jsonl"
TRAIN_PATH = ROOT / "type_predictor_train.jsonl"
VAL_PATH = ROOT / "type_predictor_val.jsonl"
TEST_PATH = ROOT / "type_predictor_test.jsonl"
SUMMARY_PATH = ROOT / "split_summary.json"
ASSIGNMENTS_PATH = ARTIFACTS_DIR / "split_assignments.jsonl"

RANDOM_STATE = 42
TRAIN_RATIO = 0.8
VAL_RATIO = 0.1
TEST_RATIO = 0.1


def load_rows() -> list[dict]:
    with INPUT_PATH.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


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


def extract_entity_from_spans(row: dict) -> tuple[str, str]:
    sentence = row["sentence"]
    entity_from_chars = sentence[row["start_char"] : row["end_char"]]
    entity_from_tokens = " ".join(sentence.split(" ")[row["start_token"] : row["end_token"] + 1])
    return entity_from_chars, entity_from_tokens


def stratified_split(rows: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
    labels = [row["type"] for row in rows]
    indices = list(range(len(rows)))

    train_idx, holdout_idx = train_test_split(
        indices,
        test_size=(1.0 - TRAIN_RATIO),
        stratify=labels,
        random_state=RANDOM_STATE,
        shuffle=True,
    )

    holdout_labels = [labels[idx] for idx in holdout_idx]
    val_idx, test_idx = train_test_split(
        holdout_idx,
        test_size=0.5,
        stratify=holdout_labels,
        random_state=RANDOM_STATE,
        shuffle=True,
    )

    train_rows = [copy.deepcopy(rows[idx]) for idx in train_idx]
    val_rows = [copy.deepcopy(rows[idx]) for idx in val_idx]
    test_rows = [copy.deepcopy(rows[idx]) for idx in test_idx]
    return train_rows, val_rows, test_rows


def add_eval_categories(train_rows: list[dict], eval_rows: list[dict]) -> list[dict]:
    train_sentences = {row["sentence"] for row in train_rows}
    output = []
    for row in eval_rows:
        new_row = copy.deepcopy(row)
        if new_row["sentence"] in train_sentences:
            new_row["evaluation_category"] = "seen_sentence_new_entity"
        else:
            new_row["evaluation_category"] = "unseen_sentence"
        output.append(new_row)
    return output


def count_types(rows: list[dict]) -> Counter:
    return Counter(row["type"] for row in rows)


def count_type_and_category(rows: list[dict]) -> dict[str, dict[str, int]]:
    counts = defaultdict(lambda: {"unseen_sentence": 0, "seen_sentence_new_entity": 0})
    for row in rows:
        counts[row["type"]][row["evaluation_category"]] += 1
    return dict(sorted(counts.items()))


def write_split_assignments(
    train_rows: list[dict],
    val_rows: list[dict],
    test_rows: list[dict],
) -> None:
    ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)
    sentence_groups = []
    for split_name, rows in [("train", train_rows), ("validation", val_rows), ("test", test_rows)]:
        by_sentence = defaultdict(list)
        for row in rows:
            by_sentence[row["sentence"]].append(row)
        for sentence, sentence_rows in by_sentence.items():
            type_counts = Counter(row["type"] for row in sentence_rows)
            sentence_groups.append(
                {
                    "sentence": sentence,
                    "assigned_split": split_name,
                    "row_count": len(sentence_rows),
                    "type_counts": dict(sorted(type_counts.items())),
                    "row_ids": [row["id"] for row in sentence_rows],
                }
            )

    sentence_groups.sort(key=lambda item: (item["assigned_split"], item["sentence"]))
    dump_jsonl(ASSIGNMENTS_PATH, sentence_groups)


def validate(
    original_rows: list[dict],
    train_rows: list[dict],
    val_rows: list[dict],
    test_rows: list[dict],
) -> dict:
    errors = []
    all_rows = train_rows + val_rows + test_rows
    original_by_id = {row["id"]: row for row in original_rows}
    seen_ids = set()

    for split_name, rows in [("train", train_rows), ("validation", val_rows), ("test", test_rows)]:
        for row in rows:
            row_id = row["id"]
            if row_id in seen_ids:
                errors.append(f"duplicate row id across splits: {row_id}")
            seen_ids.add(row_id)

            if row_id not in original_by_id:
                errors.append(f"row id missing from original dataset: {row_id}")
                continue

            baseline = original_by_id[row_id]
            compare_keys = sorted(set(row.keys()) | set(baseline.keys()) - {"evaluation_category"})
            for key in compare_keys:
                if key == "evaluation_category":
                    continue
                if row.get(key) != baseline.get(key):
                    errors.append(f"{split_name} row {row_id} changed original field {key}")
                    break

            chars_entity, tokens_entity = extract_entity_from_spans(row)
            if chars_entity != row["entity"]:
                errors.append(f"{split_name} row {row_id} char span mismatch")
            if tokens_entity != row["entity"]:
                errors.append(f"{split_name} row {row_id} token span mismatch")

            if split_name == "train":
                if "evaluation_category" in row:
                    errors.append(f"train row {row_id} should not have evaluation_category")
            else:
                if row.get("evaluation_category") not in {"unseen_sentence", "seen_sentence_new_entity"}:
                    errors.append(f"{split_name} row {row_id} missing valid evaluation_category")

    if len(original_rows) != len(all_rows):
        errors.append("row count mismatch after splitting")
    if len(original_by_id) != len(seen_ids):
        errors.append("not all row ids are present exactly once")

    all_types = sorted({row["type"] for row in original_rows})
    for split_name, rows in [("train", train_rows), ("validation", val_rows), ("test", test_rows)]:
        split_types = {row["type"] for row in rows}
        missing_types = sorted(set(all_types) - split_types)
        if missing_types:
            errors.append(f"{split_name} missing types: {missing_types}")

    repeat_train, repeat_val, repeat_test = stratified_split(original_rows)
    repeat_val = add_eval_categories(repeat_train, repeat_val)
    repeat_test = add_eval_categories(repeat_train, repeat_test)
    if [row["id"] for row in repeat_train] != [row["id"] for row in train_rows]:
        errors.append("train split is not deterministic for the fixed seed")
    if [row["id"] for row in repeat_val] != [row["id"] for row in val_rows]:
        errors.append("validation split is not deterministic for the fixed seed")
    if [row["id"] for row in repeat_test] != [row["id"] for row in test_rows]:
        errors.append("test split is not deterministic for the fixed seed")

    return {
        "ok": not errors,
        "errors": errors,
    }


def make_summary(
    original_rows: list[dict],
    train_rows: list[dict],
    val_rows: list[dict],
    test_rows: list[dict],
    validation_result: dict,
) -> dict:
    original_type_counts = count_types(original_rows)
    train_type_counts = count_types(train_rows)
    val_type_counts = count_types(val_rows)
    test_type_counts = count_types(test_rows)

    def split_block(name: str, rows: list[dict]) -> dict:
        return {
            "name": name,
            "rows": len(rows),
            "percentage": len(rows) / len(original_rows),
            "unique_sentences": len({row["sentence"] for row in rows}),
            "type_counts": dict(sorted(count_types(rows).items())),
        }

    summary = {
        "random_seed": RANDOM_STATE,
        "requested_split_ratios": {
            "train": TRAIN_RATIO,
            "validation": VAL_RATIO,
            "test": TEST_RATIO,
        },
        "totals": {
            "original_rows": len(original_rows),
            "train_rows": len(train_rows),
            "validation_rows": len(val_rows),
            "test_rows": len(test_rows),
        },
        "splits": {
            "train": split_block("train", train_rows),
            "validation": split_block("validation", val_rows),
            "test": split_block("test", test_rows),
        },
        "per_type_counts": {},
        "evaluation_category_counts": {
            "validation": dict(sorted(Counter(row["evaluation_category"] for row in val_rows).items())),
            "test": dict(sorted(Counter(row["evaluation_category"] for row in test_rows).items())),
        },
        "evaluation_category_counts_by_type": {
            "validation": count_type_and_category(val_rows),
            "test": count_type_and_category(test_rows),
        },
        "validation": validation_result,
    }

    for entity_type in sorted(original_type_counts):
        summary["per_type_counts"][entity_type] = {
            "original": original_type_counts[entity_type],
            "train": train_type_counts[entity_type],
            "validation": val_type_counts[entity_type],
            "test": test_type_counts[entity_type],
            "train_ratio": train_type_counts[entity_type] / original_type_counts[entity_type],
            "validation_ratio": val_type_counts[entity_type] / original_type_counts[entity_type],
            "test_ratio": test_type_counts[entity_type] / original_type_counts[entity_type],
        }

    return summary


def main() -> None:
    original_rows = load_rows()
    ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)
    train_rows, val_rows, test_rows = stratified_split(original_rows)
    val_rows = add_eval_categories(train_rows, val_rows)
    test_rows = add_eval_categories(train_rows, test_rows)

    dump_jsonl(TRAIN_PATH, train_rows)
    dump_jsonl(VAL_PATH, val_rows)
    dump_jsonl(TEST_PATH, test_rows)
    write_split_assignments(train_rows, val_rows, test_rows)

    validation_result = validate(original_rows, train_rows, val_rows, test_rows)
    summary = make_summary(original_rows, train_rows, val_rows, test_rows, validation_result)
    SUMMARY_PATH.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")

    print(json.dumps(summary["totals"], ensure_ascii=False, indent=2))
    print(json.dumps(summary["evaluation_category_counts"], ensure_ascii=False, indent=2))
    if not validation_result["ok"]:
        raise SystemExit("split validation failed")


if __name__ == "__main__":
    main()