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(infer,chat,diff): honor --device instead of hard-coding device_map=auto (#1460)
Younes Beriane4eca01e2787f
diff --git a/changelog.d/0.75.1/1460.fixed.md b/changelog.d/0.75.1/1460.fixed.mdnew file mode 100644index 00000000..b34738ae--- /dev/null+++ b/changelog.d/0.75.1/1460.fixed.md@@ -0,0 +1,13 @@+- `soup infer`, `soup chat` and `soup diff` now honor `--device` when loading+ models instead of always passing `device_map="auto"` and+ `torch_dtype=torch.float16` to `from_pretrained` (#1443 by @drakeo338 in+ #1460). `cpu` (and `mlx` on this path) is pinned to the CPU in `float32`;+ `cuda:N` and `mps` are pinned to that device; plain `cuda` keeps+ `device_map="auto"`. GPUs keep `float16`. Values are case-insensitive, and+ an unknown `--device` (`gpu`, `auto`, `cuda:0,1`, ...) now raises an error+ instead of being printed and ignored.+- Default-path change: the CLIs always auto-detect a device when `--device` is+ not given, so these rules apply without the flag too, and to `soup bench`,+ which loads through `soup infer`. On a CPU-only host the model now loads in+ `float32` pinned to the CPU instead of `"auto"`/`float16`, which doubles its+ RAM use (a 7B model needs about 28 GB instead of 14 GB).diff --git a/docs/commands.md b/docs/commands.mdindex 3c26e38a..7032c482 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -32,6 +32,7 @@ soup infer --model ./output --input p.jsonl Batch inferencesoup infer --model ./output --input p.jsonl --cuda-graphs Experimental CUDA graph decode (Qwen2/Llama, one GPU, PyTorch >= 2.14)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/CERsoup chat --model ./output Interactive chat+soup infer|chat|diff ... --device cpu|cuda|cuda:N|mps Pick where the model loads (see below)soup push --model ./output --repo user/name Upload to HuggingFacesoup push --model ./output --repo user/name --collection user/coll-abc123 Add to HF Collectionsoup merge --adapter ./output Merge LoRA with base model@@ -377,6 +378,23 @@ soup version [--full] [--json] Show version (--full: system info,soup --verbose <command> Full traceback on errors```+### Choosing the device for `soup infer`, `soup chat` and `soup diff`++`--device` decides where these commands load the model. Without it, the+device is auto-detected and the same rules apply to what was detected (this+also covers `soup bench`, which loads through the `soup infer` path).++| `--device` | Placement | Dtype |+|---|---|---|+| `cpu` | pinned to the CPU | `float32` (twice the RAM of `float16`: a 7B model needs about 28 GB) |+| `cuda` | `device_map="auto"`: accelerate may use every visible GPU and spill to the CPU if the model does not fit | `float16` |+| `cuda:N` | pinned to GPU `N` | `float16` |+| `mps` | pinned to the Apple GPU | `float16` |+| `mlx` | runs on the CPU on this path | `float32` |++Values are case-insensitive. Any other value (`gpu`, `auto`, `cuda:0,1`, ...)+is refused with an error instead of being ignored.+### Best-of-N recovery and publication`soup data best-of-n` appends and synchronizes one checkpoint record after eachdiff --git a/src/soup_cli/commands/chat.py b/src/soup_cli/commands/chat.pyindex 810ca07e..1ddcd3f5 100644--- a/src/soup_cli/commands/chat.py+++ b/src/soup_cli/commands/chat.py@@ -191,7 +191,6 @@ def chat(model_obj, tokenizer, history,max_tokens=max_tokens,temperature=temperature,- device=device,)history.append({"role": "assistant", "content": response})@@ -216,9 +215,12 @@ def _load_model(trust_remote_code: bool = False,):"""Load model and tokenizer. Supports LoRA adapters and full models."""- import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer+ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtype++ device_map, torch_dtype = resolve_inference_device_map_and_dtype(device)+console.print("[dim]Loading tokenizer...[/]")tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=trust_remote_code@@ -233,8 +235,8 @@ def _load_model(base = AutoModelForCausalLM.from_pretrained(base_model,trust_remote_code=trust_remote_code,- device_map="auto",- torch_dtype=torch.float16,+ device_map=device_map,+ torch_dtype=torch_dtype,)console.print(f"[dim]Loading LoRA adapter: {model_path}...[/]")model_obj = PeftModel.from_pretrained(base, model_path)@@ -243,8 +245,8 @@ def _load_model(model_obj = AutoModelForCausalLM.from_pretrained(model_path,trust_remote_code=trust_remote_code,- device_map="auto",- torch_dtype=torch.float16,+ device_map=device_map,+ torch_dtype=torch_dtype,)model_obj.eval()@@ -257,7 +259,6 @@ def _generate(messages: list[dict],max_tokens: int = 512,temperature: float = 0.7,- device: str = "cuda",) -> str:"""Generate a response from the model given message history."""import torchdiff --git a/src/soup_cli/commands/diff.py b/src/soup_cli/commands/diff.pyindex 7c585e03..55b2fa8b 100644--- a/src/soup_cli/commands/diff.py+++ b/src/soup_cli/commands/diff.py@@ -218,14 +218,16 @@ def _load_model(trust_remote_code: bool = False,):"""Load a model and tokenizer."""- import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer+ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtypefrom soup_cli.utils.trust_remote import (model_requires_trust_remote_code,resolve_trust_remote_code,)+ device_map, torch_dtype = resolve_inference_device_map_and_dtype(device)+path = Path(model_path)adapter_config_path = path / "adapter_config.json"is_adapter = adapter_config_path.exists()@@ -261,16 +263,16 @@ def _load_model(base = AutoModelForCausalLM.from_pretrained(base_model,trust_remote_code=trc,- device_map="auto",- torch_dtype=torch.float16,+ device_map=device_map,+ torch_dtype=torch_dtype,)model_obj = PeftModel.from_pretrained(base, model_path)else:model_obj = AutoModelForCausalLM.from_pretrained(model_path,trust_remote_code=trc,- device_map="auto",- torch_dtype=torch.float16,+ device_map=device_map,+ torch_dtype=torch_dtype,)model_obj.eval()diff --git a/src/soup_cli/commands/infer.py b/src/soup_cli/commands/infer.pyindex a481446e..a1b985ff 100644--- a/src/soup_cli/commands/infer.py+++ b/src/soup_cli/commands/infer.py@@ -664,14 +664,16 @@ def _load_model(is_local: Optional[bool] = None,) -> tuple:"""Load a model and tokenizer (reuses diff.py pattern)."""- import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer+ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtypefrom soup_cli.utils.trust_remote import (model_requires_trust_remote_code,resolve_trust_remote_code,)+ device_map, torch_dtype = resolve_inference_device_map_and_dtype(device)+if is_local is None:try:is_local = Path(model_path).exists()@@ -717,16 +719,16 @@ def _load_model(base_obj = AutoModelForCausalLM.from_pretrained(base_model,trust_remote_code=trc,- device_map="auto",- torch_dtype=torch.float16,+ device_map=device_map,+ torch_dtype=torch_dtype,)model_obj = PeftModel.from_pretrained(base_obj, model_path)else:model_obj = AutoModelForCausalLM.from_pretrained(model_path,trust_remote_code=trc,- device_map="auto",- torch_dtype=torch.float16,+ device_map=device_map,+ torch_dtype=torch_dtype,)model_obj.eval()diff --git a/src/soup_cli/utils/gpu.py b/src/soup_cli/utils/gpu.pyindex 0af27058..2e87de93 100644--- a/src/soup_cli/utils/gpu.py+++ b/src/soup_cli/utils/gpu.py@@ -6,7 +6,10 @@ import jsonimport mathimport osimport re-from typing import Optional+from typing import TYPE_CHECKING, Optional++if TYPE_CHECKING:+ import torch# A safetensors file starts with a u64 little-endian header length, then a# JSON header carrying each tensor's dtype + shape. Reading it costs a few@@ -97,6 +100,68 @@ def resolve_device_map(device: str):return "auto"+def resolve_inference_device_map_and_dtype(+ device: Optional[str],+) -> tuple[str | dict, "torch.dtype"]:+ """Map an inference ``--device`` value to ``from_pretrained`` kwargs (#1443).++ ``infer.py``, ``chat.py`` and ``diff.py`` each accept a ``device`` argument+ (explicit ``--device`` flag, or auto-detected via :func:`detect_device`)+ but used to hard-code ``device_map="auto", torch_dtype=torch.float16`` on+ every ``from_pretrained`` call regardless of it. ``device_map="auto"``+ lets ``accelerate`` place the model on any visible accelerator, which is+ exactly wrong when the user asked for the CPU on purpose (to leave VRAM+ free for a training job, or because the model does not fit on the GPU).++ This lives next to :func:`resolve_device_map` because both decide what a+ device string becomes for ``device_map=``, but they answer different+ questions and must not be merged: :func:`resolve_device_map` pins one+ *rank* of a ``torchrun`` / ``accelerate launch`` training job by reading+ ``LOCAL_RANK`` / ``WORLD_SIZE`` from the environment. There is no rank+ here — only the single device the user named or auto-detection picked —+ so a plain, unindexed accelerator (``"cuda"``) is left as ``"auto"``+ (harmless with one visible device, and how every trainer in this module+ already treats that case), while an explicit index (``"cuda:0"``) or+ ``"mps"`` is pinned directly instead.++ Args:+ device: ``"cpu"``, ``"cuda"``, ``"cuda:<n>"``, ``"mps"``, ``"mlx"``+ (any case — MLX has its own load path and never reaches+ ``from_pretrained`` in normal use, but a caller that lands here+ anyway must not pass ``"mlx"`` through as a torch device), or+ ``None``/empty when it was genuinely never resolved. Any other+ value raises :class:`ValueError` instead of being silently+ ignored.++ Returns:+ A ``(device_map, torch_dtype)`` pair to splat into+ ``from_pretrained(**kwargs)``: ``{"": "cpu"}`` and ``float32`` for+ CPU/MLX, ``{"": device}`` (lower-cased) and ``float16`` for+ MPS or an explicitly indexed ``cuda:<n>``, ``"auto"`` and ``float16``+ for plain ``cuda`` (accelerate may use every visible GPU), or+ the pre-#1443 ``"auto"``/``float16`` default when ``device`` is+ unset.+ """+ import torch++ if not device:+ return "auto", torch.float16++ normalized = str(device).strip().lower()+ if not re.fullmatch(r"cpu|mlx|mps|cuda(:\d+)?", normalized):+ raise ValueError(+ f"Unsupported --device {device!r}: use cpu, cuda, cuda:<index> or mps."+ )++ if normalized in ("cpu", "mlx"):+ return {"": "cpu"}, torch.float32++ if normalized == "mps" or ":" in normalized:+ return {"": normalized}, torch.float16++ return "auto", torch.float16++def detect_device(backend: Optional[str] = None) -> tuple[str, str]:"""Detect available accelerator device with full Apple Silicon runtime disambiguation.diff --git a/tests/test_bugfixes.py b/tests/test_bugfixes.pyindex af894d46..37f2a209 100644--- a/tests/test_bugfixes.py+++ b/tests/test_bugfixes.py@@ -143,7 +143,10 @@ class TestDiffModelLoading:from soup_cli.commands.diff import _load_modelsource = inspect.getsource(_load_model)- assert "torch_dtype=torch.float16" in source+ # #1443 resolves the value per --device instead of hard-coding+ # float16, but both from_pretrained calls must still use the+ # `torch_dtype=` spelling the floor Transformers version requires.+ assert source.count("torch_dtype=torch_dtype") == 2# Substring-safe: torch_dtype=... contains the letters dtype=bare = source.replace("torch_dtype=", "")assert "dtype=" not in barediff --git a/tests/test_issue1443_device_map.py b/tests/test_issue1443_device_map.pynew file mode 100644index 00000000..4c249903--- /dev/null+++ b/tests/test_issue1443_device_map.py@@ -0,0 +1,304 @@+"""Regression tests for #1443: `--device` is echoed but never used by+`soup infer`, `soup chat` and `soup diff` — every `_load_model` loads with+`device_map="auto"` and the hard-coded `torch_dtype=torch.float16`+regardless of the flag. `device_map="auto"` lets accelerate place the model+on any visible accelerator, which is exactly wrong when the user asked for+the CPU on purpose (to leave VRAM free for a training job, or because the+model does not fit on the GPU).+"""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+import torch+from typer.testing import CliRunner++from tests.conftest import strip_ansi++runner = CliRunner()+++def _mock_env():+ tokenizer = MagicMock()+ tokenizer.pad_token = "<pad>"+ model = MagicMock()+ return tokenizer, model+++def _assert_cpu_placement(name: str, load, model) -> None:+ kwargs = load.call_args.kwargs+ device_map = kwargs.get("device_map")+ dtype = kwargs.get("torch_dtype")++ assert device_map != "auto", (+ f"{name}._load_model(device='cpu') still passes device_map='auto' "+ f"to from_pretrained; with a visible GPU, accelerate would still "+ f"place the model there although the user asked for the CPU"+ )+ assert device_map == {"": "cpu"} or model.to.called, (+ f"{name}._load_model(device='cpu') never resolves the model onto "+ f"the CPU (device_map={device_map!r}, model.to() called="+ f"{model.to.called})"+ )+ assert dtype == torch.float32, (+ f"{name}._load_model(device='cpu') must load in float32 on the CPU "+ f"(got {dtype})"+ )+++def test_infer_load_model_cpu_uses_cpu_device_map_and_dtype():+ from soup_cli.commands.infer import _load_model++ tokenizer, model = _mock_env()+ with patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=model+ ) as load, patch(+ "soup_cli.utils.trust_remote.resolve_trust_remote_code", return_value=False+ ), patch(+ "soup_cli.utils.trust_remote.model_requires_trust_remote_code",+ return_value=False,+ ):+ _load_model("some-org/some-model", None, "cpu")+ _assert_cpu_placement("infer", load, model)+++def test_chat_load_model_cpu_uses_cpu_device_map_and_dtype():+ from soup_cli.commands.chat import _load_model++ tokenizer, model = _mock_env()+ with patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=model+ ) as load:+ _load_model("some-org/some-model", None, False, "cpu")+ _assert_cpu_placement("chat", load, model)+++def test_diff_load_model_cpu_uses_cpu_device_map_and_dtype():+ from soup_cli.commands.diff import _load_model++ tokenizer, model = _mock_env()+ with patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=model+ ) as load, patch(+ "soup_cli.utils.trust_remote.resolve_trust_remote_code", return_value=False+ ), patch(+ "soup_cli.utils.trust_remote.model_requires_trust_remote_code",+ return_value=False,+ ):+ _load_model("some-org/some-model", None, "cpu")+ _assert_cpu_placement("diff", load, model)+++def _write_adapter_config(model_dir: Path, base_model: str = "some-org/base-model") -> None:+ model_dir.mkdir(parents=True, exist_ok=True)+ (model_dir / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": base_model, "r": 8})+ )+++def test_infer_load_model_cpu_uses_cpu_device_map_and_dtype_on_adapter_branch(+ tmp_path: Path,+):+ """The adapter branch loads the *base* model with the same device_map/dtype (#1443).++ Both `_load_model` branches share one `device_map, torch_dtype` pair+ computed up front, but the existing cpu test above only ever exercises+ the full-model (else) branch, since its `model_path` is not a real local+ directory. Reverting only the adapter branch's `from_pretrained` call+ back to a hard-coded `device_map="auto"` must fail here even though the+ full-model test still passes.+ """+ from soup_cli.commands.infer import _load_model++ _write_adapter_config(tmp_path)+ tokenizer, model = _mock_env()+ base_obj = MagicMock()+ with patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=base_obj+ ) as load, patch(+ "peft.PeftModel.from_pretrained", return_value=model+ ), patch(+ "soup_cli.utils.trust_remote.resolve_trust_remote_code", return_value=False+ ), patch(+ "soup_cli.utils.trust_remote.model_requires_trust_remote_code",+ return_value=False,+ ):+ _load_model(str(tmp_path), None, "cpu")+ _assert_cpu_placement("infer (adapter branch)", load, base_obj)+++def test_chat_load_model_cpu_uses_cpu_device_map_and_dtype_on_adapter_branch(+ tmp_path: Path,+):+ from soup_cli.commands.chat import _load_model++ _write_adapter_config(tmp_path)+ tokenizer, model = _mock_env()+ base_obj = MagicMock()+ with patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=base_obj+ ) as load, patch(+ "peft.PeftModel.from_pretrained", return_value=model+ ):+ _load_model(str(tmp_path), "some-org/base-model", True, "cpu")+ _assert_cpu_placement("chat (adapter branch)", load, base_obj)+++def test_diff_load_model_cpu_uses_cpu_device_map_and_dtype_on_adapter_branch(+ tmp_path: Path,+):+ from soup_cli.commands.diff import _load_model++ _write_adapter_config(tmp_path)+ tokenizer, model = _mock_env()+ base_obj = MagicMock()+ with patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=base_obj+ ) as load, patch(+ "peft.PeftModel.from_pretrained", return_value=model+ ), patch(+ "soup_cli.utils.trust_remote.resolve_trust_remote_code", return_value=False+ ), patch(+ "soup_cli.utils.trust_remote.model_requires_trust_remote_code",+ return_value=False,+ ):+ _load_model(str(tmp_path), None, "cpu")+ _assert_cpu_placement("diff (adapter branch)", load, base_obj)+++def test_chat_cli_without_device_flag_uses_the_auto_detected_device(tmp_path: Path):+ """Without `--device`, the auto-detected device must be what reaches the+ load, so the panel and the actual placement agree (#1443 acceptance+ criterion 3), and the CLI assertion goes through the ANSI-strip helper+ (criterion 4).+ """+ from soup_cli.cli import app++ model_dir = tmp_path / "model"+ model_dir.mkdir()+ (model_dir / "config.json").write_text("{}")++ tokenizer, model = _mock_env()+ with patch(+ "soup_cli.utils.gpu.detect_device", return_value=("cpu", "CPU (no GPU detected)")+ ), patch(+ "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer+ ), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=model+ ) as load:+ result = runner.invoke(app, ["chat", "--model", str(model_dir)], input="")++ output = strip_ansi(result.output)+ assert "Device: cpu" in output, output+ _assert_cpu_placement("chat (CLI auto-detect)", load, model)+++ ("device", "expected"),+ [+ ("cpu", ({"": "cpu"}, torch.float32)),+ ("CPU", ({"": "cpu"}, torch.float32)),+ ("mlx", ({"": "cpu"}, torch.float32)),+ ("mps", ({"": "mps"}, torch.float16)),+ ("cuda:1", ({"": "cuda:1"}, torch.float16)),+ # Plain `cuda` deliberately stays "auto" (every visible GPU); pinned+ # here so the choice cannot drift silently.+ ("cuda", ("auto", torch.float16)),+ (None, ("auto", torch.float16)),+ ("", ("auto", torch.float16)),+ ],+)+def test_resolver_table(monkeypatch, device, expected):+ from soup_cli.utils import gpu++ monkeypatch.setattr(gpu, "cuda_supports_bf16", lambda: False)+ assert gpu.resolve_inference_device_map_and_dtype(device) == expected+++def test_resolver_keeps_float16_even_when_cuda_supports_bf16(monkeypatch):+ from soup_cli.utils import gpu++ monkeypatch.setattr(gpu, "cuda_supports_bf16", lambda: True)+ assert gpu.resolve_inference_device_map_and_dtype("cuda") == ("auto", torch.float16)+ assert gpu.resolve_inference_device_map_and_dtype("cuda:0") == (+ {"": "cuda:0"}, torch.float16,+ )+ assert gpu.resolve_inference_device_map_and_dtype("mps") == ({"": "mps"}, torch.float16)+++ "device", ["foo", "gpu", "tpu", "xpu", "auto", "cuda:abc", "cuda:0,1"]+)+def test_resolver_refuses_an_unknown_device(device):+ from soup_cli.utils import gpu++ with pytest.raises(ValueError, match="cpu, cuda"):+ gpu.resolve_inference_device_map_and_dtype(device)+++ ("device", "expected"), [("MPS", {"": "mps"}), ("CUDA:0", {"": "cuda:0"})]+)+def test_pinned_device_map_uses_the_normalised_name(monkeypatch, device, expected):+ from soup_cli.utils import gpu++ monkeypatch.setattr(gpu, "cuda_supports_bf16", lambda: False)+ device_map, dtype = gpu.resolve_inference_device_map_and_dtype(device)+ assert device_map == expected and dtype == torch.float16+ assert torch.device(device_map[""]) # what accelerate will hand to torch+++def _prep(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ model_dir = tmp_path / "merged"+ model_dir.mkdir()+ (model_dir / "config.json").write_text(json.dumps({}))+ (tmp_path / "prompts.jsonl").write_text(json.dumps({"prompt": "hi"}) + "\n")+ return str(model_dir)+++def test_infer_cli_hands_the_resolved_device_to_the_loader(tmp_path, monkeypatch):+ from soup_cli.cli import app++ model_dir = _prep(tmp_path, monkeypatch)+ with patch(+ "soup_cli.commands.infer._load_model",+ side_effect=RuntimeError("stop after the load call"),+ ) as load:+ result = runner.invoke(+ app,+ ["infer", "-m", model_dir, "-i", "prompts.jsonl", "-o", "o.jsonl", "--device", "cpu"],+ )+ assert "Device: cpu" in " ".join(strip_ansi(result.output).split()), result.output+ assert load.call_args.args[2] == "cpu", load.call_args+++def test_diff_cli_hands_the_resolved_device_to_the_loader(tmp_path, monkeypatch):+ from soup_cli.cli import app++ model_dir = _prep(tmp_path, monkeypatch)+ with patch(+ "soup_cli.commands.diff._load_model",+ side_effect=RuntimeError("stop after the load call"),+ ) as load:+ result = runner.invoke(+ app, ["diff", "-a", model_dir, "-b", model_dir, "--prompt", "hi", "--device", "cpu"],+ )+ assert "Device: cpu" in " ".join(strip_ansi(result.output).split()), result.output+ assert load.call_args_list[0].args[2] == "cpu", load.call_args_listdiff --git a/tests/test_issue781_inference_bos.py b/tests/test_issue781_inference_bos.pyindex 097c4910..a10d3383 100644--- a/tests/test_issue781_inference_bos.py+++ b/tests/test_issue781_inference_bos.py@@ -362,7 +362,7 @@ def _via_chat(tok, messages):from soup_cli.commands.chat import _generatemodel = _RecordingModel()- _generate(model, tok, list(messages), max_tokens=1, temperature=0.0, device="cpu")+ _generate(model, tok, list(messages), max_tokens=1, temperature=0.0)return model.sent