diff --git a/examples/swm/README.md b/examples/swm/README.md new file mode 100644 index 0000000000..e7b544f3e5 --- /dev/null +++ b/examples/swm/README.md @@ -0,0 +1,11 @@ +# Shallow water model + +The NCAR [SWM](https://github.com/NCAR/SWM) shallow water benchmark written with `gt4py.next`. +Start with the notebook; the other two files only support it. + +- `swm.ipynb`: the model, a choice of backends, its validation, and an opt-in performance + comparison across all backends. +- `swm_numpy.py`: a NumPy implementation of the same scheme, which the notebook validates + against. +- `swm_reference.npz`: `u`, `v` and `p` after the full 4000-step benchmark on the 16x16 grid, + from NCAR/SWM `ref/16x16`. diff --git a/examples/swm/swm.ipynb b/examples/swm/swm.ipynb new file mode 100644 index 0000000000..b30704e716 --- /dev/null +++ b/examples/swm/swm.ipynb @@ -0,0 +1,697 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "GT4Py - GridTools Framework\n", + "\n", + "Copyright (c) 2014-2024, ETH Zurich\n", + "All rights reserved.\n", + "\n", + "Please, refer to the LICENSE file in the root directory.\n", + "SPDX-License-Identifier: BSD-3-Clause" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Shallow Water Model\n", + "\n", + "A doubly periodic shallow water model on an Arakawa C-grid, integrated with a leapfrog\n", + "scheme and a Robert-Asselin time filter, ported from the NCAR\n", + "[SWM](https://github.com/NCAR/SWM) mini-app, a long-standing benchmark for comparing\n", + "programming models.\n", + "\n", + "The prognostic equations are\n", + "\n", + "$$\n", + "\\frac{\\partial \\mathbf{V}}{\\partial t} + \\zeta\\,\\mathbf{k} \\times \\mathbf{V}\n", + " + \\nabla\\left(P + \\tfrac{1}{2}\\mathbf{V}\\cdot\\mathbf{V}\\right) = 0,\n", + "\\qquad\n", + "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", + "$$\n", + "\n", + "without rotation (the Coriolis parameter $f$ is zero, as in NCAR/SWM), discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975,\n", + "his Eq. 4). The four intermediates below are his mass fluxes and diagnostics,\n", + "\n", + "$$\n", + "U = \\overline{P}^{\\,x} u, \\qquad V = \\overline{P}^{\\,y} v, \\qquad\n", + "H = P + \\tfrac{1}{2}\\left(\\overline{u^2}^{\\,x} + \\overline{v^2}^{\\,y}\\right), \\qquad\n", + "\\eta = \\frac{\\delta_x v - \\delta_y u}{\\overline{P}^{\\,xy}} ,\n", + "$$\n", + "\n", + "named `cu`, `cv`, `h` and `z` here." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from typing import Any\n", + "\n", + "import numpy as np\n", + "\n", + "import gt4py.next as gtx\n", + "from gt4py.next import backend as next_backend, experimental as gtx_experimental\n", + "from gt4py._core import definitions as core_defs\n", + "\n", + "import swm_numpy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Grid and backend\n", + "\n", + "Fields carry **one halo cell on every side**, so the domain runs from `-1` to `M+1`. All\n", + "three prognostic fields share this one index space; the C-grid staggering is expressed by\n", + "the shifts inside the operators rather than by different array shapes.\n", + "\n", + "The backend that executes the field operator also allocates its fields. The compiled\n", + "`gtfn` and `dace` backends generate C++ or CUDA. The experimental embedded backends run the\n", + "Python of the field operator on the arrays of one library: `embedded_numpy`,\n", + "`embedded_cupy`, `embedded_jax` and `embedded_torch`. JAX and torch take a `device` to choose\n", + "between CPU and GPU; without one, JAX uses its default device and torch the CPU." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "I = gtx.Dimension(\"I\")\n", + "J = gtx.Dimension(\"J\")\n", + "\n", + "IJField = gtx.Field[gtx.Dims[I, J], gtx.float64]\n", + "\n", + "M = swm_numpy.M # 16\n", + "N = swm_numpy.N # 16\n", + "\n", + "DX = swm_numpy.DX # 100 km\n", + "DY = swm_numpy.DY\n", + "DT = swm_numpy.DT # 90 s\n", + "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### jax.jit and torch.compile\n", + "\n", + "Embedded execution runs the Python of the field operator on every call. The experimental\n", + "backends `gtx_experimental.jax_jit` and `gtx_experimental.torch_compile` instead run it\n", + "once under `jax.jit` or `torch.compile`, on fields of JAX arrays or torch tensors, and call\n", + "the compiled function from then on. They write `out=` like any other backend.\n", + "\n", + "A program is traced again for every new field domain, so each grid size compiles once. The\n", + "scalars are traced, so `tdt` and `alpha` changing after the first step do not compile\n", + "again." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Choosing a backend\n", + "\n", + "Uncomment one of the backends below." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "CPU = core_defs.Device(core_defs.DeviceType.CPU, 0)\n", + "CUDA = core_defs.Device(core_defs.DeviceType.CUDA, 0)\n", + "\n", + "backend, device = gtx_experimental.embedded_numpy, None\n", + "# backend, device = gtx.gtfn_cpu, None\n", + "# backend, device = gtx.gtfn_gpu, None\n", + "# backend, device = gtx.dace_cpu, None\n", + "# backend, device = gtx.dace_gpu, None\n", + "# backend, device = gtx_experimental.embedded_cupy, None\n", + "# backend, device = gtx_experimental.embedded_jax, CPU\n", + "# backend, device = gtx_experimental.embedded_jax, CUDA\n", + "# backend, device = gtx_experimental.jax_jit, CPU\n", + "# backend, device = gtx_experimental.jax_jit, CUDA\n", + "# backend, device = gtx_experimental.embedded_torch, CPU\n", + "# backend, device = gtx_experimental.embedded_torch, CUDA\n", + "# backend, device = gtx_experimental.torch_compile, CUDA" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Differential operators\n", + "\n", + "Each operator comes in two variants that differ only in shift direction. The forward form\n", + "($+1$) maps an unstaggered quantity onto a staggered location, the backward form ($-1$)\n", + "maps back. Which one a term needs is fixed by where its operands live: `p` and `h` sit at\n", + "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", + "\n", + "Staggered dimensions would remove the need for the two shift directions, and operators\n", + "generic over the dimension would remove the separate $x$ and $y$ variants, which are features currently being worked on." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def avg_x(f: IJField) -> IJField:\n", + " \"\"\"Average onto the next x-face.\"\"\"\n", + " return 0.5 * (f(I + 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_y(f: IJField) -> IJField:\n", + " \"\"\"Average onto the next y-face.\"\"\"\n", + " return 0.5 * (f(J + 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_x_staggered(f: IJField) -> IJField:\n", + " \"\"\"Average an x-staggered field back onto cell centres.\"\"\"\n", + " return 0.5 * (f(I - 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_y_staggered(f: IJField) -> IJField:\n", + " \"\"\"Average a y-staggered field back onto cell centres.\"\"\"\n", + " return 0.5 * (f(J - 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_x(dx: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Forward difference in x.\"\"\"\n", + " return (f(I + 1) - f) / dx\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_y(dy: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Forward difference in y.\"\"\"\n", + " return (f(J + 1) - f) / dy\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_x_staggered(dx: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Backward difference in x, for an x-staggered field.\"\"\"\n", + " return (f - f(I - 1)) / dx\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_y_staggered(dy: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Backward difference in y, for a y-staggered field.\"\"\"\n", + " return (f - f(J - 1)) / dy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The timestep\n", + "\n", + "One fused field operator produces all six updated fields. The first three are the leapfrog\n", + "update of the prognostic variables; the last three are the time-filtered previous level,\n", + "\n", + "$$ u^{\\text{old}} \\leftarrow u + \\alpha\\,(u^{\\text{new}} - 2u + u^{\\text{old}}) , $$\n", + "\n", + "which suppresses the computational mode of the leapfrog scheme." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def timestep(\n", + " u: IJField,\n", + " v: IJField,\n", + " p: IJField,\n", + " uold: IJField,\n", + " vold: IJField,\n", + " pold: IJField,\n", + " dx: gtx.float64,\n", + " dy: gtx.float64,\n", + " tdt: gtx.float64,\n", + " alpha: gtx.float64,\n", + ") -> tuple[IJField, IJField, IJField, IJField, IJField, IJField]:\n", + " \"\"\"Advance one leapfrog step and return (unew, vnew, pnew, uold, vold, pold).\"\"\"\n", + " cu = avg_x(p) * u\n", + " cv = avg_y(p) * v\n", + " z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p))\n", + " h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v))\n", + "\n", + " unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt\n", + " vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt\n", + " pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt\n", + "\n", + " uold_new = u + alpha * (unew - 2.0 * u + uold)\n", + " vold_new = v + alpha * (vnew - 2.0 * v + vold)\n", + " pold_new = p + alpha * (pnew - 2.0 * p + pold)\n", + "\n", + " return unew, vnew, pnew, uold_new, vold_new, pold_new" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Periodicity\n", + "\n", + "The domain wraps in both directions. Here the halo is refreshed **outside** the field\n", + "operator, after each step: the operator computes the interior only, and the halo is then\n", + "overwritten with the opposite edge by assigning to the field. Field assignment works for\n", + "every array library, including JAX, whose arrays are immutable and get a new buffer.\n", + "\n", + "Rows are copied before columns, which is what fills the corners correctly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def apply_periodic(field: gtx.Field, m: int = M, n: int = N) -> None:\n", + " \"\"\"Refresh the one-cell halo of `field` from the opposite edge.\"\"\"\n", + "\n", + " def copy(dst: dict, src: dict) -> None:\n", + " dst_domain = gtx.domain(dst)\n", + " src_buffer = field[gtx.domain(src)].ndarray\n", + " field[dst_domain] = type(field).from_array(src_buffer, domain=dst_domain)\n", + "\n", + " all_j = (-1, n + 1)\n", + " copy({I: (-1, 0), J: all_j}, {I: (m - 1, m), J: all_j})\n", + " copy({I: (m, m + 1), J: all_j}, {I: (0, 1), J: all_j})\n", + " all_i = (-1, m + 1)\n", + " copy({I: all_i, J: (-1, 0)}, {I: all_i, J: (n - 1, n)})\n", + " copy({I: all_i, J: (n, n + 1)}, {I: all_i, J: (0, 1)})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Time loop\n", + "\n", + "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", + "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", + "with the filter switched off, which is how the leapfrog scheme is started.\n", + "\n", + "A `Model` holds the fields of one integration and the field operator bound to its backend,\n", + "so that repeated calls of `advance` continue the same integration with the same compiled\n", + "or traced operator. The halo refresh runs outside the field operator.\n", + "`advance(..., periodic=False)` skips it: the results are wrong, but the steps then run back\n", + "to back without host work in between." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Model:\n", + " def __init__(\n", + " self,\n", + " m: int = M,\n", + " n: int = N,\n", + " *,\n", + " backend: next_backend.Backend,\n", + " device: core_defs.Device | None = None,\n", + " ):\n", + " self.m, self.n = m, n\n", + " self.domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", + " self.interior = gtx.domain({I: (0, m), J: (0, n)})\n", + " self.step = timestep.with_backend(backend)\n", + " self.cycle = 0\n", + "\n", + " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", + " return gtx.as_field(\n", + " self.domain, np.pad(a, 1, mode=\"wrap\"), allocator=backend, device=device\n", + " )\n", + "\n", + " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", + " self.u, self.v, self.p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " self.uold, self.vold, self.pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " # A valid halo in every buffer keeps `p` nonzero there when the refresh is skipped.\n", + " self.unew, self.vnew, self.pnew = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + "\n", + " def advance(self, cycles: int, periodic: bool = True) -> None:\n", + " \"\"\"Integrate `cycles` more steps.\"\"\"\n", + " for _ in range(cycles):\n", + " tdt = DT if self.cycle == 0 else 2.0 * DT\n", + " alpha = 0.0 if self.cycle == 0 else ALPHA\n", + "\n", + " self.step(\n", + " self.u,\n", + " self.v,\n", + " self.p,\n", + " self.uold,\n", + " self.vold,\n", + " self.pold,\n", + " DX,\n", + " DY,\n", + " tdt,\n", + " alpha,\n", + " out=(self.unew, self.vnew, self.pnew, self.uold, self.vold, self.pold),\n", + " domain=self.interior,\n", + " offset_provider={},\n", + " )\n", + "\n", + " if periodic:\n", + " for field in (self.unew, self.vnew, self.pnew):\n", + " apply_periodic(field, self.m, self.n)\n", + "\n", + " self.u, self.unew = self.unew, self.u\n", + " self.v, self.vnew = self.vnew, self.v\n", + " self.p, self.pnew = self.pnew, self.p\n", + " self.cycle += 1\n", + "\n", + "\n", + "def run(\n", + " itmax: int,\n", + " m: int = M,\n", + " n: int = N,\n", + " *,\n", + " backend: next_backend.Backend,\n", + " device: core_defs.Device | None = None,\n", + ") -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", + " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", + " model = Model(m, n, backend=backend, device=device)\n", + " model.advance(itmax)\n", + " return model.u, model.v, model.p\n", + "\n", + "\n", + "def interior_of(field: gtx.Field, m: int = M, n: int = N) -> np.ndarray:\n", + " return field.asnumpy()[1 : m + 1, 1 : n + 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation against NumPy\n", + "\n", + "The companion module `swm_numpy.py` implements the same scheme with `numpy.roll`, which\n", + "gives periodicity for free and needs no halo at all. Agreement between the two is a check\n", + "that the halo bookkeeping here is right." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "STEPS = 100\n", + "\n", + "# Both implementations evaluate the same expressions, but compiled backends and the JIT\n", + "# compilers may reorder or fuse operations, so agreement is to rounding, not bit-for-bit.\n", + "# Tolerances are absolute because u and v cross zero.\n", + "ATOL_UV = 3e-12 # peak |u|, |v| ~ 4\n", + "ATOL_P = 1e-9 # peak |p| ~ 5e4\n", + "\n", + "\n", + "def test_matches_numpy(backend: next_backend.Backend, device: core_defs.Device | None = None):\n", + " u, v, p = run(STEPS, backend=backend, device=device)\n", + " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", + "\n", + " np.testing.assert_allclose(interior_of(u), u_ref, atol=ATOL_UV)\n", + " np.testing.assert_allclose(interior_of(v), v_ref, atol=ATOL_UV)\n", + " np.testing.assert_allclose(interior_of(p), p_ref, atol=ATOL_P)\n", + "\n", + "\n", + "test_matches_numpy(backend, device)\n", + "print(\"GT4Py and NumPy agree after\", STEPS, \"steps\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation against the NCAR reference\n", + "\n", + "`swm_reference.npz` holds `u`, `v`, `p` after the full 4000-step benchmark, taken from\n", + "[NCAR/SWM](https://github.com/NCAR/SWM) `ref/16x16` (Apache-2.0). Reproducing it end to\n", + "end is the real correctness check." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def test_matches_reference(backend: next_backend.Backend, device: core_defs.Device | None = None):\n", + " u, v, p = run(swm_numpy.ITMAX, backend=backend, device=device)\n", + " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", + " interior_of(u), interior_of(v), interior_of(p)\n", + " )\n", + "\n", + " reference = np.load(\"swm_reference.npz\")\n", + " np.testing.assert_allclose(u_out, reference[\"u\"], atol=ATOL_UV)\n", + " np.testing.assert_allclose(v_out, reference[\"v\"], atol=ATOL_UV)\n", + " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", + "\n", + "\n", + "test_matches_reference(backend, device)\n", + "print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The flow\n", + "\n", + "`u`, `v` and `p` after `STEPS` steps." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "u, v, p = run(STEPS, backend=backend, device=device)\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))\n", + "for ax, field, name in zip(axes, (u, v, p), (\"u\", \"v\", \"p\")):\n", + " image = ax.contourf(interior_of(field).T, levels=20)\n", + " ax.set_title(f\"{name} after {STEPS} steps\")\n", + " ax.set_aspect(\"equal\")\n", + " fig.colorbar(image, ax=ax)\n", + "fig.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Performance comparison\n", + "\n", + "The same model on every backend installed here: the compiled `gtfn` and `dace` backends on\n", + "CPU and GPU, and embedded execution on NumPy, CuPy, JAX and torch arrays, eagerly and\n", + "under `jax.jit` and `torch.compile`. Each backend is first checked against the NumPy\n", + "implementation, then timed on a sweep of grid sizes.\n", + "\n", + "The timed steps skip the halo refresh, which runs on the host between two steps. Their\n", + "results are therefore wrong, but the steps run back to back: GPU work is launched\n", + "asynchronously and the host's dispatch of the next step overlaps with the device's\n", + "execution of the previous one. This emulates real-world use cases: in more complex models the Python dispatch overhead is hidden even on smaller grids.\n", + "\n", + "The first steps include compilation and the first leapfrog step uses different scalars, so\n", + "`WARMUP_STEPS` run before any timing; the first step is reported separately. Then\n", + "`REPEATS` blocks of `TIMED_STEPS` steps are timed, each between two waits for the device,\n", + "and the median time per step over the blocks is reported. The comparison takes minutes, so\n", + "it is opt-in. Start the kernel with `PYTHONOPTIMIZE=1` to time without GT4Py's runtime\n", + "checks." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import importlib.util\n", + "import json\n", + "import statistics\n", + "import time\n", + "\n", + "RUN_PERFORMANCE_COMPARISON = False\n", + "\n", + "GRID_SIZES = (64, 256, 1024, 2048, 4096)\n", + "WARMUP_STEPS = 5\n", + "TIMED_STEPS = 20\n", + "REPEATS = 5\n", + "\n", + "\n", + "def installed(module: str) -> bool:\n", + " return importlib.util.find_spec(module) is not None\n", + "\n", + "\n", + "def comparison_backends() -> dict[str, tuple[next_backend.Backend, core_defs.Device | None]]:\n", + " \"\"\"Every backend whose libraries and devices are available here, with its device.\"\"\"\n", + " try:\n", + " import cupy\n", + "\n", + " gpu = cupy.cuda.runtime.getDeviceCount() > 0\n", + " except (ImportError, RuntimeError):\n", + " gpu = False\n", + "\n", + " backends = {\"dace_cpu\": (gtx.dace_cpu, None)}\n", + " if gpu:\n", + " backends[\"dace_gpu\"] = (gtx.dace_gpu, None)\n", + " backends[\"gtfn_cpu\"] = (gtx.gtfn_cpu, None)\n", + " if gpu:\n", + " backends[\"gtfn_gpu\"] = (gtx.gtfn_gpu, None)\n", + " backends[\"numpy\"] = (gtx_experimental.embedded_numpy, None)\n", + " if gpu:\n", + " backends[\"cupy\"] = (gtx_experimental.embedded_cupy, None)\n", + " if installed(\"jax\"):\n", + " import jax\n", + "\n", + " device = CUDA if jax.default_backend() == \"gpu\" else CPU\n", + " label = \"cuda\" if device is CUDA else \"cpu\"\n", + " backends[f\"jax [{label}]\"] = (gtx_experimental.embedded_jax, device)\n", + " backends[f\"jax.jit [{label}]\"] = (gtx_experimental.jax_jit, device)\n", + " if installed(\"torch\"):\n", + " import torch\n", + "\n", + " device = CUDA if torch.cuda.is_available() else None\n", + " label = \"cuda\" if device else \"cpu\"\n", + " backends[f\"torch [{label}]\"] = (gtx_experimental.embedded_torch, device)\n", + " backends[f\"torch.compile [{label}]\"] = (gtx_experimental.torch_compile, device)\n", + " return backends\n", + "\n", + "\n", + "def wait(model: Model) -> None:\n", + " \"\"\"Block until the device has finished every step launched so far.\"\"\"\n", + " for field in (model.u, model.v, model.p, model.uold, model.vold, model.pold):\n", + " buffer = field.ndarray\n", + " library = type(buffer).__module__.split(\".\")[0]\n", + " if hasattr(buffer, \"block_until_ready\"):\n", + " buffer.block_until_ready()\n", + " elif library == \"cupy\":\n", + " buffer.device.synchronize()\n", + " elif library == \"torch\" and buffer.is_cuda:\n", + " import torch\n", + "\n", + " torch.cuda.synchronize(buffer.device)\n", + "\n", + "\n", + "def time_steps(\n", + " size: int, backend: next_backend.Backend, device: core_defs.Device | None\n", + ") -> dict[str, Any]:\n", + " \"\"\"Return the time of the first step and the time per step of each timed block.\"\"\"\n", + " model = Model(size, size, backend=backend, device=device)\n", + "\n", + " start = time.perf_counter()\n", + " model.advance(1, periodic=False)\n", + " wait(model)\n", + " first_step = time.perf_counter() - start\n", + " model.advance(WARMUP_STEPS - 1, periodic=False)\n", + "\n", + " per_step = []\n", + " for _ in range(REPEATS):\n", + " wait(model)\n", + " start = time.perf_counter()\n", + " model.advance(TIMED_STEPS, periodic=False)\n", + " wait(model)\n", + " per_step.append((time.perf_counter() - start) / TIMED_STEPS)\n", + "\n", + " if not all(np.isfinite(field.asnumpy()).all() for field in (model.u, model.v, model.p)):\n", + " raise FloatingPointError(\"non-finite fields after the timed steps\")\n", + " return {\"first_step\": first_step, \"per_step\": per_step}\n", + "\n", + "\n", + "def compare(grid_sizes=GRID_SIZES) -> dict[str, dict[int, dict[str, Any]]]:\n", + " \"\"\"Validate every backend, then time it on every grid size.\"\"\"\n", + " timings = {}\n", + " for name, (comparison_backend, comparison_device) in comparison_backends().items():\n", + " test_matches_numpy(comparison_backend, comparison_device)\n", + " timings[name] = {}\n", + " for size in grid_sizes:\n", + " timings[name][size] = time_steps(size, comparison_backend, comparison_device)\n", + " median = 1e3 * statistics.median(timings[name][size][\"per_step\"])\n", + " print(f\"{name:24} {size:5}^2 {median:10.3f} ms/step\", flush=True)\n", + " return timings\n", + "\n", + "\n", + "def report(timings: dict[str, dict[int, dict[str, Any]]]) -> None:\n", + " sizes = list(next(iter(timings.values())))\n", + " header = \"\".join(f\"{f'{size}^2':>12}\" for size in sizes)\n", + " print(f\"{'median ms/step':24}{header} {'first step [s]':>16}\")\n", + " for name, by_size in timings.items():\n", + " steady = \"\".join(\n", + " f\"{1e3 * statistics.median(result['per_step']):12.3f}\" for result in by_size.values()\n", + " )\n", + " first = \"/\".join(f\"{result['first_step']:.2f}\" for result in by_size.values())\n", + " print(f\"{name:24}{steady} {first:>16}\")\n", + "\n", + " fig, ax = plt.subplots(figsize=(7, 4.5))\n", + " for name, by_size in timings.items():\n", + " points = [size * size for size in by_size]\n", + " medians = [1e3 * statistics.median(result[\"per_step\"]) for result in by_size.values()]\n", + " ax.loglog(points, medians, marker=\"o\", label=name)\n", + " ax.set_xlabel(\"grid points\")\n", + " ax.set_ylabel(\"median time per step [ms]\")\n", + " ax.legend(fontsize=\"small\")\n", + " fig.tight_layout()\n", + "\n", + "\n", + "if RUN_PERFORMANCE_COMPARISON:\n", + " timings = compare()\n", + " with open(\"swm_timings.json\", \"w\") as file:\n", + " json.dump(timings, file)\n", + " report(timings)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## References\n", + "\n", + "Sadourny, R. (1975). The dynamics of finite-difference models of the shallow-water\n", + "equations. *Journal of the Atmospheric Sciences*, 32(4), 680-689.\n", + "[doi:10.1175/1520-0469(1975)032<0680:TDOFDM>2.0.CO;2](https://doi.org/10.1175/1520-0469(1975)032%3C0680:TDOFDM%3E2.0.CO;2)\n", + "\n", + "The benchmark itself --- its configuration, initial condition and reference data --- is\n", + "[NCAR/SWM](https://github.com/NCAR/SWM), which implements the same model across a range of\n", + "languages and programming models." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/examples/swm/swm_numpy.py b/examples/swm/swm_numpy.py new file mode 100644 index 0000000000..7db27aa980 --- /dev/null +++ b/examples/swm/swm_numpy.py @@ -0,0 +1,164 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +NumPy reference for the shallow water model example. + +Companion to `swm.ipynb`. The model is doubly periodic, so periodicity is expressed here +with `numpy.roll` on interior-only arrays of shape `(M, N)` -- there is no halo. The +notebook's GT4Py version instead carries one halo cell per side and updates it explicitly, +which is what makes the two implementations worth comparing. +""" + +from __future__ import annotations + +import numpy as np + + +# Model constants of the NCAR/SWM benchmark configuration. +M = 16 +N = 16 +DX = 100000.0 +DY = 100000.0 +DT = 90.0 +ALPHA = 0.001 +A = 1000000.0 +P_MEAN = 50000.0 +ITMAX = 4000 + + +def avg_x(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, -1, axis=0) + f) + + +def avg_y(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, -1, axis=1) + f) + + +def avg_x_staggered(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, 1, axis=0) + f) + + +def avg_y_staggered(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, 1, axis=1) + f) + + +def delta_x(dx: float, f: np.ndarray) -> np.ndarray: + return (np.roll(f, -1, axis=0) - f) / dx + + +def delta_y(dy: float, f: np.ndarray) -> np.ndarray: + return (np.roll(f, -1, axis=1) - f) / dy + + +def delta_x_staggered(dx: float, f: np.ndarray) -> np.ndarray: + return (f - np.roll(f, 1, axis=0)) / dx + + +def delta_y_staggered(dy: float, f: np.ndarray) -> np.ndarray: + return (f - np.roll(f, 1, axis=1)) / dy + + +def initial_conditions( + m: int = M, n: int = N, dx: float = DX, dy: float = DY, a: float = A, p_mean: float = P_MEAN +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Return the initial `u`, `v`, `p` on the interior grid, each of shape `(m, n)`. + + The velocity field is derived from a doubly periodic stream function + `psi = a * sin(2*pi*(i+0.5)/m) * sin(2*pi*(j+0.5)/n)`. + """ + d_i = 2.0 * np.pi / m + d_j = 2.0 * np.pi / n + el = n * dx + pcf = (np.pi * np.pi * a * a) / (el * el) + + psi = ( + a + * np.sin((np.arange(0, m + 1).reshape(-1, 1) + 0.5) * d_i) + * np.sin((np.arange(0, n + 1) + 0.5) * d_j) + ) + p = ( + pcf + * (np.cos(2.0 * np.arange(0, m).reshape(-1, 1) * d_i) + np.cos(2.0 * np.arange(0, n) * d_j)) + + p_mean + ) + u = -(psi[1:, 1:] - psi[1:, :-1]) / dy + v = (psi[1:, 1:] - psi[:-1, 1:]) / dx + + return u, v, p + + +def timestep( + u: np.ndarray, + v: np.ndarray, + p: np.ndarray, + uold: np.ndarray, + vold: np.ndarray, + pold: np.ndarray, + dx: float, + dy: float, + tdt: float, + alpha: float, +) -> tuple[np.ndarray, ...]: + """One leapfrog step with a Robert-Asselin time filter. Returns the six updated fields.""" + cu = avg_x(p) * u + cv = avg_y(p) * v + z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p)) + h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v)) + + unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt + vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt + pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt + + uold_new = u + alpha * (unew - 2.0 * u + uold) + vold_new = v + alpha * (vnew - 2.0 * v + vold) + pold_new = p + alpha * (pnew - 2.0 * p + pold) + + return unew, vnew, pnew, uold_new, vold_new, pold_new + + +def run( + itmax: int, + m: int = M, + n: int = N, + dx: float = DX, + dy: float = DY, + dt: float = DT, + alpha: float = ALPHA, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Integrate `itmax` steps and return the final interior `u`, `v`, `p`.""" + u, v, p = initial_conditions(m, n, dx, dy) + uold, vold, pold = u.copy(), v.copy(), p.copy() + + for cycle in range(itmax): + # The first step is forward Euler and unfiltered; afterwards leapfrog with tdt = 2*dt. + tdt = dt if cycle == 0 else 2.0 * dt + step_alpha = 0.0 if cycle == 0 else alpha + unew, vnew, pnew, uold, vold, pold = timestep( + u, v, p, uold, vold, pold, dx, dy, tdt, step_alpha + ) + u, v, p = unew, vnew, pnew + + return u, v, p + + +def to_reference_layout( + u: np.ndarray, v: np.ndarray, p: np.ndarray +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Convert interior `(M, N)` fields to the `(M+1, N+1)` layout of the NCAR/SWM dumps. + + The extra row and column are the periodic images the original Fortran carried + explicitly; which side they sit on differs per field because of the C-grid staggering. + """ + return ( + np.pad(u, ((1, 0), (0, 1)), mode="wrap"), + np.pad(v, ((0, 1), (1, 0)), mode="wrap"), + np.pad(p, ((0, 1), (0, 1)), mode="wrap"), + ) diff --git a/examples/swm/swm_reference.npz b/examples/swm/swm_reference.npz new file mode 100644 index 0000000000..6a9ca4af2f Binary files /dev/null and b/examples/swm/swm_reference.npz differ