Datasets:
File size: 15,890 Bytes
0bf2389 | 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | from __future__ import annotations
import json
import unittest
from collections import Counter, defaultdict
from pathlib import Path
from barbet_bgd.generation_v2 import (
ALL_TASK_FAMILIES_V2,
CONFIDENCE_SEMANTICS,
FAMILY_INPUT_TYPES_V2,
GenerationPlanV2,
TASK_FAMILIES_V2,
generate_record_v2,
)
from barbet_bgd.quality_v2 import expected_source_hash_v2, validate_record_quality_v2
from barbet_bgd.validation import validate_record
ROOT = Path(__file__).resolve().parents[1]
class GenerationV2Tests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.config = json.loads(
(ROOT / "configs/selected_sft_1m_v2.json").read_text(encoding="utf-8")
)
cls.plan = GenerationPlanV2(cls.config)
def test_exact_scale_and_balanced_plan(self) -> None:
self.assertEqual(self.config["total_records"], 1_000_000)
self.assertEqual(self.config["dataset_name"], "barbet-bgd-synthetic-sft-1m-tw-v2")
primitives = Counter(self.plan.position(index).primitive for index in range(100))
mixtures = Counter(self.plan.position(index).mixture_category for index in range(100))
serializers = Counter(self.plan.position(index).serializer for index in range(100))
self.assertEqual(primitives, Counter(self.config["primitive_percent"]))
self.assertEqual(mixtures, Counter(self.config["mixture_percent"]))
self.assertEqual(serializers, Counter(self.config["serializer_percent"]))
self.assertEqual(sum(self.plan.position(index).is_long_context for index in range(100)), 5)
def test_generation_is_index_deterministic(self) -> None:
indexes = (0, 5, 62, 99, 100, 1_762, 979_999, 980_000, 989_999, 990_000, 999_999)
for index in indexes:
self.assertEqual(
generate_record_v2(self.config, self.plan, index),
generate_record_v2(self.config, self.plan, index),
)
def test_source_group_split_lock(self) -> None:
for boundary in (980_000, 990_000):
before = generate_record_v2(self.config, self.plan, boundary - 1)
after = generate_record_v2(self.config, self.plan, boundary)
self.assertNotEqual(before["source_group"], after["source_group"])
self.assertNotEqual(before["split"], after["split"])
for start in (0, 5, 979_995, 980_000, 989_995, 990_000):
rows = [generate_record_v2(self.config, self.plan, start + offset) for offset in range(5)]
self.assertEqual(len({row["source_group"] for row in rows}), 1)
self.assertEqual(len({row["split"] for row in rows}), 1)
def test_all_51_families_are_reached_and_pass_independent_quality(self) -> None:
seen: set[str] = set()
for index in range(1_200):
record = generate_record_v2(self.config, self.plan, index)
seen.add(record["task_family"])
self.assertEqual(validate_record(record), [])
self.assertEqual(validate_record_quality_v2(record)["hard_failures"], [])
self.assertEqual(seen, set(ALL_TASK_FAMILIES_V2))
self.assertEqual(sum(len(value) for value in TASK_FAMILIES_V2.values()) + 4, 51)
def test_visible_query_schema_and_honest_confidence(self) -> None:
for index in range(300):
record = generate_record_v2(self.config, self.plan, index)
spec = record["task_spec"]
self.assertIn("query", spec)
self.assertIsInstance(spec["query"], str)
self.assertTrue(spec["query"].strip())
self.assertIsInstance(spec["requested_schema"], dict)
self.assertEqual(record["target"]["confidence_semantics"], CONFIDENCE_SEMANTICS)
self.assertEqual(record["quality"]["confidence_semantics"], CONFIDENCE_SEMANTICS)
self.assertLess(len(spec["allowed_actions"]), 10)
if record["primitive"] == "EXTRACT":
self.assertEqual(
spec["requested_fields"],
[field["name"] for field in record["target"]["fields"]],
)
def test_domain_collision_and_transcription_policy_have_no_label_leakage(self) -> None:
# This index pairs the organisation 「南風教育科技室」 with the
# explicitly declared 文化典藏 domain. The organisation name must not
# create a second classification label.
domain_record = generate_record_v2(self.config, self.plan, 30_033)
self.assertEqual(domain_record["task_family"], "DOMAIN_CLASSIFICATION")
self.assertEqual(domain_record["target"]["decision"], "CULTURE")
self.assertEqual(validate_record_quality_v2(domain_record)["hard_failures"], [])
transcription_records = []
for index in range(2_000):
record = generate_record_v2(self.config, self.plan, index)
if record["task_family"] == "TRANSCRIPTION_MODE":
transcription_records.append(record)
self.assertTrue(transcription_records)
for record in transcription_records:
self.assertEqual(record["task_spec"]["constraints"], {})
self.assertEqual(record["inputs"][0]["units"][0].get("attributes"), {})
self.assertEqual(validate_record_quality_v2(record)["hard_failures"], [])
def test_family_signatures_are_not_generic_aliases(self) -> None:
seen: dict[str, set[str]] = {}
for index in range(1_200):
record = generate_record_v2(self.config, self.plan, index)
seen.setdefault(
record["task_family"], {item["type"] for item in record["inputs"]}
)
for family, required in FAMILY_INPUT_TYPES_V2.items():
self.assertTrue(required.issubset(seen[family]), family)
def test_rank_and_match_have_opaque_unlabelled_balanced_candidates(self) -> None:
winner_positions: dict[str, Counter[int]] = defaultdict(Counter)
for index in range(5_000):
record = generate_record_v2(self.config, self.plan, index)
if record["primitive"] not in {"RANK", "MATCH"}:
continue
candidate_input = next(
item for item in record["inputs"] if "candidate" in item["type"]
)
candidates = candidate_input["units"]
forbidden = {"relevance", "score", "grade", "rank", "is_correct", "gold", "winner"}
for unit in candidates:
self.assertTrue(unit["id"].startswith("cand:x7"))
self.assertFalse(forbidden.intersection(unit))
winner = (
record["target"]["ranking"][0]
if record["primitive"] == "RANK"
else record["target"]["canonical_id"]
)
winner_positions[record["task_family"]][
[unit["id"] for unit in candidates].index(winner)
] += 1
for family, counts in winner_positions.items():
expected_width = 5 if family.endswith("RANKING") else 4
self.assertEqual(set(counts), set(range(expected_width)), family)
def test_alignment_ids_are_opaque_and_permutations_vary(self) -> None:
permutations: dict[str, set[tuple[int, ...]]] = defaultdict(set)
for index in range(2_000):
record = generate_record_v2(self.config, self.plan, index)
if record["primitive"] != "ALIGN":
continue
source, destination = record["inputs"]
destination_ids = [unit["id"] for unit in destination["units"]]
pairs = {
alignment["source"][0]: alignment["target"][0]
for alignment in record["target"]["alignments"]
}
source_ids = [unit["id"] for unit in source["units"]]
self.assertTrue(
all(left.rsplit(":", 1)[-1] != right.rsplit(":", 1)[-1] for left, right in pairs.items())
)
permutations[record["task_family"]].add(
tuple(destination_ids.index(pairs[source_id]) for source_id in source_ids)
)
for family, values in permutations.items():
self.assertGreaterEqual(len(values), 4, family)
def test_locate_abstention_has_no_attribute_match(self) -> None:
negatives = 0
for index in range(2_000):
record = generate_record_v2(self.config, self.plan, index)
if record["primitive"] != "LOCATE" or record["target"]["decision"] != "ABSTAIN":
continue
negatives += 1
required = record["task_spec"]["constraints"]["required_attributes"]
matches = [
unit
for item in record["inputs"]
for unit in item["units"]
if required.items() <= unit.get("attributes", {}).items()
]
self.assertEqual(matches, [])
self.assertEqual(record["target"]["evidence"], [])
self.assertGreater(negatives, 0)
def test_verify_outcomes_are_balanced_inside_every_family(self) -> None:
decisions: dict[str, Counter[str]] = defaultdict(Counter)
for index in range(5_000):
record = generate_record_v2(self.config, self.plan, index)
if record["primitive"] == "VERIFY":
decisions[record["task_family"]][record["target"]["decision"]] += 1
self.assertEqual(len(decisions), 6)
for family, counts in decisions.items():
self.assertEqual(set(counts), {"PASS", "FAIL", "UNCERTAIN"}, family)
self.assertLessEqual(max(counts.values()) - min(counts.values()), 2, family)
def test_classification_labels_do_not_alias_with_paraphrase_cycle(self) -> None:
expected = {
"INTENT_CLASSIFICATION": {"QUERY_STATUS", "UPDATE_SCHEDULE", "SUBMIT_APPLICATION", "RETRIEVE_EVIDENCE", "REQUEST_REVIEW", "CANCEL_REQUEST", "REPORT_INCIDENT", "VERIFY_BOOKING"},
"EMOTION_CLASSIFICATION": {"POSITIVE", "NEGATIVE", "NEUTRAL", "CAUTIOUS"},
"TRANSCRIPTION_MODE": {"VERBATIM", "READABLE", "SELECTIVE_SPEAKER", "ANONYMIZED"},
}
for start in (0, 980_000, 990_000):
seen = defaultdict(set)
for index in range(start, start + 1_000):
if self.plan.position(index).primitive != "CLASSIFY":
continue
record = generate_record_v2(self.config, self.plan, index)
seen[record["task_family"]].add(record["target"]["decision"])
for family, labels in expected.items():
self.assertEqual(seen[family], labels, (start, family))
def test_verifier_and_router_expose_no_candidate_gold_state(self) -> None:
for index in range(300):
if self.plan.position(index).primitive not in {"VERIFY", "ROUTE"}:
continue
record = generate_record_v2(self.config, self.plan, index)
self.assertNotIn('"candidate_state"', json.dumps(record["inputs"]))
if record["task_family"] == "MODALITY_ROUTING" and record["target"]["action"]["tool"].startswith("POINT_"):
args = record["target"]["action"]["arguments"]
self.assertNotIn("modality:u01", args["unit_ids"])
def test_rank_negatives_are_plausible_values_not_error_sentinels(self) -> None:
seen = set()
for index in range(100):
if self.plan.position(index).primitive != "RANK":
continue
record = generate_record_v2(self.config, self.plan, index)
seen.add(record["task_family"])
self.assertNotIn("不符-", json.dumps(record["inputs"], ensure_ascii=False))
candidates = record["inputs"][1]["units"]
for unit in candidates:
for value in unit["attributes"].values():
self.assertIn(str(value), unit["text"])
self.assertEqual(len(seen), 5)
def test_speaker_identity_does_not_require_same_recording_channel(self) -> None:
changed_channel = 0
for index in range(400):
if self.plan.position(index).primitive != "MATCH":
continue
record = generate_record_v2(self.config, self.plan, index)
if record["task_family"] != "SPEAKER_MATCHING":
continue
query = record["inputs"][0]["units"][0]["attributes"]
winner = next(unit for unit in record["inputs"][1]["units"] if unit["id"] == record["target"]["canonical_id"])
self.assertEqual(winner["attributes"]["speaker_signature"], query["speaker_signature"])
changed_channel += winner["attributes"]["channel"] != query["channel"]
self.assertGreater(changed_channel, 0)
def test_eight_train_templates_and_heldout_profiles(self) -> None:
train_templates: dict[str, set[str]] = defaultdict(set)
confidence_values: dict[str, set[float]] = defaultdict(set)
for index in range(1_200):
record = generate_record_v2(self.config, self.plan, index)
train_templates[record["task_family"]].add(record["presentation"]["template_id"])
confidence_values[record["task_family"]].add(record["target"]["confidence_target"])
self.assertTrue(all(len(values) >= 8 for values in train_templates.values()))
self.assertTrue(all(len(values) >= 2 for values in confidence_values.values()))
heldout: dict[str, set[str]] = defaultdict(set)
for start in (980_000, 990_000):
for index in range(start, start + 600):
record = generate_record_v2(self.config, self.plan, index)
heldout[record["task_family"]].add(record["presentation"]["template_id"])
for family, values in heldout.items():
self.assertTrue(values.isdisjoint(train_templates[family]), family)
def test_instructions_do_not_announce_evaluation_split(self) -> None:
for index in (0, 980_000, 980_009, 990_000, 990_009):
record = generate_record_v2(self.config, self.plan, index)
query = record["task_spec"]["query"]
for phrase in ("驗證集", "測試案例", "未見模板", "保留模板"):
self.assertNotIn(phrase, query)
def test_provenance_hash_covers_visible_source_content(self) -> None:
for index in (0, 5, 62, 500, 1_762, 980_000, 990_000):
record = generate_record_v2(self.config, self.plan, index)
self.assertEqual(record["provenance"]["source_hash"], expected_source_hash_v2(record))
mutated = json.loads(json.dumps(record, ensure_ascii=False))
mutated["inputs"][0]["units"][0]["text"] += "異動"
self.assertNotEqual(record["provenance"]["source_hash"], expected_source_hash_v2(mutated))
def test_context_bucket_uses_measured_input_characters(self) -> None:
short = generate_record_v2(self.config, self.plan, 0)
self.assertEqual(short["quality"]["context_length_bucket"], "SHORT_LT_0.5K")
self.assertEqual(short["quality"]["context_length_measure"], "input_unit_text_characters_v2")
self.assertLess(short["quality"]["context_length_value"], 500)
# long_index=86 is the first 64K slot in the deterministic permutation.
cycle, rank = divmod(86, self.plan.long_per_cycle)
index = cycle * 100 + self.plan.long_slots[rank]
long_record = generate_record_v2(self.config, self.plan, index)
self.assertEqual(long_record["quality"]["context_length_bucket"], "64K-128K")
self.assertGreaterEqual(long_record["quality"]["context_length_value"], 64_000)
self.assertLess(long_record["quality"]["context_length_value"], 128_000)
self.assertEqual(validate_record_quality_v2(long_record)["hard_failures"], [])
if __name__ == "__main__":
unittest.main()
|