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
feat(eval): support batched greedy generation in ship scorers (#1958)
Nurkhan Esenbek82d726c408b8
diff --git a/changelog.d/0.76.0/1958.added.md b/changelog.d/0.76.0/1958.added.mdnew file mode 100644index 00000000..ce0cb884--- /dev/null+++ b/changelog.d/0.76.0/1958.added.md@@ -0,0 +1 @@+- Task and bundled-suite eval scorers support optional batch generation with scalar fallback; live greedy generators use bounded left-padded batches, and scorer revision 6 prevents generation failures from earning credit (#1759 by @kok-o in #1958).diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 20a7b206..27f3acba 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -485,6 +485,25 @@ CPU-instant):| `mini_safety` | refusal-rate on harmful prompts (under-refusal = regression) | refusal heuristic || `mini_over_refusal` | benign prompts are NOT refused (over-refusal = regression) | refusal heuristic (inverse) |+Custom task evaluation and bundled suites accept an ordinary `gen(prompt) -> str`+callable and also use its optional `gen.batch(prompts) -> list[str]` method. Batch+results must preserve prompt order and have the same length as the input. If the+batch raises, scalar retries isolate failed items; a malformed result fails the+batch and a non-string item fails that item. Generation failures always score zero,+including when an empty response would otherwise match or count as non-refusal.++The shared live greedy generator used by `soup ship` exposes this method with left+padding, the same prompt/chat-template preparation as scalar decoding, and bounded+batches of eight prompts. Python callers can set `make_generator(..., batch_size=1)`+or another positive size. Each prompt returns one completion even when the model's+saved generation configuration requests multiple sequences; the shared model+configuration is not changed. Successful outputs retain the same scores and the default+CLI output format is unchanged. CPU tests compare real tiny GPT-2 and Llama outputs+against scalar generation; no GPU throughput or cross-device numerical equivalence+is claimed. Scorer revision 6 marks the corrected generation-failure handling, so+older saved baselines receive the existing provenance warning. Progress events are+a separate follow-up to #1759.+Each suite is >20 items so a single-item flip (1/N < 0.05) trips the default threshold insteadof being rounded away. The scorer is answer-**extraction** — a spurious substring inside a word(`"B"` in "**B**erlin") no longer scores, which is a **breaking** change from the v0.25.0diff --git a/src/soup_cli/eval/custom.py b/src/soup_cli/eval/custom.pyindex ee9f2ed4..33ae65f7 100644--- a/src/soup_cli/eval/custom.py+++ b/src/soup_cli/eval/custom.py@@ -8,6 +8,7 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Optional+from soup_cli.eval.generation import generate_outputsfrom soup_cli.utils.final_answer import answers_match, parse_completion, parse_referencefrom soup_cli.utils.safe_regex import check_config_regex@@ -365,8 +366,8 @@ def run_eval(Args:model_path: Path to model directory.tasks: List of EvalTask objects.- generate_fn: Optional callable(prompt: str) -> str. If None, uses- a default pipeline from transformers.+ generate_fn: Optional callable(prompt: str) -> str, optionally exposing+ batch(prompts) -> list[str]. If None, uses a transformers pipeline.Returns:EvalResults with per-task scores and aggregates.@@ -375,9 +376,12 @@ def run_eval(generate_fn = _create_default_generator(model_path)results: list[EvalResult] = []- for task in tasks:- output = generate_fn(task.prompt)- result = score_task(task, output)+ outputs = generate_outputs(generate_fn, [task.prompt for task in tasks])+ for task, output in zip(tasks, outputs):+ result = (+ score_task(task, output) if output is not None+ else EvalResult(task=task, output="", score=0.0, matched=False)+ )results.append(result)eval_results = EvalResults(results=results)diff --git a/src/soup_cli/eval/forgetting.py b/src/soup_cli/eval/forgetting.pyindex 95019051..715f7b11 100644--- a/src/soup_cli/eval/forgetting.py+++ b/src/soup_cli/eval/forgetting.py@@ -10,6 +10,7 @@ import refrom dataclasses import dataclassfrom typing import Callable, Literal, Optional, Tuple+from soup_cli.eval.generation import generate_outputsfrom soup_cli.utils.final_answer import iter_boxed_answersMiniBenchmark = list[dict[str, str]]@@ -450,11 +451,12 @@ class ForgettingDetector:def _evaluate(self) -> float:correct = 0- for item in self.benchmark:- output = self.generate_fn(- build_mcq_prompt(item["question"], item.get("answer", ""))- )- if not isinstance(output, str):+ outputs = generate_outputs(self.generate_fn, [+ build_mcq_prompt(item["question"], item.get("answer", ""))+ for item in self.benchmark+ ])+ for item, output in zip(self.benchmark, outputs):+ if output is None:continueif score_answer(output, item["answer"]):correct += 1diff --git a/src/soup_cli/eval/gate_suites.py b/src/soup_cli/eval/gate_suites.pyindex e9b25670..7a0f963e 100644--- a/src/soup_cli/eval/gate_suites.py+++ b/src/soup_cli/eval/gate_suites.py@@ -54,6 +54,7 @@ from pathlib import Pathfrom typing import Callable, Tuplefrom soup_cli.eval.forgetting import MINI_BENCHMARKS, ForgettingDetector+from soup_cli.eval.generation import generate_outputsGeneratorFn = Callable[[str], str]@@ -94,14 +95,16 @@ DEFAULT_GENERAL_SUITE: Tuple[str, ...] = tuple(MINI_BENCHMARKS) + EXTENDED_SUITE#: Bump this integer in the **same change** that alters a bundled scorer's#: behaviour, and update ``BUNDLED_SCORER_FINGERPRINT`` with it. The revision#: test fails if a scorer's output moves without the revision moving.-BUNDLED_SCORER_REVISION: int = 5+BUNDLED_SCORER_REVISION: int = 6#: SHA-256 of deterministic ``score_bundled_suite`` outputs under the fixed-#: fingerprint corpus in ``bundled_scorer_fingerprint``. Locked to revision 5;+#: fingerprint corpus in ``bundled_scorer_fingerprint``. Locked to revision 6;#: update together with ``BUNDLED_SCORER_REVISION``. Revisions 4 and 5 (#1192)#: changed ``mini_arithmetic``'s and then ``mini_common_sense``'s items, not a#: scorer: the corpus fixes correctness by item parity, so the hash did not#: move, but old baselines are on the old scale.+#: Revision 6 makes failed generations fail every suite, including over-refusal.+#: The fixed corpus has no generation failures, so its hash remains unchanged.BUNDLED_SCORER_FINGERPRINT: str = ("80992ac0369233b36d82e41c6f2baff510f6331a6647329fa139c4a99259d5c4")@@ -195,19 +198,6 @@ def load_suite_items(name: str) -> Tuple[dict, ...]:return _load_gate_fixture(filename)-def _call(gen: GeneratorFn, prompt: str) -> str:- """Invoke ``gen`` for one prompt; a generation error / non-str result scores- as a failure (empty string) and an oversized result is truncated to- ``_MAX_OUTPUT_LEN`` — so one bad generation never aborts a run."""- try:- out = gen(prompt)- except Exception: # noqa: BLE001 — a generation error is a failed item, not a crash- return ""- if not isinstance(out, str):- return ""- return out[:_MAX_OUTPUT_LEN]--def _fraction_passing(items: Tuple[dict, ...], gen: GeneratorFn, predicate) -> float:@@ -220,8 +210,11 @@ def _fraction_passing(if not items:return 0.0passed = 0- for item in items:- output = _call(gen, item.get("prompt", ""))+ outputs = generate_outputs(gen, [item.get("prompt", "") for item in items])+ for item, output in zip(items, outputs):+ if output is None:+ continue+ output = output[:_MAX_OUTPUT_LEN]try:if predicate(item, output):passed += 1@@ -438,7 +431,7 @@ def score_bundled_suite(name: str, gen: GeneratorFn) -> float:#355 — the ``gen`` guard is not defensive tidiness. Before it, anon-callable ``gen`` returned **0.0** on the behavioural suites (every- ``gen(prompt)`` raised inside ``_call``'s blanket handler and scored as a+ ``gen(prompt)`` raised inside the old blanket handler and scored as afailed item) while RAISING ``TypeError`` out of the MCQ branch. In leg 2 a0.0 reads as "the model failed every item" -> DON'T SHIP, so a caller errorwas indistinguishable from a regression **and failed in the direction thatdiff --git a/src/soup_cli/eval/generation.py b/src/soup_cli/eval/generation.pynew file mode 100644index 00000000..47c7bdee--- /dev/null+++ b/src/soup_cli/eval/generation.py@@ -0,0 +1,35 @@+"""Ordered optional batch generation shared by the pure evaluation scorers."""++from typing import Callable, Optional+++def generate_outputs(gen: Callable[[str], str], prompts: list[str]) -> list[Optional[str]]:+ """Return one output per prompt; ``None`` marks a failed generation.++ A callable ``batch(prompts) -> list[str]`` is optional. If a batch raises,+ scalar retries isolate failures to their items. A malformed result cannot+ be aligned safely and fails the batch; non-string items fail individually.+ Empty strings remain valid outputs, distinct from generation failures.+ """+ if not callable(gen):+ raise TypeError("gen must be callable")+ if not prompts:+ return []+ batch = getattr(gen, "batch", None)+ if callable(batch):+ try:+ outputs = batch(prompts)+ except Exception: # noqa: BLE001 — retry scalars to isolate failed items+ pass+ else:+ if not isinstance(outputs, list) or len(outputs) != len(prompts):+ return [None] * len(prompts)+ return [output if isinstance(output, str) else None for output in outputs]+ outputs = []+ for prompt in prompts:+ try:+ output = gen(prompt)+ except Exception: # noqa: BLE001 — a generation error is a failed item+ output = None+ outputs.append(output if isinstance(output, str) else None)+ return outputsdiff --git a/src/soup_cli/utils/live_eval.py b/src/soup_cli/utils/live_eval.pyindex e1885130..c5205c1c 100644--- a/src/soup_cli/utils/live_eval.py+++ b/src/soup_cli/utils/live_eval.py@@ -281,15 +281,18 @@ def make_generator(quantization: Optional[str] = None,loaded: Optional[tuple] = None,chat_template_kwargs: Optional[dict] = None,+ batch_size: int = 8,) -> GeneratorFn:"""Build a deterministic ``GeneratorFn`` closure (greedy decode).``loaded`` lets a caller share an already-loaded ``(model, tokenizer,device)`` triple across several closures (base + multi off one load).``dtype``/``quantization`` are ignored when ``loaded`` is given, same as- ``device``.+ ``device``. The closure also exposes ``batch(prompts) -> list[str]`` using+ greedy decoding, left padding and at most ``batch_size`` prompts per call."""_check_positive_int(max_new_tokens, "max_new_tokens")+ _check_positive_int(batch_size, "batch_size")options = validate_chat_template_kwargs(chat_template_kwargs)if loaded is not None and (not isinstance(loaded, tuple) or len(loaded) != 3):raise ValueError("loaded must be a (model, tokenizer, device) tuple")@@ -324,6 +327,41 @@ def make_generator(gen_ids = out[0][prompt_len:]return tokenizer.decode(gen_ids, skip_special_tokens=True)+ def _batch(prompts: list[str]) -> list[str]:+ if not isinstance(prompts, list) or any(not isinstance(p, str) for p in prompts):+ raise TypeError("prompts must be a list of strings")+ outputs = []+ for start in range(0, len(prompts), batch_size):+ encodings = [+ encode_prompt(tokenizer, prompt, chat_template_kwargs=options)+ for prompt in prompts[start:start + batch_size]+ ]+ width = max(row["input_ids"].shape[1] for row in encodings)+ if pad_id is None:+ raise ValueError("batch generation requires a pad or EOS token")+ # Pad tensors on the left without mutating the shared tokenizer.+ # Each prompt uses exactly the scalar rendering/truncation contract.+ inputs = {+ key: torch.cat([+ torch.nn.functional.pad(+ row[key], (width - row[key].shape[1], 0),+ value=pad_id if key == "input_ids" else 0,+ )+ for row in encodings+ ]).to(dev)+ for key in encodings[0]+ }+ with torch.no_grad():+ generated = model.generate(+ **inputs, max_new_tokens=max_new_tokens,+ do_sample=False, num_return_sequences=1, pad_token_id=pad_id,+ )+ outputs.extend(+ tokenizer.decode(row[width:], skip_special_tokens=True) for row in generated+ )+ return outputs++ _gen.batch = _batchreturn _gendiff --git a/tests/test_issue1759_batched_scorers.py b/tests/test_issue1759_batched_scorers.pynew file mode 100644index 00000000..34f889ca--- /dev/null+++ b/tests/test_issue1759_batched_scorers.py@@ -0,0 +1,250 @@+"""#1759: scorer batching preserves ordered scalar behavior and greedy output."""++import pytest++from soup_cli.eval.custom import EvalTask, run_eval+from soup_cli.eval.gate_suites import (+ DEFAULT_GENERAL_SUITE,+ _fingerprint_generator,+ score_bundled_suite,+)+++class BatchGenerator:+ def __init__(self, scalar):+ self.scalar = scalar+ self.batches = []++ def __call__(self, prompt):+ pytest.fail("batch-capable generator must not be called one prompt at a time")++ def batch(self, prompts):+ self.batches.append(prompts)+ return [self.scalar(prompt) for prompt in prompts]++[email protected]("suite", DEFAULT_GENERAL_SUITE)+def test_all_bundled_suites_have_identical_scalar_and_batch_scores(suite):+ batch = BatchGenerator(_fingerprint_generator)+ expected = score_bundled_suite(suite, _fingerprint_generator)+ assert 0 < expected < 1+ assert score_bundled_suite(suite, batch) == expected+ assert len(batch.batches) == 1+ assert len(batch.batches[0]) > 20+++def test_custom_eval_preserves_order_outputs_scores_and_categories():+ tasks = [+ EvalTask("one", "A", "alpha"),+ EvalTask("two", "B", "beta"),+ EvalTask("one", "wrong", "beta"),+ ]++ def scalar(prompt):+ return {"one": "A", "two": "B"}[prompt]++ batch = BatchGenerator(scalar)+ assert run_eval("unused", tasks, batch) == run_eval("unused", tasks, scalar)+ assert batch.batches == [["one", "two", "one"]]++[email protected]("batched", [False, True])+def test_generation_error_is_failed_item_even_with_empty_expected(batched):+ def scalar(prompt):+ if prompt == "bad":+ raise RuntimeError("generation failed")+ return "A"++ class Generator:+ __call__ = staticmethod(scalar)++ def batch(self, prompts):+ raise RuntimeError("batch failed")++ gen = Generator() if batched else scalar+ result = run_eval("unused", [EvalTask("bad", ""), EvalTask("good", "A")], gen)+ assert [item.score for item in result.results] == [0, 1]+ assert result.accuracy == 0.5+ assert score_bundled_suite("mini_over_refusal", lambda prompt: scalar("bad")) == 0++[email protected]("outputs", [["A"], ["A", "B", "C"], "AB", [None, "B"]])+def test_malformed_batch_does_not_misalign_or_award_failure(outputs):+ class Generator:+ def __call__(self, prompt):+ return "unexpected scalar retry"++ def batch(self, prompts):+ return outputs++ result = run_eval("unused", [EvalTask("one", ""), EvalTask("two", "B")], Generator())+ assert result.results[0].score == 0+ assert result.results[1].score == (1 if outputs == [None, "B"] else 0)++[email protected]("arch", ["gpt2", "llama"])[email protected]("batch_size", [1, 2, 3])+def test_real_cpu_greedy_batch_matches_scalar(arch, batch_size):+ torch = pytest.importorskip("torch")+ pytest.importorskip("transformers")+ from soup_cli.utils.live_eval import make_generator+ from tests._tiny_hf_models import build_gpt2, build_llama++ torch.manual_seed(1759)+ tokenizer = tiny_tokenizer()+ tokenizer.padding_side = "right" # The generator must enforce left padding itself.+ model = (build_gpt2 if arch == "gpt2" else build_llama)(tokenizer).eval()+ gen = make_generator(+ "unused", loaded=(model, tokenizer, "cpu"), max_new_tokens=4, batch_size=batch_size+ )+ prompts = ["hi", "hello world", "the quick brown fox jumps", "hello"]+ assert gen.batch(prompts) == [gen(prompt) for prompt in prompts]+ assert gen.batch([]) == []+ assert tokenizer.padding_side == "right"++[email protected]("arch", ["gpt2", "llama"])[email protected]("batch_size", [1, 2])+def test_saved_multiple_return_config_preserves_scalar_results(arch, batch_size, tmp_path):+ torch = pytest.importorskip("torch")+ transformers = pytest.importorskip("transformers")+ from soup_cli.utils.live_eval import make_generator+ from tests._tiny_hf_models import build_gpt2, build_llama++ torch.manual_seed(1759)+ tokenizer = tiny_tokenizer()+ model = (build_gpt2 if arch == "gpt2" else build_llama)(tokenizer).eval()+ model.generation_config.num_beams = 2+ model.generation_config.num_return_sequences = 2+ model.generation_config.save_pretrained(tmp_path)+ model.generation_config = transformers.GenerationConfig.from_pretrained(+ tmp_path, local_files_only=True+ )+ saved_config = model.generation_config.to_dict()+ assert saved_config["num_beams"] == saved_config["num_return_sequences"] == 2+ gen = make_generator(+ "unused", loaded=(model, tokenizer, "cpu"), max_new_tokens=4, batch_size=batch_size+ )+ prompts = ["hi", "hello world", "the quick brown fox jumps"]+ expected = [gen(prompt) for prompt in prompts]+ outputs = gen.batch(prompts)+ assert len(outputs) == len(prompts)+ assert outputs == expected+ tasks = [EvalTask(prompt, answer) for prompt, answer in zip(prompts, expected)]+ scalar_result = run_eval("unused", tasks, lambda prompt: gen(prompt))+ assert scalar_result.accuracy == 1+ assert run_eval("unused", tasks, gen) == scalar_result+ assert model.generation_config.to_dict() == saved_config+++def tiny_tokenizer():+ from tokenizers import Tokenizer, models, pre_tokenizers+ from transformers import PreTrainedTokenizerFast++ vocab = {+ word: index+ for index, word in enumerate(+ [+ "<pad>",+ "<unk>",+ "<eos>",+ "hi",+ "hello",+ "world",+ "the",+ "quick",+ "brown",+ "fox",+ "jumps",+ ]+ )+ }+ backend = Tokenizer(models.WordLevel(vocab, unk_token="<unk>"))+ backend.pre_tokenizer = pre_tokenizers.Whitespace()+ return PreTrainedTokenizerFast(+ tokenizer_object=backend,+ pad_token="<pad>",+ unk_token="<unk>",+ eos_token="<eos>",+ )++[email protected]("value", [0, -1, True, 1.5])+def test_bad_batch_size_refused_before_loading(value, monkeypatch):+ from soup_cli.utils import live_eval++ monkeypatch.setattr(live_eval, "load_model_and_tokenizer", lambda *a, **k: pytest.fail("load"))+ with pytest.raises(ValueError, match="batch_size"):+ live_eval.make_generator("unused", batch_size=value)+++def test_live_batches_are_bounded_left_padded_and_slice_after_full_width():+ import torch++ from soup_cli.utils.live_eval import make_generator++ tokenizer = tiny_tokenizer()+ recorded = []++ class Model:+ def generate(self, **kwargs):+ recorded.append(kwargs)+ assert kwargs["do_sample"] is False+ inputs = kwargs["input_ids"]+ return torch.cat([inputs, torch.full((len(inputs), 1), 3)], dim=1)++ gen = make_generator("unused", loaded=(Model(), tokenizer, "cpu"), batch_size=2)+ assert gen.batch(["hi", "hello world", "the quick brown", "hi", "world"]) == ["hi"] * 5+ assert [len(call["input_ids"]) for call in recorded] == [2, 2, 1]+ assert recorded[0]["input_ids"].tolist() == [[0, 3], [4, 5]]+ assert recorded[0]["attention_mask"].tolist() == [[0, 1], [1, 1]]+ assert recorded[1]["attention_mask"].tolist() == [[1, 1, 1], [0, 0, 1]]++[email protected]("suite", DEFAULT_GENERAL_SUITE)+def test_batch_exceptions_fall_back_and_failed_items_never_pass(suite):+ class Generator:+ def __call__(self, prompt):+ raise RuntimeError("failed item")++ def batch(self, prompts):+ raise RuntimeError("failed batch")++ assert score_bundled_suite(suite, Generator()) == 0++[email protected]("thinking", [False, True])+def test_batch_uses_scalar_chat_rendering_and_option_snapshot(thinking):+ import torch++ from soup_cli.utils.live_eval import encode_prompt, make_generator++ tokenizer = tiny_tokenizer()+ tokenizer.chat_template = (+ "{{ 'the ' if enable_thinking else '' }}{{ messages[0]['content'] }} world"+ )+ recorded = []++ class Model:+ def generate(self, input_ids, attention_mask, **kwargs):+ recorded.extend(+ [row[mask.bool()].tolist() for row, mask in zip(input_ids, attention_mask)]+ )+ return torch.cat([input_ids, torch.full((len(input_ids), 1), 3)], dim=1)++ options = {"enable_thinking": thinking}+ gen = make_generator(+ "unused", loaded=(Model(), tokenizer, "cpu"), chat_template_kwargs=options, batch_size=2+ )+ options["enable_thinking"] = not thinking+ prompts = ["hi", "hello world"]+ assert gen.batch(prompts) == ["hi", "hi"]+ assert recorded == [+ encode_prompt(+ tokenizer,+ prompt,+ chat_template_kwargs={"enable_thinking": thinking},+ return_tensors=None,+ )["input_ids"]+ for prompt in prompts+ ]