File size: 10,222 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
"""Pure input preparation and validation for Chiron evaluation datasets."""
from __future__ import annotations

import json
import math
import re

from prompt.base.prediction_sft import SYSTEM_PROMPT, USER_PROMPT


def render_user_prompt(template, adapter, observations, questions):
    return (template
            .replace("{record_context}", adapter.record_context())
            .replace("{observations}", adapter.format_observations_block(observations))
            .replace("{questions}", adapter.format_question_block(questions)))


def prepare_case(sample, sample_index, adapter, args):
    """Freeze the exact input and complete scoring denominator before requesting a model."""
    observations = adapter.select_observations(sample, seed=args.seed, sample_index=sample_index)
    predictions = adapter.select_target_predictions(
        sample, seed=args.seed, sample_index=sample_index,
        min_questions=args.min_questions, max_questions=args.max_questions,
    )
    if not observations or any(not isinstance(s, str) or not s.strip() for s in observations):
        raise ValueError("No usable observations")
    if not predictions or any(not p.ground_truth.strip() for p in predictions):
        raise ValueError("No usable prediction questions or ground truths")
    # Some adapters render a fixed question (for example Twitter), so their
    # raw question field can be empty. Preserve the adapter rendering policy.
    questions = [p.question for p in predictions]
    golds = [p.ground_truth for p in predictions]
    reference = adapter.score_predictions(golds, golds)
    failure_details = {"n_correct": 0}
    if "n_traits" in reference:
        failure_details["n_traits"] = reference["n_traits"]
    return {
        # A person can have several QA records; each input row is evaluated once.
        "domain": adapter.name, "row_id": sample_index + 1,
        "sample_id": str(adapter.get_sample_id(sample)),
        "data_source": sample.data_source,
        "split": sample.split,
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT.strip()},
            {"role": "user", "content": render_user_prompt(
                USER_PROMPT.strip(), adapter, observations, questions)},
        ],
        "raw_output": "", "answer_text": "", "predictions": [],
        "questions": questions, "ground_truths": golds, "score": 0.0,
        "metric": adapter.metric_name(), "metric_details": failure_details,
        "n_questions": len(predictions), "n_observations": len(observations),
        "extra_info": sample.extra_info,
    }


def read_records(path, limit=None):
    with path.open(encoding="utf-8") as handle:
        count = 0
        for line in handle:
            if not line.strip():
                continue
            if limit is not None and count >= limit:
                break
            row = json.loads(line)
            if not isinstance(row, dict):
                raise ValueError("Each evaluation row must be an object")
            count += 1
            yield row


def input_messages(messages):
    """Accept frozen system/user inputs, optionally followed by an empty SFT answer."""
    if not isinstance(messages, list):
        raise ValueError("messages must contain system and user text")
    if any(not isinstance(m, dict) for m in messages):
        raise ValueError("Each message must be an object")
    messages = [dict(m) for m in messages]
    if messages and messages[-1].get("role") == "assistant":
        if messages[-1].get("content") != "":
            raise ValueError("Evaluation input must not contain an assistant answer")
        messages.pop()
    if [m.get("role") for m in messages] != ["system", "user"]:
        raise ValueError("Exactly one system message and one user message are required")
    if any(not isinstance(m.get("content"), str) or not m["content"].strip() for m in messages):
        raise ValueError("Message contents must be nonempty text")
    return [{"role": m["role"], "content": m["content"]} for m in messages]


def prepare_measurement_case(row, index, vocab):
    if row.get("signal", "measurement") != "measurement":
        raise ValueError("Expected a measurement row")
    messages = input_messages(row.get("messages"))
    user = messages[1]["content"]
    if user.count("<person_records>") != 1 or user.count("</person_records>") != 1:
        raise ValueError("Measurement input requires one person_records block")
    if not user.split("<person_records>", 1)[1].split("</person_records>", 1)[0].strip():
        raise ValueError("Person records are empty")
    if user.index("</person_records>") < user.index("<person_records>"):
        raise ValueError("Person record boundaries are reversed")
    measurement = row.get("measurement")
    if not isinstance(measurement, dict):
        raise ValueError("measurement must be an object containing targets")
    targets = measurement.get("targets")
    if not isinstance(targets, list) or not targets:
        raise ValueError("Measurement targets are required")
    names = {value: key for key, value in vocab.items()}
    seen, checked = set(), []
    for target in targets:
        if not isinstance(target, dict):
            raise ValueError("Each measurement target must be an object")
        cid, name, score = target.get("construct_id"), target.get("construct"), target.get("score")
        if type(cid) is not int or cid not in names or cid in seen or name != names[cid]:
            raise ValueError("Target must use a unique ID and name from the 109-construct vocabulary")
        if type(score) not in (int, float) or not math.isfinite(score) or not -1 <= score <= 1:
            raise ValueError("Measurement target scores must be finite and in [-1, 1]")
        seen.add(cid)
        checked.append({"construct_id": cid, "construct": name, "gold": float(score)})
    return {"domain": row["domain"], "row_id": index + 1, "sample_id": str(row.get("sample_id", index + 1)),
            "messages": messages, "targets": checked}


def validate_population_studies(studies):
    """Validate complete study contracts before starting any generation."""
    if not studies:
        raise ValueError("Test data is empty")
    seen_studies, seen_conditions, seen_cells, seen_effects, seen_indices = set(), set(), set(), set(), set()
    for study in studies:
        sid = study.get("domain")
        if not isinstance(sid, str) or not sid or sid in seen_studies:
            raise ValueError("Each population study must have a unique name")
        seen_studies.add(sid)
        if not isinstance(study.get("prompts"), list) or not study["prompts"]:
            raise ValueError(f"{sid}: condition prompts are required")
        if not isinstance(study.get("effects"), list) or not study["effects"]:
            raise ValueError(f"{sid}: human effect definitions are required")
        study_cells = set()
        for prompt in study["prompts"]:
            key = prompt.get("condition_key")
            if not isinstance(key, str) or not key or key in seen_conditions or prompt.get("study_id") != sid:
                raise ValueError(f"{sid}: invalid or duplicate condition")
            if not isinstance(prompt.get("condition_id"), str) or not prompt["condition_id"]:
                raise ValueError(f"{sid}: condition_id is required")
            seen_conditions.add(key)
            if type(prompt.get("original_n")) is not int or prompt["original_n"] < 1:
                raise ValueError(f"{key}: original_n must be a positive integer")
            prompt["messages"] = input_messages(prompt.get("messages"))
            if not isinstance(prompt.get("questions"), list) or not prompt["questions"]:
                raise ValueError(f"{key}: question definitions are required")
            # Each ordered Q block must have a corresponding answer-scale definition.
            numbers = [int(n) for n in re.findall(r"(?m)^Q(\d+)[.:]", prompt["messages"][1]["content"])]
            if numbers != list(range(1, len(prompt["questions"]) + 1)):
                raise ValueError(f"{key}: prompt question order does not match the definitions")
            for q in prompt["questions"]:
                cell = q.get("cell_id")
                if not isinstance(cell, str) or not cell or cell in seen_cells:
                    raise ValueError(f"{key}: duplicate or missing cell_id")
                seen_cells.add(cell); study_cells.add(cell)
                options = q.get("options")
                if not isinstance(options, list) or not options:
                    raise ValueError(f"{cell}: response options are required")
                ids = [o.get("id") for o in options]
                if any(type(i) is not int or i < 1 for i in ids) or len(ids) != len(set(ids)):
                    raise ValueError(f"{cell}: option IDs must be unique positive integers")
                if any(type(o.get("analysis_value")) not in (int, float) or not math.isfinite(o["analysis_value"])
                       for o in options):
                    raise ValueError(f"{cell}: finite analysis values are required")
            index = prompt.get("_eval_index")
            if type(index) is not int or index < 0 or index in seen_indices:
                raise ValueError("Population conditions require unique frozen _eval_index values")
            seen_indices.add(index)
        for effect in study["effects"]:
            key = effect.get("effect_key")
            if not isinstance(key, str) or not key or key in seen_effects or effect.get("study_id") != sid:
                raise ValueError(f"{sid}: invalid or duplicate effect")
            seen_effects.add(key)
            for field in ("human_target", "statistic_spec", "identifiability"):
                if not isinstance(effect.get(field), dict):
                    raise ValueError(f"{key}: {field} is required")
            if effect.get("indicator") not in {"d", "b", "eta-square", "f", "chi-square"}:
                raise ValueError(f"{key}: unsupported effect indicator")
            if not effect.get("cells") or any(c.get("cell_id") not in study_cells for c in effect["cells"]):
                raise ValueError(f"{key}: effect references missing condition cells")