File size: 8,158 Bytes
575b0ec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | import pytest
from tdprm.data.segment import char_spans_to_token_spans, response_segments, segment, token_char_offsets
from tdprm.data.verify import extract_math_answer, hotpot_scores, last_boxed, verify
def test_segment_markers_preamble_and_final():
text = "Let me think.\nStep 1: Add 2 and 3.\nStep 2: Get 5.\nFinal answer: \\boxed{5}\n"
seg = segment(text)
assert seg.marker_found and seg.num_steps == 2
assert seg.steps[0][0] == 0 # preamble merged into step 1
assert text[seg.steps[1][0]:].startswith("Step 2")
assert text[seg.final_start:].startswith("Final answer")
bounds = seg.bounds()
assert bounds[0][0] == 0 and bounds[-1][1] == len(text)
assert all(bounds[i][1] == bounds[i + 1][0] for i in range(len(bounds) - 1))
@pytest.mark.parametrize("marker", ["**Step 1:**", "### Step 1:", "Step 1.", " step 1 :", "**Step 1**:",
"- Step 1:", "*Step 1:*", "- **Step 1:**"])
def test_segment_marker_variants(marker):
text = f"{marker} first\n{marker.replace('1', '2')} second\n**Final answer:** yes"
seg = segment(text)
assert seg.num_steps == 2 and seg.marker_found
@pytest.mark.parametrize("final", ["Final answer: \\boxed{5}", "Step 3: Final answer: \\boxed{5}",
"**Step 3: Final Answer:** \\boxed{5}", "*Final answer: \\boxed{5}",
"Step 3: Final answer:\n\\boxed{5}"])
def test_segment_final_answer_variants(final):
text = f"Step 1: Add.\nStep 2: Get 5.\n{final}"
seg = segment(text)
assert seg.num_steps == 2 and text[seg.final_start:] == final
assert extract_math_answer(text) == "5"
def test_plan_headings_are_not_final_answers():
text = "Step 1: Find X.\nStep 2: Provide the final answer.\nX is Paris.\nStep 3: Final answer."
seg = segment(text)
assert seg.num_steps == 3 and seg.final_start == len(text)
def test_segment_fallback_paragraphs_and_no_final():
text = "First paragraph.\n\nSecond paragraph\nstill second.\n\nThird."
seg = segment(text)
assert not seg.marker_found and seg.num_steps == 3 and seg.final_start == len(text)
def test_fallback_paragraphs_start_at_line_start():
text = "First.\n\n \\[ x = 1 \\]\n\nLast."
seg = segment(text)
assert not seg.marker_found and [text[a:b] for a, b in seg.steps][1].startswith(" \\[")
def test_segment_empty_body():
seg = segment("Final answer: 7")
assert seg.num_steps == 0 and seg.bounds() == [(0, len("Final answer: 7"))]
@pytest.fixture(scope="module")
def qwen_tok():
transformers = pytest.importorskip("transformers")
try:
return transformers.AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
except Exception as exc: # offline
pytest.skip(f"tokenizer unavailable: {exc}")
def test_token_offsets_exact_with_unicode(qwen_tok):
text = ("Step 1: Let x = 3·4 — note 中文 and émojis 🙂.\nStep 2: Then x² = 144.\n"
"Final answer: \\boxed{144}")
ids = qwen_tok.encode(text, add_special_tokens=False) + [qwen_tok.convert_tokens_to_ids("<|im_end|>")]
decoded, offsets = token_char_offsets(qwen_tok, ids)
assert decoded == text and len(offsets) == len(ids) + 1 and offsets[-1] == len(text)
assert offsets == sorted(offsets)
seg, spans = response_segments(qwen_tok, ids)
assert seg.num_steps == 2 and len(spans) == 3
assert spans[0][0] == 0 and spans[-1][1] == len(ids)
assert all(spans[i][1] == spans[i + 1][0] for i in range(len(spans) - 1))
step2 = qwen_tok.decode(ids[spans[1][0]:spans[1][1]], skip_special_tokens=True)
assert step2.lstrip().startswith("Step 2")
final = qwen_tok.decode(ids[spans[2][0]:spans[2][1]], skip_special_tokens=True)
assert "Final answer" in final
def test_char_to_token_assignment_by_first_char():
offsets = [0, 3, 7, 10, 12] # 4 tokens
assert char_spans_to_token_spans(offsets, [(0, 7), (7, 12)]) == [(0, 2), (2, 4)]
assert char_spans_to_token_spans(offsets, [(0, 5), (5, 12)]) == [(0, 2), (2, 4)]
def test_math_verification():
assert last_boxed("x \\boxed{\\frac{1}{2}} y \\boxed{3}") == "3"
assert extract_math_answer("Step 1: ...\nFinal answer: \\boxed{\\dfrac{1}{2}}") == "\\dfrac{1}{2}"
assert verify("math", "Final answer: \\boxed{0.5}", "\\frac{1}{2}")["score"] == 1.0
assert verify("math500", "Final answer: \\boxed{\\frac{1}{3}}", "\\frac{1}{2}")["score"] == 0.0
assert verify("gsm8k", "Step 1: 1,234 total.\nFinal answer: \\boxed{1234}", "1234")["score"] == 1.0
assert verify("math", "no answer here", "4")["score"] == 0.0
def test_hotpot_verification():
assert hotpot_scores("The Beatles", "Beatles")["em"] == 1.0
r = verify("hotpotqa", "Step 1: ...\nFinal answer: **the Beatles**", "Beatles")
assert r["score"] == 1.0 and r["has_answer"] == 1.0
assert verify("hotpotqa", "Step 1: guess\nFinal answer: no", "yes")["score"] == 0.0
assert verify("hotpotqa", "Step 1: X.\nStep 2: Final answer: The Beatles", "Beatles")["score"] == 1.0
assert verify("hotpotqa", "Step 1: X.\n**Final Answer:**\n\nThe Beatles\n", "Beatles")["score"] == 1.0
assert verify("hotpotqa", "Step 1: X.\nStep 2: Give the final answer.\nThe Beatles", "Beatles")["score"] == 0.0
@pytest.mark.parametrize("line,letter", [("B", "B"), ("B) False", "B"), ("(C)", "C"), ("\\boxed{A}", "A"),
("Option C", "C"), ("**A**", "A"), ("False", "B"), ("Uncertain.", "C"),
("A) True", "A"), ("C: Uncertain", "C")])
def test_proverqa_option_letter(line, letter):
r = verify("proverqa_hard", f"Step 1: premise.\nFinal answer: {line}", letter)
assert r["score"] == 1.0 and r["has_answer"] == 1.0
def test_proverqa_verification_rejects_wrong_or_ambiguous():
assert verify("proverqa", "Step 1: x\nFinal answer: B", "A")["score"] == 0.0
assert verify("proverqa", "Step 1: x\nFinal answer: True or False", "A")["has_answer"] == 0.0
assert verify("proverqa", "Step 1: no final line", "A")["score"] == 0.0
def test_proverqa_prompt_and_question_text():
from tdprm.data.prepare import prover_split
from tdprm.data.prompts import build_messages
from tdprm.states.stateset import question_text
raw = "Context:\nA is B. B is C.\n\nQuestion: Is A C?\n\nOptions:\nA) True\nB) False\nC) Uncertain\n"
context, question = prover_split(raw)
assert context == "A is B. B is C." and question == "Is A C?\nOptions:\nA) True\nB) False\nC) Uncertain"
msgs = build_messages("proverqa", question, context)
assert msgs[1]["content"].startswith("Context:\nA is B.") and "Final answer: <A, B or C>" in msgs[0]["content"]
assert question_text(msgs).startswith("Is A C?")
def test_retest_only_writes_base_unsolved_prompts(tmp_path, monkeypatch):
"""v2 data pipeline input: prompts the base model solved 0 of 10 times, rebuilt from an existing rollouts file."""
import json
import sys
import pandas as pd
from tdprm import paths
from tdprm.sampling import base_rollouts
from tdprm.sampling.generate import write_jsonl_gz
for name in ("DATA", "ROLLOUTS"):
monkeypatch.setattr(paths, name, tmp_path / name.lower())
pool = [{"id": f"m{i}", "domain": "math", "data_source": "math", "question": f"q{i}", "answer": str(i)}
for i in range(4)]
(tmp_path / "data" / "pool").mkdir(parents=True)
(tmp_path / "data" / "pool" / "math_train.jsonl").write_text("".join(json.dumps(r) + "\n" for r in pool))
solved = {"m0": 0, "m1": 3, "m2": 0} # m3 never sampled (too long)
write_jsonl_gz(tmp_path / "rollouts" / "qwen1.5b_math.jsonl.gz",
[{"id": pid, "sample": j, "R": float(j < k)} for pid, k in solved.items() for j in range(10)])
monkeypatch.setattr(sys, "argv", ["x", "--backbone", "qwen1.5b", "--domain", "math", "--retest-only"])
base_rollouts.main()
df = pd.read_parquet(tmp_path / "data" / "train" / "math_qwen1.5b_retest.parquet")
assert sorted(r["id"] for r in df["extra_info"]) == ["m0", "m2"]
|