diff --git a/docs/development/ADRs/next/0024-Compilation-Runners.md b/docs/development/ADRs/next/0024-Compilation-Runners.md index 23c173a9ba..4614220a4e 100644 --- a/docs/development/ADRs/next/0024-Compilation-Runners.md +++ b/docs/development/ADRs/next/0024-Compilation-Runners.md @@ -7,7 +7,7 @@ tags: [] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) - **Created**: 2026-07-08 -- **Updated**: 2026-10-27 +- **Updated**: 2026-12-02 In the context of ahead-of-time compilation of many program variants (`CompiledProgramsPool`), facing a thread pool that can neither hide the @@ -94,10 +94,11 @@ otherwise raised when the affected program variant is first called. ### Graceful degradation -Backends that customize `Backend.compile` (which cannot be decomposed) or -whose executor is not picklable are compiled in the calling thread, with a -warning stating the reason. A non-conforming backend keeps working — it just -does not offload. +Backends that customize `Backend.compile` (which cannot be decomposed) or whose executor +is not picklable are compiled in the calling thread, with a warning stating the reason. +So is a task that references a class declared in an interactive `__main__` +([ADR 0030](0030-Dimensions_As_Nominal_Types.md)). A non-conforming backend keeps working — it +just does not offload. ## Alternatives considered diff --git a/docs/development/ADRs/next/0026-Staggered_Dimensions.md b/docs/development/ADRs/next/0026-Staggered_Dimensions.md index af2c11d9ae..65364d1524 100644 --- a/docs/development/ADRs/next/0026-Staggered_Dimensions.md +++ b/docs/development/ADRs/next/0026-Staggered_Dimensions.md @@ -7,7 +7,13 @@ tags: [] - **Status**: valid - **Authors**: Till Ehrengruber (@tehrengruber) - **Created**: 2026-07-08 -- **Updated**: 2026-07-09 +- **Updated**: 2026-12-02 + +> The *encoding* of this record is superseded by +> [ADR 0030](0030-Dimensions_As_Nominal_Types.md): a staggered dimension is the +> real, interned class `Staggered[D]`, not a name prefix. The semantics below -- +> half-integer positions, the shift convention, and the gtfn treatment -- are +> unchanged. A **staggered dimension** is a dimension sitting at the **half-integer** positions of a base dimension. For example, in a cell-centered 2D Cartesian grid @@ -58,22 +64,26 @@ index arithmetic is encoded in `common.connectivity_for_cartesian_shift`. ## Encoding -A staggered dimension is encoded as its base dimension's name with the internal -`_Staggered` prefix (`common._STAGGERED_PREFIX`), rather than as a new attribute -on `Dimension`. The helpers `is_staggered`, `flip_staggered` and -`as_non_staggered` operate purely on that prefix. - -Dimensions are identified by their **name** and appear throughout the toolchain -in more than one form: as a `common.Dimension` instance, but also as an -`itir.AxisLiteral` (and as plain strings in generated backend code). Adding a -"staggered" flag to `Dimension` would have required threading it through every one -of these representations and every place that constructs, compares, or lowers a -dimension — a large, invasive change touching the frontend, the IR, and all -backends. Carrying the marker in the name instead means the frontend and IR pass -it through unchanged, without any of those formats having to learn about -staggering. The leading underscore marks the prefix as internal — user code goes -through the `is_staggered` / `flip_staggered` / `as_non_staggered` helpers -(exported from `gt4py.next`) rather than manipulating the name directly. +A staggered dimension was encoded as its base dimension's name with the internal +`_Staggered` prefix, rather than as a new attribute on `Dimension`. Since +[ADR 0030](0030-Dimensions_As_Nominal_Types.md) it is the class +`common.Staggered[D]`, whose identity is the class itself; the helpers +`is_staggered`, `flip_staggered` and `as_non_staggered` are unchanged in meaning +and now read the class's `base`. Only a declared +`CartesianAxisIndex` can be staggered, which makes a doubly staggered dimension +and a staggered mesh location type errors. + +The rationale of the superseded encoding: dimensions were identified by their **name** +and appeared throughout the toolchain in more than one form: as a `common.Dimension` +instance, but also as an `itir.AxisLiteral` (and as plain strings in generated backend +code). Adding a "staggered" flag to `Dimension` would have required threading it through +every one of these representations and every place that constructs, compares, or lowers +a dimension — a large, invasive change touching the frontend, the IR, and all backends. +Carrying the marker in the name instead meant the frontend and IR passed it through +unchanged, without any of those formats having to learn about staggering. The leading +underscore marked the prefix as internal — user code went through the `is_staggered` / +`flip_staggered` / `as_non_staggered` helpers (exported from `gt4py.next`) rather than +manipulating the name directly. ## Dimension Constraints @@ -87,8 +97,9 @@ by the `as_non_staggered` name. In gtfn a staggered dimension is emitted as a C++ `using` alias of its base dimension's tag (`_add_staggered_aliases` in `itir_to_gtfn_ir.py`): e.g. -`_StaggeredIDim_t` becomes an alias of `IDim_t`, and `visit_AxisLiteral` -correspondingly emits the base dimension name. +the staggered tag's mangled name becomes an alias of the base tag's mangled type +(`_t`). Axis literals keep the staggered name, which the alias makes the +same type. The reason is that gtfn lowers a shift to an integer offset along a SID axis, and a half-integer shift produces exactly such an offset (see diff --git a/docs/development/ADRs/next/0030-Dimensions_As_Nominal_Types.md b/docs/development/ADRs/next/0030-Dimensions_As_Nominal_Types.md new file mode 100644 index 0000000000..83a677e76e --- /dev/null +++ b/docs/development/ADRs/next/0030-Dimensions_As_Nominal_Types.md @@ -0,0 +1,207 @@ +--- +tags: [] +--- + +# Dimensions as Nominal Types + +- **Status**: accepted +- **Authors**: Enrique González Paredes (@egparedes) +- **Created**: 2026-09-18 +- **Updated**: 2026-12-03 + +A concrete dimension becomes a **class**, and an index along it an **instance** of +that class — the shape `enum.Enum` uses, where the class is the collection and +the instances are its members: + +```python +class IDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +class Cell(gtx.DimensionIndex): ... # a mesh location: not a Cartesian axis + + +IDim # the dimension -- annotated `gtx.Dimension` +IDim(0) # an index into it -- annotated `IDim` +``` + +so `gtx.Field[gtx.Dims[IDim], gtx.float64]` is valid for any PEP 484 checker with +no GT4Py mypy plugin. + +A dimension's **identity is the Python type** in user code, embedded execution and +program calls, and its `tag` — the string that crosses into the +IR and the generated code — is its **qualified Python name**, `f"{cls.__module__}:{cls.__qualname__}"` (a staggered dimension embeds its +base's full tag). Below the frontend a dimension is a `DimensionRef` value naming that +class (see *Two levels* below). Dimensions on a Cartesian axis, with index arithmetic +and a staggered partner, subclass `CartesianAxisIndex`; mesh locations subclass +`DimensionIndex` directly. + +## Context + +`Dimension` was a frozen dataclass whose instances are values, not types. Two +consequences drove this change. + +**Dimensions were not usable as types.** `Field[[IDim], float64]` needed a +dedicated mypy plugin that substituted at most four distinct placeholders per run, +made `TypeVar`s over dimensions impossible, and served only mypy — no other checker. +See #2503. + +**Names are load-bearing in too many places.** A neighbor connectivity is +currently spread over four independently authored strings that must agree by +string equality and are never checked against each other at declaration time: the +`FieldOffset` tag, the Python variable it is bound to, the local `Dimension`'s +name, and the `offset_provider` key. Whichever one reaches +`common.get_offset` depends on the execution path and the operation. Making a +dimension's identity its Python type is the prerequisite for collapsing those +names into one declaration (a follow-up ADR covers the connectivity half). + +## Decision + +### Identity is the Python type; the tag is the qualified name + +Two dimension classes are the same dimension if and only if they are the same +class. The static view (checkers see nominal types) and the runtime view +(equality is `is`) agree by construction, and the tag, unique among importable +classes, is also a valid IR spelling. + +The alternative — `(name, kind)` value equality plus an interning registry, so +that independently declared same-named dimensions stay interchangeable — was +considered and rejected. It decouples the Python type's identity from the IR's, +and needs a name-keyed registry. It also cannot give a dimension nested inside another +declaration a unique name without further convention, which the connectivity +work requires. + +One concrete example: take two distinct classes, both named `I`. Under `(name, kind)` +equality they compare equal, so `typing` caches `Field[Dims[I]]` once and returns that +same object for the other class. A type checker sees two types where the runtime sees +one. Under type identity they are two types in both views. + +### Two levels: classes in user code, `DimensionRef` values in the toolchain + +Classes stay the identity in user code, in embedded execution and wherever a call +enters GT4Py. Type specifications, the IR and the backends instead carry a +`DimensionRef`: an immutable, interned value with the class's module, qualname, +`kind`, whether it is a Cartesian axis and, for a staggered dimension, its base. The +conversion happens once per class, where classes enter the toolchain (type translation +of annotations and arguments, offset providers, scan axes). + +Below the frontend, two refs are equal if all their fields are: the same qualified +name, `kind`, Cartesian axis flag and staggered base is the same dimension. The IR is therefore +self-contained and a compile task ships no user classes, except, for now, the +connectivities of the offset provider, which still hold dimension classes. + +Because a re-run notebook cell gives an *equal* ref for a *new* class, program calls +still compare by class, in the same `__debug__`-only argument check as the type +check: when a program, or a field operator called as one, receives a field, +named-collection element or connectivity built on a different class of the same +name as a dimension its annotations, scan axis or `FieldOffset`s declare, the call +is rejected, embedded or compiled. + +### Consequences of the tag being a qualified name + +1. **Nothing is imported from a tag.** The roundtrip backend, which runs the generated + program embedded, on classes, takes them from the fields and connectivities of each + call. It synthesizes a class from the ref only for a dimension that none of them + has: such a dimension exists only inside the program. + +2. **Dimensions must be importable to be pickled**, i.e. declared at module level. + `__init_subclass__` rejects a `` qualname as an early heuristic; it is + neither necessary nor sufficient (`type("Dyn", ...)` inside a function passes, + a class deleted after creation passes), so the authoritative check remains + pickle's own `save_global`. + + A spawn worker cannot re-import an **interactive `__main__`** (a notebook, the + REPL, `python -c`), so a compile job that holds a class declared there is compiled + in the calling thread, with a warning. Scripts keep parallel compilation. + +3. **No registry.** Module-level classes pickle by reference. + +4. **Cache fingerprints depend on module paths.** A dimension is fingerprinted by + qualified name, `kind` and Cartesian axis flag (a staggered one through its base), so + moving a declaration to another module invalidates compiled artifacts. Re-running a + notebook cell that declares the same dimension reuses them, unless one of these changed. + +5. **Generated identifiers need injective mangling.** A tag is not a valid C++, + DaCe or `eve` identifier, so backends escape it, without mapping two tags to + one identifier. + +6. **Staggered dimensions become a real parametrized type.** ADR 0026's + `_Staggered` *name prefix* cannot survive type identity: `Dimension(f"_Staggered{name}")` + names no importable type, and the prefix cannot recover the base dimension's + module. `Staggered[D]` replaces it and supersedes that part of ADR 0026. + + `Staggered[KDim]` is a **real class**, built and interned on first use (a PEP 695 + generic would give a `typing` alias, not a class). It is a *different* dimension, so + it does not subclass `KDim` and only inherits its `kind`. It keeps its base, and its + tag is `[]`, so its ref is rebuilt from the tag without importing + anything. The intern table is keyed by the base class, like `typing`'s subscription + cache, not by a user-authored name. + +### Cartesian axes are a level of the hierarchy + +A **Cartesian axis** is an oriented integer line, i.e. a two-way infinite path graph: a +0-cell at each integer and a 1-cell between consecutive ones. Integer shifts (`D + n`) +preserve these two *cell classes* and half-integer shifts swap them (ADR 0026); a +`CartesianAxisIndex` names one class and `Staggered[...]` the other. A `Domain` selects a +range of it; periodic grids are not modelled. Mesh locations have no such translation: +their neighbours come from connectivity tables. Loosely, a declared dimension is itself +called "a Cartesian axis". Two levels below the root encode this: + +``` +DimensionIndex # the root; every `type[DimensionIndex]` keeps its meaning +├── AnyCartesianAxisIndex # either cell class of a Cartesian axis +│ ├── CartesianAxisIndex # a declared cell class: what users subclass +│ └── Staggered[D: CartesianAxisIndex] # its derived partner +└── (direct subclasses) # mesh locations, and index spaces without geometry +``` + +Both levels sit *below* `DimensionIndex`, so `Staggered[K]` stays a `DimensionIndex` +and no annotation or `issubclass` guard in the tree widens. The bound is on the +*declared* level, and `Staggered[K]` is only an `AnyCartesianAxisIndex`, so: + +| Rejected | Statically (mypy, pyright) | At runtime | +| ----------------------------------------------- | -------------------------- | --------------------------------------------- | +| `Staggered[Staggered[K]]` | `[type-var]` | `TypeError` | +| `Staggered[Cell]`, staggering a local dimension | `[type-var]` | `TypeError` | +| `Cell + 1`, `Cell - 1` | `[operator]` | `TypeError`; a `DSLError` in a field operator | + +**Open question:** The hierarchy says what a dimension is, not how dimensions relate to +each other: the Cartesian axes `I` and `J` are +orthogonal factors of a product grid, each its own horizontal direction, while the +mesh locations `Cell`, `Edge` and `Vertex` of a typical model are different entity +sets on *one* shared horizontal space. Expressing that relation belongs with a future +entity level (e.g. a `LocationIndex`) and is left to a later ADR. + +### `Dimension` is annotation-only + +`common.Dimension` becomes an alias for `type[DimensionIndex]`. + +### Naming + +A dimension's name is `.tag` (typed `common.Tag`) and `.value` keeps its meaning as the +index position, on the *instance*. + +### Display uses the unqualified name + +The `tag` is qualified, but it is *identity and IR spelling*, not a display name. +User-facing diagnostics use `cls.__qualname__` by default, so a field reads like +`Field[[IDim], float64]`. + +### Equality between dimensions is identity + +`I == J` is `True` only for the same class. With an integer, `I == 5` builds a `Domain` +instead, for `concat_where`. + +## Alternatives considered + +- **`(name, kind)` value equality with an interning registry.** See Decision. + +## References + +- Resolves, without a plugin, the static-typing gap reported in #2503 (closed). +- Supersedes the `_Staggered` name-prefix mechanism of + [ADR 0026](0026-Staggered_Dimensions.md); the indexing convention there is + unchanged. +- Consequence for the build cache of [ADR 0023](0023-Fingerprinting.md). diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index 9132ffe478..a3aea6d1b1 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -22,6 +22,7 @@ Writing a new ADR is simple: - [0021 - Argument Descriptors](0021-Argument-Descriptors.md) - [0023 - Fingerprinting](0023-Fingerprinting.md) - [0026 - Staggered Dimensions](0026-Staggered_Dimensions.md) +- [0030 - Dimensions as Nominal Types](0030-Dimensions_As_Nominal_Types.md) ### Frontend and Parsing #frontend diff --git a/docs/user/next/dsl/field-operators.md b/docs/user/next/dsl/field-operators.md index 004142bd4f..b9ad71aceb 100644 --- a/docs/user/next/dsl/field-operators.md +++ b/docs/user/next/dsl/field-operators.md @@ -23,8 +23,8 @@ import numpy as np import gt4py.next as gtx -I = gtx.Dimension("I") -J = gtx.Dimension("J") +class I(gtx.CartesianAxisIndex): ... +class J(gtx.CartesianAxisIndex): ... ``` The examples use these fields: diff --git a/docs/user/next/dsl/premap.md b/docs/user/next/dsl/premap.md index c8e4a5eead..23699c63ea 100644 --- a/docs/user/next/dsl/premap.md +++ b/docs/user/next/dsl/premap.md @@ -46,7 +46,7 @@ import gt4py.next as gtx `i + 1`: ```{code-cell} ipython3 -I = gtx.Dimension("I") +class I(gtx.CartesianAxisIndex): ... IField = gtx.Field[gtx.Dims[I], gtx.float64] a = gtx.as_field({I: 6}, np.array([0.0, 1.0, 4.0, 9.0, 16.0, 25.0])) @@ -172,13 +172,13 @@ dimensions, the offsets `E2C` (the cells of every edge) and `C2E` (the edges of every cell), and the connectivity tables behind them. ```{code-cell} ipython3 -Cell = gtx.Dimension("Cell") -Edge = gtx.Dimension("Edge") -E2CDim = gtx.Dimension("E2C", kind=gtx.DimensionKind.LOCAL) -C2EDim = gtx.Dimension("C2E", kind=gtx.DimensionKind.LOCAL) +class Cell(gtx.DimensionIndex): ... +class Edge(gtx.DimensionIndex): ... +class E2CDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... +class C2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... -E2C = gtx.FieldOffset("E2C", source=Cell, target=(Edge, E2CDim)) -C2E = gtx.FieldOffset("C2E", source=Edge, target=(Cell, C2EDim)) +E2C = gtx.FieldOffset(E2CDim.tag, source=Cell, target=(Edge, E2CDim)) +C2E = gtx.FieldOffset(C2EDim.tag, source=Edge, target=(Cell, C2EDim)) edge_to_cell_table = np.array( [[0, -1], [2, -1], [2, -1], [3, -1], [4, -1], [5, -1], @@ -189,8 +189,8 @@ cell_to_edge_table = np.array( ) offset_provider = { - "E2C": gtx.as_connectivity([Edge, E2CDim], codomain=Cell, data=edge_to_cell_table), - "C2E": gtx.as_connectivity([Cell, C2EDim], codomain=Edge, data=cell_to_edge_table), + E2CDim.tag: gtx.as_connectivity([Edge, E2CDim], codomain=Cell, data=edge_to_cell_table), + C2EDim.tag: gtx.as_connectivity([Cell, C2EDim], codomain=Edge, data=cell_to_edge_table), } CellField = gtx.Field[gtx.Dims[Cell], gtx.float64] diff --git a/docs/user/next/dsl/programs.md b/docs/user/next/dsl/programs.md index 3cfb64c858..e7f13b2930 100644 --- a/docs/user/next/dsl/programs.md +++ b/docs/user/next/dsl/programs.md @@ -43,8 +43,8 @@ import numpy as np import gt4py.next as gtx -I = gtx.Dimension("I") -J = gtx.Dimension("J") +class I(gtx.CartesianAxisIndex): ... +class J(gtx.CartesianAxisIndex): ... IJField = gtx.Field[gtx.Dims[I, J], gtx.float64] diff --git a/docs/user/next/dsl/scan-operators.md b/docs/user/next/dsl/scan-operators.md index 6abce97f8d..6b0c0bbe7e 100644 --- a/docs/user/next/dsl/scan-operators.md +++ b/docs/user/next/dsl/scan-operators.md @@ -28,8 +28,8 @@ import numpy as np import gt4py.next as gtx -I = gtx.Dimension("I") -K = gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL) +class I(gtx.CartesianAxisIndex): ... +class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... KField = gtx.Field[gtx.Dims[K], gtx.float64] IKField = gtx.Field[gtx.Dims[I, K], gtx.float64] diff --git a/docs/user/next/index.md b/docs/user/next/index.md index 78f7fddf69..2ed660db48 100644 --- a/docs/user/next/index.md +++ b/docs/user/next/index.md @@ -30,8 +30,8 @@ tags: [remove-stderr] --- import gt4py.next as gtx -I = gtx.Dimension("I") -J = gtx.Dimension("J") +class I(gtx.CartesianAxisIndex): ... +class J(gtx.CartesianAxisIndex): ... IJField = gtx.Field[gtx.Dims[I, J], gtx.float64] @@ -56,8 +56,9 @@ if __name__ == "__main__": Three ideas are behind this code: -- **Fields have named dimensions.** A field is an array defined over a domain - of the grid, and its axes are identified by name instead of by position. +- **Fields have dimensions.** A field is an array defined over a domain + of the grid, and its axes are identified by dimensions, which are classes + such as `I` and `J` above, instead of by position. Neighbors are accessed by calling a field with an offset, `phi(I + 1)`, or through the connectivities of an unstructured mesh. - **Computations are operators on whole fields.** There are no loops and no diff --git a/docs/user/next/python/grids-and-fields.md b/docs/user/next/python/grids-and-fields.md index dae608fb92..9e9fdd9263 100644 --- a/docs/user/next/python/grids-and-fields.md +++ b/docs/user/next/python/grids-and-fields.md @@ -27,13 +27,17 @@ import gt4py.next as gtx ## Dimensions -A `Dimension` is a named axis. Two dimensions are the same if they have the same -name and kind. +A dimension is a class, and an axis of a grid. Cartesian axes subclass +`gtx.CartesianAxisIndex`, which supports index arithmetic such as `I + 1` and +staggering; the optional `kind` argument tells horizontal (the default), +vertical and local dimensions apart. Two dimensions are the same if and only if +they are the same class, so declaring `I` a second time creates a *different* +dimension. ```{code-cell} ipython3 -I = gtx.Dimension("I") -J = gtx.Dimension("J") -K = gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL) +class I(gtx.CartesianAxisIndex): ... +class J(gtx.CartesianAxisIndex): ... +class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... ``` ```{tip} @@ -175,7 +179,7 @@ print(field.asnumpy()) Indexing a field gives another field, a view of a part of the original one. Plain integers and slices are **relative** indices: they count positions from the start of the field, as in NumPy. **Absolute** indices, written -`Dimension(index)`, refer to the indices of the domain. The domain of `field` +`D(index)`, where `D` is a dimension, refer to the indices of the domain. The domain of `field` starts at 2 in the `J` direction, so these two expressions select the same column: @@ -198,11 +202,13 @@ align: center A mesh with 6 cells and 12 edges ``` -Every type of location is a dimension, and fields are allocated as usual: +Every type of location is a dimension too. Mesh locations are not Cartesian +axes, so they subclass `gtx.DimensionIndex`. Fields are allocated as usual: ```{code-cell} ipython3 -Cell = gtx.Dimension("Cell") -Edge = gtx.Dimension("Edge") +class Cell(gtx.DimensionIndex): ... +class Edge(gtx.DimensionIndex): ... + cell_values = gtx.as_field([Cell], np.array([1.0, 1.0, 2.0, 3.0, 5.0, 8.0])) edge_values = gtx.zeros({Edge: 12}) @@ -244,10 +250,11 @@ Three objects describe this relation in GT4Py: ```{code-cell} ipython3 # 1. A local dimension, which numbers the neighbors of each edge (0 and 1) -E2CDim = gtx.Dimension("E2C", kind=gtx.DimensionKind.LOCAL) +class E2CDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... -# 2. An offset, the name used inside operators to go from the edges to their cells -E2C = gtx.FieldOffset("E2C", source=Cell, target=(Edge, E2CDim)) +# 2. An offset, used inside operators to go from the edges to their cells. +# It is named by the tag of the local dimension. +E2C = gtx.FieldOffset(E2CDim.tag, source=Cell, target=(Edge, E2CDim)) # 3. A connectivity, which holds the actual table e2c_connectivity = gtx.as_connectivity([Edge, E2CDim], codomain=Cell, data=edge_to_cell_table) @@ -269,18 +276,19 @@ The offset is only a symbol. This keeps the operators independent of the mesh: the same code runs on a different mesh by providing a different table. ```{important} -Give the same name to the local dimension and to the offset (`"E2C"` above). -The reductions over the neighbors rely on it to find the connectivity. +Name the offset with the `tag` of its local dimension (`E2CDim.tag` above), and +use the same tag as key in the offset provider. The reductions over the +neighbors rely on it to find the connectivity. ``` ### The offset provider When an operator using offsets is called, the connectivities are passed in the -`offset_provider` argument, a dictionary from the names of the offsets to the -connectivities: +`offset_provider` argument, a dictionary from the names of the offsets (the tags +of their local dimensions) to the connectivities: ```{code-cell} ipython3 -offset_provider = {"E2C": e2c_connectivity} +offset_provider = {E2CDim.tag: e2c_connectivity} ``` [Premap and neighbors](../dsl/premap.md#unstructured-meshes) shows how the diff --git a/docs/user/next/python/running.md b/docs/user/next/python/running.md index cf9072bde4..e0917e78e0 100644 --- a/docs/user/next/python/running.md +++ b/docs/user/next/python/running.md @@ -34,8 +34,8 @@ import numpy as np import gt4py.next as gtx from gt4py.next import where -I = gtx.Dimension("I") -J = gtx.Dimension("J") +class I(gtx.CartesianAxisIndex): ... +class J(gtx.CartesianAxisIndex): ... IJField = gtx.Field[gtx.Dims[I, J], gtx.float64] diff --git a/docs/user/next/quickstart.md b/docs/user/next/quickstart.md index 598ad3bf5c..b5f1a91199 100644 --- a/docs/user/next/quickstart.md +++ b/docs/user/next/quickstart.md @@ -33,17 +33,21 @@ C++17 must also be available on the system. ## Dimensions -In GT4Py, the axes of the grid have names. A **dimension** is created once, and -it is then used to declare fields, to move between grid points, and to select the -region where a computation runs. +In GT4Py, the axes of the grid are **dimensions**, and a dimension is a class. +Cartesian axes, such as `I` and `J` below, subclass `gtx.CartesianAxisIndex`, +which also supports index arithmetic such as `I + 1` and staggering. A dimension +is declared once, and it is then used to declare fields, to move between grid +points, and to select the region where a computation runs. A dimension is +identified by its class, so declaring `I` again creates a *different* dimension: +reuse the first declaration instead. ```{code-cell} ipython3 import numpy as np import gt4py.next as gtx -I = gtx.Dimension("I") -J = gtx.Dimension("J") +class I(gtx.CartesianAxisIndex): ... +class J(gtx.CartesianAxisIndex): ... ``` ## Fields diff --git a/docs/user/next/workshop/exercises/1_simple_addition.ipynb b/docs/user/next/workshop/exercises/1_simple_addition.ipynb index 7f42f2b9d8..dc2895dc4c 100644 --- a/docs/user/next/workshop/exercises/1_simple_addition.ipynb +++ b/docs/user/next/workshop/exercises/1_simple_addition.ipynb @@ -36,8 +36,12 @@ "metadata": {}, "outputs": [], "source": [ - "I = gtx.Dimension(\"I\")\n", - "J = gtx.Dimension(\"J\")\n", + "class I(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", + "class J(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", "size = 10" ] }, diff --git a/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb b/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb index dd1a30cc6b..c5c14d716a 100644 --- a/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb +++ b/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb @@ -51,8 +51,12 @@ "metadata": {}, "outputs": [], "source": [ - "I = gtx.Dimension(\"I\")\n", - "J = gtx.Dimension(\"J\")\n", + "class I(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", + "class J(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", "size = 10" ] }, @@ -141,7 +145,7 @@ "output_type": "stream", "text": [ "Result:\n", - "⟨Domain(I[horizontal]=(0:10), J[horizontal]=(0:10)) → DType(scalar_type=, tensor_shape=())⟩\n", + "⟨Domain(I=(0:10), J=(0:10)) → DType(scalar_type=, tensor_shape=())⟩\n", "[[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]\n", " [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]\n", " [ 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.]\n", diff --git a/docs/user/next/workshop/exercises/helpers.py b/docs/user/next/workshop/exercises/helpers.py index 8fd90daf20..82c0ef6a57 100644 --- a/docs/user/next/workshop/exercises/helpers.py +++ b/docs/user/next/workshop/exercises/helpers.py @@ -11,7 +11,7 @@ import gt4py.next as gtx from gt4py.next.iterator.embedded import MutableLocatedField from gt4py.next import neighbor_sum, where, Dims -from gt4py.next import Dimension, DimensionKind, FieldOffset +from gt4py.next import CartesianAxisIndex, Dimension, DimensionIndex, DimensionKind, FieldOffset from gt4py.next.program_processors.runners import roundtrip from gt4py.next.program_processors.runners.gtfn import ( run_gtfn as gtfn_cpu, @@ -377,18 +377,43 @@ def ripple_field(domain: gtx.Domain, *, allocator=None) -> MutableLocatedField: ) -C = Dimension("C") -V = Dimension("V") -E = Dimension("E") -K = Dimension("K", kind=gtx.DimensionKind.VERTICAL) - -C2EDim = Dimension("C2E", kind=DimensionKind.LOCAL) -C2E = FieldOffset("C2E", source=E, target=(C, C2EDim)) -V2EDim = Dimension("V2E", kind=DimensionKind.LOCAL) -V2E = FieldOffset("V2E", source=E, target=(V, V2EDim)) -E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) -E2V = FieldOffset("E2V", source=V, target=(E, E2VDim)) -E2CDim = Dimension("E2C", kind=DimensionKind.LOCAL) -E2C = FieldOffset("E2C", source=C, target=(E, E2CDim)) -E2C2VDim = Dimension("E2C2V", kind=DimensionKind.LOCAL) -E2C2V = FieldOffset("E2C2V", source=V, target=(E, E2C2VDim)) +class C(DimensionIndex): ... + + +class V(DimensionIndex): ... + + +class E(DimensionIndex): ... + + +class K(CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +class C2EDim(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +C2E = FieldOffset(C2EDim.tag, source=E, target=(C, C2EDim)) + + +class V2EDim(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +V2E = FieldOffset(V2EDim.tag, source=E, target=(V, V2EDim)) + + +class E2VDim(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +E2V = FieldOffset(E2VDim.tag, source=V, target=(E, E2VDim)) + + +class E2CDim(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +E2C = FieldOffset(E2CDim.tag, source=C, target=(E, E2CDim)) + + +class E2C2VDim(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +E2C2V = FieldOffset(E2C2VDim.tag, source=V, target=(E, E2C2VDim)) diff --git a/docs/user/next/workshop/slides/slides_1.ipynb b/docs/user/next/workshop/slides/slides_1.ipynb index f1e0229d4f..5948aa990d 100644 --- a/docs/user/next/workshop/slides/slides_1.ipynb +++ b/docs/user/next/workshop/slides/slides_1.ipynb @@ -184,7 +184,7 @@ "output_type": "stream", "text": [ "a definition: \n", - " ⟨Domain(Cell[horizontal]=(0:5), K[vertical]=(0:6)) → DType(scalar_type=, tensor_shape=())⟩\n", + " ⟨Domain(Cell=(0:5), K=(0:6)) → DType(scalar_type=, tensor_shape=())⟩\n", "a array: \n", " [[0. 0. 0. 0. 0. 0.]\n", " [0. 0. 0. 0. 0. 0.]\n", @@ -207,8 +207,11 @@ } ], "source": [ - "Cell = gtx.Dimension(\"Cell\")\n", - "K = gtx.Dimension(\"K\", kind=gtx.DimensionKind.VERTICAL)\n", + "class Cell(gtx.DimensionIndex): ...\n", + "\n", + "\n", + "class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ...\n", + "\n", "\n", "domain = gtx.domain({Cell: 5, K: 6})\n", "\n", diff --git a/docs/user/next/workshop/slides/slides_2.ipynb b/docs/user/next/workshop/slides/slides_2.ipynb index 6686bd7e14..59e1930a82 100644 --- a/docs/user/next/workshop/slides/slides_2.ipynb +++ b/docs/user/next/workshop/slides/slides_2.ipynb @@ -54,8 +54,10 @@ "metadata": {}, "outputs": [], "source": [ - "Cell = gtx.Dimension(\"Cell\")\n", - "K = gtx.Dimension(\"K\", kind=gtx.DimensionKind.VERTICAL)" + "class Cell(gtx.DimensionIndex): ...\n", + "\n", + "\n", + "class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ..." ] }, { @@ -115,7 +117,7 @@ "output_type": "stream", "text": [ "result field: \n", - " ⟨Domain(K[vertical]=(0:6)) → DType(scalar_type=, tensor_shape=())⟩ \n", + " ⟨Domain(K=(0:6)) → DType(scalar_type=, tensor_shape=())⟩ \n", " [1. 2. 3. 5. 8. 0.]\n" ] } @@ -152,8 +154,7 @@ "metadata": {}, "outputs": [], "source": [ - "Cell = gtx.Dimension(\"Cell\")\n", - "Edge = gtx.Dimension(\"Edge\")" + "class Edge(gtx.DimensionIndex): ..." ] }, { @@ -272,8 +273,10 @@ "metadata": {}, "outputs": [], "source": [ - "E2CDim = gtx.Dimension(\"E2C\", kind=gtx.DimensionKind.LOCAL)\n", - "E2C = gtx.FieldOffset(\"E2C\", source=Cell, target=(Edge, E2CDim))" + "class E2CDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ...\n", + "\n", + "\n", + "E2C = gtx.FieldOffset(E2CDim.tag, source=Cell, target=(Edge, E2CDim))" ] }, { @@ -317,7 +320,7 @@ " nearest_cell_to_edge(cell_field, out=edge_field)\n", "\n", "\n", - "run_nearest_cell_to_edge(cell_field, edge_field, offset_provider={\"E2C\": E2C_offset_provider})\n", + "run_nearest_cell_to_edge(cell_field, edge_field, offset_provider={E2CDim.tag: E2C_offset_provider})\n", "\n", "print(\"0th adjacent cell's value: {}\".format(edge_field.asnumpy()))" ] @@ -392,7 +395,7 @@ " sum_adjacent_cells(cell_field, out=edge_field)\n", "\n", "\n", - "run_sum_adjacent_cells(cell_field, edge_field, offset_provider={\"E2C\": E2C_offset_provider})\n", + "run_sum_adjacent_cells(cell_field, edge_field, offset_provider={E2CDim.tag: E2C_offset_provider})\n", "\n", "print(\"sum of adjacent cells: {}\".format(edge_field.asnumpy()))" ] diff --git a/docs/user/next/workshop/slides/slides_3.ipynb b/docs/user/next/workshop/slides/slides_3.ipynb index bd85f5027b..a85937180f 100644 --- a/docs/user/next/workshop/slides/slides_3.ipynb +++ b/docs/user/next/workshop/slides/slides_3.ipynb @@ -54,8 +54,10 @@ "metadata": {}, "outputs": [], "source": [ - "Cell = gtx.Dimension(\"Cell\")\n", - "K = gtx.Dimension(\"K\", kind=gtx.DimensionKind.VERTICAL)" + "class Cell(gtx.DimensionIndex): ...\n", + "\n", + "\n", + "class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ..." ] }, { diff --git a/docs/user/next/workshop/slides/slides_4.ipynb b/docs/user/next/workshop/slides/slides_4.ipynb index a5b8aaf78f..4567390c20 100644 --- a/docs/user/next/workshop/slides/slides_4.ipynb +++ b/docs/user/next/workshop/slides/slides_4.ipynb @@ -54,7 +54,7 @@ "metadata": {}, "outputs": [], "source": [ - "K = gtx.Dimension(\"K\", kind=gtx.DimensionKind.VERTICAL)" + "class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ..." ] }, { diff --git a/examples/lap_cartesian_vs_next.ipynb b/examples/lap_cartesian_vs_next.ipynb index 9a8dfc92b5..fd4a4338c8 100644 --- a/examples/lap_cartesian_vs_next.ipynb +++ b/examples/lap_cartesian_vs_next.ipynb @@ -65,10 +65,16 @@ "# allocator = gtx.gtfn_cpu\n", "# allocator = gtx.gtfn_gpu\n", "\n", + "\n", "# Note: for gt4py.next, names don't matter, for gt4py.cartesian they have to be \"I\", \"J\", \"K\"\n", - "I = gtx.Dimension(\"I\")\n", - "J = gtx.Dimension(\"J\")\n", - "K = gtx.Dimension(\"K\", kind=gtx.DimensionKind.VERTICAL)\n", + "class I(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", + "class J(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", + "class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ...\n", + "\n", "\n", "domain = gtx.domain({I: nx, J: ny, K: nz})\n", "\n", diff --git a/examples/next/swm/swm.ipynb b/examples/next/swm/swm.ipynb index 3c50f53159..14f98e31ad 100644 --- a/examples/next/swm/swm.ipynb +++ b/examples/next/swm/swm.ipynb @@ -112,8 +112,11 @@ }, "outputs": [], "source": [ - "I = gtx.Dimension(\"I\")\n", - "J = gtx.Dimension(\"J\")\n", + "class I(gtx.CartesianAxisIndex): ...\n", + "\n", + "\n", + "class J(gtx.CartesianAxisIndex): ...\n", + "\n", "\n", "IJField = gtx.Field[gtx.Dims[I, J], gtx.float64]\n", "\n", diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index cfcb0bc831..e54c8eee6b 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -22,14 +22,18 @@ from .._core.definitions import CUPY_DEVICE_TYPE, Device, DeviceType, is_scalar_type from . import common, ffront, iterator, program_processors, typing from .common import ( + AnyCartesianAxisIndex, + CartesianAxisIndex, CartesianConnectivity, Connectivity, Dimension, + DimensionIndex, DimensionKind, Dims, Domain, Field, GridType, + Staggered, UnitRange, as_non_staggered, domain, @@ -117,7 +121,11 @@ "is_scalar_type", # from common "Dimension", + "DimensionIndex", + "AnyCartesianAxisIndex", + "CartesianAxisIndex", "DimensionKind", + "Staggered", "Dims", "Field", "CartesianConnectivity", diff --git a/src/gt4py/next/common/__init__.py b/src/gt4py/next/common/__init__.py index 174c81644d..90b5e6c5a7 100644 --- a/src/gt4py/next/common/__init__.py +++ b/src/gt4py/next/common/__init__.py @@ -15,8 +15,9 @@ and the lazy imports used by the `Dimension` operators (see `dimensions`). 1. `ranges`: unbounded and bounded unit ranges (`Infinity`, `UnitRange`). -2. `dimensions`: `Dimension` and its kinds, ordering and promotion of dimensions, - staggered dimensions, named ranges and indices. +2. `dimensions`: dimension classes (`DimensionIndex`, `Dimension`) and their refs, kinds + and tags, ordering and promotion of dimensions, staggered dimensions, dimension ranges + and indices. 3. `domains`: `Domain` and `GridType`. 4. `fields`: the `Field` protocols and the primitive value types. 5. `connectivities`: connectivity types and protocols, `CartesianConnectivity`. @@ -44,42 +45,59 @@ is_neighbor_table as is_neighbor_table, ) from gt4py.next.common.dimensions import ( - _STAGGERED_PREFIX as _STAGGERED_PREFIX, AbsoluteIndexElement as AbsoluteIndexElement, AbsoluteIndexSequence as AbsoluteIndexSequence, + AnyCartesianAxisIndex as AnyCartesianAxisIndex, AnyIndexElement as AnyIndexElement, AnyIndexSequence as AnyIndexSequence, AnyIndexSpec as AnyIndexSpec, + CanonicalAbsoluteIndexSequence as CanonicalAbsoluteIndexSequence, + CartesianAxisIndex as CartesianAxisIndex, Dimension as Dimension, + DimensionIndex as DimensionIndex, DimensionKind as DimensionKind, + DimensionLike as DimensionLike, + DimensionMeta as DimensionMeta, + DimensionRange as DimensionRange, + DimensionRef as DimensionRef, + DimensionSelection as DimensionSelection, + DimensionSlice as DimensionSlice, Dims as Dims, DimsT as DimsT, DimT as DimT, DimT_co as DimT_co, DomainDimT as DomainDimT, - FiniteNamedRange as FiniteNamedRange, + FiniteDimensionRange as FiniteDimensionRange, IntIndex as IntIndex, - NamedIndex as NamedIndex, - NamedRange as NamedRange, - NamedSlice as NamedSlice, RelativeIndexElement as RelativeIndexElement, RelativeIndexSequence as RelativeIndexSequence, ShapeTs as ShapeTs, + Staggered as Staggered, + StaggeredMeta as StaggeredMeta, Tag as Tag, as_any_index_sequence as as_any_index_sequence, as_non_staggered as as_non_staggered, + capture_dimension_classes as capture_dimension_classes, + cartesian_shift as cartesian_shift, check_dims as check_dims, + codegen_name as codegen_name, + dimension_range as dimension_range, + dimension_ref as dimension_ref, + dimension_refs as dimension_refs, flip_staggered as flip_staggered, is_absolute_index_sequence as is_absolute_index_sequence, is_any_index_element as is_any_index_element, - is_finite_named_range as is_finite_named_range, + is_capturing_dimension_classes as is_capturing_dimension_classes, + is_cartesian_axis as is_cartesian_axis, + is_dimension_slice as is_dimension_slice, + is_finite_dimension_range as is_finite_dimension_range, is_int_index as is_int_index, - is_named_slice as is_named_slice, is_relative_index_sequence as is_relative_index_sequence, is_staggered as is_staggered, - named_range as named_range, order_dimensions as order_dimensions, promote_dims as promote_dims, + replay_dimension_classes as replay_dimension_classes, + split_parametrized_tag as split_parametrized_tag, ) from gt4py.next.common.domains import ( Domain as Domain, @@ -109,6 +127,8 @@ hash_offset_provider_items_by_id as hash_offset_provider_items_by_id, is_offset_provider as is_offset_provider, is_offset_provider_type as is_offset_provider_type, + normalize_offset_provider as normalize_offset_provider, + normalize_symbolic_domain_sizes as normalize_symbolic_domain_sizes, offset_provider_to_type as offset_provider_to_type, ) from gt4py.next.common.ranges import ( diff --git a/src/gt4py/next/common/connectivities.py b/src/gt4py/next/common/connectivities.py index 2eaac05aff..8878da1f95 100644 --- a/src/gt4py/next/common/connectivities.py +++ b/src/gt4py/next/common/connectivities.py @@ -27,11 +27,16 @@ @dataclasses.dataclass(frozen=True) class ConnectivityType: # TODO(havogt): would better live in type_specifications but would have to solve a circular import - domain: tuple[dimensions.Dimension, ...] - codomain: dimensions.Dimension + #: Dimension refs; dimension classes passed to the constructor are converted. + domain: tuple[dimensions.DimensionRef, ...] + codomain: dimensions.DimensionRef skip_value: Optional[core_defs.IntegralScalar] dtype: core_defs.DType + def __post_init__(self) -> None: + object.__setattr__(self, "domain", tuple(dimensions.dimension_refs(self.domain))) + object.__setattr__(self, "codomain", dimensions.dimension_ref(self.codomain)) + @property def has_skip_values(self) -> bool: return self.skip_value is not None @@ -43,11 +48,11 @@ class NeighborConnectivityType(ConnectivityType): max_neighbors: int @property - def source_dim(self) -> dimensions.Dimension: + def source_dim(self) -> dimensions.DimensionRef: return self.domain[0] @property - def neighbor_dim(self) -> dimensions.Dimension: + def neighbor_dim(self) -> dimensions.DimensionRef: return self.domain[1] @@ -72,22 +77,24 @@ def codomain(self) -> dimensions.DimT_co: def __gt_type__(self) -> ConnectivityType: if is_neighbor_table(self): return NeighborConnectivityType( - domain=self.domain.dims, - codomain=self.codomain, + domain=tuple(dimensions.dimension_refs(self.domain.dims)), + codomain=dimensions.dimension_ref(self.codomain), dtype=self.dtype, skip_value=self.skip_value, max_neighbors=self.ndarray.shape[1], ) else: return ConnectivityType( - domain=self.domain.dims, - codomain=self.codomain, + domain=tuple(dimensions.dimension_refs(self.domain.dims)), + codomain=dimensions.dimension_ref(self.codomain), dtype=self.dtype, skip_value=self.skip_value, ) @abc.abstractmethod - def _inverse_image(self, image_range: ranges.UnitRange) -> Sequence[dimensions.NamedRange]: ... + def _inverse_image( + self, image_range: ranges.UnitRange + ) -> Sequence[dimensions.DimensionRange]: ... @property @abc.abstractmethod @@ -313,8 +320,8 @@ def for_relocation( ) -> CartesianConnectivity[dimensions.DomainDimT, dimensions.DimT]: return cls(new, codomain=old) - def _inverse_image(self, image_range: ranges.UnitRange) -> Sequence[dimensions.NamedRange]: - return (dimensions.named_range((self.domain_dim, image_range - self.offset)),) + def _inverse_image(self, image_range: ranges.UnitRange) -> Sequence[dimensions.DimensionRange]: + return (dimensions.dimension_range((self.domain_dim, image_range - self.offset)),) def premap( self, @@ -347,13 +354,5 @@ def connectivity_for_cartesian_shift( staggered dimension does not, e.g. `I + 0.5` maps `I(i)` to `IHalf(i+1)` (position `i+½`) while `IHalf + 0.5` maps `IHalf(i)` to `I(i)`. """ - integral_offset, staggered_offset = divmod(offset, 1) - if staggered_offset == 0.5: - if not dimensions.is_staggered(dim): - integral_offset += 1 - return CartesianConnectivity( - dim, int(integral_offset), codomain=dimensions.flip_staggered(dim) - ) - else: - assert staggered_offset == 0 - return CartesianConnectivity(dim, int(integral_offset), codomain=dim) + integral_offset, codomain = dimensions.cartesian_shift(dim, offset) + return CartesianConnectivity(dim, integral_offset, codomain=codomain) diff --git a/src/gt4py/next/common/dimensions.py b/src/gt4py/next/common/dimensions.py index cbb27c1aff..e7dad358c1 100644 --- a/src/gt4py/next/common/dimensions.py +++ b/src/gt4py/next/common/dimensions.py @@ -9,16 +9,26 @@ from __future__ import annotations +import contextlib +import contextvars +import copyreg import dataclasses import enum import functools +import re import types -from collections.abc import Iterable, Sequence +from collections.abc import Iterable, Iterator, Sequence from typing import ( TYPE_CHECKING, Any, + ClassVar, + Final, Generic, + Literal, NamedTuple, + NoReturn, + Optional, + Self, TypeAlias, TypeGuard, TypeVar, @@ -28,6 +38,8 @@ overload, ) +from typing_extensions import Protocol, TypeIs + from gt4py._core import definitions as core_defs from gt4py.eve import utils from gt4py.eve.type_definitions import StrEnum @@ -37,16 +49,20 @@ if TYPE_CHECKING: from gt4py.next.common import connectivities, domains else: - # Higher layers, only needed when a `Dimension` operator is called (not seen by `tach`) - # TODO(egparedes): decide in #2899 if the `Dimension` operators (`I + 1`, `I < 1`) are core - # functionality or an embedded implementation. In the latter case, register them lazily - # (as done for the fbuiltins) and remove this dependency. + # An import cycle: the `Dimension` operators build objects of higher layers (`I < 1` a + # `Domain`, `I + 1` a `Connectivity`). Importing them lazily only hides it (also from `tach`). + # TODO(egparedes): break the cycle, e.g. by registering the operators from outside, as done + # for the fbuiltins. connectivities = utils.lazy_import_module(".connectivities") domains = utils.lazy_import_module(".domains") DimT = TypeVar("DimT", bound="Dimension") # , covariant=True) + + DimT_co = TypeVar("DimT_co", bound="Dimension", covariant=True) + + ShapeTs = TypeVarTuple("ShapeTs") @@ -56,6 +72,9 @@ class Dims(tuple[Unpack[ShapeTs]]): ... DimsT = TypeVar("DimsT", bound=Dims, covariant=True) +_T = TypeVar("_T") + + DomainDimT = TypeVar("DomainDimT", bound="Dimension") @@ -75,63 +94,400 @@ def __str__(self) -> str: _DIM_KIND_ORDER = {DimensionKind.HORIZONTAL: 0, DimensionKind.LOCAL: 1, DimensionKind.VERTICAL: 2} -@dataclasses.dataclass(frozen=True) -class Dimension: - value: str - kind: DimensionKind = dataclasses.field(default=DimensionKind.HORIZONTAL) +#: The module in every staggered tag: the public import path of `Staggered`, not `__name__`. +#: Tags end up in the IR, the generated code and the cache fingerprints, so they must not change +#: when `Staggered` moves to another submodule of `common`. +_STAGGERED_MODULE: Final = "gt4py.next.common" + + +#: Interned refs: equal refs are the identical object. `pickle` memoizes objects by identity, so +#: two equal but distinct refs would give different `pickle`-based content hashes +#: (`eve.utils.content_hash`) for equal IR. +_DIMENSION_REF_INTERN: Final[dict[tuple[Any, ...], DimensionRef]] = {} + + +class _InternedDimensionRefMeta(type): + """ + Makes `DimensionRef(...)` an interning factory, also for `dataclasses.replace` and unpickling. + """ + + def __call__( # a factory with the dataclass's signature + cls, + module: str, + qualname: str, + kind: DimensionKind | str, + is_cartesian_axis: bool = False, + base: Optional[DimensionRef] = None, + ) -> DimensionRef: + if not isinstance(module, str) or not isinstance(qualname, str): + raise TypeError(f"Invalid dimension module or qualname: {module!r}, {qualname!r}.") + if not isinstance(is_cartesian_axis, bool): + raise TypeError(f"'is_cartesian_axis' must be a 'bool', got {is_cartesian_axis!r}.") + if base is not None and not isinstance(base, DimensionRef): + raise TypeError(f"Invalid staggered base: {base!r}.") + key = (module, qualname, DimensionKind(kind), is_cartesian_axis, base) + if (ref := _DIMENSION_REF_INTERN.get(key)) is None: + # validates in `__post_init__`; `setdefault`, so that racing threads get the same ref + ref = _DIMENSION_REF_INTERN.setdefault(key, super().__call__(*key)) + return ref + + +@dataclasses.dataclass(frozen=True, eq=False) +class DimensionRef(metaclass=_InternedDimensionRefMeta): + """ + An immutable, interned value referring to a dimension, for everything below the frontend. + + Type specifications, the IR and the backends carry it instead of the class, so they do not + need to import the module that declared the dimension. `dimension_ref(cls)` creates it. + + A ref never compares equal to a dimension class: such a comparison is a missed conversion + and raises `TypeError`. Hash-based lookups (`cls in {ref}`) cannot be checked and are simply + misses. + + Examples: + >>> class I(CartesianAxisIndex): ... + >>> ref = dimension_ref(I) + >>> ref + DimensionRef(gt4py.next.common.dimensions:I, horizontal, cartesian_axis) + >>> str(ref) # the display form, same as the class's + 'I[horizontal]' + >>> flip_staggered(ref) is dimension_ref(Staggered[I]) + True + """ + + module: str + qualname: str + kind: DimensionKind + #: Whether it is either cell class of a Cartesian axis: a `CartesianAxisIndex` or a + #: `Staggered[...]`. Not derivable from `kind`: `IDim` and `Cell` are both `HORIZONTAL`. + is_cartesian_axis: bool = False + #: The base dimension of a staggered dimension, `None` otherwise. + base: Optional[DimensionRef] = None + + def __post_init__(self) -> None: + if self.is_cartesian_axis and self.kind is DimensionKind.LOCAL: + raise ValueError(f"A Cartesian axis cannot have kind 'local': '{self!r}'.") + if self.base is not None: + base = self.base + if base.base is not None or not base.is_cartesian_axis: + raise TypeError( + f"'{base}' is not a declared Cartesian axis and cannot be staggered." + ) + if ( + self.module != _STAGGERED_MODULE + or self.qualname != f"Staggered[{base.qualname}]" + or self.kind is not base.kind + or not self.is_cartesian_axis + ): + raise ValueError(f"'{self!r}' is not the staggered dimension of '{base!r}'.") + # The hash is cached, since refs are hashed often. As an attribute, not a dataclass + # field, it is left out of the pickle (see `__reduce__`) and of the fingerprint. + object.__setattr__(self, "_hash", hash(self._identity_key())) + + def __reduce__(self) -> tuple[Any, ...]: + # By value, through the constructor, so an unpickled ref is interned too. + return (DimensionRef, self._identity_key()) + + @property + def tag(self) -> Tag: + """ + The dimension's IR spelling: `module:qualname`, `[]` if staggered. + """ + if self.base is not None: + return f"{self.module}:Staggered[{self.base.tag}]" + return f"{self.module}:{self.qualname}" + + # All fields: the same qualified name with e.g. another kind is another dimension. + def _identity_key(self) -> tuple[Any, ...]: + return (self.module, self.qualname, self.kind, self.is_cartesian_axis, self.base) + + def __eq__(self, other: object) -> bool: + if self is other: + return True + if isinstance(other, DimensionRef): + return self._identity_key() == other._identity_key() + if isinstance(other, DimensionMeta): + raise TypeError( + f"Comparing {self!r} with the dimension class {other!r}: missing a conversion" + " to 'DimensionRef'? (use 'common.dimension_ref(cls)')." + ) + return NotImplemented + + def __ne__(self, other: object) -> bool: + result = self.__eq__(other) + return result if result is NotImplemented else not result + + def __hash__(self) -> int: + return self._hash # type: ignore[attr-defined] # set in `__post_init__` def __str__(self) -> str: - return f"{self.value}[{self.kind}]" + # the display form, same as `str()` of the class + return f"{self.qualname}[{self.kind}]" + + def __repr__(self) -> str: + # distinct from the class's repr (`pkg:IDim[horizontal]`) + axis = ", cartesian_axis" if self.is_cartesian_axis else "" + return f"DimensionRef({self.tag}, {self.kind}{axis})" + + def __copy__(self) -> Self: + return self + + def __deepcopy__(self, memo: Any) -> Self: + return self + + @classmethod + def from_tag( + cls, tag: Tag, kind: DimensionKind, *, is_cartesian_axis: bool = False + ) -> DimensionRef: + """ + Rebuild a ref from its properties. + """ + if (parts := split_parametrized_tag(tag)) is not None: + owner_tag, base_tag = parts + if owner_tag != f"{_STAGGERED_MODULE}:Staggered": + raise ValueError( + f"'{tag}' is not a dimension tag: only 'Staggered' is parametrized." + ) + base = cls.from_tag(base_tag, kind, is_cartesian_axis=True) + return _staggered_ref(base) + module, sep, qualname = tag.partition(":") + if not sep or not module or not qualname or ":" in qualname: + raise ValueError(f"'{tag}' is not a dimension tag ('module:qualname').") + return cls(module=module, qualname=qualname, kind=kind, is_cartesian_axis=is_cartesian_axis) + + +def _staggered_ref(base: DimensionRef) -> DimensionRef: + return DimensionRef( + module=_STAGGERED_MODULE, + qualname=f"Staggered[{base.qualname}]", + kind=base.kind, + is_cartesian_axis=True, + base=base, + ) + + +#: Name of the class attribute holding a dimension class's ref. +_REF_ATTR: Final = "_gt_dimension_ref_" + + +def dimension_ref(dim: Dimension | DimensionRef) -> DimensionRef: + """ + Return the value referring to `dim` (a dimension class or already a ref). + """ + if isinstance(dim, DimensionRef): + return dim + if not isinstance(dim, DimensionMeta): + raise TypeError(f"Expected a dimension, got '{dim!r}'.") + if (ref := dim.__dict__.get(_REF_ATTR)) is None: + if "base" in dim.__dict__: # a staggered dimension, see `is_staggered` + ref = _staggered_ref(dimension_ref(dim.base)) # type: ignore[attr-defined] # staggered + else: + ref = DimensionRef( + module=dim.__module__, + qualname=dim.__qualname__, + kind=dim.kind, + is_cartesian_axis=issubclass(dim, AnyCartesianAxisIndex), + ) + type.__setattr__(dim, _REF_ATTR, ref) + if (sink := _DIMENSION_CLASS_CAPTURE.get()) is not None: + sink.append((ref, dim)) + return ref + + +#: Set while `capture_dimension_classes` is active: the `(ref, class)` pairs converted so far. +_DIMENSION_CLASS_CAPTURE: contextvars.ContextVar[Optional[list[tuple[DimensionRef, Dimension]]]] = ( + contextvars.ContextVar("_DIMENSION_CLASS_CAPTURE", default=None) +) + + +def is_capturing_dimension_classes() -> bool: + """Whether `capture_dimension_classes` is active (conversion caches must then be bypassed).""" + return _DIMENSION_CLASS_CAPTURE.get() is not None + + +def replay_dimension_classes(pairs: Iterable[tuple[DimensionRef, Dimension]]) -> None: + """Record `(ref, class)` pairs captured earlier (e.g. by a cached conversion), if capturing.""" + if (sink := _DIMENSION_CLASS_CAPTURE.get()) is not None: + sink.extend(pairs) + + +@contextlib.contextmanager +def capture_dimension_classes() -> Iterator[list[tuple[DimensionRef, Dimension]]]: + """ + Record the `(ref, class)` pair of every dimension class converted to a ref in the block. + + Wrapping a type translation (of an annotation or an argument) in this yields exactly the + classes it used, so that a call can compare dimensions by class identity. + """ + sink: list[tuple[DimensionRef, Dimension]] = [] + token = _DIMENSION_CLASS_CAPTURE.set(sink) + try: + yield sink + finally: + _DIMENSION_CLASS_CAPTURE.reset(token) + + +def dimension_refs(dims: Iterable[Dimension | DimensionRef]) -> list[DimensionRef]: + """`dimension_ref` over a sequence; a converter for type-specification fields.""" + return [dimension_ref(dim) for dim in dims] + + +class DimensionMeta(type): + """ + Metaclass of all dimension classes: the operators of a dimension, e.g. `I + 1` or `I < 5`. + """ + + kind: DimensionKind + + # NOTE: mandatory, Python sets `__hash__ = None` in a class body that only defines `__eq__`. + __hash__ = type.__hash__ + + @property + def tag(cls) -> Tag: + """ + The dimension's identity: its qualified Python name, and its spelling in the IR. - def __call__(self, val: int) -> NamedIndex: - return NamedIndex(self, val) + Use `__qualname__` for display, see `__str__`. + """ + return dimension_ref(cast(Dimension, cls)).tag - def __add__(self, offset: int | float) -> connectivities.Connectivity: - return connectivities.connectivity_for_cartesian_shift(self, offset) + @property + def value(cls) -> NoReturn: + """ + Reject `SomeDim.value`: a dimension's name is `tag`, `value` is an index position. - def __sub__(self, offset: int | float) -> connectivities.Connectivity: - return self + (-offset) + Without this the read would silently return the slot descriptor of the instance attribute. + """ + raise AttributeError( + f"'{cls.__qualname__}' is a dimension and has no 'value': its name is '.tag'," + f" and an *index* into it -- '{cls.__qualname__}(0)' -- is what has '.value'." + ) + + def __repr__(cls) -> str: + return f"{cls.tag}[{cls.kind}]" + + def __str__(cls) -> str: + # the unqualified name, for readable diagnostics; `repr` has the full tag + return f"{cls.__qualname__}[{cls.kind}]" + + # The self-type is an unbounded `TypeVar` (as in typeshed's `EnumMeta.__iter__`), because mypy + # rejects a bound one: it is not a supertype of the metaclass. + @overload + def at(cls: type[_T], value: IntIndex, /) -> _T: ... + @overload + def at( + cls, start: Optional[IntIndex], stop: Optional[IntIndex], / + ) -> DimensionRange[ranges.UnitRange]: ... + @overload + def at(cls, range_: ranges.UnitRange | range, /) -> DimensionRange[ranges.UnitRange]: ... + def at(cls, *args: Any) -> Any: + """ + Select a point or a range on this dimension, in absolute coordinates. + + One integer is always a point; two bounds or a range are a range. Bounds are + absolute coordinates (a negative number is not counted from the end), and a `None` + bound is open: indexing a field with it extends to the field's own bound. + + Args: + *args: Either one integer (a point), two bounds `start, stop` (each an integer + or `None`), or one `UnitRange` or `range` with step 1. + + Returns: + The point `cls(value)`, or a `DimensionRange` on `cls`. + + Raises: + TypeError: If the arguments are none of the forms above. + ValueError: If a `range` has a step other than 1. + + Examples: + >>> class I(CartesianAxisIndex): ... + >>> I.at(3) + I=3 + >>> print(I.at(0, 10)) + I=(0:10) + >>> I.at(5, None).value + UnitRange(5, Infinity.POSITIVE) + >>> I.at(range(2, 4)) == I.at(ranges.UnitRange(2, 4)) == I.at(2, 4) + True + """ + dim = cast(Dimension, cls) + match args: + case (value,) if is_int_index(value): + return dim(int(value)) + case (ranges.UnitRange() | range() as rng,): + return DimensionRange(dim, ranges.unit_range(rng)) + case (start, stop) if all(b is None or is_int_index(b) for b in args): + return DimensionRange( + dim, + ranges.UnitRange( + ranges.Infinity.NEGATIVE if start is None else start, + ranges.Infinity.POSITIVE if stop is None else stop, + ), + ) + raise TypeError( + f"'{cls.__qualname__}.at()' takes a point ('at(3)'), two bounds ('at(0, 10)'," + f" 'None' for an open bound) or a range ('at(range(0, 10))'), got {args!r}." + ) + + # NOTE: the self-type restricts index arithmetic to Cartesian axes. mypy applies it at the call + # sites, but rejects the definition, hence the suppression. + def __add__( # type: ignore[misc] + cls: type[AnyCartesianAxisIndex], + offset: int | float, + ) -> connectivities.Connectivity: + if not issubclass(cls, AnyCartesianAxisIndex): + raise TypeError( + f"'{cls.__qualname__}' is not a Cartesian axis: only a dimension declared as" + " 'CartesianAxisIndex' (or its 'Staggered[...]' partner) has index arithmetic." + ) + return connectivities.connectivity_for_cartesian_shift(cls, offset) + + def __sub__( # type: ignore[misc] + cls: type[AnyCartesianAxisIndex], + offset: int | float, + ) -> connectivities.Connectivity: + return cls + (-offset) - def __gt__(self, value: core_defs.IntegralScalar) -> domains.Domain: + def __gt__(cls: Dimension, value: core_defs.IntegralScalar) -> domains.Domain: # type: ignore[misc] return domains.Domain( - dims=(self,), ranges=(ranges.UnitRange(value + 1, ranges.Infinity.POSITIVE),) + dims=(cls,), ranges=(ranges.UnitRange(value + 1, ranges.Infinity.POSITIVE),) ) - def __ge__(self, value: core_defs.IntegralScalar) -> domains.Domain: + def __ge__(cls: Dimension, value: core_defs.IntegralScalar) -> domains.Domain: # type: ignore[misc] return domains.Domain( - dims=(self,), ranges=(ranges.UnitRange(value, ranges.Infinity.POSITIVE),) + dims=(cls,), ranges=(ranges.UnitRange(value, ranges.Infinity.POSITIVE),) ) - def __lt__(self, value: core_defs.IntegralScalar) -> domains.Domain: + def __lt__(cls: Dimension, value: core_defs.IntegralScalar) -> domains.Domain: # type: ignore[misc] return domains.Domain( - dims=(self,), ranges=(ranges.UnitRange(ranges.Infinity.NEGATIVE, value),) + dims=(cls,), ranges=(ranges.UnitRange(ranges.Infinity.NEGATIVE, value),) ) - def __le__(self, value: core_defs.IntegralScalar) -> domains.Domain: + def __le__(cls: Dimension, value: core_defs.IntegralScalar) -> domains.Domain: # type: ignore[misc] return domains.Domain( - dims=(self,), ranges=(ranges.UnitRange(ranges.Infinity.NEGATIVE, value + 1),) + dims=(cls,), ranges=(ranges.UnitRange(ranges.Infinity.NEGATIVE, value + 1),) ) - @overload # type: ignore[override] # incompatible with supertype `object.__eq__` which returns `bool`. - def __eq__(self, value: Dimension) -> bool: ... + @overload # type: ignore[override] # incompatible with `type.__eq__`, which returns `bool`. + def __eq__(cls, value: DimensionMeta) -> bool: ... @overload - def __eq__(self, value: core_defs.IntegralScalar) -> domains.Domain: ... - def __eq__(self, value: Dimension | core_defs.IntegralScalar) -> bool | domains.Domain: - if isinstance(value, Dimension): - return self.value == value.value and self.kind == value.kind + def __eq__(cls, value: core_defs.IntegralScalar) -> domains.Domain: ... + def __eq__( # type: ignore[misc] + cls: Dimension, value: DimensionMeta | core_defs.IntegralScalar + ) -> bool | domains.Domain: + if isinstance(value, DimensionMeta): + return NotImplemented # both sides decline, so Python falls back to identity if isinstance(value, core_defs.INTEGRAL_TYPES): - return domains.Domain(dims=(self,), ranges=(ranges.UnitRange(value, value + 1),)) - # This will fallback to default identity comparison if reflection also returns `NotImplemented`, - # which does identity comparison, see https://docs.python.org/3/reference/datamodel.html#object.__eq__. + return domains.Domain(dims=(cls,), ranges=(ranges.UnitRange(value, value + 1),)) return NotImplemented - @overload # type: ignore[override] # incompatible with supertype `object.__ne__` which returns `bool`. - def __ne__(self, value: Dimension) -> bool: ... + @overload # type: ignore[override] # incompatible with `type.__ne__`, which returns `bool`. + def __ne__(cls, value: DimensionMeta) -> bool: ... @overload - def __ne__(self, value: core_defs.IntegralScalar) -> domains.Domain: ... - def __ne__(self, value: Dimension | core_defs.IntegralScalar) -> bool | domains.Domain: - if isinstance(value, Dimension): - return self.value != value.value or self.kind != value.kind + def __ne__(cls, value: core_defs.IntegralScalar) -> domains.Domain: ... + def __ne__( # type: ignore[misc] + cls: Dimension, value: DimensionMeta | core_defs.IntegralScalar + ) -> bool | domains.Domain: if isinstance(value, core_defs.INTEGRAL_TYPES): raise NotImplementedError( "'Dimension.__ne__' with an integer value produces two disjoint domains, " @@ -141,76 +497,442 @@ def __ne__(self, value: Dimension | core_defs.IntegralScalar) -> bool | domains. return NotImplemented +class DimensionIndex(metaclass=DimensionMeta): + """ + A dimension. A concrete dimension is a *subclass*; an index along it an *instance*. + + As in `enum.Enum`, the class is the collection and the instances are its members. `tag`, its + qualified Python name, is how a dimension is spelled in the IR. + + Examples: + >>> class I(CartesianAxisIndex): ... + >>> class K(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + >>> str(I), K.kind + ('I[horizontal]', ) + + `repr` spells the full tag, `module:qualname`, then the kind. In a doctest the module is + the one the docstring belongs to: + + >>> I + gt4py.next.common.dimensions:I[horizontal] + + >>> I(0) + I=0 + >>> I(0).dim is I, I(0).value + (True, 0) + + Two dimension classes are the same dimension only if they are the same class: + + >>> class I2(CartesianAxisIndex): ... + >>> I == I2 + False + """ + + kind: ClassVar[DimensionKind] = DimensionKind.HORIZONTAL + + __slots__ = ("value",) + + #: Index position along the dimension. The dimension's *name* is `tag`, on the class. + value: int + + def __init_subclass__(cls, /, kind: Optional[DimensionKind] = None, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + if "tag" in cls.__dict__: + raise TypeError( + f"'{cls.__qualname__}' sets 'tag' in its class body, which has no effect:" + " a dimension's tag is its qualified Python name. Rename the class instead." + ) + if "at" in cls.__dict__: + raise TypeError( + f"'{cls.__qualname__}' defines 'at', which would shadow 'Dimension.at', the" + " selection of a point or a range on the dimension." + ) + if "" in cls.__qualname__: + raise TypeError( + f"'{cls.__qualname__}' must be declared at module level: a dimension's tag is" + " its qualified name, which must be unique and lets the class be pickled." + ) + if cls.__module__ == "__mp_main__": + # The name of a script's `__main__` in a `multiprocessing` spawn worker: the tag and + # fingerprint must be the same as in the parent process. + cls.__module__ = "__main__" + if kind is not None: + cls.kind = kind + if cls.kind is DimensionKind.LOCAL and issubclass(cls, AnyCartesianAxisIndex): + raise TypeError( + f"'{cls.__qualname__}' is a Cartesian axis and cannot have kind 'local'." + ) + + def __init__(self, value: int) -> None: + self.value = value + + def __repr__(self) -> str: + return f"{type(self).__qualname__}={self.value}" + + __str__ = __repr__ + + def __eq__(self, other: object) -> bool: + if isinstance(other, DimensionIndex): + # NOTE: `is`, not `==`: a dimension's identity is its type (ADR 0030). + return type(self) is type(other) and self.value == other.value + return NotImplemented + + def __hash__(self) -> int: + return hash((type(self), self.value)) + + @property + def dim(self) -> Dimension: + """The dimension this index runs along, i.e. its own class.""" + return type(self) + + +#: A concrete dimension. +#: +#: NOTE: a `type` statement, not a plain `TypeAlias`, so that `Dimension("I")` raises: calling a +#: plain alias of `type[X]` would return `type("I")`, i.e. `str`. Code that inspects annotations +#: must resolve the alias first, see `xtyping.resolve_annotation`. +type Dimension = type[DimensionIndex] + + +#: A dimension class (in user code) or its `DimensionRef` (in the toolchain). +type DimensionLike = Dimension | DimensionRef + + +class AnyCartesianAxisIndex(DimensionIndex): + """ + Either cell class of a Cartesian axis: a declared `CartesianAxisIndex` or its `Staggered[...]`. + + See ADR 0030. Use it in annotations where both are accepted, i.e. for Cartesian shifts; + declare axes with `CartesianAxisIndex`. + """ + + __slots__ = () + + +class CartesianAxisIndex(AnyCartesianAxisIndex): + """ + A declared dimension on a Cartesian axis: integer index arithmetic and one staggered partner. + + Mesh locations (vertices, edges, cells) and index spaces without geometry subclass + `DimensionIndex` directly. Only a `CartesianAxisIndex` can be staggered. + + Examples: + >>> class I(CartesianAxisIndex): ... + >>> (I + 1).codomain is I, (I + 0.5).codomain is Staggered[I] + (True, True) + + A mesh location is not an axis: + + >>> class Cell(DimensionIndex): ... + >>> Cell + 1 # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'Cell' is not a Cartesian axis: ... + >>> Staggered[Cell] # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'Cell' is not a declared Cartesian axis and cannot be staggered: ... + """ + + __slots__ = () + + +_STAGGERED_TAG_RE: Final = re.compile(r"^(?P[^\[\]]+)\[(?P.+)\]$") + + +def split_parametrized_tag(tag: Tag) -> tuple[Tag, Tag] | None: + """ + Split a parametrized dimension tag `[]` into its two tags. + + Returns: + The owner and base tags, or `None` if `tag` is not parametrized. + + Examples: + >>> split_parametrized_tag("gt4py.next.common:Staggered[my.module:K]") + ('gt4py.next.common:Staggered', 'my.module:K') + >>> split_parametrized_tag("my.module:K") is None + True + """ + if (match := _STAGGERED_TAG_RE.match(tag)) is None: + return None + return match["owner"], match["base"] + + +def codegen_name(tag: Tag) -> str: + """ + Mangle a dimension or offset tag into a valid generated identifier. + + Dots, colons and brackets are escaped, and so is the underscore: every `_` in the result + starts a two-character escape, which keeps the mapping injective. + + Args: + tag: A dimension or offset tag, i.e. a qualified Python name. + + Returns: + A valid identifier, unique for each distinct `tag`. + + Examples: + >>> codegen_name("mod:V2E.Local") + 'mod_cV2E_dLocal' + >>> codegen_name("a_b.c") + 'a_ub_dc' + """ + # `_` first, so the underscores introduced by the other escapes are not re-escaped + return ( + tag.replace("_", "_u") + .replace(".", "_d") + .replace(":", "_c") + .replace("[", "_l") + .replace("]", "_r") + ) + + +#: The range of a `DimensionRange`: any `UnitRange` (a `Domain` narrows it to an `_Rng`). +_RangeT_co = TypeVar("_RangeT_co", bound="ranges.UnitRange", covariant=True) + + +_SelectionValueT_co = TypeVar("_SelectionValueT_co", covariant=True) + + +class DimensionSelection(Protocol[_SelectionValueT_co]): + """ + A point or a range on one dimension, in absolute coordinates. + + `dim` is the dimension and `value` the selection on it: an `int` for a point (a + `DimensionIndex` instance, e.g. `IDim(3)`) or a `UnitRange` for a range (a + `DimensionRange`, e.g. `IDim.at(0, 10)`). + + This unifies *access*, not semantics: indexing a field with a point removes the + dimension, while indexing it with a range keeps it. + """ + + @property + def dim(self) -> Dimension: ... + + @property + def value(self) -> _SelectionValueT_co: ... + + +class DimensionRange(NamedTuple, Generic[_RangeT_co]): + """ + A range on one dimension, in absolute coordinates. + + The range counterpart of a `DimensionIndex` instance, which is a point on its dimension: + both are a `DimensionSelection`. `Dimension.at(start, stop)` builds one. + """ + + dim: Dimension + value: _RangeT_co + + def __str__(self) -> str: + # the same short form as a point (`I=3`) + return f"{self.dim.__qualname__}={self.value}" + + +#: Interned staggered dimensions, by base dimension class: `Staggered[K]` must return the same +#: class every time, since dimensions compare by identity. +_STAGGERED_CACHE: dict[Dimension, Dimension] = {} + + +class StaggeredMeta(DimensionMeta): + """ + Metaclass of `Staggered`: `Staggered[K]` creates a dimension class, once per base `K`. + + A generic `Staggered[D]` would make `Staggered[K]` a `typing` alias, not a class, and so not + a dimension. + """ + + #: Set by `__getitem__` on each parametrization. Its presence is what distinguishes a + #: staggered dimension from the bare `Staggered` base, which is also a `StaggeredMeta`. + base: Dimension + + def __getitem__(cls, base: Dimension) -> Dimension: + if "base" in cls.__dict__: + raise TypeError( + f"'{cls.__qualname__}' is already staggered; a dimension cannot be staggered twice." + ) + if not isinstance(base, DimensionMeta): + raise TypeError(f"'Staggered' expects a dimension, got '{base!r}'.") + if is_staggered(base): + raise TypeError( + f"'{base.__qualname__}' is already staggered; a dimension cannot be staggered twice." + ) + if not issubclass(base, CartesianAxisIndex): + raise TypeError( + f"'{base.__qualname__}' is not a declared Cartesian axis and cannot be staggered:" + " only a dimension declared as 'CartesianAxisIndex' has a staggered partner." + ) + if (staggered := _STAGGERED_CACHE.get(base)) is None: + staggered = cast( + Dimension, + StaggeredMeta( + f"Staggered[{base.__qualname__}]", + # not `(cls, base)`: `issubclass(Staggered[K], K)` must be false + (cls,), + { + "_staggered_base": base, + "base": base, + "kind": base.kind, + "__slots__": (), + "__module__": cls.__module__, + "__qualname__": f"{cls.__qualname__}[{base.__qualname__}]", + }, + ), + ) + # NOTE: `setdefault`, so that two threads building `Staggered[K]` get the same class. + staggered = _STAGGERED_CACHE.setdefault(base, staggered) + return staggered + + if TYPE_CHECKING: - # These exist as on-the fly replacements for Dimension instances - # (which are not types) during typechecking (with mypy). We can - # track up to four distinct dimensions at a time, everything beyond - # becomes AnyDim + # Type checkers see an ordinary generic. Its bound rejects doubly staggered dimensions, + # mesh locations and local dimensions. + class Staggered[D: CartesianAxisIndex](AnyCartesianAxisIndex): + base: ClassVar[type[CartesianAxisIndex]] + +else: + + class Staggered(AnyCartesianAxisIndex, metaclass=StaggeredMeta): + """ + A dimension sitting at the half-integer positions of a base dimension (ADR 0026). - @dataclasses.dataclass(frozen=True) - class _DimA(Dimension): ... + `Staggered[K]` is a real, interned dimension class: subscripting the same base twice + returns the identical object, so it round-trips through the IR by identity. + """ - @dataclasses.dataclass(frozen=True) - class _DimB(Dimension): ... + # NOTE: pinned, so that the class and its pickles agree with the tags. + __module__ = _STAGGERED_MODULE + __slots__ = () - @dataclasses.dataclass(frozen=True) - class _DimC(Dimension): ... + def __init_subclass__(cls, /, **kwargs: Any) -> None: + # the marker is set by the metaclass + if "_staggered_base" not in cls.__dict__: + raise TypeError( + f"'{cls.__qualname__}' cannot subclass a staggered dimension directly;" + " write 'Staggered[BaseDim]'." + ) + super().__init_subclass__(**kwargs) - @dataclasses.dataclass(frozen=True) - class _DimD(Dimension): ... - @dataclasses.dataclass(frozen=True) - class _AnyDim(Dimension): ... +def _reduce_staggered(cls: StaggeredMeta) -> Any: + """ + Pickle a staggered dimension through its base, falling back to by-reference. + + `pickle` cannot look up the brackets in `Staggered[K].__qualname__`. The bare `Staggered` has + no `base` and is pickled by reference. + """ + if "base" not in cls.__dict__: + return cls.__qualname__ + return (_make_staggered, (cls.base,)) + +def _make_staggered(base: Dimension) -> Dimension: + return Staggered[base] # type: ignore[valid-type] # runtime subscription, see StaggeredMeta -_STAGGERED_PREFIX = "_Staggered" +# `pickle` stores a class by its `__qualname__`, which it cannot look up for `Staggered[K]`. +copyreg.pickle(StaggeredMeta, _reduce_staggered) -def is_staggered(dim: Dimension) -> bool: - """Return whether `dim` is a staggered dimension.""" - return dim.value.startswith(_STAGGERED_PREFIX) +_AnyDimT = TypeVar("_AnyDimT", bound="Dimension | DimensionRef") + + +def is_staggered(dim: Dimension | DimensionRef) -> bool: + """ + Return whether `dim` (a class or a ref) is a staggered dimension. -def flip_staggered(dim: Dimension) -> Dimension: - """Return the staggered counterpart of `dim`.""" + Not `issubclass(dim, Staggered)`, which is also true for the bare `Staggered`. + """ + if isinstance(dim, DimensionRef): + return dim.base is not None + return "base" in dim.__dict__ + + +@overload +def flip_staggered(dim: DimensionRef) -> DimensionRef: ... +@overload +def flip_staggered(dim: Dimension) -> Dimension: ... +def flip_staggered(dim: Dimension | DimensionRef) -> Dimension | DimensionRef: + """Return the staggered counterpart of `dim` (a class or a ref, answered in kind).""" + if isinstance(dim, DimensionRef): + if dim.base is not None: + return dim.base + if not dim.is_cartesian_axis: + raise TypeError( + f"'{dim.qualname}' is not a declared Cartesian axis and cannot be staggered:" + " only a dimension declared as 'CartesianAxisIndex' has a staggered partner." + ) + return _staggered_ref(dim) if is_staggered(dim): - return Dimension(dim.value[len(_STAGGERED_PREFIX) :], dim.kind) - else: - return Dimension(f"{_STAGGERED_PREFIX}{dim.value}", dim.kind) + return cast(Dimension, dim.base) # type: ignore[attr-defined] # guarded by is_staggered + return Staggered[dim] # type: ignore[valid-type] # runtime subscription -def as_non_staggered(dim: Dimension) -> Dimension: +@overload +def as_non_staggered(dim: DimensionRef) -> DimensionRef: ... +@overload +def as_non_staggered(dim: Dimension) -> Dimension: ... +def as_non_staggered(dim: Dimension | DimensionRef) -> Dimension | DimensionRef: """Return the non-staggered base dimension of `dim` (`dim` itself if already non-staggered).""" if is_staggered(dim): return flip_staggered(dim) return dim -def order_dimensions(dims: Iterable[Dimension]) -> list[Dimension]: - """Find the canonical ordering of the dimensions in `dims`.""" +def is_cartesian_axis(dim: Dimension | DimensionRef) -> bool: + """Return whether `dim` (a class or a ref) is either cell class of a Cartesian axis.""" + return dimension_ref(dim).is_cartesian_axis + + +@overload +def cartesian_shift(dim: DimensionRef, offset: int | float) -> tuple[int, DimensionRef]: ... +@overload +def cartesian_shift(dim: Dimension, offset: int | float) -> tuple[int, Dimension]: ... +def cartesian_shift( + dim: Dimension | DimensionRef, offset: int | float +) -> tuple[int, Dimension | DimensionRef]: + """ + Return the integral index offset and the codomain of shifting `dim` by `offset`. + + Works on a class or a ref alike (answered in kind), so the frontend can type a Cartesian shift + without building an embedded `CartesianConnectivity`. See `connectivity_for_cartesian_shift`. + """ + integral_offset, staggered_offset = divmod(offset, 1) + if staggered_offset == 0.5: + if not is_staggered(dim): + integral_offset += 1 + return int(integral_offset), flip_staggered(dim) + else: + assert staggered_offset == 0 + return int(integral_offset), dim + + +def _dimension_order_key(dim: Dimension | DimensionRef) -> tuple[int, str, str]: + # NOTE: `qualname` first, not `tag`: moving a declaration to another module must not reorder a + # field's dimensions. `tag` only breaks ties between same-named dimensions. + base = as_non_staggered(dimension_ref(dim)) + return (_DIM_KIND_ORDER[base.kind], base.qualname, base.tag) + + +def order_dimensions(dims: Iterable[_AnyDimT]) -> list[_AnyDimT]: + """Find the canonical ordering of the dimensions in `dims` (classes or refs).""" if sum(1 for dim in dims if dim.kind == DimensionKind.LOCAL) > 1: raise ValueError("There are more than one dimension with DimensionKind 'LOCAL'.") - return sorted( - dims, - key=lambda dim: ( - _DIM_KIND_ORDER[dim.kind], - as_non_staggered(dim).value, - ), - ) + return sorted(dims, key=_dimension_order_key) -def check_dims(dims: Sequence[Dimension]) -> None: +def check_dims(dims: Sequence[Dimension] | Sequence[DimensionRef]) -> None: _check_dims(tuple(dims)) @functools.cache -def _check_dims(dims: tuple[Dimension, ...]) -> None: +def _check_dims(dims: tuple[Dimension, ...] | tuple[DimensionRef, ...]) -> None: # A dimension and its staggered counterpart (i.e. sharing the same non-staggered base dimension) # denote different grid locations and must not appear together in the same field/domain: mixing # them is ambiguous (it makes `order_dimensions` non-total and produces duplicate backend tags). - seen: dict[Dimension, Dimension] = {} + seen: dict[DimensionRef, Dimension | DimensionRef] = {} for dim in dims: - base = as_non_staggered(dim) + base = as_non_staggered(dimension_ref(dim)) if base in seen: raise ValueError( f"Dimensions '{seen[base]}' and '{dim}' cannot be combined: a dimension and its " @@ -223,21 +945,21 @@ def _check_dims(dims: tuple[Dimension, ...]) -> None: ) -def promote_dims(*dims_list: Sequence[Dimension]) -> list[Dimension]: +def promote_dims(*dims_list: Sequence[_AnyDimT]) -> list[_AnyDimT]: """ Find an ordering of multiple lists of dimensions. The resulting list contains all unique dimensions from the input lists, sorted first by dims_kind_order, i.e., `Dimension.kind` (`HORIZONTAL` < `LOCAL` < `VERTICAL`) and then - lexicographically by `Dimension.value`. + lexicographically by their unqualified name. Examples: >>> from gt4py.next.common import Dimension - >>> I = Dimension("I", DimensionKind.HORIZONTAL) - >>> J = Dimension("J", DimensionKind.HORIZONTAL) - >>> K = Dimension("K", DimensionKind.VERTICAL) - >>> E2V = Dimension("E2V", kind=DimensionKind.LOCAL) - >>> E2C = Dimension("E2C", kind=DimensionKind.LOCAL) + >>> class I(CartesianAxisIndex, kind=DimensionKind.HORIZONTAL): ... + >>> class J(CartesianAxisIndex, kind=DimensionKind.HORIZONTAL): ... + >>> class K(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + >>> class E2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + >>> class E2C(DimensionIndex, kind=DimensionKind.LOCAL): ... >>> promote_dims([J, K], [I, K]) == [I, J, K] True >>> promote_dims([K, J], [I, K]) @@ -255,45 +977,55 @@ def promote_dims(*dims_list: Sequence[Dimension]) -> list[Dimension]: @functools.cache -def _promote_dims(dims_list: tuple[tuple[Dimension, ...], ...]) -> tuple[Dimension, ...]: +def _promote_dims(dims_list: tuple[tuple[_AnyDimT, ...], ...]) -> tuple[_AnyDimT, ...]: for dims in dims_list: - check_dims(dims) + check_dims(dims) # type: ignore[arg-type] # homogeneous unique_dims = {dim for dims in dims_list for dim in dims} promoted_dims = order_dimensions(unique_dims) - check_dims(promoted_dims) + check_dims(promoted_dims) # type: ignore[arg-type] # homogeneous return tuple(promoted_dims) -class NamedRange(NamedTuple, Generic[ranges._Rng]): - dim: Dimension - unit_range: ranges._Rng +IntIndex: TypeAlias = int | core_defs.IntegralScalar - def __str__(self) -> str: - return f"{self.dim}={self.unit_range}" +FiniteDimensionRange: TypeAlias = DimensionRange[ranges.FiniteUnitRange] -IntIndex: TypeAlias = int | core_defs.IntegralScalar +RelativeIndexElement: TypeAlias = IntIndex | slice | types.EllipsisType -class NamedIndex(NamedTuple): - dim: Dimension - value: IntIndex - def __str__(self) -> str: - return f"{self.dim}={self.value}" +#: Slice syntax for a range on a dimension, `field[I(5):I(10)]`; a missing bound is open, and +#: the only step is 1. Evaluated lazily, because `slice` is not subscriptable at runtime. +type DimensionSlice[D: DimensionIndex] = ( + slice[D, D, Literal[1] | None] + | slice[D, None, Literal[1] | None] + | slice[None, D, Literal[1] | None] +) + + +AbsoluteIndexElement: TypeAlias = DimensionSelection | DimensionSlice -FiniteNamedRange: TypeAlias = NamedRange[ranges.FiniteUnitRange] -RelativeIndexElement: TypeAlias = IntIndex | slice | types.EllipsisType -NamedSlice: TypeAlias = slice # once slice is generic we should do: slice[NamedIndex, NamedIndex, Literal[1]], see https://peps.python.org/pep-0696/ -AbsoluteIndexElement: TypeAlias = NamedIndex | NamedRange | NamedSlice AnyIndexElement: TypeAlias = RelativeIndexElement | AbsoluteIndexElement -AbsoluteIndexSequence: TypeAlias = Sequence[NamedRange | NamedIndex] + + +AbsoluteIndexSequence: TypeAlias = Sequence[DimensionRange | DimensionIndex | DimensionSlice] + + +#: An absolute index after `embedded.common.canonicalize_any_index_sequence`: no slices. +CanonicalAbsoluteIndexSequence: TypeAlias = Sequence[DimensionRange | DimensionIndex] + + RelativeIndexSequence: TypeAlias = tuple[ slice | IntIndex | types.EllipsisType, ... ] # is a tuple but called Sequence for symmetry + + AnyIndexSequence: TypeAlias = RelativeIndexSequence | AbsoluteIndexSequence + + AnyIndexSpec: TypeAlias = AnyIndexElement | AnyIndexSequence @@ -303,22 +1035,35 @@ def is_int_index(p: Any) -> TypeGuard[IntIndex]: return isinstance(p, (int, core_defs.INTEGRAL_TYPES)) -def is_finite_named_range(v: NamedRange) -> TypeGuard[FiniteNamedRange]: - return ranges.UnitRange.is_finite(v.unit_range) +def is_finite_dimension_range(v: DimensionRange) -> TypeGuard[FiniteDimensionRange]: + return ranges.UnitRange.is_finite(v.value) + +def is_dimension_slice(obj: object) -> TypeIs[DimensionSlice[DimensionIndex]]: + """ + Check whether `obj` is a `DimensionSlice`. -def is_named_slice(obj: AnyIndexSpec) -> TypeGuard[slice]: - return isinstance(obj, slice) and ( - isinstance(obj.start, NamedIndex) and isinstance(obj.stop, NamedIndex) + That is a slice whose bounds are dimension indices (or `None` for an open bound, but not + both) and whose step is `None` or 1. + """ + if not isinstance(obj, slice) or obj.step not in (None, 1): + return False + bounds = (obj.start, obj.stop) + return any(isinstance(b, DimensionIndex) for b in bounds) and all( + b is None or isinstance(b, DimensionIndex) for b in bounds ) def is_any_index_element(v: AnyIndexSpec) -> TypeGuard[AnyIndexElement]: - return is_int_index(v) or isinstance(v, (NamedRange, NamedIndex, slice)) or v is Ellipsis + return ( + is_int_index(v) or isinstance(v, (DimensionRange, DimensionIndex, slice)) or v is Ellipsis + ) -def is_absolute_index_sequence(v: AnyIndexSequence) -> TypeGuard[AbsoluteIndexSequence]: - return isinstance(v, Sequence) and all(isinstance(e, (NamedRange, NamedIndex)) for e in v) +def is_absolute_index_sequence(v: AnyIndexSequence) -> TypeGuard[CanonicalAbsoluteIndexSequence]: + return isinstance(v, Sequence) and all( + isinstance(e, (DimensionRange, DimensionIndex)) for e in v + ) def is_relative_index_sequence(v: AnyIndexSequence) -> TypeGuard[RelativeIndexSequence]: @@ -332,7 +1077,7 @@ def as_any_index_sequence(index: AnyIndexSpec) -> AnyIndexSequence: return cast(AnyIndexSequence, (index,) if is_any_index_element(index) else index) -def named_range(v: tuple[Dimension, ranges.RangeLike]) -> NamedRange: - if isinstance(v, NamedRange): +def dimension_range(v: tuple[Dimension, ranges.RangeLike]) -> DimensionRange: + if isinstance(v, DimensionRange): return v - return NamedRange(v[0], ranges.unit_range(v[1])) + return DimensionRange(v[0], ranges.unit_range(v[1])) diff --git a/src/gt4py/next/common/domains.py b/src/gt4py/next/common/domains.py index 3a90b7f234..55aba3cbf5 100644 --- a/src/gt4py/next/common/domains.py +++ b/src/gt4py/next/common/domains.py @@ -23,15 +23,15 @@ @dataclasses.dataclass(frozen=True, init=False) -class Domain(Sequence[dimensions.NamedRange[ranges_._Rng]], Generic[ranges_._Rng]): - """Describes the `Domain` of a `Field` as a `Sequence` of `NamedRange` s.""" +class Domain(Sequence[dimensions.DimensionRange[ranges_._Rng]], Generic[ranges_._Rng]): + """Describes the `Domain` of a `Field` as a `Sequence` of `DimensionRange` s.""" dims: tuple[dimensions.Dimension, ...] ranges: tuple[ranges_._Rng, ...] def __init__( self, - *args: dimensions.NamedRange[ranges_._Rng], + *args: dimensions.DimensionRange[ranges_._Rng], dims: Optional[Sequence[dimensions.Dimension]] = None, ranges: Optional[Sequence[ranges_._Rng]] = None, ) -> None: @@ -44,7 +44,7 @@ def __init__( ) assert dims is not None and ranges is not None # for mypy - if not all(isinstance(dim, dimensions.Dimension) for dim in dims): + if not all(isinstance(dim, dimensions.DimensionMeta) for dim in dims): raise ValueError( f"'dims' argument needs to be a 'tuple[Dimension, ...]', got '{dims}'." ) @@ -60,9 +60,9 @@ def __init__( object.__setattr__(self, "dims", tuple(dims)) object.__setattr__(self, "ranges", tuple(ranges)) else: - if not all(isinstance(arg, dimensions.NamedRange) for arg in args): + if not all(isinstance(arg, dimensions.DimensionRange) for arg in args): raise ValueError( - f"Elements of 'Domain' need to be instances of 'NamedRange', got '{args}'." + f"Elements of 'Domain' need to be instances of 'DimensionRange', got '{args}'." ) dims, ranges = zip(*args) if args else ((), ()) object.__setattr__(self, "dims", tuple(dims)) @@ -94,24 +94,27 @@ def __str__(self) -> str: return f"Domain({', '.join(f'{e}' for e in self)})" @overload - def __getitem__(self, index: int) -> dimensions.NamedRange: ... + def __getitem__(self, index: int) -> dimensions.DimensionRange: ... @overload def __getitem__(self, index: slice) -> Self: ... @overload - def __getitem__(self, index: dimensions.Dimension) -> dimensions.NamedRange: ... + def __getitem__( + self, index: dimensions.Dimension | dimensions.DimensionRef + ) -> dimensions.DimensionRange: ... def __getitem__( - self, index: int | slice | dimensions.Dimension - ) -> dimensions.NamedRange | Domain: - if isinstance(index, dimensions.Dimension): - try: - index = self.dims.index(index) - except ValueError as ex: - raise KeyError(f"No Dimension of type '{index}' is present in the Domain.") from ex + self, index: int | slice | dimensions.Dimension | dimensions.DimensionRef + ) -> dimensions.DimensionRange | Domain: + if isinstance(index, (dimensions.DimensionMeta, dimensions.DimensionRef)): + # a ref (from a type specification) matches the class it describes + found = self.dim_index(index) + if found is None: + raise KeyError(f"No Dimension of type '{index}' is present in the Domain.") + index = found if isinstance(index, int): - return dimensions.NamedRange(dim=self.dims[index], unit_range=self.ranges[index]) + return dimensions.DimensionRange(dim=self.dims[index], value=self.ranges[index]) if isinstance(index, slice): dims_slice = self.dims[index] ranges_slice = self.ranges[index] @@ -124,17 +127,21 @@ def __and__(self, other: Domain) -> Domain: Intersect `Domain`s, missing `Dimension`s are considered infinite. Examples: - >>> from gt4py.next.common import Dimension, NamedRange, UnitRange - >>> I = Dimension("I") - >>> J = Dimension("J") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionRange, UnitRange + >>> class I(CartesianAxisIndex): ... + >>> class J(CartesianAxisIndex): ... - >>> Domain(NamedRange(I, UnitRange(-1, 3))) & Domain(NamedRange(I, UnitRange(1, 6))) - Domain(dims=(Dimension(value='I', kind=),), ranges=(UnitRange(1, 3),)) + >>> print( + ... Domain(DimensionRange(I, UnitRange(-1, 3))) + ... & Domain(DimensionRange(I, UnitRange(1, 6))) + ... ) + Domain(I=(1:3)) - >>> Domain(NamedRange(I, UnitRange(-1, 3)), NamedRange(J, UnitRange(2, 4))) & Domain( - ... NamedRange(I, UnitRange(1, 6)) + >>> print( + ... Domain(DimensionRange(I, UnitRange(-1, 3)), DimensionRange(J, UnitRange(2, 4))) + ... & Domain(DimensionRange(I, UnitRange(1, 6))) ... ) - Domain(dims=(Dimension(value='I', kind=), Dimension(value='J', kind=)), ranges=(UnitRange(1, 3), UnitRange(2, 4))) + Domain(I=(1:3), J=(2:4)) """ broadcast_dims = tuple(dimensions.promote_dims(self.dims, other.dims)) intersected_ranges = tuple( @@ -182,11 +189,14 @@ def slice_at(self) -> utils.IndexerCallable[slice, Domain]: Create a new domain by slicing the domain ranges at the provided relative slices. Examples: - >>> from gt4py.next.common import Dimension, NamedRange, UnitRange - >>> I, J = Dimension("I"), Dimension("J") - >>> domain = Domain(NamedRange(I, UnitRange(0, 10)), NamedRange(J, UnitRange(5, 15))) - >>> domain.slice_at[2:3, 2:5] - Domain(dims=(Dimension(value='I', kind=), Dimension(value='J', kind=)), ranges=(UnitRange(2, 3), UnitRange(7, 10))) + >>> from gt4py.next.common import CartesianAxisIndex, DimensionRange, UnitRange + >>> class I(CartesianAxisIndex): ... + >>> class J(CartesianAxisIndex): ... + >>> domain = Domain( + ... DimensionRange(I, UnitRange(0, 10)), DimensionRange(J, UnitRange(5, 15)) + ... ) + >>> print(domain.slice_at[2:3, 2:5]) + Domain(I=(2:3), J=(7:10)) """ def _domain_slicer(*args: slice) -> Domain: @@ -209,17 +219,28 @@ def is_empty(self) -> bool: return any(rng.is_empty() for rng in self.ranges) @overload - def dim_index(self, dim: dimensions.Dimension, *, allow_missing: Literal[False]) -> int: ... + def dim_index( + self, dim: dimensions.Dimension | dimensions.DimensionRef, *, allow_missing: Literal[False] + ) -> int: ... @overload def dim_index( - self, dim: dimensions.Dimension, *, allow_missing: Literal[True] = True + self, + dim: dimensions.Dimension | dimensions.DimensionRef, + *, + allow_missing: Literal[True] = True, ) -> Optional[int]: ... - def dim_index(self, dim: dimensions.Dimension, *, allow_missing: bool = True) -> Optional[int]: - if dim in self.dims: + def dim_index( + self, dim: dimensions.Dimension | dimensions.DimensionRef, *, allow_missing: bool = True + ) -> Optional[int]: + if isinstance(dim, dimensions.DimensionRef): + for i, d in enumerate(self.dims): + if dimensions.dimension_ref(d) == dim: + return i + elif dim in self.dims: return self.dims.index(dim) - elif allow_missing: + if allow_missing: return None else: raise ValueError(f"Dimension '{dim}' not found in Domain.") @@ -228,19 +249,19 @@ def pop(self, index: int | dimensions.Dimension = -1) -> Domain: return self.replace(index) def insert( - self, index: int | dimensions.Dimension, *named_ranges: dimensions.NamedRange + self, index: int | dimensions.Dimension, *dimension_ranges: dimensions.DimensionRange ) -> Domain: if isinstance(index, int) and index == len(self.dims): - new_dims, new_ranges = zip(*named_ranges) + new_dims, new_ranges = zip(*dimension_ranges) return Domain(dims=self.dims + new_dims, ranges=self.ranges + new_ranges) else: - return self.replace(index, *named_ranges) + return self.replace(index, *dimension_ranges) def replace( - self, index: int | dimensions.Dimension, *named_ranges: dimensions.NamedRange + self, index: int | dimensions.Dimension, *dimension_ranges: dimensions.DimensionRange ) -> Domain: - assert all(isinstance(nr, dimensions.NamedRange) for nr in named_ranges) - if isinstance(index, dimensions.Dimension): + assert all(isinstance(nr, dimensions.DimensionRange) for nr in dimension_ranges) + if isinstance(index, dimensions.DimensionMeta): dim_index = self.dim_index(index) if dim_index is None: raise ValueError(f"Dimension '{index}' not found in Domain.") @@ -251,8 +272,8 @@ def replace( ) if index < 0: index += len(self.dims) - new_dims = (arg.dim for arg in named_ranges) if len(named_ranges) > 0 else () - new_ranges = (arg.unit_range for arg in named_ranges) if len(named_ranges) > 0 else () + new_dims = (arg.dim for arg in dimension_ranges) if len(dimension_ranges) > 0 else () + new_ranges = (arg.value for arg in dimension_ranges) if len(dimension_ranges) > 0 else () dims = self.dims[:index] + tuple(new_dims) + self.dims[index + 1 :] ranges = self.ranges[:index] + tuple(new_ranges) + self.ranges[index + 1 :] @@ -271,7 +292,7 @@ def __getstate__(self) -> dict[str, Any]: DomainLike: TypeAlias = ( Sequence[tuple[dimensions.Dimension, ranges_.RangeLike]] | Mapping[dimensions.Dimension, ranges_.RangeLike] -) # `Domain` is `Sequence[NamedRange]` and therefore a subset +) # `Domain` is `Sequence[DimensionRange]` and therefore a subset def domain(domain_like: DomainLike) -> Domain: @@ -279,26 +300,26 @@ def domain(domain_like: DomainLike) -> Domain: Construct `Domain` from `DomainLike` object. Examples: - >>> from gt4py.next.common import Dimension - >>> I = Dimension("I") - >>> J = Dimension("J") + >>> from gt4py.next.common import CartesianAxisIndex + >>> class I(CartesianAxisIndex): ... + >>> class J(CartesianAxisIndex): ... - >>> domain(((I, (2, 4)), (J, (3, 5)))) - Domain(dims=(Dimension(value='I', kind=), Dimension(value='J', kind=)), ranges=(UnitRange(2, 4), UnitRange(3, 5))) + >>> print(domain(((I, (2, 4)), (J, (3, 5))))) + Domain(I=(2:4), J=(3:5)) - >>> domain({I: (2, 4), J: (3, 5)}) - Domain(dims=(Dimension(value='I', kind=), Dimension(value='J', kind=)), ranges=(UnitRange(2, 4), UnitRange(3, 5))) + >>> print(domain({I: (2, 4), J: (3, 5)})) + Domain(I=(2:4), J=(3:5)) - >>> domain(((I, 2), (J, 4))) - Domain(dims=(Dimension(value='I', kind=), Dimension(value='J', kind=)), ranges=(UnitRange(0, 2), UnitRange(0, 4))) + >>> print(domain(((I, 2), (J, 4)))) + Domain(I=(0:2), J=(0:4)) - >>> domain({I: 2, J: 4}) - Domain(dims=(Dimension(value='I', kind=), Dimension(value='J', kind=)), ranges=(UnitRange(0, 2), UnitRange(0, 4))) + >>> print(domain({I: 2, J: 4})) + Domain(I=(0:2), J=(0:4)) """ if isinstance(domain_like, Domain): return domain_like if isinstance(domain_like, Sequence): - return Domain(*tuple(dimensions.named_range(d) for d in domain_like)) + return Domain(*tuple(dimensions.dimension_range(d) for d in domain_like)) if isinstance(domain_like, Mapping): if all(isinstance(elem, core_defs.INTEGRAL_TYPES) for elem in domain_like.values()): return Domain( diff --git a/src/gt4py/next/common/fields.py b/src/gt4py/next/common/fields.py index 42138e536a..fc7af32475 100644 --- a/src/gt4py/next/common/fields.py +++ b/src/gt4py/next/common/fields.py @@ -61,7 +61,10 @@ def __gt_domain__(self) -> domains.Domain: @property def __gt_dims__(self) -> tuple[str, ...]: - return tuple(d.value for d in self.__gt_domain__.dims) + # NOTE: the unqualified name, not the `tag`. This is the interop protocol with + # `gt4py.cartesian`, which identifies axes by their bare names (`"I"`, `"J"`, `"K"`); a + # qualified tag would not match and the axes would be transposed wrongly (ADR 0030). + return tuple(d.__qualname__ for d in self.__gt_domain__.dims) @runtime_checkable @@ -205,13 +208,20 @@ def __setitem__( #: Type alias for primitive numeric values (i.e. scalars or fields). NumericValue: TypeAlias = core_defs.Scalar | Field + + NumericValueT = TypeVar("NumericValueT", bound=NumericValue) + + NUMERIC_VALUE_TYPES: Final[tuple[type[NumericValue], ...]] = xtyping.get_represented_types( NumericValue ) + #: Type alias for any kind primitive value understood by GT4Py DSL. PrimitiveValue: TypeAlias = NumericValue # For now, only numeric values, in the future it could include functions, enums, ... + + PRIMITIVE_VALUE_TYPES: Final[tuple[type[PrimitiveValue], ...]] = xtyping.get_represented_types( PrimitiveValue ) diff --git a/src/gt4py/next/common/offset_providers.py b/src/gt4py/next/common/offset_providers.py index 957452fa81..74393f50f1 100644 --- a/src/gt4py/next/common/offset_providers.py +++ b/src/gt4py/next/common/offset_providers.py @@ -10,16 +10,22 @@ from __future__ import annotations from collections.abc import Callable, Mapping -from typing import Any, TypeAlias, TypeGuard +from typing import Any, Optional, TypeAlias, TypeGuard, TypeVar from gt4py.next.common import connectivities, dimensions OffsetProviderElem: TypeAlias = connectivities.NeighborTable + + OffsetProviderTypeElem: TypeAlias = connectivities.NeighborConnectivityType + + # Note: `OffsetProvider` and `OffsetProviderType` should not be accessed directly, # use the `get_offset` and `get_offset_type` functions instead. OffsetProvider: TypeAlias = Mapping[dimensions.Tag, OffsetProviderElem] + + OffsetProviderType: TypeAlias = Mapping[dimensions.Tag, OffsetProviderTypeElem] @@ -35,6 +41,52 @@ def is_offset_provider_type(obj: Any) -> TypeGuard[OffsetProviderType]: return all(isinstance(el, OffsetProviderTypeElem) for el in obj.values()) +def _dimension_tag_key(key: str | dimensions.Dimension | dimensions.DimensionRef) -> str: + """ + Normalize a key of a string-keyed configuration mapping that may name a dimension. + + A dimension class or ref becomes its tag; a string is kept as is. + """ + if isinstance(key, (dimensions.DimensionMeta, dimensions.DimensionRef)): + return dimensions.dimension_ref(key).tag + if not isinstance(key, str): + raise TypeError(f"Expected a string or a dimension as key, got '{key!r}'.") + return key + + +_V = TypeVar("_V") + + +def normalize_offset_provider(offset_provider: Mapping[Any, _V]) -> dict[str, _V]: + """Key an offset provider by strings: a dimension key (a local dimension) becomes its tag.""" + if all(isinstance(k, str) for k in offset_provider): + return offset_provider # type: ignore[return-value] # the common case, no copy + return {_dimension_tag_key(k): v for k, v in offset_provider.items()} + + +def normalize_symbolic_domain_sizes( + sizes: Optional[Mapping[Any, _V]], +) -> Optional[dict[str, _V]]: + """ + Key `symbolic_domain_sizes` by dimension tag; dimension classes and refs are accepted. + + Every key must name a dimension, so a string that is not a tag (`module:qualname`, e.g. a bare + name like `"Cell"`) could never match and is rejected rather than silently ignored. + """ + if sizes is None: + return None + result: dict[str, _V] = {} + for key, value in sizes.items(): + tag = _dimension_tag_key(key) + if ":" not in tag: + raise ValueError( + f"'symbolic_domain_sizes' key '{tag}' is not a dimension tag ('module:qualname')" + " and would never match; use the dimension class as the key." + ) + result[tag] = value + return result + + def offset_provider_to_type( offset_provider: OffsetProvider | OffsetProviderType, ) -> OffsetProviderType: diff --git a/src/gt4py/next/common/ranges.py b/src/gt4py/next/common/ranges.py index 70c9ca750a..30f84876da 100644 --- a/src/gt4py/next/common/ranges.py +++ b/src/gt4py/next/common/ranges.py @@ -45,12 +45,20 @@ def __ge__(self, other: int | Infinity) -> bool: def __gt__(self, other: int | Infinity) -> bool: return self is self.POSITIVE and other is not self + def __str__(self) -> str: + return "inf" if self is self.POSITIVE else "-inf" + + def __repr__(self) -> str: + return f"{type(self).__name__}.{self.name}" + def _as_int(v: core_defs.IntegralScalar | Infinity) -> int | Infinity: return v if isinstance(v, Infinity) else int(v) _Left = TypeVar("_Left", int, Infinity) + + _Right = TypeVar("_Right", int, Infinity) @@ -102,7 +110,7 @@ def is_empty(self) -> bool: ) # post_init ensures that empty is represented as UnitRange(0, 0) def __repr__(self) -> str: - return f"UnitRange({self.start}, {self.stop})" + return f"UnitRange({self.start!r}, {self.stop!r})" @overload def __getitem__(self, index: int) -> int: ... @@ -176,6 +184,7 @@ def __str__(self) -> str: FiniteUnitRange: TypeAlias = UnitRange[int, int] + _Rng = TypeVar( "_Rng", FiniteUnitRange, @@ -184,6 +193,7 @@ def __str__(self) -> str: UnitRange[Infinity, Infinity], ) + RangeLike: TypeAlias = ( _Rng | range diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index 11453d5138..3d4c77802e 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -68,7 +68,7 @@ class FieldConstructor: def __init__( self, allocator: Allocator | None = None, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, device: core_defs.Device | None = None, ): if allocator is None: @@ -175,7 +175,7 @@ def as_field( ) -> nd_array_field.NdArrayField: """Create a `Field` from an array-like object. See :func:`as_field` for details.""" if isinstance(domain, Sequence) and all( - isinstance(dim, common.Dimension) for dim in domain + isinstance(dim, common.DimensionMeta) for dim in domain ): domain = cast(Sequence[common.Dimension], domain) if len(domain) != data.ndim: @@ -332,7 +332,7 @@ def asarray( class _CustomLayoutConstructor(_FieldArrayConstructor): allocator: next_allocators.FieldBufferAllocatorProtocol device: core_defs.Device | None = None - aligned_index: Sequence[common.NamedIndex] | None = None + aligned_index: Sequence[common.DimensionIndex] | None = None @functools.cached_property def device_id(self) -> int: @@ -381,7 +381,7 @@ def asarray( @eve.utils.optional_lru_cache def _field_constructor( allocator: Allocator | None, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, device: core_defs.Device | None = None, ) -> FieldConstructor: return FieldConstructor(allocator, aligned_index=aligned_index, device=device) @@ -392,7 +392,7 @@ def empty( domain: common.DomainLike, dtype: core_defs.DTypeLike = DEFAULT_DTYPE, *, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, allocator: Allocator | None = None, device: core_defs.Device | None = None, ) -> nd_array_field.NdArrayField: @@ -428,7 +428,7 @@ def empty( Initialize a field in one dimension with a backend and a range domain: >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> a = gtx.empty({IDim: range(3, 10)}, allocator=gtx.itir_python) >>> a.shape (7,) @@ -437,7 +437,7 @@ def empty( >>> import numpy as np >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> a = gtx.empty({IDim: range(3, 10)}, allocator=np) >>> a.shape (7,) @@ -445,7 +445,7 @@ def empty( Initialize with a device and an integer domain. It works like a shape with named dimensions: >>> from gt4py._core import definitions as core_defs - >>> JDim = gtx.Dimension("J") + >>> class JDim(gtx.CartesianAxisIndex): ... >>> b = gtx.empty( ... {IDim: 3, JDim: 3}, int, device=core_defs.Device(core_defs.DeviceType.CPU, 0) ... ) @@ -462,7 +462,7 @@ def zeros( domain: common.DomainLike, dtype: core_defs.DTypeLike = DEFAULT_DTYPE, *, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, allocator: Allocator | None = None, device: core_defs.Device | None = None, ) -> nd_array_field.NdArrayField: @@ -473,7 +473,7 @@ def zeros( Examples: >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> gtx.zeros({IDim: range(3, 10)}, allocator=gtx.itir_python).ndarray array([0., 0., 0., 0., 0., 0., 0.]) """ @@ -487,7 +487,7 @@ def ones( domain: common.DomainLike, dtype: core_defs.DTypeLike = DEFAULT_DTYPE, *, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, allocator: Allocator | None = None, device: core_defs.Device | None = None, ) -> nd_array_field.NdArrayField: @@ -498,7 +498,7 @@ def ones( Examples: >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> gtx.ones({IDim: range(3, 10)}, allocator=gtx.itir_python).ndarray array([1., 1., 1., 1., 1., 1., 1.]) """ @@ -513,7 +513,7 @@ def full( fill_value: core_defs.Scalar, dtype: core_defs.DTypeLike | None = None, *, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, allocator: Allocator | None = None, device: core_defs.Device | None = None, ) -> nd_array_field.NdArrayField: @@ -529,7 +529,7 @@ def full( Examples: >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> gtx.full({IDim: 3}, 5, allocator=gtx.itir_python).ndarray array([5, 5, 5]) """ @@ -545,7 +545,7 @@ def as_field( dtype: core_defs.DTypeLike | None = None, *, origin: Mapping[common.Dimension, int] | None = None, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, allocator: Allocator | None = None, device: core_defs.Device | None = None, ) -> nd_array_field.NdArrayField: @@ -574,7 +574,7 @@ def as_field( Examples: >>> import numpy as np >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> xdata = np.array([1, 2, 3]) Automatic domain from just dimensions: @@ -612,7 +612,7 @@ def as_connectivity( dtype: core_defs.DTypeLike | None = None, *, origin: Mapping[common.Dimension, int] | None = None, - aligned_index: Sequence[common.NamedIndex] | None = None, + aligned_index: Sequence[common.DimensionIndex] | None = None, allocator: Allocator | None = None, device: core_defs.Device | None = None, skip_value: core_defs.IntegralScalar | eve.NothingType | None = eve.NOTHING, @@ -648,17 +648,17 @@ def as_connectivity( Examples: >>> import numpy as np >>> from gt4py import next as gtx - >>> Vertex = gtx.Dimension("Vertex") - >>> Edge = gtx.Dimension("Edge") - >>> V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) + >>> class Vertex(gtx.DimensionIndex): ... + >>> class Edge(gtx.DimensionIndex): ... + >>> class V2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... >>> data = np.array([[0, 1], [1, 2], [2, 0]]) >>> conn = gtx.as_connectivity([Vertex, V2EDim], Edge, data) >>> conn.ndarray array([[0, 1], [1, 2], [2, 0]]) - >>> conn.domain - Domain(dims=(Dimension(value='Vertex', kind=), Dimension(value='V2E', kind=)), ranges=(UnitRange(0, 3), UnitRange(0, 2))) + >>> print(conn.domain) + Domain(Vertex=(0:3), V2EDim=(0:2)) """ if skip_value is eve.NOTHING: skip_value = ( diff --git a/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index e0d9644b66..7ef5b45fbf 100644 --- a/src/gt4py/next/custom_layout_allocators.py +++ b/src/gt4py/next/custom_layout_allocators.py @@ -38,7 +38,7 @@ def __gt_allocate__( domain: common.Domain, dtype: core_defs.DType[core_defs.ScalarT], device_id: int = 0, - aligned_index: Optional[Sequence[common.NamedIndex]] = None, # absolute position + aligned_index: Optional[Sequence[common.DimensionIndex]] = None, # absolute position ) -> core_allocators.TensorBuffer[core_defs.DeviceTypeT, core_defs.ScalarT]: ... @@ -91,7 +91,7 @@ def is_field_allocation_tool_for( def _absolute_to_relative_index( - indices: Sequence[common.NamedIndex], domain: common.Domain + indices: Sequence[common.DimensionIndex], domain: common.Domain ) -> Sequence[int]: """Convert absolute indices to relative indices based on the domain's dimensions. @@ -101,15 +101,15 @@ def _absolute_to_relative_index( dim_to_index = {named_idx.dim: int(named_idx.value) for named_idx in indices} result = [] - for named_range in domain: - dim = named_range.dim - abs_idx = dim_to_index.get(dim, named_range.unit_range.start) - if abs_idx < named_range.unit_range.start or abs_idx >= named_range.unit_range.stop: + for dim_range in domain: + dim = dim_range.dim + abs_idx = dim_to_index.get(dim, dim_range.value.start) + if abs_idx < dim_range.value.start or abs_idx >= dim_range.value.stop: raise ValueError( f"Absolute index for dimension '{dim}' is {abs_idx}, " - f"which is outside the domain range [{named_range.unit_range.start}, {named_range.unit_range.stop})." + f"which is outside the domain range [{dim_range.value.start}, {dim_range.value.stop})." ) - result.append(abs_idx - named_range.unit_range.start) + result.append(abs_idx - dim_range.value.start) return result @@ -135,7 +135,7 @@ def __gt_allocate__( domain: common.Domain, dtype: core_defs.DType[core_defs.ScalarT], device_id: int = 0, - aligned_index: Optional[Sequence[common.NamedIndex]] = None, # absolute position + aligned_index: Optional[Sequence[common.DimensionIndex]] = None, # absolute position ) -> core_allocators.TensorBuffer[core_defs.DeviceTypeT, core_defs.ScalarT]: shape = domain.shape layout_map = self.layout_mapper(domain.dims) @@ -224,7 +224,7 @@ def __gt_allocate__( domain: common.Domain, dtype: core_defs.DType[core_defs.ScalarT], device_id: int = 0, - aligned_index: Optional[Sequence[common.NamedIndex]] = None, # absolute position + aligned_index: Optional[Sequence[common.DimensionIndex]] = None, # absolute position ) -> core_allocators.TensorBuffer[core_defs.DeviceTypeT, core_defs.ScalarT]: raise self.exception diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 4826c3f31a..ed2ba73836 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -250,5 +250,7 @@ def _unflatten_connectivity( _unflatten_connectivity, ) -# e.g. the `Dimension`s of an offset provider in the arguments of `jax.jit` -jax.tree_util.register_static(common.Dimension) +# e.g. the `Dimension`s of an offset provider in the arguments of `jax.jit`: a dimension is a +# class, so its type is its metaclass (registered by exact type, as all pytree nodes) +jax.tree_util.register_static(common.DimensionMeta) +jax.tree_util.register_static(common.StaggeredMeta) diff --git a/src/gt4py/next/embedded/array_libraries/torch_ops.py b/src/gt4py/next/embedded/array_libraries/torch_ops.py index e700fb2cd4..b64ca59246 100644 --- a/src/gt4py/next/embedded/array_libraries/torch_ops.py +++ b/src/gt4py/next/embedded/array_libraries/torch_ops.py @@ -204,21 +204,21 @@ def _connectivity(data: torch.Tensor, /, *args: Any, **kwargs: Any) -> Any: # pytree contexts are plain constants: objects created in the region, as the domains of -# the fields a call returns, are no constants for `torch.compile` -_DomainContext = tuple[tuple[str, common.DimensionKind, int, int], ...] +# the fields a call returns, are no constants for `torch.compile`. A dimension is a class, +# declared outside of the region, so it is kept as it is: its identity is the dimension's. +_DomainContext = tuple[tuple[common.Dimension, int, int], ...] def _domain_to_context(domain: common.Domain) -> _DomainContext: return tuple( - (dim.value, dim.kind, rng.start, rng.stop) - for dim, rng in zip(domain.dims, domain.ranges, strict=True) + (dim, rng.start, rng.stop) for dim, rng in zip(domain.dims, domain.ranges, strict=True) ) def _domain_from_context(context: _DomainContext) -> common.Domain: return common.Domain( - dims=tuple(common.Dimension(value, kind) for value, kind, _, _ in context), - ranges=tuple(common.UnitRange(start, stop) for _, _, start, stop in context), + dims=tuple(dim for dim, _, _ in context), + ranges=tuple(common.UnitRange(start, stop) for _, start, stop in context), ) @@ -247,8 +247,7 @@ def _unflatten_field( #: with an array compared by memory _ConnectivityContext = tuple[ _DomainContext, - str, - common.DimensionKind, + common.Dimension, Optional[int], _StaticValuesByMemory | nd_array_field.StaticValues, ] @@ -279,8 +278,7 @@ def _flatten_connectivity( skip_value = connectivity.skip_value return [ndarray], ( _domain_to_context(connectivity.domain), - codomain.value, - codomain.kind, + codomain, None if skip_value is None else int(skip_value), static_values, ) @@ -290,7 +288,7 @@ def _unflatten_connectivity( children: list[torch.Tensor], context: _ConnectivityContext ) -> nd_array_field.NdArrayConnectivityField: (ndarray,) = children - domain, codomain_value, codomain_kind, skip_value, context_static_values = context + domain, codomain, skip_value, context_static_values = context static_values: Any = context_static_values if _is_concrete(ndarray): static_values = nd_array_field.StaticValues.IN_BUFFER @@ -304,7 +302,7 @@ def _unflatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField = nd_array_field.NdArrayConnectivityField( _domain_from_context(domain), ndarray, - common.Dimension(codomain_value, codomain_kind), + codomain, skip_value, _static_values=static_values, ) # type: ignore[abstract, unused-ignore] # see 'jax_ops._unflatten_connectivity' diff --git a/src/gt4py/next/embedded/common.py b/src/gt4py/next/embedded/common.py index 39089547b8..6cffce7662 100644 --- a/src/gt4py/next/embedded/common.py +++ b/src/gt4py/next/embedded/common.py @@ -12,7 +12,7 @@ import itertools import operator from collections.abc import Iterator, Sequence -from typing import Any, Optional, cast +from typing import Any, Optional, TypeGuard, cast from gt4py.next import common from gt4py.next.embedded import exceptions as embedded_exceptions @@ -33,7 +33,7 @@ def sub_domain(domain: common.Domain, index: common.AnyIndexSpec) -> common.Doma def _relative_sub_domain( domain: common.Domain, index: common.RelativeIndexSequence ) -> common.Domain: - named_ranges: list[common.NamedRange] = [] + dimension_ranges: list[common.DimensionRange] = [] expanded = _expand_ellipsis(index, len(domain)) if len(domain) < len(expanded): @@ -45,7 +45,7 @@ def _relative_sub_domain( if isinstance(idx, slice): try: sliced = _slice_range(rng, idx) - named_ranges.append(common.NamedRange(dim, sliced)) + dimension_ranges.append(common.DimensionRange(dim, sliced)) except IndexError as ex: raise embedded_exceptions.IndexOutOfBounds( domain=domain, indices=index, index=idx, dim=dim @@ -60,24 +60,25 @@ def _relative_sub_domain( domain=domain, indices=index, index=idx, dim=dim ) - return common.Domain(*named_ranges) + return common.Domain(*dimension_ranges) def _absolute_sub_domain( - domain: common.Domain, index: common.AbsoluteIndexSequence + domain: common.Domain, index: common.CanonicalAbsoluteIndexSequence ) -> common.Domain: - named_ranges: list[common.NamedRange] = [] + dimension_ranges: list[common.DimensionRange] = [] for i, (dim, rng) in enumerate(domain): if (pos := _find_index_of_dim(dim, index)) is not None: named_idx = index[pos] - _, idx = named_idx + idx = named_idx.value if isinstance(idx, common.UnitRange): - if not idx <= rng: + clipped = _clip_open_bounds(idx, rng) + if clipped is None: raise embedded_exceptions.IndexOutOfBounds( domain=domain, indices=index, index=named_idx, dim=dim ) - named_ranges.append(common.NamedRange(dim, idx)) + dimension_ranges.append(common.DimensionRange(dim, clipped)) else: # not in new domain assert common.is_int_index(idx) @@ -87,9 +88,34 @@ def _absolute_sub_domain( ) else: # dimension not mentioned in slice - named_ranges.append(common.NamedRange(dim, domain.ranges[i])) + dimension_ranges.append(common.DimensionRange(dim, domain.ranges[i])) - return common.Domain(*named_ranges) + return common.Domain(*dimension_ranges) + + +def _clip_open_bounds( + selection: common.UnitRange, bounds: common.UnitRange +) -> Optional[common.UnitRange]: + """ + Replace the open (infinite) sides of `selection` by the corresponding sides of `bounds`. + + Indexing a field with an open bound selects up to the field's own bound on that side. Every + infinite side is an open bound, also that of an infinite `Domain` or `DimensionRange` used + as an index. + + Returns: + The clipped range, or `None` if a closed bound of `selection` lies outside `bounds`. + """ + start, stop = selection.start, selection.stop + if start is common.Infinity.NEGATIVE: + start = bounds.start + elif not bounds.start <= start <= bounds.stop: + return None + if stop is common.Infinity.POSITIVE: + stop = bounds.stop + elif not bounds.start <= stop <= bounds.stop: + return None + return common.UnitRange(start, stop) def domain_intersection(*domains: common.Domain) -> common.Domain: @@ -97,11 +123,9 @@ def domain_intersection(*domains: common.Domain) -> common.Domain: Return the intersection of the given domains. Example: - >>> I = common.Dimension("I") - >>> domain_intersection( - ... common.domain({I: (0, 5)}), common.domain({I: (1, 3)}) - ... ) # doctest: +ELLIPSIS - Domain(dims=(Dimension(value='I', ...), ranges=(UnitRange(1, 3),)) + >>> class I(common.CartesianAxisIndex): ... + >>> print(domain_intersection(common.domain({I: (0, 5)}), common.domain({I: (1, 3)}))) + Domain(I=(1:3)) """ if not domains: return common.Domain() @@ -120,8 +144,8 @@ def restrict_to_intersection( Return the with each other intersected domains, ignoring 'ignore_dims' dimensions for the intersection. Example: - >>> I = common.Dimension("I") - >>> J = common.Dimension("J") + >>> class I(common.CartesianAxisIndex): ... + >>> class J(common.CartesianAxisIndex): ... >>> res = restrict_to_intersection( ... common.domain({I: (0, 5), J: (1, 2)}), ... common.domain({I: (1, 3), J: (0, 3)}), @@ -150,9 +174,9 @@ def restrict_to_intersection( ) -def iterate_domain(domain: common.Domain) -> Iterator[tuple[common.NamedIndex]]: +def iterate_domain(domain: common.Domain) -> Iterator[tuple[common.DimensionIndex]]: for idx in itertools.product(*(list(r) for r in domain.ranges)): - yield tuple(common.NamedIndex(d, i) for d, i in zip(domain.dims, idx)) # type: ignore[misc] # trust me, `idx` is `tuple[int, ...]` + yield tuple(d(i) for d, i in zip(domain.dims, idx)) # type: ignore[misc] # trust me, `idx` is `tuple[int, ...]` def _expand_ellipsis( @@ -185,35 +209,52 @@ def _slice_range(input_range: common.UnitRange, slice_obj: slice) -> common.Unit def _find_index_of_dim( dim: common.Dimension, - domain_slice: common.Domain | Sequence[common.NamedRange | common.NamedIndex | Any], + domain_slice: common.Domain | Sequence[common.DimensionRange | common.DimensionIndex | Any], ) -> Optional[int]: - for i, (d, _) in enumerate(domain_slice): - if dim == d: + for i, elem in enumerate(domain_slice): + if dim == elem.dim: return i return None def canonicalize_any_index_sequence(index: common.AnyIndexSpec) -> common.AnyIndexSpec: - # TODO: instead of canonicalizing to `NamedRange`, we should canonicalize to `NamedSlice` - new_index: common.AnyIndexSpec = (index,) if isinstance(index, slice) else index - if isinstance(new_index, tuple) and all(isinstance(i, slice) for i in new_index): - new_index = tuple([_named_slice_to_named_range(i) for i in new_index]) # type: ignore[arg-type, assignment] # all i's are slices as per if statement - return new_index - - -def _named_slice_to_named_range(idx: common.NamedSlice) -> common.NamedRange | common.NamedSlice: - assert hasattr(idx, "start") and hasattr(idx, "stop") - if common.is_named_slice(idx): - start_dim, start_value = idx.start - stop_dim, stop_value = idx.stop - if start_dim != stop_dim: - raise IndexError( - f"Dimensions slicing mismatch between '{start_dim.value}' and '{stop_dim.value}'." - ) - assert isinstance(start_value, int) and isinstance(stop_value, int) - return common.NamedRange(start_dim, common.UnitRange(start_value, stop_value)) - if isinstance(idx.start, common.NamedIndex) and idx.stop is None: - raise IndexError(f"Upper bound needs to be specified for {idx}.") - if isinstance(idx.stop, common.NamedIndex) and idx.start is None: - raise IndexError(f"Lower bound needs to be specified for {idx}.") - return idx + # A `DimensionRange` is the canonical absolute form; a dimension slice is only input syntax. + elements = index if isinstance(index, tuple) else (index,) + if not any(_is_slice_with_dimension_bound(e) for e in elements): + return index + result: list[common.DimensionRange | common.DimensionIndex] = [] + for e in elements: + if _is_slice_with_dimension_bound(e): + result.append(_dimension_slice_to_range(e)) + elif isinstance(e, (common.DimensionRange, common.DimensionIndex)): + result.append(e) + else: + raise IndexError(f"Cannot mix relative index '{e}' with absolute indices in '{index}'.") + return tuple(result) + + +def _is_slice_with_dimension_bound(idx: object) -> TypeGuard[slice]: + return isinstance(idx, slice) and ( + isinstance(idx.start, common.DimensionIndex) or isinstance(idx.stop, common.DimensionIndex) + ) + + +def _dimension_slice_to_range(idx: slice) -> common.DimensionRange: + if idx.step not in (None, 1): + raise IndexError(f"Invalid slice '{idx}': only a step of 1 is supported.") + if not common.is_dimension_slice(idx): + raise IndexError( + f"Invalid slice '{idx}': both bounds must be indices on one dimension, or 'None' for" + " an open bound." + ) + start, stop = idx.start, idx.stop + if start is not None and stop is not None and start.dim != stop.dim: + raise IndexError( + "Dimensions slicing mismatch between" + f" '{start.dim.__qualname__}' and '{stop.dim.__qualname__}'." + ) + bound = start if start is not None else stop + assert bound is not None # `is_dimension_slice` requires at least one bound + return bound.dim.at( + None if start is None else start.value, None if stop is None else stop.value + ) diff --git a/src/gt4py/next/embedded/context.py b/src/gt4py/next/embedded/context.py index 0e25af0067..3506a0c9d8 100644 --- a/src/gt4py/next/embedded/context.py +++ b/src/gt4py/next/embedded/context.py @@ -18,7 +18,7 @@ import gt4py.next.errors.exceptions as exceptions -_column_ranges: contextvars.ContextVar[tuple[common.NamedRange, ...]] = contextvars.ContextVar( +_column_ranges: contextvars.ContextVar[tuple[common.DimensionRange, ...]] = contextvars.ContextVar( "_column_ranges" ) _offset_provider: contextvars.ContextVar[common.OffsetProvider] = contextvars.ContextVar( @@ -33,16 +33,16 @@ @overload -def get_column_ranges() -> tuple[common.NamedRange, ...]: ... +def get_column_ranges() -> tuple[common.DimensionRange, ...]: ... @overload -def get_column_ranges(default: _T) -> tuple[common.NamedRange, ...] | _T: ... +def get_column_ranges(default: _T) -> tuple[common.DimensionRange, ...] | _T: ... def get_column_ranges( default: _T = _NO_DEFAULT_SENTINEL, -) -> tuple[common.NamedRange, ...] | _T: +) -> tuple[common.DimensionRange, ...] | _T: """Ranges of the column (scan) dimensions in the current embedded execution context.""" result = _column_ranges.get(default) if result is _NO_DEFAULT_SENTINEL: @@ -73,7 +73,7 @@ def get_offset_provider(default: _T = _NO_DEFAULT_SENTINEL) -> common.OffsetProv @contextlib.contextmanager def update( *, - column_ranges: tuple[common.NamedRange, ...] | eve.NothingType = eve.NOTHING, + column_ranges: tuple[common.DimensionRange, ...] | eve.NothingType = eve.NOTHING, offset_provider: common.OffsetProvider | eve.NothingType = eve.NOTHING, ) -> Generator[None, None, None]: """Context handler updating the current embedded context with the provided values.""" diff --git a/src/gt4py/next/embedded/exceptions.py b/src/gt4py/next/embedded/exceptions.py index 8d8baf1af8..2f3ce7f3c3 100644 --- a/src/gt4py/next/embedded/exceptions.py +++ b/src/gt4py/next/embedded/exceptions.py @@ -23,8 +23,14 @@ def __init__( index: common.AnyIndexElement, dim: common.Dimension, ): + # `str` of each element: the `repr` of a tuple would show qualified dimension tags + indices_str = ( + f"({', '.join(str(i) for i in indices)})" + if isinstance(indices, tuple) + else str(indices) + ) super().__init__( - f"Out of bounds: slicing {domain} with index `{indices}`, `{index}` is out of bounds in dimension `{dim}`." + f"Out of bounds: slicing {domain} with index `{indices_str}`, `{index}` is out of bounds in dimension `{dim}`." ) self.domain = domain self.indices = indices diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 2be6dcd62a..f218035fa2 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -144,7 +144,7 @@ def from_array( domain = common.domain(domain) array = _asarray(data, dtype) - assert all(isinstance(d, common.Dimension) for d in domain.dims), domain + assert all(isinstance(d, common.DimensionMeta) for d in domain.dims), domain assert len(domain) == array.ndim assert all(s == 1 or len(r) == s for r, s in zip(domain.ranges, array.shape)) @@ -504,11 +504,11 @@ def from_array( # type: ignore[override] assert issubclass(array_ops.of(array).scalar_type(array.dtype), core_defs.INTEGRAL_TYPES) - assert all(isinstance(d, common.Dimension) for d in domain.dims), domain + assert all(isinstance(d, common.DimensionMeta) for d in domain.dims), domain assert len(domain) == array.ndim assert all(len(r) == s or s == 1 for r, s in zip(domain.ranges, array.shape)) - assert isinstance(codomain, common.Dimension) + assert isinstance(codomain, common.DimensionMeta) return cls(domain, array, codomain, _skip_value=skip_value) @@ -604,7 +604,7 @@ def _domain_premap(data: NdArrayField, *connectivities: common.Connectivity) -> f"but got '{data.domain}'." ) - current_range: common.UnitRange = data.domain[dim_idx].unit_range + current_range: common.UnitRange = data.domain[dim_idx].value new_ranges = connectivity._inverse_image(current_range) new_domain = new_domain.replace(dim_idx, *new_ranges) @@ -620,21 +620,21 @@ def _gather_output_domain( for conn in connectivities: cod = conn.codomain # the connectivity's domain, restricted to where it maps into the codomain's range - narrowed = { - nr.dim: nr.unit_range for nr in conn._inverse_image(field_domain[cod].unit_range) - } + narrowed = {nr.dim: nr.value for nr in conn._inverse_image(field_domain[cod].value)} # dimensions the connectivity adds that are not in the field yet introduced = [ - common.NamedRange(dim, rng) for dim, rng in narrowed.items() if dim not in domain.dims + common.DimensionRange(dim, rng) + for dim, rng in narrowed.items() + if dim not in domain.dims ] - result: list[common.NamedRange] = [] + result: list[common.DimensionRange] = [] for nr in domain: if nr.dim == cod: # the codomain expands into the connectivity's domain dimensions if cod in narrowed: # keep the codomain itself when it maps to itself - result.append(common.NamedRange(cod, nr.unit_range & narrowed[cod])) + result.append(common.DimensionRange(cod, nr.value & narrowed[cod])) result.extend(introduced) elif nr.dim in narrowed: # a dimension shared with the connectivity: narrow it - result.append(common.NamedRange(nr.dim, nr.unit_range & narrowed[nr.dim])) + result.append(common.DimensionRange(nr.dim, nr.value & narrowed[nr.dim])) else: result.append(nr) domain = common.Domain(*result) @@ -676,7 +676,7 @@ def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivit conn = conn if sub_domain == conn.domain else conn.restrict(sub_domain) index, index_dims = ops.asarray(conn.ndarray), conn.domain.dims else: - unit_range = new_domain[dim].unit_range + unit_range = new_domain[dim].value index = xp.arange(unit_range.start, unit_range.stop, device=ops.device(buffer)) index_dims = (dim,) if index_dims != gathered: @@ -684,7 +684,7 @@ def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivit if stride != 1: # in int64, so that the linear index cannot overflow index = xp.astype(index, xp.int64) * stride indices.append(index) - offset += data.domain[axis].unit_range.start * stride + offset += data.domain[axis].value.start * stride stride *= buffer.shape[axis] if hi - lo > 1: @@ -711,7 +711,7 @@ def _lay_out( order = sorted(range(len(dims)), key=lambda i: target_dims.index(dims[i])) if order != list(range(len(dims))): array = xp.permute_dims(array, tuple(order)) - shape = tuple(len(domain[d].unit_range) if d in dims else 1 for d in target_dims) + shape = tuple(len(domain[d].value) if d in dims else 1 for d in target_dims) return xp.reshape(array, shape) @@ -742,7 +742,7 @@ def _identity_index_array( """Index array selecting `dim` unchanged over `domain`, in the field's index space, on the device of `like`.""" xp = ops.xp d_idx = domain.dim_index(dim, allow_missing=False) - unit_range = domain[d_idx].unit_range + unit_range = domain[d_idx].value indices = xp.arange( unit_range.start, unit_range.stop, @@ -884,19 +884,21 @@ def _intersect_fields( def _stack_domains(*domains: common.Domain, dim: common.Dimension) -> common.Domain: if not domains: return common.Domain() - dim_start = domains[0][dim].unit_range.start - dim_stop = domains[-1][dim].unit_range.stop - return domains[0].replace(dim, common.NamedRange(dim, common.UnitRange(dim_start, dim_stop))) + dim_start = domains[0][dim].value.start + dim_stop = domains[-1][dim].value.stop + return domains[0].replace( + dim, common.DimensionRange(dim, common.UnitRange(dim_start, dim_stop)) + ) def _concat(*fields: common.Field, dim: common.Dimension) -> common.Field: # TODO(havogt): this function could be extended to a general concat # currently only concatenate along the given dimension - sorted_fields = sorted(fields, key=lambda f: f.domain[dim].unit_range.start) + sorted_fields = sorted(fields, key=lambda f: f.domain[dim].value.start) for prev, curr in itertools.pairwise(sorted_fields): - left = prev.domain[dim].unit_range.stop - right = curr.domain[dim].unit_range.start + left = prev.domain[dim].value.stop + right = curr.domain[dim].value.start if left > right: raise ValueError("Fields to concatenate must not overlap.") if left < right: @@ -989,11 +991,11 @@ def _concat_where( def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> common.Connectivity: if not fbuiltins.is_cartesian_offset(offset): - target_dims = ", ".join(d.value for d in offset.target) + target_dims = ", ".join(d.__qualname__ for d in offset.target) # for the diagnostic raise ValueError( f"'as_offset' is only supported for Cartesian offsets " f"(single target dimension equal to source dimension); " - f"got source '{offset.source.value}' and target ({target_dims})." + f"got source '{offset.source.__qualname__}' and target ({target_dims})." ) source_dim = offset.source coords = _identity_index_array( @@ -1032,7 +1034,7 @@ def _builtin_op( current_offset_provider = embedded_context.get_offset_provider(None) assert current_offset_provider is not None offset_definition = common.get_offset( - current_offset_provider, axis.value + current_offset_provider, axis.tag ) # assumes offset and local dimension have same name assert common.is_neighbor_table(offset_definition) @@ -1040,7 +1042,7 @@ def _builtin_op( # unlike the other dimensions, the neighbor dimension is not intersected: a reduction # needs the field at every neighbor of the table neighbors, table_neighbors = field.domain[axis], offset_definition.domain[axis] - if not neighbors.unit_range >= table_neighbors.unit_range: + if not neighbors.value >= table_neighbors.value: raise ValueError( f"Field has neighbors '{neighbors}', which do not cover the neighbors " f"'{table_neighbors}' of the connectivity." @@ -1050,8 +1052,7 @@ def _builtin_op( new_domain = common.Domain(*[nr for nr in domain if nr.dim != axis]) if new_domain.is_empty(): shape = tuple( - len(nr.unit_range) if common.UnitRange.is_finite(nr.unit_range) else 1 - for nr in new_domain + len(nr.value) if common.UnitRange.is_finite(nr.value) else 1 for nr in new_domain ) empty = ops.xp.empty( shape, dtype=ops.dtype(field.dtype.scalar_type), device=ops.device(field.ndarray) @@ -1064,8 +1065,7 @@ def _builtin_op( if offset_definition.skip_value is None: # a field broadcast (size 1) along a dimension of the table is expanded to its extent table_shape = tuple( - len(nr.unit_range) if nr.dim in offset_definition.domain.dims else 1 - for nr in domain + len(nr.value) if nr.dim in offset_definition.domain.dims else 1 for nr in domain ) neighbor_values = ops.xp.broadcast_to( field.ndarray, np.broadcast_shapes(field.ndarray.shape, table_shape) @@ -1151,15 +1151,17 @@ def _broadcast(field: common.Field, new_dimensions: Sequence[common.Dimension]) if field.domain.dims == new_dimensions: return field domain_slice: list[slice | None] = [] - named_ranges = [] + dimension_ranges = [] for dim in new_dimensions: if (pos := embedded_common._find_index_of_dim(dim, field.domain)) is not None: domain_slice.append(slice(None)) - named_ranges.append(common.NamedRange(dim, field.domain[pos].unit_range)) + dimension_ranges.append(common.DimensionRange(dim, field.domain[pos].value)) else: - domain_slice.append(None) - named_ranges.append(common.NamedRange(dim, common.UnitRange.infinite())) - return common._field(field.ndarray[tuple(domain_slice)], domain=common.Domain(*named_ranges)) + domain_slice.append(None) # np.newaxis + dimension_ranges.append(common.DimensionRange(dim, common.UnitRange.infinite())) + return common._field( + field.ndarray[tuple(domain_slice)], domain=common.Domain(*dimension_ranges) + ) def _builtins_broadcast( @@ -1187,7 +1189,7 @@ def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdA def _get_slices_from_domain_slice( domain: common.Domain, - domain_slice: common.Domain | Sequence[common.NamedRange | common.NamedIndex], + domain_slice: common.Domain | Sequence[common.DimensionRange | common.DimensionIndex], ) -> common.RelativeIndexSequence: """Generate slices for sub-array extraction based on named ranges or named indices within a Domain. @@ -1207,8 +1209,7 @@ def _get_slices_from_domain_slice( for pos_old, (dim, _) in enumerate(domain): if (pos := embedded_common._find_index_of_dim(dim, domain_slice)) is not None: - _, index_or_range = domain_slice[pos] - slice_indices.append(_compute_slice(index_or_range, domain, pos_old)) + slice_indices.append(_compute_slice(domain_slice[pos].value, domain, pos_old)) else: slice_indices.append(slice(None)) return tuple(slice_indices) @@ -1231,14 +1232,17 @@ def _compute_slice( ValueError: If `new_rng` is not an integer or a UnitRange. """ if isinstance(rng, common.UnitRange): + # an open side of `rng` selects up to the field's own bound, i.e. the buffer's end start = ( rng.start - domain.ranges[pos].start if common.UnitRange.is_left_finite(domain.ranges[pos]) + and common.UnitRange.is_left_finite(rng) else None ) stop = ( rng.stop - domain.ranges[pos].start if common.UnitRange.is_right_finite(domain.ranges[pos]) + and common.UnitRange.is_right_finite(rng) else None ) return slice(start, stop) diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 2a8863f0b7..54d91128fa 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -56,8 +56,8 @@ def __call__( # type: ignore[override] f"Scan axis '{scan_axis}' has no range, or ranges that differ, in the output domain." ) if scan_axis in domain_intersection.dims: - scan_range = common.NamedRange( - scan_axis, scan_range.unit_range & domain_intersection[scan_axis].unit_range + scan_range = common.DimensionRange( + scan_axis, scan_range.value & domain_intersection[scan_axis].value ) non_scan_domain = common.Domain(*[nr for nr in domain_intersection if nr.dim != scan_axis]) @@ -76,10 +76,10 @@ def __call__( # type: ignore[override] like=field_utils.first_buffer(*(arguments.extract(arg) for arg in all_args)), ) - def scan_loop(hpos: Sequence[common.NamedIndex]) -> None: + def scan_loop(hpos: Sequence[common.DimensionIndex]) -> None: acc: xtyping.MaybeNestedInTuple[core_defs.ScalarT] = self.init - for k in scan_range.unit_range if self.forward else reversed(scan_range.unit_range): - pos = (*hpos, common.NamedIndex(scan_axis, k)) + for k in scan_range.value if self.forward else reversed(scan_range.value): + pos = (*hpos, scan_axis(k)) new_args = [_tuple_at(pos, arg) for arg in args] new_kwargs = {k: _tuple_at(pos, v) for k, v in kwargs.items()} acc = self.fun(acc, *new_args, **new_kwargs) # type: ignore[arg-type] # need to express that the first argument is the same type as the return @@ -156,8 +156,8 @@ def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> def _get_vertical_ranges( domain: xtyping.MaybeNestedInTuple[common.Domain], -) -> tuple[common.NamedRange, ...]: - ranges: dict[common.Dimension, common.NamedRange] = {} +) -> tuple[common.DimensionRange, ...]: + ranges: dict[common.Dimension, common.DimensionRange] = {} ambiguous: set[common.Dimension] = set() for d in utils.flatten_nested_tuple((domain,)): for nr in d: @@ -200,7 +200,7 @@ def _is_maybe_nested_in_tuple_of_scalars( def _tuple_assign_value( - pos: Sequence[common.NamedIndex], + pos: Sequence[common.DimensionIndex], target: xtyping.MaybeNestedInTuple[common.MutableField], source: xtyping.MaybeNestedInTuple[array_ops.NDValue], ) -> None: @@ -212,7 +212,7 @@ def impl(target: common.MutableField, source: array_ops.NDValue) -> None: def _tuple_at( - pos: Sequence[common.NamedIndex], + pos: Sequence[common.DimensionIndex], field: xtyping.MaybeNestedInTuple[common.Field | array_ops.NDValue], ) -> array_ops.NDValue | tuple[array_ops.NDValue | tuple, ...]: @named_collections.tree_map_named_collection diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 75244861ad..7008650564 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -31,11 +31,17 @@ errors, utils, ) -from gt4py.next.embedded import context as embedded_context, operators as embedded_operators +from gt4py.next.embedded import ( + array_ops, + context as embedded_context, + operators as embedded_operators, +) from gt4py.next.ffront import ( + fbuiltins, field_operator_ast as foast, foast_to_gtir, past_process_args, + source_utils, stages as ffront_stages, transform_utils, type_info as ffront_type_info, @@ -64,7 +70,13 @@ def program_call_context( enable_jit: bool, kwargs: dict[str, Any], ) -> contextlib.AbstractContextManager: - """Hook called at the beginning and end of a program call.""" + """ + Hook called at the beginning and end of a program call. + + `offset_provider` is passed as the user gave it: its keys may still be dimension classes + (normalization to tags happens later, in the compiled-program pool or before embedded + execution). + """ return ProgramCallMetricsCollector() @@ -79,6 +91,29 @@ def embedded_program_call_context( return metrics.metrics_source_key_setter(f"{program.__name__}<'embedded'>") +def _capture_referenced_dimensions(definition_stage: Any, seen: set[int]) -> None: + """ + Convert (and so capture) the dimensions a definition references beyond its annotations. + + The scan axis, and the source and targets of each `FieldOffset` among the closure variables + of the definition and, recursively, of the field operators it calls -- e.g. a local + dimension no annotation names. Uses the *current* closure variables of each function, not + the (fingerprint-cached) frontend stages. + """ + definition = getattr(definition_stage, "definition", None) + if definition is None or id(definition) in seen: + return + seen.add(id(definition)) + if (axis := (getattr(definition_stage, "attributes", None) or {}).get("axis")) is not None: + common.dimension_ref(axis) # a scan operator's axis + for value in source_utils.get_closure_vars_from_function(definition).values(): + if isinstance(value, fbuiltins.FieldOffset): + common.dimension_ref(value.source) + common.dimension_refs(value.target) + elif (stage := getattr(value, "definition_stage", None)) is not None: + _capture_referenced_dimensions(stage, seen) + + @dataclasses.dataclass(frozen=True) class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): """ @@ -127,6 +162,78 @@ def with_compilation_options( ), ) + @functools.cached_property + def _declared_dimension_classes(self) -> dict[common.DimensionRef, common.Dimension]: + """ + The dimension classes the definition declares, by ref. + + Captured from the very conversions the frontend does (`type_translation.from_type_hint` + of each annotation), so every annotation form is covered by construction, plus the + dimensions referenced beyond annotations (`_capture_referenced_dimensions`). + Computed per program-like *object*, not cached by fingerprint: a redefined class has an + equal fingerprint, and its identity is the point. + """ + definition = getattr(self.definition_stage, "definition", None) + if definition is None: + return {} + with common.capture_dimension_classes() as captured: + try: + hints = typing.get_type_hints(definition) + except Exception: # unresolvable annotations are reported by the frontend + hints = {} + for hint in hints.values(): + try: + type_translation.from_type_hint(hint) + except Exception: # not a translatable annotation: reported by the frontend + continue + _capture_referenced_dimensions(self.definition_stage, seen=set()) + return {ref: cls for ref, cls in reversed(captured)} # first declaration wins + + def _check_dimension_identity( + self, name: str, captured: Sequence[tuple[common.DimensionRef, common.Dimension]] + ) -> None: + """ + Compare the argument dimensions `captured` while translating the arguments (see + `common.capture_dimension_classes`) with the declared ones, by class identity. + + Below the frontend dimensions are `DimensionRef` values, and a dimension redefined with + the same kind (a re-run notebook cell) has an *equal* ref. At a program call the class + is the identity, so an argument built on the previous class is rejected here. + """ + declared = self._declared_dimension_classes + for ref, cls in captured: + if (expected := declared.get(ref)) is not None and expected is not cls: + raise errors.DSLError( + None, + f"Invalid argument types in call to '{name}'.\n" + f"An argument uses dimension '{cls.__qualname__}', and the definition uses" + f" '{expected.__qualname__}': they are two different classes named" + f" '{ref.tag}'. Was the dimension redefined (e.g. a notebook cell re-run)?" + " Re-create the argument, or re-define the program, with the current class.", + ) + + def _capture_argument_dimensions( + self, args: Sequence[Any], kwargs: dict[str, Any], offset_provider: Any + ) -> tuple[ + list[ts.TypeSpec], + dict[str, ts.TypeSpec], + list[tuple[common.DimensionRef, common.Dimension]], + ]: + """Translate the arguments (as the type check does) and capture their dimension classes.""" + with common.capture_dimension_classes() as captured: + arg_types = [type_translation.from_value(arg) for arg in args] + kwarg_types = {k: type_translation.from_value(v) for k, v in kwargs.items()} + for conn in (offset_provider or {}).values(): + # NOTE: duck-typed: `isinstance(conn, common.Connectivity)` is a slow runtime + # protocol check. Domain (incl. a local dimension) and codomain are converted at + # the edge like everything else; a bare dimension is a named Cartesian offset. + if isinstance(conn, common.DimensionMeta): + common.dimension_ref(conn) # type: ignore[arg-type] # a dimension class + elif (codomain := getattr(conn, "codomain", None)) is not None: + common.dimension_ref(codomain) + common.dimension_refs(conn.domain.dims) + return arg_types, kwarg_types, captured + @functools.cached_property def _compiled_programs(self) -> compiled_program.CompiledProgramsPool: # This cached property initializer is only called when JITting the first @@ -367,11 +474,15 @@ def __call__( kwargs=kwargs, ): if __debug__: + arg_types, kwarg_types, captured = self._capture_argument_dimensions( + args, kwargs, offset_provider + ) + # Dimensions are compared by class identity before the type check + # below compares them as (equal-by-value) `DimensionRef`s. + self._check_dimension_identity(self.definition_stage.definition.__name__, captured) # TODO: remove or make dependency on self.past_stage optional past_process_args._validate_args( - self.past_stage.past_node, - arg_types=[type_translation.from_value(arg) for arg in args], - kwarg_types={k: type_translation.from_value(v) for k, v in kwargs.items()}, + self.past_stage.past_node, arg_types=arg_types, kwarg_types=kwarg_types ) if self._has_compiled_backend: @@ -383,6 +494,9 @@ def __call__( self._embedded_runner(*args, offset_provider=offset_provider, **kwargs) else: # Embedded execution. + # NOTE: the compiled path normalizes in `CompiledProgramsPool`, the embedded + # backends in their runner + offset_provider = common.normalize_offset_provider(offset_provider) with embedded_context.update(offset_provider=offset_provider): with embedded_program_call_context(self, args, offset_provider, kwargs): self.definition_stage.definition(*args, **kwargs) @@ -544,6 +658,20 @@ def __gt_closure_vars__(self) -> dict[str, Any]: return self.foast_stage.closure_vars def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> Any: + if __debug__ and not embedded_context.within_valid_context() and self.definition_stage: + # called as a program: see `_check_dimension_identity`. A 0-d array + # is a scalar to embedded execution (e.g. traced by `jax.jit`), has no type spec of + # its own and no dimension, so it is skipped. + *_, captured = self._capture_argument_dimensions( + [arg for arg in args if not array_ops.is_0d_array(arg)], + { + k: v + for k, v in kwargs.items() + if k not in ("offset_provider", "domain") and not array_ops.is_0d_array(v) + }, + kwargs.get("offset_provider"), + ) + self._check_dimension_identity(self.definition_stage.definition.__name__, captured) if not embedded_context.within_valid_context() and self._has_compiled_backend: # non embedded execution offset_provider = {**kwargs.pop("offset_provider", {})} @@ -568,7 +696,9 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> else: if not embedded_context.within_valid_context(): # field_operator as program - kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} + kwargs["offset_provider"] = { + **common.normalize_offset_provider(kwargs.pop("offset_provider", {})) + } if isinstance(self.backend, next_backend.EmbeddedBackend): return self._embedded_runner(*args, **kwargs) attributes = ( @@ -738,7 +868,7 @@ def scan_operator( >>> import gt4py.next as gtx >>> from gt4py.next.iterator import embedded >>> embedded._column_range = 1 # implementation detail - >>> KDim = gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL) + >>> class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... >>> inp = gtx.as_field([KDim], np.ones((10,))) >>> out = gtx.as_field([KDim], np.zeros((10,))) >>> @gtx.scan_operator(axis=KDim, forward=True, init=0.0) diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index c67febaf0a..1edaa8afd5 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -93,7 +93,7 @@ PYTHON_TYPE_BUILTINS = [bool, int, float, tuple] PYTHON_TYPE_BUILTIN_NAMES = [t.__name__ for t in PYTHON_TYPE_BUILTINS] -TYPE_BUILTINS = [ +TYPE_BUILTINS: list[Any] = [ common.Field, common.Dimension, int8, @@ -477,7 +477,7 @@ def __getitem__(self, offset: int) -> common.Connectivity: offset_definition = common.get_offset(current_offset_provider, self.value) assert common.is_neighbor_table(offset_definition) - named_index = common.NamedIndex(self.target[-1], offset) + named_index = (self.target[-1])(offset) connectivity = offset_definition[named_index] return connectivity diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index af63c8d1b4..4707e7a246 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -13,7 +13,7 @@ from gt4py import eve from gt4py.eve import NodeTranslator, NodeVisitor, traits from gt4py.next import common, errors -from gt4py.next.common import Dimension, DimensionKind, promote_dims +from gt4py.next.common import DimensionKind, promote_dims from gt4py.next.ffront import ( dialect_ast_enums, experimental, @@ -42,9 +42,8 @@ def with_altered_scalar_kind( >>> print(with_altered_scalar_kind(scalar_t, ts.ScalarKind.BOOL)) bool - >>> field_t = ts.FieldType( - ... dims=[Dimension(value="I")], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) - ... ) + >>> class I(common.CartesianAxisIndex): ... + >>> field_t = ts.FieldType(dims=[I], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)) >>> print(with_altered_scalar_kind(field_t, ts.ScalarKind.FLOAT32)) Field[[I], float32] """ @@ -175,7 +174,8 @@ class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTransla >>> from gt4py.next import Field >>> from gt4py.next.ffront.source_utils import SourceDefinition, get_closure_vars_from_function >>> from gt4py.next.ffront.func_to_foast import FieldOperatorParser - >>> IDim = Dimension("IDim") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionIndex + >>> class IDim(CartesianAxisIndex): ... >>> def example(a: "Field[[IDim], float]", b: "Field[[IDim], float]"): ... return a + b @@ -482,7 +482,7 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> foast.Subscri " choose one." ) ], - hints=[f"Write the displacement directly, e.g. '{source.value} + 1'."], + hints=[f"Write the displacement directly, e.g. '{source.qualname} + 1'."], ) new_type = new_value.type case ts.FieldType(dims=dims, dtype=dtype): @@ -697,6 +697,18 @@ def _deduce_binop_type( and type_info.is_arithmetic(right.type) ): # e.g. `IDim+1` or `IDim+0.5` + if not common.is_cartesian_axis(left.type.dim): + raise errors.DSLError( + left.location, + f"'{left.type.dim.qualname}' is not a Cartesian axis, so it has no index " + f"arithmetic and '{node.op}' cannot shift along it.", + hints=[ + ( + "Declare a Cartesian axis as 'class IDim(gtx.CartesianAxisIndex): ...';" + " shift along a mesh location with a connectivity instead." + ) + ], + ) if not isinstance(right, foast.Constant): raise errors.DSLError( right.location, @@ -710,7 +722,7 @@ def _deduce_binop_type( raise errors.DSLError( right.location, f"Invalid offset '{right.value}' for a Cartesian shift of dimension " - f"'{left.type.dim.value}'.", + f"'{left.type.dim.qualname}'.", hints=[ ( "Use an integer offset to shift within the dimension, or a half-integer " @@ -718,8 +730,8 @@ def _deduce_binop_type( ) ], ) - conn = common.connectivity_for_cartesian_shift(left.type.dim, offset_index) - return ts.OffsetType(source=conn.codomain, target=(conn.domain_dim,)) + _, codomain = common.cartesian_shift(left.type.dim, offset_index) + return ts.OffsetType(source=codomain, target=(left.type.dim,)) else: raise errors.DSLError(node.location, err_msg) @@ -989,12 +1001,12 @@ def _visit_as_offset(self, node: foast.Call, **kwargs: Any) -> foast.Call: assert isinstance(arg_0, ts.OffsetType) assert isinstance(arg_1, ts.FieldType) if not fbuiltins.is_cartesian_offset(arg_0): - target_dims = ", ".join(d.value for d in arg_0.target) + target_dims = ", ".join(d.qualname for d in arg_0.target) # for the diagnostic raise errors.DSLError( node.location, f"'as_offset' is only supported for Cartesian offsets " f"(single target dimension equal to source dimension); " - f"got source '{arg_0.source.value}' and target ({target_dims}).", + f"got source '{arg_0.source.qualname}' and target ({target_dims}).", ) if not type_info.is_integral(arg_1): raise errors.DSLError( @@ -1019,7 +1031,7 @@ def _visit_as_offset(self, node: foast.Call, **kwargs: Any) -> foast.Call: def _deduce_where_return_type( self, func_name: str, - cond_dims: Sequence[Dimension], + cond_dims: Sequence[common.DimensionRef], true_branch: ts.FieldType | ts.TupleType | ts.NamedCollectionType, false_branch: ts.FieldType | ts.TupleType | ts.NamedCollectionType, location: eve.SourceLocation, diff --git a/src/gt4py/next/ffront/foast_pretty_printer.py b/src/gt4py/next/ffront/foast_pretty_printer.py index 8b2e369501..06b4d6b228 100644 --- a/src/gt4py/next/ffront/foast_pretty_printer.py +++ b/src/gt4py/next/ffront/foast_pretty_printer.py @@ -238,7 +238,8 @@ def pretty_format(node: foast.LocatedNode) -> str: Pretty print (to string) an `foast.LocatedNode`. >>> from gt4py.next import Field, Dimension, field_operator, float64 - >>> IDim = Dimension("IDim") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionIndex + >>> class IDim(CartesianAxisIndex): ... >>> @field_operator ... def field_op(a: Field[[IDim], float64]) -> Field[[IDim], float64]: ... return a + 1.0 diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 64fb5daba2..bd978246b5 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -80,7 +80,8 @@ class FieldOperatorLowering(eve.PreserveLocationVisitor, eve.NodeTranslator): >>> from gt4py.next.ffront.func_to_foast import FieldOperatorParser >>> from gt4py.next import Field, Dimension, float64 >>> - >>> IDim = Dimension("IDim") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionIndex + >>> class IDim(CartesianAxisIndex): ... >>> def fieldop(inp: Field[[IDim], "float64"]): ... return inp >>> @@ -230,12 +231,12 @@ def visit_Symbol(self, node: foast.Symbol, **kwargs: Any) -> itir.Sym: def visit_Name(self, node: foast.Name, **kwargs: Any) -> itir.SymRef | itir.AxisLiteral: if isinstance(node.type, ts.DimensionType): - return itir.AxisLiteral(value=node.type.dim.value, kind=node.type.dim.kind) + return itir.AxisLiteral(dim=node.type.dim) return im.ref(node.id) def visit_Attribute(self, node: foast.Attribute, **kwargs: Any) -> itir.AxisLiteral: if isinstance(node.type, ts.DimensionType): - return itir.AxisLiteral(value=node.type.dim.value, kind=node.type.dim.kind) + return itir.AxisLiteral(dim=node.type.dim) if isinstance(named_tup_type := node.value.type, ts.NamedCollectionType): ind = named_tup_type.keys.index(node.attr) @@ -310,18 +311,16 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr: # `field(Dim + idx)` (where `idx` is integer or half 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)), + left=foast.LocatedNode(type=ts.DimensionType(dim=common.DimensionRef() as dim)), right=foast.Constant(value=offset_index), ): if arg.op == dialect_ast_enums.BinaryOperator.SUB: offset_index *= -1 - conn = common.connectivity_for_cartesian_shift(dim, offset_index) + shift_offset, codomain = common.cartesian_shift(dim, offset_index) current_expr = im.as_fieldop( im.lambda_("__it")( im.deref( - im.shift( - im.cartesian_offset(conn.domain_dim, conn.codomain), conn.offset - )("__it") + im.shift(im.cartesian_offset(dim, codomain), shift_offset)("__it") ) ) )(current_expr) diff --git a/src/gt4py/next/ffront/foast_to_past.py b/src/gt4py/next/ffront/foast_to_past.py index 5faa7aba2a..ce0412496b 100644 --- a/src/gt4py/next/ffront/foast_to_past.py +++ b/src/gt4py/next/ffront/foast_to_past.py @@ -63,7 +63,7 @@ class OperatorToProgram(workflow.Workflow[ConcreteFOASTOperatorDef, ConcretePAST Example: >>> from gt4py import next as gtx >>> from gt4py.next.otf import arguments, workflow - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> @gtx.field_operator ... def copy(a: gtx.Field[[IDim], gtx.float32]) -> gtx.Field[[IDim], gtx.float32]: diff --git a/src/gt4py/next/ffront/func_to_foast.py b/src/gt4py/next/ffront/func_to_foast.py index 14dceb25d1..66ad238639 100644 --- a/src/gt4py/next/ffront/func_to_foast.py +++ b/src/gt4py/next/ffront/func_to_foast.py @@ -53,7 +53,7 @@ def func_to_foast(inp: DSLFieldOperatorDef) -> FOASTOperatorDef: Examples: >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> const = gtx.float32(2.0) >>> def dsl_operator(a: gtx.Field[[IDim], gtx.float32]) -> gtx.Field[[IDim], gtx.float32]: @@ -140,7 +140,8 @@ class FieldOperatorParser(DialectParser[foast.FunctionDefinition]): >>> from gt4py.next import Field, Dimension >>> float64 = float - >>> IDim = Dimension("IDim") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionIndex + >>> class IDim(CartesianAxisIndex): ... >>> def field_op(inp: Field[[IDim], float64]): ... return inp >>> foast_tree = FieldOperatorParser.apply_to_function(field_op) diff --git a/src/gt4py/next/ffront/func_to_past.py b/src/gt4py/next/ffront/func_to_past.py index 9915456bfe..6b94ff794d 100644 --- a/src/gt4py/next/ffront/func_to_past.py +++ b/src/gt4py/next/ffront/func_to_past.py @@ -44,7 +44,7 @@ def func_to_past(inp: DSLProgramDef) -> PASTProgramDef: Examples: >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> @gtx.field_operator ... def copy(a: gtx.Field[[IDim], gtx.float32]) -> gtx.Field[[IDim], gtx.float32]: diff --git a/src/gt4py/next/ffront/past_process_args.py b/src/gt4py/next/ffront/past_process_args.py index 13da6915d0..db94bff959 100644 --- a/src/gt4py/next/ffront/past_process_args.py +++ b/src/gt4py/next/ffront/past_process_args.py @@ -79,7 +79,7 @@ def _process_args( def _field_constituents_range_and_dims( arg: Any, # TODO(havogt): improve typing arg_type: ts.DataType, -) -> Iterator[tuple[tuple[tuple[int, int], ...], list[common.Dimension]]]: +) -> Iterator[tuple[tuple[tuple[int, int], ...], list[common.DimensionRef]]]: match arg_type: case ts.TupleType(): for el, el_type in zip(arg, arg_type.types): diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index 79854bf170..a7fc028053 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -27,7 +27,7 @@ ) from gt4py.next.ffront.stages import ConcretePASTProgramDef from gt4py.next.iterator import ir as itir -from gt4py.next.iterator.ir_utils import ir_makers as im +from gt4py.next.iterator.ir_utils import ir_makers as im, misc as ir_misc from gt4py.next.iterator.transforms import remap_symbols, replace_get_domain_range_with_constants from gt4py.next.otf import arguments, stages, workflow from gt4py.next.type_system import type_info, type_specifications as ts @@ -40,7 +40,7 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: Example: >>> from gt4py import next as gtx >>> from gt4py.next.otf import arguments, workflow - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> @gtx.field_operator ... def copy(a: gtx.Field[[IDim], gtx.float32]) -> gtx.Field[[IDim], gtx.float32]: @@ -71,7 +71,7 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: """ all_closure_vars = transform_utils._get_closure_vars_recursively(inp.data.closure_vars) offsets_and_dimensions = transform_utils._filter_closure_vars_by_type( - all_closure_vars, fbuiltins.FieldOffset, common.Dimension + all_closure_vars, fbuiltins.FieldOffset, common.DimensionMeta ) grid_type = transform_utils._deduce_grid_type( inp.data.grid_type, offsets_and_dimensions.values() @@ -136,6 +136,9 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: } compile_time_args = dataclasses.replace(inp.args, args=args, kwargs=kwargs) + # Two different dimensions spelled with one tag would collide on every generated name. + ir_misc.check_program_dimension_refs(itir_program, compile_time_args.offset_provider_type) + if config.DEBUG or inp.data.debug: devtools.debug(itir_program) @@ -214,7 +217,8 @@ class ProgramLowering( >>> from gt4py.next import Dimension, Field >>> >>> float64 = float - >>> IDim = Dimension("IDim") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionIndex + >>> class IDim(CartesianAxisIndex): ... >>> >>> def fieldop(inp: Field[[IDim], "float64"]) -> Field[[IDim], "float64"]: ... >>> def program(inp: Field[[IDim], "float64"], out: Field[[IDim], "float64"]): @@ -349,9 +353,7 @@ def _construct_itir_domain_arg( domain_args = [] for dim_i, dim in enumerate(out_type.dims): # an expression for the range of a dimension - dim_range = im.call("get_domain_range")( - out_expr, itir.AxisLiteral(value=dim.value, kind=dim.kind) - ) + dim_range = im.call("get_domain_range")(out_expr, itir.AxisLiteral(dim=dim)) dim_start, dim_stop = im.tuple_get(0, dim_range), im.tuple_get(1, dim_range) # bounds @@ -375,11 +377,11 @@ def _construct_itir_domain_arg( ) if dim.kind == common.DimensionKind.LOCAL: - raise ValueError(f"common.Dimension '{dim.value}' must not be local.") + raise ValueError(f"common.DimensionRef '{dim.qualname}' must not be local.") domain_args.append( itir.FunCall( fun=itir.SymRef(id="named_range"), - args=[itir.AxisLiteral(value=dim.value, kind=dim.kind), lower, upper], + args=[itir.AxisLiteral(dim=dim), lower, upper], ) ) @@ -397,7 +399,7 @@ def _construct_itir_domain_arg( ) def _construct_itir_initialized_domain_arg( - self, dim_i: int, dim: common.Dimension, node_domain: past.Dict + self, dim_i: int, dim: common.DimensionRef, node_domain: past.Dict ) -> list[itir.FunCall]: assert len(node_domain.values_[dim_i].elts) == 2 keys_dims_types = cast(ts.DimensionType, node_domain.keys_[dim_i].type).dim diff --git a/src/gt4py/next/ffront/transform_utils.py b/src/gt4py/next/ffront/transform_utils.py index cac74ae88b..09c9d4b9ee 100644 --- a/src/gt4py/next/ffront/transform_utils.py +++ b/src/gt4py/next/ffront/transform_utils.py @@ -62,7 +62,7 @@ def _deduce_grid_type( if isinstance(o, fbuiltins.FieldOffset) and not fbuiltins.is_cartesian_offset(o): deduced_grid_type = common.GridType.UNSTRUCTURED break - if isinstance(o, common.Dimension) and o.kind == common.DimensionKind.LOCAL: + if isinstance(o, common.DimensionMeta) and o.kind == common.DimensionKind.LOCAL: deduced_grid_type = common.GridType.UNSTRUCTURED break diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index aa906d543b..8217880d0f 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -8,7 +8,7 @@ import functools import inspect from collections.abc import Callable, Iterable -from typing import Any, Iterator, Optional, Sequence, cast +from typing import Any, Final, Iterator, Optional, Sequence, cast import gt4py.next.ffront.type_specifications as ts_ffront import gt4py.next.type_system.type_specifications as ts @@ -193,6 +193,19 @@ def _tree_map_type_constructor_drop_python_type( return result +class _UnknownDim(common.DimensionIndex): + """ + Placeholder for a dimension that cannot be determined, shown only in a diagnostic. + + Displays as `...` so the resulting error reads `Field[[...], ]`. It is never lowered + or resolved, so the unimportable qualname this gives its `tag` is harmless. + """ + + +_UnknownDim.__qualname__ = "..." +_UNKNOWN_DIM: Final = _UnknownDim + + def _scan_param_promotion( param: ts.TypeSpec, arg: ts.TypeSpec ) -> ts.FieldType | ts.TupleType | ts.NamedCollectionType: @@ -205,13 +218,12 @@ def _scan_param_promotion( Example: -------- + >>> class I(common.CartesianAxisIndex): ... >>> _scan_param_promotion( ... ts.ScalarType(kind=ts.ScalarKind.INT64), - ... ts.FieldType( - ... dims=[common.Dimension("I")], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) - ... ), + ... ts.FieldType(dims=[I], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)), ... ) - FieldType(dims=[Dimension(value='I', kind=)], dtype=ScalarType(kind=, shape=None)) + FieldType(dims=[DimensionRef(gt4py.next.ffront.type_info:I, horizontal, cartesian_axis)], dtype=ScalarType(kind=, shape=None)) """ def _as_field(dtype: ts.TypeSpec, path: tuple[int, ...]) -> ts.FieldType: @@ -228,7 +240,7 @@ def _as_field(dtype: ts.TypeSpec, path: tuple[int, ...]) -> ts.FieldType: # argument type differ. As such we can not extract the dimensions # and just return a generic field shown in the error later on. # TODO: we want some generic field type here, but our type system does not support it yet. - return ts.FieldType(dims=[common.Dimension("...")], dtype=dtype) + return ts.FieldType(dims=[_UNKNOWN_DIM], dtype=dtype) # Note: In the promotion of the scalar type to field type we drop the information about # the original python type in NamedCollections as we want to be able to express compatibility diff --git a/src/gt4py/next/ffront/type_specifications.py b/src/gt4py/next/ffront/type_specifications.py index b5ef19befd..4e87877984 100644 --- a/src/gt4py/next/ffront/type_specifications.py +++ b/src/gt4py/next/ffront/type_specifications.py @@ -20,5 +20,5 @@ class FieldOperatorType(ts.CallableType): class ScanOperatorType(ts.CallableType): - axis: common.Dimension + axis: common.DimensionRef = ts.dimension_field() definition: ts.FunctionType diff --git a/src/gt4py/next/field_utils.py b/src/gt4py/next/field_utils.py index f81d5b09dd..2061d278b1 100644 --- a/src/gt4py/next/field_utils.py +++ b/src/gt4py/next/field_utils.py @@ -41,8 +41,9 @@ def field_from_typespec( The tuple structure and dtype is taken from a type_specifications.DataType, which is either ScalarType or a CollectionTypeSpec of ScalarType (possibly nested). + >>> class I(common.CartesianAxisIndex): ... >>> field_from_typespec( - ... ts.ScalarType(kind=ts.ScalarKind.INT32), common.domain({common.Dimension("I"): 1}) + ... ts.ScalarType(kind=ts.ScalarKind.INT32), common.domain({I: 1}) ... ) # doctest: +ELLIPSIS NdArrayField(... dtype=int32...) >>> field_from_typespec( @@ -52,7 +53,7 @@ def field_from_typespec( ... ts.ScalarType(kind=ts.ScalarKind.FLOAT32), ... ] ... ), - ... common.domain({common.Dimension("I"): 1}), + ... common.domain({I: 1}), ... ) # doctest: +ELLIPSIS (NdArrayField(... dtype=int32...), NdArrayField(... dtype=float32...)) """ diff --git a/src/gt4py/next/fingerprinting.py b/src/gt4py/next/fingerprinting.py index f0739a102b..0fcc57d633 100644 --- a/src/gt4py/next/fingerprinting.py +++ b/src/gt4py/next/fingerprinting.py @@ -49,13 +49,13 @@ import sys import types from collections.abc import Callable, Collection, Iterable, Iterator, Mapping -from typing import Any, Final, Optional, TypeAlias, TypeVar +from typing import Any, Final, Optional, TypeAlias, TypeVar, cast from unittest import mock import xxhash from gt4py.eve import concepts, datamodels, utils as eve_utils -from gt4py.next import utils as next_utils +from gt4py.next import common, utils as next_utils _T = TypeVar("_T") @@ -222,6 +222,16 @@ def _instance_state(obj: Any) -> tuple[Any, ...]: *((member.name, member.value) for member in obj), state=b"enum_class\0" + eve_utils.get_fully_qualified_name(obj).encode(), ), + # A parametrized dimension such as `Staggered[K]` has no importable qualified name (its + # `__qualname__` contains brackets), so the by-reference `type` deconstruction rejects it. + # It is fully determined by its base dimension, which *is* importable -- the same reduction + # its `copyreg` registration in `common.dimensions` uses. The bare `Staggered` base is an + # ordinary class. + common.StaggeredMeta: lambda obj: ( + Deconstruction.from_pieces(obj.base, state=b"staggered_dimension") + if "base" in obj.__dict__ + else EmptyDeconstruction.from_reference(obj) + ), type(None): lambda obj: EmptyDeconstruction.from_typed_value(type(None)), bool: lambda obj: EmptyDeconstruction.from_typed_value(bool, b"1" if obj else b"0"), int: lambda obj: EmptyDeconstruction.from_typed_value(type(obj), str(int(obj)).encode()), @@ -326,8 +336,21 @@ def object_deconstruct_fallback(obj: Any) -> Deconstruction: ) +def _dimension_deconstruction(obj: common.DimensionMeta, *, strict: bool = True) -> Deconstruction: + # NOTE: by reference, like any class, plus its ref, which has the declared `kind` and whether + # it is a Cartesian axis. They decide a field's layout order (`order_dimensions`), the scan axis and whether there is + # index arithmetic, so a dimension redefined under the same name with another one (a re-run + # notebook cell) must not reuse cached stages or artifacts. A staggered dimension goes through + # its base (see above), so it inherits this. See ADR 0030. + reference = Deconstruction.from_reference(obj, strict=strict).state + return Deconstruction.from_pieces( + common.dimension_ref(cast(common.Dimension, obj)), state=b"dimension\0" + reference + ) + + #: Strict deconstructors map used by `strict_fingerprinter` STRICT_DECONSTRUCTORS: Final[dict[type, Deconstructor]] = _COMMON_DECONSTRUCTORS | { + common.DimensionMeta: _dimension_deconstruction, type: EmptyDeconstruction.from_reference, types.FunctionType: EmptyDeconstruction.from_reference, types.BuiltinFunctionType: EmptyDeconstruction.from_reference, @@ -387,6 +410,7 @@ def _lenient_function_deconstruction(func: types.FunctionType) -> Deconstruction #: Tolerant deconstructors map used by `lenient_fingerprinter` LENIENT_DECONSTRUCTORS: Final[dict[type, Deconstructor]] = { + common.DimensionMeta: functools.partial(_dimension_deconstruction, strict=False), types.FunctionType: _lenient_function_deconstruction, types.BuiltinFunctionType: _lenient_reference, types.ModuleType: _lenient_reference, diff --git a/src/gt4py/next/iterator/builtins.py b/src/gt4py/next/iterator/builtins.py index d222f100df..db5c233e84 100644 --- a/src/gt4py/next/iterator/builtins.py +++ b/src/gt4py/next/iterator/builtins.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +from gt4py.next import common from gt4py.next.iterator.dispatcher import Dispatcher @@ -67,6 +68,17 @@ def map_tuple(*args): raise BackendNotSelectedError() +class ConstList(common.DimensionIndex, kind=common.DimensionKind.LOCAL): + """ + The local dimension of a list of one repeated value (`make_const_list`). + + The value is broadcast against the neighbor lists it is combined with, and a materialized + constant list has extent 1 along it. It indexes no table, so it is never in an offset provider. + """ + + __slots__ = () + + @builtin_dispatch def make_const_list(*args): raise BackendNotSelectedError() diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 1a84a488a8..8b9bb53ca1 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -122,8 +122,8 @@ def __gt_origin__(self) -> typing.Never: def __gt_type__(self) -> common.NeighborConnectivityType: return common.NeighborConnectivityType( - domain=self.domain_dims, - codomain=self.codomain_dim, + domain=tuple(common.dimension_refs(self.domain_dims)), + codomain=common.dimension_ref(self.codomain_dim), max_neighbors=self._max_neighbors, skip_value=self.skip_value, dtype=self.dtype, @@ -175,7 +175,7 @@ def __call__( __getitem__ = restrict # type: ignore[assignment] - def _inverse_image(self, image_range: common.UnitRange) -> Sequence[common.NamedRange]: + def _inverse_image(self, image_range: common.UnitRange) -> Sequence[common.DimensionRange]: raise NotImplementedError @property @@ -209,12 +209,6 @@ def skip_value( NamedFieldIndices: TypeAlias = Mapping[Tag, FieldIndex | SparsePositionEntry] -# Magic local dimension for the result of a `make_const_list`. -# A clean implementation will probably involve to tag the `make_const_list` -# with the neighborhood it is meant to be used with. -_CONST_DIM = common.Dimension(value="_CONST_DIM", kind=common.DimensionKind.LOCAL) - - @runtime_checkable class ItIterator(Protocol): """ @@ -383,16 +377,16 @@ def deref(self): return impl -NamedRange: TypeAlias = tuple[Tag | common.Dimension, range] +TaggedRange: TypeAlias = tuple[Tag | common.Dimension, range] @builtins.cartesian_domain.register(EMBEDDED) -def cartesian_domain(*args: NamedRange) -> runtime.CartesianDomain: +def cartesian_domain(*args: TaggedRange) -> runtime.CartesianDomain: return runtime.CartesianDomain(args) @builtins.unstructured_domain.register(EMBEDDED) -def unstructured_domain(*args: NamedRange) -> runtime.UnstructuredDomain: +def unstructured_domain(*args: TaggedRange) -> runtime.UnstructuredDomain: return runtime.UnstructuredDomain(args) @@ -402,7 +396,7 @@ def unstructured_domain(*args: NamedRange) -> runtime.UnstructuredDomain: @builtins.named_range.register(EMBEDDED) -def named_range(tag: Tag | common.Dimension, start: int, end: int) -> NamedRange: +def named_range(tag: Tag | common.Dimension, start: int, end: int) -> TaggedRange: # TODO revisit this pattern after the discussion of 0d-field vs scalar if isinstance(start, ConstantField): start = start.value @@ -502,13 +496,13 @@ def execute_shift( for i, p in reversed(list(enumerate(new_entry))): # first shift applies to the last sparse dimensions of that axis type if p is None: - if tag == _CONST_DIM.value: + if tag == builtins.ConstList.tag: new_entry[i] = 0 else: offset_implementation = common.get_offset(offset_provider, tag) assert common.is_neighbor_table(offset_implementation) source_dim = offset_implementation.__gt_type__().source_dim - cur_index = pos[source_dim.value] + cur_index = pos[source_dim.tag] assert common.is_int_index(cur_index) if offset_implementation[cur_index, index].as_scalar() in [ None, @@ -523,17 +517,17 @@ def execute_shift( if isinstance(tag, common.CartesianConnectivity): new_pos = copy.copy(pos) - value = new_pos.pop(tag.domain_dim.value) + value = new_pos.pop(tag.domain_dim.tag) assert common.is_int_index(value) - new_pos[tag.codomain.value] = value + index + tag.offset + new_pos[tag.codomain.tag] = value + index + tag.offset return new_pos offset_implementation = common.get_offset(offset_provider, tag) if common.is_neighbor_table(offset_implementation): source_dim = offset_implementation.__gt_type__().source_dim - assert source_dim.value in pos + assert source_dim.tag in pos new_pos = pos.copy() - new_pos.pop(source_dim.value) - cur_index = pos[source_dim.value] + new_pos.pop(source_dim.tag) + cur_index = pos[source_dim.tag] assert common.is_int_index(cur_index) if offset_implementation[cur_index, index].as_scalar() in [ None, @@ -543,7 +537,7 @@ def execute_shift( else: new_index = offset_implementation[cur_index, index].as_scalar() assert new_index is not None - new_pos[offset_implementation.codomain.value] = int(new_index) + new_pos[offset_implementation.codomain.tag] = int(new_index) return new_pos @@ -666,15 +660,15 @@ def _get_axes( In case all arguments are zero-dimensional return an empty sequence. >>> from gt4py import next as gtx - >>> IDim = gtx.Dimension("I") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> i_field: LocatedField = _wrap_field( ... gtx.empty({IDim: range(3, 10)}, allocator=gtx.itir_python) ... ) - >>> _get_axes((i_field, i_field)) - (Dimension(value='I', kind=),) + >>> _get_axes((i_field, i_field)) == (IDim,) + True - >>> JDim = gtx.Dimension("J") + >>> class JDim(gtx.CartesianAxisIndex): ... >>> j_field: LocatedField = _wrap_field( ... gtx.empty({JDim: range(3, 10)}, allocator=gtx.itir_python) ... ) @@ -689,8 +683,8 @@ def _get_axes( ... ValueError: Fields are defined on different axes. - >>> _get_axes((i_field, zero_dim_field), ignore_zero_dims=True) - (Dimension(value='I', kind=),) + >>> _get_axes((i_field, zero_dim_field), ignore_zero_dims=True) == (IDim,) + True """ if isinstance(field_or_tuple, tuple): els_axes = [] @@ -765,7 +759,7 @@ def _make_tuple( except embedded_exceptions.IndexOutOfBounds: return _UNDEFINED else: - column_range = _get_column_range().unit_range + column_range = _get_column_range().value assert column_range is not None col: list[ @@ -832,7 +826,7 @@ def deref(self) -> Any: axes = _get_axes(self.field, ignore_zero_dims=True) if __debug__: - if not all(axis.value in shifted_pos.keys() for axis in axes if axis is not None): + if not all(axis.tag in shifted_pos.keys() for axis in axes if axis is not None): raise IndexError("Iterator position doesn't point to valid location for its field.") slice_column = dict[Tag, range]() if self.column_axis is not None: @@ -842,7 +836,7 @@ def deref(self) -> Any: assert isinstance(k_pos, int) # the following range describes a range in the field # (negative values are relative to the origin, not relative to the size) - slice_column[self.column_axis] = range(k_pos, k_pos + len(column_range.unit_range)) + slice_column[self.column_axis] = range(k_pos, k_pos + len(column_range.value)) assert _is_concrete_position(shifted_pos) position = {**shifted_pos, **slice_column} @@ -853,7 +847,7 @@ def _get_sparse_dimensions(axes: Sequence[common.Dimension]) -> list[common.Dime return [ axis for axis in axes - if isinstance(axis, common.Dimension) and axis.kind == common.DimensionKind.LOCAL + if isinstance(axis, common.DimensionMeta) and axis.kind == common.DimensionKind.LOCAL ] @@ -874,18 +868,18 @@ def make_in_iterator( new_pos: Position = pos.copy() for sparse_dim in set(sparse_dimensions): init = [None] * sparse_dimensions.count(sparse_dim) - new_pos[sparse_dim.value] = init # type: ignore[assignment] # looks like mypy is confused + new_pos[sparse_dim.tag] = init # type: ignore[assignment] # looks like mypy is confused if column_dimension is not None: - column_range = _get_column_range().unit_range + column_range = _get_column_range().value # if we deal with column stencil the column position is just an offset by which the whole column needs to be shifted assert column_range is not None - new_pos[column_dimension.value] = column_range.start + new_pos[column_dimension.tag] = column_range.start it = MDIterator( - inp, new_pos, column_axis=column_dimension.value if column_dimension is not None else None + inp, new_pos, column_axis=column_dimension.tag if column_dimension is not None else None ) if len(sparse_dimensions) >= 1: if len(sparse_dimensions) == 1: - return SparseListIterator(it, sparse_dimensions[0].value) + return SparseListIterator(it, sparse_dimensions[0].tag) else: raise NotImplementedError( f"More than one local dimension is currently not supported, got {sparse_dimensions}." @@ -909,23 +903,23 @@ def dims(self) -> tuple[common.Dimension, ...]: def _translate_named_indices( self, _named_indices: NamedFieldIndices - ) -> common.AbsoluteIndexSequence: + ) -> common.CanonicalAbsoluteIndexSequence: named_indices: Mapping[common.Dimension, FieldIndex | SparsePositionEntry] = { - d: _named_indices[d.value] for d in self._ndarrayfield.__gt_domain__.dims + d: _named_indices[d.tag] for d in self._ndarrayfield.__gt_domain__.dims } - domain_slice: list[common.NamedRange | common.NamedIndex] = [] + domain_slice: list[common.DimensionRange | common.DimensionIndex] = [] for d, v in named_indices.items(): if isinstance(v, range): - domain_slice.append(common.NamedRange(d, common.UnitRange(v.start, v.stop))) + domain_slice.append(common.DimensionRange(d, common.UnitRange(v.start, v.stop))) elif isinstance(v, list): assert len(v) == 1 # only 1 sparse dimension is supported assert common.is_int_index( v[0] ) # derefing a concrete element in a sparse field, not a slice - domain_slice.append(common.NamedIndex(d, v[0])) + domain_slice.append(d(v[0])) else: assert common.is_int_index(v) - domain_slice.append(common.NamedIndex(d, v)) + domain_slice.append(d(v)) return tuple(domain_slice) def field_getitem(self, named_indices: NamedFieldIndices) -> Any: @@ -940,7 +934,7 @@ def field_setitem(self, named_indices: NamedFieldIndices, value: Any): ] = v elif isinstance(value, _ConstList): self._ndarrayfield[ - self._translate_named_indices({**named_indices, _CONST_DIM.value: 0}) + self._translate_named_indices({**named_indices, builtins.ConstList.tag: 0}) ] = value.value else: self._ndarrayfield[self._translate_named_indices(named_indices)] = value @@ -953,7 +947,7 @@ def __gt_origin__(self) -> tuple[int, ...]: def _is_field_axis(axis: Axis) -> TypeGuard[FieldAxis]: - return isinstance(axis, FieldAxis) + return isinstance(axis, common.DimensionMeta) def _is_tuple_axis(axis: Axis) -> TypeGuard[TupleAxis]: @@ -974,13 +968,13 @@ def get_ordered_indices(axes: Iterable[Axis], pos: NamedFieldIndices) -> tuple[F res.append(slice(None)) else: assert _is_field_axis(axis) - assert axis.value in pos - assert isinstance(axis.value, str) - elem = pos[axis.value] + assert axis.tag in pos + assert isinstance(axis.tag, str) + elem = pos[axis.tag] if _is_sparse_position_entry(elem): - sparse_position_tracker.setdefault(axis.value, 0) - res.append(elem[sparse_position_tracker[axis.value]]) - sparse_position_tracker[axis.value] += 1 + sparse_position_tracker.setdefault(axis.tag, 0) + res.append(elem[sparse_position_tracker[axis.tag]]) + sparse_position_tracker[axis.tag] += 1 else: assert isinstance(elem, (int, np.integer, slice, range)) res.append(elem) @@ -1055,7 +1049,9 @@ def __gt_builtin_func__(func: Callable, /) -> NoReturn: # type: ignore[override @property def domain(self) -> common.Domain: if self._cur_index is None: - return common.Domain(common.NamedRange(self._dimension, common.UnitRange.infinite())) + return common.Domain( + common.DimensionRange(self._dimension, common.UnitRange.infinite()) + ) else: return common.Domain() @@ -1091,10 +1087,12 @@ def premap( raise NotImplementedError() def restrict(self, item: common.AnyIndexSpec) -> Self: - if isinstance(item, Sequence) and all(isinstance(e, common.NamedIndex) for e in item): + if isinstance(item, Sequence) and all(isinstance(e, common.DimensionIndex) for e in item): assert len(item) == 1 - assert isinstance(item[0], common.NamedIndex) # for mypy errors on multiple lines below - d, r = item[0] + assert isinstance( + item[0], common.DimensionIndex + ) # for mypy errors on multiple lines below + d, r = item[0].dim, item[0].value assert d == self._dimension assert isinstance(r, core_defs.INTEGRAL_TYPES) # TODO(tehrengruber): Use a regular zero dimensional field instead. @@ -1362,7 +1360,7 @@ def __gt_type__(self) -> ts.ListType: assert isinstance(element_type, ts.DataType) return ts.ListType( element_type=element_type, - offset_type=_CONST_DIM, + offset_type=builtins.ConstList, ) @@ -1444,7 +1442,7 @@ class SparseListIterator: offsets: Sequence[OffsetPart] = dataclasses.field(default_factory=list, kw_only=True) def deref(self) -> Any: - if self.list_offset == _CONST_DIM.value: + if self.list_offset == builtins.ConstList.tag: return _ConstList( value=self.it.shift(*self.offsets, SparseTag(self.list_offset), 0).deref() ) @@ -1574,7 +1572,7 @@ class _Scan: axis: common.Dimension def __call__(self, *iters: ItIterator) -> Column: - column_range = _get_column_range().unit_range + column_range = _get_column_range().value sorted_column_range = column_range if self.is_forward else reversed(column_range) state = self.init col = Column(column_range.start, np.zeros(len(column_range), dtype=_elem_dtype(self.init))) @@ -1593,7 +1591,7 @@ def scan(scan_pass: Callable, is_forward: bool, init: Any, axis: common.Dimensio def _dimension_to_tag( domain: runtime.CartesianDomain | runtime.UnstructuredDomain, ) -> dict[Tag, range]: - return {k.value: v for k, v in domain.items()} + return {k.tag: v for k, v in domain.items()} def _validate_domain(domain: Domain, offset_provider_type: common.OffsetProviderType) -> None: @@ -1616,7 +1614,7 @@ def set_at( @runtime.get_domain_range.register(EMBEDDED) def get_domain_range(field: common.Field, dim: common.Dimension) -> tuple[int, int]: - return (field.domain[dim].unit_range.start, field.domain[dim].unit_range.stop) + return (field.domain[dim].value.start, field.domain[dim].value.stop) @runtime.if_stmt.register(EMBEDDED) @@ -1666,22 +1664,22 @@ def _compute_at_position( def _extract_column_range( domain: dict[Tag, range], sten: Callable -) -> common.NamedRange | eve.NothingType: - if isinstance(sten, _Scan) and (column_axis := sten.axis).value in domain: - return common.NamedRange( +) -> common.DimensionRange | eve.NothingType: + if isinstance(sten, _Scan) and (column_axis := sten.axis).tag in domain: + return common.DimensionRange( column_axis, - common.UnitRange(domain[column_axis.value].start, domain[column_axis.value].stop), + common.UnitRange(domain[column_axis.tag].start, domain[column_axis.tag].stop), ) return eve.NOTHING def _as_column_ranges( - column_range: common.NamedRange | eve.NothingType, -) -> tuple[common.NamedRange] | eve.NothingType: - return (column_range,) if isinstance(column_range, common.NamedRange) else eve.NOTHING + column_range: common.DimensionRange | eve.NothingType, +) -> tuple[common.DimensionRange] | eve.NothingType: + return (column_range,) if isinstance(column_range, common.DimensionRange) else eve.NOTHING -def _get_column_range() -> common.NamedRange: +def _get_column_range() -> common.DimensionRange: (column_range,) = embedded_context.get_column_ranges() return column_range @@ -1695,9 +1693,9 @@ def _get_output_type( col_range = _extract_column_range(domain, fun) col_dim: Optional[common.Dimension] = None - if isinstance(col_range, common.NamedRange): + if isinstance(col_range, common.DimensionRange): col_dim = col_range.dim - del domain[col_range.dim.value] + del domain[col_range.dim.tag] # determine dtype by computing result at one point pos_in_domain = next(iter(_domain_iterator(domain))) @@ -1712,19 +1710,23 @@ def _fieldspec_list_to_value( ) -> tuple[common.Domain, ts.TypeSpec]: """Translate the list element type into the domain.""" if isinstance(type_, ts.ListType): - if type_.offset_type == _CONST_DIM: + if type_.offset_type == common.dimension_ref(builtins.ConstList): return domain.insert( - len(domain), common.named_range((_CONST_DIM, 1)) + len(domain), common.dimension_range((builtins.ConstList, 1)) ), type_.element_type else: offset_provider = embedded_context.get_offset_provider() offset_type = type_.offset_type - assert isinstance(offset_type, common.Dimension) - connectivity = common.get_offset(offset_provider, offset_type.value) + assert isinstance(offset_type, common.DimensionRef) + connectivity = common.get_offset(offset_provider, offset_type.tag) assert common.is_neighbor_table(connectivity) + # NOTE: the type carries a ref; the embedded field needs the class, which the + # connectivity (a runtime object) has. + local_dim = connectivity.domain.dims[1] + assert common.dimension_ref(local_dim) == offset_type return domain.insert( len(domain), - common.named_range((offset_type, connectivity.__gt_type__().max_neighbors)), + common.dimension_range((local_dim, connectivity.__gt_type__().max_neighbors)), ), type_.element_type return domain, type_ @@ -1770,12 +1772,12 @@ def closure( if not (isinstance(out, common.Field) or is_tuple_of_field(out)): raise TypeError("'Out' needs to be a located field.") - column_range: common.NamedRange | eve.NothingType = _extract_column_range(domain, sten) + column_range: common.DimensionRange | eve.NothingType = _extract_column_range(domain, sten) column_dim = None - if isinstance(column_range, common.NamedRange): + if isinstance(column_range, common.DimensionRange): column_dim = column_range.dim - del domain[column_range.dim.value] + del domain[column_range.dim.tag] out = as_tuple_field(out) if is_tuple_of_field(out) else _wrap_field(out) promoted_ins = [promote_scalars(inp) for inp in ins] @@ -1788,10 +1790,10 @@ def closure( assert _is_concrete_position(pos) out.field_setitem(pos, res) else: - column_range = cast(common.NamedRange, column_range) + column_range = cast(common.DimensionRange, column_range) col_pos = pos.copy() - for k in column_range.unit_range: - col_pos[column_range.dim.value] = k + for k in column_range.value: + col_pos[column_range.dim.tag] = k assert _is_concrete_position(col_pos) out.field_setitem(col_pos, res[k]) # type: ignore[index] diff --git a/src/gt4py/next/iterator/ir.py b/src/gt4py/next/iterator/ir.py index f024ef6168..b7bb41f3dd 100644 --- a/src/gt4py/next/iterator/ir.py +++ b/src/gt4py/next/iterator/ir.py @@ -40,7 +40,8 @@ class Node(eve.Node): def __str__(self) -> str: from gt4py.next.iterator.pretty_printer import pformat - return pformat(self) + # For display (e.g. embedded in messages): short dimension names, no header. + return pformat(self, dimension_header=False) def __hash__(self) -> int: return hash( @@ -90,10 +91,19 @@ class OffsetLiteral(Expr): class AxisLiteral(Expr): - # TODO(havogt): Refactor to use declare Axis/Dimension at the Program level. - # Now every use of the literal has to provide the kind, where usually we only care of the name. - value: str - kind: common.DimensionKind = common.DimensionKind.HORIZONTAL + #: The dimension, as a self-contained value: all its properties (e.g. the kind) are in the + #: IR, so nothing below the frontend imports the module that declared it. A dimension class + #: passed to the constructor is converted. + dim: common.DimensionRef = eve.field(converter=common.dimension_ref, kw_only=True) + + @property + def value(self) -> common.Tag: + """The dimension's tag, its IR spelling.""" + return self.dim.tag + + @property + def kind(self) -> common.DimensionKind: + return self.dim.kind class CartesianOffset(Expr): diff --git a/src/gt4py/next/iterator/ir_utils/domain_utils.py b/src/gt4py/next/iterator/ir_utils/domain_utils.py index 6bd28f6dbc..488244047a 100644 --- a/src/gt4py/next/iterator/ir_utils/domain_utils.py +++ b/src/gt4py/next/iterator/ir_utils/domain_utils.py @@ -133,7 +133,14 @@ def _unstructured_translate_range_statically( @dataclasses.dataclass(frozen=True) class SymbolicDomain: grid_type: common.GridType - ranges: dict[common.Dimension, SymbolicRange] + #: Keyed by `DimensionRef`; dimension classes passed to the constructor are converted. + ranges: dict[common.DimensionRef, SymbolicRange] + + def __post_init__(self) -> None: + if not all(isinstance(dim, common.DimensionRef) for dim in self.ranges): + object.__setattr__( + self, "ranges", {common.dimension_ref(dim): r for dim, r in self.ranges.items()} + ) def __hash__(self) -> int: return hash((self.grid_type, frozenset(self.ranges.items()))) @@ -149,19 +156,17 @@ def empty(self) -> bool | None: def from_expr(cls, node: itir.Node) -> SymbolicDomain: assert cpm.is_call_to(node, ("unstructured_domain", "cartesian_domain")) - ranges: dict[common.Dimension, SymbolicRange] = {} + ranges: dict[common.DimensionRef, SymbolicRange] = {} for named_range in node.args: assert cpm.is_call_to(named_range, "named_range") axis_literal, lower_bound, upper_bound = named_range.args assert isinstance(axis_literal, itir.AxisLiteral) - ranges[common.Dimension(value=axis_literal.value, kind=axis_literal.kind)] = ( - SymbolicRange(lower_bound, upper_bound) - ) + ranges[axis_literal.dim] = SymbolicRange(lower_bound, upper_bound) return cls(_GRID_TYPE_MAPPING[node.fun.id], ranges) def as_expr(self) -> itir.FunCall: - converted_ranges: dict[common.Dimension, tuple[itir.Expr, itir.Expr]] = { + converted_ranges: dict[common.DimensionLike, tuple[itir.Expr, itir.Expr]] = { key: (value.start, value.stop) for key, value in self.ranges.items() } return im.domain(self.grid_type, converted_ranges) @@ -213,8 +218,8 @@ def translate( connectivity: common.NeighborTable | common.NeighborConnectivityType if common.is_offset_provider(offset_provider): connectivity = common.get_offset(offset_provider, off.value) - old_dim = connectivity.domain.dims[0] - new_dim = connectivity.codomain + old_dim = common.dimension_ref(connectivity.domain.dims[0]) + new_dim = common.dimension_ref(connectivity.codomain) else: assert common.is_offset_provider_type(offset_provider) connectivity = common.get_offset_type(offset_provider, off.value) @@ -222,10 +227,10 @@ def translate( new_dim = connectivity.codomain assert new_dim not in new_ranges or old_dim == new_dim - if symbolic_domain_sizes is not None and new_dim.value in symbolic_domain_sizes: + if symbolic_domain_sizes is not None and new_dim.tag in symbolic_domain_sizes: new_range = SymbolicRange( im.literal(str(0), builtins.INTEGER_INDEX_BUILTIN), - im.ensure_expr(symbolic_domain_sizes[new_dim.value]), + im.ensure_expr(symbolic_domain_sizes[new_dim.tag]), ) else: assert common.is_neighbor_table(connectivity) @@ -340,9 +345,10 @@ def domain_complement(domain: SymbolicDomain) -> SymbolicDomain: def promote_domain( - domain: SymbolicDomain, target_dims: Iterable[common.Dimension] + domain: SymbolicDomain, target_dims: Iterable[common.DimensionLike] ) -> SymbolicDomain: """Return a domain that is extended with the dimensions of target_dims.""" + target_dims = common.dimension_refs(target_dims) assert set(domain.ranges.keys()).issubset(target_dims) dims_dict = { dim: domain.ranges[dim] diff --git a/src/gt4py/next/iterator/ir_utils/ir_makers.py b/src/gt4py/next/iterator/ir_utils/ir_makers.py index 5ef7399b2a..72e1bbe2da 100644 --- a/src/gt4py/next/iterator/ir_utils/ir_makers.py +++ b/src/gt4py/next/iterator/ir_utils/ir_makers.py @@ -7,7 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause import typing -from typing import Any, Callable, Iterable, Optional, TypeAlias, Union +from typing import Any, Callable, Iterable, Mapping, Optional, TypeAlias, Union from gt4py._core import definitions as core_defs from gt4py.next import common @@ -15,7 +15,7 @@ from gt4py.next.type_system import type_specifications as ts, type_translation -ExprLike: TypeAlias = Union[str, core_defs.Scalar, common.Dimension, itir.Expr] +ExprLike: TypeAlias = Union[str, core_defs.Scalar, common.Dimension, common.DimensionRef, itir.Expr] def sym(sym_or_name: Union[str, itir.Sym], type_: str | ts.TypeSpec | None = None) -> itir.Sym: @@ -90,7 +90,7 @@ def ensure_expr(expr_like: ExprLike) -> itir.Expr: return ref(expr_like) elif core_defs.is_scalar_type(expr_like): return literal_from_value(expr_like) - elif isinstance(expr_like, common.Dimension): + elif isinstance(expr_like, (common.DimensionMeta, common.DimensionRef)): return axis_literal(expr_like) assert isinstance(expr_like, itir.Expr), expr_like return expr_like @@ -451,11 +451,11 @@ def _impl(*its: itir.Expr) -> itir.FunCall: def domain( grid_type: Union[common.GridType, str], - ranges_or_domain: dict[common.Dimension, tuple[itir.Expr, itir.Expr]] | common.Domain, + ranges_or_domain: Mapping[common.DimensionLike, tuple[itir.Expr, itir.Expr]] | common.Domain, ) -> itir.FunCall: """ - >>> IDim = common.Dimension(value="IDim", kind=common.DimensionKind.HORIZONTAL) - >>> JDim = common.Dimension(value="JDim", kind=common.DimensionKind.HORIZONTAL) + >>> class IDim(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... + >>> class JDim(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... >>> str(domain(common.GridType.CARTESIAN, {IDim: (0, 10), JDim: (0, 20)})) 'c⟨ IDimₕ: [0, 10[, JDimₕ: [0, 20[ ⟩' >>> str(domain(common.GridType.UNSTRUCTURED, {IDim: (0, 10), JDim: (0, 20)})) @@ -490,14 +490,14 @@ def domain( def get_field_domain( grid_type: Union[common.GridType, str], field: str | itir.Expr, - dims: Iterable[common.Dimension] | None = None, + dims: Iterable[common.DimensionLike] | None = None, ) -> itir.Expr: + refs = None if dims is None else common.dimension_refs(dims) if isinstance(field, itir.Expr) and isinstance(field.type, ts.FieldType): - assert dims is None or all(d1 == d2 for d1, d2 in zip(field.type.dims, dims, strict=True)) - dims = field.type.dims - else: - if dims is None: - raise ValueError("Field expression must be typed if 'dims' is not given.") + assert refs is None or all(d1 == d2 for d1, d2 in zip(field.type.dims, refs, strict=True)) + refs = field.type.dims + elif refs is None: + raise ValueError("Field expression must be typed if 'dims' is not given.") return domain( grid_type, @@ -506,13 +506,13 @@ def get_field_domain( tuple_get(0, call("get_domain_range")(field, dim)), tuple_get(1, call("get_domain_range")(field, dim)), ) - for dim in dims + for dim in refs }, ) def named_range( - dim: itir.AxisLiteral | common.Dimension, start: itir.Expr, stop: itir.Expr + dim: itir.AxisLiteral | common.DimensionLike, start: itir.Expr, stop: itir.Expr ) -> itir.FunCall: return call("named_range")(dim, start, stop) @@ -582,17 +582,17 @@ def _impl(*its: itir.Expr) -> itir.FunCall: return _impl -def axis_literal(dim: common.Dimension) -> itir.AxisLiteral: - return itir.AxisLiteral(value=dim.value, kind=dim.kind) +def axis_literal(dim: common.DimensionLike) -> itir.AxisLiteral: + return itir.AxisLiteral(dim=dim) -def broadcast(expr: ExprLike, dims: Iterable[common.Dimension]) -> itir.FunCall: +def broadcast(expr: ExprLike, dims: Iterable[common.DimensionLike]) -> itir.FunCall: """ Create a broadcast FunCall of `expr` to `dims`. Examples -------- - >>> IDim = common.Dimension("IDim") + >>> class IDim(common.CartesianAxisIndex): ... >>> str(broadcast("a", (IDim,))) 'broadcast(a, {IDimₕ})' """ @@ -600,7 +600,7 @@ def broadcast(expr: ExprLike, dims: Iterable[common.Dimension]) -> itir.FunCall: def cartesian_offset( - domain: common.Dimension, codomain: Optional[common.Dimension] = None + domain: common.DimensionLike, codomain: Optional[common.DimensionLike] = None ) -> itir.CartesianOffset: if codomain is None: codomain = domain @@ -629,7 +629,7 @@ def _impl(it: itir.Expr) -> itir.FunCall: return _impl -def index(dim: common.Dimension) -> itir.FunCall: +def index(dim: common.DimensionLike) -> itir.FunCall: """ Create a call to the `index` builtin, shorthand for `call("index")(axis)`, after converting the given dimension to `itir.AxisLiteral`. @@ -640,7 +640,7 @@ def index(dim: common.Dimension) -> itir.FunCall: Returns: A function that constructs a Field of indices in the given dimension. """ - return call("index")(itir.AxisLiteral(value=dim.value, kind=dim.kind)) + return call("index")(itir.AxisLiteral(dim=dim)) def map_list(op): @@ -663,7 +663,7 @@ def reduce(op, expr): return call(call("reduce")(op, expr)) -def scan(expr, forward, init, axis: itir.AxisLiteral | common.Dimension): +def scan(expr, forward, init, axis: itir.AxisLiteral | common.DimensionLike): """Create a `scan` call.""" return call("scan")(expr, forward, init, axis) diff --git a/src/gt4py/next/iterator/ir_utils/misc.py b/src/gt4py/next/iterator/ir_utils/misc.py index 35322172f2..ade4e31a11 100644 --- a/src/gt4py/next/iterator/ir_utils/misc.py +++ b/src/gt4py/next/iterator/ir_utils/misc.py @@ -17,7 +17,7 @@ from gt4py.next.iterator import embedded, ir as itir from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm, ir_makers as im from gt4py.next.iterator.transforms import inline_lambdas -from gt4py.next.type_system import type_specifications as ts +from gt4py.next.type_system import type_info, type_specifications as ts @dataclasses.dataclass(frozen=True) @@ -121,11 +121,12 @@ def unwrap_scan( identity function. This function allows treating a scan stencil like a regular stencil during a transformation avoiding the complexity introduced by the different IR format. + >>> class K(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... >>> scan = im.scan( ... im.lambda_("state", "arg")(im.plus("state", im.deref("arg"))), ... True, ... 0.0, - ... common.Dimension("K", common.DimensionKind.VERTICAL), + ... K, ... ) >>> stencil, back_trafo = unwrap_scan(scan) >>> str(stencil) @@ -234,8 +235,8 @@ def grid_type_from_domain(domain: itir.FunCall) -> common.GridType: return common.GridType.UNSTRUCTURED -def dim_from_axis_literal(axis_literal: itir.AxisLiteral) -> common.Dimension: - return common.Dimension(value=axis_literal.value, kind=axis_literal.kind) +def dim_from_axis_literal(axis_literal: itir.AxisLiteral) -> common.DimensionRef: + return axis_literal.dim def _flatten_tuple_expr(expr: itir.Expr) -> tuple[itir.Expr]: @@ -282,3 +283,43 @@ def value_from_literal(literal: itir.Literal) -> core_defs.Scalar: assert literal.value in ["True", "False"] return literal.value == "True" return getattr(embedded, str(literal.type))(literal.value) + + +def check_consistent_dimension_refs(refs: Iterable[common.DimensionRef]) -> None: + """ + Reject two different refs spelled with the same tag. + + They would collide on every identifier derived from the tag (gtfn tag types, DaCe symbols, + offset-provider keys). The base of a staggered dimension is checked as well. + """ + seen: dict[common.Tag, common.DimensionRef] = {} + for ref in (r for top in refs for r in (top, top.base) if r is not None): + if (other := seen.setdefault(ref.tag, ref)) != ref: + raise ValueError( + f"Two different dimensions share the tag '{ref.tag}': {other!r} and {ref!r}." + " Was a dimension redefined (e.g. a notebook cell re-run with another 'kind')?" + ) + + +def check_program_dimension_refs( + program: itir.Program, + offset_provider_type: common.OffsetProviderType, +) -> None: + """ + Reject a program in which two different `DimensionRef`s share a tag. + + Collects the refs of the parameter types, the axis literals and the offset-provider types; + see `check_consistent_dimension_refs`. + """ + refs: list[common.DimensionRef] = [ + axis.dim for axis in program.walk_values().if_isinstance(itir.AxisLiteral) + ] + for param in program.params: + if param.type is not None: + for type_ in type_info.primitive_constituents(param.type): + if isinstance(type_, ts.FieldType): + refs.extend(type_.dims) + for conn_type in offset_provider_type.values(): + if isinstance(conn_type, common.ConnectivityType): + refs.extend((*conn_type.domain, conn_type.codomain)) + check_consistent_dimension_refs(refs) diff --git a/src/gt4py/next/iterator/pretty_parser.py b/src/gt4py/next/iterator/pretty_parser.py index b58f66436f..d4fd628828 100644 --- a/src/gt4py/next/iterator/pretty_parser.py +++ b/src/gt4py/next/iterator/pretty_parser.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +from collections.abc import Mapping from typing import Union from lark import ( @@ -16,12 +17,17 @@ visitors as lark_visitors, ) +from gt4py.next import common from gt4py.next.iterator import ir, pretty_printer from gt4py.next.type_system import type_specifications as ts -GRAMMAR = """ - start: fencil_definition +_AXIS_KIND_FROM_SUFFIX = {v: k for k, v in pretty_printer._AXIS_KIND_SUFFIX.items()} + + +GRAMMAR = r""" + start: dim_decl* _root + _root: fencil_definition | function_definition | declaration | stencil_closure @@ -30,13 +36,24 @@ | program | prec0 + // Header entry giving a short dimension name its full spelling (see `pretty_printer`). + dim_decl: "dim" TAG "=" AXIS_LITERAL ";" + SYM: CNAME SYM_REF: CNAME TYPE_LITERAL: CNAME INT_LITERAL: SIGNED_INT FLOAT_LITERAL: SIGNED_FLOAT - OFFSET_LITERAL: ( INT_LITERAL | CNAME ) "ₒ" - AXIS_LITERAL: CNAME ("ᵥ" | "ₕ") + // A dimension tag is `module:qualname` (ADR 0030), and -- for a parametrized dimension + // such as `Staggered[pkg:K]` -- with one bracketed tag. A short dimension name (declared + // in the header) and an offset tag are the same without the module part. + // Its parts are Python identifiers, Unicode included (`[^\W\d]\w*`: a letter or `_`, then + // word characters). Unambiguous here: a tag starts with a letter (a float does not), and + // the literal's suffix terminates it. The suffixes are word characters too, but cannot + // occur in an identifier: Python NFKC-normalizes them (e.g. `ₕ` to `h`). + TAG: /[^\W\d]\w*(?:\.[^\W\d]\w*)*(?::[^\W\d]\w*(?:\.[^\W\d]\w*)*)?(?:\[[^\W\d]\w*(?:\.[^\W\d]\w*)*(?::[^\W\d]\w*(?:\.[^\W\d]\w*)*)?\])?/ + OFFSET_LITERAL: ( INT_LITERAL | TAG ) "ₒ" + AXIS_LITERAL: TAG ("ᵥ" | "ₕ" | "ₗ") "ᵃ"? INFINITY_LITERAL: "∞" | "-∞" _literal: INT_LITERAL | FLOAT_LITERAL | OFFSET_LITERAL | AXIS_LITERAL | INFINITY_LITERAL ID_NAME: CNAME @@ -112,6 +129,24 @@ """ # noqa: RUF001 [ambiguous-unicode-character-string] +def _split_axis_literal(text: str) -> tuple[str, common.DimensionKind, bool]: + """Split an axis literal into its name, kind and whether it is spelled as a Cartesian axis.""" + name = text.removesuffix(pretty_printer._CARTESIAN_AXIS_SUFFIX) + return name[:-1], _AXIS_KIND_FROM_SUFFIX[name[-1]], name != text + + +def _is_full_tag(name: str) -> bool: + # Only a full tag has a module part; a short name is a (dotted) qualname. + return ":" in name + + +def _full_dimension_ref(text: str) -> common.DimensionRef: + # NOTE: the tag and the suffixes rebuild the `DimensionRef` without importing the declaring + # module. + tag, kind, is_cartesian_axis = _split_axis_literal(text) + return common.DimensionRef.from_tag(tag, kind, is_cartesian_axis=is_cartesian_axis) + + def _bare_literal(value: str) -> ir.Literal: """A literal written without a type annotation.""" return ir.Literal(value=value, type=pretty_printer.implied_literal_type(value)) @@ -119,6 +154,14 @@ def _bare_literal(value: str) -> ir.Literal: @lark_visitors.v_args(inline=True) class ToIrTransformer(lark_visitors.Transformer): + def __init__(self, dimensions: Mapping[str, common.DimensionRef]) -> None: + """ + Args: + dimensions: The short dimension names the header declares. + """ + super().__init__(visit_tokens=True) + self.dimensions = dimensions + def SYM(self, value: lark_lexer.Token) -> ir.Sym: return ir.Sym(id=value.value) @@ -172,9 +215,24 @@ def INFINITY_LITERAL(self, value: lark_lexer.Token) -> ir.InfinityLiteral: return ir.InfinityLiteral.POSITIVE def AXIS_LITERAL(self, value: lark_lexer.Token) -> ir.AxisLiteral: - name = value.value[:-1] - kind = ir.DimensionKind.HORIZONTAL if value.value[-1] == "ₕ" else ir.DimensionKind.VERTICAL - return ir.AxisLiteral(value=name, kind=kind) + name, kind, is_cartesian_axis = _split_axis_literal(value.value) + if _is_full_tag(name): + return ir.AxisLiteral(dim=_full_dimension_ref(value.value)) + if (dim := self.dimensions.get(name)) is None: + raise ValueError( + f"Dimension '{name}' is not declared. A short dimension name needs a header entry" + f" '{pretty_printer.DIMENSION_HEADER_KEYWORD} {name} = :" + ";'; otherwise spell the full tag 'module:qualname' in place." + ) + if dim.kind != kind or (is_cartesian_axis and not dim.is_cartesian_axis): + raise ValueError( + f"'{value.value}' does not match the declaration of '{name}':" + f" '{pretty_printer.format_full_axis_literal(dim)}'." + ) + return ir.AxisLiteral(dim=dim) + + def dim_decl(self, *args: object) -> None: + return None # read by `pparse` before the transformation def lam(self, *args: ir.Node) -> ir.Lambda: *params, expr = args @@ -322,14 +380,45 @@ def program(self, fid: str, *args: ir.Node) -> ir.Program: declarations=declarations, ) - def start(self, arg: ir.Node) -> ir.Node: - return arg + def start(self, *args: ir.Node | None) -> ir.Node: + *_header, root = args + assert root is not None + return root + + +def _dimension_header(tree: lark_tree.Tree) -> dict[str, common.DimensionRef]: + dimensions: dict[str, common.DimensionRef] = {} + for decl in tree.children: + if not (isinstance(decl, lark_tree.Tree) and decl.data == "dim_decl"): + continue + name, literal = (str(token) for token in decl.children) + if _is_full_tag(name): + raise ValueError(f"Invalid short dimension name '{name}': it has a module part.") + if not _is_full_tag(_split_axis_literal(literal)[0]): + raise ValueError( + f"The declaration of '{name}' must spell the full tag, got '{literal}'." + ) + if name in dimensions: + raise ValueError(f"Dimension '{name}' is declared twice.") + dimensions[name] = _full_dimension_ref(literal) + return dimensions def pparse(pretty_str: str) -> ir.Node: + """ + Parse the text `pretty_printer.pformat` prints back to the IR node. + + A dimension is either spelled in full in place (`module:qualname` with its kind and + Cartesian axis suffixes, e.g. `my.dims:IDimₕᵃ`), which keeps hand-written IR easy, or by a + short name with its kind suffix (`IDimₕ`) declared in the header (`dim IDim = my.dims:IDimₕᵃ;`). + A short name that the header does not declare is an error: nothing is imported to guess it. + + Raises: + ValueError: If a dimension is malformed, undeclared or does not match its declaration. + """ parser = lark.Lark(GRAMMAR, parser="earley") tree = parser.parse(pretty_str) try: - return ToIrTransformer(visit_tokens=True).transform(tree) + return ToIrTransformer(_dimension_header(tree)).transform(tree) except lark_exceptions.VisitError as e: raise e.orig_exc from None diff --git a/src/gt4py/next/iterator/pretty_printer.py b/src/gt4py/next/iterator/pretty_printer.py index 5fbba8920e..00c099f266 100644 --- a/src/gt4py/next/iterator/pretty_printer.py +++ b/src/gt4py/next/iterator/pretty_printer.py @@ -9,16 +9,37 @@ """A pretty printer for the functional IR. Inspired by P. Yelland, “A New Approach to Optimal Code Formatting”, 2015 + +Dimensions are printed by a short name followed by their kind suffix (`ₕ` horizontal, `ᵥ` +vertical, `ₗ` local). A header at the top of the printed root node maps each short name to the +dimension's full spelling: its tag `module:qualname`, kind suffix and, for a +Cartesian axis, `ᵃ`. `pretty_parser` rebuilds the exact `DimensionRef`s from it, without +importing anything: + + dim IDim = my.model.dims:IDimₕᵃ; + dim Staggered[KDim] = gt4py.next.common:Staggered[my.model.dims:KDim]ᵥᵃ; + c⟨ IDimₕ: [0, 10[, Staggered[KDim]ᵥ: [0, 81[ ⟩ + +The short name is the qualname. Different dimensions sharing one are told apart by the +shortest module suffix that distinguishes them (`dims.IDim`, `other.dims.IDim`). Dimensions +that share their whole tag (they differ only in the suffixes) have no distinguishing +short name and are printed in full in place. + +`pformat` serializes: it prints the header, so its output parses back. `str(node)` displays: +it prints the same short names without the header, to read well inside messages, and does not +parse back. """ # TODO(tehrengruber): add support for printing the types of itir.Sym nodes from __future__ import annotations import types as _types -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Iterable, Iterator, Mapping, Sequence from typing import Final +from gt4py import eve from gt4py.eve import NodeTranslator +from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.type_system import type_specifications as ts, type_translation @@ -134,6 +155,68 @@ def implied_literal_type(value: str) -> ts.ScalarType: DEFAULT_WIDTH: Final = 100 +_AXIS_KIND_SUFFIX: Final = { + common.DimensionKind.HORIZONTAL: "ₕ", + common.DimensionKind.VERTICAL: "ᵥ", + common.DimensionKind.LOCAL: "ₗ", +} +#: Printed after the kind suffix of a Cartesian axis. Together with the tag and the kind it is +#: enough to rebuild the `DimensionRef` without importing anything. +_CARTESIAN_AXIS_SUFFIX: Final = "ᵃ" + +#: Keyword of a dimension header entry: `dim = ;`. +DIMENSION_HEADER_KEYWORD: Final = "dim" + + +def format_full_axis_literal(dim: common.DimensionRef) -> str: + """The self-contained spelling of a dimension: tag, kind suffix and Cartesian axis suffix.""" + axis_suffix = _CARTESIAN_AXIS_SUFFIX if dim.is_cartesian_axis else "" + return dim.tag + _AXIS_KIND_SUFFIX[dim.kind] + axis_suffix + + +def _module_depth(dim: common.DimensionRef) -> int: + # A staggered dimension is told apart by its base: its own module is always `common`. + return _module_depth(dim.base) if dim.base is not None else dim.module.count(".") + 1 + + +def _short_name(dim: common.DimensionRef, depth: int) -> str: + """The qualname, prefixed by the last `depth` components of the module path.""" + if dim.base is not None: + owner = dim.qualname.partition("[")[0] + return f"{owner}[{_short_name(dim.base, depth)}]" + module_suffix = dim.module.split(".")[-depth:] if depth else [] + return ".".join([*module_suffix, dim.qualname]) + + +def short_dimension_names(dims: Iterable[common.DimensionRef]) -> dict[common.DimensionRef, str]: + """ + Assign each of `dims` a distinct short name for printing. + + The short name is the qualname. Where several dimensions would share one, each of them is + prefixed by one more component of its module path, until the names differ or the module + paths are exhausted. Dimensions that still share a name (their tags are equal, they differ + in the suffixes only) get none. + + Returns: + The short name of each dimension that has one; deterministic for a given set of `dims`. + """ + unique = sorted(set(dims), key=lambda dim: (dim.tag, dim.kind.value, dim.is_cartesian_axis)) + depths = dict.fromkeys(unique, 0) + while True: + groups: dict[str, list[common.DimensionRef]] = {} + for dim in unique: + groups.setdefault(_short_name(dim, depths[dim]), []).append(dim) + deepened = False + for group in groups.values(): + if len(group) > 1: + for dim in group: + if depths[dim] < _module_depth(dim): + depths[dim] += 1 + deepened = True + if not deepened: + return {group[0]: name for name, group in groups.items() if len(group) == 1} + + class PrettyPrinter(NodeTranslator): def __init__( self, @@ -143,6 +226,8 @@ def __init__( super().__init__() self.indent: int = indent self.width: int = width + #: Dimensions printed by short name; any other is printed in full in place. + self.short_names: Mapping[common.DimensionRef, str] = {} @staticmethod def _hmerge(*blocks: list[str]) -> list[str]: @@ -225,12 +310,12 @@ def visit_CartesianOffset(self, node: ir.CartesianOffset, *, prec: int) -> list[ return [f"{domain}→{codomain}"] def visit_AxisLiteral(self, node: ir.AxisLiteral, *, prec: int) -> list[str]: - kind = "" - if node.kind == ir.DimensionKind.HORIZONTAL: - kind = "ₕ" - elif node.kind == ir.DimensionKind.VERTICAL: - kind = "ᵥ" - return [str(node.value) + kind] + # NOTE: the literal carries its `DimensionRef`, so printing needs no import. A short + # name stands for the full spelling given in the header (see `apply`). + dim = node.dim + if (short_name := self.short_names.get(dim)) is not None: + return [short_name + _AXIS_KIND_SUFFIX[dim.kind]] + return [format_full_axis_literal(dim)] def visit_SymRef(self, node: ir.SymRef, *, prec: int) -> list[str]: return [node.id] @@ -406,13 +491,47 @@ def visit_Program(self, node: ir.Program, *, prec: int) -> list[str]: ) @classmethod - def apply(cls, node: ir.Node, indent: int, width: int) -> str: - return "\n".join(cls(indent=indent, width=width).visit(node, prec=0)) + def apply(cls, node: ir.Node, indent: int, width: int, *, dimension_header: bool = True) -> str: + """Print `node` with short dimension names, preceded by their header if requested.""" + printer = cls(indent=indent, width=width) + dims = eve.walk_values(node).if_isinstance(ir.AxisLiteral).getattr("dim") + printer.short_names = short_dimension_names(dims) + header = ( + [ + f"{DIMENSION_HEADER_KEYWORD} {name} = {format_full_axis_literal(dim)};" + for dim, name in sorted(printer.short_names.items(), key=lambda item: item[1]) + ] + if dimension_header + else [] + ) + return "\n".join([*header, *printer.visit(node, prec=0)]) -def pformat(x: ir.Node, indent: int = DEFAULT_INDENT, width: int = DEFAULT_WIDTH) -> str: - return PrettyPrinter.apply(x, indent, width) +def pformat( + x: ir.Node, + indent: int = DEFAULT_INDENT, + width: int = DEFAULT_WIDTH, + *, + dimension_header: bool = True, +) -> str: + """ + Print `x` in the syntax `pretty_parser.pparse` reads back. + + Args: + x: The node to print. + indent: Spaces per indentation level. + width: Preferred maximum line width. + dimension_header: Whether to declare the short dimension names in a header. Without + it (as in `str(node)`) the text is for display only and does not parse back. + """ + return PrettyPrinter.apply(x, indent, width, dimension_header=dimension_header) -def pprint(x: ir.Node, indent: int = DEFAULT_INDENT, width: int = DEFAULT_WIDTH) -> None: - print(pformat(x, indent, width)) +def pprint( + x: ir.Node, + indent: int = DEFAULT_INDENT, + width: int = DEFAULT_WIDTH, + *, + dimension_header: bool = True, +) -> None: + print(pformat(x, indent, width, dimension_header=dimension_header)) diff --git a/src/gt4py/next/iterator/tracing.py b/src/gt4py/next/iterator/tracing.py index 4450d1c276..4e23b93bb7 100644 --- a/src/gt4py/next/iterator/tracing.py +++ b/src/gt4py/next/iterator/tracing.py @@ -140,8 +140,8 @@ def __call__(self, *args): def make_node(o): if isinstance(o, Node): return o - if isinstance(o, common.Dimension): - return AxisLiteral(value=o.value, kind=o.kind) + if isinstance(o, common.DimensionMeta): + return AxisLiteral(dim=o) if isinstance(o, common.Infinity): if o is common.Infinity.POSITIVE: return itir.InfinityLiteral.POSITIVE diff --git a/src/gt4py/next/iterator/transforms/fuse_as_fieldop.py b/src/gt4py/next/iterator/transforms/fuse_as_fieldop.py index 7889582964..9ecd51fd46 100644 --- a/src/gt4py/next/iterator/transforms/fuse_as_fieldop.py +++ b/src/gt4py/next/iterator/transforms/fuse_as_fieldop.py @@ -252,7 +252,7 @@ class FuseAsFieldOp( >>> from gt4py import next as gtx >>> from gt4py.next import utils >>> from gt4py.next.iterator.ir_utils import ir_makers as im - >>> IDim = gtx.Dimension("IDim") + >>> class IDim(gtx.CartesianAxisIndex): ... >>> field_type = ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.INT32)) >>> d = im.domain("cartesian_domain", {IDim: (0, 1)}) >>> nested_as_fieldop = im.op_as_fieldop("plus", d)( diff --git a/src/gt4py/next/iterator/transforms/infer_domain.py b/src/gt4py/next/iterator/transforms/infer_domain.py index 0027d2c766..b53fd44303 100644 --- a/src/gt4py/next/iterator/transforms/infer_domain.py +++ b/src/gt4py/next/iterator/transforms/infer_domain.py @@ -161,8 +161,8 @@ def _extract_accessed_domains( def _filter_domain_dimensions( domain: domain_utils.SymbolicDomain, - dims: list[common.Dimension], - additional_dims: Optional[dict[common.Dimension, domain_utils.SymbolicRange]] = None, + dims: list[common.DimensionRef], + additional_dims: Optional[dict[common.DimensionRef, domain_utils.SymbolicRange]] = None, ) -> domain_utils.SymbolicDomain: assert isinstance(domain, domain_utils.SymbolicDomain) retained = {dim: domain.ranges[dim] for dim in dims if dim in domain.ranges} @@ -172,8 +172,8 @@ def _filter_domain_dimensions( def _extract_scan_axis( - domain: domain_utils.SymbolicDomain, axis: common.Dimension -) -> dict[common.Dimension, domain_utils.SymbolicRange]: + domain: domain_utils.SymbolicDomain, axis: common.DimensionRef +) -> dict[common.DimensionRef, domain_utils.SymbolicRange]: assert isinstance(domain, domain_utils.SymbolicDomain) return {axis: domain.ranges[axis]} if axis in domain.ranges else {} @@ -458,8 +458,10 @@ def infer_expr( - domain: The domain `expr` is read at. Keyword Arguments: - - symbolic_domain_sizes: A dictionary mapping axes names, e.g., `I`, `Vertex`, to a symbol - name or expression that evaluates to the length of that axis. + - symbolic_domain_sizes: A dictionary mapping dimension tags (`module:qualname`, e.g. + `IDim.tag`) to a symbol name or expression that evaluates to the length of that axis. + Not normalized here: callers pass tags (`infer_program` and the pass manager accept + dimension classes too, see `common.normalize_symbolic_domain_sizes`). - allow_uninferred: Allow `as_fieldop` expressions whose domain is either unknown (e.g. because of a dynamic shift) or never accessed. - keep_existing_domains: If `True`, keep existing domains in `as_fieldop` expressions and @@ -586,6 +588,7 @@ def infer_program( assert not program.function_definitions, ( "Domain propagation does not support function definitions." ) + symbolic_domain_sizes = common.normalize_symbolic_domain_sizes(symbolic_domain_sizes) program = itir_type_inference.infer( program, offset_provider_type=common.offset_provider_to_type(offset_provider) diff --git a/src/gt4py/next/iterator/transforms/infer_domain_ops.py b/src/gt4py/next/iterator/transforms/infer_domain_ops.py index 20327c0589..58d4408c18 100644 --- a/src/gt4py/next/iterator/transforms/infer_domain_ops.py +++ b/src/gt4py/next/iterator/transforms/infer_domain_ops.py @@ -54,7 +54,7 @@ def visit_FunCall(self, node: itir.FunCall, **kwargs) -> itir.Node: inference.reinfer(arg1) assert isinstance(arg1.type, ts.DimensionType) - dim: common.Dimension = arg1.type.dim + dim: common.DimensionRef = arg1.type.dim value: itir.Expr = arg2 if cpm.is_call_to(node, ("less", "less_equal", "greater", "greater_equal", "eq")): diff --git a/src/gt4py/next/iterator/transforms/inline_fundefs.py b/src/gt4py/next/iterator/transforms/inline_fundefs.py index 2b8767e4a2..5c5156627f 100644 --- a/src/gt4py/next/iterator/transforms/inline_fundefs.py +++ b/src/gt4py/next/iterator/transforms/inline_fundefs.py @@ -44,7 +44,7 @@ def prune_unreferenced_fundefs(program: itir.Program) -> itir.Program: ... params=[im.sym("a")], ... expr=im.deref("a"), ... ) - >>> IDim = common.Dimension(value="IDim", kind=common.DimensionKind.HORIZONTAL) + >>> class IDim(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... >>> program = itir.Program( ... id="testee", ... function_definitions=[fun1, fun2], diff --git a/src/gt4py/next/iterator/transforms/pass_manager.py b/src/gt4py/next/iterator/transforms/pass_manager.py index 067dde468f..109269c94c 100644 --- a/src/gt4py/next/iterator/transforms/pass_manager.py +++ b/src/gt4py/next/iterator/transforms/pass_manager.py @@ -55,8 +55,8 @@ def _max_domain_range_sizes(offset_provider: common.OffsetProvider) -> dict[str, sizes: dict[str, int] = {} for provider in offset_provider.values(): if common.is_neighbor_table(provider): - src_dim = provider.__gt_type__().source_dim.value - codomain_dim = provider.__gt_type__().codomain.value + src_dim = provider.__gt_type__().source_dim.tag + codomain_dim = provider.__gt_type__().codomain.tag sizes[src_dim] = max(sizes.get(src_dim, 0), provider.ndarray.shape[0]) sizes[codomain_dim] = max( sizes.get(codomain_dim, 0), @@ -111,7 +111,7 @@ def _process_symbolic_domains_option( """ if symbolic_domain_sizes: assert not use_max_domain_range_on_unstructured_shift, "Options are mutually exclusive." - return symbolic_domain_sizes + return common.normalize_symbolic_domain_sizes(symbolic_domain_sizes) if use_max_domain_range_on_unstructured_shift is None: use_max_domain_range_on_unstructured_shift = _has_dynamic_domains(ir) diff --git a/src/gt4py/next/iterator/transforms/prune_empty_concat_where.py b/src/gt4py/next/iterator/transforms/prune_empty_concat_where.py index 33d184e7e4..1323a07bbb 100644 --- a/src/gt4py/next/iterator/transforms/prune_empty_concat_where.py +++ b/src/gt4py/next/iterator/transforms/prune_empty_concat_where.py @@ -24,7 +24,7 @@ PRG = TypeVar("PRG", bound=itir.Program | itir.Expr) -def _broadcast_to(expr: itir.Expr, target_dims: list[common.Dimension]) -> itir.Expr: +def _broadcast_to(expr: itir.Expr, target_dims: list[common.DimensionRef]) -> itir.Expr: """Broadcast `expr` to `target_dims` if it does not have these dimensions already.""" assert isinstance(expr.type, (ts.FieldType, ts.ScalarType)) if type_info.extract_dims(expr.type) != target_dims: @@ -84,7 +84,7 @@ class _PruneEmptyConcatWhere(PreserveLocationVisitor, NodeTranslator): `gt4py.next.iterator.transforms.concat_where.expand_tuple_args` before to prune them. >>> from gt4py.next import common - >>> IDim = common.Dimension("IDim") + >>> class IDim(common.CartesianAxisIndex): ... >>> field_t = ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)) >>> expr = im.concat_where( ... im.domain(common.GridType.CARTESIAN, {IDim: (10, itir.InfinityLiteral.POSITIVE)}), diff --git a/src/gt4py/next/iterator/transforms/remove_broadcast.py b/src/gt4py/next/iterator/transforms/remove_broadcast.py index a0c46b21de..6efb17ba99 100644 --- a/src/gt4py/next/iterator/transforms/remove_broadcast.py +++ b/src/gt4py/next/iterator/transforms/remove_broadcast.py @@ -24,14 +24,13 @@ class RemoveBroadcast(PreserveLocationVisitor, NodeTranslator): Example: >>> from gt4py.next import Dimension, common - >>> IDim = Dimension("IDim") - >>> JDim = Dimension("JDim") + >>> from gt4py.next.common import CartesianAxisIndex, DimensionIndex + >>> class IDim(CartesianAxisIndex): ... + >>> class JDim(CartesianAxisIndex): ... >>> domain = im.domain(common.GridType.CARTESIAN, {IDim: (0, 10), JDim: (0, 10)}) >>> expr = im.call("broadcast")( ... im.ref("inp"), - ... im.make_tuple( - ... *(itir.AxisLiteral(value=dim.value, kind=dim.kind) for dim in (IDim, JDim)) - ... ), + ... im.make_tuple(*(itir.AxisLiteral(dim=dim) for dim in (IDim, JDim))), ... ) >>> expr.annex.domain = domain_utils.SymbolicDomain.from_expr(domain) >>> transformed = RemoveBroadcast.apply(expr) diff --git a/src/gt4py/next/iterator/transforms/replace_get_domain_range_with_constants.py b/src/gt4py/next/iterator/transforms/replace_get_domain_range_with_constants.py index f3696a9f80..fea9176256 100644 --- a/src/gt4py/next/iterator/transforms/replace_get_domain_range_with_constants.py +++ b/src/gt4py/next/iterator/transforms/replace_get_domain_range_with_constants.py @@ -54,8 +54,8 @@ class ReplaceGetDomainRangeWithConstants(PreserveLocationVisitor, NodeTranslator Example: >>> from gt4py import next as gtx - >>> KDim = common.Dimension(value="KDim", kind=common.DimensionKind.VERTICAL) - >>> Vertex = common.Dimension(value="Vertex", kind=common.DimensionKind.HORIZONTAL) + >>> class KDim(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + >>> class Vertex(common.DimensionIndex, kind=common.DimensionKind.HORIZONTAL): ... >>> sizes = { ... "out": gtx.domain({Vertex: (0, 10), KDim: (0, 20)}), @@ -114,7 +114,10 @@ def visit_FunCall(self, node: itir.FunCall, **kwargs) -> itir.FunCall: f"'{field}'." ) - index = next((i for i, d in enumerate(domain.dims) if d.value == dim.value), None) - assert index is not None, f"Dimension {dim.value} not found in {domain.dims}" + # NOTE: `dim` is the IR argument -- an `AxisLiteral` whose `value` is the dimension's tag + # -- while `domain.dims` holds dimension classes, so the tag is what they share. + assert isinstance(dim, itir.AxisLiteral) + index = next((i for i, d in enumerate(domain.dims) if d.tag == dim.value), None) + assert index is not None, f"Dimension '{dim.value}' not found in {domain.dims}" return im.make_tuple(domain.ranges[index].start, domain.ranges[index].stop) diff --git a/src/gt4py/next/iterator/transforms/scan_fusion.py b/src/gt4py/next/iterator/transforms/scan_fusion.py index 9dcee60db3..f8c1bbde8f 100644 --- a/src/gt4py/next/iterator/transforms/scan_fusion.py +++ b/src/gt4py/next/iterator/transforms/scan_fusion.py @@ -110,12 +110,8 @@ def visit_FunCall(self, expr: ir.FunCall, **kwargs: Any) -> ir.Expr: if not ( isinstance(axis, ir.CartesianOffset) and axis.domain.kind == common.DimensionKind.VERTICAL - and common.as_non_staggered( - common.Dimension(axis.domain.value, axis.domain.kind) - ) - == common.as_non_staggered( - common.Dimension(axis.codomain.value, axis.codomain.kind) - ) + and common.as_non_staggered(axis.domain.dim) + == common.as_non_staggered(axis.codomain.dim) and isinstance(distance, ir.OffsetLiteral) and isinstance(distance.value, int) ): diff --git a/src/gt4py/next/iterator/transforms/unroll_reduce.py b/src/gt4py/next/iterator/transforms/unroll_reduce.py index c4ea32fc36..cfb7bb3226 100644 --- a/src/gt4py/next/iterator/transforms/unroll_reduce.py +++ b/src/gt4py/next/iterator/transforms/unroll_reduce.py @@ -44,7 +44,7 @@ def _get_partial_offset_tags(reduce_args: Iterable[itir.Expr]) -> Iterable[str]: assert all(isinstance(arg.type, ts.ListType) for arg in reduce_args) return [ - arg.type.offset_type.value # type: ignore[union-attr] # checked in previous lines + arg.type.offset_type.tag # type: ignore[union-attr] # checked in previous lines for arg in reduce_args if arg.type.offset_type is not None # type: ignore[union-attr] # checked in previous lines ] diff --git a/src/gt4py/next/iterator/type_system/inference.py b/src/gt4py/next/iterator/type_system/inference.py index 3fa95f6123..abfbe48c9c 100644 --- a/src/gt4py/next/iterator/type_system/inference.py +++ b/src/gt4py/next/iterator/type_system/inference.py @@ -462,7 +462,7 @@ def visit_SetAt(self, node: itir.SetAt, *, ctx) -> None: assert target_type.dtype == expr_type.dtype def visit_AxisLiteral(self, node: itir.AxisLiteral, **kwargs) -> ts.DimensionType: - return ts.DimensionType(dim=common.Dimension(value=node.value, kind=node.kind)) + return ts.DimensionType(dim=node.dim) # TODO: revisit what we want to do with OffsetLiterals as we already have an Offset type in # the frontend. @@ -563,7 +563,7 @@ def visit_FunCall( if is_call_to(stencil, "scan"): axis = stencil.args[3] assert isinstance(axis, itir.AxisLiteral) - syntactic_info["scan_axis"] = common.Dimension(value=axis.value, kind=axis.kind) + syntactic_info["scan_axis"] = axis.dim fun = self.visit(node.fun, ctx=ctx) args = self.visit(node.args, ctx=ctx) diff --git a/src/gt4py/next/iterator/type_system/type_specifications.py b/src/gt4py/next/iterator/type_system/type_specifications.py index 40c6dde6d7..71bfd7b8ee 100644 --- a/src/gt4py/next/iterator/type_system/type_specifications.py +++ b/src/gt4py/next/iterator/type_system/type_specifications.py @@ -8,12 +8,13 @@ from typing import Literal +from gt4py.eve import datamodels as eve_datamodels from gt4py.next import common from gt4py.next.type_system import type_specifications as ts class NamedRangeType(ts.TypeSpec): - dim: common.Dimension + dim: common.DimensionRef = ts.dimension_field() class OffsetLiteralType(ts.TypeSpec): @@ -21,13 +22,15 @@ class OffsetLiteralType(ts.TypeSpec): class CartesianOffsetType(ts.TypeSpec): - domain: common.Dimension - codomain: common.Dimension + domain: common.DimensionRef = ts.dimension_field() + codomain: common.DimensionRef = ts.dimension_field() class IteratorType(ts.DataType, ts.CallableType): - position_dims: list[common.Dimension] | Literal["unknown"] - defined_dims: list[common.Dimension] + position_dims: list[common.DimensionRef] | Literal["unknown"] = eve_datamodels.field( + converter=lambda dims: dims if dims == "unknown" else common.dimension_refs(dims) + ) + defined_dims: list[common.DimensionRef] = ts.dimension_list_field() element_type: ts.DataType diff --git a/src/gt4py/next/iterator/type_system/type_synthesizer.py b/src/gt4py/next/iterator/type_system/type_synthesizer.py index c1f6c31e79..293c700423 100644 --- a/src/gt4py/next/iterator/type_system/type_synthesizer.py +++ b/src/gt4py/next/iterator/type_system/type_synthesizer.py @@ -347,7 +347,7 @@ def apply_lift( # we would need to look inside the stencil to find out where the resulting iterator # is defined, e.g. using trace shift, instead just use an empty list which means # everywhere - defined_dims: list[common.Dimension] = [] + defined_dims: list[common.DimensionRef] = [] return it_ts.IteratorType( position_dims=position_dims, defined_dims=defined_dims, element_type=stencil_return_type ) @@ -355,7 +355,7 @@ def apply_lift( return apply_lift -def _collect_and_check_dimensions(input_: ts.TypeSpec) -> list[common.Dimension]: +def _collect_and_check_dimensions(input_: ts.TypeSpec) -> list[common.DimensionRef]: """ Extracts dimensions from non-zero-dimensional field inputs and ensures they match. """ @@ -405,15 +405,17 @@ def _canonicalize_nb_fields( Transform neighbor / sparse field type by removal of local dimension and addition of corresponding `ListType` dtype. Examples: + >>> class Vertex(common.DimensionIndex): ... + >>> class V2E(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... >>> input_field = ts.FieldType( ... dims=[ - ... common.Dimension(value="Vertex"), - ... common.Dimension(value="V2E", kind=common.DimensionKind.LOCAL), + ... Vertex, + ... V2E, ... ], ... dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64), ... ) >>> _canonicalize_nb_fields(input_field) - FieldType(dims=[Dimension(value='Vertex', kind=)], dtype=ListType(element_type=ScalarType(kind=, shape=None), offset_type=Dimension(value='V2E', kind=))) + FieldType(dims=[DimensionRef(gt4py.next.iterator.type_system.type_synthesizer:Vertex, horizontal)], dtype=ListType(element_type=ScalarType(kind=, shape=None), offset_type=DimensionRef(gt4py.next.iterator.type_system.type_synthesizer:V2E, local))) """ match input_: case tuple() | ts.TupleType(): @@ -447,10 +449,10 @@ def _canonicalize_nb_fields( def _resolve_dimensions( - input_dims: list[common.Dimension], + input_dims: list[common.DimensionRef], shift_tuple: tuple[itir.OffsetLiteral | itir.CartesianOffset, ...], offset_provider_type: common.OffsetProviderType, -) -> list[common.Dimension]: +) -> list[common.DimensionRef]: """ Resolves the final dimensions by applying shifts from the given shift tuple. @@ -474,12 +476,12 @@ def _resolve_dimensions( tells you the dimensions of the field returned by the `as_fieldop`, in this case `[Vertex, K]`. - >>> Edge = common.Dimension(value="Edge") - >>> Vertex = common.Dimension(value="Vertex") - >>> Cell = common.Dimension(value="Cell") - >>> K = common.Dimension(value="K", kind=common.DimensionKind.VERTICAL) - >>> V2E = common.Dimension(value="V2E") - >>> C2V = common.Dimension(value="C2V") + >>> class Edge(common.DimensionIndex): ... + >>> class Vertex(common.DimensionIndex): ... + >>> class Cell(common.DimensionIndex): ... + >>> class K(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + >>> class V2E(common.DimensionIndex): ... + >>> class C2V(common.DimensionIndex): ... >>> input_dims = [Edge, K] >>> shift_tuple = ( ... itir.OffsetLiteral(value="C2V"), @@ -503,12 +505,14 @@ def _resolve_dimensions( ... max_neighbors=4, ... ), ... } - >>> _resolve_dimensions(input_dims, shift_tuple, offset_provider_type) - [Dimension(value='Cell', kind=), Dimension(value='K', kind=)] + >>> _resolve_dimensions( + ... common.dimension_refs(input_dims), shift_tuple, offset_provider_type + ... ) + [DimensionRef(gt4py.next.iterator.type_system.type_synthesizer:Cell, horizontal), DimensionRef(gt4py.next.iterator.type_system.type_synthesizer:K, vertical, cartesian_axis)] >>> from gt4py.next.iterator.ir_utils import ir_makers as im - >>> IDim = common.Dimension(value="IDim") + >>> class IDim(common.CartesianAxisIndex): ... >>> IHalfDim = common.flip_staggered(IDim) - >>> JDim = common.Dimension(value="JDim") + >>> class JDim(common.CartesianAxisIndex): ... >>> JHalfDim = common.flip_staggered(JDim) >>> input_dims = [IDim, JDim] >>> shift_tuple = ( @@ -523,8 +527,10 @@ def _resolve_dimensions( ... ), ... itir.OffsetLiteral(value=0), ... ) - >>> _resolve_dimensions(input_dims, shift_tuple, offset_provider_type) - [Dimension(value='JDim', kind=), Dimension(value='IDim', kind=)] + >>> _resolve_dimensions( + ... common.dimension_refs(input_dims), shift_tuple, offset_provider_type + ... ) + [DimensionRef(gt4py.next.iterator.type_system.type_synthesizer:JDim, horizontal, cartesian_axis), DimensionRef(gt4py.next.iterator.type_system.type_synthesizer:IDim, horizontal, cartesian_axis)] """ resolved_dims = [] @@ -566,7 +572,7 @@ def applied_as_fieldop( # For each stencil parameter all locations it is `deref`ed on # see :func:`gt4py.next.iterator.transforms.trace_stencil`. shift_sequences_per_param: list[set[tuple[itir.OffsetLiteral, ...]]] | None, - scan_axis: common.Dimension | None = None, + scan_axis: common.DimensionRef | None = None, ) -> ts.FieldType | ts.TupleType | ts.DeferredType: if any( isinstance(el, ts.DeferredType) @@ -580,7 +586,7 @@ def applied_as_fieldop( if not domain: deduced_domain = None - output_dims: list[common.Dimension] = [] + output_dims: list[common.DimensionRef] = [] if offset_provider_type is not None and shift_sequences_per_param is not None: for field, shift_sequences in zip( new_fields, shift_sequences_per_param, strict=True @@ -595,7 +601,7 @@ def applied_as_fieldop( ), ) - assert all(isinstance(dim, common.Dimension) for dim in output_dims) + assert all(isinstance(dim, common.DimensionRef) for dim in output_dims) deduced_domain = ts.DomainType(dims=output_dims) if deduced_domain and scan_axis is not None: @@ -738,13 +744,13 @@ def apply_shift( assert isinstance(it, it_ts.IteratorType) if it.position_dims == "unknown": # nothing to do here return it - new_position_dims: list[common.Dimension] | str + new_position_dims: list[common.DimensionRef] | str if offset_provider_type: new_position_dims = [*it.position_dims] assert len(offset_literals) % 2 == 0 for offset_axis, _ in zip(offset_literals[:-1:2], offset_literals[1::2], strict=True): - source_dim: common.Dimension - target_dim: common.Dimension + source_dim: common.DimensionRef + target_dim: common.DimensionRef if isinstance(offset_axis, it_ts.CartesianOffsetType): source_dim, target_dim = offset_axis.domain, offset_axis.codomain else: diff --git a/src/gt4py/next/otf/arguments.py b/src/gt4py/next/otf/arguments.py index 5b825b7a05..8d796b1360 100644 --- a/src/gt4py/next/otf/arguments.py +++ b/src/gt4py/next/otf/arguments.py @@ -142,6 +142,11 @@ class CompileTimeArgs: # context would be `{"a": (FieldDomainDescriptor(...), None)}`. argument_descriptor_contexts: ArgStaticDescriptorsContextsByType + def __post_init__(self) -> None: + object.__setattr__( + self, "offset_provider", common.normalize_offset_provider(self.offset_provider) + ) + @property def offset_provider_type(self) -> common.OffsetProviderType: return common.offset_provider_to_type(self.offset_provider) diff --git a/src/gt4py/next/otf/artifacts.py b/src/gt4py/next/otf/artifacts.py index fa3226153b..a0ff2bd207 100644 --- a/src/gt4py/next/otf/artifacts.py +++ b/src/gt4py/next/otf/artifacts.py @@ -60,6 +60,9 @@ class SDFGCodeSpec(SourceCodeSpec): source_language: str = "SDFG" file_extension: str = "sdfg" + #: Offset-provider keys of the connectivity tables the SDFG takes as arguments, sorted. The + #: array names are mangled, so the bindings need the keys to look the tables up. + connectivity_keys: tuple[str, ...] = () @dataclasses.dataclass(frozen=True, kw_only=True) diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 4c524eedcd..565ceeaf05 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -211,7 +211,7 @@ def make_argument( source_buffer=name, dimensions=[ DimensionSpec( - name=dim.value, + name=common.codegen_name(dim.tag), static_stride=1 if ( unstructured_horizontal_has_unit_stride diff --git a/src/gt4py/next/otf/compiled_program.py b/src/gt4py/next/otf/compiled_program.py index c3fc14bd91..8888e913cb 100644 --- a/src/gt4py/next/otf/compiled_program.py +++ b/src/gt4py/next/otf/compiled_program.py @@ -399,6 +399,9 @@ def __call__( (defined by 'static_params') in case `enable_jit` is True. Otherwise, it is an error. """ + # NOTE: the one place keys of a class-keyed provider become tags, for calls and for + # `compile` alike (see `_compile_variant`), so both compute the same cache key. + offset_provider = common.normalize_offset_provider(offset_provider) canonical_args, canonical_kwargs = self._args_canonicalizer(*args, **kwargs) if (extractor := self._primitive_values_extractor) is not None: args, kwargs = extractor(*canonical_args, **canonical_kwargs) @@ -635,6 +638,7 @@ def _compile_variant( # key computed here call_key: CompiledProgramsKey | None = None, ) -> None: + offset_provider = common.normalize_offset_provider(offset_provider) # type: ignore[assignment] # same values if not common.is_offset_provider(offset_provider): if common.is_offset_provider_type(offset_provider): raise ValueError( diff --git a/src/gt4py/next/otf/runners.py b/src/gt4py/next/otf/runners.py index 1dfdb70eaa..2b04ea880b 100644 --- a/src/gt4py/next/otf/runners.py +++ b/src/gt4py/next/otf/runners.py @@ -13,6 +13,7 @@ import atexit import concurrent.futures import dataclasses +import io import multiprocessing import os import pathlib @@ -183,15 +184,50 @@ def _run_compilation_task_in_worker( return executor(compilable) +def _interactive_main_reference(obj: object) -> str | None: + """ + Return the name of a class from an interactive `__main__` that `obj` references, if any. + + A spawn worker re-imports a *script's* `__main__` (as `__mp_main__`), so classes declared + there resolve in the worker. An interactive `__main__` -- a notebook kernel, the REPL, + `python -c` -- has no `__file__` to re-import, so a class declared there pickles fine in the + parent (which has it) and then fails to unpickle in the worker. Dimensions are classes + identified by their qualified name (ADR 0030), which makes this the common case in + notebooks. + + Only scans when `__main__` is interactive, so ordinary scripts pay nothing. + """ + main = sys.modules.get("__main__") + if main is None or getattr(main, "__file__", None): + return None + found: list[str] = [] + + class _Scanner(pickle.Pickler): + # `reducer_override` is consulted for classes too, before the by-reference default + def reducer_override(self, o: object) -> Any: + if not found and isinstance(o, type) and o.__module__ == "__main__": + found.append(o.__qualname__) + return NotImplemented + + try: + _Scanner(io.BytesIO()).dump(obj) + except Exception: + # An object that cannot be pickled at all: not this check's business. It surfaces when + # the pool pickles the task, which is where an unpicklable job is reported. + return None + return found[0] if found else None + + class ProcessRunner: """Compiles in a ``ProcessPoolExecutor`` (``spawn``). The worker runs the task's executor (post-lowering compile) and returns the picklable ``CompilationArtifact``. - Tasks that cannot be offloaded — a known ``no_offload_reason`` or an executor - that stdlib ``pickle`` cannot serialize — are compiled in the calling thread - instead (with a warning), so they behave as under ``SerialRunner``. + Tasks that cannot be offloaded — a known ``no_offload_reason``, an executor + that stdlib ``pickle`` cannot serialize, or a reference to a class declared in an + interactive ``__main__`` — are compiled in the calling thread instead (with a + warning), so they behave as under ``SerialRunner``. """ def __init__(self, max_workers: int, shared_session_cache_dir: str) -> None: @@ -221,7 +257,15 @@ def submit( executor_blob = pickle.dumps(task.executor) except Exception as error: # pickling arbitrary object graphs raises arbitrary errors reason = f"its executor is not picklable ({error!s})" - if executor_blob is None: + if ( + reason is None + and (name := _interactive_main_reference((task.executor, task.compilable))) is not None + ): + reason = ( + f"it references '{name}', declared in an interactive '__main__' (a notebook, the" + " REPL or 'python -c'), which a worker process cannot import" + ) + if reason is not None: warnings.warn( f"Compiling '{task.name}' in the calling thread instead of a worker process " f"because {reason}.", @@ -229,6 +273,7 @@ def submit( ) return _run_in_calling_thread(task) + assert executor_blob is not None # set whenever no reason to fall back was found try: compilable_blob = pickle.dumps(task.compilable) except Exception as error: # pickling arbitrary object graphs raises arbitrary errors diff --git a/src/gt4py/next/program_processors/codegens/gtfn/codegen.py b/src/gt4py/next/program_processors/codegens/gtfn/codegen.py index 3c7750184c..2647165b63 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/codegen.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/codegen.py @@ -117,7 +117,8 @@ def visit_Literal(self, node: gtfn_ir.Literal, **kwargs: Any) -> str: case "bool": return node.value.lower() case "axis_literal": - return node.value + # a qualified tag names a `generated::_t` tag type: mangle it as declared + return common.codegen_name(node.value) case _: # TODO(tehrengruber): we should probably shouldn't just allow anything here. Revisit. return node.value @@ -145,7 +146,9 @@ def visit_TaggedValues(self, node: gtfn_ir.TaggedValues, **kwargs: Any) -> str: ) def visit_OffsetLiteral(self, node: gtfn_ir.OffsetLiteral, **kwargs: Any) -> str: - return node.value if isinstance(node.value, str) else f"{node.value}_c" + # NOTE: a string offset literal names a tag type declared as `generated::_t`, so + # it must be mangled exactly as the declaration was (see `common.codegen_name`). + return common.codegen_name(node.value) if isinstance(node.value, str) else f"{node.value}_c" SidComposite = as_mako( "::gridtools::sid::composite::keys<${','.join(f'::gridtools::integral_constant' for i in range(len(values)))}>::make_values(${','.join(values)})" diff --git a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py index 2ec88d7bb5..8193979b13 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -66,9 +66,17 @@ class GTFNTranslationStep( # No default: the device must agree with the other steps of the pipeline, so # forgetting to pass it must fail instead of silently targeting the CPU. device_type: core_defs.DeviceType = dataclasses.field(kw_only=True) + #: Keyed by dimension (class, ref or tag); normalized to tags. symbolic_domain_sizes: dict[str, itir.Expr] | None = None use_max_domain_range_on_unstructured_shift: bool | None = None + def __post_init__(self) -> None: + object.__setattr__( + self, + "symbolic_domain_sizes", + common.normalize_symbolic_domain_sizes(self.symbolic_domain_sizes), + ) + def _default_code_spec(self) -> artifacts.HeaderAndSourceCodeSpec: match self.device_type: case core_defs.DeviceType.CUDA: @@ -105,11 +113,13 @@ def _process_regular_arguments( or dim.kind is common.DimensionKind.LOCAL ): # translate sparse dimensions to tuple dtype - dim_name = dim.value + # NOTE: the tag is the offset-provider key, and its mangled form names the + # `generated::_t` tag type. A legacy `FieldOffset` carries it as `value`. + dim_name = dim.value if isinstance(dim, fbuiltins.FieldOffset) else dim.tag connectivity = common.get_offset_type(offset_provider_type, dim_name) assert isinstance(connectivity, common.NeighborConnectivityType) size = connectivity.max_neighbors - arg = f"gridtools::sid::dimension_to_tuple_like({arg})" + arg = f"gridtools::sid::dimension_to_tuple_like({arg})" arg_exprs.append(arg) return parameters, arg_exprs @@ -126,10 +136,16 @@ def _process_connectivity_args( "Neighbor table indices must be of type 'np.int32' or 'np.int64'." ) + # NOTE: `name` is the offset-provider key, a qualified tag, so every identifier + # derived from it is mangled -- and identically, since the parameter name is + # referenced below and the `generated::_t` tag type is declared elsewhere. + cname = common.codegen_name(name) + param_name = GENERATED_CONNECTIVITY_PARAM_PREFIX + cname + # parameter parameters.append( interface.Parameter( - name=GENERATED_CONNECTIVITY_PARAM_PREFIX + name.lower(), + name=param_name, type_=ts.FieldType( dims=list(connectivity_type.domain), dtype=type_translation.from_dtype(connectivity_type.dtype), @@ -140,13 +156,13 @@ def _process_connectivity_args( # connectivity argument expression nbtbl = ( f"gridtools::fn::sid_neighbor_table::as_neighbor_table<" - f"generated::{connectivity_type.domain[0].value}_t, " - f"generated::{connectivity_type.domain[1].value}_t, " + f"generated::{common.codegen_name(connectivity_type.domain[0].tag)}_t, " + f"generated::{common.codegen_name(connectivity_type.domain[1].tag)}_t, " f"{connectivity_type.max_neighbors}" - f">(std::forward({GENERATED_CONNECTIVITY_PARAM_PREFIX}{name.lower()}))" + f">(std::forward({param_name}))" ) arg_exprs.append( - f"gridtools::hymap::keys::make_values({nbtbl})" + f"gridtools::hymap::keys::make_values({nbtbl})" ) else: raise AssertionError( diff --git a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py index 9604dca506..592fc277b6 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py @@ -81,14 +81,14 @@ def _is_tuple_of_ref_or_literal(expr: itir.Expr) -> bool: return False -def _dimension_tag(dim: common.Dimension, grid_type: common.GridType) -> TagDefinition: +def _dimension_tag(dim: common.DimensionRef, grid_type: common.GridType) -> TagDefinition: alias = None if grid_type == common.GridType.UNSTRUCTURED: alias = { common.DimensionKind.HORIZONTAL: _horizontal_dimension, common.DimensionKind.VERTICAL: _vertical_dimension, }.get(dim.kind) - return TagDefinition(name=Sym(id=dim.value), alias=alias) + return TagDefinition(name=Sym(id=common.codegen_name(dim.tag)), alias=alias) def _collect_tag_definitions( @@ -97,7 +97,7 @@ def _collect_tag_definitions( offset_provider_type: common.OffsetProviderType, ) -> dict[str, TagDefinition]: """Collect dimension and offset tags from parameters, domains, shifts and connectivities.""" - dims: OrderedSet[common.Dimension] = OrderedSet() + dims: OrderedSet[common.DimensionRef] = OrderedSet() for param in node.params: if param.type is not None: for type_ in type_info.primitive_constituents(param.type): @@ -113,23 +113,43 @@ def _collect_tag_definitions( assert isinstance(connectivity_type, common.NeighborConnectivityType) dims.update([*connectivity_type.domain, connectivity_type.codomain]) return { - **{dim.value: _dimension_tag(dim, grid_type) for dim in dims}, - **{name: TagDefinition(name=Sym(id=name)) for name in offset_provider_type}, + **{dim.tag: _dimension_tag(dim, grid_type) for dim in dims}, + **{ + name: TagDefinition(name=Sym(id=common.codegen_name(name))) + for name in offset_provider_type + }, } +def _collect_staggered_bases(node: itir.Program) -> dict[str, str]: + """Map the tag of every staggered dimension in `node` to the tag of its base.""" + refs: set[common.DimensionRef] = { + axis.dim for axis in node.walk_values().if_isinstance(itir.AxisLiteral) + } + for param in node.params: + if param.type is not None: + for type_ in type_info.primitive_constituents(param.type): + if isinstance(type_, ts.FieldType): + refs.update(type_.dims) + return {ref.tag: ref.base.tag for ref in refs if ref.base is not None} + + def _add_staggered_aliases( - offset_definitions: dict[str, TagDefinition], + offset_definitions: dict[str, TagDefinition], staggered_bases: dict[str, str] ) -> dict[str, TagDefinition]: """Turn every staggered dimension tag into a alias of its base dimension.""" result: dict[str, TagDefinition] = {} aliases: dict[str, TagDefinition] = {} for name, tag_def in offset_definitions.items(): - if tag_def.alias is None and common.is_staggered(common.Dimension(value=name)): - base_name = common.as_non_staggered(common.Dimension(value=name)).value + # NOTE: this dict mixes dimension tags with offset tags; only dimension refs found in + # the program (which carry their staggered base) are looked up. + if tag_def.alias is None and (base_name := staggered_bases.get(name)) is not None: # ensure the base tag exists (as alias target and loop dimension) in this position - result.setdefault(base_name, TagDefinition(name=Sym(id=base_name))) - aliases[name] = TagDefinition(name=Sym(id=name), alias=SymRef(id=base_name)) + result.setdefault(base_name, TagDefinition(name=Sym(id=common.codegen_name(base_name)))) + aliases[name] = TagDefinition( + name=Sym(id=common.codegen_name(name)), + alias=SymRef(id=common.codegen_name(base_name)), + ) else: result[name] = tag_def return {**result, **aliases} @@ -157,11 +177,16 @@ def visit_FunCall(self, node: itir.FunCall) -> itir.FunCall: assert isinstance(node.args[0], itir.FunCall) first_axis_literal = node.args[0].args[0] assert isinstance(first_axis_literal, itir.AxisLiteral) - if first_axis_literal.kind == itir.DimensionKind.VERTICAL: + if ir_utils_misc.dim_from_axis_literal(first_axis_literal).kind == ( + itir.DimensionKind.VERTICAL + ): assert len(node.args) == 2 assert isinstance(node.args[1], itir.FunCall) assert isinstance(node.args[1].args[0], itir.AxisLiteral) - assert node.args[1].args[0].kind == itir.DimensionKind.HORIZONTAL + assert ( + ir_utils_misc.dim_from_axis_literal(node.args[1].args[0]).kind + == itir.DimensionKind.HORIZONTAL + ) return itir.FunCall(fun=node.fun, args=[node.args[1], node.args[0]]) return node @@ -317,7 +342,7 @@ def visit_CartesianOffset(self, node: itir.CartesianOffset, **kwargs: Any) -> Li def visit_AxisLiteral(self, node: itir.AxisLiteral, **kwargs: Any) -> Literal: assert isinstance(node.type, ts.DimensionType) - return Literal(value=node.type.dim.value, type="axis_literal") + return Literal(value=node.type.dim.tag, type="axis_literal") def _make_domain(self, node: itir.FunCall) -> tuple[TaggedValues, TaggedValues]: tags = [] @@ -402,7 +427,9 @@ def _visit_unstructured_domain(self, node: itir.FunCall, **kwargs: Any) -> Node: common.get_offset_type(self.offset_provider_type, o), common.NeighborConnectivityType, ): - connectivities.append(SymRef(id=o)) + # `o` is an offset-provider key, i.e. a qualified tag: mangle it exactly as + # its `TagDefinition` was, or the reference names an undeclared tag type. + connectivities.append(SymRef(id=common.codegen_name(o))) return UnstructuredDomain( tagged_sizes=sizes, tagged_offsets=domain_offsets, connectivities=connectivities ) @@ -590,7 +617,8 @@ def convert_el_to_sid(el_expr: Expr, el_type: ts.ScalarType | ts.FieldType) -> E backend=backend, scans=[scan], args=[self._visit_output_argument(node.target), *lowered_inputs], - axis=SymRef(id=axis.value), + # the scan axis names its `generated::_t` tag type: mangle as declared + axis=SymRef(id=common.codegen_name(axis.value)), ) assert projector is None # only scans have projectors return StencilExecution( @@ -611,7 +639,8 @@ def visit_Program(self, node: itir.Program, **kwargs: Any) -> Program: executions = self._merge_scans(executions) function_definitions = self.visit(node.function_definitions) + extracted_functions offset_definitions = _add_staggered_aliases( - _collect_tag_definitions(node, self.grid_type, self.offset_provider_type) + _collect_tag_definitions(node, self.grid_type, self.offset_provider_type), + _collect_staggered_bases(node), ) return Program( id=SymbolName(node.id), diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py b/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py index b96538a0c1..326a8ce966 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py @@ -9,6 +9,7 @@ from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg import lower_program_to_sdfg from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_utils import ( + as_map_variable, flatten_tuple_fields, get_map_variable, safe_replace_symbolic, @@ -16,6 +17,7 @@ __all__ = [ + "as_map_variable", "flatten_tuple_fields", "get_map_variable", "lower_program_to_sdfg", diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_domain.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_domain.py index a4f001d7ae..9bd2e53c06 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_domain.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_domain.py @@ -33,7 +33,7 @@ class FieldopDomainRange: stop: symbolic expression for upper bound (exclusive) """ - dim: gtx_common.Dimension + dim: gtx_common.DimensionRef start: dace.symbolic.SymbolicType stop: dace.symbolic.SymbolicType @@ -85,7 +85,7 @@ def visit_FunCall(self, node: gtir.FunCall) -> TargetDomain: def get_element_subset( - dims: Sequence[gtx_common.Dimension], origin: Optional[Sequence[dace.symbolic.SymExpr]] + dims: Sequence[gtx_common.DimensionRef], origin: Optional[Sequence[dace.symbolic.SymExpr]] ) -> dace_subsets.Range: """ Helper function to construct the Memlet subset to access an element in the field @@ -114,7 +114,7 @@ def get_element_subset( def get_field_layout( field_domain: FieldopDomain, -) -> tuple[list[gtx_common.Dimension], list[dace.symbolic.SymExpr], list[dace.symbolic.SymExpr]]: +) -> tuple[list[gtx_common.DimensionRef], list[dace.symbolic.SymExpr], list[dace.symbolic.SymExpr]]: """ Parse the field operator domain and generate the shape of the result field. diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_python_codegen.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_python_codegen.py index 173d3a246c..6326351e23 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_python_codegen.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_python_codegen.py @@ -15,6 +15,7 @@ from gt4py.eve import codegen from gt4py.eve.codegen import FormatTemplate as as_fmt +from gt4py.next import common as gtx_common from gt4py.next.iterator import builtins, ir as gtir from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm @@ -135,7 +136,10 @@ class PythonCodegen(codegen.TemplatedGenerator): Literal = as_fmt("{value}") def visit_AxisLiteral(self, node: gtir.AxisLiteral, **kwargs: Any) -> str: - return node.value + # NOTE: mangled, because the result becomes part of a DaCe symbol name. A qualified tag + # there contains dots, which DaCe re-parses as attribute access, leaving plain sympy + # symbols (with no `dtype`) among an array's free symbols. + return gtx_common.codegen_name(node.value) def visit_FunCall(self, node: gtir.FunCall, args_map: dict[str, gtir.Node]) -> str: if cpm.is_let(node): diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index 748172444f..26a0d023c3 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -568,7 +568,7 @@ def make_field( # the local dimension is converted into `ListType` data element if not isinstance(data_type.dtype, ts.ScalarType): raise ValueError(f"Invalid field type {data_type}.") - if not gtx_common.has_offset(self.offset_provider_type, local_dim.value): + if not gtx_common.has_offset(self.offset_provider_type, local_dim.tag): raise ValueError( f"The provided local dimension {local_dim} does not match any offset provider type." ) @@ -808,7 +808,7 @@ def unique_lib_node_name(self, lib_node_type: str) -> str: return f"{next(self.uids[lib_node_type])}" def _make_array_shape_and_strides( - self, name: str, dims: Sequence[gtx_common.Dimension] + self, name: str, dims: Sequence[gtx_common.DimensionRef] ) -> tuple[list[dace.symbolic.SymbolicType], list[dace.symbolic.SymbolicType]]: """ Parse field dimensions and allocate symbols for array shape and strides. @@ -829,7 +829,7 @@ def _make_array_shape_and_strides( for dim in dims: if dim.kind == gtx_common.DimensionKind.LOCAL: # for local dimension, the size is taken from the associated connectivity type - shape.append(neighbor_table_types[dim.value].max_neighbors) + shape.append(neighbor_table_types[dim.tag].max_neighbors) elif gtx_dace_args.is_connectivity_identifier(name, self.offset_provider_type): # we use symbolic size for the global dimension of a connectivity shape.append(gtx_dace_args.field_size_symbol(name, dim, neighbor_table_types)) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py index e904ff4c1b..6a3786738f 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py @@ -41,7 +41,7 @@ def _translate_concat_where_branch( sdfg_builder: gtir_to_sdfg.SDFGBuilder, source_expr: gtir.Expr, is_lower: bool, - concat_dim: gtx_common.Dimension, + concat_dim: gtx_common.DimensionRef, concat_dim_bound_expr: gtir.Expr, output_domain: domain_utils.SymbolicDomain, output_type: ts.FieldType, @@ -259,7 +259,7 @@ def translate_concat_where( local_dim = node.type.dtype.offset_type assert local_dim is not None dtype = gtx_dace_args.as_dace_type(node.type.dtype.element_type) - offset_provider_type = sdfg_builder.get_offset_provider_type(local_dim.value) + offset_provider_type = sdfg_builder.get_offset_provider_type(local_dim.tag) assert isinstance(offset_provider_type, gtx_common.NeighborConnectivityType) local_idx = gtx_common.order_dimensions([*output_dims, local_dim]).index(local_dim) output_shape.insert(local_idx, offset_provider_type.max_neighbors) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py index 659815204c..18af996638 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py @@ -96,7 +96,7 @@ def _create_field_operator_impl( output_domain: infer_domain.NonTupleDomainAccess, output_type: ts.FieldType, map_exit: dace_nodes.MapExit | None, - inner_dims: Sequence[gtx_common.Dimension], + inner_dims: Sequence[gtx_common.DimensionRef], is_zero_dim: bool, ) -> gtir_to_sdfg_types.FieldopData | None: """ @@ -228,7 +228,7 @@ def create_field_operator( input_edges: Iterable[gtir_to_sdfg_lambda.DataflowInputEdge], output: MaybeNestedInTuple[gtir_to_sdfg_lambda.DataflowOutputEdge | None], output_domain: infer_domain.DomainAccess, - inner_dims: Sequence[gtx_common.Dimension] = (), + inner_dims: Sequence[gtx_common.DimensionRef] = (), ) -> gtir_to_sdfg_types.FieldopResult: """ Helper method to build the output of a field operator, which can consist of diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index d432193523..c6fac4c861 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -34,7 +34,7 @@ from gt4py import eve from gt4py.eve.xtyping import MaybeNestedInTuple, NestedTuple from gt4py.next import common as gtx_common, utils as gtx_utils -from gt4py.next.iterator import ir as gtir +from gt4py.next.iterator import builtins as gtir_builtins, ir as gtir from gt4py.next.iterator.ir_utils import ( common_pattern_matcher as cpm, ir_makers as im, @@ -58,10 +58,6 @@ ) -# Magic local dimension used for list of values with length known at compile-time. -_CONST_DIM: Final = gtx_common.Dimension(value="_CONST_DIM", kind=gtx_common.DimensionKind.LOCAL) - - @dataclasses.dataclass(frozen=True) class ValueExpr: """ @@ -143,8 +139,8 @@ class IteratorExpr: field: dace_nodes.AccessNode gt_dtype: ts.ListType | ts.ScalarType - field_domain: list[tuple[gtx_common.Dimension, dace.symbolic.SymbolicType]] - indices: dict[gtx_common.Dimension, DataExpr] + field_domain: list[tuple[gtx_common.DimensionRef, dace.symbolic.SymbolicType]] + indices: dict[gtx_common.DimensionRef, DataExpr] def __post_init__(self) -> None: gtx_common.check_dims([dim for dim, _ in self.field_domain]) @@ -166,7 +162,7 @@ def get_memlet_subset(self, sdfg: dace.SDFG) -> dace_subsets.Range: field_desc = self.field.desc(sdfg) if isinstance(self.gt_dtype, ts.ListType): assert len(field_desc.shape) == len(self.field_domain) + 1 - local_dim: gtx_common.Dimension = self.gt_dtype.offset_type # type: ignore[assignment] # checked in __post_init__ + local_dim: gtx_common.DimensionRef = self.gt_dtype.offset_type # type: ignore[assignment] # checked in __post_init__ # construct the full subset according to the canonical field domain sorted_dims = gtx_common.order_dimensions( [dim for dim, _ in self.field_domain] + [local_dim] @@ -592,7 +588,7 @@ def _construct_tasklet_result( return ValueExpr( dc_node=temp_node, gt_dtype=( - ts.ListType(element_type=data_type, offset_type=_CONST_DIM) + ts.ListType(element_type=data_type, offset_type=gtir_builtins.ConstList) if use_array else data_type ), @@ -652,7 +648,7 @@ def _visit_deref(self, node: gtir.FunCall) -> DataExpr: assert len(field_desc.shape) == len(arg_expr.field_domain) field_indices = [(dim, arg_expr.indices[dim]) for dim, _ in arg_expr.field_domain] index_connectors = [ - IndexConnectorFmt.format(dim=dim.value) + IndexConnectorFmt.format(dim=gtx_common.codegen_name(dim.tag)) for dim, index in field_indices if not isinstance(index, SymbolExpr) ] @@ -662,7 +658,7 @@ def _visit_deref(self, node: gtir.FunCall) -> DataExpr: index_internals = ",".join( str(index.value - offset) if isinstance(index := arg_expr.indices[dim], SymbolExpr) - else f"{IndexConnectorFmt.format(dim=dim.value)} - {offset}" + else f"{IndexConnectorFmt.format(dim=gtx_common.codegen_name(dim.tag))} - {offset}" for (dim, offset) in arg_expr.field_domain ) deref_node, connector_mapping = self._add_tasklet( @@ -681,7 +677,7 @@ def _visit_deref(self, node: gtir.FunCall) -> DataExpr: # add termination points for the dynamic iterator indices for dim, index_expr in field_indices: - index_connector = IndexConnectorFmt.format(dim=dim.value) + index_connector = IndexConnectorFmt.format(dim=gtx_common.codegen_name(dim.tag)) if isinstance(index_expr, MemletExpr): self._add_input_data_edge( index_expr.dc_node, @@ -1117,7 +1113,8 @@ def _visit_neighbors(self, node: gtir.FunCall) -> ValueExpr: gt_field=ts.FieldType( dims=[conn_type.domain[0]], dtype=ts.ListType( - element_type=tt.from_dtype(conn_type.dtype), offset_type=_CONST_DIM + element_type=tt.from_dtype(conn_type.dtype), + offset_type=gtir_builtins.ConstList, ), ), subset=dace_subsets.Range.from_string( @@ -1130,7 +1127,8 @@ def _visit_neighbors(self, node: gtir.FunCall) -> ValueExpr: self.sdfg, (conn_type.max_neighbors,), field_desc.dtype ) neighbors_node = self.state.add_access(neighbors_temp) - offset_type = gtx_common.Dimension(offset, gtx_common.DimensionKind.LOCAL) + # the connectivity's own local dimension: an offset tag does not name a dimension + offset_type = conn_type.neighbor_dim neighbor_idx = gtir_to_sdfg_utils.get_map_variable(offset_type) index_connector = "__index" @@ -1160,7 +1158,7 @@ def _visit_neighbors(self, node: gtir.FunCall) -> ValueExpr: ) self._add_mapped_tasklet( - name=f"{offset}_neighbors", + name=f"{gtx_common.codegen_name(offset)}_neighbors", map_ranges={neighbor_idx: f"0:{conn_type.max_neighbors}"}, code=tasklet_expression, inputs=input_memlets, @@ -1187,8 +1185,8 @@ def _visit_list_get(self, node: gtir.FunCall) -> ValueExpr: assert len(src_desc.shape) == len(src_arg.subset) src_subset = src_arg.subset local_dim = src_arg.gt_dtype.offset_type - all_dims = gtx_common.order_dimensions([*src_arg.gt_field.dims, local_dim]) # type: ignore[list-item] # checked in MemletExpr.__post_init__ - local_dim_index = all_dims.index(local_dim) # type: ignore[arg-type] # checked in MemletExpr.__post_init__ + all_dims = gtx_common.order_dimensions([*src_arg.gt_field.dims, local_dim]) # type: ignore[type-var] # checked in MemletExpr.__post_init__ + local_dim_index = all_dims.index(local_dim) elif isinstance(src_arg, ValueExpr): assert len(src_desc.shape) == 1 src_subset = dace_subsets.Range.from_array(src_desc) @@ -1284,15 +1282,15 @@ def _visit_map(self, node: gtir.FunCall) -> ValueExpr: tasklet_expression = f"{output_connector} = {fun_python_code}" input_args = [self.visit(arg) for arg in node.args] - input_conn_types: dict[gtx_common.Dimension, gtx_common.NeighborConnectivityType] = {} + input_conn_types: dict[gtx_common.DimensionRef, gtx_common.NeighborConnectivityType] = {} for input_arg in input_args: assert isinstance(input_arg.gt_dtype, ts.ListType) assert input_arg.gt_dtype.offset_type is not None offset_type = input_arg.gt_dtype.offset_type - if offset_type == _CONST_DIM: + if offset_type == gtx_common.dimension_ref(gtir_builtins.ConstList): # this input argument is the result of `make_const_list` continue - offset_provider_t = self.subgraph_builder.get_offset_provider_type(offset_type.value) + offset_provider_t = self.subgraph_builder.get_offset_provider_type(offset_type.tag) assert isinstance(offset_provider_t, gtx_common.NeighborConnectivityType) input_conn_types[offset_type] = offset_provider_t @@ -1330,7 +1328,9 @@ def _visit_map(self, node: gtir.FunCall) -> ValueExpr: raise ValueError(f"More than one local dimension in map expression {node}.") input_size = input_desc.shape[0] if input_size == 1: - assert input_arg.gt_dtype.offset_type == _CONST_DIM + assert input_arg.gt_dtype.offset_type == gtx_common.dimension_ref( + gtir_builtins.ConstList + ) input_memlets[conn] = dace.Memlet(data=input_node.data, subset="0") elif input_size == local_size: input_memlets[conn] = dace.Memlet(data=input_node.data, subset=map_index) @@ -1346,7 +1346,7 @@ def _visit_map(self, node: gtir.FunCall) -> ValueExpr: if conn_type.has_skip_values: # In case the `map_list` input expressions contain skip values, we use # the connectivity-based offset provider as mask for map computation. - conn_data = gtx_dace_args.connectivity_identifier(offset_type.value) + conn_data = gtx_dace_args.connectivity_identifier(offset_type.tag) conn_desc = self.sdfg.arrays[conn_data] conn_desc.transient = False @@ -1361,7 +1361,8 @@ def _visit_map(self, node: gtir.FunCall) -> ValueExpr: gt_field=ts.FieldType( dims=[conn_type.domain[0]], dtype=ts.ListType( - element_type=tt.from_dtype(conn_type.dtype), offset_type=_CONST_DIM + element_type=tt.from_dtype(conn_type.dtype), + offset_type=gtir_builtins.ConstList, ), ), subset=dace_subsets.Range.from_string( @@ -1408,7 +1409,7 @@ def _broadcast_const_list( ) -> ValueExpr: assert list_type.offset_type is not None offset_provider_t = self.subgraph_builder.get_offset_provider_type( - list_type.offset_type.value + list_type.offset_type.tag ) assert isinstance(offset_provider_t, gtx_common.NeighborConnectivityType) local_size = offset_provider_t.max_neighbors @@ -1448,7 +1449,7 @@ def _visit_reduce(self, node: gtir.FunCall) -> ValueExpr: and input_expr.gt_dtype.offset_type is not None ) offset_type = input_expr.gt_dtype.offset_type - offset_provider_type = self.subgraph_builder.get_offset_provider_type(offset_type.value) + offset_provider_type = self.subgraph_builder.get_offset_provider_type(offset_type.tag) assert isinstance(offset_provider_type, gtx_common.NeighborConnectivityType) inp_conn = "_in" @@ -1460,7 +1461,7 @@ def _visit_reduce(self, node: gtir.FunCall) -> ValueExpr: and input_expr.gt_dtype.offset_type is not None ) offset_type = input_expr.gt_dtype.offset_type - connectivity = gtx_dace_args.connectivity_identifier(offset_type.value) + connectivity = gtx_dace_args.connectivity_identifier(offset_type.tag) self.sdfg.arrays[connectivity].transient = False reduce_node = gtx_library_nodes.ReduceWithSkipValues( @@ -1687,7 +1688,8 @@ def _make_unstructured_shift( gt_field=ts.FieldType( dims=[conn_type.source_dim], dtype=ts.ListType( - element_type=tt.from_dtype(conn_type.dtype), offset_type=_CONST_DIM + element_type=tt.from_dtype(conn_type.dtype), + offset_type=gtir_builtins.ConstList, ), ), subset=dace_subsets.Range.from_string( @@ -1892,7 +1894,7 @@ def _visit_Lambda_impl( and node.expr.type.offset_type is not None and isinstance(result, (MemletExpr, ValueExpr)) and isinstance(result.gt_dtype, ts.ListType) - and result.gt_dtype.offset_type == _CONST_DIM + and result.gt_dtype.offset_type == gtx_common.dimension_ref(gtir_builtins.ConstList) ): result = self._broadcast_const_list(result, node.expr.type) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py index 60a275abe3..7a0c354e4e 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py @@ -185,9 +185,7 @@ def _construct_if_branch_output( assert out_type.dtype.offset_type is not None assert isinstance(out_type.dtype.element_type, ts.ScalarType) dtype = gtx_dace_args.as_dace_type(out_type.dtype.element_type) - offset_provider_type = sdfg_builder.get_offset_provider_type( - out_type.dtype.offset_type.value - ) + offset_provider_type = sdfg_builder.get_offset_provider_type(out_type.dtype.offset_type.tag) assert isinstance(offset_provider_type, gtx_common.NeighborConnectivityType) shape = [*shape, offset_provider_type.max_neighbors] diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index de38900e6a..4e8e252b81 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -75,7 +75,7 @@ def _lower_lambda_to_nested_sdfg( lambda_params: Sequence[gtir.Sym], scan_forward: bool, scan_carry_symbol: gtir.Sym, - scan_dim: gtx_common.Dimension, + scan_dim: gtx_common.DimensionRef, ) -> tuple[gtir_to_sdfg.SubgraphContext, gtir_to_sdfg_types.FieldopResult]: """ Helper method to lower the lambda node representing the scan stencil dataflow @@ -162,7 +162,7 @@ def get_scan_output_shape( assert isinstance(scan_init_data.gt_type, ts.ListType) assert scan_init_data.gt_type.offset_type offset_type = scan_init_data.gt_type.offset_type - offset_provider_type = sdfg_builder.get_offset_provider_type(offset_type.value) + offset_provider_type = sdfg_builder.get_offset_provider_type(offset_type.tag) assert isinstance(offset_provider_type, gtx_common.NeighborConnectivityType) list_size = offset_provider_type.max_neighbors # The local (list) dimension of the scan result takes the position that @@ -329,7 +329,7 @@ def _handle_dataflow_result_of_nested_sdfg( outer_ctx: gtir_to_sdfg.SubgraphContext, inner_data: gtir_to_sdfg_types.FieldopData, output_domain: infer_domain.NonTupleDomainAccess, - scan_dim: gtx_common.Dimension, + scan_dim: gtx_common.DimensionRef, ) -> gtir_to_sdfg_lambda.DataflowOutputEdge | None: assert isinstance(inner_data.gt_type, ts.FieldType) inner_dataname = inner_data.dc_node.data diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_types.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_types.py index 47baf902ec..123d35cc31 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_types.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_types.py @@ -65,7 +65,7 @@ def get_local_view( ) if isinstance(self.gt_type, ts.FieldType): - it_indices: dict[gtx_common.Dimension, gtir_to_sdfg_lambda.DataExpr] + it_indices: dict[gtx_common.DimensionRef, gtir_to_sdfg_lambda.DataExpr] if isinstance(self.dc_node.desc(sdfg), dace.data.Scalar): assert len(self.gt_type.dims) == 0 # zero-dimensional field it_indices = {} diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py index 9b5fbdbbc2..b717bf74c8 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py @@ -49,7 +49,14 @@ def debug_info( return default -def get_map_variable(dim: gtx_common.Dimension) -> str: +def as_map_variable(param: gtx_common.DimensionLike | str) -> str: + """A map-parameter option (DaCe transformations): a dimension becomes its map variable.""" + if isinstance(param, (gtx_common.DimensionMeta, gtx_common.DimensionRef)): + return get_map_variable(param) + return param + + +def get_map_variable(dim: gtx_common.DimensionLike) -> str: """ Format map variable name based on the naming convention for application-specific SDFG transformations. """ @@ -59,7 +66,7 @@ def get_map_variable(dim: gtx_common.Dimension) -> str: # dimensions and decide whether two maps have the same iteration space. dim = gtx_common.as_non_staggered(dim) suffix = "dim" if dim.kind == gtx_common.DimensionKind.LOCAL else "" - return f"i_{dim.value}_gtx_{dim.kind}{suffix}" + return f"i_{gtx_common.codegen_name(dim.tag)}_gtx_{dim.kind}{suffix}" def make_tasklet_connector_for(name: str) -> str: diff --git a/src/gt4py/next/program_processors/runners/dace/sdfg_args.py b/src/gt4py/next/program_processors/runners/dace/sdfg_args.py index f33fbf8bb5..6f86d4ae1c 100644 --- a/src/gt4py/next/program_processors/runners/dace/sdfg_args.py +++ b/src/gt4py/next/program_processors/runners/dace/sdfg_args.py @@ -9,7 +9,7 @@ from __future__ import annotations import re -from typing import Final, Literal +from typing import Final, Literal, Optional import dace @@ -53,35 +53,46 @@ def as_itir_type(dtype: dace.typeclass) -> ts.ScalarType: return ts.ScalarType(kind) -def connectivity_identifier(name: str) -> str: - return f"{CONNECTIVITY_INDENTIFIER_PREFIX}{name}" +def connectivity_identifier(offset: str) -> str: + """Name of the SDFG array holding the connectivity of an offset-provider key.""" + return f"{CONNECTIVITY_INDENTIFIER_PREFIX}{gtx_common.codegen_name(offset)}" + + +def _connectivity_offset( + name: str, offset_provider_type: gtx_common.OffsetProviderType +) -> Optional[str]: + """The offset-provider key whose connectivity array is called `name`, if any.""" + if not name.startswith(CONNECTIVITY_INDENTIFIER_PREFIX): + return None + return next( + (offset for offset in offset_provider_type if connectivity_identifier(offset) == name), + None, + ) def is_connectivity_identifier( name: str, offset_provider_type: gtx_common.OffsetProviderType | None = None ) -> bool: - if (m := CONNECTIVITY_INDENTIFIER_RE.match(name)) is None: - return False - elif offset_provider_type is None: + if offset_provider_type is None: # If no offset provider type is provided, we assume there is a connectivity identifier # that matches the CONNECTIVITY_INDENTIFIER_RE. - return True - else: - return gtx_common.has_offset(offset_provider_type, m[1]) + return CONNECTIVITY_INDENTIFIER_RE.match(name) is not None + return _connectivity_offset(name, offset_provider_type) is not None def _field_symbol( field_name: str, - dim: gtx_common.Dimension, + dim: gtx_common.DimensionLike, sym: Literal["size", "stride"], offset_provider_type: gtx_common.OffsetProviderType | None, ) -> dace.symbol: - if (m := CONNECTIVITY_INDENTIFIER_RE.match(field_name)) is None: - name = f"__{field_name}_{dim.value}_{sym}" + dim = gtx_common.dimension_ref(dim) # a class or a ref + if CONNECTIVITY_INDENTIFIER_RE.match(field_name) is None: + name = f"__{field_name}_{gtx_common.codegen_name(dim.tag)}_{sym}" else: # a connectivity field assert offset_provider_type is not None - assert m[1] in offset_provider_type - offset = m[1] + offset = _connectivity_offset(field_name, offset_provider_type) + assert offset is not None conn_type = offset_provider_type[offset] assert isinstance(conn_type, gtx_common.NeighborConnectivityType) if dim == conn_type.source_dim: @@ -95,7 +106,7 @@ def _field_symbol( def field_size_symbol( field_name: str, - dim: gtx_common.Dimension, + dim: gtx_common.DimensionLike, offset_provider_type: gtx_common.OffsetProviderType, ) -> dace.symbol: return _field_symbol(field_name, dim, "size", offset_provider_type) @@ -103,28 +114,27 @@ def field_size_symbol( def field_stride_symbol( field_name: str, - dim: gtx_common.Dimension, + dim: gtx_common.DimensionLike, offset_provider_type: gtx_common.OffsetProviderType | None = None, ) -> dace.symbol: return _field_symbol(field_name, dim, "stride", offset_provider_type) -def _range_symbol_name(field_name: str, axis: str) -> str: +def _range_symbol_name(field_name: str, dim: gtx_common.DimensionLike) -> str: """Common part of the name for the range start/stop symbols.""" - dim = gtx_common.Dimension(axis) field_range = im.call("get_domain_range")(field_name, dim) return gtir_python_codegen.get_source(field_range) -def range_start_symbol(field_name: str, dim: gtx_common.Dimension) -> dace.symbol: +def range_start_symbol(field_name: str, dim: gtx_common.DimensionLike) -> dace.symbol: """Format name of the start symbol for domain range.""" - name = f"{_range_symbol_name(field_name, dim.value)}_0" + name = f"{_range_symbol_name(field_name, dim)}_0" return dace.symbol(name, FIELD_SYMBOL_DTYPE) -def range_stop_symbol(field_name: str, dim: gtx_common.Dimension) -> dace.symbol: +def range_stop_symbol(field_name: str, dim: gtx_common.DimensionLike) -> dace.symbol: """Format name of the stop symbol for domain range.""" - name = f"{_range_symbol_name(field_name, dim.value)}_1" + name = f"{_range_symbol_name(field_name, dim)}_1" return dace.symbol(name, FIELD_SYMBOL_DTYPE) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/loop_blocking.py b/src/gt4py/next/program_processors/runners/dace/transformations/loop_blocking.py index 21e08394ba..4559fc5c5f 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/loop_blocking.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/loop_blocking.py @@ -103,16 +103,21 @@ class LoopBlocking(dace_transformation.SingleStateTransformation): def __init__( self, blocking_size: Optional[int] = None, - blocking_parameters: Optional[Sequence[Union[gtx_common.Dimension, str]]] = None, + blocking_parameters: Optional[ + Union[gtx_common.DimensionLike, str, Sequence[Union[gtx_common.DimensionLike, str]]] + ] = None, require_independent_nodes: Optional[bool] = None, promote_independent_memlets: Optional[bool] = None, independent_node_threshold: Optional[int] = None, ) -> None: super().__init__() if blocking_parameters is not None: + if isinstance(blocking_parameters, (str, gtx_common.DimensionMeta)) or isinstance( + blocking_parameters, gtx_common.DimensionRef + ): + blocking_parameters = [blocking_parameters] self.blocking_parameters = [ - gtx_dace_lowering.get_map_variable(p) if isinstance(p, gtx_common.Dimension) else p - for p in blocking_parameters + gtx_dace_lowering.as_map_variable(p) for p in blocking_parameters ] else: self.blocking_parameters = None diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion_extended.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion_extended.py index fd87d8a9f8..27cff0268b 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion_extended.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion_extended.py @@ -189,7 +189,7 @@ def gt_vertical_map_split_fusion( validate_all: bool = False, allow_shared_output: bool = False, shared_output_data: Optional[Sequence[str]] = None, - shared_output_split_dimension: Optional[Union[gtx_common.Dimension, str]] = None, + shared_output_split_dimension: Optional[Union[gtx_common.DimensionLike, str]] = None, ) -> int: """Performs vertical map splitting on the provided SDFG. @@ -688,7 +688,7 @@ def __init__( fuse_map_fragments: Optional[bool] = None, allow_shared_output: Optional[bool] = None, shared_output_data: Optional[Sequence[str]] = None, - shared_output_split_dimension: Optional[Union[gtx_common.Dimension, str]] = None, + shared_output_split_dimension: Optional[Union[gtx_common.DimensionLike, str]] = None, single_use_data: Optional[dict[dace.SDFG, set[str]]] = None, consolidate_edges_only_if_not_extending: Optional[bool] = None, **kwargs: Any, @@ -710,7 +710,9 @@ def __init__( ) self._shared_output_split_parameter = ( gtx_dace_lowering.get_map_variable(shared_output_split_dimension) - if isinstance(shared_output_split_dimension, gtx_common.Dimension) + if isinstance( + shared_output_split_dimension, (gtx_common.DimensionMeta, gtx_common.DimensionRef) + ) else shared_output_split_dimension ) self._single_use_data = single_use_data @@ -1087,8 +1089,8 @@ def _restrict_fusion_to_newly_created_maps( def _check_shared_output_options( allow_shared_output: bool, shared_output_data: Optional[Sequence[str]], - split_dimension: Optional[Union[gtx_common.Dimension, str]], -) -> tuple[bool, Optional[Sequence[str]], Optional[Union[gtx_common.Dimension, str]]]: + split_dimension: Optional[Union[gtx_common.DimensionLike, str]], +) -> tuple[bool, Optional[Sequence[str]], Optional[Union[gtx_common.DimensionLike, str]]]: """Warn about inactive or empty shared-output selections.""" if not allow_shared_output and (shared_output_data is not None or split_dimension is not None): warnings.warn( diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py index 2f56671da8..90fb648b10 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py @@ -19,7 +19,7 @@ def gt_set_iteration_order( sdfg: dace.SDFG, unit_strides_dim: Optional[ - Union[str, gtx_common.Dimension, list[Union[str, gtx_common.Dimension]]] + Union[str, gtx_common.DimensionLike, list[Union[str, gtx_common.DimensionLike]]] ] = None, unit_strides_kind: Optional[gtx_common.DimensionKind] = None, validate: bool = True, @@ -115,7 +115,7 @@ class MapIterationOrder(dace_transformation.SingleStateTransformation): def __init__( self, unit_strides_dims: Optional[ - Union[str, gtx_common.Dimension, list[Union[str, gtx_common.Dimension]]] + Union[str, gtx_common.DimensionLike, list[Union[str, gtx_common.DimensionLike]]] ] = None, unit_strides_kind: Optional[gtx_common.DimensionKind] = None, *args: Any, @@ -125,12 +125,12 @@ def __init__( if unit_strides_dims is not None and unit_strides_kind is not None: raise ValueError("Specified both 'unit_strides_dims' and 'unit_strides_kind'.") elif unit_strides_dims is not None: - if isinstance(unit_strides_dims, (gtx_common.Dimension, str)): + if isinstance( + unit_strides_dims, (gtx_common.DimensionMeta, gtx_common.DimensionRef, str) + ): unit_strides_dims = [unit_strides_dims] self.unit_strides_dims = [ - unit_strides_dim - if isinstance(unit_strides_dim, str) - else gtx_dace_lowering.get_map_variable(unit_strides_dim) + gtx_dace_lowering.as_map_variable(unit_strides_dim) for unit_strides_dim in unit_strides_dims ] elif unit_strides_kind is not None: diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/bindings.py b/src/gt4py/next/program_processors/runners/dace/workflow/bindings.py index 82e6b3fc3c..a9bf48c26d 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/bindings.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/bindings.py @@ -8,11 +8,13 @@ from __future__ import annotations +from collections.abc import Sequence from typing import Final import dace from gt4py.eve import codegen +from gt4py.next import common as gtx_common from gt4py.next.otf import artifacts from gt4py.next.program_processors.runners.dace import ( sdfg_args as gtx_dace_args, @@ -194,20 +196,26 @@ def _parse_gt_param( def _parse_gt_connectivities( - code: codegen.TextBlock, sdfg_arglist: dict[str, dace.data.Data] + code: codegen.TextBlock, + sdfg_arglist: dict[str, dace.data.Data], + connectivity_keys: Sequence[str], ) -> None: + offsets = { + gtx_dace_args.connectivity_identifier(offset): offset for offset in connectivity_keys + } for sdfg_arg_index, (arg_name, arg_desc) in enumerate(sdfg_arglist.items()): if gtx_dace_args.is_connectivity_identifier(arg_name): + # a missed table would keep a stale pointer on fast-call, so fail instead + if (offset := offsets.get(arg_name)) is None: + raise ValueError(f"No offset-provider key for connectivity argument '{arg_name}'.") assert isinstance(arg_desc, dace.data.Array) assert len(arg_desc.shape) == 2 assert gtx_dace_utils.is_compile_time_size(arg_desc.shape[1]) origin_size_arg = arg_desc.shape[0] assert len(origin_size_arg.free_symbols) == 1 origin_size_param = next(iter(origin_size_arg.free_symbols)) - m = gtx_dace_args.CONNECTIVITY_INDENTIFIER_RE.match(arg_name) - assert m is not None - conn_arg = f"{_cb_neighbor_table}_{m[1]}" - code.append(f'{conn_arg} = {_cb_offset_provider}["{m[1]}"]') + conn_arg = f"{_cb_neighbor_table}_{gtx_common.codegen_name(offset)}" + code.append(f'{conn_arg} = {_cb_offset_provider}["{offset}"]') _update_sdfg_array_ptr(code, conn_arg, sdfg_arg_index) _parse_gt_param( # set the size in the horizontal dimension param_name=origin_size_param, @@ -283,7 +291,7 @@ def _create_sdfg_bindings( # where, due to limited lifetime of the fixtures, the connectivity fields # might get reallocated. In order to avoid problems, we update the connectivity # arrays as well in SDFG fastcall. - _parse_gt_connectivities(code, sdfg_arglist) + _parse_gt_connectivities(code, sdfg_arglist, program_source.code_spec.connectivity_keys) return artifacts.BindingSource(code.text, library_deps=tuple()) diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py index 76956e4579..62aab4fba4 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -521,6 +521,15 @@ def __call__( arg_types = inp.args.args + connectivity_keys = tuple( + sorted( + offset + for offset in inp.args.offset_provider + if (conn_id := gtx_dace_args.connectivity_identifier(offset)) in sdfg.arrays + and not sdfg.arrays[conn_id].transient + ) + ) + program_parameters = tuple( interface.Parameter(param.id, arg_type) for param, arg_type in zip(program.params, arg_types) @@ -530,6 +539,6 @@ def __call__( entry_point=interface.Function(program.id, program_parameters), source_code=gtx_wfdcommon.serialize_sdfg_as_json(sdfg), # type: ignore[arg-type] # The source code is typed as a `str`, but we assign a JSON dictionary. library_deps=tuple(), - code_spec=artifacts.SDFGCodeSpec(), + code_spec=artifacts.SDFGCodeSpec(connectivity_keys=connectivity_keys), ) return module diff --git a/src/gt4py/next/program_processors/runners/experimental/embedded.py b/src/gt4py/next/program_processors/runners/experimental/embedded.py index efa3c9e288..39071d7edd 100644 --- a/src/gt4py/next/program_processors/runners/experimental/embedded.py +++ b/src/gt4py/next/program_processors/runners/experimental/embedded.py @@ -87,6 +87,9 @@ def with_named_collections(**kwargs: Any) -> None: ) def call(*args: Any, **kwargs: Any) -> None: + if "offset_provider" in kwargs: + # before `wrap`: tracing compilers need string keys (a pytree's keys are sorted) + kwargs["offset_provider"] = common.normalize_offset_provider(kwargs["offset_provider"]) if not is_program: if "out" not in kwargs: raise errors.MissingArgumentError(None, "out", True) diff --git a/src/gt4py/next/program_processors/runners/roundtrip.py b/src/gt4py/next/program_processors/runners/roundtrip.py index d5384e1d2b..14ba89f485 100644 --- a/src/gt4py/next/program_processors/runners/roundtrip.py +++ b/src/gt4py/next/program_processors/runners/roundtrip.py @@ -14,7 +14,7 @@ import tempfile import textwrap import types -from collections.abc import Iterable +from collections.abc import Iterable, Mapping from typing import Any, Optional from gt4py.eve import codegen @@ -24,9 +24,11 @@ common, config, custom_layout_allocators as next_allocators, + utils, ) from gt4py.next.ffront import foast_to_gtir, foast_to_past, past_to_itir -from gt4py.next.iterator import ir as itir, transforms as itir_transforms +from gt4py.next.iterator import builtins, ir as itir, transforms as itir_transforms +from gt4py.next.iterator.ir_utils import misc as ir_misc from gt4py.next.otf import artifacts, stages, workflow from gt4py.next.type_system import type_info, type_specifications as ts @@ -60,11 +62,20 @@ def visit_Literal(self, node: itir.Literal, **kwargs: Any) -> str: return f"np.{dtype}(np.nan)" return node.value - OffsetLiteral = as_fmt("{value}") - AxisLiteral = as_fmt("{value}") + # NOTE: a tag is a qualified Python name, which is not a valid Python *identifier*, so the + # emitted program refers to each axis and offset through its mangled name. The header binds + # the names of the offsets, `_bind_dimensions` those of the axes. + def visit_OffsetLiteral(self, node: itir.OffsetLiteral, **kwargs: Any) -> str: + # an integer offset literal is a shift amount, not a name + return common.codegen_name(node.value) if isinstance(node.value, str) else str(node.value) + + def visit_AxisLiteral(self, node: itir.AxisLiteral, **kwargs: Any) -> str: + return common.codegen_name(node.value) def visit_CartesianOffset(self, node: itir.CartesianOffset, **kwargs: Any) -> str: - return f"gtx.CartesianConnectivity({node.domain.value}, codomain={node.codomain.value})" + domain = common.codegen_name(node.domain.value) + codomain = common.codegen_name(node.codomain.value) + return f"gtx.CartesianConnectivity({domain}, codomain={codomain})" FunCall = as_fmt("{fun}({','.join(args)})") Lambda = as_mako("(lambda ${','.join(params)}: ${expr})") @@ -109,9 +120,12 @@ def visit_Temporary(self, node: itir.Temporary, **kwargs: Any) -> str: # Caches the generated source by IR hash so re-codegen is skipped within a process. -_SOURCE_CACHE: dict[int, tuple[str, str]] = {} -# Caches the loaded module by source string and debug flag so re-exec is skipped within a process. -_MODULE_CACHE: dict[tuple[str, bool], types.ModuleType] = {} +_SOURCE_CACHE: dict[int, tuple[str, str, dict[str, common.DimensionRef]]] = {} +# Caches the loaded module by source string, debug flag and the identities of the dimension +# classes bound into it, so re-exec is skipped within a process. A dimension redefined since (a +# re-run notebook cell) has the same tag but a new class, and gets its own module: a cached module +# is never mutated, so a program loaded earlier keeps working with its classes. +_MODULE_CACHE: dict[tuple[str, bool, tuple[int, ...]], types.ModuleType] = {} def _generate_source( @@ -120,8 +134,13 @@ def _generate_source( use_embedded: bool, offset_provider: common.OffsetProvider, transforms: itir_transforms.GTIRTransform, -) -> tuple[str, str]: - """Generate the Python source for an ITIR program. Returns ``(source_code, entry_point_name)``.""" +) -> tuple[str, str, dict[str, common.DimensionRef]]: + """ + Generate the Python source for an ITIR program. + + Returns ``(source_code, entry_point_name, axis_dims)``: the source refers to each dimension by + its mangled name, which is bound to a class when the program is called, see `_bind_dimensions`. + """ # TODO(tehrengruber): just a temporary solution until we have a proper generic # caching mechanism cache_key = hash( @@ -166,24 +185,73 @@ def _generate_source( """ ) - offset_literals_src = "\n".join(f'{o} = offset("{o}")' for o in offset_literals) - axis_literals_src = "\n".join( - f'{o.value} = gtx.Dimension("{o.value}", kind=gtx.DimensionKind("{o.kind}"))' - for o in axis_literals_set + offset_literals_src = "\n".join( + f'{common.codegen_name(o)} = offset("{o}")' for o in offset_literals ) - source_code = f"{header}{offset_literals_src}\n{axis_literals_src}\n{program}" + axis_dims = {common.codegen_name(o.value): o.dim for o in axis_literals_set} + source_code = f"{header}{offset_literals_src}\n{program}" assert isinstance(ir, itir.Program) entry_point_name = ir.id - _SOURCE_CACHE[cache_key] = (source_code, entry_point_name) - return source_code, entry_point_name + _SOURCE_CACHE[cache_key] = (source_code, entry_point_name, axis_dims) + return source_code, entry_point_name, axis_dims + +@functools.cache +def _synthesize_dimension(ref: common.DimensionRef) -> common.Dimension: + """Make a dimension class with the given ref, without importing the one it was made from.""" + assert ref.base is None + return types.new_class( + ref.qualname.rpartition(".")[2], + (common.CartesianAxisIndex if ref.is_cartesian_axis else common.DimensionIndex,), + {"kind": ref.kind}, + lambda ns: ns.update(__module__=ref.module, __qualname__=ref.qualname), + ) -def _load_module(source_code: str, debug: bool) -> types.ModuleType: - cache_key = (source_code, debug) - if cache_key in _MODULE_CACHE: - return _MODULE_CACHE[cache_key] + +def _bind_dimensions( + axis_dims: Mapping[str, common.DimensionRef], + args: tuple[Any, ...], + offset_provider: Mapping[str, Any], +) -> dict[str, common.Dimension]: + """ + Choose the dimension class for each ref of a program, as the program runs embedded on classes. + + It is the class that the fields and connectivities of the call are built on. A dimension that + none of them has only exists inside the program, so any class with its ref does. + """ + # `iterator.embedded` uses this class itself + classes = {common.dimension_ref(builtins.ConstList): builtins.ConstList} + for value in (*utils.flatten_nested_tuple(args), *offset_provider.values()): + if not isinstance(value, common.Field): + continue + codomain = (value.codomain,) if isinstance(value, common.Connectivity) else () + for dim in (*value.domain.dims, *codomain): + for cls in {dim, common.as_non_staggered(dim)}: + if classes.setdefault(common.dimension_ref(cls), cls) is not cls: + raise ValueError( + f"The arguments use two different classes for the dimension '{cls.tag}'." + " Was it redefined (e.g. by re-running a notebook cell)?" + ) + ir_misc.check_consistent_dimension_refs([*axis_dims.values(), *classes]) + + def bind(ref: common.DimensionRef) -> common.Dimension: + if (cls := classes.get(ref)) is not None: + return cls + if ref.base is not None: + return common.flip_staggered(bind(ref.base)) + return _synthesize_dimension(ref) + + return {name: bind(ref) for name, ref in axis_dims.items()} + + +def _load_module( + source_code: str, debug: bool, bindings: dict[str, common.Dimension] +) -> types.ModuleType: + key = (source_code, debug, tuple(id(cls) for cls in bindings.values())) + if (cached := _MODULE_CACHE.get(key)) is not None: + return cached if debug: # Write to a real .py so debuggers/tracebacks have file/line info. @@ -195,13 +263,14 @@ def _load_module(source_code: str, debug: bool) -> types.ModuleType: print(source_file_name) spec = importlib.util.spec_from_file_location("module.name", source_file_name) mod = importlib.util.module_from_spec(spec) # type: ignore[arg-type] + mod.__dict__.update(bindings) spec.loader.exec_module(mod) # type: ignore[union-attr] else: mod = types.ModuleType("roundtrip_module") + mod.__dict__.update(bindings) exec(compile(source_code, "", "exec"), mod.__dict__) - _MODULE_CACHE[cache_key] = mod - return mod + return _MODULE_CACHE.setdefault(key, mod) @dataclasses.dataclass(frozen=True) @@ -215,14 +284,12 @@ class RoundtripArtifact: source_code: str entry_point_name: str + #: Mangled name in `source_code` -> dimension ref, bound to a class by each call. + axis_dims: dict[str, common.DimensionRef] dispatch_backend: next_backend.Backend | None debug: bool def load(self) -> artifacts.ExecutableProgram: - mod = _load_module(self.source_code, self.debug) - fencil = getattr(mod, self.entry_point_name) - dispatch_backend = self.dispatch_backend - def decorated_fencil( *args: Any, offset_provider: dict[str, common.Connectivity | common.Dimension], @@ -231,10 +298,12 @@ def decorated_fencil( ) -> None: if out is not None: args = (*args, out) - fencil( + bindings = _bind_dimensions(self.axis_dims, args, offset_provider) + mod = _load_module(self.source_code, self.debug, bindings) + getattr(mod, self.entry_point_name)( *args, offset_provider=offset_provider, - backend=dispatch_backend, + backend=self.dispatch_backend, **kwargs, ) @@ -251,7 +320,7 @@ class Roundtrip(workflow.Workflow[stages.CompilableProgramDef, RoundtripArtifact def __call__(self, inp: stages.CompilableProgramDef) -> RoundtripArtifact: debug = config.DEBUG if self.debug is None else self.debug - source_code, entry_point_name = _generate_source( + source_code, entry_point_name, axis_dims = _generate_source( inp.data, offset_provider=inp.args.offset_provider, debug=debug, @@ -262,6 +331,7 @@ def __call__(self, inp: stages.CompilableProgramDef) -> RoundtripArtifact: return RoundtripArtifact( source_code=source_code, entry_point_name=entry_point_name, + axis_dims=axis_dims, dispatch_backend=self.dispatch_backend, debug=debug, ) diff --git a/src/gt4py/next/type_system/mypy_plugin.py b/src/gt4py/next/type_system/mypy_plugin.py index 08934d72b2..b1153c6a95 100644 --- a/src/gt4py/next/type_system/mypy_plugin.py +++ b/src/gt4py/next/type_system/mypy_plugin.py @@ -19,11 +19,6 @@ The goal of this plugin is to reduce the amount of false positives from mypy that arise from correct usage of GT4Py. The following are examples for such false positives: -Dimensions are not fields: - - IDim = gtx.Dimension("IDim") - gtx.Field[gtx.Dims[IDim], float] # IDim is not a valid type - mixed precision math / different ways of describing the same dtype: a: gtx.Field[gtx.Dims[IDim], gtx.float64] @@ -35,10 +30,10 @@ The documentation on mypy plugins is at https://mypy.readthedocs.io/en/latest/extending_mypy.html -Known limitation: the fallback hook that rewrites stray 'Dimension' instances in type aliases -matches on the *variable name* ending in 'Dim' ('fullname.endswith("Dim")'). A dimension bound to -a name that does not end in 'Dim' -- e.g. 'I = gtx.Dimension("I")' -- silently gets no plugin -support at all. +Dimensions need no plugin support: a concrete dimension is a class +('class IDim(gtx.CartesianAxisIndex): ...'), which is a valid annotation for any type checker. See ADR +0030. The plugin only provides the mixed-precision hooks below; it is scheduled for removal once +dtype-generic fields land. """ from __future__ import annotations @@ -46,22 +41,10 @@ import typing -def iter_dim_names() -> typing.Iterator[str]: - """Go through the four distinct place holders, then yield _AnyDim for everything after.""" - yield "_DimA" - yield "_DimB" - yield "_DimC" - yield "_DimD" - while True: - yield "_AnyDim" - - # if we can not import mypy we are not type checking with mypy, so we can skip all this try: from mypy import plugin as mplugin, types - DIM_MAP: dict[str, types.Type] = {} - FLOAT_TYPES = ["builtins.float", "numpy.float32", "numpy.float64"] INT_TYPES = [ "builtins.int", @@ -71,60 +54,6 @@ def iter_dim_names() -> typing.Iterator[str]: "numpy.signedinteger", ] - def fixup_dims_type(ctx: mplugin.AnalyzeTypeContext) -> types.Type: - """ - Overwrite Dims[...] to contain actual types. - - Example: - - CellDim = Dimension("CellDim") # this is not a type - a: Field[Dims[CellDim], gtx.float] # we transform this to Field[Dims[_DimA]] where _DimA *is* a type - - The actual types are defined in 'gt4py.next.common.dimensions', if typing.TYPE_CHECKING is true. - """ - module_name = "gt4py.next.common.dimensions" - dims = iter_dim_names() - args = [] - if ctx.type.args: - # replacement 'Dims[OneDim, OtherDim]' -> 'Dims[_DimA, _DimB]' happens here - for arg in ctx.type.args: - argname = getattr(arg, "name", "unknown") - if argname not in DIM_MAP: - DIM_MAP[argname] = ctx.api.analyze_type( - ctx.api.named_type(f"{module_name}.{next(dims)}", []) - ) - args.append(DIM_MAP[argname]) - else: - # do not accidentally replace 'Dims' -> 'Dims[Any]' (the former matches any number of dims, the latter only one) - args = [types.UnpackType(typ=types.AnyType(types.TypeOfAny.explicit))] - result = ctx.api.analyze_type(ctx.api.named_type("gt4py.next.common.dimensions.Dims", args)) - return result - - def fixup_dims_from_typealiases(ctx: mplugin.AnalyzeTypeContext) -> types.Type: - """ - Catch 'Dimension' instances that made it through other replacements, this seems to happen in type aliases. - - Example: - - T = TypeVar("T", bound=(float, float64)) - CellDim = Dimension("CellDim") - CellField: TypeAlias = Field[Dims[CellDim], T] - - If we have seen this dimension instance before, reuse the same dim type in the replacement, else use `_AnyDim` - """ - result: types.Type | types.AnyType = types.AnyType( - types.TypeOfAny.explicit - ) # Fallback to Any if _AnyDim is not found - try: - if ctx.type.name not in DIM_MAP: - DIM_MAP[ctx.type.name] = ctx.api.analyze_type( - ctx.api.named_type("gt4py.next.common.dimensions._AnyDim", []) - ) - result = DIM_MAP[ctx.type.name] - except AssertionError: # this probably happens when a dim type is analyzed in a context from where _AnyDim is unreachable - pass - return result - def blur_float_precision(ctx: mplugin.AnalyzeTypeContext) -> types.Type: """Turn everything into 'builtins.float'.""" # Note(ricoh): have tried to return numpy dtypes from here but ran into some error from mypy @@ -134,7 +63,7 @@ def blur_int_precision(ctx: mplugin.AnalyzeTypeContext) -> types.Type: """Turn everything into 'builtins.int'""" return ctx.api.named_type("builtins.int", []) - class TreatDimensionsAsTypes(mplugin.Plugin): + class BlurScalarPrecision(mplugin.Plugin): def get_type_analyze_hook( self, fullname: str ) -> typing.Callable[[mplugin.AnalyzeTypeContext], types.Type] | None: @@ -143,27 +72,22 @@ def get_type_analyze_hook( If a callback is returned, it has to return a mypy-representation of a valid type. """ - # replace Dims args with actual types - if fullname == "gt4py.next.common.dimensions.Dims": - return fixup_dims_type - # replace stray 'Dimension' instances - elif ( - fullname.endswith("Dim") and not fullname == "gt4py.next.common.dimensions._AnyDim" - ): - return fixup_dims_from_typealiases # treat all float precision types the same (GT4Py dsl will catch actual problems) - elif fullname in FLOAT_TYPES: + if fullname in FLOAT_TYPES: return blur_float_precision # treat all int precision types the same (GT4Py dsl will catch actual problems) elif fullname in INT_TYPES: return blur_int_precision return None + #: Deprecated alias: downstream configs may still name the old symbol. + TreatDimensionsAsTypes = BlurScalarPrecision + def plugin(version: str) -> type[mplugin.Plugin]: """ This is the entry point mypy looks for if this module was pointed to in config as a plugin. """ - return TreatDimensionsAsTypes + return BlurScalarPrecision except ImportError: pass diff --git a/src/gt4py/next/type_system/type_info.py b/src/gt4py/next/type_system/type_info.py index 5e727821a5..d80eb1e7f3 100644 --- a/src/gt4py/next/type_system/type_info.py +++ b/src/gt4py/next/type_system/type_info.py @@ -102,7 +102,7 @@ def primitive_constituents( Return the primitive types contained in a composite type. >>> from gt4py.next import common - >>> I = common.Dimension(value="I") + >>> class I(common.CartesianAxisIndex): ... >>> int_type = ts.ScalarType(kind=ts.ScalarKind.INT64) >>> field_type = ts.FieldType(dims=[I], dtype=int_type) @@ -382,7 +382,7 @@ def is_tuple_of_type(type_: ts.TypeSpec, expected_type: type | tuple) -> TypeGua return isinstance(type_, ts.TupleType) and is_type_or_tuple_of_type(type_, expected_type) -def extract_dims(symbol_type: ts.TypeSpec) -> list[common.Dimension]: +def extract_dims(symbol_type: ts.TypeSpec) -> list[common.DimensionRef]: """ Try to extract field dimensions if possible. @@ -391,10 +391,10 @@ def extract_dims(symbol_type: ts.TypeSpec) -> list[common.Dimension]: Examples: >>> extract_dims(ts.ScalarType(kind=ts.ScalarKind.INT64, shape=[3, 4])) [] - >>> I = common.Dimension(value="I") - >>> J = common.Dimension(value="J") + >>> class I(common.CartesianAxisIndex): ... + >>> class J(common.CartesianAxisIndex): ... >>> extract_dims(ts.FieldType(dims=[I, J], dtype=ts.ScalarType(kind=ts.ScalarKind.INT64))) - [Dimension(value='I', kind=), Dimension(value='J', kind=)] + [DimensionRef(gt4py.next.type_system.type_info:I, horizontal, cartesian_axis), DimensionRef(gt4py.next.type_system.type_info:J, horizontal, cartesian_axis)] """ if isinstance(symbol_type, ts.ScalarType): return [] @@ -408,8 +408,8 @@ def is_local_field(type_: ts.FieldType) -> bool: Return if `type_` is a field defined on a local dimension. Examples: - >>> V = common.Dimension(value="V") - >>> V2E = common.Dimension(value="V2E", kind=common.DimensionKind.LOCAL) + >>> class V(common.DimensionIndex): ... + >>> class V2E(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... >>> is_local_field( ... ts.FieldType(dims=[V, V2E], dtype=ts.ScalarType(kind=ts.ScalarKind.INT64)) ... ) @@ -442,7 +442,7 @@ def is_compatible_type(type_a: ts.TypeSpec, type_b: ts.TypeSpec) -> bool: Beside that this function simply checks for equality of types. >>> bool_type = ts.ScalarType(kind=ts.ScalarKind.BOOL) - >>> IDim = common.Dimension(value="IDim") + >>> class IDim(common.CartesianAxisIndex): ... >>> type_on_i_of_i_it = it_ts.IteratorType( ... position_dims=[IDim], defined_dims=[IDim], element_type=bool_type ... ) @@ -452,7 +452,7 @@ def is_compatible_type(type_a: ts.TypeSpec, type_b: ts.TypeSpec) -> bool: >>> is_compatible_type(type_on_i_of_i_it, type_on_undefined_of_i_it) True - >>> JDim = common.Dimension(value="JDim") + >>> class JDim(common.CartesianAxisIndex): ... >>> type_on_j_of_j_it = it_ts.IteratorType( ... position_dims=[JDim], defined_dims=[JDim], element_type=bool_type ... ) @@ -570,20 +570,24 @@ def promote( `offset_type` of `None` (a list from `make_const_list`) is compatible with any other. >>> dtype = ts.ScalarType(kind=ts.ScalarKind.INT64) - >>> I, J, K = (common.Dimension(value=dim) for dim in ["I", "J", "K"]) + >>> class I(common.CartesianAxisIndex): ... + + >>> class J(common.CartesianAxisIndex): ... + + >>> class K(common.CartesianAxisIndex): ... >>> promoted: ts.FieldType = promote( ... ts.FieldType(dims=[I, J], dtype=dtype), ts.FieldType(dims=[I, J, K], dtype=dtype), dtype ... ) - >>> promoted.dims == [I, J, K] and promoted.dtype == dtype + >>> promoted.dims == common.dimension_refs([I, J, K]) and promoted.dtype == dtype True >>> promoted: ts.FieldType = promote( ... ts.FieldType(dims=[I, J], dtype=dtype), ts.FieldType(dims=[K], dtype=dtype) ... ) - >>> promoted.dims == [I, J, K] and promoted.dtype == dtype + >>> promoted.dims == common.dimension_refs([I, J, K]) and promoted.dtype == dtype True - >>> V2E = common.Dimension(value="V2E", kind=common.DimensionKind.LOCAL) + >>> class V2E(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... >>> list_dtype = ts.ListType(element_type=dtype, offset_type=V2E) >>> promote( ... ts.FieldType(dims=[I], dtype=list_dtype), @@ -903,9 +907,9 @@ def function_signature_incompatibilities_field( if field_type.dims and source_dim not in field_type.dims: yield ( f"Incompatible offset can not shift field defined on " - f"{', '.join([dim.value for dim in field_type.dims])} from " - f"{source_dim.value} to target dim(s): " - f"{', '.join([dim.value for dim in target_dims])}" + f"{', '.join([dim.qualname for dim in field_type.dims])} from " + f"{source_dim.qualname} to target dim(s): " + f"{', '.join([dim.qualname for dim in target_dims])}" ) diff --git a/src/gt4py/next/type_system/type_specifications.py b/src/gt4py/next/type_system/type_specifications.py index ca5cf81a3a..dc1aabcb48 100644 --- a/src/gt4py/next/type_system/type_specifications.py +++ b/src/gt4py/next/type_system/type_specifications.py @@ -49,8 +49,35 @@ class VoidType(TypeSpec): """ +# NOTE: type specifications store only `common.DimensionRef` values. The constructors accept +# dimension classes too and convert them, so that user code can pass what it has. +def dimension_field() -> typing.Any: + """A datamodel field holding a `common.DimensionRef`, converting a dimension class.""" + return eve_datamodels.field(converter=common.dimension_ref) + + +def _optional_dimension_ref( + dim: Optional[common.Dimension | common.DimensionRef], +) -> Optional[common.DimensionRef]: + return None if dim is None else common.dimension_ref(dim) + + +def dimension_list_field() -> typing.Any: + """A datamodel field holding a list of `common.DimensionRef`, converting dimension classes.""" + return eve_datamodels.field(converter=_dims_list) + + +def _dims_list(dims: typing.Any) -> typing.Any: + # NOTE: `FieldType.dims` may be `...` (see `FieldType.__str__`), which passes through. + return dims if dims is Ellipsis else common.dimension_refs(dims) + + +def _dims_tuple(dims: typing.Iterable[common.Dimension | common.DimensionRef]) -> tuple: + return tuple(common.dimension_refs(dims)) + + class DimensionType(TypeSpec): - dim: common.Dimension + dim: common.DimensionRef = dimension_field() def __str__(self) -> str: return str(self.dim) @@ -61,7 +88,7 @@ class IndexType(TypeSpec): Represents the type of an index into a dimension. """ - dim: common.Dimension + dim: common.DimensionRef = dimension_field() def __str__(self) -> str: return f"Index[{self.dim}]" @@ -69,8 +96,10 @@ def __str__(self) -> str: class OffsetType(TypeSpec): # TODO(havogt): replace by ConnectivityType - source: common.Dimension - target: tuple[common.Dimension] | tuple[common.Dimension, common.Dimension] + source: common.DimensionRef = dimension_field() + target: tuple[common.DimensionRef] | tuple[common.DimensionRef, common.DimensionRef] = ( + eve_datamodels.field(converter=_dims_tuple) + ) #: The offset-provider key; `None` for the untagged Cartesian `Dim + offset`. tag: Optional[common.Tag] = None @@ -114,20 +143,28 @@ class ListType(DataType): """ element_type: DataType - offset_type: common.Dimension | None + #: The local dimension the list runs along. `None` where type inference does not know it, + #: which is how it spells the result of `make_const_list`; embedded execution and the DaCe + #: lowering use `iterator.builtins.ConstList` for the same thing. + #: TODO(egparedes): use `iterator.builtins.ConstList` in type inference too, and drop `None`. + offset_type: common.DimensionRef | None = eve_datamodels.field( + converter=_optional_dimension_ref + ) class FieldType(DataType, CallableType): - dims: list[common.Dimension] + dims: list[common.DimensionRef] = dimension_list_field() dtype: ScalarType | ListType def __str__(self) -> str: - dims = "..." if self.dims is Ellipsis else f"[{', '.join(dim.value for dim in self.dims)}]" + dims = ( + "..." if self.dims is Ellipsis else f"[{', '.join(dim.qualname for dim in self.dims)}]" + ) return f"Field[{dims}, {self.dtype}]" @eve_datamodels.validator("dims") def _dims_validator( - self, attribute: eve_datamodels.Attribute, dims: list[common.Dimension] + self, attribute: eve_datamodels.Attribute, dims: list[common.DimensionRef] ) -> None: common.check_dims(dims) @@ -227,4 +264,4 @@ def constructed_type(self) -> TypeSpec: class DomainType(DataType): - dims: list[common.Dimension] + dims: list[common.DimensionRef] = dimension_list_field() diff --git a/src/gt4py/next/type_system/type_translation.py b/src/gt4py/next/type_system/type_translation.py index df721da0e7..757fb5b346 100644 --- a/src/gt4py/next/type_system/type_translation.py +++ b/src/gt4py/next/type_system/type_translation.py @@ -12,6 +12,7 @@ import builtins import collections.abc +import contextvars import dataclasses import enum import functools @@ -19,7 +20,7 @@ import sys import types import typing -from typing import Any, ForwardRef, Optional, TypeAlias +from typing import Any, ForwardRef, Optional, TypeAlias, cast import numpy as np import numpy.typing as npt @@ -113,6 +114,12 @@ def make_type(type_: type) -> ts.TypeSpec: ) keys = [*named_collections.elements_keys(type_)] + if any( + isinstance(annotation, (str, ForwardRef)) + for class_ in type_.__mro__ + for annotation in getattr(class_, "__annotations__", {}).values() + ): + _note_namespace_lookup() # postponed annotations, resolved in the module namespace hints = named_collections.elements_types( type_, globalns=sys.modules[type_.__module__].__dict__ ) @@ -130,7 +137,10 @@ def make_type(type_: type) -> ts.TypeSpec: def _resolve_type_alias(type_hint: Any) -> Any: """Resolve a PEP 695 type alias, reporting its failures the way annotations do.""" try: - return xtyping.eval_type_alias(type_hint) + resolved = xtyping.eval_type_alias(type_hint) + if resolved is not type_hint: + _note_namespace_lookup() # an alias's value is looked up lazily, by name + return resolved except NameError as error: raise ValueError( f"Type annotation '{type_hint}' has undefined forward references." @@ -155,6 +165,7 @@ def canonicalize_type_hint( if isinstance(type_hint, str): type_hint = ForwardRef(type_hint) if isinstance(type_hint, ForwardRef): + _note_namespace_lookup() try: type_hint = xtyping.eval_forward_ref(type_hint, globalns=globalns, localns=localns) except Exception as error: @@ -183,7 +194,6 @@ def canonicalize_type_hint( return canonical_type, args, tuple(extra_args) -@eve_utils.optional_lru_cache(maxsize=None, typed=False) def from_type_hint( type_hint: Any, *, @@ -191,6 +201,74 @@ def from_type_hint( localns: Optional[dict[str, Any]] = None, ) -> ts.TypeSpec: """Convert any kind of Python type hint to a GT4Py TypeSpec.""" + # NOTE: cached together with the dimension classes the conversion captured, which are + # replayed into an active capture (see `common.capture_dimension_classes`). A conversion + # that looked names up in a namespace (string or forward-ref annotations, type aliases) + # depends on the namespace's current contents, not only on the hint: its entry is only + # reused while every dimension class it captured is still the one its module defines (a + # re-run notebook cell redefining a dimension invalidates it). + key = (type_hint, globalns, localns) if globalns is None and localns is None else None + try: + cached = _FROM_TYPE_HINT_CACHE.get(key) if key is not None else None + except TypeError: # an unhashable hint + key = cached = None + if cached is not None: + type_spec, captured_pairs, namespace_dependent = cached + if not namespace_dependent or all( + _is_current_dimension_class(cls) for _, cls in captured_pairs + ): + if captured_pairs: + common.replay_dimension_classes(captured_pairs) + return type_spec + + outer = _NAMESPACE_LOOKUPS.get() + looked_up = [False] + token = _NAMESPACE_LOOKUPS.set(looked_up) + try: + with common.capture_dimension_classes() as captured: + type_spec = _from_type_hint(type_hint, globalns=globalns, localns=localns) + finally: + _NAMESPACE_LOOKUPS.reset(token) + if looked_up[0] and outer is not None: + outer[0] = True # the enclosing conversion depends on the namespace too + if key is not None: + _FROM_TYPE_HINT_CACHE[key] = (type_spec, tuple(captured), looked_up[0]) + common.replay_dimension_classes(captured) + return type_spec + + +_FROM_TYPE_HINT_CACHE: dict[ + Any, tuple[ts.TypeSpec, tuple[tuple[common.DimensionRef, common.Dimension], ...], bool] +] = {} + + +def _is_current_dimension_class(cls: common.Dimension) -> bool: + """Whether `cls` is still what its (loaded) module defines under its qualname.""" + if common.is_staggered(cls): + return _is_current_dimension_class(cls.base) # type: ignore[attr-defined] # staggered + obj: Any = sys.modules.get(cls.__module__) + for attr in cls.__qualname__.split("."): + obj = getattr(obj, attr, None) + return obj is cls + + +#: Set during a `from_type_hint` conversion: whether it looked names up in a namespace. +_NAMESPACE_LOOKUPS: contextvars.ContextVar[Optional[list[bool]]] = contextvars.ContextVar( + "_NAMESPACE_LOOKUPS", default=None +) + + +def _note_namespace_lookup() -> None: + if (looked_up := _NAMESPACE_LOOKUPS.get()) is not None: + looked_up[0] = True + + +def _from_type_hint( + type_hint: Any, + *, + globalns: Optional[dict[str, Any]] = None, + localns: Optional[dict[str, Any]] = None, +) -> ts.TypeSpec: from_type_hint_same_ns = functools.partial(from_type_hint, globalns=globalns, localns=localns) canonical_type, args, extra_args = canonicalize_type_hint( @@ -210,7 +288,7 @@ def from_type_hint( case common.Field: if (n_args := len(args)) != 2: raise ValueError(f"Field type requires two arguments, got {n_args}: '{type_hint}'.") - dims: list[common.Dimension] = [] + dims: list[common.DimensionRef] = [] dim_arg, dtype_arg = args dim_arg = ( list(typing.get_args(dim_arg)) @@ -219,9 +297,11 @@ def from_type_hint( ) if isinstance(dim_arg, list): for d in dim_arg: - if not isinstance(d, common.Dimension): + if not isinstance(d, common.DimensionMeta): raise ValueError(f"Invalid field dimension definition '{d}'.") - dims.append(d) + dims.append( + common.dimension_ref(cast(common.Dimension, d)) + ) # edge: class -> value else: raise ValueError(f"Invalid field dimensions '{dim_arg}'.") @@ -342,10 +422,10 @@ def from_value(value: Any) -> ts.TypeSpec: f"Value '{value}' is out of range to be representable as 'INT32' or 'INT64'." ) return candidate_type - elif isinstance(value, common.Dimension): - symbol_type = ts.DimensionType(dim=value) + elif isinstance(value, common.DimensionMeta): + symbol_type = ts.DimensionType(dim=common.dimension_ref(cast(common.Dimension, value))) elif isinstance(value, common.Field): - dims = list(value.domain.dims) + dims = common.dimension_refs(value.domain.dims) dtype = from_type_hint(value.dtype.scalar_type) assert isinstance(dtype, ts.ScalarType) symbol_type = ts.FieldType(dims=dims, dtype=dtype) @@ -364,6 +444,13 @@ def from_value(value: Any) -> ts.TypeSpec: else: type_ = xtyping.infer_type(value, annotate_callable_kwargs=True) symbol_type = from_type_hint(type_) + if common.is_capturing_dimension_classes() and isinstance( + value, named_collections.CUSTOM_NAMED_COLLECTION_TYPES + ): + # The type comes from the collection's annotations; at a program call, the classes + # of the *values* matter too (see `common.capture_dimension_classes`). + for key in named_collections.elements_keys(type(value)): + from_value(getattr(value, key)) # type: ignore[arg-type] # str keys if isinstance(symbol_type, (ts.DataType, ts.CallableType, ts.OffsetType, ts.DimensionType)): return symbol_type diff --git a/tests/next_tests/artifacts/custom_named_collections.py b/tests/next_tests/artifacts/custom_named_collections.py index d7e9cb1bf1..aea5aa7bdc 100644 --- a/tests/next_tests/artifacts/custom_named_collections.py +++ b/tests/next_tests/artifacts/custom_named_collections.py @@ -15,11 +15,21 @@ from gt4py import next as gtx from gt4py.eve.xtyping import NestedTuple -from gt4py.next import common, Dimension, Field, float32, float64, Dims, named_collections +from gt4py.next import ( + common, + Dimension, + CartesianAxisIndex, + DimensionIndex, + Field, + float32, + float64, + Dims, + named_collections, +) from gt4py.next.type_system import type_specifications as ts -TDim = Dimension("TDim") # Meaningless dimension just for tests +class TDim(CartesianAxisIndex): ... class SingleElementNamedTupleNamedCollection(NamedTuple): diff --git a/tests/next_tests/benchmarks/benchmark_program_call.py b/tests/next_tests/benchmarks/benchmark_program_call.py index 166509e8f3..45e0c8bed6 100644 --- a/tests/next_tests/benchmarks/benchmark_program_call.py +++ b/tests/next_tests/benchmarks/benchmark_program_call.py @@ -41,8 +41,10 @@ from pytest_benchmark import fixture as ptb_fixture -Cell = gtx.Dimension("Cell") -IDim = gtx.Dimension("IDim") +class Cell(gtx.DimensionIndex): ... + + +class IDim(gtx.CartesianAxisIndex): ... @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) diff --git a/tests/next_tests/fixtures/past_common.py b/tests/next_tests/fixtures/past_common.py index 0b2681059c..3699e0fdaf 100644 --- a/tests/next_tests/fixtures/past_common.py +++ b/tests/next_tests/fixtures/past_common.py @@ -13,9 +13,7 @@ import gt4py.next as gtx from gt4py.next import float64 - -IDim = gtx.Dimension("IDim") -JDim = gtx.Dimension("JDim") +from next_tests.integration_tests.cases_utils import IDim # TODO(tehrengruber): Improve test structure. Identity needs to be decorated diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index 0452bbd82e..f995dbaf06 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -658,7 +658,7 @@ def get_param_types( def get_param_size(param_type: ts.TypeSpec, sizes: dict[gtx.Dimension, int]) -> int: match param_type: case ts.FieldType(dims=dims): - return int(np.prod([sizes[dim] for dim in sizes if dim in dims])) + return int(np.prod([sizes[dim] for dim in sizes if common.dimension_ref(dim) in dims])) case ts.ScalarType(shape=shape): return int(np.prod(shape)) if shape else 1 case ts.TupleType(types=types): @@ -678,12 +678,12 @@ def extend_domain( for dim, (lower, upper) in extend.items(): domain = domain.replace( dim, - common.named_range( + common.dimension_range( ( dim, ( - domain[dim].unit_range.start - lower, - domain[dim].unit_range.stop + upper, + domain[dim].value.start - lower, + domain[dim].value.stop + upper, ), ) ), diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index afdbc99619..8112bbf447 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -31,6 +31,9 @@ import next_tests +from next_tests.toy_connectivity import C2EDim, Cell, E2VDim, Edge, V2EDim, Vertex + + __all__ = [ "exec_alloc_descriptor", "mesh_descriptor", @@ -180,29 +183,38 @@ def debug_itir(tree): DimsType = TypeVar("DimsType") DType = TypeVar("DType") -IDim = gtx.Dimension("IDim") + +class IDim(gtx.CartesianAxisIndex): ... + + IHalfDim = common.flip_staggered(IDim) -JDim = gtx.Dimension("JDim") + + +class JDim(gtx.CartesianAxisIndex): ... + + JHalfDim = common.flip_staggered(JDim) -KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + KHalfDim = common.flip_staggered(KDim) Ioff = gtx.FieldOffset("Ioff", source=IDim, target=(IDim,)) Koff = gtx.FieldOffset("Koff", source=KDim, target=(KDim,)) -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -Cell = gtx.Dimension("Cell") + EdgeOffset = gtx.FieldOffset("EdgeOffset", source=Edge, target=(Edge,)) -V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -C2EDim = gtx.Dimension("C2E", kind=gtx.DimensionKind.LOCAL) -C2VDim = gtx.Dimension("C2V", kind=gtx.DimensionKind.LOCAL) -V2E = gtx.FieldOffset("V2E", source=Edge, target=(Vertex, V2EDim)) -E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) -C2E = gtx.FieldOffset("C2E", source=Edge, target=(Cell, C2EDim)) -C2V = gtx.FieldOffset("C2V", source=Vertex, target=(Cell, C2VDim)) + +class C2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +V2E = gtx.FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) +E2V = gtx.FieldOffset(E2VDim.tag, source=Vertex, target=(Edge, E2VDim)) +C2E = gtx.FieldOffset(C2EDim.tag, source=Edge, target=(Cell, C2EDim)) +C2V = gtx.FieldOffset(C2VDim.tag, source=Vertex, target=(Cell, C2VDim)) size = 10 diff --git a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py index e613e3db92..e298515208 100644 --- a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py +++ b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py @@ -30,13 +30,22 @@ from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations -IDim = gtx.Dimension("I") +class IDim(gtx.CartesianAxisIndex): ... + + I_SIZE = 8 -Cell = gtx.Dimension("Cell") -Edge = gtx.Dimension("Edge") -C2EDim = gtx.Dimension("C2E", kind=gtx.DimensionKind.LOCAL) -C2E = gtx.FieldOffset("C2E", source=Edge, target=(Cell, C2EDim)) + +class Cell(gtx.DimensionIndex): ... + + +class Edge(gtx.DimensionIndex): ... + + +class C2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +C2E = gtx.FieldOffset(C2EDim.tag, source=Edge, target=(Cell, C2EDim)) C2E_TABLE = np.array( [ @@ -213,7 +222,7 @@ def test_write_back_buffer_elimination_from_lowering_with_reduction( survived until the transformation runs. """ offset_provider = { - "C2E": constructors.as_connectivity( + C2EDim.tag: constructors.as_connectivity( domain={Cell: N_CELLS, C2EDim: 4}, codomain=Edge, data=C2E_TABLE, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py index 820bb86903..6688bf9292 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause import inspect +import re import threading import warnings from typing import Optional, NamedTuple @@ -310,7 +311,7 @@ def test_compile_unstructured_without_offset_provider_errors( args, kwargs = cases.get_default_data(unstructured_case, compile_testee_unstructured) # depending on the compilation runner the error is raised on compile or on the first call - with pytest.raises(KeyError, match="'V2E' not found in offset provider"): + with pytest.raises(KeyError, match=f"'{re.escape(V2E.value)}' not found in offset provider"): compile_testee_unstructured.compile() compile_testee_unstructured(*args, **kwargs) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py index 3c7273123d..15a6ea1df7 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py @@ -457,7 +457,7 @@ def testee(a: cases.EField, b: cases.EField) -> cases.VField: t = concat_where(Vertex < 2, a(V2E), b(V2E)) return neighbor_sum(t, axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() vertex_mask = np.arange(unstructured_case.default_sizes[Vertex]) < 2 cases.verify_with_default_data( unstructured_case, @@ -480,7 +480,7 @@ def testee( t = concat_where(KDim < 2, a(V2E), b(V2E)) return neighbor_sum(t, axis=V2EDim) - v2e_table = unstructured_case_3d.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case_3d.offset_provider[V2EDim.tag].asnumpy() k_mask = np.arange(unstructured_case_3d.default_sizes[KDim]) < 2 cases.verify_with_default_data( unstructured_case_3d, @@ -500,7 +500,7 @@ def test_with_local_and_nonlocal_field(unstructured_case, static_domains: bool): def testee(a: cases.EField, b: cases.VField) -> cases.VField: return neighbor_sum(concat_where(Vertex < 2, a(V2E), b), axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() vertex_mask = np.arange(unstructured_case.default_sizes[Vertex]) < 2 cases.verify_with_default_data( unstructured_case, @@ -527,7 +527,7 @@ def testee( t = concat_where(Vertex < 2, (a(V2E), b(V2E)), (c(V2E), d(V2E))) return neighbor_sum(t[0], axis=V2EDim), neighbor_sum(t[1], axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() vertex_mask = np.arange(unstructured_case.default_sizes[Vertex]) < 2 cases.verify_with_default_data( unstructured_case, @@ -560,7 +560,7 @@ def testee(a: cases.EField) -> tuple[cases.VField, cases.VField]: neighbor_sum(concat_where(Vertex < 2, 3, a(V2E)), axis=V2EDim), ) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() vertex_mask = np.arange(unstructured_case.default_sizes[Vertex]) < 2 cases.verify_with_default_data( unstructured_case, @@ -593,7 +593,7 @@ def testee( t = concat_where(Vertex < 2, (a(V2E), c), (3, b(V2E))) return neighbor_sum(t[0], axis=V2EDim), neighbor_sum(t[1], axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() vertex_mask = np.arange(unstructured_case.default_sizes[Vertex]) < 2 cases.verify_with_default_data( unstructured_case, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py index 9685b894b4..0cf0511a17 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py @@ -31,11 +31,11 @@ def testee( ) # multiplication with shifted `ones` because reduction of only non-shifted field with local dimension is not supported inp = unstructured_case.as_field( - [Vertex, V2EDim], unstructured_case.offset_provider["V2E"].asnumpy() + [Vertex, V2EDim], unstructured_case.offset_provider[V2EDim.tag].asnumpy() ) ones = cases.allocate(unstructured_case, testee, "ones").strategy(cases.ConstInitializer(1))() - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() cases.verify( unstructured_case, testee, @@ -55,7 +55,7 @@ def testee(inp: gtx.Field[[Vertex, V2EDim], int32]) -> gtx.Field[[Vertex], int32 return inp[V2EDim(0)] + inp[V2EDim(1)] + inp[V2EDim(2)] + inp[V2EDim(3)] inp = unstructured_case.as_field( - [Vertex, V2EDim], unstructured_case.offset_provider["V2E"].asnumpy() + [Vertex, V2EDim], unstructured_case.offset_provider[V2EDim.tag].asnumpy() ) cases.verify( @@ -77,7 +77,7 @@ def testee(inp: gtx.Field[[Vertex, V2EDim], int32]) -> gtx.Field[[Vertex], int64 return inp_64[V2EDim(0)] + inp_64[V2EDim(1)] + inp_64[V2EDim(2)] + inp_64[V2EDim(3)] inp = unstructured_case.as_field( - [Vertex, V2EDim], unstructured_case.offset_provider["V2E"].asnumpy() + [Vertex, V2EDim], unstructured_case.offset_provider[V2EDim.tag].asnumpy() ) cases.verify( @@ -99,7 +99,7 @@ def testee(inp: gtx.Field[[Vertex, V2EDim], int32]) -> gtx.Field[[Vertex], int32 return neighbor_sum(inp, axis=V2EDim) inp = unstructured_case.as_field( - [Vertex, V2EDim], unstructured_case.offset_provider["V2E"].asnumpy() + [Vertex, V2EDim], unstructured_case.offset_provider[V2EDim.tag].asnumpy() ) cases.verify( @@ -107,7 +107,7 @@ def testee(inp: gtx.Field[[Vertex, V2EDim], int32]) -> gtx.Field[[Vertex], int32 testee, inp, out=cases.allocate(unstructured_case, testee, cases.RETURN)(), - ref=np.sum(unstructured_case.offset_provider["V2E"].asnumpy(), axis=1), + ref=np.sum(unstructured_case.offset_provider[V2EDim.tag].asnumpy(), axis=1), ) @@ -118,7 +118,7 @@ def test_write_local_field(unstructured_case): def testee(inp: gtx.Field[[Edge], int32]) -> gtx.Field[[Vertex, V2EDim], int32]: return inp(V2E) - v2e = unstructured_case.offset_provider["V2E"] + v2e = unstructured_case.offset_provider[V2EDim.tag] v2e_table = v2e.asnumpy() out = unstructured_case.as_field([Vertex, V2EDim], np.zeros_like(v2e_table)) inp = cases.allocate(unstructured_case, testee, "inp")() diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py index 8ba6f3091a..bd1a0bbaa0 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py @@ -11,12 +11,28 @@ import pytest -from gt4py.next import Dimension, DimensionKind, Field, field_operator, int32, int64, scan_operator +from gt4py.next import ( + Dimension, + CartesianAxisIndex, + DimensionIndex, + DimensionKind, + Field, + field_operator, + int32, + int64, + scan_operator, +) from gt4py.next.ffront.ast_passes import single_static_assign as ssa from gt4py.next.ffront.foast_pretty_printer import pretty_format from gt4py.next.ffront.func_to_foast import FieldOperatorParser +class I(CartesianAxisIndex): ... + + +class KDim(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + + @pytest.mark.parametrize( "test_case", [ @@ -45,7 +61,6 @@ def test_one_to_one(test_case: str): def test_fieldop(): - I = Dimension("I") @field_operator def foo(inp1: Field[[I], int64], inp2: Field[[I], int64]): @@ -67,7 +82,6 @@ def bar(inp1: Field[[I], int64], inp2: Field[[I], int64]) -> Field[[I], int64]: def test_scanop(): - KDim = Dimension("KDim", kind=DimensionKind.VERTICAL) @scan_operator(axis=KDim, forward=False, init=1) def scan(inp: int32) -> int32: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py index 6c2f0e598f..96a2f0b7e5 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py @@ -61,7 +61,7 @@ def test_import_offset_module_unstructured_shift(unstructured_case): def testee(a: cases.EField) -> cases.VField: return neighbor_sum(a(cases.V2E), axis=cases.V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[cases.V2EDim.tag].asnumpy() cases.verify_with_default_data( unstructured_case, testee, @@ -78,7 +78,7 @@ def testee(a: cases.VField) -> cases.EField: cases.verify_with_default_data( unstructured_case, testee, - ref=lambda a: a[unstructured_case.offset_provider["E2V"].asnumpy()[:, 0]], + ref=lambda a: a[unstructured_case.offset_provider[cases.E2VDim.tag].asnumpy()[:, 0]], ) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index ba9acdfce4..d7e2182315 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -484,7 +484,7 @@ def testee( ) return neighbor_sum(t.neighbors, axis=V2EDim), t.center - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() mask = unstructured_case.as_field( [Vertex], np.random.choice(a=[False, True], size=unstructured_case.default_sizes[Vertex]) ) @@ -642,7 +642,7 @@ def testee( ) return neighbor_sum(t.neighbors, axis=V2EDim), t.center - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() vertex_mask = np.arange(unstructured_case.default_sizes[Vertex]) < 2 cases.verify_with_default_data( unstructured_case, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_program.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_program.py index 21bb6f8406..e7091ce829 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_program.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_program.py @@ -88,9 +88,12 @@ def test_copy_execution(cartesian_case, copy_program_def): cases.verify_with_default_data(cartesian_case, copy_program, ref=lambda in_field: in_field) +class EmbeddedSilentDim(gtx.CartesianAxisIndex): ... + + def test_embedded_program_call_is_silent(): """Embedded execution is the default (no backend): calling it must not warn.""" - dim = gtx.Dimension("EmbeddedSilentDim") + dim = EmbeddedSilentDim @gtx.field_operator def add_one(a: gtx.Field[gtx.Dims[dim], gtx.float64]) -> gtx.Field[gtx.Dims[dim], gtx.float64]: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py index a36dac3625..18c66974ca 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py @@ -17,6 +17,7 @@ from next_tests.integration_tests import cases from next_tests.integration_tests.cases import ( + C2EDim, C2E, E2V, V2E, @@ -52,7 +53,7 @@ def testee(edge_f: cases.EField) -> cases.VField: inp = cases.allocate(unstructured_case, testee, "edge_f", strategy=strategy)() out = cases.allocate(unstructured_case, testee, cases.RETURN)() - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() ref = np.max( inp.asnumpy()[v2e_table], axis=1, @@ -69,7 +70,7 @@ def minover(edge_f: cases.EField) -> cases.VField: out = min_over(edge_f(V2E), axis=V2EDim) return out - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() cases.verify_with_default_data( unstructured_case, minover, @@ -99,7 +100,7 @@ def reduction_ek_field( "fop", [reduction_e_field, reduction_ek_field], ids=lambda fop: fop.__name__ ) def test_neighbor_sum(unstructured_case_3d, fop): - v2e_table = unstructured_case_3d.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case_3d.offset_provider[V2EDim.tag].asnumpy() edge_f = cases.allocate(unstructured_case_3d, fop, "edge_f")() @@ -151,7 +152,7 @@ def fencil_op(edge_f: EKField) -> VKField: def fencil(edge_f: EKField, out: VKField): fencil_op(edge_f, out=out) - v2e_table = unstructured_case_3d.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case_3d.offset_provider[V2EDim.tag].asnumpy() field = cases.allocate(unstructured_case_3d, fencil, "edge_f", sizes={KDim: 2})() out = cases.allocate(unstructured_case_3d, fencil_op, cases.RETURN, sizes={KDim: 1})() @@ -184,7 +185,7 @@ def reduce_expr(edge_f: cases.EField) -> cases.VField: def fencil(edge_f: cases.EField, out: cases.VField): reduce_expr(edge_f, out=out) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() cases.verify_with_default_data( unstructured_case, fencil, @@ -206,7 +207,7 @@ def test_reduction_with_common_expression(unstructured_case): def testee(flux: cases.EField) -> cases.VField: return neighbor_sum(flux(V2E) + flux(V2E), axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() cases.verify_with_default_data( unstructured_case, testee, @@ -222,7 +223,7 @@ def test_reduction_expression_with_where(unstructured_case): def testee(mask: cases.VBoolField, inp: cases.EField) -> cases.VField: return neighbor_sum(where(mask, inp(V2E), inp(V2E)), axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() mask = unstructured_case.as_field( [Vertex], np.random.choice(a=[False, True], size=unstructured_case.default_sizes[Vertex]) @@ -251,7 +252,7 @@ def test_reduction_expression_with_where_and_tuples(unstructured_case): def testee(mask: cases.VBoolField, inp: cases.EField) -> cases.VField: return neighbor_sum(where(mask, (inp(V2E), inp(V2E)), (inp(V2E), inp(V2E)))[1], axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() mask = unstructured_case.as_field( [Vertex], np.random.choice(a=[False, True], size=unstructured_case.default_sizes[Vertex]) @@ -280,7 +281,7 @@ def test_reduction_expression_with_where_and_scalar(unstructured_case): def testee(mask: cases.VBoolField, inp: cases.EField) -> cases.VField: return neighbor_sum(inp(V2E) + where(mask, inp(V2E), 1), axis=V2EDim) - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() mask = unstructured_case.as_field( [Vertex], np.random.choice(a=[False, True], size=unstructured_case.default_sizes[Vertex]) @@ -325,7 +326,7 @@ def testee(a: cases.VField) -> cases.EField: cases.verify_with_default_data( unstructured_case, testee, - ref=lambda a: a[unstructured_case.offset_provider["E2V"].asnumpy()[:, 0]], + ref=lambda a: a[unstructured_case.offset_provider[E2VDim.tag].asnumpy()[:, 0]], ) @@ -346,7 +347,7 @@ def testee(a: cases.VField) -> cases.EField: out = cases.allocate(unstructured_case, testee, cases.RETURN)() ORIGIN = 2 - e2v_table = unstructured_case.offset_provider["E2V"].asnumpy() + e2v_table = unstructured_case.offset_provider[E2VDim.tag].asnumpy() neighbor_0_iter = iter(enumerate(e2v_table[:, 0])) edge_start = next(i for i, v in neighbor_0_iter if v >= ORIGIN) edge_stop = next(i for i, v in neighbor_0_iter if v < ORIGIN) @@ -391,16 +392,16 @@ def composed_shift_unstructured(inp: cases.VField) -> cases.CField: cases.verify_with_default_data( unstructured_case, composed_shift_unstructured_flat, - ref=lambda inp: inp[unstructured_case.offset_provider["E2V"].asnumpy()[:, 0]][ - unstructured_case.offset_provider["C2E"].asnumpy()[:, 0] + ref=lambda inp: inp[unstructured_case.offset_provider[E2VDim.tag].asnumpy()[:, 0]][ + unstructured_case.offset_provider[C2EDim.tag].asnumpy()[:, 0] ], ) cases.verify_with_default_data( unstructured_case, composed_shift_unstructured_intermediate_result, - ref=lambda inp: inp[unstructured_case.offset_provider["E2V"].asnumpy()[:, 0]][ - unstructured_case.offset_provider["C2E"].asnumpy()[:, 0] + ref=lambda inp: inp[unstructured_case.offset_provider[E2VDim.tag].asnumpy()[:, 0]][ + unstructured_case.offset_provider[C2EDim.tag].asnumpy()[:, 0] ], comparison=lambda inp, tmp: np.all(inp == tmp), ) @@ -408,8 +409,8 @@ def composed_shift_unstructured(inp: cases.VField) -> cases.CField: cases.verify_with_default_data( unstructured_case, composed_shift_unstructured, - ref=lambda inp: inp[unstructured_case.offset_provider["E2V"].asnumpy()[:, 0]][ - unstructured_case.offset_provider["C2E"].asnumpy()[:, 0] + ref=lambda inp: inp[unstructured_case.offset_provider[E2VDim.tag].asnumpy()[:, 0]][ + unstructured_case.offset_provider[C2EDim.tag].asnumpy()[:, 0] ], ) @@ -431,7 +432,7 @@ def testee(a: cases.VField) -> cases.EField: out = cases.allocate(unstructured_case, testee, cases.RETURN)() ORIGIN = 2 - e2v_table = unstructured_case.offset_provider["E2V"].asnumpy() + e2v_table = unstructured_case.offset_provider[E2VDim.tag].asnumpy() neighbor_iter = iter(enumerate(e2v_table)) edge_start = next(i for i, v in neighbor_iter if all(v >= ORIGIN)) edge_stop = next(i for i, v in neighbor_iter if any(v < ORIGIN)) @@ -452,11 +453,12 @@ def testee(a: cases.VField) -> cases.VField: unstructured_case, testee, ref=lambda a: np.sum( - np.sum(a[unstructured_case.offset_provider["E2V"].asnumpy()], axis=1, initial=0)[ - unstructured_case.offset_provider["V2E"].asnumpy() + np.sum(a[unstructured_case.offset_provider[E2VDim.tag].asnumpy()], axis=1, initial=0)[ + unstructured_case.offset_provider[V2EDim.tag].asnumpy() ], axis=1, - where=unstructured_case.offset_provider["V2E"].asnumpy() != common._DEFAULT_SKIP_VALUE, + where=unstructured_case.offset_provider[V2EDim.tag].asnumpy() + != common._DEFAULT_SKIP_VALUE, ), comparison=lambda a, tmp_2: np.all(a == tmp_2), ) @@ -477,8 +479,8 @@ def testee(inp: cases.EField) -> cases.EField: unstructured_case, testee, ref=lambda inp: np.sum( - np.sum(inp[unstructured_case.offset_provider["V2E"].asnumpy()], axis=1)[ - unstructured_case.offset_provider["E2V"].asnumpy() + np.sum(inp[unstructured_case.offset_provider[V2EDim.tag].asnumpy()], axis=1)[ + unstructured_case.offset_provider[E2VDim.tag].asnumpy() ], axis=1, ), @@ -495,7 +497,7 @@ def reduce_tuple_element(e: cases.EField, v: cases.VField) -> cases.EField: tmp = red(E2V[0]) return tmp - v2e = unstructured_case.offset_provider["V2E"] + v2e = unstructured_case.offset_provider[V2EDim.tag] cases.verify_with_default_data( unstructured_case, reduce_tuple_element, @@ -504,7 +506,7 @@ def reduce_tuple_element(e: cases.EField, v: cases.VField) -> cases.EField: axis=1, initial=0, where=v2e.asnumpy() != common._DEFAULT_SKIP_VALUE, - )[unstructured_case.offset_provider["E2V"].asnumpy()[:, 0]], + )[unstructured_case.offset_provider[E2VDim.tag].asnumpy()[:, 0]], ) @@ -516,7 +518,7 @@ def testee(a: cases.EField, b: cases.EField) -> cases.VField: tmp = neighbor_sum(b(V2E) if 2 < 3 else a(V2E), axis=V2EDim) return tmp - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() cases.verify_with_default_data( unstructured_case, testee, @@ -538,7 +540,7 @@ def testee(inp: gtx.Field[[Edge], int32]) -> gtx.Field[[Vertex], int32]: inp = cases.allocate(unstructured_case, testee, "inp")() - v2e_table = unstructured_case.offset_provider["V2E"].asnumpy() + v2e_table = unstructured_case.offset_provider[V2EDim.tag].asnumpy() cases.verify( unstructured_case, testee, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py index 8e46e93fd1..2033f71801 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py @@ -28,6 +28,9 @@ ) +class LDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + @pytest.mark.uses_scan def test_scalar_scan(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=(0.0)) @@ -254,8 +257,6 @@ def testee(a: cases.IFloatField, b: cases.IKFloatField) -> cases.IKFloatField: @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator def test_scan_combined_with_field_on_another_vertical_dim(cartesian_case): - LDim = gtx.Dimension("LDim", kind=gtx.DimensionKind.VERTICAL) - @gtx.scan_operator(axis=KDim, forward=True, init=0.0) def cumsum(state: float, inp: float) -> float: return state + inp diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_staggered.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_staggered.py index 5b7430fc91..ac348266f3 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_staggered.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_staggered.py @@ -13,6 +13,7 @@ from next_tests.integration_tests import cases from next_tests.integration_tests.cases import ( + E2VDim, E2V, Edge, IDim, @@ -222,7 +223,7 @@ def testee( )() out = cases.allocate(unstructured_case_3d, testee, cases.RETURN)() - e2v_table = unstructured_case_3d.offset_provider["E2V"].asnumpy() + e2v_table = unstructured_case_3d.offset_provider[E2VDim.tag].asnumpy() cases.verify( unstructured_case_3d, testee, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py index 8900154140..3db69adf0e 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py @@ -17,6 +17,7 @@ from next_tests.integration_tests import cases from next_tests.integration_tests.cases import ( + E2VDim, E2V, Case, KDim, @@ -38,9 +39,9 @@ def exec_alloc_descriptor(): translation=functools.partial( gtfn.make_gtfn_translation, symbolic_domain_sizes={ - "Cell": "num_cells", - "Edge": "num_edges", - "Vertex": "num_vertices", + Cell.tag: "num_cells", + Edge.tag: "num_edges", + Vertex.tag: "num_vertices", }, ), ) @@ -81,7 +82,9 @@ def test_verification(testee, exec_alloc_descriptor, mesh_descriptor): a = cases.allocate(unstructured_case, testee, "a")() out = cases.allocate(unstructured_case, testee, "out")() - first_nbs, second_nbs = (mesh_descriptor.offset_provider["E2V"].asnumpy()[:, i] for i in [0, 1]) + first_nbs, second_nbs = ( + mesh_descriptor.offset_provider[E2VDim.tag].asnumpy()[:, i] for i in [0, 1] + ) ref = (a.ndarray * 2)[first_nbs] + (a.ndarray * 2)[second_nbs] cases.verify( diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py index c94f908748..84de6fcfbf 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py @@ -177,8 +177,8 @@ def testee(a: cases.EField, b: cases.EField) -> tuple[cases.VField, cases.VField unstructured_case, testee, ref=lambda a, b: [ - np.sum(a[unstructured_case.offset_provider["V2E"].asnumpy()], axis=1), - np.sum(b[unstructured_case.offset_provider["V2E"].asnumpy()], axis=1), + np.sum(a[unstructured_case.offset_provider[V2EDim.tag].asnumpy()], axis=1), + np.sum(b[unstructured_case.offset_provider[V2EDim.tag].asnumpy()], axis=1), ], comparison=lambda a, tmp: (np.all(a[0] == tmp[0]), np.all(a[1] == tmp[1])), ) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_type_conversion.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_type_conversion.py index 2c12d74f50..6a160cefc3 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_type_conversion.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_type_conversion.py @@ -51,7 +51,7 @@ def testee(a: gtx.Field[[Vertex], np.float64]) -> gtx.Field[[Edge], int64]: tmp = astype(a(E2V), int64) return neighbor_sum(tmp, axis=E2VDim) - e2v_table = unstructured_case.offset_provider["E2V"].asnumpy() + e2v_table = unstructured_case.offset_provider[E2VDim.tag].asnumpy() cases.verify_with_default_data( unstructured_case, diff --git a/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py b/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py index 9f51689d77..845a95925c 100644 --- a/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py +++ b/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py @@ -17,6 +17,7 @@ import gt4py.next as gtx from gt4py.next import common, Dims, gtfn_cpu, typing as gtx_typing from gt4py.next.instrumentation import gpu_profiler, hooks +from next_tests.integration_tests.cases_utils import IDim try: from gt4py.next.program_processors.runners import dace as dace_backends @@ -26,9 +27,6 @@ BACKENDS = [None, gtfn_cpu] -IDim = gtx.Dimension("IDim") - - @gtx.field_operator def fop(cond: bool, a: gtx.Field[gtx.Dims[IDim], float], b: gtx.Field[gtx.Dims[IDim], float]): return a if cond else b diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py index 408f0d9d5f..e0ce6e5bfa 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py @@ -54,6 +54,13 @@ from next_tests.integration_tests.feature_tests.math_builtin_test_data import math_builtin_test_data from next_tests.unit_tests.conftest import program_processor, run_processor +from next_tests.integration_tests.cases_utils import IDim + + +class Node(gtx.DimensionIndex): ... + + +class NeighDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... def array_maker(*lists): @@ -67,9 +74,6 @@ def _listify(val): return res -IDim = gtx.Dimension("IDim") - - def field_maker(*arrays): res = list(map(gtx.as_field.partial([IDim]), arrays)) return res @@ -241,9 +245,6 @@ def foo(a): def test_can_deref(program_processor, stencil): program_processor, validate = program_processor - Node = gtx.Dimension("Node") - NeighDim = gtx.Dimension("Neighbor", kind=gtx.DimensionKind.LOCAL) - inp = gtx.as_field([Node], np.ones((1,), dtype=np.int32)) out = gtx.as_field([Node], np.asarray([0], dtype=inp.dtype)) diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_conditional.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_conditional.py index eae66d425b..9ffa655593 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_conditional.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_conditional.py @@ -14,9 +14,7 @@ from gt4py.next.iterator.runtime import set_at, fendef, fundef from next_tests.unit_tests.conftest import program_processor, run_processor - - -IDim = gtx.Dimension("IDim") +from next_tests.integration_tests.cases_utils import IDim @fundef diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_implicit_fencil.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_implicit_fencil.py index 66a1edc189..1078764bc2 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_implicit_fencil.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_implicit_fencil.py @@ -16,7 +16,8 @@ from next_tests.unit_tests.conftest import program_processor, run_processor -I = gtx.Dimension("I") +class I(gtx.CartesianAxisIndex): ... + _isize = 10 diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_program.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_program.py index 5a386ee807..74dd1dda21 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_program.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_program.py @@ -25,7 +25,9 @@ from next_tests.unit_tests.conftest import program_processor, run_processor -I = gtx.Dimension("I") +class I(gtx.CartesianAxisIndex): ... + + Ioff = gtx.CartesianConnectivity(I) diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_strided_offset_provider.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_strided_offset_provider.py index 68e5f9d532..bd675b5f51 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_strided_offset_provider.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_strided_offset_provider.py @@ -17,13 +17,21 @@ from gt4py.next.iterator.embedded import StridedConnectivityField -LocA = gtx.Dimension("LocA") -LocAB = gtx.Dimension("LocAB") -LocB = gtx.Dimension("LocB") # unused +class Dummy(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +class LocA(gtx.DimensionIndex): ... + + +class LocAB(gtx.DimensionIndex): ... + + +class LocB(gtx.DimensionIndex): ... + LocA2LocAB = offset("O") LocA2LocAB_offset_provider = StridedConnectivityField( - domain_dims=(LocA, gtx.Dimension("Dummy", kind=gtx.DimensionKind.LOCAL)), + domain_dims=(LocA, Dummy), codomain_dim=LocAB, max_neighbors=2, ) diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_tuple.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_tuple.py index 95a1eb67f0..f1cd666b83 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_tuple.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_tuple.py @@ -16,9 +16,14 @@ from next_tests.unit_tests.conftest import program_processor, run_processor -IDim = gtx.Dimension("IDim") -JDim = gtx.Dimension("JDim") -KDim = gtx.Dimension("KDim") +class IDim(gtx.CartesianAxisIndex): ... + + +class JDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex): ... + # semantics of stencil return that is called from the fencil (after `:` the structure of the output) # `return a` -> a: field diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py index 2b4847d3c3..daaf9d05f8 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py @@ -88,7 +88,7 @@ def test_ffront_compute_zavgS(exec_alloc_descriptor): setup.input_field, setup.S_fields[0], out=zavgS, - offset_provider={"E2V": setup.edges2node_connectivity}, + offset_provider={E2VDim.tag: setup.edges2node_connectivity}, ) assert_close(-199755464.25741270, np.min(zavgS.asnumpy())) @@ -113,8 +113,8 @@ def test_ffront_nabla(exec_alloc_descriptor): setup.vol_field, out=(pnabla_MXX, pnabla_MYY), offset_provider={ - "E2V": setup.edges2node_connectivity, - "V2E": setup.nodes2edge_connectivity, + E2VDim.tag: setup.edges2node_connectivity, + V2EDim.tag: setup.nodes2edge_connectivity, }, ) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py index 97f81a2086..7548654617 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py @@ -30,10 +30,6 @@ ] -Cell = gtx.Dimension("Cell") -KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) - - class State(NamedTuple): z_q_new: float w_new: float diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py index 5437c45484..134ea7b342 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py @@ -14,6 +14,8 @@ import gt4py.next as gtx from next_tests.integration_tests import cases from next_tests.integration_tests.cases import ( + E2VDim, + C2EDim, IDim, JDim, KDim, @@ -553,7 +555,7 @@ def test_program_unstructured(unstructured_case): unstructured_case.default_sizes[Cell], unstructured_case.default_sizes[Edge], inout=(out_a_shifted, out_a), - ref=(a.asnumpy()[unstructured_case.offset_provider["C2E"].asnumpy()[:, 1]], a), + ref=(a.asnumpy()[unstructured_case.offset_provider[C2EDim.tag].asnumpy()[:, 1]], a), ) @@ -608,7 +610,7 @@ def test_program_temporary(unstructured_case): extend={Cell: (-restrict_cell[0], restrict_cell[1])}, )() - e2v = a.asnumpy()[unstructured_case.offset_provider["E2V"].asnumpy()[:, 1]] + e2v = a.asnumpy()[unstructured_case.offset_provider[E2VDim.tag].asnumpy()[:, 1]] cases.verify( unstructured_case, prog_temporary, @@ -624,7 +626,7 @@ def test_program_temporary(unstructured_case): inout=(out_edge, out_cell), ref=( e2v[restrict_edge[0] : edge_size + restrict_edge[1]], - e2v[unstructured_case.offset_provider["C2E"].asnumpy()[:, 1]][ + e2v[unstructured_case.offset_provider[C2EDim.tag].asnumpy()[:, 1]][ restrict_cell[0] : cell_size + restrict_cell[1] ], ), diff --git a/tests/next_tests/integration_tests/multi_feature_tests/fvm_nabla_setup.py b/tests/next_tests/integration_tests/multi_feature_tests/fvm_nabla_setup.py index 84c8937b7e..ad0ee43cf4 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/fvm_nabla_setup.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/fvm_nabla_setup.py @@ -10,6 +10,7 @@ import numpy as np + try: from atlas4py import ( Config, @@ -35,14 +36,11 @@ from gt4py import next as gtx from gt4py.next.iterator import atlas_utils +from next_tests.toy_connectivity import E2VDim, Edge, V2EDim, Vertex -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -V2E = gtx.FieldOffset("V2E", source=Edge, target=(Vertex, V2EDim)) -E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) +V2E = gtx.FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) +E2V = gtx.FieldOffset(E2VDim.tag, source=Vertex, target=(Edge, E2VDim)) def assert_close(expected, actual): diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_anton_toy.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_anton_toy.py index 6ae2af59a9..485d8fca6b 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_anton_toy.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_anton_toy.py @@ -24,9 +24,13 @@ from next_tests.unit_tests.conftest import program_processor, run_processor -IDim = gtx.Dimension("IDim") -JDim = gtx.Dimension("JDim") -KDim = gtx.Dimension("KDim") +class IDim(gtx.CartesianAxisIndex): ... + + +class JDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex): ... # cross-reference why new type inference does not support this diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_fvm_nabla.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_fvm_nabla.py index e7984f7cd3..587c279b68 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_fvm_nabla.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_fvm_nabla.py @@ -31,18 +31,18 @@ from gt4py.next.iterator.runtime import set_at, fendef, fundef, offset from next_tests.integration_tests.multi_feature_tests.fvm_nabla_setup import ( + E2VDim, + Edge, + V2EDim, + Vertex, assert_close, nabla_setup, ) from next_tests.unit_tests.conftest import program_processor, run_processor -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) - -V2E = offset("V2E") -E2V = offset("E2V") +V2E = offset(V2EDim.tag) +E2V = offset(E2VDim.tag) @fundef @@ -119,7 +119,7 @@ def test_compute_zavgS(program_processor): zavgS, setup.input_field, setup.S_fields[0], - offset_provider={"E2V": setup.edges2node_connectivity}, + offset_provider={E2VDim.tag: setup.edges2node_connectivity}, ) if validate: @@ -133,7 +133,7 @@ def test_compute_zavgS(program_processor): zavgS, setup.input_field, setup.S_fields[1], - offset_provider={"E2V": setup.edges2node_connectivity}, + offset_provider={E2VDim.tag: setup.edges2node_connectivity}, ) if validate: assert_close(-1000788897.3202186, np.min(zavgS.asnumpy())) @@ -167,7 +167,7 @@ def test_compute_zavgS2(program_processor): zavgS, setup.input_field, setup.S_fields, - offset_provider={"E2V": setup.edges2node_connectivity}, + offset_provider={E2VDim.tag: setup.edges2node_connectivity}, ) if validate: @@ -203,8 +203,8 @@ def test_nabla(program_processor): setup.sign_field, setup.vol_field, offset_provider={ - "E2V": setup.edges2node_connectivity, - "V2E": setup.nodes2edge_connectivity, + E2VDim.tag: setup.edges2node_connectivity, + V2EDim.tag: setup.nodes2edge_connectivity, }, ) @@ -243,8 +243,8 @@ def test_nabla2(program_processor): setup.sign_field, setup.vol_field, offset_provider={ - "E2V": setup.edges2node_connectivity, - "V2E": setup.nodes2edge_connectivity, + E2VDim.tag: setup.edges2node_connectivity, + V2EDim.tag: setup.nodes2edge_connectivity, }, ) @@ -321,8 +321,8 @@ def test_nabla_sign(program_processor): vertex_index, # TODO(havogt): should be an index function field setup.is_pole_edge_field, offset_provider={ - "E2V": setup.edges2node_connectivity, - "V2E": setup.nodes2edge_connectivity, + E2VDim.tag: setup.edges2node_connectivity, + V2EDim.tag: setup.nodes2edge_connectivity, }, ) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_if_stmt.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_if_stmt.py index 1aac9c76d1..79af99d26c 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_if_stmt.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_if_stmt.py @@ -15,6 +15,7 @@ from gt4py.next.iterator.runtime import fendef, fundef, if_stmt, set_at from next_tests.unit_tests.conftest import program_processor_no_transforms, run_processor +from next_tests.integration_tests.cases_utils import IDim @fundef @@ -22,9 +23,6 @@ def multiply(alpha, inp): return deref(alpha) * deref(inp) -IDim = gtx.Dimension("IDim") - - @pytest.mark.uses_ir_if_stmts @pytest.mark.parametrize("cond", [True, False]) def test_if_stmt(program_processor_no_transforms, cond): diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_temporaries.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_temporaries.py index 60aef83302..1138fccc5e 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_temporaries.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_temporaries.py @@ -22,11 +22,9 @@ from gt4py.next.iterator.runtime import fendef, fundef, set_at, temporary from next_tests.unit_tests.conftest import program_processor_no_transforms, run_processor +from next_tests.integration_tests.cases_utils import IDim, JDim -IDim = gtx.Dimension("IDim") -JDim = gtx.Dimension("JDim") - i = gtx.CartesianConnectivity(IDim) j = gtx.CartesianConnectivity(JDim) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_with_toy_connectivity.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_with_toy_connectivity.py index ad2337237d..fdf8cf5114 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_with_toy_connectivity.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_with_toy_connectivity.py @@ -27,6 +27,7 @@ from gt4py.next.program_processors.runners import gtfn from next_tests.toy_connectivity import ( + C2EDim, C2E, E2V, V2E, @@ -93,7 +94,7 @@ def test_sum_edges_to_vertices(program_processor, stencil): program_processor, inp, out=out, - offset_provider={"V2E": v2e_conn}, + offset_provider={V2EDim.tag: v2e_conn}, ) if validate: assert np.allclose(out.asnumpy(), ref) @@ -115,7 +116,7 @@ def test_map_neighbors(program_processor): program_processor, inp, out=out, - offset_provider={"V2E": v2e_conn}, + offset_provider={V2EDim.tag: v2e_conn}, ) if validate: assert np.allclose(out.asnumpy(), ref) @@ -138,7 +139,7 @@ def test_map_make_const_list(program_processor): program_processor, inp, out=out, - offset_provider={"V2E": v2e_conn}, + offset_provider={V2EDim.tag: v2e_conn}, ) if validate: assert np.allclose(out.asnumpy(), ref) @@ -162,8 +163,8 @@ def test_first_vertex_neigh_of_first_edge_neigh_of_cells_fencil(program_processo inp, out=out, offset_provider={ - "E2V": e2v_conn, - "C2E": c2e_conn, + E2VDim.tag: e2v_conn, + C2EDim.tag: c2e_conn, }, ) if validate: @@ -191,7 +192,7 @@ def test_sparse_input_field(program_processor): non_sparse, inp, out=out, - offset_provider={"V2E": v2e_conn}, + offset_provider={V2EDim.tag: v2e_conn}, ) if validate: @@ -215,8 +216,8 @@ def test_sparse_input_field_v2v(program_processor): inp, out=out, offset_provider={ - "V2V": v2v_conn, - "V2E": v2e_conn, + V2VDim.tag: v2v_conn, + V2EDim.tag: v2e_conn, }, ) @@ -242,7 +243,7 @@ def test_slice_sparse(program_processor): program_processor, inp, out=out, - offset_provider={"V2V": v2v_conn}, + offset_provider={V2VDim.tag: v2v_conn}, ) if validate: @@ -266,7 +267,7 @@ def test_slice_twice_sparse(program_processor): program_processor, inp, out=out, - offset_provider={"V2V": v2v_conn}, + offset_provider={V2VDim.tag: v2v_conn}, ) if validate: @@ -291,7 +292,7 @@ def test_slice_shifted_sparse(program_processor): program_processor, inp, out=out, - offset_provider={"V2V": v2v_conn}, + offset_provider={V2VDim.tag: v2v_conn}, ) if validate: @@ -320,7 +321,7 @@ def test_lift(program_processor): program_processor, inp, out=out, - offset_provider={"V2V": v2v_conn}, + offset_provider={V2VDim.tag: v2v_conn}, ) if validate: assert np.allclose(out.asnumpy(), ref) @@ -343,7 +344,7 @@ def test_shift_sparse_input_field(program_processor): program_processor, inp, out=out, - offset_provider={"V2V": v2v_conn}, + offset_provider={V2VDim.tag: v2v_conn}, ) if validate: @@ -373,8 +374,8 @@ def test_shift_sparse_input_field2(program_processor): out2 = gtx.as_field([Vertex], np.zeros([9], dtype=inp.dtype)) offset_provider = { - "E2V": e2v_conn, - "V2E": v2e_conn, + E2VDim.tag: e2v_conn, + V2EDim.tag: v2e_conn, } domain = {Vertex: range(0, 9)} @@ -428,7 +429,7 @@ def test_sparse_shifted_stencil_reduce(program_processor): program_processor, inp, out=out, - offset_provider={"V2V": v2v_conn}, + offset_provider={V2VDim.tag: v2v_conn}, ) if validate: diff --git a/tests/next_tests/regression_tests/embedded_tests/test_domain_pickle.py b/tests/next_tests/regression_tests/embedded_tests/test_domain_pickle.py index b69950928d..7e34c727aa 100644 --- a/tests/next_tests/regression_tests/embedded_tests/test_domain_pickle.py +++ b/tests/next_tests/regression_tests/embedded_tests/test_domain_pickle.py @@ -10,8 +10,11 @@ from gt4py.next import common -I = common.Dimension("I") -J = common.Dimension("J") + +class I(common.CartesianAxisIndex): ... + + +class J(common.CartesianAxisIndex): ... def test_domain_pickle_after_slice(): diff --git a/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py b/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py index 89a72b428f..689d0d5f71 100644 --- a/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py +++ b/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py @@ -36,15 +36,23 @@ ) -V = gtx.Dimension("V") -E = gtx.Dimension("E") +class V(gtx.DimensionIndex): ... + + +class E(gtx.DimensionIndex): ... + + +#: N1 == N3 == N4, but N2 differs: the tag is `TaggedOffDim.tag`, the variable is `off_a`. +class TaggedOffDim(gtx.DimensionIndex, kind=common.DimensionKind.LOCAL): ... + + +off_a = gtx.FieldOffset(TaggedOffDim.tag, source=E, target=(V, TaggedOffDim)) -#: N1 == N3 == N4, but N2 differs: the tag is `TaggedOff`, the variable is `off_a`. -TaggedOffDim = gtx.Dimension("TaggedOff", kind=common.DimensionKind.LOCAL) -off_a = gtx.FieldOffset("TaggedOff", source=E, target=(V, TaggedOffDim)) #: N1 == N2 == N4, but N3 differs: the local dimension is `Neigh`, the tag is `OffB`. -Neigh = gtx.Dimension("Neigh", kind=common.DimensionKind.LOCAL) +class Neigh(gtx.DimensionIndex, kind=common.DimensionKind.LOCAL): ... + + OffB = gtx.FieldOffset("OffB", source=E, target=(V, Neigh)) @@ -61,7 +69,7 @@ def _case(exec_alloc_descriptor, tag: str, local_dim: common.Dimension) -> cases mesh = cases_utils.simple_mesh(exec_alloc_descriptor.allocator) # NOTE: `.asnumpy()`, not `.ndarray`: under a GPU allocator the latter is a device # array, and `simple_mesh` builds the table from NumPy anyway. - v2e_arr = mesh.offset_provider["V2E"].asnumpy() + v2e_arr = mesh.offset_provider[cases_utils.V2EDim.tag].asnumpy() return cases.Case( ( None @@ -85,7 +93,7 @@ def _case(exec_alloc_descriptor, tag: str, local_dim: common.Dimension) -> cases @pytest.fixture def case_tag_vs_variable_name(exec_alloc_descriptor): - return _case(exec_alloc_descriptor, "TaggedOff", TaggedOffDim) + return _case(exec_alloc_descriptor, TaggedOffDim.tag, TaggedOffDim) @pytest.fixture @@ -110,7 +118,7 @@ def foo(a: Field[Dims[E], float]) -> Field[Dims[V], float]: cases.verify_with_default_data( case_tag_vs_variable_name, foo, - lambda a: a[_neighbor_table(case_tag_vs_variable_name, "TaggedOff")[:, 1]], + lambda a: a[_neighbor_table(case_tag_vs_variable_name, TaggedOffDim.tag)[:, 1]], ) @@ -122,7 +130,7 @@ def foo(a: Field[Dims[E], float]) -> Field[Dims[V], float]: cases.verify_with_default_data( case_tag_vs_variable_name, foo, - lambda a: np.sum(a[_neighbor_table(case_tag_vs_variable_name, "TaggedOff")], axis=1), + lambda a: np.sum(a[_neighbor_table(case_tag_vs_variable_name, TaggedOffDim.tag)], axis=1), ) diff --git a/tests/next_tests/toy_connectivity.py b/tests/next_tests/toy_connectivity.py index 154b666c5d..c368b04245 100644 --- a/tests/next_tests/toy_connectivity.py +++ b/tests/next_tests/toy_connectivity.py @@ -12,18 +12,31 @@ from gt4py.next.iterator import builtins, ir as itir -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -Cell = gtx.Dimension("Cell") -V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -C2EDim = gtx.Dimension("C2E", kind=gtx.DimensionKind.LOCAL) -V2VDim = gtx.Dimension("V2V", kind=gtx.DimensionKind.LOCAL) - -V2E = gtx.FieldOffset("V2E", source=Edge, target=(Vertex, V2EDim)) -E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) -C2E = gtx.FieldOffset("C2E", source=Edge, target=(Cell, C2EDim)) -V2V = gtx.FieldOffset("V2V", source=Vertex, target=(Vertex, V2VDim)) +class Vertex(gtx.DimensionIndex): ... + + +class Edge(gtx.DimensionIndex): ... + + +class Cell(gtx.DimensionIndex): ... + + +class V2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +class E2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +class C2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +class V2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +V2E = gtx.FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) +E2V = gtx.FieldOffset(E2VDim.tag, source=Vertex, target=(Edge, E2VDim)) +C2E = gtx.FieldOffset(C2EDim.tag, source=Edge, target=(Cell, C2EDim)) +V2V = gtx.FieldOffset(V2VDim.tag, source=Vertex, target=(Vertex, V2VDim)) # 3x3 periodic edges cells # 0 - 1 - 2 - 0 1 2 diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index 1afb82397c..d22e1711d3 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -26,6 +26,12 @@ import next_tests +class dummy_origin(gtx.DimensionIndex): ... + + +class dummy_neighbor(gtx.DimensionIndex): ... + + ProgramProcessor: TypeAlias = backend.Backend | program_formatter.ProgramFormatter @@ -98,8 +104,8 @@ def run_processor( class DummyConnectivity(common.Connectivity): max_neighbors: int has_skip_values: int - source_dim: gtx.Dimension = gtx.Dimension("dummy_origin") - codomain: gtx.Dimension = gtx.Dimension("dummy_neighbor") + source_dim: gtx.Dimension = dummy_origin + codomain: gtx.Dimension = dummy_neighbor def _optional_module(name: str) -> list[ModuleType]: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py index ff369bec0a..5a2d8ae15a 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -19,7 +19,7 @@ from next_tests.unit_tests.conftest import asarray, strict_array_on_device1 -D = common.Dimension("D") +class D(common.DimensionIndex): ... @pytest.fixture diff --git a/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py b/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py index 025957fdab..6fafb8b3f0 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py @@ -12,8 +12,7 @@ import gt4py.next as gtx from gt4py.next import errors - -IDim = gtx.Dimension("IDim") +from next_tests.integration_tests.cases_utils import IDim, KDim @gtx.field_operator @@ -42,9 +41,6 @@ def test_basic(): assert np.allclose(out.ndarray, a.ndarray + b.ndarray) -KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) - - @gtx.scan_operator(axis=KDim, forward=True, init=0.0) def cumsum(state: gtx.float64, inp: gtx.float64) -> gtx.float64: return state + inp diff --git a/tests/next_tests/unit_tests/embedded_tests/test_common.py b/tests/next_tests/unit_tests/embedded_tests/test_common.py index fc7272ae2d..48e48d713e 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_common.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_common.py @@ -13,7 +13,7 @@ import pytest from gt4py.next import common -from gt4py.next.common import UnitRange, NamedIndex, NamedRange +from gt4py.next.common import UnitRange, DimensionIndex from gt4py.next.embedded import exceptions as embedded_exceptions from gt4py.next.embedded.common import ( _slice_range, @@ -39,9 +39,16 @@ def test_slice_range(rng, slce, expected): assert result == expected -I = common.Dimension("I") -J = common.Dimension("J") -K = common.Dimension("K") +class I(common.CartesianAxisIndex): ... + + +class J(common.CartesianAxisIndex): ... + + +class K(common.CartesianAxisIndex): ... + + +class KV(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... @pytest.mark.parametrize( @@ -49,12 +56,12 @@ def test_slice_range(rng, slce, expected): [ ([(I, (2, 5))], 1, []), ([(I, (2, 5))], slice(1, 2), [(I, (3, 4))]), - ([(I, (2, 5))], NamedIndex(I, 2), []), - ([(I, (2, 5))], NamedRange(I, UnitRange(2, 3)), [(I, (2, 3))]), + ([(I, (2, 5))], I(2), []), + ([(I, (2, 5))], I.at(2, 3), [(I, (2, 3))]), ([(I, (-2, 3))], 1, []), ([(I, (-2, 3))], slice(1, 2), [(I, (-1, 0))]), - ([(I, (-2, 3))], NamedIndex(I, 1), []), - ([(I, (-2, 3))], NamedRange(I, UnitRange(2, 3)), [(I, (2, 3))]), + ([(I, (-2, 3))], I(1), []), + ([(I, (-2, 3))], I.at(2, 3), [(I, (2, 3))]), ([(I, (-2, 3))], -5, []), ([(I, (-2, 3))], -6, IndexError), ([(I, (-2, 3))], slice(-7, -6), IndexError), @@ -63,36 +70,45 @@ def test_slice_range(rng, slce, expected): ([(I, (-2, 3))], 5, IndexError), ([(I, (-2, 3))], slice(4, 5), [(I, (2, 3))]), ([(I, (-2, 3))], slice(5, 6), IndexError), - ([(I, (-2, 3))], NamedIndex(I, -3), IndexError), - ([(I, (-2, 3))], NamedRange(I, UnitRange(-3, -2)), IndexError), - ([(I, (-2, 3))], NamedIndex(I, 3), IndexError), - ([(I, (-2, 3))], NamedRange(I, UnitRange(3, 4)), IndexError), + ([(I, (-2, 3))], I(-3), IndexError), + ([(I, (-2, 3))], I.at(-3, -2), IndexError), + ([(I, (-2, 3))], I(3), IndexError), + ([(I, (-2, 3))], I.at(3, 4), IndexError), + # an open bound extends to the domain's own bound + ([(I, (2, 5))], I.at(3, None), [(I, (3, 5))]), + ([(I, (2, 5))], I.at(None, 4), [(I, (2, 4))]), + ([(I, (2, 5))], I.at(None, None), [(I, (2, 5))]), + ([(I, (2, 5))], I.at(5, None), [(I, (5, 5))]), + ([(I, (2, 5))], I.at(6, None), IndexError), + ([(I, (2, 5))], I.at(1, None), IndexError), + ([(I, (2, 5))], I.at(None, 6), IndexError), + ([(I, (2, 5))], I.at(None, 1), IndexError), ([(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], 2, [(J, (3, 6)), (K, (4, 7))]), ( [(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], slice(2, 3), [(I, (4, 5)), (J, (3, 6)), (K, (4, 7))], ), - ([(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], NamedIndex(I, 2), [(J, (3, 6)), (K, (4, 7))]), + ([(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], I(2), [(J, (3, 6)), (K, (4, 7))]), ( [(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], - NamedRange(I, UnitRange(2, 3)), + I.at(2, 3), [(I, (2, 3)), (J, (3, 6)), (K, (4, 7))], ), - ([(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], NamedIndex(J, 3), [(I, (2, 5)), (K, (4, 7))]), + ([(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], J(3), [(I, (2, 5)), (K, (4, 7))]), ( [(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], - NamedRange(J, UnitRange(4, 5)), + J.at(4, 5), [(I, (2, 5)), (J, (4, 5)), (K, (4, 7))], ), ( [(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], - (NamedIndex(J, 3), NamedIndex(I, 2)), + (J(3), I(2)), [(K, (4, 7))], ), ( [(I, (2, 5)), (J, (3, 6)), (K, (4, 7))], - (NamedRange(J, UnitRange(4, 5)), NamedIndex(I, 2)), + (J.at(4, 5), I(2)), [(J, (4, 5)), (K, (4, 7))], ), ( @@ -131,9 +147,9 @@ def test_sub_domain(domain, index, expected): def test_iterate_domain(): domain = common.domain({I: 2, J: 3}) ref = [] - for i in domain[I].unit_range: - for j in domain[J].unit_range: - ref.append(((I, i), (J, j))) + for i in domain[I].value: + for j in domain[J].value: + ref.append((I(i), J(j))) testee = list(iterate_domain(domain)) @@ -143,19 +159,26 @@ def test_iterate_domain(): @pytest.mark.parametrize( "slices, expected", [ - [slice(I(3), I(4)), (NamedRange(I, common.UnitRange(3, 4)),)], + [slice(I(3), I(4)), (I.at(3, 4),)], [ (slice(J(3), J(6)), slice(I(3), I(5))), - (NamedRange(J, common.UnitRange(3, 6)), NamedRange(I, common.UnitRange(3, 5))), + (J.at(3, 6), I.at(3, 5)), ], - [slice(I(1), J(7)), IndexError], - [slice(I(1), None), IndexError], - [slice(None, K(8)), IndexError], + [slice(I(1), None), (I.at(1, None),)], + [slice(None, K(8)), (K.at(None, 8),)], + [slice(I(1), I(3), 1), (I.at(1, 3),)], + [(I(2), slice(J(3), J(6))), (I(2), J.at(3, 6))], + [(slice(1, 2), slice(2, 3)), (slice(1, 2), slice(2, 3))], # relative: unchanged + [slice(I(1), J(7)), (IndexError, "mismatch between 'I' and 'J'")], + [slice(I(1), I(7), 2), (IndexError, "step")], + [slice(I(1), 7), (IndexError, "both bounds must be indices")], + [(slice(I(1), I(7)), 2), (IndexError, "Cannot mix relative index")], + [(slice(I(1), I(3)), slice(0, 2)), (IndexError, "Cannot mix relative index")], ], ) def test_slicing(slices, expected): - if expected is IndexError: - with pytest.raises(IndexError): + if isinstance(expected, tuple) and expected[0] is IndexError: + with pytest.raises(IndexError, match=expected[1]): canonicalize_any_index_sequence(slices) else: testee = canonicalize_any_index_sequence(slices) @@ -197,8 +220,7 @@ def test_domain_intersection_matches_pairwise_and(testee): def test_domain_intersection_equal_domains_unordered_dims(): - K_vertical = common.Dimension("K", kind=common.DimensionKind.VERTICAL) - unordered = common.Domain(dims=(K_vertical, I), ranges=(UnitRange(0, 2), UnitRange(0, 3))) + unordered = common.Domain(dims=(KV, I), ranges=(UnitRange(0, 2), UnitRange(0, 3))) with pytest.raises(ValueError, match="not ordered correctly"): domain_intersection(unordered, unordered) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_context.py b/tests/next_tests/unit_tests/embedded_tests/test_context.py index 36fe0d0c71..0431ae9eb0 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_context.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_context.py @@ -11,6 +11,10 @@ import gt4py.next.embedded.context as ctx import gt4py.next.common as common from gt4py.next.errors import exceptions +from next_tests.integration_tests.cases_utils import IDim + + +class NewDim(common.CartesianAxisIndex): ... def test_getters(): @@ -30,16 +34,14 @@ def test_update_with_both_parameters(): assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - initial_column_range = (common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)),) + initial_column_range = (common.DimensionRange(IDim, common.UnitRange(0, 4)),) initial_offset_provider = {} with ctx.update(column_ranges=initial_column_range, offset_provider=initial_offset_provider): assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - test_column_range = ( - common.NamedRange(common.Dimension("NewDim"), common.UnitRange(-1, 1)), - ) + test_column_range = (common.DimensionRange(NewDim, common.UnitRange(-1, 1)),) test_offset_provider = {"I": "NewDim"} with ctx.update(column_ranges=test_column_range, offset_provider=test_offset_provider): @@ -58,7 +60,7 @@ def test_update_with_no_parameters(): assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - initial_column_range = (common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)),) + initial_column_range = (common.DimensionRange(IDim, common.UnitRange(0, 4)),) initial_offset_provider = {} with ctx.update(column_ranges=initial_column_range, offset_provider=initial_offset_provider): @@ -81,7 +83,7 @@ def test_update_with_exception(): assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - initial_column_range = (common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)),) + initial_column_range = (common.DimensionRange(IDim, common.UnitRange(0, 4)),) initial_offset_provider = {} with pytest.raises(RuntimeError, match="Outer exception"): @@ -91,9 +93,7 @@ def test_update_with_exception(): assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - test_column_range = ( - common.NamedRange(common.Dimension("NewDim"), common.UnitRange(-1, 1)), - ) + test_column_range = (common.DimensionRange(NewDim, common.UnitRange(-1, 1)),) test_offset_provider = {"I": "NewDim"} with pytest.raises(RuntimeError, match="Inner exception"): diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index a851bd1d55..13432fdddd 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -13,19 +13,19 @@ from typing import Callable, Iterable, Optional import array_api_compat -import array_api_strict import numpy as np import pytest from gt4py._core import definitions as core_defs from gt4py.next import common, constructors from gt4py.next.common import ( + CartesianAxisIndex, Dimension, + DimensionIndex, DimensionKind, Domain, Field, - NamedIndex, - NamedRange, + Staggered, UnitRange, ) from gt4py.next.embedded import ( @@ -49,9 +49,67 @@ ) -D0 = Dimension("D0") -D1 = Dimension("D1") -D2 = Dimension("D2") +class I(CartesianAxisIndex): ... + + +class J(CartesianAxisIndex): ... + + +class V(DimensionIndex): ... + + +class E(DimensionIndex): ... + + +class E2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class V2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class C(DimensionIndex): ... + + +class K(CartesianAxisIndex): ... + + +class C2E2CO(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class A(DimensionIndex): ... + + +class B(DimensionIndex): ... + + +class X(CartesianAxisIndex): ... + + +class Y(CartesianAxisIndex): ... + + +class L(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class S(DimensionIndex): ... + + +class T(DimensionIndex): ... + + +class U(DimensionIndex): ... + + +class M(DimensionIndex): ... + + +class C2V(DimensionIndex): ... + + +class KV(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + + +_DEFAULT_DIMS = (I, J, K) @pytest.fixture( @@ -83,9 +141,25 @@ def unary_logical_op(request): yield request.param +def _default_dim(i: int) -> Dimension: + """ + Return the `i`-th default dimension: `I`, `J`, `K`, then `D3`, `D4`, ... created on first use. + + The dimensions must be *stable across calls*: two domains built by separate calls are + compared by the tests, and a fresh class per call would be a different dimension. Each is + bound as a module attribute, so it is also importable by its qualified name. + """ + if i < len(_DEFAULT_DIMS): + return _DEFAULT_DIMS[i] + name = f"D{i}" + if name not in globals(): + globals()[name] = type(name, (common.DimensionIndex,), {"__module__": __name__}) + return globals()[name] + + def _make_default_domain(shape: tuple[int, ...]) -> Domain: return common.Domain( - dims=tuple(Dimension(f"D{i}") for i in range(len(shape))), + dims=tuple(_default_dim(i) for i in range(len(shape))), ranges=tuple(UnitRange(0, s) for s in shape), ) @@ -123,7 +197,7 @@ def are_equal_fields(a: Field, b: Field) -> bool: def test_nd_array_field_buffer_info(nd_array_implementation): data = asarray(nd_array_implementation, [[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) - field = common._field(data, domain=common.domain({D0: 2, D1: 2})) + field = common._field(data, domain=common.domain({I: 2, J: 2})) assert field.array_ns is nd_array_implementation field_ndarray = field.ndarray @@ -146,7 +220,7 @@ def test_nd_array_field_buffer_info(nd_array_implementation): def test_nd_array_field_buffer_info_refreshed_on_buffer_replacement(nd_array_implementation): def make_field(): data = asarray(nd_array_implementation, [[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) - return common._field(data, domain=common.domain({D0: 2, D1: 2})) + return common._field(data, domain=common.domain({I: 2, J: 2})) exported, not_exported = make_field(), make_field() old_buffer = exported.ndarray @@ -220,16 +294,14 @@ def test_where_builtin_different_domain(nd_array_implementation): true_ = np.asarray([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32) false_ = np.asarray([7.0, 8.0, 9.0, 10.0], dtype=np.float32) - cond_field = common._field( - asarray(nd_array_implementation, cond), domain=common.domain({D1: 2}) - ) + cond_field = common._field(asarray(nd_array_implementation, cond), domain=common.domain({J: 2})) true_field = common._field( asarray(nd_array_implementation, true_), - domain=common.domain({D0: common.UnitRange(0, 2), D1: common.UnitRange(-1, 2)}), + domain=common.domain({I: common.UnitRange(0, 2), J: common.UnitRange(-1, 2)}), ) false_field = common._field( asarray(nd_array_implementation, false_), - domain=common.domain({D1: common.UnitRange(-1, 3)}), + domain=common.domain({J: common.UnitRange(-1, 3)}), ) expected = np.where(cond[np.newaxis, :], true_[:, 1:], false_[np.newaxis, 1:-1]) @@ -327,14 +399,14 @@ def test_unary_arithmetic_ops(unary_arithmetic_op, nd_array_implementation): @pytest.mark.parametrize( - "dims,expected_indices", [((D0,), (slice(5, 10), None)), ((D1,), (None, slice(5, 10)))] + "dims,expected_indices", [((I,), (slice(5, 10), None)), ((J,), (None, slice(5, 10)))] ) def test_binary_operations_with_intersection(binary_arithmetic_op, dims, expected_indices): arr1 = np.arange(10) arr1_domain = common.Domain(dims=dims, ranges=(UnitRange(0, 10),)) arr2 = np.ones((5, 5)) - arr2_domain = common.Domain(dims=(D0, D1), ranges=(UnitRange(5, 10), UnitRange(5, 10))) + arr2_domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 10), UnitRange(5, 10))) field1 = common._field(arr1, domain=arr1_domain) field2 = common._field(arr2, domain=arr2_domain) @@ -392,7 +464,7 @@ def test_broadcast_0d_array(nd_array_implementation): two = asarray(nd_array_implementation, 2.0, dtype=np.float32) field = _make_field_or_scalar([1.0, 2.0, 3.0], nd_array_implementation) - broadcasted = fbuiltins.broadcast(two, (D0,)) + broadcasted = fbuiltins.broadcast(two, (I,)) # as for a scalar: the value itself, which broadcasts in the operations it takes part in assert broadcasted is two @@ -402,7 +474,7 @@ def test_broadcast_0d_array(nd_array_implementation): def test_where_with_0d_array_branches(nd_array_implementation): mask = common._field( asarray(nd_array_implementation, [True, False], dtype=np.bool_), - domain=common.domain({D0: 2}), + domain=common.domain({I: 2}), ) one = asarray(nd_array_implementation, 1.0, dtype=np.float32) @@ -463,7 +535,6 @@ def test_mixed_fields_concat_where(product_nd_array_implementation): first_impl, second_impl = product_nd_array_implementation if not is_cupy(first_impl) and is_cupy(second_impl): pytest.skip("Converting a CuPy array to a CPU library requires an explicit copy.") - K = Dimension("K") domain = common.domain({K: 4}) true_field = common._field( asarray(first_impl, [1.0, 2.0, 3.0, 4.0], dtype=np.float64), domain=domain @@ -505,9 +576,6 @@ def test_mixed_fields_concat_where(product_nd_array_implementation): def test_neighbor_reduction_keeps_dtype( builtin, expected, expected_bool, dtype, nd_array_implementation ): - E = Dimension("E") - V = Dimension("V") - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) conn = common._connectivity( np.asarray([[0, 1], [1, -1]], dtype=np.int32), codomain=V, @@ -519,7 +587,7 @@ def test_neighbor_reduction_keeps_dtype( asarray(nd_array_implementation, data, dtype=dtype), domain={E: 2, E2V: 2} ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): if dtype == "bool" and is_array_api_strict(nd_array_implementation): with pytest.raises(TypeError): builtin(field, axis=E2V) @@ -556,14 +624,13 @@ def fma(a: common.Field, b: common.Field, c: common.Field, /) -> common.Field: def test_domain_premap(): # Translation case - I = Dimension("I") - J = Dimension("J") N = 10 data_field = common._field( 0.1 * np.arange(N * N).reshape((N, N)), domain=common.Domain( - common.NamedRange(I, common.unit_range(N)), common.NamedRange(J, common.unit_range(N)) + common.DimensionRange(I, common.unit_range(N)), + common.DimensionRange(J, common.unit_range(N)), ), ) conn = common.CartesianConnectivity.for_translation(J, +1) @@ -572,8 +639,8 @@ def test_domain_premap(): expected = common._field( data_field.ndarray, domain=common.Domain( - common.NamedRange(I, common.unit_range(N)), - common.NamedRange(J, common.unit_range((-1, N - 1))), + common.DimensionRange(I, common.unit_range(N)), + common.DimensionRange(J, common.unit_range((-1, N - 1))), ), ) @@ -581,19 +648,18 @@ def test_domain_premap(): assert np.all(result.ndarray == expected.ndarray) # Relocation case - I_half = Dimension("I_half") - conn = common.CartesianConnectivity.for_relocation(I, I_half) + conn = common.CartesianConnectivity.for_relocation(I, Staggered[I]) result = data_field.premap(conn) expected = common._field( data_field.ndarray, domain=common.Domain( dims=( - I_half, + Staggered[I], J, ), - ranges=(data_field.domain[I].unit_range, data_field.domain[J].unit_range), + ranges=(data_field.domain[I].value, data_field.domain[J].value), ), ) @@ -602,8 +668,6 @@ def test_domain_premap(): def test_reshuffling_premap(): - I = Dimension("I") - J = Dimension("J") ij_field = common._field( np.asarray([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]), @@ -630,8 +694,6 @@ def test_reshuffling_premap(): def test_remapping_premap(): - V = Dimension("V") - E = Dimension("E") V_START, V_STOP = 2, 7 E_START, E_STOP = 0, 10 @@ -656,9 +718,6 @@ def test_remapping_premap(): def test_remapping_premap_multineighbor(): - V = Dimension("V") - E = Dimension("E") - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) V_START, V_STOP = 2, 7 v_field = common._field( @@ -683,7 +742,6 @@ def test_remapping_premap_multineighbor(): def test_remapping_premap_same_dim(): - V = Dimension("V") V_START, V_STOP = 2, 7 v_field = common._field( @@ -708,8 +766,6 @@ def test_remapping_premap_same_dim(): def test_remapping_premap_same_dim_multineighbor(): # Regression for #1583: source dim == target dim with a LOCAL neighbor dim (C2E2CO shape). - V = Dimension("V") - V2V = Dimension("V2V", kind=DimensionKind.LOCAL) V_START, V_STOP = 2, 7 v_field = common._field( @@ -743,9 +799,6 @@ def test_remapping_premap_same_dim_multineighbor(): def test_premap_same_dim_multineighbor_with_extra_dim(): # The actual #1583 bug shape: C2E2CO on a field with an extra (kept) dimension. - C = Dimension("C") - K = Dimension("K") - C2E2CO = Dimension("C2E2CO", kind=DimensionKind.LOCAL) NC, NK, NN = 5, 3, 4 c_field = common._field( @@ -769,10 +822,6 @@ def test_premap_same_dim_multineighbor_with_extra_dim(): def test_gather_premap_multiple_connectivities(): # Multiple gather connectivities introducing new dims in a single premap (was unsupported). - A = Dimension("A") - B = Dimension("B") - X = Dimension("X") - Y = Dimension("Y") NA, NB = 3, 4 f = common._field( @@ -797,8 +846,6 @@ def test_gather_premap_multiple_connectivities(): def test_gather_premap_reshuffle_multiple_connectivities(): # Simultaneous multi-axis reshuffle (the multi-axis `as_offset` shape): codomains stay in their # own domains, so out[i, j] = f[ci[i, j], cj[i, j]] (not a sequential composition). - I = Dimension("I") - J = Dimension("J") NI, NJ = 3, 4 f = common._field( @@ -819,9 +866,6 @@ def test_gather_premap_reshuffle_multiple_connectivities(): def test_gather_premap_two_connectivities_same_new_dim(): # Two connectivities introducing the *same* new dim -> diagonal gather out[x] = f[ca[x], cb[x]]. - A = Dimension("A") - B = Dimension("B") - X = Dimension("X") NA, NB = 3, 4 f = common._field( @@ -845,9 +889,6 @@ def test_gather_premap_two_connectivities_same_new_dim(): def test_gather_premap_reads_non_codomain_field_dim(): # A connectivity that reads a field dim (B) other than its codomain (A): B is shared/narrowed. - A = Dimension("A") - B = Dimension("B") - L = Dimension("L", kind=DimensionKind.LOCAL) NA, NB = 3, 4 f = common._field( @@ -870,11 +911,6 @@ def test_gather_premap_reads_non_codomain_field_dim(): def test_gather_premap_shared_domain_dim(): # Two connectivities sharing a non-codomain domain dim (S): S is intersected and kept once. - A = Dimension("A") - B = Dimension("B") - S = Dimension("S") - T = Dimension("T") - U = Dimension("U") NA, NB = 3, 4 f = common._field( @@ -901,9 +937,6 @@ def test_gather_premap_shared_domain_dim(): def test_gather_premap_mix_introducing_and_preserving(): # One connectivity introduces a dim (X), another reshuffles a dim in place (B): allowed together. - A = Dimension("A") - B = Dimension("B") - X = Dimension("X") NA, NB = 3, 4 f = common._field( @@ -928,10 +961,6 @@ def test_gather_premap_mix_introducing_and_preserving(): def test_premap_chained_connectivities_raises(): # One connectivity reads a dim (B) that another remaps -> unsupported chained composition. - A = Dimension("A") - B = Dimension("B") - L = Dimension("L", kind=DimensionKind.LOCAL) - M = Dimension("M") f = common._field( np.arange(12).reshape(3, 4).astype(float), @@ -954,8 +983,6 @@ def test_premap_chained_connectivities_raises(): def test_premap_non_contiguous_inverse_image_raises(): # A connectivity whose in-range indices are not a contiguous block cannot yield a contiguous domain. - V = Dimension("V") - E = Dimension("E") f = common._field( np.arange(5).astype(float), domain=common.Domain(dims=(V,), ranges=(UnitRange(0, 5),)) @@ -971,8 +998,6 @@ def test_premap_non_contiguous_inverse_image_raises(): def test_premap_disjoint_inverse_image_raises(): - V = Dimension("V") - E = Dimension("E") f = common._field( np.arange(5).astype(float), domain=common.Domain(dims=(V,), ranges=(UnitRange(0, 5),)) @@ -987,14 +1012,6 @@ def test_premap_disjoint_inverse_image_raises(): f.premap(conn) -_GV = Dimension("GV") -_GE = Dimension("GE") -_GK = Dimension("GK", kind=DimensionKind.VERTICAL) -_GX = Dimension("GX") -_GE2V = Dimension("GE2V", kind=DimensionKind.LOCAL) -_GV2V = Dimension("GV2V", kind=DimensionKind.LOCAL) - - def _gather_case(xp, field_dims, conn_dims, codomain, table, skip_value=None): rng = np.random.default_rng(42) data = rng.random(tuple(len(r) for _, r in field_dims)) @@ -1031,20 +1048,20 @@ def test_gather_premap_single_axis(nd_array_implementation, layout, start): NV, NK, NX, NE = 6, 3, 2, 5 rng = np.random.default_rng(0) v_range = UnitRange(start, start + NV) - k, x = (_GK, UnitRange(0, NK)), (_GX, UnitRange(0, NX)) + k, x = (KV, UnitRange(0, NK)), (X, UnitRange(0, NX)) if layout == "same_dim": - conn_dims = [(_GV, v_range), (_GV2V, UnitRange(0, 3))] + conn_dims = [(V, v_range), (V2V, UnitRange(0, 3))] elif layout == "permutation": - conn_dims = [(_GV, v_range)] + conn_dims = [(V, v_range)] else: - conn_dims = [(_GE, UnitRange(0, NE)), (_GE2V, UnitRange(0, 2))] + conn_dims = [(E, UnitRange(0, NE)), (E2V, UnitRange(0, 2))] field_dims = { - "neighbor_leading": [(_GV, v_range), k], - "neighbor_trailing": [k, (_GV, v_range)], - "neighbor_middle": [x, (_GV, v_range), k], - "one_dim": [(_GV, v_range)], - "same_dim": [(_GV, v_range), k], - "permutation": [(_GV, v_range), k], + "neighbor_leading": [(V, v_range), k], + "neighbor_trailing": [k, (V, v_range)], + "neighbor_middle": [x, (V, v_range), k], + "one_dim": [(V, v_range)], + "same_dim": [(V, v_range), k], + "permutation": [(V, v_range), k], }[layout] table_shape = tuple(len(r) for _, r in conn_dims) table = ( @@ -1052,11 +1069,11 @@ def test_gather_premap_single_axis(nd_array_implementation, layout, start): if layout == "permutation" else rng.integers(start, start + NV, size=table_shape) ).astype(np.int32) - field, conn, data = _gather_case(nd_array_implementation, field_dims, conn_dims, _GV, table) + field, conn, data = _gather_case(nd_array_implementation, field_dims, conn_dims, V, table) result = field.premap(conn) - axis = [d for d, _ in field_dims].index(_GV) + axis = [d for d, _ in field_dims].index(V) expected_dims = ( *(d for d, _ in field_dims[:axis]), *(d for d, _ in conn_dims), @@ -1081,16 +1098,16 @@ def test_gather_premap_codomain_in_non_leading_connectivity_position( table = rng.integers(0, 3, size=(n_neighbors, 5)).astype(np.int32) # (GV2V, GV) -> GV field, conn, data = _gather_case( nd_array_implementation, - [(_GV, UnitRange(0, 3)), (_GK, UnitRange(0, 2))], - [(_GV2V, UnitRange(5, 5 + n_neighbors)), (_GV, UnitRange(0, 5))], - _GV, + [(V, UnitRange(0, 3)), (KV, UnitRange(0, 2))], + [(V2V, UnitRange(5, 5 + n_neighbors)), (V, UnitRange(0, 5))], + V, table, ) result = field.premap(conn) assert result.domain == common.Domain( - dims=(_GV, _GV2V, _GK), + dims=(V, V2V, KV), ranges=(UnitRange(0, 3), UnitRange(5, 5 + n_neighbors), UnitRange(0, 2)), ) expected = np.empty((3, n_neighbors, 2)) @@ -1105,16 +1122,16 @@ def test_gather_premap_single_axis_narrowed(nd_array_implementation): table = np.asarray([[0, 1], [2, 3], [4, 5], [7, 8]], dtype=np.int32) field, conn, data = _gather_case( nd_array_implementation, - [(_GV, UnitRange(0, 6)), (_GK, UnitRange(0, 2))], - [(_GE, UnitRange(0, 4)), (_GE2V, UnitRange(0, 2))], - _GV, + [(V, UnitRange(0, 6)), (KV, UnitRange(0, 2))], + [(E, UnitRange(0, 4)), (E2V, UnitRange(0, 2))], + V, table, ) result = field.premap(conn) assert result.domain == common.Domain( - dims=(_GE, _GE2V, _GK), ranges=(UnitRange(0, 3), UnitRange(0, 2), UnitRange(0, 2)) + dims=(E, E2V, KV), ranges=(UnitRange(0, 3), UnitRange(0, 2), UnitRange(0, 2)) ) assert np.array_equal(result.asnumpy(), np.take(data, table[:3], axis=0)) @@ -1131,9 +1148,9 @@ def test_gather_premap_skip_values_on_offset_domain( table = np.where(table == -9, skip_value, table + start).astype(np.int32) field, conn, data = _gather_case( nd_array_implementation, - [(_GV, UnitRange(start, start + NV)), (_GK, UnitRange(0, NK))], - [(_GE, UnitRange(0, 4)), (_GE2V, UnitRange(0, 2))], - _GV, + [(V, UnitRange(start, start + NV)), (KV, UnitRange(0, NK))], + [(E, UnitRange(0, 4)), (E2V, UnitRange(0, 2))], + V, table, skip_value=skip_value, ) @@ -1143,8 +1160,8 @@ def test_gather_premap_skip_values_on_offset_domain( connectivities.append( common._connectivity( nd_array_implementation.asarray(k_table), - domain=common.Domain(dims=(_GX,), ranges=(UnitRange(0, NK),)), - codomain=_GK, + domain=common.Domain(dims=(X,), ranges=(UnitRange(0, NK),)), + codomain=KV, ) ) @@ -1165,20 +1182,18 @@ def _gather_reference(data, field_domain, connectivities, out_domain): out = np.zeros(out_domain.shape) valid = np.ones(out_domain.shape, dtype=bool) for idx in np.ndindex(*out_domain.shape): - coord = {nr.dim: nr.unit_range.start + i for nr, i in zip(out_domain, idx)} + coord = {nr.dim: nr.value.start + i for nr, i in zip(out_domain, idx)} field_idx = [] for nr in field_domain: if nr.dim in by_codomain: table, domain, skip = by_codomain[nr.dim] - value = int( - table[tuple(coord[d] - domain[d].unit_range.start for d in domain.dims)] - ) + value = int(table[tuple(coord[d] - domain[d].value.start for d in domain.dims)]) if value == skip: valid[idx] = False break else: value = coord[nr.dim] - field_idx.append(value - nr.unit_range.start) + field_idx.append(value - nr.value.start) else: out[idx] = data[tuple(field_idx)] return out, valid @@ -1192,37 +1207,37 @@ def _table(rng, domain, codomain_range, skip_value=None): def _multi_gather_case(name, rng): - v, k = (_GV, UnitRange(3, 9)), (_GK, UnitRange(2, 6)) - e, e2v, x = (_GE, UnitRange(0, 5)), (_GE2V, UnitRange(0, 2)), (_GX, UnitRange(0, 7)) + v, k = (V, UnitRange(3, 9)), (KV, UnitRange(2, 6)) + e, e2v, x = (E, UnitRange(0, 5)), (E2V, UnitRange(0, 2)), (X, UnitRange(0, 7)) if name == "as_offset": # (GE, GK) -> GK on a (GE, GK) field - field_dims, conns, out_dims = [e, k], [([e, k], _GK, -1)], [e, k] + field_dims, conns, out_dims = [e, k], [([e, k], KV, -1)], [e, k] elif name == "neighbor_and_level": # (GE, GE2V) -> GV and (GE, GE2V, GK) -> GK on (GV, GK) field_dims = [v, k] - conns = [([e, e2v], _GV, -1), ([e, e2v, k], _GK, None)] + conns = [([e, e2v], V, -1), ([e, e2v, k], KV, None)] out_dims = [e, e2v, k] elif name == "per_level_neighbor": # (GE, GK) -> GV on a (GV, GK) field - field_dims, conns, out_dims = [v, k], [([e, k], _GV, -1)], [e, k] + field_dims, conns, out_dims = [v, k], [([e, k], V, -1)], [e, k] elif name == "as_offset_narrowed": # GE and GK narrowed by the table, negative GE start - field_dims = [(_GE, UnitRange(-2, 3)), k] - conn_dims = [(_GE, UnitRange(-1, 2)), (_GK, UnitRange(3, 5))] - conns, out_dims = [(conn_dims, _GK, -1)], conn_dims + field_dims = [(E, UnitRange(-2, 3)), k] + conn_dims = [(E, UnitRange(-1, 2)), (KV, UnitRange(3, 5))] + conns, out_dims = [(conn_dims, KV, -1)], conn_dims elif name == "neighbor_and_level_narrowed": # the level table narrows GK field_dims = [v, k] - k_narrowed = (_GK, UnitRange(3, 5)) - conns = [([e, e2v], _GV, -1), ([e, e2v, k_narrowed], _GK, None)] + k_narrowed = (KV, UnitRange(3, 5)) + conns = [([e, e2v], V, -1), ([e, e2v, k_narrowed], KV, None)] out_dims = [e, e2v, k_narrowed] elif name == "per_level_neighbor_narrowed": # the table narrows GK, negative GK starts - field_dims = [v, (_GK, UnitRange(-3, 2))] - k_narrowed = (_GK, UnitRange(-2, 1)) - conns, out_dims = [([e, k_narrowed], _GV, -1)], [e, k_narrowed] + field_dims = [v, (KV, UnitRange(-3, 2))] + k_narrowed = (KV, UnitRange(-2, 1)) + conns, out_dims = [([e, k_narrowed], V, -1)], [e, k_narrowed] elif name == "disjoint": # (GE, GE2V) -> GV and a (GK,) -> GK permutation on (GV, GK) field_dims = [v, k] - conns = [([e, e2v], _GV, -1), ([k], _GK, "permutation")] + conns = [([e, e2v], V, -1), ([k], KV, "permutation")] out_dims = [e, e2v, k] else: assert name == "diagonal" # (GX,) -> GV and (GX,) -> GE on (GV, GE): out[x] = f[a[x], b[x]] - field_dims = [v, (_GE, UnitRange(-2, 3))] - conns = [([x], _GV, None), ([x], _GE, None)] + field_dims = [v, (E, UnitRange(-2, 3))] + conns = [([x], V, None), ([x], E, None)] out_dims = [x] field_domain = common.Domain( dims=tuple(d for d, _ in field_dims), ranges=tuple(r for _, r in field_dims) @@ -1232,7 +1247,7 @@ def _multi_gather_case(name, rng): domain = common.Domain( dims=tuple(d for d, _ in conn_dims), ranges=tuple(r for _, r in conn_dims) ) - codomain_range = field_domain[codomain].unit_range + codomain_range = field_domain[codomain].value if skip == "permutation": table = (codomain_range.start + rng.permutation(len(codomain_range))).astype(np.int32) skip = None @@ -1285,14 +1300,14 @@ def test_gather_premap_multiple_or_reading_connectivities(nd_array_implementatio "conn_dims, codomains, expected_dims", [ # two connectivities over disjoint ranges of the same new dimension - ([[(_GX, UnitRange(0, 3))], [(_GX, UnitRange(3, 6))]], [_GV, _GE], (_GX,)), + ([[(X, UnitRange(0, 3))], [(X, UnitRange(3, 6))]], [V, E], (X,)), # a reshuffle over a range of the field dimension the field does not have - ([[(_GE, UnitRange(5, 7))]], [_GE], (_GV, _GE)), + ([[(E, UnitRange(5, 7))]], [E], (V, E)), ], ids=["disjoint_new_dimension", "outside_field"], ) def test_gather_premap_empty_output(nd_array_implementation, conn_dims, codomains, expected_dims): - field_domain = common.Domain(dims=(_GV, _GE), ranges=(UnitRange(3, 9), UnitRange(-2, 3))) + field_domain = common.Domain(dims=(V, E), ranges=(UnitRange(3, 9), UnitRange(-2, 3))) field = common._field( asarray(nd_array_implementation, np.ones(field_domain.shape)), domain=field_domain ) @@ -1300,7 +1315,7 @@ def test_gather_premap_empty_output(nd_array_implementation, conn_dims, codomain common._connectivity( asarray( # every entry maps into the field, so only the domains are disjoint nd_array_implementation, - np.full([len(r) for _, r in dims], field_domain[codomain].unit_range.start), + np.full([len(r) for _, r in dims], field_domain[codomain].value.start), dtype=np.int32, ), domain=common.Domain(dims=tuple(d for d, _ in dims), ranges=tuple(r for _, r in dims)), @@ -1327,22 +1342,21 @@ def test_gather_premap_empty_output(nd_array_implementation, conn_dims, codomain def test_neighbor_reduction_with_non_default_skip_value( nd_array_implementation, reduction, expected ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) field = common._field( asarray(nd_array_implementation, [1.0, 5.0, 3.0, 7.0], dtype=np.float64), - domain=common.Domain(dims=(_GV,), ranges=(UnitRange(0, 4),)), + domain=common.Domain(dims=(V,), ranges=(UnitRange(0, 4),)), ) conn = common._connectivity( asarray(nd_array_implementation, [[0, 1], [2, -2], [-2, 3]], dtype=np.int32), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 3), UnitRange(0, 2))), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 3), UnitRange(0, 2))), + codomain=V, skip_value=-2, ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): result = reduction(field.premap(conn), axis=E2V) - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(0, 3),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(0, 3),)) assert np.array_equal(result.asnumpy(), expected) @@ -1360,23 +1374,22 @@ def test_neighbor_reduction_with_non_default_skip_value( def test_neighbor_reduction_without_skip_value_masks_nothing( nd_array_implementation, reduction, np_reduction, table ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) values = np.asarray([[1.0, 5.0], [3.0, 7.0]]) field = common._field( asarray(nd_array_implementation, values, dtype=np.float64), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), ) conn = common._connectivity( asarray(nd_array_implementation, table, dtype=np.int32), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), + codomain=V, skip_value=None, ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): result = reduction(field, axis=E2V) - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(0, 2),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(0, 2),)) assert np.array_equal(result.asnumpy(), np_reduction(values, axis=1)) @@ -1385,29 +1398,28 @@ def test_neighbor_reduction_without_skip_value_masks_nothing( def test_neighbor_reduction_of_field_broadcast_along_neighbors( nd_array_implementation, reduction, np_reduction, skip_value ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) values = np.asarray([2.0, 3.0, 4.0]) table = np.asarray([[0, 1], [2, 0 if skip_value is None else skip_value], [1, 2]]) field = fbuiltins.broadcast( common._field( asarray(nd_array_implementation, values, dtype=np.float64), - domain=common.Domain(dims=(_GE,), ranges=(UnitRange(0, 3),)), + domain=common.Domain(dims=(E,), ranges=(UnitRange(0, 3),)), ), - (_GE, E2V), + (E, E2V), ) conn = common._connectivity( asarray(nd_array_implementation, table, dtype=np.int32), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 3), UnitRange(0, 2))), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 3), UnitRange(0, 2))), + codomain=V, skip_value=skip_value, ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): result = reduction(field, axis=E2V) is_neighbor = table != skip_value if skip_value is not None else np.ones(table.shape, bool) expected = [np_reduction(np.full(int(n.sum()), v)) for v, n in zip(values, is_neighbor)] - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(0, 3),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(0, 3),)) assert np.array_equal(result.asnumpy(), expected) @@ -1415,22 +1427,21 @@ def test_neighbor_reduction_of_field_broadcast_along_neighbors( def test_neighbor_reduction_ignores_field_values_beyond_the_neighbors( nd_array_implementation, skip_value ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) field = common._field( asarray(nd_array_implementation, [[1.0, 2.0, 100.0], [3.0, 4.0, 100.0]], dtype=np.float64), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 3))), + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 3))), ) conn = common._connectivity( asarray(nd_array_implementation, [[0, 1], [1, 0]], dtype=np.int32), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), + codomain=V, skip_value=skip_value, ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): result = fbuiltins.neighbor_sum(field, axis=E2V) - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(0, 2),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(0, 2),)) assert np.array_equal(result.asnumpy(), [3.0, 7.0]) @@ -1440,53 +1451,48 @@ def test_neighbor_reduction_ignores_field_values_beyond_the_neighbors( def test_neighbor_reduction_after_narrowing_premap( nd_array_implementation, reduction, np_reduction, skip_value, start ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) table = np.asarray([[0, 1], [2, 3 if skip_value is None else skip_value], [4, 5], [6, 7]]) table = np.where(table == skip_value, table, table + start) if skip_value else table + start values = np.arange(1.0, 5.0) conn = common._connectivity( asarray(nd_array_implementation, table, dtype=np.int32), - domain=common.Domain( - dims=(_GE, E2V), ranges=(UnitRange(start, start + 4), UnitRange(0, 2)) - ), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(start, start + 4), UnitRange(0, 2))), + codomain=V, skip_value=skip_value, ) field = common._field( asarray(nd_array_implementation, values, dtype=np.float64), - domain=common.Domain(dims=(_GV,), ranges=(UnitRange(start, start + 4),)), + domain=common.Domain(dims=(V,), ranges=(UnitRange(start, start + 4),)), ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): result = reduction(field.premap(conn), axis=E2V) # only the first two edges have all their neighbors in the field expected = [ np_reduction([values[v - start] for v in row if v != skip_value]) for row in table[:2] ] - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(start, start + 2),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(start, start + 2),)) assert np.array_equal(result.asnumpy(), expected) def test_neighbor_reduction_of_field_broadcast_along_another_dimension(nd_array_implementation): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) - K = Dimension("K", kind=DimensionKind.VERTICAL) conn = common._connectivity( asarray(nd_array_implementation, [[0, 1], [2, -1]], dtype=np.int32), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), + codomain=V, skip_value=-1, ) field = common._field( asarray(nd_array_implementation, [[1.0, 2.0], [4.0, 8.0]], dtype=np.float64), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), ) - with embedded_context.update(offset_provider={"E2V": conn}): - result = fbuiltins.neighbor_sum(fbuiltins.broadcast(field, (_GE, E2V, K)), axis=E2V) + with embedded_context.update(offset_provider={E2V.tag: conn}): + result = fbuiltins.neighbor_sum(fbuiltins.broadcast(field, (E, E2V, KV)), axis=E2V) assert result.domain == common.Domain( - dims=(_GE, K), ranges=(UnitRange(0, 2), UnitRange.infinite()) + dims=(E, KV), ranges=(UnitRange(0, 2), UnitRange.infinite()) ) assert np.array_equal(result.asnumpy().ravel(), [3.0, 4.0]) @@ -1497,8 +1503,8 @@ def test_neighbor_reduction_of_field_broadcast_along_another_dimension(nd_array_ def _e2v_on_edges_0_to_4(nd_array_implementation, neighbor_dim): return common._connectivity( asarray(nd_array_implementation, _E2V_TABLE, dtype=np.int32), - domain=common.Domain(dims=(_GE, neighbor_dim), ranges=(UnitRange(0, 4), UnitRange(0, 2))), - codomain=_GV, + domain=common.Domain(dims=(E, neighbor_dim), ranges=(UnitRange(0, 4), UnitRange(0, 2))), + codomain=V, skip_value=-1, ) @@ -1511,78 +1517,73 @@ def _e2v_on_edges_0_to_4(nd_array_implementation, neighbor_dim): def test_neighbor_reduction_reads_where_field_and_table_overlap( nd_array_implementation, edges, expected_edges, expected ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) values = [[1.0, 2.0], [10.0, 20.0], [100.0, 200.0], [1000.0, 2000.0]] field = common._field( asarray(nd_array_implementation, values, dtype=np.float64), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(*edges), UnitRange(0, 2))), + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(*edges), UnitRange(0, 2))), ) with embedded_context.update( - offset_provider={"E2V": _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} + offset_provider={E2V.tag: _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} ): result = fbuiltins.neighbor_sum(field, axis=E2V) - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(*expected_edges),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(*expected_edges),)) assert np.array_equal(result.asnumpy(), expected) def test_neighbor_reduction_to_an_empty_domain_keeps_the_other_dimensions(nd_array_implementation): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) - K = Dimension("K", kind=DimensionKind.VERTICAL) field = common._field( asarray(nd_array_implementation, np.ones((4, 2, 3)), dtype=np.float32), domain=common.Domain( - dims=(_GE, E2V, K), ranges=(UnitRange(10, 14), UnitRange(0, 2), UnitRange(0, 3)) + dims=(E, E2V, KV), ranges=(UnitRange(10, 14), UnitRange(0, 2), UnitRange(0, 3)) ), ) with embedded_context.update( - offset_provider={"E2V": _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} + offset_provider={E2V.tag: _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} ): result = fbuiltins.neighbor_sum(field, axis=E2V) - assert result.domain == common.Domain(dims=(_GE, K), ranges=(UnitRange(0, 0), UnitRange(0, 3))) + assert result.domain == common.Domain(dims=(E, KV), ranges=(UnitRange(0, 0), UnitRange(0, 3))) assert result.asnumpy().shape == (0, 3) assert result.dtype == field.dtype def test_neighbor_sum_over_no_neighbors(nd_array_implementation): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) field = common._field( asarray(nd_array_implementation, np.ones((2, 2)), dtype=np.float64), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 2))), ) conn = common._connectivity( asarray(nd_array_implementation, np.zeros((2, 0)), dtype=np.int32), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 0))), - codomain=_GV, + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 2), UnitRange(0, 0))), + codomain=V, skip_value=-1, ) - with embedded_context.update(offset_provider={"E2V": conn}): + with embedded_context.update(offset_provider={E2V.tag: conn}): result = fbuiltins.neighbor_sum(field, axis=E2V) - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(0, 2),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(0, 2),)) assert np.array_equal(result.asnumpy(), [0.0, 0.0]) @pytest.mark.parametrize("broadcast", [True, False], ids=["broadcast", "without_edges"]) def test_neighbor_reduction_of_field_broadcast_along_the_table(nd_array_implementation, broadcast): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) field = common._field( asarray(nd_array_implementation, [1.0, 2.0], dtype=np.float64), domain=common.Domain(dims=(E2V,), ranges=(UnitRange(0, 2),)), ) if broadcast: - field = fbuiltins.broadcast(field, (_GE, E2V)) + field = fbuiltins.broadcast(field, (E, E2V)) with embedded_context.update( - offset_provider={"E2V": _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} + offset_provider={E2V.tag: _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} ): result = fbuiltins.neighbor_sum(field, axis=E2V) - assert result.domain == common.Domain(dims=(_GE,), ranges=(UnitRange(0, 4),)) + assert result.domain == common.Domain(dims=(E,), ranges=(UnitRange(0, 4),)) assert np.array_equal(result.asnumpy(), [1.0, 3.0, 1.0, 3.0]) @@ -1590,16 +1591,15 @@ def test_neighbor_reduction_of_field_broadcast_along_the_table(nd_array_implemen def test_neighbor_reduction_without_all_neighbors_of_the_table_raises( nd_array_implementation, neighbors ): - E2V = Dimension("E2V", kind=DimensionKind.LOCAL) field = common._field( asarray( nd_array_implementation, np.ones((4, neighbors[1] - neighbors[0])), dtype=np.float64 ), - domain=common.Domain(dims=(_GE, E2V), ranges=(UnitRange(0, 4), UnitRange(*neighbors))), + domain=common.Domain(dims=(E, E2V), ranges=(UnitRange(0, 4), UnitRange(*neighbors))), ) with embedded_context.update( - offset_provider={"E2V": _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} + offset_provider={E2V.tag: _e2v_on_edges_0_to_4(nd_array_implementation, E2V)} ): with pytest.raises(ValueError, match="neighbors"): fbuiltins.neighbor_sum(field, axis=E2V) @@ -1607,7 +1607,6 @@ def test_neighbor_reduction_without_all_neighbors_of_the_table_raises( def test_as_offset_1d(): # Dynamic per-point shift along I: out[i] == f[i + off[i]], full domain when all shifts in-bounds. - I = Dimension("I") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) f = common._field( @@ -1624,7 +1623,6 @@ def test_as_offset_1d(): def test_as_offset_narrow_offset_dtype_no_wrap(): # An int8 offset field over a domain larger than 128 must not wrap into the index table. - I = Dimension("I") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) N = 200 @@ -1642,8 +1640,6 @@ def test_as_offset_narrow_offset_dtype_no_wrap(): def test_as_offset_2d_shift_one_keep_other(): # Shift along I by a per-(i, j) offset, leave J: out[i, j] == f[i + off[i, j], j]. - I = Dimension("I") - J = Dimension("J") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) NI, NJ = 4, 3 @@ -1662,7 +1658,6 @@ def test_as_offset_2d_shift_one_keep_other(): def test_as_offset_boundary_narrows_domain(): # A uniform out-of-bounds shift narrows the result to the contiguous in-range sub-domain. - I = Dimension("I") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) f = common._field( @@ -1680,7 +1675,6 @@ def test_as_offset_boundary_narrows_domain(): def test_as_offset_scattered_oob_raises(): # An out-of-bounds shift in the interior cannot yield a contiguous domain. - I = Dimension("I") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) f = common._field( @@ -1697,8 +1691,6 @@ def test_as_offset_scattered_oob_raises(): def test_as_offset_introduces_dimension(): # `off` carries a dim the field lacks: the result gains it, out[i, j] == f[i + off[i, j]]. - I = Dimension("I") - J = Dimension("J") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) f = common._field( @@ -1717,7 +1709,6 @@ def test_as_offset_introduces_dimension(): def test_as_offset_nonzero_origin(): # Field and offset over a domain that does not start at 0: indices must be shifted by the domain start. - I = Dimension("I") Ioff = fbuiltins.FieldOffset("Ioff", source=I, target=(I,)) dom = common.Domain(dims=(I,), ranges=(UnitRange(2, 12),)) @@ -1733,8 +1724,6 @@ def test_as_offset_nonzero_origin(): def test_as_offset_2d_shift_second_axis(): # Shift along J (the non-leading axis) by a per-(i, j) offset, leave I: out[i, j] == f[i, j + off[i, j]]. - I = Dimension("I") - J = Dimension("J") Joff = fbuiltins.FieldOffset("Joff", source=J, target=(J,)) NI, NJ = 3, 4 @@ -1753,23 +1742,18 @@ def test_as_offset_2d_shift_second_axis(): def test_as_offset_non_cartesian_offset_raises(): # `as_offset` only supports Cartesian (self-shift) offsets: single target equal to source. - I = Dimension("I") - J = Dimension("J") - Vertex = Dimension("Vertex", kind=DimensionKind.HORIZONTAL) - Edge = Dimension("Edge", kind=DimensionKind.HORIZONTAL) - V2EDim = Dimension("V2EDim", kind=DimensionKind.LOCAL) off_I = common._field( np.zeros(3, dtype=int), domain=common.Domain(dims=(I,), ranges=(UnitRange(0, 3),)) ) off_V = common._field( - np.zeros(3, dtype=int), domain=common.Domain(dims=(Vertex,), ranges=(UnitRange(0, 3),)) + np.zeros(3, dtype=int), domain=common.Domain(dims=(V,), ranges=(UnitRange(0, 3),)) ) # 2-element target (neighbor offset) - V2E = fbuiltins.FieldOffset("V2E", source=Edge, target=(Vertex, V2EDim)) + V2V_off = fbuiltins.FieldOffset(V2V.tag, source=V, target=(V, V2V)) with pytest.raises(ValueError, match="Cartesian"): - as_offset(V2E, off_V) + as_offset(V2V_off, off_V) # 1-element target but source != target[0] (cross-dim) IfromJ = fbuiltins.FieldOffset("IfromJ", source=I, target=(J,)) @@ -1782,39 +1766,39 @@ def test_as_offset_non_cartesian_offset_raises(): [ ( ( - (D0,), + (I,), common._field( - np.arange(10), domain=common.Domain(dims=(D0,), ranges=(UnitRange(0, 10),)) + np.arange(10), domain=common.Domain(dims=(I,), ranges=(UnitRange(0, 10),)) ), - Domain(dims=(D0,), ranges=(UnitRange(0, 10),)), + Domain(dims=(I,), ranges=(UnitRange(0, 10),)), ) ), ( ( - (D0, D1), + (I, J), common._field( - np.arange(10), domain=common.Domain(dims=(D0,), ranges=(UnitRange(0, 10),)) + np.arange(10), domain=common.Domain(dims=(I,), ranges=(UnitRange(0, 10),)) ), - Domain(dims=(D0, D1), ranges=(UnitRange(0, 10), UnitRange.infinite())), + Domain(dims=(I, J), ranges=(UnitRange(0, 10), UnitRange.infinite())), ) ), ( ( - (D0, D1), + (I, J), common._field( - np.arange(10), domain=common.Domain(dims=(D1,), ranges=(UnitRange(0, 10),)) + np.arange(10), domain=common.Domain(dims=(J,), ranges=(UnitRange(0, 10),)) ), - Domain(dims=(D0, D1), ranges=(UnitRange.infinite(), UnitRange(0, 10))), + Domain(dims=(I, J), ranges=(UnitRange.infinite(), UnitRange(0, 10))), ) ), ( ( - (D0, D1, D2), + (I, J, K), common._field( - np.arange(10), domain=common.Domain(dims=(D1,), ranges=(UnitRange(0, 10),)) + np.arange(10), domain=common.Domain(dims=(J,), ranges=(UnitRange(0, 10),)) ), Domain( - dims=(D0, D1, D2), + dims=(I, J, K), ranges=(UnitRange.infinite(), UnitRange(0, 10), UnitRange.infinite()), ), ) @@ -1828,11 +1812,11 @@ def test_field_broadcast(new_dims, field, expected_domain): @pytest.mark.parametrize( "domain_slice", - [(NamedRange(D0, UnitRange(0, 10)),), common.Domain(dims=(D0,), ranges=(UnitRange(0, 10),))], + [(I.at(0, 10),), common.Domain(dims=(I,), ranges=(UnitRange(0, 10),))], ) def test_get_slices_with_named_indices_3d_to_1d(domain_slice): field_domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(0, 10), UnitRange(0, 10), UnitRange(0, 10)) + dims=(I, J, K), ranges=(UnitRange(0, 10), UnitRange(0, 10), UnitRange(0, 10)) ) slices = _get_slices_from_domain_slice(field_domain, domain_slice) assert slices == (slice(0, 10, None), slice(None), slice(None)) @@ -1840,18 +1824,18 @@ def test_get_slices_with_named_indices_3d_to_1d(domain_slice): def test_get_slices_with_named_index(): field_domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(0, 10), UnitRange(0, 10), UnitRange(0, 10)) + dims=(I, J, K), ranges=(UnitRange(0, 10), UnitRange(0, 10), UnitRange(0, 10)) ) - named_index = (NamedRange(D0, UnitRange(0, 10)), (D1, 2), (D2, 3)) + named_index = (I.at(0, 10), J(2), K(3)) slices = _get_slices_from_domain_slice(field_domain, named_index) assert slices == (slice(0, 10, None), 2, 3) def test_get_slices_invalid_type(): field_domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(0, 10), UnitRange(0, 10), UnitRange(0, 10)) + dims=(I, J, K), ranges=(UnitRange(0, 10), UnitRange(0, 10), UnitRange(0, 10)) ) - new_domain = ((D0, "1"),) + new_domain = (I("1"),) with pytest.raises(ValueError): _get_slices_from_domain_slice(field_domain, new_domain) @@ -1860,27 +1844,27 @@ def test_get_slices_invalid_type(): "domain_slice,expected_dimensions,expected_shape", [ ( - (NamedRange(D0, UnitRange(7, 9)), NamedRange(D1, UnitRange(8, 10))), - (D0, D1, D2), + (I.at(7, 9), J.at(8, 10)), + (I, J, K), (2, 2, 15), ), ( - (NamedRange(D0, UnitRange(7, 9)), NamedRange(D2, UnitRange(12, 20))), - (D0, D1, D2), + (I.at(7, 9), K.at(12, 20)), + (I, J, K), (2, 10, 8), ), - (common.Domain(dims=(D0,), ranges=(UnitRange(7, 9),)), (D0, D1, D2), (2, 10, 15)), - ((NamedIndex(D0, 8),), (D1, D2), (10, 15)), - ((NamedIndex(D1, 9),), (D0, D2), (5, 15)), - ((NamedIndex(D2, 11),), (D0, D1), (5, 10)), - ((NamedIndex(D0, 8), NamedRange(D1, UnitRange(8, 10))), (D1, D2), (2, 15)), - (NamedIndex(D0, 5), (D1, D2), (10, 15)), - (NamedRange(D0, UnitRange(5, 7)), (D0, D1, D2), (2, 10, 15)), + (common.Domain(dims=(I,), ranges=(UnitRange(7, 9),)), (I, J, K), (2, 10, 15)), + ((I(8),), (J, K), (10, 15)), + ((J(9),), (I, K), (5, 15)), + ((K(11),), (I, J), (5, 10)), + ((I(8), J.at(8, 10)), (J, K), (2, 15)), + (I(5), (J, K), (10, 15)), + (I.at(5, 7), (I, J, K), (2, 10, 15)), ], ) def test_absolute_indexing(domain_slice, expected_dimensions, expected_shape): domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) + dims=(I, J, K), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) ) field = common._field(np.ones((5, 10, 15)), domain=domain) indexed_field = field[domain_slice] @@ -1892,13 +1876,13 @@ def test_absolute_indexing(domain_slice, expected_dimensions, expected_shape): def test_absolute_indexing_dim_sliced(): domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) + dims=(I, J, K), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) ) field = common._field(np.ones((5, 10, 15)), domain=domain) - indexed_field_1 = field[D1(8) : D1(10), D0(5) : D0(9)] + indexed_field_1 = field[J(8) : J(10), I(5) : I(9)] expected = field[ - NamedRange(dim=D0, unit_range=UnitRange(5, 9)), - NamedRange(dim=D1, unit_range=UnitRange(8, 10)), + I.at(5, 9), + J.at(8, 10), ] assert isinstance(indexed_field_1, common.Field) @@ -1907,11 +1891,11 @@ def test_absolute_indexing_dim_sliced(): def test_absolute_indexing_dim_sliced_single_slice(): domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) + dims=(I, J, K), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) ) field = common._field(np.ones((5, 10, 15)), domain=domain) - indexed_field_1 = field[D2(11)] - indexed_field_2 = field[NamedIndex(D2, 11)] + indexed_field_1 = field[K(11)] + indexed_field_2 = field[K(11)] assert isinstance(indexed_field_1, common.Field) assert are_equal_fields(indexed_field_1, indexed_field_2) @@ -1919,28 +1903,77 @@ def test_absolute_indexing_dim_sliced_single_slice(): def test_absolute_indexing_wrong_dim_sliced(): domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) + dims=(I, J, K), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) ) field = common._field(np.ones((5, 10, 15)), domain=domain) - with pytest.raises(IndexError, match="Dimensions slicing mismatch between 'D1' and 'D0'."): - field[D1(8) : D0(10)] + with pytest.raises(IndexError, match="Dimensions slicing mismatch between 'J' and 'I'."): + field[J(8) : I(10)] -def test_absolute_indexing_empty_dim_sliced(): - domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 10), UnitRange(5, 15), UnitRange(10, 25)) - ) - field = common._field(np.ones((5, 10, 15)), domain=domain) - with pytest.raises(IndexError, match="Lower bound needs to be specified"): - field[: D0(10)] +@pytest.mark.parametrize( + "index, expected", + [ + (slice(I(7), None), I.at(7, 10)), + (I.at(7, None), I.at(7, 10)), + (slice(None, I(7)), I.at(5, 7)), + (I.at(None, 7), I.at(5, 7)), + (I.at(None, None), I.at(5, 10)), + ((slice(I(7), None), slice(None, J(8))), (I.at(7, 10), J.at(5, 8))), + ], +) +def test_absolute_indexing_open_bound(index, expected): + # an open bound extends to the field's own bound, whether spelled as a slice or with `at` + domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 10), UnitRange(5, 15))) + field = common._field(np.arange(50).reshape((5, 10)), domain=domain) + + assert are_equal_fields(field[index], field[expected]) + + +def test_absolute_indexing_infinite_domain(): + # every infinite side is an open bound, also when indexing with a `Domain` + domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 10), UnitRange(5, 15))) + field = common._field(np.arange(50).reshape((5, 10)), domain=domain) + + infinite = common.Domain(dims=(I,), ranges=(UnitRange.infinite(),)) + assert are_equal_fields(field[infinite], field) + half_open = common.Domain(dims=(J,), ranges=(UnitRange(7, common.Infinity.POSITIVE),)) + assert are_equal_fields(field[half_open], field[J.at(7, 15)]) + + +@pytest.mark.parametrize( + "index", + [ + slice(I(3), None), + I.at(11, None), + slice(None, I(11)), + I.at(None, 4), + slice(I(6), I(11)), + I.at(4, 7), + ], +) +def test_absolute_indexing_closed_bound_out_of_bounds(index): + domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 10), UnitRange(5, 15))) + field = common._field(np.ones((5, 10)), domain=domain) + + with pytest.raises(embedded_exceptions.IndexOutOfBounds): + field[index] + + +def test_absolute_indexing_slice_step(): + domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 10), UnitRange(5, 15))) + field = common._field(np.ones((5, 10)), domain=domain) + + assert are_equal_fields(field[I(6) : I(8) : 1], field[I.at(6, 8)]) + with pytest.raises(IndexError, match="step"): + field[I(6) : I(8) : 2] def test_absolute_indexing_value_return(): - domain = common.Domain(dims=(D0, D1), ranges=(UnitRange(10, 20), UnitRange(5, 15))) + domain = common.Domain(dims=(I, J), ranges=(UnitRange(10, 20), UnitRange(5, 15))) field = common._field(np.reshape(np.arange(100, dtype=np.int32), (10, 10)), domain=domain) - named_index = (NamedIndex(D0, 12), NamedIndex(D1, 6)) + named_index = (I(12), J(6)) assert isinstance(field, common.Field) value = field[named_index] @@ -1954,24 +1987,24 @@ def test_absolute_indexing_value_return(): ( (slice(None, 5), slice(None, 2)), (5, 2), - Domain(NamedRange(D0, UnitRange(5, 10)), NamedRange(D1, UnitRange(2, 4))), + Domain(I.at(5, 10), J.at(2, 4)), ), ( (slice(None, 5),), (5, 10), - Domain(NamedRange(D0, UnitRange(5, 10)), NamedRange(D1, UnitRange(2, 12))), + Domain(I.at(5, 10), J.at(2, 12)), ), - ((Ellipsis, 1), (10,), Domain(NamedRange(D0, UnitRange(5, 15)))), + ((Ellipsis, 1), (10,), Domain(I.at(5, 15))), ( (slice(2, 3), slice(5, 7)), (1, 2), - Domain(NamedRange(D0, UnitRange(7, 8)), NamedRange(D1, UnitRange(7, 9))), + Domain(I.at(7, 8), J.at(7, 9)), ), - ((slice(1, 2), 0), (1,), Domain(NamedRange(D0, UnitRange(6, 7)))), + ((slice(1, 2), 0), (1,), Domain(I.at(6, 7))), ], ) def test_relative_indexing_slice_2D(index, expected_shape, expected_domain): - domain = common.Domain(dims=(D0, D1), ranges=(UnitRange(5, 15), UnitRange(2, 12))) + domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 15), UnitRange(2, 12))) field = common._field(np.ones((10, 10)), domain=domain) indexed_field = field[index] @@ -1983,46 +2016,38 @@ def test_relative_indexing_slice_2D(index, expected_shape, expected_domain): @pytest.mark.parametrize( "index, expected_shape, expected_domain", [ - ((1, slice(None), 2), (15,), Domain(dims=(D1,), ranges=(UnitRange(10, 25),))), + ((1, slice(None), 2), (15,), Domain(dims=(J,), ranges=(UnitRange(10, 25),))), ( (slice(None), slice(None), 2), (10, 15), - Domain(dims=(D0, D1), ranges=(UnitRange(5, 15), UnitRange(10, 25))), + Domain(dims=(I, J), ranges=(UnitRange(5, 15), UnitRange(10, 25))), ), ( (slice(None),), (10, 15, 10), - Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20)) - ), + Domain(dims=(I, J, K), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20))), ), ( (slice(None), slice(None), slice(None)), (10, 15, 10), - Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20)) - ), + Domain(dims=(I, J, K), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20))), ), ( (slice(None)), (10, 15, 10), - Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20)) - ), + Domain(dims=(I, J, K), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20))), ), - ((0, Ellipsis, 0), (15,), Domain(dims=(D1,), ranges=(UnitRange(10, 25),))), + ((0, Ellipsis, 0), (15,), Domain(dims=(J,), ranges=(UnitRange(10, 25),))), ( Ellipsis, (10, 15, 10), - Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20)) - ), + Domain(dims=(I, J, K), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20))), ), ], ) def test_relative_indexing_slice_3D(index, expected_shape, expected_domain): domain = common.Domain( - dims=(D0, D1, D2), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20)) + dims=(I, J, K), ranges=(UnitRange(5, 15), UnitRange(10, 25), UnitRange(10, 20)) ) field = common._field(np.ones((10, 15, 10)), domain=domain) indexed_field = field[index] @@ -2034,7 +2059,7 @@ def test_relative_indexing_slice_3D(index, expected_shape, expected_domain): @pytest.mark.parametrize("index, expected_value", [((1, 0), 10), ((0, 1), 1)]) def test_relative_indexing_value_return(index, expected_value): - domain = common.Domain(dims=(D0, D1), ranges=(UnitRange(5, 15), UnitRange(2, 12))) + domain = common.Domain(dims=(I, J), ranges=(UnitRange(5, 15), UnitRange(2, 12))) field = common._field(np.reshape(np.arange(100, dtype=int), (10, 10)), domain=domain) indexed_field = field[index] @@ -2043,16 +2068,16 @@ def test_relative_indexing_value_return(index, expected_value): @pytest.mark.parametrize("lazy_slice", [lambda f: f[13], lambda f: f[:5, :3, :2]]) def test_relative_indexing_out_of_bounds(lazy_slice): - domain = common.Domain(dims=(D0, D1), ranges=(UnitRange(3, 13), UnitRange(-5, 5))) + domain = common.Domain(dims=(I, J), ranges=(UnitRange(3, 13), UnitRange(-5, 5))) field = common._field(np.ones((10, 10)), domain=domain) with pytest.raises((embedded_exceptions.IndexOutOfBounds, IndexError)): lazy_slice(field) -@pytest.mark.parametrize("index", [D0, "1", (D0, D1)]) +@pytest.mark.parametrize("index", [I, "1", (I, J)]) def test_field_unsupported_index(index): - domain = common.Domain(dims=(D0,), ranges=(UnitRange(0, 10),)) + domain = common.Domain(dims=(I,), ranges=(UnitRange(0, 10),)) field = common._field(np.ones((10,)), domain=domain) with pytest.raises(IndexError, match="Unsupported index type"): field[index] @@ -2064,16 +2089,14 @@ def test_field_unsupported_index(index): ((1, 1), 42.0), ( (1, slice(None)), - common._field( - np.ones((10,)) * 42.0, domain=common.Domain(NamedRange(D1, UnitRange(0, 10))) - ), + common._field(np.ones((10,)) * 42.0, domain=common.Domain(J.at(0, 10))), ), ], ) def test_setitem(index, value): field = common._field( np.arange(100).reshape(10, 10), - domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 10), UnitRange(0, 10))), + domain=common.Domain(dims=(I, J), ranges=(UnitRange(0, 10), UnitRange(0, 10))), ) expected = np.copy(field.asnumpy()) @@ -2098,7 +2121,7 @@ def test_setitem(index, value): _ROW, lambda xp, v: common._field( asarray(xp, v, dtype=np.float64), - domain=common.Domain(NamedRange(D1, UnitRange(0, 10))), + domain=common.Domain(J.at(0, 10)), ), ), ( @@ -2106,7 +2129,7 @@ def test_setitem(index, value): _ROW, lambda xp, v: common._field( asarray(xp, v, dtype=np.float32), - domain=common.Domain(NamedRange(D1, UnitRange(0, 10))), + domain=common.Domain(J.at(0, 10)), ), ), ], @@ -2123,7 +2146,7 @@ def test_setitem_array_libraries(nd_array_implementation, index, source, make_va value = make_value(xp, source) field = common._field( asarray(xp, np.arange(100).reshape(10, 10), dtype=np.float64), - domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 10), UnitRange(0, 10))), + domain=common.Domain(dims=(I, J), ranges=(UnitRange(0, 10), UnitRange(0, 10))), ) expected = np.arange(100, dtype=np.float64).reshape(10, 10) expected[index] = source @@ -2139,7 +2162,7 @@ def test_setitem_array_libraries(nd_array_implementation, index, source, make_va def test_astype_c_type_alias(nd_array_implementation, c_type, expected): field = common._field( asarray(nd_array_implementation, [1.0, 2.0], dtype=np.float64), - domain=common.Domain(NamedRange(D0, UnitRange(0, 2))), + domain=common.Domain(I.at(0, 2)), ) result = fbuiltins.astype(field, c_type) @@ -2160,7 +2183,7 @@ def _other_library_pairs(): @pytest.mark.parametrize("field_xp, value_xp", _other_library_pairs()) def test_setitem_field_of_other_library_raises(field_xp, value_xp): - domain = common.Domain(NamedRange(D0, UnitRange(0, 3))) + domain = common.Domain(I.at(0, 3)) field = common._field(asarray(field_xp, np.arange(3), dtype=np.float64), domain=domain) value = common._field(asarray(value_xp, np.ones(3), dtype=np.float64), domain=domain) @@ -2172,7 +2195,7 @@ def test_setitem_plain_array_raises(nd_array_implementation): xp = nd_array_implementation field = common._field( asarray(xp, np.arange(3), dtype=np.float64), - domain=common.Domain(NamedRange(D0, UnitRange(0, 3))), + domain=common.Domain(I.at(0, 3)), ) with pytest.raises(TypeError, match=r"ndarray\[\.\.\.\]"): @@ -2182,12 +2205,10 @@ def test_setitem_plain_array_raises(nd_array_implementation): def test_setitem_wrong_domain(): field = common._field( np.arange(100).reshape(10, 10), - domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 10), UnitRange(0, 10))), + domain=common.Domain(dims=(I, J), ranges=(UnitRange(0, 10), UnitRange(0, 10))), ) - value_incompatible = common._field( - np.ones((10,)) * 42.0, domain=common.Domain(NamedRange(D1, UnitRange(-5, 5))) - ) + value_incompatible = common._field(np.ones((10,)) * 42.0, domain=common.Domain(J.at(-5, 5))) with pytest.raises(ValueError, match=r"Incompatible 'Domain'.*"): field[(1, slice(None))] = value_incompatible @@ -2196,7 +2217,7 @@ def test_setitem_wrong_domain(): def test_nd_array_field_getstate_excludes_cached_properties(): """Test that __getstate__ only serializes dataclass fields, excluding cached properties.""" data = np.asarray([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) - field = constructors.as_field((D0, D1), data) + field = constructors.as_field((I, J), data) # Access a cached property to populate the cache _ = field.__gt_buffer_info__ @@ -2214,7 +2235,7 @@ def test_nd_array_field_getstate_excludes_cached_properties(): def test_nd_array_field_pickle_roundtrip(): """Test that NdArrayField can be pickled and unpickled correctly using getstate/setstate.""" - original = constructors.as_field((D0, D1), np.arange(12.0).reshape(3, 4)) + original = constructors.as_field((I, J), np.arange(12.0).reshape(3, 4)) # Access cached property to ensure it's not included in serialization _ = original.__gt_buffer_info__ @@ -2235,15 +2256,12 @@ def test_nd_array_field_pickle_roundtrip(): def test_nd_array_connectivity_field_buffer_info(nd_array_implementation): - V = Dimension("V") - E = Dimension("E") - V_START, V_STOP = 2, 7 E_START, E_STOP = 0, 10 e2v_conn = common._connectivity( asarray(nd_array_implementation, np.roll(np.arange(E_START, E_STOP), 1), dtype=np.int32), - domain=common.domain([common.named_range((E, (E_START, E_STOP)))]), + domain=common.domain([common.dimension_range((E, (E_START, E_STOP)))]), codomain=V, ) assert e2v_conn.array_ns is nd_array_implementation @@ -2256,12 +2274,10 @@ def test_nd_array_connectivity_field_buffer_info(nd_array_implementation): def test_nd_array_connectivity_field_getstate_excludes_runtime_caches(): - V = Dimension("V") - E = Dimension("E") e2v_conn = common._connectivity( np.asarray([2, 3, 4, 5]), - domain=common.domain([common.named_range((E, (0, 4)))]), + domain=common.domain([common.dimension_range((E, (0, 4)))]), codomain=V, ) @@ -2280,18 +2296,16 @@ def test_nd_array_connectivity_field_getstate_excludes_runtime_caches(): def test_nd_array_connectivity_field_setstate_restores_state_without_caches(): - V = Dimension("V") - E = Dimension("E") original = common._connectivity( np.asarray([2, 3, 4, 5]), - domain=common.domain([common.named_range((E, (0, 4)))]), + domain=common.domain([common.dimension_range((E, (0, 4)))]), codomain=V, skip_value=-1, ) restored = common._connectivity( np.asarray([0, 0, 0, 0]), - domain=common.domain([common.named_range((E, (0, 4)))]), + domain=common.domain([common.dimension_range((E, (0, 4)))]), codomain=V, ) @@ -2306,15 +2320,13 @@ def test_nd_array_connectivity_field_setstate_restores_state_without_caches(): def test_connectivity_field_inverse_image(): - V = Dimension("V") - E = Dimension("E") V_START, V_STOP = 2, 7 E_START, E_STOP = 0, 10 e2v_conn = common._connectivity( np.roll(np.arange(E_START, E_STOP), 1), - domain=common.domain([common.named_range((E, (E_START, E_STOP)))]), + domain=common.domain([common.dimension_range((E, (E_START, E_STOP)))]), codomain=V, ) @@ -2323,9 +2335,6 @@ def test_connectivity_field_inverse_image(): def test_connectivity_field_inverse_image_2d_domain(): - V = Dimension("V") - C = Dimension("C") - C2V = Dimension("C2V") V_START, V_STOP = 0, 3 C_START, C_STOP = 0, 3 @@ -2335,8 +2344,8 @@ def test_connectivity_field_inverse_image_2d_domain(): np.asarray([[0, 0, 2], [1, 1, 2], [2, 2, 2]]), domain=common.domain( [ - common.named_range((C, (C_START, C_STOP))), - common.named_range((C2V, (C2V_START, C2V_STOP))), + common.dimension_range((C, (C_START, C_STOP))), + common.dimension_range((C2V, (C2V_START, C2V_STOP))), ] ), codomain=V, @@ -2381,15 +2390,13 @@ def test_connectivity_field_inverse_image_2d_domain(): def test_connectivity_field_inverse_image_non_contiguous(): - V = Dimension("V") - E = Dimension("E") V_START, V_STOP = 2, 7 E_START, E_STOP = 0, 10 e2v_conn = common._connectivity( np.asarray([0, 1, 2, 3, 4, 9, 7, 5, 8, 6]), - domain=common.domain([common.named_range((E, (E_START, E_STOP)))]), + domain=common.domain([common.dimension_range((E, (E_START, E_STOP)))]), codomain=V, ) @@ -2404,9 +2411,6 @@ def test_connectivity_field_inverse_image_non_contiguous(): def test_connectivity_field_inverse_image_2d_domain_skip_values(): - V = Dimension("V") - C = Dimension("C") - C2V = Dimension("C2V") V_START, V_STOP = 0, 3 C_START, C_STOP = 0, 4 @@ -2416,8 +2420,8 @@ def test_connectivity_field_inverse_image_2d_domain_skip_values(): np.asarray([[-1, 0, 2, -1], [1, 1, 2, 2], [2, 2, -1, -1], [-1, 2, -1, -1]]), domain=common.domain( [ - common.named_range((C, (C_START, C_STOP))), - common.named_range((C2V, (C2V_START, C2V_STOP))), + common.dimension_range((C, (C_START, C_STOP))), + common.dimension_range((C2V, (C2V_START, C2V_STOP))), ] ), codomain=V, @@ -2486,22 +2490,22 @@ def test_inverse_image_box(index_array, expected): @pytest.mark.parametrize( "cond, true_data, false_data, expected", [ - (D0 == 0, ([0, 0], None), ([1, 1], None), ([0, 1], None)), - (D0 == -1, ([0, 0], {D0: (-1, 1)}), ([1, 1], {D0: (0, 2)}), ([0, 1, 1], {D0: (-1, 2)})), - (D0 < 0, ([0, 0], {D0: (-2, 0)}), ([1, 1], {D0: (0, 2)}), ([0, 0, 1, 1], {D0: (-2, 2)})), - (D0 == 1, ([0, 0, 0], None), ([1, 1, 1], None), ([1, 0, 1], None)), + (I == 0, ([0, 0], None), ([1, 1], None), ([0, 1], None)), + (I == -1, ([0, 0], {I: (-1, 1)}), ([1, 1], {I: (0, 2)}), ([0, 1, 1], {I: (-1, 2)})), + (I < 0, ([0, 0], {I: (-2, 0)}), ([1, 1], {I: (0, 2)}), ([0, 0, 1, 1], {I: (-2, 2)})), + (I == 1, ([0, 0, 0], None), ([1, 1, 1], None), ([1, 0, 1], None)), # non-contiguous domain - (D0 <= 0, ([0, 0], {D0: (-2, 0)}), ([1, 1], {D0: (0, 2)}), None), + (I <= 0, ([0, 0], {I: (-2, 0)}), ([1, 1], {I: (0, 2)}), None), # empty result domain ( - D0 < 0, - ([0, 0], {D0: (0, 2)}), - ([1, 1], {D0: (-2, 0)}), - ([], {D0: (0, 0)}), + I < 0, + ([0, 0], {I: (0, 2)}), + ([1, 1], {I: (-2, 0)}), + ([], {I: (0, 0)}), ), # broadcasting from scalar (needs infinite domain support) pytest.param( - D0 == 0, + I == 0, ([0, 0], None), (1, None), ([0, 1], None), @@ -2558,42 +2562,42 @@ def test_concat_where( [ # finite domain → two complement regions (left and right of the domain) ( - common.Domain(dims=(D0,), ranges=(UnitRange(2, 5),)), + common.Domain(dims=(I,), ranges=(UnitRange(2, 5),)), ( - common.Domain(dims=(D0,), ranges=(UnitRange(common.Infinity.NEGATIVE, 2),)), - common.Domain(dims=(D0,), ranges=(UnitRange(5, common.Infinity.POSITIVE),)), + common.Domain(dims=(I,), ranges=(UnitRange(common.Infinity.NEGATIVE, 2),)), + common.Domain(dims=(I,), ranges=(UnitRange(5, common.Infinity.POSITIVE),)), ), ), # single-point domain ( - D0 == 3, + I == 3, ( - common.Domain(dims=(D0,), ranges=(UnitRange(common.Infinity.NEGATIVE, 3),)), - common.Domain(dims=(D0,), ranges=(UnitRange(4, common.Infinity.POSITIVE),)), + common.Domain(dims=(I,), ranges=(UnitRange(common.Infinity.NEGATIVE, 3),)), + common.Domain(dims=(I,), ranges=(UnitRange(4, common.Infinity.POSITIVE),)), ), ), - # open on the left (D0 < 5) → only a right complement + # open on the left (I < 5) → only a right complement ( - common.Domain(dims=(D0,), ranges=(UnitRange(common.Infinity.NEGATIVE, 5),)), - (common.Domain(dims=(D0,), ranges=(UnitRange(5, common.Infinity.POSITIVE),)),), + common.Domain(dims=(I,), ranges=(UnitRange(common.Infinity.NEGATIVE, 5),)), + (common.Domain(dims=(I,), ranges=(UnitRange(5, common.Infinity.POSITIVE),)),), ), - # open on the right (D0 >= 5) → only a left complement + # open on the right (I >= 5) → only a left complement ( - common.Domain(dims=(D0,), ranges=(UnitRange(5, common.Infinity.POSITIVE),)), - (common.Domain(dims=(D0,), ranges=(UnitRange(common.Infinity.NEGATIVE, 5),)),), + common.Domain(dims=(I,), ranges=(UnitRange(5, common.Infinity.POSITIVE),)), + (common.Domain(dims=(I,), ranges=(UnitRange(common.Infinity.NEGATIVE, 5),)),), ), # full line (both infinite) → empty complement ( common.Domain( - dims=(D0,), + dims=(I,), ranges=(UnitRange(common.Infinity.NEGATIVE, common.Infinity.POSITIVE),), ), (), ), # empty domain → complement is the full line ( - common.Domain(dims=(D0,), ranges=(UnitRange(3, 3),)), - (common.Domain(dims=(D0,), ranges=(UnitRange.infinite(),)),), + common.Domain(dims=(I,), ranges=(UnitRange(3, 3),)), + (common.Domain(dims=(I,), ranges=(UnitRange.infinite(),)),), ), ], ) @@ -2608,62 +2612,62 @@ def test_invert_domain(domain, expected): [ # two adjacent fields, already ordered ( - [([1, 2], {D0: (0, 2)}), ([3, 4], {D0: (2, 4)})], - D0, - ([1, 2, 3, 4], {D0: (0, 4)}), + [([1, 2], {I: (0, 2)}), ([3, 4], {I: (2, 4)})], + I, + ([1, 2, 3, 4], {I: (0, 4)}), None, ), # two adjacent fields, reverse order → _concat sorts them ( - [([3, 4], {D0: (2, 4)}), ([1, 2], {D0: (0, 2)})], - D0, - ([1, 2, 3, 4], {D0: (0, 4)}), + [([3, 4], {I: (2, 4)}), ([1, 2], {I: (0, 2)})], + I, + ([1, 2, 3, 4], {I: (0, 4)}), None, ), # three fields ( - [([1], {D0: (0, 1)}), ([2], {D0: (1, 2)}), ([3], {D0: (2, 3)})], - D0, - ([1, 2, 3], {D0: (0, 3)}), + [([1], {I: (0, 1)}), ([2], {I: (1, 2)}), ([3], {I: (2, 3)})], + I, + ([1, 2, 3], {I: (0, 3)}), None, ), # single field (trivial concat) ( - [([10, 20, 30], {D0: (5, 8)})], - D0, - ([10, 20, 30], {D0: (5, 8)}), + [([10, 20, 30], {I: (5, 8)})], + I, + ([10, 20, 30], {I: (5, 8)}), None, ), # gap between fields → NonContiguousDomain ( - [([1, 2], {D0: (0, 2)}), ([3, 4], {D0: (3, 5)})], - D0, + [([1, 2], {I: (0, 2)}), ([3, 4], {I: (3, 5)})], + I, None, embedded_exceptions.NonContiguousDomain, ), # overlapping fields → ValueError ( - [([1, 2, 3], {D0: (0, 3)}), ([4, 5, 6], {D0: (2, 5)})], - D0, + [([1, 2, 3], {I: (0, 3)}), ([4, 5, 6], {I: (2, 5)})], + I, None, ValueError, ), # three fields: first two overlap, third is disjoint from both ( [ - ([1, 2], {D0: (0, 2)}), - ([3, 4], {D0: (1, 3)}), - ([5, 6], {D0: (10, 12)}), + ([1, 2], {I: (0, 2)}), + ([3, 4], {I: (1, 3)}), + ([5, 6], {I: (10, 12)}), ], - D0, + I, None, ValueError, ), # negative domain indices ( - [([1, 2], {D0: (-3, -1)}), ([3], {D0: (-1, 0)})], - D0, - ([1, 2, 3], {D0: (-3, 0)}), + [([1, 2], {I: (-3, -1)}), ([3], {I: (-1, 0)})], + I, + ([1, 2, 3], {I: (-3, 0)}), None, ), ], @@ -2690,23 +2694,20 @@ def test_concat(fields_data, dim, expected_data, expect_error): def test_connectivity_field_setitem_raises(): conn = common._connectivity( np.asarray([[0, 1], [-1, -1]]), - codomain=D0, - domain=common.domain({D1: (0, 2), D2: (0, 2)}), + codomain=I, + domain=common.domain({J: (0, 2), K: (0, 2)}), skip_value=-1, ) with pytest.raises(TypeError, match="item assignment"): - conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) + conn[J(1)] = np.asarray([0, 1]) def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) conn = common._connectivity( np.asarray([[0, 1], [1, 2], [2, 3]]), codomain=V, - domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + domain=common.domain({E: (0, 3), E2V: (0, 2)}), ) field = common._field(np.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) calls = 0 @@ -2720,7 +2721,7 @@ def counting_inverse_image_box(*args, **kwargs): monkeypatch.setattr(nd_array_field, "_inverse_image_box", counting_inverse_image_box) for _ in range(3): - result = field.premap(conn[NamedIndex(E2VDim, 0)]) + result = field.premap(conn[E2V(0)]) assert calls == 1 assert result.domain == common.domain({E: (0, 2)}) @@ -2732,16 +2733,15 @@ def _scan_cumsum(x, k_dim): scan = operators.ScanOperator(lambda state, v: state + v, forward=True, init=0.0, axis=k_dim) with embedded_context.update( - column_ranges=(NamedRange(k_dim, UnitRange(0, 4)),), offset_provider={} + column_ranges=(common.DimensionRange(k_dim, UnitRange(0, 4)),), offset_provider={} ): return scan(x) def test_scan_result_in_namespace_and_on_device_of_inputs(nd_array_implementation): - K = Dimension("K", kind=DimensionKind.VERTICAL) data = asarray(nd_array_implementation, np.ones(4), dtype=np.float64) - result = _scan_cumsum(common._field(data, domain=common.domain({K: 4})), K) + result = _scan_cumsum(common._field(data, domain=common.domain({KV: 4})), KV) assert array_api_compat.array_namespace(result.ndarray) is array_api_compat.array_namespace( data @@ -2751,10 +2751,9 @@ def test_scan_result_in_namespace_and_on_device_of_inputs(nd_array_implementatio def test_scan_result_on_non_default_device_of_inputs(): - K = Dimension("K", kind=DimensionKind.VERTICAL) data = strict_array_on_device1(np.ones(4)) - result = _scan_cumsum(common._field(data, domain=common.domain({K: 4})), K) + result = _scan_cumsum(common._field(data, domain=common.domain({KV: 4})), KV) assert result.ndarray.device == data.device np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0, 4.0]) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 8f6fb25cd3..9daaf3cfc7 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -13,20 +13,40 @@ import pytest from gt4py.next import common -from gt4py.next.common import Dimension, DimensionKind, NamedIndex +from gt4py.next.common import CartesianAxisIndex, DimensionIndex, DimensionKind from gt4py.next.embedded import context as embedded_context, nd_array_field from gt4py.next.ffront import fbuiltins -D0 = Dimension("D0") -D1 = Dimension("D1") +class I(CartesianAxisIndex): ... + + +class J(CartesianAxisIndex): ... + + +class V(DimensionIndex): ... + + +class E(DimensionIndex): ... + + +class E2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class C(DimensionIndex): ... + + +class B(DimensionIndex): ... + + +class KV(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... @pytest.mark.requires_jax def test_jax_jit_field_arguments(): import jax - domain = common.domain({D0: (1, 3), D1: (2, 5)}) + domain = common.domain({I: (1, 3), J: (2, 5)}) a = common._field( jax.numpy.asarray(np.arange(6, dtype=np.float64).reshape(2, 3)), domain=domain ) @@ -47,7 +67,7 @@ def add(x, y): def test_jax_pytree_roundtrip(): import jax - domain = common.domain({D0: (1, 3), D1: (2, 5)}) + domain = common.domain({I: (1, 3), J: (2, 5)}) field = common._field(jax.numpy.ones((2, 3), dtype=np.float64), domain=domain) children, treedef = jax.tree_util.tree_flatten(field) @@ -59,7 +79,7 @@ def test_jax_pytree_roundtrip(): assert restored.domain == domain other_field = common._field( - jax.numpy.ones((2, 3), dtype=np.float64), domain=common.domain({D0: (0, 2), D1: (2, 5)}) + jax.numpy.ones((2, 3), dtype=np.float64), domain=common.domain({I: (0, 2), J: (2, 5)}) ) # the domain is part of the tree structure, hence a domain change forces a 'jax.jit' retrace assert jax.tree_util.tree_structure(other_field) != treedef @@ -69,7 +89,7 @@ def test_jax_pytree_roundtrip(): def test_jax_pytree_rejects_fields_of_other_libraries(): import jax - field = common._field(np.ones(3), domain=common.domain({D0: 3})) + field = common._field(np.ones(3), domain=common.domain({I: 3})) with pytest.raises(TypeError, match="Only fields of JAX arrays"): jax.jit(lambda f: f * 2.0)(field) @@ -79,17 +99,16 @@ def test_jax_pytree_rejects_fields_of_other_libraries(): def test_jax_pytree_non_array_leaves(): import jax - D_BATCH = Dimension("D_BATCH") - field = common._field(jax.numpy.arange(3.0), domain=common.domain({D0: 3})) - batched = common._field(jax.numpy.ones((2, 3)), domain=common.domain({D_BATCH: 2, D0: 3})) + field = common._field(jax.numpy.arange(3.0), domain=common.domain({I: 3})) + batched = common._field(jax.numpy.ones((2, 3)), domain=common.domain({B: 2, I: 3})) shapes = jax.tree.map(lambda x: x.shape, field) assert jax.tree.leaves(shapes) == [3] assert jax.eval_shape(lambda f: f * 2.0, field).ndarray.shape == (3,) # a field with an axis index as leaf, as `vmap` prefix for the batched field's buffer - axes = nd_array_field.NdArrayField(common.domain({D0: 3}), 0) + axes = nd_array_field.NdArrayField(common.domain({I: 3}), 0) sums = jax.vmap(lambda f: f.ndarray.sum(), in_axes=(axes,))( - nd_array_field.NdArrayField(common.domain({D0: 3}), batched.ndarray) + nd_array_field.NdArrayField(common.domain({I: 3}), batched.ndarray) ) np.testing.assert_allclose(sums, [3.0, 3.0]) @@ -98,7 +117,7 @@ def test_jax_pytree_non_array_leaves(): def test_jax_traced_array_dispatch(): import jax - domain = common.domain({D0: (0, 3)}) + domain = common.domain({I: (0, 3)}) x = jax.numpy.arange(3, dtype=np.float64) def loss(arr): @@ -111,10 +130,10 @@ def loss(arr): np.testing.assert_allclose(jax.jit(loss)(x), loss(x)) offsets = jax.numpy.asarray([[2, 0], [1, 2]]) - codomain = common.domain({D0: (0, 2), D1: (0, 2)}) + codomain = common.domain({I: (0, 2), J: (0, 2)}) def make_connectivity(arr): - return common._connectivity(arr, codomain=D0, domain=codomain).ndarray + return common._connectivity(arr, codomain=I, domain=codomain).ndarray np.testing.assert_array_equal(jax.jit(make_connectivity)(offsets), offsets) @@ -123,20 +142,17 @@ def make_connectivity(arr): def test_jax_grad_through_premap_with_skip_values(): import jax - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) e2v = common._connectivity( jax.numpy.asarray([[0, 1], [2, -1]], dtype=np.int32), codomain=V, - domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + domain=common.domain({E: (0, 2), E2V: (0, 2)}), skip_value=-1, ) def loss(x): field = common._field(x, domain=common.domain({V: (0, 4)})) - with embedded_context.update(offset_provider={"E2V": e2v}): - result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2VDim) + with embedded_context.update(offset_provider={E2V.tag: e2v}): + result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2V) return jax.numpy.sum(result.ndarray) x = jax.numpy.asarray([4.0, 9.0, 16.0, -1.0]) @@ -158,16 +174,13 @@ def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: def test_jax_jit_premap_with_connectivity_argument(num_field_vertices): import jax - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) table = _skip_value_e2v_table(300) - conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + conn_domain = common.domain({E: (0, table.shape[0]), E2V: (0, 2)}) field_domain = common.domain({V: (0, num_field_vertices)}) def premap_and_reduce(field, conn): - with embedded_context.update(offset_provider={"E2V": conn}): - return fbuiltins.neighbor_sum(field.premap(conn), axis=E2VDim) + with embedded_context.update(offset_provider={E2V.tag: conn}): + return fbuiltins.neighbor_sum(field.premap(conn), axis=E2V) expected = premap_and_reduce( common._field(np.arange(num_field_vertices, dtype=np.float64), domain=field_domain), @@ -209,11 +222,10 @@ def test_jax_jit_premap_with_unsupported_connectivity_is_not_wrong(): import jax E, field, conn_a, _ = _jax_narrowing_setup() - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) conn_2d = common._connectivity( jax.numpy.asarray([[0, 1], [1, 2], [3, 3]], dtype=np.int32), codomain=conn_a.codomain, - domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + domain=common.domain({E: (0, 3), E2V: (0, 2)}), ) def built_in_trace(conn): @@ -226,8 +238,8 @@ def premap(field, conn): # closed over by the trace (lambda: jax.jit(lambda f: f.premap(conn_a))(field), lambda: field.premap(conn_a)), ( - lambda: jax.jit(lambda f: f.premap(conn_2d[NamedIndex(E2VDim, 1)]))(field), - lambda: field.premap(conn_2d[NamedIndex(E2VDim, 1)]), + lambda: jax.jit(lambda f: f.premap(conn_2d[E2V(1)]))(field), + lambda: field.premap(conn_2d[E2V(1)]), ), # built from another tracer, directly and behind a pytree boundary ( @@ -255,10 +267,8 @@ def test_jax_jit_premap_with_as_offset_computed_in_trace(): from gt4py.next.ffront import experimental - C = Dimension("C") - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({C: (0, 2), K: (0, 4)}) + Koff = fbuiltins.FieldOffset("Koff", source=KV, target=(KV,)) + domain = common.domain({C: (0, 2), KV: (0, 4)}) values = np.arange(8, dtype=np.float64).reshape(2, 4) offsets = np.asarray([[1, 1, 0, -1], [0, 2, 1, 0]], dtype=np.int32) @@ -292,20 +302,17 @@ def shifted(field, offset_field): def test_jax_jit_premap_with_field_offset_does_not_leak_tracers(): import jax - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - E2V = fbuiltins.FieldOffset("E2V", source=V, target=(E, E2VDim)) + E2V_off = fbuiltins.FieldOffset(E2V.tag, source=V, target=(E, E2V)) conn = common._connectivity( jax.numpy.asarray([[0, 1], [2, 3]], dtype=np.int32), codomain=V, - domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + domain=common.domain({E: (0, 2), E2V: (0, 2)}), ) field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) def shifted(field, conn): - with embedded_context.update(offset_provider={"E2V": conn}): - return field(E2V) + with embedded_context.update(offset_provider={E2V.tag: conn}): + return field(E2V_off) with jax.checking_leaks(): result = jax.jit(shifted)(field, conn) @@ -317,20 +324,17 @@ def shifted(field, conn): def test_nested_jax_jit_premap_narrows(): import jax - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) conn = common._connectivity( jax.numpy.asarray([[0, 1], [2, 3], [4, 5]], dtype=np.int32), codomain=V, - domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + domain=common.domain({E: (0, 3), E2V: (0, 2)}), ) field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) inner = jax.jit(lambda field, conn: field.premap(conn)) result = jax.jit(lambda field, conn: inner(field, conn))(field, conn) - assert result.domain == common.domain({E: (0, 2), E2VDim: (0, 2)}) + assert result.domain == common.domain({E: (0, 2), E2V: (0, 2)}) np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) @@ -338,11 +342,8 @@ def test_nested_jax_jit_premap_narrows(): def test_jax_jit_retraces_per_connectivity_buffer(): import jax - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) table = jax.numpy.asarray(_skip_value_e2v_table(8)) - conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + conn_domain = common.domain({E: (0, table.shape[0]), E2V: (0, 2)}) field = common._field(jax.numpy.arange(8, dtype=np.float64), domain=common.domain({V: (0, 8)})) traces = 0 @@ -373,8 +374,6 @@ def premap(field, conn): def test_jax_jit_premap_non_contiguous_inverse_image_raises(): import jax - V = Dimension("V") - E = Dimension("E") conn = common._connectivity( jax.numpy.asarray([0, 5, 1], dtype=np.int32), codomain=V, @@ -390,15 +389,12 @@ def test_jax_jit_premap_non_contiguous_inverse_image_raises(): def test_jax_jit_premap_with_restricted_connectivity_argument(): import jax - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) table = _skip_value_e2v_table(8) - conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + conn_domain = common.domain({E: (0, table.shape[0]), E2V: (0, 2)}) field_domain = common.domain({V: (0, 4)}) def premap_first_neighbor(field, conn): - return field.premap(conn[NamedIndex(E2VDim, 0)]) + return field.premap(conn[E2V(0)]) expected = premap_first_neighbor( common._field(np.arange(4, dtype=np.float64), domain=field_domain), @@ -419,8 +415,6 @@ def _jax_narrowing_setup(): """A field on V:(1,4) and two tables on E:(0,5) mapping into it on E:(1,4) and on E:(0,3).""" import jax - V = Dimension("V") - E = Dimension("E") field = common._field(jax.numpy.asarray([10.0, 20.0, 30.0]), domain=common.domain({V: (1, 4)})) conn_domain = common.domain({E: (0, 5)}) conn_a = common._connectivity( @@ -618,9 +612,8 @@ def test_jax_jit_as_offset_connectivity_through_cond_and_scan(): from gt4py.next.ffront import experimental - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({K: (0, 4)}) + Koff = fbuiltins.FieldOffset("Koff", source=KV, target=(KV,)) + domain = common.domain({KV: (0, 4)}) field = common._field(jax.numpy.asarray([0.0, 1.0, 2.0, 3.0]), domain=domain) offsets = common._field(jax.numpy.asarray([1, 1, 0, -1], dtype=np.int32), domain=domain) @@ -650,7 +643,7 @@ def via_scan(field, offset_field): def test_jax_jit_traced_scalar_operands(): import jax - field = common._field(jax.numpy.arange(3.0), domain=common.domain({D0: 3})) + field = common._field(jax.numpy.arange(3.0), domain=common.domain({I: 3})) @jax.jit def compute(f, a, n): @@ -668,7 +661,7 @@ def compute(f, a, n): def test_jax_jit_traced_python_scalar_keeps_the_field_dtype(): import jax - field = common._field(jax.numpy.arange(3.0, dtype=np.float32), domain=common.domain({D0: 3})) + field = common._field(jax.numpy.arange(3.0, dtype=np.float32), domain=common.domain({I: 3})) for expression, expected in ( (lambda f, a: a * f, [0.0, 4.0, 8.0]), @@ -684,11 +677,11 @@ def test_jax_jit_traced_python_scalar_keeps_the_field_dtype(): def test_jax_jit_setitem_traced_scalar(): import jax - field = common._field(jax.numpy.zeros(3), domain=common.domain({D0: 3})) + field = common._field(jax.numpy.zeros(3), domain=common.domain({I: 3})) @jax.jit def fill(f, a): - f[common.domain({D0: (1, 2)})] = a + f[common.domain({I: (1, 2)})] = a return f np.testing.assert_array_equal(fill(field, 7.0).asnumpy(), [0.0, 7.0, 0.0]) @@ -698,9 +691,9 @@ def fill(f, a): def test_jax_jit_as_scalar_of_traced_field(): import jax - field = common._field(jax.numpy.arange(3.0), domain=common.domain({D0: 3})) + field = common._field(jax.numpy.arange(3.0), domain=common.domain({I: 3})) - result = jax.jit(lambda f: f[NamedIndex(D0, 2)].as_scalar() * 2.0)(field) + result = jax.jit(lambda f: f[I(2)].as_scalar() * 2.0)(field) assert float(result) == 4.0 @@ -711,18 +704,16 @@ def test_jax_jit_scan_operator(): import gt4py.next as gtx - K = Dimension("K", kind=DimensionKind.VERTICAL) - - @gtx.scan_operator(axis=K, forward=True, init=0.0) + @gtx.scan_operator(axis=KV, forward=True, init=0.0) def scaled_cumsum(state: gtx.float64, x: gtx.float64, a: gtx.float64) -> gtx.float64: return state + a * x def run(x, a): - out = common._field(jax.numpy.zeros(4), domain=common.domain({K: 4})) + out = common._field(jax.numpy.zeros(4), domain=common.domain({KV: 4})) scaled_cumsum(x, a, out=out, offset_provider={}) return out - x = common._field(jax.numpy.arange(1.0, 5.0), domain=common.domain({K: 4})) + x = common._field(jax.numpy.arange(1.0, 5.0), domain=common.domain({KV: 4})) np.testing.assert_array_equal(jax.jit(run)(x, 2.0).asnumpy(), run(x, 2.0).asnumpy()) np.testing.assert_array_equal(jax.jit(run)(x, 2.0).asnumpy(), [2.0, 6.0, 12.0, 20.0]) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py index c8bf0d0211..b76459cebc 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py @@ -13,13 +13,30 @@ from gt4py._core import definitions as core_defs from gt4py.next import common -from gt4py.next.common import Dimension, DimensionKind, NamedRange, UnitRange +from gt4py.next.common import CartesianAxisIndex, DimensionIndex, DimensionKind from gt4py.next.ffront import fbuiltins -D0 = Dimension("D0") -D1 = Dimension("D1") -D2 = Dimension("D2") +class I(CartesianAxisIndex): ... + + +class J(CartesianAxisIndex): ... + + +class V(DimensionIndex): ... + + +class E(DimensionIndex): ... + + +class E2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class K(CartesianAxisIndex): ... + + +class KV(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + _TORCH_DEVICES = [ "cpu", @@ -31,7 +48,7 @@ def _torch_field(values, device, dtype=None): import torch tensor = torch.asarray(values, dtype=dtype or torch.float64, device=device) - return common._field(tensor, domain=common.domain({D0: tensor.shape[0]})) + return common._field(tensor, domain=common.domain({I: tensor.shape[0]})) @pytest.mark.requires_torch @@ -115,15 +132,12 @@ def test_torch_scan_result_on_device_of_inputs(device): from gt4py.next.embedded import context as embedded_context, operators - K = Dimension("K", kind=DimensionKind.VERTICAL) - scan = operators.ScanOperator(lambda state, x: state + x, forward=True, init=0.0, axis=K) + scan = operators.ScanOperator(lambda state, x: state + x, forward=True, init=0.0, axis=KV) x = common._field( - torch.ones(4, dtype=torch.float64, device=device), domain=common.domain({K: 4}) + torch.ones(4, dtype=torch.float64, device=device), domain=common.domain({KV: 4}) ) - with embedded_context.update( - column_ranges=(NamedRange(K, UnitRange(0, 4)),), offset_provider={} - ): + with embedded_context.update(column_ranges=(KV.at(0, 4),), offset_provider={}): result = scan(x) assert result.ndarray.device.type == device @@ -136,7 +150,7 @@ def test_torch_asnumpy_of_tensor_requiring_grad(device): import torch tensor = torch.asarray([1.0, 2.0], dtype=torch.float64, device=device).requires_grad_() - field = common._field(tensor, domain=common.domain({D0: 2})) + field = common._field(tensor, domain=common.domain({I: 2})) np.testing.assert_array_equal(field.asnumpy(), [1.0, 2.0]) @@ -148,13 +162,10 @@ def test_torch_grad_through_premap_with_skip_values(device): from gt4py.next.embedded import context as embedded_context - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) e2v = common._connectivity( torch.asarray([[0, 1], [2, -1]], dtype=torch.int32, device=device), codomain=V, - domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + domain=common.domain({E: (0, 2), E2V: (0, 2)}), skip_value=-1, ) # the skip entry gathers some element before it is masked, and the gradient is NaN where @@ -162,8 +173,8 @@ def test_torch_grad_through_premap_with_skip_values(device): x = torch.tensor([4.0, 9.0, 16.0, 1.0], dtype=torch.float64, device=device, requires_grad=True) field = common._field(x, domain=common.domain({V: (0, 4)})) - with embedded_context.update(offset_provider={"E2V": e2v}): - result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2VDim) + with embedded_context.update(offset_provider={E2V.tag: e2v}): + result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2V) loss = torch.sum(result.ndarray) loss.backward() @@ -177,7 +188,7 @@ def test_torch_buffer_info(device): import torch data = torch.arange(24.0, dtype=torch.float64, device=device).reshape(2, 3, 4)[:, 1:, ::2] - field = common._field(data, domain=common.domain({D0: 2, D1: 2, D2: 2})) + field = common._field(data, domain=common.domain({I: 2, J: 2, K: 2})) buffer_info = field.__gt_buffer_info__ diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch_compile.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch_compile.py index 26df120a1d..b0f583a2d8 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch_compile.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch_compile.py @@ -10,18 +10,33 @@ import pytest from gt4py.next import common -from gt4py.next.common import Dimension, DimensionKind, NamedIndex +from gt4py.next.common import CartesianAxisIndex, DimensionIndex, DimensionKind from gt4py.next.embedded import context as embedded_context, nd_array_field from gt4py.next.ffront import experimental, fbuiltins pytestmark = pytest.mark.requires_torch -D0 = Dimension("D0") -D1 = Dimension("D1") -V = Dimension("V") -E = Dimension("E") -E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + +class I(CartesianAxisIndex): ... + + +class J(CartesianAxisIndex): ... + + +class V(DimensionIndex): ... + + +class E(DimensionIndex): ... + + +class E2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class C(DimensionIndex): ... + + +class KV(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... @pytest.fixture( @@ -71,7 +86,7 @@ def _connectivity(table, device, *, domain=None, **kwargs): import torch tensor = torch.asarray(table, device=device) - domain = domain or common.domain({E: tensor.shape[0], E2VDim: tensor.shape[1]}) + domain = domain or common.domain({E: tensor.shape[0], E2V: tensor.shape[1]}) return common._connectivity(tensor, codomain=V, domain=domain, **kwargs) @@ -84,12 +99,12 @@ def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: def _premap_and_reduce(field, conn): - with embedded_context.update(offset_provider={"E2V": conn}): - return fbuiltins.neighbor_sum(field.premap(conn), axis=E2VDim) + with embedded_context.update(offset_provider={E2V.tag: conn}): + return fbuiltins.neighbor_sum(field.premap(conn), axis=E2V) def test_torch_compile_field_arguments(device): - domain = common.domain({D0: (1, 3), D1: (2, 5)}) + domain = common.domain({I: (1, 3), J: (2, 5)}) a = _field(np.arange(6.0).reshape(2, 3), domain, device) b = _field(np.ones((2, 3)), domain, device) @@ -107,7 +122,7 @@ def test_torch_compile_retraces_per_field_domain(device): compiled, graphs = _compile(lambda x: x + x, dynamic=False) for num_graphs, (start, stop) in enumerate([(0, 3), (5, 8), (0, 4)], start=1): - field = _field(np.arange(float(stop - start)), common.domain({D0: (start, stop)}), device) + field = _field(np.arange(float(stop - start)), common.domain({I: (start, stop)}), device) result = compiled(field) assert result.domain == field.domain @@ -123,14 +138,14 @@ def test_torch_compile_retraces_per_field_domain(device): def test_torch_compile_another_field_domain_without_dynamic_false(device): compiled, _ = _compile(lambda x: x + x) - compiled(_field(np.arange(3.0), common.domain({D0: (0, 3)}), device)) - compiled(_field(np.arange(3.0), common.domain({D0: (5, 8)}), device)) + compiled(_field(np.arange(3.0), common.domain({I: (0, 3)}), device)) + compiled(_field(np.arange(3.0), common.domain({I: (5, 8)}), device)) def test_torch_pytree_roundtrip(device): import torch.utils._pytree as torch_pytree - domain = common.domain({D0: (1, 3), D1: (2, 5)}) + domain = common.domain({I: (1, 3), J: (2, 5)}) field = _field(np.ones((2, 3)), domain, device) children, treespec = torch_pytree.tree_flatten(field) @@ -139,14 +154,14 @@ def test_torch_pytree_roundtrip(device): assert children[0] is field.ndarray assert torch_pytree.tree_unflatten(children, treespec).domain == domain # the domain is part of the tree structure, hence a domain change forces a retrace - other_field = _field(np.ones((2, 3)), common.domain({D0: (0, 2), D1: (2, 5)}), device) + other_field = _field(np.ones((2, 3)), common.domain({I: (0, 2), J: (2, 5)}), device) assert torch_pytree.tree_structure(other_field) != treespec def test_torch_pytree_rejects_fields_of_other_libraries(): import torch.utils._pytree as torch_pytree - field = common._field(np.ones(3), domain=common.domain({D0: 3})) + field = common._field(np.ones(3), domain=common.domain({I: 3})) with pytest.raises(TypeError, match="Only fields of torch tensors"): torch_pytree.tree_flatten(field) @@ -174,7 +189,7 @@ def test_torch_compile_premap_with_connectivity_argument(device, num_field_verti common._connectivity( table, codomain=V, - domain=common.domain({E: table.shape[0], E2VDim: 2}), + domain=common.domain({E: table.shape[0], E2V: 2}), skip_value=-1, ), ) @@ -215,7 +230,7 @@ def test_torch_compile_premap_with_restricted_connectivity_argument(device): field_domain = common.domain({V: (0, 4)}) def premap_first_neighbor(field, conn): - return field.premap(conn[NamedIndex(E2VDim, 0)]) + return field.premap(conn[E2V(0)]) field = _field(np.arange(4.0), field_domain, device) conn = _connectivity(table, device, skip_value=-1) @@ -303,7 +318,7 @@ def test_torch_compile_premap_with_connectivity_not_created_by_constructor_raise table = _skip_value_e2v_table(2) conn = _connectivity(table, device, skip_value=-1) if create == "restrict": - conn = conn[common.domain({E: (0, 4), E2VDim: (0, 2)})] + conn = conn[common.domain({E: (0, 4), E2V: (0, 2)})] else: conn = nd_array_field.NdArrayConnectivityField.from_array( conn.ndarray, V, domain=conn.domain, skip_value=-1 @@ -318,10 +333,8 @@ def test_torch_compile_premap_with_connectivity_not_created_by_constructor_raise def test_torch_compile_premap_with_as_offset_computed_in_trace(device): - C = Dimension("C") - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({C: (0, 2), K: (0, 4)}) + Koff = fbuiltins.FieldOffset("Koff", source=KV, target=(KV,)) + domain = common.domain({C: (0, 2), KV: (0, 4)}) values = np.arange(8.0).reshape(2, 4) offsets = np.asarray([[1, 1, 0, -1], [0, 2, 1, 0]], dtype=np.int32) @@ -386,7 +399,7 @@ def test_torch_compile_premap_with_inductor(device): def test_torch_compile_traced_scalar_operands(device): import torch - field = _field(np.arange(3.0), common.domain({D0: 3}), device) + field = _field(np.arange(3.0), common.domain({I: 3}), device) def compute(f, a, n): return fbuiltins.sqrt(a) * f + fbuiltins.maximum(a, 5.0) + fbuiltins.astype(n, np.float64) @@ -399,10 +412,10 @@ def compute(f, a, n): def test_torch_compile_as_scalar_of_traced_field(device): - field = _field(np.arange(3.0), common.domain({D0: 3}), device) + field = _field(np.arange(3.0), common.domain({I: 3}), device) def element_times_field(f): - return f[NamedIndex(D0, 2)].as_scalar() * f + return f[I(2)].as_scalar() * f compiled, _ = _compile(element_times_field) @@ -412,10 +425,10 @@ def element_times_field(f): def test_torch_compile_setitem_traced_scalar(device): import torch - field = _field(np.zeros(3), common.domain({D0: 3}), device) + field = _field(np.zeros(3), common.domain({I: 3}), device) def fill(f, a): - f[common.domain({D0: (1, 2)})] = a + f[common.domain({I: (1, 2)})] = a return f compiled, _ = _compile(fill) @@ -430,20 +443,18 @@ def test_torch_compile_scan_operator(device): import gt4py.next as gtx - K = Dimension("K", kind=DimensionKind.VERTICAL) - - @gtx.scan_operator(axis=K, forward=True, init=0.0) + @gtx.scan_operator(axis=KV, forward=True, init=0.0) def scaled_cumsum(state: gtx.float64, x: gtx.float64, a: gtx.float64) -> gtx.float64: return state + a * x def run(x, a): out = common._field( - torch.zeros(4, dtype=torch.float64, device=device), domain=common.domain({K: 4}) + torch.zeros(4, dtype=torch.float64, device=device), domain=common.domain({KV: 4}) ) scaled_cumsum(x, a, out=out, offset_provider={}) return out - x = _field(np.arange(1.0, 5.0), common.domain({K: 4}), device) + x = _field(np.arange(1.0, 5.0), common.domain({KV: 4}), device) a = torch.tensor(2.0, dtype=torch.float64) compiled, _ = _compile(run) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_skip_values.py b/tests/next_tests/unit_tests/embedded_tests/test_skip_values.py index 26b78a5a91..c253ac7d4e 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_skip_values.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_skip_values.py @@ -16,10 +16,16 @@ from next_tests.unit_tests.conftest import asarray -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) +class Vertex(gtx.DimensionIndex): ... + + +class Edge(gtx.DimensionIndex): ... + + +class E2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +E2V = gtx.FieldOffset(E2VDim.tag, source=Vertex, target=(Edge, E2VDim)) NV = 5 # every edge keeps at least one neighbor, so max_over and min_over are defined everywhere @@ -79,7 +85,7 @@ def test_gather_to_sparse_field(nd_array_implementation, skip_value): conn, inp, table, is_neighbor, _ = _case(xp, skip_value) out = _out(xp, table.shape, (Edge, E2VDim)) - gather(inp, out=out, offset_provider={"E2V": conn}) + gather(inp, out=out, offset_provider={E2VDim.tag: conn}) expected = inp.asnumpy()[np.where(is_neighbor, table, 0)] assert np.array_equal(out.asnumpy()[is_neighbor], expected[is_neighbor]) @@ -91,7 +97,7 @@ def test_neighbor_reductions(nd_array_implementation, skip_value): conn, inp, table, _, neighbors = _case(xp, skip_value) outs = tuple(_out(xp, (len(table),), (Edge,)) for _ in range(3)) - reductions(inp, out=outs, offset_provider={"E2V": conn}) + reductions(inp, out=outs, offset_provider={E2VDim.tag: conn}) for out, np_reduction in zip(outs, (np.sum, np.max, np.min)): assert np.array_equal(out.asnumpy(), [np_reduction(n) for n in neighbors]) @@ -103,7 +109,7 @@ def test_where_and_concat_where_over_neighbors(nd_array_implementation, skip_val conn, inp, table, _, neighbors = _case(xp, skip_value) out = _out(xp, (len(table),), (Edge,)) - masked_and_concatenated(inp, out=out, offset_provider={"E2V": conn}) + masked_and_concatenated(inp, out=out, offset_provider={E2VDim.tag: conn}) expected = [np.sum(n[n > 2.0]) if e < 3 else np.max(n) for e, n in enumerate(neighbors)] assert np.array_equal(out.asnumpy(), expected) diff --git a/tests/next_tests/unit_tests/ffront_tests/_redefinable_dims.py b/tests/next_tests/unit_tests/ffront_tests/_redefinable_dims.py new file mode 100644 index 0000000000..162849d523 --- /dev/null +++ b/tests/next_tests/unit_tests/ffront_tests/_redefinable_dims.py @@ -0,0 +1,26 @@ +# 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 + +"""Dimensions that `test_dimension_identity_at_call` redefines with `importlib.reload`.""" + +import gt4py.next as gtx + + +class IDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +class Vertex(gtx.DimensionIndex): ... + + +class Edge(gtx.DimensionIndex): ... + + +class V2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... diff --git a/tests/next_tests/unit_tests/ffront_tests/test_decorator_domain_deduction.py b/tests/next_tests/unit_tests/ffront_tests/test_decorator_domain_deduction.py index 82abd8a7a7..2817dd37dc 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_decorator_domain_deduction.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_decorator_domain_deduction.py @@ -12,11 +12,20 @@ from gt4py.next.ffront.transform_utils import _deduce_grid_type -Dim = gtx.Dimension("Dim") -LocalDim = gtx.Dimension("LocalDim", kind=gtx.DimensionKind.LOCAL) +class HDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.HORIZONTAL): ... + + +class VDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +class Dim(gtx.DimensionIndex): ... + + +class LocalDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + CartesianOffset = gtx.FieldOffset("CartesianOffset", source=Dim, target=(Dim,)) -UnstructuredOffset = gtx.FieldOffset("UnstructuredOffset", source=Dim, target=(Dim, LocalDim)) +UnstructuredOffset = gtx.FieldOffset(LocalDim.tag, source=Dim, target=(Dim, LocalDim)) def test_domain_deduction_cartesian(): @@ -28,8 +37,6 @@ def test_domain_deduction_unstructured(): assert _deduce_grid_type(None, {UnstructuredOffset}) == gtx.GridType.UNSTRUCTURED assert _deduce_grid_type(None, {LocalDim}) == gtx.GridType.UNSTRUCTURED # source and target share `.value` but differ in `.kind` -> not Cartesian - HDim = gtx.Dimension("X", kind=gtx.DimensionKind.HORIZONTAL) - VDim = gtx.Dimension("X", kind=gtx.DimensionKind.VERTICAL) CrossKindOffset = gtx.FieldOffset("CrossKind", source=HDim, target=(VDim,)) assert _deduce_grid_type(None, {CrossKindOffset}) == gtx.GridType.UNSTRUCTURED # LOCAL self-loop is unstructured diff --git a/tests/next_tests/unit_tests/ffront_tests/test_diagnostic_messages.py b/tests/next_tests/unit_tests/ffront_tests/test_diagnostic_messages.py index 7e2d4fed6e..17b20b5f2c 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_diagnostic_messages.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_diagnostic_messages.py @@ -25,9 +25,9 @@ from gt4py.next import errors, float32, float64 from gt4py.next.ffront import dialect_parser from gt4py.next.ffront.func_to_foast import FieldOperatorParser +from next_tests.integration_tests.cases_utils import IDim -IDim = gtx.Dimension("IDim") IOff = gtx.FieldOffset("Ioff", source=IDim, target=(IDim,)) # A PEP 695 alias whose value raises when it is evaluated, standing in for the diff --git a/tests/next_tests/unit_tests/ffront_tests/test_dimension_identity_at_call.py b/tests/next_tests/unit_tests/ffront_tests/test_dimension_identity_at_call.py new file mode 100644 index 0000000000..ab5394ab15 --- /dev/null +++ b/tests/next_tests/unit_tests/ffront_tests/test_dimension_identity_at_call.py @@ -0,0 +1,211 @@ +# 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 + +""" +Classes in user code, refs in the toolchain: a redefined dimension is rejected when called. + +A notebook cell re-run redefines a dimension with the same kind, so the new class has a +`DimensionRef` *equal* to the old one. Arguments built on the old class must still be rejected +at the argument check, in embedded and compiled mode alike, as when type specifications held +classes. The dimensions come from another module, `_redefinable_dims`, which is reloaded (the +"re-run") after the arguments of the first run were built. +""" + +import dataclasses +import importlib + +import numpy as np +import pytest + +import gt4py.next as gtx +from gt4py.next import common, errors + +from . import _redefinable_dims as dims + + +_DIFFERENT = "two different classes named" + +# --- the first run: data built on the original classes +old = dims +old_classes = {name: getattr(old, name) for name in ("IDim", "KDim", "Vertex", "Edge", "V2EDim")} +old_i = gtx.as_field([old_classes["IDim"]], np.ones(4)) +old_k = gtx.as_field([old_classes["KDim"]], np.ones(4)) +old_i_half = gtx.as_field([common.Staggered[old_classes["IDim"]]], np.ones(4)) + +# --- the re-run: new classes, equal refs; everything below is declared on them +dims = importlib.reload(dims) +IDim, KDim, Vertex, Edge, V2EDim = dims.IDim, dims.KDim, dims.Vertex, dims.Edge, dims.V2EDim +V2E = gtx.FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) + + +def new_i(): + return gtx.as_field([IDim], np.zeros(4)) + + +@gtx.field_operator +def fop(x: gtx.Field[gtx.Dims[IDim], gtx.float64]) -> gtx.Field[gtx.Dims[IDim], gtx.float64]: + return x + 1.0 + + +@gtx.program +def prog(x: gtx.Field[gtx.Dims[IDim], gtx.float64], y: gtx.Field[gtx.Dims[IDim], gtx.float64]): + fop(x, out=y) + + +@gtx.field_operator +def list_form(x: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return x + + +@gtx.scan_operator(axis=KDim, forward=True, init=0.0) +def cumsum(state: float, x: float) -> float: + return state + x + + +@dataclasses.dataclass +class Pair: + a: gtx.Field[gtx.Dims[IDim], gtx.float64] + b: gtx.Field[gtx.Dims[IDim], gtx.float64] + + +@gtx.field_operator +def sum_pair(p: Pair) -> gtx.Field[gtx.Dims[IDim], gtx.float64]: + return p.a + p.b + + +@gtx.program +def pair_prog(p: Pair, out: gtx.Field[gtx.Dims[IDim], gtx.float64]): + sum_pair(p, out=out) + + +@gtx.field_operator +def staggered( + x: gtx.Field[gtx.Dims[common.Staggered[IDim]], gtx.float64], +) -> gtx.Field[gtx.Dims[common.Staggered[IDim]], gtx.float64]: + return x + + +@gtx.field_operator +def _first_neighbor( + e: gtx.Field[gtx.Dims[Edge], gtx.float64], +) -> gtx.Field[gtx.Dims[Vertex], gtx.float64]: + return e(V2E[0]) + + +@gtx.program +def first_neighbor( + e: gtx.Field[gtx.Dims[Edge], gtx.float64], out: gtx.Field[gtx.Dims[Vertex], gtx.float64] +): + _first_neighbor(e, out=out) + + +BACKENDS = pytest.mark.parametrize("backend", [None, gtx.gtfn_cpu], ids=["embedded", "gtfn_cpu"]) + + +def test_redefinition_keeps_an_equal_ref(): + assert old_classes["IDim"] is not IDim + assert common.dimension_ref(old_classes["IDim"]) == common.dimension_ref(IDim) + + +@BACKENDS +def test_program(backend): + with pytest.raises(errors.DSLError, match=_DIFFERENT): + prog.with_backend(backend)(old_i, new_i(), offset_provider={}) + + +@BACKENDS +def test_field_operator(backend): + with pytest.raises(errors.DSLError, match=_DIFFERENT): + fop.with_backend(backend)(old_i, out=new_i(), offset_provider={}) + + +@BACKENDS +def test_list_form_annotation(backend): + with pytest.raises(errors.DSLError, match=_DIFFERENT): + list_form.with_backend(backend)(old_i, out=new_i(), offset_provider={}) + + +@BACKENDS +def test_scan_operator(backend): + # the parameters are scalars: the declared dimension is the scan axis + with pytest.raises(errors.DSLError, match=_DIFFERENT): + cumsum.with_backend(backend)( + old_k, out=gtx.as_field([KDim], np.zeros(4)), offset_provider={} + ) + + +@BACKENDS +def test_named_collection(backend): + # only the collection's *values* are stale: its annotations name the current class + with pytest.raises(errors.DSLError, match=_DIFFERENT): + sum_pair.with_backend(backend)(Pair(old_i, old_i), out=new_i(), offset_provider={}) + with pytest.raises(errors.DSLError, match=_DIFFERENT): + pair_prog.with_backend(backend)(Pair(old_i, old_i), new_i(), offset_provider={}) + + +@BACKENDS +def test_staggered(backend): + with pytest.raises(errors.DSLError, match=_DIFFERENT): + staggered.with_backend(backend)( + old_i_half, + out=gtx.as_field([common.Staggered[IDim]], np.zeros(4)), + offset_provider={}, + ) + + +@BACKENDS +def test_connectivity_codomain(backend): + e = gtx.as_field([Edge], np.arange(3.0)) + out = gtx.as_field([Vertex], np.zeros(2)) + v2e = gtx.as_connectivity( + domain={Vertex: 2, V2EDim: 1}, + codomain=old_classes["Edge"], # only the codomain is stale + data=np.array([[2], [0]], np.int32), + ) + with pytest.raises(errors.DSLError, match=_DIFFERENT): + first_neighbor.with_backend(backend)(e, out, offset_provider={V2EDim.tag: v2e}) + + +@BACKENDS +def test_connectivity_local_dimension(backend): + # no annotation names `V2EDim`: the declaration is the `FieldOffset` the operator uses + e = gtx.as_field([Edge], np.arange(3.0)) + out = gtx.as_field([Vertex], np.zeros(2)) + v2e = gtx.as_connectivity( + domain={Vertex: 2, old_classes["V2EDim"]: 1}, # only the local dimension is stale + codomain=Edge, + data=np.array([[2], [0]], np.int32), + ) + with pytest.raises(errors.DSLError, match=_DIFFERENT): + first_neighbor.with_backend(backend)(e, out, offset_provider={V2EDim.tag: v2e}) + + +def test_current_classes_are_accepted_embedded(): + a = gtx.as_field([IDim], np.ones(4)) + out = gtx.as_field([IDim], np.zeros(4)) + prog.with_backend(None)(a, out, offset_provider={}) + assert np.allclose(out.asnumpy(), 2.0) + sum_pair.with_backend(None)(Pair(a, a), out=out, offset_provider={}) + assert np.allclose(out.asnumpy(), 2.0) + + +@gtx.scan_operator(axis=KDim, forward=True, init=0.0) +def scaled_cumsum(state: float, x: float, a: float) -> float: + return state + a * x + + +def test_zero_dimensional_array_scalar_is_skipped_embedded(): + # a 0-d array is a scalar to embedded execution (e.g. traced by `jax.jit`) and has no + # type spec, so the check skips it, while the field argument is still checked + out = gtx.as_field([KDim], np.zeros(4)) + scaled_cumsum.with_backend(None)( + gtx.as_field([KDim], np.arange(1.0, 5.0)), np.asarray(2.0), out=out, offset_provider={} + ) + assert np.allclose(out.asnumpy(), [2.0, 6.0, 12.0, 20.0]) + with pytest.raises(errors.DSLError, match=_DIFFERENT): + scaled_cumsum.with_backend(None)(old_k, np.asarray(2.0), out=out, offset_provider={}) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_dimension_identity_postponed_annotations.py b/tests/next_tests/unit_tests/ffront_tests/test_dimension_identity_postponed_annotations.py new file mode 100644 index 0000000000..2b56dc7f00 --- /dev/null +++ b/tests/next_tests/unit_tests/ffront_tests/test_dimension_identity_postponed_annotations.py @@ -0,0 +1,90 @@ +# 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 + +""" +A named collection with postponed (string) annotations resolves them in its module namespace. + +Its type translation therefore depends on that namespace, not only on the type object: after +only the dimension is redefined (a re-run notebook cell), the same `Pair` names the new class, +and a cached translation must not replay the old one into the edge identity check. +""" + +import importlib +import sys +import textwrap + +import numpy as np + +import gt4py.next as gtx +from gt4py.next import common +from gt4py.next.type_system import type_translation + + +_DIMS_AND_PAIR = textwrap.dedent( + """ + from __future__ import annotations + + import dataclasses + + import gt4py.next as gtx + + + class IDim(gtx.CartesianAxisIndex): ... + + + @dataclasses.dataclass + class Pair: + a: gtx.Field[gtx.Dims[IDim], gtx.float64] + """ +) + +_PROGRAM = textwrap.dedent( + """ + from __future__ import annotations + + import gt4py.next as gtx + + from postponed_pair_mod import IDim, Pair + + + @gtx.field_operator + def first(p: Pair) -> gtx.Field[gtx.Dims[IDim], gtx.float64]: + return p.a + + + @gtx.program + def prog(p: Pair, out: gtx.Field[gtx.Dims[IDim], gtx.float64]): + first(p, out=out) + """ +) + + +def test_redefined_dimension_in_postponed_annotations(tmp_path, monkeypatch): + (tmp_path / "postponed_pair_mod.py").write_text(_DIMS_AND_PAIR) + (tmp_path / "postponed_pair_prog.py").write_text(_PROGRAM) + monkeypatch.syspath_prepend(str(tmp_path)) + for name in ("postponed_pair_mod", "postponed_pair_prog"): + monkeypatch.delitem(sys.modules, name, raising=False) + + mod = importlib.import_module("postponed_pair_mod") + old = mod.IDim + type_translation.from_type_hint(mod.Pair) # the first run translates `Pair` once + + exec("class IDim(gtx.CartesianAxisIndex): ...", mod.__dict__) # only the dimension cell + new = mod.IDim + assert new is not old + + with common.capture_dimension_classes() as captured: + type_translation.from_type_hint(mod.Pair) + assert [cls for _, cls in captured] == [new] # what the annotation names *now* + + # a program written now, called with fields of the current class, is valid + prog = importlib.import_module("postponed_pair_prog").prog + out = gtx.as_field([new], np.zeros(4)) + prog.with_backend(None)(mod.Pair(gtx.as_field([new], np.ones(4))), out, offset_provider={}) + assert np.allclose(out.asnumpy(), 1.0) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_fbuiltins.py b/tests/next_tests/unit_tests/ffront_tests/test_fbuiltins.py index 5b75e9ba2e..fdfca3c8ee 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_fbuiltins.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_fbuiltins.py @@ -15,13 +15,12 @@ from gt4py.next import common, constructors from gt4py.next.ffront import fbuiltins from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim # values inside the domain of every unary math builtin (0.5 is invalid for `arccosh`) _SAFE_INPUT = {"arccosh": 2.0} -IDim = common.Dimension("IDim") - @dataclasses.dataclass class _Pair: diff --git a/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py index eb1927a776..9f31922e69 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py @@ -41,20 +41,27 @@ from gt4py.next.iterator.transforms import inline_lambdas from gt4py.next.type_system import type_specifications as ts, type_translation from gt4py.next.iterator import ir as itir +from next_tests.toy_connectivity import Edge, V2EDim, Vertex -Edge = gtx.Dimension("Edge") -Vertex = gtx.Dimension("Vertex") -V2EDim = gtx.Dimension("V2E", gtx.DimensionKind.LOCAL) -V2E = gtx.FieldOffset("V2E", source=Edge, target=(Vertex, V2EDim)) +V2E = gtx.FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) + + +class TDim(gtx.CartesianAxisIndex): ... + -TDim = gtx.Dimension("TDim") TOff = gtx.FieldOffset("TDim", source=TDim, target=(TDim,)) + + #: An offset whose tag differs from the name of the Python variable it is bound to, and #: from the name of its local dimension. Lowering must emit the *tag*. -RenamedV2EDim = gtx.Dimension("RenamedLocal", gtx.DimensionKind.LOCAL) +class RenamedV2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + renamed_v2e = gtx.FieldOffset("RenamedTag", source=Edge, target=(Vertex, RenamedV2EDim)) -UDim = gtx.Dimension("UDim") + + +class UDim(gtx.CartesianAxisIndex): ... def test_return(): @@ -781,7 +788,7 @@ def foo(edge_f: gtx.Field[gtx.Dims[Edge], float64]): parsed = FieldOperatorParser.apply_to_function(foo) lowered = FieldOperatorLowering.apply(parsed) - reference = im.as_fieldop_neighbors("V2E", "edge_f") + reference = im.as_fieldop_neighbors(V2EDim.tag, "edge_f") assert lowered.expr == reference @@ -826,7 +833,7 @@ def foo(edge_f: gtx.Field[[Edge], float64]): "plus", im.literal(value="0", type_="float64"), ) - )(im.as_fieldop_neighbors("V2E", "edge_f")) + )(im.as_fieldop_neighbors(V2EDim.tag, "edge_f")) assert lowered.expr == reference @@ -843,7 +850,7 @@ def foo(edge_f: gtx.Field[[Edge], float64]): "maximum", im.literal(value=str(np.finfo(np.float64).min), type_="float64"), ) - )(im.as_fieldop_neighbors("V2E", "edge_f")) + )(im.as_fieldop_neighbors(V2EDim.tag, "edge_f")) assert lowered.expr == reference @@ -860,7 +867,7 @@ def foo(edge_f: gtx.Field[[Edge], float64]): "minimum", im.literal(value=str(np.finfo(np.float64).max), type_="float64"), ) - )(im.as_fieldop_neighbors("V2E", "edge_f")) + )(im.as_fieldop_neighbors(V2EDim.tag, "edge_f")) assert lowered.expr == reference @@ -880,7 +887,7 @@ def foo(e1: gtx.Field[[Edge], float64], e2: gtx.Field[[Vertex, V2EDim], float64] reference = im.let( ssa.unique_name("e1_nbh", 0), - im.as_fieldop_neighbors("V2E", "e1"), + im.as_fieldop_neighbors(V2EDim.tag, "e1"), )( im.op_as_fieldop( im.reduce( @@ -970,7 +977,7 @@ def foo(inp: gtx.Field[[TDim], float64]): assert lowered.id == "foo" assert lowered.expr == im.call("broadcast")( im.ref("inp"), - im.make_tuple(*(itir.AxisLiteral(value=dim.value, kind=dim.kind) for dim in (TDim, UDim))), + im.make_tuple(*(itir.AxisLiteral(dim=dim) for dim in (TDim, UDim))), ) @@ -984,7 +991,7 @@ def foo(): assert lowered.id == "foo" assert lowered.expr == im.call("broadcast")( 1, - im.make_tuple(*(itir.AxisLiteral(value=dim.value, kind=dim.kind) for dim in (TDim, UDim))), + im.make_tuple(*(itir.AxisLiteral(dim=dim) for dim in (TDim, UDim))), ) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast.py index d72efaaa22..3291668c2f 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast.py @@ -54,6 +54,12 @@ from gt4py.next.type_system import type_specifications as ts +class ADim(gtx.CartesianAxisIndex): ... + + +class BDim(gtx.CartesianAxisIndex): ... + + DEREF = itir.SymRef(id=itb.deref.fun.__name__) PLUS = itir.SymRef(id=itb.plus.fun.__name__) MINUS = itir.SymRef(id=itb.minus.fun.__name__) @@ -71,7 +77,9 @@ XOR = itir.SymRef(id=itb.xor_.fun.__name__) LIFT = itir.SymRef(id=itb.lift.fun.__name__) -TDim = gtx.Dimension("TDim") # Meaningless dimension, used for tests. + +class TDim(gtx.CartesianAxisIndex): ... + # PEP 695 type alias, used to check that aliases are accepted as DSL annotations. type TFloatFieldAlias = gtx.Field[gtx.Dims[TDim], float64] @@ -426,8 +434,6 @@ def operator_with_refs(inp2: gtx.Field[[TDim], "float32"]): def test_wrong_return_type_annotation(): - ADim = gtx.Dimension("ADim") - BDim = gtx.Dimension("BDim") def wrong_return_type_annotation(a: gtx.Field[[ADim], float64]) -> gtx.Field[[BDim], float64]: return a @@ -449,7 +455,6 @@ def empty_dims() -> gtx.Field[[], float]: def test_zero_dims_ternary(): - ADim = gtx.Dimension("ADim") def zero_dims_ternary( cond: gtx.Field[[], float64], a: gtx.Field[[ADim], float64], b: gtx.Field[[ADim], float64] diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py index 62a8f1b755..d1a85cc7c3 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py @@ -19,7 +19,8 @@ # NOTE: These tests are sensitive to filename and the line number of the marked statement -TDim = gtx.Dimension("TDim") # Meaningless dimension, used for tests. + +class TDim(gtx.CartesianAxisIndex): ... def test_invalid_syntax_error_empty_return(): diff --git a/tests/next_tests/unit_tests/ffront_tests/test_offset_provider_keys.py b/tests/next_tests/unit_tests/ffront_tests/test_offset_provider_keys.py new file mode 100644 index 0000000000..7348de4ba1 --- /dev/null +++ b/tests/next_tests/unit_tests/ffront_tests/test_offset_provider_keys.py @@ -0,0 +1,63 @@ +# 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 + +"""An offset provider keyed by a (local) dimension class: `compile` and call agree on the key.""" + +import numpy as np +import pytest + +import gt4py.next as gtx +from next_tests.toy_connectivity import Edge, V2EDim, Vertex + + +V2E = gtx.FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) + + +@gtx.field_operator +def _first_neighbor( + e: gtx.Field[gtx.Dims[Edge], gtx.float64], +) -> gtx.Field[gtx.Dims[Vertex], gtx.float64]: + return e(V2E[0]) + + +@gtx.program +def first_neighbor( + e: gtx.Field[gtx.Dims[Edge], gtx.float64], out: gtx.Field[gtx.Dims[Vertex], gtx.float64] +): + _first_neighbor(e, out=out) + + +@pytest.fixture +def data(): + e = gtx.as_field([Edge], np.arange(3.0)) + out = gtx.as_field([Vertex], np.zeros(2)) + v2e = gtx.as_connectivity( + domain={Vertex: 2, V2EDim: 1}, codomain=Edge, data=np.array([[2], [0]], np.int32) + ) + return e, out, v2e + + +def test_compile_then_call_with_class_keyed_provider(data): + e, out, v2e = data + program = first_neighbor.with_backend(gtx.gtfn_cpu).compile(offset_provider={V2EDim: v2e}) + # a cache miss would raise: `enable_jit=False` + program(e, out, offset_provider={V2EDim: v2e}, enable_jit=False) + assert np.allclose(out.asnumpy(), [2.0, 0.0]) + # ...and the string-keyed spelling of the same provider is the same variant + program(e, out, offset_provider={V2EDim.tag: v2e}, enable_jit=False) + + +def test_connectivities_option_with_class_keys(data): + e, out, v2e = data + program = ( + first_neighbor.with_backend(gtx.gtfn_cpu) + .with_compilation_options(connectivities={V2EDim: v2e}) + .compile() + ) + program(e, out, offset_provider={V2EDim: v2e}, enable_jit=False) + assert np.allclose(out.asnumpy(), [2.0, 0.0]) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py index a25dbf7a8f..3e3b85e6e4 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py @@ -78,9 +78,9 @@ def test_copy_lowering(copy_program_def, gtir_identity_fundef): itir.FunCall, fun=P(itir.SymRef, id=eve.SymbolRef("named_range")), args=[ - P(itir.AxisLiteral, value="IDim"), - get_domain_range_pattern("out", "IDim", 0), - get_domain_range_pattern("out", "IDim", 1), + P(itir.AxisLiteral, value=IDim.tag), + get_domain_range_pattern("out", IDim.tag, 0), + get_domain_range_pattern("out", IDim.tag, 1), ], ) ], @@ -122,12 +122,12 @@ def test_copy_restrict_lowering(copy_restrict_program_def, gtir_identity_fundef) itir.FunCall, fun=P(itir.SymRef, id=eve.SymbolRef("named_range")), args=[ - P(itir.AxisLiteral, value="IDim"), + P(itir.AxisLiteral, value=IDim.tag), P( itir.FunCall, fun=P(itir.SymRef, id=eve.SymbolRef("plus")), args=[ - get_domain_range_pattern("out", "IDim", 0), + get_domain_range_pattern("out", IDim.tag, 0), P( itir.Literal, value="1", @@ -143,7 +143,7 @@ def test_copy_restrict_lowering(copy_restrict_program_def, gtir_identity_fundef) itir.FunCall, fun=P(itir.SymRef, id=eve.SymbolRef("plus")), args=[ - get_domain_range_pattern("out", "IDim", 0), + get_domain_range_pattern("out", IDim.tag, 0), P( itir.Literal, value="2", diff --git a/tests/next_tests/unit_tests/ffront_tests/test_source_utils.py b/tests/next_tests/unit_tests/ffront_tests/test_source_utils.py index 5735b4c25b..8ff9b96bf6 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_source_utils.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_source_utils.py @@ -19,15 +19,13 @@ """ import gt4py.next as gtx -from gt4py.next import Dims, Dimension, float64, neighbor_sum +from gt4py.next import Dims, float64, neighbor_sum from gt4py.next.ffront import source_utils from gt4py.next.ffront.source_utils import get_closure_vars_from_function +from next_tests.toy_connectivity import C2EDim, Cell, Edge -Cell = Dimension("Cell") -Edge = Dimension("Edge") -C2EDim = Dimension("C2E", kind=gtx.DimensionKind.LOCAL) -C2E = gtx.FieldOffset("C2E", source=Edge, target=(Cell, C2EDim)) +C2E = gtx.FieldOffset(C2EDim.tag, source=Edge, target=(Cell, C2EDim)) CField = gtx.Field[Dims[Cell], float64] EField = gtx.Field[Dims[Edge], float64] diff --git a/tests/next_tests/unit_tests/ffront_tests/test_stages.py b/tests/next_tests/unit_tests/ffront_tests/test_stages.py index 3c14182655..1a1049b968 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_stages.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_stages.py @@ -13,9 +13,7 @@ import gt4py.next as gtx from gt4py.next.ffront import stages from gt4py.next.type_system import type_specifications as ts - - -IDim = gtx.Dimension("I") +from next_tests.integration_tests.cases_utils import IDim def _field_type(kind: ts.ScalarKind) -> ts.FieldType: diff --git a/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py index 79af7ae24f..324a1e775b 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py @@ -16,6 +16,8 @@ import gt4py.next.ffront.type_specifications from gt4py.next import ( Dimension, + CartesianAxisIndex, + DimensionIndex, DimensionKind, Field, FieldOffset, @@ -36,10 +38,36 @@ from gt4py.next.type_system import type_specifications as ts from next_tests.artifacts import custom_named_collections as cnc +from next_tests.integration_tests.cases_utils import IDim, JDim +from next_tests.toy_connectivity import Edge, V2EDim, Vertex + +# the artifact's named collections are annotated with this very `TDim` +TDim = cnc.TDim + + +class X(CartesianAxisIndex): ... + + +class Y(CartesianAxisIndex): ... + + +class Y2XDim(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class K(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + + +class ADim(CartesianAxisIndex): ... + + +class BDim(CartesianAxisIndex): ... + + +class CDim(DimensionIndex): ... + # Meaningless dimensions, used for tests. -TDim = Dimension("TDim") -SDim = Dimension("SDim") +class SDim(CartesianAxisIndex): ... def test_unpack_assign(): @@ -93,8 +121,6 @@ def add_bools(a: Field[[TDim], bool], b: Field[[TDim], bool]): def test_binop_nonmatching_dims(): """Dimension promotion is applied before Binary operations, i.e., they can also work on two fields that don't have the same dimensions.""" - X = Dimension("X") - Y = Dimension("Y") def nonmatching(a: Field[[X], float64], b: Field[[Y], float64]): return a + b @@ -246,10 +272,7 @@ def domain_comparison(a: Field[[TDim], float], b: Field[[TDim], float]): @pytest.fixture def premap_setup(): - X = Dimension("X") - Y = Dimension("Y") - Y2XDim = Dimension("Y2X", kind=DimensionKind.LOCAL) - Y2X = FieldOffset("Y2X", source=X, target=(Y, Y2XDim)) + Y2X = FieldOffset(Y2XDim.tag, source=X, target=(Y, Y2XDim)) return X, Y, Y2XDim, Y2X @@ -281,7 +304,6 @@ def premap_fo(bar: Field[[X], int64]) -> Field[[Y, Y2XDim], int64]: def test_premap_nbfield_with_vertical(premap_setup): X, Y, Y2XDim, Y2X = premap_setup - K = Dimension("K", kind=DimensionKind.VERTICAL) def premap_fo(bar: Field[[X, K], int64]) -> Field[[Y, Y2XDim, K], int64]: return bar(Y2X) @@ -331,9 +353,6 @@ def mismatched_lit() -> Field[[TDim], "float32"]: def test_broadcast_multi_dim(): - ADim = Dimension("ADim") - BDim = Dimension("BDim") - CDim = Dimension("CDim") def simple_broadcast(a: Field[[ADim], float64]): return broadcast(a, (ADim, BDim, CDim)) @@ -346,9 +365,6 @@ def simple_broadcast(a: Field[[ADim], float64]): def test_broadcast_disjoint(): - ADim = Dimension("ADim") - BDim = Dimension("BDim") - CDim = Dimension("CDim") def disjoint_broadcast(a: Field[[ADim], float64]): return broadcast(a, (BDim, CDim)) @@ -358,9 +374,7 @@ def disjoint_broadcast(a: Field[[ADim], float64]): def test_broadcast_badtype(): - ADim = Dimension("ADim") BDim = "BDim" - CDim = Dimension("CDim") def badtype_broadcast(a: Field[[ADim], float64]): return broadcast(a, (BDim, CDim)) @@ -372,8 +386,6 @@ def badtype_broadcast(a: Field[[ADim], float64]): def test_where_dim(): - ADim = Dimension("ADim") - BDim = Dimension("BDim") def simple_where(a: Field[[ADim], bool], b: Field[[ADim, BDim], float64]): return where(a, b, 9.0) @@ -386,7 +398,6 @@ def simple_where(a: Field[[ADim], bool], b: Field[[ADim, BDim], float64]): def test_where_broadcast_dim(): - ADim = Dimension("ADim") def simple_where(a: Field[[ADim], bool]): return where(a, 5.0, 9.0) @@ -399,7 +410,6 @@ def simple_where(a: Field[[ADim], bool]): def test_where_tuple_dim(): - ADim = Dimension("ADim") def tuple_where(a: Field[[ADim], bool], b: Field[[ADim], float64]): return where(a, ((5.0, 9.0), (b, 6.0)), ((8.0, b), (5.0, 9.0))) @@ -425,7 +435,6 @@ def tuple_where(a: Field[[ADim], bool], b: Field[[ADim], float64]): def test_where_bad_dim(): - ADim = Dimension("ADim") def bad_dim_where(a: Field[[ADim], bool], b: Field[[ADim], float64]): return where(a, ((5.0, 9.0), (b, 6.0)), b) @@ -438,8 +447,6 @@ def bad_dim_where(a: Field[[ADim], bool], b: Field[[ADim], float64]): def test_where_mixed_dims(): - ADim = Dimension("ADim") - BDim = Dimension("BDim") def tuple_where_mix_dims( a: Field[[ADim], bool], b: Field[[ADim], float64], c: Field[[ADim, BDim], float64] @@ -526,8 +533,6 @@ def return_undefined(): def test_as_offset_dim(): - ADim = Dimension("ADim") - BDim = Dimension("BDim") Boff = FieldOffset("Boff", source=BDim, target=(BDim,)) def as_offset_dim(a: Field[[ADim, BDim], float], b: Field[[ADim], int]): @@ -538,8 +543,6 @@ def as_offset_dim(a: Field[[ADim, BDim], float], b: Field[[ADim], int]): def test_as_offset_dtype(): - ADim = Dimension("ADim") - BDim = Dimension("BDim") Boff = FieldOffset("Boff", source=BDim, target=(BDim,)) def as_offset_dtype(a: Field[[ADim, BDim], float], b: Field[[BDim], float]): @@ -550,10 +553,7 @@ def as_offset_dtype(a: Field[[ADim, BDim], float], b: Field[[BDim], float]): def test_as_offset_non_cartesian(): - Vertex = Dimension("Vertex", kind=DimensionKind.HORIZONTAL) - Edge = Dimension("Edge", kind=DimensionKind.HORIZONTAL) - V2EDim = Dimension("V2EDim", kind=DimensionKind.LOCAL) - V2E = FieldOffset("V2E", source=Edge, target=(Vertex, V2EDim)) + V2E = FieldOffset(V2EDim.tag, source=Edge, target=(Vertex, V2EDim)) def as_offset_neighbor(a: Field[[Edge], float], b: Field[[Edge], int]): return a(as_offset(V2E, b)) @@ -561,8 +561,6 @@ def as_offset_neighbor(a: Field[[Edge], float], b: Field[[Edge], int]): with pytest.raises(errors.DSLError, match="Cartesian"): _ = FieldOperatorParser.apply_to_function(as_offset_neighbor) - IDim = Dimension("IDim") - JDim = Dimension("JDim") IfromJ = FieldOffset("IfromJ", source=IDim, target=(JDim,)) def as_offset_cross_dim(a: Field[[IDim], float], b: Field[[IDim], int]): @@ -572,6 +570,15 @@ def as_offset_cross_dim(a: Field[[IDim], float], b: Field[[IDim], int]): _ = FieldOperatorParser.apply_to_function(as_offset_cross_dim) +@pytest.mark.parametrize("offset", [1, -1, 0.5]) +def test_cartesian_shift_off_an_axis(offset): + def shift_along_mesh_location(a: Field[[Edge], float]): + return a(Edge + offset) + + with pytest.raises(errors.DSLError, match="'Edge' is not a Cartesian axis"): + _ = FieldOperatorParser.apply_to_function(shift_along_mesh_location) + + vpfloat: TypeAlias = float32 wpfloat: TypeAlias = float64 diff --git a/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_domain_utils.py b/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_domain_utils.py index 4aac031406..febd3cafd3 100644 --- a/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_domain_utils.py +++ b/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_domain_utils.py @@ -13,16 +13,20 @@ from gt4py.next.iterator import ir as itir from gt4py.next.iterator.ir_utils import domain_utils, ir_makers as im from gt4py.next import common, constructors +from next_tests.toy_connectivity import E2VDim, Edge, V2EDim, V2VDim, Vertex + + +class I(common.CartesianAxisIndex): ... + -I = common.Dimension("I") IHalf = common.flip_staggered(I) -J = common.Dimension("J") -K = common.Dimension("J", kind=common.DimensionKind.VERTICAL) -Vertex = common.Dimension("Vertex") -Edge = common.Dimension("Edge") -V2EDim = common.Dimension("V2E", kind=common.DimensionKind.LOCAL) -E2VDim = common.Dimension("E2V", kind=common.DimensionKind.LOCAL) -V2VDim = common.Dimension("V2V", kind=common.DimensionKind.LOCAL) + + +class J(common.CartesianAxisIndex): ... + + +class K(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + a_range = domain_utils.SymbolicRange(0, 10) another_range = domain_utils.SymbolicRange(5, 15) @@ -103,7 +107,7 @@ def test_domain_union_all_empty(): def test_unstructured_translate_empty_range(): offset_provider = { - "V2E": constructors.as_connectivity( + V2EDim.tag: constructors.as_connectivity( domain={Vertex: (0, 4), V2EDim: 1}, codomain=Edge, data=np.asarray([0, 1, 2, 3], dtype=fbuiltins.IndexType).reshape((4, 1)), @@ -113,10 +117,10 @@ def test_unstructured_translate_empty_range(): im.domain(common.GridType.UNSTRUCTURED, {Vertex: (2, 2)}) # empty ) translated = domain.translate( - [itir.OffsetLiteral(value="V2E"), itir.OffsetLiteral(value=0)], offset_provider + [itir.OffsetLiteral(value=V2EDim.tag), itir.OffsetLiteral(value=0)], offset_provider ) assert translated.empty() - assert set(translated.ranges.keys()) == {Edge} + assert set(translated.ranges.keys()) == {common.dimension_ref(Edge)} def test_domain_intersection(): @@ -150,7 +154,7 @@ def test_domain_intersection_empty_with_infinite_range(): result = domain_utils.domain_intersection(empty, half_infinite) assert result.empty() - assert result.ranges[I].stop != itir.InfinityLiteral.POSITIVE + assert result.ranges[common.dimension_ref(I)].stop != itir.InfinityLiteral.POSITIVE def test_domain_union_then_intersection(): @@ -242,19 +246,19 @@ def test_is_finite_symbolic_domain(ranges, expected): @pytest.mark.parametrize( "shift_chain, expected_end_domain", [ - (("V2V", 0), {Vertex: (0, 4)}), - (("V2V", 1), {Vertex: (0, 4)}), - (("V2V", 2), {Vertex: (0, 1)}), - (("V2V", 3), {Vertex: (1, 4)}), - (("V2V", 0, "V2V", 3, "V2V", 0), {Vertex: (1, 4)}), - (("V2E", 0), {Edge: (0, 4)}), - (("V2E", 0, "E2V", 0), {Vertex: (0, 4)}), - (("V2V", 3, "V2E", 0), {Edge: (1, 4)}), + ((V2VDim.tag, 0), {Vertex: (0, 4)}), + ((V2VDim.tag, 1), {Vertex: (0, 4)}), + ((V2VDim.tag, 2), {Vertex: (0, 1)}), + ((V2VDim.tag, 3), {Vertex: (1, 4)}), + ((V2VDim.tag, 0, V2VDim.tag, 3, V2VDim.tag, 0), {Vertex: (1, 4)}), + ((V2EDim.tag, 0), {Edge: (0, 4)}), + ((V2EDim.tag, 0, E2VDim.tag, 0), {Vertex: (0, 4)}), + ((V2VDim.tag, 3, V2EDim.tag, 0), {Edge: (1, 4)}), ], ) def test_unstructured_translate(shift_chain, expected_end_domain): offset_provider = { - "V2V": constructors.as_connectivity( + V2VDim.tag: constructors.as_connectivity( domain={Vertex: (0, 4), V2VDim: 5}, codomain=Vertex, data=np.asarray( @@ -262,7 +266,7 @@ def test_unstructured_translate(shift_chain, expected_end_domain): dtype=fbuiltins.IndexType, ), ), - "V2E": constructors.as_connectivity( + V2EDim.tag: constructors.as_connectivity( domain={Vertex: (0, 4), V2EDim: 1}, codomain=Edge, data=np.asarray( @@ -272,7 +276,7 @@ def test_unstructured_translate(shift_chain, expected_end_domain): dtype=fbuiltins.IndexType, ).reshape((4, 1)), ), - "E2V": constructors.as_connectivity( + E2VDim.tag: constructors.as_connectivity( domain={Edge: (0, 4), E2VDim: 1}, codomain=Vertex, data=np.asarray( @@ -299,7 +303,7 @@ def test_unstructured_translate_with_symbolic_domain_sizes(as_type): # expression instead of the connectivity table. This makes `translate` work for a type-only # `OffsetProviderType` (which has no table) as well as a runtime `OffsetProvider`. offset_provider = { - "V2E": constructors.as_connectivity( + V2EDim.tag: constructors.as_connectivity( domain={Vertex: (0, 4), V2EDim: 1}, codomain=Edge, data=np.asarray([0, 1, 2, 3], dtype=fbuiltins.IndexType).reshape((4, 1)), @@ -312,9 +316,9 @@ def test_unstructured_translate_with_symbolic_domain_sizes(as_type): im.domain(common.GridType.UNSTRUCTURED, {Vertex: (0, 4)}) ) translated = domain.translate( - [itir.OffsetLiteral(value="V2E"), itir.OffsetLiteral(value=0)], + [itir.OffsetLiteral(value=V2EDim.tag), itir.OffsetLiteral(value=0)], offset_provider, - symbolic_domain_sizes={"Edge": im.ref("num_edges")}, + symbolic_domain_sizes={Edge.tag: im.ref("num_edges")}, ) expected = im.domain(common.GridType.UNSTRUCTURED, {Edge: (0, im.ref("num_edges"))}) @@ -338,13 +342,13 @@ def test_non_contiguous_domain_warning(monkeypatch): monkeypatch.setattr(domain_utils, "_NON_CONTIGUOUS_DOMAIN_WARNING_SKIPPED_OFFSET_TAGS", set()) offset_provider = { - "V2V": constructors.as_connectivity( + V2VDim.tag: constructors.as_connectivity( domain={Vertex: (0, 100), V2VDim: 1}, codomain=Vertex, data=np.asarray([0] + [99] * 99, dtype=fbuiltins.IndexType).reshape((100, 1)), ) } - shift_chain = ("V2V", 0) + shift_chain = (V2VDim.tag, 0) shift_chain = [im.ensure_offset(o) for o in shift_chain] domain = domain_utils.SymbolicDomain.from_expr( im.domain(common.GridType.UNSTRUCTURED, {Vertex: (0, 2)}) @@ -358,13 +362,13 @@ def test_non_contiguous_domain_warning(monkeypatch): def test_oob_error(): offset_provider = { - "V2V": constructors.as_connectivity( + V2VDim.tag: constructors.as_connectivity( domain={Vertex: (0, 3), V2VDim: 1}, codomain=Vertex, data=np.asarray([0, -1, 1], dtype=fbuiltins.IndexType).reshape((3, 1)), ) } - shift_chain = ("V2V", 0) + shift_chain = (V2VDim.tag, 0) shift_chain = [im.ensure_offset(o) for o in shift_chain] domain = domain_utils.SymbolicDomain.from_expr( im.domain(common.GridType.UNSTRUCTURED, {Vertex: (0, 3)}) diff --git a/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_misc.py b/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_misc.py index 2c332d6e29..255454cb80 100644 --- a/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_misc.py +++ b/tests/next_tests/unit_tests/iterator_tests/ir_utils_tests/test_misc.py @@ -6,9 +6,12 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses + import pytest from gt4py import next as gtx +from gt4py.next import common from gt4py.next.iterator import ir as itir from gt4py.next.iterator.ir_utils import ir_makers as im, misc from gt4py.next.iterator.transforms import inline_lambdas @@ -117,3 +120,20 @@ def test_extract_projector(expr, expected_expr): applied_projector = inline_lambdas.InlineLambdas.apply(applied_projector) inlined_expr = inline_lambdas.InlineLambdas.apply(expr) assert applied_projector == inlined_expr + + +class IDim(gtx.CartesianAxisIndex): ... + + +class JDim(gtx.CartesianAxisIndex): ... + + +def test_check_consistent_dimension_refs_rejects_a_shared_tag(): + ref = common.dimension_ref(IDim) + redefined = dataclasses.replace(ref, kind=common.DimensionKind.VERTICAL) + misc.check_consistent_dimension_refs([ref, ref, common.dimension_ref(JDim)]) + with pytest.raises(ValueError, match="share the tag"): + misc.check_consistent_dimension_refs([ref, redefined]) + # a staggered dimension refers to its base, also where the base itself is absent + with pytest.raises(ValueError, match=f"share the tag '{ref.tag}'"): + misc.check_consistent_dimension_refs([common.flip_staggered(ref), redefined]) diff --git a/tests/next_tests/unit_tests/iterator_tests/test_embedded_field_with_list.py b/tests/next_tests/unit_tests/iterator_tests/test_embedded_field_with_list.py index 3a6562e6be..7c34b94a50 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_embedded_field_with_list.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_embedded_field_with_list.py @@ -11,7 +11,7 @@ import gt4py.next as gtx from gt4py.next.embedded import context as embedded_context -from gt4py.next.iterator import embedded, runtime +from gt4py.next.iterator import builtins, embedded, runtime from gt4py.next.iterator.builtins import ( as_fieldop, deref, @@ -23,10 +23,16 @@ ) -E = gtx.Dimension("E") -V = gtx.Dimension("V") -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -E2V = gtx.FieldOffset("E2V", source=V, target=(E, E2VDim)) +class E(gtx.DimensionIndex): ... + + +class V(gtx.DimensionIndex): ... + + +class E2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +E2V = gtx.FieldOffset(E2VDim.tag, source=V, target=(E, E2VDim)) # 0 --0-- 1 --1-- 2 @@ -44,7 +50,7 @@ def testee(inp): return as_fieldop(lambda it: neighbors(E2V, it), domain)(inp) inp = gtx.as_field([V], np.arange(3)) - with embedded_context.update(offset_provider={"E2V": e2v_conn}): + with embedded_context.update(offset_provider={E2VDim.tag: e2v_conn}): result = testee(inp) ref = e2v_arr @@ -62,7 +68,7 @@ def testee(): ref = np.asarray([[42.0], [42.0]]) assert result.domain.dims[0] == E - assert result.domain.dims[1] == embedded._CONST_DIM # this is implementation detail + assert result.domain.dims[1] == builtins.ConstList # this is implementation detail assert result.shape[1] == 1 # this is implementation detail np.testing.assert_array_equal(result.asnumpy(), ref) @@ -76,7 +82,7 @@ def testee(inp): ) inp = gtx.as_field([V], np.arange(3)) - with embedded_context.update(offset_provider={"E2V": e2v_conn}): + with embedded_context.update(offset_provider={E2VDim.tag: e2v_conn}): result = testee(inp) ref = e2v_arr + 42.0 @@ -94,7 +100,7 @@ def testee(inp, mask): inp = gtx.as_field([V], np.arange(3)) mask_field = gtx.as_field([E], np.array([True, False])) - with embedded_context.update(offset_provider={"E2V": e2v_conn}): + with embedded_context.update(offset_provider={E2VDim.tag: e2v_conn}): result = testee(inp, mask_field) ref = np.empty_like(e2v_arr, dtype=float) @@ -122,7 +128,7 @@ def testee(inp, mask): inp = gtx.as_field([V], np.arange(3)) mask_field = gtx.as_field([E], np.array([True, False])) - with embedded_context.update(offset_provider={"E2V": e2v_conn}): + with embedded_context.update(offset_provider={E2VDim.tag: e2v_conn}): result = testee(inp, mask_field) ref = np.empty_like(e2v_arr, dtype=float) @@ -145,6 +151,6 @@ def testee(): ref = np.asarray([[43.0], [43.0]]) assert result.domain.dims[0] == E - assert result.domain.dims[1] == embedded._CONST_DIM # this is implementation detail + assert result.domain.dims[1] == builtins.ConstList # this is implementation detail assert result.shape[1] == 1 # this is implementation detail np.testing.assert_array_equal(result.asnumpy(), ref) diff --git a/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py b/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py index 7a133e2d49..842b97a9c2 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py @@ -16,8 +16,13 @@ from next_tests.unit_tests.conftest import strict_array_on_device1 +class I(common.CartesianAxisIndex): ... + + +class K(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + + def test_lift_accepts_cartesian_dimension_offset(): - K = common.Dimension("K", kind=common.DimensionKind.VERTICAL) lifted = embedded.lift(lambda *args: 0)() lifted.shift(common.CartesianConnectivity(K), 1) # must not raise @@ -36,7 +41,6 @@ def test_as_fieldop_result_in_namespace_and_on_device_of_inputs(make_array): from gt4py.next.iterator import builtins, runtime - I = common.Dimension("I") data = make_array() inp = common._field(data, domain=common.domain({I: 3})) @@ -58,7 +62,6 @@ def test_as_fieldop_result_on_device_of_inputs(): from gt4py.next.iterator import builtins, runtime - I = common.Dimension("I") inp = common._field( torch.arange(3.0, dtype=torch.float64, device="cuda"), domain=common.domain({I: 3}) ) diff --git a/tests/next_tests/unit_tests/iterator_tests/test_inline_dynamic_shifts.py b/tests/next_tests/unit_tests/iterator_tests/test_inline_dynamic_shifts.py index fb159de5bb..c7e617cbae 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_inline_dynamic_shifts.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_inline_dynamic_shifts.py @@ -5,13 +5,12 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from gt4py import next as gtx -from gt4py.next import utils from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.transforms import inline_dynamic_shifts from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim + -IDim = gtx.Dimension("IDim") field_type = ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.INT32)) IOff = im.cartesian_offset(IDim, IDim) diff --git a/tests/next_tests/unit_tests/iterator_tests/test_pretty_parser.py b/tests/next_tests/unit_tests/iterator_tests/test_pretty_parser.py index 83a16a980c..95983bc088 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_pretty_parser.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_pretty_parser.py @@ -7,13 +7,28 @@ # SPDX-License-Identifier: BSD-3-Clause import pytest +from lark import exceptions as lark_exceptions +import gt4py.next as gtx +from gt4py.next import common from gt4py.next.iterator import builtins, ir from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.pretty_parser import pparse from gt4py.next.type_system import type_specifications as ts +class I(gtx.CartesianAxisIndex): ... + + +class J(gtx.CartesianAxisIndex): ... + + +class IDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + def test_symref(): testee = "x" expected = ir.SymRef(id="x") @@ -87,13 +102,13 @@ def test_only_a_literal_can_be_annotated(): def test_typed_literal_does_not_shadow_named_range(): - assert pparse("c⟨ IDimₕ: [0:i64, 4:i64[ ⟩") == ir.FunCall( + assert pparse(f"c⟨ {IDim.tag}ₕᵃ: [0:i64, 4:i64[ ⟩") == ir.FunCall( fun=ir.SymRef(id="cartesian_domain"), args=[ ir.FunCall( fun=ir.SymRef(id="named_range"), args=[ - ir.AxisLiteral(value="IDim"), + ir.AxisLiteral(dim=IDim), im.literal("0", "int64"), im.literal("4", "int64"), ], @@ -186,11 +201,11 @@ def test_infinity_literal(): def test_named_range_unbounded(): - testee = "KDimᵥ: [-∞, ∞[" + testee = f"{KDim.tag}ᵥᵃ: [-∞, ∞[" expected = ir.FunCall( fun=ir.SymRef(id="named_range"), args=[ - ir.AxisLiteral(value="KDim", kind=ir.DimensionKind.VERTICAL), + ir.AxisLiteral(dim=KDim), ir.InfinityLiteral.NEGATIVE, ir.InfinityLiteral.POSITIVE, ], @@ -215,10 +230,8 @@ def test_subtraction_of_infinity_is_not_a_negative_literal(testee, rhs): def test_cartesian_offset(): - testee = "Iₕ→Jₕ" - expected = ir.CartesianOffset( - domain=ir.AxisLiteral(value="I"), codomain=ir.AxisLiteral(value="J") - ) + testee = f"{I.tag}ₕᵃ→{J.tag}ₕᵃ" + expected = ir.CartesianOffset(domain=ir.AxisLiteral(dim=I), codomain=ir.AxisLiteral(dim=J)) actual = pparse(testee) assert actual == expected @@ -243,21 +256,29 @@ def test_make_tuple(): def test_named_range_horizontal(): - testee = "IDimₕ: [x, y[" + testee = f"{IDim.tag}ₕᵃ: [x, y[" expected = ir.FunCall( fun=ir.SymRef(id="named_range"), - args=[ir.AxisLiteral(value="IDim"), ir.SymRef(id="x"), ir.SymRef(id="y")], + args=[ir.AxisLiteral(dim=IDim), ir.SymRef(id="x"), ir.SymRef(id="y")], ) actual = pparse(testee) assert actual == expected -def test_named_range_vertical(): - testee = "IDimᵥ: [x, y[" +def test_axis_literal_spec_from_suffixes_without_import(): + # the tag and the suffixes rebuild the spec, and nothing is + # imported (the module does not exist) + testee = "not.imported:Outer.Localₗ: [x, y[" expected = ir.FunCall( fun=ir.SymRef(id="named_range"), args=[ - ir.AxisLiteral(value="IDim", kind=ir.DimensionKind.VERTICAL), + ir.AxisLiteral( + dim=common.DimensionRef( + module="not.imported", + qualname="Outer.Local", + kind=common.DimensionKind.LOCAL, + ) + ), ir.SymRef(id="x"), ir.SymRef(id="y"), ], @@ -266,6 +287,38 @@ def test_named_range_vertical(): assert actual == expected +def test_staggered_axis_literal(): + testee = f"{common.Staggered[KDim].tag}ᵥᵃ" + assert pparse(testee) == ir.AxisLiteral(dim=common.Staggered[KDim]) + + +def test_short_dimension_names_from_the_header(): + testee = f""" + dim IDim = {IDim.tag}ₕᵃ; + dim Staggered[KDim] = {common.Staggered[KDim].tag}ᵥᵃ; + c⟨ IDimₕ: [0, 1[, Staggered[KDim]ᵥ: [0, 2[ ⟩ + """ + assert pparse(testee) == im.domain( + common.GridType.CARTESIAN, {IDim: (0, 1), common.Staggered[KDim]: (0, 2)} + ) + + +def test_short_dimension_name_in_a_program(): + testee = f""" + dim IDim = {IDim.tag}ₕᵃ; + f(x, y) {{ + y @ c⟨ IDimₕ: [0, 1[ ⟩ ← x; + }} + """ + program = pparse(testee) + assert isinstance(program, ir.Program) + assert program.body[0].domain == im.domain(common.GridType.CARTESIAN, {IDim: (0, 1)}) + + +def test_header_entries_do_not_have_to_be_used(): + assert pparse(f"dim IDim = {IDim.tag}ₕᵃ; x") == im.ref("x") + + def test_cartesian_domain(): testee = "c⟨ x, y ⟩" expected = ir.FunCall( @@ -419,3 +472,41 @@ def test_program(): def test_transformer_error_is_not_wrapped(): with pytest.raises(ValueError, match="nonesuch"): pparse("t = temporary(domain=cartesian_domain(), dtype=nonesuch);") + + +@pytest.mark.parametrize("testee", ["IDimₕ", "pkg.mod.IDimₕ"]) +def test_short_dimension_name_without_header_is_rejected(testee): + # a short name means nothing without its declaration: nothing is imported to guess it + with pytest.raises(ValueError, match="is not declared"): + pparse(testee) + + +@pytest.mark.parametrize( + "testee", + [ + pytest.param(f"dim IDim = {IDim.tag}ₕᵃ; IDimᵥ", id="kind"), + pytest.param(f"dim Cell = pkg:Cellₕ; Cellₕᵃ", id="cartesian_axis"), + ], +) +def test_short_dimension_name_contradicting_its_declaration_is_rejected(testee): + with pytest.raises(ValueError, match="does not match the declaration"): + pparse(testee) + + +@pytest.mark.parametrize( + "testee, message", + [ + (f"dim IDim = {IDim.tag}ₕᵃ; dim IDim = {IDim.tag}ₕᵃ; x", "declared twice"), + ("dim IDim = Iₕ; x", "must spell the full tag"), + (f"dim pkg:IDim = {IDim.tag}ₕᵃ; x", "has a module part"), + ], +) +def test_malformed_dimension_header_is_rejected(testee, message): + with pytest.raises(ValueError, match=message): + pparse(testee) + + +@pytest.mark.parametrize("testee", ["pkg:Other[pkg:K]ᵥᵃ", "pkg:A:Bₕ"]) +def test_malformed_dimension_tag_is_rejected(testee): + with pytest.raises((ValueError, lark_exceptions.LarkError)): + pparse(testee) diff --git a/tests/next_tests/unit_tests/iterator_tests/test_pretty_printer.py b/tests/next_tests/unit_tests/iterator_tests/test_pretty_printer.py index 1144b727b2..723dff82a7 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_pretty_printer.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_pretty_printer.py @@ -8,6 +8,9 @@ import pytest +import gt4py.next as gtx + +from gt4py.next import common from gt4py.next.iterator import builtins, ir, pretty_printer from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.pretty_printer import PrettyPrinter, pformat @@ -234,10 +237,8 @@ def test_shift(): def test_cartesian_offset(): - testee = ir.CartesianOffset( - domain=ir.AxisLiteral(value="I"), codomain=ir.AxisLiteral(value="J") - ) - expected = "Iₕ→Jₕ" + testee = ir.CartesianOffset(domain=ir.AxisLiteral(dim=IDim), codomain=ir.AxisLiteral(dim=JDim)) + expected = f"dim IDim = {IDim.tag}ₕᵃ;\ndim JDim = {JDim.tag}ₕᵃ;\nIDimₕ→JDimₕ" actual = pformat(testee) assert actual == expected @@ -259,30 +260,144 @@ def test_make_tuple(): assert actual == expected -def test_axis_literal_horizontal(): - testee = ir.AxisLiteral(value="I", kind=ir.DimensionKind.HORIZONTAL) - expected = "Iₕ" - actual = pformat(testee) - assert actual == expected +class IDim(gtx.CartesianAxisIndex): ... -def test_axis_literal_vertical(): - testee = ir.AxisLiteral(value="I", kind=ir.DimensionKind.VERTICAL) - expected = "Iᵥ" - actual = pformat(testee) - assert actual == expected +class JDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +class Vertex(gtx.DimensionIndex): ... + + +class LocalDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +@pytest.mark.parametrize( + "dim, suffix", [(IDim, "ₕᵃ"), (KDim, "ᵥᵃ"), (Vertex, "ₕ"), (LocalDim, "ₗ")] +) +def test_axis_literal(dim, suffix): + # the body names the dimension and its kind; the header spells the tag and all suffixes + expected = f"dim {dim.__qualname__} = {dim.tag}{suffix};\n{dim.__qualname__}{suffix[0]}" + assert pformat(ir.AxisLiteral(dim=dim)) == expected + + +def test_axis_literal_without_header_is_printed_in_full(): + # a printer not run through `apply` assigns no short names + assert PrettyPrinter().visit(ir.AxisLiteral(dim=IDim), prec=0) == [f"{IDim.tag}ₕᵃ"] + + +def test_axis_literal_of_unimportable_spec(): + # printing never imports: the literal carries its spec + spec = common.DimensionRef( + module="not.loaded", + qualname="KDim", + kind=common.DimensionKind.VERTICAL, + is_cartesian_axis=True, + ) + assert pformat(ir.AxisLiteral(dim=spec)) == "dim KDim = not.loaded:KDimᵥᵃ;\nKDimᵥ" def test_named_range_horizontal(): testee = ir.FunCall( fun=ir.SymRef(id="named_range"), - args=[ir.AxisLiteral(value="IDim"), ir.SymRef(id="x"), ir.SymRef(id="y")], + args=[ir.AxisLiteral(dim=IDim), ir.SymRef(id="x"), ir.SymRef(id="y")], ) - expected = "IDimₕ: [x, y[" + expected = f"dim IDim = {IDim.tag}ₕᵃ;\nIDimₕ: [x, y[" actual = pformat(testee) assert actual == expected +def test_dimension_header_is_printed_once_at_the_root(): + testee = im.make_tuple( + im.domain(common.GridType.CARTESIAN, {IDim: (0, 10), common.Staggered[KDim]: (0, 5)}), + ir.AxisLiteral(dim=IDim), + ) + expected = ( + f"dim IDim = {IDim.tag}ₕᵃ;\n" + f"dim Staggered[KDim] = {common.Staggered[KDim].tag}ᵥᵃ;\n" + "{c⟨ IDimₕ: [0, 10[, Staggered[KDim]ᵥ: [0, 5[ ⟩, IDimₕ}" + ) + assert pformat(testee) == expected + + +def _ref( + module: str, + qualname: str, + kind: common.DimensionKind = common.DimensionKind.HORIZONTAL, + is_cartesian_axis: bool = False, +) -> common.DimensionRef: + return common.DimensionRef(module, qualname, kind, is_cartesian_axis) + + +def test_short_names_are_qualnames_if_unique(): + names = pretty_printer.short_dimension_names([_ref("a.b", "Vertex"), _ref("a.b", "Edge")]) + assert names == {_ref("a.b", "Vertex"): "Vertex", _ref("a.b", "Edge"): "Edge"} + + +def test_colliding_short_names_get_the_shortest_distinguishing_module_suffix(): + dims = [_ref("pkg.x.dims", "Vertex"), _ref("pkg.y.dims", "Vertex"), _ref("dims", "Vertex")] + names = pretty_printer.short_dimension_names(dims) + assert names == { + _ref("dims", "Vertex"): "dims.Vertex", + _ref("pkg.x.dims", "Vertex"): "x.dims.Vertex", + _ref("pkg.y.dims", "Vertex"): "y.dims.Vertex", + } + # deterministic: independent of the order the dimensions are met in + assert pretty_printer.short_dimension_names(reversed(dims)) == names + + +def test_colliding_staggered_short_names_are_told_apart_by_their_base(): + vertical = common.DimensionKind.VERTICAL + k1, k2 = ( + _ref(module, "K", vertical, is_cartesian_axis=True) for module in ("pkg.one", "pkg.two") + ) + k1_half, k2_half = ( + common.DimensionRef.from_tag( + f"gt4py.next.common:Staggered[{k.tag}]", vertical, is_cartesian_axis=True + ) + for k in (k1, k2) + ) + testee = im.make_tuple(*(ir.AxisLiteral(dim=dim) for dim in (k1, k2, k1_half, k2_half))) + assert pformat(testee).splitlines()[-1] == ( + "{one.Kᵥ, two.Kᵥ, Staggered[one.K]ᵥ, Staggered[two.K]ᵥ}" + ) + + +def test_colliding_short_names_in_the_header(): + testee = im.make_tuple( + ir.AxisLiteral(dim=_ref("pkg.dims", "I")), ir.AxisLiteral(dim=_ref("other.dims", "I")) + ) + assert pformat(testee) == ( + "dim other.dims.I = other.dims:Iₕ;\ndim pkg.dims.I = pkg.dims:Iₕ;\n" + "{pkg.dims.Iₕ, other.dims.Iₕ}" + ) + + +def test_dimensions_sharing_their_tag_are_printed_in_full(): + # equal tags, different kinds: no short name tells them apart + horizontal = _ref("pkg", "X") + vertical = _ref("pkg", "X", common.DimensionKind.VERTICAL) + testee = im.make_tuple(ir.AxisLiteral(dim=horizontal), ir.AxisLiteral(dim=vertical)) + assert pformat(testee) == "{pkg:Xₕ, pkg:Xᵥ}" + + +def test_str_displays_short_names_without_header(): + testee = im.domain(common.GridType.CARTESIAN, {IDim: (0, 10)}) + assert str(testee) == "c⟨ IDimₕ: [0, 10[ ⟩" + assert pformat(testee, dimension_header=False) == str(testee) + assert pformat(testee) == f"dim IDim = {IDim.tag}ₕᵃ;\n{testee}" + + +def test_str_displays_disambiguated_short_names(): + testee = im.make_tuple( + ir.AxisLiteral(dim=_ref("pkg.dims", "I")), ir.AxisLiteral(dim=_ref("other.dims", "I")) + ) + assert str(testee) == "{pkg.dims.Iₕ, other.dims.Iₕ}" + + def test_cartesian_domain(): testee = ir.FunCall( fun=ir.SymRef(id="cartesian_domain"), args=[ir.SymRef(id="x"), ir.SymRef(id="y")] diff --git a/tests/next_tests/unit_tests/iterator_tests/test_pretty_roundtrip.py b/tests/next_tests/unit_tests/iterator_tests/test_pretty_roundtrip.py index 81396d8c59..b0f6e37e1e 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_pretty_roundtrip.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_pretty_roundtrip.py @@ -16,6 +16,8 @@ import pytest +import gt4py.next as gtx +from gt4py.next import common from gt4py.next.iterator import builtins, ir from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.pretty_parser import pparse @@ -23,9 +25,40 @@ from gt4py.next.type_system import type_specifications as ts +class I(gtx.CartesianAxisIndex): ... + + +class J(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +class Vertex(gtx.DimensionIndex): ... + + _SET_AT = ir.SetAt(expr=im.ref("x"), domain=im.call("cartesian_domain")(), target=im.ref("y")) +def _ref( + module: str, + qualname: str, + kind: common.DimensionKind = common.DimensionKind.VERTICAL, + is_cartesian_axis: bool = True, +) -> common.DimensionRef: + return common.DimensionRef(module, qualname, kind, is_cartesian_axis) + + +def _axes(*dims: common.DimensionRef | type) -> ir.FunCall: + return im.make_tuple(*(ir.AxisLiteral(dim=dim) for dim in dims)) + + +def _staggered(base: common.DimensionRef) -> common.DimensionRef: + return common.DimensionRef.from_tag( + f"gt4py.next.common:Staggered[{base.tag}]", base.kind, is_cartesian_axis=True + ) + + _LONG_NAME = ( "very_loooooooooooooooooooong_condition_to_force_a_line_break_and_test_alignment_of_branches" ) @@ -65,26 +98,49 @@ id="shift", ), pytest.param( - ir.CartesianOffset(domain=ir.AxisLiteral(value="I"), codomain=ir.AxisLiteral(value="J")), + ir.CartesianOffset(domain=ir.AxisLiteral(dim=I), codomain=ir.AxisLiteral(dim=J)), id="cartesian_offset", ), pytest.param( im.tuple_get(im.literal("42", builtins.INTEGER_INDEX_BUILTIN), "x"), id="tuple_get" ), pytest.param(im.make_tuple("x", "y"), id="make_tuple"), + pytest.param(ir.AxisLiteral(dim=I), id="axis_literal"), + pytest.param(ir.AxisLiteral(dim=Vertex), id="axis_literal_location"), + pytest.param(ir.AxisLiteral(dim=common.Staggered[KDim]), id="axis_literal_staggered"), + pytest.param( + ir.AxisLiteral( + dim=common.DimensionRef( + module="not.imported", + qualname="Outer.Local", + kind=common.DimensionKind.LOCAL, + ) + ), + id="axis_literal_not_importable", + ), + pytest.param(_axes(_ref("a.dims", "K"), _ref("b.dims", "K"), KDim), id="colliding_qualnames"), pytest.param( - ir.AxisLiteral(value="I", kind=ir.DimensionKind.HORIZONTAL), id="axis_literal_horizontal" + _axes(*(_staggered(_ref(module, "K")) for module in ("a.dims", "b.dims"))), + id="colliding_staggered_qualnames", ), pytest.param( - ir.AxisLiteral(value="I", kind=ir.DimensionKind.VERTICAL), id="axis_literal_vertical" + _axes(_ref("a", "K"), _ref("a", "K", common.DimensionKind.HORIZONTAL)), + id="dimensions_sharing_their_tag", ), pytest.param( - im.named_range(ir.AxisLiteral(value="IDim"), "x", "y"), id="named_range_horizontal" + _axes( + _ref("maillage.géo", "Δx"), + _ref("other.géo", "Δx"), # collides: told apart by non-ASCII module parts + _staggered(_ref("maillage.géo", "Ωz")), + _ref("maillage.géo", "_Ñ1", common.DimensionKind.LOCAL, is_cartesian_axis=False), + ), + id="non_ascii_identifiers", ), pytest.param( - im.named_range(ir.AxisLiteral(value="IDim", kind=ir.DimensionKind.VERTICAL), "x", "y"), - id="named_range_vertical", + im.domain(common.GridType.CARTESIAN, {I: (0, 1), common.Staggered[KDim]: ("x", "y")}), + id="cartesian_domain_with_dimensions", ), + pytest.param(im.named_range(ir.AxisLiteral(dim=I), "x", "y"), id="named_range"), pytest.param(im.call("cartesian_domain")("x"), id="cartesian_domain"), pytest.param(im.call("unstructured_domain")("x"), id="unstructured_domain"), pytest.param(im.if_("x", "y", "z"), id="if_short"), @@ -131,6 +187,22 @@ ), id="program", ), + pytest.param( + ir.Program( + id="f", + function_definitions=[], + params=[im.sym("x"), im.sym("y")], + declarations=[], + body=[ + ir.SetAt( + expr=im.ref("x"), + domain=im.domain(common.GridType.UNSTRUCTURED, {Vertex: (0, 1), KDim: (0, 2)}), + target=im.ref("y"), + ) + ], + ), + id="program_with_dimensions", + ), pytest.param(im.literal("1.0", "float32"), id="literal_float32"), pytest.param(im.literal("1", "int64"), id="literal_int64"), pytest.param(im.literal("1", "int8"), id="literal_int8"), @@ -161,7 +233,7 @@ pytest.param(ir.InfinityLiteral.NEGATIVE, id="infinity_negative"), pytest.param( im.named_range( - ir.AxisLiteral(value="KDim", kind=ir.DimensionKind.VERTICAL), + ir.AxisLiteral(dim=KDim), ir.InfinityLiteral.NEGATIVE, im.literal("5", "int32"), ), diff --git a/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py b/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py index bf2df06bf2..a742561830 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py @@ -15,19 +15,29 @@ from gt4py.next.iterator.runtime import CartesianDomain, UnstructuredDomain, _deduce_domain, fundef +class dummy_codomain(gtx.DimensionIndex): ... + + +class dummy_origin(gtx.DimensionIndex): ... + + +class dummy_neighbor(gtx.DimensionIndex): ... + + @fundef def foo(inp): return deref(inp) connectivity = common.ConnectivityType( - domain=[gtx.Dimension("dummy_origin"), gtx.Dimension("dummy_neighbor")], - codomain=gtx.Dimension("dummy_codomain"), + domain=[dummy_origin, dummy_neighbor], + codomain=dummy_codomain, skip_value=common._DEFAULT_SKIP_VALUE, dtype=None, ) -I = gtx.Dimension("I") + +class I(gtx.CartesianAxisIndex): ... def test_deduce_domain(): diff --git a/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py b/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py index af2eb1398b..7a014031d4 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py @@ -26,6 +26,7 @@ from gt4py.next.type_system import type_specifications as ts from next_tests.integration_tests.cases import ( + C2EDim, C2E, E2V, V2E, @@ -100,21 +101,15 @@ def expression_test_cases(): bool_type, ), ( - im.named_range( - itir.AxisLiteral(value="Vertex", kind=common.DimensionKind.HORIZONTAL), 0, 1 - ), + im.named_range(itir.AxisLiteral(dim=Vertex), 0, 1), it_ts.NamedRangeType(dim=Vertex), ), ( - im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(value="IDim"), 0, 1)), + im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)), ts.DomainType(dims=[IDim]), ), ( - im.call("unstructured_domain")( - im.named_range( - itir.AxisLiteral(value="Vertex", kind=common.DimensionKind.HORIZONTAL), 0, 1 - ) - ), + im.call("unstructured_domain")(im.named_range(itir.AxisLiteral(dim=Vertex), 0, 1)), ts.DomainType(dims=[Vertex]), ), # make_tuple @@ -131,7 +126,7 @@ def expression_test_cases(): ), # neighbors ( - im.neighbors("E2V", im.ref("a", it_on_e_of_e_type)), + im.neighbors(E2VDim.tag, im.ref("a", it_on_e_of_e_type)), ts.ListType(element_type=it_on_e_of_e_type.element_type, offset_type=E2VDim), ), # cast @@ -183,7 +178,7 @@ def expression_test_cases(): ts.TupleType(types=[int_type, float64_type]), ), # shift - (im.shift("V2E", 1)(im.ref("it", it_on_v_of_e_type)), it_on_e_of_e_type), + (im.shift(V2EDim.tag, 1)(im.ref("it", it_on_v_of_e_type)), it_on_e_of_e_type), # cartesian shift via `CartesianOffset` (im.shift(Ioff, 1)(im.ref("it", it_ijk_type)), it_ijk_type), # as_fieldop @@ -207,7 +202,7 @@ def expression_test_cases(): ), ( im.as_fieldop( - im.lambda_("it")(im.deref(im.shift(Koff, 1)(im.shift("V2E", 0)("it")))), + im.lambda_("it")(im.deref(im.shift(Koff, 1)(im.shift(V2EDim.tag, 0)("it")))), vertex_k_domain, )(im.ref("inp", float_edge_k_field)), float_vertex_k_field, @@ -216,7 +211,7 @@ def expression_test_cases(): im.as_fieldop( im.lambda_("it1", "it2")( im.plus( - im.deref(im.shift("E2V", 1)(im.shift("C2E", 1)("it1"))), + im.deref(im.shift(E2VDim.tag, 1)(im.shift(C2EDim.tag, 1)("it1"))), im.deref(im.shift(Koff, 1)("it2")), ), ), @@ -229,7 +224,7 @@ def expression_test_cases(): ), ( im.as_fieldop( - im.lambda_("it")(im.deref(im.shift("V2E", 0)("it"))), + im.lambda_("it")(im.deref(im.shift(V2EDim.tag, 0)("it"))), vertex_k_domain, )(im.ref("inp", float_edge_k_field)), float_vertex_k_field, @@ -262,15 +257,11 @@ def expression_test_cases(): False, im.as_fieldop( im.lambda_("a", "b")(im.plus(im.deref("a"), im.deref("b"))), - im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ), + im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)), )(im.ref("inp", float_i_field), 1.0), im.as_fieldop( "deref", - im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ), + im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)), )(im.ref("inp", float_i_field)), ), float_i_field, @@ -391,7 +382,7 @@ def test_late_offset_axis(): mesh = simple_mesh(None) func = im.lambda_("dim")(im.shift(im.ref("dim"), 1)(im.ref("it", it_on_v_of_e_type))) - testee = im.call(func)(im.ensure_offset("V2E")) + testee = im.call(func)(im.ensure_offset(V2EDim.tag)) result = itir_type_inference.infer( testee, offset_provider_type=mesh.offset_provider_type, allow_undeclared_symbols=True @@ -413,9 +404,7 @@ def test_cast_first_arg_inference(): def test_cartesian_fencil_definition(): - cartesian_domain = im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ) + cartesian_domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)) testee = itir.Program( id="f", @@ -444,10 +433,8 @@ def test_cartesian_fencil_definition(): def test_unstructured_fencil_definition(): mesh = simple_mesh(None) unstructured_domain = im.call("unstructured_domain")( - im.named_range( - itir.AxisLiteral(value="Vertex", kind=common.DimensionKind.HORIZONTAL), 0, 1 - ), - im.named_range(itir.AxisLiteral(value="KDim", kind=common.DimensionKind.VERTICAL), 0, 1), + im.named_range(itir.AxisLiteral(dim=Vertex), 0, 1), + im.named_range(itir.AxisLiteral(dim=KDim), 0, 1), ) testee = itir.Program( @@ -458,7 +445,7 @@ def test_unstructured_fencil_definition(): body=[ itir.SetAt( expr=im.as_fieldop( - im.lambda_("it")(im.deref(im.shift("V2E", 0)("it"))), unstructured_domain + im.lambda_("it")(im.deref(im.shift(V2EDim.tag, 0)("it"))), unstructured_domain )(im.ref("inp")), domain=unstructured_domain, target=im.ref("out"), @@ -479,9 +466,7 @@ def test_unstructured_fencil_definition(): def test_function_definition(): - cartesian_domain = im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ) + cartesian_domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)) testee = itir.Program( id="f", @@ -511,10 +496,8 @@ def test_function_definition(): def test_fencil_with_nb_field_input(): mesh = simple_mesh(None) unstructured_domain = im.call("unstructured_domain")( - im.named_range( - itir.AxisLiteral(value="Vertex", kind=common.DimensionKind.HORIZONTAL), 0, 1 - ), - im.named_range(itir.AxisLiteral(value="KDim", kind=common.DimensionKind.VERTICAL), 0, 1), + im.named_range(itir.AxisLiteral(dim=Vertex), 0, 1), + im.named_range(itir.AxisLiteral(dim=KDim), 0, 1), ) testee = itir.Program( @@ -541,9 +524,7 @@ def test_fencil_with_nb_field_input(): def test_program_tuple_setat_short_target(): - cartesian_domain = im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ) + cartesian_domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)) testee = itir.Program( id="f", @@ -572,9 +553,7 @@ def test_program_tuple_setat_short_target(): def test_program_setat_without_domain(): - cartesian_domain = im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ) + cartesian_domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)) testee = itir.Program( id="f", @@ -596,9 +575,7 @@ def test_program_setat_without_domain(): def test_if_stmt(): - cartesian_domain = im.call("cartesian_domain")( - im.named_range(itir.AxisLiteral(value="IDim"), 0, 1) - ) + cartesian_domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=IDim), 0, 1)) testee = itir.IfStmt( cond=im.literal_from_value(True), @@ -624,7 +601,7 @@ def test_as_fieldop_without_domain_nb_field_input(): testee = im.as_fieldop(stencil)(im.ref("inp1", float_vertex_v2e_field)) result = itir_type_inference.infer( - testee, offset_provider_type={"V2E": V2E}, allow_undeclared_symbols=True + testee, offset_provider_type={V2EDim.tag: V2E}, allow_undeclared_symbols=True ) assert result.type == ts.FieldType(dims=[Vertex], dtype=float64_list_type) assert result.fun.args[0].type.pos_only_args[0] == it_ts.IteratorType( diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py index e4a8bf2330..cc4a7c437e 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py @@ -7,17 +7,17 @@ # SPDX-License-Identifier: BSD-3-Clause import pytest -from gt4py.next import common, utils +from gt4py.next import utils from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.transforms import inline_lambdas from gt4py.next.iterator.transforms.collapse_tuple import CollapseTuple from gt4py.next.iterator.type_system import type_specifications as it_ts from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import KDim + int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) -Vertex = common.Dimension(value="Vertex", kind=common.DimensionKind.HORIZONTAL) -KDim = common.Dimension(value="KDim", kind=common.DimensionKind.VERTICAL) def test_simple_make_tuple_tuple_get(uids: utils.IDGeneratorPool): diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_canonicalize_domain_args.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_canonicalize_domain_args.py index 58086670f9..07a81b01fd 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_canonicalize_domain_args.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_canonicalize_domain_args.py @@ -14,9 +14,11 @@ inline_lambdas, ) from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) -IDim = common.Dimension(value="IDim", kind=common.DimensionKind.HORIZONTAL) + + field_type = ts.FieldType(dims=[IDim], dtype=int_type) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_expand_tuple_args.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_expand_tuple_args.py index efb050d516..2e93c7fb88 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_expand_tuple_args.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_expand_tuple_args.py @@ -15,9 +15,11 @@ ) from gt4py.next.type_system import type_specifications as ts from gt4py.next.iterator.type_system import type_specifications as it_ts +from next_tests.integration_tests.cases_utils import IDim int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) -IDim = common.Dimension(value="IDim", kind=common.DimensionKind.HORIZONTAL) + + field_type = ts.FieldType(dims=[IDim], dtype=int_type) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_transform_to_as_fieldop.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_transform_to_as_fieldop.py index 2517c7ab55..86e7fa7fe8 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_transform_to_as_fieldop.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_concat_where_transform_to_as_fieldop.py @@ -12,10 +12,9 @@ from gt4py.next.iterator.transforms.concat_where import transform_to_as_fieldop from gt4py.next.iterator.transforms.concat_where.transform_to_as_fieldop import _in from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim, JDim int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) -IDim = common.Dimension(value="IDim", kind=common.DimensionKind.HORIZONTAL) -JDim = common.Dimension(value="JDim", kind=common.DimensionKind.HORIZONTAL) def test_in_helper(): diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_cse.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_cse.py index a9ef6f288e..862bbf3d2f 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_cse.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_cse.py @@ -20,9 +20,12 @@ ) +class I(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... + + @pytest.fixture def offset_provider_type(request): - return {"I": common.Dimension("I", kind=common.DimensionKind.HORIZONTAL)} + return {"I": I} @pytest.fixture diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_dead_code_elimination.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_dead_code_elimination.py index 6f519b246b..bc1dbc3355 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_dead_code_elimination.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_dead_code_elimination.py @@ -14,7 +14,10 @@ from gt4py.next.iterator import ir as itir from gt4py.next.iterator.transforms import dead_code_elimination -TDim = common.Dimension(value="TDim") + +class TDim(common.CartesianAxisIndex): ... + + int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) field_type = ts.FieldType(dims=[TDim], dtype=int_type) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py index 3aab352b32..ba9f2f108c 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py @@ -25,15 +25,13 @@ from gt4py.next.iterator.transforms import infer_domain from gt4py.next.iterator.transforms.constant_folding import ConstantFolding from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim, JDim, KDim +from next_tests.toy_connectivity import E2VDim, Edge, Vertex float_type = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) -IDim = common.Dimension(value="IDim", kind=common.DimensionKind.HORIZONTAL) -JDim = common.Dimension(value="JDim", kind=common.DimensionKind.HORIZONTAL) -KDim = common.Dimension(value="KDim", kind=common.DimensionKind.VERTICAL) -Vertex = common.Dimension(value="Vertex", kind=common.DimensionKind.HORIZONTAL) -Edge = common.Dimension(value="Edge", kind=common.DimensionKind.HORIZONTAL) -E2VDim = common.Dimension(value="E2V", kind=common.DimensionKind.LOCAL) + + float_i_field = ts.FieldType(dims=[IDim], dtype=float_type) float_ij_field = ts.FieldType(dims=[IDim, JDim], dtype=float_type) tuple_float_i_field = ts.TupleType( @@ -47,7 +45,7 @@ @pytest.fixture def unstructured_offset_provider(): return { - "E2V": constructors.as_connectivity( + E2VDim.tag: constructors.as_connectivity( domain={Edge: 1, E2VDim: 2}, codomain=Vertex, data=np.array([[0, 1]], dtype=np.int32), @@ -223,9 +221,9 @@ def test_multi_length_shift(): def test_unstructured_shift(unstructured_offset_provider): - stencil = im.lambda_("arg0")(im.deref(im.shift("E2V", 1)("arg0"))) + stencil = im.lambda_("arg0")(im.deref(im.shift(E2VDim.tag, 1)("arg0"))) domain = im.domain(common.GridType.UNSTRUCTURED, {Edge: (0, 1)}) - accessed_vertex = unstructured_offset_provider["E2V"].ndarray[0, 1] + accessed_vertex = unstructured_offset_provider[E2VDim.tag].ndarray[0, 1] expected_domains = {"in_field1": {Vertex: (accessed_vertex, accessed_vertex + np.int32(1))}} testee, expected = setup_test_as_fieldop(stencil, domain, expected_domains=expected_domains) @@ -1168,9 +1166,9 @@ def test_scan(): def test_symbolic_domain_sizes(unstructured_offset_provider): - stencil = im.lambda_("arg0")(im.deref(im.shift("E2V", 1)("arg0"))) + stencil = im.lambda_("arg0")(im.deref(im.shift(E2VDim.tag, 1)("arg0"))) domain = im.domain(common.GridType.UNSTRUCTURED, {Edge: (0, 1)}) - symbolic_domain_sizes = {"Vertex": "num_vertices"} + symbolic_domain_sizes = {Vertex.tag: "num_vertices"} expected_domains = {"in_field1": {Vertex: (0, im.ref("num_vertices"))}} testee, expected = setup_test_as_fieldop( stencil, @@ -1412,7 +1410,7 @@ def test_concat_where_unstructured_shift_in_never_selected_branch(unstructured_o # `Edge: [1, 1)` range must not raise. domain = im.domain(common.GridType.UNSTRUCTURED, {Edge: (0, 1)}) cond = im.domain(common.GridType.UNSTRUCTURED, {Edge: (1, itir.InfinityLiteral.POSITIVE)}) - stencil_e2v = im.lambda_("it")(im.deref(im.shift("E2V", 0)("it"))) + stencil_e2v = im.lambda_("it")(im.deref(im.shift(E2VDim.tag, 0)("it"))) domain_empty = im.domain(common.GridType.UNSTRUCTURED, {Edge: (1, 1)}) domain_a = im.domain(common.GridType.UNSTRUCTURED, {Vertex: (0, 0)}) @@ -1439,7 +1437,7 @@ def test_concat_where_unstructured_shift_in_never_selected_branch(unstructured_o def test_broadcast(): - testee = im.call("broadcast")("in_field", im.make_tuple(itir.AxisLiteral(value="IDim"))) + testee = im.call("broadcast")("in_field", im.make_tuple(itir.AxisLiteral(dim=IDim))) domain = im.domain(common.GridType.CARTESIAN, {IDim: (0, 10)}) expected_domains = { "in_field": {IDim: (0, 10)}, diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_expand_tuple_maps.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_expand_tuple_maps.py index 4dc3373832..ece28573be 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_expand_tuple_maps.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_expand_tuple_maps.py @@ -8,15 +8,15 @@ import pytest -from gt4py.next import common, utils +from gt4py.next import utils from gt4py.next.iterator import ir as itir from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.transforms.collapse_tuple import CollapseTuple from gt4py.next.iterator.transforms.expand_tuple_maps import ExpandTupleMaps from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim -IDim = common.Dimension("IDim") T = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) i_field = ts.FieldType(dims=[IDim], dtype=T) i_tuple_field = ts.TupleType(types=[i_field, i_field]) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py index 3af2dd09f9..c9c3145863 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py @@ -22,10 +22,12 @@ collapse_tuple as ct, ) from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim, JDim + + +class Neighbor(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... -IDim = common.Dimension("IDim") -JDim = common.Dimension("JDim") field_type = ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.INT32)) IOff = im.cartesian_offset(IDim, IDim) @@ -363,7 +365,7 @@ def test_inline_as_fieldop_with_list_dtype(uids: utils.IDGeneratorPool): dims=[IDim], dtype=ts.ListType( element_type=ts.ScalarType(kind=ts.ScalarKind.INT32), - offset_type=common.Dimension("Neighbor", kind=common.DimensionKind.LOCAL), + offset_type=Neighbor, ), ) d = im.domain("cartesian_domain", {IDim: (0, 1)}) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py index c6c82d56a7..2e8bbc502c 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py @@ -10,7 +10,6 @@ import pytest import functools from gt4py.next import utils -from gt4py.next import common from gt4py.next.iterator import builtins, ir as itir from gt4py.next.iterator.transforms import ( global_tmps, @@ -24,11 +23,9 @@ ir_makers as im, misc as ir_utils_misc, ) +from next_tests.integration_tests.cases_utils import IDim, KDim -IDim = common.Dimension(value="IDim") -JDim = common.Dimension(value="JDim") -KDim = common.Dimension(value="KDim", kind=common.DimensionKind.VERTICAL) index_type = ts.ScalarType(kind=getattr(ts.ScalarKind, builtins.INTEGER_INDEX_BUILTIN.upper())) float_type = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) i_field_type = ts.FieldType(dims=[IDim], dtype=float_type) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py index 53ba1627b4..ec2b2f4c4b 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py @@ -6,11 +6,12 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.iterator.transforms.inline_into_scan import InlineIntoScan from gt4py.next.iterator.ir_utils import ir_makers as im +from next_tests.integration_tests.cases_utils import KDim + def _make_scan(*args: list[str], scanpass_body: ir.Expr) -> ir.Expr: return ir.FunCall( @@ -22,7 +23,7 @@ def _make_scan(*args: list[str], scanpass_body: ir.Expr) -> ir.Expr: ), im.literal("0.0", "float64"), im.literal("True", "bool"), - im.axis_literal(common.Dimension("KDim", common.DimensionKind.VERTICAL)), + im.axis_literal(KDim), ], ) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_scalar.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_scalar.py index 4569b42305..f391363e76 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_scalar.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_scalar.py @@ -13,7 +13,10 @@ from gt4py.next.iterator.transforms import inline_scalar from gt4py.next.iterator.ir_utils import ir_makers as im -TDim = common.Dimension(value="TDim") + +class TDim(common.CartesianAxisIndex): ... + + int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_casts.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_casts.py index b1a18ddab8..1fa8b1ec84 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_casts.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_casts.py @@ -6,11 +6,11 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from gt4py import next as gtx from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.iterator.transforms.prune_casts import PruneCasts from gt4py.next.iterator.type_system import inference as type_inference from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim def test_prune_casts_simple(): @@ -25,7 +25,6 @@ def test_prune_casts_simple(): def test_prune_casts_fieldop(): - IDim = gtx.Dimension("IDim") x_ref = im.ref("x", ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT32))) y_ref = im.ref("y", ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64))) testee = im.op_as_fieldop("plus")( diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_empty_concat_where.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_empty_concat_where.py index ead2bd1724..a0e6897c28 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_empty_concat_where.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_prune_empty_concat_where.py @@ -17,11 +17,11 @@ from gt4py.next.iterator.transforms.inline_lambdas import InlineLambdas from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm, domain_utils from gt4py.next.type_system import type_info, type_specifications as ts +from next_tests.toy_connectivity import Edge, V2EDim, Vertex + + +class K(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... -Vertex = common.Dimension(value="Vertex", kind=common.DimensionKind.HORIZONTAL) -Edge = common.Dimension(value="Edge", kind=common.DimensionKind.HORIZONTAL) -V2EDim = common.Dimension(value="V2E", kind=common.DimensionKind.LOCAL) -K = common.Dimension(value="K", kind=common.DimensionKind.VERTICAL) float64 = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) vertex_k_field = ts.FieldType(dims=[Vertex, K], dtype=float64) @@ -230,7 +230,7 @@ def branch_expr(branch: tuple[str, ts.FieldType] | itir.Expr) -> itir.Expr: { dim: bounds for dim, bounds in accessed_domain.items() - if dim in type_info.extract_dims(inner.type) + if common.dimension_ref(dim) in type_info.extract_dims(inner.type) }, ) ) @@ -246,13 +246,13 @@ def test_prune_equal_branches_containing_unstructured_shift(): failing on the `V2E` translation during the re-inference). """ offset_provider = { - "V2E": constructors.as_connectivity( + V2EDim.tag: constructors.as_connectivity( domain={Vertex: 1, V2EDim: 2}, codomain=Edge, data=np.array([[0, 1]], dtype=np.int32), ) } - stencil = im.lambda_("it")(im.deref(im.shift("V2E", 0)("it"))) + stencil = im.lambda_("it")(im.deref(im.shift(V2EDim.tag, 0)("it"))) branch = im.as_fieldop(stencil)(im.ref("e", edge_field)) accessed_domain = {Vertex: (0, 1), K: (0, 10)} diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py index 095820fc2a..e07628e5b1 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py @@ -10,16 +10,16 @@ import pytest -from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.iterator.ir_utils import ir_makers as im -from gt4py.next.iterator.transforms import pass_manager -from gt4py.next.iterator.transforms import scan_fusion +from gt4py.next.iterator.transforms import pass_manager, scan_fusion from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import KDim + def make_shadowed_program(scope): - k = common.Dimension("K", kind=common.DimensionKind.VERTICAL) + k = KDim field_type = ts.FieldType(dims=[k], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)) domain = im.domain("cartesian_domain", {k: (0, 5)}) scan = im.scan( diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py index edb16c0381..463bfcd063 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py @@ -8,11 +8,12 @@ import pytest -from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.iterator.transforms.simple_inline_heuristic import is_eligible_for_inlining from gt4py.next.iterator.ir_utils import ir_makers as im +from next_tests.integration_tests.cases_utils import KDim + @pytest.fixture def scan(): @@ -31,7 +32,7 @@ def scan(): ), im.literal("True", "bool"), im.literal("0.0", "float64"), - im.axis_literal(common.Dimension("KDim", common.DimensionKind.VERTICAL)), + im.axis_literal(KDim), ], ) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_unroll_reduce.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_unroll_reduce.py index 8083c56a8f..1422e8d0b4 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_unroll_reduce.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_unroll_reduce.py @@ -15,25 +15,40 @@ from gt4py.next.type_system import type_specifications as ts +class dummy_codomain(common.DimensionIndex): ... + + +class dummy_origin(common.DimensionIndex): ... + + +class dummy_neighbor(common.DimensionIndex): ... + + +#: The local dimensions of the neighbor lists under test. Each one's `tag` is also its IR offset +#: string and its offset-provider key: `UnrollReduce` looks a connectivity up by the local +#: dimension of the list it reduces, so those three names must be a single string (ADR 0030). +class Dim(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... + + +class Dim2(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... + + def dummy_connectivity_type(max_neighbors: int, has_skip_values: bool): return common.NeighborConnectivityType( - domain=[common.Dimension("dummy_origin"), common.Dimension("dummy_neighbor")], - codomain=common.Dimension("dummy_codomain"), + domain=[dummy_origin, dummy_neighbor], + codomain=dummy_codomain, skip_value=common._DEFAULT_SKIP_VALUE if has_skip_values else None, dtype=None, max_neighbors=max_neighbors, ) -def _list_type(dim: str) -> ts.ListType: - return ts.ListType( - element_type=ts.DataType(), - offset_type=common.Dimension(value=dim, kind=common.DimensionKind.LOCAL), - ) +def _list_type(dim: common.Dimension) -> ts.ListType: + return ts.ListType(element_type=ts.DataType(), offset_type=dim) -def typed_neighbors(dim: str, arg: str | ir.Expr) -> ir.FunCall: - neighbors = im.neighbors(dim, arg) +def typed_neighbors(dim: common.Dimension, arg: str | ir.Expr) -> ir.FunCall: + neighbors = im.neighbors(dim.tag, arg) neighbors.type = _list_type(dim) return neighbors @@ -45,32 +60,32 @@ def has_skip_values(request): @pytest.fixture def basic_reduction(): - return im.reduce("foo", 0.0)(typed_neighbors("Dim", "x")) + return im.reduce("foo", 0.0)(typed_neighbors(Dim, "x")) @pytest.fixture def reduction_with_shift_on_second_arg(): const_list = im.call("make_const_list")(42) - const_list.type = _list_type("Dim") - return im.reduce("foo", 0.0)(const_list, typed_neighbors("Dim", "y")) + const_list.type = _list_type(Dim) + return im.reduce("foo", 0.0)(const_list, typed_neighbors(Dim, "y")) @pytest.fixture def reduction_with_incompatible_shifts(): - return im.reduce("foo", 0.0)(typed_neighbors("Dim", "x"), typed_neighbors("Dim2", "y")) + return im.reduce("foo", 0.0)(typed_neighbors(Dim, "x"), typed_neighbors(Dim2, "y")) @pytest.fixture def reduction_with_irrelevant_full_shift(): return im.reduce("foo", 0.0)( - typed_neighbors("Dim", im.shift("IrrelevantDim", 0)("x")), typed_neighbors("Dim", "y") + typed_neighbors(Dim, im.shift("IrrelevantDim", 0)("x")), typed_neighbors(Dim, "y") ) @pytest.fixture def reduction_if(): - if_expr = im.if_(True, typed_neighbors("Dim", "x"), "y") - if_expr.type = _list_type("Dim") + if_expr = im.if_(True, typed_neighbors(Dim, "x"), "y") + if_expr.type = _list_type(Dim) return im.reduce("foo", 0.0)(if_expr) @@ -86,7 +101,7 @@ def reduction_if(): def test_get_partial_offsets(reduction, request): partial_offsets = _get_partial_offset_tags(request.getfixturevalue(reduction).args) - assert set(partial_offsets) == {"Dim"} + assert set(partial_offsets) == {Dim.tag} def _expected(red, max_neighbors, has_skip_values, shifted_arg=0): @@ -116,7 +131,7 @@ def test_basic(basic_reduction, has_skip_values, uids: utils.IDGeneratorPool): expected = _expected(basic_reduction, 3, has_skip_values) offset_provider_type = { - "Dim": dummy_connectivity_type(max_neighbors=3, has_skip_values=has_skip_values) + Dim.tag: dummy_connectivity_type(max_neighbors=3, has_skip_values=has_skip_values) } actual = UnrollReduce.apply( basic_reduction, offset_provider_type=offset_provider_type, uids=uids @@ -130,7 +145,7 @@ def test_reduction_with_shift_on_second_arg( expected = _expected(reduction_with_shift_on_second_arg, 1, has_skip_values, 1) offset_provider_type = { - "Dim": dummy_connectivity_type(max_neighbors=1, has_skip_values=has_skip_values) + Dim.tag: dummy_connectivity_type(max_neighbors=1, has_skip_values=has_skip_values) } actual = UnrollReduce.apply( reduction_with_shift_on_second_arg, offset_provider_type=offset_provider_type, uids=uids @@ -141,7 +156,9 @@ def test_reduction_with_shift_on_second_arg( def test_reduction_with_if(reduction_if, uids: utils.IDGeneratorPool): expected = _expected(reduction_if, 2, False) - offset_provider_type = {"Dim": dummy_connectivity_type(max_neighbors=2, has_skip_values=False)} + offset_provider_type = { + Dim.tag: dummy_connectivity_type(max_neighbors=2, has_skip_values=False) + } actual = UnrollReduce.apply(reduction_if, offset_provider_type=offset_provider_type, uids=uids) assert actual == expected @@ -152,7 +169,7 @@ def test_reduction_with_irrelevant_full_shift( expected = _expected(reduction_with_irrelevant_full_shift, 3, False) offset_provider_type = { - "Dim": dummy_connectivity_type(max_neighbors=3, has_skip_values=False), + Dim.tag: dummy_connectivity_type(max_neighbors=3, has_skip_values=False), "IrrelevantDim": dummy_connectivity_type( max_neighbors=1, has_skip_values=True ), # different max_neighbors and skip value to trigger error @@ -167,16 +184,16 @@ def test_reduction_with_irrelevant_full_shift( "offset_provider_type", [ { - "Dim": dummy_connectivity_type(max_neighbors=3, has_skip_values=False), - "Dim2": dummy_connectivity_type(max_neighbors=2, has_skip_values=False), + Dim.tag: dummy_connectivity_type(max_neighbors=3, has_skip_values=False), + Dim2.tag: dummy_connectivity_type(max_neighbors=2, has_skip_values=False), }, { - "Dim": dummy_connectivity_type(max_neighbors=3, has_skip_values=False), - "Dim2": dummy_connectivity_type(max_neighbors=3, has_skip_values=True), + Dim.tag: dummy_connectivity_type(max_neighbors=3, has_skip_values=False), + Dim2.tag: dummy_connectivity_type(max_neighbors=3, has_skip_values=True), }, { - "Dim": dummy_connectivity_type(max_neighbors=3, has_skip_values=False), - "Dim2": dummy_connectivity_type(max_neighbors=2, has_skip_values=True), + Dim.tag: dummy_connectivity_type(max_neighbors=3, has_skip_values=False), + Dim2.tag: dummy_connectivity_type(max_neighbors=2, has_skip_values=True), }, ], ) diff --git a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_cpp_interface.py b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_cpp_interface.py index 8e5e8dcca4..6962e0ec56 100644 --- a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_cpp_interface.py +++ b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_cpp_interface.py @@ -15,6 +15,12 @@ from gt4py.next.otf.binding import interface +class bar(gtx.DimensionIndex): ... + + +class foo(gtx.DimensionIndex): ... + + @pytest.fixture def function_scalar_example(): return interface.Function( @@ -54,15 +60,13 @@ def function_buffer_example(): interface.Parameter( name="a_buf", type_=ts.FieldType( - dims=[gtx.Dimension("bar"), gtx.Dimension("foo")], + dims=[bar, foo], dtype=ts.ScalarType(ts.ScalarKind.FLOAT64), ), ), interface.Parameter( name="b_buf", - type_=ts.FieldType( - dims=[gtx.Dimension("bar")], dtype=ts.ScalarType(ts.ScalarKind.INT64) - ), + type_=ts.FieldType(dims=[bar], dtype=ts.ScalarType(ts.ScalarKind.INT64)), ), ], ) @@ -99,11 +103,11 @@ def function_tuple_example(): type_=ts.TupleType( types=[ ts.FieldType( - dims=[gtx.Dimension("bar"), gtx.Dimension("foo")], + dims=[bar, foo], dtype=ts.ScalarType(ts.ScalarKind.FLOAT64), ), ts.FieldType( - dims=[gtx.Dimension("bar"), gtx.Dimension("foo")], + dims=[bar, foo], dtype=ts.ScalarType(ts.ScalarKind.FLOAT64), ), ] diff --git a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py index ba83a07b2d..69106e6df7 100644 --- a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py +++ b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py @@ -6,17 +6,21 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import shutil import jinja2 import pytest import gt4py.next as gtx import gt4py.next.type_system.type_specifications as ts -from gt4py.next import config +from gt4py.next import common, config from gt4py.next.otf import artifacts from gt4py.next.otf.binding import cpp_interface, interface, nanobind -from gt4py.next.otf.compilation import cache + + +class I(gtx.CartesianAxisIndex): ... + + +class J(gtx.CartesianAxisIndex): ... def make_program_source(name: str) -> artifacts.ProgramSource: @@ -26,7 +30,7 @@ def make_program_source(name: str) -> artifacts.ProgramSource: interface.Parameter( name="buf", type_=ts.FieldType( - dims=[gtx.Dimension("I"), gtx.Dimension("J")], + dims=[I, J], dtype=ts.ScalarType(ts.ScalarKind.FLOAT32), ), ), @@ -35,11 +39,11 @@ def make_program_source(name: str) -> artifacts.ProgramSource: type_=ts.TupleType( types=[ ts.FieldType( - dims=[gtx.Dimension("I"), gtx.Dimension("J")], + dims=[I, J], dtype=ts.ScalarType(ts.ScalarKind.FLOAT32), ), ts.FieldType( - dims=[gtx.Dimension("I"), gtx.Dimension("J")], + dims=[I, J], dtype=ts.ScalarType(ts.ScalarKind.FLOAT32), ), ] @@ -49,11 +53,13 @@ def make_program_source(name: str) -> artifacts.ProgramSource: ), returns=True, ) + # the generated bindings reference tag types named after the mangled dimension tags + i_t, j_t = (common.codegen_name(d.tag) for d in (I, J)) func = cpp_interface.render_function_declaration( entry_point, - """\ - const auto xdim = gridtools::at_key(sid_get_upper_bounds(buf)); - const auto ydim = gridtools::at_key(sid_get_upper_bounds(buf)); + f"""\ + const auto xdim = gridtools::at_key(sid_get_upper_bounds(buf)); + const auto ydim = gridtools::at_key(sid_get_upper_bounds(buf)); return xdim * ydim * sc;\ """, ) @@ -62,12 +68,12 @@ def make_program_source(name: str) -> artifacts.ProgramSource: #include #include namespace generated { - struct I_t {} constexpr inline I; - struct J_t {} constexpr inline J; + struct {{i_t}}_t {} constexpr inline {{i_t}}; + struct {{j_t}}_t {} constexpr inline {{j_t}}; } {{func}}\ """ - ).render(func=func) + ).render(func=func, i_t=i_t, j_t=j_t) return artifacts.ProgramSource( entry_point=entry_point, diff --git a/tests/next_tests/unit_tests/otf_tests/test_compilation_task_dimension_classes.py b/tests/next_tests/unit_tests/otf_tests/test_compilation_task_dimension_classes.py new file mode 100644 index 0000000000..713315d047 --- /dev/null +++ b/tests/next_tests/unit_tests/otf_tests/test_compilation_task_dimension_classes.py @@ -0,0 +1,225 @@ +# 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 + +""" +Which user dimension classes does a shipped compilation task still reference? + +The `ProcessRunner` compiles in a spawn worker, which cannot import classes declared in an +interactive `__main__` (a notebook). Below the frontend, dimensions are `DimensionRef` values, +so the compile task should not need the classes at all. These tests pickle exactly what +`ProcessRunner.submit` ships -- `(task.executor, task.compilable)` -- and record +every dimension class referenced from an interactive-like `__main__`. +""" + +import io +import os +import pickle +import subprocess +import sys +import types +import warnings + +import numpy as np +import pytest + +import gt4py.next as gtx +from gt4py.next import common +from gt4py.next.otf import arguments, compilation_tasks, runners + + +def _notebook_dim(name: str, base: type, **kwargs) -> gtx.Dimension: + # As if declared in a notebook cell: module `__main__`, which a spawn worker cannot import. + return common.DimensionMeta( + name, (base,), {"__module__": "__main__", "__qualname__": name, "__slots__": ()}, **kwargs + ) + + +NbIDim = _notebook_dim("NbIDim", gtx.CartesianAxisIndex) +NbKDim = _notebook_dim("NbKDim", gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL) +NbVertex = _notebook_dim("NbVertex", gtx.DimensionIndex) +NbEdge = _notebook_dim("NbEdge", gtx.DimensionIndex) +NbV2EDim = _notebook_dim("NbV2EDim", gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL) +NbKHalfDim = common.Staggered[NbKDim] + +NbV2E = gtx.FieldOffset("NbV2E", source=NbEdge, target=(NbVertex, NbV2EDim)) + + +@gtx.field_operator +def _cartesian_shift( + a: gtx.Field[gtx.Dims[NbIDim, NbKDim], gtx.float64], +) -> gtx.Field[gtx.Dims[NbIDim, NbKDim], gtx.float64]: + return a(NbIDim + 1) + a(NbKHalfDim + 0.5)(NbKDim - 0.5) + + +@gtx.program +def cartesian_program( + a: gtx.Field[gtx.Dims[NbIDim, NbKDim], gtx.float64], + out: gtx.Field[gtx.Dims[NbIDim, NbKDim], gtx.float64], +): + _cartesian_shift(a, out=out, domain={NbIDim: (0, 4), NbKDim: (0, 3)}) + + +@gtx.field_operator +def _neighbor_shift( + e: gtx.Field[gtx.Dims[NbEdge], gtx.float64], +) -> gtx.Field[gtx.Dims[NbVertex], gtx.float64]: + return e(NbV2E[0]) + + +@gtx.program +def unstructured_program( + e: gtx.Field[gtx.Dims[NbEdge], gtx.float64], + out: gtx.Field[gtx.Dims[NbVertex], gtx.float64], +): + _neighbor_shift(e, out=out) + + +@pytest.fixture +def interactive_main(monkeypatch): + main = types.ModuleType("__main__") # no `__file__`: a notebook / REPL `__main__` + for dim in (NbIDim, NbKDim, NbVertex, NbEdge, NbV2EDim): + setattr(main, dim.__qualname__, dim) + monkeypatch.setitem(sys.modules, "__main__", main) + return main + + +def _main_dimensions_referenced(obj: object) -> list[str]: + found: list[str] = [] + + class _Scanner(pickle.Pickler): + def reducer_override(self, o: object): + if isinstance(o, common.DimensionMeta) and o.__module__ == "__main__": + found.append(o.__qualname__) + return NotImplemented + + _Scanner(io.BytesIO()).dump(obj) + return found + + +def _shipped(program, *args, offset_provider): + task = compilation_tasks.make_compilation_task( + gtx.gtfn_cpu, + program.definition_stage, + arguments.CompileTimeArgs.from_concrete(*args, offset_provider=offset_provider), + ) + return task.executor, task.compilable + + +def test_cartesian_task_references_no_dimension_class(interactive_main): + a = gtx.zeros({NbIDim: 4, NbKDim: 3}) + shipped = _shipped(cartesian_program, a, a, offset_provider={}) + + assert _main_dimensions_referenced(shipped) == [] + # ...which is exactly the condition under which `ProcessRunner` falls back to compiling in + # the calling thread + assert runners._interactive_main_reference(shipped) is None + + +def test_unstructured_task_still_references_connectivity_dimensions(interactive_main): + """ + The runtime offset provider is still shipped (`CompileTimeArgs.offset_provider`, needed by + the worker-side ITIR passes for domain sizes and `prune_empty_concat_where`), and a + connectivity's `domain` and `codomain` are dimension classes. + """ + e = gtx.zeros({NbEdge: 3}) + v = gtx.zeros({NbVertex: 2}) + v2e = gtx.as_connectivity( + domain={NbVertex: 2, NbV2EDim: 1}, codomain=NbEdge, data=np.array([[0], [2]], np.int32) + ) + executor, compilable = _shipped(unstructured_program, e, v, offset_provider={"NbV2E": v2e}) + + assert _main_dimensions_referenced(compilable.data) == [] # the IR is self-contained + assert _main_dimensions_referenced(compilable.args.args) == [] # so are the arg types + assert sorted(set(_main_dimensions_referenced(compilable.args.offset_provider))) == [ + "NbEdge", + "NbV2EDim", + "NbVertex", + ] + + +def test_cartesian_task_compiles_in_a_spawn_worker(interactive_main, tmp_path): + """The real thing: a spawn worker, which cannot import `__main__`, unpickles and compiles.""" + a = gtx.zeros({NbIDim: 4, NbKDim: 3}) + task = compilation_tasks.make_compilation_task( + gtx.gtfn_cpu, + cartesian_program.definition_stage, + arguments.CompileTimeArgs.from_concrete(a, a, offset_provider={}), + ) + runner = runners.ProcessRunner(max_workers=1, shared_session_cache_dir=str(tmp_path)) + try: + with warnings.catch_warnings(): + warnings.filterwarnings("error", message=".*in the calling thread.*") + future = runner.submit(task) # no fallback to the calling thread + artifact = future.result(timeout=600) + finally: + runner.shutdown(wait=True) + assert artifact is not None + assert callable(gtx.gtfn_cpu.load_artifact(artifact)) + + +_GUARDED_SCRIPT = """ +import concurrent.futures +import multiprocessing +import warnings + +import numpy as np + +import gt4py.next as gtx +from gt4py.next import common, fingerprinting + + +class Vertex(gtx.DimensionIndex): ... +class Edge(gtx.DimensionIndex): ... +class E2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +E2V = gtx.FieldOffset(E2VDim.tag, source=Vertex, target=(Edge, E2VDim)) + + +@gtx.field_operator(backend=gtx.gtfn_cpu) +def first_vertex(v: gtx.Field[gtx.Dims[Vertex], gtx.float64]) -> gtx.Field[gtx.Dims[Edge], gtx.float64]: + return v(E2V[0]) + + +def describe(): + dims = (Vertex, E2VDim, common.Staggered[KDim]) + return [(common.dimension_ref(d), fingerprinting.strict_fingerprinter(d)) for d in dims] + + +if __name__ == "__main__": + warnings.filterwarnings("error", message=".*in the calling thread.*") + context = multiprocessing.get_context("spawn") + with concurrent.futures.ProcessPoolExecutor(1, mp_context=context) as pool: + assert pool.submit(describe).result() == describe() + assert pool.submit(common.dimension_ref, Vertex).result() is common.dimension_ref(Vertex) + + e2v = gtx.as_connectivity([Edge, E2VDim], Vertex, np.array([[1, 0], [2, 1]], np.int32)) + out = gtx.zeros({Edge: 2}) + first_vertex(gtx.as_field([Vertex], np.arange(3.0)), out=out, offset_provider={E2VDim.tag: e2v}) + assert out.asnumpy().tolist() == [1.0, 2.0] +""" + + +def test_dimensions_declared_in_a_script_compile_in_a_spawn_worker(tmp_path): + """ + A spawn worker re-imports a script's `__main__` as `__mp_main__`: its dimensions are the same. + + The IR holds refs made in the parent, the connectivity's classes are converted in the worker. + """ + script = tmp_path / "script.py" + script.write_text(_GUARDED_SCRIPT) + result = subprocess.run( + [sys.executable, str(script)], + env=os.environ + | {"GT4PY_BUILD_JOBS_MODE": "process", "GT4PY_BUILD_CACHE_DIR": str(tmp_path / "cache")}, + capture_output=True, + text=True, + timeout=600, + ) + assert result.returncode == 0, result.stderr diff --git a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py index f8323091c4..cc6a9d795d 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py +++ b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py @@ -5,10 +5,10 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import dataclasses import collections import concurrent.futures import contextvars +import dataclasses import gc import traceback import warnings @@ -18,19 +18,26 @@ import pytest from gt4py import eve, next as gtx -from gt4py.next import utils -from gt4py.next import errors, backend, broadcast, common -from gt4py.next.iterator.transforms.collapse_tuple import CollapseTuple -from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py._core import definitions as core_defs -from gt4py.next.otf import arguments, compilation_tasks, compiled_program, runners, workflow -from gt4py.next import config, fingerprinting -from gt4py.next.type_system import type_specifications as ts +from gt4py.next import ( + backend, + broadcast, + common, + config, + errors, + fingerprinting, + neighbor_sum, + utils, +) from gt4py.next.iterator import ir as itir -from gt4py.next.program_processors.runners import gtfn +from gt4py.next.iterator.ir_utils import domain_utils, ir_makers as im +from gt4py.next.iterator.transforms.collapse_tuple import CollapseTuple +from gt4py.next.otf import arguments, compilation_tasks, compiled_program, runners, workflow from gt4py.next.program_processors.codegens.gtfn import gtfn_module -from gt4py.next.iterator.ir_utils import domain_utils -from gt4py.next import neighbor_sum +from gt4py.next.program_processors.runners import gtfn +from gt4py.next.type_system import type_specifications as ts + +from next_tests.toy_connectivity import E2V, V2E, E2VDim, Edge, V2EDim, Vertex def test_static_arg_from_enum(): @@ -69,7 +76,10 @@ def test_sanitize_static_args_wrong_type(): static_arg.validate("foo", ts.ScalarType(kind=ts.ScalarKind.INT32)) -TDim = gtx.Dimension("TDim") +class TDim(gtx.CartesianAxisIndex): ... + + +class T2TDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... @pytest.fixture @@ -255,20 +265,19 @@ def shutdown(self, wait: bool = True) -> None: def test_variants_compile_against_shared_compile_time_connectivities(testee_prog, monkeypatch, xp): runner = _RecordingRunner() monkeypatch.setattr(compiled_program.runners, "get_default_runner", lambda: runner) - LocalDim = gtx.Dimension("Local", kind=gtx.DimensionKind.LOCAL) table = np.array([[0, 1], [1, 0]], dtype=np.int32) - conn = gtx.as_connectivity([TDim, LocalDim], TDim, xp.asarray(table)) - offset_provider = {"T2T": conn} + conn = gtx.as_connectivity([TDim, T2TDim], TDim, xp.asarray(table)) + offset_provider = {T2TDim.tag: conn} testee_prog.compile(cond=[True, False], offset_provider=offset_provider) testee_prog(cond=True, out=gtx.zeros({TDim: 2}, dtype=bool), offset_provider=offset_provider) - first, second = (task.compilable.args.offset_provider["T2T"] for task in runner.tasks) + first, second = (task.compilable.args.offset_provider[T2TDim.tag] for task in runner.tasks) assert first is second assert type(first) is compilation_tasks._CompileTimeConnectivity assert np.array_equal(first.ndarray, table) (call,) = runner.calls - assert call["offset_provider"]["T2T"] is conn + assert call["offset_provider"][T2TDim.tag] is conn _LOADED_FINGERPRINTS: list[str] = [] @@ -295,9 +304,8 @@ def __call__(self, compilable): ids=lambda xp: getattr(xp, "__name__", "cupy"), ) def test_compilable_fingerprint_is_independent_of_runner(testee_prog, monkeypatch, tmp_path, xp): - LocalDim = gtx.Dimension("Local", kind=gtx.DimensionKind.LOCAL) table = np.array([[0, 1], [1, 0]], dtype=np.int32) - offset_provider = {"T2T": gtx.as_connectivity([TDim, LocalDim], TDim, xp.asarray(table))} + offset_provider = {T2TDim.tag: gtx.as_connectivity([TDim, T2TDim], TDim, xp.asarray(table))} all_runners = [ runners.SerialRunner(), runners.ThreadRunner(max_workers=1), @@ -365,9 +373,8 @@ def __call__(self, compilable): def test_persistent_cache_filled_in_process_mode_hits_in_other_modes( testee_prog, monkeypatch, tmp_path, xp ): - LocalDim = gtx.Dimension("Local", kind=gtx.DimensionKind.LOCAL) table = np.asfortranarray(np.array([[0, 1], [1, 0]], dtype=np.int32)) - offset_provider = {"T2T": gtx.as_connectivity([TDim, LocalDim], TDim, xp.asarray(table))} + offset_provider = {T2TDim.tag: gtx.as_connectivity([TDim, T2TDim], TDim, xp.asarray(table))} all_runners = [ runners.ProcessRunner(max_workers=1, shared_session_cache_dir=str(tmp_path / "session")), runners.ThreadRunner(max_workers=1), @@ -421,18 +428,12 @@ def __call__(self, compilable): ids=lambda xp: getattr(xp, "__name__", "cupy"), ) def test_translation_against_compile_time_view_matches_runtime_tables(monkeypatch, xp): - V = gtx.Dimension("V") - E = gtx.Dimension("E") - V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) - E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) - V2E = gtx.FieldOffset("V2E", source=E, target=(V, V2EDim)) - E2V = gtx.FieldOffset("E2V", source=V, target=(E, E2VDim)) rng = np.random.default_rng(0) e2v = np.asfortranarray(rng.integers(0, 50, size=(80, 2)).astype(np.int32)) v2e = np.asfortranarray(rng.integers(0, 80, size=(50, 4)).astype(np.int32)) offset_provider = { - "V2E": gtx.as_connectivity([V, V2EDim], E, xp.asarray(v2e)), - "E2V": gtx.as_connectivity([E, E2VDim], V, xp.asarray(e2v)), + V2EDim.tag: gtx.as_connectivity([Vertex, V2EDim], Edge, xp.asarray(v2e)), + E2VDim.tag: gtx.as_connectivity([Edge, E2VDim], Vertex, xp.asarray(e2v)), } static_translations = [] translate_statically = domain_utils._unstructured_translate_range_statically @@ -458,24 +459,24 @@ def counting_translate_statically(*args, **kwargs): ) @gtx.field_operator - def fop(v: gtx.Field[[V], gtx.int32]) -> gtx.Field[[V], gtx.int32]: + def fop(v: gtx.Field[[Vertex], gtx.int32]) -> gtx.Field[[Vertex], gtx.int32]: e = neighbor_sum(v(E2V), axis=E2VDim) return neighbor_sum(e(V2E), axis=V2EDim) @gtx.program(backend=translating_backend, static_domains=True) - def prog(v: gtx.Field[[V], gtx.int32], out: gtx.Field[[V], gtx.int32]): - fop(v, out=out, domain={V: (3, 40)}) + def prog(v: gtx.Field[[Vertex], gtx.int32], out: gtx.Field[[Vertex], gtx.int32]): + fop(v, out=out, domain={Vertex: (3, 40)}) prog( - gtx.zeros({V: 50}, dtype=np.int32), - gtx.zeros({V: 50}, dtype=np.int32), + gtx.zeros({Vertex: 50}, dtype=np.int32), + gtx.zeros({Vertex: 50}, dtype=np.int32), offset_provider=offset_provider, ) view_source, runtime_source = _TRANSLATED_SOURCES assert view_source == runtime_source assert "_CompileTimeConnectivity" in static_translations - assert type(offset_provider["V2E"]).__name__ in static_translations + assert type(offset_provider[V2EDim.tag]).__name__ in static_translations def _formatted_traceback(error: BaseException) -> str: diff --git a/tests/next_tests/unit_tests/otf_tests/test_roundtrip_redefinition.py b/tests/next_tests/unit_tests/otf_tests/test_roundtrip_redefinition.py new file mode 100644 index 0000000000..f2e2b2c285 --- /dev/null +++ b/tests/next_tests/unit_tests/otf_tests/test_roundtrip_redefinition.py @@ -0,0 +1,67 @@ +# 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 + +""" +The roundtrip backend must run on the classes of the arguments after a notebook-style redefinition. + +With a stale class, a second run after re-executing the defining module fails with a `KeyError` on +the column axis. +""" + +import importlib +import sys +import textwrap + +import numpy as np + +import gt4py.next as gtx +from gt4py.next.program_processors.runners import roundtrip + + +_SOURCE = textwrap.dedent( + """ + import gt4py.next as gtx + + + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + + @gtx.scan_operator(axis=KDim, forward=True, init=0.0) + def cumsum(state: float, x: float) -> float: + return state + x + + + @gtx.program + def prog(x: gtx.Field[gtx.Dims[KDim], float], out: gtx.Field[gtx.Dims[KDim], float]): + cumsum(x, out=out) + """ +) + + +def _run(kdim, program) -> np.ndarray: + x = gtx.as_field([kdim], np.ones(4)) + out = gtx.as_field([kdim], np.zeros(4)) + program(x, out, offset_provider={}) + return out.asnumpy() + + +def test_rerun_module_with_roundtrip(tmp_path, monkeypatch): + (tmp_path / "nbmod_spike_scan.py").write_text(_SOURCE) + monkeypatch.syspath_prepend(str(tmp_path)) + monkeypatch.delitem(sys.modules, "nbmod_spike_scan", raising=False) + module = importlib.import_module("nbmod_spike_scan") + first_kdim, first_prog = module.KDim, module.prog.with_backend(roundtrip.default) + assert np.allclose(_run(first_kdim, first_prog), [1, 2, 3, 4]) + + module = importlib.reload(module) # the notebook re-run: a new `KDim` class, same ref + assert module.KDim is not first_kdim + second_prog = module.prog.with_backend(roundtrip.default) + assert np.allclose(_run(module.KDim, second_prog), [1, 2, 3, 4]) + # the program loaded in the first run is still alive and still works on its own classes: + # loading the second one must not have re-bound the first one's (cached) module + assert np.allclose(_run(first_kdim, first_prog), [1, 2, 3, 4]) diff --git a/tests/next_tests/unit_tests/otf_tests/test_runners.py b/tests/next_tests/unit_tests/otf_tests/test_runners.py index b40313fa21..4d4f0be8ea 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_runners.py +++ b/tests/next_tests/unit_tests/otf_tests/test_runners.py @@ -27,6 +27,24 @@ from next_tests.fixtures import compilation as fixtures_compilation +class Vertex(gtx.DimensionIndex): ... + + +class Edge(gtx.DimensionIndex): ... + + +class V2EDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +class V2VDim(gtx.DimensionIndex, kind=gtx.DimensionKind.LOCAL): ... + + +class Cell(gtx.DimensionIndex): ... + + +class IDim(gtx.CartesianAxisIndex): ... + + @pytest.fixture def process_runner(tmp_path): runner = runners.ProcessRunner(max_workers=1, shared_session_cache_dir=str(tmp_path)) @@ -156,9 +174,6 @@ def compile(self, program, compile_time_args): def _v2e_tables(xp): - Vertex = gtx.Dimension("Vertex") - Edge = gtx.Dimension("Edge") - V2EDim = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) table = np.array([[0, 1], [1, 2], [2, 0]], dtype=np.int32) c_order = gtx.as_connectivity([Vertex, V2EDim], Edge, xp.asarray(table)) f_order = type(c_order).from_array( @@ -219,7 +234,7 @@ def test_compile_time_connectivity_fingerprint_depends_only_on_content(): conn.domain, Vertex, np.array([[0, 1], [1, 2], [2, 0]], dtype=np.int32) ), "domain": gtx.as_connectivity( - [gtx.Dimension("Cell"), conn.domain.dims[1]], + [Cell, conn.domain.dims[1]], Edge, np.array([[0, 1], [1, 2], [2, 0]], dtype=np.int32), ), @@ -239,8 +254,6 @@ def fingerprint(c): def test_compile_time_connectivity_pickles_as_file_reference(): - Vertex = gtx.Dimension("Vertex") - V2VDim = gtx.Dimension("V2V", kind=gtx.DimensionKind.LOCAL) table = np.arange(4000, dtype=np.int32).reshape(1000, 4) % 1000 table[::7, 3] = -1 conn = compilation_tasks.compile_time_offset_provider( @@ -277,8 +290,6 @@ def test_compile_time_connectivity_copies_are_valid(): def test_compile_time_table_files_are_content_addressed_and_kept(tmp_path, monkeypatch): monkeypatch.setattr(compilation_tasks._cache, "_session_cache_dir_path", tmp_path) - Vertex = gtx.Dimension("Vertex") - V2VDim = gtx.Dimension("V2V", kind=gtx.DimensionKind.LOCAL) table = np.array([[0, 1], [1, 0]], dtype=np.int32) sources = [gtx.as_connectivity([Vertex, V2VDim], Vertex, table) for _ in range(8)] @@ -336,6 +347,31 @@ def test_make_compilation_task_compiles_against_compile_time_view(): assert compiled_against["Vertex"] is offset_provider["Vertex"] +def test_offloaded_task_ships_cartesian_connectivities_as_they_are(process_runner): + # an affine connectivity has no table to write (its `asnumpy` raises): it is not converted + cartesian = common.CartesianConnectivity(IDim, 1) + compile_time_args = dataclasses.replace( + arguments.CompileTimeArgs.empty(), offset_provider={"Ioff": cartesian, "I": IDim} + ) + backend = next_backend.Backend( + name="test_backend", + executor=_RecursingExecutor(depth=0), + allocator=None, + transforms=lambda inp: inp, + ) + task = compilation_tasks.make_compilation_task( + backend, definition_stage=None, compile_time_args=compile_time_args + ) + + shipped = task.compilable + assert shipped.args.offset_provider["Ioff"] is cartesian + assert shipped.args.offset_provider["I"] is IDim + restored = pickle.loads(pickle.dumps(shipped)).args.offset_provider["Ioff"] + assert (restored.domain_dim, restored.codomain, restored.offset) == (IDim, IDim, 1) + future = process_runner.submit(task) # offloaded to a worker, not compiled in the caller + assert callable(future.result(timeout=120).load()) + + def test_compile_time_connectivity_registry_prunes_on_gc(): _, offset_provider = _v2e_tables(np) conn = offset_provider.pop("V2EF") @@ -609,3 +645,38 @@ def test_default_runner_is_serial_in_worker_process(): runners.reset_default_runner() assert isinstance(runners.get_default_runner(), runners.SerialRunner) runners.reset_default_runner() + + +class TestInteractiveMainReference: + """ + A class declared in an interactive `__main__` pickles in the parent but not in a worker. + + Dimensions are classes identified by their qualified name (ADR 0030), so a notebook that + declares one would otherwise break the default process-pool compilation. + """ + + @staticmethod + def _main_class(name: str) -> type: + cls = type(name, (), {}) + cls.__module__ = "__main__" + return cls + + def test_found_when_main_is_interactive(self, monkeypatch): + interactive_main = type(sys)("__main__") # a notebook / REPL `__main__`: no `__file__` + cls = self._main_class("NotebookDim") + interactive_main.NotebookDim = cls + monkeypatch.setitem(sys.modules, "__main__", interactive_main) + assert runners._interactive_main_reference({"nested": [cls]}) == "NotebookDim" + + def test_ignored_when_main_is_a_script(self, monkeypatch): + # a spawn worker re-imports a script's `__main__`, so its classes do resolve there + script_main = type(sys)("__main__") + script_main.__file__ = "/some/script.py" + cls = self._main_class("ScriptDim") + script_main.ScriptDim = cls + monkeypatch.setitem(sys.modules, "__main__", script_main) + assert runners._interactive_main_reference(cls) is None + + def test_ignored_for_classes_from_ordinary_modules(self, monkeypatch): + monkeypatch.setitem(sys.modules, "__main__", type(sys)("__main__")) + assert runners._interactive_main_reference([dataclasses.dataclass, int]) is None diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py index 4c761ec4b7..5361efc847 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py @@ -8,7 +8,8 @@ import copy -from gt4py._core import filecache +from gt4py._core import definitions as gtx_definitions, filecache +import numpy as np import pytest import gt4py.next as gtx @@ -33,10 +34,13 @@ ) +class IDim(gtx.CartesianAxisIndex): ... + + def _make_cartesian_program() -> itir.Program: """Point-wise operation on a 1D cartesian field.""" float_type = ts.ScalarType(kind=ts.ScalarKind.FLOAT32) - param_types = [ts.FieldType(dims=[gtx.Dimension("I")], dtype=float_type), float_type] + param_types = [ts.FieldType(dims=[IDim], dtype=float_type), float_type] domain = itir.FunCall( fun=itir.SymRef(id="cartesian_domain"), @@ -44,7 +48,7 @@ def _make_cartesian_program() -> itir.Program: itir.FunCall( fun=itir.SymRef(id="named_range"), args=[ - itir.AxisLiteral(value="I"), + itir.AxisLiteral(dim=IDim), im.literal("0", builtins.INTEGER_INDEX_BUILTIN), im.literal("10", builtins.INTEGER_INDEX_BUILTIN), ], @@ -187,3 +191,23 @@ def test_gtfn_file_cache(): bare_gtfn_translation_step(compilable_program) == cached_gtfn_translation_step.cache[cache_key] ) + + +def test_connectivity_parameters_differing_in_case_are_distinct(): + vertex = common.DimensionRef("mesh", "Vertex", "horizontal") + edge = common.DimensionRef("mesh", "Edge", "horizontal") + offset_provider_type = { + f"{module}:V2EDim": common.NeighborConnectivityType( + domain=(vertex, common.DimensionRef(module, "V2EDim", "local")), + codomain=edge, + skip_value=None, + dtype=gtx_definitions.dtype(np.int32), + max_neighbors=2, + ) + for module in ("meshA", "mesha") + } + + translation = gtfn_module.GTFNTranslationStep(device_type=gtx_definitions.DeviceType.CPU) + parameters, _ = translation._process_connectivity_args(offset_provider_type) + + assert len({parameter.name for parameter in parameters}) == 2 diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py index c533629c74..14351ba1d9 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py @@ -16,9 +16,13 @@ from gt4py.next.type_system import type_specifications as ts -Cell = gtx.Dimension("Cell") -Vertex = gtx.Dimension("Vertex") -KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) +class Cell(gtx.DimensionIndex): ... + + +class Vertex(gtx.DimensionIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... def test_funcall_to_op(): @@ -73,7 +77,7 @@ def test_unstructured_param_dimension_tag(dim, alias): ) result = it2gtfn.GTFN_lowering.apply(testee, offset_provider_type={}) aliases = {str(tag.name.id): tag.alias for tag in result.offset_definitions} - assert aliases[dim.value] == alias + assert aliases[common.codegen_name(dim.tag)] == alias def _scan_execution(axis: str, output: str) -> gtfn_ir.ScanExecution: diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace.py index d381e0ff51..faea3c7764 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace.py @@ -22,7 +22,7 @@ from gt4py.next.ffront.fbuiltins import where from next_tests.integration_tests import cases -from next_tests.integration_tests.cases import E2V +from next_tests.integration_tests.cases import E2VDim, E2V from next_tests.integration_tests.cases_utils import ( Edge, IDim, @@ -208,7 +208,7 @@ def verify_testee(): def test_dace_fastcall_with_connectivity(unstructured_case, monkeypatch): """Test reuse of SDFG arguments between program calls by means of SDFG fastcall API.""" - connectivity_E2V = unstructured_case.offset_provider["E2V"].asnumpy() + connectivity_E2V = unstructured_case.offset_provider[E2VDim.tag].asnumpy() @gtx.field_operator def testee(a: cases.VField) -> cases.EField: diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py index 2eb9d87172..b9cd3c3e3f 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py @@ -9,22 +9,21 @@ """Test the bindings stage of the dace backend workflow.""" import functools -import dace + import numpy as np import pytest -from gt4py.eve import formatting from gt4py import next as gtx -from gt4py.next import common as gtx_common, int32 +from gt4py.eve import formatting +from gt4py.next import common as gtx_common, int32, neighbor_sum from gt4py.next.otf import artifacts from gt4py.next.program_processors.runners import dace as dace_runner from gt4py.next.program_processors.runners.dace import workflow as dace_workflow -from gt4py.next import neighbor_sum -from next_tests.integration_tests.cases import E2V, E2VDim, V2E, V2EDim -from next_tests.integration_tests import cases -from next_tests.integration_tests import cases_utils -from next_tests.unit_tests.test_common import IDim, JDim, KDim +from next_tests.integration_tests import cases, cases_utils + +# the dimensions the `cartesian_case` fixture is sized on +from next_tests.integration_tests.cases import E2V, V2E, E2VDim, IDim, JDim, KDim, V2EDim _bind_func_name = "update_sdfg_args" @@ -154,6 +153,12 @@ def {_bind_func_name}(device, sdfg_argtypes, args, sdfg_call_args, offset_provid ) +# The generated binding names each table variable after the *mangled* offset key -- it has to be +# a valid identifier -- but looks the table up in the offset provider by the real, qualified tag. +_E2V_TABLE = f"table_{gtx_common.codegen_name(E2VDim.tag)}" +_V2E_TABLE = f"table_{gtx_common.codegen_name(V2EDim.tag)}" + + def _binding_source_unstructured(use_metrics: bool) -> str: metrics_arg_index = 2 idx = [0, 4, 5, 1, 6, 7, 8, 2, 10, 9, 3, 12, 11] @@ -174,14 +179,14 @@ def {_bind_func_name}(device, sdfg_argtypes, args, sdfg_call_args, offset_provid sdfg_call_args[{idx[4]}] = ctypes.c_int(args_1.domain.ranges[0].start) sdfg_call_args[{idx[5]}] = ctypes.c_int(args_1.domain.ranges[0].stop) sdfg_call_args[{idx[6]}] = ctypes.c_int(args_1.__gt_buffer_info__.elem_strides[0]) - table_E2V = offset_provider["E2V"] - sdfg_call_args[{idx[7]}].value = table_E2V.__gt_buffer_info__.data_ptr - sdfg_call_args[{idx[8]}] = ctypes.c_int(table_E2V.__gt_buffer_info__.elem_strides[0]) - sdfg_call_args[{idx[9]}] = ctypes.c_int(table_E2V.__gt_buffer_info__.elem_strides[1]) - table_V2E = offset_provider["V2E"] - sdfg_call_args[{idx[10]}].value = table_V2E.__gt_buffer_info__.data_ptr - sdfg_call_args[{idx[11]}] = ctypes.c_int(table_V2E.__gt_buffer_info__.elem_strides[0]) - sdfg_call_args[{idx[12]}] = ctypes.c_int(table_V2E.__gt_buffer_info__.elem_strides[1]) + {_E2V_TABLE} = offset_provider["{E2VDim.tag}"] + sdfg_call_args[{idx[7]}].value = {_E2V_TABLE}.__gt_buffer_info__.data_ptr + sdfg_call_args[{idx[8]}] = ctypes.c_int({_E2V_TABLE}.__gt_buffer_info__.elem_strides[0]) + sdfg_call_args[{idx[9]}] = ctypes.c_int({_E2V_TABLE}.__gt_buffer_info__.elem_strides[1]) + {_V2E_TABLE} = offset_provider["{V2EDim.tag}"] + sdfg_call_args[{idx[10]}].value = {_V2E_TABLE}.__gt_buffer_info__.data_ptr + sdfg_call_args[{idx[11]}] = ctypes.c_int({_V2E_TABLE}.__gt_buffer_info__.elem_strides[0]) + sdfg_call_args[{idx[12]}] = ctypes.c_int({_V2E_TABLE}.__gt_buffer_info__.elem_strides[1]) """ ) @@ -204,14 +209,14 @@ def {_bind_func_name}(device, sdfg_argtypes, args, sdfg_call_args, offset_provid sdfg_call_args[{idx[2]}].value = args_1.__gt_buffer_info__.data_ptr sdfg_call_args[{idx[3]}] = ctypes.c_int(args_1.domain.ranges[0].stop) sdfg_call_args[{idx[4]}] = ctypes.c_int(args_1.__gt_buffer_info__.elem_strides[0]) - table_E2V = offset_provider["E2V"] - sdfg_call_args[{idx[5]}].value = table_E2V.__gt_buffer_info__.data_ptr - sdfg_call_args[{idx[6]}] = ctypes.c_int(table_E2V.__gt_buffer_info__.elem_strides[0]) - sdfg_call_args[{idx[7]}] = ctypes.c_int(table_E2V.__gt_buffer_info__.elem_strides[1]) - table_V2E = offset_provider["V2E"] - sdfg_call_args[{idx[8]}].value = table_V2E.__gt_buffer_info__.data_ptr - sdfg_call_args[{idx[9]}] = ctypes.c_int(table_V2E.__gt_buffer_info__.elem_strides[0]) - sdfg_call_args[{idx[10]}] = ctypes.c_int(table_V2E.__gt_buffer_info__.elem_strides[1]) + {_E2V_TABLE} = offset_provider["{E2VDim.tag}"] + sdfg_call_args[{idx[5]}].value = {_E2V_TABLE}.__gt_buffer_info__.data_ptr + sdfg_call_args[{idx[6]}] = ctypes.c_int({_E2V_TABLE}.__gt_buffer_info__.elem_strides[0]) + sdfg_call_args[{idx[7]}] = ctypes.c_int({_E2V_TABLE}.__gt_buffer_info__.elem_strides[1]) + {_V2E_TABLE} = offset_provider["{V2EDim.tag}"] + sdfg_call_args[{idx[8]}].value = {_V2E_TABLE}.__gt_buffer_info__.data_ptr + sdfg_call_args[{idx[9]}] = ctypes.c_int({_V2E_TABLE}.__gt_buffer_info__.elem_strides[0]) + sdfg_call_args[{idx[10]}] = ctypes.c_int({_V2E_TABLE}.__gt_buffer_info__.elem_strides[1]) """ ) @@ -238,7 +243,11 @@ def mocked_compile_call( for line in inp.binding_source.source_code.splitlines() if not line.lstrip().startswith("assert") ) - assert formatting.format_python_source(binding_source_pruned) == binding_source_ref + # both sides go through the same formatter, so the comparison does not depend on where + # the long (mangled) connectivity names happen to wrap + assert formatting.format_python_source( + binding_source_pruned + ) == formatting.format_python_source(binding_source_ref) return _dace_compile_call(self, inp) @@ -376,8 +385,8 @@ def testee(a: cases.VField, b: cases.VField): b = cases.allocate(test_case, testee, "b")() ref = np.sum( - np.sum(a.asnumpy()[offset_provider["E2V"].asnumpy()], axis=1, initial=0)[ - offset_provider["V2E"].asnumpy() + np.sum(a.asnumpy()[offset_provider[E2VDim.tag].asnumpy()], axis=1, initial=0)[ + offset_provider[V2EDim.tag].asnumpy() ], axis=1, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_domain.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_domain.py index 0a432cd65c..c9f78e0ed9 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_domain.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_domain.py @@ -32,12 +32,12 @@ def test_symbolic_domain(): assert gtx_dace_domain.get_field_domain(domain) == [ gtx_dace_domain.FieldopDomainRange( - Vertex, + gtx_common.dimension_ref(Vertex), dace.symbolic.SymExpr(gtx_dace_args.range_start_symbol("arg", Vertex)), dace.symbolic.SymExpr(gtx_dace_args.range_stop_symbol("arg", Vertex)), ), gtx_dace_domain.FieldopDomainRange( - KDim, + gtx_common.dimension_ref(KDim), dace.symbolic.SymExpr(gtx_dace_args.range_start_symbol("arg", KDim)), dace.symbolic.SymExpr(gtx_dace_args.range_stop_symbol("arg", KDim)), ), diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py index 078a5a2620..4ca8105a68 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py @@ -8,23 +8,24 @@ """Test the translation stage of the dace backend workflow.""" -import dace -import pytest - import re import uuid from typing import Callable from unittest import mock +import dace +import pytest +from dace import nodes as dace_nodes + from gt4py._core import definitions as core_defs from gt4py.next import common as gtx_common, fingerprinting from gt4py.next.iterator import ir as itir from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.otf import arguments as otf_arguments, workflow as otf_workflow -from gt4py.next.program_processors.runners.dace import lowering as gtx_dace_lowering +from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args from gt4py.next.program_processors.runners.dace.workflow import ( - translation as dace_wf_translation, common as dace_wf_common, + translation as dace_wf_translation, ) from gt4py.next.type_system import type_specifications as ts @@ -34,12 +35,11 @@ IDim, JDim, KDim, + V2EDim, Vertex, skip_value_mesh, ) -from dace import nodes as dace_nodes - FLOAT_TYPE = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) IFTYPE = ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE) @@ -131,16 +131,16 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): if has_unit_stride: # The vertical dimension stride symbols must not be set to 1. expected |= { - "__x_Edge_stride": 1, - "__y_Vertex_stride": 1, - "__gt_conn_V2E_source_stride": 1, + gtx_dace_args.field_stride_symbol("x", Edge).name: 1, + gtx_dace_args.field_stride_symbol("y", Vertex).name: 1, + f"__{gtx_dace_args.connectivity_identifier(V2EDim.tag)}_source_stride": 1, } if disable_field_origin: expected |= { - "__x_Edge_range_0": 0, - "__x_KDim_range_0": 0, - "__y_Vertex_range_0": 0, - "__y_KDim_range_0": 0, + gtx_dace_args.range_start_symbol("x", Edge).name: 0, + gtx_dace_args.range_start_symbol("x", KDim).name: 0, + gtx_dace_args.range_start_symbol("y", Vertex).name: 0, + gtx_dace_args.range_start_symbol("y", KDim).name: 0, } assert constant_symbols == expected @@ -173,17 +173,18 @@ def test_translation_grid_type(grid_type): if grid_type == gtx_common.GridType.UNSTRUCTURED: ir = _make_unstructured_program("translation_grid_type_unstructured") offset_provider = skip_value_mesh(None).offset_provider + v2e_conn = gtx_dace_args.connectivity_identifier(V2EDim.tag) expected_strides = { - "x": ("1", "__x_KDim_stride"), - "y": ("1", "__y_KDim_stride"), - "gt_conn_V2E": ("1", "__gt_conn_V2E_neighbor_stride"), + "x": ("1", gtx_dace_args.field_stride_symbol("x", KDim).name), + "y": ("1", gtx_dace_args.field_stride_symbol("y", KDim).name), + v2e_conn: ("1", f"__{v2e_conn}_neighbor_stride"), } else: ir = _make_cartesian_program("translation_grid_type_cartesian") offset_provider = {} expected_strides = { - "x": ("__x_IDim_stride", "__x_JDim_stride"), - "y": ("__y_IDim_stride", "__y_JDim_stride"), + name: tuple(gtx_dace_args.field_stride_symbol(name, dim).name for dim in (IDim, JDim)) + for name in ("x", "y") } compilable_program = otf_workflow.ConcreteArtifact( @@ -267,14 +268,18 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) field_names = ["x_0", "y_0", "y_1_0", "y_1_1"] expected = {} if has_unit_stride: - expected |= {f"__{name}_Vertex_stride": 1 for name in field_names} + expected |= { + gtx_dace_args.field_stride_symbol(name, Vertex).name: 1 for name in field_names + } if disable_field_origin: - expected |= {f"__{name}_Vertex_range_0": 0 for name in field_names} + expected |= {gtx_dace_args.range_start_symbol(name, Vertex).name: 0 for name in field_names} assert constant_symbols == expected # check that the symbols have been replaced in the translated SDFG for name in field_names: - expected_stride = "1" if has_unit_stride else f"__{name}_Vertex_stride" + expected_stride = ( + "1" if has_unit_stride else gtx_dace_args.field_stride_symbol(name, Vertex).name + ) assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py index 28c50dedc6..f28f85f1d7 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py @@ -27,6 +27,9 @@ from gt4py.next.type_system import type_specifications as ts from next_tests.integration_tests.cases_utils import ( + E2VDim, + C2VDim, + C2EDim, Cell, Edge, IDim, @@ -40,6 +43,7 @@ ) from gt4py.next.program_processors.runners.dace import lowering as dace_lowering +from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args @pytest.fixture @@ -72,48 +76,104 @@ def allow_view_arguments(): SKIP_VALUE_MESH: MeshDescriptor = skip_value_mesh(None) SIZE_TYPE = ts.ScalarType(ts.ScalarKind.INT32) FSYMBOLS = dict( - __w_IDim_range_0=0, - __w_IDim_range_1=N, - __w_IDim_stride=1, - __x_IDim_range_0=0, - __x_IDim_range_1=N, - __x_IDim_stride=1, - __y_IDim_range_0=0, - __y_IDim_range_1=N, - __y_IDim_stride=1, - __z_IDim_range_0=0, - __z_IDim_range_1=N, - __z_IDim_stride=1, + **{gtx_dace_args.range_start_symbol("w", IDim).name: 0}, + **{gtx_dace_args.range_stop_symbol("w", IDim).name: N}, + **{gtx_dace_args.field_stride_symbol("w", IDim).name: 1}, + **{gtx_dace_args.range_start_symbol("x", IDim).name: 0}, + **{gtx_dace_args.range_stop_symbol("x", IDim).name: N}, + **{gtx_dace_args.field_stride_symbol("x", IDim).name: 1}, + **{gtx_dace_args.range_start_symbol("y", IDim).name: 0}, + **{gtx_dace_args.range_stop_symbol("y", IDim).name: N}, + **{gtx_dace_args.field_stride_symbol("y", IDim).name: 1}, + **{gtx_dace_args.range_start_symbol("z", IDim).name: 0}, + **{gtx_dace_args.range_stop_symbol("z", IDim).name: N}, + **{gtx_dace_args.field_stride_symbol("z", IDim).name: 1}, ) def make_mesh_symbols(mesh: MeshDescriptor): - c2e_ndarray = mesh.offset_provider["C2E"].ndarray - c2v_ndarray = mesh.offset_provider["C2V"].ndarray - e2v_ndarray = mesh.offset_provider["E2V"].ndarray - v2e_ndarray = mesh.offset_provider["V2E"].ndarray + c2e_ndarray = mesh.offset_provider[C2EDim.tag].ndarray + c2v_ndarray = mesh.offset_provider[C2VDim.tag].ndarray + e2v_ndarray = mesh.offset_provider[E2VDim.tag].ndarray + v2e_ndarray = mesh.offset_provider[V2EDim.tag].ndarray return dict( - __cells_Cell_range_0=0, - __cells_Cell_range_1=mesh.num_cells, - __cells_Cell_stride=1, - __edges_Edge_range_0=0, - __edges_Edge_range_1=mesh.num_edges, - __edges_Edge_stride=1, - __vertices_Vertex_range_0=0, - __vertices_Vertex_range_1=mesh.num_vertices, - __vertices_Vertex_stride=1, - __gt_conn_C2E_source_size=c2e_ndarray.shape[0], - __gt_conn_C2E_source_stride=c2e_ndarray.strides[0] // c2e_ndarray.itemsize, - __gt_conn_C2E_neighbor_stride=c2e_ndarray.strides[1] // c2e_ndarray.itemsize, - __gt_conn_C2V_source_size=c2v_ndarray.shape[0], - __gt_conn_C2V_source_stride=c2v_ndarray.strides[0] // c2v_ndarray.itemsize, - __gt_conn_C2V_neighbor_stride=c2v_ndarray.strides[1] // c2v_ndarray.itemsize, - __gt_conn_E2V_source_size=e2v_ndarray.shape[0], - __gt_conn_E2V_source_stride=e2v_ndarray.strides[0] // e2v_ndarray.itemsize, - __gt_conn_E2V_neighbor_stride=e2v_ndarray.strides[1] // e2v_ndarray.itemsize, - __gt_conn_V2E_source_size=v2e_ndarray.shape[0], - __gt_conn_V2E_source_stride=v2e_ndarray.strides[0] // v2e_ndarray.itemsize, - __gt_conn_V2E_neighbor_stride=v2e_ndarray.strides[1] // v2e_ndarray.itemsize, + **{gtx_dace_args.range_start_symbol("cells", Cell).name: 0}, + **{gtx_dace_args.range_stop_symbol("cells", Cell).name: mesh.num_cells}, + **{gtx_dace_args.field_stride_symbol("cells", Cell).name: 1}, + **{gtx_dace_args.range_start_symbol("edges", Edge).name: 0}, + **{gtx_dace_args.range_stop_symbol("edges", Edge).name: mesh.num_edges}, + **{gtx_dace_args.field_stride_symbol("edges", Edge).name: 1}, + **{gtx_dace_args.range_start_symbol("vertices", Vertex).name: 0}, + **{gtx_dace_args.range_stop_symbol("vertices", Vertex).name: mesh.num_vertices}, + **{gtx_dace_args.field_stride_symbol("vertices", Vertex).name: 1}, + **{ + f"__{gtx_dace_args.connectivity_identifier(C2EDim.tag)}_source_size": c2e_ndarray.shape[ + 0 + ] + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(C2EDim.tag)}_source_stride": c2e_ndarray.strides[ + 0 + ] + // c2e_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(C2EDim.tag)}_neighbor_stride": c2e_ndarray.strides[ + 1 + ] + // c2e_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(C2VDim.tag)}_source_size": c2v_ndarray.shape[ + 0 + ] + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(C2VDim.tag)}_source_stride": c2v_ndarray.strides[ + 0 + ] + // c2v_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(C2VDim.tag)}_neighbor_stride": c2v_ndarray.strides[ + 1 + ] + // c2v_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(E2VDim.tag)}_source_size": e2v_ndarray.shape[ + 0 + ] + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(E2VDim.tag)}_source_stride": e2v_ndarray.strides[ + 0 + ] + // e2v_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(E2VDim.tag)}_neighbor_stride": e2v_ndarray.strides[ + 1 + ] + // e2v_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(V2EDim.tag)}_source_size": v2e_ndarray.shape[ + 0 + ] + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(V2EDim.tag)}_source_stride": v2e_ndarray.strides[ + 0 + ] + // v2e_ndarray.itemsize + }, + **{ + f"__{gtx_dace_args.connectivity_identifier(V2EDim.tag)}_neighbor_stride": v2e_ndarray.strides[ + 1 + ] + // v2e_ndarray.itemsize + }, ) @@ -147,6 +207,7 @@ def apply_margin_on_field_domain( to the range start, the second to be substracted from the range end. """ domain = domain_utils.SymbolicDomain.from_expr(node) + dim = gtx_common.dimension_ref(dim) domain.ranges[dim] = domain_utils.SymbolicRange( im.plus(domain.ranges[dim].start, margin[0]), im.minus(domain.ranges[dim].stop, margin[1]) ) @@ -308,15 +369,15 @@ def test_gtir_tuple_args(): x_fields = (a, a, b) tuple_symbols = { - "__x_0_IDim_range_0": 0, - "__x_0_IDim_range_1": N, - "__x_0_IDim_stride": 1, - "__x_1_0_IDim_range_0": 0, - "__x_1_0_IDim_range_1": N, - "__x_1_0_IDim_stride": 1, - "__x_1_1_IDim_range_0": 0, - "__x_1_1_IDim_range_1": N, - "__x_1_1_IDim_stride": 1, + gtx_dace_args.range_start_symbol("x_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("x_1_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_1_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_1_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("x_1_1", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_1_1", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_1_1", IDim).name: 1, } sdfg(*x_fields, c, **FSYMBOLS, **tuple_symbols) @@ -493,15 +554,15 @@ def test_gtir_tuple_return(): z_fields = (np.empty_like(a), np.empty_like(a), np.empty_like(a)) tuple_symbols = { - "__z_0_0_IDim_range_0": 0, - "__z_0_0_IDim_range_1": N, - "__z_0_0_IDim_stride": 1, - "__z_0_1_IDim_range_0": 0, - "__z_0_1_IDim_range_1": N, - "__z_0_1_IDim_stride": 1, - "__z_1_IDim_range_0": 0, - "__z_1_IDim_range_1": N, - "__z_1_IDim_stride": 1, + gtx_dace_args.range_start_symbol("z_0_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_0_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_0_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("z_0_1", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_0_1", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_0_1", IDim).name: 1, + gtx_dace_args.range_start_symbol("z_1", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_1", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_1", IDim).name: 1, } sdfg(a, b, *z_fields, **FSYMBOLS, **tuple_symbols) @@ -755,12 +816,12 @@ def test_gtir_cond_with_tuple_return(): sdfg = build_dace_sdfg(testee, CARTESIAN_OFFSETS) tuple_symbols = { - "__z_0_IDim_range_0": 0, - "__z_0_IDim_range_1": N, - "__z_0_IDim_stride": 1, - "__z_1_IDim_range_0": 0, - "__z_1_IDim_range_1": N, - "__z_1_IDim_stride": 1, + gtx_dace_args.range_start_symbol("z_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("z_1", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_1", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_1", IDim).name: 1, } for s in [False, True]: @@ -891,9 +952,9 @@ def test_gtir_cartesian_shift_left(): sdfg = build_dace_sdfg(testee, CARTESIAN_OFFSETS) symbols = FSYMBOLS | { - "__x_offset_IDim_range_0": 0, - "__x_offset_IDim_range_1": N, - "__x_offset_IDim_stride": 1, + gtx_dace_args.range_start_symbol("x_offset", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_offset", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_offset", IDim).name: 1, } sdfg(a, a_offset, b, **symbols) @@ -982,9 +1043,9 @@ def test_gtir_cartesian_shift_right(): sdfg = build_dace_sdfg(testee, CARTESIAN_OFFSETS) symbols = FSYMBOLS | { - "__x_offset_IDim_range_0": 0, - "__x_offset_IDim_range_1": N, - "__x_offset_IDim_stride": 1, + gtx_dace_args.range_start_symbol("x_offset", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_offset", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_offset", IDim).name: 1, } sdfg(a, a_offset, b, **symbols) @@ -998,15 +1059,17 @@ def test_gtir_connectivity_shift(): # apply shift 2 times along different dimensions stencil1_inlined = im.as_fieldop( im.lambda_("it")( - im.deref(im.shift("C2E", C2E_neighbor_idx)(im.shift("E2V", E2V_neighbor_idx)("it"))) + im.deref( + im.shift(C2EDim.tag, C2E_neighbor_idx)(im.shift(E2VDim.tag, E2V_neighbor_idx)("it")) + ) ) )("ev_field") # fieldview flavor of the same stncil: create an intermediate temporary field stencil1_fieldview = im.as_fieldop( - im.lambda_("it")(im.deref(im.shift("E2V", E2V_neighbor_idx)("it"))) + im.lambda_("it")(im.deref(im.shift(E2VDim.tag, E2V_neighbor_idx)("it"))) )( - im.as_fieldop(im.lambda_("it")(im.deref(im.shift("C2E", C2E_neighbor_idx)("it"))))( + im.as_fieldop(im.lambda_("it")(im.deref(im.shift(C2EDim.tag, C2E_neighbor_idx)("it"))))( "ev_field" ) ) @@ -1017,9 +1080,9 @@ def test_gtir_connectivity_shift(): im.deref( im.call( im.call("shift")( - im.ensure_offset("E2V"), + im.ensure_offset(E2VDim.tag), im.ensure_offset(E2V_neighbor_idx), - im.ensure_offset("C2E"), + im.ensure_offset(C2EDim.tag), im.ensure_offset(C2E_neighbor_idx), ) )("it") @@ -1033,9 +1096,9 @@ def test_gtir_connectivity_shift(): im.deref( im.call( im.call("shift")( - im.ensure_offset("E2V"), + im.ensure_offset(E2VDim.tag), im.plus(im.deref("e2v_off"), 0), - im.ensure_offset("C2E"), + im.ensure_offset(C2EDim.tag), im.deref("c2e_off"), ) )("it") @@ -1049,9 +1112,9 @@ def test_gtir_connectivity_shift(): im.deref( im.call( im.call("shift")( - im.ensure_offset("E2V"), + im.ensure_offset(E2VDim.tag), im.deref("e2v_off"), - im.ensure_offset("C2E"), + im.ensure_offset(C2EDim.tag), im.deref("c2e_off"), ) )("it") @@ -1068,8 +1131,8 @@ def test_gtir_connectivity_shift(): CELL_OFFSET_FTYPE = ts.FieldType(dims=[Cell], dtype=SIZE_TYPE) EDGE_OFFSET_FTYPE = ts.FieldType(dims=[Edge], dtype=SIZE_TYPE) - connectivity_C2E = SIMPLE_MESH.offset_provider["C2E"] - connectivity_E2V = SIMPLE_MESH.offset_provider["E2V"] + connectivity_C2E = SIMPLE_MESH.offset_provider[C2EDim.tag] + connectivity_E2V = SIMPLE_MESH.offset_provider[E2VDim.tag] ev = np.random.rand(SIMPLE_MESH.num_edges, SIMPLE_MESH.num_vertices) ref = ev[connectivity_C2E.asnumpy()[:, C2E_neighbor_idx], :][ @@ -1111,28 +1174,28 @@ def test_gtir_connectivity_shift(): ev, c2e_offset=np.full(SIMPLE_MESH.num_cells, C2E_neighbor_idx, dtype=np.int32), e2v_offset=np.full(SIMPLE_MESH.num_edges, E2V_neighbor_idx, dtype=np.int32), - gt_conn_C2E=connectivity_C2E.ndarray, - gt_conn_E2V=connectivity_E2V.ndarray, + **{gtx_dace_args.connectivity_identifier(C2EDim.tag): connectivity_C2E.ndarray}, + **{gtx_dace_args.connectivity_identifier(E2VDim.tag): connectivity_E2V.ndarray}, **FSYMBOLS, **make_mesh_symbols(SIMPLE_MESH), - __ce_field_Cell_range_0=0, - __ce_field_Cell_range_1=SIMPLE_MESH.num_cells, - __ce_field_Cell_stride=SIMPLE_MESH.num_edges, - __ce_field_Edge_range_0=0, - __ce_field_Edge_range_1=SIMPLE_MESH.num_edges, - __ce_field_Edge_stride=1, - __ev_field_Edge_range_0=0, - __ev_field_Edge_range_1=SIMPLE_MESH.num_edges, - __ev_field_Edge_stride=SIMPLE_MESH.num_vertices, - __ev_field_Vertex_range_0=0, - __ev_field_Vertex_range_1=SIMPLE_MESH.num_vertices, - __ev_field_Vertex_stride=1, - __c2e_offset_Cell_range_0=0, - __c2e_offset_Cell_range_1=SIMPLE_MESH.num_cells, - __c2e_offset_Cell_stride=1, - __e2v_offset_Edge_range_0=0, - __e2v_offset_Edge_range_1=SIMPLE_MESH.num_edges, - __e2v_offset_Edge_stride=1, + **{gtx_dace_args.range_start_symbol("ce_field", Cell).name: 0}, + **{gtx_dace_args.range_stop_symbol("ce_field", Cell).name: SIMPLE_MESH.num_cells}, + **{gtx_dace_args.field_stride_symbol("ce_field", Cell).name: SIMPLE_MESH.num_edges}, + **{gtx_dace_args.range_start_symbol("ce_field", Edge).name: 0}, + **{gtx_dace_args.range_stop_symbol("ce_field", Edge).name: SIMPLE_MESH.num_edges}, + **{gtx_dace_args.field_stride_symbol("ce_field", Edge).name: 1}, + **{gtx_dace_args.range_start_symbol("ev_field", Edge).name: 0}, + **{gtx_dace_args.range_stop_symbol("ev_field", Edge).name: SIMPLE_MESH.num_edges}, + **{gtx_dace_args.field_stride_symbol("ev_field", Edge).name: SIMPLE_MESH.num_vertices}, + **{gtx_dace_args.range_start_symbol("ev_field", Vertex).name: 0}, + **{gtx_dace_args.range_stop_symbol("ev_field", Vertex).name: SIMPLE_MESH.num_vertices}, + **{gtx_dace_args.field_stride_symbol("ev_field", Vertex).name: 1}, + **{gtx_dace_args.range_start_symbol("c2e_offset", Cell).name: 0}, + **{gtx_dace_args.range_stop_symbol("c2e_offset", Cell).name: SIMPLE_MESH.num_cells}, + **{gtx_dace_args.field_stride_symbol("c2e_offset", Cell).name: 1}, + **{gtx_dace_args.range_start_symbol("e2v_offset", Edge).name: 0}, + **{gtx_dace_args.range_stop_symbol("e2v_offset", Edge).name: SIMPLE_MESH.num_edges}, + **{gtx_dace_args.field_stride_symbol("e2v_offset", Edge).name: 1}, ) assert np.allclose(ce, ref) @@ -1153,11 +1216,11 @@ def test_gtir_connectivity_shift_chain(): gtir.SetAt( expr=im.as_fieldop( # let domain inference infer the domain here - im.lambda_("it")(im.deref(im.shift("E2V", E2V_neighbor_idx)("it"))), + im.lambda_("it")(im.deref(im.shift(E2VDim.tag, E2V_neighbor_idx)("it"))), )( im.as_fieldop( # let domain inference infer the domain here - im.lambda_("it")(im.deref(im.shift("V2E", V2E_neighbor_idx)("it"))), + im.lambda_("it")(im.deref(im.shift(V2EDim.tag, V2E_neighbor_idx)("it"))), )("edges") ), domain=im.get_field_domain( @@ -1172,8 +1235,8 @@ def test_gtir_connectivity_shift_chain(): sdfg = build_dace_sdfg(testee, SIMPLE_MESH.offset_provider) - connectivity_E2V = SIMPLE_MESH.offset_provider["E2V"] - connectivity_V2E = SIMPLE_MESH.offset_provider["V2E"] + connectivity_E2V = SIMPLE_MESH.offset_provider[E2VDim.tag] + connectivity_V2E = SIMPLE_MESH.offset_provider[V2EDim.tag] e = np.random.rand(SIMPLE_MESH.num_edges) ref = e[ @@ -1188,13 +1251,13 @@ def test_gtir_connectivity_shift_chain(): sdfg( e, e_out, - gt_conn_E2V=connectivity_E2V.ndarray, - gt_conn_V2E=connectivity_V2E.ndarray, + **{gtx_dace_args.connectivity_identifier(E2VDim.tag): connectivity_E2V.ndarray}, + **{gtx_dace_args.connectivity_identifier(V2EDim.tag): connectivity_V2E.ndarray}, **FSYMBOLS, **make_mesh_symbols(SIMPLE_MESH), - __edges_out_Edge_range_0=0, - __edges_out_Edge_range_1=SIMPLE_MESH.num_edges, - __edges_out_Edge_stride=1, + **{gtx_dace_args.range_start_symbol("edges_out", Edge).name: 0}, + **{gtx_dace_args.range_stop_symbol("edges_out", Edge).name: SIMPLE_MESH.num_edges}, + **{gtx_dace_args.field_stride_symbol("edges_out", Edge).name: 1}, ) assert np.allclose(e_out, ref) @@ -1223,7 +1286,7 @@ def test_gtir_neighbors_as_input(): gtir.SetAt( expr=im.let( "x", - im.as_fieldop_neighbors("V2E", "edges"), + im.as_fieldop_neighbors(V2EDim.tag, "edges"), )( im.as_fieldop( im.lambda_("it")( @@ -1239,7 +1302,7 @@ def test_gtir_neighbors_as_input(): sdfg = build_dace_sdfg(testee, SIMPLE_MESH.offset_provider) - connectivity_V2E = SIMPLE_MESH.offset_provider["V2E"] + connectivity_V2E = SIMPLE_MESH.offset_provider[V2EDim.tag] v2e_field = np.random.rand(SIMPLE_MESH.num_vertices, connectivity_V2E.shape[1], MESH_NUM_LEVELS) e = np.random.rand(SIMPLE_MESH.num_edges, MESH_NUM_LEVELS) @@ -1265,26 +1328,35 @@ def test_gtir_neighbors_as_input(): symbols = make_mesh_symbols(SIMPLE_MESH) | { # override SDFG symbols for array shape and strides because of extra K-dimension - "__edges_KDim_range_0": 0, - "__edges_KDim_range_1": e.shape[1], - "__edges_Edge_stride": e.strides[0] // e.itemsize, - "__edges_KDim_stride": e.strides[1] // e.itemsize, - "__vertices_KDim_range_0": 0, - "__vertices_KDim_range_1": v.shape[1], - "__vertices_Vertex_stride": v.strides[0] // v.itemsize, - "__vertices_KDim_stride": v.strides[1] // v.itemsize, - "__v2e_field_Vertex_range_0": 0, - "__v2e_field_Vertex_range_1": v2e_field.shape[0], - "__v2e_field_Vertex_stride": v2e_field.strides[0] // v2e_field.itemsize, - "__v2e_field_V2E_range_0": 0, - "__v2e_field_V2E_range_1": v2e_field.shape[1], - "__v2e_field_V2E_stride": v2e_field.strides[1] // v2e_field.itemsize, - "__v2e_field_KDim_range_0": 0, - "__v2e_field_KDim_range_1": v2e_field.shape[2], - "__v2e_field_KDim_stride": v2e_field.strides[2] // v2e_field.itemsize, + gtx_dace_args.range_start_symbol("edges", KDim).name: 0, + gtx_dace_args.range_stop_symbol("edges", KDim).name: e.shape[1], + gtx_dace_args.field_stride_symbol("edges", Edge).name: e.strides[0] // e.itemsize, + gtx_dace_args.field_stride_symbol("edges", KDim).name: e.strides[1] // e.itemsize, + gtx_dace_args.range_start_symbol("vertices", KDim).name: 0, + gtx_dace_args.range_stop_symbol("vertices", KDim).name: v.shape[1], + gtx_dace_args.field_stride_symbol("vertices", Vertex).name: v.strides[0] // v.itemsize, + gtx_dace_args.field_stride_symbol("vertices", KDim).name: v.strides[1] // v.itemsize, + gtx_dace_args.range_start_symbol("v2e_field", Vertex).name: 0, + gtx_dace_args.range_stop_symbol("v2e_field", Vertex).name: v2e_field.shape[0], + gtx_dace_args.field_stride_symbol("v2e_field", Vertex).name: v2e_field.strides[0] + // v2e_field.itemsize, + gtx_dace_args.range_start_symbol("v2e_field", V2EDim).name: 0, + gtx_dace_args.range_stop_symbol("v2e_field", V2EDim).name: v2e_field.shape[1], + gtx_dace_args.field_stride_symbol("v2e_field", V2EDim).name: v2e_field.strides[1] + // v2e_field.itemsize, + gtx_dace_args.range_start_symbol("v2e_field", KDim).name: 0, + gtx_dace_args.range_stop_symbol("v2e_field", KDim).name: v2e_field.shape[2], + gtx_dace_args.field_stride_symbol("v2e_field", KDim).name: v2e_field.strides[2] + // v2e_field.itemsize, } - sdfg(v2e_field, e, v, gt_conn_V2E=connectivity_V2E.ndarray, **symbols) + sdfg( + v2e_field, + e, + v, + **{gtx_dace_args.connectivity_identifier(V2EDim.tag): connectivity_V2E.ndarray}, + **symbols, + ) assert np.allclose(v, v_ref) @@ -1292,14 +1364,14 @@ def test_gtir_reduce(): init_value = np.random.rand() stencil_inlined = im.as_fieldop( im.lambda_("it")( - im.reduce("plus", im.literal_from_value(init_value))(im.neighbors("V2E", "it")) + im.reduce("plus", im.literal_from_value(init_value))(im.neighbors(V2EDim.tag, "it")) ) )("edges") stencil_fieldview = im.as_fieldop( im.lambda_("it")(im.reduce("plus", im.literal_from_value(init_value))(im.deref("it"))) - )(im.as_fieldop_neighbors("V2E", "edges")) + )(im.as_fieldop_neighbors(V2EDim.tag, "edges")) - connectivity_V2E = SIMPLE_MESH.offset_provider["V2E"] + connectivity_V2E = SIMPLE_MESH.offset_provider[V2EDim.tag] e = np.random.rand(SIMPLE_MESH.num_edges) v_ref = [ @@ -1336,7 +1408,7 @@ def test_gtir_reduce(): sdfg( e, v, - gt_conn_V2E=connectivity_V2E.ndarray, + **{gtx_dace_args.connectivity_identifier(V2EDim.tag): connectivity_V2E.ndarray}, **FSYMBOLS, **make_mesh_symbols(SIMPLE_MESH), ) @@ -1347,14 +1419,14 @@ def test_gtir_reduce_with_skip_values(): init_value = np.random.rand() stencil_inlined = im.as_fieldop( im.lambda_("it")( - im.reduce("plus", im.literal_from_value(init_value))(im.neighbors("V2E", "it")) + im.reduce("plus", im.literal_from_value(init_value))(im.neighbors(V2EDim.tag, "it")) ) )("edges") stencil_fieldview = im.as_fieldop( im.lambda_("it")(im.reduce("plus", im.literal_from_value(init_value))(im.deref("it"))) - )(im.as_fieldop_neighbors("V2E", "edges")) + )(im.as_fieldop_neighbors(V2EDim.tag, "edges")) - connectivity_V2E = SKIP_VALUE_MESH.offset_provider["V2E"] + connectivity_V2E = SKIP_VALUE_MESH.offset_provider[V2EDim.tag] e = np.random.rand(SKIP_VALUE_MESH.num_edges) v_ref = [ @@ -1393,7 +1465,7 @@ def test_gtir_reduce_with_skip_values(): sdfg( e, v, - gt_conn_V2E=connectivity_V2E.ndarray, + **{gtx_dace_args.connectivity_identifier(V2EDim.tag): connectivity_V2E.ndarray}, **FSYMBOLS, **make_mesh_symbols(SKIP_VALUE_MESH), ) @@ -1403,7 +1475,7 @@ def test_gtir_reduce_with_skip_values(): def test_gtir_reduce_dot_product(): init_value = np.random.rand() - connectivity_V2E = SKIP_VALUE_MESH.offset_provider["V2E"] + connectivity_V2E = SKIP_VALUE_MESH.offset_provider[V2EDim.tag] v2e_field = np.random.rand(*connectivity_V2E.shape) e = np.random.rand(SKIP_VALUE_MESH.num_edges) @@ -1438,7 +1510,7 @@ def test_gtir_reduce_dot_product(): )( im.op_as_fieldop(im.map_list("plus"))( im.op_as_fieldop(im.map_list("multiplies"))( - im.as_fieldop_neighbors("V2E", "edges"), + im.as_fieldop_neighbors(V2EDim.tag, "edges"), "v2e_field", ), im.op_as_fieldop("make_const_list")(1.0), @@ -1456,12 +1528,12 @@ def test_gtir_reduce_dot_product(): v2e_field, e, v, - gt_conn_V2E=connectivity_V2E.ndarray, + **{gtx_dace_args.connectivity_identifier(V2EDim.tag): connectivity_V2E.ndarray}, **make_mesh_symbols(SKIP_VALUE_MESH), - __v2e_field_Vertex_range_0=0, - __v2e_field_Vertex_range_1=SKIP_VALUE_MESH.num_vertices, - __v2e_field_Vertex_stride=connectivity_V2E.shape[1], - __v2e_field_V2E_stride=1, + **{gtx_dace_args.range_start_symbol("v2e_field", Vertex).name: 0}, + **{gtx_dace_args.range_stop_symbol("v2e_field", Vertex).name: SKIP_VALUE_MESH.num_vertices}, + **{gtx_dace_args.field_stride_symbol("v2e_field", Vertex).name: connectivity_V2E.shape[1]}, + **{gtx_dace_args.field_stride_symbol("v2e_field", V2EDim).name: 1}, ) assert np.allclose(v, v_ref) @@ -1489,7 +1561,7 @@ def test_gtir_reduce_with_cond_neighbors(use_sparse): im.if_( "pred", "v2e_field", - im.as_fieldop_neighbors("V2E", "edges"), + im.as_fieldop_neighbors(V2EDim.tag, "edges"), ) ), domain=im.get_field_domain(gtx_common.GridType.UNSTRUCTURED, "vertices", [Vertex]), @@ -1498,7 +1570,7 @@ def test_gtir_reduce_with_cond_neighbors(use_sparse): ], ) - connectivity_V2E = SKIP_VALUE_MESH.offset_provider["V2E"] + connectivity_V2E = SKIP_VALUE_MESH.offset_provider[V2EDim.tag] sdfg = build_dace_sdfg(testee, SKIP_VALUE_MESH.offset_provider) @@ -1527,13 +1599,13 @@ def test_gtir_reduce_with_cond_neighbors(use_sparse): v2e_field, e, v, - gt_conn_V2E=connectivity_V2E.ndarray, + **{gtx_dace_args.connectivity_identifier(V2EDim.tag): connectivity_V2E.ndarray}, **FSYMBOLS, **make_mesh_symbols(SKIP_VALUE_MESH), - __v2e_field_Vertex_range_0=0, - __v2e_field_Vertex_range_1=SKIP_VALUE_MESH.num_vertices, - __v2e_field_Vertex_stride=connectivity_V2E.shape[1], - __v2e_field_V2E_stride=1, + **{gtx_dace_args.range_start_symbol("v2e_field", Vertex).name: 0}, + **{gtx_dace_args.range_stop_symbol("v2e_field", Vertex).name: SKIP_VALUE_MESH.num_vertices}, + **{gtx_dace_args.field_stride_symbol("v2e_field", Vertex).name: connectivity_V2E.shape[1]}, + **{gtx_dace_args.field_stride_symbol("v2e_field", V2EDim).name: 1}, ) assert np.allclose(v, v_ref) @@ -1704,7 +1776,10 @@ def test_gtir_let_lambda_scalar_expression(): expr=im.let( "size_inner", im.plus( - domain_utils.SymbolicDomain.from_expr(domain_outer).ranges[IDim].stop, 1 + domain_utils.SymbolicDomain.from_expr(domain_outer) + .ranges[gtx_common.dimension_ref(IDim)] + .stop, + 1, ), )( im.let("tmp", im.multiplies_("a", "b"))( @@ -1733,7 +1808,7 @@ def test_gtir_let_lambda_scalar_expression(): # to the symbol `inner_size` is preserved, for which we want to test the lowering. sdfg = build_dace_sdfg(testee, offset_provider=CARTESIAN_OFFSETS, skip_domain_inference=True) - sdfg(a, b, c, d, **(FSYMBOLS | {"__x_IDim_range_1": N + 1})) + sdfg(a, b, c, d, **(FSYMBOLS | {gtx_dace_args.range_stop_symbol("x", IDim).name: N + 1})) assert np.allclose(d, (a * a * b * b * c[1 : N + 1])) @@ -1741,8 +1816,8 @@ def test_gtir_let_lambda_with_connectivity(): C2E_neighbor_idx = 1 C2V_neighbor_idx = 2 - connectivity_C2E = SIMPLE_MESH.offset_provider["C2E"] - connectivity_C2V = SIMPLE_MESH.offset_provider["C2V"] + connectivity_C2E = SIMPLE_MESH.offset_provider[C2EDim.tag] + connectivity_C2V = SIMPLE_MESH.offset_provider[C2VDim.tag] testee = gtir.Program( id="let_lambda_with_connectivity", @@ -1758,13 +1833,13 @@ def test_gtir_let_lambda_with_connectivity(): expr=im.let( "x1", im.as_fieldop( - im.lambda_("it")(im.deref(im.shift("C2E", C2E_neighbor_idx)("it"))) + im.lambda_("it")(im.deref(im.shift(C2EDim.tag, C2E_neighbor_idx)("it"))) )("edges"), )( im.let( "x2", im.as_fieldop( - im.lambda_("it")(im.deref(im.shift("C2V", C2V_neighbor_idx)("it"))) + im.lambda_("it")(im.deref(im.shift(C2VDim.tag, C2V_neighbor_idx)("it"))) )("vertices"), )(im.op_as_fieldop("plus")("x1", "x2")) ), @@ -1788,8 +1863,8 @@ def test_gtir_let_lambda_with_connectivity(): cells=c, edges=e, vertices=v, - gt_conn_C2E=connectivity_C2E.ndarray, - gt_conn_C2V=connectivity_C2V.ndarray, + **{gtx_dace_args.connectivity_identifier(C2EDim.tag): connectivity_C2E.ndarray}, + **{gtx_dace_args.connectivity_identifier(C2VDim.tag): connectivity_C2V.ndarray}, **FSYMBOLS, **make_mesh_symbols(SIMPLE_MESH), ) @@ -1815,7 +1890,7 @@ def test_gtir_let_lambda_with_origin(): gtir.SetAt( expr=im.let("e1", im.op_as_fieldop("plus")("edges", 1.0))( im.as_fieldop( - im.lambda_("it")(im.deref(im.shift("C2E", C2E_neighbor_idx)("it"))), + im.lambda_("it")(im.deref(im.shift(C2EDim.tag, C2E_neighbor_idx)("it"))), )("e1") ), domain=apply_margin_on_field_domain( @@ -1832,26 +1907,26 @@ def test_gtir_let_lambda_with_origin(): c = np.random.rand(SIMPLE_MESH.num_cells, MESH_NUM_LEVELS) e = np.random.rand(SIMPLE_MESH.num_edges, MESH_NUM_LEVELS) - connectivity_C2E = SIMPLE_MESH.offset_provider["C2E"] + connectivity_C2E = SIMPLE_MESH.offset_provider[C2EDim.tag] ref = np.concatenate( (c[:, :1], e[connectivity_C2E.asnumpy()[:, C2E_neighbor_idx], 1:] + 1.0), axis=1 ) symbols = make_mesh_symbols(SIMPLE_MESH) | { - "__cells_KDim_range_0": 0, - "__cells_KDim_range_1": MESH_NUM_LEVELS, - "__cells_Cell_stride": c.strides[0] // c.itemsize, - "__cells_KDim_stride": c.strides[1] // c.itemsize, - "__edges_KDim_range_0": 0, - "__edges_KDim_range_1": MESH_NUM_LEVELS, - "__edges_Edge_stride": e.strides[0] // e.itemsize, - "__edges_KDim_stride": e.strides[1] // e.itemsize, + gtx_dace_args.range_start_symbol("cells", KDim).name: 0, + gtx_dace_args.range_stop_symbol("cells", KDim).name: MESH_NUM_LEVELS, + gtx_dace_args.field_stride_symbol("cells", Cell).name: c.strides[0] // c.itemsize, + gtx_dace_args.field_stride_symbol("cells", KDim).name: c.strides[1] // c.itemsize, + gtx_dace_args.range_start_symbol("edges", KDim).name: 0, + gtx_dace_args.range_stop_symbol("edges", KDim).name: MESH_NUM_LEVELS, + gtx_dace_args.field_stride_symbol("edges", Edge).name: e.strides[0] // e.itemsize, + gtx_dace_args.field_stride_symbol("edges", KDim).name: e.strides[1] // e.itemsize, } sdfg( cells=c, edges=e, - gt_conn_C2E=connectivity_C2E.ndarray, + **{gtx_dace_args.connectivity_identifier(C2EDim.tag): connectivity_C2E.ndarray}, **symbols, ) @@ -1934,12 +2009,12 @@ def test_gtir_let_lambda_with_tuple1(): b_ref = np.concatenate((z_fields[1][:1], b[1 : N - 1], z_fields[1][N - 1 :])) tuple_symbols = { - "__z_0_IDim_range_0": 1, - "__z_0_IDim_range_1": N - 1, - "__z_0_IDim_stride": 1, - "__z_1_IDim_range_0": 1, - "__z_1_IDim_range_1": N - 1, - "__z_1_IDim_stride": 1, + gtx_dace_args.range_start_symbol("z_0", IDim).name: 1, + gtx_dace_args.range_stop_symbol("z_0", IDim).name: N - 1, + gtx_dace_args.field_stride_symbol("z_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("z_1", IDim).name: 1, + gtx_dace_args.range_stop_symbol("z_1", IDim).name: N - 1, + gtx_dace_args.field_stride_symbol("z_1", IDim).name: 1, } sdfg(a, b, z_fields[0][1 : N - 1], z_fields[1][1 : N - 1], **FSYMBOLS, **tuple_symbols) @@ -1992,15 +2067,15 @@ def test_gtir_let_lambda_with_tuple2(): z_fields = (np.empty_like(a), np.empty_like(a), np.empty_like(a)) tuple_symbols = { - "__z_0_IDim_range_0": 0, - "__z_0_IDim_range_1": N, - "__z_0_IDim_stride": 1, - "__z_1_IDim_range_0": 0, - "__z_1_IDim_range_1": N, - "__z_1_IDim_stride": 1, - "__z_2_IDim_range_0": 0, - "__z_2_IDim_range_1": N, - "__z_2_IDim_stride": 1, + gtx_dace_args.range_start_symbol("z_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("z_1", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_1", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_1", IDim).name: 1, + gtx_dace_args.range_start_symbol("z_2", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z_2", IDim).name: N, + gtx_dace_args.field_stride_symbol("z_2", IDim).name: 1, } sdfg(a, b, *z_fields, **FSYMBOLS, **tuple_symbols) @@ -2055,15 +2130,15 @@ def test_gtir_if_scalars(s): sdfg = build_dace_sdfg(testee, {}) tuple_symbols = { - "__x_0_IDim_range_0": 0, - "__x_0_IDim_range_1": N, - "__x_0_IDim_stride": 1, - "__x_1_0_IDim_range_0": 0, - "__x_1_0_IDim_range_1": N, - "__x_1_0_IDim_stride": 1, - "__x_1_1_IDim_range_0": 0, - "__x_1_1_IDim_range_1": N, - "__x_1_1_IDim_stride": 1, + gtx_dace_args.range_start_symbol("x_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("x_1_0", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_1_0", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_1_0", IDim).name: 1, + gtx_dace_args.range_start_symbol("x_1_1", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x_1_1", IDim).name: N, + gtx_dace_args.field_stride_symbol("x_1_1", IDim).name: 1, } sdfg(x_0=a, x_1_0=d1, x_1_1=d2, z=b, pred=np.bool_(s), **FSYMBOLS, **tuple_symbols) @@ -2237,30 +2312,30 @@ def test_gtir_concat_where_two_dimensions(): ) field_symbols = { - "__x_IDim_range_0": 0, - "__x_IDim_range_1": a.shape[0], - "__x_JDim_range_0": 0, - "__x_JDim_range_1": a.shape[1], - "__x_IDim_stride": a.strides[0] // a.itemsize, - "__x_JDim_stride": a.strides[1] // a.itemsize, - "__y_IDim_range_0": 0, - "__y_IDim_range_1": b.shape[0], - "__y_JDim_range_0": 0, - "__y_JDim_range_1": b.shape[1], - "__y_IDim_stride": b.strides[0] // b.itemsize, - "__y_JDim_stride": b.strides[1] // b.itemsize, - "__w_IDim_range_0": 0, - "__w_IDim_range_1": c.shape[0], - "__w_JDim_range_0": 0, - "__w_JDim_range_1": c.shape[1], - "__w_IDim_stride": c.strides[0] // c.itemsize, - "__w_JDim_stride": c.strides[1] // c.itemsize, - "__z_IDim_range_0": 0, - "__z_IDim_range_1": d.shape[0], - "__z_JDim_range_0": 0, - "__z_JDim_range_1": d.shape[1], - "__z_IDim_stride": d.strides[0] // d.itemsize, - "__z_JDim_stride": d.strides[1] // d.itemsize, + gtx_dace_args.range_start_symbol("x", IDim).name: 0, + gtx_dace_args.range_stop_symbol("x", IDim).name: a.shape[0], + gtx_dace_args.range_start_symbol("x", JDim).name: 0, + gtx_dace_args.range_stop_symbol("x", JDim).name: a.shape[1], + gtx_dace_args.field_stride_symbol("x", IDim).name: a.strides[0] // a.itemsize, + gtx_dace_args.field_stride_symbol("x", JDim).name: a.strides[1] // a.itemsize, + gtx_dace_args.range_start_symbol("y", IDim).name: 0, + gtx_dace_args.range_stop_symbol("y", IDim).name: b.shape[0], + gtx_dace_args.range_start_symbol("y", JDim).name: 0, + gtx_dace_args.range_stop_symbol("y", JDim).name: b.shape[1], + gtx_dace_args.field_stride_symbol("y", IDim).name: b.strides[0] // b.itemsize, + gtx_dace_args.field_stride_symbol("y", JDim).name: b.strides[1] // b.itemsize, + gtx_dace_args.range_start_symbol("w", IDim).name: 0, + gtx_dace_args.range_stop_symbol("w", IDim).name: c.shape[0], + gtx_dace_args.range_start_symbol("w", JDim).name: 0, + gtx_dace_args.range_stop_symbol("w", JDim).name: c.shape[1], + gtx_dace_args.field_stride_symbol("w", IDim).name: c.strides[0] // c.itemsize, + gtx_dace_args.field_stride_symbol("w", JDim).name: c.strides[1] // c.itemsize, + gtx_dace_args.range_start_symbol("z", IDim).name: 0, + gtx_dace_args.range_stop_symbol("z", IDim).name: d.shape[0], + gtx_dace_args.range_start_symbol("z", JDim).name: 0, + gtx_dace_args.range_stop_symbol("z", JDim).name: d.shape[1], + gtx_dace_args.field_stride_symbol("z", IDim).name: d.strides[0] // d.itemsize, + gtx_dace_args.field_stride_symbol("z", JDim).name: d.strides[1] // d.itemsize, } sdfg = build_dace_sdfg(testee, CARTESIAN_OFFSETS) @@ -2333,18 +2408,18 @@ def test_gtir_scan(id, use_symbolic_column_size): ref = np.add.accumulate(a, axis=1) + VAL symbols = FSYMBOLS | { - "__x_KDim_range_0": 0, - "__x_KDim_range_1": a.shape[1], - "__x_IDim_stride": a.strides[0] // a.itemsize, - "__x_KDim_stride": a.strides[1] // a.itemsize, - "__y_KDim_range_0": 0, - "__y_KDim_range_1": b.shape[1], - "__y_IDim_stride": b.strides[0] // b.itemsize, - "__y_KDim_stride": b.strides[1] // b.itemsize, - "__z_KDim_range_0": 0, - "__z_KDim_range_1": z.shape[1], - "__z_IDim_stride": z.strides[0] // z.itemsize, - "__z_KDim_stride": z.strides[1] // z.itemsize, + gtx_dace_args.range_start_symbol("x", KDim).name: 0, + gtx_dace_args.range_stop_symbol("x", KDim).name: a.shape[1], + gtx_dace_args.field_stride_symbol("x", IDim).name: a.strides[0] // a.itemsize, + gtx_dace_args.field_stride_symbol("x", KDim).name: a.strides[1] // a.itemsize, + gtx_dace_args.range_start_symbol("y", KDim).name: 0, + gtx_dace_args.range_stop_symbol("y", KDim).name: b.shape[1], + gtx_dace_args.field_stride_symbol("y", IDim).name: b.strides[0] // b.itemsize, + gtx_dace_args.field_stride_symbol("y", KDim).name: b.strides[1] // b.itemsize, + gtx_dace_args.range_start_symbol("z", KDim).name: 0, + gtx_dace_args.range_stop_symbol("z", KDim).name: z.shape[1], + gtx_dace_args.field_stride_symbol("z", IDim).name: z.strides[0] // z.itemsize, + gtx_dace_args.field_stride_symbol("z", KDim).name: z.strides[1] // z.itemsize, } sdfg(a, b, z, **symbols) @@ -2398,18 +2473,18 @@ def test_gtir_scan_single_level_output(): ref = np.add.accumulate(a, axis=1) symbols = FSYMBOLS | { - "__x_KDim_range_0": 0, - "__x_KDim_range_1": a.shape[1], - "__x_IDim_stride": a.strides[0] // a.itemsize, - "__x_KDim_stride": a.strides[1] // a.itemsize, - "__y_KDim_range_0": 0, - "__y_KDim_range_1": b.shape[1], - "__y_IDim_stride": b.strides[0] // b.itemsize, - "__y_KDim_stride": b.strides[1] // b.itemsize, - "__z_KDim_range_0": 0, - "__z_KDim_range_1": c.shape[1], - "__z_IDim_stride": c.strides[0] // c.itemsize, - "__z_KDim_stride": c.strides[1] // c.itemsize, + gtx_dace_args.range_start_symbol("x", KDim).name: 0, + gtx_dace_args.range_stop_symbol("x", KDim).name: a.shape[1], + gtx_dace_args.field_stride_symbol("x", IDim).name: a.strides[0] // a.itemsize, + gtx_dace_args.field_stride_symbol("x", KDim).name: a.strides[1] // a.itemsize, + gtx_dace_args.range_start_symbol("y", KDim).name: 0, + gtx_dace_args.range_stop_symbol("y", KDim).name: b.shape[1], + gtx_dace_args.field_stride_symbol("y", IDim).name: b.strides[0] // b.itemsize, + gtx_dace_args.field_stride_symbol("y", KDim).name: b.strides[1] // b.itemsize, + gtx_dace_args.range_start_symbol("z", KDim).name: 0, + gtx_dace_args.range_stop_symbol("z", KDim).name: c.shape[1], + gtx_dace_args.field_stride_symbol("z", IDim).name: c.strides[0] // c.itemsize, + gtx_dace_args.field_stride_symbol("z", KDim).name: c.strides[1] // c.itemsize, } sdfg(a, b, c, **symbols) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py index e0ba4f6d04..908d3d4230 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py @@ -20,18 +20,30 @@ from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm, ir_makers as im -from gt4py.next.iterator.transforms import pass_manager -from gt4py.next.iterator.transforms import scan_fusion +from gt4py.next.iterator.transforms import pass_manager, scan_fusion +from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args from gt4py.next.program_processors.runners.dace.workflow import backend, factory, translation from gt4py.next.program_processors.runners.dace.workflow.translation import DaCeTranslator from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim, KDim -IDim = common.Dimension("IDim") -K = common.Dimension("K", kind=common.DimensionKind.VERTICAL) + +class OtherK(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + + +K = KDim FTYPE = ts.FieldType(dims=[IDim, K], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)) +def _domain_args(name, dim, size, stride): + return { + gtx_dace_args.range_start_symbol(name, dim).name: 0, + gtx_dace_args.range_stop_symbol(name, dim).name: size, + gtx_dace_args.field_stride_symbol(name, dim).name: stride, + } + + def make_program(levels=17, forward=True, shift_axis=K): domain = im.domain("cartesian_domain", {IDim: (1, 3), K: (1, levels + 1)}) offset = im.cartesian_offset(shift_axis, shift_axis) @@ -132,14 +144,8 @@ def test_compiled_scan_fusion(tmp_path, forward, levels): expected_y[i, k], expected_z[i, k] = a, b args = dict(x=x, y=y, z=z) for name in ("x", "y", "z"): - for dim, size, stride in (("IDim", 4, levels + 2), ("K", levels + 2, 1)): - args.update( - { - f"__{name}_{dim}_range_0": 0, - f"__{name}_{dim}_range_1": size, - f"__{name}_{dim}_stride": stride, - } - ) + for dim, size, stride in ((IDim, 4, levels + 2), (K, levels + 2, 1)): + args.update(_domain_args(name, dim, size, stride)) graph(**{key: value for key, value in args.items() if key in graph.arglist()}) np.testing.assert_allclose(y, expected_y, rtol=1e-12, atol=1e-12) np.testing.assert_allclose(z, expected_z, rtol=1e-12, atol=1e-12) @@ -252,13 +258,7 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev args = dict(x=x, u=u, y=y) for name, dim in (("x", input_dim), ("u", scan_dim), ("y", scan_dim)): for axis, size, stride in ((IDim, 4, levels + 2), (dim, levels + 2, 1)): - args.update( - { - f"__{name}_{axis.value}_range_0": 0, - f"__{name}_{axis.value}_range_1": size, - f"__{name}_{axis.value}_stride": stride, - } - ) + args.update(_domain_args(name, axis, size, stride)) graph(**{key: value for key, value in args.items() if key in graph.arglist()}) np.testing.assert_allclose( y, expected, rtol=16 * np.finfo(dtype).eps, atol=16 * np.finfo(dtype).eps @@ -269,9 +269,8 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev def test_unrelated_vertical_axes_are_not_fused(): - other = common.Dimension("OtherK", kind=common.DimensionKind.VERTICAL) program = pass_manager.apply_fieldview_transforms( - make_staggered_program(other, K), offset_provider={} + make_staggered_program(OtherK, K), offset_provider={} ) assert scan_fusion.fuse_scan_inputs(program, offset_provider_type={}) == program @@ -502,14 +501,8 @@ def test_scoped_compiled_values(tmp_path): expected_y[i, k], expected_z[i, k] = a, b args = dict(x=x, y=y, z=z) for name in ("x", "y", "z"): - for dim, size, stride in (("IDim", 4, 19), ("K", 19, 1)): - args.update( - { - f"__{name}_{dim}_range_0": 0, - f"__{name}_{dim}_range_1": size, - f"__{name}_{dim}_stride": stride, - } - ) + for dim, size, stride in ((IDim, 4, 19), (K, 19, 1)): + args.update(_domain_args(name, dim, size, stride)) graph(**{key: value for key, value in args.items() if key in graph.arglist()}) np.testing.assert_allclose(y, expected_y, rtol=1e-12, atol=1e-12) np.testing.assert_allclose(z, expected_z, rtol=1e-12, atol=1e-12) @@ -604,6 +597,6 @@ def test_compiled_shadowed_scan_inputs(tmp_path, scope): out = np.full_like(x, -1.0) args = dict(x=x, w=w, out=out) for name in ("x", "w", "out"): - args.update({f"__{name}_K_range_0": 0, f"__{name}_K_range_1": 5, f"__{name}_K_stride": 1}) + args.update(_domain_args(name, K, 5, 1)) graph(**{key: value for key, value in args.items() if key in graph.arglist()}) np.testing.assert_array_equal(out, np.cumsum(2 * x)) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_dimension_parameters.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_dimension_parameters.py new file mode 100644 index 0000000000..242afb6982 --- /dev/null +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_dimension_parameters.py @@ -0,0 +1,56 @@ +# 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 + +"""Dimension-valued options of the DaCe transformations accept classes, refs and map variables.""" + +from __future__ import annotations + +import pytest + +import gt4py.next as gtx +from gt4py.next import common as gtx_common +from gt4py.next.program_processors.runners.dace import ( + lowering as gtx_dace_lowering, + transformations as gtx_transformations, +) + + +class IDim(gtx.CartesianAxisIndex): ... + + +class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + + +_I_VAR = gtx_dace_lowering.get_map_variable(IDim) +_K_VAR = gtx_dace_lowering.get_map_variable(KDim) + + +@pytest.mark.parametrize( + "param", [IDim, gtx_common.dimension_ref(IDim), _I_VAR], ids=["class", "ref", "map_variable"] +) +def test_loop_blocking_parameter(param): + # a ref must be converted too, or blocking is silently disabled + assert gtx_transformations.LoopBlocking(blocking_parameters=[param]).blocking_parameters == [ + _I_VAR + ] + assert gtx_transformations.LoopBlocking(blocking_parameters=param).blocking_parameters == [ + _I_VAR + ] + + +@pytest.mark.parametrize( + "param", [KDim, gtx_common.dimension_ref(KDim), _K_VAR], ids=["class", "ref", "map_variable"] +) +def test_map_iteration_order_parameter(param): + # a single ref used not to be wrapped in a list + assert gtx_transformations.MapIterationOrder(unit_strides_dims=param).unit_strides_dims == [ + _K_VAR + ] + assert gtx_transformations.MapIterationOrder( + unit_strides_dims=[IDim, param] + ).unit_strides_dims == [_I_VAR, _K_VAR] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_promoter.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_promoter.py index 9fab169ef1..92ca01486f 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_promoter.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_promoter.py @@ -21,6 +21,13 @@ from . import util + +class I(gtx_common.CartesianAxisIndex): ... + + +class K(gtx_common.CartesianAxisIndex, kind=gtx_common.DimensionKind.VERTICAL): ... + + N = 10 @@ -312,10 +319,8 @@ def _make_horizontal_promoter_sdfg( sdfg = dace.SDFG(util.unique_name("serial_map_promoter_tester")) state = sdfg.add_state(is_start_block=True) - h_idx = gtx_dace_lowering.get_map_variable(gtx_common.Dimension("boden")) - v_idx = gtx_dace_lowering.get_map_variable( - gtx_common.Dimension("K", gtx_common.DimensionKind.VERTICAL) - ) + h_idx = gtx_dace_lowering.get_map_variable(I) + v_idx = gtx_dace_lowering.get_map_variable(K) if d1_map_is_vertical: d1_shape = (10,) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py index bf09ec1ccd..c781b650f1 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py @@ -18,14 +18,10 @@ from gt4py.next import astype, broadcast, common, int32, neighbor_sum from next_tests import definitions +from next_tests.integration_tests.cases_utils import IDim +from next_tests.toy_connectivity import E2V, E2VDim, Edge, Vertex -IDim = gtx.Dimension("IDim") -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) - E2V_TABLE = np.asarray([[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]], dtype=np.int32) @@ -183,7 +179,7 @@ def test_out_assigned_in_the_callers_field(device, backend): out = _field(device, np.zeros(5), [Edge]) out_object = out - edge_sum_program.with_backend(backend)(f, out, offset_provider={"E2V": _e2v(device)}) + edge_sum_program.with_backend(backend)(f, out, offset_provider={E2VDim.tag: _e2v(device)}) assert out is out_object and f.ndarray is f_buffer np.testing.assert_array_equal(out.asnumpy(), [3.0, 5.0, 7.0, 5.0, 4.0]) @@ -200,9 +196,9 @@ def test_table_is_a_runtime_argument(): prog = edge_sum_program.with_backend(jax_jit.jax_jit) conn = _e2v(device) - prog(f, out, offset_provider={"E2V": conn}) + prog(f, out, offset_provider={E2VDim.tag: conn}) - stablehlo = _jitted(prog).lower(f, out, offset_provider={"E2V": conn}).as_text() + stablehlo = _jitted(prog).lower(f, out, offset_provider={E2VDim.tag: conn}).as_text() assert "tensor<5x2xi32>" in re.search(r"@main\(([^)]*)\)", stablehlo).group(1) @@ -217,14 +213,14 @@ def test_retrace_per_table_buffer(): prog = edge_sum_program.with_backend(jax_jit.jax_jit) conn = _e2v(device) - prog(_field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]), out, offset_provider={"E2V": conn}) - prog(_field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, offset_provider={"E2V": conn}) + prog(_field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]), out, offset_provider={E2VDim.tag: conn}) + prog(_field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, offset_provider={E2VDim.tag: conn}) assert _jitted(prog)._cache_size() == 1 prog( _field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, - offset_provider={"E2V": _e2v(device, E2V_TABLE.copy())}, + offset_provider={E2VDim.tag: _e2v(device, E2V_TABLE.copy())}, ) assert _jitted(prog)._cache_size() == 2 @@ -419,7 +415,9 @@ def test_connectivities_of_another_library_are_rejected(non_numpy_backend): ) with pytest.raises(TypeError, match="numpy.ndarray"): - edge_sum_program.with_backend(non_numpy_backend)(f, out, offset_provider={"E2V": numpy_e2v}) + edge_sum_program.with_backend(non_numpy_backend)( + f, out, offset_provider={E2VDim.tag: numpy_e2v} + ) @gtx.field_operator @@ -488,5 +486,5 @@ def test_compile_is_rejected(name): with pytest.raises(RuntimeError, match="does not compile"): edge_sum_program.with_backend(getattr(experimental, name)).compile( - offset_provider={"E2V": None} + offset_provider={E2VDim.tag: None} ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py index b93f637cb0..c9cbb6825c 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py @@ -26,7 +26,6 @@ import pytest import gt4py._core.definitions as core_defs -import gt4py.next as gtx from gt4py.next import common, config, custom_layout_allocators from gt4py.next.otf import artifacts, workflow from gt4py.next.otf.binding import interface @@ -35,6 +34,8 @@ from gt4py.next.program_processors.runners import gtfn from gt4py.next.type_system import type_specifications as ts +from next_tests.integration_tests.cases_utils import IDim, JDim, KDim, Vertex + def test_make_gtfn_toolchain_device(): cpu_version = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(gpu=False)) @@ -218,20 +219,20 @@ def test_compile_workflow_without_config_caches_translation(): # unstructured: unit stride on the horizontal dimension only, not on the vertical one ( common.GridType.UNSTRUCTURED, - [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], + [Vertex, KDim], True, f"1, {_DYN}", ), ( common.GridType.UNSTRUCTURED, - [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], + [Vertex, KDim], False, f"{_DYN}, {_DYN}", ), # cartesian: never unit stride, although both dimensions are horizontal ( common.GridType.CARTESIAN, - [gtx.Dimension("I"), gtx.Dimension("J")], + [IDim, JDim], True, f"{_DYN}, {_DYN}", ), diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py index 510aa1ef1d..b9857032a8 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py @@ -10,15 +10,20 @@ import pytest +from gt4py import next as gtx +from gt4py.next import common from gt4py.next.iterator import ir as itir from gt4py.next.iterator.ir_utils import ir_makers as im from gt4py.next.program_processors.runners import roundtrip +class D(gtx.CartesianAxisIndex): ... + + @pytest.mark.parametrize("debug_order", [(False, True), (True, False)]) def test_generate_source_ignores_debug_flag(debug_order, monkeypatch): monkeypatch.setattr(roundtrip, "_SOURCE_CACHE", {}) - domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(value="D"), 0, 1)) + domain = im.call("cartesian_domain")(im.named_range(itir.AxisLiteral(dim=D), 0, 1)) program = itir.Program( id="testee", function_definitions=[], @@ -57,7 +62,7 @@ def test_load_module_caches_by_debug_flag(debug_order, monkeypatch): monkeypatch.setattr(roundtrip, "_MODULE_CACHE", {}) source_code = "VALUE = 42\n" - modules = {debug: roundtrip._load_module(source_code, debug) for debug in debug_order} + modules = {debug: roundtrip._load_module(source_code, debug, {}) for debug in debug_order} try: assert modules[False] is not modules[True] assert modules[False].VALUE == modules[True].VALUE == 42 @@ -67,6 +72,82 @@ def test_load_module_caches_by_debug_flag(debug_order, monkeypatch): assert os.path.isfile(modules[True].__file__) for debug in debug_order: - assert roundtrip._load_module(source_code, debug) is modules[debug] + assert roundtrip._load_module(source_code, debug, {}) is modules[debug] finally: os.remove(modules[True].__file__) + + +def _declare(module: str, kind=common.DimensionKind.HORIZONTAL) -> common.Dimension: + """Declare a dimension `K` whose module does not need to exist.""" + namespace = {"__name__": module, "gtx": gtx} + exec(f"class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.{kind.name}): ...", namespace) + return namespace["K"] + + +def _field(*dims: common.Dimension) -> common.Field: + return gtx.zeros({dim: (0, 2) for dim in dims}) + + +def test_bind_dimensions_uses_the_classes_of_the_arguments(): + k = _declare("not.importable") + ref = common.dimension_ref(k) + axis_dims = {"k": ref, "k_half": common.flip_staggered(ref), "d": common.dimension_ref(D)} + + for arg in (_field(k), _field(common.Staggered[k])): + bindings = roundtrip._bind_dimensions(axis_dims, ((arg, 1.0), _field(D)), {}) + assert bindings == {"k": k, "k_half": common.Staggered[k], "d": D} + + +def test_bind_dimensions_synthesizes_the_other_classes(): + ref = common.dimension_ref(_declare("not.importable", common.DimensionKind.VERTICAL)) + axis_dims = {"k": ref, "k_half": common.flip_staggered(ref)} + + bindings = roundtrip._bind_dimensions(axis_dims, (_field(D),), {}) + + assert {name: common.dimension_ref(cls) for name, cls in bindings.items()} == axis_dims + assert bindings["k_half"] is common.Staggered[bindings["k"]] + # the same classes in every call, so that the loaded module is reused + assert roundtrip._bind_dimensions(axis_dims, (), {}) == bindings + + +def test_bind_dimensions_rejects_a_redefined_dimension(): + first, second = _declare("mod"), _declare("mod") + with pytest.raises(ValueError, match="two different classes"): + roundtrip._bind_dimensions({}, (_field(first), _field(second)), {}) + + vertical = _declare("mod", common.DimensionKind.VERTICAL) + with pytest.raises(ValueError, match="share the tag"): + roundtrip._bind_dimensions({"k": common.dimension_ref(first)}, (_field(vertical),), {}) + + +def test_program_on_dimensions_that_cannot_be_imported(): + k = _declare("not.importable") + domain = im.domain(common.GridType.CARTESIAN, {k: (0, 2)}) + program = itir.Program( + id="testee", + function_definitions=[], + params=[itir.Sym(id="out")], + declarations=[], + body=[ + itir.SetAt( + expr=im.as_fieldop("deref", domain)(im.call("index")(itir.AxisLiteral(dim=k))), + domain=domain, + target=itir.SymRef(id="out"), + ) + ], + ) + source_code, entry_point_name, axis_dims = roundtrip._generate_source( + program, + debug=False, + use_embedded=True, + offset_provider={}, + transforms=lambda ir, *, offset_provider: ir, + ) + artifact = roundtrip.RoundtripArtifact( + source_code, entry_point_name, axis_dims, dispatch_backend=None, debug=False + ) + out = gtx.zeros({k: (0, 2)}, dtype=gtx.int32) + + artifact.load()(out, offset_provider={}) + + assert out.asnumpy().tolist() == [0, 1] diff --git a/tests/next_tests/unit_tests/test_common.py b/tests/next_tests/unit_tests/test_common.py index 89dfaa88cb..9949547546 100644 --- a/tests/next_tests/unit_tests/test_common.py +++ b/tests/next_tests/unit_tests/test_common.py @@ -6,48 +6,97 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses +import io +import itertools import operator +import pickle +import re from typing import Optional, Pattern import numpy as np import pytest -import re +import gt4py.next.common as common from gt4py import next as gtx from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils -import gt4py.next.common as common -from gt4py.next.embedded import array_ops from gt4py.next.common import ( + CartesianAxisIndex, Dimension, + DimensionIndex, DimensionKind, + DimensionRange, Domain, Infinity, UnitRange, + dimension_range, domain, - named_range, - NamedRange, promote_dims, unit_range, ) +from gt4py.next.embedded import array_ops + + +class X(CartesianAxisIndex): ... + + +class Y(CartesianAxisIndex): ... + + +class Z(CartesianAxisIndex): ... + + +class Foo(DimensionIndex): ... + + +class J(CartesianAxisIndex): ... + + +class K(CartesianAxisIndex): ... + + +class I(common.CartesianAxisIndex): ... + + +class I_half(common.CartesianAxisIndex): ... + + +class C2E(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class V2E(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class E2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class E2C(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class E2C2V(DimensionIndex, kind=DimensionKind.LOCAL): ... + + +class ECDim(DimensionIndex): ... + + +class IDim(CartesianAxisIndex): ... + + +class JDim(CartesianAxisIndex): ... + + +class KDim(CartesianAxisIndex, kind=DimensionKind.VERTICAL): ... + -C2E = Dimension("C2E", kind=DimensionKind.LOCAL) -V2E = Dimension("V2E", kind=DimensionKind.LOCAL) -E2V = Dimension("E2V", kind=DimensionKind.LOCAL) -E2C = Dimension("E2C", kind=DimensionKind.LOCAL) -E2C2V = Dimension("E2C2V", kind=DimensionKind.LOCAL) -ECDim = Dimension("ECDim") -IDim = Dimension("IDim") -JDim = Dimension("JDim") -KDim = Dimension("KDim", kind=DimensionKind.VERTICAL) IHalfDim = common.flip_staggered(IDim) @pytest.fixture def a_domain(): return Domain( - NamedRange(IDim, UnitRange(0, 10)), - NamedRange(JDim, UnitRange(5, 15)), - NamedRange(KDim, UnitRange(20, 30)), + DimensionRange(IDim, UnitRange(0, 10)), + DimensionRange(JDim, UnitRange(5, 15)), + DimensionRange(KDim, UnitRange(20, 30)), ) @@ -255,8 +304,96 @@ def test_range_comparison(op, rng1, rng2, expected): @pytest.mark.parametrize( "named_rng_like", [(IDim, (2, 4)), (IDim, range(2, 4)), (IDim, UnitRange(2, 4))] ) -def test_named_range_like(named_rng_like): - assert named_range(named_rng_like) == (IDim, UnitRange(2, 4)) +def test_dimension_range_like(named_rng_like): + assert dimension_range(named_rng_like) == (IDim, UnitRange(2, 4)) + + +@pytest.mark.parametrize( + "selection, expected", + [ + (IDim(3), "IDim=3"), + (IDim.at(0, 9), "IDim=(0:9)"), + (IDim.at(None, 3), "IDim=(-inf:3)"), + (IDim.at(3, None), "IDim=(3:inf)"), + ], +) +def test_dimension_selection_str(selection, expected): + # a point and a range print alike, by the dimension's short name + assert str(selection) == expected + + +class TestDimensionAt: + def test_one_integer_is_a_point(self): + point = IDim.at(3) + assert point == IDim(3) and type(point) is IDim + + @pytest.mark.parametrize("value", [0, -3, np.int32(5)]) + def test_point_is_absolute(self, value): + assert IDim.at(value) == IDim(int(value)) + + def test_point_on_a_staggered_dimension(self): + assert type(common.Staggered[IDim].at(1)) is common.Staggered[IDim] + + @pytest.mark.parametrize( + "args, expected", + [ + ((0, 10), UnitRange(0, 10)), + ((-5, -2), UnitRange(-5, -2)), + ((None, 10), UnitRange(Infinity.NEGATIVE, 10)), + ((0, None), UnitRange(0, Infinity.POSITIVE)), + ((None, None), UnitRange.infinite()), + ((UnitRange(2, 4),), UnitRange(2, 4)), + ((range(2, 4),), UnitRange(2, 4)), + ((range(2, 4, 1),), UnitRange(2, 4)), + ], + ) + def test_range(self, args, expected): + assert IDim.at(*args) == DimensionRange(IDim, expected) + + @pytest.mark.parametrize("args", [(), (0, 1, 2), (slice(0, 1),), ("0",), (1.0,), (0, "1")]) + def test_invalid_arguments(self, args): + with pytest.raises(TypeError, match=r"'IDim.at\(\)' takes"): + IDim.at(*args) + + def test_range_with_step(self): + with pytest.raises(ValueError, match="step"): + IDim.at(range(0, 10, 2)) + + def test_not_visible_on_an_index(self): + assert not hasattr(IDim(3), "at") + + def test_cannot_be_shadowed(self): + with pytest.raises(TypeError, match="'at'"): + + class _Shadowing(DimensionIndex): + def at(self) -> None: ... + + +class TestDimensionSelection: + """A point (a `DimensionIndex` instance) and a range on a dimension are read alike.""" + + @pytest.mark.parametrize( + "selection, value", + [(IDim(3), 3), (IDim.at(3), 3), (IDim.at(0, 10), UnitRange(0, 10))], + ) + def test_dim_and_value(self, selection, value): + assert selection.dim is IDim and selection.value == value + + def test_dimension_slice(self): + assert common.is_dimension_slice(slice(IDim(0), IDim(10))) + assert common.is_dimension_slice(slice(IDim(0), None)) + assert common.is_dimension_slice(slice(None, IDim(10))) + assert common.is_dimension_slice(slice(IDim(0), IDim(10), 1)) + assert not common.is_dimension_slice(slice(IDim(0), IDim(10), 2)) + assert not common.is_dimension_slice(slice(0, 10)) + assert not common.is_dimension_slice(slice(None)) + assert not common.is_dimension_slice(slice(IDim(0), 10)) + assert not common.is_dimension_slice(IDim(0)) + + def test_dimension_slice_alias_is_lazy(self): + # `slice` is not subscriptable at runtime, so the alias must never be evaluated + assert common.DimensionSlice.__name__ == "DimensionSlice" + assert common.DimensionSlice[IDim] is not None def test_domain_length(a_domain): @@ -267,10 +404,16 @@ def test_domain_length(a_domain): "empty_domain, expected", [ (Domain(), False), - (Domain(NamedRange(IDim, UnitRange(0, 10))), False), - (Domain(NamedRange(IDim, UnitRange(0, 0))), True), - (Domain(NamedRange(IDim, UnitRange(0, 0)), NamedRange(JDim, UnitRange(0, 1))), True), - (Domain(NamedRange(IDim, UnitRange(0, 1)), NamedRange(JDim, UnitRange(0, 0))), True), + (Domain(DimensionRange(IDim, UnitRange(0, 10))), False), + (Domain(DimensionRange(IDim, UnitRange(0, 0))), True), + ( + Domain(DimensionRange(IDim, UnitRange(0, 0)), DimensionRange(JDim, UnitRange(0, 1))), + True, + ), + ( + Domain(DimensionRange(IDim, UnitRange(0, 1)), DimensionRange(JDim, UnitRange(0, 0))), + True, + ), ], ) def test_empty_domain(empty_domain, expected): @@ -395,7 +538,7 @@ def test_domain_dims_ranges_length_mismatch(): ValueError, match=r"Number of provided dimensions \(\d+\) does not match number of provided ranges \(\d+\)", ): - dims = [Dimension("X"), Dimension("Y"), Dimension("Z")] + dims = [X, Y, Z] ranges = [UnitRange(0, 1), UnitRange(0, 1)] Domain(dims=dims, ranges=ranges) @@ -403,26 +546,26 @@ def test_domain_dims_ranges_length_mismatch(): def test_domain_slice_at(): # Create a sample domain domain = Domain( - NamedRange(IDim, UnitRange(0, 10)), - NamedRange(JDim, UnitRange(5, 15)), - NamedRange(KDim, UnitRange(20, 30)), + DimensionRange(IDim, UnitRange(0, 10)), + DimensionRange(JDim, UnitRange(5, 15)), + DimensionRange(KDim, UnitRange(20, 30)), ) # Test indexing with slices result = domain.slice_at[slice(2, 5), slice(5, 7), slice(7, 10)] expected_result = Domain( - NamedRange(IDim, UnitRange(2, 5)), - NamedRange(JDim, UnitRange(10, 12)), - NamedRange(KDim, UnitRange(27, 30)), + DimensionRange(IDim, UnitRange(2, 5)), + DimensionRange(JDim, UnitRange(10, 12)), + DimensionRange(KDim, UnitRange(27, 30)), ) assert result == expected_result # Test indexing with out-of-range slices result = domain.slice_at[slice(2, 15), slice(5, 7), slice(7, 10)] expected_result = Domain( - NamedRange(IDim, UnitRange(2, 10)), - NamedRange(JDim, UnitRange(10, 12)), - NamedRange(KDim, UnitRange(27, 30)), + DimensionRange(IDim, UnitRange(2, 10)), + DimensionRange(JDim, UnitRange(10, 12)), + DimensionRange(KDim, UnitRange(27, 30)), ) assert result == expected_result @@ -436,21 +579,21 @@ def test_domain_slice_at(): def test_domain_dim_index(): - dims = [Dimension("X"), Dimension("Y"), Dimension("Z")] + dims = [X, Y, Z] ranges = [UnitRange(0, 1), UnitRange(0, 1), UnitRange(0, 1)] domain = Domain(dims=dims, ranges=ranges) - domain.dim_index(Dimension("Y")) == 1 + domain.dim_index(Y) == 1 - domain.dim_index(Dimension("Foo")) == None + domain.dim_index(Foo) == None def test_domain_pop(): - dims = [Dimension("X"), Dimension("Y"), Dimension("Z")] + dims = [X, Y, Z] ranges = [UnitRange(0, 1), UnitRange(0, 1), UnitRange(0, 1)] domain = Domain(dims=dims, ranges=ranges) - domain.pop(Dimension("X")) == Domain(dims=dims[1:], ranges=ranges[1:]) + domain.pop(X) == Domain(dims=dims[1:], ranges=ranges[1:]) domain.pop(0) == Domain(dims=dims[1:], ranges=ranges[1:]) @@ -463,92 +606,92 @@ def test_domain_pop(): # Valid index and named ranges ( 0, - [NamedRange(Dimension("X"), UnitRange(100, 110))], + [DimensionRange(X, UnitRange(100, 110))], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), Domain( - NamedRange(Dimension("X"), UnitRange(100, 110)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(X, UnitRange(100, 110)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), ), ( 1, - [NamedRange(Dimension("X"), UnitRange(100, 110))], + [DimensionRange(X, UnitRange(100, 110))], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("X"), UnitRange(100, 110)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(X, UnitRange(100, 110)), + DimensionRange(K, UnitRange(0, 10)), ), ), ( -1, - [NamedRange(Dimension("X"), UnitRange(100, 110))], + [DimensionRange(X, UnitRange(100, 110))], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("X"), UnitRange(100, 110)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(X, UnitRange(100, 110)), ), ), ( - Dimension("J"), + J, [ - NamedRange(Dimension("X"), UnitRange(100, 110)), - NamedRange(Dimension("Z"), UnitRange(100, 110)), + DimensionRange(X, UnitRange(100, 110)), + DimensionRange(Z, UnitRange(100, 110)), ], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("X"), UnitRange(100, 110)), - NamedRange(Dimension("Z"), UnitRange(100, 110)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(X, UnitRange(100, 110)), + DimensionRange(Z, UnitRange(100, 110)), + DimensionRange(K, UnitRange(0, 10)), ), ), # Invalid indices ( 3, - [NamedRange(Dimension("X"), UnitRange(100, 110))], + [DimensionRange(X, UnitRange(100, 110))], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), IndexError, ), ( -4, - [NamedRange(Dimension("X"), UnitRange(100, 110))], + [DimensionRange(X, UnitRange(100, 110))], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), IndexError, ), ( - Dimension("Foo"), - [NamedRange(Dimension("X"), UnitRange(100, 110))], + Foo, + [DimensionRange(X, UnitRange(100, 110))], Domain( - NamedRange(Dimension("I"), UnitRange(0, 10)), - NamedRange(Dimension("J"), UnitRange(0, 10)), - NamedRange(Dimension("K"), UnitRange(0, 10)), + DimensionRange(I, UnitRange(0, 10)), + DimensionRange(J, UnitRange(0, 10)), + DimensionRange(K, UnitRange(0, 10)), ), ValueError, ), @@ -620,10 +763,10 @@ def test_dimension_promotion( def test_dimension_promotion_repeated_calls(): - I, K = Dimension("I"), Dimension("K", kind=DimensionKind.VERTICAL) + I, K = IDim, KDim first = promote_dims([I], [K]) - first.append(Dimension("J")) + first.append(JDim) assert promote_dims([I], [K]) == [I, K] for _ in range(2): @@ -780,7 +923,6 @@ def test_array_ops_entry_point_is_from_dlpack(self, array): class TestCartesianConnectivity: def test_for_translation(self): offset = 5 - I = common.Dimension("I") result = common.CartesianConnectivity.for_translation(I, offset) assert isinstance(result, common.CartesianConnectivity) @@ -789,8 +931,6 @@ def test_for_translation(self): assert result.offset == offset def test_for_relocation(self): - I = common.Dimension("I") - I_half = common.Dimension("I_half") result = common.CartesianConnectivity.for_relocation(I, I_half) assert isinstance(result, common.CartesianConnectivity) @@ -907,3 +1047,371 @@ def test_different_dims_raises(self): d2 = Domain(dims=(JDim,), ranges=(UnitRange(3, 10),)) with pytest.raises(NotImplementedError, match="different dimensions"): d1 | d2 + + +def test_gt_dims_are_unqualified_names(): + """ + `__gt_dims__` is the interop protocol with `gt4py.cartesian`, which names axes by their bare + names (`"I"`, `"J"`, `"K"`). A dimension's `tag` is its qualified name (ADR 0030), which + cartesian would not recognize, and would then transpose the array wrongly. + """ + field = gtx.as_field([IDim, JDim], np.zeros((2, 3))) + assert field.__gt_dims__ == ("IDim", "JDim") + + +class TestStaggered: + def test_interned(self): + assert common.Staggered[KDim] is common.Staggered[KDim] + assert common.is_staggered(common.Staggered[KDim]) + assert common.flip_staggered(common.Staggered[KDim]) is KDim + + def test_a_dimension_cannot_be_staggered_twice(self): + with pytest.raises(TypeError, match="is already staggered"): + common.Staggered[common.Staggered[KDim]] + with pytest.raises(TypeError, match="is already staggered"): + common.Staggered[KDim][KDim] + + @pytest.mark.parametrize( + "dim, match", + [ + (ECDim, "is not a declared Cartesian axis"), # a mesh location + (V2E, "is not a declared Cartesian axis"), # a local dimension + (DimensionIndex, "is not a declared Cartesian axis"), + (common.AnyCartesianAxisIndex, "is not a declared Cartesian axis"), + ], + ) + def test_only_a_declared_axis_can_be_staggered(self, dim, match): + with pytest.raises(TypeError, match=match): + common.Staggered[dim] + + def test_a_staggered_dimension_is_an_axis_but_not_a_declared_one(self): + assert issubclass(common.Staggered[KDim], common.AnyCartesianAxisIndex) + assert not issubclass(common.Staggered[KDim], common.CartesianAxisIndex) + assert not issubclass(common.Staggered[KDim], KDim) + + def test_pickles_through_its_base(self): + staggered = common.Staggered[KDim] + assert pickle.loads(pickle.dumps(staggered)) is staggered + assert pickle.loads(pickle.dumps(common.Staggered)) is common.Staggered + field = gtx.as_field([staggered], np.arange(3.0)) + assert pickle.loads(pickle.dumps(field)).domain.dims == (staggered,) + + +class TestDimensionRef: + def test_tag_format(self): + assert IDim.tag == f"{__name__}:IDim" + assert common.Staggered[KDim].tag == f"gt4py.next.common:Staggered[{KDim.tag}]" + + def test_computed_once_per_class(self): + assert common.dimension_ref(IDim) is common.dimension_ref(IDim) + + def test_fields(self): + spec = common.dimension_ref(common.Staggered[KDim]) + assert spec.kind is common.DimensionKind.VERTICAL + assert spec.is_cartesian_axis is True + assert spec.base == common.dimension_ref(KDim) + assert common.dimension_ref(ECDim).is_cartesian_axis is False + + def test_staggered_helpers_on_specs(self): + k = common.dimension_ref(KDim) + assert common.flip_staggered(k) == common.dimension_ref(common.Staggered[KDim]) + assert common.flip_staggered(common.flip_staggered(k)) == k + assert common.as_non_staggered(common.flip_staggered(k)) == k + with pytest.raises(TypeError, match="is not a declared Cartesian axis"): + common.flip_staggered(common.dimension_ref(ECDim)) + + def test_from_tag_roundtrip(self): + for dim in (IDim, common.Staggered[KDim], ECDim): + spec = common.dimension_ref(dim) + assert ( + common.DimensionRef.from_tag( + spec.tag, spec.kind, is_cartesian_axis=spec.is_cartesian_axis + ) + == spec + ) + + def test_pickles_by_value(self): + spec = common.dimension_ref(common.Staggered[KDim]) + data = pickle.dumps(spec) + assert __name__.encode() in data # the tag is a string in the stream... + assert pickle.loads(data) == spec + + class _NoGlobals(pickle.Unpickler): + def find_class(self, module, name): + # ...and no class other than the spec's own machinery is referenced + assert module.startswith("gt4py.") or module in ("builtins", "copyreg"), module + return super().find_class(module, name) + + assert _NoGlobals(io.BytesIO(data)).load() == spec + + def test_is_cartesian_axis(self): + assert common.is_cartesian_axis(IDim) + assert common.is_cartesian_axis(common.dimension_ref(IDim)) + assert not common.is_cartesian_axis(common.dimension_ref(V2E)) + + def test_a_cartesian_axis_is_not_local(self): + with pytest.raises(TypeError, match="cannot have kind 'local'"): + common.DimensionMeta( + "LocalAxis", (CartesianAxisIndex,), {}, kind=common.DimensionKind.LOCAL + ) + + def test_must_be_declared_at_module_level(self): + with pytest.raises(TypeError, match="must be declared at module level"): + + class _Local(CartesianAxisIndex): ... + + def test_repr_is_distinct_from_the_class(self): + ref = common.dimension_ref(IDim) + assert repr(ref) == f"DimensionRef({IDim.tag}, horizontal, cartesian_axis)" + assert repr(ref) != repr(IDim) + assert str(ref) == str(IDim) == "IDim[horizontal]" # the display form is shared + + @pytest.mark.parametrize( + "comparison", + [ + lambda r, c: r == c, + lambda r, c: c == r, + lambda r, c: r != c, + lambda r, c: c != r, + lambda r, c: c in [r], + ], + ) + def test_ref_vs_class_comparison_raises(self, comparison): + with pytest.raises(TypeError, match="missing a conversion"): + comparison(common.dimension_ref(IDim), IDim) + + def test_hash_based_lookups_cannot_be_guarded(self): + # documented limitation: the hashes differ, so `__eq__` is never consulted + ref = common.dimension_ref(IDim) + assert IDim not in {ref} + assert {ref: 1}.get(IDim) is None + + def test_interned(self): + ref = common.dimension_ref(common.Staggered[KDim]) + fields = {f.name: getattr(ref, f.name) for f in dataclasses.fields(ref)} + assert common.DimensionRef(**fields) is ref + assert pickle.loads(pickle.dumps(ref)) is ref + assert common.DimensionRef.from_tag(ref.tag, ref.kind, is_cartesian_axis=True) is ref + assert dataclasses.replace(ref) is ref + + def test_rejected_construction_leaves_the_interned_ref_intact(self): + ref = common.dimension_ref(IDim) + # a string kind is coerced *before* the lookup: same interned object, still an enum + assert common.DimensionRef(ref.module, ref.qualname, "horizontal", True) is ref + assert ref.kind is common.DimensionKind.HORIZONTAL + with pytest.raises(ValueError): + common.DimensionRef(ref.module, ref.qualname, "sideways", True) + with pytest.raises(ValueError, match="cannot have kind 'local'"): + common.DimensionRef(ref.module, ref.qualname, "local", True) + with pytest.raises(TypeError, match="must be a 'bool'"): + common.DimensionRef(ref.module, ref.qualname, "horizontal", "cartesian_axis") + assert ref.kind is common.DimensionKind.HORIZONTAL + assert ref.is_cartesian_axis is True + assert common.dimension_ref(IDim) is ref + + def test_interning_under_contention(self): + import concurrent.futures + import threading + + barrier = threading.Barrier(8) + + def build(i: int) -> common.DimensionRef: + barrier.wait() + return common.DimensionRef( + "contention_mod", f"Dim{i // 8}", "horizontal" + ) # 8 threads race on each name + + with concurrent.futures.ThreadPoolExecutor(8) as pool: + refs = list(pool.map(build, range(8 * 50))) + for i in range(0, len(refs), 8): + assert all(r is refs[i] for r in refs[i : i + 8]) + + def test_hash_is_not_pickled_or_fingerprinted(self): + from gt4py.next import fingerprinting + + ref = common.dimension_ref(IDim) + assert [f.name for f in dataclasses.fields(ref)] == [ + "module", + "qualname", + "kind", + "is_cartesian_axis", + "base", + ] + assert b"_hash" not in pickle.dumps(ref) + assert hash(ref) == hash(pickle.loads(pickle.dumps(ref))) + assert fingerprinting.make_fingerprinter()(ref) # deterministic, by fields + + def test_content_hash_does_not_depend_on_construction(self): + from gt4py.eve import utils as eve_utils + from gt4py.next.type_system import type_specifications as ts + + dtype = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) + ref = common.dimension_ref(IDim) + parsed = common.DimensionRef.from_tag(ref.tag, ref.kind, is_cartesian_axis=True) + assert eve_utils.content_hash([ts.FieldType(dims=[IDim], dtype=dtype), ref]) == ( + eve_utils.content_hash([ts.FieldType(dims=[parsed], dtype=dtype), parsed]) + ) + + def test_from_tag_only_staggered_is_parametrized(self): + with pytest.raises(ValueError, match="only 'Staggered' is parametrized"): + common.DimensionRef.from_tag( + f"pkg:Other[{KDim.tag}]", + common.DimensionKind.VERTICAL, + is_cartesian_axis=True, + ) + + @pytest.mark.parametrize( + "change", + [ + {"module": "pkg"}, + {"qualname": "Staggered[Other]"}, + {"kind": common.DimensionKind.HORIZONTAL}, + ], + ) + def test_staggered_ref_is_validated_against_its_base(self, change): + ref = common.dimension_ref(common.Staggered[KDim]) + fields = {f.name: getattr(ref, f.name) for f in dataclasses.fields(ref)} + with pytest.raises(ValueError, match="is not the staggered dimension"): + common.DimensionRef(**(fields | change)) + + +class TestCodegenName: + """`codegen_name` must be injective: a collision means two dimensions sharing a symbol.""" + + @pytest.mark.parametrize( + "tag, expected", + [ + ("IDim", "IDim"), + ("mod.V2E.Local", "mod_dV2E_dLocal"), + ("mod:V2E.Local", "mod_cV2E_dLocal"), + ("a.b_c", "a_db_uc"), + ("a_b.c", "a_ub_dc"), + ("my__mod.X", "my_u_umod_dX"), + ("_CONST_DIM", "_uCONST_uDIM"), + # a parametrized tag: the brackets must not survive into the identifier + ("gt4py.next.common:Staggered[pkg:K]", "gt4py_dnext_dcommon_cStaggered_lpkg_cK_r"), + ], + ) + def test_known_values(self, tag, expected): + assert common.codegen_name(tag) == expected + + def test_injective_on_escape_lookalikes(self): + """Tags that look like the escape sequences themselves must still be told apart.""" + tags = ["_u", "_d", "_c", "_l", "_r", "a_ud.b", "_ud_du", "..", "__", "[]", "a[b.c]"] + tags += ["_l[_r]", "a:_c", "u", ".", "_"] + assert len({common.codegen_name(tag) for tag in tags}) == len(tags) + + def test_output_is_a_valid_identifier(self): + for tag in ["mod.V2E.Local", "a.b_c", "_CONST_DIM", "pkg.sub.Dim", "mod.Staggered[mod.K]"]: + assert re.fullmatch(r"[A-Za-z_]\w*", common.codegen_name(tag)), tag + + def test_injective_exhaustively(self): + """ + Exhaustive over the characters that can actually collide, to a length that covers + every interaction between them. + + The naive scheme -- `_` -> `__` then `.` -> `_` -- fails this with 686 collisions, + because a dot becomes a single underscore and `'..'` collides with an escaped `'_'`. + """ + # every character a tag can contain that needs escaping, plus the escape letters + alphabet = "a._:[]udclr" + seen: dict[str, str] = {} + for length in range(1, 5): + for tag in map("".join, itertools.product(alphabet, repeat=length)): + mangled = common.codegen_name(tag) + assert mangled not in seen, ( + f"collision: {seen.get(mangled)!r} and {tag!r} both map to {mangled!r}" + ) + seen[mangled] = tag + assert len(seen) == sum(len(alphabet) ** n for n in range(1, 5)) + + +class TestDimensionKeyedConfiguration: + """String-keyed configuration naming dimensions: `symbolic_domain_sizes`, offset providers.""" + + def test_symbolic_domain_sizes_accept_dimensions(self): + sizes = common.normalize_symbolic_domain_sizes( + {ECDim: "n_cells", common.dimension_ref(IDim): "n_i", KDim.tag: "n_k"} + ) + assert sizes == {ECDim.tag: "n_cells", IDim.tag: "n_i", KDim.tag: "n_k"} + + @pytest.mark.parametrize("key", ["Cell", "pkg.mod.Cell"]) # bare names never match a tag + def test_symbolic_domain_sizes_reject_keys_that_never_match(self, key): + with pytest.raises(ValueError, match="symbolic_domain_sizes"): + common.normalize_symbolic_domain_sizes({key: "n"}) + + def test_offset_provider_keys(self): + conn = object() + assert common.normalize_offset_provider({V2E: conn, "E2V": conn}) == { + V2E.tag: conn, + "E2V": conn, + } + provider = {"E2V": conn, "pkg.V2E": conn} # plain offset names, dots included, are kept + assert common.normalize_offset_provider(provider) is provider # no copy in the common case + + def test_gtfn_symbolic_domain_sizes_are_normalized(self): + from gt4py._core import definitions as core_defs + from gt4py.next.program_processors.codegens.gtfn import gtfn_module + + step = gtfn_module.GTFNTranslationStep( + device_type=core_defs.DeviceType.CPU, symbolic_domain_sizes={ECDim: "n_cells"} + ) + assert step.symbolic_domain_sizes == {ECDim.tag: "n_cells"} + with pytest.raises(ValueError, match="never match"): + gtfn_module.GTFNTranslationStep( + device_type=core_defs.DeviceType.CPU, symbolic_domain_sizes={"Cell": "n_cells"} + ) + + +class TestCartesianAxisIndex: + def test_axis_levels(self): + assert issubclass(IDim, common.CartesianAxisIndex) + assert issubclass(common.CartesianAxisIndex, common.AnyCartesianAxisIndex) + assert issubclass(common.AnyCartesianAxisIndex, DimensionIndex) + assert not issubclass(ECDim, common.AnyCartesianAxisIndex) + + @pytest.mark.parametrize("dim", [IDim, IHalfDim]) + def test_shift_along_an_axis(self, dim): + assert (dim + 1).codomain is dim + assert (dim - 1).codomain is dim + assert (dim + 0.5).codomain is common.flip_staggered(dim) + + @pytest.mark.parametrize("dim", [ECDim, V2E]) + @pytest.mark.parametrize("op", [lambda d: d + 1, lambda d: d - 1, lambda d: d + 0.5]) + def test_no_index_arithmetic_off_an_axis(self, dim, op): + with pytest.raises(TypeError, match="is not a Cartesian axis"): + op(dim) + + def test_comparisons_stay_on_every_dimension(self): + # `concat_where(EdgeDim < n, ...)` over a mesh location must keep working + assert (ECDim < 5) == Domain( + dims=(ECDim,), ranges=(UnitRange(common.Infinity.NEGATIVE, 5),) + ) + assert (ECDim == 3) == Domain(dims=(ECDim,), ranges=(UnitRange(3, 4),)) + + +def test_a_dimension_fingerprint_includes_its_ref(): + # `kind` sets the layout order and a Cartesian axis allows index arithmetic, so a dimension + # redefined under the same name with another one (a re-run notebook cell) must not reuse + # cached stages or artifacts; a staggered dimension follows its base. + from gt4py.next import fingerprinting + + def declare(source: str) -> type: + namespace = {"__name__": __name__, "common": common} + exec(source, namespace) + return namespace["Redefined"] + + horizontal = declare("class Redefined(common.CartesianAxisIndex): ...") + vertical = declare( + "class Redefined(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ..." + ) + fingerprint = fingerprinting.lenient_fingerprinter + assert fingerprint(horizontal) != fingerprint(vertical) + assert fingerprint(horizontal) != fingerprint( + declare("class Redefined(common.DimensionIndex): ...") + ) + assert fingerprint(horizontal) == fingerprint( + declare("class Redefined(common.CartesianAxisIndex): ...") + ) + assert fingerprint(common.Staggered[horizontal]) != fingerprint(common.Staggered[vertical]) + assert fingerprinting.strict_fingerprinter(KDim) == fingerprinting.strict_fingerprinter(KDim) diff --git a/tests/next_tests/unit_tests/test_constructors.py b/tests/next_tests/unit_tests/test_constructors.py index 1f79e0c66d..bf1bd5a7be 100644 --- a/tests/next_tests/unit_tests/test_constructors.py +++ b/tests/next_tests/unit_tests/test_constructors.py @@ -22,9 +22,14 @@ ) -I = gtx.Dimension("I") -J = gtx.Dimension("J") -K = gtx.Dimension("K") +class I(gtx.CartesianAxisIndex): ... + + +class J(gtx.CartesianAxisIndex): ... + + +class K(gtx.CartesianAxisIndex): ... + sizes = {I: 10, J: 10, K: 10} @@ -254,7 +259,7 @@ def test_array_namespace_allocator_with_device(self): def test_array_namespace_allocator_aligned_index_warns(self): """allocator=numpy with aligned_index → warns and ignores aligned_index.""" - aligned_index = [common.NamedIndex(I, 0)] + aligned_index = [I(0)] with pytest.warns(UserWarning, match="aligned_index"): fc = constructors.FieldConstructor(allocator=np, aligned_index=aligned_index) field = fc.zeros(self._domain) @@ -272,7 +277,7 @@ def test_field_buffer_allocator(self): def test_field_buffer_allocator_with_aligned_index(self): """allocator=FieldBufferAllocator + aligned_index → accepted without error.""" allocator = next_allocators.StandardCPUFieldBufferAllocator() - aligned_index = [common.NamedIndex(I, 0)] + aligned_index = [I(0)] fc = constructors.FieldConstructor(allocator=allocator, aligned_index=aligned_index) field = fc.zeros(self._domain) assert isinstance(field.ndarray, np.ndarray) diff --git a/tests/next_tests/unit_tests/test_custom_layout_allocators.py b/tests/next_tests/unit_tests/test_custom_layout_allocators.py index 6f54a5d930..47c657c3d3 100644 --- a/tests/next_tests/unit_tests/test_custom_layout_allocators.py +++ b/tests/next_tests/unit_tests/test_custom_layout_allocators.py @@ -17,6 +17,30 @@ import gt4py.storage.allocators as core_allocators +class D0(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... + + +class D1(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... + + +class D2(common.CartesianAxisIndex, kind=common.DimensionKind.HORIZONTAL): ... + + +class D0_vertical(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + + +class D1_local(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... + + +class D2_vertical(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + + +class D2_local(common.DimensionIndex, kind=common.DimensionKind.LOCAL): ... + + +class D1_vertical(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... + + class DummyAllocator(next_allocators.FieldBufferAllocatorProtocol): __gt_device_type__ = core_defs.DeviceType.CPU @@ -25,7 +49,7 @@ def __gt_allocate__( domain: common.Domain, dtype: core_defs.DType[core_defs.ScalarT], device_id: int = 0, - aligned_index: Optional[Sequence[common.NamedIndex]] = None, + aligned_index: Optional[Sequence[common.DimensionIndex]] = None, ) -> core_allocators.TensorBuffer[core_defs.DeviceTypeT, core_defs.ScalarT]: pass @@ -98,35 +122,39 @@ def test_horizontal_first_layout_mapper(): # Test with only horizontal dimensions dims = [ - common.Dimension("D0", common.DimensionKind.HORIZONTAL), - common.Dimension("D1", common.DimensionKind.HORIZONTAL), - common.Dimension("D2", common.DimensionKind.HORIZONTAL), + D0, + D1, + D2, ] expected_layout_map = core_allocators.BufferLayoutMap((2, 1, 0)) assert horizontal_first_layout_mapper(dims) == expected_layout_map # Test with no horizontal dimensions dims = [ - common.Dimension("D0", common.DimensionKind.VERTICAL), - common.Dimension("D1", common.DimensionKind.LOCAL), - common.Dimension("D2", common.DimensionKind.VERTICAL), + D0_vertical, + D1_local, + D2_vertical, ] expected_layout_map = core_allocators.BufferLayoutMap((2, 0, 1)) assert horizontal_first_layout_mapper(dims) == expected_layout_map # Test with a mix of dimensions dims = [ - common.Dimension("D2", common.DimensionKind.LOCAL), - common.Dimension("D0", common.DimensionKind.HORIZONTAL), - common.Dimension("D1", common.DimensionKind.VERTICAL), + D2_local, + D0, + D1_vertical, ] expected_layout_map = core_allocators.BufferLayoutMap((0, 2, 1)) assert horizontal_first_layout_mapper(dims) == expected_layout_map -Cell = common.Dimension("Cell", common.DimensionKind.HORIZONTAL) -Edge = common.Dimension("Edge", common.DimensionKind.HORIZONTAL) -K = common.Dimension("K", common.DimensionKind.VERTICAL) +class Cell(common.DimensionIndex, kind=common.DimensionKind.HORIZONTAL): ... + + +class Edge(common.DimensionIndex, kind=common.DimensionKind.HORIZONTAL): ... + + +class K(common.CartesianAxisIndex, kind=common.DimensionKind.VERTICAL): ... class TestBaseFieldBufferAllocatorAlignedIndex: @@ -151,7 +179,7 @@ def test_aligned_index_zero_origin(self): domain = common.Domain( dims=(Cell, K), ranges=(common.UnitRange(0, 10), common.UnitRange(0, 5)) ) - aligned = [common.NamedIndex(Cell, 3)] + aligned = [Cell(3)] result = allocator.__gt_allocate__(domain, core_defs.dtype(float), aligned_index=aligned) assert result.shape == (10, 5) assert result.aligned_index == (3, 0) @@ -162,7 +190,7 @@ def test_aligned_index_nonzero_origin_cell(self): domain = common.Domain( dims=(Cell, K), ranges=(common.UnitRange(100, 110), common.UnitRange(0, 5)) ) - aligned = [common.NamedIndex(Cell, 103)] + aligned = [Cell(103)] result = allocator.__gt_allocate__(domain, core_defs.dtype(float), aligned_index=aligned) assert result.shape == (10, 5) assert result.aligned_index == (3, 0) @@ -173,7 +201,7 @@ def test_aligned_index_nonzero_origin_edge(self): domain = common.Domain( dims=(Edge, K), ranges=(common.UnitRange(200, 212), common.UnitRange(0, 5)) ) - aligned = [common.NamedIndex(Edge, 207)] + aligned = [Edge(207)] result = allocator.__gt_allocate__(domain, core_defs.dtype(float), aligned_index=aligned) assert result.shape == (12, 5) assert result.aligned_index == (7, 0) @@ -184,7 +212,7 @@ def test_aligned_index_nonzero_origin_all_dims(self): domain = common.Domain( dims=(Cell, K), ranges=(common.UnitRange(50, 60), common.UnitRange(10, 15)) ) - aligned = [common.NamedIndex(Cell, 53), common.NamedIndex(K, 12)] + aligned = [Cell(53), K(12)] result = allocator.__gt_allocate__(domain, core_defs.dtype(float), aligned_index=aligned) assert result.shape == (10, 5) assert result.aligned_index == (3, 2) @@ -195,7 +223,7 @@ def test_aligned_index_at_domain_start(self): domain = common.Domain( dims=(Cell, K), ranges=(common.UnitRange(100, 110), common.UnitRange(20, 25)) ) - aligned = [common.NamedIndex(Cell, 100), common.NamedIndex(K, 20)] + aligned = [Cell(100), K(20)] result = allocator.__gt_allocate__(domain, core_defs.dtype(float), aligned_index=aligned) assert result.shape == (10, 5) assert result.aligned_index == (0, 0) @@ -204,7 +232,7 @@ def test_aligned_index_shared_between_cell_and_edge_fields(self): """Same aligned_index with both Cell and Edge can be used to allocate both a Cell-field and an Edge-field; the irrelevant dimension is ignored.""" allocator = self._make_allocator() - aligned = [common.NamedIndex(Cell, 103), common.NamedIndex(Edge, 207)] + aligned = [Cell(103), Edge(207)] cell_domain = common.Domain( dims=(Cell, K), ranges=(common.UnitRange(100, 110), common.UnitRange(0, 5)) @@ -236,7 +264,7 @@ def test_aligned_index_outside_domain_raises(self): allocator.__gt_allocate__( domain, core_defs.dtype(float), - aligned_index=[common.NamedIndex(Cell, 50)], + aligned_index=[Cell(50)], ) # After domain end @@ -244,7 +272,7 @@ def test_aligned_index_outside_domain_raises(self): allocator.__gt_allocate__( domain, core_defs.dtype(float), - aligned_index=[common.NamedIndex(Cell, 120)], + aligned_index=[Cell(120)], ) # Exactly at domain end (exclusive upper bound) @@ -252,5 +280,5 @@ def test_aligned_index_outside_domain_raises(self): allocator.__gt_allocate__( domain, core_defs.dtype(float), - aligned_index=[common.NamedIndex(Cell, 110)], + aligned_index=[Cell(110)], ) diff --git a/tests/next_tests/unit_tests/test_field_utils.py b/tests/next_tests/unit_tests/test_field_utils.py index bf5f8dadfe..25f399ca25 100644 --- a/tests/next_tests/unit_tests/test_field_utils.py +++ b/tests/next_tests/unit_tests/test_field_utils.py @@ -12,6 +12,12 @@ from gt4py.next import common, constructors, field_utils +class X(common.CartesianAxisIndex): ... + + +class Y(common.CartesianAxisIndex): ... + + @pytest.mark.parametrize( "device_type", [ @@ -23,7 +29,7 @@ def test_verify_device_field_type(nd_array_implementation_and_device_type, device_type): nd_array_implementation, compatible_device_type = nd_array_implementation_and_device_type - testee = constructors.as_field([common.Dimension("X")], nd_array_implementation.asarray([42.0])) + testee = constructors.as_field([X], nd_array_implementation.asarray([42.0])) is_correct_device = compatible_device_type == device_type assert field_utils.verify_device_field_type(testee, device_type) == is_correct_device @@ -34,8 +40,7 @@ def test_first_buffer_skips_fields_without_a_buffer(): from gt4py.next.iterator import embedded as iterator_embedded - I = common.Dimension("I") - J = common.Dimension("J") + I, J = X, Y field = common._field(np.arange(3.0), domain=common.domain({I: 3})) args = ( iterator_embedded.IndexField(I), @@ -50,6 +55,4 @@ def test_first_buffer_skips_fields_without_a_buffer(): def test_first_buffer_without_a_buffer(): from gt4py.next.iterator import embedded as iterator_embedded - assert ( - field_utils.first_buffer(iterator_embedded.IndexField(common.Dimension("I")), 1.0) is None - ) + assert field_utils.first_buffer(iterator_embedded.IndexField(X), 1.0) is None diff --git a/tests/next_tests/unit_tests/test_utils.py b/tests/next_tests/unit_tests/test_utils.py index 6068d06f3d..aad5186a85 100644 --- a/tests/next_tests/unit_tests/test_utils.py +++ b/tests/next_tests/unit_tests/test_utils.py @@ -13,11 +13,17 @@ import pytest from gt4py.eve import concepts, datamodels -from gt4py.next import fingerprinting, utils +from gt4py.next import common, fingerprinting, utils from eve_tests import definitions +class I(common.CartesianAxisIndex): ... + + +class J(common.CartesianAxisIndex): ... + + @dataclasses.dataclass class _DataclassModel: value: int @@ -427,7 +433,7 @@ def test_dicts_with_unorderable_keys_are_order_independent(self): # `Dimension`s (and other dataclasses without `__lt__`) occur as dict keys # e.g. in user closure variables. - i, j = common.Dimension("I"), common.Dimension("J") + i, j = I, J assert fingerprinting.strict_fingerprinter( {i: 1, j: 2} ) == fingerprinting.strict_fingerprinter({j: 2, i: 1}) diff --git a/tests/next_tests/unit_tests/type_system_tests/test_type_info.py b/tests/next_tests/unit_tests/type_system_tests/test_type_info.py index 14a90409bd..d8d88a82f1 100644 --- a/tests/next_tests/unit_tests/type_system_tests/test_type_info.py +++ b/tests/next_tests/unit_tests/type_system_tests/test_type_info.py @@ -11,14 +11,16 @@ import pytest from gt4py.next import ( - Dimension, - DimensionKind, + CartesianAxisIndex, ) from gt4py.next.type_system import type_info, type_specifications as ts from gt4py.next.ffront import type_specifications as ts_ffront from gt4py.next.iterator.type_system import type_specifications as ts_it +from next_tests.integration_tests.cases_utils import IDim, JDim, KDim +from next_tests.toy_connectivity import C2EDim, V2EDim -TDim = Dimension("TDim") # Meaningless dimension, used for tests. + +class TDim(CartesianAxisIndex): ... def type_info_cases() -> list[tuple[Optional[ts.TypeSpec], dict]]: @@ -61,14 +63,10 @@ def callable_type_info_cases(): if not isinstance(symbol_type, ts.CallableType) ] - IDim = Dimension("I") - JDim = Dimension("J") - KDim = Dimension("K", kind=DimensionKind.VERTICAL) - bool_type = ts.ScalarType(kind=ts.ScalarKind.BOOL) float_type = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) int_type = ts.ScalarType(kind=ts.ScalarKind.INT64) - field_type = ts.FieldType(dims=[Dimension("I")], dtype=float_type) + field_type = ts.FieldType(dims=[IDim], dtype=float_type) tuple_type = ts.TupleType(types=[bool_type, field_type]) nullary_func_type = ts.FunctionType( pos_only_args=[], pos_or_kw_args={}, kw_only_args={}, returns=ts.VoidType() @@ -261,7 +259,7 @@ def callable_type_info_cases(): [ts.TupleType(types=[float_type, field_type])], {}, [ - r"Expected 1st argument to be of type 'tuple\[bool, Field\[\[I\], float64\]\]', got 'tuple\[float64, Field\[\[I\], float64\]\]'" + r"Expected 1st argument to be of type 'tuple\[bool, Field\[\[IDim\], float64\]\]', got 'tuple\[float64, Field\[\[IDim\], float64\]\]'" ], ts.VoidType(), ), @@ -270,7 +268,7 @@ def callable_type_info_cases(): [int_type], {}, [ - r"Expected 1st argument to be of type 'tuple\[bool, Field\[\[I\], float64\]\]', got 'int64'" + r"Expected 1st argument to be of type 'tuple\[bool, Field\[\[IDim\], float64\]\]', got 'int64'" ], ts.VoidType(), ), @@ -292,8 +290,8 @@ def callable_type_info_cases(): ], {}, [ - r"Expected argument 'a' to be of type 'Field\[\[K\], int64\]', got 'Field\[\[K\], float64\]'", - r"Expected argument 'b' to be of type 'Field\[\[K\], int64\]', got 'Field\[\[K\], float64\]'", + r"Expected argument 'a' to be of type 'Field\[\[KDim\], int64\]', got 'Field\[\[KDim\], float64\]'", + r"Expected argument 'b' to be of type 'Field\[\[KDim\], int64\]', got 'Field\[\[KDim\], float64\]'", ], ts.FieldType(dims=[KDim], dtype=float_type), ), @@ -343,8 +341,8 @@ def callable_type_info_cases(): [ts.TupleType(types=[ts.FieldType(dims=[IDim, JDim, KDim], dtype=int_type)])], {}, [ - r"Expected argument 'a' to be of type 'tuple\[Field\[\[I, J, K\], int64\], " - r"Field\[\[\.\.\.\], int64\]\]', got 'tuple\[Field\[\[I, J, K\], int64\]\]'." + r"Expected argument 'a' to be of type 'tuple\[Field\[\[IDim, JDim, KDim\], int64\], " + r"Field\[\[\.\.\.\], int64\]\]', got 'tuple\[Field\[\[IDim, JDim, KDim\], int64\]\]'." ], ts.FieldType(dims=[IDim, JDim, KDim], dtype=float_type), ), @@ -412,16 +410,14 @@ def test_return_type( [ (ts.ScalarType(kind=ts.ScalarKind.INT64), False), ( - ts.FieldType(dims=[Dimension("I")], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)), + ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)), False, ), ( ts.TupleType( types=[ ts.ScalarType(kind=ts.ScalarKind.INT64), - ts.FieldType( - dims=[Dimension("I")], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) - ), + ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)), ] ), False, @@ -430,9 +426,7 @@ def test_return_type( ts.NamedCollectionType( types=[ ts.ScalarType(kind=ts.ScalarKind.INT64), - ts.FieldType( - dims=[Dimension("I")], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) - ), + ts.FieldType(dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64)), ], keys=["a", "b"], original_python_type="some.module:SomeClass", @@ -447,7 +441,7 @@ def test_return_type( types=[ ts.ScalarType(kind=ts.ScalarKind.INT64), ts.FieldType( - dims=[Dimension("I")], + dims=[IDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64), ), ], @@ -467,8 +461,6 @@ def test_needs_value_extraction(type_spec: ts.TypeSpec, expected: bool): def test_promote_lists(): float64 = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) int32 = ts.ScalarType(kind=ts.ScalarKind.INT32) - V2EDim = Dimension("V2E", kind=DimensionKind.LOCAL) - C2EDim = Dimension("C2E", kind=DimensionKind.LOCAL) const_list = ts.ListType(element_type=float64, offset_type=None) v2e_list = ts.ListType(element_type=float64, offset_type=V2EDim) diff --git a/tests/next_tests/unit_tests/type_system_tests/test_type_translation.py b/tests/next_tests/unit_tests/type_system_tests/test_type_translation.py index 08783b6efd..a78101c8f2 100644 --- a/tests/next_tests/unit_tests/type_system_tests/test_type_translation.py +++ b/tests/next_tests/unit_tests/type_system_tests/test_type_translation.py @@ -22,6 +22,7 @@ from gt4py.next import constructors from next_tests.artifacts import custom_named_collections as cnc +from next_tests.integration_tests.cases_utils import IDim, JDim class CustomInt32DType: @@ -30,9 +31,6 @@ def dtype(self) -> np.dtype: return np.dtype(np.int32) -IDim = gtx.Dimension("IDim") -JDim = gtx.Dimension("JDim") - # -- PEP 695 type aliases -- type IFloatFieldAlias = gtx.Field[gtx.Dims[IDim], float] type ChainedFieldAlias = IFloatFieldAlias @@ -100,7 +98,7 @@ def _make_type_string_for_container(cls: type) -> str: ( gtx.Field[[IDim, JDim], float], ts.FieldType( - dims=[gtx.Dimension("IDim"), gtx.Dimension("JDim")], + dims=[IDim, JDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64), ), ), @@ -264,7 +262,9 @@ def test_generic_variadic_dims(value, expected_dims): with pytest.raises(ValueError, match="Invalid field dimension definition"): type_translation.from_type_hint(gtx.Field[value, np.int32]) else: - assert type_translation.from_type_hint(gtx.Field[value, np.int32]).dims == expected_dims + assert type_translation.from_type_hint( + gtx.Field[value, np.int32] + ).dims == common.dimension_refs(expected_dims) @pytest.mark.parametrize( diff --git a/typing_tests/test_next.yaml b/typing_tests/test_next.yaml index 5db040f8df..442dbabb9c 100644 --- a/typing_tests/test_next.yaml +++ b/typing_tests/test_next.yaml @@ -4,7 +4,7 @@ import typing from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -16,7 +16,7 @@ main: | from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator(grid_type=None, backend=None) def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -26,7 +26,7 @@ main: | from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator(grid_type=None) def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -36,7 +36,7 @@ main: | from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.scan_operator(axis=KDim) def somescanop( @@ -49,7 +49,7 @@ main: | from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.scan_operator(axis=KDim, forward=True, init=0.0) def somescanop( @@ -64,7 +64,7 @@ import typing from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -85,7 +85,7 @@ import typing from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -106,7 +106,7 @@ import typing from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -127,8 +127,8 @@ import typing from gt4py import next as gtx - CellDim = gtx.Dimension("CellDim", kind=gtx.DimensionKind.HORIZONTAL) - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class CellDim(gtx.DimensionIndex, kind=gtx.DimensionKind.HORIZONTAL): ... + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... T = typing.TypeVar("T", float, gtx.float32, gtx.float64, bool, gtx.int32, gtx.int64) CellKField: typing.TypeAlias = gtx.Field[gtx.Dims[CellDim, KDim], T] @@ -145,8 +145,8 @@ import typing from gt4py import next as gtx - CellDim = gtx.Dimension("CellDim", kind=gtx.DimensionKind.HORIZONTAL) - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class CellDim(gtx.DimensionIndex, kind=gtx.DimensionKind.HORIZONTAL): ... + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... T = typing.TypeVar("T", float, gtx.float32, gtx.float64, bool, gtx.int32, gtx.int64) CellKField: typing.TypeAlias = gtx.Field[gtx.Dims[CellDim, KDim], T] CKTuple: typing.TypeAlias = tuple[CellKField[T], CellKField[T]] @@ -163,8 +163,8 @@ from gt4py import next as gtx from gt4py.next import where - CellDim = gtx.Dimension("CellDim", kind=gtx.DimensionKind.HORIZONTAL) - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class CellDim(gtx.DimensionIndex, kind=gtx.DimensionKind.HORIZONTAL): ... + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... T = typing.TypeVar("T", float, gtx.float32, gtx.float64, bool, gtx.int32, gtx.int64) CellField: typing.TypeAlias = gtx.Field[gtx.Dims[CellDim], T] CellKField: typing.TypeAlias = gtx.Field[gtx.Dims[CellDim, KDim], T] @@ -205,7 +205,7 @@ import typing from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -218,7 +218,7 @@ main: | from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.scan_operator(axis=KDim) def somescanop( @@ -236,7 +236,7 @@ import typing from gt4py import next as gtx - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: @@ -260,8 +260,8 @@ import typing from gt4py import next as gtx - CDim = gtx.Dimension("CDim", kind=gtx.DimensionKind.HORIZONTAL) - KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + class CDim(gtx.DimensionIndex, kind=gtx.DimensionKind.HORIZONTAL): ... + class KDim(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... @gtx.field_operator def foo( @@ -275,3 +275,81 @@ main: | import xarray a: xarray.NamedArray + + - case: cartesian_axis_levels + main: | + from gt4py import next as gtx + + class K(gtx.CartesianAxisIndex, kind=gtx.DimensionKind.VERTICAL): ... + class C(gtx.DimensionIndex): ... + + def any_dimension(d: gtx.Dimension) -> None: ... + def any_axis(d: type[gtx.AnyCartesianAxisIndex]) -> None: ... + + any_dimension(gtx.Staggered[K]) + any_axis(gtx.Staggered[K]) + ok_dims: gtx.Field[gtx.Dims[C, gtx.Staggered[K]], float] | None = None + ok_shift = K + 1 + ok_half = gtx.Staggered[K] - 0.5 + any_axis(C) + bad_doubly: gtx.Field[gtx.Dims[gtx.Staggered[gtx.Staggered[K]]], float] | None = None + bad_location: gtx.Field[gtx.Dims[gtx.Staggered[C]], float] | None = None + bad_shift = C + 1 + bad_shift_back = C - 1 + out: | + main:14:10: error: Argument 1 to "any_axis" has incompatible type "type[C]"; expected "type[AnyCartesianAxisIndex]" [arg-type] + main:15:46: error: Type argument "Staggered[K]" of "Staggered" must be a subtype of "CartesianAxisIndex" [type-var] + main:16:48: error: Type argument "C" of "Staggered" must be a subtype of "CartesianAxisIndex" [type-var] + main:17:13: error: Unsupported operand types for + ("type[C]" and "int") [operator] + main:18:18: error: Unsupported operand types for - ("type[C]" and "int") [operator] + + - case: dimension_selection + main: | + import numpy as np + from gt4py import next as gtx + from gt4py.next import common + + class I(gtx.CartesianAxisIndex): ... + class J(gtx.CartesianAxisIndex): ... + + point_i: I = I.at(3) + point_np: I = I.at(np.int32(3)) + point_half: gtx.Staggered[I] = gtx.Staggered[I].at(3) + point: common.DimensionSelection[int] = I.at(3) + closed: common.DimensionSelection[common.UnitRange] = I.at(0, 10) + open_left: common.DimensionRange = I.at(None, 10) + from_range: common.DimensionSelection[common.UnitRange] = I.at(range(0, 10)) + dim_slice: common.DimensionSlice[I] = slice(I(0), I(10)) + open_slice: common.DimensionSlice[I] = slice(I(0), None) + + def index(f: gtx.Field[gtx.Dims[I, J], gtx.float64]) -> None: + f[I(1), J(2) : J(4)] + f[I(1) : I(3), J.at(2)] + f[I(1) :] + f[I.at(1, None), J.at(None, 4)] + + I.at() + I.at(0, 1, 2) + I.at(slice(0, 1)) + not_a_dim_slice: common.DimensionSlice[I] = slice(0, 10) + wrong_dim: J = I.at(3) + not_any: str = I.at(0, 10).value + out: | + main:24:1: error: All overload variants of "at" of "DimensionMeta" require at least one argument [call-overload] + main:24:1: note: Possible overload variants: + main:24:1: note: def at(cls, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit], /) -> I + main:24:1: note: def at(cls, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | None, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | None, /) -> DimensionRange[UnitRange[Any, Any]] + main:24:1: note: def at(cls, UnitRange[Any, Any] | range, /) -> DimensionRange[UnitRange[Any, Any]] + main:25:1: error: No overload variant of "at" of "DimensionMeta" matches argument types "int", "int", "int" [call-overload] + main:25:1: note: Possible overload variants: + main:25:1: note: def at(cls, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit], /) -> I + main:25:1: note: def at(cls, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | None, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | None, /) -> DimensionRange[UnitRange[Any, Any]] + main:25:1: note: def at(cls, UnitRange[Any, Any] | range, /) -> DimensionRange[UnitRange[Any, Any]] + main:26:1: error: No overload variant of "at" of "DimensionMeta" matches argument type "slice[int, int, Any]" [call-overload] + main:26:1: note: Possible overload variants: + main:26:1: note: def at(cls, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit], /) -> I + main:26:1: note: def at(cls, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | None, int | int | int | int | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | None, /) -> DimensionRange[UnitRange[Any, Any]] + main:26:1: note: def at(cls, UnitRange[Any, Any] | range, /) -> DimensionRange[UnitRange[Any, Any]] + main:27:45: error: Incompatible types in assignment (expression has type "slice[int, int, Any]", variable has type "slice[I, I, Literal[1] | None] | slice[I, None, Literal[1] | None] | slice[None, I, Literal[1] | None]") [assignment] + main:28:16: error: Incompatible types in assignment (expression has type "I", variable has type "J") [assignment] + main:29:16: error: Incompatible types in assignment (expression has type "UnitRange[Any, Any]", variable has type "str") [assignment]