#!/usr/bin/env python3
# vram_budget.py - estimate what a model needs before you rent a GPU.
# Project: hostimm.com - https://hostimm.com
# AION (agent, APEX V2 architecture) - Architect AlexH
# Community: llmresearch.net (EN) / forumai.ro (RO)
# License: MIT, attribution required
"""vram_budget.py - estimate what a model needs before you rent a GPU.

Pure stdlib. No torch, no network. Run it on your laptop, then rent.
Usage:
  python vram_budget.py --params 8.03 --layers 32 --kv-heads 8 --head-dim 128 --ctx 4096
  python vram_budget.py --preset llama3-8b --ctx 32768 --concurrency 4 --dtype 4bit
"""
import argparse, json, math, sys

# bytes per parameter for weight storage
DTYPE = {"fp32": 4.0, "fp16": 2.0, "bf16": 2.0, "fp8": 1.0, "int8": 1.0, "4bit": 0.5, "6bit": 0.75}

CARDS = [  # name, vram GB, rough class
    ("RTX 4060 Ti 16GB", 16), ("RTX 4090 24GB", 24), ("RTX 3090 24GB", 24),
    ("RTX 5090 32GB", 32), ("A100 40GB", 40), ("L40S 48GB", 48),
    ("A6000 48GB", 48), ("A100 80GB", 80), ("H100 80GB", 80), ("H200 141GB", 141),
]

def kv_bytes_per_token(layers, kv_heads, head_dim, kv_dtype_bytes=2):
    # K and V, every layer, every kv head
    return 2 * layers * kv_heads * head_dim * kv_dtype_bytes

def estimate(params_b, layers, kv_heads, head_dim, ctx, batch, concurrency,
             dtype="bf16", kv_dtype="fp16", mode="inference",
             trainable_frac=0.0, optimizer="adamw"):
    p = params_b * 1e9
    weights = p * DTYPE[dtype]
    kv = kv_bytes_per_token(layers, kv_heads, head_dim, DTYPE[kv_dtype]) * ctx * batch * concurrency
    # serving only materialises logits for the sampled position, not for every token
    logits = batch * concurrency * 128256 * 2
    overhead = 1.2e9  # CUDA context, allocator fragmentation, framework
    if mode == "inference":
        act = 0.3e9 * (ctx / 8192) * batch * concurrency  # prefill peak, flash attention keeps it linear
        total = weights + kv + logits + overhead + act
    elif mode == "lora":
        trainable = p * trainable_frac
        opt = trainable * (8 if optimizer == "adamw" else 4)  # m + v in fp32
        act = 0.9e9 * batch * ctx / 2048  # with gradient checkpointing
        total = weights + opt + act + overhead
    else:  # full fine-tune, mixed precision AdamW: 16 bytes/param
        total = p * 16 + 1.5e9 * batch * ctx / 2048 + overhead
    return dict(weights=weights, kv=kv, logits=logits, overhead=overhead, total=total)

def fits(total_bytes):
    need = total_bytes / 1e9 * 1.15  # 15% headroom for fragmentation
    out = [c for c in CARDS if c[1] >= need]
    return (out[0] if out else ("multi-GPU", None)), need

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--preset", default=None)
    ap.add_argument("--params", type=float, default=8.03)
    ap.add_argument("--layers", type=int, default=32)
    ap.add_argument("--kv-heads", type=int, default=8)
    ap.add_argument("--head-dim", type=int, default=128)
    ap.add_argument("--ctx", type=int, default=4096)
    ap.add_argument("--batch", type=int, default=1)
    ap.add_argument("--concurrency", type=int, default=1)
    ap.add_argument("--dtype", default="bf16", choices=list(DTYPE))
    ap.add_argument("--kv-dtype", default="fp16", choices=list(DTYPE))
    ap.add_argument("--mode", default="inference", choices=["inference", "lora", "full"])
    ap.add_argument("--trainable-frac", type=float, default=0.005)
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()

    presets = {
        "llama3-8b": dict(params=8.03, layers=32, kv_heads=8, head_dim=128),
        "qwen2.5-7b": dict(params=7.62, layers=28, kv_heads=4, head_dim=128),
        "llama3-70b": dict(params=70.6, layers=80, kv_heads=8, head_dim=128),
        "qwen2.5-32b": dict(params=32.8, layers=64, kv_heads=8, head_dim=128),
    }
    kw = presets[a.preset] if a.preset else dict(params=a.params, layers=a.layers, kv_heads=a.kv_heads, head_dim=a.head_dim)
    r = estimate(kw["params"], kw["layers"], kw["kv_heads"], kw["head_dim"], a.ctx, a.batch,
                 a.concurrency, a.dtype, a.kv_dtype, a.mode, a.trainable_frac)
    card, need = fits(r["total"])
    gb = lambda x: round(x / 1e9, 2)
    res = {"mode": a.mode, "dtype": a.dtype, "ctx": a.ctx, "batch": a.batch, "concurrency": a.concurrency,
           "weights_gb": gb(r["weights"]), "kv_cache_gb": gb(r["kv"]), "logits_gb": gb(r["logits"]),
           "total_gb": gb(r["total"]), "needed_with_headroom_gb": round(need, 1), "smallest_card": card[0]}
    if a.json:
        print(json.dumps(res, indent=1)); return
    print(f"\n{a.mode} | {a.dtype} weights | ctx {a.ctx} | batch {a.batch} | concurrency {a.concurrency}")
    print(f"weights      {res['weights_gb']:>7.2f} GB")
    print(f"KV cache     {res['kv_cache_gb']:>7.2f} GB")
    print(f"logits       {res['logits_gb']:>7.2f} GB")
    print(f"total        {res['total_gb']:>7.2f} GB")
    print(f"rent at least {res['needed_with_headroom_gb']:>6.1f} GB -> {card[0]}")
    if res["needed_with_headroom_gb"] > 141:
        print("does not fit on one card: shard it (FSDP/ZeRO-3) or quantize")

if __name__ == "__main__":
    main()
