Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 112 additions & 46 deletions examples/swm/swm.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"\n",
"import gt4py.next as gtx\n",
"from gt4py.next import backend as next_backend, experimental as gtx_experimental\n",
"from gt4py.next.experimental import concat_where\n",
"from gt4py._core import definitions as core_defs\n",
"\n",
"import swm_numpy"
Expand Down Expand Up @@ -112,7 +113,8 @@
"\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."
"again. The grid size `m`, `n` is a static parameter of the program below, since the halo is\n",
"filled by shifting by it."
]
},
{
Expand Down Expand Up @@ -217,6 +219,41 @@
" return (f - f(J - 1)) / dy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Periodicity\n",
"\n",
"The domain wraps in both directions, and the wrap is expressed inside the field operator:\n",
"`concat_where` selects a sub-domain and takes its values from the opposite edge. At\n",
"$i = -1$ the field is read at $i + M$, at $i = M$ at $i - M$, and likewise in $j$.\n",
"\n",
"Each `concat_where` rebinds `f`, so the $j$ pass sees the already-$i$-corrected field and\n",
"the four corners come out right. Writing the four as one simultaneous expression would\n",
"leave them wrong.\n",
"\n",
"The shift distance is `m`, an argument rather than a literal. Domain inference resolves\n",
"the composition: at $i = -1$ the result comes from $i = M-1$, so the interior is all that\n",
"is ever demanded of the operator that produced it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@gtx.field_operator\n",
"def make_periodic(f: IJField, m: gtx.int32, n: gtx.int32) -> IJField:\n",
" \"\"\"Fill the one-cell halo of `f` from the opposite edge.\"\"\"\n",
" f = concat_where(I == -1, f(I + m), f)\n",
" f = concat_where(I == m, f(I - m), f)\n",
" f = concat_where(J == -1, f(J + n), f)\n",
" f = concat_where(J == n, f(J - n), f)\n",
" return f"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -249,6 +286,8 @@
" dy: gtx.float64,\n",
" tdt: gtx.float64,\n",
" alpha: gtx.float64,\n",
" m: gtx.int32,\n",
" n: gtx.int32,\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",
Expand All @@ -264,21 +303,23 @@
" 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"
" return (\n",
" make_periodic(unew, m, n),\n",
" make_periodic(vnew, m, n),\n",
" make_periodic(pnew, m, n),\n",
" uold_new,\n",
" vold_new,\n",
" pold_new,\n",
" )"
]
},
{
"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."
"The prognostic fields are written over the whole domain, halo included, while the\n",
"filtered levels only need the interior. A `program` lets each output declare its own\n",
"domain."
]
},
{
Expand All @@ -287,20 +328,47 @@
"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)})"
"@gtx.program\n",
"def timestep_program(\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",
" unew: IJField,\n",
" vnew: IJField,\n",
" pnew: IJField,\n",
" m: gtx.int32,\n",
" n: gtx.int32,\n",
"):\n",
" timestep(\n",
" u,\n",
" v,\n",
" p,\n",
" uold,\n",
" vold,\n",
" pold,\n",
" dx,\n",
" dy,\n",
" tdt,\n",
" alpha,\n",
" m,\n",
" n,\n",
" out=(unew, vnew, pnew, uold, vold, pold),\n",
" domain=(\n",
" {I: (-1, m + 1), J: (-1, n + 1)},\n",
" {I: (-1, m + 1), J: (-1, n + 1)},\n",
" {I: (-1, m + 1), J: (-1, n + 1)},\n",
" {I: (0, m), J: (0, n)},\n",
" {I: (0, m), J: (0, n)},\n",
" {I: (0, m), J: (0, n)},\n",
" ),\n",
" )"
]
},
{
Expand All @@ -313,11 +381,9 @@
"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."
"A `Model` holds the fields of one integration and the program bound to its backend, so\n",
"that repeated calls of `advance` continue the same integration with the same compiled or\n",
"traced program. Nothing here touches the halo: it is filled inside the timestep."
]
},
{
Expand All @@ -337,8 +403,7 @@
" ):\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.step = timestep_program.with_backend(backend).with_static_params(\"m\", \"n\")\n",
" self.cycle = 0\n",
"\n",
" def as_halo_field(a: np.ndarray) -> gtx.Field:\n",
Expand All @@ -349,10 +414,12 @@
" 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",
" self.unew, self.vnew, self.pnew = (\n",
" gtx.zeros(self.domain, dtype=gtx.float64, allocator=backend, device=device)\n",
" for _ in range(3)\n",
" )\n",
"\n",
" def advance(self, cycles: int, periodic: bool = True) -> None:\n",
" def advance(self, cycles: int) -> None:\n",
" \"\"\"Integrate `cycles` more steps.\"\"\"\n",
" for _ in range(cycles):\n",
" tdt = DT if self.cycle == 0 else 2.0 * DT\n",
Expand All @@ -369,15 +436,14 @@
" DY,\n",
" tdt,\n",
" alpha,\n",
" out=(self.unew, self.vnew, self.pnew, self.uold, self.vold, self.pold),\n",
" domain=self.interior,\n",
" self.unew,\n",
" self.vnew,\n",
" self.pnew,\n",
" self.m,\n",
" self.n,\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",
Expand Down Expand Up @@ -513,10 +579,10 @@
"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",
"The steps run back to back, with no host work in between: 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",
"execution of the previous one. This emulates real-world use cases: in more complex models\n",
"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",
Expand Down Expand Up @@ -606,16 +672,16 @@
" model = Model(size, size, backend=backend, device=device)\n",
"\n",
" start = time.perf_counter()\n",
" model.advance(1, periodic=False)\n",
" model.advance(1)\n",
" wait(model)\n",
" first_step = time.perf_counter() - start\n",
" model.advance(WARMUP_STEPS - 1, periodic=False)\n",
" model.advance(WARMUP_STEPS - 1)\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",
" model.advance(TIMED_STEPS)\n",
" wait(model)\n",
" per_step.append((time.perf_counter() - start) / TIMED_STEPS)\n",
"\n",
Expand Down
17 changes: 12 additions & 5 deletions src/gt4py/next/ffront/foast_passes/type_deduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,11 +698,18 @@ def _deduce_binop_type(
):
# e.g. `IDim+1` or `IDim+0.5`
if not isinstance(right, foast.Constant):
raise errors.DSLError(
right.location,
"Cartesian offsets are only supported with a literal right-hand side, "
"e.g. 'IDim + 1', but not 'IDim + expr'.",
)
# e.g. `IDim+offset` with a runtime `offset`; a non-literal offset can not be
# resolved to a staggered dimension, hence only integral offsets are allowed.
if not type_info.is_integral(right.type):
raise errors.DSLError(
right.location,
"Cartesian offsets with a non-literal right-hand side must be integral, "
f"but '{right.type}' is not.",
hints=[
"Use a literal such as 'IDim + 0.5' to shift to the staggered dimension."
],
)
return ts.OffsetType(source=left.type.dim, target=(left.type.dim,))
offset_index = right.value
if node.op == dialect_ast_enums.BinaryOperator.SUB:
offset_index *= -1
Expand Down
14 changes: 14 additions & 0 deletions src/gt4py/next/ffront/foast_to_gtir.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,20 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
)
)
)(current_expr)
# `field(Dim + expr)` (where `expr` is a runtime integer)
case foast.BinOp(
op=dialect_ast_enums.BinaryOperator.ADD | dialect_ast_enums.BinaryOperator.SUB,
left=foast.LocatedNode(type=ts.DimensionType(dim=common.Dimension() as dim)),
right=right,
):
offset = self.visit(right, **kwargs)
if arg.op == dialect_ast_enums.BinaryOperator.SUB:
offset = im.call("neg")(offset)
current_expr = im.as_fieldop(
im.lambda_("__it")(
im.deref(im.shift(im.cartesian_offset(dim), offset)("__it"))
)
)(current_expr)
# `field(as_offset(Off, offset_field))`
case foast.Call(func=foast.Name(id="as_offset")):
func_args = arg
Expand Down
28 changes: 28 additions & 0 deletions src/gt4py/next/iterator/transforms/normalize_shifts.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from gt4py.eve import NodeTranslator, PreserveLocationVisitor
from gt4py.next.iterator import ir
from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm
from gt4py.next.type_system import type_specifications as ts


class NormalizeShifts(PreserveLocationVisitor, NodeTranslator):
Expand All @@ -32,3 +34,29 @@ def visit_FunCall(self, node: ir.FunCall):
args=node.args[0].args,
)
return node


class CanonicalizeShiftOffsets(PreserveLocationVisitor, NodeTranslator):
"""
Turn integral `Literal` shift offsets into `OffsetLiteral`s.

A shift offset that is only known after inlining, e.g. a static program argument used as in
`field(IDim + offset)`, reaches the shift as an `ir.Literal`. Downstream consumers (shift
tracing, backend lowering) expect the canonical `ir.OffsetLiteral` that `ir_makers.shift`
produces for offsets that are literal from the start.
"""

def visit_FunCall(self, node: ir.FunCall) -> ir.Node:
node = self.generic_visit(node)
if cpm.is_call_to(node, "shift"):
return ir.FunCall(
fun=node.fun,
args=[
ir.OffsetLiteral(value=int(arg.value))
if isinstance(arg, ir.Literal)
and arg.type.kind in (ts.ScalarKind.INT32, ts.ScalarKind.INT64)
else arg
for arg in node.args
],
)
return node
7 changes: 6 additions & 1 deletion src/gt4py/next/iterator/transforms/pass_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@
from gt4py.next.iterator.transforms.inline_lambdas import InlineLambdas
from gt4py.next.iterator.transforms.inline_scalar import InlineScalar
from gt4py.next.iterator.transforms.merge_let import MergeLet
from gt4py.next.iterator.transforms.normalize_shifts import NormalizeShifts
from gt4py.next.iterator.transforms.normalize_shifts import (
CanonicalizeShiftOffsets,
NormalizeShifts,
)
from gt4py.next.iterator.transforms.unroll_reduce import UnrollReduce
from gt4py.next.iterator.type_system.inference import infer

Expand Down Expand Up @@ -181,6 +184,7 @@ def apply_common_transforms(
) # domain inference does not support dynamic offsets yet
ir = infer_domain_ops.InferDomainOps.apply(ir)
ir = concat_where.canonicalize_domain_argument(ir)
ir = CanonicalizeShiftOffsets().visit(ir)

ir = infer_domain.infer_program(
ir,
Expand Down Expand Up @@ -302,6 +306,7 @@ def apply_fieldview_transforms(
ir = infer_domain_ops.InferDomainOps.apply(ir)
ir = concat_where.canonicalize_domain_argument(ir)
ir = ConstantFolding.apply(ir) # type: ignore[assignment] # always an itir.Program
ir = CanonicalizeShiftOffsets().visit(ir)

ir = infer_domain.infer_program(
ir,
Expand Down
Loading