Jack04810 commited on
Commit
afa231f
·
verified ·
1 Parent(s): d986954

Add files using upload-large-folder tool

Browse files
tests/test_chart_teacher_probe_parser.py CHANGED
@@ -51,4 +51,14 @@ def test_teacher_probe_chart_eval_uses_parsed_answer():
51
 
52
  assert score == 1.0
53
  assert parsed.answer == "70"
 
 
 
 
 
 
 
 
 
 
54
  assert parsed.parse_failed is False
 
51
 
52
  assert score == 1.0
53
  assert parsed.answer == "70"
54
+
55
+
56
+ def test_teacher_probe_chart_eval_accepts_official_exact_long_bare_answer():
57
+ score, parsed = eval_teacher_probe_chart(
58
+ "Unable to arrange child care",
59
+ "Unable to arrange child care",
60
+ )
61
+ assert score == 1.0
62
+ assert parsed.answer == "Unable to arrange child care"
63
+ assert parsed.parse_failed is False
64
  assert parsed.parse_failed is False
tests/test_chartqa_core.py CHANGED
@@ -232,10 +232,20 @@ def test_in_memory_evaluation_uses_live_model_and_restores_state(
232
  assert result["checkpoint_score"] == 1.0
233
  assert result["sample_count"] == 2
234
  assert result["output_type_counts"]["other"] == 2
 
 
235
  assert model.training is True
236
  assert model.train_calls == [True]
237
  assert processor.tokenizer.padding_side == "right"
238
 
 
 
 
 
 
 
 
 
239
 
240
  def test_default_generation_path_uses_the_passed_live_model(
241
  monkeypatch: pytest.MonkeyPatch,
@@ -464,6 +474,41 @@ def test_in_memory_evaluation_rejects_empty_valid_dataset() -> None:
464
  )
465
 
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  def test_final_summary_keeps_legacy_completed_evaluation_marker() -> None:
468
  lines: list[str] = []
469
 
 
232
  assert result["checkpoint_score"] == 1.0
233
  assert result["sample_count"] == 2
234
  assert result["output_type_counts"]["other"] == 2
235
+ assert result["answer_marker_counts"]["exactly_once"] == 2
236
+ assert sum(result["answer_marker_counts"].values()) == result["sample_count"]
237
  assert model.training is True
238
  assert model.train_calls == [True]
239
  assert processor.tokenizer.padding_side == "right"
240
 
241
+ def test_answer_marker_count_is_independent_of_legacy_output_type() -> None:
242
+ classify = chartqa_core.classify_answer_marker_count
243
+ assert classify("") == "missing"
244
+ assert classify("plain answer") == "missing"
245
+ assert classify("Answer: 1") == "exactly_once"
246
+ assert classify("answer: 1\nANSWER: 2") == "multiple"
247
+
248
+
249
 
250
  def test_default_generation_path_uses_the_passed_live_model(
251
  monkeypatch: pytest.MonkeyPatch,
 
474
  )
475
 
476
 
477
+ def test_evaluation_cuda_cache_release_is_configurable(
478
+ monkeypatch: pytest.MonkeyPatch,
479
+ ) -> None:
480
+ calls: list[tuple[str, object]] = []
481
+
482
+ class _FakeCuda:
483
+ @staticmethod
484
+ def is_available() -> bool:
485
+ return True
486
+
487
+ @staticmethod
488
+ def synchronize(device=None) -> None:
489
+ calls.append(("synchronize", device))
490
+
491
+ @staticmethod
492
+ def empty_cache() -> None:
493
+ calls.append(("empty_cache", None))
494
+
495
+ fake_torch = type("FakeTorch", (), {"cuda": _FakeCuda})
496
+ monkeypatch.setattr(chartqa_core, "_try_import_torch", lambda: fake_torch)
497
+
498
+ chartqa_core._release_evaluation_cuda_cache(
499
+ ChartQAEvaluationConfig(release_cuda_cache=True),
500
+ device="cuda:1",
501
+ )
502
+ assert calls == [("synchronize", "cuda:1"), ("empty_cache", None)]
503
+
504
+ calls.clear()
505
+ chartqa_core._release_evaluation_cuda_cache(
506
+ ChartQAEvaluationConfig(release_cuda_cache=False),
507
+ device="cuda:1",
508
+ )
509
+ assert calls == []
510
+
511
+
512
  def test_final_summary_keeps_legacy_completed_evaluation_marker() -> None:
513
  lines: list[str] = []
514
 
tests/test_chartqa_teacher_gate.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from data_utils.chart.teacher_gate import (
9
+ DEFAULT_CONFIDENCE_KEY,
10
+ SCHEMA_VERSION,
11
+ apply_gate_decision,
12
+ calibrate_confidence_threshold,
13
+ chartqa_dataset_fingerprint,
14
+ chartqa_sample_fingerprint,
15
+ filter_chartqa_rows_with_teacher_gate,
16
+ validate_teacher_gate_cache,
17
+ )
18
+ from scripts.reapply_chartqa_teacher_gate_calibration import main as reapply_calibration
19
+
20
+
21
+ def _row(index: int) -> dict:
22
+ return {
23
+ "question": f"Question {index}?",
24
+ "answer": str(index),
25
+ "image": f"/old/root/train_{index:06d}.png",
26
+ "visual_fact_deplot": json.dumps(
27
+ {"source": "google/deplot", "parsed_table": f"label | value\na | {index}"}
28
+ ),
29
+ }
30
+
31
+
32
+ def _record(row: dict, index: int, confidence: float, correct: bool) -> dict:
33
+ return {
34
+ "schema_version": SCHEMA_VERSION,
35
+ "source_index": index,
36
+ "sample_fingerprint": chartqa_sample_fingerprint(row),
37
+ "teacher_output": f"Answer: {index}",
38
+ "parsed_answer": str(index),
39
+ "teacher_correct": correct,
40
+ "parse_failed": False,
41
+ "placeholder": False,
42
+ "clipped": False,
43
+ "answer_span_found": True,
44
+ "confidence": {DEFAULT_CONFIDENCE_KEY: confidence},
45
+ }
46
+
47
+
48
+ def test_fingerprint_is_path_independent_and_accepts_prepared_answer() -> None:
49
+ raw = _row(7)
50
+ prepared = {
51
+ **raw,
52
+ "question_wo_prompt": raw["question"],
53
+ "question": None,
54
+ "reference_answer": "Answer: 7",
55
+ "answer": "Answer: 7",
56
+ "image": "/new/workspace/train_000007.png",
57
+ }
58
+ assert chartqa_sample_fingerprint(raw) == chartqa_sample_fingerprint(prepared)
59
+
60
+
61
+ def test_calibration_uses_maximum_coverage_threshold_with_ties() -> None:
62
+ rows = [_row(index) for index in range(5)]
63
+ records = [
64
+ _record(rows[0], 0, 0.95, True),
65
+ _record(rows[1], 1, 0.80, True),
66
+ _record(rows[2], 2, 0.80, False),
67
+ _record(rows[3], 3, 0.50, True),
68
+ _record(rows[4], 4, 0.20, False),
69
+ ]
70
+ calibration = calibrate_confidence_threshold(
71
+ records, target_precision=0.70, min_coverage=0.20
72
+ )
73
+ assert calibration.threshold == pytest.approx(0.5)
74
+ assert calibration.retained_count == 4
75
+ assert calibration.achieved_precision == pytest.approx(0.75)
76
+
77
+
78
+ def test_calibration_fails_when_precision_target_is_unreachable() -> None:
79
+ rows = [_row(index) for index in range(4)]
80
+ records = [
81
+ _record(row, index, 1.0 - index * 0.1, correct=False)
82
+ for index, row in enumerate(rows)
83
+ ]
84
+ with pytest.raises(ValueError, match="could not meet"):
85
+ calibrate_confidence_threshold(
86
+ records, target_precision=0.9, min_coverage=0.5
87
+ )
88
+
89
+
90
+ @pytest.mark.parametrize(
91
+ "mutation",
92
+ [
93
+ {"teacher_correct": False},
94
+ {"parse_failed": True},
95
+ {"placeholder": True},
96
+ {"clipped": True},
97
+ {"answer_span_found": False},
98
+ ],
99
+ )
100
+ def test_hard_gate_rejects_each_invalid_condition(mutation: dict) -> None:
101
+ row = _row(0)
102
+ record = _record(row, 0, 0.9, True) | mutation
103
+ decided = apply_gate_decision(
104
+ record, confidence_key=DEFAULT_CONFIDENCE_KEY, threshold=0.5
105
+ )
106
+ assert decided["eligible"] is False
107
+
108
+
109
+ def test_filter_validates_complete_cache_and_excludes_failed_rows(tmp_path) -> None:
110
+ rows = [_row(index) for index in range(3)]
111
+ records = [
112
+ apply_gate_decision(
113
+ _record(row, index, confidence=0.9 - index * 0.2, correct=index != 1),
114
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
115
+ threshold=0.6,
116
+ )
117
+ for index, row in enumerate(rows)
118
+ ]
119
+ cache = tmp_path / "train.jsonl"
120
+ cache.write_text(
121
+ "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8"
122
+ )
123
+ manifest = {
124
+ "schema_version": SCHEMA_VERSION,
125
+ "complete": True,
126
+ "record_count": len(records),
127
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
128
+ "calibration": {
129
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
130
+ "threshold": 0.6,
131
+ },
132
+ "summary": {
133
+ "teacher_accuracy": 2 / 3,
134
+ "eligible_rate": 1 / 3,
135
+ "placeholder_rate": 0.0,
136
+ },
137
+ }
138
+ manifest_path = tmp_path / "manifest.json"
139
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
140
+
141
+ kept, stats = filter_chartqa_rows_with_teacher_gate(
142
+ rows,
143
+ {
144
+ "enabled": True,
145
+ "cache_path": str(cache),
146
+ "manifest_path": str(manifest_path),
147
+ },
148
+ )
149
+ assert [row["answer"] for row in kept] == ["0"]
150
+ assert stats["input_rows"] == 3
151
+ assert stats["kept_rows"] == 1
152
+ assert stats["excluded_rows"] == 2
153
+ assert kept[0]["_teacher_gate_teacher_output"] == "Answer: 0"
154
+ assert kept[0]["_teacher_gate_cache_accuracy"] == pytest.approx(2 / 3)
155
+ assert kept[0]["_teacher_gate_cache_eligible_rate"] == pytest.approx(1 / 3)
156
+
157
+
158
+ def test_hard_correct_keeps_low_confidence_correct_and_rejects_malformed(tmp_path) -> None:
159
+ rows = [_row(index) for index in range(4)]
160
+ raw_records = [
161
+ _record(rows[0], 0, confidence=0.95, correct=True),
162
+ _record(rows[1], 1, confidence=0.20, correct=True),
163
+ _record(rows[2], 2, confidence=0.99, correct=False),
164
+ _record(rows[3], 3, confidence=0.99, correct=True) | {"placeholder": True},
165
+ ]
166
+ records = [
167
+ apply_gate_decision(
168
+ record,
169
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
170
+ threshold=0.8,
171
+ )
172
+ for record in raw_records
173
+ ]
174
+ cache = tmp_path / "train.jsonl"
175
+ cache.write_text(
176
+ "".join(json.dumps(record) + "\n" for record in records),
177
+ encoding="utf-8",
178
+ )
179
+ manifest = tmp_path / "train.jsonl.manifest.json"
180
+ manifest.write_text(
181
+ json.dumps(
182
+ {
183
+ "schema_version": SCHEMA_VERSION,
184
+ "complete": True,
185
+ "record_count": len(records),
186
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
187
+ "calibration": {
188
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
189
+ "threshold": 0.8,
190
+ },
191
+ "summary": {"teacher_accuracy": 0.75, "eligible_rate": 0.25},
192
+ }
193
+ ),
194
+ encoding="utf-8",
195
+ )
196
+
197
+ legacy, legacy_stats = filter_chartqa_rows_with_teacher_gate(
198
+ rows,
199
+ {"enabled": True, "cache_path": str(cache), "manifest_path": str(manifest)},
200
+ )
201
+ hard_correct, hard_stats = filter_chartqa_rows_with_teacher_gate(
202
+ rows,
203
+ {
204
+ "enabled": True,
205
+ "selection_mode": "hard_correct",
206
+ "expected_selected_rows": 2,
207
+ "cache_path": str(cache),
208
+ "manifest_path": str(manifest),
209
+ },
210
+ )
211
+
212
+ assert [row["answer"] for row in legacy] == ["0"]
213
+ assert legacy_stats["selection_mode"] == "eligible"
214
+ assert [row["answer"] for row in hard_correct] == ["0", "1"]
215
+ assert hard_stats["hard_pass_rows"] == 2
216
+ assert hard_stats["legacy_eligible_rows"] == 1
217
+ assert hard_stats["low_confidence_correct_added_rows"] == 1
218
+ assert hard_correct[1]["_teacher_gate_confidence_pass"] is False
219
+
220
+
221
+ def test_teacher_gate_expected_selected_rows_fails_closed(tmp_path) -> None:
222
+ rows = [_row(0)]
223
+ record = apply_gate_decision(
224
+ _record(rows[0], 0, 0.2, True),
225
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
226
+ threshold=0.8,
227
+ )
228
+ cache = tmp_path / "train.jsonl"
229
+ cache.write_text(json.dumps(record) + "\n", encoding="utf-8")
230
+ manifest = tmp_path / "train.jsonl.manifest.json"
231
+ manifest.write_text(
232
+ json.dumps(
233
+ {
234
+ "schema_version": SCHEMA_VERSION,
235
+ "complete": True,
236
+ "record_count": 1,
237
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
238
+ "calibration": {
239
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
240
+ "threshold": 0.8,
241
+ },
242
+ }
243
+ ),
244
+ encoding="utf-8",
245
+ )
246
+ with pytest.raises(ValueError, match="selected-row count mismatch"):
247
+ filter_chartqa_rows_with_teacher_gate(
248
+ rows,
249
+ {
250
+ "enabled": True,
251
+ "selection_mode": "hard_correct",
252
+ "expected_selected_rows": 2,
253
+ "cache_path": str(cache),
254
+ "manifest_path": str(manifest),
255
+ },
256
+ )
257
+
258
+
259
+ @pytest.mark.parametrize(
260
+ ("selection_mode", "expected"),
261
+ [("eligible", 1590), ("hard_correct", 3220), ("all", 4576)],
262
+ )
263
+ def test_checked_in_chartqa_gate_has_expected_selection_counts(
264
+ selection_mode: str,
265
+ expected: int,
266
+ ) -> None:
267
+ root = Path(__file__).resolve().parents[1]
268
+ data_path = root / "data/chartqa/train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json"
269
+ cache_path = root / "data/chartqa/teacher_gate/llava_onevision_7b_deplot_greedy/train.jsonl"
270
+ manifest_path = Path(f"{cache_path}.manifest.json")
271
+ if not data_path.is_file() or not cache_path.is_file() or not manifest_path.is_file():
272
+ pytest.skip("checked-in/local ChartQA gate artifacts are unavailable")
273
+ rows = json.loads(data_path.read_text(encoding="utf-8"))
274
+ rows = [row for row in rows if row.get("human_or_machine", 0) == 0]
275
+ selected, stats = filter_chartqa_rows_with_teacher_gate(
276
+ rows,
277
+ {
278
+ "enabled": True,
279
+ "selection_mode": selection_mode,
280
+ "expected_selected_rows": expected,
281
+ "cache_path": str(cache_path),
282
+ "manifest_path": str(manifest_path),
283
+ "require_validation_calibration": True,
284
+ },
285
+ )
286
+ assert len(rows) == 4576
287
+ assert len(selected) == expected
288
+ assert stats["hard_pass_rows"] == 3220
289
+ assert stats["legacy_eligible_rows"] == 1590
290
+
291
+
292
+ def test_filter_fails_closed_on_dataset_change(tmp_path) -> None:
293
+ rows = [_row(0)]
294
+ record = apply_gate_decision(
295
+ _record(rows[0], 0, 0.9, True),
296
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
297
+ threshold=0.5,
298
+ )
299
+ cache = tmp_path / "train.jsonl"
300
+ cache.write_text(json.dumps(record) + "\n", encoding="utf-8")
301
+ manifest_path = tmp_path / "manifest.json"
302
+ manifest_path.write_text(
303
+ json.dumps(
304
+ {
305
+ "schema_version": SCHEMA_VERSION,
306
+ "complete": True,
307
+ "record_count": 1,
308
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
309
+ "calibration": {
310
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
311
+ "threshold": 0.5,
312
+ },
313
+ }
314
+ ),
315
+ encoding="utf-8",
316
+ )
317
+ changed = [{**rows[0], "answer": "different"}]
318
+ with pytest.raises(ValueError, match="dataset fingerprint"):
319
+ filter_chartqa_rows_with_teacher_gate(
320
+ changed,
321
+ {
322
+ "enabled": True,
323
+ "cache_path": str(cache),
324
+ "manifest_path": str(manifest_path),
325
+ },
326
+ )
327
+
328
+
329
+ def test_validation_rejects_cache_decisions_from_a_different_threshold(tmp_path) -> None:
330
+ rows = [_row(0)]
331
+ record = apply_gate_decision(
332
+ _record(rows[0], 0, 0.7, True),
333
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
334
+ threshold=0.5,
335
+ )
336
+ cache = tmp_path / "train.jsonl"
337
+ cache.write_text(json.dumps(record) + "\n", encoding="utf-8")
338
+ manifest = tmp_path / "train.jsonl.manifest.json"
339
+ manifest.write_text(
340
+ json.dumps(
341
+ {
342
+ "schema_version": SCHEMA_VERSION,
343
+ "complete": True,
344
+ "record_count": 1,
345
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
346
+ "calibration": {
347
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
348
+ "threshold": 0.8,
349
+ },
350
+ }
351
+ ),
352
+ encoding="utf-8",
353
+ )
354
+
355
+ with pytest.raises(ValueError, match="stale confidence_gate_pass"):
356
+ validate_teacher_gate_cache(rows, cache_path=cache, manifest_path=manifest)
357
+
358
+
359
+ def test_reapply_uses_validation_manifest_without_teacher_regeneration(tmp_path) -> None:
360
+ rows = [_row(0), _row(1)]
361
+ records = [
362
+ apply_gate_decision(
363
+ _record(row, index, confidence=confidence, correct=True),
364
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
365
+ threshold=0.0,
366
+ )
367
+ for index, (row, confidence) in enumerate(zip(rows, (0.9, 0.4)))
368
+ ]
369
+ cache = tmp_path / "train.jsonl"
370
+ cache.write_text(
371
+ "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8"
372
+ )
373
+ train_manifest = tmp_path / "train.jsonl.manifest.json"
374
+ train_manifest.write_text(
375
+ json.dumps(
376
+ {
377
+ "schema_version": SCHEMA_VERSION,
378
+ "complete": True,
379
+ "split": "train",
380
+ "record_count": 2,
381
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
382
+ "calibration": {
383
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
384
+ "threshold": 0.0,
385
+ },
386
+ }
387
+ ),
388
+ encoding="utf-8",
389
+ )
390
+ calibration_manifest = tmp_path / "validation.jsonl.manifest.json"
391
+ calibration_manifest.write_text(
392
+ json.dumps(
393
+ {
394
+ "schema_version": SCHEMA_VERSION,
395
+ "complete": True,
396
+ "split": "validation",
397
+ "dataset_fingerprint": "validation-fingerprint",
398
+ "calibration": {
399
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
400
+ "threshold": 0.8,
401
+ "target_precision": 0.9,
402
+ "achieved_precision": 0.9,
403
+ },
404
+ }
405
+ ),
406
+ encoding="utf-8",
407
+ )
408
+
409
+ assert reapply_calibration(
410
+ [
411
+ "--train-cache",
412
+ str(cache),
413
+ "--calibration-manifest",
414
+ str(calibration_manifest),
415
+ ]
416
+ ) == 0
417
+ updated, manifest = validate_teacher_gate_cache(
418
+ rows,
419
+ cache_path=cache,
420
+ manifest_path=train_manifest,
421
+ )
422
+ assert [record["eligible"] for record in updated] == [True, False]
423
+ assert manifest["calibration"]["source_split"] == "validation"
424
+ assert manifest["decision_source"].startswith("validation_calibrated")
425
+ validate_teacher_gate_cache(
426
+ rows,
427
+ cache_path=cache,
428
+ manifest_path=train_manifest,
429
+ require_validation_calibration=True,
430
+ )
431
+
432
+
433
+ def test_validation_calibration_requirement_rejects_train_self_calibration(
434
+ tmp_path,
435
+ ) -> None:
436
+ rows = [_row(0)]
437
+ record = apply_gate_decision(
438
+ _record(rows[0], 0, 0.9, True),
439
+ confidence_key=DEFAULT_CONFIDENCE_KEY,
440
+ threshold=0.5,
441
+ )
442
+ cache = tmp_path / "train.jsonl"
443
+ cache.write_text(json.dumps(record) + "\n", encoding="utf-8")
444
+ manifest = tmp_path / "train.jsonl.manifest.json"
445
+ manifest.write_text(
446
+ json.dumps(
447
+ {
448
+ "schema_version": SCHEMA_VERSION,
449
+ "complete": True,
450
+ "split": "train",
451
+ "record_count": 1,
452
+ "dataset_fingerprint": chartqa_dataset_fingerprint(rows),
453
+ "calibration": {
454
+ "confidence_key": DEFAULT_CONFIDENCE_KEY,
455
+ "threshold": 0.5,
456
+ "target_precision": 0.9,
457
+ "achieved_precision": 1.0,
458
+ },
459
+ }
460
+ ),
461
+ encoding="utf-8",
462
+ )
463
+
464
+ with pytest.raises(ValueError, match="validation-calibrated"):
465
+ validate_teacher_gate_cache(
466
+ rows,
467
+ cache_path=cache,
468
+ manifest_path=manifest,
469
+ require_validation_calibration=True,
470
+ )
tests/test_checkpoint_eval_policy.py CHANGED
@@ -55,6 +55,68 @@ def test_tie_resets_low_score_streak_without_overwriting_best() -> None:
55
  assert policy.state.best_step == 1
56
 
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  def test_policy_state_round_trip_preserves_best_and_streak() -> None:
59
  policy = CheckpointEvaluationPolicy(patience=3)
60
  policy.observe(0.5, step=10)
@@ -69,6 +131,18 @@ def test_policy_state_round_trip_preserves_best_and_streak() -> None:
69
  assert result.evaluation_count == 3
70
 
71
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def test_callback_state_round_trip_restores_policy_for_resume() -> None:
73
  callback = CheckpointEvaluationTriggerCallback(patience=3, tie_policy="reset")
74
  callback.policy.observe(0.5, step=10)
@@ -102,6 +176,7 @@ def test_callback_sidecar_persists_non_improved_streak_and_train_begin_restores_
102
  "lower_score_streak": 1,
103
  "evaluation_count": 2,
104
  "stop_requested": False,
 
105
  }
106
 
107
  resumed = CheckpointEvaluationTriggerCallback(patience=3)
@@ -141,9 +216,67 @@ def test_new_best_is_published_only_after_native_checkpoint_on_save(tmp_path: Pa
141
  "lower_score_streak": 0,
142
  "evaluation_count": 1,
143
  "stop_requested": False,
 
144
  }
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def test_terminal_sidecar_state_stops_a_resumed_training_run(tmp_path: Path) -> None:
148
  (tmp_path / "checkpoint-1").mkdir()
149
  callback = CheckpointEvaluationTriggerCallback(output_dir=tmp_path, patience=1)
 
55
  assert policy.state.best_step == 1
56
 
57
 
58
+ def test_dynamic_step_zero_baseline_never_saves_or_blocks_and_counts_non_improvements() -> None:
59
+ policy = CheckpointEvaluationPolicy(patience=3, tie_policy="count")
60
+
61
+ baseline = policy.establish_external_baseline(0.21, step=0)
62
+ assert (baseline.best_score, baseline.best_step, baseline.evaluation_count) == (0.21, 0, 0)
63
+ assert baseline.best_is_external is True
64
+
65
+ lower = policy.observe(0.20, step=10)
66
+ tie = policy.observe(0.21, step=25)
67
+ terminal_tie = policy.observe(0.21, step=50)
68
+
69
+ assert (lower.should_save, lower.should_stop, lower.lower_score_streak) == (False, False, 1)
70
+ assert (tie.should_save, tie.should_stop, tie.reason, tie.lower_score_streak) == (
71
+ False,
72
+ False,
73
+ "tie_counted",
74
+ 2,
75
+ )
76
+ assert (terminal_tie.should_save, terminal_tie.should_stop, terminal_tie.reason) == (
77
+ False,
78
+ True,
79
+ "patience_exhausted",
80
+ )
81
+
82
+
83
+ def test_dynamic_step_zero_baseline_saves_only_a_strict_improvement() -> None:
84
+ policy = CheckpointEvaluationPolicy(patience=3, tie_policy="count")
85
+ policy.establish_external_baseline(0.21, step=0)
86
+
87
+ improved = policy.observe(0.22, step=10)
88
+
89
+ assert (improved.should_save, improved.should_stop, improved.reason) == (True, False, "improved")
90
+ assert (improved.best_score, improved.best_step, improved.best_is_external) == (0.22, 10, False)
91
+
92
+
93
+ def test_patience_warmup_monitors_drops_but_still_saves_improvements() -> None:
94
+ policy = CheckpointEvaluationPolicy(
95
+ patience=3,
96
+ tie_policy="count",
97
+ patience_start_step=200,
98
+ )
99
+ policy.establish_external_baseline(0.30, step=0)
100
+
101
+ lower = policy.observe(0.20, step=10)
102
+ tie = policy.observe(0.30, step=100)
103
+ improved = policy.observe(0.31, step=150)
104
+ first_counted = policy.observe(0.30, step=200)
105
+ second_counted = policy.observe(0.31, step=300)
106
+ stopped = policy.observe(0.29, step=400)
107
+
108
+ assert (lower.reason, lower.lower_score_streak, lower.should_stop) == (
109
+ "patience_warmup_lower",
110
+ 0,
111
+ False,
112
+ )
113
+ assert (tie.reason, tie.lower_score_streak) == ("patience_warmup_tie", 0)
114
+ assert (improved.should_save, improved.best_step) == (True, 150)
115
+ assert first_counted.lower_score_streak == 1
116
+ assert second_counted.lower_score_streak == 2
117
+ assert (stopped.should_stop, stopped.reason) == (True, "patience_exhausted")
118
+
119
+
120
  def test_policy_state_round_trip_preserves_best_and_streak() -> None:
121
  policy = CheckpointEvaluationPolicy(patience=3)
122
  policy.observe(0.5, step=10)
 
131
  assert result.evaluation_count == 3
132
 
133
 
134
+ def test_policy_state_round_trip_preserves_patience_start_step() -> None:
135
+ policy = CheckpointEvaluationPolicy(
136
+ patience=3,
137
+ tie_policy="count",
138
+ patience_start_step=200,
139
+ )
140
+ policy.establish_external_baseline(0.5)
141
+ resumed = CheckpointEvaluationPolicy.from_state_dict(policy.state_dict())
142
+ assert resumed.patience_start_step == 200
143
+ assert resumed.observe(0.4, step=100).lower_score_streak == 0
144
+
145
+
146
  def test_callback_state_round_trip_restores_policy_for_resume() -> None:
147
  callback = CheckpointEvaluationTriggerCallback(patience=3, tie_policy="reset")
148
  callback.policy.observe(0.5, step=10)
 
176
  "lower_score_streak": 1,
177
  "evaluation_count": 2,
178
  "stop_requested": False,
179
+ "best_is_external": False,
180
  }
181
 
182
  resumed = CheckpointEvaluationTriggerCallback(patience=3)
 
216
  "lower_score_streak": 0,
217
  "evaluation_count": 1,
218
  "stop_requested": False,
219
+ "best_is_external": False,
220
  }
221
 
222
 
223
+ def test_external_baseline_only_saves_a_strict_improvement() -> None:
224
+ policy = CheckpointEvaluationPolicy(patience=3)
225
+ policy.establish_external_baseline(0.2828125, step=0)
226
+
227
+ tied = policy.observe(0.2828125, step=10)
228
+ improved = policy.observe(0.30, step=25)
229
+
230
+ assert (tied.should_save, tied.reason, tied.best_is_external) == (
231
+ False,
232
+ "tie_reset",
233
+ True,
234
+ )
235
+ assert (improved.should_save, improved.reason, improved.best_step) == (
236
+ True,
237
+ "improved",
238
+ 25,
239
+ )
240
+ assert improved.best_is_external is False
241
+ assert policy.state.best_is_external is False
242
+
243
+
244
+ def test_external_baseline_sidecar_restores_without_a_checkpoint_directory(
245
+ tmp_path: Path,
246
+ ) -> None:
247
+ callback = CheckpointEvaluationTriggerCallback(output_dir=tmp_path)
248
+ callback.policy.establish_external_baseline(0.2828125, step=0)
249
+ callback.policy.observe(0.2828125, step=10)
250
+ callback.persist(is_world_process_zero=True)
251
+
252
+ resumed = CheckpointEvaluationTriggerCallback()
253
+ resumed.on_train_begin(
254
+ SimpleNamespace(output_dir=str(tmp_path)),
255
+ SimpleNamespace(is_world_process_zero=True),
256
+ SimpleNamespace(should_training_stop=False),
257
+ )
258
+
259
+ assert resumed.policy.state.best_is_external is True
260
+ assert resumed.policy.state.best_score == 0.2828125
261
+ assert resumed.policy.state.evaluation_count == 1
262
+
263
+
264
+ def test_trigger_callback_schedules_irregular_and_regular_steps() -> None:
265
+ callback = CheckpointEvaluationTriggerCallback(
266
+ gate_steps=[10, 25, 50],
267
+ regular_steps=100,
268
+ )
269
+
270
+ triggered: list[int] = []
271
+ for step in (9, 10, 11, 25, 50, 99, 100, 101, 200):
272
+ control = SimpleNamespace(should_save=False, should_evaluate=False)
273
+ callback.on_step_end(None, SimpleNamespace(global_step=step), control)
274
+ if callback.consume_checkpoint_evaluation():
275
+ triggered.append(step)
276
+
277
+ assert triggered == [10, 25, 50, 100, 200]
278
+
279
+
280
  def test_terminal_sidecar_state_stops_a_resumed_training_run(tmp_path: Path) -> None:
281
  (tmp_path / "checkpoint-1").mkdir()
282
  callback = CheckpointEvaluationTriggerCallback(output_dir=tmp_path, patience=1)
tests/test_deepspeed_utils.py CHANGED
@@ -14,6 +14,7 @@ from opsd_utils.deepspeed_utils import (
14
  student_forward_chunk_size,
15
  sync_global_max_count,
16
  sync_global_sum_count,
 
17
  uses_deepspeed_json_file,
18
  )
19
 
@@ -40,7 +41,6 @@ def test_zero2_config_detected(monkeypatch):
40
  assert student_forward_chunk_size(32, has_vision=True) == 32
41
  assert student_forward_chunk_size(32, has_vision=False) == 32
42
 
43
-
44
  def test_ddp_config_not_deepspeed(monkeypatch):
45
  monkeypatch.setenv("ACCELERATE_CONFIG", "default_config.yaml")
46
  assert not is_deepspeed_accelerate_config()
@@ -61,3 +61,29 @@ def test_sync_global_sum_count_single_process():
61
 
62
  assert sync_global_sum_count(3, torch.device("cpu"), 1) == 3
63
  assert sync_global_sum_count(0, torch.device("cpu"), 1) == 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  student_forward_chunk_size,
15
  sync_global_max_count,
16
  sync_global_sum_count,
17
+ sync_global_sum_counts,
18
  uses_deepspeed_json_file,
19
  )
20
 
 
41
  assert student_forward_chunk_size(32, has_vision=True) == 32
42
  assert student_forward_chunk_size(32, has_vision=False) == 32
43
 
 
44
  def test_ddp_config_not_deepspeed(monkeypatch):
45
  monkeypatch.setenv("ACCELERATE_CONFIG", "default_config.yaml")
46
  assert not is_deepspeed_accelerate_config()
 
61
 
62
  assert sync_global_sum_count(3, torch.device("cpu"), 1) == 3
63
  assert sync_global_sum_count(0, torch.device("cpu"), 1) == 0
64
+
65
+
66
+ def test_sync_global_sum_counts_single_process():
67
+ import torch
68
+
69
+ assert sync_global_sum_counts([3, 2], torch.device("cpu"), 1) == [3, 2]
70
+ assert sync_global_sum_counts([0, 0], torch.device("cpu"), 1) == [0, 0]
71
+
72
+
73
+ def test_runtime_deepspeed_environment_detected_without_config_path(monkeypatch, tmp_path):
74
+ ds_json = tmp_path / "ds_zero2.json"
75
+ ds_json.write_text('{"zero_optimization": {"stage": 2}}', encoding="utf-8")
76
+ for key in (
77
+ "ACCELERATE_CONFIG",
78
+ "ACCELERATE_CONFIG_FILE",
79
+ "ACCELERATE_DEEPSPEED_ZERO_STAGE",
80
+ ):
81
+ monkeypatch.delenv(key, raising=False)
82
+ monkeypatch.setenv("ACCELERATE_USE_DEEPSPEED", "true")
83
+ monkeypatch.setenv("ACCELERATE_DEEPSPEED_CONFIG_FILE", str(ds_json))
84
+
85
+ assert is_deepspeed_accelerate_config()
86
+ assert uses_deepspeed_json_file()
87
+ assert deepspeed_zero_stage() == 2
88
+ assert deepspeed_requires_single_student_forward()
89
+ assert student_forward_chunk_size(2, has_vision=True) == 2
tests/test_exopd_target.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+
5
+ import pytest
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from config.loader import load_config, validate_config
10
+ from opsd_utils.opsd_loss import (
11
+ compute_vlm_opsd_loss_masked_batch,
12
+ token_distillation_loss_per_row,
13
+ )
14
+ from trainer.DyMETrainer import build_unprivileged_reference_scoring_inputs
15
+
16
+
17
+ def test_exopd_rkl_matches_normalized_geometric_target_and_has_student_grad():
18
+ student = torch.tensor([[[0.4, -0.1, 0.2]]], requires_grad=True)
19
+ teacher = torch.tensor([[[1.2, -0.3, 0.1]]])
20
+ reference = torch.tensor([[[-0.2, 0.8, 0.0]]])
21
+ mask = torch.ones(1, 1)
22
+
23
+ actual = token_distillation_loss_per_row(
24
+ student,
25
+ teacher,
26
+ mask,
27
+ reference_logits=reference,
28
+ reward_scale=1.25,
29
+ loss_type="exopd_rkl",
30
+ )
31
+
32
+ s_log = F.log_softmax(student, dim=-1)
33
+ t_log = F.log_softmax(teacher, dim=-1)
34
+ r_log = F.log_softmax(reference, dim=-1)
35
+ scores = 1.25 * t_log - 0.25 * r_log
36
+ q_log = scores - torch.logsumexp(scores, dim=-1, keepdim=True)
37
+ expected = F.kl_div(q_log, s_log, reduction="none", log_target=True).sum(-1).squeeze(-1)
38
+ torch.testing.assert_close(actual, expected)
39
+
40
+ actual.mean().backward()
41
+ assert student.grad is not None
42
+ assert torch.isfinite(student.grad).all()
43
+ assert teacher.grad is None
44
+ assert reference.grad is None
45
+
46
+
47
+ def test_exopd_lambda_one_is_rkl_and_jointly_slices_three_vocabularies():
48
+ torch.manual_seed(7)
49
+ student = torch.randn(2, 3, 7)
50
+ teacher = torch.randn(2, 3, 8)
51
+ reference = torch.randn(2, 3, 6)
52
+ mask = torch.ones(2, 3)
53
+
54
+ exopd = token_distillation_loss_per_row(
55
+ student,
56
+ teacher,
57
+ mask,
58
+ reference_logits=reference,
59
+ reward_scale=1.0,
60
+ loss_type="exopd_rkl",
61
+ )
62
+ rkl = token_distillation_loss_per_row(
63
+ student[..., :6],
64
+ teacher[..., :6],
65
+ mask,
66
+ loss_type="rkl",
67
+ )
68
+ torch.testing.assert_close(exopd, rkl, rtol=1e-5, atol=1e-6)
69
+
70
+
71
+ def test_exopd_cached_path_fails_closed_without_reference_logits():
72
+ inputs = {
73
+ "prompt_ids": torch.ones(1, 2, dtype=torch.long),
74
+ "prompt_mask": torch.ones(1, 2, dtype=torch.long),
75
+ "completion_ids": torch.ones(1, 1, dtype=torch.long),
76
+ "completion_mask": torch.ones(1, 1, dtype=torch.long),
77
+ "teacher_completion_logits": torch.randn(1, 1, 4),
78
+ }
79
+ with pytest.raises(RuntimeError, match="reference_completion_logits"):
80
+ compute_vlm_opsd_loss_masked_batch(
81
+ object(),
82
+ [0],
83
+ [0],
84
+ inputs,
85
+ student_completion_logits=torch.randn(1, 1, 4, requires_grad=True),
86
+ loss_type="exopd_rkl",
87
+ reward_scale=1.25,
88
+ )
89
+
90
+
91
+ def test_unprivileged_reference_view_uses_student_prompt_and_image_rows():
92
+ inputs = {
93
+ "prompt_ids": torch.arange(12).view(3, 4),
94
+ "prompt_mask": torch.ones(3, 4, dtype=torch.long),
95
+ "pixel_values": torch.randn(3, 2, 5),
96
+ "img_sizes": torch.tensor([[10, 20], [30, 40], [50, 60]]),
97
+ "completion_ids": torch.ones(3, 2, dtype=torch.long),
98
+ "completion_mask": torch.ones(3, 2, dtype=torch.long),
99
+ "teacher_prompt_ids": torch.full((3, 7), 99),
100
+ "teacher_prompt_mask": torch.ones(3, 7, dtype=torch.long),
101
+ "teacher_pixel_values_list": [torch.randn(1, 9, 5) for _ in range(3)],
102
+ }
103
+ view = build_unprivileged_reference_scoring_inputs(inputs)
104
+ assert view["teacher_prompt_ids"] is inputs["prompt_ids"]
105
+ assert view["teacher_prompt_mask"] is inputs["prompt_mask"]
106
+ assert len(view["teacher_pixel_values_list"]) == 3
107
+ torch.testing.assert_close(view["teacher_pixel_values_list"][1], inputs["pixel_values"][1:2])
108
+ torch.testing.assert_close(view["teacher_image_sizes_list"][2], inputs["img_sizes"][2:3])
109
+ assert view["teacher_num_images"].tolist() == [1, 1, 1]
110
+
111
+
112
+ def test_exopd_config_contract_accepts_both_references_and_rejects_non_extrapolation():
113
+ base = load_config("opd_only")
114
+ for reference_mode in ("initial_student", "teacher_without_privilege"):
115
+ cfg = copy.deepcopy(base)
116
+ cfg["opsd"]["loss"].update(
117
+ loss_type="exopd_rkl",
118
+ reference_mode=reference_mode,
119
+ reward_scale=1.25,
120
+ )
121
+ cfg["opsd"]["teacher_trajectory"]["enabled"] = False
122
+ assert validate_config(cfg)["opsd"]["loss"]["reference_mode"] == reference_mode
123
+
124
+ invalid = copy.deepcopy(base)
125
+ invalid["opsd"]["loss"].update(
126
+ loss_type="exopd_rkl",
127
+ reference_mode="initial_student",
128
+ reward_scale=1.0,
129
+ )
130
+ invalid["opsd"]["teacher_trajectory"]["enabled"] = False
131
+ with pytest.raises(ValueError, match="reward_scale > 1.0"):
132
+ validate_config(invalid)
tests/test_opd_only_stage.py CHANGED
@@ -14,28 +14,74 @@ def test_opd_only_yaml_is_explicit_and_isolated():
14
  assert cfg["opsd"]["loss"]["acc_gate"] is False
15
  assert cfg["opsd"]["loss"]["grpo_weight"] == 0.0
16
  assert cfg["opsd"]["loss"]["sft_weight"] == 0.0
17
- assert cfg["opsd"]["teacher_probe"]["enabled"] is True
18
- assert cfg["opsd"]["teacher_trajectory"]["enabled"] is True
19
  assert cfg["opsd"]["teacher_trajectory"]["prompt_profile"] == "chartqa_structured_trajectory"
20
  assert cfg["opsd"]["teacher_trajectory"]["require_quality_for_loss"] is True
 
 
 
 
 
 
 
 
 
 
 
 
21
  assert cfg["dataset"]["train_dataset"].endswith(
22
  "train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json"
23
  )
24
  assert cfg["data_validation"] == {
25
  "strict": True,
26
  "require_real_deplot": True,
27
- "require_qwen_rewrite": True,
28
  "expected_samples": 4576,
29
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def test_opd_only_trajectory_fkl_restores_the_exact_generated_teacher_condition():
33
  source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text(
34
  encoding="utf-8"
35
  )
36
- assert 'result[f"teacher_traj_{key}"] = value' in source
37
- assert 'key.startswith("teacher_traj_teacher_")' in source
38
- assert 'traj_inputs[key[len("teacher_traj_"):]] = value' in source
 
39
  assert '"teacher_compact_indices": eligible' in source
40
 
41
 
@@ -95,20 +141,18 @@ def test_all_yaml_recipes_are_complete_and_do_not_contain_legacy_env_syntax():
95
  def test_project_paths_use_one_explicit_root_and_are_resolved_by_loader():
96
  root = Path(__file__).resolve().parents[1]
97
  config_dir = root / "config"
98
- legacy_root = "/data/junjie/agentic-rl-main"
99
  for path in sorted(config_dir.glob("*.yaml")):
100
  raw = path.read_text(encoding="utf-8")
101
  raw_cfg = yaml.safe_load(raw)
102
- assert raw_cfg["paths"] == {"project_root": "/data/junjie/agentic-rl-main"}, path
103
- assert raw.count(legacy_root) == 1, path
104
  loaded = load_config(str(path))
105
- assert loaded["paths"]["project_root"] == "/data/junjie/agentic-rl-main"
106
  assert "project://" not in repr(loaded)
107
 
108
  opd = load_config("opd_only")
109
- assert opd["model"]["pretrained_model_path"] == str(
110
- root / "outputs/sft-chart-llava_cot/final_checkpoint"
111
- )
112
  assert opd["dataset"]["train_dataset"] == str(
113
  root / "data/chartqa/train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json"
114
  )
 
14
  assert cfg["opsd"]["loss"]["acc_gate"] is False
15
  assert cfg["opsd"]["loss"]["grpo_weight"] == 0.0
16
  assert cfg["opsd"]["loss"]["sft_weight"] == 0.0
17
+ assert cfg["opsd"]["teacher_probe"]["enabled"] is False
18
+ assert cfg["opsd"]["teacher_trajectory"]["enabled"] is False
19
  assert cfg["opsd"]["teacher_trajectory"]["prompt_profile"] == "chartqa_structured_trajectory"
20
  assert cfg["opsd"]["teacher_trajectory"]["require_quality_for_loss"] is True
21
+ assert cfg["opsd"]["teacher_trajectory"]["max_loss_rows_per_rank"] == 2
22
+ assert cfg["opsd"]["privileged_providers"] == ["visual_facts_deplot"]
23
+ assert cfg["opsd"]["gate"]["require_format_for_opsd"] is True
24
+ assert cfg["opsd"]["gate"]["skip_degenerate_for_opsd"] is True
25
+ assert cfg["opsd"]["loss"]["assert_teacher_response_prefix_empty"] is True
26
+ assert cfg["training"]["dyme_args"]["learning_rate"] == 1e-6
27
+ assert cfg["opsd"]["strict_teacher_no_gold_context"] is True
28
+ assert cfg["opsd"]["loss"]["ignore_leading_whitespace_tokens"] is True
29
+ assert cfg["opsd"]["loss"]["max_leading_whitespace_tokens"] == 4
30
+ assert cfg["dataset"]["teacher_gate"]["selection_mode"] == "hard_correct"
31
+ assert cfg["dataset"]["teacher_gate"]["expected_selected_rows"] == 3220
32
+ assert cfg["training"]["dyme_args"]["num_train_epochs"] == 5
33
  assert cfg["dataset"]["train_dataset"].endswith(
34
  "train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json"
35
  )
36
  assert cfg["data_validation"] == {
37
  "strict": True,
38
  "require_real_deplot": True,
39
+ "require_qwen_rewrite": False,
40
  "expected_samples": 4576,
41
  }
42
+ assert cfg["checkpoint_eval"]["patience_start_step"] == 0
43
+ assert cfg["checkpoint_eval"]["gate_steps"] == [10, 25, 50, 75]
44
+ assert cfg["training"]["dyme_args"]["save_total_limit"] == 3
45
+
46
+
47
+ def test_opd_only_rejects_teacher_response_prefill_when_alignment_assertion_is_enabled():
48
+ from config.loader import validate_config
49
+
50
+ cfg = load_config("opd_only")
51
+ cfg["opsd"]["privileged_providers"].append("chartqa_answer_prefix")
52
+ with pytest.raises(ValueError, match="forbids chartqa_answer_prefix"):
53
+ validate_config(cfg)
54
+
55
+
56
+ def test_opd_only_branch_records_generation_diagnostics_before_returning():
57
+ source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text()
58
+ branch = source[source.index('if self.training_stage == "opd_only":') :]
59
+ assert branch.index("log_generation_diagnostics(") < branch.index("return self._build_opd_only_batch(")
60
+
61
+
62
+ def test_opd_routing_metrics_are_recorded_only_per_ga_microbatch():
63
+ source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text(
64
+ encoding="utf-8"
65
+ )
66
+ builder = source[
67
+ source.index(" def _build_opd_only_batch(") : source.index(
68
+ " def _record_cached_teacher_gate_batch("
69
+ )
70
+ ]
71
+ loss = source[source.index(" def _compute_opd_only_loss(") :]
72
+ assert '"routing/opd_route_count"' not in builder
73
+ assert loss.count('"routing/opd_route_count"') == 1
74
+ assert loss.count('"routing/opd_filtered_count"') == 1
75
 
76
 
77
  def test_opd_only_trajectory_fkl_restores_the_exact_generated_teacher_condition():
78
  source = (Path(__file__).resolve().parents[1] / "trainer" / "DyMETrainer.py").read_text(
79
  encoding="utf-8"
80
  )
81
+ assert 'result["teacher_traj_fkl_payload"] = fkl_payload' in source
82
+ assert 'result["teacher_traj_fkl_owner"] = fkl_owner' in source
83
+ assert 'fkl_payload[key] = value' in source
84
+ assert 'selection_scope="optimizer_step"' in source
85
  assert '"teacher_compact_indices": eligible' in source
86
 
87
 
 
141
  def test_project_paths_use_one_explicit_root_and_are_resolved_by_loader():
142
  root = Path(__file__).resolve().parents[1]
143
  config_dir = root / "config"
144
+ project_root = str(root)
145
  for path in sorted(config_dir.glob("*.yaml")):
146
  raw = path.read_text(encoding="utf-8")
147
  raw_cfg = yaml.safe_load(raw)
148
+ assert raw_cfg["paths"] == {"project_root": project_root}, path
149
+ assert raw.count(project_root) == 1, path
150
  loaded = load_config(str(path))
151
+ assert loaded["paths"]["project_root"] == project_root
152
  assert "project://" not in repr(loaded)
153
 
154
  opd = load_config("opd_only")
155
+ assert Path(opd["model"]["pretrained_model_path"]).is_dir()
 
 
156
  assert opd["dataset"]["train_dataset"] == str(
157
  root / "data/chartqa/train_new_prerefine_vf_full_real_deplot_fp32_qwen25.json"
158
  )
tests/test_opd_rollout_filter.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+
5
+ import pytest
6
+
7
+ from opsd_utils.rollout_filter import classify_opd_rollout_validity
8
+
9
+
10
+ def _classify(text: str, token_ids: list[int] | None = None, **kwargs):
11
+ return classify_opd_rollout_validity(
12
+ text,
13
+ token_ids or [1, 2, 3],
14
+ answer_flag="Answer:",
15
+ **kwargs,
16
+ )
17
+
18
+
19
+ def test_well_formed_rollout_is_selected_without_gold_input() -> None:
20
+ result = _classify("Reasoning from the chart.\nAnswer: 42")
21
+ assert result["valid"] is True
22
+ assert result["format_valid"] is True
23
+ assert result["answer_flag_count"] == 1
24
+ assert "answer" not in inspect.signature(classify_opd_rollout_validity).parameters
25
+
26
+
27
+ @pytest.mark.parametrize(
28
+ ("text", "reason"),
29
+ [
30
+ ("No final marker", "missing"),
31
+ ("Answer: 1\nAnswer: 2", "multiple"),
32
+ ("Reasoning\nAnswer: ", "empty"),
33
+ ("Answer: <short answer>", "placeholder"),
34
+ ],
35
+ )
36
+ def test_malformed_or_placeholder_rollouts_are_excluded(text: str, reason: str) -> None:
37
+ result = _classify(text)
38
+ assert result["valid"] is False
39
+ if reason == "missing":
40
+ assert result["answer_flag_count"] == 0
41
+ elif reason == "multiple":
42
+ assert result["answer_flag_count"] == 2
43
+ else:
44
+ assert result[f"{reason}_answer" if reason == "empty" else reason] is True
45
+
46
+
47
+ def test_repetition_filter_is_independent_of_answer_correctness() -> None:
48
+ result = _classify("Answer: value", token_ids=[7] * 8)
49
+ assert result["degenerate"] is True
50
+ assert result["valid"] is False
51
+
52
+
53
+ def test_legacy_format_setting_can_keep_missing_marker_but_never_placeholder() -> None:
54
+ assert _classify(
55
+ "plain answer", require_format=False, skip_degenerate=False
56
+ )["valid"] is True
57
+ assert _classify(
58
+ "<short answer>", require_format=False, skip_degenerate=False
59
+ )["valid"] is False
60
+
tests/test_opd_student_logits_only.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from types import SimpleNamespace
5
+
6
+ import torch
7
+
8
+ from trainer.DyMETrainer import DyMETrainer
9
+
10
+
11
+ class _ToyStudent:
12
+ def __init__(self, vocab_size: int = 11) -> None:
13
+ self.logit_seed = torch.nn.Parameter(torch.arange(vocab_size, dtype=torch.float32))
14
+ self.calls: list[int] = []
15
+
16
+ def __call__(self, *, input_ids, logits_to_keep, **_kwargs):
17
+ self.calls.append(int(logits_to_keep))
18
+ logits = self.logit_seed.view(1, 1, -1).expand(
19
+ input_ids.size(0), int(logits_to_keep), -1
20
+ )
21
+ return SimpleNamespace(logits=logits)
22
+
23
+
24
+ def _trainer() -> DyMETrainer:
25
+ trainer = DyMETrainer.__new__(DyMETrainer)
26
+ trainer.temperature = 1.0
27
+ trainer.args = SimpleNamespace(report_to=[])
28
+ trainer.accelerator = SimpleNamespace(is_main_process=False)
29
+ return trainer
30
+
31
+
32
+ def test_completion_logits_only_skips_selected_logprob_branch(monkeypatch) -> None:
33
+ module = importlib.import_module("trainer.DyMETrainer")
34
+ trainer = _trainer()
35
+ student = _ToyStudent()
36
+ input_ids = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=torch.long)
37
+ attention_mask = torch.ones_like(input_ids)
38
+
39
+ def _unexpected_logprob(*_args, **_kwargs):
40
+ raise AssertionError("log-prob branch must not run for OPD logits-only scoring")
41
+
42
+ monkeypatch.setattr(module, "selective_log_softmax", _unexpected_logprob)
43
+ logps, completion_logits = trainer._get_per_token_logps(
44
+ student,
45
+ input_ids,
46
+ attention_mask,
47
+ pixel_values=None,
48
+ image_sizes=None,
49
+ logits_to_keep=2,
50
+ return_completion_logits=True,
51
+ return_logps=False,
52
+ )
53
+
54
+ assert logps is None
55
+ assert completion_logits.shape == (2, 2, 11)
56
+ assert student.calls == [3]
57
+ completion_logits.sum().backward()
58
+ assert student.logit_seed.grad is not None
59
+
60
+
61
+ def test_default_path_keeps_selected_logprobs() -> None:
62
+ trainer = _trainer()
63
+ student = _ToyStudent()
64
+ input_ids = torch.tensor([[1, 2, 3, 4]], dtype=torch.long)
65
+ attention_mask = torch.ones_like(input_ids)
66
+
67
+ logps, completion_logits = trainer._get_per_token_logps(
68
+ student,
69
+ input_ids,
70
+ attention_mask,
71
+ pixel_values=None,
72
+ image_sizes=None,
73
+ logits_to_keep=2,
74
+ return_completion_logits=True,
75
+ )
76
+
77
+ assert logps is not None
78
+ assert logps.shape == (1, 2)
79
+ assert completion_logits.shape == (1, 2, 11)
tests/test_opd_template_health_check.py CHANGED
@@ -129,6 +129,30 @@ def test_health_check_accepts_substantive_full_cot(tmp_path: Path) -> None:
129
  assert payload["status"] == "ok"
130
 
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def test_health_check_reports_partial_goal_without_answer_drift(tmp_path: Path) -> None:
133
  code, payload = _run(
134
  tmp_path,
 
129
  assert payload["status"] == "ok"
130
 
131
 
132
+ def test_health_check_detects_answer_format_drift(tmp_path: Path) -> None:
133
+ code, payload = _run(
134
+ tmp_path,
135
+ [
136
+ {"rollout/answer_flag_rate": 0.5, "rollout/parse_fail_rate": 0.5},
137
+ {"rollout/answer_flag_rate": 0.4, "rollout/parse_fail_rate": 0.6},
138
+ ],
139
+ )
140
+ assert code == 7
141
+ assert payload["status"] == "answer_format_drift"
142
+
143
+
144
+ def test_health_check_detects_teacher_answer_span_alignment_drift(tmp_path: Path) -> None:
145
+ code, payload = _run(
146
+ tmp_path,
147
+ [
148
+ {"loss/jsd_answer_span": 0.6, "rollout/answer_flag_rate": 1.0},
149
+ {"loss/jsd_answer_span": 0.65, "rollout/answer_flag_rate": 1.0},
150
+ ],
151
+ )
152
+ assert code == 6
153
+ assert payload["status"] == "teacher_alignment_drift"
154
+
155
+
156
  def test_health_check_reports_partial_goal_without_answer_drift(tmp_path: Path) -> None:
157
  code, payload = _run(
158
  tmp_path,
tests/test_opdvr_reward_gate.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+
5
+ import pytest
6
+ import torch
7
+
8
+ from config.loader import load_config, validate_config
9
+ from opsd_utils.opsd_loss import opdvr_reward_gated_loss_per_row
10
+
11
+
12
+ def _one_token_case(*, correct: bool, teacher_prefers_action: bool):
13
+ student = torch.tensor([[[0.0, 0.0]]], requires_grad=True)
14
+ teacher = torch.tensor(
15
+ [[[2.0, 0.0]]] if teacher_prefers_action else [[[-2.0, 0.0]]]
16
+ )
17
+ loss, diagnostics = opdvr_reward_gated_loss_per_row(
18
+ student,
19
+ teacher,
20
+ torch.tensor([[0]]),
21
+ torch.ones(1, 1),
22
+ torch.tensor([correct]),
23
+ return_diagnostics=True,
24
+ )
25
+ loss.mean().backward()
26
+ return loss, student.grad, diagnostics
27
+
28
+
29
+ def test_correct_rollout_only_reinforces_teacher_preferred_sampled_token():
30
+ active_loss, active_grad, diagnostics = _one_token_case(
31
+ correct=True, teacher_prefers_action=True
32
+ )
33
+ assert active_loss.item() > 0.0
34
+ assert active_grad[0, 0, 0].item() < 0.0
35
+ assert diagnostics["positive_token_count"].item() == 1.0
36
+
37
+ zero_loss, zero_grad, diagnostics = _one_token_case(
38
+ correct=True, teacher_prefers_action=False
39
+ )
40
+ assert zero_loss.item() == pytest.approx(0.0)
41
+ torch.testing.assert_close(zero_grad, torch.zeros_like(zero_grad))
42
+ assert diagnostics["zero_token_count"].item() == 1.0
43
+
44
+
45
+ def test_wrong_rollout_only_suppresses_teacher_disfavored_sampled_token():
46
+ active_loss, active_grad, diagnostics = _one_token_case(
47
+ correct=False, teacher_prefers_action=False
48
+ )
49
+ assert active_loss.item() < 0.0
50
+ assert active_grad[0, 0, 0].item() > 0.0
51
+ assert diagnostics["negative_token_count"].item() == 1.0
52
+
53
+ zero_loss, zero_grad, diagnostics = _one_token_case(
54
+ correct=False, teacher_prefers_action=True
55
+ )
56
+ assert zero_loss.item() == pytest.approx(0.0)
57
+ torch.testing.assert_close(zero_grad, torch.zeros_like(zero_grad))
58
+ assert diagnostics["zero_token_count"].item() == 1.0
59
+
60
+
61
+ def test_optional_teacher_correctness_gate_is_fail_closed():
62
+ student = torch.tensor([[[0.0, 0.0]]], requires_grad=True)
63
+ teacher = torch.tensor([[[2.0, 0.0]]])
64
+ loss, diagnostics = opdvr_reward_gated_loss_per_row(
65
+ student,
66
+ teacher,
67
+ torch.tensor([[0]]),
68
+ torch.ones(1, 1),
69
+ torch.tensor([True]),
70
+ teacher_correct=torch.tensor([False]),
71
+ require_teacher_correct=True,
72
+ return_diagnostics=True,
73
+ )
74
+ loss.mean().backward()
75
+ assert loss.item() == pytest.approx(0.0)
76
+ torch.testing.assert_close(student.grad, torch.zeros_like(student.grad))
77
+ assert diagnostics["effective_row_count"].item() == 0.0
78
+
79
+
80
+ def test_mask_and_row_mean_match_manual_sampled_token_objective():
81
+ student = torch.tensor(
82
+ [
83
+ [[0.0, 0.0], [0.2, -0.2]],
84
+ [[0.0, 0.0], [0.0, 0.0]],
85
+ ],
86
+ requires_grad=True,
87
+ )
88
+ teacher = torch.tensor(
89
+ [
90
+ [[2.0, 0.0], [1.0, -1.0]],
91
+ [[-2.0, 0.0], [-2.0, 0.0]],
92
+ ]
93
+ )
94
+ ids = torch.tensor([[0, 0], [0, 0]])
95
+ mask = torch.tensor([[1.0, 0.0], [1.0, 1.0]])
96
+ losses = opdvr_reward_gated_loss_per_row(
97
+ student,
98
+ teacher,
99
+ ids,
100
+ mask,
101
+ torch.tensor([True, False]),
102
+ token_chunk_size=1,
103
+ )
104
+
105
+ student_logp = torch.log_softmax(student, dim=-1).gather(-1, ids.unsqueeze(-1)).squeeze(-1)
106
+ teacher_logp = torch.log_softmax(teacher, dim=-1).gather(-1, ids.unsqueeze(-1)).squeeze(-1)
107
+ ratio = (teacher_logp - student_logp).detach()
108
+ reward = torch.stack((ratio[0].clamp_min(0), ratio[1].clamp_max(0))) * mask
109
+ expected = (-reward * student_logp).sum(-1) / mask.sum(-1)
110
+ torch.testing.assert_close(losses, expected)
111
+
112
+
113
+ def test_opdvr_config_requires_full_annotation_mode_and_accepts_trajectory():
114
+ cfg = copy.deepcopy(load_config("opd_only"))
115
+ cfg["opsd"]["loss"].update(
116
+ loss_type="opdvr",
117
+ reward_gate={
118
+ "enabled": True,
119
+ "correct_threshold": 0.5,
120
+ "token_scope": "answer_span",
121
+ "require_teacher_correct": False,
122
+ "require_teacher_gate_metadata": True,
123
+ "max_abs_log_ratio": 0.0,
124
+ },
125
+ )
126
+ cfg["dataset"]["teacher_gate"].update(
127
+ selection_mode="all", expected_selected_rows=4576
128
+ )
129
+ cfg["opsd"]["teacher_trajectory"]["enabled"] = True
130
+ validated = validate_config(cfg)
131
+ assert validated["opsd"]["loss"]["reward_gate"]["token_scope"] == "answer_span"
132
+
133
+ invalid = copy.deepcopy(cfg)
134
+ invalid["dataset"]["teacher_gate"]["selection_mode"] = "hard_correct"
135
+ with pytest.raises(ValueError, match="selection_mode=all"):
136
+ validate_config(invalid)
tests/test_opsd_loss_mask.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+
5
+ from opsd_utils.opsd_loss import (
6
+ build_opsd_answer_diagnostic_masks,
7
+ build_opsd_loss_mask,
8
+ token_distillation_loss,
9
+ token_distillation_loss_per_row,
10
+ )
11
+
12
+
13
+ class TinyWhitespaceTokenizer:
14
+ all_special_ids = [0]
15
+ pieces = {
16
+ 0: "<special>",
17
+ 1: "\n",
18
+ 2: " ",
19
+ 3: "Answer",
20
+ 4: ":",
21
+ 5: "inside",
22
+ }
23
+
24
+ def decode(self, token_ids, **_kwargs):
25
+ return "".join(self.pieces[int(token_id)] for token_id in token_ids)
26
+
27
+
28
+ class TinyAnswerTokenizer(TinyWhitespaceTokenizer):
29
+ eos_token_id = 6
30
+ all_special_ids = [0, 6]
31
+ pieces = {
32
+ **TinyWhitespaceTokenizer.pieces,
33
+ 5: "42",
34
+ 6: "<eos>",
35
+ }
36
+
37
+ def encode(self, text, add_special_tokens=False):
38
+ assert add_special_tokens is False
39
+ variants = {
40
+ "Answer:": [3, 4],
41
+ " Answer:": [2, 3, 4],
42
+ "\nAnswer:": [1, 3, 4],
43
+ "\n\nAnswer:": [1, 1, 3, 4],
44
+ }
45
+ return variants.get(text, [])
46
+
47
+
48
+ def _mask(ids: list[list[int]], attention: list[list[int]], *, maximum: int = 4):
49
+ return build_opsd_loss_mask(
50
+ torch.tensor(ids, dtype=torch.long),
51
+ torch.tensor(attention, dtype=torch.long),
52
+ TinyWhitespaceTokenizer(),
53
+ ignore_leading_whitespace_tokens=True,
54
+ max_leading_whitespace_tokens=maximum,
55
+ )
56
+
57
+
58
+ def test_leading_whitespace_is_masked_but_semantic_and_internal_space_remain() -> None:
59
+ loss_mask, stats = _mask(
60
+ [[1, 1, 3, 2, 5], [3, 2, 5, 0, 0], [0, 3, 4, 0, 0]],
61
+ [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]],
62
+ )
63
+ assert loss_mask.tolist() == [
64
+ [0, 0, 1, 1, 1],
65
+ [1, 1, 1, 0, 0],
66
+ [1, 1, 1, 0, 0],
67
+ ]
68
+ assert stats["first_semantic_positions"].tolist() == [2, 0, 0]
69
+ assert stats["leading_whitespace_masked_counts"].tolist() == [2, 0, 0]
70
+ # A special token is never classified as semantic-free whitespace.
71
+ assert stats["valid_rows"].tolist() == [True, True, True]
72
+
73
+
74
+ def test_no_semantic_and_over_limit_rows_are_fully_excluded() -> None:
75
+ loss_mask, stats = _mask(
76
+ [[1, 2, 1, 2, 0, 0], [1, 1, 1, 1, 1, 3]],
77
+ [[1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1]],
78
+ maximum=4,
79
+ )
80
+ assert loss_mask.sum(dim=1).tolist() == [0, 0]
81
+ assert stats["no_semantic_rows"].tolist() == [True, False]
82
+ assert stats["leading_whitespace_over_limit_rows"].tolist() == [False, True]
83
+ assert stats["valid_rows"].tolist() == [False, False]
84
+
85
+
86
+ def test_disabled_whitespace_filter_preserves_legacy_loss_mask() -> None:
87
+ ids = torch.tensor([[1, 1, 3]], dtype=torch.long)
88
+ attention = torch.ones_like(ids)
89
+ loss_mask, stats = build_opsd_loss_mask(
90
+ ids,
91
+ attention,
92
+ TinyWhitespaceTokenizer(),
93
+ ignore_leading_whitespace_tokens=False,
94
+ )
95
+ assert torch.equal(loss_mask, attention)
96
+ assert stats["leading_whitespace_masked_counts"].sum().item() == 0
97
+
98
+
99
+ def test_answer_diagnostics_skip_fixed_marker_and_separate_eos() -> None:
100
+ ids = torch.tensor(
101
+ [
102
+ [1, 3, 4, 2, 5, 6],
103
+ [3, 4, 5, 2, 5, 6],
104
+ [1, 3, 5, 6, 0, 0],
105
+ ]
106
+ )
107
+ attention = torch.tensor(
108
+ [
109
+ [1, 1, 1, 1, 1, 1],
110
+ [1, 1, 1, 1, 1, 1],
111
+ [1, 1, 1, 1, 0, 0],
112
+ ]
113
+ )
114
+ stats = build_opsd_answer_diagnostic_masks(
115
+ ids,
116
+ attention,
117
+ TinyAnswerTokenizer(),
118
+ answer_flag="Answer:",
119
+ )
120
+ assert stats["first_answer_positions"].tolist() == [4, 2, -1]
121
+ assert stats["answer_span_mask"].tolist() == [
122
+ [0, 0, 0, 0, 1, 0],
123
+ [0, 0, 1, 1, 1, 0],
124
+ [0, 0, 0, 0, 0, 0],
125
+ ]
126
+ assert stats["eos_mask"].tolist() == [
127
+ [0, 0, 0, 0, 0, 1],
128
+ [0, 0, 0, 0, 0, 1],
129
+ [0, 0, 0, 1, 0, 0],
130
+ ]
131
+ assert stats["answer_marker_found_rows"].tolist() == [True, True, False]
132
+ assert stats["answer_span_valid_rows"].tolist() == [True, True, False]
133
+ assert stats["eos_found_rows"].tolist() == [True, True, True]
134
+
135
+
136
+ def test_masked_whitespace_has_zero_gradient_and_first_semantic_has_gradient() -> None:
137
+ torch.manual_seed(7)
138
+ ids = torch.tensor([[1, 3, 4]], dtype=torch.long)
139
+ attention = torch.ones_like(ids)
140
+ loss_mask, _ = build_opsd_loss_mask(
141
+ ids,
142
+ attention,
143
+ TinyWhitespaceTokenizer(),
144
+ ignore_leading_whitespace_tokens=True,
145
+ max_leading_whitespace_tokens=4,
146
+ )
147
+ student = torch.randn(1, 3, 19, requires_grad=True)
148
+ teacher = torch.randn(1, 3, 19)
149
+ loss = token_distillation_loss_per_row(
150
+ student,
151
+ teacher,
152
+ loss_mask.float(),
153
+ token_chunk_size=2,
154
+ ).mean()
155
+ loss.backward()
156
+ assert torch.count_nonzero(student.grad[:, 0]).item() == 0
157
+ assert student.grad[:, 1].abs().sum().item() > 0
158
+
159
+
160
+ def test_variable_rows_match_manual_valid_row_reference_and_diagnostics() -> None:
161
+ torch.manual_seed(11)
162
+ ids = torch.tensor([[1, 3, 4, 0], [3, 4, 0, 0], [1, 2, 1, 2]])
163
+ raw_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]])
164
+ loss_mask, mask_stats = build_opsd_loss_mask(
165
+ ids,
166
+ raw_mask,
167
+ TinyWhitespaceTokenizer(),
168
+ ignore_leading_whitespace_tokens=True,
169
+ max_leading_whitespace_tokens=4,
170
+ )
171
+ student = torch.randn(3, 4, 23, requires_grad=True)
172
+ teacher = torch.randn(3, 4, 23)
173
+ row_losses, diagnostics = token_distillation_loss_per_row(
174
+ student,
175
+ teacher,
176
+ loss_mask.float(),
177
+ raw_mask=raw_mask.float(),
178
+ first_semantic_positions=mask_stats["first_semantic_positions"],
179
+ token_chunk_size=2,
180
+ return_position_stats=True,
181
+ return_diagnostics=True,
182
+ )
183
+ expected = torch.stack(
184
+ [
185
+ token_distillation_loss(
186
+ student[row : row + 1],
187
+ teacher[row : row + 1],
188
+ loss_mask[row : row + 1].float(),
189
+ )
190
+ for row in range(2)
191
+ ]
192
+ )
193
+ assert torch.allclose(row_losses[:2], expected, atol=1e-6, rtol=1e-6)
194
+ assert row_losses[2].item() == 0.0
195
+ assert diagnostics["valid_row_count"].item() == 2
196
+ assert diagnostics["raw_position_0_count"].item() == 3
197
+ assert diagnostics["position_0_active_count"].item() == 1
198
+ assert diagnostics["first_semantic_count"].item() == 2
199
+
200
+
201
+ def test_answer_span_and_eos_distribution_diagnostics_are_separate() -> None:
202
+ torch.manual_seed(19)
203
+ ids = torch.tensor([[1, 3, 4, 2, 5, 6]])
204
+ raw_mask = torch.ones_like(ids)
205
+ answer_stats = build_opsd_answer_diagnostic_masks(
206
+ ids,
207
+ raw_mask,
208
+ TinyAnswerTokenizer(),
209
+ )
210
+ student = torch.randn(1, ids.size(1), 17, requires_grad=True)
211
+ teacher = torch.randn_like(student)
212
+ _, diagnostics = token_distillation_loss_per_row(
213
+ student,
214
+ teacher,
215
+ raw_mask.float(),
216
+ raw_mask=raw_mask.float(),
217
+ first_answer_positions=answer_stats["first_answer_positions"],
218
+ answer_span_mask=answer_stats["answer_span_mask"],
219
+ eos_mask=answer_stats["eos_mask"],
220
+ diagnostic_top_k=5,
221
+ return_position_stats=True,
222
+ return_diagnostics=True,
223
+ )
224
+ assert diagnostics["first_answer_count"].item() == 1
225
+ assert diagnostics["answer_span_count"].item() == 1
226
+ assert diagnostics["eos_count"].item() == 1
227
+ assert diagnostics["first_answer_sum"].item() >= 0.0
228
+ assert diagnostics["answer_span_sum"].item() >= 0.0
229
+ assert diagnostics["eos_sum"].item() >= 0.0
230
+ assert 0.0 <= diagnostics["answer_topk_overlap_sum"].item() <= 1.0
231
+ assert 0.0 <= diagnostics["answer_shared_mass_sum"].item() <= 1.0
tests/test_opsd_loss_teacher.py CHANGED
@@ -14,6 +14,8 @@ from opsd_utils.opsd_loss import (
14
  _trim_to_effective_completion,
15
  compute_vlm_opsd_loss_masked_batch,
16
  generalized_jsd_loss,
 
 
17
  token_distillation_loss,
18
  )
19
 
@@ -108,3 +110,275 @@ def test_token_distillation_loss_srkl_and_fkl():
108
  fkl = token_distillation_loss(student, teacher, mask, loss_type="fkl")
109
  assert srkl.ndim == 0 and srkl.requires_grad
110
  assert fkl.ndim == 0 and fkl.requires_grad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  _trim_to_effective_completion,
15
  compute_vlm_opsd_loss_masked_batch,
16
  generalized_jsd_loss,
17
+ precompute_teacher_completion_logits,
18
+ token_distillation_loss_per_row,
19
  token_distillation_loss,
20
  )
21
 
 
110
  fkl = token_distillation_loss(student, teacher, mask, loss_type="fkl")
111
  assert srkl.ndim == 0 and srkl.requires_grad
112
  assert fkl.ndim == 0 and fkl.requires_grad
113
+
114
+
115
+ def test_masked_batch_maps_compact_precomputed_logits_without_student_forward():
116
+ """Trajectory FKL can reuse one batched student forward for sparse rows."""
117
+ batch_size = 4
118
+ seq = 4
119
+ vocab = 8
120
+ device = torch.device("cpu")
121
+
122
+ student = MagicMock()
123
+ teacher = MagicMock()
124
+ param = torch.nn.Parameter(torch.zeros(1, device=device))
125
+ student.parameters = lambda: iter([param])
126
+ teacher.parameters = lambda: iter([param])
127
+
128
+ def fake_teacher_forward(**kwargs):
129
+ out = MagicMock()
130
+ batch_rows = int(kwargs["input_ids"].size(0))
131
+ seq_len = int(kwargs["input_ids"].size(1))
132
+ out.logits = torch.zeros(batch_rows, seq_len, vocab, device=device)
133
+ return out
134
+
135
+ teacher.side_effect = fake_teacher_forward
136
+ precomputed_logits = torch.randn(2, 2, vocab, device=device, requires_grad=True)
137
+ inputs = {
138
+ "prompt_ids": torch.ones(batch_size, seq, dtype=torch.long),
139
+ "prompt_mask": torch.ones(batch_size, seq, dtype=torch.long),
140
+ "pixel_values": torch.randn(batch_size, 3, 8, 8),
141
+ "teacher_prompt_ids": torch.ones(2, seq, dtype=torch.long),
142
+ "teacher_prompt_mask": torch.ones(2, seq, dtype=torch.long),
143
+ "teacher_compact_indices": [1, 3],
144
+ "completion_ids": torch.ones(batch_size, 2, dtype=torch.long),
145
+ "completion_mask": torch.ones(batch_size, 2, dtype=torch.long),
146
+ "teacher_num_images": torch.ones(2, dtype=torch.long),
147
+ }
148
+
149
+ loss = compute_vlm_opsd_loss_masked_batch(
150
+ student,
151
+ [3, 1],
152
+ list(range(batch_size)),
153
+ inputs,
154
+ processor=None,
155
+ teacher_model=teacher,
156
+ acc_gate=False,
157
+ student_completion_logits=precomputed_logits,
158
+ student_completion_logits_indices=[3, 1],
159
+ loss_type="fkl",
160
+ )
161
+ loss.backward()
162
+
163
+ assert student.call_count == 0
164
+ assert teacher.call_count == 2
165
+ assert precomputed_logits.grad is not None
166
+ assert torch.isfinite(precomputed_logits.grad).all()
167
+
168
+ def test_rowwise_chunked_loss_matches_historical_per_row_reduction():
169
+ torch.manual_seed(0)
170
+ student = torch.randn(3, 5, 17, requires_grad=True)
171
+ teacher = torch.randn(3, 5, 17)
172
+ mask = torch.tensor(
173
+ [
174
+ [1, 1, 1, 1, 1],
175
+ [1, 1, 1, 0, 0],
176
+ [1, 1, 0, 0, 0],
177
+ ],
178
+ dtype=torch.float32,
179
+ )
180
+ expected = torch.stack(
181
+ [
182
+ token_distillation_loss(
183
+ student[row : row + 1],
184
+ teacher[row : row + 1],
185
+ mask[row : row + 1],
186
+ loss_type="jsd",
187
+ beta=0.5,
188
+ )
189
+ for row in range(student.size(0))
190
+ ]
191
+ )
192
+ actual = token_distillation_loss_per_row(
193
+ student,
194
+ teacher,
195
+ mask,
196
+ loss_type="jsd",
197
+ beta=0.5,
198
+ token_chunk_size=2,
199
+ )
200
+ assert torch.allclose(actual, expected, atol=1e-6, rtol=1e-6)
201
+ actual.mean().backward()
202
+ assert student.grad is not None
203
+ assert torch.isfinite(student.grad).all()
204
+
205
+ def test_prefix_cache_precompute_matches_direct_batched_teacher_scoring():
206
+ class ToyTeacher:
207
+ def __init__(self, vocab: int):
208
+ self.param = torch.nn.Parameter(torch.zeros(1))
209
+ self.vocab = vocab
210
+ self.calls: list[tuple[int, int, bool]] = []
211
+
212
+ def parameters(self):
213
+ return iter([self.param])
214
+
215
+ def __call__(
216
+ self,
217
+ *,
218
+ input_ids,
219
+ logits_to_keep=None,
220
+ use_cache=False,
221
+ **kwargs,
222
+ ):
223
+ rows = int(input_ids.size(0))
224
+ keep = int(logits_to_keep or input_ids.size(1))
225
+ logits = torch.arange(self.vocab, dtype=torch.float32).view(1, 1, -1)
226
+ logits = logits.expand(rows, keep, -1).clone()
227
+ self.calls.append((rows, keep, bool(use_cache)))
228
+ out = type("Output", (), {})()
229
+ out.logits = logits
230
+ out.past_key_values = (
231
+ (torch.zeros(rows, 1, 1, 1),),
232
+ ) if use_cache else None
233
+ return out
234
+
235
+ rows, prompt_width, completion_width, vocab = 4, 3, 3, 11
236
+ inputs = {
237
+ "prompt_ids": torch.ones(rows, prompt_width, dtype=torch.long),
238
+ "prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),
239
+ "teacher_prompt_ids": torch.ones(rows, prompt_width, dtype=torch.long),
240
+ "teacher_prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),
241
+ "completion_ids": torch.ones(rows, completion_width, dtype=torch.long),
242
+ "completion_mask": torch.ones(rows, completion_width, dtype=torch.long),
243
+ "teacher_num_images": torch.ones(rows, dtype=torch.long),
244
+ }
245
+ teacher = ToyTeacher(vocab)
246
+ cached, prefix_stats = precompute_teacher_completion_logits(
247
+ teacher,
248
+ inputs,
249
+ num_generations=rows,
250
+ teacher_score_batch_size=rows,
251
+ reuse_teacher_prefix_cache=True,
252
+ offload_teacher_logits=False,
253
+ )
254
+ direct, direct_stats = precompute_teacher_completion_logits(
255
+ teacher,
256
+ inputs,
257
+ num_generations=rows,
258
+ teacher_score_batch_size=rows,
259
+ reuse_teacher_prefix_cache=False,
260
+ offload_teacher_logits=False,
261
+ )
262
+ assert cached is not None and direct is not None
263
+ assert torch.equal(cached, direct)
264
+ assert prefix_stats["prefix_groups"] == 1.0
265
+ assert prefix_stats["continuation_calls"] == 1.0
266
+ assert prefix_stats["fallback_batches"] == 0.0
267
+ assert direct_stats["direct_batches"] == 1.0
268
+ assert teacher.calls[0][:2] == (1, 1)
269
+ assert teacher.calls[1][:2] == (rows, completion_width - 1)
270
+
271
+
272
+ def test_position_dependent_tiny_qwen2_prefix_cache_matches_direct_fp32():
273
+ """Guard real causal position/cache semantics, not a position-invariant toy."""
274
+ from transformers import Qwen2Config, Qwen2ForCausalLM
275
+
276
+ class TextOnlyQwen(torch.nn.Module):
277
+ def __init__(self):
278
+ super().__init__()
279
+ config = Qwen2Config(
280
+ vocab_size=97,
281
+ hidden_size=32,
282
+ intermediate_size=64,
283
+ num_hidden_layers=2,
284
+ num_attention_heads=4,
285
+ num_key_value_heads=2,
286
+ max_position_embeddings=128,
287
+ attention_dropout=0.0,
288
+ )
289
+ self.model = Qwen2ForCausalLM(config).float().eval()
290
+
291
+ def forward(self, *, logits_to_keep=None, **kwargs):
292
+ for key in ("pixel_values", "image_sizes", "batch_num_images"):
293
+ kwargs.pop(key, None)
294
+ output = self.model(**kwargs, return_dict=True)
295
+ if logits_to_keep is not None:
296
+ output.logits = output.logits[:, -int(logits_to_keep) :, :]
297
+ return output
298
+
299
+ torch.manual_seed(123)
300
+ teacher = TextOnlyQwen()
301
+ rows, prompt_width, completion_width = 4, 7, 5
302
+ prompt = torch.tensor([[4, 8, 15, 16, 23, 42, 7]], dtype=torch.long)
303
+ inputs = {
304
+ "prompt_ids": prompt.expand(rows, -1).clone(),
305
+ "prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),
306
+ "teacher_prompt_ids": prompt.expand(rows, -1).clone(),
307
+ "teacher_prompt_mask": torch.ones(rows, prompt_width, dtype=torch.long),
308
+ "completion_ids": torch.tensor(
309
+ [
310
+ [11, 12, 13, 14, 15],
311
+ [21, 22, 23, 24, 25],
312
+ [31, 32, 33, 34, 35],
313
+ [41, 42, 43, 44, 45],
314
+ ],
315
+ dtype=torch.long,
316
+ ),
317
+ "completion_mask": torch.ones(rows, completion_width, dtype=torch.long),
318
+ "teacher_num_images": torch.ones(rows, dtype=torch.long),
319
+ }
320
+ cached, cached_stats = precompute_teacher_completion_logits(
321
+ teacher,
322
+ inputs,
323
+ num_generations=rows,
324
+ teacher_score_batch_size=rows,
325
+ reuse_teacher_prefix_cache=True,
326
+ offload_teacher_logits=False,
327
+ )
328
+ direct, _ = precompute_teacher_completion_logits(
329
+ teacher,
330
+ inputs,
331
+ num_generations=rows,
332
+ teacher_score_batch_size=rows,
333
+ reuse_teacher_prefix_cache=False,
334
+ offload_teacher_logits=False,
335
+ )
336
+ assert cached is not None and direct is not None
337
+ assert cached_stats["prefix_groups"] == 1.0
338
+ assert cached_stats["prefix_fallback_groups"] == 0.0
339
+ assert torch.max(torch.abs(cached - direct)).item() <= 1e-5
340
+
341
+ def test_cached_teacher_logits_skip_teacher_and_preserve_student_grad():
342
+ rows, tokens, vocab = 2, 4, 13
343
+ student_logits = torch.randn(rows, tokens, vocab, requires_grad=True)
344
+ teacher_logits = torch.randn(rows, tokens, vocab)
345
+
346
+ class FrozenTeacher:
347
+ def __init__(self):
348
+ self.param = torch.nn.Parameter(torch.zeros(1))
349
+
350
+ def parameters(self):
351
+ return iter([self.param])
352
+
353
+ frozen_teacher = FrozenTeacher()
354
+ inputs = {
355
+ "prompt_ids": torch.ones(rows, 3, dtype=torch.long),
356
+ "prompt_mask": torch.ones(rows, 3, dtype=torch.long),
357
+ "completion_ids": torch.ones(rows, tokens, dtype=torch.long),
358
+ "completion_mask": torch.ones(rows, tokens, dtype=torch.long),
359
+ "teacher_completion_logits": teacher_logits,
360
+ "acc_rewards": torch.zeros(rows),
361
+ }
362
+ loss = compute_vlm_opsd_loss_masked_batch(
363
+ None,
364
+ [0, 1],
365
+ [0, 1],
366
+ inputs,
367
+ teacher_model=frozen_teacher,
368
+ acc_gate=False,
369
+ student_completion_logits=student_logits,
370
+ loss_type="jsd",
371
+ token_chunk_size=2,
372
+ )
373
+ expected = token_distillation_loss_per_row(
374
+ student_logits,
375
+ teacher_logits,
376
+ inputs["completion_mask"].float(),
377
+ loss_type="jsd",
378
+ token_chunk_size=2,
379
+ ).mean()
380
+ assert torch.allclose(loss, expected, atol=1e-6, rtol=1e-6)
381
+ loss.backward()
382
+ assert student_logits.grad is not None
383
+ assert torch.isfinite(student_logits.grad).all()
384
+ assert not hasattr(frozen_teacher, "calls")