Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

feat(eval): expose shared live prompt preparation (#1758) (#1776)

AmixDigitala832183114c2
diff --git a/changelog.d/0.76.0/1776.added.md b/changelog.d/0.76.0/1776.added.md
new file mode 100644
index 00000000..289bf952
--- /dev/null
+++ b/changelog.d/0.76.0/1776.added.md
@@ -0,0 +1 @@
+- Live evaluation exposes `encode_prompt` and `MAX_PROMPT_TOKENS`, with shared prompt preparation for both generators; `chat_template_kwargs` and `soup ship --chat-template-kwargs` let callers pass model-specific template variables without duplicating special tokens. (#1758 by @Amix29 in #1776)
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index a982c135..443c1a2f 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -3463,6 +3463,7 @@ Usage: `soup ship [OPTIONS] [<command>] [ARGS]...`
| `--config` | text | | | soup.yaml whose eval.ship block supplies defaults (CLI flags win). With --evidence alone it GATES (refuses evidence whose config_sha drifted from this config, or whose numerics family does not match); with --emit-evidence it STAMPS this config's provenance. |
| `--push` | text | | | Post the verdict as a GitHub PR comment (owner/repo#N). Auth via GITHUB_TOKEN / GH_TOKEN; needs the `gh` CLI. |
| `--device` | text | | | Device for the live run (cuda / cpu). |
+| `--chat-template-kwargs` | text | | | Live chat-template variables as a JSON object, e.g. {"enable_thinking":false}. |
## `soup shrink`
diff --git a/docs/commands.md b/docs/commands.md
index 6a6344b8..9627fbf1 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -224,6 +224,7 @@ soup ship ... --emit-evidence ev.json Re-serialise the scores as replayable --e
soup ship ... --config soup.yaml Read eval.ship gate defaults; --evidence GATES on provenance.config_sha and numerics family, --emit-evidence STAMPS both (v0.71.39 / #367); live-loads base/tuned at training.quantization when it is 4bit/8bit, else full precision (#367)
soup ship ... --push owner/repo#N Post the verdict as a GitHub PR comment (best-effort; never flips the exit code) (v0.71.39)
soup ship ... --noise-floor N Re-run base model N times; per-axis floor = max-min spread; gate at max(threshold, floor); leg-1 measured in every --task-mode (judge modes cost N judge passes, floor labelled decode+judge) (v0.73.2)
+soup ship ... --chat-template-kwargs '{"enable_thinking":false}' Pass template variables equally to base/tuned live generation; JSON object, live-only (#1758)
soup card <registry-id> -o MODELCARD.md HF model card from a registry entry: training config, evals, hashes, lineage, artifacts (v0.71.35)
soup push --model ./out --repo you/m --card <registry-id> Upload that registry-driven card as the README (HF only) (v0.71.35)
soup ci init [--data d.jsonl --suite s.yaml --evidence ev.json] [--config soup.yaml] [--branch main --python 3.11] [--force] Write .github/workflows/soup-gate.yml: data validate -> expect -> ship gate on every PR (v0.71.35); --config binds the gate to a committed config so it refuses stale evidence (v0.71.39)
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 8cba1204..86a80789 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -422,6 +422,10 @@ single regressed benchmark, or a missing baseline all yield DON'T SHIP (a missin
soup ship --base HuggingFaceTB/SmolLM2-135M-Instruct --adapter ./out \
--task-eval tasks.jsonl --device cuda
+# Live: disable thinking when the model's chat template supports that variable
+soup ship --base <m> --adapter ./out --task-eval tasks.jsonl \
+ --chat-template-kwargs '{"enable_thinking": false}'
+
# Leg-1 via LLM-as-a-judge instead of an accuracy metric
soup ship --base <m> --adapter ./out --task-eval tasks.jsonl \
--task-mode judge_score --judge-model ollama://llama3.1
@@ -673,6 +677,49 @@ Smoothed BLEU uses Chen & Cherry epsilon for zero-correct buckets where
force the score to 0.0.
+### Public live prompt preparation
+
+`make_generator` and `make_multi_generator` accept `chat_template_kwargs`, a dictionary
+of variables passed to the tokenizer's chat template. The default preserves existing
+rendering, including raw-prompt fallback when a template is absent or broken. When
+non-empty options are requested, a missing or broken template raises an error instead
+of silently ignoring those options. Whether a variable such as `enable_thinking` has an
+effect depends on the model's template.
+
+The public `encode_prompt` helper uses the same rendering, special-token handling and
+`MAX_PROMPT_TOKENS` budget (1024) as both generators. Template-rendered special tokens
+are not added a second time. With the default right truncation, over-budget prompts
+lose their trailing tokens, which can include the generation prompt, as before.
+For a caller-managed batch, prepare each prompt with
+`return_tensors=None`, then pad the resulting encodings with the same tokenizer:
+
+```python
+from soup_cli.utils.live_eval import MAX_PROMPT_TOKENS, encode_prompt, make_generator
+
+options = {"enable_thinking": False}
+encoded = [encode_prompt(tokenizer, prompt, chat_template_kwargs=options,
+ return_tensors=None) for prompt in prompts]
+batch = tokenizer.pad(encoded, padding=True, return_tensors="pt").to(device)
+
+# Reuse an already-loaded, evaluation-mode model without patching the loader.
+generate = make_generator("unused", loaded=(model, tokenizer, device),
+ chat_template_kwargs=options)
+answer = generate("hello")
+```
+
+Configure the tokenizer's padding side appropriately for your batched model. The
+helper prepares inputs; it does not run batched generation. Template options cannot
+override `conversation`, `tokenize`, `add_generation_prompt`, `continue_final_message`,
+`return_tensors`, `return_dict`, `padding`, `truncation`, `max_length`, `chat_template`
+or `return_assistant_tokens_mask`. Generators snapshot the supplied options, including
+nested values, at construction. With `loaded`, model loading options
+such as device and quantization are ignored; the supplied triple is used directly.
+
+`soup ship --chat-template-kwargs` accepts a JSON object, applies it equally to base
+and tuned generation, and refuses malformed options with usage exit code 3. The flag
+is live-only and cannot be combined with offline `--evidence`. It applies to live
+task generation; it does not configure the lm-eval benchmark legs.
+
## Quant Calibration (KL Divergence)
Compare a quantized model to a full-precision baseline on a small fixed prompt
diff --git a/src/soup_cli/commands/ship.py b/src/soup_cli/commands/ship.py
index dc55e525..3eae02b5 100644
--- a/src/soup_cli/commands/ship.py
+++ b/src/soup_cli/commands/ship.py
@@ -162,6 +162,23 @@ def _validate_noise_floor_flag(value: Optional[int]) -> Optional[int]:
return value
+def _parse_chat_template_kwargs(value: Optional[str]) -> Optional[dict]:
+ if value is None:
+ return None
+ from soup_cli.utils.live_eval import validate_chat_template_kwargs
+
+ def reject_constant(constant: str) -> NoReturn:
+ raise ValueError(f"non-finite JSON constant {constant}")
+
+ try:
+ options = json.loads(value, parse_constant=reject_constant)
+ if not isinstance(options, dict):
+ raise ValueError("expected a JSON object")
+ return validate_chat_template_kwargs(options)
+ except (ValueError, TypeError, RecursionError) as exc:
+ _fail(f"--chat-template-kwargs: {exc}", _EXIT_USAGE)
+
+
def _validate_task_mode_flag(task_mode: str) -> None:
# All three modes (metric / judge_score / pairwise) ship as of v0.71.31, so
# SUPPORTED_TASK_MODES == TASK_MODES and the old "pairwise reserved" gate is
@@ -528,6 +545,7 @@ def _resolve_generators(
adapter: Optional[str],
device: Optional[str],
quantization: Optional[str] = None,
+ chat_template_kwargs: Optional[dict] = None,
) -> Tuple[Callable[[str], str], Callable[[str], str]]:
"""Build ``(base_gen, tuned_gen)`` from live_eval (greedy decode)."""
# #316 — the behavioural suites need a budget that fits a real tool call.
@@ -554,20 +572,26 @@ def _resolve_generators(
"pass --config to reuse the training run's own quantization.[/]"
)
+ template_options = (
+ {"chat_template_kwargs": chat_template_kwargs} if chat_template_kwargs is not None else {}
+ )
base_gen = live_eval.make_generator(
base, device=device, max_new_tokens=BEHAVIOURAL_MAX_NEW_TOKENS,
dtype=dtype, quantization=quantization,
+ **template_options,
)
if adapter:
tuned_gen = live_eval.make_generator(
base, adapter=adapter, device=device,
max_new_tokens=BEHAVIOURAL_MAX_NEW_TOKENS,
dtype=dtype, quantization=quantization,
+ **template_options,
)
elif tuned:
tuned_gen = live_eval.make_generator(
tuned, device=device, max_new_tokens=BEHAVIOURAL_MAX_NEW_TOKENS,
dtype=dtype, quantization=quantization,
+ **template_options,
)
else: # pragma: no cover — _verdict_live guarantees one of tuned/adapter
raise ValueError("need --tuned or --adapter")
@@ -992,6 +1016,7 @@ def _verdict_live(
forgetting_threshold: float,
noise_floor_runs: Optional[int] = None,
quantization: Optional[str] = None,
+ chat_template_kwargs: Optional[dict] = None,
) -> ShipVerdict:
"""Run a live verdict — validate flags (exit 2), then evaluate (exit 1)."""
if not base:
@@ -1059,7 +1084,13 @@ def _verdict_live(
tuned_id = tuned if tuned else base
try:
- base_gen, tuned_gen = _resolve_generators(base, tuned, adapter, device, quantization)
+ template_options = (
+ {"chat_template_kwargs": chat_template_kwargs}
+ if chat_template_kwargs is not None else {}
+ )
+ base_gen, tuned_gen = _resolve_generators(
+ base, tuned, adapter, device, quantization, **template_options
+ )
measured_floor: Optional[NoiseFloor] = None
if noise_floor_runs is not None:
@@ -1271,9 +1302,16 @@ def ship(
device: Optional[str] = typer.Option(
None, "--device", help="Device for the live run (cuda / cpu)."
),
+ chat_template_kwargs: Optional[str] = typer.Option(
+ None, "--chat-template-kwargs",
+ help='Live chat-template variables as a JSON object, e.g. {"enable_thinking":false}.',
+ ),
) -> None:
"""Decide SHIP / DON'T SHIP for a fine-tune (exit 0 = SHIP, 2 = DON'T)."""
soup_config = None
+ template_kwargs = _parse_chat_template_kwargs(chat_template_kwargs)
+ if evidence and chat_template_kwargs is not None:
+ _fail("--chat-template-kwargs applies only to a live run, not --evidence", _EXIT_USAGE)
# `is not None` (not truthiness): an explicit empty --config must fail loud
# through _parse_ship_config, not silently disable the staleness gate.
if config is not None:
@@ -1362,6 +1400,7 @@ def ship(
forgetting_threshold=threshold,
noise_floor_runs=noise_floor,
quantization=_live_eval_quantization_from_config(soup_config),
+ **({"chat_template_kwargs": template_kwargs} if template_kwargs is not None else {}),
)
else:
_fail(
diff --git a/src/soup_cli/utils/live_eval.py b/src/soup_cli/utils/live_eval.py
index 48d187b6..e1885130 100644
--- a/src/soup_cli/utils/live_eval.py
+++ b/src/soup_cli/utils/live_eval.py
@@ -28,14 +28,15 @@ import math
import re
import time
from collections.abc import Mapping, Sequence
-from typing import Callable, Dict, List, Optional, Tuple
+from typing import Any, Callable, Dict, List, Optional, Tuple
# Public closure types (mirror the diagnose protocols).
GeneratorFn = Callable[[str], str]
MultiGen = Callable[[str, int], "list[str]"]
# Bounds — keep the live paths from running away on a 4 GB box.
-_MAX_PROMPT_TOKENS = 1024
+MAX_PROMPT_TOKENS = 1024
+_MAX_PROMPT_TOKENS = MAX_PROMPT_TOKENS # compatibility for existing private consumers
_MAX_TRAIN_ROWS = 512
_MIN_TRAIN_ROWS = 1
_DEFAULT_LORA_R = 8
@@ -134,7 +135,28 @@ def _build_quantization_config(quantization: Optional[str]):
)
-def _render_prompt_template(tokenizer: object, prompt: str) -> Tuple[str, bool]:
+def validate_chat_template_kwargs(value: Optional[dict]) -> dict:
+ """Snapshot template variables without overriding live-eval encoding controls."""
+ if value is None:
+ return {}
+ if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
+ raise ValueError("chat_template_kwargs must be a dict with string keys or None")
+ reserved = {
+ "conversation", "tokenize", "add_generation_prompt", "continue_final_message",
+ "return_tensors", "return_dict", "padding", "truncation", "max_length",
+ "chat_template", "return_assistant_tokens_mask",
+ }
+ overlap = reserved.intersection(value)
+ if overlap:
+ raise ValueError("chat_template_kwargs cannot override " + ", ".join(sorted(overlap)))
+ from copy import deepcopy
+
+ return deepcopy(value)
+
+
+def _render_prompt_template(
+ tokenizer: object, prompt: str, *, chat_template_kwargs: Optional[dict] = None,
+) -> Tuple[str, bool]:
"""Render a single user turn; also report whether the chat template produced it.
Falls back to the raw prompt when the tokenizer has no chat template or the
@@ -147,10 +169,17 @@ def _render_prompt_template(tokenizer: object, prompt: str) -> Tuple[str, bool]:
[{"role": "user", "content": prompt}],
tokenize=False,
add_generation_prompt=True,
+ **(chat_template_kwargs or {}),
)
- except Exception: # noqa: BLE001 — malformed template → raw prompt
+ except Exception as exc: # noqa: BLE001 — default malformed template → raw prompt
+ if chat_template_kwargs:
+ raise ValueError(
+ f"cannot render chat template with chat_template_kwargs: {exc}"
+ ) from exc
return prompt, False
return text, True
+ if chat_template_kwargs:
+ raise ValueError("chat_template_kwargs requires a tokenizer with a chat template")
return prompt, False
@@ -162,6 +191,29 @@ def _apply_prompt_template(tokenizer: object, prompt: str) -> str:
return _render_prompt_template(tokenizer, prompt)[0]
+def encode_prompt(
+ tokenizer: object, prompt: str, *, chat_template_kwargs: Optional[dict] = None,
+ return_tensors: Optional[str] = "pt",
+) -> Any:
+ """Render/encode one user prompt exactly as the live generators do.
+
+ The returned tokenizer encoding is truncated at ``MAX_PROMPT_TOKENS``.
+ Template-rendered special tokens are not added again. Without options,
+ missing/broken templates retain the raw-prompt fallback. Use
+ ``return_tensors=None`` and ``tokenizer.pad`` to assemble a batch.
+ """
+ if not isinstance(prompt, str):
+ raise TypeError("prompt must be a string")
+ options = validate_chat_template_kwargs(chat_template_kwargs)
+ from soup_cli.utils.vllm import encode_rendered_prompt
+
+ text, templated = _render_prompt_template(tokenizer, prompt, chat_template_kwargs=options)
+ return encode_rendered_prompt(
+ tokenizer, text, templated=templated, return_tensors=return_tensors,
+ truncation=True, max_length=MAX_PROMPT_TOKENS,
+ )
+
+
def load_model_and_tokenizer(
model_id: str,
*,
@@ -228,6 +280,7 @@ def make_generator(
dtype: Optional[str] = None,
quantization: Optional[str] = None,
loaded: Optional[tuple] = None,
+ chat_template_kwargs: Optional[dict] = None,
) -> GeneratorFn:
"""Build a deterministic ``GeneratorFn`` closure (greedy decode).
@@ -237,12 +290,11 @@ def make_generator(
``device``.
"""
_check_positive_int(max_new_tokens, "max_new_tokens")
+ 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")
import torch
- from soup_cli.utils.vllm import encode_rendered_prompt
-
model, tokenizer, dev = loaded or load_model_and_tokenizer(
model_id,
adapter=adapter,
@@ -260,15 +312,7 @@ def make_generator(
def _gen(prompt: str) -> str:
if not isinstance(prompt, str):
raise TypeError("prompt must be a string")
- text, templated = _render_prompt_template(tokenizer, prompt)
- inputs = encode_rendered_prompt(
- tokenizer,
- text,
- templated=templated,
- return_tensors="pt",
- truncation=True,
- max_length=_MAX_PROMPT_TOKENS,
- ).to(dev)
+ inputs = encode_prompt(tokenizer, prompt, chat_template_kwargs=options).to(dev)
prompt_len = inputs["input_ids"].shape[1]
with torch.no_grad():
out = model.generate(
@@ -293,12 +337,14 @@ def make_multi_generator(
trust_remote_code: bool = False,
quantization: Optional[str] = None,
loaded: Optional[tuple] = None,
+ chat_template_kwargs: Optional[dict] = None,
) -> MultiGen:
"""Build a sampling ``MultiGen`` closure: ``multi(prompt, k) -> [str, ...]``.
``quantization`` is ignored when ``loaded`` is given, same as ``device``.
"""
_check_positive_int(max_new_tokens, "max_new_tokens")
+ options = validate_chat_template_kwargs(chat_template_kwargs)
if (
isinstance(temperature, bool)
or not isinstance(temperature, (int, float))
@@ -309,8 +355,6 @@ def make_multi_generator(
raise ValueError("loaded must be a (model, tokenizer, device) tuple")
import torch
- from soup_cli.utils.vllm import encode_rendered_prompt
-
model, tokenizer, dev = loaded or load_model_and_tokenizer(
model_id,
adapter=adapter,
@@ -329,15 +373,7 @@ def make_multi_generator(
raise TypeError("prompt must be a string")
if isinstance(k, bool) or not isinstance(k, int) or k < 1:
raise ValueError("k must be a positive int")
- text, templated = _render_prompt_template(tokenizer, prompt)
- inputs = encode_rendered_prompt(
- tokenizer,
- text,
- templated=templated,
- return_tensors="pt",
- truncation=True,
- max_length=_MAX_PROMPT_TOKENS,
- ).to(dev)
+ inputs = encode_prompt(tokenizer, prompt, chat_template_kwargs=options).to(dev)
prompt_len = inputs["input_ids"].shape[1]
with torch.no_grad():
out = model.generate(
diff --git a/tests/test_issue1758_live_eval_prompts.py b/tests/test_issue1758_live_eval_prompts.py
new file mode 100644
index 00000000..79d2ce79
--- /dev/null
+++ b/tests/test_issue1758_live_eval_prompts.py
@@ -0,0 +1,235 @@
+"""Public prompt preparation must match both live generators (#1758)."""
+
+import json
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils import live_eval
+
+_TEMPLATE = (
+ "{{ bos_token }}{{ messages[0]['content'] }} "
+ "{% if enable_thinking is not defined or enable_thinking %}think{% else %}answer{% endif %}"
+ "{% if add_generation_prompt %} assistant{% endif %}"
+)
+
+
+def tokenizer():
+ from tokenizers import Tokenizer, models, pre_tokenizers, processors
+ from transformers import PreTrainedTokenizerFast
+
+ vocab = {word: index for index, word in enumerate(
+ ["<unk>", "<bos>", "<eos>", "hello", "world", "think", "answer", "assistant"]
+ )}
+ backend = Tokenizer(models.WordLevel(vocab, unk_token="<unk>"))
+ backend.pre_tokenizer = pre_tokenizers.Whitespace()
+ backend.post_processor = processors.TemplateProcessing(
+ single="<bos> $A", special_tokens=[("<bos>", 1)]
+ )
+ tok = PreTrainedTokenizerFast(
+ tokenizer_object=backend, bos_token="<bos>", eos_token="<eos>",
+ pad_token="<eos>", unk_token="<unk>",
+ )
+ tok.chat_template = _TEMPLATE
+ return tok
+
+
[email protected]("factory", ["make_generator", "make_multi_generator"])
+def test_generators_share_public_encoding_and_snapshot_options(tokenizer, factory):
+ import torch
+
+ class Recorder:
+ sent = None
+
+ def generate(self, input_ids, **kwargs):
+ self.sent = input_ids.tolist()[0]
+ return torch.cat([input_ids, input_ids[:, -1:]], dim=1)
+
+ model = Recorder()
+ options = {"enable_thinking": False}
+ generate = getattr(live_eval, factory)(
+ "unused", loaded=(model, tokenizer, "cpu"), chat_template_kwargs=options
+ )
+ options["enable_thinking"] = True
+ if factory == "make_multi_generator":
+ generate("hello", 1)
+ else:
+ generate("hello")
+ encoded = live_eval.encode_prompt(
+ tokenizer, "hello", chat_template_kwargs={"enable_thinking": False}, return_tensors=None
+ )
+ expected = tokenizer.apply_chat_template(
+ [{"role": "user", "content": "hello"}],
+ tokenize=True, return_dict=False, add_generation_prompt=True, enable_thinking=False,
+ )
+ assert model.sent == encoded["input_ids"] == expected
+ assert model.sent.count(tokenizer.bos_token_id) == 1
+ assert "think" not in tokenizer.decode(model.sent)
+
+
[email protected]("template", [None, "{{ broken( }}"])
+def test_default_fallback_preserves_raw_special_tokens(tokenizer, template):
+ tokenizer.chat_template = template
+ encoded = live_eval.encode_prompt(tokenizer, "hello", return_tensors=None)
+ assert encoded["input_ids"] == tokenizer("hello")["input_ids"]
+ with pytest.raises(ValueError, match="chat.template"):
+ live_eval.encode_prompt(tokenizer, "hello", chat_template_kwargs={"enable_thinking": False})
+
+
+def test_public_prompt_budget_and_batch_padding(tokenizer):
+ encoded = [
+ live_eval.encode_prompt(tokenizer, text, return_tensors=None)
+ for text in ["hello " * 2000, "world"]
+ ]
+ assert len(encoded[0]["input_ids"]) == live_eval.MAX_PROMPT_TOKENS == 1024
+ assert encoded[0]["input_ids"][-1] == tokenizer.convert_tokens_to_ids("hello")
+ assert tokenizer.convert_tokens_to_ids("assistant") not in encoded[0]["input_ids"]
+ batch = tokenizer.pad(encoded, padding=True, return_tensors="pt")
+ assert batch["input_ids"].shape == (2, 1024)
+ assert batch["attention_mask"][1].sum() == len(encoded[1]["input_ids"])
+
+
[email protected]("options", [
+ [], "bad", {1: False}, {"conversation": []}, {"tokenize": True},
+ {"add_generation_prompt": False}, {"continue_final_message": True},
+ {"return_tensors": "pt"}, {"return_dict": True}, {"padding": True},
+ {"truncation": True}, {"max_length": 1}, {"chat_template": "replacement"},
+ {"return_assistant_tokens_mask": True},
+])
+def test_invalid_options_fail_before_loading(monkeypatch, tokenizer, options):
+ def unexpected(*args, **kwargs):
+ pytest.fail("invalid options must fail before loading")
+
+ monkeypatch.setattr(live_eval, "load_model_and_tokenizer", unexpected)
+ for factory in [live_eval.make_generator, live_eval.make_multi_generator]:
+ with pytest.raises(ValueError, match="chat_template_kwargs"):
+ factory("unused", chat_template_kwargs=options)
+ with pytest.raises(ValueError, match="chat_template_kwargs"):
+ live_eval.encode_prompt(tokenizer, "hello", chat_template_kwargs=options)
+
+
+def test_real_model_cpu_uses_public_prompt_contract(tokenizer):
+ from tests._tiny_hf_models import build_llama
+
+ model = build_llama(tokenizer).eval()
+ result = live_eval.make_generator(
+ "unused", loaded=(model, tokenizer, "cpu"), max_new_tokens=2,
+ chat_template_kwargs={"enable_thinking": False},
+ )("hello")
+ assert isinstance(result, str)
+
+
[email protected]("adapter", [None, "adapter"])
+def test_ship_forwards_options_to_base_and_tuned(monkeypatch, adapter):
+ from soup_cli.commands.ship import _resolve_generators
+
+ calls = []
+
+ def factory(model_id, **kwargs):
+ calls.append((model_id, kwargs))
+ return lambda prompt: "answer"
+
+ monkeypatch.setattr(live_eval, "make_generator", factory)
+ _resolve_generators("base", "tuned" if adapter is None else None, adapter, "cpu",
+ chat_template_kwargs={"enable_thinking": False})
+ assert len(calls) == 2
+ assert all(c[1]["chat_template_kwargs"] == {"enable_thinking": False} for c in calls)
+
+
[email protected]("value", ["[]", "null", "bad", '{"tokenize":true}',
+ '{"enable_thinking":NaN}', '{"chat_template":"replacement"}',
+ '{"return_assistant_tokens_mask":true}'])
+def test_ship_invalid_json_options_are_usage_errors(value):
+ result = CliRunner().invoke(app, ["ship", "--chat-template-kwargs", value])
+ assert result.exit_code == 3
+ assert "--chat-template-kwargs" in result.output
+
+
+def test_ship_cli_forwards_valid_json(monkeypatch):
+ import soup_cli.commands.ship as ship_module
+
+ seen = {}
+
+ def verdict(**kwargs):
+ seen.update(kwargs)
+ raise RuntimeError("stop after flag parsing")
+
+ monkeypatch.setattr(ship_module, "_verdict_live", verdict)
+ result = CliRunner().invoke(app, ["ship", "--base", "base", "--tuned", "tuned",
+ "--task-eval", "tasks.jsonl", "--chat-template-kwargs",
+ json.dumps({"enable_thinking": False})])
+ assert isinstance(result.exception, RuntimeError)
+ assert seen["chat_template_kwargs"] == {"enable_thinking": False}
+
+
+def test_ship_refuses_template_options_in_offline_mode():
+ result = CliRunner().invoke(app, ["ship", "--evidence", "missing.json",
+ "--chat-template-kwargs", "{}"])
+ assert result.exit_code == 3
+ assert "live" in result.output
+
+
+def test_live_ship_cli_options_reach_both_generators(monkeypatch, tmp_path):
+ calls = []
+
+ def factory(model_id, **kwargs):
+ calls.append((model_id, kwargs))
+ return lambda prompt: "answer" if model_id == "tuned" else "wrong"
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "tasks.jsonl").write_text(json.dumps(
+ {"prompt": "hello", "expected": "answer", "scoring": "exact"}
+ ) + "\n")
+ monkeypatch.setattr(live_eval, "make_generator", factory)
+ result = CliRunner().invoke(app, ["ship", "--base", "base", "--tuned", "tuned",
+ "--device", "cpu", "--task-eval", "tasks.jsonl",
+ "--chat-template-kwargs", '{"enable_thinking":false}'])
+ assert result.exit_code == 0, result.output
+ assert [call[0] for call in calls] == ["base", "tuned"]
+ assert all(call[1]["chat_template_kwargs"] == {"enable_thinking": False} for call in calls)
+
+
[email protected]("factory", ["make_generator", "make_multi_generator"])
+def test_generators_snapshot_nested_template_options(tokenizer, factory):
+ import torch
+
+ tokenizer.chat_template = (
+ "{{ bos_token }}{{ messages[0]['content'] }} "
+ "{% if settings.flags.enable_thinking %}think{% else %}answer{% endif %}"
+ "{% if add_generation_prompt %} assistant{% endif %}"
+ )
+
+ class Recorder:
+ sent = None
+
+ def generate(self, input_ids, **kwargs):
+ self.sent = input_ids.tolist()[0]
+ return torch.cat([input_ids, input_ids[:, -1:]], dim=1)
+
+ model = Recorder()
+ options = {"settings": {"flags": {"enable_thinking": False}}}
+ generate = getattr(live_eval, factory)(
+ "unused", loaded=(model, tokenizer, "cpu"), chat_template_kwargs=options,
+ )
+ options["settings"]["flags"]["enable_thinking"] = True
+ if factory == "make_multi_generator":
+ generate("hello", 1)
+ else:
+ generate("hello")
+ assert tokenizer.convert_tokens_to_ids("answer") in model.sent
+ assert tokenizer.convert_tokens_to_ids("think") not in model.sent
+
+
+def test_template_error_keeps_the_underlying_diagnostic(tokenizer):
+ tokenizer.chat_template = '{{ raise_exception("named rendering cause") }}'
+ with pytest.raises(ValueError, match="cannot render chat template.*named rendering cause"):
+ live_eval.encode_prompt(tokenizer, "hello", chat_template_kwargs={"enable_thinking": False})
+
+
+def test_ship_deeply_nested_json_is_a_usage_error():
+ value = '{"nested":' + '[' * 2000 + '0' + ']' * 2000 + '}'
+ result = CliRunner().invoke(app, ["ship", "--chat-template-kwargs", value])
+ assert result.exit_code == 3
+ assert "--chat-template-kwargs" in result.output