"""Arithmetic scenarios, not a capability predictor. Standard library only."""
from decimal import Decimal, ROUND_CEILING, localcontext

DAY = Decimal(86_400)
PUBLISHED_LLAMA3_405B_PRETRAIN_FLOPS = Decimal("3.8e25")
PUBLISHED_LLAMA31_405B_GPU_HOURS = Decimal("30.84e6")
EXAMPLE_MAX_GPU_COUNT = Decimal(16_384)
EXAMPLE_EFFECTIVE_FLOPS_PER_GPU_S = Decimal("400e12")

def capacity_days(work, count, effective_rate):
    if work < 0 or count <= 0 or effective_rate <= 0:
        raise ValueError("nonnegative work and positive count/rate required")
    return work / (count * effective_rate * DAY)

def required_gpu_count(work, target_days, effective_rate):
    if work < 0 or target_days <= 0 or effective_rate <= 0:
        raise ValueError("nonnegative work and positive time/rate required")
    return (work / (effective_rate * DAY * target_days)).to_integral_value(rounding=ROUND_CEILING)

def loss_optimal_budget(delta, A, B, alpha, beta, kappa):
    """Conditional optimum when compute=kappa*N*D and excess loss=A/N^alpha+B/D^beta."""
    if min(delta, A, B, alpha, beta, kappa) <= 0:
        raise ValueError("positive parameters required")
    x = beta * delta / (alpha + beta)
    y = alpha * delta / (alpha + beta)
    n = (A / x) ** (1 / alpha)
    d = (B / y) ** (1 / beta)
    return n, d, kappa * n * d

if __name__ == "__main__":
    with localcontext() as ctx:
        ctx.prec = 40
        w, n, r = (PUBLISHED_LLAMA3_405B_PRETRAIN_FLOPS, EXAMPLE_MAX_GPU_COUNT,
                   EXAMPLE_EFFECTIVE_FLOPS_PER_GPU_S)
        assert required_gpu_count(w, Decimal(7), r) == 157077
        assert required_gpu_count(w, Decimal(30), r) == 36652
        assert capacity_days(w, n, r).quantize(Decimal(".01")) == Decimal("67.11")
        assert loss_optimal_budget(*map(Decimal, ("2", "1", "1", "1", "1", "6"))) == (1,1,6)
        print(f"Llama 3 405B published pretraining work, idealized at the illustrated rate: {capacity_days(w,n,r):.2f} days")
        print("Required GPU count at unchanged effective rate (not practical scaling forecasts):",
              {d:int(required_gpu_count(w,Decimal(d),r)) for d in (1,7,30)})
        print(f"Llama 3.1 405B cumulative GPU-hours divided by the illustrated GPU count: "
              f"{PUBLISHED_LLAMA31_405B_GPU_HOURS / (n*24):.2f} equivalent days (not measured wall-clock)")
        print("Meta technical report: https://arxiv.org/html/2407.21783v3")
        print("Kimi K3.1 Pro is a capability reference only: https://huggingface.co/moonshotai/Kimi-K3.1-Pro")
