File size: 9,362 Bytes
0194e59 | 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 | """์น์ธ P ํฉ์ฑ ๋ฐฐ์น์ ์ค์ ์ฐ์์ ํ๋ feature์ ๋ถํฌ ์ฐจ์ด๋ฅผ ์ ๋ ๊ฐ์ฌํ๋ค."""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
from typing import Sequence
import numpy as np
import torch
from torch import Tensor
PROJECT_ROOT = Path(__file__).parents[1]
SOURCE_ROOT = PROJECT_ROOT / "src"
for path in (PROJECT_ROOT, SOURCE_ROOT):
if str(path) not in sys.path:
sys.path.insert(0, str(path))
from math_grid_drawer.research.behavior_role_head06 import (
BEHAVIOR_CONTEXT_FEATURES06,
BEHAVIOR_ROLE_LABELS06,
)
from scripts.audit_math_ink_06_case_context import _load_model06
from scripts.crohme_lattice_common import writer_fit_validation
from scripts.train_math_ink_06_behavior_role import (
_materialize_product_proxy06,
_materialize_split06,
_product_proxy_records06,
)
AUDIT_FEATURES06 = (
"teacher_family_mass",
"teacher_top1",
"teacher_entropy",
"bbox_width",
"bbox_height",
"local_height_ratio",
"local_width_ratio",
"left_gap",
"right_gap",
)
def distribution_shift06(reference: Tensor, candidate: Tensor) -> dict[str, float | int]:
"""ํ์ ๋ณ์: ๊ธฐ์คยทํ๋ณด 1์ฐจ์ ๊ฐ. ์๋ ์๋ฆฌ: ํ๊ท ยทํ์คํธ์ฐจยท๋ถ์์ ๊ฑฐ๋ฆฌ์ ํ์คํ ํ๊ท ์ฐจ๋ฅผ ๊ณ์ฐํ๋ค."""
reference = reference.detach().float().flatten()
candidate = candidate.detach().float().flatten()
if not len(reference) or not len(candidate):
raise ValueError("๋ถํฌ ๋น๊ต์๋ ์์ชฝ ํ๋ณธ์ด ๋ชจ๋ ํ์ํฉ๋๋ค.")
reference_mean = float(reference.mean())
candidate_mean = float(candidate.mean())
reference_std = float(reference.std(unbiased=False))
candidate_std = float(candidate.std(unbiased=False))
pooled_std = max(
((reference_std ** 2 + candidate_std ** 2) * 0.5) ** 0.5,
1e-6,
)
quantiles = torch.linspace(0.0, 1.0, 101)
quantile_distance = float(
(torch.quantile(reference, quantiles) - torch.quantile(candidate, quantiles))
.abs()
.mean()
)
return {
"reference_samples": len(reference),
"candidate_samples": len(candidate),
"reference_mean": reference_mean,
"candidate_mean": candidate_mean,
"reference_std": reference_std,
"candidate_std": candidate_std,
"standardized_mean_difference": (candidate_mean - reference_mean) / pooled_std,
"mean_absolute_quantile_distance": quantile_distance,
}
def compare_contexts06(
reference_context: Tensor,
reference_target: Tensor,
candidate_context: Tensor,
candidate_target: Tensor,
*,
feature_names: Sequence[str] = AUDIT_FEATURES06,
) -> dict[str, object]:
"""ํ์ ๋ณ์: ์ค์ /ํฉ์ฑ context์ ์ญํ target. ์๋ ์๋ฆฌ: ๊ณตํต ์ญํ ๋ณ feature shift๋ฅผ ๋์ ์์ด ๋น๊ตํ๋ค."""
feature_index = {
name: index for index, name in enumerate(BEHAVIOR_CONTEXT_FEATURES06)
}
unknown = sorted(set(feature_names) - set(feature_index))
if unknown:
raise ValueError(f"์ ์ ์๋ ํ๋ feature์
๋๋ค: {unknown}")
roles: dict[str, object] = {}
for role_index, role in enumerate(BEHAVIOR_ROLE_LABELS06):
reference_mask = reference_target == role_index
candidate_mask = candidate_target == role_index
if not reference_mask.any() or not candidate_mask.any():
continue
features = {
name: distribution_shift06(
reference_context[reference_mask, feature_index[name]],
candidate_context[candidate_mask, feature_index[name]],
)
for name in feature_names
}
ranked = sorted(
(
{
"feature": name,
"absolute_standardized_mean_difference": abs(
float(values["standardized_mean_difference"])
),
}
for name, values in features.items()
),
key=lambda row: row["absolute_standardized_mean_difference"],
reverse=True,
)
roles[role] = {
"reference_samples": int(reference_mask.sum()),
"candidate_samples": int(candidate_mask.sum()),
"features": features,
"largest_shifts": ranked[:5],
}
return roles
def _parse_args() -> argparse.Namespace:
"""ํ์ ๋ณ์: ์ ํ teacherยทCROHME trainยทP proxy ์ค์ . ์๋ ์๋ฆฌ: ์ฌํ ๊ฐ๋ฅํ ๋ถํฌ ๊ฐ์ฌ CLI๋ฅผ ๋ง๋ ๋ค."""
parser = argparse.ArgumentParser(description="Audit P synthetic behavior proxy shift")
parser.add_argument("--adapter", type=Path, required=True)
parser.add_argument(
"--train-root", type=Path,
default=PROJECT_ROOT / "research/data/R_noncommercial/ICFHR_package/CROHME2012_data/trainData",
)
parser.add_argument("--profile", default="median_height_32")
parser.add_argument("--seed", type=int, default=17)
parser.add_argument("--teacher-batch-size", type=int, default=256)
parser.add_argument("--product-proxy-per-label", type=int, default=100)
parser.add_argument("--product-proxy-target-bases", default="cosuvwxz")
parser.add_argument("--product-proxy-lowercase-ratio", type=float, default=1.0)
parser.add_argument("--device", choices=("cuda", "cpu"), default="cuda")
parser.add_argument("--output", type=Path, required=True)
return parser.parse_args()
def main() -> None:
"""ํ์ ๋ณ์: CLI ์ธ์. ์๋ ์๋ฆฌ: ์ค์ validation๊ณผ P ํฉ์ฑ proxy๋ฅผ ์ญํ ๋ณ๋ก ๋น๊ตํด ์๋ชป๋ ๋ฐฐ์น ๊ฐ์ ์ ์ฐพ๋๋ค."""
args = _parse_args()
device = torch.device(args.device)
if device.type == "cuda" and not torch.cuda.is_available():
raise RuntimeError("CUDA ๊ฐ์ฌ๋ฅผ ์์ฒญํ์ง๋ง ์ฌ์ฉํ ์ ์์ต๋๋ค.")
adapter_payload = torch.load(args.adapter, map_location="cpu", weights_only=False)
base_checkpoint = Path(str(adapter_payload["base_checkpoint"]))
if not base_checkpoint.is_absolute():
base_checkpoint = PROJECT_ROOT / base_checkpoint
engine, adapter = _load_model06(base_checkpoint, args.adapter, device)
_fit_samples, validation_samples = writer_fit_validation(args.train_root, args.profile)
validation, validation_counts = _materialize_split06(
validation_samples,
engine,
adapter,
device=device,
teacher_batch_size=args.teacher_batch_size,
)
selection_args = argparse.Namespace(**vars(args))
# ๊ธฐ์กด fail-closed P source loader๊ฐ ์๊ตฌํ๋ ๊ฒฝ๋ก์ split ๊ณ์ฝ์ ๊ทธ๋๋ก ์ฌ์ฉํ๋ค.
selection_args.data = (
PROJECT_ROOT / "research/data/open_pretrain/hwrt_expanded_v2/hwrt_expanded.jsonl.gz"
)
selection_args.commercial_paired = (
PROJECT_ROOT / "research/data/external_trajectory_v1/commercial_ccby4.jsonl.gz"
)
selection_args.dataset_registry = PROJECT_ROOT / "research/dataset_registry.json"
selection_args.source_registry = PROJECT_ROOT / "research/math_ink_06_source_registry.json"
selection_args.hwrt_approval = (
PROJECT_ROOT / "research/approvals/HWRT-ODBL-USE-APPROVAL-v1.json"
)
product_records = _product_proxy_records06(selection_args, engine.labels)
proxy, proxy_info = _materialize_product_proxy06(
product_records,
engine,
adapter,
seed=args.seed,
device=device,
teacher_batch_size=args.teacher_batch_size,
target_bases=frozenset(args.product_proxy_target_bases),
lowercase_ratio=args.product_proxy_lowercase_ratio,
)
role_shift = compare_contexts06(
validation.tensors[1],
validation.tensors[2],
proxy.tensors[1],
proxy.tensors[2],
)
layout_features = {"bbox_height", "local_height_ratio", "bbox_width", "local_width_ratio"}
maximum_layout_shift = max(
(
float(row["absolute_standardized_mean_difference"])
for role in role_shift.values()
for row in role["largest_shifts"]
if row["feature"] in layout_features
),
default=0.0,
)
report = {
"experiment": "R-MATH-INK-06-P-PROXY-SHIFT-001",
"generated_at": datetime.now(timezone.utc).isoformat(),
"seed": args.seed,
"reference": "CROHME writer-validation truth groups",
"candidate": "approved P isolated trajectories with synthetic row layout",
"validation_role_counts": validation_counts,
"proxy": proxy_info,
"role_shift": role_shift,
"maximum_layout_absolute_smd": maximum_layout_shift,
"decision": {
"layout_distribution_compatible": maximum_layout_shift <= 0.50,
"threshold_absolute_smd": 0.50,
"expand_to_three_seeds": False,
"product_validation": False,
},
"track": "diagnostic_R_reference_plus_P_proxy",
"product_validation": False,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(json.dumps(report["decision"], ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
|