File size: 10,414 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
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
"""Domain adapter interface for Chiron pipeline modules.

Active direct-prediction scripts load prompt modules explicitly, usually
``code/prompt/base/prediction_sft.py``.
"""

from __future__ import annotations

import json
import random
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Iterator

from utils.text_utils import (
    format_generation_label,
    normalize_prediction_label,
    parse_batch_predictions,
    parse_generation_predictions,
    rouge_l_f1,
)


@dataclass
class Prediction:
    """A single prediction task for a sample."""

    question: str
    """Full question text with options (with format instruction)."""

    ground_truth: str
    """Correct answer label. New data should use bare numbers, e.g. '3'.

    Legacy datasets may still contain 'Option 3'; training/eval utilities
    normalize both forms to number-only labels.
    """


@dataclass
class MeasurementTarget:
    """A scalar psychometric target for representation shaping."""

    construct: str
    """Stable construct name, for example ``big5.extraversion``."""

    score: float
    """Normalized target score. Current joint-training code expects [-1, 1]."""


@dataclass
class Sample:
    """Domain-agnostic representation of one sample."""

    observations: list[str]
    predictions: list[Prediction]
    data_source: str
    split: str
    within_person_holdout_predictions: list[Prediction] = field(default_factory=list)
    extra_info: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, d: dict[str, Any]) -> Sample:
        predictions = [Prediction(**p) for p in d["predictions"]]
        holdout_raw = d.get("within_person_holdout_predictions")
        if holdout_raw is None:
            holdout_raw = d.get("held_out_predictions", [])
        holdout_predictions = [Prediction(**p) for p in holdout_raw]
        obs = d["observations"]
        if isinstance(obs, str):
            obs = [s.strip() for s in obs.split("\n") if s.strip()]
        return cls(
            observations=obs,
            predictions=predictions,
            within_person_holdout_predictions=holdout_predictions,
            data_source=d["data_source"],
            split=d["split"],
            extra_info=d.get("extra_info", {}),
        )


def write_jsonl(samples: Iterator[Sample], path: Path) -> int:
    """Write samples to a JSONL file. Returns number of records written."""
    path.parent.mkdir(parents=True, exist_ok=True)
    count = 0
    with path.open("w", encoding="utf-8") as f:
        for sample in samples:
            f.write(json.dumps(sample.to_dict(), ensure_ascii=False) + "\n")
            count += 1
    return count


def read_jsonl(path: Path) -> Iterator[Sample]:
    """Yield Sample instances from a JSONL file."""
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                yield Sample.from_dict(json.loads(line))


def _obs_body(observations: list[str]) -> str:
    return "\n".join(f"- {o}" for o in observations)


def _questions_body(questions: list[str]) -> str:
    """Number questions starting at 1, separating with blank lines."""
    return "\n\n".join(f"Q{i}.\n{q.strip()}" for i, q in enumerate(questions, start=1))


class DomainAdapter(ABC):
    """Lightweight interface so pipeline modules stay domain-agnostic."""

    name: str = ""
    """Short domain name used by adapters and legacy prompt lookup."""

    min_observations: int = 50
    """Default lower bound for sampled observations in direct prediction prompts."""

    max_observations: int = 100
    """Default upper bound for sampled observations in direct prediction prompts."""

    # ---- abstract: each domain must answer ----------------------------------

    @abstractmethod
    def data_source(self) -> str:
        """Dataset identifier, e.g. ``'indievalue_wvs'``."""

    @abstractmethod
    def get_sample_id(self, sample: Sample) -> str:
        """Return a unique string ID for *sample* (used for resume dedup)."""

    @abstractmethod
    def default_input_path(self) -> Path:
        """Default path (relative to repo root) for the train JSONL."""

    # ---- task semantics -----------------------------------------------------

    def task_type(self) -> str:
        """Prediction target type: ``classification`` or ``generation``."""
        return "classification"

    def metric_name(self) -> str:
        """Metric used by evolution-time scoring."""
        return "exact_match"

    def select_target_predictions(
        self,
        sample: Sample,
        *,
        seed: int,
        sample_index: int,
        max_questions: int,
        min_questions: int = 1,
    ) -> list[Prediction]:
        """Select prediction questions used in one supervised direct-prediction row.

        Domains should override this when the target-question sampling policy is
        part of the dataset semantics. The base fallback shuffles predictions
        deterministically and samples a question count uniformly from
        ``min_questions..min(max_questions, len(predictions))``. ``max_questions
        <= 0`` means use all available predictions.
        """
        preds = list(sample.predictions)
        if not preds:
            return []
        rng = random.Random(seed ^ (sample_index * 1009))
        rng.shuffle(preds)
        limit = min(max_questions, len(preds)) if max_questions > 0 else len(preds)
        floor = max(1, min(min_questions, limit))
        n_target = rng.randint(floor, limit)
        return preds[:n_target]

    def select_measurement_targets(self, sample: Sample) -> list[MeasurementTarget]:
        """Return optional scalar targets for representation shaping.

        Most direct-prediction domains do not expose continuous measurement
        targets yet, so the default is empty. Domains can override this without
        changing the direct-prediction answer format.
        """
        del sample
        return []

    def select_observations(
        self,
        sample: Sample,
        *,
        seed: int,
        sample_index: int,
    ) -> list[str]:
        """Select observation records used in one direct-prediction prompt.

        Domains with very long record lists can override this hook. The default
        mirrors the active direct-SFT policy: keep all observations when the
        record is short; otherwise deterministically sample 50-100 records.
        """
        observations = list(sample.observations)
        if len(observations) <= self.min_observations:
            return observations

        rng = random.Random(seed ^ (sample_index * 9173) ^ 0x0B5E7A)
        rng.shuffle(observations)
        n_observations = rng.randint(
            self.min_observations,
            min(self.max_observations, len(observations)),
        )
        return observations[:n_observations]

    def parse_prediction_output(
        self, text: str, n: int, *, questions: list[str] | None = None,
    ) -> list[str]:
        """Parse model prediction output into one string per question."""
        if self.task_type() == "generation":
            return parse_generation_predictions(text, n)
        return parse_batch_predictions(text, n)

    def format_ground_truth(self, ground_truth: str) -> str:
        """Render a supervised answer label for training."""
        if self.task_type() == "generation":
            return format_generation_label(ground_truth)
        return normalize_prediction_label(ground_truth)

    def format_question_block(self, questions: list[str]) -> str:
        """Render selected questions in the user prompt."""
        return _questions_body(questions)

    def record_context(self) -> str:
        """One-sentence domain context shown immediately before the records tag."""
        return "Below are records describing this person."

    def format_observations_block(self, observations: list[str]) -> str:
        """Render observations in the user prompt."""
        return _obs_body(observations)

    def format_answer_block(self, predictions: list[Prediction]) -> str:
        """Render selected ground-truth labels in the assistant message."""
        lines: list[str] = []
        for i, pred in enumerate(predictions, start=1):
            answer = self.format_ground_truth(pred.ground_truth)
            if self.task_type() == "classification":
                answer = f"Option {answer}"
            lines.append(f"Q{i}: {answer}")
        return "\n".join(lines)

    def score_predictions(self, predictions: list[str], ground_truths: list[str]) -> dict[str, Any]:
        """Return a high-is-better score plus metric details."""
        if self.task_type() == "generation":
            scores = [rouge_l_f1(p, g) for p, g in zip(predictions, ground_truths)]
            avg = sum(scores) / len(scores) if scores else 0.0
            return {
                "score": avg,
                "rouge_l_f1": avg,
                "per_example_rouge_l_f1": scores,
            }

        correct = sum(
            normalize_prediction_label(p) == normalize_prediction_label(g)
            for p, g in zip(predictions, ground_truths)
        )
        n = len(ground_truths)
        return {"score": correct / n if n else 0.0, "n_correct": correct}

    def prediction_feedback(
        self,
        questions: list[str],
        predictions: list[str],
        ground_truths: list[str],
    ) -> str:
        """Feedback block for mutation prompts."""
        if self.task_type() == "generation":
            blocks = []
            for q, p, g in zip(questions, predictions, ground_truths):
                score = rouge_l_f1(p, g)
                blocks.append(
                    f"Q: {q}\n"
                    f"  ROUGE-L F1: {score:.4f}\n"
                    f"  Generated text: {p}\n"
                    f"  Gold text: {g}"
                )
            return "\n\n".join(blocks) if blocks else "(none)"

        wrong_items = [
            f"Q: {q}\n  Predicted: {p}\n  Correct: {g}"
            for q, p, g in zip(questions, predictions, ground_truths)
            if normalize_prediction_label(p) != normalize_prediction_label(g)
        ]
        return "\n\n".join(wrong_items) if wrong_items else "(none)"