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(data): keep a call-only assistant turn with empty content in clean (#1477) (#1493)
Abdulwaarith Zakariyya82f72cc89591
diff --git a/changelog.d/0.75.1/1493.fixed.md b/changelog.d/0.75.1/1493.fixed.mdnew file mode 100644index 00000000..88bd6168--- /dev/null+++ b/changelog.d/0.75.1/1493.fixed.md@@ -0,0 +1 @@+- **`soup data clean` no longer drops a tool-calling trajectory whose call-only assistant turn has empty content (#1477 by @abdulwaarith0 in #1493).** With no flags, the `--min-tokens` check ran on every assistant turn in the `chatml` branch, so a turn with `"content": ""` and a non-empty `tool_calls`, the shape the tool-calling format itself writes, dropped its row as "Empty / Whitespace Turns" while the same turn with `"content": null` was kept and the loader accepted both. A turn that carries tool calls is now exempt from `--min-tokens`; turns with no calls keep the rule.diff --git a/docs/data.md b/docs/data.mdindex 446a2537..6cc74db3 100644--- a/docs/data.md+++ b/docs/data.md@@ -104,7 +104,7 @@ soup data clean raw_data.jsonl --strip-boilerplate --repair-code --repair-json -### Cleaning Rules & Defaults:- **Default (Safe & Non-Destructive):**1. **Control Characters & Whitespace:** Strips C0 controls (`\x00-\x1f`), zero-width spaces (`\u200b-\u200d`, `\ufeff`), and normalizes CRLF/CR to Unix LF.- 2. **Empty & Degenerate Turns:** Drops rows where the assistant turn is empty or shorter than `--min-tokens`.+ 2. **Empty & Degenerate Turns:** Drops rows where the assistant turn is empty or shorter than `--min-tokens`. A turn that carries tool calls is exempt: its payload is the calls, and `"content": ""` is what the tool-calling format writes on a call-only turn.- **Opt-In Heuristic Repairs (Flags):**1. `--strip-boilerplate`: Strips canned preambles (*"Certainly! As an AI language model..."*) and sign-offs (*"I hope this helps!"*) across multiple passes.2. `--repair-code`: Auto-closes unclosed triple backtick (```` ``` ````) code fences in assistant completions.diff --git a/src/soup_cli/utils/data_clean.py b/src/soup_cli/utils/data_clean.pyindex f04c991d..33c8bf83 100644--- a/src/soup_cli/utils/data_clean.py+++ b/src/soup_cli/utils/data_clean.py@@ -239,6 +239,12 @@ def _clean_tool_calls(return cleaned_calls+def _has_tool_calls(msg: Dict[str, Any]) -> bool:+ """True when a turn carries at least one tool call (a non-empty list)."""+ calls = msg.get("tool_calls")+ return isinstance(calls, list) and len(calls) > 0++def _clean_turn_tool_calls(msg: Dict[str, Any], applied_rules: List[str], repair_json: bool, drop_invalid_json: bool) -> bool:@@ -345,7 +351,13 @@ def clean_row(if was_cr:applied_rules.append("Markdown Code Fence Repair")- if len(sanitized_content.strip()) < min_tokens:+ # #1477 - a call-only turn carries its payload in tool_calls,+ # and "" is what the unified tool-calling format writes there;+ # keep it as the same turn with content null is kept.+ if (+ not _has_tool_calls(msg)+ and len(sanitized_content.strip()) < min_tokens+ ):return None, ["Empty / Whitespace Turns"]msg["content"] = sanitized_contentdiff --git a/tests/test_issue1477_call_only_empty_content.py b/tests/test_issue1477_call_only_empty_content.pynew file mode 100644index 00000000..924c34bd--- /dev/null+++ b/tests/test_issue1477_call_only_empty_content.py@@ -0,0 +1,119 @@+"""#1477: `soup data clean` keeps a call-only assistant turn whose content is empty.++A call-only turn carries its payload in ``tool_calls``. The unified tool-calling+format writes ``"content": ""`` on it, and the loader accepts the row, but the+``--min-tokens`` check in the ``chatml`` branch of ``clean_row`` ran on every+assistant turn and dropped it as "Empty / Whitespace Turns". The same turn with+``"content": null`` was kept. Turns with no calls (``tool_calls`` missing, null+or ``[]``) keep the ``--min-tokens`` rule.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.data.formats import format_to_messages+from soup_cli.utils.data_clean import clean_row++CALL = {"id": "c1", "type": "function",+ "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}+++def _row(content, tool_calls):+ """The issue's trajectory: a call turn, its tool result, then the answer."""+ turn = {"role": "assistant", "content": content}+ if tool_calls is not ...:+ turn["tool_calls"] = tool_calls+ return {"messages": [+ {"role": "user", "content": "Weather in Paris?"},+ turn,+ {"role": "tool", "tool_call_id": "c1", "content": "{\"temp\": 18}"},+ {"role": "assistant", "content": "It is 18C in Paris."},+ ]}+++def _call_turn(cleaned):+ return cleaned["messages"][1]+++class TestChatmlBranch:+ """Nested-call rows with no ``tools`` key are detected as ``chatml``."""++ @pytest.mark.parametrize("content", ["", " ", None], ids=["empty", "whitespace", "null"])+ def test_a_call_only_turn_is_kept(self, content):+ row = _row(content, [CALL])+ cleaned, rules = clean_row(row, "chatml")+ assert cleaned is not None, rules+ assert _call_turn(cleaned)["tool_calls"] == [CALL]+ assert "Empty / Whitespace Turns" not in rules++ def test_empty_content_is_left_as_written(self):+ cleaned, _ = clean_row(_row("", [CALL]), "chatml")+ assert _call_turn(cleaned)["content"] == ""++ def test_a_turn_with_calls_is_not_held_to_min_tokens(self):+ cleaned, rules = clean_row(_row("ok", [CALL]), "chatml", min_tokens=5)+ assert cleaned is not None, rules++ @pytest.mark.parametrize(+ "tool_calls",+ [[], None, ..., CALL],+ ids=["empty-list", "null", "missing", "bare-dict-not-a-list"],+ )+ def test_an_empty_turn_without_calls_is_still_dropped(self, tool_calls):+ """A bare dict is not a call list: the loader rejects it too."""+ cleaned, rules = clean_row(_row("", tool_calls), "chatml")+ assert cleaned is None+ assert rules == ["Empty / Whitespace Turns"]++ def test_a_short_turn_without_calls_is_still_held_to_min_tokens(self):+ cleaned, rules = clean_row(_row("ok", ...), "chatml", min_tokens=5)+ assert cleaned is None+ assert rules == ["Empty / Whitespace Turns"]++ def test_null_content_with_an_empty_list_is_kept_as_on_main(self):+ """``--min-tokens`` reads string content only; this is unchanged."""+ cleaned, rules = clean_row(_row(None, []), "chatml")+ assert cleaned is not None, rules+++class TestToolCallingBranch:+ """``{messages, tools}`` rows are detected as ``tool-calling`` and never dropped+ for an empty turn; pinned so the two branches keep agreeing."""++ @pytest.mark.parametrize("content", ["", None], ids=["empty", "null"])+ @pytest.mark.parametrize("tool_calls", [[CALL], []], ids=["one-call", "empty-list"])+ def test_the_row_is_kept(self, content, tool_calls):+ row = {**_row(content, tool_calls), "tools": [{"type": "function", "function": {+ "name": "get_weather", "parameters": {}}}]}+ cleaned, rules = clean_row(row, "tool-calling")+ assert cleaned is not None, rules+ assert _call_turn(cleaned)["content"] == content+ assert _call_turn(cleaned)["tool_calls"] == tool_calls++[email protected]("content", ["", None], ids=["empty", "null"])+def test_every_kept_call_row_loads(content):+ """What clean keeps, the loader accepts: the issue's premise, pinned."""+ row = _row(content, [CALL])+ cleaned, _ = clean_row(row, "chatml")+ assert cleaned is not None+ assert format_to_messages(cleaned, "tool-calling") is not None+++def test_cli_keeps_the_call_row(tmp_path, monkeypatch):+ """The issue's CLI run: the ``""`` row plus one plain chat row, no flags."""+ monkeypatch.chdir(tmp_path)+ plain = {"messages": [{"role": "user", "content": "Hi"},+ {"role": "assistant", "content": "Hello!"}]}+ rows = [_row("", [CALL]), plain]+ Path("raw.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")+ result = CliRunner().invoke(app, ["data", "clean", "raw.jsonl", "-o", "clean.jsonl", "-f"])+ assert result.exit_code == 0, result.output+ out = [json.loads(line) for line in Path("clean.jsonl").read_text().splitlines()]+ assert out == rows