Datasets:
File size: 10,807 Bytes
e1ced61 | 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 | """Build token-matched one-epoch SFT ablation schedules without duplication."""
from __future__ import annotations
import copy
from collections import Counter, defaultdict
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from ..hashing import canonical_json_hash
_TRANSFORMED_STATES = ("A_SAME", "A_CHANGED", "U_MISSING", "U_INVALID")
class SFTScheduleError(ValueError):
"""Raised when two schedules cannot meet the frozen fairness contract."""
@dataclass(frozen=True)
class MatchedSFTSchedules:
full_only: tuple[dict[str, Any], ...]
full_plus_intervention: tuple[dict[str, Any], ...]
loss_tokens: int
record_count: int
state_counts: dict[str, int]
def _loss_token_count(
row: Mapping[str, Any],
counter: Callable[[Mapping[str, Any]], int],
) -> int:
if not isinstance(row.get("assistant_response"), str) or not row["assistant_response"]:
raise SFTScheduleError("SFT row has no assistant_response")
count = counter(row)
if isinstance(count, bool) or not isinstance(count, int) or count <= 0:
raise SFTScheduleError("loss-token counter returned a non-positive integer")
return count
def _bounded_subset(
rows: Sequence[Mapping[str, Any]],
counts: Sequence[int],
*,
target_tokens: int,
target_rows: int,
) -> tuple[dict[str, Any], ...]:
"""Select exactly ``target_rows`` distinct rows totaling ``target_tokens``."""
if target_tokens < 0 or target_rows < 0:
raise SFTScheduleError("pair interventions exceed the full-only token budget")
if target_rows > len(rows):
raise SFTScheduleError("pair schedule cannot match the full-only record count")
if target_rows == 0:
if target_tokens:
raise SFTScheduleError("zero filler rows cannot supply non-zero loss tokens")
return ()
by_weight: dict[int, list[Mapping[str, Any]]] = defaultdict(list)
for row, count in zip(rows, counts, strict=True):
by_weight[count].append(row)
for bucket in by_weight.values():
bucket.sort(
key=lambda row: (
canonical_json_hash(
{
"group_id": row.get("group_id"),
"view_id": row.get("view_id"),
}
),
str(row.get("group_id", "")),
)
)
# ``reachable[n]`` is a bitset of token totals attainable with exactly n
# distinct rows. Binary-split weight buckets keep the transition count
# logarithmic in the number of equivalent rows. Prior frontiers are kept
# so the selected rows can be reconstructed deterministically.
reachable = [0] * (target_rows + 1)
reachable[0] = 1
mask = (1 << (target_tokens + 1)) - 1
chunks: list[tuple[tuple[int, ...], int, int]] = []
for weight in sorted(by_weight):
remaining = len(by_weight[weight])
power = 1
while remaining:
size = min(power, remaining)
prior = tuple(reachable)
shift = weight * size
for row_count in range(target_rows, size - 1, -1):
reachable[row_count] |= (prior[row_count - size] << shift) & mask
chunks.append((prior, weight, size))
remaining -= size
power <<= 1
if ((reachable[target_rows] >> target_tokens) & 1) == 0:
raise SFTScheduleError(
"no distinct full-only subset exactly matches "
f"{target_rows} rows and {target_tokens} loss tokens"
)
selected_counts: Counter[int] = Counter()
cursor_tokens = target_tokens
cursor_rows = target_rows
for prior, weight, size in reversed(chunks):
if ((prior[cursor_rows] >> cursor_tokens) & 1) == 1:
continue
if (
cursor_rows < size
or cursor_tokens < weight * size
or ((prior[cursor_rows - size] >> (cursor_tokens - weight * size)) & 1) == 0
):
raise AssertionError("bounded subset reconstruction lost its frontier")
selected_counts[weight] += size
cursor_rows -= size
cursor_tokens -= weight * size
if cursor_rows != 0 or cursor_tokens != 0:
raise AssertionError("bounded subset reconstruction did not reach zero")
selected: list[dict[str, Any]] = []
for weight in sorted(selected_counts):
selected.extend(
copy.deepcopy(dict(row)) for row in by_weight[weight][: selected_counts[weight]]
)
return tuple(selected)
def match_sft_schedules(
full_rows: Sequence[Mapping[str, Any]],
pair_rows: Sequence[Mapping[str, Any]],
*,
loss_token_counter: Callable[[Mapping[str, Any]], int],
intervention_per_state: int,
) -> MatchedSFTSchedules:
"""Match actual loss-bearing tokens and row counts across SFT arms.
The full-only schedule is exactly one copy of every admitted FULL record.
The paired schedule contains a fixed, hash-ordered quota from each
transformed state plus a distinct subset of FULL records that fills the
remaining record and loss-token budgets exactly. No row is repeated.
"""
if intervention_per_state <= 0:
raise SFTScheduleError("intervention_per_state must be positive")
full = [copy.deepcopy(dict(row)) for row in full_rows]
pair = [copy.deepcopy(dict(row)) for row in pair_rows]
if not full or not pair:
raise SFTScheduleError("SFT source schedules must be non-empty")
if any(row.get("record_kind") != "full_only" for row in full):
raise SFTScheduleError("full-only input contains another record kind")
if any(row.get("record_kind") != "full_plus_certified_intervention" for row in pair):
raise SFTScheduleError("pair input contains another record kind")
if any(row.get("split") != "train" for row in (*full, *pair)):
raise SFTScheduleError("SFT schedules may contain split=train rows only")
full_groups = [str(row.get("group_id", "")) for row in full]
if any(not group_id for group_id in full_groups) or len(full_groups) != len(set(full_groups)):
raise SFTScheduleError("full-only input must contain one row per unique group")
pair_identities = [(str(row.get("group_id", "")), str(row.get("view_id", ""))) for row in pair]
if any(not all(identity) for identity in pair_identities) or len(pair_identities) != len(
set(pair_identities)
):
raise SFTScheduleError("pair input has an empty or duplicated group/view identity")
full_group_set = set(full_groups)
by_state: dict[str, list[dict[str, Any]]] = defaultdict(list)
pair_full_by_group: dict[str, dict[str, Any]] = {}
for row in pair:
group_id = str(row["group_id"])
if group_id not in full_group_set:
raise SFTScheduleError("pair row does not belong to the full-only group set")
state = str(row.get("state", ""))
if state == "FULL":
if group_id in pair_full_by_group:
raise SFTScheduleError("pair input has multiple FULL rows for one group")
pair_full_by_group[group_id] = row
elif state in _TRANSFORMED_STATES:
by_state[state].append(row)
else:
raise SFTScheduleError(f"unexpected pair state: {state!r}")
if set(pair_full_by_group) != full_group_set:
raise SFTScheduleError("pair FULL rows do not match the full-only base groups")
selected_interventions: list[dict[str, Any]] = []
selected_groups: set[str] = set()
for state in _TRANSFORMED_STATES:
candidates = sorted(
by_state[state],
key=lambda row: (
canonical_json_hash(
{
"state": state,
"group_id": row.get("group_id"),
"view_id": row.get("view_id"),
}
),
str(row.get("group_id", "")),
),
)
if len(candidates) < intervention_per_state:
raise SFTScheduleError(
f"state {state} has {len(candidates)} rows, needs {intervention_per_state}"
)
selected_for_state: list[dict[str, Any]] = []
for candidate in candidates:
group_id = str(candidate["group_id"])
if group_id in selected_groups:
continue
selected_groups.add(group_id)
selected_for_state.append(candidate)
if len(selected_for_state) == intervention_per_state:
break
if len(selected_for_state) != intervention_per_state:
raise SFTScheduleError(
f"state {state} cannot supply {intervention_per_state} unique groups"
)
selected_interventions.extend(selected_for_state)
full_counts = [_loss_token_count(row, loss_token_counter) for row in full]
full_budget = sum(full_counts)
paired_full = [pair_full_by_group[group_id] for group_id in sorted(selected_groups)]
paired_prefix = [*selected_interventions, *paired_full]
paired_prefix_tokens = sum(_loss_token_count(row, loss_token_counter) for row in paired_prefix)
filler_candidates = [
row for group_id, row in pair_full_by_group.items() if group_id not in selected_groups
]
pair_full_counts = [_loss_token_count(row, loss_token_counter) for row in filler_candidates]
filler = _bounded_subset(
filler_candidates,
pair_full_counts,
target_tokens=full_budget - paired_prefix_tokens,
target_rows=len(full) - len(paired_prefix),
)
paired = (*paired_prefix, *filler)
def order_key(row: Mapping[str, Any]) -> tuple[str, str, str]:
return (
canonical_json_hash(
{
"schedule_seed": 20260728,
"group_id": row.get("group_id"),
"view_id": row.get("view_id"),
}
),
str(row.get("group_id", "")),
str(row.get("view_id", "")),
)
full = sorted(full, key=order_key)
paired = tuple(sorted(paired, key=order_key))
paired_tokens = sum(_loss_token_count(row, loss_token_counter) for row in paired)
if len(paired) != len(full):
raise AssertionError("matched SFT schedules have different record counts")
if paired_tokens != full_budget:
raise AssertionError("matched SFT schedules have different loss-token totals")
state_counts = Counter(str(row["state"]) for row in paired)
return MatchedSFTSchedules(
full_only=tuple(full),
full_plus_intervention=paired,
loss_tokens=full_budget,
record_count=len(full),
state_counts=dict(sorted(state_counts.items())),
)
|