Add files using upload-large-folder tool
Browse filesFiles changed (13)
- tests/test_chart_teacher_probe_parser.py+10
- tests/test_chartqa_core.py+45
- tests/test_chartqa_teacher_gate.pyAdded+470
- tests/test_checkpoint_eval_policy.py+133
- tests/test_deepspeed_utils.py+27-1
- tests/test_exopd_target.pyAdded+132
- tests/test_opd_only_stage.py+57-13
- tests/test_opd_rollout_filter.pyAdded+60
- tests/test_opd_student_logits_only.pyAdded+79
- tests/test_opd_template_health_check.py+24
- tests/test_opdvr_reward_gate.pyAdded+136
- tests/test_opsd_loss_mask.pyAdded+231
- tests/test_opsd_loss_teacher.py+274
50 unmodified lines5152535450 unmodified linesassert score == 1.0assert parsed.answer == "70"assert parsed.parse_failed is False50 unmodified lines515253545556575859606162636450 unmodified linesassert score == 1.0assert parsed.answer == "70"def test_teacher_probe_chart_eval_accepts_official_exact_long_bare_answer():score, parsed = eval_teacher_probe_chart("Unable to arrange child care","Unable to arrange child care",)assert score == 1.0assert parsed.answer == "Unable to arrange child care"assert parsed.parse_failed is Falseassert parsed.parse_failed is False
231 unmodified lines232233234235236237238239240241222 unmodified lines464465466467468469231 unmodified linesassert result["checkpoint_score"] == 1.0assert result["sample_count"] == 2assert result["output_type_counts"]["other"] == 2assert model.training is Trueassert model.train_calls == [True]assert processor.tokenizer.padding_side == "right"def test_default_generation_path_uses_the_passed_live_model(monkeypatch: pytest.MonkeyPatch,222 unmodified lines)def test_final_summary_keeps_legacy_completed_evaluation_marker() -> None:lines: list[str] = []231 unmodified lines232233234235236237238239240241242243244245246247248249250251222 unmodified lines474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514231 unmodified linesassert result["checkpoint_score"] == 1.0assert result["sample_count"] == 2assert result["output_type_counts"]["other"] == 2assert result["answer_marker_counts"]["exactly_once"] == 2assert sum(result["answer_marker_counts"].values()) == result["sample_count"]assert model.training is Trueassert model.train_calls == [True]assert processor.tokenizer.padding_side == "right"def test_answer_marker_count_is_independent_of_legacy_output_type() -> None:classify = chartqa_core.classify_answer_marker_countassert classify("") == "missing"assert classify("plain answer") == "missing"assert classify("Answer: 1") == "exactly_once"assert classify("answer: 1\nANSWER: 2") == "multiple"def test_default_generation_path_uses_the_passed_live_model(monkeypatch: pytest.MonkeyPatch,222 unmodified lines)def test_evaluation_cuda_cache_release_is_configurable(monkeypatch: pytest.MonkeyPatch,) -> None:calls: list[tuple[str, object]] = []class _FakeCuda:@staticmethoddef is_available() -> bool:return True@staticmethoddef synchronize(device=None) -> None:calls.append(("synchronize", device))@staticmethoddef empty_cache() -> None:calls.append(("empty_cache", None))fake_torch = type("FakeTorch", (), {"cuda": _FakeCuda})monkeypatch.setattr(chartqa_core, "_try_import_torch", lambda: fake_torch)chartqa_core._release_evaluation_cuda_cache(ChartQAEvaluationConfig(release_cuda_cache=True),device="cuda:1",)assert calls == [("synchronize", "cuda:1"), ("empty_cache", None)]calls.clear()chartqa_core._release_evaluation_cuda_cache(ChartQAEvaluationConfig(release_cuda_cache=False),device="cuda:1",)assert calls == []def test_final_summary_keeps_legacy_completed_evaluation_marker() -> None:lines: list[str] = []
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470from __future__ import annotations
import jsonfrom pathlib import Path
import pytest
from data_utils.chart.teacher_gate import ( DEFAULT_CONFIDENCE_KEY, SCHEMA_VERSION, apply_gate_decision, calibrate_confidence_threshold, chartqa_dataset_fingerprint, chartqa_sample_fingerprint, filter_chartqa_rows_with_teacher_gate, validate_teacher_gate_cache,)from scripts.reapply_chartqa_teacher_gate_calibration import main as reapply_calibration
def _row(index: int) -> dict: return { "question": f"Question {index}?", "answer": str(index), "image": f"/old/root/train_{index:06d}.png", "visual_fact_deplot": json.dumps( {"source": "google/deplot", "parsed_table": f"label | value\na | {index}"} ), }
def _record(row: dict, index: int, confidence: float, correct: bool) -> dict: return { "schema_version": SCHEMA_VERSION, "source_index": index, "sample_fingerprint": chartqa_sample_fingerprint(row), "teacher_output": f"Answer: {index}", "parsed_answer": str(index), "teacher_correct": correct, "parse_failed": False, "placeholder": False, "clipped": False, "answer_span_found": True, "confidence": {DEFAULT_CONFIDENCE_KEY: confidence}, }
def test_fingerprint_is_path_independent_and_accepts_prepared_answer() -> None: raw = _row(7) prepared = { **raw, "question_wo_prompt": raw["question"], "question": None, "reference_answer": "Answer: 7", "answer": "Answer: 7", "image": "/new/workspace/train_000007.png", } assert chartqa_sample_fingerprint(raw) == chartqa_sample_fingerprint(prepared)
def test_calibration_uses_maximum_coverage_threshold_with_ties() -> None: rows = [_row(index) for index in range(5)] records = [ _record(rows[0], 0, 0.95, True), _record(rows[1], 1, 0.80, True), _record(rows[2], 2, 0.80, False), _record(rows[3], 3, 0.50, True), _record(rows[4], 4, 0.20, False), ] calibration = calibrate_confidence_threshold( records, target_precision=0.70, min_coverage=0.20 ) assert calibration.threshold == pytest.approx(0.5) assert calibration.retained_count == 4 assert calibration.achieved_precision == pytest.approx(0.75)
def test_calibration_fails_when_precision_target_is_unreachable() -> None: rows = [_row(index) for index in range(4)] records = [ _record(row, index, 1.0 - index * 0.1, correct=False) for index, row in enumerate(rows) ] with pytest.raises(ValueError, match="could not meet"): calibrate_confidence_threshold( records, target_precision=0.9, min_coverage=0.5 )
@pytest.mark.parametrize( "mutation", [ {"teacher_correct": False}, {"parse_failed": True}, {"placeholder": True}, {"clipped": True}, {"answer_span_found": False}, ],)def test_hard_gate_rejects_each_invalid_condition(mutation: dict) -> None: row = _row(0) record = _record(row, 0, 0.9, True) | mutation decided = apply_gate_decision( record, confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.5 ) assert decided["eligible"] is False
def test_filter_validates_complete_cache_and_excludes_failed_rows(tmp_path) -> None: rows = [_row(index) for index in range(3)] records = [ apply_gate_decision( _record(row, index, confidence=0.9 - index * 0.2, correct=index != 1), confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.6, ) for index, row in enumerate(rows) ] cache = tmp_path / "train.jsonl" cache.write_text( "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8" ) manifest = { "schema_version": SCHEMA_VERSION, "complete": True, "record_count": len(records), "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.6, }, "summary": { "teacher_accuracy": 2 / 3, "eligible_rate": 1 / 3, "placeholder_rate": 0.0, }, } manifest_path = tmp_path / "manifest.json" manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
kept, stats = filter_chartqa_rows_with_teacher_gate( rows, { "enabled": True, "cache_path": str(cache), "manifest_path": str(manifest_path), }, ) assert [row["answer"] for row in kept] == ["0"] assert stats["input_rows"] == 3 assert stats["kept_rows"] == 1 assert stats["excluded_rows"] == 2 assert kept[0]["_teacher_gate_teacher_output"] == "Answer: 0" assert kept[0]["_teacher_gate_cache_accuracy"] == pytest.approx(2 / 3) assert kept[0]["_teacher_gate_cache_eligible_rate"] == pytest.approx(1 / 3)
def test_hard_correct_keeps_low_confidence_correct_and_rejects_malformed(tmp_path) -> None: rows = [_row(index) for index in range(4)] raw_records = [ _record(rows[0], 0, confidence=0.95, correct=True), _record(rows[1], 1, confidence=0.20, correct=True), _record(rows[2], 2, confidence=0.99, correct=False), _record(rows[3], 3, confidence=0.99, correct=True) | {"placeholder": True}, ] records = [ apply_gate_decision( record, confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.8, ) for record in raw_records ] cache = tmp_path / "train.jsonl" cache.write_text( "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8", ) manifest = tmp_path / "train.jsonl.manifest.json" manifest.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "record_count": len(records), "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.8, }, "summary": {"teacher_accuracy": 0.75, "eligible_rate": 0.25}, } ), encoding="utf-8", )
legacy, legacy_stats = filter_chartqa_rows_with_teacher_gate( rows, {"enabled": True, "cache_path": str(cache), "manifest_path": str(manifest)}, ) hard_correct, hard_stats = filter_chartqa_rows_with_teacher_gate( rows, { "enabled": True, "selection_mode": "hard_correct", "expected_selected_rows": 2, "cache_path": str(cache), "manifest_path": str(manifest), }, )
assert [row["answer"] for row in legacy] == ["0"] assert legacy_stats["selection_mode"] == "eligible" assert [row["answer"] for row in hard_correct] == ["0", "1"] assert hard_stats["hard_pass_rows"] == 2 assert hard_stats["legacy_eligible_rows"] == 1 assert hard_stats["low_confidence_correct_added_rows"] == 1 assert hard_correct[1]["_teacher_gate_confidence_pass"] is False
def test_teacher_gate_expected_selected_rows_fails_closed(tmp_path) -> None: rows = [_row(0)] record = apply_gate_decision( _record(rows[0], 0, 0.2, True), confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.8, ) cache = tmp_path / "train.jsonl" cache.write_text(json.dumps(record) + "\n", encoding="utf-8") manifest = tmp_path / "train.jsonl.manifest.json" manifest.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "record_count": 1, "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.8, }, } ), encoding="utf-8", ) with pytest.raises(ValueError, match="selected-row count mismatch"): filter_chartqa_rows_with_teacher_gate( rows, { "enabled": True, "selection_mode": "hard_correct", "expected_selected_rows": 2, "cache_path": str(cache), "manifest_path": str(manifest), }, )
@pytest.mark.parametrize( ("selection_mode", "expected"), [("eligible", 1590), ("hard_correct", 3220), ("all", 4576)],)def test_checked_in_chartqa_gate_has_expected_selection_counts( selection_mode: str, expected: int,) -> None: root = Path(__file__).resolve().parents[1] data_path = root / "data/chartqa/train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json" cache_path = root / "data/chartqa/teacher_gate/llava_onevision_7b_deplot_greedy/train.jsonl" manifest_path = Path(f"{cache_path}.manifest.json") if not data_path.is_file() or not cache_path.is_file() or not manifest_path.is_file(): pytest.skip("checked-in/local ChartQA gate artifacts are unavailable") rows = json.loads(data_path.read_text(encoding="utf-8")) rows = [row for row in rows if row.get("human_or_machine", 0) == 0] selected, stats = filter_chartqa_rows_with_teacher_gate( rows, { "enabled": True, "selection_mode": selection_mode, "expected_selected_rows": expected, "cache_path": str(cache_path), "manifest_path": str(manifest_path), "require_validation_calibration": True, }, ) assert len(rows) == 4576 assert len(selected) == expected assert stats["hard_pass_rows"] == 3220 assert stats["legacy_eligible_rows"] == 1590
def test_filter_fails_closed_on_dataset_change(tmp_path) -> None: rows = [_row(0)] record = apply_gate_decision( _record(rows[0], 0, 0.9, True), confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.5, ) cache = tmp_path / "train.jsonl" cache.write_text(json.dumps(record) + "\n", encoding="utf-8") manifest_path = tmp_path / "manifest.json" manifest_path.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "record_count": 1, "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.5, }, } ), encoding="utf-8", ) changed = [{**rows[0], "answer": "different"}] with pytest.raises(ValueError, match="dataset fingerprint"): filter_chartqa_rows_with_teacher_gate( changed, { "enabled": True, "cache_path": str(cache), "manifest_path": str(manifest_path), }, )
def test_validation_rejects_cache_decisions_from_a_different_threshold(tmp_path) -> None: rows = [_row(0)] record = apply_gate_decision( _record(rows[0], 0, 0.7, True), confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.5, ) cache = tmp_path / "train.jsonl" cache.write_text(json.dumps(record) + "\n", encoding="utf-8") manifest = tmp_path / "train.jsonl.manifest.json" manifest.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "record_count": 1, "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.8, }, } ), encoding="utf-8", )
with pytest.raises(ValueError, match="stale confidence_gate_pass"): validate_teacher_gate_cache(rows, cache_path=cache, manifest_path=manifest)
def test_reapply_uses_validation_manifest_without_teacher_regeneration(tmp_path) -> None: rows = [_row(0), _row(1)] records = [ apply_gate_decision( _record(row, index, confidence=confidence, correct=True), confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.0, ) for index, (row, confidence) in enumerate(zip(rows, (0.9, 0.4))) ] cache = tmp_path / "train.jsonl" cache.write_text( "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8" ) train_manifest = tmp_path / "train.jsonl.manifest.json" train_manifest.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "split": "train", "record_count": 2, "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.0, }, } ), encoding="utf-8", ) calibration_manifest = tmp_path / "validation.jsonl.manifest.json" calibration_manifest.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "split": "validation", "dataset_fingerprint": "validation-fingerprint", "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.8, "target_precision": 0.9, "achieved_precision": 0.9, }, } ), encoding="utf-8", )
assert reapply_calibration( [ "--train-cache", str(cache), "--calibration-manifest", str(calibration_manifest), ] ) == 0 updated, manifest = validate_teacher_gate_cache( rows, cache_path=cache, manifest_path=train_manifest, ) assert [record["eligible"] for record in updated] == [True, False] assert manifest["calibration"]["source_split"] == "validation" assert manifest["decision_source"].startswith("validation_calibrated") validate_teacher_gate_cache( rows, cache_path=cache, manifest_path=train_manifest, require_validation_calibration=True, )
def test_validation_calibration_requirement_rejects_train_self_calibration( tmp_path,) -> None: rows = [_row(0)] record = apply_gate_decision( _record(rows[0], 0, 0.9, True), confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.5, ) cache = tmp_path / "train.jsonl" cache.write_text(json.dumps(record) + "\n", encoding="utf-8") manifest = tmp_path / "train.jsonl.manifest.json" manifest.write_text( json.dumps( { "schema_version": SCHEMA_VERSION, "complete": True, "split": "train", "record_count": 1, "dataset_fingerprint": chartqa_dataset_fingerprint(rows), "calibration": { "confidence_key": DEFAULT_CONFIDENCE_KEY, "threshold": 0.5, "target_precision": 0.9, "achieved_precision": 1.0, }, } ), encoding="utf-8", )
with pytest.raises(ValueError, match="validation-calibrated"): validate_teacher_gate_cache( rows, cache_path=cache, manifest_path=manifest, require_validation_calibration=True, )54 unmodified lines5556575859608 unmodified lines69707172737427 unmodified lines10210310410510610733 unmodified lines14114214314414514614714814954 unmodified linesassert policy.state.best_step == 1def test_policy_state_round_trip_preserves_best_and_streak() -> None:policy = CheckpointEvaluationPolicy(patience=3)policy.observe(0.5, step=10)8 unmodified linesassert result.evaluation_count == 3def test_callback_state_round_trip_restores_policy_for_resume() -> None:callback = CheckpointEvaluationTriggerCallback(patience=3, tie_policy="reset")callback.policy.observe(0.5, step=10)27 unmodified lines"lower_score_streak": 1,"evaluation_count": 2,"stop_requested": False,}resumed = CheckpointEvaluationTriggerCallback(patience=3)33 unmodified lines"lower_score_streak": 0,"evaluation_count": 1,"stop_requested": False,}def test_terminal_sidecar_state_stops_a_resumed_training_run(tmp_path: Path) -> None:(tmp_path / "checkpoint-1").mkdir()callback = CheckpointEvaluationTriggerCallback(output_dir=tmp_path, patience=1)54 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211228 unmodified lines13113213313413513613713813914014114214314414514614714827 unmodified lines17617717817918018118233 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128254 unmodified linesassert policy.state.best_step == 1def test_dynamic_step_zero_baseline_never_saves_or_blocks_and_counts_non_improvements() -> None:policy = CheckpointEvaluationPolicy(patience=3, tie_policy="count")baseline = policy.establish_external_baseline(0.21, step=0)assert (baseline.best_score, baseline.best_step, baseline.evaluation_count) == (0.21, 0, 0)assert baseline.best_is_external is Truelower = policy.observe(0.20, step=10)tie = policy.observe(0.21, step=25)terminal_tie = policy.observe(0.21, step=50)assert (lower.should_save, lower.should_stop, lower.lower_score_streak) == (False, False, 1)assert (tie.should_save, tie.should_stop, tie.reason, tie.lower_score_streak) == (False,False,"tie_counted",2,)assert (terminal_tie.should_save, terminal_tie.should_stop, terminal_tie.reason) == (False,True,"patience_exhausted",)def test_dynamic_step_zero_baseline_saves_only_a_strict_improvement() -> None:policy = CheckpointEvaluationPolicy(patience=3, tie_policy="count")policy.establish_external_baseline(0.21, step=0)improved = policy.observe(0.22, step=10)assert (improved.should_save, improved.should_stop, improved.reason) == (True, False, "improved")assert (improved.best_score, improved.best_step, improved.best_is_external) == (0.22, 10, False)def test_patience_warmup_monitors_drops_but_still_saves_improvements() -> None:policy = CheckpointEvaluationPolicy(patience=3,tie_policy="count",patience_start_step=200,)policy.establish_external_baseline(0.30, step=0)lower = policy.observe(0.20, step=10)tie = policy.observe(0.30, step=100)improved = policy.observe(0.31, step=150)first_counted = policy.observe(0.30, step=200)second_counted = policy.observe(0.31, step=300)stopped = policy.observe(0.29, step=400)assert (lower.reason, lower.lower_score_streak, lower.should_stop) == ("patience_warmup_lower",0,False,)assert (tie.reason, tie.lower_score_streak) == ("patience_warmup_tie", 0)assert (improved.should_save, improved.best_step) == (True, 150)assert first_counted.lower_score_streak == 1assert second_counted.lower_score_streak == 2assert (stopped.should_stop, stopped.reason) == (True, "patience_exhausted")def test_policy_state_round_trip_preserves_best_and_streak() -> None:policy = CheckpointEvaluationPolicy(patience=3)policy.observe(0.5, step=10)8 unmodified linesassert result.evaluation_count == 3def test_policy_state_round_trip_preserves_patience_start_step() -> None:policy = CheckpointEvaluationPolicy(patience=3,tie_policy="count",patience_start_step=200,)policy.establish_external_baseline(0.5)resumed = CheckpointEvaluationPolicy.from_state_dict(policy.state_dict())assert resumed.patience_start_step == 200assert resumed.observe(0.4, step=100).lower_score_streak == 0def test_callback_state_round_trip_restores_policy_for_resume() -> None:callback = CheckpointEvaluationTriggerCallback(patience=3, tie_policy="reset")callback.policy.observe(0.5, step=10)27 unmodified lines"lower_score_streak": 1,"evaluation_count": 2,"stop_requested": False,"best_is_external": False,}resumed = CheckpointEvaluationTriggerCallback(patience=3)33 unmodified lines"lower_score_streak": 0,"evaluation_count": 1,"stop_requested": False,"best_is_external": False,}def test_external_baseline_only_saves_a_strict_improvement() -> None:policy = CheckpointEvaluationPolicy(patience=3)policy.establish_external_baseline(0.2828125, step=0)tied = policy.observe(0.2828125, step=10)improved = policy.observe(0.30, step=25)assert (tied.should_save, tied.reason, tied.best_is_external) == (False,"tie_reset",True,)assert (improved.should_save, improved.reason, improved.best_step) == (True,"improved",25,)assert improved.best_is_external is Falseassert policy.state.best_is_external is Falsedef test_external_baseline_sidecar_restores_without_a_checkpoint_directory(tmp_path: Path,) -> None:callback = CheckpointEvaluationTriggerCallback(output_dir=tmp_path)callback.policy.establish_external_baseline(0.2828125, step=0)callback.policy.observe(0.2828125, step=10)callback.persist(is_world_process_zero=True)resumed = CheckpointEvaluationTriggerCallback()resumed.on_train_begin(SimpleNamespace(output_dir=str(tmp_path)),SimpleNamespace(is_world_process_zero=True),SimpleNamespace(should_training_stop=False),)assert resumed.policy.state.best_is_external is Trueassert resumed.policy.state.best_score == 0.2828125assert resumed.policy.state.evaluation_count == 1def test_trigger_callback_schedules_irregular_and_regular_steps() -> None:callback = CheckpointEvaluationTriggerCallback(gate_steps=[10, 25, 50],regular_steps=100,)triggered: list[int] = []for step in (9, 10, 11, 25, 50, 99, 100, 101, 200):control = SimpleNamespace(should_save=False, should_evaluate=False)callback.on_step_end(None, SimpleNamespace(global_step=step), control)if callback.consume_checkpoint_evaluation():triggered.append(step)assert triggered == [10, 25, 50, 100, 200]def test_terminal_sidecar_state_stops_a_resumed_training_run(tmp_path: Path) -> None:(tmp_path / "checkpoint-1").mkdir()callback = CheckpointEvaluationTriggerCallback(output_dir=tmp_path, patience=1)
13 unmodified lines14151617181920 unmodified lines4041424344454614 unmodified lines61626313 unmodified linesstudent_forward_chunk_size,sync_global_max_count,sync_global_sum_count,uses_deepspeed_json_file,)20 unmodified linesassert student_forward_chunk_size(32, has_vision=True) == 32assert student_forward_chunk_size(32, has_vision=False) == 32def test_ddp_config_not_deepspeed(monkeypatch):monkeypatch.setenv("ACCELERATE_CONFIG", "default_config.yaml")assert not is_deepspeed_accelerate_config()14 unmodified linesassert sync_global_sum_count(3, torch.device("cpu"), 1) == 3assert sync_global_sum_count(0, torch.device("cpu"), 1) == 013 unmodified lines1415161718192020 unmodified lines41424344454614 unmodified lines616263646566676869707172737475767778798081828384858687888913 unmodified linesstudent_forward_chunk_size,sync_global_max_count,sync_global_sum_count,sync_global_sum_counts,uses_deepspeed_json_file,)20 unmodified linesassert student_forward_chunk_size(32, has_vision=True) == 32assert student_forward_chunk_size(32, has_vision=False) == 32def test_ddp_config_not_deepspeed(monkeypatch):monkeypatch.setenv("ACCELERATE_CONFIG", "default_config.yaml")assert not is_deepspeed_accelerate_config()14 unmodified linesassert sync_global_sum_count(3, torch.device("cpu"), 1) == 3assert sync_global_sum_count(0, torch.device("cpu"), 1) == 0def test_sync_global_sum_counts_single_process():import torchassert sync_global_sum_counts([3, 2], torch.device("cpu"), 1) == [3, 2]assert sync_global_sum_counts([0, 0], torch.device("cpu"), 1) == [0, 0]def test_runtime_deepspeed_environment_detected_without_config_path(monkeypatch, tmp_path):ds_json = tmp_path / "ds_zero2.json"ds_json.write_text('{"zero_optimization": {"stage": 2}}', encoding="utf-8")for key in ("ACCELERATE_CONFIG","ACCELERATE_CONFIG_FILE","ACCELERATE_DEEPSPEED_ZERO_STAGE",):monkeypatch.delenv(key, raising=False)monkeypatch.setenv("ACCELERATE_USE_DEEPSPEED", "true")monkeypatch.setenv("ACCELERATE_DEEPSPEED_CONFIG_FILE", str(ds_json))assert is_deepspeed_accelerate_config()assert uses_deepspeed_json_file()assert deepspeed_zero_stage() == 2assert deepspeed_requires_single_student_forward()assert student_forward_chunk_size(2, has_vision=True) == 2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132from __future__ import annotations
import copy
import pytestimport torchimport torch.nn.functional as F
from config.loader import load_config, validate_configfrom opsd_utils.opsd_loss import ( compute_vlm_opsd_loss_masked_batch, token_distillation_loss_per_row,)from trainer.DyMETrainer import build_unprivileged_reference_scoring_inputs
def test_exopd_rkl_matches_normalized_geometric_target_and_has_student_grad(): student = torch.tensor([[[0.4, -0.1, 0.2]]], requires_grad=True) teacher = torch.tensor([[[1.2, -0.3, 0.1]]]) reference = torch.tensor([[[-0.2, 0.8, 0.0]]]) mask = torch.ones(1, 1)
actual = token_distillation_loss_per_row( student, teacher, mask, reference_logits=reference, reward_scale=1.25, loss_type="exopd_rkl", )
s_log = F.log_softmax(student, dim=-1) t_log = F.log_softmax(teacher, dim=-1) r_log = F.log_softmax(reference, dim=-1) scores = 1.25 * t_log - 0.25 * r_log q_log = scores - torch.logsumexp(scores, dim=-1, keepdim=True) expected = F.kl_div(q_log, s_log, reduction="none", log_target=True).sum(-1).squeeze(-1) torch.testing.assert_close(actual, expected)
actual.mean().backward() assert student.grad is not None assert torch.isfinite(student.grad).all() assert teacher.grad is None assert reference.grad is None
def test_exopd_lambda_one_is_rkl_and_jointly_slices_three_vocabularies(): torch.manual_seed(7) student = torch.randn(2, 3, 7) teacher = torch.randn(2, 3, 8) reference = torch.randn(2, 3, 6) mask = torch.ones(2, 3)
exopd = token_distillation_loss_per_row( student, teacher, mask, reference_logits=reference, reward_scale=1.0, loss_type="exopd_rkl", ) rkl = token_distillation_loss_per_row( student[..., :6], teacher[..., :6], mask, loss_type="rkl", ) torch.testing.assert_close(exopd, rkl, rtol=1e-5, atol=1e-6)
def test_exopd_cached_path_fails_closed_without_reference_logits(): inputs = { "prompt_ids": torch.ones(1, 2, dtype=torch.long), "prompt_mask": torch.ones(1, 2, dtype=torch.long), "completion_ids": torch.ones(1, 1, dtype=torch.long), "completion_mask": torch.ones(1, 1, dtype=torch.long), "teacher_completion_logits": torch.randn(1, 1, 4), } with pytest.raises(RuntimeError, match="reference_completion_logits"): compute_vlm_opsd_loss_masked_batch( object(), [0], [0], inputs, student_completion_logits=torch.randn(1, 1, 4, requires_grad=True), loss_type="exopd_rkl", reward_scale=1.25, )
def test_unprivileged_reference_view_uses_student_prompt_and_image_rows(): inputs = { "prompt_ids": torch.arange(12).view(3, 4), "prompt_mask": torch.ones(3, 4, dtype=torch.long), "pixel_values": torch.randn(3, 2, 5), "img_sizes": torch.tensor([[10, 20], [30, 40], [50, 60]]), "completion_ids": torch.ones(3, 2, dtype=torch.long), "completion_mask": torch.ones(3, 2, dtype=torch.long), "teacher_prompt_ids": torch.full((3, 7), 99), "teacher_prompt_mask": torch.ones(3, 7, dtype=torch.long), "teacher_pixel_values_list": [torch.randn(1, 9, 5) for _ in range(3)], } view = build_unprivileged_reference_scoring_inputs(inputs) assert view["teacher_prompt_ids"] is inputs["prompt_ids"] assert view["teacher_prompt_mask"] is inputs["prompt_mask"] assert len(view["teacher_pixel_values_list"]) == 3 torch.testing.assert_close(view["teacher_pixel_values_list"][1], inputs["pixel_values"][1:2]) torch.testing.assert_close(view["teacher_image_sizes_list"][2], inputs["img_sizes"][2:3]) assert view["teacher_num_images"].tolist() == [1, 1, 1]
def test_exopd_config_contract_accepts_both_references_and_rejects_non_extrapolation(): base = load_config("opd_only") for reference_mode in ("initial_student", "teacher_without_privilege"): cfg = copy.deepcopy(base) cfg["opsd"]["loss"].update( loss_type="exopd_rkl", reference_mode=reference_mode, reward_scale=1.25, ) cfg["opsd"]["teacher_trajectory"]["enabled"] = False assert validate_config(cfg)["opsd"]["loss"]["reference_mode"] == reference_mode
invalid = copy.deepcopy(base) invalid["opsd"]["loss"].update( loss_type="exopd_rkl", reference_mode="initial_student", reward_scale=1.0, ) invalid["opsd"]["teacher_trajectory"]["enabled"] = False with pytest.raises(ValueError, match="reward_scale > 1.0"): validate_config(invalid)13 unmodified lines1415161718192021222324252627282930313233343536373839404153 unmodified lines959697989910010110210310410510610710810911011111211311413 unmodified linesassert cfg["opsd"]["loss"]["acc_gate"] is Falseassert cfg["opsd"]["loss"]["grpo_weight"] == 0.0assert cfg["opsd"]["loss"]["sft_weight"] == 0.0assert cfg["opsd"]["teacher_probe"]["enabled"] is Trueassert cfg["opsd"]["teacher_trajectory"]["enabled"] is Trueassert cfg["opsd"]["teacher_trajectory"]["prompt_profile"] == "chartqa_structured_trajectory"assert cfg["opsd"]["teacher_trajectory"]["require_quality_for_loss"] is Trueassert cfg["dataset"]["train_dataset"].endswith("train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json")assert cfg["data_validation"] == {"strict": True,"require_real_deplot": True,"require_qwen_rewrite": True,"expected_samples": 4576,}def test_opd_only_trajectory_fkl_restores_the_exact_generated_teacher_condition():source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text(encoding="utf-8")assert 'result[f"teacher_traj_{key}"] = value' in sourceassert 'key.startswith("teacher_traj_teacher_")' in sourceassert 'traj_inputs[key[len("teacher_traj_"):]] = value' in sourceassert '"teacher_compact_indices": eligible' in source53 unmodified linesdef test_project_paths_use_one_explicit_root_and_are_resolved_by_loader():root = Path(__file__).resolve().parents[1]config_dir = root / "config"legacy_root = "/data/junjie/agentic-rl-main"for path in sorted(config_dir.glob("*.yaml")):raw = path.read_text(encoding="utf-8")raw_cfg = yaml.safe_load(raw)assert raw_cfg["paths"] == {"project_root": "/data/junjie/agentic-rl-main"}, pathassert raw.count(legacy_root) == 1, pathloaded = load_config(str(path))assert loaded["paths"]["project_root"] == "/data/junjie/agentic-rl-main"assert "project://" not in repr(loaded)opd = load_config("opd_only")assert opd["model"]["pretrained_model_path"] == str(root / "outputs/sft-chart-llava_cot/final_checkpoint")assert opd["dataset"]["train_dataset"] == str(root / "data/chartqa/train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json")13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868753 unmodified lines14114214314414514614714814915015115215315415515615715813 unmodified linesassert cfg["opsd"]["loss"]["acc_gate"] is Falseassert cfg["opsd"]["loss"]["grpo_weight"] == 0.0assert cfg["opsd"]["loss"]["sft_weight"] == 0.0assert cfg["opsd"]["teacher_probe"]["enabled"] is Falseassert cfg["opsd"]["teacher_trajectory"]["enabled"] is Falseassert cfg["opsd"]["teacher_trajectory"]["prompt_profile"] == "chartqa_structured_trajectory"assert cfg["opsd"]["teacher_trajectory"]["require_quality_for_loss"] is Trueassert cfg["opsd"]["teacher_trajectory"]["max_loss_rows_per_rank"] == 2assert cfg["opsd"]["privileged_providers"] == ["visual_facts_deplot"]assert cfg["opsd"]["gate"]["require_format_for_opsd"] is Trueassert cfg["opsd"]["gate"]["skip_degenerate_for_opsd"] is Trueassert cfg["opsd"]["loss"]["assert_teacher_response_prefix_empty"] is Trueassert cfg["training"]["dyme_args"]["learning_rate"] == 1e-6assert cfg["opsd"]["strict_teacher_no_gold_context"] is Trueassert cfg["opsd"]["loss"]["ignore_leading_whitespace_tokens"] is Trueassert cfg["opsd"]["loss"]["max_leading_whitespace_tokens"] == 4assert cfg["dataset"]["teacher_gate"]["selection_mode"] == "hard_correct"assert cfg["dataset"]["teacher_gate"]["expected_selected_rows"] == 3220assert cfg["training"]["dyme_args"]["num_train_epochs"] == 5assert cfg["dataset"]["train_dataset"].endswith("train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json")assert cfg["data_validation"] == {"strict": True,"require_real_deplot": True,"require_qwen_rewrite": False,"expected_samples": 4576,}assert cfg["checkpoint_eval"]["patience_start_step"] == 0assert cfg["checkpoint_eval"]["gate_steps"] == [10, 25, 50, 75]assert cfg["training"]["dyme_args"]["save_total_limit"] == 3def test_opd_only_rejects_teacher_response_prefill_when_alignment_assertion_is_enabled():from config.loader import validate_configcfg = load_config("opd_only")cfg["opsd"]["privileged_providers"].append("chartqa_answer_prefix")with pytest.raises(ValueError, match="forbids chartqa_answer_prefix"):validate_config(cfg)def test_opd_only_branch_records_generation_diagnostics_before_returning():source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text()branch = source[source.index('if self.training_stage == "opd_only":') :]assert branch.index("log_generation_diagnostics(") < branch.index("return self._build_opd_only_batch(")def test_opd_routing_metrics_are_recorded_only_per_ga_microbatch():source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text(encoding="utf-8")builder = source[source.index(" def _build_opd_only_batch(") : source.index(" def _record_cached_teacher_gate_batch(")]loss = source[source.index(" def _compute_opd_only_loss(") :]assert '"routing/opd_route_count"' not in builderassert loss.count('"routing/opd_route_count"') == 1assert loss.count('"routing/opd_filtered_count"') == 1def test_opd_only_trajectory_fkl_restores_the_exact_generated_teacher_condition():source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text(encoding="utf-8")assert 'result["teacher_traj_fkl_payload"] = fkl_payload' in sourceassert 'result["teacher_traj_fkl_owner"] = fkl_owner' in sourceassert 'fkl_payload[key] = value' in sourceassert 'selection_scope="optimizer_step"' in sourceassert '"teacher_compact_indices": eligible' in source53 unmodified linesdef test_project_paths_use_one_explicit_root_and_are_resolved_by_loader():root = Path(__file__).resolve().parents[1]config_dir = root / "config"project_root = str(root)for path in sorted(config_dir.glob("*.yaml")):raw = path.read_text(encoding="utf-8")raw_cfg = yaml.safe_load(raw)assert raw_cfg["paths"] == {"project_root": project_root}, pathassert raw.count(project_root) == 1, pathloaded = load_config(str(path))assert loaded["paths"]["project_root"] == project_rootassert "project://" not in repr(loaded)opd = load_config("opd_only")assert Path(opd["model"]["pretrained_model_path"]).is_dir()assert opd["dataset"]["train_dataset"] == str(root / "data/chartqa/train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960from __future__ import annotations
import inspect
import pytest
from opsd_utils.rollout_filter import classify_opd_rollout_validity
def _classify(text: str, token_ids: list[int] | None = None, **kwargs): return classify_opd_rollout_validity( text, token_ids or [1, 2, 3], answer_flag="Answer:", **kwargs, )
def test_well_formed_rollout_is_selected_without_gold_input() -> None: result = _classify("Reasoning from the chart.\nAnswer: 42") assert result["valid"] is True assert result["format_valid"] is True assert result["answer_flag_count"] == 1 assert "answer" not in inspect.signature(classify_opd_rollout_validity).parameters
@pytest.mark.parametrize( ("text", "reason"), [ ("No final marker", "missing"), ("Answer: 1\nAnswer: 2", "multiple"), ("Reasoning\nAnswer: ", "empty"), ("Answer: <short answer>", "placeholder"), ],)def test_malformed_or_placeholder_rollouts_are_excluded(text: str, reason: str) -> None: result = _classify(text) assert result["valid"] is False if reason == "missing": assert result["answer_flag_count"] == 0 elif reason == "multiple": assert result["answer_flag_count"] == 2 else: assert result[f"{reason}_answer" if reason == "empty" else reason] is True
def test_repetition_filter_is_independent_of_answer_correctness() -> None: result = _classify("Answer: value", token_ids=[7] * 8) assert result["degenerate"] is True assert result["valid"] is False
def test_legacy_format_setting_can_keep_missing_marker_but_never_placeholder() -> None: assert _classify( "plain answer", require_format=False, skip_degenerate=False )["valid"] is True assert _classify( "<short answer>", require_format=False, skip_degenerate=False )["valid"] is False
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from __future__ import annotations
import importlibfrom types import SimpleNamespace
import torch
from trainer.DyMETrainer import DyMETrainer
class _ToyStudent: def __init__(self, vocab_size: int = 11) -> None: self.logit_seed = torch.nn.Parameter(torch.arange(vocab_size, dtype=torch.float32)) self.calls: list[int] = []
def __call__(self, *, input_ids, logits_to_keep, **_kwargs): self.calls.append(int(logits_to_keep)) logits = self.logit_seed.view(1, 1, -1).expand( input_ids.size(0), int(logits_to_keep), -1 ) return SimpleNamespace(logits=logits)
def _trainer() -> DyMETrainer: trainer = DyMETrainer.__new__(DyMETrainer) trainer.temperature = 1.0 trainer.args = SimpleNamespace(report_to=[]) trainer.accelerator = SimpleNamespace(is_main_process=False) return trainer
def test_completion_logits_only_skips_selected_logprob_branch(monkeypatch) -> None: module = importlib.import_module("trainer.DyMETrainer") trainer = _trainer() student = _ToyStudent() input_ids = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=torch.long) attention_mask = torch.ones_like(input_ids)
def _unexpected_logprob(*_args, **_kwargs): raise AssertionError("log-prob branch must not run for OPD logits-only scoring")
monkeypatch.setattr(module, "selective_log_softmax", _unexpected_logprob) logps, completion_logits = trainer._get_per_token_logps( student, input_ids, attention_mask, pixel_values=None, image_sizes=None, logits_to_keep=2, return_completion_logits=True, return_logps=False, )
assert logps is None assert completion_logits.shape == (2, 2, 11) assert student.calls == [3] completion_logits.sum().backward() assert student.logit_seed.grad is not None
def test_default_path_keeps_selected_logprobs() -> None: trainer = _trainer() student = _ToyStudent() input_ids = torch.tensor([[1, 2, 3, 4]], dtype=torch.long) attention_mask = torch.ones_like(input_ids)
logps, completion_logits = trainer._get_per_token_logps( student, input_ids, attention_mask, pixel_values=None, image_sizes=None, logits_to_keep=2, return_completion_logits=True, )
assert logps is not None assert logps.shape == (1, 2) assert completion_logits.shape == (1, 2, 11)128 unmodified lines129130131132133134128 unmodified linesassert payload["status"] == "ok"def test_health_check_reports_partial_goal_without_answer_drift(tmp_path: Path) -> None:code, payload = _run(tmp_path,128 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158128 unmodified linesassert payload["status"] == "ok"def test_health_check_detects_answer_format_drift(tmp_path: Path) -> None:code, payload = _run(tmp_path,[{"rollout/answer_flag_rate": 0.5, "rollout/parse_fail_rate": 0.5},{"rollout/answer_flag_rate": 0.4, "rollout/parse_fail_rate": 0.6},],)assert code == 7assert payload["status"] == "answer_format_drift"def test_health_check_detects_teacher_answer_span_alignment_drift(tmp_path: Path) -> None:code, payload = _run(tmp_path,[{"loss/jsd_answer_span": 0.6, "rollout/answer_flag_rate": 1.0},{"loss/jsd_answer_span": 0.65, "rollout/answer_flag_rate": 1.0},],)assert code == 6assert payload["status"] == "teacher_alignment_drift"def test_health_check_reports_partial_goal_without_answer_drift(tmp_path: Path) -> None:code, payload = _run(tmp_path,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136from __future__ import annotations
import copy
import pytestimport torch
from config.loader import load_config, validate_configfrom opsd_utils.opsd_loss import opdvr_reward_gated_loss_per_row
def _one_token_case(*, correct: bool, teacher_prefers_action: bool): student = torch.tensor([[[0.0, 0.0]]], requires_grad=True) teacher = torch.tensor( [[[2.0, 0.0]]] if teacher_prefers_action else [[[-2.0, 0.0]]] ) loss, diagnostics = opdvr_reward_gated_loss_per_row( student, teacher, torch.tensor([[0]]), torch.ones(1, 1), torch.tensor([correct]), return_diagnostics=True, ) loss.mean().backward() return loss, student.grad, diagnostics
def test_correct_rollout_only_reinforces_teacher_preferred_sampled_token(): active_loss, active_grad, diagnostics = _one_token_case( correct=True, teacher_prefers_action=True ) assert active_loss.item() > 0.0 assert active_grad[0, 0, 0].item() < 0.0 assert diagnostics["positive_token_count"].item() == 1.0
zero_loss, zero_grad, diagnostics = _one_token_case( correct=True, teacher_prefers_action=False ) assert zero_loss.item() == pytest.approx(0.0) torch.testing.assert_close(zero_grad, torch.zeros_like(zero_grad)) assert diagnostics["zero_token_count"].item() == 1.0
def test_wrong_rollout_only_suppresses_teacher_disfavored_sampled_token(): active_loss, active_grad, diagnostics = _one_token_case( correct=False, teacher_prefers_action=False ) assert active_loss.item() < 0.0 assert active_grad[0, 0, 0].item() > 0.0 assert diagnostics["negative_token_count"].item() == 1.0
zero_loss, zero_grad, diagnostics = _one_token_case( correct=False, teacher_prefers_action=True ) assert zero_loss.item() == pytest.approx(0.0) torch.testing.assert_close(zero_grad, torch.zeros_like(zero_grad)) assert diagnostics["zero_token_count"].item() == 1.0
def test_optional_teacher_correctness_gate_is_fail_closed(): student = torch.tensor([[[0.0, 0.0]]], requires_grad=True) teacher = torch.tensor([[[2.0, 0.0]]]) loss, diagnostics = opdvr_reward_gated_loss_per_row( student, teacher, torch.tensor([[0]]), torch.ones(1, 1), torch.tensor([True]), teacher_correct=torch.tensor([False]), require_teacher_correct=True, return_diagnostics=True, ) loss.mean().backward() assert loss.item() == pytest.approx(0.0) torch.testing.assert_close(student.grad, torch.zeros_like(student.grad)) assert diagnostics["effective_row_count"].item() == 0.0
def test_mask_and_row_mean_match_manual_sampled_token_objective(): student = torch.tensor( [ [[0.0, 0.0], [0.2, -0.2]], [[0.0, 0.0], [0.0, 0.0]], ], requires_grad=True, ) teacher = torch.tensor( [ [[2.0, 0.0], [1.0, -1.0]], [[-2.0, 0.0], [-2.0, 0.0]], ] ) ids = torch.tensor([[0, 0], [0, 0]]) mask = torch.tensor([[1.0, 0.0], [1.0, 1.0]]) losses = opdvr_reward_gated_loss_per_row( student, teacher, ids, mask, torch.tensor([True, False]), token_chunk_size=1, )
student_logp = torch.log_softmax(student, dim=-1).gather(-1, ids.unsqueeze(-1)).squeeze(-1) teacher_logp = torch.log_softmax(teacher, dim=-1).gather(-1, ids.unsqueeze(-1)).squeeze(-1) ratio = (teacher_logp - student_logp).detach() reward = torch.stack((ratio[0].clamp_min(0), ratio[1].clamp_max(0))) * mask expected = (-reward * student_logp).sum(-1) / mask.sum(-1) torch.testing.assert_close(losses, expected)
def test_opdvr_config_requires_full_annotation_mode_and_accepts_trajectory(): cfg = copy.deepcopy(load_config("opd_only")) cfg["opsd"]["loss"].update( loss_type="opdvr", reward_gate={ "enabled": True, "correct_threshold": 0.5, "token_scope": "answer_span", "require_teacher_correct": False, "require_teacher_gate_metadata": True, "max_abs_log_ratio": 0.0, }, ) cfg["dataset"]["teacher_gate"].update( selection_mode="all", expected_selected_rows=4576 ) cfg["opsd"]["teacher_trajectory"]["enabled"] = True validated = validate_config(cfg) assert validated["opsd"]["loss"]["reward_gate"]["token_scope"] == "answer_span"
invalid = copy.deepcopy(cfg) invalid["dataset"]["teacher_gate"]["selection_mode"] = "hard_correct" with pytest.raises(ValueError, match="selection_mode=all"): validate_config(invalid)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231from __future__ import annotations
import torch
from opsd_utils.opsd_loss import ( build_opsd_answer_diagnostic_masks, build_opsd_loss_mask, token_distillation_loss, token_distillation_loss_per_row,)
class TinyWhitespaceTokenizer: all_special_ids = [0] pieces = { 0: "<special>", 1: "\n", 2: " ", 3: "Answer", 4: ":", 5: "inside", }
def decode(self, token_ids, **_kwargs): return "".join(self.pieces[int(token_id)] for token_id in token_ids)
class TinyAnswerTokenizer(TinyWhitespaceTokenizer): eos_token_id = 6 all_special_ids = [0, 6] pieces = { **TinyWhitespaceTokenizer.pieces, 5: "42", 6: "<eos>", }
def encode(self, text, add_special_tokens=False): assert add_special_tokens is False variants = { "Answer:": [3, 4], " Answer:": [2, 3, 4], "\nAnswer:": [1, 3, 4], "\n\nAnswer:": [1, 1, 3, 4], } return variants.get(text, [])
def _mask(ids: list[list[int]], attention: list[list[int]], *, maximum: int = 4): return build_opsd_loss_mask( torch.tensor(ids, dtype=torch.long), torch.tensor(attention, dtype=torch.long), TinyWhitespaceTokenizer(), ignore_leading_whitespace_tokens=True, max_leading_whitespace_tokens=maximum, )
def test_leading_whitespace_is_masked_but_semantic_and_internal_space_remain() -> None: loss_mask, stats = _mask( [[1, 1, 3, 2, 5], [3, 2, 5, 0, 0], [0, 3, 4, 0, 0]], [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], ) assert loss_mask.tolist() == [ [0, 0, 1, 1, 1], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], ] assert stats["first_semantic_positions"].tolist() == [2, 0, 0] assert stats["leading_whitespace_masked_counts"].tolist() == [2, 0, 0] # A special token is never classified as semantic-free whitespace. assert stats["valid_rows"].tolist() == [True, True, True]
def test_no_semantic_and_over_limit_rows_are_fully_excluded() -> None: loss_mask, stats = _mask( [[1, 2, 1, 2, 0, 0], [1, 1, 1, 1, 1, 3]], [[1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1]], maximum=4, ) assert loss_mask.sum(dim=1).tolist() == [0, 0] assert stats["no_semantic_rows"].tolist() == [True, False] assert stats["leading_whitespace_over_limit_rows"].tolist() == [False, True] assert stats["valid_rows"].tolist() == [False, False]
def test_disabled_whitespace_filter_preserves_legacy_loss_mask() -> None: ids = torch.tensor([[1, 1, 3]], dtype=torch.long) attention = torch.ones_like(ids) loss_mask, stats = build_opsd_loss_mask( ids, attention, TinyWhitespaceTokenizer(), ignore_leading_whitespace_tokens=False, ) assert torch.equal(loss_mask, attention) assert stats["leading_whitespace_masked_counts"].sum().item() == 0
def test_answer_diagnostics_skip_fixed_marker_and_separate_eos() -> None: ids = torch.tensor( [ [1, 3, 4, 2, 5, 6], [3, 4, 5, 2, 5, 6], [1, 3, 5, 6, 0, 0], ] ) attention = torch.tensor( [ [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0], ] ) stats = build_opsd_answer_diagnostic_masks( ids, attention, TinyAnswerTokenizer(), answer_flag="Answer:", ) assert stats["first_answer_positions"].tolist() == [4, 2, -1] assert stats["answer_span_mask"].tolist() == [ [0, 0, 0, 0, 1, 0], [0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], ] assert stats["eos_mask"].tolist() == [ [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0], ] assert stats["answer_marker_found_rows"].tolist() == [True, True, False] assert stats["answer_span_valid_rows"].tolist() == [True, True, False] assert stats["eos_found_rows"].tolist() == [True, True, True]
def test_masked_whitespace_has_zero_gradient_and_first_semantic_has_gradient() -> None: torch.manual_seed(7) ids = torch.tensor([[1, 3, 4]], dtype=torch.long) attention = torch.ones_like(ids) loss_mask, _ = build_opsd_loss_mask( ids, attention, TinyWhitespaceTokenizer(), ignore_leading_whitespace_tokens=True, max_leading_whitespace_tokens=4, ) student = torch.randn(1, 3, 19, requires_grad=True) teacher = torch.randn(1, 3, 19) loss = token_distillation_loss_per_row( student, teacher, loss_mask.float(), token_chunk_size=2, ).mean() loss.backward() assert torch.count_nonzero(student.grad[:, 0]).item() == 0 assert student.grad[:, 1].abs().sum().item() > 0
def test_variable_rows_match_manual_valid_row_reference_and_diagnostics() -> None: torch.manual_seed(11) ids = torch.tensor([[1, 3, 4, 0], [3, 4, 0, 0], [1, 2, 1, 2]]) raw_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]]) loss_mask, mask_stats = build_opsd_loss_mask( ids, raw_mask, TinyWhitespaceTokenizer(), ignore_leading_whitespace_tokens=True, max_leading_whitespace_tokens=4, ) student = torch.randn(3, 4, 23, requires_grad=True) teacher = torch.randn(3, 4, 23) row_losses, diagnostics = token_distillation_loss_per_row( student, teacher, loss_mask.float(), raw_mask=raw_mask.float(), first_semantic_positions=mask_stats["first_semantic_positions"], token_chunk_size=2, return_position_stats=True, return_diagnostics=True, ) expected = torch.stack( [ token_distillation_loss( student[row : row + 1], teacher[row : row + 1], loss_mask[row : row + 1].float(), ) for row in range(2) ] ) assert torch.allclose(row_losses[:2], expected, atol=1e-6, rtol=1e-6) assert row_losses[2].item() == 0.0 assert diagnostics["valid_row_count"].item() == 2 assert diagnostics["raw_position_0_count"].item() == 3 assert diagnostics["position_0_active_count"].item() == 1 assert diagnostics["first_semantic_count"].item() == 2
def test_answer_span_and_eos_distribution_diagnostics_are_separate() -> None: torch.manual_seed(19) ids = torch.tensor([[1, 3, 4, 2, 5, 6]]) raw_mask = torch.ones_like(ids) answer_stats = build_opsd_answer_diagnostic_masks( ids, raw_mask, TinyAnswerTokenizer(), ) student = torch.randn(1, ids.size(1), 17, requires_grad=True) teacher = torch.randn_like(student) _, diagnostics = token_distillation_loss_per_row( student, teacher, raw_mask.float(), raw_mask=raw_mask.float(), first_answer_positions=answer_stats["first_answer_positions"], answer_span_mask=answer_stats["answer_span_mask"], eos_mask=answer_stats["eos_mask"], diagnostic_top_k=5, return_position_stats=True, return_diagnostics=True, ) assert diagnostics["first_answer_count"].item() == 1 assert diagnostics["answer_span_count"].item() == 1 assert diagnostics["eos_count"].item() == 1 assert diagnostics["first_answer_sum"].item() >= 0.0 assert diagnostics["answer_span_sum"].item() >= 0.0 assert diagnostics["eos_sum"].item() >= 0.0 assert 0.0 <= diagnostics["answer_topk_overlap_sum"].item() <= 1.0 assert 0.0 <= diagnostics["answer_shared_mass_sum"].item() <= 1.013 unmodified lines14151617181988 unmodified lines10810911013 unmodified lines_trim_to_effective_completion,compute_vlm_opsd_loss_masked_batch,generalized_jsd_loss,token_distillation_loss,)88 unmodified linesfkl = token_distillation_loss(student, teacher, mask, loss_type="fkl")assert srkl.ndim == 0 and srkl.requires_gradassert fkl.ndim == 0 and fkl.requires_grad13 unmodified lines141516171819202188 unmodified lines11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338413 unmodified lines_trim_to_effective_completion,compute_vlm_opsd_loss_masked_batch,generalized_jsd_loss,precompute_teacher_completion_logits,token_distillation_loss_per_row,token_distillation_loss,)88 unmodified linesfkl = token_distillation_loss(student, teacher, mask, loss_type="fkl")assert srkl.ndim == 0 and srkl.requires_gradassert fkl.ndim == 0 and fkl.requires_graddef test_masked_batch_maps_compact_precomputed_logits_without_student_forward():"""Trajectory FKL can reuse one batched student forward for sparse rows."""batch_size = 4seq = 4vocab = 8device = torch.device("cpu")student = MagicMock()teacher = MagicMock()param = torch.nn.Parameter(torch.zeros(1, device=device))student.parameters = lambda: iter([param])teacher.parameters = lambda: iter([param])def fake_teacher_forward(**kwargs):out = MagicMock()batch_rows = int(kwargs["input_ids"].size(0))seq_len = int(kwargs["input_ids"].size(1))out.logits = torch.zeros(batch_rows, seq_len, vocab, device=device)return outteacher.side_effect = fake_teacher_forwardprecomputed_logits = torch.randn(2, 2, vocab, device=device, requires_grad=True)inputs = {"prompt_ids": torch.ones(batch_size, seq, dtype=torch.long),"prompt_mask": torch.ones(batch_size, seq, dtype=torch.long),"pixel_values": torch.randn(batch_size, 3, 8, 8),"teacher_prompt_ids": torch.ones(2, seq, dtype=torch.long),"teacher_prompt_mask": torch.ones(2, seq, dtype=torch.long),"teacher_compact_indices": [1, 3],"completion_ids": torch.ones(batch_size, 2, dtype=torch.long),"completion_mask": torch.ones(batch_size, 2, dtype=torch.long),"teacher_num_images": torch.ones(2, dtype=torch.long),}loss = compute_vlm_opsd_loss_masked_batch(student,[3, 1],list(range(batch_size)),inputs,processor=None,teacher_model=teacher,acc_gate=False,student_completion_logits=precomputed_logits,student_completion_logits_indices=[3, 1],loss_type="fkl",)loss.backward()assert student.call_count == 0assert teacher.call_count == 2assert precomputed_logits.grad is not Noneassert torch.isfinite(precomputed_logits.grad).all()def test_rowwise_chunked_loss_matches_historical_per_row_reduction():torch.manual_seed(0)student = torch.randn(3, 5, 17, requires_grad=True)teacher = torch.randn(3, 5, 17)mask = torch.tensor([[1, 1, 1, 1, 1],[1, 1, 1, 0, 0],[1, 1, 0, 0, 0],],dtype=torch.float32,)expected = torch.stack([token_distillation_loss(student[row : row + 1],teacher[row : row + 1],mask[row : row + 1],loss_type="jsd",beta=0.5,)for row in range(student.size(0))])actual = token_distillation_loss_per_row(student,teacher,mask,loss_type="jsd",beta=0.5,token_chunk_size=2,)assert torch.allclose(actual, expected, atol=1e-6, rtol=1e-6)actual.mean().backward()assert student.grad is not Noneassert torch.isfinite(student.grad).all()def test_prefix_cache_precompute_matches_direct_batched_teacher_scoring():class ToyTeacher:def __init__(self, vocab: int):self.param = torch.nn.Parameter(torch.zeros(1))self.vocab = vocabself.calls: list[tuple[int, int, bool]] = []def parameters(self):return iter([self.param])def __call__(self,*,input_ids,logits_to_keep=None,use_cache=False,**kwargs,):rows = int(input_ids.size(0))keep = int(logits_to_keep or input_ids.size(1))logits = torch.arange(self.vocab, dtype=torch.float32).view(1, 1, -1)logits = logits.expand(rows, keep, -1).clone()self.calls.append((rows, keep, bool(use_cache)))out = type("Output", (), {})()out.logits = logitsout.past_key_values = ((torch.zeros(rows, 1, 1, 1),),) if use_cache else Nonereturn outrows, prompt_width, completion_width, vocab = 4, 3, 3, 11inputs = {"prompt_ids": torch.ones(rows, prompt_width, dtype=torch.long),"prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),"teacher_prompt_ids": torch.ones(rows, prompt_width, dtype=torch.long),"teacher_prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),"completion_ids": torch.ones(rows, completion_width, dtype=torch.long),"completion_mask": torch.ones(rows, completion_width, dtype=torch.long),"teacher_num_images": torch.ones(rows, dtype=torch.long),}teacher = ToyTeacher(vocab)cached, prefix_stats = precompute_teacher_completion_logits(teacher,inputs,num_generations=rows,teacher_score_batch_size=rows,reuse_teacher_prefix_cache=True,offload_teacher_logits=False,)direct, direct_stats = precompute_teacher_completion_logits(teacher,inputs,num_generations=rows,teacher_score_batch_size=rows,reuse_teacher_prefix_cache=False,offload_teacher_logits=False,)assert cached is not None and direct is not Noneassert torch.equal(cached, direct)assert prefix_stats["prefix_groups"] == 1.0assert prefix_stats["continuation_calls"] == 1.0assert prefix_stats["fallback_batches"] == 0.0assert direct_stats["direct_batches"] == 1.0assert teacher.calls[0][:2] == (1, 1)assert teacher.calls[1][:2] == (rows, completion_width - 1)def test_position_dependent_tiny_qwen2_prefix_cache_matches_direct_fp32():"""Guard real causal position/cache semantics, not a position-invariant toy."""from transformers import Qwen2Config, Qwen2ForCausalLMclass TextOnlyQwen(torch.nn.Module):def __init__(self):super().__init__()config = Qwen2Config(vocab_size=97,hidden_size=32,intermediate_size=64,num_hidden_layers=2,num_attention_heads=4,num_key_value_heads=2,max_position_embeddings=128,attention_dropout=0.0,)self.model = Qwen2ForCausalLM(config).float().eval()def forward(self, *, logits_to_keep=None, **kwargs):for key in ("pixel_values", "image_sizes", "batch_num_images"):kwargs.pop(key, None)output = self.model(**kwargs, return_dict=True)if logits_to_keep is not None:output.logits = output.logits[:, -int(logits_to_keep) :, :]return outputtorch.manual_seed(123)teacher = TextOnlyQwen()rows, prompt_width, completion_width = 4, 7, 5prompt = torch.tensor([[4, 8, 15, 16, 23, 42, 7]], dtype=torch.long)inputs = {"prompt_ids": prompt.expand(rows, -1).clone(),"prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),"teacher_prompt_ids": prompt.expand(rows, -1).clone(),"teacher_prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),"completion_ids": torch.tensor([[11, 12, 13, 14, 15],[21, 22, 23, 24, 25],[31, 32, 33, 34, 35],[41, 42, 43, 44, 45],],dtype=torch.long,),"completion_mask": torch.ones(rows, completion_width, dtype=torch.long),"teacher_num_images": torch.ones(rows, dtype=torch.long),}cached, cached_stats = precompute_teacher_completion_logits(teacher,inputs,num_generations=rows,teacher_score_batch_size=rows,reuse_teacher_prefix_cache=True,offload_teacher_logits=False,)direct, _ = precompute_teacher_completion_logits(teacher,inputs,num_generations=rows,teacher_score_batch_size=rows,reuse_teacher_prefix_cache=False,offload_teacher_logits=False,)assert cached is not None and direct is not Noneassert cached_stats["prefix_groups"] == 1.0assert cached_stats["prefix_fallback_groups"] == 0.0assert torch.max(torch.abs(cached - direct)).item() <= 1e-5def test_cached_teacher_logits_skip_teacher_and_preserve_student_grad():rows, tokens, vocab = 2, 4, 13student_logits = torch.randn(rows, tokens, vocab, requires_grad=True)teacher_logits = torch.randn(rows, tokens, vocab)class FrozenTeacher:def __init__(self):self.param = torch.nn.Parameter(torch.zeros(1))def parameters(self):return iter([self.param])frozen_teacher = FrozenTeacher()inputs = {"prompt_ids": torch.ones(rows, 3, dtype=torch.long),"prompt_mask": torch.ones(rows, 3, dtype=torch.long),"completion_ids": torch.ones(rows, tokens, dtype=torch.long),"completion_mask": torch.ones(rows, tokens, dtype=torch.long),"teacher_completion_logits": teacher_logits,"acc_rewards": torch.zeros(rows),}loss = compute_vlm_opsd_loss_masked_batch(None,[0, 1],[0, 1],inputs,teacher_model=frozen_teacher,acc_gate=False,student_completion_logits=student_logits,loss_type="jsd",token_chunk_size=2,)expected = token_distillation_loss_per_row(student_logits,teacher_logits,inputs["completion_mask"].float(),loss_type="jsd",token_chunk_size=2,).mean()assert torch.allclose(loss, expected, atol=1e-6, rtol=1e-6)loss.backward()assert student_logits.grad is not Noneassert torch.isfinite(student_logits.grad).all()assert not hasattr(frozen_teacher, "calls")
tests/test_chart_teacher_probe_parser.py+10
tests/test_chartqa_core.py+45
tests/test_chartqa_teacher_gate.pyAdded+470
tests/test_checkpoint_eval_policy.py+133
tests/test_deepspeed_utils.py+27-1
tests/test_exopd_target.pyAdded+132
tests/test_opd_only_stage.py+57-13
tests/test_opd_rollout_filter.pyAdded+60
tests/test_opd_student_logits_only.pyAdded+79
tests/test_opd_template_health_check.py+24
tests/test_opdvr_reward_gate.pyAdded+136
tests/test_opsd_loss_mask.pyAdded+231
tests/test_opsd_loss_teacher.py+274