|
| 1 | +from types import SimpleNamespace |
| 2 | +from unittest.mock import Mock |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from optillm.bon import best_of_n_sampling |
| 7 | + |
| 8 | + |
| 9 | +def response(*choices): |
| 10 | + return SimpleNamespace( |
| 11 | + choices=[ |
| 12 | + SimpleNamespace(message=SimpleNamespace(content=text), finish_reason=reason) |
| 13 | + for text, reason in choices |
| 14 | + ], |
| 15 | + usage=SimpleNamespace(completion_tokens=1), |
| 16 | + ) |
| 17 | + |
| 18 | + |
| 19 | +@pytest.mark.parametrize( |
| 20 | + "invalid_text, reason", [("incomplete answer", "length"), (" ", "stop")] |
| 21 | +) |
| 22 | +def test_batched_invalid_candidates_are_never_sent_to_judge(invalid_text, reason): |
| 23 | + rated = [] |
| 24 | + |
| 25 | + def create(**kwargs): |
| 26 | + if kwargs.get("n") == 2: |
| 27 | + return response((invalid_text, reason), ("complete answer", "stop")) |
| 28 | + candidate = kwargs["messages"][-2]["content"] |
| 29 | + rated.append(candidate) |
| 30 | + return response(("10" if candidate == invalid_text else "8", "stop")) |
| 31 | + |
| 32 | + client = SimpleNamespace( |
| 33 | + chat=SimpleNamespace(completions=SimpleNamespace(create=create)) |
| 34 | + ) |
| 35 | + answer, tokens = best_of_n_sampling("system", "question", client, "model", n=2) |
| 36 | + |
| 37 | + assert answer == "complete answer" |
| 38 | + assert rated == ["complete answer"] |
| 39 | + assert tokens == 2 |
| 40 | + |
| 41 | + |
| 42 | +def test_all_invalid_batch_uses_existing_sequential_fallback(): |
| 43 | + create = Mock( |
| 44 | + side_effect=[ |
| 45 | + response(("partial", "length")), |
| 46 | + response(("complete answer", "stop")), |
| 47 | + response(("9", "stop")), |
| 48 | + ] |
| 49 | + ) |
| 50 | + client = SimpleNamespace( |
| 51 | + chat=SimpleNamespace(completions=SimpleNamespace(create=create)) |
| 52 | + ) |
| 53 | + answer, tokens = best_of_n_sampling("system", "question", client, "model", n=1) |
| 54 | + |
| 55 | + assert answer == "complete answer" |
| 56 | + assert "n" not in create.call_args_list[1].kwargs |
| 57 | + assert tokens == 3 |
0 commit comments