Download code/v2/tdprm/tests/test_data.py from JoshuaW1997/tdprm-results: direct link, hf CLI and curl.
- Browser
- Download file 8.16 kB
-
https://huggingface.co/datasets/JoshuaW1997/tdprm-results/resolve/main/code/v2/tdprm/tests/test_data.py
- Command line
-
hf download hf://datasets/JoshuaW1997/tdprm-results/code/v2/tdprm/tests/test_data.py
-
curl -L -o test_data.py https://huggingface.co/datasets/JoshuaW1997/tdprm-results/resolve/main/code/v2/tdprm/tests/test_data.py
8.16 kB
| 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)) | |
| 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 | |
| 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"))] | |
| 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 | |
| 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"] | |