"""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)"