sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw
History Blame Contribute Delete
87.4 kB
"""Executable TRL backend for the frozen Qwen3.5-2B training plans.
Heavy GPU libraries are imported only inside :func:`run`. The artifact,
prompt, reward, image-integrity, and token-budget preparation below remains
CPU-testable and fails closed before a trainer can touch a GPU.
"""
from __future__ import annotations
import copy
import hashlib
import json
import os
import random
import re
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast
from ..atomic_io import (
JsonlAppender,
atomic_write_bytes,
atomic_write_json,
read_jsonl,
)
from ..hashing import canonical_json_hash, sha256_file
from ..paths import repo_root
from ..vcs import current_code_commit
from .answers import answers_equal, parse_answer
from .artifacts import ANSWER_SCHEMA_REGEX
from .evi_po_contract import (
EVIContractError,
EVIGroupContract,
build_evi_group_contracts,
evidence_spec_for_view,
)
from .ledger import CompletionEntry, CompletionTokenLedger, completion_id
from .peft_contract import (
adapter_checkpoint_errors,
trainable_parameter_errors,
trainable_parameter_manifest,
)
from .rewards import (
ArmPlan,
RewardTrace,
RewardWeights,
arm_trainer_kind,
canonical_arm,
plan_arm,
score_completion,
)
from .slots import (
comparison_slot_from_row,
comparison_slot_manifest_sha256,
)
BACKEND_ENTRYPOINT = "explicit_learning.training.backend:run"
class BackendContractError(RuntimeError):
"""Raised before training when a frozen input cannot be executed safely."""
@dataclass(frozen=True)
class PreparedRecords:
"""Framework-neutral records plus their immutable input identity."""
rows: tuple[dict[str, Any], ...]
dataset_sha256: str
record_count: int
assistant_token_count: int | None = None
def _state_digest(value: Any) -> str:
"""Hash nested optimizer/scheduler/RNG state independent of device."""
digest = hashlib.sha256()
def visit(item: Any) -> None:
if item is None or isinstance(item, bool | int | float | str):
digest.update(f"{type(item).__name__}:{item!r}\n".encode())
return
if isinstance(item, Mapping):
digest.update(b"mapping{\n")
for key in sorted(item, key=lambda candidate: str(candidate)):
visit(str(key))
visit(item[key])
digest.update(b"}\n")
return
if isinstance(item, Sequence) and not isinstance(item, str | bytes | bytearray):
digest.update(f"sequence:{len(item)}[\n".encode())
for child in item:
visit(child)
digest.update(b"]\n")
return
try:
import numpy as np
if isinstance(item, np.ndarray):
digest.update(f"numpy:{item.dtype}:{item.shape}:".encode())
digest.update(item.tobytes())
return
except ImportError:
pass
try:
import torch
if isinstance(item, torch.Tensor):
# Flatten before the uint8 byte-view: ``.view(torch.uint8)`` reinterprets
# element bytes, which requires >=1 dim, so a 0-dim scalar (e.g. an AdamW
# ``step`` counter, a 0-dim float) would otherwise raise
# "self.dim() cannot be 0 to view Float as Byte". ``reshape(-1)`` is a no-op
# view on the already-contiguous tensor and yields the same bytes for any
# rank/dtype, including bfloat16 (which has no native numpy dtype).
tensor = item.detach().contiguous().reshape(-1).view(torch.uint8).cpu()
digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode())
digest.update(tensor.numpy().tobytes())
return
except ImportError:
pass
digest.update(
f"fallback:{type(item).__module__}.{type(item).__qualname__}:{item!r}\n".encode()
)
visit(value)
return digest.hexdigest()
def _mapping(value: Any, label: str) -> Mapping[str, Any]:
if not isinstance(value, Mapping):
raise BackendContractError(f"{label} must be an object")
return value
def _dataset_identity(runtime: Mapping[str, Any], path: Path) -> str:
"""Use the frozen manifest identity; hash bytes only in unfrozen unit use."""
launch = runtime.get("_launch_manifest")
if isinstance(launch, Mapping):
identity = launch.get("dataset_manifest_sha256")
if isinstance(identity, str) and identity:
return identity
return sha256_file(path)
def _assert_output_contract(value: str, *, label: str) -> None:
rendered = f"<answer>{value}</answer>"
if re.fullmatch(ANSWER_SCHEMA_REGEX, rendered) is None:
raise BackendContractError(
f"{label} cannot be represented by the constrained answer schema"
)
def _safe_asset(root: Path, image: Mapping[str, Any]) -> Path:
raw = image.get("path")
if not isinstance(raw, str) or not raw:
raise BackendContractError("image path must be a non-empty string")
relative = Path(raw)
if relative.is_absolute() or ".." in relative.parts or "\\" in raw:
raise BackendContractError(f"unsafe training image path: {raw!r}")
root = root.resolve()
resolved = (root / relative).resolve()
try:
resolved.relative_to(root)
except ValueError as exc:
raise BackendContractError(f"training image escapes dataset root: {raw!r}") from exc
if not resolved.is_file():
raise BackendContractError(f"training image does not exist: {resolved}")
return resolved
def _system_prompt() -> str:
path = repo_root() / "prompts" / "common_system.txt"
try:
prompt = path.read_text(encoding="utf-8").strip()
except OSError as exc:
raise BackendContractError(f"cannot read common system prompt: {exc}") from exc
if not prompt:
raise BackendContractError("common system prompt is empty")
return prompt
def _user_text(question: str, choices: Sequence[Mapping[str, Any]]) -> str:
if not question:
raise BackendContractError("training question is empty")
if not choices:
return question
rendered: list[str] = []
for choice in choices:
if "key" not in choice or "text" not in choice:
raise BackendContractError("choice requires key and text")
rendered.append(f"{choice['key']}. {choice['text']}")
return question + "\n\nChoices:\n" + "\n".join(rendered)
def _prompt(
question: str,
choices: Sequence[Mapping[str, Any]],
*,
image_count: int,
) -> list[dict[str, Any]]:
if image_count <= 0:
raise BackendContractError("a VLM training record must contain an image")
content = [{"type": "image"} for _ in range(image_count)]
content.append({"type": "text", "text": _user_text(question, choices)})
return [
{"role": "system", "content": [{"type": "text", "text": _system_prompt()}]},
{"role": "user", "content": content},
]
def _images_for_view(view: Mapping[str, Any], root: Path) -> tuple[Path, ...]:
raw_images = view.get("images")
if not isinstance(raw_images, list) or not raw_images:
raise BackendContractError("training view has no images")
images = tuple(_mapping(image, "image") for image in raw_images)
indices = [image.get("image_index") for image in images]
if indices != list(range(len(images))):
raise BackendContractError("training image indices are not contiguous")
return tuple(_safe_asset(root, image) for image in images)
def _evi_group_payload(
group: EVIGroupContract,
root: Path,
*,
require_evidence: bool,
) -> dict[str, Any]:
"""Materialize the loader-side grouped relationship for one EVI base item."""
targets = {
"FULL": group.full_answer,
"CONTROL": group.full_answer,
"MISSING": "<UNANSWERABLE>",
}
if group.substitute_answer is not None:
targets["SUBSTITUTE"] = group.substitute_answer
relationships: list[dict[str, Any]] = []
for relation, slot in group.relations:
view = slot.selected_view
image_paths = _images_for_view(view, root)
evidence = (
evidence_spec_for_view(
view,
dataset_root=root,
)
if relation == "FULL" and require_evidence
else None
)
relationships.append(
{
"relation": relation,
"state": str(view["state"]),
"source_role": str(view["role"]),
"view_id": str(view["view_id"]),
"prompt": _prompt(
group.question,
[copy.deepcopy(choice) for choice in group.choices],
image_count=len(image_paths),
),
"image_paths": [str(path) for path in image_paths],
"target": targets[relation],
"evidence": evidence,
}
)
return {
"schema_version": 1,
"group_id": group.group_id,
"base_id": group.base_id,
"answer_type": group.answer_type,
"choices": [copy.deepcopy(choice) for choice in group.choices],
"candidate_targets": list(group.candidates),
"relationships": relationships,
"evidence_supervision_relation": "FULL",
}
def prepare_rl_records(runtime: Mapping[str, Any]) -> PreparedRecords:
"""Validate a v2 slot manifest and map it to one frozen comparison arm."""
dataset_path = Path(str(runtime.get("dataset_path", ""))).resolve()
if not dataset_path.is_file():
raise BackendContractError(f"comparison-slot dataset not found: {dataset_path}")
try:
raw_rows = tuple(_mapping(row, "comparison slot") for row in read_jsonl(dataset_path))
slots = tuple(comparison_slot_from_row(row) for row in raw_rows)
except (OSError, json.JSONDecodeError, ValueError) as exc:
raise BackendContractError(f"invalid comparison-slot dataset: {exc}") from exc
if not slots:
raise BackendContractError("comparison-slot dataset is empty")
expected_manifest = runtime.get("comparison_slot_manifest_sha256")
launch = runtime.get("_launch_manifest")
if isinstance(launch, Mapping):
# Production runs already bind this identity in the frozen plan and
# launcher. Re-canonicalizing all 46K slots in every rank/run only
# repeated a large hash with no additional experimental signal.
if launch.get("comparison_slot_manifest_sha256", expected_manifest) != expected_manifest:
raise BackendContractError("comparison-slot identity differs from frozen launch plan")
else:
# Direct library/unit use has no frozen launcher contract, so retain the
# local consistency check there.
actual_manifest = comparison_slot_manifest_sha256(slots)
if actual_manifest != expected_manifest:
raise BackendContractError(
f"comparison-slot manifest mismatch: {actual_manifest} != {expected_manifest}"
)
try:
arm = canonical_arm(str(runtime.get("arm", "")))
except ValueError as exc:
raise BackendContractError(str(exc)) from exc
trainer_kind = str(runtime.get("trainer_kind") or arm_trainer_kind(arm))
root = Path(str(runtime.get("dataset_asset_root", ""))).resolve()
if not root.is_dir():
raise BackendContractError(f"dataset asset root not found: {root}")
evi_payloads: dict[str, dict[str, Any]] = {}
# Every EVI trainer variant needs the same grouped relationship payload.
# The ablation arm name changes one objective coefficient, not the loader
# contract. Restricting this to the literal ``evi_po`` arm made all EVI
# ablations fail only after the GPU trainer started.
if trainer_kind == "evi_po":
evi_config = _mapping(runtime.get("evi_po_config"), "frozen EVI-PO config")
try:
lambda_direction = float(evi_config["lambda_direction"])
lambda_evidence = float(evi_config["lambda_evidence"])
except (KeyError, TypeError, ValueError) as exc:
raise BackendContractError("frozen EVI-PO weights are malformed") from exc
if lambda_direction > 0.0 or lambda_evidence > 0.0:
try:
evi_groups = build_evi_group_contracts(slots)
evi_payloads = {
group_id: _evi_group_payload(
group,
root,
require_evidence=lambda_evidence > 0.0,
)
for group_id, group in evi_groups.items()
}
except EVIContractError as exc:
raise BackendContractError(f"invalid grouped EVI-PO dataset: {exc}") from exc
prepared: list[dict[str, Any]] = []
for slot in slots:
if slot.split != "train":
raise BackendContractError(
f"evaluation leakage: slot {slot.slot_id} has split={slot.split!r}"
)
plan = plan_arm(slot, arm)
_assert_output_contract(plan.gold_target, label=f"slot {slot.slot_id} gold target")
view = (
slot.full_view
if plan.input_view_id == slot.full_view.get("view_id")
else slot.selected_view
)
if view.get("view_id") != plan.input_view_id:
raise BackendContractError(f"slot {slot.slot_id}: planned view is not persisted")
image_paths = _images_for_view(view, root)
choices = [copy.deepcopy(choice) for choice in slot.choices]
row = {
"prompt": _prompt(slot.question, choices, image_count=len(image_paths)),
"image_paths": [str(path) for path in image_paths],
"slot_id": slot.slot_id,
"group_id": slot.group_id,
"base_id": slot.base_id,
"gold_target": plan.gold_target,
"answer_type": plan.answer_type,
"choices": choices,
"arm": plan.arm,
}
if trainer_kind == "evi_po" and evi_payloads:
try:
row["evi_group"] = copy.deepcopy(evi_payloads[slot.group_id])
except KeyError as exc:
raise BackendContractError(
f"slot {slot.slot_id}: no complete EVI group payload"
) from exc
prepared.append(row)
return PreparedRecords(
rows=tuple(prepared),
dataset_sha256=_dataset_identity(runtime, dataset_path),
record_count=len(prepared),
)
def prepare_sft_records(runtime: Mapping[str, Any]) -> PreparedRecords:
"""Validate certificate-target prompt/completion records for SFT."""
dataset_path = Path(str(runtime.get("dataset_path", ""))).resolve()
if not dataset_path.is_file():
raise BackendContractError(f"SFT dataset not found: {dataset_path}")
expected_kind = str(runtime.get("arm", ""))
root = Path(str(runtime.get("dataset_asset_root", ""))).resolve()
if not root.is_dir():
raise BackendContractError(f"dataset asset root not found: {root}")
prepared: list[dict[str, Any]] = []
try:
rows = tuple(_mapping(row, "SFT row") for row in read_jsonl(dataset_path))
except (OSError, json.JSONDecodeError) as exc:
raise BackendContractError(f"invalid SFT dataset: {exc}") from exc
if not rows:
raise BackendContractError("SFT dataset is empty")
seen: set[tuple[str, str]] = set()
for row in rows:
if row.get("schema_version") != 2:
raise BackendContractError("SFT row must use schema_version=2")
if row.get("record_kind") != expected_kind:
raise BackendContractError(
f"SFT record kind {row.get('record_kind')!r} != frozen arm {expected_kind!r}"
)
if row.get("split") != "train":
raise BackendContractError("evaluation leakage: SFT row is not split=train")
question = row.get("question")
choices = row.get("choices")
images = row.get("images")
response = row.get("assistant_response")
target = row.get("target")
answer_type = row.get("answer_type")
if not isinstance(question, str) or not isinstance(choices, list):
raise BackendContractError("SFT question/choices are malformed")
if not isinstance(images, list) or not images:
raise BackendContractError("SFT row has no images")
if not isinstance(response, str) or not isinstance(target, str):
raise BackendContractError("SFT response/target is malformed")
_assert_output_contract(target, label=f"SFT row {row.get('view_id')} target")
if re.fullmatch(ANSWER_SCHEMA_REGEX, response) is None:
raise BackendContractError("SFT response violates the constrained answer schema")
if not isinstance(answer_type, str):
raise BackendContractError("SFT answer_type is malformed")
parsed = parse_answer(response)
if not parsed.valid or not answers_equal(
parsed.require_content(),
target,
answer_type,
choices=choices,
):
raise BackendContractError("SFT response does not exactly encode its target")
identity = (str(row.get("group_id", "")), str(row.get("view_id", "")))
if not all(identity) or identity in seen:
raise BackendContractError("SFT group/view identity is empty or duplicated")
seen.add(identity)
image_rows = [_mapping(image, "SFT image") for image in images]
image_paths = tuple(_safe_asset(root, image) for image in image_rows)
choice_rows = [copy.deepcopy(dict(choice)) for choice in choices]
prepared.append(
{
"prompt": _prompt(question, choice_rows, image_count=len(image_paths)),
"completion": [
{
"role": "assistant",
"content": [{"type": "text", "text": response}],
}
],
"image_paths": [str(path) for path in image_paths],
"group_id": identity[0],
"base_id": str(row.get("base_id", "")),
"view_id": identity[1],
"assistant_response": response,
}
)
return PreparedRecords(
rows=tuple(prepared),
dataset_sha256=_dataset_identity(runtime, dataset_path),
record_count=len(prepared),
)
def _completion_text(value: Any) -> str:
if isinstance(value, str):
return value
if isinstance(value, Mapping):
if "content" in value:
return _completion_text(value["content"])
if "text" in value:
return str(value["text"])
if isinstance(value, Sequence) and not isinstance(value, bytes | bytearray):
return "".join(_completion_text(item) for item in value)
raise BackendContractError(f"unsupported completion structure: {type(value)!r}")
def _aligned(values: Sequence[Any], length: int, label: str) -> list[Any]:
items = list(values)
if len(items) == length:
return items
if items and length % len(items) == 0:
repeat = length // len(items)
return [item for item in items for _ in range(repeat)]
raise BackendContractError(
f"reward metadata {label} has length {len(items)}, expected a divisor of {length}"
)
def sft_loss_token_count(processor: Any, row: Mapping[str, Any]) -> int:
"""Count the exact labels used by TRL's VLM prompt-completion collator.
TRL 1.9.1 renders the conversational prompt and completion separately,
tokenizes the rendered completion with ``add_special_tokens=False``, and
applies its attention mask as the completion-only loss mask. Consequently
assistant turn delimiters and the end-of-turn newline are loss-bearing;
tokenizing only ``assistant_response`` is not equivalent.
"""
try:
from trl.data_utils import apply_chat_template, prepare_multimodal_messages
except ImportError as exc:
raise BackendContractError(
"TRL 1.9.1 is required for exact SFT loss-token accounting"
) from exc
prompt = row.get("prompt")
completion = row.get("completion")
raw_paths = row.get("image_paths")
if (
not isinstance(prompt, list)
or not isinstance(completion, list)
or not isinstance(raw_paths, list)
or not raw_paths
):
raise BackendContractError(
"SFT loss-token accounting requires prompt, completion, and image_paths"
)
images = [_load_pil(str(path)) for path in raw_paths]
try:
rendered = apply_chat_template(
{
"prompt": prepare_multimodal_messages(
copy.deepcopy(prompt),
images=images,
),
"completion": prepare_multimodal_messages(copy.deepcopy(completion)),
},
processor,
)
except (KeyError, TypeError, ValueError) as exc:
raise BackendContractError(f"TRL SFT chat-template rendering failed: {exc}") from exc
completion_text = rendered.get("completion")
if not isinstance(completion_text, str) or not completion_text:
raise BackendContractError("TRL SFT chat template produced an empty completion")
encoded = processor(
text=[completion_text],
padding=True,
padding_side="right",
return_tensors="pt",
add_special_tokens=False,
)
if not isinstance(encoded, Mapping) or "attention_mask" not in encoded:
raise BackendContractError("processor did not return an SFT completion attention mask")
attention = encoded["attention_mask"]
try:
count = int(attention[0].sum().item())
except (AttributeError, IndexError, TypeError, ValueError) as exc:
raise BackendContractError(
"processor returned an unsupported SFT completion attention mask"
) from exc
if count <= 0:
raise BackendContractError("SFT completion has no loss-bearing tokens")
return count
def _completion_id_count(processor: Any, value: Any) -> tuple[int, bool]:
"""Return ``(non-pad token count, terminated)`` for one completion id sequence.
``terminated`` is False iff the sequence was truncated — its last token is
neither EOS nor PAD, i.e. generation hit the token cap without closing. Under
``truncation_policy: reject_sample`` (experiment.yaml) that is a rejection
signal handled by the caller, NOT a fatal contract error: a missing tokenizer
terminal id or empty sequence still raises, but truncation no longer does.
"""
if hasattr(value, "tolist"):
value = value.tolist()
if (
isinstance(value, Sequence)
and value
and isinstance(value[0], Sequence)
and not isinstance(value[0], str | bytes | bytearray)
):
if len(value) != 1:
raise BackendContractError("one completion must have exactly one token-id sequence")
value = value[0]
if not isinstance(value, Sequence) or isinstance(value, str | bytes | bytearray):
raise BackendContractError("completion_ids must contain token-id sequences")
tokenizer = getattr(processor, "tokenizer", processor)
pad_id = getattr(tokenizer, "pad_token_id", None)
ids = [int(token) for token in value]
if not ids:
raise BackendContractError("completion_ids contains no sampled tokens")
eos_value = getattr(tokenizer, "eos_token_id", None)
eos_ids = (
{int(token) for token in eos_value}
if isinstance(eos_value, Sequence) and not isinstance(eos_value, str | bytes)
else ({int(eos_value)} if eos_value is not None else set())
)
terminal_ids = set(eos_ids)
if pad_id is not None:
terminal_ids.add(int(pad_id))
if not terminal_ids:
raise BackendContractError("tokenizer exposes neither eos_token_id nor pad_token_id")
terminated = ids[-1] in terminal_ids
if pad_id is not None:
ids = [token for token in ids if token != int(pad_id)]
if not ids:
raise BackendContractError("completion_ids contains no sampled tokens")
return len(ids), terminated
def make_reward_function(
runtime: Mapping[str, Any],
*,
processor: Any,
ledger: CompletionTokenLedger,
ledger_path: Path,
trace_path: Path,
) -> Callable[..., list[float]]:
"""Create the sole reward function, including exact sampled-token accounting."""
arm = canonical_arm(str(runtime["arm"]))
run_id = str(runtime["run_id"])
generations = int(runtime["generations_per_prompt"])
weights = RewardWeights(answer=1.0, format=0.0, invalid_format_penalty=-1.0)
# Per-row provenance state: tag every emitted reward-trace row with the
# code commit and frozen-plan identity that produced it, so a merged
# multi-run analysis file is self-describing and rows from a corrupted /
# superseded code state (e.g. an arm whose first half ran before a trainer
# fix) are distinguishable from clean rows. ``code_commit`` is the ACTUAL
# running commit (git HEAD at process start, best-effort), not the frozen
# manifest's provenance commit -- the two can diverge when an arm is
# frozen under one commit but launched under a later fix, and the running
# commit is what determines whether a row is clean. ``frozen_config_sha256``
# is the stable frozen-plan identity from the verified launch manifest.
# Neither value mutates the runtime dict, so config_sha256 (and thus
# checkpoint resume) is unaffected.
launch_state = _mapping(
runtime.get("_launch_manifest"), "verified launch manifest"
)
row_code_commit = current_code_commit()
row_frozen_config_sha256 = str(launch_state["frozen_config_sha256"])
def reward(
completions: Sequence[Any],
completion_ids: Sequence[Any],
gold_target: Sequence[Any],
answer_type: Sequence[Any],
choices: Sequence[Any],
slot_id: Sequence[Any],
group_id: Sequence[Any],
base_id: Sequence[Any],
**_: Any,
) -> list[float]:
texts = [_completion_text(completion) for completion in completions]
size = len(texts)
token_id_rows = _aligned(completion_ids, size, "completion_ids")
golds = _aligned(gold_target, size, "gold_target")
types = _aligned(answer_type, size, "answer_type")
choice_rows = _aligned(choices, size, "choices")
slot_ids = _aligned(slot_id, size, "slot_id")
group_ids = _aligned(group_id, size, "group_id")
base_ids = _aligned(base_id, size, "base_id")
entries: list[CompletionEntry] = []
traces: list[dict[str, Any]] = []
rewards: list[float] = []
slot_generation: dict[str, int] = {}
for index, text in enumerate(texts):
current_slot = str(slot_ids[index])
generation_index = slot_generation.get(current_slot, 0)
slot_generation[current_slot] = generation_index + 1
if generation_index >= generations:
raise BackendContractError(
f"slot {current_slot} produced more than {generations} generations"
)
raw_choices = choice_rows[index]
if not isinstance(raw_choices, Sequence) or isinstance(
raw_choices, str | bytes | bytearray
):
raise BackendContractError("reward choices metadata is malformed")
plan = ArmPlan(
arm=arm,
slot_id=current_slot,
group_id=str(group_ids[index]),
base_id=str(base_ids[index]),
comparison_role="PERSISTED",
input_view_id="PERSISTED",
input_state="PERSISTED",
gold_target=str(golds[index]),
answer_type=str(types[index]),
choices=tuple(dict(_mapping(choice, "reward choice")) for choice in raw_choices),
)
token_count, terminated = _completion_id_count(processor, token_id_rows[index])
if terminated:
trace = score_completion(plan, text, weights=weights)
else:
# truncation_policy=reject_sample: a completion that hit the token
# cap without EOS is rejected as malformed (penalty reward, and
# loss-masked by TRL's mask_truncated_completions) rather than
# crashing the run. Its sampled tokens still count toward the
# budget ceiling, so the ledger entry is always recorded below.
trace = RewardTrace(
arm=arm,
slot_id=current_slot,
parser_valid=False,
parser_error="truncated_completion",
parsed_answer=None,
normalized_prediction=None,
normalized_gold="",
answer_component=0.0,
format_component=0.0,
total_reward=weights.invalid_format_penalty,
normalizer_branch="truncation_reject",
)
current_completion_id = completion_id(run_id, current_slot, generation_index)
entries.append(
CompletionEntry(
completion_id=current_completion_id,
token_count=token_count,
slot_id=current_slot,
generation_index=generation_index,
)
)
trace_row = {
**trace.__dict__,
"group_id": str(group_ids[index]),
"base_id": str(base_ids[index]),
"completion_id": current_completion_id,
"generation_index": generation_index,
"completion_tokens": token_count,
"terminated": terminated,
"code_commit": row_code_commit,
"frozen_config_sha256": row_frozen_config_sha256,
}
traces.append(trace_row)
rewards.append(trace.total_reward)
ledger.record_many(entries)
with JsonlAppender(trace_path) as appender:
appender.extend(traces)
return rewards
return reward
def _input_length(processor: Any, messages: Sequence[Mapping[str, Any]]) -> int:
apply_template = getattr(processor, "apply_chat_template", None)
if not callable(apply_template):
raise BackendContractError("processor has no apply_chat_template")
encoded = apply_template(
list(messages),
tokenize=True,
add_generation_prompt=False,
return_dict=True,
)
input_ids = encoded.get("input_ids") if isinstance(encoded, Mapping) else encoded
if input_ids is None:
raise BackendContractError("processor did not return input_ids")
shape = getattr(input_ids, "shape", None)
if shape is not None:
return int(shape[-1])
if isinstance(input_ids, Sequence) and input_ids and isinstance(input_ids[0], Sequence):
return len(input_ids[0])
if isinstance(input_ids, Sequence):
return len(input_ids)
raise BackendContractError("processor returned unsupported input_ids")
def _load_pil(path: str) -> Any:
from PIL import Image
with Image.open(path) as image:
return image.convert("RGB").copy()
def _materialize_images(rows: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
materialized: list[dict[str, Any]] = []
for source in rows:
row = copy.deepcopy(dict(source))
paths = row.pop("image_paths", None)
if not isinstance(paths, list) or not paths:
raise BackendContractError("prepared row has no image paths")
images = [_load_pil(str(path)) for path in paths]
if len(images) == 1:
row["image"] = images[0]
else:
row["images"] = images
row.pop("assistant_response", None)
materialized.append(row)
return materialized
def cap_sft_records(
rows: Sequence[Mapping[str, Any]],
*,
processor: Any,
max_assistant_tokens: int,
loss_token_counter: Callable[[Any, Mapping[str, Any]], int] = sft_loss_token_count,
) -> PreparedRecords:
"""Take at most one deterministic epoch without exceeding the loss-token cap."""
if max_assistant_tokens <= 0:
raise BackendContractError("SFT assistant-token cap must be positive")
scheduled: list[dict[str, Any]] = []
consumed = 0
for row in rows:
count = loss_token_counter(processor, row)
if count <= 0:
raise BackendContractError("SFT row has no loss-bearing completion tokens")
if consumed + count > max_assistant_tokens:
break
scheduled.append(copy.deepcopy(dict(row)))
consumed += count
if not scheduled:
raise BackendContractError("SFT token cap is smaller than the first admitted response")
return PreparedRecords(
rows=tuple(scheduled),
dataset_sha256="",
record_count=len(scheduled),
assistant_token_count=consumed,
)
def _rank_budget(runtime: Mapping[str, Any]) -> tuple[int, int]:
world_size = int(runtime["world_size"])
rank = int(os.environ.get("RANK", "0"))
if not 0 <= rank < world_size:
raise BackendContractError(f"RANK {rank} is outside world_size={world_size}")
total = int(runtime["max_completion_tokens_per_run"])
share, remainder = divmod(total, world_size)
return rank, share + (1 if rank < remainder else 0)
def _load_or_create_ledger(
runtime: Mapping[str, Any],
*,
dataset_sha256: str,
ledger_path: Path,
) -> CompletionTokenLedger:
rank, rank_cap = _rank_budget(runtime)
identity = canonical_json_hash(dict(runtime))
if ledger_path.exists():
return CompletionTokenLedger.load(
ledger_path,
expected_run_id=f"{runtime['run_id']}:rank-{rank}",
expected_max_tokens=rank_cap,
expected_config_sha256=identity,
expected_data_manifest_sha256=dataset_sha256,
expected_comparison_slot_manifest_sha256=str(
runtime["comparison_slot_manifest_sha256"]
),
)
return CompletionTokenLedger(
run_id=f"{runtime['run_id']}:rank-{rank}",
max_tokens=rank_cap,
config_sha256=identity,
data_manifest_sha256=dataset_sha256,
comparison_slot_manifest_sha256=str(runtime["comparison_slot_manifest_sha256"]),
)
def _accounting_frontier_paths(
checkpoint: Path,
*,
rank: int,
) -> tuple[Path, Path, Path]:
root = checkpoint / "accounting"
return (
root / f"rank-{rank}.ledger.json",
root / f"rank-{rank}.reward-trace.jsonl",
root / f"rank-{rank}.frontier.json",
)
def _snapshot_accounting_frontier(
*,
checkpoint: Path,
rank: int,
optimizer_step: int,
ledger_path: Path,
trace_path: Path,
) -> None:
"""Atomically bind reward accounting to one Trainer checkpoint frontier."""
if not ledger_path.is_file() or not trace_path.is_file():
raise BackendContractError("cannot checkpoint missing ledger/reward trace")
ledger_snapshot, trace_snapshot, frontier_path = _accounting_frontier_paths(
checkpoint, rank=rank
)
atomic_write_bytes(ledger_snapshot, ledger_path.read_bytes())
atomic_write_bytes(trace_snapshot, trace_path.read_bytes())
ledger_value = json.loads(ledger_snapshot.read_text(encoding="utf-8"))
entries = ledger_value.get("entries") if isinstance(ledger_value, dict) else None
if not isinstance(entries, list):
raise BackendContractError("checkpoint ledger snapshot has no entries list")
atomic_write_json(
frontier_path,
{
"schema_version": 2,
"optimizer_step": optimizer_step,
"rank": rank,
"ledger_completion_count": len(entries),
"ledger_consumed_tokens": ledger_value.get("consumed_tokens"),
"reward_trace_rows": sum(1 for _ in read_jsonl(trace_snapshot)),
},
)
def _restore_accounting_frontier(
*,
checkpoint: Path,
output: Path,
rank: int,
) -> None:
"""Rollback live accounting to the exact last durable Trainer checkpoint."""
ledger_snapshot, trace_snapshot, frontier_path = _accounting_frontier_paths(
checkpoint, rank=rank
)
try:
frontier = json.loads(frontier_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise BackendContractError(
f"cannot resume without accounting frontier {frontier_path}: {exc}"
) from exc
expected_step = int(checkpoint.name.removeprefix("checkpoint-"))
if (
not isinstance(frontier, dict)
or frontier.get("schema_version") != 2
or frontier.get("optimizer_step") != expected_step
or frontier.get("rank") != rank
):
raise BackendContractError("checkpoint accounting frontier identity mismatch")
if not ledger_snapshot.is_file() or not trace_snapshot.is_file():
raise BackendContractError("checkpoint accounting snapshot is incomplete")
loaded_ledger = CompletionTokenLedger.load(ledger_snapshot)
if (
loaded_ledger.completion_count != frontier.get("ledger_completion_count")
or loaded_ledger.consumed_tokens != frontier.get("ledger_consumed_tokens")
):
raise BackendContractError("checkpoint ledger counts differ from its frontier")
if sum(1 for _ in read_jsonl(trace_snapshot)) != frontier.get("reward_trace_rows"):
raise BackendContractError("checkpoint reward-trace row count mismatch")
atomic_write_bytes(
output / "token-ledgers" / f"rank-{rank}.json",
ledger_snapshot.read_bytes(),
)
atomic_write_bytes(
output / "reward-traces" / f"rank-{rank}.jsonl",
trace_snapshot.read_bytes(),
)
def _model_and_processor(runtime: Mapping[str, Any], *, sft: bool) -> tuple[Any, Any, Any]:
from peft import LoraConfig, PeftModel
from transformers import AutoModelForMultimodalLM, AutoProcessor
model_path = str(runtime["model_path"])
processor = AutoProcessor.from_pretrained(
model_path,
revision=str(runtime["model_revision"]),
)
# Note: do NOT pass use_cache here. Qwen3.5's constructor
# (Qwen3_5ForConditionalGeneration.__init__) accepts only `config`, and its
# config has no use_cache field, so the kwarg is rejected by from_pretrained.
# KV cache is disabled for training automatically via gradient_checkpointing.
model = AutoModelForMultimodalLM.from_pretrained(
model_path,
revision=str(runtime["model_revision"]),
dtype="bfloat16",
attn_implementation=str(runtime["attention_implementation"]),
)
if sft:
peft_config = LoraConfig(
task_type="CAUSAL_LM",
r=int(runtime["lora_rank"]),
lora_alpha=int(runtime["lora_alpha"]),
lora_dropout=float(runtime["lora_dropout"]),
target_modules=runtime["lora_target_modules"][0]
if runtime["lora_target_modules"] == ["all-linear"]
else list(runtime["lora_target_modules"]),
exclude_modules=["lm_head"],
bias="none",
)
return model, processor, peft_config
initial = Path(str(runtime["initial_checkpoint_path"]))
adapter_errors = adapter_checkpoint_errors(initial, runtime)
if adapter_errors:
raise BackendContractError("; ".join(adapter_errors))
model = PeftModel.from_pretrained(model, initial, is_trainable=True)
trainable_errors = trainable_parameter_errors(model)
if trainable_errors:
raise BackendContractError("; ".join(trainable_errors))
return model, processor, None
def _common_trainer_args(runtime: Mapping[str, Any]) -> dict[str, Any]:
return {
"output_dir": str(runtime["output_dir"]),
"per_device_train_batch_size": int(runtime["per_device_train_batch_size"]),
"gradient_accumulation_steps": int(runtime["gradient_accumulation_steps"]),
"num_train_epochs": 1.0,
"max_steps": int(runtime["max_optimizer_steps"]),
"learning_rate": float(runtime["learning_rate"]),
"lr_scheduler_type": "cosine",
"warmup_ratio": 0.03,
"optim": "adamw_torch",
"weight_decay": 0.0,
"adam_beta1": 0.9,
"adam_beta2": 0.999,
"adam_epsilon": 1.0e-8,
"max_grad_norm": 1.0,
"bf16": True,
"gradient_checkpointing": True,
"save_strategy": "steps",
"save_steps": int(runtime["checkpoint_interval"]),
"save_total_limit": 2,
"logging_steps": 1,
# TensorBoard logging is opt-in and gated to verified execute runs only:
# the default stays "none" so CPU contracts, dry-runs, and plan-freezes
# never emit traces. Set EXPLICIT_REPORT_TO=tensorboard only when
# launching a real training backend (launcher execute); tfevent files
# land under the run's output_dir, no network egress required.
"report_to": os.environ.get("EXPLICIT_REPORT_TO", "none"),
"run_name": str(runtime["run_id"]),
"seed": int(runtime["seed"]),
"data_seed": int(runtime["seed"]),
"dataloader_num_workers": 4,
"dataloader_pin_memory": True,
"remove_unused_columns": False,
}
def _validate_prompt_envelope(
runtime: Mapping[str, Any],
rows: Sequence[Mapping[str, Any]],
*,
processor: Any,
sft: bool,
max_prompt_tokens: int,
total_context_tokens: int,
) -> None:
# Safety gate: every row's prompt/SFT envelope must fit the frozen token
# budget. The per-row check (image decode + token count) is delegated to
# ``preflight`` which parallelizes it across a thread pool and memoizes the
# verdict by a fingerprint of the frozen inputs, removing the multi-minute
# serial GPU-idle stall. The gate stays bit-identical: the check body and
# the lowest-index failure message are unchanged, and any pool fault falls
# back to the original serial scan. See ``training.preflight``.
from .preflight import run_preflight
run_preflight(
runtime,
rows,
processor,
sft=sft,
max_prompt_tokens=max_prompt_tokens,
total_context_tokens=total_context_tokens,
)
def _train_sft(runtime: Mapping[str, Any]) -> tuple[Any, PreparedRecords, Any]:
from datasets import Dataset
from trl import SFTConfig, SFTTrainer
prepared = prepare_sft_records(runtime)
model, processor, peft_config = _model_and_processor(runtime, sft=True)
capped = cap_sft_records(
prepared.rows,
processor=processor,
max_assistant_tokens=int(runtime["max_completion_tokens_per_run"]),
)
_validate_prompt_envelope(
runtime,
capped.rows,
processor=processor,
sft=True,
max_prompt_tokens=int(runtime["max_prompt_tokens"]),
total_context_tokens=int(runtime["total_context_tokens"]),
)
dataset = Dataset.from_list(_materialize_images(capped.rows))
args = SFTConfig(
**_common_trainer_args(runtime),
max_length=None,
completion_only_loss=True,
assistant_only_loss=False,
packing=False,
shuffle_dataset=False,
)
trainer = SFTTrainer(
model=model,
args=args,
train_dataset=dataset,
processing_class=processor,
peft_config=peft_config,
)
return (
trainer,
PreparedRecords(
rows=capped.rows,
dataset_sha256=prepared.dataset_sha256,
record_count=capped.record_count,
assistant_token_count=capped.assistant_token_count,
),
processor,
)
def _train_rl(runtime: Mapping[str, Any]) -> tuple[Any, PreparedRecords, Any, Path]:
from transformers import TrainerCallback
from trl import GRPOConfig
from .lazy_dataset import LazyImageRLDataset
prepared = prepare_rl_records(runtime)
model, processor, _ = _model_and_processor(runtime, sft=False)
_validate_prompt_envelope(
runtime,
prepared.rows,
processor=processor,
sft=False,
max_prompt_tokens=int(runtime["max_prompt_tokens"]),
total_context_tokens=int(runtime["total_context_tokens"]),
)
cache_dir = os.environ.get("EXPLICIT_IMAGE_CACHE_DIR") or None
dataset = LazyImageRLDataset(prepared.rows, cache_dir=cache_dir)
output = Path(str(runtime["output_dir"]))
rank, _ = _rank_budget(runtime)
ledger_path = output / "token-ledgers" / f"rank-{rank}.json"
trace_path = output / "reward-traces" / f"rank-{rank}.jsonl"
ledger = _load_or_create_ledger(
runtime,
dataset_sha256=prepared.dataset_sha256,
ledger_path=ledger_path,
)
reward = make_reward_function(
runtime,
processor=processor,
ledger=ledger,
ledger_path=ledger_path,
trace_path=trace_path,
)
next_step_upper_bound = (
int(runtime["per_device_train_batch_size"])
* int(runtime["gradient_accumulation_steps"])
* int(runtime["max_completion_tokens"])
)
class CompletionBudgetCallback(TrainerCallback): # type: ignore[misc]
def on_step_end(self, args: Any, state: Any, control: Any, **kwargs: Any) -> Any:
del args, kwargs
can_continue = ledger.remaining_tokens >= next_step_upper_bound
import torch
distributed = torch.distributed
if distributed.is_available() and distributed.is_initialized():
device = (
torch.device("cuda", torch.cuda.current_device())
if torch.cuda.is_available()
else torch.device("cpu")
)
flag = torch.tensor(
[1 if can_continue else 0],
dtype=torch.int32,
device=device,
)
distributed.all_reduce(flag, op=distributed.ReduceOp.MIN)
can_continue = bool(flag.item())
if not can_continue:
control.should_training_stop = True
if (
runtime.get("run_mode") == "smoke"
and int(state.global_step) == 5
and not (output / "smoke-resume-boundary.json").exists()
):
control.should_save = True
control.should_training_stop = True
return control
def on_save(self, args: Any, state: Any, control: Any, **kwargs: Any) -> Any:
del kwargs
checkpoint = Path(str(args.output_dir)) / f"checkpoint-{state.global_step}"
# Persist accounting only at the same durable frontier as Trainer.
# A crash before this callback resumes the preceding checkpoint and
# legitimately regenerates the intervening rollouts.
ledger.save(ledger_path)
_snapshot_accounting_frontier(
checkpoint=checkpoint,
rank=rank,
optimizer_step=int(state.global_step),
ledger_path=ledger_path,
trace_path=trace_path,
)
return control
def on_train_end(self, args: Any, state: Any, control: Any, **kwargs: Any) -> Any:
del args, state, kwargs
ledger.save(ledger_path)
return control
common = _common_trainer_args(runtime)
vllm = _mapping(runtime.get("vllm_config"), "frozen vLLM config")
rl_kwargs = {
**common,
"dataloader_drop_last": True,
"shuffle_dataset": False,
"dataloader_prefetch_factor": 2,
"dataloader_persistent_workers": True,
"num_generations": int(runtime["generations_per_prompt"]),
"max_completion_length": int(runtime["max_completion_tokens"]),
"temperature": float(runtime["temperature"]),
"top_p": float(runtime["top_p"]),
"beta": float(runtime["beta"]),
"loss_type": str(runtime["loss_type"]),
"mask_truncated_completions": True,
"scale_rewards": "group",
"use_vllm": bool(runtime["use_vllm"]),
"vllm_mode": str(vllm["mode"]),
"vllm_gpu_memory_utilization": float(vllm["gpu_memory_utilization"]),
"vllm_max_model_length": int(vllm["max_model_length"]),
"vllm_tensor_parallel_size": int(vllm["tensor_parallel_size"]),
"vllm_enable_sleep_mode": bool(vllm["enable_sleep_mode"]),
"vllm_structured_outputs_regex": str(vllm["structured_outputs_regex"]),
"chat_template_kwargs": {"enable_thinking": bool(runtime["enable_thinking"])},
}
trainer_kind = str(runtime["trainer_kind"])
trainer_class: Any
if trainer_kind == "papo":
from .papo import PAPOTrainer
from .papo_contract import (
PAPO_ADAPTER_VERSION,
PAPO_UPSTREAM_SOURCE_SHA256,
)
papo = _mapping(runtime.get("papo_config"), "frozen PAPO config")
if (
papo.get("adapter_version") != PAPO_ADAPTER_VERSION
or papo.get("upstream_source_sha256") != PAPO_UPSTREAM_SOURCE_SHA256
):
raise BackendContractError("frozen PAPO adapter identity mismatch")
args = GRPOConfig(**rl_kwargs)
trainer_class = PAPOTrainer
trainer_extra = {"papo_config": papo}
elif trainer_kind == "evi_po":
from .evi_po import EVITrainer
from .evi_po_contract import EVI_PO_ADAPTER_VERSION
evi_po = _mapping(runtime.get("evi_po_config"), "frozen EVI-PO config")
if evi_po.get("adapter_version") != EVI_PO_ADAPTER_VERSION:
raise BackendContractError("frozen EVI-PO adapter identity mismatch")
# EVI-PO fires a RANK-DEPENDENT number of extra DDP forwards per step:
# _candidate_scores (evi_po.py:566) runs for every active group and
# _evidence_loss (:669) additionally for groups whose evidence is
# available (:778). With per_device_train_batch_size=1 a rank whose
# sharded micro-batch has no active group (raw_groups=[None]) fires 0
# extra forwards while another fires 2-3. DDP's default
# broadcast_buffers=True issues an NCCL buffer broadcast at the START of
# every model() forward, so the per-step broadcast count mismatches
# across ranks and NCCL deadlocks — deterministically, at the first step
# where the two shards diverge (the step-4 hang: one rank frozen mid
# candidate forward behind a buffer-broadcast, the other blocked at the
# metric gather). The explicit gather count is already rank-invariant
# (see evi_po._compute_loss), but the forward count is not. Disabling
# broadcast_buffers removes the per-forward collective so the asymmetry
# is harmless; the single per-step backward allreduce stays
# rank-invariant because every rank's policy forward (super()._compute_loss)
# exercises all LoRA parameters, so find_unused_parameters=False holds.
# Safe for Qwen3.5-VL: RMSNorm/LayerNorm carry no running-stat buffers
# and every rank loads the identical checkpoint, so buffers never
# diverge during training.
rl_kwargs = {**rl_kwargs, "ddp_broadcast_buffers": False}
args = GRPOConfig(**rl_kwargs)
trainer_class = EVITrainer
trainer_extra = {"evi_po_config": evi_po}
elif trainer_kind == "grpo":
from .aligned_grpo import AlignedGRPOTrainer
args = GRPOConfig(**rl_kwargs)
trainer_class = AlignedGRPOTrainer
trainer_extra = {}
else:
raise BackendContractError(f"unsupported RL trainer kind: {trainer_kind!r}")
trainer = trainer_class(
model=model,
args=args,
reward_funcs=reward,
train_dataset=dataset,
processing_class=processor,
callbacks=[CompletionBudgetCallback()],
**trainer_extra,
)
return trainer, prepared, processor, ledger_path
def _install_default_adapter_restore(
trainer: Any,
checkpoint: Path,
*,
rank: int,
) -> None:
"""Restore the trainable ``default`` (policy) adapter after a PEFT resume.
TRL's ``GRPOTrainer`` creates a frozen ``ref`` LoRA adapter -- a copy of the
pretrained init adapter used as the reference policy -- whenever ``beta != 0``
and the model is a PEFT model being re-trained (the papo / any KL arm). On
save the active ``default`` adapter lands in the checkpoint *root*
(``adapter_model.safetensors``) and the ``ref`` adapter lands in a ``ref/``
subdirectory. transformers' ``Trainer._load_from_checkpoint`` treats *any*
adapter subdirectory as "all adapters live in subdirectories" and loads ONLY
the subdirectories, skipping the root file -- so the trained policy adapter
is never restored and the model silently resumes from the init adapter.
This wrapper runs the pinned loader, then -- only when that broken
multi-adapter layout is present (a root adapter file alongside an adapter
subdirectory) -- explicitly loads the root adapter into ``default`` so the
policy weights are restored. For arms without a ``ref`` adapter (``beta ==
0``: answer_grpo / defacto / intervention_grpo / evi_po) there is no
subdirectory, the gate is False, and this is a no-op (the pinned loader
already restored ``default`` from the root). Installed for every RL resume
so a crash-recovered main run restores the policy too, not just the smoke
audit.
Restore mechanism: ``peft_model.load_adapter(checkpoint, "default",
is_trainable=True)`` -- the SAME robust path transformers' own
``_load_from_checkpoint`` takes for the single-adapter (``beta == 0``) case,
which overwrites the existing ``default`` adapter in place with the trained
root weights. An earlier implementation used
``set_peft_model_state_dict``; on the pinned peft 0.19.1 + transformers v5
stack its ``convert_peft_adapter_state_dict_for_transformers`` path silently
failed to restore on the real (DDP) resume (the model stayed at the init
adapter and the smoke resume-state audit caught it), even though it restored
correctly in a CPU repro -- so we use ``load_adapter`` instead, which is
exercised on every successful ``beta == 0`` resume and verified
elementwise-equal to the checkpoint root on the pinned stack. Optional
before/after digest logging is gated behind ``EXPLICIT_RESUME_RESTORE_DIAG``.
"""
# transformers.utils.ADAPTER_SAFE_WEIGHTS_NAME / ADAPTER_WEIGHTS_NAME, inlined
# so the gate runs torch/transformers-free (the heavy imports stay lazy inside
# the wrapper, exercised only on a real resume).
adapter_names = ("adapter_model.safetensors", "adapter_model.bin")
model_loader = getattr(trainer, "_load_from_checkpoint", None)
if not callable(model_loader):
return # the resume audit below raises on the missing pinned API
model_loader_fn = cast(Callable[..., Any], model_loader)
root_adapter = next(
(checkpoint / name for name in adapter_names if (checkpoint / name).is_file()),
None,
)
adapter_subdirs = [
child.name
for child in checkpoint.iterdir()
if child.is_dir() and any((child / name).is_file() for name in adapter_names)
]
if root_adapter is None or not adapter_subdirs:
return # single-adapter (beta == 0) layout: pinned loader restores default
def load_model(*args: Any, **kwargs: Any) -> Any:
result = model_loader_fn(*args, **kwargs)
# The pinned loader (transformers _load_from_checkpoint) took its
# multi-adapter branch because of the ref/ subdir and loaded ONLY ref/,
# skipping the root -- so `default` is still the init adapter. Restore
# the trained policy by loading the root adapter into `default` via
# peft's load_adapter (overwrite-in-place), the same path the beta == 0
# arms take. Unwrap accelerate/DDP so load_adapter targets the PeftModel;
# DDP shares parameter storage, so this writes the same tensors the
# wrapped trainer (and the smoke resume audit) see.
try:
peft_model = trainer.model
accelerator = getattr(trainer, "accelerator", None)
unwrap = getattr(accelerator, "unwrap_model", None) if accelerator is not None else None
if callable(unwrap):
try:
peft_model = unwrap(peft_model)
except Exception: # pragma: no cover - fall back to wrapped model
peft_model = trainer.model
_resume_restore_diag(rank, "before", _trainable_param_digest(trainer.model))
peft_model.load_adapter(str(checkpoint), "default", is_trainable=True)
_resume_restore_diag(rank, "after", _trainable_param_digest(trainer.model), ok=True)
except Exception as exc: # pragma: no cover - surfaces as a hard resume failure
_resume_restore_diag(rank, "exception", repr(exc), ok=False)
raise BackendContractError(
f"failed to restore default adapter from {root_adapter}: {exc}"
) from exc
return result
trainer._load_from_checkpoint = load_model
def _trainable_param_digest(model: Any) -> str:
"""sha256 over the model's trainable params (the resume-audit selection)."""
try:
return _state_digest(
{
name: parameter.detach()
for name, parameter in model.named_parameters()
if parameter.requires_grad
}
)
except Exception: # pragma: no cover - diagnostic only
return "unavailable"
def _resume_restore_diag(rank: int, stage: str, payload: Any, *, ok: bool = True) -> None:
"""Optional before/after digest log for the default-adapter restore.
No-op unless ``EXPLICIT_RESUME_RESTORE_DIAG`` is set, so production main /
ablation resumes pay nothing. Used to confirm the papo multi-adapter restore
took effect on the real (DDP) resume when validating the fix.
"""
if not os.environ.get("EXPLICIT_RESUME_RESTORE_DIAG"):
return
try:
with open(f"/tmp/papo_restore_diag_r{rank}.log", "a") as fh:
fh.write(f"{stage} ok={ok} {payload}\n")
except OSError: # pragma: no cover - diagnostic only
pass
def _install_resume_load_audit(
trainer: Any,
checkpoint: Path,
*,
rank: int,
) -> dict[str, Any]:
"""Instrument the pinned Trainer loaders and prove state was restored."""
import numpy as np
import torch
audit: dict[str, Any] = {
"schema_version": 1,
"status": "pending",
"rank": rank,
"checkpoint": str(checkpoint),
}
optimizer_loader = getattr(trainer, "_load_optimizer_and_scheduler", None)
rng_loader = getattr(trainer, "_load_rng_state", None)
model_loader = getattr(trainer, "_load_from_checkpoint", None)
if not all(callable(loader) for loader in (optimizer_loader, rng_loader, model_loader)):
raise BackendContractError(
"pinned Trainer resume loader API is unavailable for smoke audit"
)
optimizer_loader_fn = cast(Callable[..., Any], optimizer_loader)
rng_loader_fn = cast(Callable[..., Any], rng_loader)
model_loader_fn = cast(Callable[..., Any], model_loader)
def load_model(*args: Any, **kwargs: Any) -> Any:
result = model_loader_fn(*args, **kwargs)
phase_1_path = checkpoint.parent / "resume-audits" / (f"phase-1-rank-{rank}.json")
try:
phase_1 = json.loads(phase_1_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise BackendContractError(
f"cannot read phase-1 trainable state evidence: {exc}"
) from exc
loaded_adapter = {
name: parameter.detach()
for name, parameter in trainer.model.named_parameters()
if parameter.requires_grad
}
audit["phase_1_evidence_path"] = str(phase_1_path)
audit["checkpoint_trainable_parameter_sha256"] = phase_1.get(
"trainable_parameter_state_sha256"
)
audit["loaded_trainable_parameter_sha256"] = _state_digest(loaded_adapter)
audit["model_state_equal"] = (
audit["checkpoint_trainable_parameter_sha256"]
== audit["loaded_trainable_parameter_sha256"]
)
audit["model_loader_called"] = True
return result
def load_optimizer(*args: Any, **kwargs: Any) -> Any:
result = optimizer_loader_fn(*args, **kwargs)
optimizer_file = checkpoint / "optimizer.pt"
scheduler_file = checkpoint / "scheduler.pt"
if not optimizer_file.is_file() or not scheduler_file.is_file():
raise BackendContractError(
"checkpoint lacks optimizer.pt or scheduler.pt for resume audit"
)
expected_optimizer = torch.load(
optimizer_file,
map_location="cpu",
weights_only=False,
)
expected_scheduler = torch.load(
scheduler_file,
map_location="cpu",
weights_only=False,
)
actual_optimizer = trainer.optimizer.state_dict()
actual_scheduler = trainer.lr_scheduler.state_dict()
audit["checkpoint_optimizer_sha256"] = _state_digest(expected_optimizer)
audit["loaded_optimizer_sha256"] = _state_digest(actual_optimizer)
audit["checkpoint_scheduler_sha256"] = _state_digest(expected_scheduler)
audit["loaded_scheduler_sha256"] = _state_digest(actual_scheduler)
audit["optimizer_state_equal"] = (
audit["checkpoint_optimizer_sha256"] == audit["loaded_optimizer_sha256"]
)
audit["scheduler_state_equal"] = (
audit["checkpoint_scheduler_sha256"] == audit["loaded_scheduler_sha256"]
)
return result
def load_rng(*args: Any, **kwargs: Any) -> Any:
result = rng_loader_fn(*args, **kwargs)
candidates = (
checkpoint / f"rng_state_{rank}.pth",
checkpoint / "rng_state.pth",
)
rng_file = next((path for path in candidates if path.is_file()), None)
if rng_file is None:
raise BackendContractError("checkpoint lacks the rank RNG state file")
expected = torch.load(rng_file, map_location="cpu", weights_only=False)
current: dict[str, Any] = {
"python": random.getstate(),
"numpy": np.random.get_state(),
"cpu": torch.random.get_rng_state(),
}
if torch.cuda.is_available():
current["cuda"] = torch.cuda.random.get_rng_state_all()
comparisons: dict[str, bool] = {}
required_rng = {"python", "numpy", "cpu", "cuda"}
for key in required_rng:
comparisons[key] = (
key in expected
and key in current
and _state_digest(expected[key]) == _state_digest(current[key])
)
audit["checkpoint_rng_sha256"] = _state_digest(expected)
audit["loaded_rng_sha256"] = _state_digest(current)
audit["rng_components_equal"] = comparisons
audit["rng_state_equal"] = bool(comparisons) and all(comparisons.values())
return result
trainer._load_from_checkpoint = load_model
trainer._load_optimizer_and_scheduler = load_optimizer
trainer._load_rng_state = load_rng
return audit
def run(runtime: Mapping[str, Any]) -> int:
"""Execute one frozen plan after launcher's environment gate succeeds."""
output = Path(str(runtime["output_dir"])).resolve()
output.mkdir(parents=True, exist_ok=True)
completion_marker = output / "training-complete.json"
if completion_marker.exists():
raise BackendContractError(f"refusing to rerun completed training: {completion_marker}")
from transformers.trainer_utils import get_last_checkpoint
last_checkpoint = get_last_checkpoint(str(output))
process_pid = os.getpid()
trainer_kind = str(runtime["trainer_kind"])
ledger_path: Path | None = None
if trainer_kind != "sft":
rank, _ = _rank_budget(runtime)
live_ledger = output / "token-ledgers" / f"rank-{rank}.json"
live_trace = output / "reward-traces" / f"rank-{rank}.jsonl"
if last_checkpoint:
_restore_accounting_frontier(
checkpoint=Path(last_checkpoint),
output=output,
rank=rank,
)
elif live_ledger.exists() or live_trace.exists():
raise BackendContractError(
"uncheckpointed accounting exists without a Trainer checkpoint; "
"start a fresh run directory"
)
if trainer_kind == "sft":
trainer, prepared, _ = _train_sft(runtime)
else:
trainer, prepared, _, ledger_path = _train_rl(runtime)
rank = int(os.environ.get("RANK", "0"))
resume_load_audit: dict[str, Any] | None = None
if trainer_kind != "sft" and last_checkpoint is not None:
# Restores the policy adapter TRL's ref/ subdir makes the pinned loader
# skip; no-op for beta == 0 arms. Composes under the smoke audit below.
_install_default_adapter_restore(trainer, Path(last_checkpoint), rank=rank)
if runtime.get("run_mode") == "smoke" and last_checkpoint is not None:
resume_load_audit = _install_resume_load_audit(
trainer,
Path(last_checkpoint),
rank=rank,
)
result = trainer.train(resume_from_checkpoint=last_checkpoint)
actual_optimizer_steps = int(getattr(trainer.state, "global_step", -1))
import torch
distributed = torch.distributed
boundary_path = output / "smoke-resume-boundary.json"
if (
runtime.get("run_mode") == "smoke"
and last_checkpoint is None
and actual_optimizer_steps == 5
and not boundary_path.exists()
):
if distributed.is_available() and distributed.is_initialized():
distributed.barrier()
checkpoint = output / "checkpoint-5"
phase_memory_path = output / "resume-audits" / f"phase-1-rank-{rank}.json"
atomic_write_json(
phase_memory_path,
{
"rank": rank,
"trainable_parameter_state_sha256": _state_digest(
{
name: parameter.detach()
for name, parameter in trainer.model.named_parameters()
if parameter.requires_grad
}
),
"max_gpu_memory_allocated_bytes": int(torch.cuda.max_memory_allocated())
if torch.cuda.is_available()
else None,
"max_gpu_memory_reserved_bytes": int(torch.cuda.max_memory_reserved())
if torch.cuda.is_available()
else None,
},
)
if distributed.is_available() and distributed.is_initialized():
distributed.barrier()
if rank == 0:
if not checkpoint.is_dir():
raise BackendContractError("forced smoke resume boundary has no checkpoint-5")
frontier_rows = []
for ledger_rank in range(int(runtime["world_size"])):
ledger_snapshot, trace_snapshot, frontier = _accounting_frontier_paths(
checkpoint,
rank=ledger_rank,
)
if not all(path.is_file() for path in (ledger_snapshot, trace_snapshot, frontier)):
raise BackendContractError(
f"checkpoint-5 accounting frontier missing for rank {ledger_rank}"
)
frontier_rows.append(
{
"rank": ledger_rank,
"ledger": str(ledger_snapshot),
"reward_trace": str(trace_snapshot),
"frontier": str(frontier),
}
)
launch_manifest = _mapping(runtime.get("_launch_manifest"), "verified launch manifest")
phase_memory = [
{
**json.loads(
(output / "resume-audits" / f"phase-1-rank-{memory_rank}.json").read_text(
encoding="utf-8"
)
),
"path": str(output / "resume-audits" / f"phase-1-rank-{memory_rank}.json"),
}
for memory_rank in range(int(runtime["world_size"]))
]
atomic_write_json(
boundary_path,
{
"schema_version": 1,
"kind": "forced_new_process_smoke_resume_boundary",
"status": "awaiting_new_process_resume",
"optimizer_step": 5,
"first_process_pid": process_pid,
"checkpoint_path": str(checkpoint),
"accounting_frontiers": frontier_rows,
"phase_1_rank_memory": phase_memory,
"frozen_config_sha256": launch_manifest["frozen_config_sha256"],
"run_manifest_sha256": launch_manifest["run_manifest_sha256"],
},
)
if distributed.is_available() and distributed.is_initialized():
distributed.barrier()
# The smoke matrix wrapper observes the durable boundary and launches
# the exact same frozen plan in a new process.
return 75
if trainer_kind != "sft" and actual_optimizer_steps != int(runtime["max_optimizer_steps"]):
raise BackendContractError(
"RL run ended at "
f"{actual_optimizer_steps} optimizer steps; expected "
f"{runtime['max_optimizer_steps']}"
)
if resume_load_audit is not None:
required = (
resume_load_audit.get("model_loader_called") is True
and resume_load_audit.get("model_state_equal") is True
and resume_load_audit.get("optimizer_state_equal") is True
and resume_load_audit.get("scheduler_state_equal") is True
and resume_load_audit.get("rng_state_equal") is True
)
resume_load_audit["status"] = "passed" if required else "failed"
if not required:
raise BackendContractError(f"Trainer resume-state audit failed: {resume_load_audit}")
atomic_write_json(
output / "resume-audits" / f"phase-2-rank-{rank}.json",
resume_load_audit,
)
final_adapter = output / "final-adapter"
trainer.save_model(str(final_adapter))
realized_completion_tokens = 0
realized_completion_count = 0
max_gpu_memory_allocated = (
int(torch.cuda.max_memory_allocated()) if torch.cuda.is_available() else 0
)
max_gpu_memory_reserved = (
int(torch.cuda.max_memory_reserved()) if torch.cuda.is_available() else 0
)
if ledger_path is not None:
ledger_value = json.loads(ledger_path.read_text(encoding="utf-8"))
realized_completion_tokens = int(ledger_value["consumed_tokens"])
entries = ledger_value.get("entries")
if not isinstance(entries, list):
raise BackendContractError("completion ledger entries are malformed")
realized_completion_count = len(entries)
if torch.distributed.is_available() and torch.distributed.is_initialized():
device = torch.device("cuda", torch.cuda.current_device())
totals = torch.tensor(
[realized_completion_tokens, realized_completion_count],
dtype=torch.int64,
device=device,
)
torch.distributed.all_reduce(totals, op=torch.distributed.ReduceOp.SUM)
realized_completion_tokens = int(totals[0].item())
realized_completion_count = int(totals[1].item())
memory = torch.tensor(
[max_gpu_memory_allocated, max_gpu_memory_reserved],
dtype=torch.int64,
device=device,
)
torch.distributed.all_reduce(memory, op=torch.distributed.ReduceOp.MAX)
max_gpu_memory_allocated = int(memory[0].item())
max_gpu_memory_reserved = int(memory[1].item())
torch.distributed.barrier()
if rank == 0:
metrics = getattr(result, "metrics", {})
launch_manifest = _mapping(runtime.get("_launch_manifest"), "verified launch manifest")
parameter_rows, parameter_sha = trainable_parameter_manifest(trainer.model)
ledger_manifest: list[dict[str, Any]] = []
observed_slot_generations: dict[str, set[int]] = {}
if trainer_kind != "sft":
expected_config_sha = canonical_json_hash(dict(runtime))
for ledger_rank in range(int(runtime["world_size"])):
ledger_file = output / "token-ledgers" / f"rank-{ledger_rank}.json"
_, remainder = divmod(
int(runtime["max_completion_tokens_per_run"]),
int(runtime["world_size"]),
)
base_cap = int(runtime["max_completion_tokens_per_run"]) // int(
runtime["world_size"]
)
expected_cap = base_cap + (1 if ledger_rank < remainder else 0)
loaded = CompletionTokenLedger.load(
ledger_file,
expected_run_id=f"{runtime['run_id']}:rank-{ledger_rank}",
expected_max_tokens=expected_cap,
expected_config_sha256=expected_config_sha,
expected_data_manifest_sha256=prepared.dataset_sha256,
expected_comparison_slot_manifest_sha256=str(
runtime["comparison_slot_manifest_sha256"]
),
)
ledger_value = json.loads(ledger_file.read_text(encoding="utf-8"))
for entry in ledger_value["entries"]:
slot_id = entry.get("slot_id")
generation_index = entry.get("generation_index")
if not isinstance(slot_id, str) or not isinstance(generation_index, int):
raise BackendContractError("ledger lacks measured slot/generation identity")
observed_slot_generations.setdefault(slot_id, set()).add(generation_index)
ledger_manifest.append(
{
"rank": ledger_rank,
"path": str(ledger_file),
"completion_count": loaded.completion_count,
"consumed_tokens": loaded.consumed_tokens,
}
)
if sum(row["consumed_tokens"] for row in ledger_manifest) != (
realized_completion_tokens
):
raise BackendContractError("rank ledger token totals disagree")
if sum(row["completion_count"] for row in ledger_manifest) != (
realized_completion_count
):
raise BackendContractError("rank ledger completion totals disagree")
expected_completion_count = (
int(runtime["max_optimizer_steps"])
* int(runtime["per_device_train_batch_size"])
* int(runtime["gradient_accumulation_steps"])
* int(runtime["world_size"])
)
if realized_completion_count != expected_completion_count:
raise BackendContractError(
f"realized {realized_completion_count} completions; "
f"expected {expected_completion_count}"
)
expected_generations = set(range(int(runtime["generations_per_prompt"])))
if any(
generations != expected_generations
for generations in observed_slot_generations.values()
):
raise BackendContractError(
"one or more sampled slots lack the exact generation index set"
)
expected_unique_slots = expected_completion_count // int(
runtime["generations_per_prompt"]
)
if len(observed_slot_generations) != expected_unique_slots:
raise BackendContractError(
f"measured {len(observed_slot_generations)} unique slots; "
f"expected {expected_unique_slots}"
)
trace_manifest: list[dict[str, Any]] = []
malformed_completion_count = 0
completion_truncation_count = 0
if trainer_kind != "sft":
for trace_rank in range(int(runtime["world_size"])):
trace_file = output / "reward-traces" / f"rank-{trace_rank}.jsonl"
traces = list(read_jsonl(trace_file))
ledger_row = ledger_manifest[trace_rank]
if len(traces) != ledger_row["completion_count"]:
raise BackendContractError(
f"rank {trace_rank} reward trace/ledger row-count mismatch"
)
invalid = sum(1 for trace in traces if trace.get("parser_valid") is not True)
malformed_completion_count += invalid
truncated = sum(1 for trace in traces if trace.get("terminated") is False)
completion_truncation_count += truncated
trace_manifest.append(
{
"rank": trace_rank,
"path": str(trace_file),
"row_count": len(traces),
"malformed_completion_count": invalid,
"completion_truncation_count": truncated,
}
)
checkpoint_manifest = []
for checkpoint in sorted(
output.glob("checkpoint-*"),
key=lambda path: int(path.name.removeprefix("checkpoint-")),
):
if checkpoint.is_dir():
checkpoint_manifest.append(
{
"optimizer_step": int(checkpoint.name.removeprefix("checkpoint-")),
"path": str(checkpoint),
}
)
resume_probe: dict[str, Any] | None = None
if runtime.get("run_mode") == "smoke":
try:
boundary = json.loads(boundary_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise BackendContractError(
f"completed smoke lacks forced resume boundary: {exc}"
) from exc
checkpoint_5 = output / "checkpoint-5"
if (
not isinstance(boundary, dict)
or boundary.get("optimizer_step") != 5
or boundary.get("first_process_pid") == process_pid
or Path(str(last_checkpoint)).resolve() != checkpoint_5.resolve()
or not checkpoint_5.is_dir()
):
raise BackendContractError(
"smoke did not resume checkpoint-5 in a distinct process"
)
rank_resume_audits = []
for resume_rank in range(int(runtime["world_size"])):
audit_path = output / "resume-audits" / f"phase-2-rank-{resume_rank}.json"
audit = json.loads(audit_path.read_text(encoding="utf-8"))
rank_resume_audits.append(
{
**audit,
"path": str(audit_path),
}
)
if any(audit.get("status") != "passed" for audit in rank_resume_audits):
raise BackendContractError("one or more rank resume-load audits failed")
resume_probe = {
"status": "passed",
"checkpoint_step": 5,
"resumed_to_step": actual_optimizer_steps,
"first_process_pid": boundary["first_process_pid"],
"resumed_process_pid": process_pid,
"accounting_frontiers": boundary["accounting_frontiers"],
"phase_1_rank_evidence": boundary["phase_1_rank_memory"],
"rank_resume_load_audits": rank_resume_audits,
}
phase_1_memory = boundary.get("phase_1_rank_memory", [])
if not isinstance(phase_1_memory, list):
raise BackendContractError("smoke phase-1 memory evidence is malformed")
max_gpu_memory_allocated = max(
[max_gpu_memory_allocated]
+ [
int(row["max_gpu_memory_allocated_bytes"])
for row in phase_1_memory
if row.get("max_gpu_memory_allocated_bytes") is not None
]
)
max_gpu_memory_reserved = max(
[max_gpu_memory_reserved]
+ [
int(row["max_gpu_memory_reserved_bytes"])
for row in phase_1_memory
if row.get("max_gpu_memory_reserved_bytes") is not None
]
)
log_history = [
dict(row)
for row in getattr(trainer.state, "log_history", [])
if isinstance(row, Mapping)
]
atomic_write_json(
completion_marker,
{
"schema_version": 4,
"status": "completed",
"trained": True,
"run_id": runtime["run_id"],
"trainer_kind": trainer_kind,
"run_mode": runtime["run_mode"],
"arm": runtime["arm"],
"dataset_sha256": prepared.dataset_sha256,
"record_count": prepared.record_count,
"assistant_token_count": prepared.assistant_token_count,
"optimizer_steps": actual_optimizer_steps,
"realized_sampled_completion_tokens": realized_completion_tokens
if trainer_kind != "sft"
else None,
"realized_sampled_completion_count": realized_completion_count
if trainer_kind != "sft"
else None,
"sampled_completion_token_safety_ceiling": runtime["max_completion_tokens_per_run"]
if trainer_kind != "sft"
else None,
"comparison_slot_manifest_sha256": runtime.get("comparison_slot_manifest_sha256"),
"rank_0_ledger": str(ledger_path) if ledger_path else None,
"rank_ledger_manifest": ledger_manifest,
"rank_reward_trace_manifest": trace_manifest,
"prompt_truncation_count": 0,
"completion_truncation_count": completion_truncation_count,
"oom_count": 0,
"malformed_completion_count": malformed_completion_count
if trainer_kind != "sft"
else None,
"unique_prompt_groups_consumed": (
len(observed_slot_generations) if trainer_kind != "sft" else None
),
"checkpoint_manifest": checkpoint_manifest,
"forced_process_resume_probe": resume_probe,
"final_adapter": str(final_adapter),
"trainable_parameters": parameter_rows,
"trainable_parameter_manifest_sha256": parameter_sha,
"base_model_revision": runtime["model_revision"],
"base_model_snapshot_sha256": runtime["model_snapshot_sha256"],
"environment_lock_sha256": runtime["environment_lock_sha256"],
"evaluation_manifest_sha256": runtime["evaluation_manifest_sha256"],
"system_prompt_sha256": runtime["system_prompt_sha256"],
"papo_config": runtime.get("papo_config"),
"evi_po_config": runtime.get("evi_po_config"),
"frozen_config_sha256": launch_manifest["frozen_config_sha256"],
"run_manifest_sha256": launch_manifest["run_manifest_sha256"],
"code_commit": launch_manifest["code_commit"],
"metrics": metrics if isinstance(metrics, Mapping) else {},
"log_history": log_history,
"max_gpu_memory_allocated_bytes": (
max_gpu_memory_allocated if torch.cuda.is_available() else None
),
"max_gpu_memory_reserved_bytes": (
max_gpu_memory_reserved if torch.cuda.is_available() else None
),
"papo_gpu_contract_probe": getattr(
trainer,
"papo_gpu_contract_probe",
None,
),
"evi_gpu_contract_probe": getattr(
trainer,
"evi_gpu_contract_probe",
None,
),
},
)
# On completion of a real (non-smoke) run, amend the frozen run-manifest so
# the pushed artifact reports ``completed`` / ``trained=True`` with the
# realized optimizer step count, instead of the perpetual ``planned`` state
# it was frozen with. The original frozen-plan hash is preserved verbatim
# inside the ``completion`` block for provenance, and the smoke path is
# excluded so smoke_gate's manifest-hash invariant stays intact. This
# amendment happens only after the optimizer-step contract above has
# passed and the completion marker is durable, so it never affects a run
# that might still resume. The amendment writes a single shared run-manifest
# file, so it must run on rank 0 only: ``launch_manifest`` is bound inside
# the ``if rank == 0`` block above, and on multi-rank runs rank != 0 would
# otherwise reach this reference unbound (UnboundLocalError) and also race
# rank 0 on the same file.
if rank == 0 and str(runtime["run_mode"]) != "smoke":
manifest_path = Path(launch_manifest["run_manifest_path"])
completed_manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
completed_manifest["status"] = "completed"
completed_manifest["trained"] = True
completed_manifest["completion"] = {
"optimizer_steps": actual_optimizer_steps,
"code_commit": current_code_commit(),
"frozen_code_commit": launch_manifest["code_commit"],
"run_manifest_sha256": launch_manifest["run_manifest_sha256"],
"frozen_config_sha256": launch_manifest["frozen_config_sha256"],
}
atomic_write_json(manifest_path, completed_manifest)
return 0