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(gpu): parse Hub model sizes via regex and support MoE to prevent VRAM under-prediction (#1198) (#1285)
Areen Agrawal3b4fce53a3df
diff --git a/changelog.d/0.75.1/1285.fixed.md b/changelog.d/0.75.1/1285.fixed.mdnew file mode 100644index 00000000..c5311389--- /dev/null+++ b/changelog.d/0.75.1/1285.fixed.md@@ -0,0 +1 @@+- **Hardware-fit gate correctly infers Hub model sizes using boundary-safe regex and MoE parsing (#1198 by @Areen-09 in #1285).** `utils/gpu.py:model_size_from_name` previously relied on a static scan of hardcoded substring markers and fell back to 7.0B, causing VRAM under-prediction up to ~58x–96x on large models (such as 72B, 32B, 14B, 405B, 675B) and substring collision bugs (e.g., `11b` matching `1b`, `17b`/`27b` matching `7b`, `0.8b` matching `8b`, and `8x7b` matching `7b`). Model sizes are now dynamically parsed with boundary-safe regex, active-parameter tokens (`-aNNb`) are filtered to retain total parameters, and MoE architectures (`8x7B`, `8x22B`, generic `NxMb`, and Llama 4 `17B-16E`) are supported. The same parameter estimate also drives `batch_size: auto`, `soup cost`, and `soup profile`, while Hub IDs carrying no size marker (`DeepSeek-V3`, `Kimi-K2`, `GLM-5`, `MiniMax-M2`) still fall back to 7.0B, an under-estimate for those models.diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 24dfd188..8e4f08de 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -1118,6 +1118,11 @@ soup env checkGiven (params, seq_len, batch_size, optimizer, quant, peft, gradient_checkpointing), the analytical predictor returns a 5-bucket peak-VRAM breakdown (weights / optimizer / gradients / activations / overhead) and an OK/OOM verdict with a 10% safety margin.+For `soup train`, `params_b` is derived by `model_size_from_name`:+- A local checkpoint path is measured directly from safetensors metadata headers.+- A Hub id is parsed: e.g. `72B`, `8x7B` → `46.7` total, `17B-16E` → `109` total, with active-parameter markers (`-A22B`) ignored.+- An id with no size token (e.g. `DeepSeek-V3`, `Kimi-K2`, `GLM-5`, `MiniMax-M2`) still falls back to `7B`, which under-predicts these models (they have 229B to 1T parameters). Point `base:` at a local download to have the checkpoint measured instead.+```pythonfrom soup_cli.utils.hardware_fit import HardwareFitInput, decide_hardware_fitdiff --git a/src/soup_cli/utils/gpu.py b/src/soup_cli/utils/gpu.pyindex 5f210757..0af27058 100644--- a/src/soup_cli/utils/gpu.py+++ b/src/soup_cli/utils/gpu.py@@ -345,18 +345,46 @@ def model_size_from_name(model_name: str) -> float:if marker in name_lower:return size- # Longer markers first: "1.7b" contains "7b", so a naive scan would call a- # 1.7B model a 7B one (and over-predict its VRAM by 4x).- size_markers = [- ("70b", 70), ("65b", 65), ("34b", 34), ("33b", 33),- ("13b", 13), ("8b", 8), ("3b", 3),- ("1.5b", 1.5), ("1.7b", 1.7), ("0.5b", 0.5), ("0.6b", 0.6),- ("7b", 7), ("1b", 1),- ]-- for marker, size in size_markers:- if marker in name_lower:- return size+ # OLMoE names the ACTIVE count before the total ("OLMoE-1B-7B": 1B active,+ # 6.9B total), so its first size token is not the total (#1198).+ if "olmoe-1b-7b" in name_lower:+ return 6.9++ # MoE models specify expert count and expert size (e.g. Mixtral 8x7B, 8x22B,+ # or generic NxMb). Handle explicitly before standard billion tokens:+ # 8x7B has ~46.7B total parameters, 8x22B has ~141.0B total parameters (#1198).+ moe_match = re.search(r"(?<![a-z0-9.])(\d+)x(\d+(?:\.\d+)?)b(?![a-z0-9])", name_lower)+ if moe_match:+ n_exp = int(moe_match.group(1))+ exp_sz = float(moe_match.group(2))+ if (n_exp, exp_sz) == (8, 7.0):+ return 46.7+ if (n_exp, exp_sz) == (8, 22.0):+ return 141.0+ return n_exp * exp_sz++ # Llama 4 names carry the ACTIVE count and the expert count ("17B-16E"), so the+ # size token is not the total (#1198). Known totals first; otherwise active x+ # experts, an over-estimate, which is the safe direction for this gate.+ llama4_totals = {(17.0, 16): 109.0, (17.0, 128): 400.0}+ active_experts = re.search(+ r"(?<![a-z0-9.])(\d+(?:\.\d+)?)b-(\d+)e(?![a-z0-9]|[-+]\d)", name_lower+ )+ if active_experts:+ active, experts = float(active_experts.group(1)), int(active_experts.group(2))+ return llama4_totals.get((active, experts), active * experts)++ # Strip active-parameter tokens with separator spellings (e.g. "-a-22b",+ # "_act_22b") so total parameters are parsed rather than active parameters+ # if the active count appears earlier and uses hyphenated separators (#1198).+ cleaned = re.sub(r"[-_]a(?:ct(?:ive)?)?[-_]?\d+(?:\.\d+)?b(?![a-z0-9])", "", name_lower)++ # Parse total parameter size token in billions (e.g. 72b, 32b, 14b, 405b, 4b, 1.7b).+ # Uses boundary lookarounds to avoid substring false matches (such as "11b" matching+ # "1b", "17b" or "27b" matching "7b", or "0.8b" matching "8b") (#1198).+ b_match = re.search(r"(?<![a-z0-9.])(\d+(?:\.\d+)?)b(?![a-z0-9])", cleaned)+ if b_match:+ return float(b_match.group(1))# Sub-billion checkpoints carry their size in MILLIONS (SmolLM2-135M,# SmolVLM-256M, ...). Without this they fell through to the 7B default anddiff --git a/tests/test_gpu.py b/tests/test_gpu.pyindex 73b500cc..f296badf 100644--- a/tests/test_gpu.py+++ b/tests/test_gpu.py@@ -8,6 +8,23 @@ def test_model_size_detection():assert model_size_from_name("meta-llama/Llama-3.1-70B") == 70assert model_size_from_name("codellama/CodeLlama-7b-hf") == 7assert model_size_from_name("some-unknown-model") == 7.0 # default+ # #1198: Previously unhandled sizes that fell back to 7.0B+ assert model_size_from_name("Qwen/Qwen2.5-72B-Instruct") == 72+ assert model_size_from_name("Qwen/Qwen2.5-32B") == 32+ assert model_size_from_name("Qwen/Qwen2.5-14B") == 14+ assert model_size_from_name("meta-llama/Llama-3.1-405B") == 405+ assert model_size_from_name("Qwen/Qwen3-4B") == 4+ # #1198: Active parameter tokens ignored in favor of total parameter count+ assert model_size_from_name("Qwen/Qwen3-235B-A22B") == 235+ assert model_size_from_name("Qwen/Qwen3-Coder-30B-A3B-Instruct") == 30+ # #1198: MoE explicit spelling+ assert model_size_from_name("mistralai/Mixtral-8x7B-v0.1") == 46.7+ assert model_size_from_name("mistralai/Mixtral-8x22B-v0.1") == 141.0+ # #1198: Boundary-safe regex avoids substring false matches+ assert model_size_from_name("meta-llama/Llama-3.2-11B-Vision-Instruct") == 11+ assert model_size_from_name("meta-llama/Llama-4-Scout-17B-16E-Instruct") == 109+ assert model_size_from_name("Qwen/Qwen3.5-27B") == 27+ assert model_size_from_name("Qwen/Qwen3.5-0.8B") == 0.8def test_batch_size_cpu():diff --git a/tests/test_issue1198_model_size_parsing.py b/tests/test_issue1198_model_size_parsing.pynew file mode 100644index 00000000..37095214--- /dev/null+++ b/tests/test_issue1198_model_size_parsing.py@@ -0,0 +1,217 @@+"""Tests for Issue #1198: Hardware-fit gate Hub model size estimation.++Validates that model_size_from_name correctly parses model sizes from Hub IDs+using boundary-safe regex, handles MoE (NxMb) models, respects total parameters+over active-parameter markers (-aNNb), handles Llama 4 active+expert count (17B-16E),+and resolves recipe bases in catalog.py within 10% of their actual parameter count+or explicitly allowlists them.+"""++from __future__ import annotations++import re++import pytest++from soup_cli.recipes.catalog import RECIPES+from soup_cli.utils.gpu import model_size_from_name++# Hub base models in the recipe catalogue whose repository IDs carry no parameter+# count marker (such as "14B" or "8x7B") and therefore fall back to the default 7.0B+# guess, or whose size is not specified in the recipe metadata ("N/A").+_UNRESOLVABLE_CATALOG_REASONS = {+ "MiniMaxAI/MiniMax-M2": "Version 'M2' carries no param count in ID (real: 228.7B).",+ "MiniMaxAI/MiniMax-M3": "Model ID specifies version 'M3', carrying no parameter count (428B).",+ "PaddlePaddle/PaddleOCR-VL": "Specialized OCR VL model with no parameter count (size N/A).",+ "Qwen/Qwen-Image": "Qwen image foundation model with no parameter count (size N/A).",+ "deepseek-ai/DeepSeek-OCR": "Domain OCR model with no parameter count (size N/A).",+ "deepseek-ai/DeepSeek-V3": "DeepSeek V3 671B MoE carrying no parameter count in repo ID.",+ "deepseek-ai/DeepSeek-V3-0324": "DeepSeek V3 carrying no parameter count in ID (real: 684.5B).",+ "deepseek-ai/DeepSeek-V4-Flash": "DeepSeek V4 Flash architecture with no parameter count.",+ "deepseek-ai/DeepSeek-V4-Pro": "DeepSeek V4 Pro architecture with no parameter count.",+ "facebook/seamless-m4t-v2-large": "Uses 'v2-large' designation rather than param count (2.3B).",+ "microsoft/Phi-3.5-mini-instruct": "Uses 'mini' descriptor rather than param count (3.8B).",+ "microsoft/phi-4": "Model ID specifies release 'phi-4' without parameter count (14B).",+ "mistralai/Devstral-Small-2507": "Uses 'Small-2507' descriptor rather than param count (24B).",+ "mistralai/Magistral-Small": "Uses 'Small' descriptor rather than param count (24B).",+ "moonshotai/Kimi-K2-Base": "Version 'K2-Base' carries no parameter count (size N/A).",+ "moonshotai/Kimi-K2-Thinking": "Reasoning variant of K2 with no parameter count (size N/A).",+ "moonshotai/Kimi-K2.5": "Model ID specifies version 'K2.5' without parameter count (1T).",+ "moonshotai/Kimi-K2.6": "Model ID specifies version 'K2.6' without parameter count (1T).",+ "openbmb/MiniCPM-V-2_6": "Model ID specifies version '2_6' without parameter count (8B).",+ "sentence-transformers/all-mpnet-base-v2": "Embedding model with no parameter count.",+ "zai-org/GLM-4.6": "Model ID specifies release '4.6' without param count (real: 356.8B).",+ "zai-org/GLM-5": "Model ID specifies release '5' without parameter count (real: 753.9B).",+ "zai-org/GLM-5.1": "Model ID specifies release '5.1' without parameter count (754B).",+}++# Hub safetensors totals for catalog bases whose recipe label is NOT the total+# parameter count (#1161 / #1168), so the label cannot be the yardstick for them.+_KNOWN_TOTAL_B = {+ "meta-llama/Llama-4-Scout-17B-16E-Instruct": 108.6, # label 17B is the active count+ "deepseek-ai/DeepSeek-V3-0324": 684.5, # deepseek-v3-7b-sft, label 7B+ "zai-org/GLM-5": 753.9, # label 9B+ "MiniMaxAI/MiniMax-M2": 228.7, # label 9B+ "zai-org/GLM-4.6": 356.8, # label 9B+}++++class TestIssue1198HubModelSizeParsing:+ """Acceptance criteria tests for Issue #1198."""++ @pytest.mark.parametrize(+ ("model_id", "expected_size"),+ [+ ("Qwen/Qwen2.5-72B-Instruct", 72.0),+ ("Qwen/Qwen2.5-32B", 32.0),+ ("Qwen/Qwen2.5-14B", 14.0),+ ("meta-llama/Llama-3.1-405B", 405.0),+ ("Qwen/Qwen3-235B-A22B", 235.0),+ ("mistralai/Mixtral-8x7B-v0.1", 46.7),+ ("mistralai/Mixtral-8x22B-v0.1", 141.0),+ ("Qwen/Qwen3-4B", 4.0),+ ],+ )+ def test_issue_reported_models(self, model_id: str, expected_size: float) -> None:+ """Verify the exact models reported in issue #1198 resolve accurately."""+ assert model_size_from_name(model_id) == pytest.approx(expected_size)++ @pytest.mark.parametrize(+ ("model_id", "expected_size"),+ [+ # Models > 8B must never resolve to <= 8.0+ ("meta-llama/Llama-3.1-70B", 70.0),+ ("meta-llama/Llama-3.2-90B-Vision-Instruct", 90.0),+ ("meta-llama/Llama-3.1-405B", 405.0),+ ("Qwen/Qwen2.5-72B-Instruct", 72.0),+ ("Qwen/Qwen2.5-32B", 32.0),+ ("Qwen/Qwen2.5-Coder-14B-Instruct", 14.0),+ ("meta-llama/Llama-3.2-11B-Vision-Instruct", 11.0),+ ("meta-llama/Llama-4-Scout-17B-16E-Instruct", 109.0),+ ("mistralai/Pixtral-12B-2409", 12.0),+ ("mistralai/Mistral-Small-24B-Instruct-2501", 24.0),+ ("Qwen/Qwen3.5-27B", 27.0),+ ("Qwen/Qwen3-Coder-30B-A3B-Instruct", 30.0),+ ("Qwen/Qwen3.5-35B-A3B", 35.0),+ ("Qwen/Qwen3.5-122B-A10B", 122.0),+ ("Qwen/Qwen3.5-397B-A17B", 397.0),+ ("nvidia/Nemotron-4-340B-Instruct", 340.0),+ ("mistralai/Mistral-Large-3-675B-Instruct-2512", 675.0),+ ("openai/gpt-oss-20b", 20.0),+ ("openai/gpt-oss-120b", 120.0),+ ("mistralai/Mixtral-8x7B-v0.1", 46.7),+ ("mistralai/Mixtral-8x22B-v0.1", 141.0),+ ],+ )+ def test_large_models_never_resolve_to_eight_or_less(+ self, model_id: str, expected_size: float+ ) -> None:+ """Acceptance Criterion 2: No Hub id of a model larger than 8B resolves to 8 or less."""+ resolved = model_size_from_name(model_id)+ assert resolved > 8.0+ assert resolved == pytest.approx(expected_size)++ @pytest.mark.parametrize(+ ("model_id", "expected"),+ [+ ("meta-llama/Llama-4-Scout-17B-16E-Instruct", 109.0),+ ("meta-llama/Llama-4-Maverick-17B-128E-Instruct", 400.0),+ ("org/custom-7b-8e", 56.0), # unknown NNb-MMe: active x experts, an over-estimate+ ],+ )+ def test_llama4_active_and_expert_count(self, model_id: str, expected: float) -> None:+ """Llama 4 carries active size + expert count ('17B-16E'); parse real total (#1198)."""+ assert model_size_from_name(model_id) == pytest.approx(expected)++ def test_active_parameter_variations(self) -> None:+ """Active parameter tokens must never mask the total parameter count."""+ assert model_size_from_name("Qwen/Qwen3-235B-A22B") == 235.0+ assert model_size_from_name("Qwen/Qwen3-235B-a22b") == 235.0+ assert model_size_from_name("Qwen/Qwen3-235B-act22b") == 235.0+ assert model_size_from_name("Qwen/Qwen3-235B-active22b") == 235.0+ assert model_size_from_name("Qwen/Qwen3-a-22b-235b") == 235.0+ assert model_size_from_name("Qwen/Qwen3-act-22b-235b") == 235.0+ assert model_size_from_name("Qwen/Qwen3-Coder-30B-A3B-Instruct") == 30.0+ assert model_size_from_name("Qwen/Qwen3.5-122B-A10B") == 122.0+ assert model_size_from_name("Qwen/Qwen3.5-397B-A17B") == 397.0++ @pytest.mark.parametrize(+ "model_id", ["allenai/OLMoE-1B-7B-0924", "allenai/OLMoE-1B-7B-0125-Instruct"]+ )+ def test_olmoe_active_count_comes_first(self, model_id: str) -> None:+ """'OLMoE-1B-7B' is 1B active / 6.9B total; the first token is not the total."""+ assert model_size_from_name(model_id) == pytest.approx(6.9)++ @pytest.mark.parametrize(+ ("model_id", "expected"),+ [+ ("org/model-4bit-70b", 70.0), # "4bit" is not a size: the lookahead+ ("org/model-x0.8b-3b", 3.0), # "8b" inside "x0.8b": the "." in the lookbehind+ ("org/model-v2x7b-13b", 13.0), # "2x7b" inside "v2x7b": the MoE lookbehind+ ("org/model-v3b-13b", 13.0), # a non-default answer, unlike v3b-7b == 7.0+ ("org/moe-30b-a3b-8e", 30.0), # "3b-8e" inside "a3b-8e": the Llama 4 lookbehind+ ("org/model-13b-2ep", 13.0), # "2e" inside "2ep": the Llama 4 lookahead+ ],+ )+ def test_each_boundary_is_load_bearing(self, model_id: str, expected: float) -> None:+ """Pin regex boundaries to prevent regressions from lookahead/lookbehind mutations."""+ assert model_size_from_name(model_id) == expected++ def test_learning_rate_not_parsed_as_expert_count(self) -> None:+ """Exponents like '5e-6' or '2e-5' after size must not be read as expert count."""+ assert model_size_from_name("Minbyul/biomistral-7b-5e-6-foobar") == 7.0+ assert model_size_from_name("org/model-7b-2e-5") == 7.0++ def test_generic_moe_fallback(self) -> None:+ """Generic NxMb pattern computes expert product as upper bound for hardware fit."""+ assert model_size_from_name("custom-org/moe-4x7b-base") == 28.0+ assert model_size_from_name("custom-org/moe-16x12b-instruct") == 192.0++ def test_decimal_size_tokens(self) -> None:+ """Decimals are parsed correctly without substring collisions."""+ assert model_size_from_name("Qwen/Qwen2.5-0.5B-Instruct") == 0.5+ assert model_size_from_name("Qwen/Qwen3.5-0.8B") == 0.8+ assert model_size_from_name("Qwen/Qwen2.5-1.5B-Instruct") == 1.5+ assert model_size_from_name("HuggingFaceTB/SmolLM2-1.7B-Instruct") == 1.7+ assert model_size_from_name("LiquidAI/LFM2-1.2B") == 1.2+ assert model_size_from_name("ise-uiuc/Magicoder-S-DS-6.7B") == 6.7++ def test_every_allowlisted_base_is_still_used(self) -> None:+ """Ensure every base in allowlist and _KNOWN_TOTAL_B is actually used in RECIPES."""+ used = {recipe.model for recipe in RECIPES.values()}+ stale = sorted((set(_UNRESOLVABLE_CATALOG_REASONS) | set(_KNOWN_TOTAL_B)) - used)+ assert not stale, f"allowlist names bases no recipe uses: {stale}"++ def test_recipe_catalog_resolution_or_allowlist(self) -> None:+ """Acceptance Criterion 1: Every recipe base resolves within 10% or is documented."""+ seen_models = set()+ for name, recipe in RECIPES.items():+ model = recipe.model+ if model in seen_models:+ continue+ seen_models.add(model)++ parsed = model_size_from_name(model)++ # Match recipe size like "8B", "135M", "0.5B", etc.+ size_match = re.match(r"^(\d+(?:\.\d+)?)([BM])$", recipe.size)+ if size_match:+ val = float(size_match.group(1))+ unit = size_match.group(2)+ expected_b = val if unit == "B" else val / 1000.0+ expected_b = _KNOWN_TOTAL_B.get(model, expected_b)+ rel_diff = abs(parsed - expected_b) / expected_b++ if rel_diff > 0.10:+ assert model in _UNRESOLVABLE_CATALOG_REASONS, (+ f"Recipe '{name}' with model '{model}' resolved to {parsed}B, "+ f"deviating from recipe size {recipe.size} ({expected_b}B) "+ f"by {rel_diff:.1%}, but not in _UNRESOLVABLE_CATALOG_REASONS."+ )+ else:+ # Recipe size is "N/A" or non-standard+ assert model in _UNRESOLVABLE_CATALOG_REASONS, (+ f"Recipe '{name}' with model '{model}' has non-standard size '{recipe.size}', "+ "but is not documented in _UNRESOLVABLE_CATALOG_REASONS."+ )