File size: 12,567 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
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
#!/usr/bin/env python3
"""Assemble all three supervision signals into one shuffled SFT JSONL.

Inputs (relative to this repository): data/sft/prediction/train.jsonl (already x2),
  data/sft/measurement/{item_response,llm_intensity,prediction_reuse,human_gold}/train.jsonl,
  data/sft/population/{train.jsonl,train_index.jsonl}, data/raw/measurement/construct_vocab.json.
Output: data/sft/joint_train.jsonl only; existing output is replaced atomically.

    python code/build_joint_training.py

Default recipe: prediction unchanged, measurement x2, population x5; seed 42.
Rows always have sample_id, signal, domain, messages, measurement. The tuple
(signal, domain, sample_id) identifies a source sample; copies keep that ID.
IDs start at 1. Measurement construct indices separately range from 0 to 108.
Prediction IDs omit the redundant domain prefix. Population IDs are condition:rN.

No model, API or third-party Python package is needed. Sources remain unchanged.
Disk-backed shuffling bounds memory usage; temporary files are removed on exit.
Use the Chiron training entry point to infer loss masking from signal. An
unmodified ShareGPT reader does not suppress CE on measurement-only examples.
"""
from __future__ import annotations

import argparse
from collections import Counter
from contextlib import ExitStack
import json
import math
from pathlib import Path
import random
import tempfile

ROOT = Path(__file__).resolve().parents[1]
SFT = ROOT / "data/sft"
OUTPUT = SFT / "joint_train.jsonl"
FIELDS = ("sample_id", "signal", "domain", "messages", "measurement")
MEASUREMENT_SOURCES = (
    ("item_response", 10900),
    ("llm_intensity", 15250),
    ("prediction_reuse", 23424),
    ("human_gold", 3499),
)


def positive_integer(value):
    number = int(value)
    if number < 1:
        raise argparse.ArgumentTypeError("repeat counts must be positive integers")
    return number


def load_vocab():
    vocab = json.loads((ROOT / "data/raw/measurement/construct_vocab.json").read_text(encoding="utf-8"))
    if (not isinstance(vocab, dict) or len(vocab) != 109
            or any(type(value) is not int for value in vocab.values())
            or sorted(vocab.values()) != list(range(109))):
        raise ValueError("Expected 109 construct names with indices 0 through 108")
    return vocab


def validate_row(row, vocab):
    """Reject invalid supervision instead of silently dropping or clipping it."""
    if tuple(row) != FIELDS:
        raise ValueError("Expected exactly the five joint fields in their standard order")
    if row["signal"] not in {"prediction", "measurement", "population"}:
        raise ValueError("Unknown signal")
    if any(not isinstance(row[key], str) or not row[key].strip() for key in ("sample_id", "domain")):
        raise ValueError("Sample and domain identifiers must be nonempty strings")
    messages = row["messages"]
    if (not isinstance(messages, list) or len(messages) != 3
            or any(not isinstance(m, dict) or set(m) != {"role", "content"} for m in messages)
            or [m["role"] for m in messages] != ["system", "user", "assistant"]
            or any(not isinstance(m["content"], str) for m in messages)):
        raise ValueError("Expected system, user, assistant messages with string content")
    if not messages[0]["content"].strip() or not messages[1]["content"].strip():
        raise ValueError("Empty system or user input")
    user, assistant = messages[1]["content"], messages[2]["content"]
    if (user.count("<person_records>") != 1 or user.count("</person_records>") != 1
            or user.index("<person_records>") >= user.index("</person_records>")):
        raise ValueError("Missing or ambiguous person-record boundary")
    measurement = row["measurement"]
    if not isinstance(measurement, dict) or set(measurement) != {"targets"} or not isinstance(measurement["targets"], list):
        raise ValueError("Measurement must contain a targets list, including when empty")
    targets = measurement["targets"]
    if row["signal"] == "measurement":
        if assistant != "" or not targets:
            raise ValueError("Measurement rows require targets and an empty assistant")
    elif not assistant.strip() or targets:
        raise ValueError("Prediction/population rows require an answer and no measurement targets")
    if "<think>" in assistant or "</think>" in assistant:
        raise ValueError("Reasoning tags are not direct SFT targets")
    ids = set()
    for target in targets:
        if not isinstance(target, dict) or set(target) != {"construct_id", "construct", "score"}:
            raise ValueError("Unexpected measurement target fields")
        cid, name, score = target["construct_id"], target["construct"], target["score"]
        if type(cid) is not int or not isinstance(name, str) or vocab.get(name) != cid or cid in ids:
            raise ValueError("Unknown, mismatched or duplicate construct")
        if type(score) not in (int, float) or not math.isfinite(score) or not -1 <= score <= 1:
            raise ValueError("Measurement scores must be finite and within [-1, 1]")
        ids.add(cid)


def normalize(row, signal, index=None):
    if signal == "population":
        domain = index["study_id"]
        respondent = index["respondent_index"]
        if type(respondent) is not int or respondent < 1:
            raise ValueError("Population respondent indices must start at 1")
        sid = f"{index['condition_id']}:r{respondent}"
    else:
        domain, sid = row["domain"], row["sample_id"]
        if not isinstance(sid, str) or not isinstance(domain, str):
            raise ValueError("Expected string source identifiers")
        if signal == "prediction":
            prefix = domain + ":"
            if not sid.startswith(prefix):
                raise ValueError("Prediction source ID must carry its domain prefix")
            sid = sid[len(prefix):]
        if not sid.isdecimal() or int(sid) < 1:
            raise ValueError("Source sample IDs must start at 1")
        if signal == "measurement" and row.get("chiron_repr_only") is not True:
            raise ValueError("Measurement source is not marked measurement-only")
    return {"sample_id": sid, "signal": signal, "domain": domain,
            "messages": row["messages"],
            "measurement": row["measurement"] if signal == "measurement" else {"targets": []}}


def build(output=OUTPUT, *, measurement_repeat=2, population_repeat=5, seed=42):
    if type(seed) is not int or any(type(n) is not int or n < 1 for n in (measurement_repeat, population_repeat)):
        raise ValueError("Seed must be an integer and repeat counts positive integers")
    output = Path(output).expanduser().resolve()
    if not output.is_relative_to(SFT) or output.parent != SFT or output.suffix != ".jsonl":
        raise ValueError("Joint output must be a .jsonl directly inside data/sft")
    vocab = load_vocab()
    sources = [(SFT / "prediction/train.jsonl", "prediction", 220096, 1)]
    sources += [(SFT / "measurement" / name / "train.jsonl", "measurement", count, measurement_repeat)
                for name, count in MEASUREMENT_SOURCES]
    sources += [(SFT / "population/train.jsonl", "population", 23191, population_repeat)]
    counts, target_counts = Counter(), Counter()
    seen_constructs = set()
    identities = {}
    offsets = []
    temporary_output = None
    try:
        with ExitStack() as stack:
            spool = stack.enter_context(tempfile.TemporaryFile(mode="w+b", dir=SFT))
            population_index = stack.enter_context((SFT / "population/train_index.jsonl").open(encoding="utf-8"))
            for path, signal, expected, repeat in sources:
                source_offsets = []
                with path.open(encoding="utf-8") as handle:
                    for number, line in enumerate(handle, 1):
                        try:
                            source = json.loads(line)
                            index = None
                            if signal == "population":
                                index = json.loads(next(population_index))
                                if type(index["sample_id"]) is not int or index["sample_id"] != number:
                                    raise ValueError("Population index is not aligned to SFT row order")
                            row = normalize(source, signal, index)
                            validate_row(row, vocab)
                        except (KeyError, TypeError, ValueError, StopIteration) as exc:
                            raise ValueError(f"{path.relative_to(ROOT)} line {number}: {exc}") from exc
                        payload = (json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
                        offset = spool.tell()
                        identity = (signal, row["domain"], row["sample_id"])
                        if identity in identities:
                            previous_offset, length = identities[identity]
                            spool.seek(previous_offset)
                            same = spool.read(length) == payload
                            spool.seek(offset)
                            if not same:
                                raise ValueError(f"One sample ID refers to different content: {identity}")
                        else:
                            identities[identity] = (offset, len(payload))
                        spool.write(payload)
                        source_offsets.append((offset, len(payload)))
                        for target in row["measurement"]["targets"]:
                            seen_constructs.add(target["construct_id"])
                            target_counts[target["construct_id"]] += repeat
                if len(source_offsets) != expected:
                    raise ValueError(f"{path.relative_to(ROOT)}: expected {expected} rows, found {len(source_offsets)}")
                # Repeat the complete source block; source rows retain their order.
                offsets.extend(source_offsets * repeat)
                counts[signal] += expected * repeat
            if next(population_index, None) is not None:
                raise ValueError("Population index contains extra rows")
            if seen_constructs != set(range(109)):
                raise ValueError("The measurement mixture does not cover all 109 constructs")
            random.Random(seed).shuffle(offsets)
            with tempfile.NamedTemporaryFile(mode="wb", dir=SFT, prefix=".joint_train.", suffix=".tmp", delete=False) as handle:
                temporary_output = Path(handle.name)
                for offset, length in offsets:
                    spool.seek(offset)
                    payload = spool.read(length)
                    if len(payload) != length:
                        raise ValueError("Incomplete intermediate row")
                    handle.write(payload)
            # Read the actual output before publishing it; invalid input leaves
            # any previous joint file untouched and all temporary files cleaned.
            actual = Counter()
            actual_targets = Counter()
            with temporary_output.open(encoding="utf-8") as handle:
                for line in handle:
                    row = json.loads(line)
                    validate_row(row, vocab)
                    actual[row["signal"]] += 1
                    actual_targets.update(target["construct_id"] for target in row["measurement"]["targets"])
            if actual != counts or actual_targets != target_counts:
                raise ValueError("Written mixture counts do not match the source recipe")
            temporary_output.replace(output)
            print(json.dumps({"output": str(output.relative_to(ROOT)), "rows": sum(counts.values()),
                              "signals": dict(counts), "constructs": len(seen_constructs), "seed": seed}, ensure_ascii=False))
    finally:
        if temporary_output is not None:
            temporary_output.unlink(missing_ok=True)
    return dict(counts)


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--measurement-repeat", type=positive_integer, default=2)
    parser.add_argument("--population-repeat", type=positive_integer, default=5)
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()
    build(measurement_repeat=args.measurement_repeat, population_repeat=args.population_repeat, seed=args.seed)


if __name__ == "__main__":
    main()