Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(eval): preserve JSON boolean types in tool-call scoring (#1756)
Faisal Fayaz9f038a031efd
diff --git a/changelog.d/0.76.0/1756.fixed.md b/changelog.d/0.76.0/1756.fixed.mdnew file mode 100644index 00000000..7880e8b4--- /dev/null+++ b/changelog.d/0.76.0/1756.fixed.md@@ -0,0 +1 @@+- **Tool-call eval scorers no longer credit a JSON number as a boolean (#1755 by @Faisal-Fayaz in #1756).** `tool_call_match` and `tool_call_args_subset` compared parsed `arguments` with Python `==`, and Python has `bool` as a subclass of `int`: a model that answered `{"enabled": 1}` where the task expected `{"enabled": true}` scored `1.0` — full credit for a wrong answer, through `score_task` and `run_eval` alike. Both are valid JSON, and they are different arguments. Arguments are now compared with a `_json_equal` that rules on `bool` before anything else, so a boolean and a number never match at any depth, while numbers stay equal across forms (`1 == 1.0` still matches, as before). It walks nested arguments through an explicit worklist rather than recursion, so an argument nested as deeply as `json.loads` accepts is still scored instead of raising. `tool_call_match` scores such a call `0.0`; `tool_call_args_subset` keeps its `0.5` function-name credit and gives no argument credit, so `0.5`, and its `0.5` `matched` threshold is unchanged. Scores recorded before this change can be higher than the same outputs score now, because a boolean/number substitution used to count as correct.diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 27f3acba..6af3a689 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -968,6 +968,19 @@ How the string scorers read an output:| `contains` | `expected` as a whole alphanumeric-bounded token, case-insensitive via `str.lower()` on both sides (so `istanbul` does not match `İstanbul`, nor `s` match `ſ`) | match | no match || `exact` | The whole stripped output, case-insensitive | no match | no match |+The two tool-call scorers parse the call and compare `arguments` as **JSON**, not as+strings, and `1` is not `true` there: JSON has one boolean type and one number type, and a+boolean compared with `==` against a number would be equal in Python (`True == 1`). So++| `scoring` | Scores | gold `{"enabled": true}` vs `{"enabled": true}` | vs `{"enabled": 1}` |+|---|---|---|---|+| `tool_call_match` | the parsed `arguments` objects must be equal, JSON types included; the function name must match too | match | no match |+| `tool_call_args_subset` | `0.5` for the function name plus `0.5` for the fraction of expected arguments present with a matching value | `1.0` | `0.5` — the name matched, the argument did not |++Numbers still compare equal across forms, so gold `{"n": 1}` matches `{"n": 1.0}`; that is+existing behaviour and not a rounding of the policy. The rule applies inside nested objects+and lists, and whether `arguments` is an object or a JSON string does not change it.+`answer` refuses, at load time, an `expected` that states no single answer (a multi-lineworked solution with no `####`, an empty `\boxed{}`, a hedge between values), naming the line.`contains` cannot read negation: `It is not 4, so 5.` still contains `4`. Its bound is andiff --git a/src/soup_cli/eval/custom.py b/src/soup_cli/eval/custom.pyindex 33ae65f7..57e4304a 100644--- a/src/soup_cli/eval/custom.py+++ b/src/soup_cli/eval/custom.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import mathimport refrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -251,6 +252,64 @@ def _parse_args(func: dict) -> Optional[dict]:return None+def _json_equal(expected: Any, actual: Any) -> bool:+ """Compare two parsed-JSON values the way JSON does, not the way Python does.++ JSON has one boolean type and one number type; Python has ``bool`` as a subclass of+ ``int``, so ``True == 1`` and ``False == 0`` — including inside dicts and lists.+ Comparing parsed tool-call arguments with ``==`` therefore gives a model that+ answered ``1`` the full credit owed to one that answered ``true``, and a model that+ answered ``false`` the credit for ``0``. Both are valid JSON, and they are different+ arguments (#1755).++ Numbers are deliberately left equal across forms: ``1 == 1.0`` still compares equal,+ which is an existing control and not a policy change. A ``type(a) == type(b)`` guard+ would separate them, which is why this rules on ``bool`` first and then defers to+ ``==``.++ ``expected`` here is the gold side of a user's eval task file, so both arguments are+ user-supplied; neither is a Soup config field.++ The walk is a worklist rather than recursion, so nesting depth costs heap and not+ Python stack: ``json.loads`` accepts an argument hundreds of levels deep, and a+ recursive comparison raised ``RecursionError`` on one instead of scoring it. The+ pending list cannot cycle because both sides come from ``json.loads``, which cannot+ build a self-referential document.+ """+ pending: list[tuple[Any, Any]] = [(expected, actual)]+ while pending:+ want, got = pending.pop()+ # bool before everything: it is a subclass of int, so every other branch below would+ # otherwise treat True as 1.+ if isinstance(want, bool) or isinstance(got, bool):+ if not (isinstance(want, bool) and isinstance(got, bool) and want is got):+ return False+ continue+ if isinstance(want, dict) and isinstance(got, dict):+ if want.keys() != got.keys():+ return False+ pending.extend((want[key], got[key]) for key in want)+ continue+ if isinstance(want, list) and isinstance(got, list):+ if len(want) != len(got):+ return False+ pending.extend(zip(want, got))+ continue+ # JSON has no NaN literal, but Python's parser accepts a bare NaN, so a task+ # file can carry one. The old dict ``==`` matched NaN with NaN through CPython's+ # shared singleton; keep that so recorded scores do not change (#1755).+ if (+ isinstance(want, float)+ and isinstance(got, float)+ and math.isnan(want)+ and math.isnan(got)+ ):+ continue+ if want != got:+ return False+ return True++def tool_call_match(output: str, expected: str) -> bool:"""Exact tool-call match: function name and arguments must match."""out = _parse_tool_call(output)@@ -267,7 +326,7 @@ def tool_call_match(output: str, expected: str) -> bool:exp_args = _parse_args(exp_func)if out_args is None or exp_args is None:return False- return out_args == exp_args+ return _json_equal(exp_args, out_args)def tool_call_name_match(output: str, expected: str) -> bool:@@ -316,7 +375,9 @@ def tool_call_args_subset(output: str, expected: str) -> float:args_score = 0.5 if not out_args else 0.0else:matched = sum(- 1 for k, v in exp_args.items() if k in out_args and out_args[k] == v+ 1+ for k, v in exp_args.items()+ if k in out_args and _json_equal(v, out_args[k]))args_score = 0.5 * (matched / len(exp_args))diff --git a/tests/test_tool_call_json_types.py b/tests/test_tool_call_json_types.pynew file mode 100644index 00000000..c82553d2--- /dev/null+++ b/tests/test_tool_call_json_types.py@@ -0,0 +1,385 @@+"""Tests for issue #1755 — tool-call scorers must not conflate JSON booleans with numbers.++JSON has one boolean type and one number type. Python has ``bool`` as a subclass of+``int``, so ``True == 1`` and ``False == 0``, and that holds inside dicts and lists too.+Both scorers compared parsed arguments with ``==``, so a model that answered ``1`` where+the task expected ``true`` was given the full credit owed to one that answered ``true`` —+a wrong answer scored as a right one, through ``score_task`` and ``run_eval`` alike.++The policy implemented here is the one the issue's Expected section states:++- ``tool_call_match`` gives ``0.0`` for a boolean/number substitution;+- ``tool_call_args_subset`` keeps its ``0.5`` function-name credit and gives no argument+ credit, so ``0.5``. Its existing ``0.5`` ``matched`` threshold is untouched;+- numbers stay equal across forms, so ``1 == 1.0`` and ``0 == 0.0`` still match. The+ issue calls that a passing control and not a policy change.++Every case here is driven through ``score_task`` rather than the scorer functions alone,+because the scorer's return value is not what the bug was reported against.+"""++from __future__ import annotations++import json++import pytest++from soup_cli.eval.custom import EvalTask, run_eval, score_task++#: The two scorers that compare argument values.+COMPARING_SCORERS = ("tool_call_match", "tool_call_args_subset")++#: What each scorer must answer for a boolean/number substitution. The subset scorer+#: keeps half its credit for the function name, which does match.+EXPECTED_ON_SUBSTITUTION = {"tool_call_match": 0.0, "tool_call_args_subset": 0.5}++#: (gold, generated) pairs that are different JSON values of different JSON types.+#: Both directions, both booleans, per the issue.+SUBSTITUTIONS = [+ (True, 1),+ (False, 0),+ (1, True),+ (0, False),+ (True, False),+ (False, True),+]++#: (label, gold, generated) pairs that must keep scoring 1.0. `1 == 1.0` is the one that+#: a `type(a) == type(b)` guard would break, which is why it is here.+CONTROLS = [+ ("equal booleans", True, True),+ ("equal false", False, False),+ ("one equals one point zero", 1, 1.0),+ ("zero equals zero point zero", 0, 0.0),+ ("equal strings", "a", "a"),+ ("equal null", None, None),+ ("equal floats", 1.5, 1.5),+]+++def call(arguments: object, name: str = "set_flag") -> str:+ """One tool call, in the shape both scorers parse.++ The value goes under an `enabled` key rather than being the whole of `arguments`:+ `_parse_args` returns `None` unless `arguments` parses to a dict, so a bare scalar+ would take both scorers down a different path and quietly score 1.0 whatever it was.+ """+ return json.dumps({"function": {"name": name, "arguments": {"enabled": arguments}}})+++def call_args(arguments: dict, name: str = "set_flag") -> str:+ """One tool call whose `arguments` is exactly `arguments`, with no nesting added."""+ return json.dumps({"function": {"name": name, "arguments": arguments}})+++def task(scoring: str, expected_arguments: object) -> EvalTask:+ return EvalTask(prompt="set the flag", expected=call(expected_arguments), scoring=scoring)+++def scored(scoring: str, gold: object, generated: object) -> float:+ return score_task(task(scoring, gold), call(generated)).score+++#: A depth the parser accepts and that a recursive comparison could not walk: 600 nested+#: dicts raised `RecursionError` on the first cut, where 300 still passed.+DEEP_DEPTH = 600++#: The same nesting at a depth that worked even then. Kept beside `DEEP_DEPTH` so the+#: deep cases cannot pass by comparison being refused wholesale at any size.+SHALLOW_DEPTH = 100+++def nested_dict(depth: int, leaf: object) -> dict:+ """One argument object `depth` dicts deep, `leaf` at the bottom."""+ value = leaf+ for _ in range(depth):+ value = {"k": value}+ return {"enabled": value}+++def nested_list(depth: int, leaf: object) -> dict:+ """One argument object `depth` lists deep, `leaf` at the bottom."""+ value = leaf+ for _ in range(depth):+ value = [value]+ return {"enabled": value}+++class TestABooleanIsNotItsNumericTwin:+ """The defect: a wrong answer scored as a right one."""++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ @pytest.mark.parametrize(("gold", "generated"), SUBSTITUTIONS)+ def test_a_substitution_does_not_score(self, scoring: str, gold, generated) -> None:+ assert scored(scoring, gold, generated) == EXPECTED_ON_SUBSTITUTION[scoring], (+ f"{scoring} gave a JSON {type(generated).__name__} where the task expected a "+ f"JSON {type(gold).__name__}. They are different JSON values, so the answer "+ "is wrong and must not earn argument credit."+ )++ def test_the_subset_scorer_halves_only_the_swapped_argument(self) -> None:+ """The partial-credit arithmetic, which the single-argument cases cannot show.++ Two expected arguments, one correct and one swapped: the name credit is the same+ 0.5 as `test_the_subset_scorer_keeps_exactly_its_name_credit`, and the argument+ credit is halved rather than withheld, so 0.5 + 0.25. Reverting the matched-count+ to `==` would make both arguments match and score 1.0.+ """+ result = score_task(+ EvalTask(+ prompt="p",+ expected=call_args({"enabled": True, "level": 2}),+ scoring="tool_call_args_subset",+ ),+ call_args({"enabled": 1, "level": 2}),+ )+ assert result.score == pytest.approx(0.75)++ def test_the_subset_scorer_keeps_exactly_its_name_credit(self) -> None:+ """CONTROL for the 0.5. Half the score is the function name matching, which is+ unaffected; only the argument half is withheld. If this ever fell below 0.5 the+ ``matched >= 0.5`` threshold in score_task would report the task as not matched,+ which is a behaviour change the issue explicitly did not ask for."""+ result = score_task(task("tool_call_args_subset", {"enabled": True}),+ call({"enabled": 1}))+ assert result.score == 0.5+ assert result.matched is True, "the issue asked for no change to the 0.5 threshold"++ def test_a_wrong_function_name_still_scores_zero_not_half(self) -> None:+ """CONTROL. The retained 0.5 is the NAME credit, so a name mismatch must still be+ 0.0 — otherwise the fix would have read as 'arguments are always worth half'."""+ result = score_task(+ task("tool_call_args_subset", {"enabled": True}),+ call({"enabled": 1}, name="other_fn"),+ )+ assert result.score == 0.0+ assert result.matched is False+++class TestWhatMustKeepScoring:+ """The controls. A fix that separates `1` from `1.0` is wrong, not stricter."""++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ @pytest.mark.parametrize(("label", "gold", "generated"), CONTROLS, ids=[c[0] for c in CONTROLS])+ def test_equal_values_still_score(self, scoring: str, label: str, gold, generated) -> None:+ assert scored(scoring, {"enabled": gold}, {"enabled": generated}) == 1.0, (+ f"{label}: equal arguments must still earn full credit. Numbers comparing "+ "equal across forms is an existing control, not a policy change."+ )++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ def test_a_mixed_object_of_equal_values_scores(self, scoring: str) -> None:+ """CONTROL. A whole argument object that is genuinely equal still matches, so+ the fix did not turn into 'every object must be compared element-wise strictly'."""+ same = {"flag": True, "count": 1.0, "label": "a", "items": [1, 2, {"deep": None}]}+ assert scored(scoring, same, dict(same)) == 1.0+++class TestTheSubstitutionIsCaughtInsideNesting:+ """A substitution buried in a list or a nested object is the same defect."""++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ @pytest.mark.parametrize(+ ("label", "gold", "generated"),+ [+ ("nested dict", {"a": {"b": True}}, {"a": {"b": 1}}),+ # The swapped element must be a bool against its own numeric twin. An+ # earlier cut used [1, 2] vs [1, True], which compares 2 with True --+ # different under plain `==` as well, so the case passed with the bool+ # branch disabled and proved nothing.+ ("inside a list", {"a": [1, 1]}, {"a": [1, True]}),+ ("list of objects", {"a": [{"b": False}]}, {"a": [{"b": 0}]}),+ ],+ ids=["nested dict", "inside a list", "list of objects"],+ )+ def test_a_buried_substitution_does_not_score(+ self, scoring: str, label, gold, generated+ ) -> None:+ assert scored(scoring, gold, generated) == EXPECTED_ON_SUBSTITUTION[scoring], (+ f"{label}: the comparison recurses, so a substitution at any depth is caught"+ )++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ def test_an_equal_structure_still_scores(self, scoring: str) -> None:+ same = {"a": [1, 2, {"b": True, "c": [0.5]}]}+ assert scored(scoring, same, {"a": [1, 2, {"b": True, "c": [0.5]}]}) == 1.0++ def test_a_list_of_a_different_length_does_not_score(self) -> None:+ assert scored("tool_call_match", {"a": [1, 2]}, {"a": [1, 2, 3]}) == 0.0++ def test_a_dict_with_a_different_key_set_does_not_score(self) -> None:+ assert scored("tool_call_match", {"a": 1}, {"a": 1, "b": 2}) == 0.0+++class TestDeeplyNestedArgumentsAreStillJudged:+ """`json.loads` accepts deep nesting, so the scorers have to judge it too.++ The first recursive cut walked the tree through Python calls and raised+ `RecursionError` on an argument 600 levels deep: a call that the old `==` scored 1.0+ aborted the whole eval run instead. Every case here goes through `score_task`, and+ the shallow depth rides along because it passed even with the bug — a deep case alone+ would not show that the fix changed nothing for arguments of ordinary size.+ """++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ @pytest.mark.parametrize("depth", [SHALLOW_DEPTH, DEEP_DEPTH])+ @pytest.mark.parametrize("build", [nested_dict, nested_list], ids=["dicts", "lists"])+ def test_deeply_nested_equal_arguments_score(self, scoring: str, depth: int, build) -> None:+ assert scored(scoring, build(depth, True), build(depth, True)) == 1.0, (+ f"{depth} levels of {build.__name__}: these arguments are equal, so they must "+ "score as they did under the old `==`. Refusing them, or returning False, "+ "would be a policy change the issue did not ask for."+ )++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ @pytest.mark.parametrize("depth", [SHALLOW_DEPTH, DEEP_DEPTH])+ @pytest.mark.parametrize("build", [nested_dict, nested_list], ids=["dicts", "lists"])+ def test_a_deeply_nested_substitution_does_not_score(+ self, scoring: str, depth: int, build+ ) -> None:+ assert (+ scored(scoring, build(depth, True), build(depth, 1))+ == EXPECTED_ON_SUBSTITUTION[scoring]+ ), (+ f"{depth} levels of {build.__name__}: the leaf is a JSON boolean against its "+ "numeric twin, so the defect at the bottom of the tree is the defect at the "+ "top. The old code would have scored this 1.0, which is the point of the fix."+ )++ @pytest.mark.parametrize(+ ("generated_leaf", "expected_score"),+ [(True, 1.0), (1, 0.0)],+ ids=["equal", "substitution"],+ )+ def test_run_eval_judges_a_deep_argument_instead_of_aborting(+ self, generated_leaf: object, expected_score: float+ ) -> None:+ """The public path. Under the recursion this raised, taking the run down with it."""+ results = run_eval(+ model_path="unused",+ tasks=[+ EvalTask(+ prompt="set the flag",+ expected=call_args(nested_dict(DEEP_DEPTH, True)),+ scoring="tool_call_match",+ )+ ],+ generate_fn=lambda prompt: call_args(nested_dict(DEEP_DEPTH, generated_leaf)),+ )+ assert results.results[0].score == expected_score+ assert results.accuracy == expected_score+++class TestAMissingKeyIsStillAMissingKey:+ """CONTROL. The subset scorer counts present keys; the fix must not change that.++ These build their argument objects directly rather than through `call`, which nests+ a single value under `enabled` and would turn a two-key expected object into+ `{"enabled": {"enabled": ..., "level": 2}}`.+ """++ def test_a_missing_argument_is_not_matched(self) -> None:+ result = score_task(+ EvalTask(+ prompt="p",+ expected=call_args({"enabled": True, "level": 2}),+ scoring="tool_call_args_subset",+ ),+ call_args({"enabled": True}),+ )+ # One of two expected arguments present and correct: 0.5 name + 0.25 args.+ assert result.score == pytest.approx(0.75)++ def test_an_extra_argument_does_not_inflate_the_score(self) -> None:+ result = score_task(+ EvalTask(+ prompt="p",+ expected=call_args({"enabled": True}),+ scoring="tool_call_args_subset",+ ),+ call_args({"enabled": True, "extra": 99}),+ )+ assert result.score == 1.0+++class TestItReachesThePublicPaths:+ """The issue reports the score through `score_task` and `run_eval`, not a helper.++ Everything above drives `score_task`. These two drive the entry point a caller+ actually uses, so the fix cannot be satisfied by changing a private helper that+ nothing routes through.+ """++ def test_run_eval_scores_a_substitution_as_incorrect(self) -> None:+ results = run_eval(+ model_path="unused",+ tasks=[task("tool_call_match", {"enabled": True})],+ generate_fn=lambda prompt: call({"enabled": 1}),+ )+ assert results.results[0].score == 0.0+ assert results.results[0].matched is False+ assert results.accuracy == 0.0++ def test_run_eval_keeps_scoring_a_correct_call(self) -> None:+ results = run_eval(+ model_path="unused",+ tasks=[task("tool_call_match", {"enabled": True})],+ generate_fn=lambda prompt: call({"enabled": True}),+ )+ assert results.results[0].score == 1.0+ assert results.accuracy == 1.0++ def test_run_eval_halves_a_subset_scorer_substitution(self) -> None:+ results = run_eval(+ model_path="unused",+ tasks=[task("tool_call_args_subset", {"enabled": True})],+ generate_fn=lambda prompt: call({"enabled": 1}),+ )+ assert results.results[0].score == 0.5+++class TestNaNMatchesItself:+ """NaN is not a JSON value, but Python's parser accepts a bare one, so a task file+ can carry it. The old dict comparison matched NaN with NaN through CPython's shared+ singleton; keep that so recorded scores do not change (#1755)."""++ @staticmethod+ def _nan_call():+ return json.dumps({"function": {"name": "f", "arguments": {"v": float("nan")}}})++ def test_a_nan_answer_matches_a_nan_gold(self):+ task = EvalTask(prompt="p", expected=self._nan_call(), scoring="tool_call_match")+ assert score_task(task, self._nan_call()).score == 1.0+++class TestStringEncodedArgumentsBehaveTheSame:+ """CONTROL. `_parse_args` accepts `arguments` as a JSON string or an object, and both+ spellings must be judged by the same rule — otherwise the fix would only close half+ the door, since the existing tests all use the string spelling."""++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ @pytest.mark.parametrize(("gold", "generated"), [(True, 1), (1, True)])+ def test_encoded_arguments_are_compared_the_same_way(self, scoring, gold, generated) -> None:+ output = json.dumps(+ {"function": {"name": "set_flag", "arguments": json.dumps({"enabled": generated})}}+ )+ expected = json.dumps(+ {"function": {"name": "set_flag", "arguments": json.dumps({"enabled": gold})}}+ )+ from soup_cli.eval.custom import score_task as direct++ assert direct(EvalTask(prompt="p", expected=expected, scoring=scoring),+ output).score == EXPECTED_ON_SUBSTITUTION[scoring]++ @pytest.mark.parametrize("scoring", COMPARING_SCORERS)+ def test_encoded_equal_arguments_still_score(self, scoring) -> None:+ output = json.dumps(+ {"function": {"name": "set_flag", "arguments": json.dumps({"enabled": 1.0})}}+ )+ expected = json.dumps(+ {"function": {"name": "set_flag", "arguments": json.dumps({"enabled": 1})}}+ )+ from soup_cli.eval.custom import score_task as direct++ assert direct(EvalTask(prompt="p", expected=expected, scoring=scoring),+ output).score == 1.0