{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Acceleration with Numba\n",
    "\n",
    "We explore how the computation of cost functions can be dramatically accelerated with numba's JIT compiler.\n",
    "\n",
    "The run-time of iminuit is usually dominated by the execution time of the cost function. To get good performance, it recommended to use array arthimetic and scipy and numpy functions in the body of the cost function. Python loops should be avoided, but if they are unavoidable, [Numba](https://numba.pydata.org/) can help. Numba can also parallelize numerical calculations to make full use of multi-core CPUs and even do computations on the GPU.\n",
    "\n",
    "Note: This tutorial shows how one can generate faster pdfs with Numba. Before you start to write your own pdf, please check whether one is already implemented in the [numba_stats library](https://github.com/HDembinski/numba-stats). If you have a pdf that is not included there, please consider contributing it to numba_stats."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install matplotlib numpy numba scipy iminuit\n",
    "from iminuit import Minuit\n",
    "import numpy as np\n",
    "import numba as nb\n",
    "import math\n",
    "from scipy.stats import expon, norm\n",
    "from matplotlib import pyplot as plt\n",
    "from argparse import Namespace"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The standard fit in particle physics is the fit of a peak over some smooth background. We generate a Gaussian peak over exponential background, using scipy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(1)  # fix seed\n",
    "\n",
    "# true parameters for signal and background\n",
    "truth = Namespace(n_sig=2000, f_bkg=10, sig=(5.0, 0.5), bkg=(0.0, 4.0))\n",
    "n_bkg = truth.n_sig * truth.f_bkg\n",
    "\n",
    "# make a data set\n",
    "x = np.empty(truth.n_sig + n_bkg)\n",
    "\n",
    "# fill m variables\n",
    "x[: truth.n_sig] = norm(*truth.sig).rvs(truth.n_sig)\n",
    "x[truth.n_sig :] = expon(*truth.bkg).rvs(n_bkg)\n",
    "\n",
    "# cut a range in x\n",
    "xrange = np.array((1.0, 9.0))\n",
    "ma = (xrange[0] < x) & (x < xrange[1])\n",
    "x = x[ma]\n",
    "\n",
    "plt.hist(\n",
    "    (x[truth.n_sig :], x[: truth.n_sig]),\n",
    "    bins=50,\n",
    "    stacked=True,\n",
    "    label=(\"background\", \"signal\"),\n",
    ")\n",
    "plt.xlabel(\"x\")\n",
    "plt.legend();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ideal starting values for iminuit\n",
    "start = np.array((truth.n_sig, n_bkg, truth.sig[0], truth.sig[1], truth.bkg[1]))\n",
    "\n",
    "\n",
    "# iminuit instance factory, will be called a lot in the benchmarks blow\n",
    "def m_init(fcn):\n",
    "    m = Minuit(fcn, start, name=(\"ns\", \"nb\", \"mu\", \"sigma\", \"lambd\"))\n",
    "    m.limits = ((0, None), (0, None), None, (0, None), (0, None))\n",
    "    m.errordef = Minuit.LIKELIHOOD\n",
    "    return m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# extended likelihood (https://doi.org/10.1016/0168-9002(90)91334-8)\n",
    "# this version uses numpy and scipy and array arithmetic\n",
    "def nll(par):\n",
    "    n_sig, n_bkg, mu, sigma, lambd = par\n",
    "    s = norm(mu, sigma)\n",
    "    b = expon(0, lambd)\n",
    "    # normalisation factors are needed for pdfs, since x range is restricted\n",
    "    sn = s.cdf(xrange)\n",
    "    bn = b.cdf(xrange)\n",
    "    sn = sn[1] - sn[0]\n",
    "    bn = bn[1] - bn[0]\n",
    "    return (n_sig + n_bkg) - np.sum(\n",
    "        np.log(s.pdf(x) / sn * n_sig + b.pdf(x) / bn * n_bkg)\n",
    "    )\n",
    "\n",
    "\n",
    "nll(start)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%timeit -r 3 -n 1\n",
    "m = m_init(nll)  # setup time is negligible\n",
    "m.migrad();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see whether we can beat that. The code above is already pretty fast, because numpy and scipy routines are fast, and we spend most of the time in those. But these implementations do not parallelize the execution and are not optimised for this particular CPU, unlike numba-jitted functions.\n",
    "\n",
    "To use numba, in theory we just need to put the `njit` decorator on top of the function, but often that doesn't work out of the box. numba understands many numpy functions, but no scipy. We must evaluate the code that uses scipy in 'object mode', which is numba-speak for calling into the Python interpreter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# first attempt to use numba\n",
    "@nb.njit(parallel=True)\n",
    "def nll(par):\n",
    "    n_sig, n_bkg, mu, sigma, lambd = par\n",
    "    with nb.objmode(spdf=\"float64[:]\", bpdf=\"float64[:]\", sn=\"float64\", bn=\"float64\"):\n",
    "        s = norm(mu, sigma)\n",
    "        b = expon(0, lambd)\n",
    "        # normalisation factors are needed for pdfs, since x range is restricted\n",
    "        sn = np.diff(s.cdf(xrange))[0]\n",
    "        bn = np.diff(b.cdf(xrange))[0]\n",
    "        spdf = s.pdf(x)\n",
    "        bpdf = b.pdf(x)\n",
    "    no = n_sig + n_bkg\n",
    "    return no - np.sum(np.log(spdf / sn * n_sig + bpdf / bn * n_bkg))\n",
    "\n",
    "\n",
    "nll(start)  # test and warm-up JIT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%timeit -r 3 -n 1 m = m_init(nll)\n",
    "m.migrad()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is even a bit slower. :( Let's break the original function down by parts to see why."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# let's time the body of the function\n",
    "n_sig, n_bkg, mu, sigma, lambd = start\n",
    "s = norm(mu, sigma)\n",
    "b = expon(0, lambd)\n",
    "# normalisation factors are needed for pdfs, since x range is restricted\n",
    "sn = np.diff(s.cdf(xrange))[0]\n",
    "bn = np.diff(b.cdf(xrange))[0]\n",
    "spdf = s.pdf(x)\n",
    "bpdf = b.pdf(x)\n",
    "\n",
    "%timeit -r 3 -n 100 norm(*start[2:4]).pdf(x)\n",
    "%timeit -r 3 -n 500 expon(0, start[4]).pdf(x)\n",
    "%timeit -r 3 -n 1000 n_sig + n_bkg - np.sum(np.log(spdf / sn * n_sig + bpdf / bn * n_bkg))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most of the time is spend in `norm` and `expon` which numba could not accelerate and the total time is dominated by the slowest part.\n",
    "\n",
    "This, unfortunately, means we have to do much more manual work to make the function faster, since we have to replace the scipy routines with Python code that numba can accelerate and run in parallel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# when parallel is enabled, also enable associative math\n",
    "kwd = {\"parallel\": True, \"fastmath\": {\"reassoc\", \"contract\", \"arcp\"}}\n",
    "\n",
    "\n",
    "@nb.njit(**kwd)\n",
    "def sum_log(fs, spdf, fb, bpdf):\n",
    "    return np.sum(np.log(fs * spdf + fb * bpdf))\n",
    "\n",
    "\n",
    "@nb.njit(**kwd)\n",
    "def norm_pdf(x, mu, sigma):\n",
    "    invs = 1.0 / sigma\n",
    "    z = (x - mu) * invs\n",
    "    invnorm = 1 / np.sqrt(2 * np.pi) * invs\n",
    "    return np.exp(-0.5 * z ** 2) * invnorm\n",
    "\n",
    "\n",
    "@nb.njit(**kwd)\n",
    "def nb_erf(x):\n",
    "    y = np.empty_like(x)\n",
    "    for i in nb.prange(len(x)):\n",
    "        y[i] = math.erf(x[i])\n",
    "    return y\n",
    "\n",
    "\n",
    "@nb.njit(**kwd)\n",
    "def norm_cdf(x, mu, sigma):\n",
    "    invs = 1.0 / (sigma * np.sqrt(2))\n",
    "    z = (x - mu) * invs\n",
    "    return 0.5 * (1 + nb_erf(z))\n",
    "\n",
    "\n",
    "@nb.njit(**kwd)\n",
    "def expon_pdf(x, lambd):\n",
    "    inv_lambd = 1.0 / lambd\n",
    "    return inv_lambd * np.exp(-inv_lambd * x)\n",
    "\n",
    "\n",
    "@nb.njit(**kwd)\n",
    "def expon_cdf(x, lambd):\n",
    "    inv_lambd = 1.0 / lambd\n",
    "    return 1.0 - np.exp(-inv_lambd * x)\n",
    "\n",
    "\n",
    "def nll(par):\n",
    "    n_sig, n_bkg, mu, sigma, lambd = par\n",
    "    # normalisation factors are needed for pdfs, since x range is restricted\n",
    "    sn = norm_cdf(xrange, mu, sigma)\n",
    "    bn = expon_cdf(xrange, lambd)\n",
    "    sn = sn[1] - sn[0]\n",
    "    bn = bn[1] - bn[0]\n",
    "    spdf = norm_pdf(x, mu, sigma)\n",
    "    bpdf = expon_pdf(x, lambd)\n",
    "    no = n_sig + n_bkg\n",
    "    return no - sum_log(n_sig / sn, spdf, n_bkg / bn, bpdf)\n",
    "\n",
    "\n",
    "nll(start)  # test and warm-up JIT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see how well these versions do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%timeit -r 5 -n 100 norm_pdf(x, *start[2:4])\n",
    "%timeit -r 5 -n 500 expon_pdf(x, start[4])\n",
    "%timeit -r 5 -n 1000 sum_log(n_sig / sn, spdf, n_bkg / bn, bpdf)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Only a minor improvement for `sum_log`, but the pdf calculation was drastically accelerated. Since this was the bottleneck before, we expect also Migrad to finish faster now."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%timeit -r 3 -n 1\n",
    "m = m_init(nll)  # setup time is negligible\n",
    "m.migrad();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Success! We managed to get a big speed improvement over the initial code. This is impressive, but it cost us a lot of developer time. This is not always a good trade-off, especially if you consider that library routines are heavily tested, while you always need to test your own code in addition to writing it.\n",
    "\n",
    "By putting these faster functions into a library, however, we would only have to pay the developer cost once. You can find those in the [numba_stats library](https://github.com/HDembinski/numba-stats).\n",
    "\n",
    "Try to compile the functions again with `parallel=False` to see how much of the speed increase came from the parallelization and how much from the generally optimized code that `numba` generated for our specific CPU. On my machine, the gain was entirely due to numba.\n",
    "\n",
    "In general, it is good advice to not automatically add `parallel=True`, because this comes with an overhead of breaking data into chunks, copy chunks to the individual CPUs and finally merging everything back together. For large arrays, this overhead is negligible, but for small arrays, it can be a net loss.\n",
    "\n",
    "So why is `numba` so fast even without parallelization? We can look at the assembly code generated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for signature, code in norm_pdf.inspect_asm().items():\n",
    "    print(f\"signature: {signature}\\n{'-'*(len(str(signature)) + 11)}\\n{code[:1000]}\\n[...]\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This code section is very long, but the assembly grammar is very simple. Constants starts with `.` and `SOMETHING:` is a jump label for the assembly equivalent of `goto`. Everything else is an instruction with its name on the left and the arguments are on the right.\n",
    "\n",
    "The interesting commands are those that end with `pd` and `ps`, those are SIMD instructions that operate on up to eight doubles at once. This is where the speed comes from."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "from collections import Counter\n",
    "\n",
    "for signature, code in norm_pdf.inspect_asm().items():\n",
    "    print(f\"signature: {signature}\\n{'-'*(len(str(signature)) + 11)}\")\n",
    "    simd_instructions = re.findall(\" *([a-z]+p[ds])\\t*%\", code)\n",
    "    c = Counter(simd_instructions)\n",
    "    print(\"SIMD instructions\")\n",
    "    for k, v in c.items():\n",
    "        print(f\"{k:10}: {v:5}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `mov`: copy values from memory to CPU registers and back\n",
    "- `sub`: subtract numbers\n",
    "- `mul`: multiply numbers\n",
    "- `xor`: binary xor, the compiler often inserts these to zero out memory\n",
    "\n",
    "You can google all the other commands.\n",
    "\n",
    "There is a lot of repetition, because the optimizer partially unrolled some loops to make them faster. Using unrolled loops only works if the remaining chunk of data is large enough. Since the compiler does not know the length of the incoming array, it also generates sections which handle shorter chunks and all the code to select which section to use. Finally, there is some code which does the translation from and to Python objects with corresponding error handling.\n",
    "\n",
    "We don't need to write SIMD instructions by hand, the optimizer does it for us and in a very sophisticated way."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.13 ('venv': venv)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  },
  "vscode": {
   "interpreter": {
    "hash": "bdbf20ff2e92a3ae3002db8b02bd1dd1b287e934c884beb29a73dced9dbd0fa3"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
