Datasets:
Download src/explicit_learning/training/sft_schedule.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/training/sft_schedule.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/training/sft_schedule.py
-
curl -L -o sft_schedule.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/training/sft_schedule.py
10.8 kB
| """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.""" | |
| 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())), | |
| ) | |