Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions client/TRAINING_DATA.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ fails bundle validation on leakage. Synthetic data is only for pipeline tests.
FT4 must evaluate an adapter against held-out and general control tasks before
any deployment or merge.

`/good` and `/bad` are recorded against the episode of the last answered
turn, in `manifests/operator-verdicts.jsonl` beside the sealed episodes. A
`/bad` episode is never an SFT target, whatever its automatic labels say,
and its final answer is an undesirable preference observation; a `/good` one
is a desirable observation.

## Operator fine-tuning jobs (FT4A)

Fine-tuning is an operator control-plane operation. It is not registered in
Expand Down
29 changes: 27 additions & 2 deletions client/cli/rag_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,11 @@ def read_user_input():

return text

# The session of the last answered turn: /good and /bad are recorded
# against its training episode.

last_session_id = None

while True:
STATUS.end_turn()

Expand Down Expand Up @@ -693,12 +698,31 @@ def read_user_input():
"verdict": user_input[1:],
"question": q[:500]})

# The captured episode carries the automatic labels; the
# verdict goes beside it, so a /bad answer never becomes a
# positive example and a /good one is known to be good.

recorded = False

if TRAINING_STORE is not None and last_session_id:
try:
episode_id = TRAINING_STORE.latest_episode_id(last_session_id)

if episode_id:
TRAINING_STORE.record_verdict(episode_id, user_input[1:])
recorded = True
except Exception:
recorded = False

where = " and on its training episode" if recorded else ""

if user_input == "/good":
n = save_experience(q, a)
print(f"Saved as fine-tuning sample "
f"({n} in experience.jsonl)\n")
f"({n} in experience.jsonl){where}\n")
else:
print("Noted as bad (archived, not used for training)\n")
print(f"Noted as bad (archived, not used for training)"
f"{where}\n")
else:
print("No complete exchange to rate.\n")

Expand Down Expand Up @@ -1027,6 +1051,7 @@ def read_user_input():
session_handle = SessionHandle(
SESSION_STORE, new_session_id(), session_configuration,
)
last_session_id = session_handle.session_id
# What the tree is actually built and tested with, discovered once.
# It feeds the verification policy as well as the build gate: a run of
# the project's own test command is the project's own verification,
Expand Down
74 changes: 74 additions & 0 deletions client/tests/test_operator_verdicts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""The operator's /good and /bad reach the training data.

They used to be archived beside the conversation and nowhere else, so an
answer called bad kept the automatic final_success label of its episode
and stayed a positive example.
"""

import tempfile
import unittest
from pathlib import Path

from tests.test_sft_dataset import episode, turn
from training.preference_dataset import OutcomeLabel, OutcomeLabelPolicy
from training.sft_dataset import SFTDatasetBuilder
from training.training_store import TrainingStore, TrainingStoreError


def answered(episode_id):
return episode([turn(0, output="the answer", labels=("final_success",))],
episode_id=episode_id, task_id=episode_id)


class Journal(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.store = TrainingStore(Path(self.temp.name) / "training")

def tearDown(self):
self.temp.cleanup()

def test_the_latest_verdict_wins_and_bad_names_are_refused(self):
self.store.save_episode(answered("episode_a"))
self.store.record_verdict("episode_a", "good")
self.store.record_verdict("episode_a", "bad")

self.assertEqual(self.store.operator_verdicts(), {"episode_a": "bad"})

for episode_id, verdict in (("episode_a", "meh"), ("../x", "bad")):
with self.assertRaises(TrainingStoreError):
self.store.record_verdict(episode_id, verdict)

def test_the_latest_episode_is_found(self):
self.assertIsNone(self.store.latest_episode_id())
self.store.save_episode(answered("episode_a"))
self.store.save_episode(answered("episode_b"))

self.assertEqual(self.store.latest_episode_id(), "episode_b")
self.assertIsNone(self.store.latest_episode_id("another-session"))

def test_a_bad_answer_is_never_an_sft_target(self):
self.store.save_episode(answered("episode_a"))
self.assertEqual(len(SFTDatasetBuilder(self.store).build().samples), 1)

self.store.record_verdict("episode_a", "bad")
result = SFTDatasetBuilder(self.store).build()

self.assertEqual(list(result.samples), [])
self.assertGreater(result.report["exclusion_reasons"]["operator_rejected"], 0)


class Preferences(unittest.TestCase):
def test_the_verdict_outranks_the_automatic_label(self):
source = answered("episode_a")
last = source.turns[-1]

self.assertEqual(OutcomeLabelPolicy().label(source, last)[0], OutcomeLabel.DESIRABLE)
self.assertEqual(OutcomeLabelPolicy({"episode_a": "bad"}).label(source, last)[:2],
(OutcomeLabel.UNDESIRABLE, ("operator_rejected",)))
self.assertEqual(OutcomeLabelPolicy({"episode_a": "good"}).label(source, last)[:2],
(OutcomeLabel.DESIRABLE, ("operator_approved",)))


if __name__ == "__main__":
unittest.main()
20 changes: 18 additions & 2 deletions client/training/preference_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@


PREFERENCE_SCHEMA_VERSION = 1
OUTCOME_POLICY_VERSION = 1
OUTCOME_POLICY_VERSION = 2
PREFERENCE_EXPORTER_VERSION = 1
CONTEXT_INDEX_SCHEMA_VERSION = 1

Expand Down Expand Up @@ -272,6 +272,10 @@ class OutcomeLabelPolicy:
"plan_progress", "recovery_after_failure",
})

def __init__(self, verdicts: Mapping[str, str] | None = None) -> None:
#: The operator's /good and /bad, by episode.
self.verdicts = dict(verdicts or {})

def label(self, episode: TrainingEpisode, turn: TrainingTurn
) -> tuple[OutcomeLabel, tuple[str, ...], EvidenceStrength]:
"""Label one turn from observed outcomes, or refuse to.
Expand All @@ -287,6 +291,17 @@ def label(self, episode: TrainingEpisode, turn: TrainingTurn
if not turn.primary_candidate or turn.role.lower() in {"explorer", "reviewer"}:
return OutcomeLabel.UNKNOWN, ("auxiliary_turn",), EvidenceStrength.WEAK

# The operator's verdict on the answer outranks every automatic label:
# it is the one judgement made by someone who read it.

verdict = self.verdicts.get(episode.episode_id)

if verdict and not turn.tool_calls and turn is episode.turns[-1]:
if verdict == "bad":
return OutcomeLabel.UNDESIRABLE, ("operator_rejected",), EvidenceStrength.STRONG

return OutcomeLabel.DESIRABLE, ("operator_approved",), EvidenceStrength.STRONG

labels = set(turn.labels)
statuses = [call.status for call in turn.tool_calls]
successes = sum(status in {"ok", "success"} for status in statuses)
Expand Down Expand Up @@ -461,7 +476,8 @@ def __init__(self, store: TrainingStore | str | os.PathLike[str], *,
self.store = store if isinstance(store, TrainingStore) else TrainingStore(store)
self.configuration = configuration or PreferenceConfiguration()
self.redaction_policy = redaction_policy or TrainingRedactionPolicy.from_environment()
self.outcome_policy = outcome_policy or OutcomeLabelPolicy()
self.outcome_policy = outcome_policy or OutcomeLabelPolicy(
self.store.operator_verdicts())
self.index = DecisionContextIndex(self.store.root)

def _source_checksum(self, episode_id: str) -> str:
Expand Down
8 changes: 8 additions & 0 deletions client/training/sft_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ def build(self) -> SFTBuildResult:
represented_projects: Counter[str] = Counter()

metadata = sorted(self.store.iterate_metadata(), key=lambda item: str(item.get("episode_id")))
verdicts = self.store.operator_verdicts()

for item in metadata:
episode_id = str(item.get("episode_id", ""))
Expand Down Expand Up @@ -687,6 +688,13 @@ def build(self) -> SFTBuildResult:
rejection_counts["project_filtered"] += len(episode.turns)
continue

# An answer the operator called bad is never a target, whatever
# the automatic labels say.

if verdicts.get(episode_id) == "bad":
rejection_counts["operator_rejected"] += len(episode.turns)
continue

represented_projects[project] += 1

for view_hash, snapshot in episode.tool_views.items():
Expand Down
67 changes: 67 additions & 0 deletions client/training/training_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import re
import tempfile
import fcntl
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterator, Mapping

Expand Down Expand Up @@ -215,6 +216,72 @@ def load_episode(self, episode_id: str) -> TrainingEpisode:

raise TrainingStoreError(f"could not load training episode: {exc}") from exc

def record_verdict(self, episode_id: str, verdict: str) -> None:
"""Append an operator's /good or /bad on an episode.

Episodes are sealed by checksum, so a verdict given after the fact is
kept beside them, in its own append-only journal, and the dataset
builders read both.
"""

if verdict not in {"good", "bad"}:
raise TrainingStoreError(f"unknown verdict: {verdict}")

self._path(self.episodes, episode_id, ".json")
entry = json.dumps({"episode_id": episode_id, "verdict": verdict,
"at": datetime.now(timezone.utc).isoformat(timespec="seconds")},
sort_keys=True)
lock = os.open(self.manifests / ".store.lock", os.O_RDWR | os.O_CREAT, 0o600)

try:
fcntl.flock(lock, fcntl.LOCK_EX)

with (self.manifests / "operator-verdicts.jsonl").open("a", encoding="utf-8") as stream:
stream.write(entry + "\n")
stream.flush()
os.fsync(stream.fileno())
finally:
fcntl.flock(lock, fcntl.LOCK_UN)
os.close(lock)

def operator_verdicts(self) -> dict[str, str]:
"""The latest operator verdict on each episode that has one."""

journal = self.manifests / "operator-verdicts.jsonl"
verdicts: dict[str, str] = {}

if not journal.exists():
return verdicts

with journal.open(encoding="utf-8") as stream:
for line in stream:
try:
item = json.loads(line)
except json.JSONDecodeError:
continue

if item.get("verdict") in {"good", "bad"}:
verdicts[str(item.get("episode_id"))] = item["verdict"]

return verdicts

def latest_episode_id(self, session_id: str | None = None) -> str | None:
"""The most recently stored episode, of this session when one is named."""

for item in reversed(list(self.iterate_metadata())):
episode_id = str(item.get("episode_id", ""))

if session_id is None:
return episode_id

try:
if self.load_episode(episode_id).session_id == session_id:
return episode_id
except TrainingStoreError:
continue

return None

def iterate_metadata(self, *, eligibility: str | None = None) -> Iterator[Mapping[str, object]]:
manifest = self.manifests / "episodes.jsonl"

Expand Down
Loading