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(profile): recognize full fine-tuning and budget model optimizer & gradients (#1423) (#2041)
Nariman Abdikarimb53f99bda4aa
diff --git a/changelog.d/0.76.0/2041.fixed.md b/changelog.d/0.76.0/2041.fixed.mdnew file mode 100644index 00000000..48f6f8ff--- /dev/null+++ b/changelog.d/0.76.0/2041.fixed.md@@ -0,0 +1 @@+- `soup profile` and the MCP `tool_profile` now correctly recognize full fine-tuning runs (`lora.r: 0`, Spectrum, LISA, PRM, and classifiers without LoRA), budgeting the whole model parameter count, optimizer state, and gradients instead of reporting 0 trainable parameters and 0 GB optimizer memory (#1423, #2041 by @Nari-Ab).diff --git a/src/soup_cli/commands/profile.py b/src/soup_cli/commands/profile.pyindex 9777dd5f..ab8bb08c 100644--- a/src/soup_cli/commands/profile.py+++ b/src/soup_cli/commands/profile.py@@ -62,6 +62,11 @@ def profile(# Resolve GPU memorygpu_memory_gb, gpu_memory_source = _resolve_gpu_memory(gpu)+ # Resolve PEFT mode (#1423)+ from soup_cli.utils.hardware_fit import resolve_peft_mode++ peft = resolve_peft_mode(cfg)+# Compute profileresult = estimate_total(model_name=cfg.base,@@ -73,6 +78,7 @@ def profile(seq_len=cfg.data.max_length,optimizer=cfg.training.optimizer,gradient_checkpointing=cfg.training.gradient_checkpointing,+ peft=peft,)# Speed estimates@@ -141,10 +147,16 @@ def _resolve_gpu_memory(gpu: str | None) -> tuple[float, str]:def _render_profile(result: dict, cfg, gpu_memory_gb: float, gpu_memory_source: str) -> None:"""Render Rich profile output."""# Model info+ if result.get("peft") == "full":+ trainable_str = f"(trainable: {result['trainable_params']:,.0f}, full fine-tuning)"+ else:+ trainable_str = (+ f"(trainable: {result['trainable_params']:,.0f} with LoRA r={cfg.training.lora.r})"+ )+model_info = (f"Model: [bold]{cfg.base}[/]\n"- f"Params: [bold]{result['model_params_b']:.1f}B[/] "- f"(trainable: {result['trainable_params']:,.0f} with LoRA r={cfg.training.lora.r})\n"+ f"Params: [bold]{result['model_params_b']:.1f}B[/] {trainable_str}\n"f"Quantization: [bold]{result['quantization']}[/]")if result["gradient_checkpointing"]:@@ -155,7 +167,10 @@ def _render_profile(result: dict, cfg, gpu_memory_gb: float, gpu_memory_source:mem_table.add_column("Component", style="bold")mem_table.add_column("Memory", justify="right")mem_table.add_row("Model", f"~{result['model_memory_gb']:.1f} GB")- mem_table.add_row("LoRA", f"~{result['lora_memory_gb']:.1f} GB")+ if result.get("peft") == "full":+ mem_table.add_row("Gradients", f"~{result['gradients_memory_gb']:.1f} GB")+ else:+ mem_table.add_row("LoRA", f"~{result['lora_memory_gb']:.1f} GB")mem_table.add_row("Optimizer", f"~{result['optimizer_memory_gb']:.1f} GB")mem_table.add_row(f"Activations (bs={result['batch_size']}, seq={result['seq_len']})",diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex e157c64c..ebb94d8e 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -340,9 +340,8 @@ def _build_hardware_fit_input(cfg):``"auto"``, unknown model size, unsupported quant, out-of-range dims), inwhich case the caller skips the gate rather than guess."""- from soup_cli.trainer.sft import is_full_finetunefrom soup_cli.utils.gpu import model_size_from_name- from soup_cli.utils.hardware_fit import HardwareFitInput+ from soup_cli.utils.hardware_fit import HardwareFitInput, resolve_peft_modetcfg = cfg.trainingbs = getattr(tcfg, "batch_size", None)@@ -357,41 +356,7 @@ def _build_hardware_fit_input(cfg):quant = _HW_FIT_QUANT.get(str(getattr(tcfg, "quantization", "none") or "none"))if quant is None:return None- task = getattr(cfg, "task", None)- if quant == "4bit":- peft = "qlora"- elif task == "prm" or (- task in CLASSIFICATION_TASKS- and not (tcfg.classifier_lora and tcfg.lora.r > 0)- ) or (task == "asr" and not (tcfg.asr_lora and tcfg.lora.r > 0)):- # #795: these trainers decide full fine-tuning themselves -- PRM always,- # the classifier family and ASR unless their own LoRA opt-in is on- # (classifier.py:262, asr.py::_should_use_lora). Budgeting them as LoRA- # under-predicts, the unsafe direction.- peft = "full"- elif is_full_finetune(tcfg):- # #471 — was an independent, hand-maintained check- # (unfrozen_parameters / freeze_layers / freeze_ratio) that had- # drifted from sft.py's real full-FT decision in BOTH directions:- # it missed lisa_enabled/lora.r==0 (under-predicting VRAM for those- # runs) and treated bare freeze_layers/freeze_ratio as sufficient on- # its own even with lora.r>0 still on (over-predicting — and able to- # falsely refuse a launch that would fit, since freeze_layers/- # freeze_ratio only reduce what's trainable WITHIN LoRA or full-FT,- # they don't select the mode). Now shares is_full_finetune with- # sft.py's SFTTrainerWrapper._resolve_load_dtype so the two cannot- # disagree again.- #- # #377 — lisa_train_embeddings=false freezes the always-on group and- # lowers real VRAM, but LISA stays "full" here on purpose: the analytical- # predictor has no measured constant for the frozen-embeddings trainable- # set, and over-predicting is the safe failure (under-predicting is a- # silent WDDM spill on Windows). A frozen-embeddings run that would fit- # can therefore still be refused by pre-flight; --allow-oom-attempt is- # the documented bypass, and crediting the saving is a hardware follow-up.- peft = "full"- else:- peft = "lora"+ peft = resolve_peft_mode(cfg, quant=quant)optimizer = str(getattr(tcfg, "optimizer", "adamw_torch") or "adamw_torch")if optimizer not in _HW_FIT_OPTIMIZERS:optimizer = "adamw_torch"diff --git a/src/soup_cli/mcp_server/registry.py b/src/soup_cli/mcp_server/registry.pyindex 60f0018e..01de01f8 100644--- a/src/soup_cli/mcp_server/registry.py+++ b/src/soup_cli/mcp_server/registry.py@@ -499,6 +499,10 @@ def tool_profile(args: dict) -> dict:batch_size = 4 if batch_size == "auto" else int(batch_size)gpu_memory_gb, gpu_memory_source = _resolve_gpu_memory_mcp(gpu)+ from soup_cli.utils.hardware_fit import resolve_peft_mode++ peft = resolve_peft_mode(cfg)+result = estimate_total(model_name=cfg.base,model_params_b=model_params_b,@@ -509,6 +513,7 @@ def tool_profile(args: dict) -> dict:seq_len=cfg.data.max_length,optimizer=cfg.training.optimizer,gradient_checkpointing=cfg.training.gradient_checkpointing,+ peft=peft,)tokens_per_sec = estimate_speed(model_params_b, cfg.training.quantization, batch_size)result["tokens_per_sec"] = round(tokens_per_sec, 1)diff --git a/src/soup_cli/utils/hardware_fit.py b/src/soup_cli/utils/hardware_fit.pyindex 50e93df7..c8d47ad2 100644--- a/src/soup_cli/utils/hardware_fit.py+++ b/src/soup_cli/utils/hardware_fit.py@@ -19,12 +19,14 @@ Public surface:- ``HardwareFitReport`` frozen dataclass.- ``estimate_peak_vram_gb(inp)`` -> ``VRAMBreakdown``.- ``decide_hardware_fit(inp, *, available_vram_gb)`` -> ``HardwareFitReport``.+- ``resolve_peft_mode(cfg, quant=None)`` -> ``str``."""from __future__ import annotationsimport mathfrom dataclasses import dataclass+from typing import AnyVRAM_SAFETY_MARGIN = 0.10 # 10% headroom@@ -218,6 +220,40 @@ _OPTIM_BYTES_PER_PARAM = {}+def resolve_peft_mode(cfg: Any, quant: str | None = None) -> str:+ """Resolve the effective PEFT mode ('full', 'qlora', or 'lora') for a config.++ Shared between train hardware-fit preflight, `soup profile`, and MCP `tool_profile` (#1423).+ """+ from soup_cli.trainer.classifier import CLASSIFICATION_TASKS+ from soup_cli.trainer.sft import is_full_finetune++ tcfg = getattr(cfg, "training", None)+ if quant is None and tcfg is not None:+ quant = str(getattr(tcfg, "quantization", "none") or "none")++ task = getattr(cfg, "task", None)+ if quant == "4bit":+ return "qlora"+ if task == "prm" or (+ task in CLASSIFICATION_TASKS+ and not (+ getattr(tcfg, "classifier_lora", False)+ and getattr(getattr(tcfg, "lora", None), "r", 0) > 0+ )+ ) or (+ task == "asr"+ and not (+ getattr(tcfg, "asr_lora", False)+ and getattr(getattr(tcfg, "lora", None), "r", 0) > 0+ )+ ):+ return "full"+ if tcfg is not None and is_full_finetune(tcfg):+ return "full"+ return "lora"++def _trainable_param_fraction(peft: str) -> float:"""LoRA / DoRA / QLoRA train ~1% of parameters. Full = 100%."""if peft == "full":diff --git a/src/soup_cli/utils/profiler.py b/src/soup_cli/utils/profiler.pyindex 453878cd..a2306e6c 100644--- a/src/soup_cli/utils/profiler.py+++ b/src/soup_cli/utils/profiler.py@@ -220,6 +220,7 @@ def estimate_total(seq_len: int,optimizer: str,gradient_checkpointing: bool,+ peft: str = "lora",) -> dict:"""Compute full memory profile.@@ -228,10 +229,19 @@ def estimate_total(arch = get_model_arch(model_name, model_params_b)model_mem = estimate_model_memory(model_params_b, quantization)- lora_mem = estimate_lora_memory(model_params_b, lora_r, lora_alpha)- trainable = estimate_trainable_params(- model_params_b, lora_r, arch["hidden_size"]- )+ if peft == "full":+ # #1423: full fine-tuning trains the whole model+ trainable = int(model_params_b * 1e9)+ lora_mem = 0.0+ # Gradients are 2 bytes/param (FP16/BF16)+ grad_mem = trainable * 2 / (1024**3)+ else:+ trainable = estimate_trainable_params(+ model_params_b, lora_r, arch["hidden_size"]+ )+ lora_mem = estimate_lora_memory(model_params_b, lora_r, lora_alpha)+ grad_mem = 0.0+opt_mem = estimate_optimizer_memory(trainable, optimizer)act_mem = estimate_activation_memory(batch_size, seq_len, arch["hidden_size"], arch["num_layers"],@@ -239,15 +249,17 @@ def estimate_total()overhead = 1.5 # CUDA context + fragmentation- total = model_mem + lora_mem + opt_mem + act_mem + overhead+ total = model_mem + lora_mem + opt_mem + grad_mem + act_mem + overheadreturn {"model_name": model_name,"model_params_b": model_params_b,"trainable_params": trainable,"quantization": quantization,+ "peft": peft,"model_memory_gb": round(model_mem, 2),"lora_memory_gb": round(lora_mem, 2),+ "gradients_memory_gb": round(grad_mem, 2),"optimizer_memory_gb": round(opt_mem, 2),"activation_memory_gb": round(act_mem, 2),"overhead_gb": overhead,diff --git a/tests/test_profile_full_finetune.py b/tests/test_profile_full_finetune.pynew file mode 100644index 00000000..c7f8ff08--- /dev/null+++ b/tests/test_profile_full_finetune.py@@ -0,0 +1,234 @@+"""Regression tests for Issue #1423:+Unified full fine-tuning PEFT classification & profiler budgeting.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.mcp_server.registry import tool_profile+from tests.conftest import strip_ansi+++def _plain(text: str) -> str:+ """ANSI-stripped, whitespace-collapsed output, safe to substring-match."""+ return " ".join(strip_ansi(text).split())+++BASE_MODEL = "meta-llama/Llama-3.1-8B"++CONFIG_QLORA = """+base: meta-llama/Llama-3.1-8B+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: 4bit+ batch_size: 1+ gradient_checkpointing: true+ lora:+ r: 16+ alpha: 16+"""++CONFIG_LORA_CONTROL = """+base: meta-llama/Llama-3.1-8B+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: none+ batch_size: 1+ gradient_checkpointing: true+ lora:+ r: 16+ alpha: 16+"""++CONFIG_LORA_ZERO = """+base: meta-llama/Llama-3.1-8B+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: none+ batch_size: 1+ gradient_checkpointing: true+ lora:+ r: 0+ alpha: 16+"""++CONFIG_SPECTRUM = """+base: meta-llama/Llama-3.1-8B+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: none+ batch_size: 1+ gradient_checkpointing: true+ unfrozen_parameters:+ - "model.layers.0.*"+"""++CONFIG_LISA = """+base: meta-llama/Llama-3.1-8B+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: none+ batch_size: 1+ gradient_checkpointing: true+ lisa_enabled: true+"""++CONFIG_PRM = """+base: meta-llama/Llama-3.1-8B+task: prm+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: none+ batch_size: 1+ gradient_checkpointing: true+"""++CONFIG_CLASSIFIER = """+base: meta-llama/Llama-3.1-8B+task: classifier+data:+ train: dummy.jsonl+ max_length: 512+training:+ quantization: none+ batch_size: 1+ gradient_checkpointing: true+ num_labels: 2+"""++ALL_CONFIGS = [+ ("lora_control", CONFIG_LORA_CONTROL, "lora", False),+ ("lora_zero", CONFIG_LORA_ZERO, "full", True),+ ("spectrum", CONFIG_SPECTRUM, "full", True),+ ("lisa", CONFIG_LISA, "full", True),+ ("prm", CONFIG_PRM, "full", True),+ ("classifier", CONFIG_CLASSIFIER, "full", True),+]+++class TestProfileFullFinetune:+ @pytest.mark.parametrize("name,yaml_text,expected_peft,is_full_ft", ALL_CONFIGS)+ def test_profile_json_trainable_params_and_optimizer(+ self, tmp_path: Path, name: str, yaml_text: str, expected_peft: str, is_full_ft: bool+ ) -> None:+ cfg_file = tmp_path / f"{name}.yaml"+ cfg_file.write_text(yaml_text, encoding="utf-8")++ runner = CliRunner()+ result = runner.invoke(app, ["profile", "--config", str(cfg_file), "--json"])+ assert result.exit_code == 0, result.output+ data = json.loads(result.output)++ assert data.get("peft") == expected_peft++ if is_full_ft:+ assert data["trainable_params"] == 8_000_000_000+ assert data["optimizer_memory_gb"] > 0+ assert data["gradients_memory_gb"] == 14.9+ assert data["total_memory_gb"] == 62.28+ else:+ assert data["trainable_params"] == 29_360_128+ assert data["total_memory_gb"] == 17.74+ assert data["gradients_memory_gb"] == 0.0++ @pytest.mark.parametrize("name,yaml_text,expected_peft,is_full_ft", ALL_CONFIGS)+ def test_cli_and_preflight_peft_classification_agree(+ self, tmp_path: Path, name: str, yaml_text: str, expected_peft: str, is_full_ft: bool+ ) -> None:+ from soup_cli.commands.train import _build_hardware_fit_input+ from soup_cli.config.loader import load_config+ from soup_cli.utils.hardware_fit import resolve_peft_mode++ cfg_file = tmp_path / f"{name}.yaml"+ cfg_file.write_text(yaml_text, encoding="utf-8")+ cfg = load_config(str(cfg_file))++ # Check shared resolve_peft_mode+ resolved_peft = resolve_peft_mode(cfg)+ assert resolved_peft == expected_peft++ # Check train preflight builds matching peft+ inp = _build_hardware_fit_input(cfg)+ assert inp is not None+ assert inp.peft == expected_peft++ @pytest.mark.parametrize("name,yaml_text,expected_peft,is_full_ft", ALL_CONFIGS)+ def test_mcp_tool_profile_parity_with_cli(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ name: str,+ yaml_text: str,+ expected_peft: str,+ is_full_ft: bool,+ ) -> None:+ monkeypatch.chdir(tmp_path)+ cfg_file = tmp_path / "soup.yaml"+ cfg_file.write_text(yaml_text, encoding="utf-8")++ # Run CLI --json+ runner = CliRunner()+ cli_res = runner.invoke(app, ["profile", "--config", "soup.yaml", "--json"])+ assert cli_res.exit_code == 0, cli_res.output+ cli_data = json.loads(cli_res.output)++ # Run MCP tool_profile+ mcp_data = tool_profile({"config": "soup.yaml"})++ assert mcp_data["trainable_params"] == cli_data["trainable_params"]+ assert mcp_data["total_memory_gb"] == cli_data["total_memory_gb"]+ assert mcp_data["optimizer_memory_gb"] == cli_data["optimizer_memory_gb"]+ assert mcp_data.get("peft") == cli_data.get("peft")++ def test_cli_rendering_full_finetune_labels(self, tmp_path: Path) -> None:+ cfg_file = tmp_path / "lora_zero.yaml"+ cfg_file.write_text(CONFIG_LORA_ZERO, encoding="utf-8")++ runner = CliRunner()+ result = runner.invoke(app, ["profile", "--config", str(cfg_file), "--gpu", "rtx4090"])+ assert result.exit_code == 0+ plain = _plain(result.output)+ assert "full fine-tuning" in plain+ assert "Gradients ~14.9 GB" in plain+ assert "Does NOT fit in 24 GB VRAM" in plain+ assert "Fits in 24 GB VRAM" not in plain++ def test_cli_rendering_lora_control_unchanged(self, tmp_path: Path) -> None:+ cfg_file = tmp_path / "lora_control.yaml"+ cfg_file.write_text(CONFIG_LORA_CONTROL, encoding="utf-8")++ runner = CliRunner()+ result = runner.invoke(app, ["profile", "--config", str(cfg_file), "--gpu", "rtx4090"])+ assert result.exit_code == 0+ plain = _plain(result.output)+ assert "with LoRA r=16" in plain+ assert "Fits in 24 GB VRAM" in plain+ assert "Gradients" not in plain++ def test_profile_and_mcp_label_a_4bit_lora_run_qlora(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.chdir(tmp_path)+ (tmp_path / "soup.yaml").write_text(CONFIG_QLORA, encoding="utf-8")+ result = CliRunner().invoke(app, ["profile", "--config", "soup.yaml", "--json"])+ assert result.exit_code == 0, result.output+ assert json.loads(result.output)["peft"] == "qlora"+ assert tool_profile({"config": "soup.yaml"})["peft"] == "qlora"