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(serve): honour --device in the transformers loader (#1479)
Younes Beriane0f7ab958525d
diff --git a/changelog.d/0.75.1/1479.fixed.md b/changelog.d/0.75.1/1479.fixed.mdnew file mode 100644index 00000000..49de68a7--- /dev/null+++ b/changelog.d/0.75.1/1479.fixed.md@@ -0,0 +1,12 @@+- `soup serve --device` now reaches the transformers loader. `_load_model` ignored+ its `device` argument and always passed `device_map="auto"`, so `--device cpu`+ still placed the model on a visible GPU. The base model, the merged model and the+ speculative draft model now use the same placement rule as `soup infer` / `chat` /+ `diff`: `cuda:N` is accepted and pinned to that GPU (it was accepted and ignored+ before), `mps` is pinned, `mlx` runs on the CPU, and `cuda` keeps+ `device_map="auto"`. Unknown values are refused with exit code 2 naming+ `cpu, cuda, cuda:<index> or mps`; `--device` is case-insensitive. An explicit+ `--kv-cache-type bf16` / `f16` still sets the load dtype on every device.+ Behaviour change: on a CPU-only host the default load is now float32 pinned to the+ CPU, which doubles its RAM (a 7B model needs about 28 GB instead of 14 GB)+ (#1478 by @drakeo338 in #1479).diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.pyindex 13dd52fc..d2686c92 100644--- a/src/soup_cli/commands/serve.py+++ b/src/soup_cli/commands/serve.py@@ -26,6 +26,7 @@ logger = logging.getLogger(__name__)console = Console()+def _validate_adapter_name(name: str) -> bool:"""Validate adapter name: alphanumeric + hyphens only."""if not name:@@ -99,7 +100,13 @@ def serve(device: Optional[str] = typer.Option(None,"--device",- help="Device: cuda, mps, cpu. Auto-detected if not set.",+ help=(+ "Device: cuda, cuda:<index>, mps or cpu. Auto-detected if not set. "+ "With the transformers backend, cpu loads on the CPU in float32 "+ "(unless --kv-cache-type bf16/f16 picks the dtype); cuda:<index> "+ "and mps are pinned to that device; cuda uses device_map=auto, "+ "all in float16."+ ),),max_tokens_default: int = typer.Option(512,@@ -454,6 +461,18 @@ def serve()raise typer.Exit(code=2)+ if device:+ from rich.markup import escape as _rich_escape++ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtype++ device = device.strip().lower()+ try:+ resolve_inference_device_map_and_dtype(device)+ except ValueError as exc:+ console.print(f"[red]--device:[/] {_rich_escape(str(exc))}")+ raise typer.Exit(code=2) from exc+# v0.53.10 #152 — pre-fetch base from a non-HF hub before serve starts.if hub and hub != "hf":from soup_cli.utils.hubs import apply_hub_to_cli_model@@ -1343,16 +1362,23 @@ def _load_model("""Load model and tokenizer.``kv_cache_dtype`` (v0.71.14 #140) selects the model compute dtype so the- transformers DynamicCache runs in it: ``"bfloat16"`` → bf16, else the- default float16. The bf16/f16 ``kv_cache_type`` values map here; q8_0 uses+ transformers DynamicCache runs in it: ``"bfloat16"`` → bf16, ``"float16"``+ → fp16, else the default (float16; float32 on ``device="cpu"``). The+ bf16/f16 ``kv_cache_type`` values map here; q8_0 usesa quantized cache via generate kwargs and leaves the model dtype unchanged."""import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer- load_dtype = (- torch.bfloat16 if kv_cache_dtype == "bfloat16" else torch.float16- )+ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtype++ device_map, default_dtype = resolve_inference_device_map_and_dtype(device)+ if kv_cache_dtype == "bfloat16":+ load_dtype = torch.bfloat16+ elif kv_cache_dtype == "float16":+ load_dtype = torch.float16+ else:+ load_dtype = default_dtypeconsole.print("[dim]Loading tokenizer...[/]")tokenizer = AutoTokenizer.from_pretrained(@@ -1368,7 +1394,7 @@ def _load_model(base = AutoModelForCausalLM.from_pretrained(base_model,trust_remote_code=trust_remote_code,- device_map="auto",+ device_map=device_map,torch_dtype=load_dtype,)console.print(f"[dim]Loading LoRA adapter: {model_path}...[/]")@@ -1378,7 +1404,7 @@ def _load_model(model_obj = AutoModelForCausalLM.from_pretrained(model_path,trust_remote_code=trust_remote_code,- device_map="auto",+ device_map=device_map,torch_dtype=load_dtype,)@@ -1452,10 +1478,11 @@ def _load_draft_model(speculative_model: str, device: str):import osimport re- import torchfrom rich.markup import escapefrom transformers import AutoModelForCausalLM+ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtype+# SSRF protection: block URL-based model pathsif re.match(r'^https?://', speculative_model):console.print(@@ -1473,11 +1500,12 @@ def _load_draft_model(speculative_model: str, device: str):assert_safe_top_level_weights(speculative_model)+ device_map, dtype = resolve_inference_device_map_and_dtype(device)console.print(f"[dim]Loading draft model: {escape(speculative_model)}...[/]")draft = AutoModelForCausalLM.from_pretrained(speculative_model,- device_map="auto" if device != "cpu" else "cpu",- torch_dtype=torch.float16 if device != "cpu" else torch.float32,+ device_map=device_map,+ torch_dtype=dtype,)draft.eval()return draftdiff --git a/tests/test_issue1478_serve_device_map.py b/tests/test_issue1478_serve_device_map.pynew file mode 100644index 00000000..03273213--- /dev/null+++ b/tests/test_issue1478_serve_device_map.py@@ -0,0 +1,163 @@+"""Regression tests for #1478: ``soup serve --device`` reaches the transformers loader.++``serve._load_model`` used to load the base model and the merged model with a hard-coded+``device_map="auto"``, so ``--device cpu`` could still place the model on a visible GPU.+It now places the model with the same rule as ``soup infer`` / ``chat`` / ``diff``+(``utils.gpu.resolve_inference_device_map_and_dtype``).+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest+import torch+from typer.testing import CliRunner++from tests.conftest import strip_ansi++runner = CliRunner()+++def _collapse(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def _load(device, *, is_adapter=False, kv_cache_dtype=None):+ """Run the real ``_load_model`` with transformers/peft mocked; return the loader mock."""+ from soup_cli.commands.serve import _load_model++ tokenizer = MagicMock()+ tokenizer.pad_token = "<pad>"+ with patch("transformers.AutoTokenizer.from_pretrained", return_value=tokenizer), patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=MagicMock()+ ) as load, patch("peft.PeftModel.from_pretrained", return_value=MagicMock()):+ _load_model(+ model_path="some-org/some-model",+ base_model="some-org/base-model" if is_adapter else None,+ is_adapter=is_adapter,+ device=device,+ kv_cache_dtype=kv_cache_dtype,+ )+ return load++[email protected]("is_adapter", [False, True], ids=["plain", "base+adapter"])+ ("device", "device_map", "dtype"),+ [+ ("cpu", {"": "cpu"}, torch.float32),+ ("mlx", {"": "cpu"}, torch.float32),+ ("mps", {"": "mps"}, torch.float16),+ ("cuda:1", {"": "cuda:1"}, torch.float16),+ ("cuda", "auto", torch.float16),+ ],+)+def test_loader_places_the_model_by_the_shared_rule(is_adapter, device, device_map, dtype):+ load = _load(device, is_adapter=is_adapter)+ assert load.call_count == 1+ kwargs = load.call_args.kwargs+ assert kwargs["device_map"] == device_map, kwargs+ assert kwargs["torch_dtype"] == dtype, kwargs+++def test_no_device_behaves_as_the_helper_default():+ from soup_cli.utils.gpu import resolve_inference_device_map_and_dtype++ device_map, dtype = resolve_inference_device_map_and_dtype(None)+ kwargs = _load(None).call_args.kwargs+ assert (kwargs["device_map"], kwargs["torch_dtype"]) == (device_map, dtype)+++ ("device", "kv_cache_dtype", "dtype"),+ [+ ("cpu", "float16", torch.float16),+ ("cpu", "bfloat16", torch.bfloat16),+ ("cuda", "float16", torch.float16),+ ("cuda", "bfloat16", torch.bfloat16),+ ],+)+def test_explicit_kv_cache_type_still_sets_the_load_dtype(device, kv_cache_dtype, dtype):+ assert _load(device, kv_cache_dtype=kv_cache_dtype).call_args.kwargs["torch_dtype"] == dtype+++def test_load_model_refuses_an_unknown_device_even_when_called_directly():+ with pytest.raises(ValueError, match="cpu, cuda, cuda:<index> or mps"):+ _load("tpu")+++def _serve_to_the_loader(tmp_path, *args):+ """Invoke the real CLI and stop at ``_load_model``; return (result, loader mock)."""+ pytest.importorskip("fastapi")+ pytest.importorskip("uvicorn")+ from soup_cli.cli import app++ with patch(+ "soup_cli.commands.serve._load_model", side_effect=RuntimeError("stop after the load call")+ ) as load:+ result = runner.invoke(app, ["serve", "--model", str(tmp_path), *args])+ return result, load+++ ("given", "passed"),+ [+ ("cpu", "cpu"),+ (" CPU ", "cpu"),+ ("cuda", "cuda"),+ ("CUDA", "cuda"),+ ("cuda:1", "cuda:1"),+ ("mps", "mps"),+ ],+)+def test_cli_hands_the_normalised_device_to_the_loader(tmp_path, given, passed):+ _, load = _serve_to_the_loader(tmp_path, "--device", given)+ assert load.call_args.kwargs["device"] == passed, load.call_args++[email protected]("bad", ["tpu", "gpu", "auto", "cuda:abc", "cuda:0,1", "cpu0"])+def test_cli_refuses_an_unknown_device_naming_the_accepted_values(tmp_path, bad):+ result, load = _serve_to_the_loader(tmp_path, "--device", bad)+ assert result.exit_code == 2, (result.output, repr(result.exception))+ assert not load.called+ text = _collapse(result.output)+ assert "cpu, cuda, cuda:<index> or mps" in text, text+ assert repr(bad) in text, text+++def test_cli_refuses_a_markup_like_device_instead_of_crashing(tmp_path):+ result, _ = _serve_to_the_loader(tmp_path, "--device", "[/bold]")+ assert result.exit_code == 2, (result.output, repr(result.exception))+ assert "[/bold]" in _collapse(result.output)+++def test_vllm_backend_still_reaches_its_server_without_a_device_argument(tmp_path):+ pytest.importorskip("fastapi")+ pytest.importorskip("uvicorn")+ from soup_cli.cli import app++ with patch("soup_cli.utils.vllm.is_vllm_available", return_value=True), patch(+ "soup_cli.commands.serve._serve_vllm", return_value=MagicMock()+ ) as serve_vllm, patch("uvicorn.run"):+ result = runner.invoke(+ app, ["serve", "--model", str(tmp_path), "--backend", "vllm", "--device", "cuda"]+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert "device" not in serve_vllm.call_args.kwargs++[email protected]("device", ["cpu", "cuda", "cuda:1", "mps"])+def test_the_draft_model_is_placed_like_the_main_model(device):+ """One flag, one placement: the speculative draft must land where the main model does."""+ from soup_cli.commands.serve import _load_draft_model++ main = _load(device).call_args.kwargs+ with patch(+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=MagicMock()+ ) as load:+ _load_draft_model("some-org/draft", device)+ draft = load.call_args.kwargs+ assert (draft["device_map"], draft["torch_dtype"]) == (+ main["device_map"], main["torch_dtype"],+ )diff --git a/tests/test_speculative_decoding.py b/tests/test_speculative_decoding.pyindex 17d3c7bb..8e3e9363 100644--- a/tests/test_speculative_decoding.py+++ b/tests/test_speculative_decoding.py@@ -75,7 +75,7 @@ class TestDraftModelLoading:_load_draft_model("small-model", "cpu")call_kwargs = mock_load.call_args[1]- assert call_kwargs["device_map"] == "cpu"+ assert call_kwargs["device_map"] == {"": "cpu"}def test_load_draft_model_blocks_urls(self):"""_load_draft_model should reject URL-based model paths (SSRF)."""