"""Module 3: how many parameters does LoRA train, and roughly how much memory will a run need?

Memory figures are rules of thumb for the model weights and optimizer state only.
Activations (which grow with batch size and sequence length) come on top; gradient
checkpointing reduces them. Always leave headroom and measure on your hardware.
"""
from __future__ import annotations

from dataclasses import dataclass


def lora_params(d_in: int, d_out: int, r: int) -> int:
    """LoRA replaces an update to W (d_out x d_in) with B (d_out x r) @ A (r x d_in)."""
    return r * (d_in + d_out)


@dataclass
class DecoderShape:
    hidden: int
    intermediate: int
    layers: int
    heads: int
    kv_heads: int
    head_dim: int

    def projections(self) -> dict[str, tuple[int, int]]:
        q = self.heads * self.head_dim
        kv = self.kv_heads * self.head_dim
        return {"q_proj": (self.hidden, q), "k_proj": (self.hidden, kv), "v_proj": (self.hidden, kv),
                "o_proj": (q, self.hidden), "gate_proj": (self.hidden, self.intermediate),
                "up_proj": (self.hidden, self.intermediate), "down_proj": (self.intermediate, self.hidden)}


ALL_LINEAR = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj")


def model_lora_params(shape: DecoderShape, r: int, targets: tuple[str, ...] = ALL_LINEAR) -> int:
    proj = shape.projections()
    unknown = set(targets) - proj.keys()
    if unknown:
        raise ValueError(f"unknown target modules: {sorted(unknown)}")
    per_layer = sum(lora_params(*proj[t], r) for t in targets)
    return per_layer * shape.layers


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


def gib(n_bytes: float) -> float:
    return n_bytes / 2**30


def estimate_memory_gib(n_params: float, method: str, trainable: float = 0.0) -> float:
    """Rough GPU memory for weights + gradients + AdamW state (activations excluded).

    full  : bf16 weights and grads (2 + 2 bytes) + fp32 master weights and two Adam moments (12 bytes) = 16 bytes/param
    lora  : frozen bf16 base (2 bytes/param) + 16 bytes per trainable adapter param
    qlora : frozen 4-bit base (about 0.5 bytes/param plus ~10% for quantization constants) + 16 bytes per adapter param
    """
    if method == "full":
        return gib(16 * n_params)
    if method == "lora":
        return gib(2 * n_params + 16 * trainable)
    if method == "qlora":
        return gib(0.55 * n_params + 16 * trainable)
    if method == "inference-bf16":
        return gib(2 * n_params)
    if method == "inference-4bit":
        return gib(0.55 * n_params)
    raise ValueError("method must be full, lora, qlora, inference-bf16 or inference-4bit")


def effective_batch(per_device: int, grad_accum: int, devices: int = 1) -> int:
    return per_device * grad_accum * devices


def training_steps(n_examples: int, per_device: int, grad_accum: int, epochs: float, devices: int = 1) -> int:
    per_epoch = -(-n_examples // effective_batch(per_device, grad_accum, devices))  # ceiling division
    return int(per_epoch * epochs)
