{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4ba25110",
   "metadata": {},
   "source": [
    "# Part 9. Compilation and parallel computing\n",
    "\n",
    "The ladder of laziness from {doc}`part 8 <p8_sciaga>` ends with two rungs that we reach for only\n",
    "at the very end. **Compilation** turns a Python loop into the processor’s machine code.\n",
    "**Parallel computing** divides the work among several processor cores. Both rungs come at\n",
    "a price. Compilation takes time, and it works only for numbers and arrays, not for arbitrary\n",
    "Python objects. Parallel computing requires starting additional threads or processes and dividing\n",
    "up the work, and the speedup is at most the number of cores. We use the Numba compiler and the\n",
    "`concurrent.futures` module from the standard library. The examples are familiar: the double loop\n",
    "from {doc}`part 1 <p1_pomiar>`, the Collatz steps from Lecture 1, Lab 8, and\n",
    "{doc}`part 2 <p2_algorytm>`, Gaussian elimination from Lecture 6 and {doc}`part 6 <p6_scipy>`,\n",
    "and the summation of `float` numbers from Lecture 1 and {doc}`part 4 <p4_biblioteka>`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "270771a7",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.\n",
    "import platform\n",
    "import statistics\n",
    "import subprocess\n",
    "import sys\n",
    "import textwrap\n",
    "import timeit\n",
    "from importlib.metadata import version\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter\n",
    "\n",
    "INDYGO, BURSZTYN, ZIELEN = \"#4f46e5\", \"#d97706\", \"#059669\"\n",
    "SZARY, TUSZ, SIATKA = \"#94a3b8\", \"#334155\", \"#e2e8f0\"\n",
    "JEDNOSTKI = ((\"s\", 1.0), (\"ms\", 1e-3), (\"µs\", 1e-6), (\"ns\", 1e-9))\n",
    "\n",
    "\n",
    "def zmierz(f, *args, cel=0.02, proby=7):\n",
    "    \"\"\"Mediana czasu jednego wywołania f(*args), w sekundach.\n",
    "\n",
    "    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo\n",
    "    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.\n",
    "    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne\n",
    "    programy.\n",
    "    \"\"\"\n",
    "    zegar = timeit.Timer(lambda: f(*args))\n",
    "    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena\n",
    "    if t > cel:                         # wolna funkcja: trzy wywołania\n",
    "        return statistics.median(zegar.repeat(repeat=3, number=1))\n",
    "    n = 1\n",
    "    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją\n",
    "        n *= 10\n",
    "        t = zegar.timeit(number=n)\n",
    "    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s\n",
    "    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n\n",
    "\n",
    "\n",
    "def czas(s):\n",
    "    \"\"\"Czas w sekundach jako napis z jednostką, np. 1.23 ms.\"\"\"\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if s >= 0.9995 * skala or jednostka == \"ns\":\n",
    "            v = s / skala\n",
    "            if v >= 99.95:\n",
    "                return f\"{v:.0f} {jednostka}\"\n",
    "            return f\"{v:#.3g} {jednostka}\"\n",
    "\n",
    "\n",
    "def krotnosc(r):\n",
    "    \"\"\"Iloraz czasów jako napis: 340×, 2.5×, 0.81×.\"\"\"\n",
    "    if r >= 10:\n",
    "        return f\"{r:.0f}×\"\n",
    "    return f\"{r:.1f}×\" if r >= 1 else f\"{r:.2f}×\"\n",
    "\n",
    "\n",
    "def porownaj(warianty, *args, zgodne=None):\n",
    "    \"\"\"Mierzy warianty (nazwa → funkcja) na tych samych danych.\n",
    "\n",
    "    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem\n",
    "    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to\n",
    "    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas\n",
    "    danego. Zwraca słownik czasów.\n",
    "    \"\"\"\n",
    "    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}\n",
    "    wzorzec = next(iter(wyniki.values()))\n",
    "    for nazwa, w in wyniki.items():\n",
    "        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):\n",
    "            raise AssertionError(f\"wariant „{nazwa}” daje inny wynik\")\n",
    "    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}\n",
    "    baza = next(iter(czasy.values()))\n",
    "    szer = max(len(nazwa) for nazwa in czasy)\n",
    "    wiersze = [f\"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}\"]\n",
    "    for nazwa, t in czasy.items():\n",
    "        wiersze.append(f\"{nazwa:{szer}}  {czas(t):>9}\"\n",
    "                       f\"  {krotnosc(baza / t):>14}\")\n",
    "    print(\"\\n\".join(wiersze))\n",
    "    return czasy\n",
    "\n",
    "\n",
    "def srodowisko(*biblioteki):\n",
    "    \"\"\"Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki.\"\"\"\n",
    "    if sys.platform == \"darwin\":\n",
    "        procesor = subprocess.run(\n",
    "            [\"sysctl\", \"-n\", \"machdep.cpu.brand_string\"],\n",
    "            capture_output=True, text=True).stdout.strip()\n",
    "        system = f\"macOS {platform.mac_ver()[0]}\"\n",
    "    else:\n",
    "        procesor = platform.processor()\n",
    "        system = f\"{platform.system()} {platform.release()}\"\n",
    "    opis = [procesor or platform.machine(), system,\n",
    "            f\"Python {platform.python_version()}\"]\n",
    "    opis += [f\"{b} {version(b)}\" for b in biblioteki]\n",
    "    print(textwrap.fill(\"Pomiary: \" + \", \".join(opis), width=79,\n",
    "                        subsequent_indent=\"  \"))\n",
    "\n",
    "\n",
    "def upewnij(warunek, tresc):\n",
    "    \"\"\"Pilnuje zdań z tekstu rozdziału.\n",
    "\n",
    "    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.\n",
    "    \"\"\"\n",
    "    if not warunek:\n",
    "        raise AssertionError(f\"Tekst rozdziału twierdzi: {tresc}. \"\n",
    "                             \"Pomiar temu przeczy.\")\n",
    "\n",
    "\n",
    "def _os_czasu(v, _):\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if v >= 0.9995 * skala:\n",
    "            return f\"{v / skala:.0f} {jednostka}\"\n",
    "    return f\"{v / 1e-9:g} ns\"\n",
    "\n",
    "\n",
    "def wykres_czasow(czasy, tytul):\n",
    "    \"\"\"Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony.\"\"\"\n",
    "    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze\n",
    "    t = [czasy[nazwa] for nazwa in nazwy]\n",
    "    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))\n",
    "    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors=\"white\",\n",
    "               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])\n",
    "    for i, v in enumerate(t):\n",
    "        ax.annotate(czas(v), (v, i), xytext=(9, 0), va=\"center\",\n",
    "                    textcoords=\"offset points\", fontsize=9, color=TUSZ)\n",
    "    ax.set_yticks(range(len(nazwy)), nazwy)\n",
    "    ax.set_xscale(\"log\")\n",
    "    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety\n",
    "    ax.xaxis.set_major_locator(LogLocator(base=10))\n",
    "    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.grid(axis=\"x\", color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\", \"left\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.tick_params(axis=\"y\", length=0)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def wykres_skalowania(rozmiary, serie, tytul, opis_x=\"n\"):\n",
    "    \"\"\"Czas w zależności od rozmiaru danych, obie osie logarytmiczne.\"\"\"\n",
    "    fig, ax = plt.subplots(figsize=(8, 4))\n",
    "    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), \"osD\")\n",
    "    for (nazwa, czasy_serii), kolor, znak in style:\n",
    "        ax.loglog(rozmiary, czasy_serii, \"-\", marker=znak, color=kolor,\n",
    "                  lw=2, ms=6, label=nazwa)\n",
    "    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.yaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.set_xlabel(opis_x)\n",
    "    ax.grid(color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.legend(loc=\"best\", frameon=False, fontsize=9)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c6aaad7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import multiprocessing\n",
    "import os\n",
    "import pathlib\n",
    "import platform\n",
    "import subprocess\n",
    "import sys\n",
    "import tempfile\n",
    "import textwrap\n",
    "import time\n",
    "from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n",
    "from fractions import Fraction\n",
    "\n",
    "import numba\n",
    "import numpy as np\n",
    "from numba import njit, prange\n",
    "from numba.core.errors import TypingError\n",
    "\n",
    "srodowisko(\"numpy\", \"numba\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb877a66",
   "metadata": {},
   "source": [
    "Parallel computing depends on how many cores the processor has. Apple computers have two kinds of\n",
    "cores: *performance* cores and slower *efficiency* cores. We read this off with the system command\n",
    "`sysctl`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d873c4a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sysctl(klucz):\n",
    "    \"\"\"Parametr systemu macOS jako napis (pusty, gdy go nie ma).\"\"\"\n",
    "    if sys.platform != \"darwin\":\n",
    "        return \"\"\n",
    "    wynik = subprocess.run([\"sysctl\", \"-n\", klucz], capture_output=True,\n",
    "                           text=True)\n",
    "    return wynik.stdout.strip()\n",
    "\n",
    "\n",
    "wydajne = sysctl(\"hw.perflevel0.physicalcpu\")\n",
    "energooszczedne = sysctl(\"hw.perflevel1.physicalcpu\")\n",
    "print(\"rdzenie procesora:\", os.cpu_count())\n",
    "if wydajne and energooszczedne:\n",
    "    print(f\"  w tym wydajne: {wydajne}, energooszczędne: {energooszczedne}\")\n",
    "print(\"wątki, których domyślnie używa Numba:\", numba.get_num_threads())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d35cbfe",
   "metadata": {},
   "source": [
    "## Numba: just-in-time compilation\n",
    "\n",
    "The CPython interpreter executes bytecode instruction by instruction and checks the types of the\n",
    "objects at every operation ({doc}`part 1 <p1_pomiar>`). Numba works differently. On the first call\n",
    "of a function, it reads the types of the arguments, for example `int64`, and translates the whole\n",
    "function into the processor’s machine code using LLVM, the library on which, for example, the\n",
    "`clang` compiler is also built. Such compilation at the moment of first use is called\n",
    "*just-in-time* (JIT) compilation. The `njit` decorator (from *no Python*) requires the function to\n",
    "use only numbers, NumPy arrays, tuples, and a few simple data structures, but not Python objects.\n",
    "Let us compile the first program from part 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec811e55",
   "metadata": {},
   "outputs": [],
   "source": [
    "def suma_petla(n):\n",
    "    s = 0\n",
    "    for i in range(n):\n",
    "        for j in range(n):\n",
    "            s += i + j\n",
    "    return s\n",
    "\n",
    "\n",
    "suma_petla_jit = njit(suma_petla)        # ta sama funkcja, skompilowana\n",
    "\n",
    "start = time.perf_counter()\n",
    "wynik = suma_petla_jit(100)              # kompilacja i obliczenie\n",
    "t_pierwsze = time.perf_counter() - start\n",
    "start = time.perf_counter()\n",
    "suma_petla_jit(100)                      # samo obliczenie\n",
    "t_drugie = time.perf_counter() - start\n",
    "print(f\"wynik: {wynik}\")\n",
    "print(f\"pierwsze wywołanie: {czas(t_pierwsze)}, drugie: {czas(t_drugie)}\")\n",
    "print(\"skompilowane wersje:\", suma_petla_jit.signatures)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "147554c4",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(t_pierwsze > 1000 * t_drugie,\n",
    "        \"pierwsze wywołanie trwa tysiące razy dłużej niż drugie\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c6c64da",
   "metadata": {},
   "source": [
    "The first call includes the compilation and takes thousands of times longer than the second. The\n",
    "`signatures` list shows for which argument types the function has already been compiled: here, for\n",
    "a single integer of type `int64`. A call with an argument of a different type, for example\n",
    "`float`, would trigger the compilation of a second version. The `zmierz` function from part 1\n",
    "calls the measured function once before measuring, so the compilation time does not appear in the\n",
    "tables of this part. Compilation pays off only when the function computes for a long time or is\n",
    "called many times.\n",
    "\n",
    "How does the time grow with $n$? We measure the Python version for $n\\le1000$ and the compiled one\n",
    "all the way up to $n=10^6$, that is, up to $10^{12}$ iterations of the inner loop. We compare every\n",
    "result with the formula $S(n)=n^2(n-1)$ from part 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e271f3c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"{'n':>9}  {'Python':>9}  {'Numba':>9}\")\n",
    "czasy_jit = {}\n",
    "for n in [10**2, 10**3, 10**4, 10**5, 10**6]:\n",
    "    assert suma_petla_jit(n) == n**2 * (n - 1)\n",
    "    czasy_jit[n] = zmierz(suma_petla_jit, n)\n",
    "    t_python = czas(zmierz(suma_petla, n)) if n <= 1000 else \"—\"\n",
    "    print(f\"{n:>9}  {t_python:>9}  {czas(czasy_jit[n]):>9}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f71782bf",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_jit[10**6] < 3 * czasy_jit[10**2],\n",
    "        \"czas skompilowanej funkcji nie zależy od n\")\n",
    "upewnij(czasy_jit[10**6] < 1e-6,\n",
    "        \"dla n = 10⁶ skompilowana funkcja potrzebuje mniej niż mikrosekundy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9b4bec3",
   "metadata": {},
   "source": [
    "The time of the Python version grows like $n^2$: an $n$ ten times larger means a computation one\n",
    "hundred times longer. The time of the compiled function does not depend on $n$ at all, and for\n",
    "$n=10^6$ it is shorter than a microsecond. Yet a trillion additions would take a hundred seconds\n",
    "even at ten billion additions per second. So the compiler must have found a shortcut. Here is the\n",
    "machine code it generated (we omit the wrapper that converts Python objects into machine numbers):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9fb01ecd",
   "metadata": {},
   "outputs": [],
   "source": [
    "asm = suma_petla_jit.inspect_asm(suma_petla_jit.signatures[0])\n",
    "rozkazy = []\n",
    "for wiersz in asm.split(\"cpython\")[0].splitlines():\n",
    "    if wiersz.startswith(\"\\t\") and not wiersz.strip().startswith(\".\"):\n",
    "        rozkazy.append(\" \".join(wiersz.split()))     # rozkaz procesora\n",
    "    elif wiersz.startswith((\"LBB\", \".LBB\")):\n",
    "        rozkazy.append(wiersz)                       # etykieta skoku\n",
    "print(f\"procesor: {platform.machine()}, rozkazów: \"\n",
    "      f\"{sum(not r.endswith(':') for r in rozkazy)}\")\n",
    "print(\"\\n\".join(rozkazy))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66b8caab",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if platform.machine() == \"arm64\":      # tekst opisuje kod dla arm64\n",
    "    skoki = [r.split()[0] for r in rozkazy\n",
    "             if r.split()[0] in (\"b\", \"cbz\", \"cbnz\", \"tbz\", \"tbnz\")\n",
    "             or r.startswith(\"b.\")]\n",
    "    upewnij(len(rozkazy) < 40 and skoki == [\"b.lt\"]\n",
    "            and any(r.startswith((\"mul\", \"madd\")) for r in rozkazy),\n",
    "            \"kod funkcji to kilkanaście rozkazów bez pętli, z jednym \"\n",
    "            \"skokiem warunkowym b.lt i mnożeniami\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5806cd72",
   "metadata": {},
   "source": [
    "This is the entire code of the function: a dozen or so instructions for the arm64 processor on\n",
    "which this page was built (on a different processor the instructions look different). There is no\n",
    "loop in it. The only conditional branch (`b.lt`) handles the case $n\\le0$, in which the result is\n",
    "$0$. The rest is a few multiplications (`mul`, `umulh`, `madd`) and additions. The LLVM optimizer\n",
    "recognized that the loops sum arithmetic progressions and replaced them with a formula, the same\n",
    "$n^2(n-1)$ that we derived ourselves in part 1. **The compiler is lazy too.** Two things follow\n",
    "from this. First, the compiler will sometimes turn a simple loop into a formula on its own.\n",
    "Second, when measuring compiled code, you also have to check that the compiler has not removed\n",
    "precisely the work you wanted to measure.\n",
    "\n",
    "## A loop that cannot be vectorized: Collatz steps\n",
    "\n",
    "In {doc}`part 5 <p5_numpy>` we moved loops into NumPy. The Collatz steps are not suited to this:\n",
    "each number needs a different number of steps, and the next step depends on the previous one.\n",
    "NumPy would have to carry all the trajectories along at once until the longest one ends. A loop\n",
    "compiled by Numba computes exactly as many steps for each number as needed.\n",
    "\n",
    "We compare four versions: each number separately and with a table of known results, in Python and\n",
    "in Numba. The table of known results is a simpler variant of the dictionary-based memoization from\n",
    "part 2. We go through the numbers in order and follow the trajectory of the number `start` only up\n",
    "to the first number smaller than `start`. By then we already know the number of steps for that\n",
    "number. Nobody knows whether every trajectory eventually drops below its starting point: this\n",
    "statement is equivalent to the Collatz conjecture. For the numbers checked here, the computation\n",
    "terminates, so for them it is true."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1df2ae9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def kroki(n):\n",
    "    k = 0\n",
    "    while n != 1:\n",
    "        n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "        k += 1\n",
    "    return k\n",
    "\n",
    "\n",
    "def kroki_wszystkie(N):\n",
    "    return np.array([kroki(n) for n in range(1, N + 1)])\n",
    "\n",
    "\n",
    "def kroki_tablica(N):\n",
    "    \"\"\"Kroki dla n ≤ N; trajektorię liczby start śledzimy tylko do\n",
    "    pierwszej liczby mniejszej od start, bo jej wynik już znamy.\"\"\"\n",
    "    znane = np.zeros(N + 1, dtype=np.int64)\n",
    "    for start in range(2, N + 1):\n",
    "        n, k = start, 0\n",
    "        while n >= start:\n",
    "            n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "            k += 1\n",
    "        znane[start] = k + znane[n]\n",
    "    return znane[1:]\n",
    "\n",
    "\n",
    "kroki_jit = njit(kroki)\n",
    "kroki_tablica_jit = njit(kroki_tablica)\n",
    "\n",
    "\n",
    "@njit\n",
    "def kroki_wszystkie_jit(N):\n",
    "    wynik = np.empty(N, dtype=np.int64)\n",
    "    for n in range(1, N + 1):\n",
    "        wynik[n - 1] = kroki_jit(n)\n",
    "    return wynik\n",
    "\n",
    "\n",
    "def te_same(a, b):\n",
    "    return np.array_equal(np.asarray(a), np.asarray(b))\n",
    "\n",
    "\n",
    "N = 10**5\n",
    "czasy_collatz = porownaj({\n",
    "    \"Python: każda liczba osobno\": kroki_wszystkie,\n",
    "    \"Python: tablica znanych wyników\": kroki_tablica,\n",
    "    \"Numba: każda liczba osobno\": kroki_wszystkie_jit,\n",
    "    \"Numba: tablica znanych wyników\": kroki_tablica_jit}, N, zgodne=te_same)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0bc8658",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c = czasy_collatz\n",
    "upewnij(10 < c[\"Python: każda liczba osobno\"]\n",
    "        / c[\"Numba: każda liczba osobno\"] < 200,\n",
    "        \"kompilacja przyspiesza ten sam program dziesiątki razy\")\n",
    "upewnij(c[\"Python: każda liczba osobno\"]\n",
    "        > 4 * c[\"Python: tablica znanych wyników\"]\n",
    "        and c[\"Numba: każda liczba osobno\"]\n",
    "        > 4 * c[\"Numba: tablica znanych wyników\"],\n",
    "        \"tablica znanych wyników przyspiesza wielokrotnie w obu językach\")\n",
    "upewnij(300 < c[\"Python: każda liczba osobno\"]\n",
    "        / c[\"Numba: tablica znanych wyników\"] < 3000,\n",
    "        \"kompilacja i lepszy algorytm razem dają przyspieszenie rzędu \"\n",
    "        \"tysiąca razy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0295409",
   "metadata": {},
   "source": [
    "Compilation speeds up the same program tens of times, and the table of known results gives\n",
    "a several-fold speedup in both Python and Numba. The two rungs of the ladder act independently, so\n",
    "their gains multiply: together they give a speedup on the order of a thousand times. Such a fast\n",
    "program lets us reach further. Let us find the number $n\\le10^7$ with the longest trajectory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8530ba68",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 10**7\n",
    "start = time.perf_counter()\n",
    "kroki_do_N = kroki_tablica_jit(N)\n",
    "t_N = time.perf_counter() - start\n",
    "rekord = int(np.argmax(kroki_do_N))\n",
    "print(f\"n ≤ {N}: najwięcej kroków ({kroki_do_N[rekord]}) ma n = {rekord + 1}\")\n",
    "print(f\"czas: {czas(t_N)}\")\n",
    "t_python = 100 * czasy_collatz[\"Python: każda liczba osobno\"]\n",
    "print(f\"Python, każda liczba osobno: ponad {czas(t_python)} (szacunek)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4912d8e0",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(t_N < 1, \"rekord dla n ≤ 10⁷ liczy się w ułamku sekundy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51e5cb5a",
   "metadata": {},
   "source": [
    "Numba finds the record for $n\\le10^7$ in a fraction of a second. The Python version, number by\n",
    "number, would need more than a hundred times as much time as in the table for $N=10^5$: there are\n",
    "a hundred times as many numbers, and their trajectories are longer on average.\n",
    "\n",
    "Numba computes with 64-bit integers, not with Python’s unbounded integers. So let us check that\n",
    "the trajectories do not leave the range of the type `int64`. Here, too, it is enough to go up to\n",
    "the first number smaller than the starting number, because we checked the rest of the trajectory\n",
    "earlier. We compare each new number with the maximum before we compute the next one from it, and\n",
    "the starting numbers are small. So if the maximum is smaller than $(2^{63}-1)/3$, then no\n",
    "operation $3n+1$ has left the range."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e62802b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "@njit\n",
    "def najwieksza_liczba(N):\n",
    "    \"\"\"Największa liczba na trajektoriach liczb n ≤ N.\"\"\"\n",
    "    m = 1\n",
    "    for start in range(2, N + 1):\n",
    "        n = start\n",
    "        while n >= start:\n",
    "            n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "            m = max(m, n)\n",
    "    return m\n",
    "\n",
    "\n",
    "m = najwieksza_liczba(N)\n",
    "granica = np.iinfo(np.int64).max // 3\n",
    "print(f\"największa liczba na trajektoriach n ≤ {N}: {m} ≈ {m:.1e}\")\n",
    "print(f\"(2⁶³ - 1) / 3 ≈ {granica:.1e}, zapas: {granica / m:.0f} razy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0b1c72b",
   "metadata": {},
   "source": [
    "## Compilation will not replace a library: Gaussian elimination\n",
    "\n",
    "In part 6, Gaussian elimination from Lecture 6 in pure Python lost to the function\n",
    "`np.linalg.solve` (the LAPACK library) by a factor of hundreds. Will compilation even the odds?\n",
    "Numba does not compile lists of lists, so we write the same algorithm on a NumPy array, with\n",
    "explicit loops."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a59b0afc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def eliminacja(A, b):\n",
    "    \"\"\"Eliminacja Gaussa z częściowym wyborem elementu głównego (wykład 6).\"\"\"\n",
    "    n = len(A)\n",
    "    M = [list(w) + [bi] for w, bi in zip(A, b)]\n",
    "    for k in range(n):\n",
    "        p = max(range(k, n), key=lambda i: abs(M[i][k]))\n",
    "        M[k], M[p] = M[p], M[k]\n",
    "        for i in range(k + 1, n):\n",
    "            m = M[i][k] / M[k][k]\n",
    "            M[i] = [a - m * c for a, c in zip(M[i], M[k])]\n",
    "    x = [0] * n\n",
    "    for i in reversed(range(n)):\n",
    "        s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))\n",
    "        x[i] = s / M[i][i]\n",
    "    return x\n",
    "\n",
    "\n",
    "@njit\n",
    "def eliminacja_jit(A, b):\n",
    "    \"\"\"Ten sam algorytm na tablicy NumPy, z jawnymi pętlami.\"\"\"\n",
    "    n = len(A)\n",
    "    M = np.empty((n, n + 1))\n",
    "    M[:, :n] = A\n",
    "    M[:, n] = b\n",
    "    for k in range(n):\n",
    "        p = k + np.argmax(np.abs(M[k:, k]))      # element główny\n",
    "        for j in range(n + 1):\n",
    "            M[k, j], M[p, j] = M[p, j], M[k, j]\n",
    "        for i in range(k + 1, n):\n",
    "            m = M[i, k] / M[k, k]\n",
    "            for j in range(k, n + 1):\n",
    "                M[i, j] -= m * M[k, j]\n",
    "    x = np.zeros(n)\n",
    "    for i in range(n - 1, -1, -1):\n",
    "        s = 0.0\n",
    "        for j in range(i + 1, n):\n",
    "            s += M[i, j] * x[j]\n",
    "        x[i] = (M[i, n] - s) / M[i, i]\n",
    "    return x\n",
    "\n",
    "\n",
    "los = np.random.default_rng(2026)\n",
    "rozmiary = [50, 100, 200, 400, 800]\n",
    "czasy_gauss = {\"eliminacja w Pythonie (część 6)\": [],\n",
    "               \"ta sama eliminacja w Numbie\": [],\n",
    "               \"np.linalg.solve (LAPACK)\": []}\n",
    "print(f\"{'n':>4}  {'Python':>9}  {'Numba':>9}  {'LAPACK':>9}\"\n",
    "      f\"  {'Numba / LAPACK':>14}\")\n",
    "for n in rozmiary:\n",
    "    A = los.integers(-9, 10, (n, n)).astype(float)\n",
    "    b = los.integers(-9, 10, n).astype(float)\n",
    "    x = np.linalg.solve(A, b)\n",
    "    assert np.allclose(eliminacja_jit(A, b), x)\n",
    "    t_py = math.nan                          # Python tylko do n = 200\n",
    "    if n <= 200:\n",
    "        assert np.allclose(eliminacja(A.tolist(), b.tolist()), x)\n",
    "        t_py = zmierz(eliminacja, A.tolist(), b.tolist())\n",
    "    t_nb = zmierz(eliminacja_jit, A, b)\n",
    "    t_la = zmierz(np.linalg.solve, A, b)\n",
    "    for nazwa, t in zip(czasy_gauss, (t_py, t_nb, t_la)):\n",
    "        czasy_gauss[nazwa].append(t)\n",
    "    t_py = czas(t_py) if n <= 200 else \"—\"\n",
    "    print(f\"{n:>4}  {t_py:>9}  {czas(t_nb):>9}  {czas(t_la):>9}\"\n",
    "          f\"  {krotnosc(t_nb / t_la):>14}\")\n",
    "wykres_skalowania(rozmiary, czasy_gauss, \"Rozwiązanie układu n × n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96c68af6",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "py, nb, la = czasy_gauss.values()\n",
    "upewnij(py[2] > 200 * la[2],\n",
    "        \"w czystym Pythonie eliminacja przegrywa z LAPACK-iem setki razy\")\n",
    "upewnij(30 < py[2] / nb[2] < 300,\n",
    "        \"dla n = 200 Numba przyspiesza eliminację rzędu stu razy\")\n",
    "upewnij(nb[-1] > 5 * la[-1] and nb[-1] / la[-1] > 3 * nb[0] / la[0],\n",
    "        \"LAPACK jest dla dużych n wielokrotnie szybszy od Numby, \"\n",
    "        \"a jego przewaga rośnie z n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56595c87",
   "metadata": {},
   "source": [
    "Numba speeds up the elimination by a factor on the order of a hundred, but LAPACK remains faster,\n",
    "and its advantage grows with $n$. For large systems it is several-fold. Compilation removes the\n",
    "cost of the interpreter, but it does not change the algorithm. For each $k$, our loop passes over\n",
    "the whole remaining part of the matrix and spends more time reading from memory than computing.\n",
    "LAPACK divides the matrix into blocks that fit in the CPU cache and performs most of the work as\n",
    "matrix multiplication (BLAS) with vector instructions, and it can also use several cores. This is\n",
    "the result of decades of work by specialists, and the `njit` decorator will not replace it. The\n",
    "instructor’s study shows the same thing: there, single-threaded BLAS was faster than C code\n",
    "running on four cores.\n",
    "\n",
    "## Pitfalls of compilation\n",
    "\n",
    "### Integers have 64 bits\n",
    "\n",
    "In Python, integers are unbounded. In Numba, as in NumPy (part 5), they have 64 bits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5782fea6",
   "metadata": {},
   "outputs": [],
   "source": [
    "@njit\n",
    "def silnia(n):\n",
    "    w = 1\n",
    "    for k in range(2, n + 1):\n",
    "        w *= k\n",
    "    return w\n",
    "\n",
    "\n",
    "for n in (20, 21, 25):\n",
    "    print(f\"{n}!  Numba: {silnia(n):>20}   Python: {math.factorial(n)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbce7c99",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(silnia(20) == math.factorial(20) and silnia(21) < 0\n",
    "        and 0 < silnia(25) != math.factorial(25),\n",
    "        \"20! jest poprawne, 21! wychodzi ujemne, a 25! dodatnie, ale błędne\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55d4941c",
   "metadata": {},
   "source": [
    "The number $20!$ fits in the range of the type `int64` (up to $2^{63}-1\\approx9.2\\cdot10^{18}$),\n",
    "but $21!$ no longer does. The result silently “wraps around” and comes out negative, and $25!$ is\n",
    "positive but wrong. That is why, when compiling, we keep an eye on the range, as with the Collatz\n",
    "steps. Exact computations with large numbers (factorials, the binomial coefficients from part 2)\n",
    "stay in Python.\n",
    "\n",
    "### The same loop gives the same result, unless we allow changes\n",
    "\n",
    "Let us sum a million copies of the number `0.1`, as in part 4. We compare the loop in Python, the\n",
    "same loop compiled by Numba, the same loop with the option `fastmath=True`, and the function\n",
    "`np.sum`. The results differ in the last digits, so in the contract we allow a relative difference\n",
    "of $10^{-9}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a74aebf9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def suma_po_kolei(x):\n",
    "    s = 0.0\n",
    "    for i in range(len(x)):\n",
    "        s += x[i]\n",
    "    return s\n",
    "\n",
    "\n",
    "suma_jit = njit(suma_po_kolei)\n",
    "suma_jit_fastmath = njit(fastmath=True)(suma_po_kolei)\n",
    "\n",
    "x = np.full(10**6, 0.1)\n",
    "sumy = {\"pętla w Pythonie\": suma_po_kolei,\n",
    "        \"ta sama pętla w Numbie\": suma_jit,\n",
    "        \"Numba, fastmath=True\": suma_jit_fastmath,\n",
    "        \"np.sum\": np.sum}\n",
    "czasy_sumy = porownaj(sumy, x, zgodne=lambda a, b: math.isclose(\n",
    "    a, b, rel_tol=1e-9))\n",
    "print()\n",
    "for nazwa, f in {**sumy, \"math.fsum\": math.fsum}.items():\n",
    "    print(f\"{nazwa:>24}: {float(f(x))!r}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f00e4eb1",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "w_py, w_nb, w_fm = (float(f(x)) for f in list(sumy.values())[:3])\n",
    "upewnij(w_nb == w_py, \"skompilowana pętla daje co do bitu ten sam wynik\")\n",
    "upewnij(w_fm != w_nb and abs(w_fm - 1e5) < abs(w_nb - 1e5),\n",
    "        \"fastmath zmienia wynik, tu akurat na dokładniejszy\")\n",
    "upewnij(czasy_sumy[\"ta sama pętla w Numbie\"]\n",
    "        > 3 * czasy_sumy[\"Numba, fastmath=True\"],\n",
    "        \"fastmath jest kilka razy szybsze\")\n",
    "upewnij(math.fsum(x) == 1e5, \"math.fsum daje 100000.0\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7b04f99",
   "metadata": {},
   "source": [
    "By default, Numba preserves the order of operations from the code and the rules of the IEEE 754\n",
    "standard, so the compiled loop gives a result that is bit-for-bit identical to that of the Python\n",
    "loop, with the same rounding error. The option `fastmath=True` allows the compiler to change the\n",
    "order of the additions. The compiler then accumulates several partial sums at once with vector\n",
    "instructions. This is several times faster, but the result is different. Here it happens to be\n",
    "more accurate, but the compiler promises nothing of the kind. With `fastmath` it also assumes,\n",
    "for example, that the data contain no `nan` and no infinities. The function `np.sum` uses\n",
    "*pairwise summation*, which usually gives a smaller error than adding the numbers one after\n",
    "another. The correctly rounded sum, $100000.0$, is given by `math.fsum`. The\n",
    "{doc}`IEEE 754 <../ieee754/ieee754>` deep dive says more about the order of operations on\n",
    "floating-point numbers.\n",
    "\n",
    "### Only numbers and arrays"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d44473fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "@njit\n",
    "def harmoniczna(n):\n",
    "    s = Fraction(0)\n",
    "    for k in range(1, n + 1):\n",
    "        s += Fraction(1, k)\n",
    "    return s\n",
    "\n",
    "\n",
    "try:\n",
    "    harmoniczna(10)\n",
    "except TypingError as blad:\n",
    "    opis = next(w for w in str(blad).splitlines() if \"Fraction\" in w)\n",
    "    print(\"TypingError:\")\n",
    "    print(textwrap.fill(opis, width=79))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dc2df7a",
   "metadata": {},
   "source": [
    "The compiler must know the type of every variable and be able to convert it into a machine type.\n",
    "It does not know the `Fraction` class, Python’s big integers, or SymPy expressions, and it will not\n",
    "call functions from SciPy or SymPy either. So the exact computations from Lectures 3 and 6 and the\n",
    "harmonic numbers from {doc}`part 7 <p7_sympy>` stay in Python. That does no harm, because there\n",
    "the time goes into the arithmetic on large numbers itself, not into the interpreter. We pass NumPy\n",
    "arrays to compiled functions, not Python lists: Numba accepts lists only with a warning that this\n",
    "feature will be removed.\n",
    "\n",
    "## Parallel computing\n",
    "\n",
    "An ordinary Python program computes on a single core. The work can be divided up in three ways.\n",
    "\n",
    "* **Threads** (the `threading` module, the `ThreadPoolExecutor` class) share the program’s memory.\n",
    "  In standard CPython, however, the *global interpreter lock* (GIL) allows only one thread at\n",
    "  a time to execute Python code.\n",
    "* **Processes** (the `multiprocessing` module, the `ProcessPoolExecutor` class) are separate\n",
    "  programs, each with its own interpreter and its own lock. They compute truly in parallel, but\n",
    "  each one has to be started, and the tasks and results have to be sent between the processes.\n",
    "* **Compiled code** does not need the interpreter, so it does not need the lock either. Numba\n",
    "  distributes the iterations of a `prange` loop among threads.\n",
    "\n",
    "### Threads and processes in pure Python\n",
    "\n",
    "Child processes must know the function they are to execute. On macOS and Windows, a new process\n",
    "starts from scratch (the `spawn` method) and does not see functions defined in notebook cells, so\n",
    "the function has to be placed in a module. In your own program, an ordinary `.py` file next to the\n",
    "notebook is enough. Here, to keep the notebook self-contained, we write the module to a temporary\n",
    "directory. We choose the `spawn` method explicitly so that the program behaves the same way on\n",
    "every system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1395b642",
   "metadata": {},
   "outputs": [],
   "source": [
    "MODUL = '''\\\n",
    "def kroki(n):\n",
    "    k = 0\n",
    "    while n != 1:\n",
    "        n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "        k += 1\n",
    "    return k\n",
    "\n",
    "\n",
    "def kroki_przedzialu(a, b):\n",
    "    \"\"\"Liczby kroków Collatza dla n = a, a + 1, ..., b - 1.\"\"\"\n",
    "    return [kroki(n) for n in range(a, b)]\n",
    "'''\n",
    "katalog = pathlib.Path(tempfile.mkdtemp())\n",
    "(katalog / \"collatz_zadania.py\").write_text(MODUL)\n",
    "sys.path.insert(0, str(katalog))         # procesy potomne dostaną tę ścieżkę\n",
    "import collatz_zadania\n",
    "\n",
    "\n",
    "def przedzialy(N, czesci):\n",
    "    \"\"\"Dzieli 1, ..., N na kolejne przedziały [a, b).\"\"\"\n",
    "    g = [1 + N * k // czesci for k in range(czesci + 1)]\n",
    "    return list(zip(g, g[1:]))\n",
    "\n",
    "\n",
    "def w_puli(pula, N, czesci):\n",
    "    \"\"\"Kroki dla n ≤ N policzone w puli wątków albo procesów.\"\"\"\n",
    "    poczatki, konce = zip(*przedzialy(N, czesci))\n",
    "    wynik = []\n",
    "    for kawalek in pula.map(collatz_zadania.kroki_przedzialu, poczatki,\n",
    "                            konce):\n",
    "        wynik += kawalek\n",
    "    return np.array(wynik)\n",
    "\n",
    "\n",
    "spawn = multiprocessing.get_context(\"spawn\")\n",
    "watki = ThreadPoolExecutor(max_workers=4)\n",
    "start = time.perf_counter()\n",
    "procesy = ProcessPoolExecutor(max_workers=4, mp_context=spawn)\n",
    "w_puli(procesy, 100, 4)                  # uruchomienie procesów\n",
    "t_start = time.perf_counter() - start\n",
    "print(\"uruchomienie puli czterech procesów:\", czas(t_start))\n",
    "\n",
    "N = 10**5\n",
    "czasy_pule = porownaj({\"jeden proces\": lambda: kroki_wszystkie(N),\n",
    "                       \"4 wątki\": lambda: w_puli(watki, N, 16),\n",
    "                       \"4 procesy\": lambda: w_puli(procesy, N, 16)},\n",
    "                      zgodne=te_same)\n",
    "watki.shutdown()\n",
    "procesy.shutdown()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50a33eaa",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c = czasy_pule\n",
    "upewnij(c[\"4 wątki\"] > 0.8 * c[\"jeden proces\"],\n",
    "        \"cztery wątki nie przyspieszają\")\n",
    "upewnij(1.5 < c[\"jeden proces\"] / c[\"4 procesy\"] < 4,\n",
    "        \"cztery procesy przyspieszają wyraźnie, choć mniej niż cztery razy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f147981",
   "metadata": {},
   "source": [
    "Four threads give no speedup at all: the lock passes from thread to thread, so at any moment only\n",
    "one of them is computing. Four processes give a clear speedup, though less than fourfold. The\n",
    "tasks and results have to be serialized into bytes (the `pickle` module) and sent between the\n",
    "processes, and in the meantime the processor also serves other programs. We divided the work into\n",
    "sixteen tasks, four per process, so that the cores that finish early have something to do.\n",
    "\n",
    "The process pool also has to be started, which takes time (the first line above). For a small\n",
    "task, a new pool loses to a single process:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08144731",
   "metadata": {},
   "outputs": [],
   "source": [
    "def nowa_pula(N):\n",
    "    with ProcessPoolExecutor(max_workers=4, mp_context=spawn) as pula:\n",
    "        return w_puli(pula, N, 16)\n",
    "\n",
    "\n",
    "czasy_male = porownaj({\"jeden proces\": lambda: kroki_wszystkie(1000),\n",
    "                       \"nowa pula czterech procesów\": lambda: nowa_pula(1000)},\n",
    "                      zgodne=te_same)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d61aa21",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_male[\"nowa pula czterech procesów\"]\n",
    "        > 3 * czasy_male[\"jeden proces\"],\n",
    "        \"przy małym zadaniu nowa pula przegrywa z jednym procesem\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "740f209a",
   "metadata": {},
   "source": [
    "So we create a process pool once and give it large chunks of work. It pays off only when the work\n",
    "of a single process takes much longer than starting it up and transferring the data.\n",
    "\n",
    "### Numba: threads without the lock\n",
    "\n",
    "It is enough to replace `range` with `prange` and add the option `parallel=True`, and Numba will\n",
    "distribute the iterations of the loop among threads. This is allowed because the iterations are\n",
    "independent: each one writes a different element of the array `wynik`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "495db801",
   "metadata": {},
   "outputs": [],
   "source": [
    "@njit(parallel=True)\n",
    "def kroki_rownolegle(N):\n",
    "    wynik = np.empty(N, dtype=np.int64)\n",
    "    for i in prange(N):                  # obroty pętli dzielone między wątki\n",
    "        wynik[i] = kroki_jit(i + 1)\n",
    "    return wynik\n",
    "\n",
    "\n",
    "N = 10**5\n",
    "czasy_prange = porownaj({\n",
    "    \"Numba: każda liczba osobno\": kroki_wszystkie_jit,\n",
    "    \"Numba: prange\": kroki_rownolegle,\n",
    "    \"Numba: tablica znanych wyników\": kroki_tablica_jit}, N, zgodne=te_same)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4fc5e54",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c = czasy_prange\n",
    "upewnij(c[\"Numba: każda liczba osobno\"] > 3 * c[\"Numba: prange\"],\n",
    "        \"prange przyspiesza kilka razy\")\n",
    "upewnij(c[\"Numba: prange\"] > c[\"Numba: tablica znanych wyników\"],\n",
    "        \"tablica znanych wyników na jednym rdzeniu jest szybsza od prange\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "399022af",
   "metadata": {},
   "source": [
    "The `prange` loop gives a speedup of several times. Still, the version with the table of known\n",
    "results on a single core is faster than the parallel version on all cores. **A better algorithm\n",
    "beats more cores.** That version cannot easily be parallelized, because each step uses the\n",
    "results of the previous ones.\n",
    "\n",
    "### How much additional cores help\n",
    "\n",
    "Let us measure how the time depends on the number $k$ of processes (pure Python, $N=10^5$) and of\n",
    "Numba threads ($N=10^6$, so that the work of a single thread takes about as long). The speedup is\n",
    "$S_k=T_1/T_k$, where $T_k$ is the time on $k$ cores. Ideally, $S_k=k$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a474c0db",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "def wykres_przyspieszenia(liczby, serie, tytul, wydajne=None):\n",
    "    \"\"\"Przyspieszenie T₁/Tₖ w zależności od liczby k procesów albo wątków.\"\"\"\n",
    "    fig, ax = plt.subplots(figsize=(8, 4))\n",
    "    ax.plot(liczby, liczby, \"--\", color=SZARY, lw=1.5,\n",
    "            label=\"idealnie: k razy\")\n",
    "    for (nazwa, czasy_serii), kolor, znak in zip(serie.items(),\n",
    "                                                 (INDYGO, BURSZTYN), \"os\"):\n",
    "        ax.plot(liczby, [czasy_serii[0] / t for t in czasy_serii], \"-\",\n",
    "                marker=znak, color=kolor, lw=2, ms=6, label=nazwa)\n",
    "    if wydajne:\n",
    "        ax.axvline(wydajne, color=SZARY, lw=1, ls=\":\")\n",
    "        ax.annotate(f\"rdzenie wydajne: {wydajne}\", (wydajne, liczby[-1]),\n",
    "                    xytext=(-6, 0), textcoords=\"offset points\", ha=\"right\",\n",
    "                    va=\"top\", fontsize=9, color=TUSZ)\n",
    "    ax.set_xticks(liczby)\n",
    "    ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f\"{v:g}×\"))\n",
    "    ax.set_xlabel(\"liczba procesów albo wątków k\")\n",
    "    ax.grid(color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.legend(loc=\"lower right\", frameon=False, fontsize=9)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84db8bb2",
   "metadata": {},
   "outputs": [],
   "source": [
    "liczby = [k for k in (1, 2, 4, 6, 8, 10, 12, 16) if k <= os.cpu_count()]\n",
    "czasy_procesow, czasy_watkow = [], []\n",
    "for k in liczby:\n",
    "    with ProcessPoolExecutor(max_workers=k, mp_context=spawn) as pula:\n",
    "        w_puli(pula, 1000, k)            # uruchomienie procesów\n",
    "        czasy_procesow.append(zmierz(w_puli, pula, 10**5, 4 * k))\n",
    "    numba.set_num_threads(k)\n",
    "    czasy_watkow.append(zmierz(kroki_rownolegle, 10**6))\n",
    "numba.set_num_threads(numba.config.NUMBA_NUM_THREADS)\n",
    "\n",
    "print(f\"{'k':>3}  {'procesy':>9}  {'S_k':>6}  {'wątki Numby':>11}  {'S_k':>6}\")\n",
    "for k, tp, tw in zip(liczby, czasy_procesow, czasy_watkow):\n",
    "    print(f\"{k:>3}  {czas(tp):>9}  {krotnosc(czasy_procesow[0] / tp):>6}\"\n",
    "          f\"  {czas(tw):>11}  {krotnosc(czasy_watkow[0] / tw):>6}\")\n",
    "wykres_przyspieszenia(\n",
    "    liczby, {\"procesy, czysty Python, N = 10⁵\": czasy_procesow,\n",
    "             \"wątki Numby (prange), N = 10⁶\": czasy_watkow},\n",
    "    \"Kroki Collatza: przyspieszenie na k rdzeniach\",\n",
    "    int(wydajne) if wydajne else None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e161fac8",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "S_p = [czasy_procesow[0] / t for t in czasy_procesow]\n",
    "S_w = [czasy_watkow[0] / t for t in czasy_watkow]\n",
    "for S in (S_p, S_w):\n",
    "    upewnij(S[-1] > S[1] and all(s < k for s, k in zip(S, liczby) if k >= 4)\n",
    "            and S[-1] < 0.8 * liczby[-1],\n",
    "            \"przyspieszenie rośnie z liczbą rdzeni, ale wolniej niż idealnie, \"\n",
    "            \"a przy wszystkich rdzeniach jest wyraźnie mniejsze od ich liczby\")\n",
    "if wydajne and energooszczedne:          # procesor z dwoma rodzajami rdzeni\n",
    "    upewnij(int(energooszczedne) > 0 and int(wydajne) < liczby[-1],\n",
    "            \"tylko część rdzeni to rdzenie wydajne\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22aa9dd1",
   "metadata": {},
   "source": [
    "The speedup grows with the number of processes and threads, but more slowly than in the ideal\n",
    "case, and with all cores in use it is clearly smaller than their number. There are several\n",
    "reasons for this. The cores are not all alike: on the computer on which this page was built, only\n",
    "some of them are performance cores, and the additional tasks land on the slower efficiency cores.\n",
    "On top of that come the costs of dividing up the work, the memory shared by all cores, and other\n",
    "programs running at the same time. That is why the plot looks a little different every time the\n",
    "page is built.\n",
    "\n",
    "Almost every program has a part that must be executed sequentially: reading the data, dividing up\n",
    "the work, collecting the results. If it takes a fraction $f$ of the time on a single core, then on\n",
    "$k$ cores\n",
    "\n",
    "$$\n",
    "S_k\\le\\frac{1}{f+(1-f)/k}<\\frac1f.\n",
    "$$\n",
    "\n",
    "This is **Amdahl’s law** (G. Amdahl, 1967). With $f=5\\%$, no number of cores will speed the\n",
    "program up more than $20$ times. The conclusions are the same as along the whole ladder: first we\n",
    "reduce the work (mathematics, algorithm), then we speed up each of its steps (library,\n",
    "vectorization, compilation), and only at the very end do we divide it among cores.\n",
    "\n",
    "### What else to keep in mind\n",
    "\n",
    "* **Libraries already compute in parallel.** The `@` operator and the function `np.linalg.solve`\n",
    "  call the BLAS and LAPACK libraries, which can themselves use several cores. A pool of processes,\n",
    "  each of which runs a multithreaded BLAS, creates more threads than there are cores, and then the\n",
    "  threads take time away from one another. The number of BLAS threads is limited with environment\n",
    "  variables set before NumPy is imported (for example `OMP_NUM_THREADS` or `OPENBLAS_NUM_THREADS`,\n",
    "  depending on the library) or with the `threadpoolctl` package.\n",
    "* **Shared data means race conditions.** When two threads modify the same element of an array, for\n",
    "  example `h[k] += 1` in a `prange` loop, the result depends on which one gets there first\n",
    "  (a *race condition*), and it is wrong. Numba recognizes a sum `s += …` in a `prange` loop as\n",
    "  a reduction and computes it correctly. It is safest when each iteration of the loop writes its\n",
    "  own element of the result, as in `kroki_rownolegle`.\n",
    "* **Python without the lock.** Since version 3.13 there has been a separate build of the CPython\n",
    "  interpreter without the GIL (PEP 703; experimental in version 3.13, officially supported since\n",
    "  3.14, but not the default). In it, threads execute Python code in parallel, and it is up to the\n",
    "  programmer to ensure correct access to shared data.\n",
    "* **Other compilers.** Cython translates Python with type declarations into C. Functions written\n",
    "  in C can be called from Python through the `ctypes` module (we compiled C programs in the\n",
    "  {doc}`IEEE 754 <../ieee754/ieee754>` deep dive). The JAX, PyTorch, and CuPy libraries can\n",
    "  compute on graphics cards.\n",
    "\n",
    "## Summary: Collatz steps from Python to Numba\n",
    "\n",
    "Let us collect the times of all the versions of computing the Collatz steps for $n\\le10^5$ from\n",
    "this part."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b689d59",
   "metadata": {},
   "outputs": [],
   "source": [
    "podsumowanie = {\n",
    "    \"Python\": czasy_collatz[\"Python: każda liczba osobno\"],\n",
    "    \"Python, 4 wątki\": czasy_pule[\"4 wątki\"],\n",
    "    \"Python, 4 procesy\": czasy_pule[\"4 procesy\"],\n",
    "    \"Python, tablica znanych wyników\":\n",
    "        czasy_collatz[\"Python: tablica znanych wyników\"],\n",
    "    \"Numba\": czasy_collatz[\"Numba: każda liczba osobno\"],\n",
    "    \"Numba, prange\": czasy_prange[\"Numba: prange\"],\n",
    "    \"Numba, tablica znanych wyników\":\n",
    "        czasy_collatz[\"Numba: tablica znanych wyników\"],\n",
    "}\n",
    "wykres_czasow(podsumowanie, \"Kroki Collatza dla n ≤ 100 000\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7d66a36",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(min(podsumowanie, key=podsumowanie.get)\n",
    "        == \"Numba, tablica znanych wyników\",\n",
    "        \"najszybsza jest Numba z tablicą znanych wyników\")\n",
    "upewnij(podsumowanie[\"Python, tablica znanych wyników\"]\n",
    "        < podsumowanie[\"Python, 4 procesy\"],\n",
    "        \"w Pythonie lepszy algorytm na jednym rdzeniu wygrywa z czterema \"\n",
    "        \"procesami\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71b6e17d",
   "metadata": {},
   "source": [
    "The fastest is Numba with the table of known results: a better algorithm, compiled, on a single\n",
    "core. In pure Python, too, the better algorithm on a single core beats four processes. The order\n",
    "of the rungs on the ladder of laziness is no accident:\n",
    "\n",
    "1. **Algorithm first.** The table of known results gives a several-fold speedup, on a single core\n",
    "   and without new tools.\n",
    "2. **Then compilation.** Numba speeds up loops that cannot be vectorized tens of times, but it\n",
    "   will not replace a library such as LAPACK, and it computes only with machine numbers.\n",
    "3. **Cores last.** They give a speedup of at most the number of cores, and less in practice.\n",
    "   Threads in pure Python give nothing.\n",
    "\n",
    "## References\n",
    "\n",
    "* S. K. Lam, A. Pitrou, S. Seibert, *Numba: a LLVM-based Python JIT compiler*, LLVM-HPC 2015;\n",
    "  the Numba documentation (the chapters on `parallel=True` and `fastmath`).\n",
    "* G. M. Amdahl, *Validity of the single processor approach to achieving large scale computing\n",
    "  capabilities*, AFIPS 1967.\n",
    "* The Python documentation: the modules `concurrent.futures`, `multiprocessing` (process start\n",
    "  methods), `threading`; PEP 703 (CPython without the GIL).\n",
    "* M. Gorelick, I. Ozsvald, *High Performance Python*, 2nd ed., O'Reilly 2020, the chapters on\n",
    "  compilation and on the `multiprocessing` module.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Check which loops the compiler turns into a formula: `s += i`, `s += i * i`, `s += i**3`,\n",
    "   `s += i % 7`, `s += 1 / (i + 1)`. Measure the time for $n=10^3$ and $n=10^6$ and look at the\n",
    "   machine code (`inspect_asm`).\n",
    "2. ★★ Compile with Numba the function `krok_zycia_petle` from part 5, rewritten for a `uint8`\n",
    "   array, and compare it with the function `krok_zycia` from Lab 8 (`np.roll`) for $200\\times200$\n",
    "   and $2000\\times2000$ boards. Which version wins? How much does the modulo division in the\n",
    "   innermost loop cost, and how can it be avoided?\n",
    "3. ★★ Measure from which $N$ on a new pool of four processes pays off, including its startup. Plot\n",
    "   the time of a single process and the time of the pool as functions of $N$.\n",
    "4. ★★ Write a version of `kroki_rownolegle` that returns only the record: the number with the\n",
    "   largest number of steps, and that number of steps. Check in the Numba documentation which\n",
    "   reductions can be computed in a `prange` loop.\n",
    "5. ★★★ Estimate the area of the lemniscate from Lecture 5 by the Monte Carlo method in Numba with\n",
    "   a `prange` loop. Is the result the same on every run? How can you make it reproducible?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
