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): read nested tool calls, and stop soup train on zero training rows (#1217) (#1321)
Abdulwaarith Zakariyya1fdef3be4ca7
diff --git a/changelog.d/0.75.1/1321.fixed.md b/changelog.d/0.75.1/1321.fixed.mdnew file mode 100644index 00000000..c875e78c--- /dev/null+++ b/changelog.d/0.75.1/1321.fixed.md@@ -0,0 +1,2 @@+- **`format: tool-calling` dropped every row `soup agent synth` writes, and `soup train --dry-run` still said "Ready to train!" on 0 rows (#1217 by @abdulwaarith0 in #1321).** The converter now reads calls where agent data puts them: assistant turns keep their own `tool_calls` and `tool` turns their `tool_call_id`, in source order, so a trajectory is no longer rewritten as "answer, then call". A top-level `tool_calls` list still works as the single-call form. `tools` is optional, `format: auto` detects `{messages, tools}` as tool-calling, and synthesised rows carry the schema of the tool they call. `soup train` now exits 1, on `--dry-run` and on a real run, when the data loads zero training rows, naming the format and the first dropped row's reason.+ (#1217 by @abdulwaarith0 in #1321)diff --git a/docs/data.md b/docs/data.mdindex 5699909e..6faeb426 100644--- a/docs/data.md+++ b/docs/data.md@@ -896,7 +896,9 @@ prints `Warning: N of M rows dropped` with the first row's index and theconverter's reason. For a local file it also prints the `soup data validate`command that lists them all. Thecount agrees with `soup data validate` for the same file. Before #1181 the rows-were dropped without a word.+were dropped without a word. If a load ends with zero training rows, `soup train`+stops with exit 1 before loading the model, `--dry-run` included, naming the format+the rows were read as and the first row's drop reason (#1217).## Demo Datasets (`soup data demo`)diff --git a/docs/training.md b/docs/training.mdindex 5f0a1650..953b5cb0 100644--- a/docs/training.md+++ b/docs/training.md@@ -1417,6 +1417,8 @@ training:]}```+Add a top-level `tools` list (OpenAI function schemas) to put the schemas in front of the model as a system turn; with `format: auto`, a row with `messages` and `tools` is detected as tool-calling. Multi-turn trajectories keep their order: each assistant turn keeps its `tool_calls` and each `tool` turn its `tool_call_id`. The older shape, with the calls in a top-level `tool_calls` list, still loads: those calls become one assistant turn after `messages`.+Arguments are parsed as JSON only — never `eval()`. `soup eval custom` can score tool-call accuracy (function name + argument JSON equality).```bashdiff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex 595213e7..c17104ad 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -109,6 +109,45 @@ def _train_sample_count(dcfg, dataset) -> int:return count if valid else rows+def _refuse_empty_train(dcfg, dataset) -> None:+ """Stop a run whose data loaded zero training rows (#1217).++ The loader drops rows its format cannot convert (one bad line must not+ abort a load), so a format mismatch loads nothing and still returns+ cleanly. Before this, ``--dry-run`` then printed "Data OK: 0 train+ samples" and "Config valid. Ready to train!", and the real run loaded the+ model before failing on an empty dataset. Names the format and the first+ drop reason, which is what the user has to change.+ """+ from rich.markup import escape++ from soup_cli.data.loader import last_load_outcome++ if _train_sample_count(dcfg, dataset) > 0:+ return+ outcome = last_load_outcome()+ fmt = outcome.fmt or dcfg.format+ message = (+ f"[red]No training rows:[/] {escape(str(dcfg.train))} loaded 0 train "+ f"samples as format {escape(repr(fmt))}."+ )+ if outcome.first_drop is not None:+ drop_fmt, index, reason, _source = outcome.first_drop+ message += (+ f"\nEvery row that failed to convert was dropped. First: row "+ f"{index} (as {escape(repr(drop_fmt))}): {escape(reason)}."+ "\nFix those rows, or set data.format to the format they are in."+ )+ else:+ message += (+ "\nNo row failed to convert: the data is empty, every row went to "+ "validation (data.val_split), or the rows were skipped for missing "+ "media files."+ )+ console.print(message)+ raise typer.Exit(1)++def _build_hardware_fit_input(cfg):"""Best-effort ``HardwareFitInput`` from a ``SoupConfig``.@@ -1462,7 +1501,10 @@ def train(cfg.data,preserve_source_columns=cfg.task == "grpo",)- console.print(f"[green]Data OK:[/] {len(dataset['train'])} train samples")+ _refuse_empty_train(cfg.data, dataset)+ console.print(+ f"[green]Data OK:[/] {_train_sample_count(cfg.data, dataset)} train samples"+ )if "val" in dataset:console.print(f"[green]Val:[/] {len(dataset['val'])} samples")console.print("[green]Config valid. Ready to train![/]")@@ -1474,6 +1516,7 @@ def train(cfg.data,preserve_source_columns=cfg.task == "grpo",)+ _refuse_empty_train(cfg.data, dataset)console.print(f"[green]Loaded:[/] {_train_sample_count(cfg.data, dataset)} train samples")diff --git a/src/soup_cli/data/formats.py b/src/soup_cli/data/formats.pyindex 3e50dcc6..80190ea3 100644--- a/src/soup_cli/data/formats.py+++ b/src/soup_cli/data/formats.py@@ -12,6 +12,7 @@ Supported formats:- embedding: {"anchor": ..., "positive": ..., "negative": ...} — sentence embedding pairs/triplets- audio: {"audio": ..., "messages": [...]} — audio + conversation for speech models- tool-calling: {"messages": [...], "tools": [...], "tool_calls": [...]} — function-calling training+ (the calls may instead sit on the assistant turns: the OpenAI fine-tuning shape)"""import json@@ -35,7 +36,9 @@ FORMAT_SIGNATURES = {# v0.71.32 — ASR (Whisper): audio path + reference transcript."asr": {"audio", "text"},"plaintext": {"text"},- "tool-calling": {"messages", "tools", "tool_calls"},+ # #1217: top-level "tool_calls" is optional; the OpenAI fine-tuning shape+ # carries "tools" at the top level and the calls inside assistant turns.+ "tool-calling": {"messages", "tools"},}@@ -48,7 +51,7 @@ def detect_format(data: list[dict]) -> str:keys = set(sample.keys())# Check more specific formats first (llava/sharegpt4v before sharegpt).- # tool-calling (messages+tools+tool_calls) is checked BEFORE audio+ # tool-calling (messages+tools) is checked BEFORE audio# (audio+messages): a row carrying both would otherwise match audio first# and silently drop its tools/tool_calls. tool-calling before chatml# (signature is a superset of chatml). asr ({audio, text}) is checked@@ -72,7 +75,7 @@ def detect_format(data: list[dict]) -> str:f"llava/sharegpt4v (image, conversations), "f"embedding (anchor, positive), "f"audio (audio, messages), "- f"tool-calling (messages, tools, tool_calls), "+ f"tool-calling (messages, tools), "f"plaintext (text)")@@ -375,43 +378,17 @@ def _convert_vision(row: dict) -> dict:return result-def _convert_tool_calling(row: dict) -> dict:- """Normalize tool-calling row to unified messages format.-- Input:- {- "messages": [{"role": "user", "content": ...}],- "tools": [{"type": "function", "function": {...}}, ...],- "tool_calls": [{"function": {"name": ..., "arguments": "json-string"}}],- }-- Output (unified format — tool schema embedded in system message,- tool_calls attached to final assistant turn):- {- "messages": [- {"role": "system", "content": "<tool schema description>"},- {"role": "user", "content": "..."},- {"role": "assistant", "content": "", "tool_calls": [...]},- ]- }+def _normalize_tool_calls(tool_calls: object, field: str) -> list[dict]:+ """Validate a ``tool_calls`` list and return it in the unified shape.- Security: every tool_call's 'arguments' must be JSON-parseable. Tool schemas- must be a list of dicts. Invalid rows raise ValueError and are mapped to None- by the outer handler.+ Each call keeps ``function.name`` and ``function.arguments`` (a dict is+ serialized, a string must parse as JSON), plus its ``id`` and ``type`` when+ the source carries them: a ``tool`` turn's ``tool_call_id`` refers to that+ ``id``, and some chat templates render it."""- tools = row["tools"]- tool_calls = row["tool_calls"]-- if not isinstance(tools, list):- raise ValueError("tool-calling 'tools' must be a list")if not isinstance(tool_calls, list):- raise ValueError("tool-calling 'tool_calls' must be a list")-- for tool in tools:- if not isinstance(tool, dict):- raise ValueError("tool-calling tool entries must be dicts")-- normalized_tool_calls = []+ raise ValueError(f"tool-calling '{field}' must be a list")+ normalized = []for call in tool_calls:if not isinstance(call, dict):raise ValueError("tool_calls entries must be dicts")@@ -434,45 +411,138 @@ def _convert_tool_calling(row: dict) -> dict:args_str = json.dumps(args)else:raise ValueError("tool_calls 'arguments' must be str or dict")- normalized_tool_calls.append({- "function": {"name": name, "arguments": args_str},- })+ entry: dict = {}+ for key in ("id", "type"):+ if call.get(key) is not None:+ if not isinstance(call[key], str):+ raise ValueError(f"tool_calls '{key}' must be a string")+ entry[key] = call[key]+ entry["function"] = {"name": name, "arguments": args_str}+ normalized.append(entry)+ return normalized+++def _convert_tool_calling(row: dict) -> dict:+ """Normalize tool-calling row to unified messages format.++ Two input shapes are accepted (#1217):++ - calls nested in the conversation (the OpenAI fine-tuning shape, and what+ ``soup agent synth`` writes): assistant turns carry their own+ ``tool_calls`` and ``tool`` turns their ``tool_call_id``;+ - the legacy single-call shape: the calls sit in a top-level ``tool_calls``+ list and become one assistant turn appended after ``messages``.++ {+ "messages": [{"role": "user", "content": ...}, ...],+ "tools": [{"type": "function", "function": {...}}, ...], # optional+ "tool_calls": [{"function": {"name": ..., "arguments": "json-string"}}],+ }++ Output (unified format: the tool schema, when ``tools`` is non-empty, embedded+ in a leading system message; messages in source order, each assistant turn+ keeping its own tool_calls):+ {+ "messages": [+ {"role": "system", "content": "<tool schema description>"},+ {"role": "user", "content": "..."},+ {"role": "assistant", "content": "", "tool_calls": [...]},+ {"role": "tool", "content": "...", "tool_call_id": "..."},+ {"role": "assistant", "content": "..."},+ ]+ }++ The top-level ``tool_calls`` is appended only when no assistant turn+ already carries calls, so a multi-turn trajectory is never reordered into+ "answer first, call afterwards".++ Security: every tool_call's 'arguments' must be JSON-parseable. Tool schemas+ must be a list of dicts. Invalid rows raise ValueError and are mapped to None+ by the outer handler.+ """+ tools = row.get("tools")+ if isinstance(tools, str):+ # Some exported datasets store the schema list as a JSON string, since+ # per-tool parameter schemas differ from row to row.+ try:+ tools = json.loads(tools)+ except json.JSONDecodeError as exc:+ raise ValueError(+ f"tool-calling 'tools' is a string that is not JSON: {exc}"+ ) from exc+ if tools is not None:+ if not isinstance(tools, list):+ raise ValueError("tool-calling 'tools' must be a list")+ for tool in tools:+ if not isinstance(tool, dict):+ raise ValueError("tool-calling tool entries must be dicts")++ top_level_calls = row.get("tool_calls")+ legacy_tool_calls = (+ [] if top_level_calls is None+ else _normalize_tool_calls(top_level_calls, "tool_calls")+ )original_messages = row["messages"]if not isinstance(original_messages, list) or not original_messages:raise ValueError("tool-calling 'messages' must be a non-empty list")- tool_schema_descriptions = []- for tool in tools:- function_def = tool.get("function", {})- tool_name = function_def.get("name", "unknown")- description = function_def.get("description", "")- params = function_def.get("parameters", {})- tool_schema_descriptions.append(- f"- {tool_name}: {description}\n parameters: {json.dumps(params)}"- )-- system_content = (- "You have access to the following tools. When a tool call is needed, "- "respond with a function call in JSON.\n\n"- + "\n".join(tool_schema_descriptions)- )+ messages: list[dict] = []+ if tools:+ tool_schema_descriptions = []+ for tool in tools:+ function_def = tool.get("function", {})+ tool_name = function_def.get("name", "unknown")+ description = function_def.get("description", "")+ params = function_def.get("parameters", {})+ tool_schema_descriptions.append(+ f"- {tool_name}: {description}\n parameters: {json.dumps(params)}"+ )+ messages.append({+ "role": "system",+ "content": (+ "You have access to the following tools. When a tool call is "+ "needed, respond with a function call in JSON.\n\n"+ + "\n".join(tool_schema_descriptions)+ ),+ })- messages: list[dict] = [{"role": "system", "content": system_content}]+ has_nested_calls = Falsefor msg in original_messages:if not isinstance(msg, dict) or "role" not in msg:raise ValueError("tool-calling messages must be dicts with 'role'")- if msg["role"] == "system":+ role = msg["role"]+ if role == "system" and tools:# Merge user system message into our synthesized system contentmessages[0]["content"] = msg.get("content", "") + "\n\n" + messages[0]["content"]continue- messages.append({"role": msg["role"], "content": msg.get("content", "")})-- if normalized_tool_calls:+ content = msg.get("content", "")+ calls = []+ if role == "assistant" and msg.get("tool_calls") is not None:+ calls = _normalize_tool_calls(msg["tool_calls"], "messages.tool_calls")+ if calls and content is None:+ # The OpenAI shape writes "content": null on a call-only turn.+ content = ""+ # Any other null content would render as the literal text "None" in a+ # chat template, so the row is dropped, as the other converters do.+ out = {+ "role": role,+ "content": _require_str_content(content, f"tool-calling {role} content"),+ }+ if calls:+ has_nested_calls = True+ out["tool_calls"] = calls+ elif role == "tool" and msg.get("tool_call_id") is not None:+ if not isinstance(msg["tool_call_id"], str):+ raise ValueError("tool-calling 'tool_call_id' must be a string")+ out["tool_call_id"] = msg["tool_call_id"]+ messages.append(out)++ if legacy_tool_calls and not has_nested_calls:messages.append({"role": "assistant","content": "",- "tool_calls": normalized_tool_calls,+ "tool_calls": legacy_tool_calls,})return {"messages": messages}diff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.pyindex 90f98572..c57cb58a 100644--- a/src/soup_cli/data/loader.py+++ b/src/soup_cli/data/loader.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+from dataclasses import dataclass, replacefrom pathlib import Pathfrom rich.console import Console@@ -168,6 +169,31 @@ def _load_txt(path: Path) -> list[dict]:return [{"text": line} for line in lines]+@dataclass(frozen=True)+class LoadOutcome:+ """What the most recent :func:`load_dataset` call converted (#1217).++ ``fmt`` is the format the rows were converted as (resolved, never+ ``"auto"``); ``first_drop`` is ``(format, row index, reason, source)`` for+ the first row a converter dropped. ``soup train`` reads it to say why a+ load ended with zero training rows instead of printing "Ready to train".++ Frozen, and replaced (never mutated) as a load progresses, so a caller+ holding one keeps a snapshot that no later load can change.+ """++ fmt: str | None = None+ first_drop: tuple[str, int, str, str | None] | None = None+++_last_load = LoadOutcome()+++def last_load_outcome() -> LoadOutcome:+ """The :class:`LoadOutcome` of the most recent :func:`load_dataset` call."""+ return _last_load++def _format_rows(raw_data: list[dict],fmt: str,@@ -199,8 +225,15 @@ def _format_rows(if preserve_source_columns:normalized = {**raw_row, **normalized}formatted.append(normalized)+ global _last_loadif dropped and first_drop is not None:_report_dropped_rows(dropped, len(raw_data), fmt, first_drop, source)+ if _last_load.first_drop is None:+ _last_load = replace(+ _last_load, first_drop=(fmt, first_drop[0], first_drop[1], source)+ )+ if _last_load.fmt is None:+ _last_load = replace(_last_load, fmt=fmt)return formatted@@ -391,6 +424,9 @@ def load_dataset(consistently whenever data.train is a list, so this branch only hasto pick which loader — not re-validate the shape."""+ global _last_load+ _last_load = LoadOutcome()+train_path = data_config.trainif isinstance(train_path, list):diff --git a/src/soup_cli/data/sft_format.py b/src/soup_cli/data/sft_format.pyindex 30d6929d..63ba6364 100644--- a/src/soup_cli/data/sft_format.py+++ b/src/soup_cli/data/sft_format.py@@ -81,11 +81,13 @@ def build_format_row("has no chat_template — falling back to text path. Pass ""data.chat_template explicitly to enable masking.[/]")- return _wrap_with_prompt_strategy(- _wrap_with_reasoning_effort(- _legacy_text_format_row(tokenizer), reasoning_effort- ),- prompt_strategy_spec,+ return _wrap_dropping_arrow_nulls(+ _wrap_with_prompt_strategy(+ _wrap_with_reasoning_effort(+ _legacy_text_format_row(tokenizer), reasoning_effort+ ),+ prompt_strategy_spec,+ ))if use_train_field:@@ -99,12 +101,42 @@ def build_format_row()else:inner = _build_full_sequence_format_row(tokenizer, max_length)- return _wrap_with_prompt_strategy(- _wrap_with_reasoning_effort(inner, reasoning_effort),- prompt_strategy_spec,+ return _wrap_dropping_arrow_nulls(+ _wrap_with_prompt_strategy(+ _wrap_with_reasoning_effort(inner, reasoning_effort),+ prompt_strategy_spec,+ ))+# Per-message keys only some turns carry (#1217). ``Dataset.from_list`` gives+# every message every key seen in the column, so a plain user turn reaches the+# formatter as ``{"tool_calls": None, "tool_call_id": None, ...}``, and a+# template that branches on ``'tool_calls' in message`` (Llama 3.x) renders+# it as a call.+_SPARSE_MESSAGE_KEYS = ("tool_calls", "tool_call_id")+++def _wrap_dropping_arrow_nulls(inner: Callable[[dict], dict]) -> Callable[[dict], dict]:+ """Decorate ``inner`` so the ``None`` placeholders Arrow adds are removed."""++ def wrapped(example: dict) -> dict:+ msgs = example.get("messages")+ if not isinstance(msgs, list):+ return inner(example)+ cleaned = [+ {+ key: value for key, value in msg.items()+ if not (key in _SPARSE_MESSAGE_KEYS and value is None)+ }+ if isinstance(msg, dict) else msg+ for msg in msgs+ ]+ return inner({**example, "messages": cleaned})++ return wrapped++def _wrap_with_prompt_strategy(inner: Callable[[dict], dict], spec: Any | None) -> Callable[[dict], dict]:diff --git a/src/soup_cli/utils/agent_forge.py b/src/soup_cli/utils/agent_forge.pyindex 1a34ec37..ba323382 100644--- a/src/soup_cli/utils/agent_forge.py+++ b/src/soup_cli/utils/agent_forge.py@@ -3,7 +3,7 @@Parses OpenAPI 3.x, MCP server manifests, and GraphQL introspection JSONinto a canonical ``Endpoint`` shape, then synthesises a tool-calling SFTdataset where each row is ``{messages: [user, assistant{tool_calls}],-tool: <name>, source_endpoint: <path>}``.+tools: [<schema>], tool: <name>, source_endpoint: <path>}``.The parser surface is intentionally parser-only — no network code, no``$ref`` resolution that would let a crafted spec read arbitrary files.@@ -56,13 +56,20 @@ class SynthRow:messages: Tuple[Mapping[str, Any], ...]tool: strsource_endpoint: str+ # #1217: the OpenAI-style schema of the tool the row calls. Written as a+ # top-level "tools" key so `format: tool-calling` puts the schema in front+ # of the model and `format: auto` detects the row as tool-calling.+ tools: Tuple[Mapping[str, Any], ...] = ()def to_dict(self) -> Dict[str, Any]:- return {+ out: Dict[str, Any] = {"messages": [dict(m) for m in self.messages],"tool": self.tool,"source_endpoint": self.source_endpoint,}+ if self.tools:+ out["tools"] = [dict(t) for t in self.tools]+ return out@dataclass(frozen=True)@@ -417,6 +424,19 @@ def endpoint_to_rows(f"examples_per_endpoint must be in [1, {_MAX_ROWS_PER_ENDPOINT}]")desc = endpoint.description or f"Call {endpoint.tool}"+ # Parameter schemas stay opaque (see Endpoint.parameters), so each+ # property is typed as "any" rather than guessed.+ tool_schema = {+ "type": "function",+ "function": {+ "name": endpoint.tool,+ "description": desc,+ "parameters": {+ "type": "object",+ "properties": {p: {} for p in endpoint.parameters},+ },+ },+ }user_templates = [f"Please {desc}.",f"How do I use {endpoint.tool}?",@@ -447,6 +467,7 @@ def endpoint_to_rows(),tool=endpoint.tool,source_endpoint=endpoint.path,+ tools=(tool_schema,),))return rowsdiff --git a/tests/test_issue1217_tool_calling_nested.py b/tests/test_issue1217_tool_calling_nested.pynew file mode 100644index 00000000..860295ef--- /dev/null+++ b/tests/test_issue1217_tool_calling_nested.py@@ -0,0 +1,483 @@+"""#1217: `format: tool-calling` reads the calls where agent data puts them.++`soup agent synth` / `soup agent train` write each call inside its assistant+turn (the OpenAI shape), but the tool-calling converter only read top-level+`tools` / `tool_calls` keys, so every synthesised row was dropped and+`soup train --dry-run` still printed "Ready to train!". In rows it did accept,+the call was re-appended after the final answer and `tool_call_id` was lost.++The converter now keeps the calls on their own turns (the top-level list is+the legacy single-call form), `tools` is optional, `detect_format` classifies+`{messages, tools}` as tool-calling, and synth rows carry a `tools` schema.+The zero-row stop is covered in test_issue1217_zero_row_stop.py.+"""++from __future__ import annotations++import json+import re+from pathlib import Path+from types import SimpleNamespace++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.schema import DataConfig+from soup_cli.data.formats import (+ detect_format,+ format_to_messages,+ format_to_messages_with_reason,+)+from soup_cli.data.loader import load_dataset+from soup_cli.utils.agent_forge import (+ Endpoint,+ endpoint_to_rows,+ synthesise_dataset,+ write_dataset,+)+from tests.conftest import strip_ansi++_BASE = "hf-internal-testing/tiny-random-LlamaForCausalLM"+_WEATHER_TOOL = {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Weather for a city",+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},+ },+}+_SCHEMA_TURN = {+ "role": "system",+ "content": (+ "You have access to the following tools. When a tool call is needed, "+ "respond with a function call in JSON.\n\n"+ "- get_weather: Weather for a city\n"+ ' parameters: {"type": "object", "properties": {"city": {"type": "string"}}}'+ ),+}+++def _call(call_id: str, city: str, *, as_dict: bool = False) -> dict:+ arguments = {"city": city} if as_dict else json.dumps({"city": city})+ return {+ "id": call_id,+ "type": "function",+ "function": {"name": "get_weather", "arguments": arguments},+ }+++def _normalized_call(call_id: str, city: str) -> dict:+ return {+ "id": call_id,+ "type": "function",+ "function": {"name": "get_weather", "arguments": json.dumps({"city": city})},+ }+++def _plain(text: str) -> str:+ return re.sub(r"\s+", " ", strip_ansi(text)).strip()+++def _write_jsonl(path: Path, rows: list[dict]) -> None:+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")+++def _loaded_rows(path: str, data_format: str) -> list[dict]:+ """The rows `soup train` would train on."""+ config = DataConfig(train=path, format=data_format, val_split=0.0)+ return list(load_dataset(config)["train"])+++# --- The synthesised dataset loads with the recipe `soup agent train` prints ---+++_ENDPOINTS = [+ Endpoint(tool="listPets", method="get", path="/pets", description="List pets",+ parameters=(), spec_kind="openapi"),+ Endpoint(tool="getPet", method="get", path="/pets/{id}", description="Get a pet",+ parameters=("id", "fields"), spec_kind="openapi"),+]++[email protected]("data_format", ["tool-calling", "auto"])+def test_every_synthesised_row_loads_with_its_tool_call(+ tmp_path, monkeypatch, data_format+):+ monkeypatch.chdir(tmp_path)+ rows = synthesise_dataset(_ENDPOINTS, examples_per_endpoint=3)+ write_dataset(rows, "agent_dataset.jsonl")++ loaded = _loaded_rows("agent_dataset.jsonl", data_format)++ assert len(loaded) == len(rows) == 6+ for source, got in zip(rows, loaded):+ calls = [m for m in got["messages"] if m.get("tool_calls")]+ assert len(calls) == 1+ assert calls[0]["tool_calls"][0]["function"]["name"] == source.tool+ assert got["messages"][0]["role"] == "system"+ assert f"- {source.tool}: " in got["messages"][0]["content"]+++def test_the_printed_recipe_dry_runs_with_the_synthesised_rows(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ Path("openapi.yaml").write_text(+ "openapi: 3.0.0\ninfo: {title: pets, version: '1'}\npaths:\n"+ " /pets:\n get:\n operationId: listPets\n summary: List pets\n",+ encoding="utf-8",+ )+ runner = CliRunner()+ planned = runner.invoke(app, ["agent", "train", "--spec", "openapi.yaml", "--base", _BASE])+ assert planned.exit_code == 0, planned.output+ assert "format: tool-calling" in planned.output+ Path("agent_train.yaml").write_text(+ f"base: {_BASE}\ntask: sft\ndata:\n train: agent_dataset.jsonl\n"+ " format: tool-calling\n val_split: 0.0\n"+ "training:\n epochs: 3\n lr: 2.0e-5\n batch_size: auto\n"+ "output: ./agent_train_output\n",+ encoding="utf-8",+ )++ result = runner.invoke(app, ["train", "--config", "agent_train.yaml", "--dry-run"])++ output = _plain(result.output)+ assert result.exit_code == 0, output+ assert "Data OK: 4 train samples" in output+ assert "dropped" not in output+++def test_a_synth_row_carries_the_schema_of_its_endpoint():+ row = endpoint_to_rows(_ENDPOINTS[1], 1)[0].to_dict()++ assert row["tools"] == [{+ "type": "function",+ "function": {+ "name": "getPet",+ "description": "Get a pet",+ "parameters": {"type": "object", "properties": {"id": {}, "fields": {}}},+ },+ }]+ assert detect_format([row]) == "tool-calling"+++# --- Each row shape, converted exactly --------------------------------------+++def test_call_nested_in_the_assistant_turn_without_top_level_keys():+ row = {"messages": [+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "tool_calls": [_call("call_0", "Paris")]},+ ]}++ assert format_to_messages(row, "tool-calling") == {"messages": [+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "tool_calls": [_normalized_call("call_0", "Paris")]},+ ]}+++def test_the_openai_fine_tuning_shape():+ row = {+ "messages": [+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": None, "tool_calls": [_call("call_0", "Paris")]},+ {"role": "tool", "tool_call_id": "call_0", "content": '{"temp": 21}'},+ {"role": "assistant", "content": "It is 21 C in Paris."},+ ],+ "tools": [_WEATHER_TOOL],+ }++ assert format_to_messages(row, "tool-calling") == {"messages": [+ _SCHEMA_TURN,+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "tool_calls": [_normalized_call("call_0", "Paris")]},+ {"role": "tool", "content": '{"temp": 21}', "tool_call_id": "call_0"},+ {"role": "assistant", "content": "It is 21 C in Paris."},+ ]}+++def test_the_documented_top_level_shape_still_converts():+ row = {+ "messages": [{"role": "user", "content": "Weather in Paris?"}],+ "tools": [_WEATHER_TOOL],+ "tool_calls": [{"function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}}],+ }++ assert format_to_messages(row, "tool-calling") == {"messages": [+ _SCHEMA_TURN,+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}},+ ]},+ ]}+++def test_two_tool_rounds_keep_source_order_and_their_ids():+ messages = [+ {"role": "user", "content": "Paris, then Rome?"},+ {"role": "assistant", "content": "", "tool_calls": [_call("call_0", "Paris")]},+ {"role": "tool", "tool_call_id": "call_0", "content": "21"},+ {"role": "assistant", "content": "", "tool_calls": [_call("call_1", "Rome")]},+ {"role": "tool", "tool_call_id": "call_1", "content": "25"},+ {"role": "assistant", "content": "Paris 21 C, Rome 25 C."},+ ]+ # The top-level list repeats the calls, as the issue's documented-shape+ # row does; it must not be appended after the final answer again.+ row = {+ "messages": messages,+ "tools": [_WEATHER_TOOL],+ "tool_calls": [_call("call_0", "Paris")],+ }++ converted = format_to_messages(row, "tool-calling")["messages"]++ assert [m["role"] for m in converted] == [+ "system", "user", "assistant", "tool", "assistant", "tool", "assistant",+ ]+ assert converted[2]["tool_calls"] == [_normalized_call("call_0", "Paris")]+ assert converted[3]["tool_call_id"] == "call_0"+ assert converted[4]["tool_calls"] == [_normalized_call("call_1", "Rome")]+ assert converted[5]["tool_call_id"] == "call_1"+ assert converted[6] == {"role": "assistant", "content": "Paris 21 C, Rome 25 C."}+++def test_two_parallel_calls_in_one_assistant_turn():+ row = {+ "messages": [+ {"role": "user", "content": "Paris and Rome?"},+ {"role": "assistant", "content": "",+ "tool_calls": [_call("call_0", "Paris"), _call("call_1", "Rome")]},+ {"role": "tool", "tool_call_id": "call_0", "content": "21"},+ {"role": "tool", "tool_call_id": "call_1", "content": "25"},+ {"role": "assistant", "content": "21 and 25."},+ ],+ "tools": [_WEATHER_TOOL],+ }++ converted = format_to_messages(row, "tool-calling")["messages"]++ assert converted[2]["tool_calls"] == [+ _normalized_call("call_0", "Paris"), _normalized_call("call_1", "Rome"),+ ]+ assert [m.get("tool_call_id") for m in converted[3:5]] == ["call_0", "call_1"]+ assert converted[-1] == {"role": "assistant", "content": "21 and 25."}++[email protected]("as_dict", [False, True], ids=["json-string", "dict"])+def test_arguments_as_a_json_string_or_a_dict(as_dict):+ row = {"messages": [+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "tool_calls": [_call("c", "Paris", as_dict=as_dict)]},+ ]}++ converted = format_to_messages(row, "tool-calling")["messages"]++ assert converted[1]["tool_calls"][0]["function"]["arguments"] == '{"city": "Paris"}'++[email protected]("tools", [None, []], ids=["absent", "empty"])+def test_without_tools_there_is_no_schema_turn(tools):+ row = {"messages": [+ {"role": "system", "content": "Be brief."},+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "tool_calls": [_call("c", "Paris")]},+ ]}+ if tools is not None:+ row["tools"] = tools++ converted = format_to_messages(row, "tool-calling")["messages"]++ assert converted[0] == {"role": "system", "content": "Be brief."}+ assert [m["role"] for m in converted] == ["system", "user", "assistant"]+++def test_with_tools_the_rows_system_prompt_is_merged_into_the_schema_turn():+ row = {+ "messages": [+ {"role": "system", "content": "Be brief."},+ {"role": "user", "content": "Weather in Paris?"},+ ],+ "tools": [_WEATHER_TOOL],+ }++ converted = format_to_messages(row, "tool-calling")["messages"]++ assert converted[0] == {+ "role": "system", "content": "Be brief.\n\n" + _SCHEMA_TURN["content"],+ }+ assert [m["role"] for m in converted] == ["system", "user"]+++_OPENAI_ROW = {+ "messages": [+ {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "tool_calls": [_call("call_0", "Paris")]},+ {"role": "tool", "tool_call_id": "call_0", "content": "21"},+ {"role": "assistant", "content": "21 C."},+ ],+ "tools": [_WEATHER_TOOL],+}+++def test_auto_detects_the_openai_shape_and_converts_it_like_the_explicit_format(tmp_path):+ path = tmp_path / "agent.jsonl"+ _write_jsonl(path, [_OPENAI_ROW])++ assert detect_format([_OPENAI_ROW]) == "tool-calling"+ assert _loaded_rows(str(path), "auto") == _loaded_rows(str(path), "tool-calling")+++def test_auto_keeps_nested_calls_when_the_row_has_no_tools(tmp_path):+ # No top-level "tools": the row is plain chatml, which keeps the messages+ # (and their calls) as written.+ row = {"messages": _OPENAI_ROW["messages"]}+ path = tmp_path / "chat.jsonl"+ _write_jsonl(path, [row])++ assert _loaded_rows(str(path), "auto") == [row]+++def test_tool_calling_is_still_detected_before_audio():+ row = {**_OPENAI_ROW, "audio": "a.wav"}++ assert detect_format([row]) == "tool-calling"+++def test_tools_as_a_json_string_convert_like_a_list(tmp_path):+ row = {**_OPENAI_ROW, "tools": json.dumps([_WEATHER_TOOL])}+ path = tmp_path / "agent.jsonl"+ _write_jsonl(path, [row])++ assert format_to_messages(row, "tool-calling") == format_to_messages(+ _OPENAI_ROW, "tool-calling"+ )+ assert len(_loaded_rows(str(path), "auto")) == 1+++def test_tools_as_a_string_that_is_not_json_drops_the_row():+ row = {**_OPENAI_ROW, "tools": "{not json"}++ converted, why = format_to_messages_with_reason(row, "tool-calling")++ assert converted is None+ assert "'tools' is a string that is not JSON" in why+++# --- Null content is only allowed on a call-only assistant turn --------------+++# A call-only turn with null content converting to "" is pinned by+# test_the_openai_fine_tuning_shape above.+++ "turn",+ [+ {"role": "assistant", "content": None, "tool_calls": []},+ {"role": "assistant", "content": None},+ {"role": "user", "content": None},+ {"role": "tool", "tool_call_id": "call_0", "content": None},+ ],+ ids=["assistant-empty-calls", "assistant-no-calls", "user", "tool"],+)+def test_null_content_outside_a_call_turn_drops_the_row(turn):+ # A template printing {{ message.content }} would render the literal "None".+ row = {"messages": [{"role": "user", "content": "q"}, turn]}++ converted, why = format_to_messages_with_reason(row, "tool-calling")++ assert converted is None+ assert f"tool-calling {turn['role']} content must be a string" in why+++# --- Malformed nested calls are still dropped, with a reason -----------------+++ ("assistant", "reason"),+ [+ ({"role": "assistant", "tool_calls": [+ {"function": {"name": "get_weather", "arguments": "{bad"}}]},+ "must be JSON-parseable"),+ ({"role": "assistant", "tool_calls": {"function": {"name": "f"}}},+ "'messages.tool_calls' must be a list"),+ ({"role": "assistant", "tool_calls": [{"function": {"name": ""}}]},+ "'function.name' must be a non-empty string"),+ ({"role": "assistant", "tool_calls": [+ {"id": 7, "function": {"name": "f", "arguments": "{}"}}]},+ "'id' must be a string"),+ ],+ ids=["bad-json", "not-a-list", "empty-name", "non-string-id"],+)+def test_a_malformed_nested_call_drops_the_row(assistant, reason):+ row = {"messages": [{"role": "user", "content": "q"}, assistant]}++ converted, why = format_to_messages_with_reason(row, "tool-calling")++ assert converted is None+ assert reason in why+++def test_a_non_string_tool_call_id_drops_the_row():+ row = {"messages": [+ {"role": "user", "content": "q"},+ {"role": "tool", "tool_call_id": 3, "content": "21"},+ ]}++ converted, why = format_to_messages_with_reason(row, "tool-calling")++ assert converted is None+ assert "'tool_call_id' must be a string" in why+++# --- The rendered training text, through Arrow and a tool-aware template -------+++# The Llama 3.x templates branch on `'tool_calls' in message`, so they see a+# key that is present with a None value as a call.+_LLAMA_STYLE_TEMPLATE = (+ "{%- for message in messages %}"+ "{%- if message.role == 'tool' %}"+ "<tool id={{ message.tool_call_id }}>{{ message.content }}</tool>"+ "{%- elif 'tool_calls' in message %}"+ "{%- if message.tool_calls|length != 1 %}"+ "{{ raise_exception('one call per turn') }}"+ "{%- endif %}"+ "{% generation %}<call>{{ message.tool_calls[0].function.name }}"+ "({{ message.tool_calls[0].function.arguments }})</call>{% endgeneration %}"+ "{%- elif message.role == 'assistant' %}"+ "{% generation %}<a>{{ message.content }}</a>{% endgeneration %}"+ "{%- else %}<{{ message.role }}>{{ message.content }}</{{ message.role }}>"+ "{%- endif %}"+ "{%- endfor %}"+)+++def test_the_trajectory_renders_in_source_order_through_arrow():+ from datasets import Dataset+ from transformers import AutoTokenizer++ from soup_cli.data.sft_format import build_format_row++ tokenizer = AutoTokenizer.from_pretrained(_BASE)+ tokenizer.chat_template = _LLAMA_STYLE_TEMPLATE+ data_cfg = SimpleNamespace(+ chat_template=None,+ train_on_responses_only=True,+ train_on_messages_with_train_field=False,+ max_length=512,+ )+ row = format_to_messages({"messages": _OPENAI_ROW["messages"]}, "tool-calling")+ # The trainer maps rows through Arrow, which gives every message the+ # sparse keys it lacks as None (a user turn gets "tool_calls": None).+ arrow_rows = Dataset.from_list([row])+ assert arrow_rows[0]["messages"][0]["tool_calls"] is None++ formatted = arrow_rows.map(+ build_format_row(tokenizer, data_cfg), remove_columns=["messages"]+ )++ text = tokenizer.decode(formatted[0]["input_ids"], skip_special_tokens=True)+ assert re.sub(r"\s+", "", text) == re.sub(r"\s+", "", (+ '<user>Weather in Paris?</user><call>get_weather({"city": "Paris"})</call>'+ "<tool id=call_0>21</tool><a>21 C.</a>"+ ))diff --git a/tests/test_issue1217_zero_row_stop.py b/tests/test_issue1217_zero_row_stop.pynew file mode 100644index 00000000..3320b292--- /dev/null+++ b/tests/test_issue1217_zero_row_stop.py@@ -0,0 +1,189 @@+"""#1217: a load that ends with zero training rows stops `soup train`.++The loader drops rows its format cannot convert, so a format mismatch loads+nothing and still returns cleanly. `soup train --dry-run` then printed+"Data OK: 0 train samples" and "Config valid. Ready to train!", and the real+run loaded the model before failing on an empty dataset. Both now exit 1+with the format and the first drop reason.+"""++from __future__ import annotations++import dataclasses+import json+import re+from pathlib import Path+from types import SimpleNamespace++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.schema import DataConfig+from soup_cli.data.loader import last_load_outcome, load_dataset+from tests.conftest import strip_ansi++_BASE = "hf-internal-testing/tiny-random-LlamaForCausalLM"+_CHAT = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}]+++def _plain(text: str) -> str:+ return re.sub(r"\s+", " ", strip_ansi(text)).strip()+++def _write_jsonl(path: Path, rows: list[dict]) -> None:+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")+++def _loaded_rows(path: str, data_format: str) -> list[dict]:+ config = DataConfig(train=path, format=data_format, val_split=0.0)+ return list(load_dataset(config)["train"])++++def _write_config(path: Path, data_file: str, data_format: str) -> None:+ path.write_text(+ f"base: {_BASE}\ntask: sft\ndata:\n train: {data_file}\n"+ f" format: {data_format}\n val_split: 0.0\noutput: ./out\n",+ encoding="utf-8",+ )+++def test_dry_run_with_zero_rows_exits_non_zero_naming_format_and_reason(+ tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ _write_jsonl(Path("data.jsonl"), [{"instruction": "q", "output": "a"}] * 2)+ _write_config(Path("soup.yaml"), "data.jsonl", "chatml")++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ output = _plain(result.output)+ assert result.exit_code == 1, output+ assert "Ready to train" not in output+ assert "Data OK" not in output+ assert (+ "No training rows: data.jsonl loaded 0 train samples as format 'chatml'."+ ) in output+ assert "First: row 0 (as 'chatml'): 'messages'." in output+++def test_the_real_run_with_zero_rows_stops_before_the_model_loads(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ _write_jsonl(Path("data.jsonl"), [{"instruction": "q", "output": "a"}])+ _write_config(Path("soup.yaml"), "data.jsonl", "chatml")++ import soup_cli.trainer.sft as sft++ def _must_not_run(*args, **kwargs):+ raise AssertionError("the trainer was set up for a run with no rows")++ monkeypatch.setattr(sft.SFTTrainerWrapper, "setup", _must_not_run)++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])++ output = _plain(result.output)+ assert result.exit_code == 1, output+ assert "No training rows: data.jsonl loaded 0 train samples as format 'chatml'." in output+ assert "Loaded:" not in output+++def test_zero_rows_without_a_drop_says_no_row_failed_to_convert(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ # A drop in an earlier load must not leak into this one's message.+ _write_jsonl(Path("bad.jsonl"), [{"instruction": "q", "output": "a"}])+ _loaded_rows("bad.jsonl", "chatml")+ assert last_load_outcome().first_drop is not None+ Path("empty.jsonl").write_text("", encoding="utf-8")+ _write_config(Path("soup.yaml"), "empty.jsonl", "chatml")++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ output = _plain(result.output)+ assert result.exit_code == 1, output+ assert "loaded 0 train samples as format 'chatml'." in output+ assert "No row failed to convert" in output+ assert "First: row" not in output+++def test_dry_run_with_rows_still_says_ready_to_train(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ _write_jsonl(Path("data.jsonl"), [{"messages": _CHAT}])+ _write_config(Path("soup.yaml"), "data.jsonl", "chatml")++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ output = _plain(result.output)+ assert result.exit_code == 0, output+ assert "Data OK: 1 train samples" in output+ assert "Config valid. Ready to train!" in output+++def test_a_pre_tokenized_run_counts_its_cache_not_the_loaders_view(tmp_path):+ # #1054: under `pre_tokenized` the loader sees the original file and keeps+ # nothing, while training reads the Arrow cache. The stop must not fire.+ import typer++ from soup_cli.commands.train import _refuse_empty_train++ cache = tmp_path / "cache"+ cache.mkdir()+ (cache / "metadata.json").write_text(json.dumps({"row_count": 6}), encoding="utf-8")+ dcfg = SimpleNamespace(format="pre_tokenized", tokenized_path=str(cache), train="d.jsonl")++ _refuse_empty_train(dcfg, {"train": []})++ (cache / "metadata.json").unlink()+ with pytest.raises(typer.Exit):+ _refuse_empty_train(dcfg, {"train": []})+++def test_a_pre_tokenized_dry_run_reports_the_caches_row_count(tmp_path, monkeypatch):+ # The loader sees the original file and keeps nothing; the run trains on+ # the cache's rows, so that is the count the dry run must print.+ monkeypatch.chdir(tmp_path)+ Path("cache").mkdir()+ Path("cache/metadata.json").write_text(json.dumps({"row_count": 6}), encoding="utf-8")+ _write_jsonl(Path("data.jsonl"), [{"messages": _CHAT}])+ Path("soup.yaml").write_text(+ f"base: {_BASE}\ntask: sft\ndata:\n train: data.jsonl\n"+ " format: pre_tokenized\n tokenized_path: ./cache\n val_split: 0.0\n"+ "output: ./out\n",+ encoding="utf-8",+ )++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ output = _plain(result.output)+ assert result.exit_code == 0, output+ assert "Data OK: 6 train samples" in output+ assert "Config valid. Ready to train!" in output+++def test_the_outcome_is_a_snapshot_no_caller_or_later_load_can_change(+ tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ _write_jsonl(Path("bad.jsonl"), [{"instruction": "q", "output": "a"}])+ _write_jsonl(Path("good.jsonl"), [{"messages": _CHAT}])++ _loaded_rows("bad.jsonl", "chatml")+ held = last_load_outcome()+ with pytest.raises(dataclasses.FrozenInstanceError):+ held.first_drop = None++ _loaded_rows("good.jsonl", "chatml")++ assert held.first_drop == ("chatml", 0, "'messages'", "bad.jsonl")+ assert last_load_outcome().first_drop is None+++def test_the_outcome_names_the_resolved_format_not_auto(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ _write_jsonl(Path("data.jsonl"), [{"messages": _CHAT}, {"instruction": "q"}])++ assert len(_loaded_rows("data.jsonl", "auto")) == 1++ outcome = last_load_outcome()+ assert outcome.fmt == "chatml"+ assert outcome.first_drop == ("chatml", 1, "'messages'", "data.jsonl")diff --git a/tests/test_issue764_run_status_reconciliation.py b/tests/test_issue764_run_status_reconciliation.pyindex bdb61766..7a9c5bc8 100644--- a/tests/test_issue764_run_status_reconciliation.py+++ b/tests/test_issue764_run_status_reconciliation.py@@ -34,7 +34,9 @@ def _write_config(tmp_path):(tmp_path / "soup.yaml").write_text("base: sshleifer/tiny-gpt2\n""task: sft\n"- "data: {train: data.jsonl, format: alpaca}\n"+ # val_split 0: at the default 0.1 the one row goes to validation and+ # `soup train` stops on an empty train split (#1217).+ "data: {train: data.jsonl, format: alpaca, val_split: 0.0}\n""training: {epochs: 1, lr: 1e-4, batch_size: 1}\n",encoding="utf-8",)diff --git a/tests/test_issue835_fp8_gate.py b/tests/test_issue835_fp8_gate.pyindex dd128518..b4177851 100644--- a/tests/test_issue835_fp8_gate.py+++ b/tests/test_issue835_fp8_gate.py@@ -591,7 +591,12 @@ class TestSoupTrainReachesTheStop:yaml.safe_dump({"base": "nobody/not-a-real-model","task": "sft",- "data": {"train": "train.jsonl", "format": "chatml", "max_length": 64},+ # val_split 0: at the default 0.1 the one row goes to validation+ # and `soup train` stops on an empty train split (#1217).+ "data": {+ "train": "train.jsonl", "format": "chatml", "max_length": 64,+ "val_split": 0.0,+ },**({"backend": backend} if backend else {}),"training": {"epochs": 1,