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): wire classifier, reranker, and cross_encoder data loading (#1219) (#1306)
Nurkhan Esenbek2bcdbc9a7c6f
diff --git a/changelog.d/0.75.1/1306.fixed.md b/changelog.d/0.75.1/1306.fixed.mdnew file mode 100644index 00000000..fbb166e9--- /dev/null+++ b/changelog.d/0.75.1/1306.fixed.md@@ -0,0 +1 @@+- **Fix classifier, reranker, and cross_encoder data loading and row validation (#1219 by @kok-o in #1306).** Sequence classification tasks (`classifier`, `reranker`, `cross_encoder`) were losing dataset columns such as `label`, `text_a`, `text_b`, `question`, and `answer` during dataset normalization because `preserve_source_columns` was restricted to `task == "grpo"`, causing crashes with `TypeError: label must be int / str / list, got NoneType` after model loading. Centralized source column retention in `task_preserves_source_columns` shared across `soup train` and `soup sweep`, added task-scoped `cross_encoder` format handling for `text_a`/`text_b` and `question`/`answer` pairs, gated `data.format: cross_encoder` to `task: cross_encoder` at schema validation, and added upfront dataset label and shape validation that fails immediately at data load and on `--dry-run` with specific row indices before model weights are loaded.diff --git a/docs/data.md b/docs/data.mdindex 1b08ab24..d154ad85 100644--- a/docs/data.md+++ b/docs/data.md@@ -663,6 +663,13 @@ Or use `.txt` files directly (one document per line).With `embedding_loss: contrastive` (the default), each row's negatives are the other rows' positives in the same batch, so a batch needs at least two rows: `batch_size: 1` is refused at config load, `batch_size: auto` resolves to at least 2, and the last partial batch of each epoch is dropped. This also applies when `triplet` falls back to contrastive because the rows have no `negative`. Use `triplet` with a `negative` on every row, or `cosine`, to train at batch size 1.+**Cross-Encoder (paired sequence classification - `data.format: cross_encoder`):**+```json+{"text_a": "What is Python?", "text_b": "Python is a programming language.", "label": 1}+{"question": "What is Python?", "answer": "Python is a programming language.", "label": 1}+```+Reads paired text columns (`text_a`/`text_b` or `question`/`answer`) carrying a `label` field. Gated strictly to `task: cross_encoder` (`format: auto` resolves to `cross_encoder` for this task) to preserve global format detection for other tasks.+**Audio (speech + conversation):**```json{"audio": "recording.wav", "messages": [{"role": "user", "content": "Transcribe."}, {"role": "assistant", "content": "Hello world."}]}diff --git a/docs/training.md b/docs/training.mdindex 101993fa..a3cfca24 100644--- a/docs/training.md+++ b/docs/training.md@@ -665,7 +665,7 @@ modality: textbackend: transformersdata:- train: ./data/labelled.jsonl # rows: {"text": "...", "label": "spam"} or {"text": "...", "label": [0, 1, 0]}+ train: ./data/labelled.jsonl # rows: {"text": "...", "label": "spam"} or {"text": "...", "label": [0, 2]}max_length: 256training:@@ -677,6 +677,11 @@ training:batch_size: 32```+**Row shapes by task:**+- `task: classifier`: Single-input sequences via `{"text": "sample", "label": 1}` or `{"text": "sample", "label": "spam"}` (also accepts ChatML rows carrying `label`). Multi-label datasets pass lists of active label indices or names: `{"text": "sample", "label": [0, 2]}` or `{"text": "sample", "label": ["ham", "promo"]}`.+- `task: reranker`: Query and document text via `{"text": "query doc", "label": "relevant"}` (or an integer class index).+- `task: cross_encoder`: Paired inputs via `{"text_a": "query", "text_b": "doc", "label": 1}` or `{"question": "query", "answer": "doc", "label": 1}`.+Routes `classifier` / `reranker` / `cross_encoder` through`AutoModelForSequenceClassification`. Multi-label heads cap at 1024 entries perrow, dedup via set conversion, and reject null bytes in label strings.diff --git a/src/soup_cli/commands/sweep.py b/src/soup_cli/commands/sweep.pyindex a4db9aaf..13b71f29 100644--- a/src/soup_cli/commands/sweep.py+++ b/src/soup_cli/commands/sweep.py@@ -475,7 +475,11 @@ def _run_single(base_cfg, params: dict, run_name: str, config_path: Path) -> dic_reject_unknown_sweep_params(config_dict)from soup_cli.config.schema import SoupConfig- from soup_cli.data.loader import load_dataset+ from soup_cli.data.loader import (+ data_config_for_task,+ load_dataset,+ task_preserves_source_columns,+ )from soup_cli.experiment.tracker import ExperimentTrackerfrom soup_cli.monitoring.display import TrainingDisplayfrom soup_cli.trainer.dispatch import build_trainer@@ -493,8 +497,8 @@ def _run_single(base_cfg, params: dict, run_name: str, config_path: Path) -> dicif val_notice:console.print(f"[yellow]Note:[/] {val_notice}")dataset = load_dataset(- loader_data_config(cfg),- preserve_source_columns=cfg.task == "grpo",+ data_config_for_task(loader_data_config(cfg), cfg.task),+ preserve_source_columns=task_preserves_source_columns(cfg.task),)console.print(f"[dim]Loaded {len(dataset['train'])} train samples[/]")diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex dd755350..1e2535bb 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -7,7 +7,7 @@ import jsonimport osimport refrom pathlib import Path-from typing import TYPE_CHECKING, Annotated+from typing import TYPE_CHECKING, Annotated, Anyimport typerfrom rich.console import Console@@ -15,8 +15,13 @@ from rich.markup import escape as markup_escapefrom rich.panel import Panelfrom soup_cli.config.loader import load_config-from soup_cli.data.loader import load_dataset+from soup_cli.data.loader import (+ data_config_for_task,+ load_dataset,+ task_preserves_source_columns,+)from soup_cli.monitoring.display import TrainingDisplay+from soup_cli.trainer.classifier import CLASSIFICATION_TASKSfrom soup_cli.utils.gpu import detect_device, get_gpu_info, resolve_quantizationif TYPE_CHECKING: # pragma: no cover - type hints only, no runtime import@@ -108,6 +113,22 @@ def _train_sample_count(dcfg, dataset) -> int:return count if valid else rows+def _validate_classification_dataset_if_applicable(cfg: Any, dataset: dict) -> None:+ """Validate sequence classification rows upfront if task is in CLASSIFICATION_TASKS."""+ if cfg.task in CLASSIFICATION_TASKS:+ from rich.markup import escape++ from soup_cli.trainer.classifier import validate_classification_dataset++ try:+ validate_classification_dataset(cfg, dataset)+ except (ValueError, TypeError) as exc:+ console.print(+ f"[red]Error validating {cfg.task} dataset:[/] {escape(str(exc))}"+ )+ raise typer.Exit(1) from exc++def _refuse_empty_train(dcfg, dataset) -> None:"""Stop a run whose data loaded zero training rows (#1217).@@ -177,7 +198,7 @@ def _build_hardware_fit_input(cfg):if quant == "4bit":peft = "qlora"elif task == "prm" or (- task in ("classifier", "reranker", "cross_encoder")+ task in CLASSIFICATION_TASKSand not (tcfg.classifier_lora and tcfg.lora.r > 0)) or (task == "asr" and not (tcfg.asr_lora and tcfg.lora.r > 0)):# #795: these trainers decide full fine-tuning themselves -- PRM always,@@ -1294,8 +1315,7 @@ def train(# v0.53.2 review-fix: classifier-family tasks train a sequence-classification# head, not a causal-LM LoRA — render "head" instead of LoRA r/alpha.- classifier_family = ("classifier", "reranker", "cross_encoder")- if cfg.task in classifier_family:+ if cfg.task in CLASSIFICATION_TASKS:# v0.71.12 #146 — render BOTH the head line AND a LoRA line when the# opt-in classifier LoRA path is active.head_line = (@@ -1519,10 +1539,11 @@ def train(if val_notice:console.print(f"[yellow]Note:[/] {val_notice}")dataset = load_dataset(- run_data_config,- preserve_source_columns=cfg.task == "grpo",+ data_config_for_task(run_data_config, cfg.task),+ preserve_source_columns=task_preserves_source_columns(cfg.task),)_refuse_empty_train(cfg.data, dataset)+ _validate_classification_dataset_if_applicable(cfg, dataset)console.print(f"[green]Data OK:[/] {_train_sample_count(cfg.data, dataset)} train samples")@@ -1536,10 +1557,11 @@ def train(if val_notice:console.print(f"[yellow]Note:[/] {val_notice}")dataset = load_dataset(- run_data_config,- preserve_source_columns=cfg.task == "grpo",+ data_config_for_task(run_data_config, cfg.task),+ preserve_source_columns=task_preserves_source_columns(cfg.task),)_refuse_empty_train(cfg.data, dataset)+ _validate_classification_dataset_if_applicable(cfg, dataset)console.print(f"[green]Loaded:[/] {_train_sample_count(cfg.data, dataset)} train samples")diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 30290965..58ed884f 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -395,6 +395,8 @@ class DataConfig(BaseModel):"raft",# v0.71.32 — ASR (Whisper): rows are {"audio": path, "text": transcript}"asr",+ # Issue #1219 — Cross-encoder paired sequence classification+ "cross_encoder",] = Field(default="auto",description="Data format",@@ -4875,7 +4877,7 @@ class SoupConfig(BaseModel):@model_validator(mode="after")def _validate_expand_layers_scope(self) -> "SoupConfig":- """#1325 — ``training.expand_layers`` (LLaMA Pro) is wired only in the+ """#1325 - ``training.expand_layers`` (LLaMA Pro) is wired only in thetransformers text SFT/pretrain ``_setup_transformers`` paths. Everyother task/backend/modality accepts the fields and then silentlytrains the unexpanded model, so refuse at load with the actual@@ -5571,6 +5573,16 @@ class SoupConfig(BaseModel):)return self+ @model_validator(mode="after")+ def _validate_cross_encoder_format(self) -> "SoupConfig":+ """#1219 - only the cross_encoder trainer reads pair rows."""+ if self.data.format == "cross_encoder" and self.task != "cross_encoder":+ raise ValueError(+ "data.format='cross_encoder' requires task='cross_encoder'; "+ f"got task={self.task!r}"+ )+ return self+@model_validator(mode="after")def _validate_distill_compat(self) -> "SoupConfig":"""v0.52.0 Part C — ``task='distill'`` gate."""diff --git a/src/soup_cli/data/formats.py b/src/soup_cli/data/formats.pyindex 80190ea3..e2ea2c86 100644--- a/src/soup_cli/data/formats.py+++ b/src/soup_cli/data/formats.py@@ -91,6 +91,8 @@ VALID_FORMATS = ("raft",# v0.71.32 — ASR (Whisper): {"audio": path, "text": transcript}."asr",+ # Issue #1219 — Cross-encoder paired text classification.+ "cross_encoder",)# A malformed row makes a converter raise one of these; the drop contract is@@ -139,6 +141,8 @@ def _dispatch_conversion(row: dict, fmt: str) -> dict:return _convert_raft(row)elif fmt == "asr":return _convert_asr(row)+ elif fmt == "cross_encoder":+ return _convert_cross_encoder(row)else:return _convert_vision(row)@@ -355,6 +359,39 @@ def _convert_asr(row: dict) -> dict:return {"audio": audio, "text": text}+def _convert_cross_encoder(row: dict) -> dict:+ """Convert cross-encoder paired row (Issue #1219).++ Input: {"text_a": ..., "text_b": ..., "label": ...}+ or: {"question": ..., "answer": ..., "label": ...}+ Output: dict with the pair fields and optional label preserved.+ """+ if "text_a" in row and "text_b" in row:+ a, b = row["text_a"], row["text_b"]+ if not isinstance(a, str) or not isinstance(b, str):+ raise TypeError(+ "cross_encoder rows require 'text_a' and 'text_b' to be str; "+ f"got text_a={type(a).__name__}, text_b={type(b).__name__}"+ )+ res = {"text_a": a, "text_b": b}+ elif "question" in row and "answer" in row:+ q, ans = row["question"], row["answer"]+ if not isinstance(q, str) or not isinstance(ans, str):+ raise TypeError(+ "cross_encoder rows require 'question' and 'answer' to be str; "+ f"got question={type(q).__name__}, answer={type(ans).__name__}"+ )+ res = {"question": q, "answer": ans}+ else:+ raise ValueError(+ "cross_encoder row requires 'text_a' + 'text_b' (or 'question' + "+ f"'answer'). Row keys: {sorted(row)!r}"+ )+ if "label" in row:+ res["label"] = row["label"]+ return res++def _convert_vision(row: dict) -> dict:"""Convert LLaVA / ShareGPT4V vision format to unified messages + image.diff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.pyindex a1321d77..24c81711 100644--- a/src/soup_cli/data/loader.py+++ b/src/soup_cli/data/loader.py@@ -194,6 +194,34 @@ def last_load_outcome() -> LoadOutcome:return _last_load+# Tasks that require source columns preserved across dataset format normalisation (#1219).+# GRPO uses raw columns for custom reward functions (answer, expected, etc.).+# The classifier family (classifier, reranker, cross_encoder) uses source columns+# to retain label, paired text (text_a, text_b, question, answer), and metadata.+PRESERVE_SOURCE_TASKS: frozenset[str] = frozenset({+ "grpo",+ "classifier",+ "reranker",+ "cross_encoder",+})+++def task_preserves_source_columns(task: str) -> bool:+ """Return whether task requires source dataset columns to be preserved."""+ return task in PRESERVE_SOURCE_TASKS+++def data_config_for_task(data_config: DataConfig, task: str) -> DataConfig:+ """Resolve ``format: auto`` for task: cross_encoder (#1219).++ ``detect_format`` cannot see the task, and ``{question, answer}`` is also+ GSM8K's shape, so pair rows are recognised only when the task reads them.+ """+ if task == "cross_encoder" and data_config.format == "auto":+ return data_config.model_copy(update={"format": "cross_encoder"})+ return data_config++def _format_rows(raw_data: list[dict],fmt: str,diff --git a/src/soup_cli/trainer/classifier.py b/src/soup_cli/trainer/classifier.pyindex 00a8beb6..6f423917 100644--- a/src/soup_cli/trainer/classifier.py+++ b/src/soup_cli/trainer/classifier.py@@ -40,6 +40,8 @@ from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargsconsole = Console()+CLASSIFICATION_TASKS: tuple[str, ...] = ("classifier", "reranker", "cross_encoder")+# Cap on multi-label list entries — defense against malformed dataset rows# (security review v0.53.2 H2). Matches v0.52.0 ``_MAX_LABELS=1024``._MAX_MULTI_LABEL_ENTRIES: int = 1024@@ -175,6 +177,56 @@ def _label_index()+def validate_classification_dataset(cfg: SoupConfig, dataset: dict) -> None:+ """Validate that classification dataset splits have required fields and valid labels (#1219).++ Checked at load and on --dry-run so missing or invalid labels fail before+ model weights are initialized, reporting the exact row index.+ """+ if cfg.task not in CLASSIFICATION_TASKS:+ return++ is_paired = (cfg.task == "cross_encoder")+ tcfg = cfg.training+ if tcfg.num_labels is None:+ raise ValueError(+ f"task={cfg.task!r} requires training.num_labels to be set"+ )+ num_labels = int(tcfg.num_labels)+ multi_label = (tcfg.classifier_kind == "multi_label")+ label_names = (+ list(tcfg.label_names) if tcfg.label_names is not None else None+ )++ for split in ("train", "val"):+ if split not in dataset or not dataset[split]:+ continue+ for idx, row in enumerate(dataset[split]):+ if not isinstance(row, dict):+ raise TypeError(+ f"{split} row {idx}: expected dict row, got {type(row).__name__}"+ )+ if is_paired:+ try:+ _row_to_pair(row)+ except Exception as exc:+ raise ValueError(f"{split} row {idx}: {exc}") from exc+ else:+ try:+ _row_to_text(row)+ except Exception as exc:+ raise ValueError(f"{split} row {idx}: {exc}") from exc++ if "label" not in row or row["label"] is None:+ raise ValueError(+ f"{split} row {idx}: missing required 'label' field for task '{cfg.task}'"+ )+ try:+ _normalise_label(row["label"], label_names, num_labels, multi_label)+ except Exception as exc:+ raise ValueError(f"{split} row {idx}: {exc}") from exc++class ClassifierTrainerWrapper:"""High-level wrapper for classifier / reranker / cross_encoder training."""@@ -238,6 +290,7 @@ class ClassifierTrainerWrapper:problem_type = ("multi_label_classification" if multi_label else "single_label_classification")+ validate_classification_dataset(cfg, dataset)console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")self.tokenizer = AutoTokenizer.from_pretrained(@@ -253,6 +306,12 @@ class ClassifierTrainerWrapper:problem_type=problem_type,trust_remote_code=self._trust_remote_code,)+ label_names = (+ list(tcfg.label_names) if tcfg.label_names is not None else None+ )+ if label_names is not None:+ self.model.config.id2label = {i: name for i, name in enumerate(label_names)}+ self.model.config.label2id = {name: i for i, name in enumerate(label_names)}# v0.71.12 #146 — opt-in LoRA / PEFT path. Default-off# (``classifier_lora=False``) preserves the v0.53.2 full-finetune@@ -296,9 +355,6 @@ class ClassifierTrainerWrapper:)is_paired = (cfg.task == "cross_encoder")- label_names = (- list(tcfg.label_names) if tcfg.label_names is not None else None- )def encode(row: dict) -> dict:if is_paired:@@ -327,6 +383,8 @@ class ClassifierTrainerWrapper:if "val" in dataset and dataset["val"]:raw_val = Dataset.from_list(dataset["val"])eval_ds = raw_val.map(encode, remove_columns=raw_val.column_names)+ self.train_dataset = train_ds+ self.eval_dataset = eval_dsoutput_dir = Path(cfg.output)if cfg.experiment_name:diff --git a/tests/test_issue1219_classifier_data_loader.py b/tests/test_issue1219_classifier_data_loader.pynew file mode 100644index 00000000..a742c6b5--- /dev/null+++ b/tests/test_issue1219_classifier_data_loader.py@@ -0,0 +1,482 @@+"""Tests for Issue #1219: classifier/reranker/cross_encoder data loading and validation.++Verifies:+1. Source column retention via shared helper `task_preserves_source_columns`.+2. Format detection and conversion for `cross_encoder` (both text_a/text_b and question/answer).+3. Upfront label and shape validation with specific row indices on --dry-run and at load.+4. All variants: string labels, integer labels, multi-label lists, chatml with label,+ reranker, cross_encoder (with both auto and explicit formats).+5. Documented example end-to-end training through `soup train`.+"""++from __future__ import annotations++import ast+import json+from pathlib import Path+from typing import Any++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.loader import load_config_from_string+from soup_cli.data.formats import (+ FORMAT_SIGNATURES,+ VALID_FORMATS,+ detect_format,+ format_to_messages,+)+from soup_cli.data.loader import (+ PRESERVE_SOURCE_TASKS,+ data_config_for_task,+ load_dataset,+ task_preserves_source_columns,+)+from soup_cli.trainer.classifier import (+ ClassifierTrainerWrapper,+ validate_classification_dataset,+)+from tests._windows_ci import skip_on_windows_ci+from tests.conftest import strip_ansi+++def _strip_ansi(text: str) -> str:+ """Strip ANSI color codes and collapse whitespace for resilient assertions."""+ plain = strip_ansi(text)+ return " ".join(plain.split())+++class TestTaskPreservesSourceColumns:+ """One helper decides which tasks keep source columns; train and sweep must agree."""++ def test_expected_tasks_in_preserve_set(self) -> None:+ assert PRESERVE_SOURCE_TASKS == {+ "grpo",+ "classifier",+ "reranker",+ "cross_encoder",+ }++ @pytest.mark.parametrize(+ ("task", "expected"),+ [+ ("grpo", True),+ ("classifier", True),+ ("reranker", True),+ ("cross_encoder", True),+ ("sft", False),+ ("dpo", False),+ ("kto", False),+ ("orpo", False),+ ("reward_model", False),+ ("pretrain", False),+ ("embedding", False),+ ("distill", False),+ ("unlearn", False),+ ],+ )+ def test_helper_predicate_values(self, task: str, expected: bool) -> None:+ assert task_preserves_source_columns(task) is expected++ def test_train_and_sweep_use_same_helper_ast(self) -> None:+ """Audit AST of train.py and sweep.py: both must call task_preserves_source_columns."""+ repo_root = Path(__file__).resolve().parents[1]+ train_py = (repo_root / "src/soup_cli/commands/train.py").read_text(encoding="utf-8")+ sweep_py = (repo_root / "src/soup_cli/commands/sweep.py").read_text(encoding="utf-8")++ # Neither file should have the old hardcoded cfg.task == "grpo"+ assert 'preserve_source_columns=cfg.task == "grpo"' not in train_py+ assert 'preserve_source_columns=cfg.task == "grpo"' not in sweep_py++ # Both must call task_preserves_source_columns+ assert "task_preserves_source_columns(cfg.task)" in train_py+ assert "task_preserves_source_columns(cfg.task)" in sweep_py++ # Both must import task_preserves_source_columns from soup_cli.data.loader+ train_ast = ast.parse(train_py)+ sweep_ast = ast.parse(sweep_py)++ def finds_import(tree: ast.AST, target_name: str) -> bool:+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and node.module == "soup_cli.data.loader":+ for name in node.names:+ if name.name == target_name:+ return True+ return False++ assert finds_import(train_ast, "task_preserves_source_columns"), (+ "train.py must import task_preserves_source_columns"+ )+ assert finds_import(sweep_ast, "task_preserves_source_columns"), (+ "sweep.py must import task_preserves_source_columns"+ )+++class TestCrossEncoderFormat:+ """Format detection and conversion for paired sequence classification."""++ def test_signatures_and_valid_formats(self) -> None:+ assert "cross_encoder" not in FORMAT_SIGNATURES+ assert "cross_encoder" in VALID_FORMATS++ def test_detect_format_text_a_text_b(self) -> None:+ rows = [{"text_a": "query", "text_b": "passage", "label": 1}]+ with pytest.raises(ValueError, match="Cannot detect format"):+ detect_format(rows)++ def test_detect_format_question_answer(self) -> None:+ rows = [{"question": "what is this?", "answer": "it is a cat", "label": 0}]+ with pytest.raises(ValueError, match="Cannot detect format"):+ detect_format(rows)++ def test_conversion_preserves_pairs_and_label(self) -> None:+ row_ab = {"text_a": "first", "text_b": "second", "label": "relevant", "meta": 123}+ out_ab = format_to_messages(row_ab, "cross_encoder")+ assert out_ab is not None+ assert out_ab["text_a"] == "first"+ assert out_ab["text_b"] == "second"+ assert out_ab["label"] == "relevant"++ row_qa = {"question": "q?", "answer": "a!", "label": 1}+ out_qa = format_to_messages(row_qa, "cross_encoder")+ assert out_qa is not None+ assert out_qa["question"] == "q?"+ assert out_qa["answer"] == "a!"+ assert out_qa["label"] == 1++ def test_conversion_rejects_non_string_pairs(self) -> None:+ assert format_to_messages({"text_a": 123, "text_b": "good"}, "cross_encoder") is None+ bad_qa = {"question": "q", "answer": ["not", "string"]}+ assert format_to_messages(bad_qa, "cross_encoder") is None+++class TestLabelValidationUpfront:+ """Missing or invalid labels must fail at load and on --dry-run with row index."""++ def test_validate_missing_label_names_row_index(self) -> None:+ cfg = load_config_from_string(+ """+ base: sshleifer/tiny-gpt2+ task: classifier+ training:+ num_labels: 2+ data:+ train: ./fake.jsonl+ """+ )+ dataset = {+ "train": [+ {"text": "good message", "label": 1},+ {"text": "bad message missing label"},+ {"text": "another good message", "label": 0},+ ]+ }+ with pytest.raises(ValueError, match=r"train row 1: missing required 'label' field"):+ validate_classification_dataset(cfg, dataset)++ def test_validate_invalid_label_type_names_row_index(self) -> None:+ cfg = load_config_from_string(+ """+ base: sshleifer/tiny-gpt2+ task: classifier+ training:+ num_labels: 2+ data:+ train: ./fake.jsonl+ """+ )+ dataset = {+ "train": [+ {"text": "message", "label": True},+ ]+ }+ with pytest.raises(ValueError, match=r"train row 0: label must not be bool"):+ validate_classification_dataset(cfg, dataset)++ def test_dry_run_refuses_missing_label_with_row_index(self, tmp_path: Path) -> None:+ data_file = tmp_path / "data.jsonl"+ data_file.write_text(+ json.dumps({"text": "sample 0", "label": "ham"}) + "\n"+ + json.dumps({"text": "sample 1"}) + "\n"+ )+ cfg_file = tmp_path / "soup.yaml"+ cfg_file.write_text(+ f"""+ base: sshleifer/tiny-gpt2+ task: classifier+ data:+ train: {data_file.as_posix()}+ max_length: 64+ val_split: 0.0+ training:+ num_labels: 2+ label_names: [ham, spam]+ """+ )+ runner = CliRunner()+ res = runner.invoke(app, ["train", "--config", str(cfg_file), "--dry-run"])+ assert res.exit_code == 1+ clean = _strip_ansi(res.output)+ assert "train row 1" in clean+ assert "missing required 'label' field" in clean++ def test_train_load_refuses_missing_label_before_model_loads(self, tmp_path: Path) -> None:+ data_file = tmp_path / "data.jsonl"+ data_file.write_text(+ json.dumps({"text": "sample 0"}) + "\n"+ )+ cfg_file = tmp_path / "soup.yaml"+ cfg_file.write_text(+ f"""+ base: invalid-model-that-would-fail-if-loaded+ task: classifier+ data:+ train: {data_file.as_posix()}+ max_length: 64+ val_split: 0.0+ training:+ num_labels: 2+ label_names: [ham, spam]+ """+ )+ runner = CliRunner()+ res = runner.invoke(app, ["train", "--config", str(cfg_file), "--yes"])+ assert res.exit_code == 1+ clean = _strip_ansi(res.output)+ assert "train row 0" in clean+ assert "missing required 'label' field" in clean+ assert "Setting up model + trainer" not in clean+++class TestDatasetVariantsLoading:+ """Verify all variants preserve source columns and setup succeeds."""++ @pytest.mark.parametrize(+ ("fmt", "rows", "task", "training_dict", "expected_labels"),+ [+ # String labels with label_names (auto format)+ (+ "auto",+ [{"text": f"text {i}", "label": "spam" if i % 2 else "ham"} for i in range(4)],+ "classifier",+ {"num_labels": 2, "label_names": ["ham", "spam"]},+ [0, 1, 0, 1],+ ),+ # String labels with explicit plaintext format+ (+ "plaintext",+ [{"text": f"text {i}", "label": "spam" if i % 2 else "ham"} for i in range(4)],+ "classifier",+ {"num_labels": 2, "label_names": ["ham", "spam"]},+ [0, 1, 0, 1],+ ),+ # Integer labels (auto format)+ (+ "auto",+ [{"text": f"text {i}", "label": i % 3} for i in range(6)],+ "classifier",+ {"num_labels": 3},+ [0, 1, 2, 0, 1, 2],+ ),+ # Integer labels with explicit plaintext format+ (+ "plaintext",+ [{"text": f"text {i}", "label": i % 3} for i in range(6)],+ "classifier",+ {"num_labels": 3},+ [0, 1, 2, 0, 1, 2],+ ),+ # Multi-label lists (auto format)+ (+ "auto",+ [{"text": f"text {i}", "label": [0, 2]} for i in range(3)],+ "classifier",+ {"num_labels": 3, "classifier_kind": "multi_label"},+ [[1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 1.0]],+ ),+ # Multi-label lists with label names+ (+ "plaintext",+ [{"text": f"text {i}", "label": ["ham", "promo"]} for i in range(3)],+ "classifier",+ {+ "num_labels": 3,+ "classifier_kind": "multi_label",+ "label_names": ["ham", "spam", "promo"],+ },+ [[1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 1.0]],+ ),+ # ChatML rows carrying label (auto format)+ (+ "auto",+ [+ {+ "messages": [{"role": "user", "content": f"hello {i}"}],+ "label": "spam" if i % 2 else "ham",+ }+ for i in range(4)+ ],+ "classifier",+ {"num_labels": 2, "label_names": ["ham", "spam"]},+ [0, 1, 0, 1],+ ),+ # ChatML rows carrying label (explicit chatml format)+ (+ "chatml",+ [+ {+ "messages": [{"role": "user", "content": f"hello {i}"}],+ "label": "spam" if i % 2 else "ham",+ }+ for i in range(4)+ ],+ "classifier",+ {"num_labels": 2, "label_names": ["ham", "spam"]},+ [0, 1, 0, 1],+ ),+ # task: reranker (auto format)+ (+ "auto",+ [{"text": f"query doc {i}", "label": "relevant"} for i in range(3)],+ "reranker",+ {"num_labels": 1, "label_names": ["relevant"]},+ [0, 0, 0],+ ),+ # task: reranker (explicit plaintext format)+ (+ "plaintext",+ [{"text": f"query doc {i}", "label": "relevant"} for i in range(3)],+ "reranker",+ {"num_labels": 1, "label_names": ["relevant"]},+ [0, 0, 0],+ ),+ # task: cross_encoder with text_a and text_b (auto format)+ (+ "auto",+ [{"text_a": f"q {i}", "text_b": f"doc {i}", "label": i % 2} for i in range(4)],+ "cross_encoder",+ {"num_labels": 2},+ [0, 1, 0, 1],+ ),+ # task: cross_encoder with text_a and text_b (explicit cross_encoder format)+ (+ "cross_encoder",+ [{"text_a": f"q {i}", "text_b": f"doc {i}", "label": i % 2} for i in range(4)],+ "cross_encoder",+ {"num_labels": 2},+ [0, 1, 0, 1],+ ),+ # task: cross_encoder with question and answer (auto format)+ (+ "auto",+ [{"question": f"q {i}", "answer": f"ans {i}", "label": 1} for i in range(3)],+ "cross_encoder",+ {"num_labels": 2},+ [1, 1, 1],+ ),+ # task: cross_encoder with question and answer (explicit cross_encoder format)+ (+ "cross_encoder",+ [{"question": f"q {i}", "answer": f"ans {i}", "label": 1} for i in range(3)],+ "cross_encoder",+ {"num_labels": 2},+ [1, 1, 1],+ ),+ ],+ )+ def test_load_dataset_retains_columns_and_validates(+ self,+ tmp_path: Path,+ fmt: str,+ rows: list[dict[str, Any]],+ task: str,+ training_dict: dict[str, Any],+ expected_labels: list[Any],+ ) -> None:+ import yaml++ data_file = tmp_path / f"test_{task}_{fmt}.jsonl"+ data_file.write_text("\n".join(json.dumps(r) for r in rows) + "\n")++ cfg_obj = {+ "base": "hf-internal-testing/tiny-random-LlamaForCausalLM",+ "task": task,+ "data": {+ "train": data_file.as_posix(),+ "format": fmt,+ "val_split": 0.0,+ "max_length": 64,+ },+ "training": training_dict,+ }+ cfg = load_config_from_string(yaml.safe_dump(cfg_obj))++ # 1. load_dataset with task_preserves_source_columns and data_config_for_task+ dataset = load_dataset(+ data_config_for_task(cfg.data, cfg.task),+ preserve_source_columns=task_preserves_source_columns(cfg.task),+ )+ assert len(dataset["train"]) == len(rows)+ for row in dataset["train"]:+ assert "label" in row++ # 2. validate_classification_dataset passes+ validate_classification_dataset(cfg, dataset)++ # 3. Setup wrapper+ wrapper = ClassifierTrainerWrapper(cfg, device="cpu")+ wrapper.setup(dataset)+ assert wrapper.train_dataset is not None+ assert wrapper.train_dataset["labels"] == expected_labels+++class TestDocumentedExampleTraining:+ """End-to-end training of the documented classifier example."""++ @skip_on_windows_ci+ def test_documented_classifier_example_trains_and_records_labels(+ self, tmp_path: Path+ ) -> None:+ labels = ["ham", "spam", "promo"]+ data_path = tmp_path / "labelled.jsonl"+ data_path.write_text(+ "\n".join(+ json.dumps({"text": f"message {i}", "label": labels[i % 3]})+ for i in range(6)+ )+ + "\n"+ )+ out_dir = tmp_path / "out"+ cfg_file = tmp_path / "cls.yaml"+ cfg_file.write_text(+ f"""+ base: hf-internal-testing/tiny-random-LlamaForCausalLM+ task: classifier+ data:+ train: {data_path.as_posix()}+ max_length: 64+ val_split: 0.0+ training:+ num_labels: 3+ label_names: [ham, spam, promo]+ quantization: none+ epochs: 1+ batch_size: 2+ output: {out_dir.as_posix()}+ """+ )+ runner = CliRunner()+ res = runner.invoke(app, ["train", "--config", str(cfg_file), "--yes"])+ clean = _strip_ansi(res.output)+ assert res.exit_code == 0, f"Command failed: {res.output}"+ assert "Auto-detected format: plaintext" in clean+ assert "Loaded: 6 train samples" in clean+ assert "Training Complete!" in clean++ # Verify saved model config recorded the labels+ saved_config_path = out_dir / "config.json"+ assert saved_config_path.exists(), "config.json should be saved in output directory"+ saved_cfg = json.loads(saved_config_path.read_text(encoding="utf-8"))+ assert saved_cfg.get("id2label") == {"0": "ham", "1": "spam", "2": "promo"}+ assert saved_cfg.get("label2id") == {"ham": 0, "spam": 1, "promo": 2}diff --git a/tests/test_issue1219_pair_rows_are_task_scoped.py b/tests/test_issue1219_pair_rows_are_task_scoped.pynew file mode 100644index 00000000..535cc1ed--- /dev/null+++ b/tests/test_issue1219_pair_rows_are_task_scoped.py@@ -0,0 +1,104 @@+import json++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.loader import load_config_from_string+from soup_cli.data.formats import detect_format+from tests.conftest import strip_ansi++BASE = "hf-internal-testing/tiny-random-LlamaForCausalLM"+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def test_question_answer_rows_are_not_detected_globally():+ """GSM8K's row shape. Only task: cross_encoder reads it as a pair (#1219)."""+ with pytest.raises(ValueError, match="Cannot detect format"):+ detect_format([{"question": "What is 2+2?", "answer": "4"}])++[email protected]("task", ["sft", "grpo"])+def test_question_answer_rows_are_not_ready_to_train_off_cross_encoder(+ tmp_path, monkeypatch, task+):+ monkeypatch.chdir(tmp_path)+ rows = [{"question": f"What is {i}+{i}?", "answer": str(2 * i)} for i in range(4)]+ (tmp_path / "qa.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n")+ reward = " reward_fn: accuracy\n" if task == "grpo" else ""+ (tmp_path / "soup.yaml").write_text(+ f"base: {BASE}\ntask: {task}\ndata:\n train: qa.jsonl\n val_split: 0.0\n"+ f"training:\n quantization: none\n{reward}"+ )+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])+ assert result.exit_code != 0, _plain(result.output)+ assert "Ready to train" not in _plain(result.output)+++def test_pretrain_text_rows_with_question_answer_columns_stay_plaintext():+ rows = [{"text": "doc", "question": "q", "answer": "a"}]+ assert detect_format(rows) == "plaintext"+++def test_cross_encoder_format_requires_the_cross_encoder_task():+ with pytest.raises(ValueError, match="requires task='cross_encoder'"):+ load_config_from_string(+ "base: a/b\ntask: sft\ndata:\n train: x.jsonl\n format: cross_encoder\n"+ )+++def test_validate_names_a_val_row_missing_its_label():+ """The val split is checked too: #1313 evaluates it, so a bad val row would+ otherwise fail only after the model loads."""+ from soup_cli.trainer.classifier import validate_classification_dataset++ cfg = load_config_from_string(+ "base: a/b\ntask: classifier\ntraining:\n num_labels: 2\ndata:\n train: x.jsonl\n"+ )+ dataset = {+ "train": [{"text": "a", "label": 0}],+ "val": [{"text": "b", "label": 1}, {"text": "c"}],+ }+ with pytest.raises(ValueError, match=r"val row 1: missing required 'label' field"):+ validate_classification_dataset(cfg, dataset)++[email protected]("pair", [("text_a", "text_b"), ("question", "answer")])+def test_cross_encoder_auto_reads_both_pair_shapes_through_soup_train(+ tmp_path, monkeypatch, pair+):+ monkeypatch.chdir(tmp_path)+ left, right = pair+ rows = [{left: f"q {i}", right: f"doc {i}", "label": i % 2} for i in range(4)]+ (tmp_path / "pairs.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n")+ (tmp_path / "soup.yaml").write_text(+ f"base: {BASE}\ntask: cross_encoder\ndata:\n train: pairs.jsonl\n val_split: 0.0\n"+ "training:\n num_labels: 2\n quantization: none\n"+ )+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])+ output = _plain(result.output)+ assert result.exit_code == 0, (output, repr(result.exception))+ assert "Data OK: 4 train samples" in output++[email protected]("pair", [("text_a", "text_b"), ("question", "answer")])+def test_real_run_reads_pair_rows_the_way_the_dry_run_does(tmp_path, monkeypatch, pair):+ """The real-run load resolves ``format: auto`` for cross_encoder too, so it+ reaches the row check instead of stopping at format detection (#1219)."""+ monkeypatch.chdir(tmp_path)+ left, right = pair+ rows = [{left: f"q {i}", right: f"doc {i}", "label": i % 2} for i in range(3)]+ rows.append({left: "q 3", right: "doc 3"}) # no label: the row check must name it+ (tmp_path / "pairs.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n")+ (tmp_path / "soup.yaml").write_text(+ "base: invalid-model-that-would-fail-if-loaded\ntask: cross_encoder\n"+ "data:\n train: pairs.jsonl\n val_split: 0.0\n"+ "training:\n num_labels: 2\n quantization: none\n"+ )+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])+ output = _plain(result.output)+ assert result.exit_code == 1, (output, repr(result.exception))+ assert "train row 3: missing required 'label' field" in output