Datasets:
Download code/tests/test_generation_v2.py from voidful/barbet-sft: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/tests/test_generation_v2.py
- Command line
-
hf download hf://datasets/voidful/barbet-sft/code/tests/test_generation_v2.py
-
curl -L -o test_generation_v2.py https://huggingface.co/datasets/voidful/barbet-sft/resolve/main/code/tests/test_generation_v2.py
15.9 kB
| 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): | |
| 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() | |