"""
approx.py -- exp, reciprocal, rsqrt, tanh, sigmoid, GELU and SiLU the way hardware computes them
================================================================================================

[Why we need it]
    A matrix unit only multiplies and adds. Softmax needs exp and a division, normalization needs 1/sqrt, and the
    activations of transformers (GELU, SiLU) need exp or tanh. A vector unit evaluates these "transcendental"
    functions in a SPECIAL-FUNCTION UNIT (SFU) built from three cheap ingredients:
        1. a small TABLE indexed by the top bits of the input (read-only memory),
        2. a short POLYNOMIAL evaluated with multiply-adds (Horner's rule),
        3. NEWTON-RAPHSON iterations that double the number of correct bits each time (for 1/x and 1/sqrt(x)),
    plus RANGE REDUCTION, which maps any input onto a small interval where the table and polynomial work:
        exp(x) = 2^(x log2 e) = 2^n * 2^f   with n an integer and f in [0, 1);
    2^n costs nothing -- it is an addition to the exponent field of the result -- so only 2^f is approximated.
    This module implements each ingredient on real numbers, in float32 arithmetic (every intermediate result is
    rounded to float32, as a float32 datapath would), and attaches a cost estimate (table bits, multipliers,
    adders, latency, area and energy at 45 nm) to every approximation, so that accuracy and cost can be traded.

[Main pieces]
    Approx                      : an approximation = a function + its hardware cost; call it like a function
    fit_segments / piecewise    : table-based piecewise polynomials of degree 0 (pure table), 1 (piecewise
                                  linear) or 2-3 (piecewise quadratic/cubic) on uniform segments
    remez                       : the true minimax polynomial on one interval (Remez exchange)
    exp_rr                      : exp by range reduction + a (piecewise) polynomial for 2^f
    exp_schraudolph             : the one-multiply "bit trick" exp (Schraudolph 1999)
    recip_nr, rsqrt_nr          : table seed + Newton-Raphson; rsqrt_magic: the "fast inverse square root" seed
    sigmoid_from, silu_from     : composites built from exp and reciprocal
    gelu_tanh, gelu_sigmoid     : the two common closed-form GELU approximations
    softmax                     : row softmax with pluggable exp / reciprocal (max subtraction included)
    *_ref                       : float64 reference functions; rel_err / abs_err / bits: error measures

[Cost model] (assumptions, stated once)
    - Datapath: float32 multipliers and adders; a multiply-add (FMA) costs one multiplier + one adder.
      Area and energy from Lecture 1's 45 nm numbers (Horowitz 2014): fp32 multiply 3.7 pJ / 7,700 um^2,
      fp32 add 0.9 pJ / 4,184 um^2. A fully pipelined SFU needs one unit per operation in the chain.
    - Tables: TABLE_UM2_PER_BIT = 0.7 um^2 per bit (the SRAM density assumed in Lecture 2; a ROM is denser, so
      tables are charged generously); read energy from Lecture 1's SRAM model for the table's size.
    - Latency: table read 1 cycle, multiply 3, add 4, FMA 4 (Lecture 2's operator library); the operations of
      one evaluation form a chain, so latency = sum of the chain.

[Usage]
    import numpy as np, approx as ap
    e = ap.exp_rr(segments=1, degree=3)          # cubic minimax-like polynomial for 2^f
    x = np.linspace(-20, 0, 1001)
    ap.rel_err(e(x), ap.exp_ref(x)), e.area_um2(), e.latency()

[Edge cases]
    - exp_rr flushes results below 2^-126 to zero and saturates above float32's range to inf (like an SFU
      without subnormal support). Its argument reduction x * log2(e) is done in float32, which limits accuracy
      to ~2^-18 for |x| > 64 (production libraries split ln 2 into two parts, "Cody-Waite reduction").
    - recip_nr / rsqrt_nr: 0 -> inf; rsqrt of a negative number -> NaN; recip keeps the sign of x.
    - Piecewise approximations clamp their input to [lo, hi]; pass `outside` to define the function beyond it.
"""

import math
from dataclasses import dataclass

import numpy as np

import course_path

course_path.use("lecture01")

from energy_model import HOROWITZ_AREA_UM2, HOROWITZ_OP_PJ, sram_pj_per_byte  # noqa: E402

F32 = np.float32
MUL_PJ, MUL_UM2 = HOROWITZ_OP_PJ[("fp", "mult", 32)], HOROWITZ_AREA_UM2[("fp", "mult", 32)]
ADD_PJ, ADD_UM2 = HOROWITZ_OP_PJ[("fp", "add", 32)], HOROWITZ_AREA_UM2[("fp", "add", 32)]
TABLE_UM2_PER_BIT = 0.7
LAT = {"table": 1, "mul": 3, "add": 4, "fma": 4}
LOG2E = F32(1.4426950408889634)


def f32(x):
    """Any array-like -> float32 numpy array (values rounded to the nearest float32)."""
    return np.asarray(x, dtype=np.float64).astype(F32)


# =====================================================================================================================
# Reference functions (float64) and error measures
# =====================================================================================================================

_erf = np.vectorize(math.erf, otypes=[float])


def exp_ref(x):
    """exp in float64 (the reference all approximations are compared with)."""
    with np.errstate(over="ignore"):
        return np.exp(np.asarray(x, dtype=np.float64))


def sigmoid_ref(x):
    """1 / (1 + exp(-x)) in float64, written so that it never overflows."""
    x = np.asarray(x, dtype=np.float64)
    e = np.exp(-np.abs(x))
    return np.where(x >= 0, 1 / (1 + e), e / (1 + e))


def silu_ref(x):
    """SiLU (swish): x * sigmoid(x) -- the activation inside Llama's SwiGLU feed-forward network."""
    return np.asarray(x, dtype=np.float64) * sigmoid_ref(x)


def gelu_ref(x):
    """Exact GELU: x * Phi(x) = 0.5 x (1 + erf(x / sqrt 2)) (BERT, GPT-2 use it or its tanh approximation)."""
    x = np.asarray(x, dtype=np.float64)
    return 0.5 * x * (1 + _erf(x / math.sqrt(2)))


def rel_err(y, ref):
    """
    Largest relative error max |y - ref| / |ref| (ignoring points where ref == 0).

    [Edge cases] inf/NaN in y where ref is finite count as an infinite error (a real failure of the approximation).
    """
    y, ref = np.asarray(y, dtype=np.float64), np.asarray(ref, dtype=np.float64)
    m = ref != 0
    with np.errstate(invalid="ignore", over="ignore"):
        e = np.abs(y[m] - ref[m]) / np.abs(ref[m])
    e = np.where(np.isfinite(e), e, np.inf)
    return float(e.max()) if e.size else 0.0


def abs_err(y, ref):
    """Largest absolute error max |y - ref|."""
    d = np.abs(np.asarray(y, dtype=np.float64) - np.asarray(ref, dtype=np.float64))
    d = np.where(np.isfinite(d), d, np.inf)
    return float(d.max())


def bits(err):
    """Correct bits implied by a relative error: -log2(err) (24 = float32 precision, 8 = bfloat16)."""
    return float("inf") if err == 0 else -math.log2(err)


# =====================================================================================================================
# An approximation and its cost
# =====================================================================================================================

@dataclass
class Approx:
    """
    One hardware approximation of a function, with the resources it needs per evaluation.

    [Fields]
        name       : label for tables
        fn         : the approximation itself, array -> float32 array (also reachable by calling the object)
        entries    : table entries (coefficients stored in the table); 0 = no table
        entry_bits : bits per table entry (32: coefficients kept in float32)
        reads      : table entries read per evaluation (degree + 1 for a piecewise polynomial)
        mul, add, fma : float32 operations in the evaluation chain
    [Methods] table_bits, area_um2(), energy_pj(), latency(), cost_row()
    [Python tip] Defining __call__ lets an object be used like a function: e = exp_rr(...); e(x).
    """
    name: str
    fn: object
    entries: int = 0
    entry_bits: int = 32
    reads: int = 0
    mul: int = 0
    add: int = 0
    fma: int = 0

    def __call__(self, x):
        return self.fn(x)

    @property
    def table_bits(self):
        return self.entries * self.entry_bits

    def area_um2(self):
        """Table area + one arithmetic unit per operation of the (fully pipelined) chain."""
        return (self.table_bits * TABLE_UM2_PER_BIT + self.mul * MUL_UM2 + self.add * ADD_UM2
                + self.fma * (MUL_UM2 + ADD_UM2))

    def energy_pj(self):
        """Energy of one evaluation: table reads + arithmetic."""
        table = 0.0
        if self.entries:
            table = self.reads * self.entry_bits / 8 * sram_pj_per_byte(max(self.table_bits / 8, 8))
        return table + self.mul * MUL_PJ + self.add * ADD_PJ + self.fma * (MUL_PJ + ADD_PJ)

    def latency(self):
        """Cycles from input to result (the operations form one dependent chain)."""
        return ((LAT["table"] if self.entries else 0) + self.mul * LAT["mul"] + self.add * LAT["add"]
                + self.fma * LAT["fma"])

    def cost_row(self):
        """[table bits, multipliers + adders (FMA counts as both), area um^2, energy pJ, latency] for print_table."""
        return [f"{self.table_bits:,}", self.mul + self.add + 2 * self.fma, f"{self.area_um2():,.0f}",
                f"{self.energy_pj():.1f}", self.latency()]


def combine(name, fn, *parts, mul=0, add=0, fma=0):
    """
    An Approx built from other Approx objects (e.g. sigmoid = reciprocal(1 + exp(-x))): costs are summed.

    [Edge cases] Tables of the parts are kept separate (their bits add up); `reads` adds up too.
    """
    return Approx(name, fn,
                  entries=sum(p.entries for p in parts),
                  entry_bits=max([p.entry_bits for p in parts] + [32]),
                  reads=sum(p.reads for p in parts),
                  mul=mul + sum(p.mul for p in parts), add=add + sum(p.add for p in parts),
                  fma=fma + sum(p.fma for p in parts))


# =====================================================================================================================
# Table-based piecewise polynomials
# =====================================================================================================================

def fit_segments(f, lo, hi, segments, degree, relative=False):
    """
    Coefficients of a piecewise polynomial approximating f on [lo, hi) cut into `segments` equal pieces.

    [Idea] Hardware picks the segment with the top bits of the input (no comparison needed when the segment width
        is a power of two) and evaluates a small polynomial in the OFFSET t = x - left edge of the segment.
        - degree 0: one constant per segment = a pure lookup table. The best constant (minimax) is the midpoint of
          the function's range on the segment: (fmin + fmax) / 2 for absolute error, or 2 fmin fmax / (fmin + fmax)
          for relative error (equal relative error at both ends).
        - degree >= 1: interpolate f at the degree + 1 Chebyshev nodes of the segment. Chebyshev nodes cluster near
          the ends and give an error within a small factor of the true minimax polynomial (see remez()); the
          error of degree d shrinks like h^(d+1) as the segment width h shrinks -- each halving of h buys d + 1
          bits. That is why a small table plus a quadratic beats a huge table of constants.
    [Args]
        f        : vectorized function of float64 arrays
        lo, hi   : the interval; segments: number of equal segments (>= 1); degree: polynomial degree (>= 0)
        relative : fit for relative instead of absolute error (only matters for degree 0)
    [Returns] float64 array (segments, degree + 1); column j multiplies t^j
    [Edge cases] For degree 0 the function is sampled at 65 points per segment to find its min and max, so it
        need not be monotone. relative=True requires f not to change sign inside a segment.
    """
    h = (hi - lo) / segments
    lefts = lo + h * np.arange(segments)
    if degree == 0:
        t = np.linspace(0.0, h, 65)
        v = f(lefts[:, None] + t[None, :])
        vmin, vmax = v.min(axis=1), v.max(axis=1)
        if relative:
            c = 2 * vmin * vmax / (vmin + vmax)
        else:
            c = (vmin + vmax) / 2
        return c[:, None]
    k = np.arange(degree + 1)
    nodes = h / 2 * (1 - np.cos((2 * k + 1) * np.pi / (2 * (degree + 1))))       # Chebyshev nodes in [0, h]
    V = np.vander(nodes, degree + 1, increasing=True)
    Y = f(lefts[:, None] + nodes[None, :])                                         # (segments, degree + 1)
    return np.linalg.solve(V, Y.T).T


def horner32(coeffs, t):
    """
    Evaluate sum_j coeffs[..., j] * t^j in float32 with Horner's rule: (((c_d t + c_{d-1}) t + ...) t + c_0).

    [Idea] Horner needs d multiply-adds for degree d and no powers -- the standard hardware schedule.
    [Args] coeffs: (..., degree + 1) float32; t: float32 array broadcastable to coeffs[..., 0]
    [Returns] float32 array
    [Python tip] Every numpy operation on two float32 arrays rounds its result to float32, so this function
        reproduces a float32 datapath with separate (non-fused) multiply and add roundings.
    """
    acc = coeffs[..., -1].astype(F32)
    for j in range(coeffs.shape[-1] - 2, -1, -1):
        acc = acc * t + coeffs[..., j]
    return acc


def _segment_eval(x, coeffs, lo, hi):
    """Evaluate a piecewise polynomial (from fit_segments, already float32) at float32 inputs clamped to [lo, hi]."""
    segments = coeffs.shape[0]
    h = (hi - lo) / segments
    xc = np.clip(x, F32(lo), F32(hi))
    idx = np.clip(np.floor((xc.astype(np.float64) - lo) / h).astype(np.int64), 0, segments - 1)
    t = (xc - f32(lo + idx * h)).astype(F32)
    return horner32(coeffs[idx], t)


def piecewise(f, lo, hi, segments, degree, relative=False, name=None, outside=None):
    """
    A table-based piecewise polynomial approximation of f on [lo, hi].

    [Args]
        f, lo, hi, segments, degree, relative : as in fit_segments
        name    : label (default "deg-d x S segments")
        outside : optional function (x, y) -> y that fixes the result outside [lo, hi] -- e.g. for GELU,
                  0 below lo and x above hi
    [Returns] Approx with entries = segments x (degree + 1), reads = degree + 1, fma = degree
    [Edge cases] segments = 1 still counts as a table (degree + 1 constants) -- see exp_rr for the case where the
        constants are hard-wired instead.
    """
    coeffs = f32(fit_segments(f, lo, hi, segments, degree, relative))

    def fn(x):
        x = f32(x)
        y = _segment_eval(x, coeffs, lo, hi)
        return f32(outside(x, y)) if outside else y

    return Approx(name or f"deg-{degree} x {segments} segments", fn, entries=segments * (degree + 1),
                  reads=degree + 1, fma=degree)


# =====================================================================================================================
# Minimax polynomials (Remez exchange)
# =====================================================================================================================

def remez(f, lo, hi, degree, relative=False, iters=40, grid=20001):
    """
    The minimax polynomial of a given degree on [lo, hi]: the one whose largest error is as small as possible.

    [Idea] Chebyshev's equioscillation theorem: the minimax polynomial of degree d is the unique one whose error
        reaches its maximum magnitude E at d + 2 points with ALTERNATING signs. The Remez exchange finds it:
        1. guess d + 2 reference points (Chebyshev extrema);
        2. solve the linear system p(x_i) + (-1)^i E / w(x_i) = f(x_i) for the d + 1 coefficients and E
           (w = 1 for absolute error, 1/|f| for relative error);
        3. move the reference points to the extrema of the new error curve and repeat until the error levels out.
    [Args] f: vectorized float64 function; lo, hi; degree; relative: minimize relative error; iters; grid points
    [Returns] (coeffs, max_err): float64 coefficients in the offset t = x - lo (lowest power first), and the
        largest (weighted) error on the grid
    [Edge cases] Works for smooth functions on short intervals (all this course needs). If the error curve has fewer
        than d + 2 alternating extrema (a degenerate case), the iteration stops with the current polynomial.
    """
    n = degree
    g = np.linspace(lo, hi, grid)
    fg = f(g)
    wg = 1 / np.abs(fg) if relative else np.ones_like(g)
    k = np.arange(n + 2)
    xs = (lo + hi) / 2 - (hi - lo) / 2 * np.cos(np.pi * k / (n + 1))
    c = None
    for _ in range(iters):
        A = np.vander(xs - lo, n + 1, increasing=True)
        w = 1 / np.abs(f(xs)) if relative else np.ones_like(xs)
        sign = (-1.0) ** np.arange(n + 2)
        sol = np.linalg.solve(np.column_stack([A, sign / w]), f(xs))
        c = sol[:-1]
        err = (np.polynomial.polynomial.polyval(g - lo, c) - fg) * wg
        # one extremum per run of equal sign
        s = np.sign(err)
        s[s == 0] = 1
        cuts = np.flatnonzero(np.diff(s)) + 1
        runs = np.split(np.arange(grid), cuts)
        ext = np.array([r[np.argmax(np.abs(err[r]))] for r in runs])
        while len(ext) > n + 2:                            # drop the smaller end until d + 2 remain
            ext = ext[1:] if abs(err[ext[0]]) < abs(err[ext[-1]]) else ext[:-1]
        if len(ext) < n + 2:
            break
        new = g[ext]
        if np.allclose(new, xs, rtol=0, atol=(hi - lo) / grid):
            xs = new
            break
        xs = new
    err = (np.polynomial.polynomial.polyval(g - lo, c) - fg) * wg
    return c, float(np.abs(err).max())


# =====================================================================================================================
# exp
# =====================================================================================================================

def _pow2_coeffs(segments, degree, fit):
    """Coefficients (segments, degree + 1) for 2^t on [0, 1) by the requested fitting method."""
    p2 = lambda t: np.exp2(t)                                                       # noqa: E731
    if fit == "taylor":                                       # Taylor series at the segment's left edge
        h = 1.0 / segments
        lefts = h * np.arange(segments)
        k = np.arange(degree + 1)
        base = math.log(2) ** k / np.array([math.factorial(j) for j in k])
        return np.exp2(lefts)[:, None] * base[None, :]
    if fit == "remez":
        h = 1.0 / segments
        return np.array([remez(p2, i * h, (i + 1) * h, degree, relative=True)[0] for i in range(segments)])
    return fit_segments(p2, 0.0, 1.0, segments, degree, relative=True)


def exp_rr(segments=1, degree=3, fit="cheb", cody_waite=False, name=None):
    """
    exp(x) by range reduction: y = x log2(e); n = floor(y); f = y - n in [0, 1); exp(x) = 2^n * p(f).

    [Idea] Reduction turns an unbounded input into f in [0, 1), where 2^f lies in [1, 2): a smooth function on a
        short interval, easy for a polynomial. 2^n is applied by adding n to the result's exponent field (free in
        hardware). With segments > 1 the polynomial is piecewise (a table of coefficients indexed by the top bits
        of f) -- the "table + low-degree polynomial" structure of GPU special-function units.
        The reduction itself has an error: y = x log2(e) is rounded to float32, and an error of half an ulp of y
        (2^-19 for |y| near 30) becomes a relative error of the result. Cody-Waite reduction avoids it by computing
        f = (x - n ln2_hi - n ln2_lo) log2(e), where ln2_hi has so few bits that n ln2_hi is exact: two more FMAs.
    [Args]
        segments   : pieces of [0, 1) (1 = a single polynomial whose constants are hard-wired: no table)
        degree     : polynomial degree for 2^f (0 = a pure table of 2^f values)
        fit        : "cheb" (Chebyshev interpolation, near-minimax), "remez" (minimax relative error) or "taylor"
        cody_waite : use the two-constant reduction (accurate to ~float32 rounding instead of ~2^-19 at |x| ~ 30)
    [Returns] Approx; cost = 1 multiply (x log2 e) + 1 add (y - n) + `degree` FMAs (+ 2 FMAs for Cody-Waite;
        + the table if segments > 1)
    [Edge cases] n < -126 flushes to 0 (no subnormals); n > 127 gives inf; NaN propagates. If the float32 product
        puts n one off near an integer, f lands just outside [0, 1); the polynomial of the edge segment is then
        evaluated slightly outside its interval (accurate, since it is smooth).
    """
    coeffs = f32(_pow2_coeffs(segments, degree, fit))
    ln2_hi, ln2_lo = F32(0.693145751953125), F32(1.4286068203094172e-06)       # ln2_hi has 16 significant bits

    def fn(x):
        x = f32(x)
        with np.errstate(over="ignore", invalid="ignore"):
            y = x * LOG2E                                        # float32 multiply: the reduction step
            n = np.floor(y)
            if cody_waite:
                r = (x - n * ln2_hi).astype(F32)
                r = (r - n * ln2_lo).astype(F32)
                frac = (r * LOG2E).astype(F32)
            else:
                frac = (y - n).astype(F32)
            idx = np.clip(np.floor(np.nan_to_num(frac) * segments).astype(np.int64), 0, segments - 1)
            t = (frac - f32(idx / segments)).astype(F32)
            p = horner32(coeffs[idx], t)
            n = np.nan_to_num(n, nan=0.0, posinf=1000, neginf=-1000)
            out = np.ldexp(p, np.clip(n, -1000, 1000).astype(np.int32))
            out = np.where(n < -126, F32(0), out)            # flush to zero: no subnormal results
        return f32(np.where(np.isnan(x), np.nan, out))

    table = segments > 1 or degree == 0
    method = "table" if degree == 0 else fit
    label = name or (f"exp: 2^f deg-{degree}" + (f" x {segments} seg" if segments > 1 else "") + f" ({method}"
                     + (", Cody-Waite)" if cody_waite else ")"))
    return Approx(label, fn, entries=segments * (degree + 1) if table else 0, reads=degree + 1 if table else 0,
                  mul=1, add=1, fma=degree + (2 if cody_waite else 0))


def exp_schraudolph(correction=True):
    """
    Schraudolph's exp (Neural Computation 1999): write a x + b straight into the bits of a float.

    [Idea] A float32 with exponent field E and mantissa bits M has value 2^(E-127) (1 + M / 2^23). Computing the
        INTEGER i = 2^23 (x log2 e + 127) and reinterpreting its bits as a float gives 2^n (1 + f): exactly the
        range reduction of exp_rr with the linear "polynomial" 2^f ~ 1 + f, at the cost of one multiply-add.
        Relative error: up to +6.1% (1 + f vs 2^f). Subtracting a constant from i (correction=True) centres the
        error: the minimax shift is 0.0356 (298,650 in units of 2^-23), giving about +-3.6%. (Schraudolph chose a
        somewhat larger shift, which minimizes the RMS error instead of the maximum.)
    [Returns] Approx (1 FMA, no table)
    [Edge cases] Valid for x in about [-87, 88]; outside, the integer leaves the exponent range -- we clamp the
        input to that interval.
    """
    a = F32(2 ** 23 / math.log(2))
    b = F32(127 * 2 ** 23 - (298650 if correction else 0))

    def fn(x):
        x = np.clip(f32(x), F32(-87), F32(88))
        i = (a * x + b).astype(np.int32)
        return i.view(F32)

    return Approx("exp: Schraudolph bit trick" + (" (corrected)" if correction else ""), fn, fma=1)


# =====================================================================================================================
# Reciprocal and reciprocal square root
# =====================================================================================================================

def _split(x):
    """x = m * 2^e with m in [1, 2): returns (m float32, e int)."""
    m, e = np.frexp(x)
    return (m * 2).astype(F32), (e - 1).astype(np.int32)


def recip_nr(segments=16, degree=0, iters=1):
    """
    1/x as seed + Newton-Raphson: write |x| = m 2^e, look up r ~ 1/m in a table, refine r <- r (2 - m r).

    [Idea] If r = (1 + eps) / m, one Newton step gives r (2 - m r) = (1 - eps^2) / m: the relative error is
        SQUARED, so the number of correct bits doubles. A 16-entry table (about 5 bits) becomes ~10 bits after one
        step and ~20 after two. Each step costs two multiplies and one subtraction -- trading table size for
        latency. 2^-e is again an exponent subtraction.
    [Args] segments: table entries over m in [1, 2); degree: 0 (constants) or 1 (linear seed); iters: Newton steps
    [Returns] Approx
    [Edge cases] x = 0 -> +-inf; the sign of x is restored at the end; NaN propagates.
    """
    coeffs = f32(fit_segments(lambda m: 1 / m, 1.0, 2.0, segments, degree, relative=True))

    def fn(x):
        x = f32(x)
        a = np.abs(x)
        with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
            m, e = _split(a)
            r = _segment_eval(m, coeffs, 1.0, 2.0)
            for _ in range(iters):
                r = r * (F32(2) - m * r)
            out = np.ldexp(r, -e)
        out = np.where(a == 0, np.inf, out)
        out = np.where(np.isinf(a), 0.0, out)
        return f32(np.copysign(out, x))

    return Approx(f"recip: {segments}-entry deg-{degree} seed + {iters} NR", fn, entries=segments * (degree + 1),
                  reads=degree + 1, fma=degree, mul=2 * iters, add=iters)


def rsqrt_nr(segments=16, degree=0, iters=1):
    """
    1/sqrt(x) as seed + Newton-Raphson: x = m 4^k with m in [1, 4); r ~ 1/sqrt(m) from a table;
    refine r <- r (1.5 - 0.5 m r^2).

    [Idea] As for the reciprocal, each Newton step roughly squares the relative error (it becomes ~1.5 eps^2).
        The exponent is made EVEN so that sqrt(4^k) = 2^k stays a pure exponent operation; the table therefore
        covers m in [1, 4). 0.5 m is an exponent decrement (free).
    [Args] segments: table entries over [1, 4); degree: 0 or 1; iters: Newton steps
    [Returns] Approx (Newton step: 3 multiplies + 1 subtraction)
    [Edge cases] x = 0 -> inf; x < 0 -> NaN; inf -> 0.
    """
    coeffs = f32(fit_segments(lambda m: 1 / np.sqrt(m), 1.0, 4.0, segments, degree, relative=True))

    def fn(x):
        x = f32(x)
        with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
            m, e = _split(np.abs(x))
            odd = (e % 2) != 0
            m = np.where(odd, m * F32(2), m).astype(F32)
            e = np.where(odd, e - 1, e)
            r = _segment_eval(m, coeffs, 1.0, 4.0)
            half = (m * F32(0.5)).astype(F32)
            for _ in range(iters):
                r = r * (F32(1.5) - half * (r * r))
            out = np.ldexp(r, -(e // 2))
        out = np.where(x == 0, np.inf, out)
        out = np.where(np.isinf(x), 0.0, out)
        return f32(np.where(x < 0, np.nan, out))

    return Approx(f"rsqrt: {segments}-entry deg-{degree} seed + {iters} NR", fn, entries=segments * (degree + 1),
                  reads=degree + 1, fma=degree, mul=3 * iters, add=iters)


def rsqrt_magic(iters=1):
    """
    The "fast inverse square root" of Quake III (1999): seed = 0x5f3759df - (bits(x) >> 1), then Newton steps.

    [Idea] Shifting a float's bit pattern right by one halves its exponent (a crude sqrt of the log); subtracting
        from a magic constant negates it and corrects the mantissa on average. The seed has a relative error of
        about 3.4% with NO table; one Newton step brings it to ~0.17%.
    [Returns] Approx (seed: one integer subtract, counted as an add; Newton: 3 multiplies + 1 subtraction each)
    [Edge cases] Positive normal inputs only (0, negatives and inf are not handled -- as in the original).
    """
    def fn(x):
        x = f32(x)
        i = np.int32(0x5F3759DF) - (x.view(np.int32) >> 1)
        r = i.view(F32)
        half = (x * F32(0.5)).astype(F32)
        for _ in range(iters):
            r = r * (F32(1.5) - half * (r * r))
        return r

    return Approx(f"rsqrt: magic constant + {iters} NR", fn, add=1 + iters, mul=3 * iters)


# =====================================================================================================================
# Activations built from the pieces
# =====================================================================================================================

def sigmoid_from(exp_a, recip_a, name=None):
    """
    sigmoid(x) = 1 / (1 + exp(-x)) from an exp and a reciprocal approximation.

    [Edge cases] For x < -88, exp(-x) overflows to inf and 1 / inf = 0: the correct limit, with no special case.
    """
    def fn(x):
        x = f32(x)
        with np.errstate(over="ignore"):
            return recip_a(F32(1) + exp_a(-x))

    return combine(name or f"sigmoid via {exp_a.name} / {recip_a.name}", fn, exp_a, recip_a, add=1)


def silu_from(sig_a, name=None):
    """SiLU(x) = x * sigmoid(x) from a sigmoid approximation (one extra multiply)."""
    def fn(x):
        x = f32(x)
        return (x * sig_a(x)).astype(F32)

    return combine(name or f"silu = x * ({sig_a.name})", fn, sig_a, mul=1)


def gelu_tanh(tanh_fn=None):
    """
    The tanh form of GELU (Hendrycks & Gimpel 2016; used by GPT-2):
        0.5 x (1 + tanh( sqrt(2/pi) (x + 0.044715 x^3) )).

    [Args] tanh_fn: a tanh implementation (default: exact tanh, i.e. only the FORMULA's error is measured)
    [Returns] Approx counting the polynomial part (x^2, FMA, two multiplies, final FMA and multiply) and one
        tanh as an exp + reciprocal pair would cost if no tanh table exists (not modeled: we count 0 for it)
    """
    tanh_fn = tanh_fn or (lambda v: f32(np.tanh(np.asarray(v, dtype=np.float64))))
    k = F32(math.sqrt(2 / math.pi))

    def fn(x):
        x = f32(x)
        u = (k * x) * (F32(1) + F32(0.044715) * (x * x))
        return (F32(0.5) * x * (F32(1) + tanh_fn(u))).astype(F32)

    return Approx("gelu: tanh formula (exact tanh)", fn, mul=4, fma=2)


def gelu_sigmoid():
    """GELU ~ x * sigmoid(1.702 x) (Hendrycks & Gimpel's cheaper approximation); exact sigmoid."""
    def fn(x):
        x = f32(x)
        return (x * f32(sigmoid_ref(F32(1.702) * x))).astype(F32)

    return Approx("gelu: x * sigmoid(1.702 x) (exact sigmoid)", fn, mul=2)


def gelu_piecewise(segments, degree, lo=-8.0, hi=8.0):
    """GELU from a piecewise polynomial on [lo, hi]; 0 below lo and x above hi (GELU's limits)."""
    def outside(x, y):
        return np.where(x < lo, 0.0, np.where(x > hi, x, y))

    return piecewise(gelu_ref, lo, hi, segments, degree, name=f"gelu: deg-{degree} x {segments} seg on [{lo:g},{hi:g}]",
                     outside=outside)


# =====================================================================================================================
# Softmax
# =====================================================================================================================

def softmax(x, exp_fn=None, recip_fn=None, subtract_max=True, axis=-1):
    """
    Row softmax in float32 with pluggable exp and reciprocal, the way a vector unit computes it:
        m = max(x); e = exp(x - m); s = sum(e); y = e * (1 / s).

    [Idea] Subtracting the row maximum makes every exponent <= 0, so exp never overflows and the largest term is
        exactly 1; it does not change the result mathematically (exp(x - m) / sum exp(x - m) = exp(x) / sum exp(x)).
        Multiplying by one reciprocal is cheaper than n divisions.
    [Args] x: array; exp_fn / recip_fn: approximations (default exact float32); subtract_max: set False to see
        overflow; axis: the softmax axis
    [Returns] float32 array of probabilities
    [Edge cases] Without max subtraction, rows with large entries overflow exp to inf and give NaN (inf / inf).
        The sum is accumulated in float64 and rounded once (an idealization of a float32 tree reduction).
    """
    x = f32(x)
    exp_fn = exp_fn or (lambda v: f32(exp_ref(v)))
    recip_fn = recip_fn or (lambda v: f32(1.0 / np.asarray(v, dtype=np.float64)))
    if subtract_max:
        x = (x - x.max(axis=axis, keepdims=True)).astype(F32)
    with np.errstate(over="ignore", invalid="ignore"):
        e = exp_fn(x)
        s = f32(e.astype(np.float64).sum(axis=axis, keepdims=True))
        return (e * recip_fn(s)).astype(F32)


# =====================================================================================================================
# Self-test
# =====================================================================================================================

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    # exp: range reduction + a degree-5 polynomial is accurate to float32 level on the softmax range
    xs = f32(np.linspace(-10, 0, 200001))               # float32 inputs: the reference sees the same numbers
    e5 = exp_rr(degree=5, fit="remez")
    assert rel_err(e5(xs), exp_ref(xs)) < 1e-6, rel_err(e5(xs), exp_ref(xs))
    # Cody-Waite reduction removes the reduction error floor on a wide range
    xw = f32(np.linspace(-80, 0, 200001))
    assert rel_err(exp_rr(1, 6, "remez", cody_waite=True)(xw), exp_ref(xw)) < 3e-7
    assert rel_err(exp_rr(1, 6, "remez")(xw), exp_ref(xw)) > 2e-6
    # minimax beats Chebyshev interpolation beats Taylor, at the same degree
    t = f32(np.linspace(-20, 0, 100001))
    errs = {fit: rel_err(exp_rr(degree=2, fit=fit)(t), exp_ref(t)) for fit in ("taylor", "cheb", "remez")}
    assert errs["remez"] < errs["cheb"] < errs["taylor"], errs
    # Schraudolph: ~6% uncorrected, ~3.6% with the minimax shift
    assert 0.055 < rel_err(exp_schraudolph(False)(t), exp_ref(t)) < 0.065
    assert rel_err(exp_schraudolph(True)(t), exp_ref(t)) < 0.037
    # Newton-Raphson doubles the bits: 16-entry table ~5 bits, +1 step ~10, +2 steps ~20
    x = f32(np.exp(rng.uniform(-20, 20, 100000)))
    b = [bits(rel_err(recip_nr(16, 0, i)(x), 1 / x.astype(np.float64))) for i in range(3)]
    assert b[0] > 4.5 and b[1] > 2 * b[0] - 1.5 and b[2] > 19, b
    assert rel_err(recip_nr(16, 0, 1)(-x), -1 / x.astype(np.float64)) == rel_err(recip_nr(16, 0, 1)(x), 1 / x.astype(np.float64))
    r = rsqrt_nr(16, 0, 2)                                   # 4.3% seed -> 0.28% -> 1.2e-5 (error ~ 1.5 eps^2)
    assert rel_err(r(x), 1 / np.sqrt(x.astype(np.float64))) < 2e-5
    assert rel_err(rsqrt_nr(64, 1, 1)(x), 1 / np.sqrt(x.astype(np.float64))) < 3e-7
    assert np.isnan(r(f32([-1.0]))[0]) and np.isinf(r(f32([0.0]))[0])
    m0 = rel_err(rsqrt_magic(0)(x), 1 / np.sqrt(x.astype(np.float64)))
    m1 = rel_err(rsqrt_magic(1)(x), 1 / np.sqrt(x.astype(np.float64)))
    assert 0.03 < m0 < 0.036 and 0.0015 < m1 < 0.0019, (m0, m1)
    # piecewise GELU: error falls with segments and degree
    g = np.linspace(-10, 10, 40001)
    e1 = abs_err(gelu_piecewise(16, 1)(g), gelu_ref(g))
    e2 = abs_err(gelu_piecewise(64, 1)(g), gelu_ref(g))
    e3 = abs_err(gelu_piecewise(16, 2)(g), gelu_ref(g))
    assert e2 < e1 / 10 and e3 < e1 / 3, (e1, e2, e3)
    # softmax with an exact exp matches float64; without max subtraction it overflows
    z = rng.normal(0, 3, (8, 100))
    ref = np.exp(z - z.max(1, keepdims=True))
    ref /= ref.sum(1, keepdims=True)
    assert abs_err(softmax(z), ref) < 1e-6
    assert np.isnan(softmax(z + 100, subtract_max=False)).any()
    # costs are consistent
    assert exp_rr(1, 3).entries == 0 and exp_rr(8, 2).entries == 24 and exp_rr(1, 3).latency() == 3 + 4 + 12
    print("approx.py self-test passed")
    for a in (exp_rr(1, 3), exp_rr(16, 1), recip_nr(16, 0, 2), rsqrt_nr(64, 1, 1)):
        print(f"  {a.name:40s} area {a.area_um2():8,.0f} um^2  energy {a.energy_pj():5.1f} pJ  latency {a.latency():3d}")
