File size: 6,311 Bytes
1b86964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Export population responses to messages-only SFT and a separate row index.

Input: data/intermediate/population/population.jsonl.
Outputs: data/sft/population/{train.jsonl,train_index.jsonl}.

Defaults are relative to the repository, independent of the working directory.
The index uses one-based sample, respondent, item, and presentation indices.
Population arrays and all internal computations use zero-based indices.
"""
from __future__ import annotations

import argparse
import copy
import itertools
import json
from pathlib import Path
import re
import sys

import numpy as np

REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT / "code") not in sys.path:
    sys.path.insert(0, str(REPO_ROOT / "code"))

from prompt.base.population_sft import INTRO, ITEM_INSTRUCTION, ITEM_VARIANTS

SHUFFLE_SEED = 20260909


def split_prompt(text, n):
    matches = list(re.finditer(r"(?m)^Q(\d+)\.\n", text))
    assert [int(m.group(1)) for m in matches] == list(range(1, n + 1))
    prefix = text[:matches[0].start()]
    blocks = []
    for i, match in enumerate(matches):
        end = matches[i + 1].start() if i + 1 < n else len(text)
        blocks.append(text[match.end():end].rstrip())
    assert all(ITEM_INSTRUCTION in block and "Choose exactly one option:" in block for block in blocks)
    return prefix, blocks


def presentation_groups(q):
    """Move complete dependent groups; keep consecutive free items together."""
    groups = copy.deepcopy(q["protected_components"])
    free = q["free_items"]
    for _, values in itertools.groupby(enumerate(free), lambda x: x[1] - x[0]):
        groups.append([value for _, value in values])
    groups.sort(key=lambda x: x[0])
    assert sorted(j for block in groups for j in block) == list(range(len(q["questions"])))
    return groups


def render(q, answer, variant, order):
    prefix, blocks = split_prompt(q["messages"][1]["content"], len(answer))
    old = INTRO[0]
    assert prefix.startswith(old + "\n")
    prefix = INTRO[variant] + prefix[len(old):]
    prompt = prefix + "\n\n".join(
        f"Q{i + 1}.\n" + blocks[j].replace(ITEM_INSTRUCTION, ITEM_VARIANTS[variant])
        for i, j in enumerate(order))
    output = "\n".join(f"Q{i + 1}: Option {int(answer[j])}" for i, j in enumerate(order))
    return {"messages": [copy.deepcopy(q["messages"][0]),
                         {"role": "user", "content": prompt},
                         {"role": "assistant", "content": output}]}


def build_rows(populations):
    """Return rows and one-based sidecar indices without file access.

    Preserve the supplied condition order: a single shared RNG controls all
    presentation choices and the final shuffle. Each respondent appears once.
    """
    populations = list(populations)
    rng = np.random.default_rng(SHUFFLE_SEED)
    rows, indices = [], []
    conditions = set()
    for q in populations:
        n, j = q["original_n"], len(q["questions"])
        assert n > 0 and j > 0 and len(q["respondents"]) == n
        assert [m["role"] for m in q["messages"]] == ["system", "user"]
        assert q["condition_key"] not in conditions
        groups = presentation_groups(q)
        _, blocks = split_prompt(q["messages"][1]["content"], j)
        references = any(re.search(
            r"\b(?:Q\d+|previous (?:question|answer)|preceding (?:question|answer)|question (?:number )?\d+)\b",
            block, re.I) for block in blocks)
        variants = rng.permutation(np.arange(n) % 4)
        reorder = rng.permutation(np.arange(n) % 2).astype(bool)
        for i, answer in enumerate(q["respondents"]):
            assert len(answer) == j
            assert all(1 <= int(value) <= len(q["questions"][k]["options"])
                       for k, value in enumerate(answer))
            order = list(range(j))
            if reorder[i] and len(groups) > 1 and not references:
                permutation = rng.permutation(len(groups))
                if np.array_equal(permutation, np.arange(len(groups))):
                    permutation = np.roll(permutation, 1)
                order = [item for k in permutation for item in groups[int(k)]]
            variant = int(variants[i])
            rows.append(render(q, answer, variant, order))
            indices.append({"study_id": q["study_id"], "condition_id": q["condition_id"],
                            "respondent_index": i + 1,
                            "presentation_variant": variant + 1,
                            "presented_to_canonical_items": [item + 1 for item in order]})
        conditions.add(q["condition_key"])
    order = rng.permutation(len(rows))
    rows = [rows[i] for i in order]
    indices = [{"sample_id": number, **indices[i]} for number, i in enumerate(order, 1)]
    return rows, indices


def write_jsonl(path, rows):
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input-file", type=Path,
                        default=REPO_ROOT / "data/intermediate/population/population.jsonl")
    parser.add_argument("--output-dir", type=Path,
                        default=REPO_ROOT / "data/sft/population")
    args = parser.parse_args()
    with args.input_file.open(encoding="utf-8") as handle:
        populations = [json.loads(line) for line in handle if line.strip()]
    if args.output_dir.resolve() == REPO_ROOT / "data/sft/population":
        split = json.loads((REPO_ROOT / "data/raw/population/split.json").read_text(encoding="utf-8"))
        if set(q["study_id"] for q in populations) != set(split["train_studies"]):
            parser.error("Default SFT output requires the complete training population")
    if args.output_dir.resolve().is_relative_to(REPO_ROOT / "data/raw"):
        parser.error("--output-dir must not be inside data/raw")
    rows, indices = build_rows(populations)
    args.output_dir.mkdir(parents=True, exist_ok=True)
    write_jsonl(args.output_dir / "train.jsonl", rows)
    write_jsonl(args.output_dir / "train_index.jsonl", indices)
    print(f"Wrote {len(rows)} training rows and row indices to {args.output_dir}")


if __name__ == "__main__":
    main()