File size: 11,059 Bytes
1cf4bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d1449
1cf4bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d1449
 
 
 
 
 
 
 
1cf4bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d1449
1cf4bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89976c1
1cf4bd2
 
 
 
89976c1
1cf4bd2
 
89976c1
1cf4bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89976c1
 
 
 
 
 
 
 
 
 
 
 
 
1cf4bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#!/usr/bin/env python3
"""Build the per-individual QA dataset (Parquet shards) for the Blog domain.

Input
-----
``data_*.zst``: zstd-compressed JSON arrays. Each element is one individual
with fields ``observations`` (list[str]), ``predictions`` (list of
``{question, ground_truth}``), ``data_source`` (str), ``split`` (str), and
``extra_info`` (dict). The upstream split label is ignored — this script
re-derives train / val / test deterministically.

Output
------
``<output-dir>/<split>-00000-of-00001.parquet`` for split in {train, val, test}.

Per-row schema
~~~~~~~~~~~~~~
::

    observations: list[str]
    predictions:  list[{question, ground_truth}]
    data_source:  str ("Blog Authorship Corpus")
    split:        str ("train" | "val" | "test")
    held_out_predictions: list[{question, ground_truth}]   # train only; absent on val/test
    extra_info:   {interview_id, n_observations, n_predictions, [n_held_out_predictions]}

Selection / split policy
~~~~~~~~~~~~~~~~~~~~~~~~
* Drop individuals with fewer than ``MIN_OBSERVATIONS`` observations.
* If observations exceed ``MAX_OBSERVATIONS``, deterministically subsample.
* Per individual, shuffle predictions with ``SEED + interview_id`` and split
  ~2/3 -> ``predictions`` and ~1/3 -> ``held_out``.
* Drop individuals with fewer than ``MIN_PREDICTIONS`` predictions or fewer
  than ``MIN_HELD_OUT`` held-out items.
* Globally shuffle qualified individuals with ``SEED`` and assign 90/5/5
  to train/val/test.
* For val/test, the held-out slice is folded into ``predictions`` so the eval
  pool is the union; the ``held_out_predictions`` field is dropped.

Self-contained: depends only on ``pyarrow`` (+ ``zstd`` binary on PATH).
No chiron imports.
"""

from __future__ import annotations

import argparse
import json
import random
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterator

import pyarrow as pa
import pyarrow.parquet as pq

# --- fixed policy -----------------------------------------------------------
SEED = 42

MIN_OBSERVATIONS = 20
MAX_OBSERVATIONS = 200

HELD_OUT_FRACTION = 1.0 / 3.0   # 2/3 -> predictions, 1/3 -> held-out

MIN_PREDICTIONS = 5
MIN_HELD_OUT = 3

TRAIN_RATIO = 0.9
VAL_RATIO = 0.05
TEST_RATIO = 0.05

DATA_SOURCE = "Blog Authorship Corpus"


# --- helpers -----------------------------------------------------------------

@dataclass
class _Row:
    interview_id: str
    observations: list[str]
    predictions: list[dict[str, str]]
    held_out: list[dict[str, str]]


def _decompress_zst(path: Path) -> bytes:
    return subprocess.check_output(["zstd", "-dcf", str(path)])


def _iter_records(input_dir: Path) -> Iterator[dict]:
    files = sorted(input_dir.glob("data_*.zst"))
    if not files:
        raise SystemExit(f"no data_*.zst files in {input_dir}")
    for p in files:
        arr = json.loads(_decompress_zst(p))
        for r in arr:
            yield r


def _interview_seed(interview_id: str) -> int:
    try:
        return SEED + int(interview_id)
    except (TypeError, ValueError):
        return SEED + (hash(str(interview_id)) & 0x7FFFFFFF)


def _normalize_ground_truth(value: str) -> str:
    """Return number-only labels; accepts legacy values like 'Option 2'."""
    m = re.search(r"(?:option\s*)?(\d+)", value.strip(), re.IGNORECASE)
    if not m:
        raise ValueError(f"cannot parse ground_truth: {value!r}")
    return m.group(1)


def _record_to_row(rec: dict) -> _Row | None:
    extra = rec.get("extra_info") or {}
    interview_id = str(extra.get("interview_id") or "")
    if not interview_id:
        return None

    observations = list(rec.get("observations") or [])
    predictions = list(rec.get("predictions") or [])
    if len(observations) < MIN_OBSERVATIONS:
        return None
    if not predictions:
        return None

    rng = random.Random(_interview_seed(interview_id))

    # Cap observations by deterministic subsample (preserve order after sample).
    if len(observations) > MAX_OBSERVATIONS:
        idxs = sorted(rng.sample(range(len(observations)), MAX_OBSERVATIONS))
        observations = [observations[i] for i in idxs]

    # Per-individual split predictions -> (predictions, held_out).
    pred_pool = list(predictions)
    rng.shuffle(pred_pool)
    n_held = max(1, int(round(len(pred_pool) * HELD_OUT_FRACTION)))
    n_held = min(n_held, len(pred_pool) - 1)  # ensure at least one prediction left
    if n_held < 1:
        return None
    n_pred = len(pred_pool) - n_held
    if n_pred < MIN_PREDICTIONS or n_held < MIN_HELD_OUT:
        return None

    pred_slice = pred_pool[:n_pred]
    held_slice = pred_pool[n_pred:]

    def _clean(items: list[dict]) -> list[dict[str, str]]:
        out = []
        for it in items:
            q = it.get("question")
            gt = it.get("ground_truth")
            if not isinstance(q, str) or not isinstance(gt, str):
                continue
            out.append({"question": q, "ground_truth": _normalize_ground_truth(gt)})
        return out

    pred_clean = _clean(pred_slice)
    held_clean = _clean(held_slice)
    if len(pred_clean) < MIN_PREDICTIONS or len(held_clean) < MIN_HELD_OUT:
        return None

    return _Row(
        interview_id=interview_id,
        observations=observations,
        predictions=pred_clean,
        held_out=held_clean,
    )


def _partition_split_counts(n: int) -> tuple[int, int, int]:
    n_val = round(n * VAL_RATIO)
    n_test = round(n * TEST_RATIO)
    n_train = n - n_val - n_test
    if n_train < 1 and n > 0:
        half = max(0, n - 1) // 2
        n_train, n_val, n_test = 1, half, n - 1 - half
    return n_train, n_val, n_test


def _record_to_dict(rec: _Row, split: str) -> dict[str, Any]:
    extra: dict[str, Any] = {
        "interview_id": rec.interview_id,
        "n_observations": len(rec.observations),
    }
    if split == "train":
        out = {
            "observations": rec.observations,
            "predictions": rec.predictions,
            "data_source": DATA_SOURCE,
            "split": "train",
            "held_out_predictions": rec.held_out,
        }
        extra["n_predictions"] = len(rec.predictions)
        extra["n_held_out_predictions"] = len(rec.held_out)
    else:
        merged = list(rec.predictions) + list(rec.held_out)
        out = {
            "observations": rec.observations,
            "predictions": merged,
            "data_source": DATA_SOURCE,
            "split": split,
        }
        extra["n_predictions"] = len(merged)
    out["extra_info"] = extra
    return out


# --- arrow schemas (explicit so train and val/test are stable) ---------------

_PRED_TYPE = pa.struct([
    pa.field("question", pa.string()),
    pa.field("ground_truth", pa.string()),
])

_TRAIN_SCHEMA = pa.schema([
    pa.field("observations", pa.list_(pa.string())),
    pa.field("predictions", pa.list_(_PRED_TYPE)),
    pa.field("data_source", pa.string()),
    pa.field("split", pa.string()),
    pa.field("held_out_predictions", pa.list_(_PRED_TYPE)),
    pa.field("extra_info", pa.struct([
        pa.field("interview_id", pa.string()),
        pa.field("n_observations", pa.int32()),
        pa.field("n_predictions", pa.int32()),
        pa.field("n_held_out_predictions", pa.int32()),
    ])),
])

_EVAL_SCHEMA = pa.schema([
    pa.field("observations", pa.list_(pa.string())),
    pa.field("predictions", pa.list_(_PRED_TYPE)),
    pa.field("data_source", pa.string()),
    pa.field("split", pa.string()),
    pa.field("extra_info", pa.struct([
        pa.field("interview_id", pa.string()),
        pa.field("n_observations", pa.int32()),
        pa.field("n_predictions", pa.int32()),
    ])),
])


def _write_split(records: list[dict], split: str, output_dir: Path, *,
                 compression: str | None, compression_level: int | None) -> Path:
    schema = _TRAIN_SCHEMA if split == "train" else _EVAL_SCHEMA
    table = pa.Table.from_pylist(records, schema=schema)
    out_path = output_dir / f"{split}-00000-of-00001.parquet"
    pq.write_table(
        table, out_path,
        compression=compression,
        compression_level=compression_level,
        use_dictionary=True,
    )
    return out_path


def parse_args() -> argparse.Namespace:
    domain_dir = Path(__file__).resolve().parent.parent
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument(
        "--input-dir",
        type=Path,
        default=domain_dir / "upstream",
        help="Directory containing the upstream data_*.zst shards.",
    )
    p.add_argument("--output-dir", type=Path, default=domain_dir / "qa_parquet")
    p.add_argument("--max-rows", type=int, default=0,
                   help="Debug: stop after this many input rows (0 = all).")
    p.add_argument("--compression", default="zstd",
                   choices=["zstd", "gzip", "snappy", "brotli", "lz4", "none"])
    p.add_argument("--compression-level", type=int, default=None)
    return p.parse_args()


def main() -> None:
    args = parse_args()
    args.output_dir.mkdir(parents=True, exist_ok=True)

    pool: list[_Row] = []
    raw_seen = 0
    skipped = 0

    for rec in _iter_records(args.input_dir):
        raw_seen += 1
        if args.max_rows and raw_seen > args.max_rows:
            break
        row = _record_to_row(rec)
        if row is None:
            skipped += 1
            continue
        pool.append(row)

    rng = random.Random(SEED)
    rng.shuffle(pool)
    n = len(pool)
    n_train, n_val, _n_test = _partition_split_counts(n)

    splits = {
        "train": pool[:n_train],
        "val": pool[n_train : n_train + n_val],
        "test": pool[n_train + n_val :],
    }

    # Preserve the published IID test policy: exclude the historical training
    # prefix, then retain only the first test row for each adapter identity.
    train_ids = {str(rec.interview_id) for rec in splits["train"][:4366]}
    seen_test_ids: set[str] = set()
    clean_test: list[_Row] = []
    for rec in splits["test"]:
        sample_id = str(rec.interview_id)
        if sample_id in train_ids or sample_id in seen_test_ids:
            continue
        seen_test_ids.add(sample_id)
        clean_test.append(rec)
    splits["test"] = clean_test

    comp = None if args.compression == "none" else args.compression
    written: dict[str, dict] = {}
    for split_name, recs in splits.items():
        if not recs:
            continue
        records = [_record_to_dict(r, split_name) for r in recs]
        path = _write_split(records, split_name, args.output_dir,
                            compression=comp, compression_level=args.compression_level)
        written[split_name] = {"rows": len(records), "path": str(path)}

    print(json.dumps({
        "raw_lines_seen": raw_seen,
        "samples_built": n,
        "skipped_insufficient_data": skipped,
        "split_counts": {k: len(v) for k, v in splits.items()},
        "written": written,
    }, indent=2))


if __name__ == "__main__":
    main()