"""Back-of-the-envelope LLM math: memory, KV cache, compute and throughput.

Standard library only. Every function returns an estimate; real numbers depend on
the framework, kernels, batch size and hardware. Use these to sanity-check plans,
not to promise performance.

Run as a script for a quick report:

    python3 tools/llm_math.py --params 8e9 --layers 32 --kv-heads 8 --head-dim 128 --context 8192
"""

from __future__ import annotations

import argparse

BYTES_PER_PARAM = {
    "fp32": 4.0,
    "bf16": 2.0,
    "fp16": 2.0,
    "fp8": 1.0,
    "int8": 1.0,
    "int4": 0.5,
}

GIB = 1024**3


def _bytes(dtype: str) -> float:
    try:
        return BYTES_PER_PARAM[dtype]
    except KeyError as exc:
        raise ValueError(f"unknown dtype {dtype!r}; choose from {sorted(BYTES_PER_PARAM)}") from exc


def weight_memory_bytes(params: float, dtype: str = "bf16") -> float:
    """Memory to hold the model weights: parameters x bytes per parameter."""
    if params <= 0:
        raise ValueError("params must be positive")
    return params * _bytes(dtype)


def kv_cache_bytes_per_token(layers: int, kv_heads: int, head_dim: int, dtype: str = "bf16") -> float:
    """KV cache per token: 2 (keys and values) x layers x kv_heads x head_dim x bytes."""
    if min(layers, kv_heads, head_dim) <= 0:
        raise ValueError("layers, kv_heads and head_dim must be positive")
    return 2 * layers * kv_heads * head_dim * _bytes(dtype)


def kv_cache_bytes(
    layers: int, kv_heads: int, head_dim: int, tokens: int, batch: int = 1, dtype: str = "bf16"
) -> float:
    """Total KV cache for `batch` sequences of `tokens` tokens each."""
    if tokens < 0 or batch <= 0:
        raise ValueError("tokens must be >= 0 and batch must be positive")
    return kv_cache_bytes_per_token(layers, kv_heads, head_dim, dtype) * tokens * batch


def full_finetune_memory_bytes(params: float) -> float:
    """Rough memory for full fine-tuning with Adam in mixed precision, excluding activations.

    About 16 bytes per parameter: bf16 weights (2) + bf16 gradients (2)
    + fp32 master weights (4) + two fp32 Adam moments (8).
    """
    if params <= 0:
        raise ValueError("params must be positive")
    return params * 16.0


def training_flops(params: float, tokens: float) -> float:
    """Approximate training compute for a dense transformer: 6 x params x tokens."""
    if params <= 0 or tokens <= 0:
        raise ValueError("params and tokens must be positive")
    return 6.0 * params * tokens


def inference_flops_per_token(params: float) -> float:
    """Approximate forward-pass compute per generated token for a dense model: 2 x params."""
    if params <= 0:
        raise ValueError("params must be positive")
    return 2.0 * params


def compute_optimal_tokens(params: float, tokens_per_param: float = 20.0) -> float:
    """Training tokens suggested by the compute-optimal ("Chinchilla") rule of thumb (~20 per parameter)."""
    if params <= 0:
        raise ValueError("params must be positive")
    return params * tokens_per_param


def max_decode_tokens_per_second(weight_bytes: float, memory_bandwidth_bytes_per_s: float) -> float:
    """Upper bound on single-sequence decode speed when generation is memory-bandwidth bound.

    Each new token needs (at least) one full read of the weights, so
    tokens/s <= bandwidth / weight bytes. Real systems reach a fraction of this.
    """
    if weight_bytes <= 0 or memory_bandwidth_bytes_per_s <= 0:
        raise ValueError("weight_bytes and bandwidth must be positive")
    return memory_bandwidth_bytes_per_s / weight_bytes


def cost_usd(input_tokens: int, output_tokens: int, usd_per_m_input: float, usd_per_m_output: float) -> float:
    """API cost given prices per million input and output tokens."""
    if min(input_tokens, output_tokens) < 0 or min(usd_per_m_input, usd_per_m_output) < 0:
        raise ValueError("tokens and prices must be non-negative")
    return input_tokens / 1e6 * usd_per_m_input + output_tokens / 1e6 * usd_per_m_output


def estimate_tokens(text: str, chars_per_token: float = 4.0) -> int:
    """Very rough token estimate for English prose (about 4 characters per token).

    Use the model's real tokenizer when accuracy matters; code and non-English
    text often use many more tokens per character.
    """
    if chars_per_token <= 0:
        raise ValueError("chars_per_token must be positive")
    if not text:
        return 0
    return max(1, round(len(text) / chars_per_token))


def _report(args: argparse.Namespace) -> str:
    w = weight_memory_bytes(args.params, args.dtype)
    kv = kv_cache_bytes(args.layers, args.kv_heads, args.head_dim, args.context, args.batch, args.kv_dtype)
    lines = [
        f"weights ({args.dtype}):            {w / GIB:8.2f} GiB",
        f"KV cache per token ({args.kv_dtype}):  {kv_cache_bytes_per_token(args.layers, args.kv_heads, args.head_dim, args.kv_dtype) / 1024:8.1f} KiB",
        f"KV cache ({args.batch} x {args.context} tokens): {kv / GIB:8.2f} GiB",
        f"full fine-tune (no activations): {full_finetune_memory_bytes(args.params) / GIB:8.1f} GiB",
        f"compute-optimal training tokens: {compute_optimal_tokens(args.params):.3g}",
    ]
    if args.bandwidth_gbs:
        tps = max_decode_tokens_per_second(w, args.bandwidth_gbs * 1e9)
        lines.append(f"decode upper bound at {args.bandwidth_gbs:g} GB/s: {tps:8.1f} tokens/s")
    return "\n".join(lines)


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description="Back-of-the-envelope LLM memory and compute estimates.")
    parser.add_argument("--params", type=float, required=True, help="parameter count, e.g. 8e9")
    parser.add_argument("--dtype", default="bf16", choices=sorted(BYTES_PER_PARAM))
    parser.add_argument("--layers", type=int, default=32)
    parser.add_argument("--kv-heads", type=int, default=8)
    parser.add_argument("--head-dim", type=int, default=128)
    parser.add_argument("--context", type=int, default=8192)
    parser.add_argument("--batch", type=int, default=1)
    parser.add_argument("--kv-dtype", default="bf16", choices=sorted(BYTES_PER_PARAM))
    parser.add_argument("--bandwidth-gbs", type=float, default=0.0, help="memory bandwidth in GB/s")
    print(_report(parser.parse_args(argv)))


if __name__ == "__main__":
    main()
