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(infer): add batched causal inference (#1083)

Samarth Mukhija33716a65b610
diff --git a/changelog.d/0.75.1/1083.added.md b/changelog.d/0.75.1/1083.added.md
new file mode 100644
index 00000000..cfc6f536
--- /dev/null
+++ b/changelog.d/0.75.1/1083.added.md
@@ -0,0 +1 @@
+- **`soup infer` supports opt-in batched causal-LM inference with `--batch-size`; the default remains 1 so existing inference behavior is preserved. fp16/bf16 batching may not be bit-exact with batch size 1.** (#765 by @Samearth17 in #1083)
diff --git a/docs/commands.md b/docs/commands.md
index 7cfa19d5..79ffbb4a 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -28,8 +28,8 @@ soup train --config soup.yaml --push-as user/repo Auto-push each checkpoint to
soup train --config soup.yaml --push-as user/repo --hf-resume Resume from latest HF checkpoint branch (not with training.relora_steps)
soup train --config soup.yaml --find-lr LR range finder: write recommended LR JSON
soup train --config soup.yaml --cloud modal|lambda --gpu a100 Render a cloud GPU controller (plan-only; --cloud-submit submits live)
-soup infer --model ./output --input p.jsonl Batch inference
-soup infer --model ./output --input p.jsonl --cuda-graphs Experimental CUDA graph decode (Qwen2/Llama, one GPU, PyTorch >= 2.14)
+soup infer --model ./output --input p.jsonl [--batch-size N] Batch inference; default batch size is 1; fp16/bf16 batching may not be bit-exact with batch size 1
+soup infer --model ./output --input p.jsonl --cuda-graphs Experimental CUDA graph decode (Qwen2/Llama, one GPU, PyTorch >= 2.14; batch size 1 only)
soup infer --task asr --model <whisper|adapter> --input a.jsonl --output o.jsonl [--audio-dir d --asr-language en --asr-task transcribe|translate] Whisper transcription + WER/CER
soup chat --model ./output Interactive chat
soup infer|chat|diff ... --device cpu|cuda|cuda:N|mps Pick where the model loads (see below)
diff --git a/src/soup_cli/commands/infer.py b/src/soup_cli/commands/infer.py
index 8ebdd314..8af248a8 100644
--- a/src/soup_cli/commands/infer.py
+++ b/src/soup_cli/commands/infer.py
@@ -91,6 +91,16 @@ def infer(
"-t",
help="Sampling temperature (0 = greedy)",
),
+ batch_size: int = typer.Option(
+ 1,
+ "--batch-size",
+ min=1,
+ help=(
+ "Number of causal-LM prompts to generate together "
+ "(default: 1; batching is opt-in; fp16/bf16 batching "
+ "may not be bit-exact with batch size 1)"
+ ),
+ ),
device: Optional[str] = typer.Option(
None,
"--device",
@@ -197,6 +207,12 @@ def infer(
audio_dir=audio_dir,
)
return
+ if cuda_graphs is True and batch_size > 1:
+ raise typer.BadParameter(
+ "--cuda-graphs records a batch of 1 and cannot be combined with "
+ "--batch-size above 1. Omit --cuda-graphs, or use --batch-size 1"
+ )
+
if task != "text":
console.print(f"[red]Unknown --task {task!r}; expected 'text' or 'asr'.[/]")
raise typer.Exit(2)
@@ -215,7 +231,6 @@ def infer(
console.print(
f"[dim]Local path not found; treating {model_ref!r} as a HF repo id.[/]"
)
- model_target = model_ref
# Read prompts
prompts = _read_prompts(input_path)
@@ -232,7 +247,7 @@ def infer(
console.print(
Panel(
- f"Model: [bold]{model_target}[/]\n"
+ f"Model: [bold]{model_ref}[/]\n"
f"Input: [bold]{input_path}[/] ({len(prompts)} prompts)\n"
f"Output: [bold]{output_file}[/]\n"
f"Device: [bold]{device}[/]\n"
@@ -245,7 +260,11 @@ def infer(
# Load model — gate trust_remote_code via the v0.36.0 helper.
console.print("[dim]Loading model...[/]")
model_obj, tokenizer = _load_model(
- model_target, base, device, trust_remote_code, is_local=(model_kind == "local"),
+ model_ref,
+ base,
+ device,
+ trust_remote_code,
+ is_local=(model_kind == "local"),
)
if cuda_graphs is True:
from soup_cli.utils.cuda_graphs import cuda_graph_generation_kwargs
@@ -289,29 +308,54 @@ def infer(
):
progress_task = progress.add_task("Generating...", total=len(prompts))
- for prompt_text in prompts:
- messages = [{"role": "user", "content": prompt_text}]
- try:
- response, token_count = _generate(
- model_obj, tokenizer, messages,
- max_tokens=max_tokens, temperature=temperature,
- **({"cuda_graphs": True} if cuda_graphs is True else {}),
+ if batch_size == 1:
+ prompt_batches = [[prompt] for prompt in prompts]
+ else:
+ prompt_batches = [
+ prompts[start : start + batch_size]
+ for start in range(0, len(prompts), batch_size)
+ ]
+
+ for prompt_batch in prompt_batches:
+ if batch_size == 1:
+ messages = [{"role": "user", "content": prompt_batch[0]}]
+ try:
+ generated = [
+ _generate(
+ model_obj,
+ tokenizer,
+ messages,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ **({"cuda_graphs": True} if cuda_graphs is True else {}),
+ )
+ ]
+ except Exception as exc:
+ if cuda_graphs is not True:
+ raise
+ raise _cuda_graph_failure(exc) from exc
+ else:
+ generated = _generate_batch(
+ model_obj,
+ tokenizer,
+ prompt_batch,
+ max_tokens=max_tokens,
+ temperature=temperature,
)
- except Exception as exc:
- if cuda_graphs is not True:
- raise
- raise _cuda_graph_failure(exc) from exc
-
- result = {
- "prompt": prompt_text,
- "response": response,
- "tokens_generated": token_count,
- }
- out_f.write(json.dumps(result, ensure_ascii=False) + "\n")
- out_f.flush()
- total_tokens += token_count
- num_results += 1
- progress.update(progress_task, advance=1)
+
+ for prompt_text, (response, token_count) in zip(
+ prompt_batch, generated, strict=True
+ ):
+ result = {
+ "prompt": prompt_text,
+ "response": response,
+ "tokens_generated": token_count,
+ }
+ out_f.write(json.dumps(result, ensure_ascii=False) + "\n")
+ out_f.flush()
+ total_tokens += token_count
+ num_results += 1
+ progress.update(progress_task, advance=1)
elapsed = time.time() - start_time
tokens_per_sec = total_tokens / elapsed if elapsed > 0 else 0
@@ -778,6 +822,92 @@ def _generate(
return response_text, token_count
+def _generate_batch(
+ model, tokenizer, prompts, max_tokens=256, temperature=0.7,
+) -> list[tuple[str, int]]:
+ """Generate responses for a causal-LM prompt batch in input order."""
+ from soup_cli.utils.vllm import _render_chat_prompt, encode_rendered_prompt
+
+ rendered = []
+ templated = None
+ for prompt in prompts:
+ text, row_templated = _render_chat_prompt(
+ [{"role": "user", "content": prompt}],
+ tokenizer,
+ fallback_on_error=False,
+ )
+ if templated is None:
+ templated = row_templated
+ elif templated != row_templated:
+ raise ValueError("mixed chat-template rendering modes in one batch")
+ rendered.append(text)
+
+ original_padding_side = tokenizer.padding_side
+ tokenizer.padding_side = "left"
+ try:
+ inputs = encode_rendered_prompt(
+ tokenizer,
+ rendered,
+ templated=bool(templated),
+ padding=True,
+ return_tensors="pt",
+ )
+ input_ids = inputs["input_ids"].to(model.device)
+ attention_mask = inputs["attention_mask"].to(model.device)
+ input_width = input_ids.shape[1]
+
+ import torch
+
+ with torch.no_grad():
+ gen_kwargs = {
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ "max_new_tokens": max_tokens,
+ "do_sample": temperature > 0,
+ "pad_token_id": tokenizer.pad_token_id,
+ }
+ if temperature > 0:
+ gen_kwargs["temperature"] = temperature
+ gen_kwargs["top_p"] = 0.9
+ outputs = model.generate(**gen_kwargs)
+
+ results = []
+ eos_token_ids = getattr(tokenizer, "eos_token_id", None)
+ if eos_token_ids is None:
+ eos_token_ids = set()
+ elif isinstance(eos_token_ids, (list, tuple, set)):
+ eos_token_ids = set(eos_token_ids)
+ else:
+ eos_token_ids = {int(eos_token_ids)}
+
+ for output in outputs:
+ new_tokens = output[input_width:]
+ token_count = new_tokens.shape[0]
+ pad_token_id = tokenizer.pad_token_id
+
+ for index, token in enumerate(new_tokens):
+ token_id = int(token)
+ if token_id in eos_token_ids:
+ token_count = index + 1
+ break
+ if token_id == pad_token_id:
+ token_count = index
+ break
+
+ actual_tokens = new_tokens[:token_count]
+ results.append(
+ (
+ tokenizer.decode(
+ actual_tokens, skip_special_tokens=True
+ ).strip(),
+ token_count,
+ )
+ )
+ return results
+ finally:
+ tokenizer.padding_side = original_padding_side
+
+
def _count_prompt_tokens(tokenizer, prompt_text: str) -> int:
"""Tokens in the chat-templated prompt: the length the static cache must hold."""
from soup_cli.utils.vllm import encode_chat_prompt
@@ -825,7 +955,12 @@ def _warm_cuda_graphs(model, tokenizer, prompts: list[str], max_tokens: int) ->
messages = [{"role": "user", "content": _longest_prompt(tokenizer, prompts)}]
try:
_generate(
- model, tokenizer, messages, max_tokens=max_tokens, temperature=0.0, cuda_graphs=True,
+ model,
+ tokenizer,
+ messages,
+ max_tokens=max_tokens,
+ temperature=0.0,
+ cuda_graphs=True,
min_tokens=min(max_tokens, _CUDA_GRAPH_WARMUP_TOKENS),
)
except Exception as exc:
diff --git a/tests/test_cuda_graph_cli.py b/tests/test_cuda_graph_cli.py
index 8b255ab6..a7dc1d8d 100644
--- a/tests/test_cuda_graph_cli.py
+++ b/tests/test_cuda_graph_cli.py
@@ -135,6 +135,25 @@ def test_cuda_graphs_reject_asr_before_loading(monkeypatch, tmp_path):
load.assert_not_called()
+def test_cuda_graphs_reject_batch_size_above_one_before_loading(monkeypatch, tmp_path):
+ from soup_cli.cli import app
+ from soup_cli.commands import infer
+
+ model_dir = _infer_env(monkeypatch, tmp_path, ["question"], MagicMock())
+ load = MagicMock(return_value=(object(), object()))
+ monkeypatch.setattr(infer, "_load_model", load)
+
+ result = CliRunner().invoke(
+ app,
+ _infer_args(model_dir, "--cuda-graphs", "--batch-size", "2"),
+ )
+
+ assert result.exit_code == 2
+ assert "--batch-size above 1" in _plain(result.output)
+ assert "Omit --cuda-graphs" in _plain(result.output)
+ load.assert_not_called()
+
+
def test_unsupported_graph_model_preserves_existing_output(monkeypatch, tmp_path):
from soup_cli.cli import app
from soup_cli.commands import infer
diff --git a/tests/test_infer.py b/tests/test_infer.py
index 5815831e..a9bdcf66 100644
--- a/tests/test_infer.py
+++ b/tests/test_infer.py
@@ -5,6 +5,168 @@ from unittest.mock import MagicMock, PropertyMock
import pytest
+from tests.conftest import strip_ansi
+
+
+class _BatchTokenizer:
+ def __init__(self, *, templated: bool):
+ self.chat_template = "dummy" if templated else None
+ self.pad_token_id = 0
+ self.padding_side = "right"
+ self.calls = []
+ self.padding_sides = []
+ self.template_calls = []
+
+ def apply_chat_template(self, messages, **kwargs):
+ self.template_calls.append((messages, kwargs))
+ return f"templated:{messages[0]['content']}"
+
+ def __call__(
+ self,
+ texts,
+ *,
+ add_special_tokens=True,
+ padding=False,
+ return_tensors=None,
+ ):
+ import torch
+
+ is_batch = isinstance(texts, list)
+ text_rows = texts if is_batch else [texts]
+ self.calls.append(
+ {
+ "is_batch": is_batch,
+ "add_special_tokens": add_special_tokens,
+ "padding": padding,
+ "return_tensors": return_tensors,
+ }
+ )
+ self.padding_sides.append(self.padding_side)
+ rows = [list(range(1, len(text) % 3 + 2)) for text in text_rows]
+ width = max(len(row) for row in rows)
+ padded = []
+ masks = []
+ for row in rows:
+ pad_count = width - len(row)
+ if self.padding_side == "left":
+ padded.append([self.pad_token_id] * pad_count + row)
+ masks.append([0] * pad_count + [1] * len(row))
+ else:
+ padded.append(row + [self.pad_token_id] * pad_count)
+ masks.append([1] * len(row) + [0] * pad_count)
+ return {
+ "input_ids": torch.tensor(padded),
+ "attention_mask": torch.tensor(masks),
+ }
+
+ def decode(self, token_ids, skip_special_tokens=True):
+ return f"response-{int(token_ids[-1])}"
+
+
+class _DeterministicBatchModel:
+ def __init__(self):
+ import torch
+
+ self.device = torch.device("cpu")
+ self.generate_calls = []
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ import torch
+
+ self.generate_calls.append(
+ {
+ "input_ids": input_ids.clone(),
+ "attention_mask": attention_mask.clone(),
+ "kwargs": kwargs,
+ }
+ )
+ generated = []
+ for row, mask in zip(input_ids, attention_mask, strict=True):
+ signature = int(row[mask.bool()].sum())
+ generated.append(torch.tensor([[100 + signature]]))
+ return torch.cat([input_ids, torch.cat(generated)], dim=1)
+
+
+class _CharTokenizer:
+ """Small tokenizer whose generated answer can depend on prompt content."""
+
+ chat_template = "chars"
+ pad_token_id = 0
+ eos_token_id = 2
+ padding_side = "right"
+
+ def apply_chat_template(self, messages, **kwargs):
+ return messages[0]["content"]
+
+ def __call__(
+ self,
+ texts,
+ *,
+ add_special_tokens=True,
+ padding=False,
+ return_tensors=None,
+ ):
+ import torch
+
+ rows = texts if isinstance(texts, list) else [texts]
+ encoded = [[ord(char) % 251 + 3 for char in text] for text in rows]
+ width = max(len(row) for row in encoded)
+ input_ids = []
+ attention_mask = []
+ for row in encoded:
+ pad_count = width - len(row)
+ if self.padding_side == "left":
+ input_ids.append([self.pad_token_id] * pad_count + row)
+ attention_mask.append([0] * pad_count + [1] * len(row))
+ else:
+ input_ids.append(row + [self.pad_token_id] * pad_count)
+ attention_mask.append([1] * len(row) + [0] * pad_count)
+ return {
+ "input_ids": torch.tensor(input_ids),
+ "attention_mask": torch.tensor(attention_mask),
+ }
+
+ def decode(self, token_ids, skip_special_tokens=True):
+ tokens = [int(token) for token in token_ids]
+ return "answer-" + str(tokens[0] - 1000) if tokens else ""
+
+
+class _EchoModel:
+ """Return a token derived from each row, with EOS for selected prompts."""
+
+ def __init__(self):
+ import torch
+
+ self.device = torch.device("cpu")
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ import torch
+
+ generated = []
+ for row, mask in zip(input_ids, attention_mask, strict=True):
+ prompt_sum = int(row[mask.bool()].sum())
+ response = 1000 + prompt_sum
+ if prompt_sum % 2:
+ generated.append(torch.tensor([response, 2]))
+ else:
+ generated.append(torch.tensor([response]))
+ width = max(len(row) for row in generated)
+ padded = [
+ torch.cat([row, torch.zeros(width - len(row), dtype=torch.long)])
+ for row in generated
+ ]
+ return torch.cat([input_ids, torch.stack(padded)], dim=1)
+
+
+def _expected_pairs(prompts):
+ tokenizer = _CharTokenizer()
+ expected = []
+ for prompt in prompts:
+ encoded = tokenizer(prompt, return_tensors="pt")
+ prompt_sum = int(encoded["input_ids"].sum())
+ expected.append((prompt, f"answer-{prompt_sum}", 2 if prompt_sum % 2 else 1))
+ return expected
+
# ─── Prompt Reading Tests ───────────────────────────────────────────────────
@@ -29,6 +191,104 @@ class TestReadPrompts:
assert result[1] == "Explain gravity."
assert result[2] == "Hello world."
+
+class TestPromptDependentBatchPairing:
+ MAX_TOKENS = 12
+ PAIRING_PROMPTS = [
+ "a",
+ "hello world",
+ "x!",
+ "the quick brown fox",
+ "hi",
+ "zz top!",
+ "0123456789",
+ ]
+
+ def test_batch_matches_one_by_one_prompt_dependent_results(self):
+ from soup_cli.commands.infer import _generate, _generate_batch
+
+ tokenizer = _CharTokenizer()
+ model = _EchoModel()
+ batched = _generate_batch(
+ model,
+ tokenizer,
+ self.PAIRING_PROMPTS,
+ max_tokens=self.MAX_TOKENS,
+ temperature=0,
+ )
+ one_by_one = [
+ _generate(
+ model,
+ tokenizer,
+ [{"role": "user", "content": prompt}],
+ max_tokens=self.MAX_TOKENS,
+ temperature=0,
+ )
+ for prompt in self.PAIRING_PROMPTS
+ ]
+
+ assert [
+ (prompt, response, token_count)
+ for prompt, (response, token_count) in zip(
+ self.PAIRING_PROMPTS, batched, strict=True
+ )
+ ] == [
+ (prompt, response, token_count)
+ for prompt, (response, token_count) in zip(
+ self.PAIRING_PROMPTS, one_by_one, strict=True
+ )
+ ] == _expected_pairs(self.PAIRING_PROMPTS)
+
+ @pytest.mark.parametrize("batch_size", [2, 3, 8])
+ def test_cli_batch_sizes_match_batch_one(self, tmp_path, monkeypatch, batch_size):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts_path = tmp_path / "prompts.jsonl"
+ prompts_path.write_text(
+ "".join(
+ json.dumps({"prompt": prompt}) + "\n"
+ for prompt in self.PAIRING_PROMPTS
+ )
+ )
+ monkeypatch.chdir(tmp_path)
+ outputs = []
+ for size in (1, batch_size):
+ model = _EchoModel()
+ tokenizer = _CharTokenizer()
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._load_model",
+ lambda *args, model=model, tokenizer=tokenizer, **kwargs: (
+ model,
+ tokenizer,
+ ),
+ )
+ output_path = tmp_path / f"output-{size}.jsonl"
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", "fake/model",
+ "--input", str(prompts_path),
+ "--output", str(output_path),
+ "--device", "cpu",
+ "--batch-size", str(size),
+ "--max-tokens", str(self.MAX_TOKENS),
+ "--temperature", "0",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ outputs.append(
+ [json.loads(line) for line in output_path.read_text().splitlines()]
+ )
+
+ assert outputs[0] == outputs[1]
+ assert [
+ (row["prompt"], row["response"], row["tokens_generated"])
+ for row in outputs[1]
+ ] == _expected_pairs(self.PAIRING_PROMPTS)
+
def test_read_plain_text_prompts(self, tmp_path):
"""Should read plain text lines as prompts."""
from soup_cli.commands.infer import _read_prompts
@@ -172,6 +432,64 @@ class TestInferCLI:
result = runner.invoke(app, ["infer", "--help"])
assert result.exit_code == 0
assert "batch inference" in result.output.lower()
+ assert "--batch-size" in strip_ansi(result.output)
+
+ @pytest.mark.parametrize("batch_size", [0, -1])
+ def test_batch_size_must_be_positive(self, tmp_path, batch_size, monkeypatch):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts_file = tmp_path / "prompts.jsonl"
+ prompts_file.write_text(json.dumps({"prompt": "test"}) + "\n")
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._load_model",
+ lambda *args, **kwargs: (object(), object()),
+ )
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", str(tmp_path),
+ "--input", str(prompts_file),
+ "--output", str(tmp_path / "out.jsonl"),
+ "--batch-size", str(batch_size),
+ ],
+ )
+
+ assert result.exit_code == 2
+ assert "x>=1" in result.output
+
+ def test_cuda_graphs_refuses_batched_generation_before_model_load(
+ self, tmp_path, monkeypatch
+ ):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts_file = tmp_path / "prompts.jsonl"
+ prompts_file.write_text(json.dumps({"prompt": "test"}) + "\n")
+
+ def fail_model_load(*args, **kwargs):
+ raise AssertionError("model loading must not run for an invalid option pair")
+
+ monkeypatch.setattr("soup_cli.commands.infer._load_model", fail_model_load)
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", "fake/model",
+ "--input", str(prompts_file),
+ "--output", str(tmp_path / "out.jsonl"),
+ "--cuda-graphs",
+ "--batch-size", "2",
+ ],
+ )
+
+ assert result.exit_code == 2
+ assert "cannot be combined" in strip_ansi(result.output)
+ assert "--batch-size above 1" in strip_ansi(result.output)
def test_required_options_error(self):
"""Should fail if required options are missing."""
@@ -413,6 +731,445 @@ class TestGenerate:
assert "Assistant:" in tokenizer_call_args
+class TestGenerateBatch:
+ def test_batch_template_errors_are_not_silently_fallback(self):
+ from soup_cli.commands.infer import _generate_batch
+
+ class BrokenTemplateTokenizer(_BatchTokenizer):
+ def apply_chat_template(self, messages, **kwargs):
+ raise ValueError("broken chat template")
+
+ with pytest.raises(ValueError, match="broken chat template"):
+ _generate_batch(
+ _DeterministicBatchModel(),
+ BrokenTemplateTokenizer(templated=True),
+ ["first", "second"],
+ max_tokens=1,
+ temperature=0,
+ )
+
+ def test_batch_generation_uses_left_padding_and_one_call(self):
+ from soup_cli.commands.infer import _generate_batch
+
+ model = _DeterministicBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+
+ results = _generate_batch(
+ model,
+ tokenizer,
+ ["xx", "xxxx"],
+ max_tokens=4,
+ temperature=0,
+ )
+
+ assert len(results) == 2
+ assert len(model.generate_calls) == 1
+ assert tokenizer.padding_side == "right"
+ assert tokenizer.padding_sides[-1] == "left"
+ assert tokenizer.calls[-1] == {
+ "is_batch": True,
+ "add_special_tokens": False,
+ "padding": True,
+ "return_tensors": "pt",
+ }
+ assert model.generate_calls[0]["input_ids"][0, 0].item() == 0
+
+ def test_batch_generation_counts_tokens_before_padding(self):
+ import torch
+
+ from soup_cli.commands.infer import _generate_batch
+
+ class VariableLengthBatchModel:
+ device = torch.device("cpu")
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ generated = []
+ lengths = [2, 5]
+
+ for index, (row, mask) in enumerate(
+ zip(input_ids, attention_mask, strict=True)
+ ):
+ signature = int(row[mask.bool()].sum())
+ tokens = [
+ 100 + signature + offset
+ for offset in range(lengths[index])
+ ]
+ generated.append(torch.tensor([tokens], dtype=torch.long))
+
+ max_length = max(lengths)
+ padded = [
+ torch.cat(
+ [
+ tokens,
+ torch.zeros(
+ (1, max_length - tokens.shape[1]),
+ dtype=torch.long,
+ ),
+ ],
+ dim=1,
+ )
+ for tokens in generated
+ ]
+ return torch.cat([input_ids, torch.cat(padded)], dim=1)
+
+ model = VariableLengthBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+
+ results = _generate_batch(
+ model,
+ tokenizer,
+ ["first", "second"],
+ max_tokens=5,
+ temperature=0,
+ )
+
+ assert [token_count for _, token_count in results] == [2, 5]
+
+
+ def test_batch_generation_stops_counting_at_eos(self):
+ import torch
+
+ from soup_cli.commands.infer import _generate_batch
+
+ class EosBatchModel:
+ device = torch.device("cpu")
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ generated = []
+ for index, (row, mask) in enumerate(
+ zip(input_ids, attention_mask, strict=True)
+ ):
+ signature = int(row[mask.bool()].sum())
+ if index == 0:
+ tokens = [
+ 100 + signature,
+ 99,
+ 101 + signature,
+ 102 + signature,
+ 103 + signature,
+ ]
+ else:
+ tokens = [
+ 110 + signature,
+ 111 + signature,
+ 112 + signature,
+ 113 + signature,
+ 114 + signature,
+ ]
+ generated.append(torch.tensor([tokens], dtype=torch.long))
+
+ return torch.cat([input_ids, torch.cat(generated)], dim=1)
+
+ model = EosBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+ tokenizer.eos_token_id = 99
+
+ results = _generate_batch(
+ model,
+ tokenizer,
+ ["first", "second"],
+ max_tokens=5,
+ temperature=0,
+ )
+
+ assert [token_count for _, token_count in results] == [2, 5]
+
+
+ def test_batch_generation_uses_attention_mask_for_padding(self):
+ import torch
+
+ from soup_cli.commands.infer import _generate_batch
+
+ class MaskCheckingModel:
+ device = torch.device("cpu")
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ assert torch.equal(
+ attention_mask == 0,
+ input_ids == 99,
+ )
+ generated = torch.tensor(
+ [[101], [102]],
+ dtype=torch.long,
+ )
+ return torch.cat([input_ids, generated], dim=1)
+
+ model = MaskCheckingModel()
+ tokenizer = _BatchTokenizer(templated=True)
+ tokenizer.pad_token_id = 99
+
+ results = _generate_batch(
+ model,
+ tokenizer,
+ ["x", "xx"],
+ max_tokens=1,
+ temperature=0,
+ )
+
+ assert [response for response, _ in results] == [
+ "response-101",
+ "response-102",
+ ]
+
+
+ def test_batch_generation_restores_original_padding_side(self):
+ from soup_cli.commands.infer import _generate_batch
+
+ model = _DeterministicBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+
+ _generate_batch(model, tokenizer, ["first", "second"], temperature=0)
+
+ assert tokenizer.padding_sides[-1] == "left"
+ assert tokenizer.padding_side == "right"
+
+ def test_templated_and_untemplated_batch_encoding(self):
+ from soup_cli.commands.infer import _generate_batch
+
+ for templated, expected_special_tokens in ((True, False), (False, True)):
+ model = _DeterministicBatchModel()
+ tokenizer = _BatchTokenizer(templated=templated)
+
+ _generate_batch(model, tokenizer, ["one", "two"], temperature=0)
+
+ assert tokenizer.calls[-1]["add_special_tokens"] is expected_special_tokens
+
+ def test_batch_generation_preserves_prompt_response_order(self):
+ import torch
+
+ from soup_cli.commands.infer import _generate_batch
+
+ class OrderedBatchModel:
+ device = torch.device("cpu")
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ generated = [
+ torch.tensor([[101 + index]], dtype=torch.long)
+ for index in range(input_ids.shape[0])
+ ]
+ return torch.cat([input_ids, torch.cat(generated)], dim=1)
+
+ model = OrderedBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+
+ results = _generate_batch(
+ model,
+ tokenizer,
+ ["first", "second"],
+ max_tokens=1,
+ temperature=0,
+ )
+
+ assert [response for response, _ in results] == [
+ "response-101",
+ "response-102",
+ ]
+
+
+ def test_batch_size_one_uses_legacy_generate_path(self, tmp_path, monkeypatch):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts_path = tmp_path / "prompts.jsonl"
+ prompts_path.write_text(json.dumps({"prompt": "hello"}) + "\n")
+ output_path = tmp_path / "output.jsonl"
+ monkeypatch.chdir(tmp_path)
+
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._load_model",
+ lambda *args, **kwargs: (object(), object()),
+ )
+
+ calls = []
+
+ def fake_generate(model, tokenizer, messages, *, max_tokens, temperature):
+ calls.append(messages)
+ return "legacy-response", 3
+
+ def fail_generate_batch(*args, **kwargs):
+ raise AssertionError("_generate_batch must not be used for batch_size=1")
+
+ monkeypatch.setattr("soup_cli.commands.infer._generate", fake_generate)
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._generate_batch",
+ fail_generate_batch,
+ )
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", "fake/model",
+ "--input", str(prompts_path),
+ "--output", str(output_path),
+ "--device", "cpu",
+ "--batch-size", "1",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert len(calls) == 1
+ assert json.loads(output_path.read_text()) == {
+ "prompt": "hello",
+ "response": "legacy-response",
+ "tokens_generated": 3,
+ }
+
+
+ def test_default_batch_size_uses_legacy_generate_path(self, tmp_path, monkeypatch):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts_path = tmp_path / "prompts.jsonl"
+ prompts_path.write_text(json.dumps({"prompt": "hello"}) + "\n")
+ output_path = tmp_path / "output.jsonl"
+ monkeypatch.chdir(tmp_path)
+
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._load_model",
+ lambda *args, **kwargs: (object(), object()),
+ )
+
+ calls = []
+
+ def fake_generate(model, tokenizer, messages, *, max_tokens, temperature):
+ calls.append(messages)
+ return "legacy-response", 3
+
+ def fail_generate_batch(*args, **kwargs):
+ raise AssertionError("_generate_batch must not be used for default batch_size=1")
+
+ monkeypatch.setattr("soup_cli.commands.infer._generate", fake_generate)
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._generate_batch",
+ fail_generate_batch,
+ )
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", "fake/model",
+ "--input", str(prompts_path),
+ "--output", str(output_path),
+ "--device", "cpu",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert len(calls) == 1
+ assert json.loads(output_path.read_text()) == {
+ "prompt": "hello",
+ "response": "legacy-response",
+ "tokens_generated": 3,
+ }
+
+
+ def test_cli_batches_keep_prompt_response_pairs_in_input_order(self, tmp_path, monkeypatch):
+ import torch
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts_path = tmp_path / "prompts.jsonl"
+ prompts = ["please say a", "say b", "say c", "now say d", "say e"]
+ prompts_path.write_text(
+ "".join(json.dumps({"prompt": prompt}) + "\n" for prompt in prompts)
+ )
+ output_path = tmp_path / "output.jsonl"
+ class UniqueBatchModel:
+ device = torch.device("cpu")
+
+ def __init__(self):
+ self.next_token = 101
+ self.generate_calls = []
+
+ def generate(self, input_ids, attention_mask, **kwargs):
+ self.generate_calls.append(input_ids.clone())
+ rows = []
+ for _ in range(input_ids.shape[0]):
+ rows.append(torch.tensor([[self.next_token]]))
+ self.next_token += 1
+ return torch.cat([input_ids, torch.cat(rows)], dim=1)
+
+ model = UniqueBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._load_model",
+ lambda *args, **kwargs: (model, tokenizer),
+ )
+ monkeypatch.chdir(tmp_path)
+
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", "fake/model",
+ "--input", str(prompts_path),
+ "--output", str(output_path),
+ "--device", "cpu",
+ "--batch-size", "2",
+ "--temperature", "0",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ rows = [json.loads(line) for line in output_path.read_text().splitlines()]
+ assert [(row["prompt"], row["response"]) for row in rows] == [
+ (prompt, f"response-{101 + index}")
+ for index, prompt in enumerate(prompts)
+ ]
+ assert len(model.generate_calls) == 3
+
+ def test_batch_size_one_and_eight_have_identical_outputs(
+ self, tmp_path, monkeypatch
+ ):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ prompts = [f"prompt-{index}" for index in range(5)]
+ prompts_path = tmp_path / "prompts.jsonl"
+ prompts_path.write_text(
+ "".join(json.dumps({"prompt": prompt}) + "\n" for prompt in prompts)
+ )
+ monkeypatch.chdir(tmp_path)
+ outputs = []
+ models = []
+ for batch_size in (1, 8):
+ model = _DeterministicBatchModel()
+ tokenizer = _BatchTokenizer(templated=True)
+ monkeypatch.setattr(
+ "soup_cli.commands.infer._load_model",
+ lambda *args, model=model, tokenizer=tokenizer, **kwargs: (
+ model,
+ tokenizer,
+ ),
+ )
+ output_path = tmp_path / f"output-{batch_size}.jsonl"
+ result = CliRunner().invoke(
+ app,
+ [
+ "infer",
+ "--model", "fake/model",
+ "--input", str(prompts_path),
+ "--output", str(output_path),
+ "--device", "cpu",
+ "--batch-size", str(batch_size),
+ "--temperature", "0",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ outputs.append([json.loads(line) for line in output_path.read_text().splitlines()])
+ models.append(model)
+
+ assert outputs[0] == outputs[1]
+ assert len(models[0].generate_calls) == 5
+ assert len(models[1].generate_calls) == 1
+
+
# ─── Import Tests ─────────────────────────────────────────────────────────
@@ -543,4 +1300,3 @@ class TestInferHFRepoId:
assert called_model_arg == repo_id
assert "\\" not in called_model_arg
assert "/" in called_model_arg
-