| """Coarse VRAM-fit estimation for one-consumer-GPU LoRA jobs. |
| |
| Used by the open-model policy (``model_policy = "allow"``) to sanity-check that an |
| unlisted HF model can plausibly run on the requested GPU before provisioning it. |
| |
| These are deliberately coarse heuristics (documented ±20%): they exist to catch |
| *provably impossible* configurations (70B bf16 on a 24 GB card) and to warn on tight |
| fits — not to guarantee success. Calibrated against the measured catalog entries |
| (Qwen3-0.6B/4B/8B, Qwen3.5 dense). |
| """ |
|
|
| from __future__ import annotations |
|
|
| import math |
| import os |
| import re |
| from dataclasses import dataclass |
|
|
|
|
| def _gpu_vram_table() -> dict[str, int]: |
| try: |
| from autoslm.providers.base import GPU_INFO |
|
|
| return {name: info.vram_gb for name, info in GPU_INFO.items()} |
| except Exception: |
| return {"RTX 4090": 24, "RTX 5090": 32} |
|
|
|
|
| GPU_VRAM_GB = _gpu_vram_table() |
|
|
| _BYTES_PER_PARAM = { |
| "bf16": 2.0, |
| "fp16": 2.0, |
| "4bit-qlora": 0.55, |
| } |
|
|
| |
| |
| _BASE_OVERHEAD_GB = 4.0 |
| |
| |
| |
| _ACT_COEF = 0.12 |
| |
| |
| |
| _KV_COEF = 2.0 |
| _KV_CAP = 8.0 |
| |
| |
| |
| |
| _TRAIN_COEF = 0.27 |
| |
| |
| |
| |
| |
| _VLLM_COLOCATE_FLOOR_GB = 28.0 |
| _VOCAB_DEFAULT = 152_000 |
| |
| |
| _LOGITS_BUDGET_GB = 6.0 |
|
|
|
|
| def grpo_seq_escalation_gb(params_b: float | None, seq_len: int) -> int: |
| """Extra GB a long-context GRPO run needs beyond its base footprint. |
| |
| Big-model GRPO is tight: colocate holds 2 weight copies + a KV pool, so headroom shrinks |
| with model size and long context overflows it. Calibrated on a bf16 9.7B GRPO run (RunPod): |
| fits 80 GB to seq 4096 but OOMs at 8192. Safe headroom ~ 48500/params_b tokens; past that |
| escalate, STEEPER for bigger models. Applies to both catalog and open-model GRPO so neither |
| under-provisions. |
| """ |
| coef = 0.9 |
| if not params_b: |
| return 0 |
| seq_thresh = 48_500.0 / params_b |
| if seq_len <= seq_thresh: |
| return 0 |
| return math.ceil(coef * params_b * (seq_len / seq_thresh - 1)) |
|
|
|
|
| def params_b_from_str(s: str | None) -> float | None: |
| """Leading param count (billions) from a catalog ``params`` string, e.g. |
| "4.7B (text-only fine-tune)" -> 4.7, "9.7B (text-only fine-tune)" -> 9.7.""" |
| if not s: |
| return None |
| m = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*B", s) |
| return float(m.group(1)) if m else None |
|
|
|
|
| @dataclass(frozen=True) |
| class VramEstimate: |
| params_b: float | None |
| algorithm: str |
| quant: str |
| est_gb: float | None |
| gpu: str |
| gpu_gb: int |
| verdict: str |
|
|
| def describe(self) -> str: |
| if self.est_gb is None: |
| return f"{self.gpu}: VRAM need unknown (could not read model size)" |
| return ( |
| f"{self.gpu} ({self.gpu_gb} GB): estimated ~{self.est_gb:.0f} GB needed " |
| f"({self.params_b:.1f}B params, {self.quant}, {self.algorithm}) -> {self.verdict}" |
| ) |
|
|
|
|
| def estimate_vram_gb( |
| params_b: float, |
| algorithm: str, |
| quant: str = "bf16", |
| *, |
| seq_len: int = 1024, |
| max_tokens: int | None = None, |
| lora_rank: int = 32, |
| batch_size: int = 1, |
| group_size: int = 8, |
| thinking: bool = False, |
| use_vllm: bool = True, |
| ) -> float: |
| """Estimated peak VRAM (GB) for a LoRA job on one GPU, over the full knob matrix. |
| |
| Terms (all in GB): |
| weights params x bytes/param (bf16=2, 4bit-qlora=0.55) |
| base CUDA context + framework + fragmentation headroom |
| lora_opt LoRA adapter + grads + Adam states (rank-linear, model-scaled) |
| activations grad-checkpointed activations ~ batch x seq x sqrt(params) |
| grpo only: |
| +weights colocated vLLM holds a 2nd resident weight copy at the rollout peak |
| (sleep mode offloads it BETWEEN steps, not during) -- skipped when |
| use_vllm is False (transformers generation, single copy) |
| kv vLLM KV pool ~ seq x sqrt(params) |
| logits fp32 logits [per_device_comps, completion, vocab] |
| """ |
| bpp = _BYTES_PER_PARAM.get(quant, 2.0) |
| weights = params_b * bpp |
| algo = "grpo" if (algorithm or "").lower() in ("grpo", "rl") else "sft" |
| width = math.sqrt(max(params_b, 0.1)) |
| lora_opt = (lora_rank / 16.0) * (0.3 + 0.04 * params_b) |
| base = weights + _BASE_OVERHEAD_GB + lora_opt |
| if algo == "grpo": |
| |
| |
| |
| |
| rollout = 0.0 |
| if use_vllm: |
| rollout = weights + min(_KV_COEF * (seq_len / 1024.0) * width, _KV_CAP) |
| group_factor = max(1.0, (max(1, group_size) / 4.0) ** 0.5) |
| think_factor = 1.3 if thinking else 1.0 |
| activations = _TRAIN_COEF * (seq_len / 1024.0) * width * group_factor * think_factor |
| |
| |
| |
| |
| |
| |
| completion = max_tokens if max_tokens else min(seq_len, 1024) |
| logits = min(completion * _VOCAB_DEFAULT * 4 / 1e9, _LOGITS_BUDGET_GB) |
| train = activations + logits |
| return base + max(rollout, train) |
| return base + _ACT_COEF * max(1, batch_size) * (seq_len / 1024.0) * width |
|
|
|
|
| def model_required_vram_gb( |
| model_id: str, |
| algorithm: str, |
| *, |
| train=None, |
| thinking: bool = False, |
| headroom: float = 1.1, |
| ) -> int: |
| """Cheapest-sufficient VRAM (GB) for a specific run -- the matrix the allocator and |
| ``resolve_gpu_policy`` both size against. |
| |
| Catalog models size from their known param count + the run's actual knobs (``train`` |
| may be a TrainSpec, a dict, or None for recipe defaults). Curated GRPO floors |
| (``grpo_min_vram_gb``) stay as HARD floors so we never under-provision a validated |
| model; the matrix only ever sizes UP from there. Unlisted open models size from HF |
| metadata, falling back to the 24 GB tier when the size can't be read. |
| """ |
|
|
| |
| |
| |
| def _g(obj, key): |
| if obj is None: |
| return None |
| return obj.get(key) if isinstance(obj, dict) else getattr(obj, key, None) |
|
|
| def _pos_int(v, default): |
| try: |
| if isinstance(v, bool): |
| return default |
| f = float(v) |
| return int(f) if math.isfinite(f) and f >= 1 else default |
| except (TypeError, ValueError): |
| return default |
|
|
| seq_len = _pos_int(_g(train, "max_length"), 1024) |
| max_tokens = _pos_int(_g(train, "max_tokens"), None) |
| lora_rank = _pos_int(_g(train, "lora_rank"), 32) |
| group_size = _pos_int(_g(train, "group_size"), 8) |
| batch_size = _pos_int(_g(train, "batch_size"), 1) |
|
|
| def _need( |
| params_b: float, algorithm: str, *, quant: str = "bf16", use_vllm: bool = True |
| ) -> int: |
| |
| |
| est = estimate_vram_gb( |
| params_b, |
| algorithm, |
| quant, |
| seq_len=seq_len, |
| max_tokens=max_tokens, |
| lora_rank=lora_rank, |
| batch_size=batch_size, |
| group_size=group_size, |
| thinking=thinking, |
| use_vllm=use_vllm, |
| ) |
| return math.ceil(est * headroom) |
|
|
| from autoslm.catalog import MODELS |
|
|
| info = MODELS.get(model_id) |
| is_grpo = (algorithm or "").lower() in ("grpo", "rl") |
| if info is not None: |
| params_b = params_b_from_str(info.params) |
| quant = getattr(info, "quant", "bf16") or "bf16" |
| |
| |
| use_vllm = True |
| need = _need(params_b or 4.0, algorithm, quant=quant, use_vllm=use_vllm) |
| |
| floor = 0 |
| if is_grpo and getattr(info, "grpo_min_vram_gb", 0): |
| floor = int(info.grpo_min_vram_gb) |
| if quant == "4bit-qlora": |
| |
| |
| |
| _q_floor = ( |
| int(getattr(info, "grpo_min_vram_gb", 0) or info.min_vram_gb) |
| if is_grpo |
| else int(info.min_vram_gb) |
| ) |
| floor = max(floor, _q_floor) |
| |
| |
| if is_grpo and floor: |
| floor += grpo_seq_escalation_gb(params_b, seq_len) |
| need = max(need, floor) |
| |
| |
| |
| |
| |
| |
| |
| if is_grpo and use_vllm: |
| floor_gb = 24 if (params_b or 0.0) <= 1.0 else int(_VLLM_COLOCATE_FLOOR_GB) |
| need = max(need, floor_gb) |
| return need |
| |
| params_b = fetch_hf_params_b(model_id) |
| if params_b is None: |
| return 24 |
| |
| need = _need(params_b, "grpo") |
| |
| |
| if is_grpo: |
| need += grpo_seq_escalation_gb(params_b, seq_len) |
| return need |
|
|
|
|
| def fetch_hf_params_b(model_id: str) -> float | None: |
| """Total params (billions) from the HF API safetensors metadata (no download).""" |
| if os.environ.get("AUTOSLM_SKIP_NET"): |
| return None |
| try: |
| from huggingface_hub import HfApi |
|
|
| info = HfApi(token=os.environ.get("HF_TOKEN")).model_info( |
| model_id, expand=["safetensors"] |
| ) |
| total = getattr(getattr(info, "safetensors", None), "total", None) |
| if total: |
| return float(total) / 1e9 |
| except Exception: |
| |
| |
| pass |
| return None |
|
|
|
|
| def check_fit( |
| model_id: str, |
| algorithm: str, |
| gpu: str, |
| quant: str = "bf16", |
| params_b: float | None = None, |
| ) -> VramEstimate: |
| """Estimate whether ``model_id`` plausibly trains on ``gpu``; never raises.""" |
| gpu_gb = GPU_VRAM_GB.get(gpu, 32) |
| if params_b is None: |
| params_b = fetch_hf_params_b(model_id) |
| if params_b is None: |
| return VramEstimate(None, algorithm, quant, None, gpu, gpu_gb, "unknown") |
| est = estimate_vram_gb(params_b, algorithm, quant) |
| if est > gpu_gb * 1.15: |
| verdict = "too_big" |
| elif est > gpu_gb * 0.85: |
| verdict = "tight" |
| else: |
| verdict = "fits" |
| return VramEstimate(params_b, algorithm, quant, est, gpu, gpu_gb, verdict) |
|
|