From f4d23650756a77377a87937524892dc01a7e31de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Thu, 3 Dec 2026 16:58:45 +0100 Subject: [PATCH 1/5] =?UTF-8?q?personal/egparedes:=20connectivities=20as?= =?UTF-8?q?=20types=20=E2=80=94=20follow=20the=20design=20of=20gt4py#2899?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../connectivities-as-types.md | 120 ++++++++++-------- .../connectivities-as-types_alternatives.md | 4 +- .../connectivities-as-types_identity.md | 48 ++++--- .../connectivities-as-types_slides.md | 12 +- .../connectivities-as-types_staggering.md | 4 +- content/shared/dimensions-as-types.md | 2 +- 6 files changed, 98 insertions(+), 92 deletions(-) diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md index 4213f5e..7107465 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md @@ -3,7 +3,7 @@ title: "Connectivities as types: one declaration for offset, local dimension and author: egparedes tags: [type-system, type-checking, dimensions, local-dimensions, connectivities, offset-provider, unstructured, neighbor-sum, reduction, frontend, foast, gtir, embedded, gtfn, dace, nominal-types, dependent-types, metaclass, serialization, fingerprint, staggering, axis-dimensions, cw-complex, exterior-calculus, domain, dimension-kind, ugrid, sgrid, migration, adr, tech-debt, shared-local-dimensions, implemented] created: 2026-09-17 -updated: 2026-10-02 +updated: 2026-12-03 status: draft --- @@ -12,7 +12,7 @@ status: draft > `FieldOffset` tag, the local `Dimension` name and the `offset_provider` key — > plus a fourth, hidden one: the Python variable the `FieldOffset` is bound to. > Make the connectivity a **class** that *contains* its local dimension, is its -> own provider key, and whose identity — like every dimension's (ADR 0029) — is +> own provider key, and whose identity — like every dimension's (ADR 0030) — is > its qualified Python name. In the IR it is named by its local dimension's > tag, so shifts, reductions and sparse arguments all find the table under one > string: @@ -30,12 +30,12 @@ status: draft > identity constraints in the current tree, six (A1–A5 and A9, the embedded > position-dict key) dissolve by construction, three (A6–A8) collapse into a > single bind-time check, and one (A10, the `AxisLiteral` round-trip) remains, -> re-expressed over `tag` instead of `Dimension.value`. +> re-expressed over `DimensionRef` instead of `Dimension.value`. > **Implementation.** The design below is implemented on the stacked > GridTools/gt4py PRs listed in [Implementation](#implementation) (top branch -> `connectivities-as-types-8-typed-positions`), with ADR 0029 (dimensions as -> nominal types) and ADR 0030 (connectivities as types). The *Problem* section +> `connectivities-as-types-8-typed-positions`), with ADR 0030 (dimensions as +> nominal types) and ADR 0031 (connectivities as types; planned number). The *Problem* section > and the constraint catalogue in the appendix > [[personal/egparedes/connectivities-as-types/connectivities-as-types_research|Tag and name constraints — full catalogue]] > describe gt4py `main` (`b3c53fa7e`, v1.2.2), the tree the stack is based on. @@ -56,7 +56,7 @@ status: draft > [[personal/havogt/dimension-generic-fields/dimension-generic-fields|Generic dimensions and statically > typed staggering]], whose Part II also proposed the `Staggered[D]` shape > used here. It **supersedes** [[shared/dimensions-as-types|Dimensions as -> types]]: the dimension design below (ADR 0029) replaces that note's +> types]]: the dimension design below (ADR 0030) replaces that note's > `(name, kind)` value identity and interning registry with type identity, and > is stated here in full. It overlaps with > [[personal/havogt/mesh-and-first-class-halos/mesh-and-first-class-halos|A mesh concept with @@ -150,7 +150,9 @@ what is one idea — *a mapping between two index spaces, plus a name for it*. | Concept | Role | Replaces | | --- | --- | --- | -| `DimensionIndex` | a dimension is a subclass, an index along it an instance (ADR 0029); the root — mesh locations, axes and local dimensions are all subclasses, so every `type[DimensionIndex]` annotation in the tree keeps its meaning | `Dimension` instances | +| `DimensionIndex` | a dimension is a subclass, an index along it an instance (ADR 0030); the root — mesh locations, axes and local dimensions are all subclasses, so every `type[DimensionIndex]` annotation at the Python edge keeps its meaning | `Dimension` instances | +| `DimensionRef` | an immutable, interned value naming a dimension class (module, qualname, `kind`, whether it is a Cartesian axis, staggered base); what type specifications, the IR and the backends carry instead of the class (see [Identity](#identity-is-the-qualified-python-name)) | `Dimension` instances below the frontend | +| `DimensionRange` | a range on a dimension, `KDim.at(0, 10)`; a point is an index, `KDim(3)`. `field[KDim(5):KDim(10)]` is slice syntax for a range | `NamedRange` (`NamedIndex` for a point) | | `CartesianAxisIndex(AnyCartesianAxisIndex)` | a **declared Cartesian axis**: an index space with integer index arithmetic and exactly one staggered partner (see [Cartesian axis dimensions](#cartesian-axis-dimensions)). `AnyCartesianAxisIndex` is either cell class of such an axis, declared or derived | — (new; today `kind != LOCAL` is the nearest approximation, and it does not separate a Cartesian axis from a mesh location) | | `Staggered[D: CartesianAxisIndex]` | the axis's derived partner, at the half-integer positions of `D`; a real, interned class (see [`Staggered[D]`](#staggeredd)) | the `_Staggered` name prefix | | `LocalDimensionIndex(DimensionIndex)` | a local dimension: **owned** (declared nested in, or adopted by, its connectivity), or **owner-less** (optionally with `size=n`, which sets `max_neighbors = min_neighbors = n`); carries the neighbor counts | `Dimension(..., kind=LOCAL)`, `_CONST_DIM` | @@ -235,11 +237,11 @@ use for `a(V2E)`. The iterator-level `it_ts.OffsetLiteralType` / ### Sketch ```python -# ── dimensions (ADR 0029) ───────────────────────────────────────────────── +# ── dimensions (ADR 0030) ───────────────────────────────────────────────── class DimensionMeta(type): @property def tag(cls) -> Tag: # identity, and the IR spelling - return f"{cls.__module__}.{cls.__qualname__}" + return f"{cls.__module__}:{cls.__qualname__}" kind: DimensionKind __hash__ = type.__hash__ # __eq__ stays for `I == 5` -> Domain def __add__( # I + 1, K + 0.5; a Cartesian axis only @@ -282,7 +284,7 @@ Staggered[KDim] # KDim's derived partner; # Staggered[Staggered[KDim]] is a type error -# ── connectivities (ADR 0030) ───────────────────────────────────────────── +# ── connectivities (ADR 0031) ───────────────────────────────────────────── class ConnectivityMeta(type): tag: Tag # the declaration's qualified name offset_tag: Tag # how the IR names it, see "Identity" @@ -353,7 +355,7 @@ already names a buffer's origin in gt4py (`__gt_origin__`). ### Identity is the qualified Python name A dimension's or connectivity's identity is the Python type; its tag is -`f"{cls.__module__}.{cls.__qualname__}"` (except `Staggered[D]`, whose tag +`f"{cls.__module__}:{cls.__qualname__}"` (except `Staggered[D]`, whose tag embeds its base's full tag, rule 1; a connectivity is *named in the IR* by its `offset_tag`, rule 7). The static view (checkers see nominal types) and the runtime view (equality is `is`) agree by construction, and the tag is a @@ -368,37 +370,38 @@ that aliasing disappears. The cost is that the many function-local dummy dimensions in `tests/next_tests` move to module level. The consequences, stated as rules: -1. **Reconstruction from the IR is an import.** `resolve(tag)` imports the - longest importable module prefix and walks the rest as attributes, the way - `pickle` references a class, so a nested `V2E.Local` resolves naturally and a - redefined declaration resolves to the new class. `AxisLiteral` stores only the - tag; its `kind` and `dim` are read-only properties off the resolved class, and - `kind` is optional because a local dimension's is `None`. Memoization, `resolve_loaded` and the `Staggered[D]` grammar: [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. -2. **Types reaching the IR must be importable.** `` in a qualname is - rejected at class creation (for dimensions and connectivities); pickle's - own `save_global` stays the authoritative check. Interactive `__main__` - (REPL, notebooks, `python -c`) matters — every notebook declares its +1. **Two levels, and nothing is imported from a tag.** Classes are the identity at the + Python edge: user code, embedded execution and program calls. Below it, type + specifications, the IR and the backends carry a `DimensionRef`, an interned value + equal to another one if all its fields are; `dimension_ref(cls)` is the only + conversion. `AxisLiteral` stores the ref, and its `value` (the tag) and `kind` are + read-only properties of it. Details, and the `Staggered[D]` grammar: [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. +2. **Types must be importable to be pickled.** Only the connectivities of an offset + provider still carry classes into a compile job. `` in a qualname is + rejected at class creation (for dimensions and connectivities), as an early + heuristic; pickle's own `save_global` stays the authoritative check. Interactive + `__main__` (REPL, notebooks, `python -c`) matters — every notebook declares its dimensions there — so the process-pool runner (`BUILD_JOBS_MODE=process`) detects a job that references such a class and, with a warning, **compiles it in the calling thread** instead of failing in a spawn worker. 3. **No registry.** Classes pickle by reference. The one narrow `copyreg` hook is for `Staggered[D]`, whose bracketed qualname `save_global` cannot look up. -4. **Fingerprints depend on qualified names, plus `kind`.** A dimension is - deconstructed as its by-reference name *and* its `kind`, so redefining one under - the same name with another kind does invalidate artifacts; a staggered dimension +4. **Fingerprints depend on qualified names, plus the `DimensionRef`.** A dimension is + deconstructed as its by-reference name *and* its ref, i.e. also its `kind` and + whether it is a Cartesian axis, so redefining one under the same name with another + kind or axis level does invalidate artifacts; a staggered dimension is fingerprinted through its base. `base` cannot be flipped in place at all — `Staggered[K]` is interned by base identity and its tag embeds the base tag, so a - different base is a different class. The axis level - (`CartesianAxisIndex` versus `DimensionIndex`) is deliberately *not* - fingerprinted: it changes what is accepted, never what is emitted. A connectivity + different base is a different class. The axis level is included because the + frontend cache uses this fingerprint and index arithmetic depends on it. A connectivity declaration is fingerprinted *additionally* by its domain, codomain, `Local` and counts. Either way the ADR 0023 cache invalidates on module renames. 5. **Codegen names need injective mangling.** `codegen_name(tag)` is a prefix - escape (`_`→`_u`, `.`→`_d`, `[`→`_l`, `]`→`_r`); the obvious alternative is + escape (`_`→`_u`, `.`→`_d`, `:`→`_c`, `[`→`_l`, `]`→`_r`); the obvious alternative is not injective. 6. **Staggering is part of the dimension change.** The `_Staggered` name prefix needs the name→class lookup that type identity removes, so `Staggered[D]` is a - real class and part of ADR 0029 (PR A), with its parameter bounded on a + real class and part of ADR 0030 (PR A), with its parameter bounded on a declared [Cartesian axis](#cartesian-axis-dimensions). Rules 3–6 in full — the hook, the fingerprint deconstructors, the exhaustive @@ -418,12 +421,15 @@ stated as rules: truth value. The residual hazard is narrow and accepted: a dict holding both an integer key and a dimension-class key whose hashes collide would reach `bool(Domain)`. Class-keyed providers hold only classes and tag strings, and a - `str` compares unequal to a class, so they cannot. ADR 0029 records this. + `str` compares unequal to a class, so they cannot. 9. **Same-named declarations are different connectivities.** Two declarations with the same qualified name from different modules, or a redefinition, are simply different classes; no warning is issued, and `check_neighbor_table` hints "was the declaration redefined?" when a table - built for one is bound to the other. + built for one is bound to the other. For dimensions, a re-run notebook cell gives + an *equal* ref for a *new* class, so a call compares the classes of its arguments + with the ones the definition declares, by identity and under `__debug__` only; two + different refs with one tag in a program are an error. ### Cartesian axis dimensions @@ -481,7 +487,7 @@ staggered partner is still accepted, raising a `DSLError` in a field operator an `TypeError` in embedded execution (PR C, where `as_offset(dim, field)` lands). Only `+`/`-` and `as_offset` are restricted — comparison still builds a `Domain` on any dimension, which `concat_where` needs over `CellDim`/`EdgeDim`. Hand-written -iterator IR is unchecked, since it names dimensions by tag like the rest of the IR. +iterator IR is unchecked. The self-type costs two definition-site suppressions, one per checker; P4 of [`staggered_probe.py`](staggered_probe.py) pins it down and [[personal/egparedes/connectivities-as-types/connectivities-as-types_typing|the typing appendix]] records both diagnostics. @@ -555,13 +561,14 @@ of [Cartesian axis dimensions](#cartesian-axis-dimensions). `+1` index correction the position convention requires when shifting *out of* an unstaggered dimension: `K + 0.5` maps `K(i)` to `Staggered[K](i+1)` (position `i+½`), `Staggered[K] + 0.5` maps `Staggered[K](i)` to `K(i)`. - The frontend accepts only integer and half-integer literal offsets and - types the shift as an `OffsetType` at type-deduction time; statically, + The frontend accepts only integer and half-integer literal offsets, + computes the shift on refs (`cartesian_shift`) and types it as an `OffsetType` + at type-deduction time; statically, `K + 0.5` is a plain `Connectivity`. `check_dims` rejects a dimension and its staggered counterpart in one field or domain, and `order_dimensions` orders by the base, so a staggered field has the layout of its base. - **IR, serialization and fingerprints.** The tag is - `gt4py.next.common.Staggered[]` — the one tag that is not a + `gt4py.next.common:Staggered[]` — the one tag that is not a qualified name. Its grammar, the `copyreg` hook and fingerprinting through the base are in [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. - **Backends.** gtfn emits the staggered tag as a C++ alias of its base tag @@ -660,7 +667,7 @@ tables assign different neighbors to the same domain element. The model: in the local dimension, is an `arg-type` error, probe P1b), while a `Local` generated in `__init_subclass__` and annotated `ClassVar[type[LocalDimensionIndex]]` on the base is rejected by - both as *not valid as a type* — the very error class ADR 0029 exists to + both as *not valid as a type* — the very error class ADR 0030 exists to remove. Two lines per connectivity buy a real type; ICON4Py has 16 declarations. Its tag is `.Local`, unique by construction. - `Local` is **not** passed through the base subscription @@ -689,10 +696,10 @@ tables assign different neighbors to the same domain element. The model: ICON4Py's memory layout for those fields. (Backend support for sparse fields over an owner-less axis *other than* `ConstList` is not part of the stack: such a field still needs some bound table over its axis.) -- `_CONST_DIM` is replaced by the owner-less - `common.ConstList(LocalDimensionIndex, size=1)`, one class used by iterator - embedded and the DaCe lowering with identity checks, and refused as an - adopted `Local`. (Type inference still +- `_CONST_DIM` is replaced by `iterator.builtins.ConstList`, one class used by iterator + embedded and the DaCe lowering. #2899 declares it as a `DimensionIndex` of kind + `LOCAL`; #2907 is to make it an owner-less `LocalDimensionIndex, size=1`, refused as + an adopted `Local`. (Type inference still represents a constant list as `ListType(offset_type=None)`.) - `neighbor_sum(..., axis=V2E.Local)` — the local axis stays **explicit**. `axis=V2E` as sugar is deliberately not offered; it would blur the two @@ -725,13 +732,13 @@ tables assign different neighbors to the same domain element. The model: | Frontend declaration | `Dimension(LOCAL)` + `FieldOffset` + provider key | one class | | Frontend types | `ts.OffsetType(source, target)`, tag dropped | `ts.ShiftType(domain, codomain, tag)` produced by the class (`__gt_type__`), `tag` set to `offset_tag`; `V2E.Local` in DSL code types as the local dimension | | FOAST → GTIR | shift tag = **Python variable name** | tag = `offset_tag`; the variable name is irrelevant (GridTools/gt4py#2898) | -| ITIR | `OffsetLiteral(str)` + dict lookup; `AxisLiteral(value, kind)` | `OffsetLiteral(offset_tag)`, unchanged node; `AxisLiteral(value)` with `kind` derived | +| ITIR | `OffsetLiteral(str)` + dict lookup; `AxisLiteral(value, kind)` | `OffsetLiteral(offset_tag)`, unchanged node; `AxisLiteral(dim: DimensionRef)`, with `value` and `kind` derived | | ITIR types | `ListType.offset_type: Dimension` | unchanged (already the local dim) | | Embedded field | `get_offset(provider, axis.value)` | table over the local dimension (`connectivity_key_over`); `V2E.bound_table()` | | Embedded iterator | positions keyed by name strings; `SparseTag` | positions keyed by dimension classes; `SparseAxis(dim)` | | gtfn | `dim.value` lookups; `TagDefinition` per tag and per `neighbor_dim` | still a `TagDefinition` per offset tag (and per differing `neighbor_dim`, i.e. for sharers), named by `codegen_name(tag)`; sparse-argument lookups through `connectivity_key_over` | | DaCe | ~10 `offset_type.value` lookups; `Dimension(offset, LOCAL)` synthesized | `codegen_name` for array/symbol names; `connectivity_key_over`; a local dimension sized from its own table (`local_dimension_size`); no synthesis | -| roundtrip backend | emits `gtx.Dimension("")` / `offset("")` as source text | emits ` = gtx.resolve("")` for axes and ` = offset("")` for offsets | +| roundtrip backend | emits `gtx.Dimension("")` / `offset("")` as source text | binds `` axis names to the classes of the call's fields and connectivities (synthesized from the ref only for a dimension none of them has), and emits ` = offset("")` for offsets | | Provider | `Mapping[str, NeighborTable]`; `offset_provider_type: Mapping[str, NeighborConnectivityType]` | public: `{V2E: table}`, and `table_types={V2E: NeighborTableType(...)}` (`TableTypesLike`, normalized to `TableTypes = Mapping[Tag, NeighborTableType]`) for ahead-of-time compilation (a dotted tag string is also accepted; the type stays `Mapping[Any, …]`); internal: keyed by `offset_tag`, normalized at the entry points; no deprecation window (a migration script for ICON4Py instead) | ### What it deletes @@ -739,7 +746,7 @@ tables assign different neighbors to the same domain element. The model: `FieldOffset` (both forms) and its export; bare-name provider keys (rejected at the strict entry points); the `_Staggered` prefix and its string sniffing (replaced by the `Staggered[D]` class and a small `[]` tag -grammar); `_CONST_DIM` as a magic name; the stored `AxisLiteral.kind`; +grammar); `_CONST_DIM` as a magic name; the separate `value` and `kind` fields of `AxisLiteral`; `SparseTag`; `NamedIndex` and the dimension half of the mypy plugin; `DimensionIndex(kind=LOCAL)` as a way to declare a local dimension, and the `LOCAL` member of `DimensionKind` itself (derived from `LocalDimensionIndex`); and the @@ -772,8 +779,8 @@ raise, with why each loses: - **Keep every concept and fix only which string wins.** It enforces the tangle instead of removing it; no concept goes away. - **`(name, kind)` value equality with an interning registry.** It decouples the - Python type's identity from the IR's, so it needs a registry, a `copyreg` hook and - a custom fingerprint deconstructor to paper over the gap — and still cannot give a + Python type's identity from the IR's, so it needs a name-keyed registry and a + blanket `copyreg` hook to paper over the gap — and still cannot give a nested `V2E.Local` a unique name. - **Static-only `max_neighbors` / `min_neighbors`.** Counts are not known statically: `fvm_nabla_setup.py` sizes `V2E` from the atlas mesh and ICON's skip values are @@ -783,13 +790,13 @@ raise, with why each loses: ## Relation to gt4py ADRs - **ADR 0019 (Connectivities).** The part naming `FieldOffset` as the frontend - identifier is superseded by ADR 0030; the `Connectivity` / `NeighborTable` / + identifier is superseded by ADR 0031; the `Connectivity` / `NeighborTable` / `ConnectivityType` vocabulary is kept ([What stays](#what-stays-and-why)). - **ADR 0026 (Staggered dimensions).** Its encoding is superseded by `Staggered[D]` ([above](#staggeredd)); its semantics are unchanged, and [Cartesian axis dimensions](#cartesian-axis-dimensions) states the structure they encode. -- **ADR 0029 (Dimensions as nominal types)** and **ADR 0030 (Connectivities - as types)** record this design in the gt4py tree. +- **ADR 0030 (Dimensions as nominal types)** and **ADR 0031 (Connectivities + as types; planned number)** record this design in the gt4py tree. - **ADR 0023 (build cache).** Fingerprints depend on qualified names, so the cache invalidates on module renames (Identity, rule 4). @@ -824,7 +831,7 @@ with the reasoning, so that a later reader does not reopen them. remove the one cosmetic cost of choosing which member of a pair to declare. It has to be static — it changes the integer correction `connectivity_for_cartesian_shift` bakes in, hence the emitted stencil — and it - would have to join `kind` in the dimension fingerprint, which rule 4 now + would have to be a field of `DimensionRef`, hence of the fingerprint, which rule 4 now establishes as a pattern rather than an obstacle. See [[personal/egparedes/connectivities-as-types/connectivities-as-types_staggering|the staggering appendix]]. Not in this stack. @@ -868,19 +875,20 @@ GridTools/gt4py#2898 (merged 2026-09-23) fixed the N2 leak first: unstructured shifts lower with the offset's own tag, shift lowering is type-driven so module-qualified offsets (`a(mod.V2E)`) work, and a regression matrix {shift, `neighbor_sum`} × {tag ≠ variable name, tag ≠ local-dimension name} -guards it. The rest is a stack of four GridTools/gt4py PRs, each green in CI -on its own, each based on the previous one: +guards it. The rest is a stack of four GridTools/gt4py PRs, each meant to be +green in CI on its own and based on the previous one. #2907 and the PRs above it still sit +on an earlier state of #2899, without `DimensionRef`: | PR | Branch | What | | --- | --- | --- | -| A: GridTools/gt4py#2899 | `connectivities-as-types-2-dimension-classes` | `feat[next]`: a concrete dimension is a class identified by its qualified name (ADR 0029); `codegen_name`; `CartesianAxisIndex` / `AnyCartesianAxisIndex` (both exported from `gtx`) and `Staggered[D: CartesianAxisIndex]`, with `__add__`/`__sub__` restricted to an axis statically and at runtime; interactive-`__main__` fallback; `NamedIndex` and the dimension half of the mypy plugin removed; mypy typing case `cartesian_axis_levels`; `ConstList` with `size=1` replaces the `_CONST_DIM` aliases; `AxisLiteral` stores only its tag, deriving `kind` and `dim`; printing IR never imports (`resolve_loaded`); offset tag = local dimension tag = provider key in the tree | -| B: GridTools/gt4py#2907 | `connectivities-as-types-3-neighbor-connectivity` | `feat[next]`: `NeighborConnectivity[Domain, Codomain]`, `LocalDimensionIndex` (and `DimensionKind.LOCAL` removed: a local's `kind` is `None`, localness comes from `common.is_local_dimension`, and `order_dimensions` ranks horizontal/local/vertical explicitly), `check_neighbor_table`, `local_dimension_of`, declaration fingerprinting; usable in the DSL; shared local dimensions, in the declarations and in the backends (`connectivity_key_over`, DaCe `local_dimension_size`); `NeighborTableType` and `ts.ShiftType`; pyright in the typing nox session, with `reportUnnecessaryTypeIgnoreComment: error` so a rejection that stops firing fails the run; ADR 0030 | +| A: GridTools/gt4py#2899 | `connectivities-as-types-2-dimension-classes` | `feat[next]`: a concrete dimension is a class identified by its qualified name (ADR 0030); `DimensionRef` values below the frontend, also in `AxisLiteral`, so nothing is imported from a tag; `codegen_name`; `CartesianAxisIndex` / `AnyCartesianAxisIndex` (both exported from `gtx`) and `Staggered[D: CartesianAxisIndex]`, with `__add__`/`__sub__` restricted to an axis statically and at runtime; `DimensionRange` (was `NamedRange`) and `Dimension.at`; class-identity check of call arguments; interactive-`__main__` fallback; `NamedIndex` and the dimension half of the mypy plugin removed; mypy typing case `cartesian_axis_levels`; `iterator.builtins.ConstList` (still of kind `LOCAL`) replaces the `_CONST_DIM` aliases; offset tag = local dimension tag = provider key in the tree | +| B: GridTools/gt4py#2907 | `connectivities-as-types-3-neighbor-connectivity` | `feat[next]`: `NeighborConnectivity[Domain, Codomain]`, `LocalDimensionIndex` (and `DimensionKind.LOCAL` removed: a local's `kind` is `None`, localness comes from `common.is_local_dimension`, and `order_dimensions` ranks horizontal/local/vertical explicitly), `check_neighbor_table`, `local_dimension_of`, declaration fingerprinting; usable in the DSL; shared local dimensions, in the declarations and in the backends (`connectivity_key_over`, DaCe `local_dimension_size`); `NeighborTableType` and `ts.ShiftType`; pyright in the typing nox session, with `reportUnnecessaryTypeIgnoreComment: error` so a rejection that stops firing fails the run; ADR 0031 (planned number) | | C: GridTools/gt4py#2910 | `connectivities-as-types-6-class-keyed-providers` | `feat[next]!`: the tree and docs declare connectivities as classes; class-keyed offset providers with `check_offset_provider` at every entry point; `FieldOffset` removed; `as_offset(dim, field)` restricted to an `AnyCartesianAxisIndex`; `table_types` replaces `offset_provider_type`; migration script | | D: GridTools/gt4py#2912 | `connectivities-as-types-8-typed-positions` | `refactor[next]`: `MultiDimensionIndex` and typed embedded positions | `NeighborTableType`, -`TableTypes` and `ts.ShiftType` land in B, `table_types` in C; ADR 0029 and -ADR 0030 are in A and B respectively. +`TableTypes` and `ts.ShiftType` land in B, `table_types` in C; ADR 0030 and +ADR 0031 are in A and B respectively. **ICON4Py migration.** `scripts/python/migrate_connectivities.py` (PR C) rewrites `Dimension(...)` and `FieldOffset(...)` declarations (connectivities @@ -904,7 +912,7 @@ left to ICON4Py. bit vector; the alignment convention and its antisymmetry; why extents are declared; the six axis-level alternatives and the staggering follow-ups. - [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|What type identity costs the IR, pickle and codegen]]: - the mechanics behind Identity rules 1 and 3–6 — reconstruction by import, the one + the mechanics behind Identity rules 1 and 3–6 — `DimensionRef`, the one `copyreg` hook, fingerprinting, the injective codegen mangling and the `Staggered[D]` tag grammar. - [[personal/egparedes/connectivities-as-types/connectivities-as-types_typing|Decisions made by running mypy and pyright]]: diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md index d950e1c..c573732 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md @@ -30,8 +30,8 @@ statically meaningful. [[shared/dimensions-as-types|dimensions as types]] and GridTools/gt4py#2844). Keeps independently declared same-named dimensions interchangeable and avoids the importability rule. Rejected because it decouples the Python -type's identity from the IR's, needs a registry plus `copyreg` plus a custom -fingerprint deconstructor to paper over that gap, and cannot give a nested +type's identity from the IR's, needs a name-keyed registry and a blanket +`copyreg` hook to paper over that gap, and cannot give a nested `V2E.Local` a unique name without further convention. See [[personal/egparedes/connectivities-as-types/connectivities-as-types#identity-is-the-qualified-python-name|Identity]]. **Integer type parameters for `max_neighbors`** (`LocalDimensionIndex[F: int, M: int]`). diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md index 7d8ef22..42fc07c 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md @@ -8,40 +8,38 @@ status: draft > **Appendix** to [[personal/egparedes/connectivities-as-types/connectivities-as-types|Connectivities as types]]. > The mechanics behind rules 1 and 3-6 of *Identity is the qualified Python name*: -> reconstruction by import, the one `copyreg` hook, fingerprinting, the injective +> `DimensionRef`, the one `copyreg` hook, fingerprinting, the injective > codegen mangling, and the `Staggered[D]` tag grammar. -## Rule 1 — reconstruction from the IR is an import +## Rule 1 — two levels -1. **Reconstruction from the IR is an import.** `resolve(tag)` imports the - longest importable module prefix and walks the rest as attributes (nested - classes like `V2E.Local` resolve naturally), the way `pickle` references a - class. Only where the module path ends is memoized: the attribute walk is - repeated, so a declaration redefined under the same name (a re-run - notebook cell) resolves to the new class. `AxisLiteral` stores only the tag - and derives `kind` and `dim` from it as read-only properties (the `TODO` at - `iterator/ir.py:93`); the derived `kind` is optional, since a local - dimension's is `None`; - printing IR never imports (`resolve_loaded`). `Staggered[D]` tags use the - small grammar `[]`, resolved by subscripting the owner. +1. **Nothing is imported from a tag.** `DimensionRef(module, qualname, kind, + is_cartesian_axis, base)` is frozen, interned and pickled by value. Comparing a ref + with a dimension class raises `TypeError`, since one side missed its conversion; + hash-based lookups cannot be checked and are misses. `AxisLiteral` stores the ref. + `DimensionRef.from_tag(tag, kind, is_cartesian_axis=...)` rebuilds one from text: + the pretty printer prints short names plus a header with each dimension's tag, kind + and axis flag, from which the parser rebuilds the refs. The roundtrip backend, which + runs on classes, takes them from the fields and connectivities of each call. + `Staggered[D]` tags use the small grammar `[]`. ## Rules 3-6 — registry, fingerprints, mangling, staggering 3. **No registry.** Classes pickle by reference. One narrow `copyreg` hook exists, for `Staggered[D]`, whose bracketed qualname `save_global` cannot look up; it reduces to the base dimension and re-interns. -4. **Fingerprints depend on qualified names, plus `kind`.** A dimension is - deconstructed as its by-reference name *and* its declaration-time `kind`, which - decides a field's layout order and the scan axis — so a dimension redefined under - the same name with another kind does *not* reuse artifacts. `Staggered[D]` goes +4. **Fingerprints depend on qualified names, plus the `DimensionRef`.** A dimension is + deconstructed as its by-reference name *and* its ref. The ref has the `kind`, which + decides a field's layout order and the scan axis, and the axis level + (`CartesianAxisIndex` versus `DimensionIndex`), on which index arithmetic depends — + so a dimension redefined under the same name with another of either does *not* reuse + cached stages or artifacts. `Staggered[D]` goes through its base and inherits this; its base cannot be flipped in place, since - the class is interned by base identity and its tag embeds the base tag. The axis - level (`CartesianAxisIndex` versus `DimensionIndex`) is deliberately *not* - fingerprinted: it changes what is accepted, never what is emitted. A connectivity + the class is interned by base identity and its tag embeds the base tag. A connectivity declaration is fingerprinted *additionally* by its domain, codomain, `Local` and counts. Consequently the ADR 0023 build cache invalidates on module renames. 5. **Codegen names need injective mangling.** `codegen_name(tag)` is a prefix - escape — `_`→`_u`, `.`→`_d`, `[`→`_l`, `]`→`_r` — used by gtfn, DaCe, the + escape — `_`→`_u`, `.`→`_d`, `:`→`_c`, `[`→`_l`, `]`→`_r` — used by gtfn, DaCe, the roundtrip backend and the nanobind bindings; its inverse `from_codegen_name` is used by DaCe to parse names back. The simpler "escape `__`, then replace `.`" is **not** injective (`".."` and `"_"` @@ -49,16 +47,16 @@ status: draft to length 4. 6. **Staggering is part of the dimension change.** The `_Staggered` name prefix needs the name→class lookup that type identity removes, so - `Staggered[D]` is a real class and part of ADR 0029 (PR A), together with + `Staggered[D]` is a real class and part of ADR 0030 (PR A), together with the [[personal/egparedes/connectivities-as-types/connectivities-as-types#cartesian-axis-dimensions|Cartesian axis dimensions]] its parameter is bounded on; see [[personal/egparedes/connectivities-as-types/connectivities-as-types#staggeredd|`Staggered[D]`]]. ## The `Staggered[D]` tag - **IR and serialization.** The tag is - `gt4py.next.common.Staggered[]` — the one tag that is not a - qualified name. `resolve` parses the `[]` grammar and - subscripts the owner, the IR pretty-parser accepts it, and `codegen_name` + `gt4py.next.common:Staggered[]` — the one tag that is not a + qualified name. `DimensionRef.from_tag` parses the `[]` grammar + without importing the base, the IR pretty-parser accepts it, and `codegen_name` escapes the brackets. `pickle` cannot look up a bracketed qualname, so one `copyreg` hook reduces a staggered class to its base and re-subscripts on load; fingerprints are likewise taken through the base. diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md index cc8e75e..7de8f67 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md @@ -27,7 +27,7 @@ npx -y @marp-team/marp-cli@4 --no-stdin \ One declaration for offset, local dimension and provider key -ADR 0029 (dimensions) · ADR 0030 (connectivities) +ADR 0030 (dimensions) · ADR 0031 (connectivities; planned number) > **Appendix** to [Connectivities as types](connectivities-as-types), summarising the note it is published alongside; where the two disagree the note is authoritative. Every slide links the section it compresses, and the deck adds no facts of its own. Rendering instructions are on the slide before this one. @@ -81,11 +81,11 @@ The class *contains* its local dimension and *is* its own provider key. Nothing ## Identity is the qualified Python name -`tag = f"{cls.__module__}.{cls.__qualname__}"` +`tag = f"{cls.__module__}:{cls.__qualname__}"` - the static view (nominal types) and the runtime view (`is`) agree by construction -- reconstruction from the IR is an **import**, the way `pickle` references a class -- so `` dimensions are rejected, and a redefinition is a *different* connectivity +- below the frontend a dimension is a **`DimensionRef` value**: nothing is imported from a tag +- pickling needs importable classes, so `` dimensions are rejected, and a redefinition is a *different* connectivity - the IR names a connectivity by its `offset_tag` = its local dimension's tag, so shifts, reductions and sparse arguments find one table under **one** string → [Identity](connectivities-as-types#identity-is-the-qualified-python-name) @@ -164,8 +164,8 @@ Of ten cross-object identity constraints: **six dissolve**, three collapse into | PR | Contents | | --- | --- | -| A #2899 | dimensions as classes, `Staggered[D]`, ADR 0029 | -| B #2907 | `NeighborConnectivity`, `LocalDimensionIndex`, ADR 0030 | +| A #2899 | dimensions as classes, `DimensionRef`, `Staggered[D]`, ADR 0030 | +| B #2907 | `NeighborConnectivity`, `LocalDimensionIndex`, ADR 0031 (planned) | | C #2910 | class-keyed providers, `FieldOffset` removed, migration script | | D #2912 | `MultiDimensionIndex`, typed embedded positions | diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md index 50eb4dc..34d437c 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md @@ -240,8 +240,8 @@ Numbered as in the main note's *Open questions*. readable without the declaration, the frontend and embedded shift test matrix doubles, and the keyword would have to be folded into the dimension fingerprint. That last cost is now a known quantity rather than an open hole: Identity rule 4 - fingerprints a dimension's `kind` alongside its by-reference name, so an - alignment keyword would follow the same pattern. Not in this stack. + fingerprints a dimension's `DimensionRef` alongside its by-reference name, so an + alignment would be one more field of the ref. Not in this stack. 6. **`kind`'s remaining two jobs.** Once `LOCAL` leaves the enum, `kind` is a layout sort key and a name for the scan axis. Layout is a property of the field, diff --git a/content/shared/dimensions-as-types.md b/content/shared/dimensions-as-types.md index 329c897..bc59e56 100644 --- a/content/shared/dimensions-as-types.md +++ b/content/shared/dimensions-as-types.md @@ -9,7 +9,7 @@ status: superseded > **Superseded** by > [[personal/egparedes/connectivities-as-types/connectivities-as-types|Connectivities as types]] -> (gt4py ADR 0028, GridTools/gt4py#2899), which makes a dimension a class with +> (gt4py ADR 0030, GridTools/gt4py#2899), which makes a dimension a class with > *type* identity (its qualified name) instead of the `(name, kind)` value > identity and interning registry proposed here. Kept for reference until that > proposal moves to `shared/`. From fc4b60f501b916aefd1eff3e713300a47d8d3a55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Thu, 3 Dec 2026 17:02:13 +0100 Subject: [PATCH 2/5] =?UTF-8?q?personal/egparedes:=20connectivities=20as?= =?UTF-8?q?=20types=20=E2=80=94=20layout=20order=20and=20roundtrip=20synth?= =?UTF-8?q?esis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../connectivities-as-types/connectivities-as-types.md | 3 ++- .../connectivities-as-types_identity.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md index 7107465..235c5cc 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md @@ -494,7 +494,8 @@ The self-type costs two definition-site suppressions, one per checker; P4 of `kind` **shrinks.** It carries four jobs today: `LOCAL` marks a neighbor axis; `order_dimensions` sorts by `(kind, as_non_staggered(dim).value)`, so it decides -memory layout order (constraint F4); `order_dimensions` also uses it to enforce +memory layout order (constraint F4; #2899 sorts by +kind rank, then base qualname, then base tag, so the module does not decide the order); `order_dimensions` also uses it to enforce at most one `LOCAL` dimension; and `VERTICAL` names the scan axis and, by convention, the undecomposed one. The first and third are now class facts — `kind == LOCAL` iff `issubclass(d, LocalDimensionIndex)` — so **`LOCAL` leaves the diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md index 42fc07c..0526e31 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md @@ -20,7 +20,8 @@ status: draft `DimensionRef.from_tag(tag, kind, is_cartesian_axis=...)` rebuilds one from text: the pretty printer prints short names plus a header with each dimension's tag, kind and axis flag, from which the parser rebuilds the refs. The roundtrip backend, which - runs on classes, takes them from the fields and connectivities of each call. + runs on classes, takes them from the fields and connectivities of each call, and synthesizes a class + from the ref only for a dimension none of them has. `Staggered[D]` tags use the small grammar `[]`. ## Rules 3-6 — registry, fingerprints, mangling, staggering From ebe1301a8c1dd4d0abbb17148208e47ae26d69a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Fri, 4 Dec 2026 00:29:08 +0100 Subject: [PATCH 3/5] =?UTF-8?q?personal/egparedes:=20connectivities=20as?= =?UTF-8?q?=20types=20=E2=80=94=20Domain=20truthiness,=20periodic=20grids,?= =?UTF-8?q?=20layout=20tie-break?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../connectivities-as-types.md | 29 +++++++++++-------- .../connectivities-as-types_staggering.md | 20 +++++++------ 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md index 235c5cc..5f5d0ca 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md @@ -379,7 +379,8 @@ stated as rules: 2. **Types must be importable to be pickled.** Only the connectivities of an offset provider still carry classes into a compile job. `` in a qualname is rejected at class creation (for dimensions and connectivities), as an early - heuristic; pickle's own `save_global` stays the authoritative check. Interactive + heuristic: a tag is the qualified name, which must be unique and lets the class + be pickled; pickle's own `save_global` stays the authoritative check. Interactive `__main__` (REPL, notebooks, `python -c`) matters — every notebook declares its dimensions there — so the process-pool runner (`BUILD_JOBS_MODE=process`) detects a job that references such a class and, with a warning, @@ -417,11 +418,13 @@ stated as rules: `NotImplemented` when the right operand is a dimension, so Python falls back to `is` and `I == J` is always a `bool`. It builds a `Domain` only for an *integral* right operand — `I == 5` — which is the one documented exception to "equality is - `is`", and `Domain.__bool__` raises, so a `Domain` can never be mistaken for a - truth value. The residual hazard is narrow and accepted: a dict holding both an - integer key and a dimension-class key whose hashes collide would reach - `bool(Domain)`. Class-keyed providers hold only classes and tag strings, and a - `str` compares unequal to a class, so they cannot. + `is`". A `Domain` is a non-empty `Sequence`, hence truthy, so a container that + mixes integers and dimension classes misbehaves: `I in [5]` is `True` and + `[3, 4].count(I) == 2`. The hazard is inherited from `main` and out of scope here; + a raising `Domain.__bool__` would be a separate change, after a check of the + `if domain:` call sites, where truthiness today means "has a dimension". + Class-keyed providers hold only classes and tag strings, and a `str` compares + unequal to a class, so they are not affected. 9. **Same-named declarations are different connectivities.** Two declarations with the same qualified name from different modules, or a redefinition, are simply different classes; no warning is issued, and @@ -495,7 +498,7 @@ The self-type costs two definition-site suppressions, one per checker; P4 of `kind` **shrinks.** It carries four jobs today: `LOCAL` marks a neighbor axis; `order_dimensions` sorts by `(kind, as_non_staggered(dim).value)`, so it decides memory layout order (constraint F4; #2899 sorts by -kind rank, then base qualname, then base tag, so the module does not decide the order); `order_dimensions` also uses it to enforce +kind rank, then base qualname, then base tag, so the module only breaks ties between equal qualnames); `order_dimensions` also uses it to enforce at most one `LOCAL` dimension; and `VERTICAL` names the scan axis and, by convention, the undecomposed one. The first and third are now class facts — `kind == LOCAL` iff `issubclass(d, LocalDimensionIndex)` — so **`LOCAL` leaves the @@ -846,11 +849,13 @@ with the reasoning, so that a later reader does not reopen them. §4d). 7. **A cell `degree` on the axis.** Left out because **nothing consumes it** until an exterior-calculus surface exists; a static `degree=0|1` is itself perfectly - well defined and needs no periodicity. The ranges do *not* substitute for it: a - periodic axis gives both classes `[0, n)` under either assignment and halo - padding makes the widths arbitrary, so degree is not inferable from extents in - general. The dependency runs the other way — *deriving extents* needs the degree - plus a periodicity and halo policy. A degree is *canonical* for + well defined. The axis is the infinite integer line (ADR 0030); a `Domain` selects + a bounded range of it, and periodicity is a wrap-around rule of the grid, not of + the dimension. The ranges do *not* substitute for a degree: on a periodic grid both + classes can be `[0, n)` under either assignment and halo padding makes the widths + arbitrary, so degree is not inferable from extents in general. The dependency + runs the other way — *deriving extents* needs the degree plus the grid's + wrap-around and halo policy. A degree is *canonical* for a mesh location and only *declarational* for an axis, so it belongs on the `LocationIndex` of the next item; see [[personal/egparedes/connectivities-as-types/connectivities-as-types_staggering|the staggering appendix]] and [[personal/egparedes/connectivities-as-types/connectivities-as-types_conventions|conventions]] §4a. diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md index 34d437c..5294729 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md @@ -18,9 +18,10 @@ status: draft A **Cartesian axis** is an index space with integer index arithmetic and exactly one staggered partner — the dimensions `CartesianConnectivity` acts on. -Read one axis of a Cartesian grid as a -1-dimensional CW complex — a path when the axis is bounded, a cycle when it is -periodic. Such a complex has exactly two cell classes, of degree 0 and 1, and a +The axis itself is the two-way infinite integer line (ADR 0030); read it as a +1-dimensional CW complex. A `Domain` selects a bounded range of it, which is a +path complex; a periodic grid is that range plus a wrap-around rule owned by the +grid, not a property of the dimension. Such a complex has exactly two cell classes, of degree 0 and 1, and a declared axis together with its `Staggered[·]` name those two classes. `Staggered` is the **involution that swaps them**. The types do not say which class has degree 0, and they need not: the ADR 0026 position convention @@ -99,7 +100,7 @@ a reference implementation and on boundary index ranges. ## 3. Extents **Extents are declared, never derived.** A path complex has `n` 0-cells and -`n - 1` 1-cells; a cycle has `n` and `n`. So the two members of a pair do not in +`n - 1` 1-cells; with a periodic wrap-around the grid may use `n` and `n`. So the two members of a pair do not in general have the same range, and for a bounded, halo-free complex *which one is wider is the degree assignment* (periodicity or halo padding destroys that correspondence — see §7): @@ -110,8 +111,9 @@ the interfaces run `[0, n+1)`. Both are expressible without any new type-level concept because a `Domain` holds absolute `UnitRange(start, stop)`s rather than sizes — see [[personal/havogt/field-data-protocol/field-data-protocol|the field data protocol]] -for why absolute addressing is the right domain model — and the periodic case -needs nothing extra, the two ranges simply coincide in size. The invariant a grid +for why absolute addressing is the right domain model — and a periodic grid +needs nothing extra from the dimension: the two ranges coincide in size and the +wrap-around belongs to the grid's boundary or halo handling. The invariant a grid builder owes is that the two ranges *interleave*; their sizes then differ by at most one when the complex is closed, and halo extension relaxes even that (two of SGRID's four bounded cases, `low` and `high`, have equal sizes). An absolute range @@ -268,10 +270,10 @@ Numbered as in the main note's *Open questions*. exterior-calculus surface exists (Proposal 1 of [[personal/egparedes/discretization-independent-fd-syntax|the surface-syntax note]]). Absolute ranges do **not** determine the - degree in general: a periodic axis gives both classes `[0, n)` under either + degree in general: on a periodic grid both classes can be `[0, n)` under either assignment, and halo padding makes the relative widths arbitrary. A static degree - needs no periodicity and would not be ill-defined — it is *deriving extents* that - needs the degree together with a periodicity and halo policy. Revisit if that + is a property of the infinite line and would not be ill-defined — it is *deriving + extents* that needs the degree together with the grid's wrap-around and halo policy. Revisit if that surface lands — but note that a degree is *canonical* for a mesh location and only *declarational* for a Cartesian axis, so it belongs on the `LocationIndex` of the main note's item 8 rather than here From 6d529f2acd7d7488ee9d1800a70b6ffdda10c1e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Fri, 4 Dec 2026 16:30:09 +0100 Subject: [PATCH 4/5] =?UTF-8?q?personal/egparedes:=20connectivities=20as?= =?UTF-8?q?=20types=20=E2=80=94=20dimensions=20compare=20and=20pickle=20by?= =?UTF-8?q?=20ref,=20as=20in=20gt4py#2899?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../connectivities-as-types.md | 134 +++++++++--------- .../connectivities-as-types_alternatives.md | 7 +- .../connectivities-as-types_identity.md | 33 ++--- .../connectivities-as-types_slides.md | 5 +- .../connectivities-as-types_staggering.md | 6 +- 5 files changed, 96 insertions(+), 89 deletions(-) diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md index 5f5d0ca..896b7ce 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md @@ -3,7 +3,7 @@ title: "Connectivities as types: one declaration for offset, local dimension and author: egparedes tags: [type-system, type-checking, dimensions, local-dimensions, connectivities, offset-provider, unstructured, neighbor-sum, reduction, frontend, foast, gtir, embedded, gtfn, dace, nominal-types, dependent-types, metaclass, serialization, fingerprint, staggering, axis-dimensions, cw-complex, exterior-calculus, domain, dimension-kind, ugrid, sgrid, migration, adr, tech-debt, shared-local-dimensions, implemented] created: 2026-09-17 -updated: 2026-12-03 +updated: 2026-12-04 status: draft --- @@ -57,7 +57,7 @@ status: draft > typed staggering]], whose Part II also proposed the `Staggered[D]` shape > used here. It **supersedes** [[shared/dimensions-as-types|Dimensions as > types]]: the dimension design below (ADR 0030) replaces that note's -> `(name, kind)` value identity and interning registry with type identity, and +> `(name, kind)` value identity and interning registry with qualified-name identity, and > is stated here in full. It overlaps with > [[personal/havogt/mesh-and-first-class-halos/mesh-and-first-class-halos|A mesh concept with > first-class halos]], which proposes replacing the same `offset_provider` @@ -154,7 +154,7 @@ what is one idea — *a mapping between two index spaces, plus a name for it*. | `DimensionRef` | an immutable, interned value naming a dimension class (module, qualname, `kind`, whether it is a Cartesian axis, staggered base); what type specifications, the IR and the backends carry instead of the class (see [Identity](#identity-is-the-qualified-python-name)) | `Dimension` instances below the frontend | | `DimensionRange` | a range on a dimension, `KDim.at(0, 10)`; a point is an index, `KDim(3)`. `field[KDim(5):KDim(10)]` is slice syntax for a range | `NamedRange` (`NamedIndex` for a point) | | `CartesianAxisIndex(AnyCartesianAxisIndex)` | a **declared Cartesian axis**: an index space with integer index arithmetic and exactly one staggered partner (see [Cartesian axis dimensions](#cartesian-axis-dimensions)). `AnyCartesianAxisIndex` is either cell class of such an axis, declared or derived | — (new; today `kind != LOCAL` is the nearest approximation, and it does not separate a Cartesian axis from a mesh location) | -| `Staggered[D: CartesianAxisIndex]` | the axis's derived partner, at the half-integer positions of `D`; a real, interned class (see [`Staggered[D]`](#staggeredd)) | the `_Staggered` name prefix | +| `Staggered[D: CartesianAxisIndex]` | the axis's derived partner, at the half-integer positions of `D`; a real class, built once when `D` is declared (see [`Staggered[D]`](#staggeredd)) | the `_Staggered` name prefix | | `LocalDimensionIndex(DimensionIndex)` | a local dimension: **owned** (declared nested in, or adopted by, its connectivity), or **owner-less** (optionally with `size=n`, which sets `max_neighbors = min_neighbors = n`); carries the neighbor counts | `Dimension(..., kind=LOCAL)`, `_CONST_DIM` | | `NeighborConnectivity[Domain, Codomain]` | the **static part of a neighbor table's type**: the shift handle in DSL code and the provider key; contains its `Local`; holds no data and is never instantiated | `FieldOffset`, the `V2EDim` convention | | `MultiDimensionIndex[D, *Ls]` | a position in the product of a primary and local dimensions, a tuple of indices; user-facing, nothing in the toolchain requires it | — (new; the iterator-embedded position dicts are keyed by dimension classes, not name strings) | @@ -243,7 +243,8 @@ class DimensionMeta(type): def tag(cls) -> Tag: # identity, and the IR spelling return f"{cls.__module__}:{cls.__qualname__}" kind: DimensionKind - __hash__ = type.__hash__ # __eq__ stays for `I == 5` -> Domain + def __eq__(cls, other): ... # equal refs: same dimension; `I == 5` -> Domain + def __hash__(cls) -> int: ... # from the ref def __add__( # I + 1, K + 0.5; a Cartesian axis only cls: type[AnyCartesianAxisIndex], offset: int | float ) -> Connectivity: ... @@ -276,8 +277,8 @@ class LocalDimensionIndex(DimensionIndex): # kind is LOCAL; `kind=LOCAL` els class MultiDimensionIndex[D: DimensionIndex, *Ls](tuple[D, *Ls]): ... # shape checked at runtime -# the TYPE_CHECKING form; at runtime a metaclass subscription builds the -# interned classes, since a PEP 695 alias fails `issubclass` (ADR 0026) +# the TYPE_CHECKING form; at runtime each declared axis builds its partner +# class once, since a PEP 695 alias fails `issubclass` (ADR 0026) class Staggered[D: CartesianAxisIndex](AnyCartesianAxisIndex): ... Staggered[KDim] # KDim's derived partner; @@ -354,46 +355,48 @@ already names a buffer's origin in gt4py (`__gt_origin__`). ### Identity is the qualified Python name -A dimension's or connectivity's identity is the Python type; its tag is +A dimension's or connectivity's identity is its qualified Python name; its tag is `f"{cls.__module__}:{cls.__qualname__}"` (except `Staggered[D]`, whose tag embeds its base's full tag, rule 1; a connectivity is *named in the IR* by its -`offset_tag`, rule 7). The static view (checkers see nominal types) and the -runtime view (equality is `is`) agree by construction, and the tag is a -valid, unique IR string. This is the point on which this note supersedes +`offset_tag`, rule 7). Two dimension classes are the same dimension iff their +`DimensionRef`s are equal (rule 8), so the tag is a valid, unique IR string. This is +the point on which this note supersedes [[shared/dimensions-as-types|dimensions as types]] and GridTools/gt4py#2844, -which chose `(name, kind)` value equality plus an interning registry so that -the test tree's many independently declared `IDim`s stay interchangeable. -Under value equality the `typing` subscription cache aliases -`Field[Dims[I]] is Field[Dims[I2]]` for two distinct same-named classes, so -the static and runtime views disagree exactly there; under type identity -that aliasing disappears. The cost is that the many function-local dummy +which chose `(name, kind)` value equality on the *unqualified* name plus an interning +registry so that the test tree's many independently declared `IDim`s stay +interchangeable; under it, same-named dimensions from two modules are one dimension. +The cost is that the many function-local dummy dimensions in `tests/next_tests` move to module level. The consequences, stated as rules: -1. **Two levels, and nothing is imported from a tag.** Classes are the identity at the - Python edge: user code, embedded execution and program calls. Below it, type +1. **Two levels, and nothing is imported from a tag.** Classes are what the + Python edge works on: user code, embedded execution and program calls. Below it, type specifications, the IR and the backends carry a `DimensionRef`, an interned value equal to another one if all its fields are; `dimension_ref(cls)` is the only conversion. `AxisLiteral` stores the ref, and its `value` (the tag) and `kind` are read-only properties of it. Details, and the `Staggered[D]` grammar: [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. -2. **Types must be importable to be pickled.** Only the connectivities of an offset - provider still carry classes into a compile job. `` in a qualname is - rejected at class creation (for dimensions and connectivities), as an early - heuristic: a tag is the qualified name, which must be unique and lets the class - be pickled; pickle's own `save_global` stays the authoritative check. Interactive - `__main__` (REPL, notebooks, `python -c`) matters — every notebook declares its - dimensions there — so the process-pool runner (`BUILD_JOBS_MODE=process`) - detects a job that references such a class and, with a warning, - **compiles it in the calling thread** instead of failing in a spawn worker. -3. **No registry.** Classes pickle by reference. The one narrow `copyreg` hook is - for `Staggered[D]`, whose bracketed qualname `save_global` cannot look up. -4. **Fingerprints depend on qualified names, plus the `DimensionRef`.** A dimension is - deconstructed as its by-reference name *and* its ref, i.e. also its `kind` and - whether it is a Cartesian axis, so redefining one under the same name with another - kind or axis level does invalidate artifacts; a staggered dimension - is fingerprinted through its base. `base` cannot be flipped in place at all — - `Staggered[K]` is interned by base identity and its tag embeds the base tag, so a - different base is a different class. The axis level is included because the +2. **Dimensions are declared at module level, with a `class` statement.** `` + in a qualname is rejected at class creation (for dimensions and connectivities): a + tag is the qualified name, which must be unique and lets the class be pickled. A + plain call of the metaclass is rejected too, as a guard against accidents. The body + of a dimension class is empty apart from a docstring and `kind`, since a class + rebuilt from its ref has nothing else. +3. **No registry; a dimension pickles as its ref.** A `copyreg` reduction on the + dimension metaclasses (`Staggered[D]` included) pickles every dimension class as + its `DimensionRef`. Loading returns the already loaded class with that ref (a + `sys.modules` lookup, no import), else a synthesized equal one + (`common.synthesize_dimension`), so a dimension declared in an interactive + `__main__` (REPL, notebook, `python -c`) reaches a compile worker like any other. + By-value picklers such as `cloudpickle` cannot rebuild a dimension. The + process-pool runner still compiles in the calling thread, with a warning, a job + that references another class of an interactive `__main__`. +4. **Fingerprints are the `DimensionRef`.** A dimension is deconstructed as its ref + only — qualified name, `kind`, whether it is a Cartesian axis and, for a staggered + one, its base — so a synthesized stand-in fingerprints like the class, a re-run + cell reuses artifacts unless the ref changed, and redefining a dimension with + another kind or axis level invalidates them. `base` cannot be flipped in place at + all: `Staggered[K]` is built from `K` and its tag embeds the base tag, so a + different base is a different dimension. The axis level is included because the frontend cache uses this fingerprint and index arithmetic depends on it. A connectivity declaration is fingerprinted *additionally* by its domain, codomain, `Local` and counts. Either way the ADR 0023 cache invalidates on module renames. @@ -401,11 +404,11 @@ stated as rules: escape (`_`→`_u`, `.`→`_d`, `:`→`_c`, `[`→`_l`, `]`→`_r`); the obvious alternative is not injective. 6. **Staggering is part of the dimension change.** The `_Staggered` name prefix - needs the name→class lookup that type identity removes, so `Staggered[D]` is a + needs a name→class lookup that qualified-name identity removes, so `Staggered[D]` is a real class and part of ADR 0030 (PR A), with its parameter bounded on a declared [Cartesian axis](#cartesian-axis-dimensions). - Rules 3–6 in full — the hook, the fingerprint deconstructors, the exhaustive + Rules 3–6 in full — pickling, the fingerprint deconstructors, the exhaustive mangling test and the `_Staggered` history — are in [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. 7. **The IR names a connectivity by its `offset_tag`.** That is its local dimension's tag when it declares the local dimension: shifts, reductions @@ -414,11 +417,13 @@ stated as rules: *sharing* another one's local dimension is named by its own tag, since the local tag already names the owner's table; for that case the backends have a fallback lookup, `connectivity_key_over` (see *The local dimension*). -8. **Equality is identity for dimension operands.** `DimensionMeta.__eq__` returns - `NotImplemented` when the right operand is a dimension, so Python falls back to - `is` and `I == J` is always a `bool`. It builds a `Domain` only for an *integral* - right operand — `I == 5` — which is the one documented exception to "equality is - `is`". A `Domain` is a non-empty `Sequence`, hence truthy, so a container that +8. **Dimension classes compare by ref.** `I == J` is a `bool`, `True` iff their + `DimensionRef`s are equal; `hash` follows. So a redefined class (a re-run cell, + `importlib.reload`) and a synthesized stand-in are the same dimension as the + original, while `is`, `isinstance`, `issubclass` and `match` keep Python's meaning. + Class identity is a rejected alternative in ADR 0030: rejecting a redefined class + in user code would need a separate check at every program call. `==` builds a + `Domain` only for an *integral* right operand — `I == 5` (ADR 22). A `Domain` is a non-empty `Sequence`, hence truthy, so a container that mixes integers and dimension classes misbehaves: `I in [5]` is `True` and `[3, 4].count(I) == 2`. The hazard is inherited from `main` and out of scope here; a raising `Domain.__bool__` would be a separate change, after a check of the @@ -429,10 +434,9 @@ stated as rules: declarations with the same qualified name from different modules, or a redefinition, are simply different classes; no warning is issued, and `check_neighbor_table` hints "was the declaration redefined?" when a table - built for one is bound to the other. For dimensions, a re-run notebook cell gives - an *equal* ref for a *new* class, so a call compares the classes of its arguments - with the ones the definition declares, by identity and under `__debug__` only; two - different refs with one tag in a program are an error. + built for one is bound to the other. Dimensions differ here (rule 8): a + redefinition with an equal ref is the same dimension; two different refs with one + tag in a program are an error. ### Cartesian axis dimensions @@ -530,10 +534,9 @@ ADR 0026 — the position convention, the shift rule and the backend treatment prefix on the dimension name to a class, whose parameter is the declared axis of [Cartesian axis dimensions](#cartesian-axis-dimensions). -- **Runtime representation.** `Staggered[K]` is a real, interned class: - `Staggered` has a metaclass whose `__getitem__` builds one class per base - and caches it by base identity (with `setdefault`, so concurrent - compilation threads see one class). `Staggered[K]`'s only base is `Staggered`, +- **Runtime representation.** `Staggered[K]` is a real class, built once when + `K` is declared and kept on it, so `Staggered[K]` always returns the same class + without a global cache. `Staggered[K]`'s only base is `Staggered`, which derives from `AnyCartesianAxisIndex` — so it is an axis by inheritance and deliberately *not* a subclass of `K`, so a `Field[Dims[Staggered[K]]]` is rejected where a `Field[Dims[K]]` is required; it has `base = K` and `K`'s @@ -572,9 +575,9 @@ of [Cartesian axis dimensions](#cartesian-axis-dimensions). its staggered counterpart in one field or domain, and `order_dimensions` orders by the base, so a staggered field has the layout of its base. - **IR, serialization and fingerprints.** The tag is - `gt4py.next.common:Staggered[]` — the one tag that is not a - qualified name. Its grammar, the `copyreg` hook and fingerprinting through - the base are in [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. + `gt4py.next.common.dimensions:Staggered[]` (the module where `Staggered` + is declared) — the one tag that is not a qualified name. Its grammar, pickling + and fingerprinting through the base are in [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. - **Backends.** gtfn emits the staggered tag as a C++ alias of its base tag (`_add_staggered_aliases`), since its shift primitive can offset along an axis but not rename it. DaCe names map variables by the base @@ -742,7 +745,7 @@ tables assign different neighbors to the same domain element. The model: | Embedded iterator | positions keyed by name strings; `SparseTag` | positions keyed by dimension classes; `SparseAxis(dim)` | | gtfn | `dim.value` lookups; `TagDefinition` per tag and per `neighbor_dim` | still a `TagDefinition` per offset tag (and per differing `neighbor_dim`, i.e. for sharers), named by `codegen_name(tag)`; sparse-argument lookups through `connectivity_key_over` | | DaCe | ~10 `offset_type.value` lookups; `Dimension(offset, LOCAL)` synthesized | `codegen_name` for array/symbol names; `connectivity_key_over`; a local dimension sized from its own table (`local_dimension_size`); no synthesis | -| roundtrip backend | emits `gtx.Dimension("")` / `offset("")` as source text | binds `` axis names to the classes of the call's fields and connectivities (synthesized from the ref only for a dimension none of them has), and emits ` = offset("")` for offsets | +| roundtrip backend | emits `gtx.Dimension("")` / `offset("")` as source text | declares each axis itself, ` = common.synthesize_dimension(DimensionRef(...))`, equal to the class of the call's fields, and emits ` = offset("")` for offsets | | Provider | `Mapping[str, NeighborTable]`; `offset_provider_type: Mapping[str, NeighborConnectivityType]` | public: `{V2E: table}`, and `table_types={V2E: NeighborTableType(...)}` (`TableTypesLike`, normalized to `TableTypes = Mapping[Tag, NeighborTableType]`) for ahead-of-time compilation (a dotted tag string is also accepted; the type stays `Mapping[Any, …]`); internal: keyed by `offset_tag`, normalized at the entry points; no deprecation window (a migration script for ICON4Py instead) | ### What it deletes @@ -782,10 +785,9 @@ raise, with why each loses: - **Keep every concept and fix only which string wins.** It enforces the tangle instead of removing it; no concept goes away. -- **`(name, kind)` value equality with an interning registry.** It decouples the - Python type's identity from the IR's, so it needs a name-keyed registry and a - blanket `copyreg` hook to paper over the gap — and still cannot give a - nested `V2E.Local` a unique name. +- **`(name, kind)` value equality with an interning registry.** Same-named + dimensions declared in two modules become interchangeable, it needs a name-keyed + registry, and it cannot give a nested `V2E.Local` a unique name. - **Static-only `max_neighbors` / `min_neighbors`.** Counts are not known statically: `fvm_nabla_setup.py` sizes `V2E` from the atlas mesh and ICON's skip values are configuration-dependent, so a static count forces duplicate classes or always-on @@ -882,12 +884,16 @@ shifts lower with the offset's own tag, shift lowering is type-driven so module-qualified offsets (`a(mod.V2E)`) work, and a regression matrix {shift, `neighbor_sum`} × {tag ≠ variable name, tag ≠ local-dimension name} guards it. The rest is a stack of four GridTools/gt4py PRs, each meant to be -green in CI on its own and based on the previous one. #2907 and the PRs above it still sit -on an earlier state of #2899, without `DimensionRef`: +green in CI on its own and based on the previous one, on top of two preparation PRs: +GridTools/gt4py#3087 (`connectivities-as-types-1-preparation`: open named slices, +the `cartesian_shift` helper and other preparations) and GridTools/gt4py#3088 +(`connectivities-as-types-1b-mechanical-renames`: `NamedRange` → `DimensionRange`), +both below #2899. #2907 and the PRs above it still sit on an earlier state of #2899, +without `DimensionRef`: | PR | Branch | What | | --- | --- | --- | -| A: GridTools/gt4py#2899 | `connectivities-as-types-2-dimension-classes` | `feat[next]`: a concrete dimension is a class identified by its qualified name (ADR 0030); `DimensionRef` values below the frontend, also in `AxisLiteral`, so nothing is imported from a tag; `codegen_name`; `CartesianAxisIndex` / `AnyCartesianAxisIndex` (both exported from `gtx`) and `Staggered[D: CartesianAxisIndex]`, with `__add__`/`__sub__` restricted to an axis statically and at runtime; `DimensionRange` (was `NamedRange`) and `Dimension.at`; class-identity check of call arguments; interactive-`__main__` fallback; `NamedIndex` and the dimension half of the mypy plugin removed; mypy typing case `cartesian_axis_levels`; `iterator.builtins.ConstList` (still of kind `LOCAL`) replaces the `_CONST_DIM` aliases; offset tag = local dimension tag = provider key in the tree | +| A: GridTools/gt4py#2899 | `connectivities-as-types-2-dimension-classes` | `feat[next]`: a concrete dimension is a class identified by its qualified name (ADR 0030); `DimensionRef` values below the frontend, also in `AxisLiteral`, so nothing is imported from a tag; `codegen_name`; `CartesianAxisIndex` / `AnyCartesianAxisIndex` (both exported from `gtx`) and `Staggered[D: CartesianAxisIndex]`, with `__add__`/`__sub__` restricted to an axis statically and at runtime; `Dimension.at`; dimension classes equal by ref and pickled as refs (`synthesize_dimension`); `NamedIndex` and the dimension half of the mypy plugin removed; mypy typing case `cartesian_axis_levels`; `iterator.builtins.ConstList` (still of kind `LOCAL`) replaces the `_CONST_DIM` aliases; offset tag = local dimension tag = provider key in the tree | | B: GridTools/gt4py#2907 | `connectivities-as-types-3-neighbor-connectivity` | `feat[next]`: `NeighborConnectivity[Domain, Codomain]`, `LocalDimensionIndex` (and `DimensionKind.LOCAL` removed: a local's `kind` is `None`, localness comes from `common.is_local_dimension`, and `order_dimensions` ranks horizontal/local/vertical explicitly), `check_neighbor_table`, `local_dimension_of`, declaration fingerprinting; usable in the DSL; shared local dimensions, in the declarations and in the backends (`connectivity_key_over`, DaCe `local_dimension_size`); `NeighborTableType` and `ts.ShiftType`; pyright in the typing nox session, with `reportUnnecessaryTypeIgnoreComment: error` so a rejection that stops firing fails the run; ADR 0031 (planned number) | | C: GridTools/gt4py#2910 | `connectivities-as-types-6-class-keyed-providers` | `feat[next]!`: the tree and docs declare connectivities as classes; class-keyed offset providers with `check_offset_provider` at every entry point; `FieldOffset` removed; `as_offset(dim, field)` restricted to an `AnyCartesianAxisIndex`; `table_types` replaces `offset_provider_type`; migration script | | D: GridTools/gt4py#2912 | `connectivities-as-types-8-typed-positions` | `refactor[next]`: `MultiDimensionIndex` and typed embedded positions | @@ -918,8 +924,8 @@ left to ICON4Py. bit vector; the alignment convention and its antisymmetry; why extents are declared; the six axis-level alternatives and the staggering follow-ups. - [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|What type identity costs the IR, pickle and codegen]]: - the mechanics behind Identity rules 1 and 3–6 — `DimensionRef`, the one - `copyreg` hook, fingerprinting, the injective codegen mangling and the + the mechanics behind Identity rules 1 and 3–6 — `DimensionRef`, + pickling as a ref, fingerprinting, the injective codegen mangling and the `Staggered[D]` tag grammar. - [[personal/egparedes/connectivities-as-types/connectivities-as-types_typing|Decisions made by running mypy and pyright]]: why `Local` is annotated nowhere and must be a `TypeAlias` when shared, what the diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md index c573732..3e2a42e 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md @@ -28,10 +28,9 @@ statically meaningful. **`(name, kind)` value equality with an interning registry** (the design of [[shared/dimensions-as-types|dimensions as types]] and GridTools/gt4py#2844). -Keeps independently declared same-named dimensions interchangeable and -avoids the importability rule. Rejected because it decouples the Python -type's identity from the IR's, needs a name-keyed registry and a blanket -`copyreg` hook to paper over that gap, and cannot give a nested +Keeps independently declared same-named dimensions interchangeable. +Rejected because same-named dimensions from two modules become one, it needs a +name-keyed registry, and it cannot give a nested `V2E.Local` a unique name without further convention. See [[personal/egparedes/connectivities-as-types/connectivities-as-types#identity-is-the-qualified-python-name|Identity]]. **Integer type parameters for `max_neighbors`** (`LocalDimensionIndex[F: int, M: int]`). diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md index 0526e31..54f61b1 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md @@ -8,7 +8,7 @@ status: draft > **Appendix** to [[personal/egparedes/connectivities-as-types/connectivities-as-types|Connectivities as types]]. > The mechanics behind rules 1 and 3-6 of *Identity is the qualified Python name*: -> `DimensionRef`, the one `copyreg` hook, fingerprinting, the injective +> `DimensionRef`, pickling as a ref, fingerprinting, the injective > codegen mangling, and the `Staggered[D]` tag grammar. ## Rule 1 — two levels @@ -20,34 +20,36 @@ status: draft `DimensionRef.from_tag(tag, kind, is_cartesian_axis=...)` rebuilds one from text: the pretty printer prints short names plus a header with each dimension's tag, kind and axis flag, from which the parser rebuilds the refs. The roundtrip backend, which - runs on classes, takes them from the fields and connectivities of each call, and synthesizes a class - from the ref only for a dimension none of them has. + runs on classes, declares each dimension in its generated source with + `common.synthesize_dimension(DimensionRef(...))`, a class equal to the original. `Staggered[D]` tags use the small grammar `[]`. ## Rules 3-6 — registry, fingerprints, mangling, staggering -3. **No registry.** Classes pickle by reference. One narrow `copyreg` hook - exists, for `Staggered[D]`, whose bracketed qualname `save_global` cannot - look up; it reduces to the base dimension and re-interns. -4. **Fingerprints depend on qualified names, plus the `DimensionRef`.** A dimension is - deconstructed as its by-reference name *and* its ref. The ref has the `kind`, which +3. **No registry.** A `copyreg` reduction on both dimension metaclasses pickles every + dimension class, `Staggered[D]` included, as its `DimensionRef`; loading returns the + loaded class with that ref (a `sys.modules` lookup, no import), else + `synthesize_dimension(ref)`. By-value picklers such as `cloudpickle` bypass it and + cannot rebuild a dimension. +4. **Fingerprints are the `DimensionRef`.** A dimension is deconstructed as its ref + only, so a synthesized stand-in fingerprints like the class. The ref has the `kind`, which decides a field's layout order and the scan axis, and the axis level (`CartesianAxisIndex` versus `DimensionIndex`), on which index arithmetic depends — so a dimension redefined under the same name with another of either does *not* reuse cached stages or artifacts. `Staggered[D]` goes through its base and inherits this; its base cannot be flipped in place, since - the class is interned by base identity and its tag embeds the base tag. A connectivity + the class is built from its base and its tag embeds the base tag. A connectivity declaration is fingerprinted *additionally* by its domain, codomain, `Local` and counts. Consequently the ADR 0023 build cache invalidates on module renames. 5. **Codegen names need injective mangling.** `codegen_name(tag)` is a prefix escape — `_`→`_u`, `.`→`_d`, `:`→`_c`, `[`→`_l`, `]`→`_r` — used by gtfn, DaCe, the - roundtrip backend and the nanobind bindings; its inverse - `from_codegen_name` is used by DaCe to parse names back. The simpler + roundtrip backend and the nanobind bindings. There is no inverse: DaCe gets the + provider keys of its connectivities passed in. The simpler "escape `__`, then replace `.`" is **not** injective (`".."` and `"_"` collide); the prefix escape is tested exhaustively over its alphabet up to length 4. 6. **Staggering is part of the dimension change.** The `_Staggered` name - prefix needs the name→class lookup that type identity removes, so + prefix needs a name→class lookup that qualified-name identity removes, so `Staggered[D]` is a real class and part of ADR 0030 (PR A), together with the [[personal/egparedes/connectivities-as-types/connectivities-as-types#cartesian-axis-dimensions|Cartesian axis dimensions]] its parameter is bounded on; see [[personal/egparedes/connectivities-as-types/connectivities-as-types#staggeredd|`Staggered[D]`]]. @@ -55,9 +57,8 @@ status: draft ## The `Staggered[D]` tag - **IR and serialization.** The tag is - `gt4py.next.common:Staggered[]` — the one tag that is not a + `gt4py.next.common.dimensions:Staggered[]` — the one tag that is not a qualified name. `DimensionRef.from_tag` parses the `[]` grammar without importing the base, the IR pretty-parser accepts it, and `codegen_name` - escapes the brackets. `pickle` cannot look up a bracketed qualname, so one - `copyreg` hook reduces a staggered class to its base and re-subscripts on - load; fingerprints are likewise taken through the base. + escapes the brackets. Pickling goes through the ref, whose `base` rebuilds the + partner on load; fingerprints are likewise taken through the base. diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md index 7de8f67..544cc3e 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md @@ -83,9 +83,9 @@ The class *contains* its local dimension and *is* its own provider key. Nothing `tag = f"{cls.__module__}:{cls.__qualname__}"` -- the static view (nominal types) and the runtime view (`is`) agree by construction +- dimension classes with equal `DimensionRef`s are the same dimension: a re-run cell is no new dimension - below the frontend a dimension is a **`DimensionRef` value**: nothing is imported from a tag -- pickling needs importable classes, so `` dimensions are rejected, and a redefinition is a *different* connectivity +- a dimension pickles as its ref, so notebook dimensions reach compile workers; `` dimensions are rejected, and a redefined connectivity is a *different* connectivity - the IR names a connectivity by its `offset_tag` = its local dimension's tag, so shifts, reductions and sparse arguments find one table under **one** string → [Identity](connectivities-as-types#identity-is-the-qualified-python-name) @@ -164,6 +164,7 @@ Of ten cross-object identity constraints: **six dissolve**, three collapse into | PR | Contents | | --- | --- | +| #3087, #3088 | preparations, `NamedRange` → `DimensionRange` | | A #2899 | dimensions as classes, `DimensionRef`, `Staggered[D]`, ADR 0030 | | B #2907 | `NeighborConnectivity`, `LocalDimensionIndex`, ADR 0031 (planned) | | C #2910 | class-keyed providers, `FieldOffset` removed, migration script | diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md index 5294729..a26ee00 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md @@ -207,8 +207,8 @@ becomes expressible and needs a new `check_dims` rule; and it makes answers, so `I + 0.5` could not compute its own codomain and neither `as_non_staggered` nor the typed `dual()` would be well defined. It also spells a per-*pair* fact at every use site, so two modules can disagree about one grid, and -it duplicates the whole bracketed-tag apparatus (a second interned family, tag -grammar, `copyreg` hook and codegen escape). Parameterizing the alignment, if it +it duplicates the whole bracketed-tag apparatus (a second derived family, tag +grammar and codegen escape). Parameterizing the alignment, if it is done at all, is one class keyword on the declared axis — see [[personal/egparedes/connectivities-as-types/connectivities-as-types#open-questions--follow-ups|Open questions]]. @@ -242,7 +242,7 @@ Numbered as in the main note's *Open questions*. readable without the declaration, the frontend and embedded shift test matrix doubles, and the keyword would have to be folded into the dimension fingerprint. That last cost is now a known quantity rather than an open hole: Identity rule 4 - fingerprints a dimension's `DimensionRef` alongside its by-reference name, so an + fingerprints a dimension by its `DimensionRef`, so an alignment would be one more field of the ref. Not in this stack. 6. **`kind`'s remaining two jobs.** Once `LOCAL` leaves the enum, `kind` is a From eaf5bcfe21ce39e41a6b80a714fd29f45869be06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Fri, 4 Dec 2026 22:37:32 +0100 Subject: [PATCH 5/5] =?UTF-8?q?personal/egparedes:=20connectivities=20as?= =?UTF-8?q?=20types=20=E2=80=94=20follow=20gt4py#2907=20(ConnectivityRef,?= =?UTF-8?q?=20plain=20local=20dimensions,=20LOCAL=20kept)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../connectivities-as-types.md | 189 ++++++++++-------- .../connectivities-as-types_alternatives.md | 8 +- .../connectivities-as-types_conventions.md | 2 +- ...onnectivities-as-types_dependent-typing.md | 17 +- .../connectivities-as-types_identity.md | 4 +- .../connectivities-as-types_slides.md | 11 +- .../connectivities-as-types_staggering.md | 4 +- .../connectivities-as-types_typing.md | 34 ++-- 8 files changed, 151 insertions(+), 118 deletions(-) diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md index 896b7ce..da52321 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types.md @@ -35,7 +35,7 @@ status: draft > **Implementation.** The design below is implemented on the stacked > GridTools/gt4py PRs listed in [Implementation](#implementation) (top branch > `connectivities-as-types-8-typed-positions`), with ADR 0030 (dimensions as -> nominal types) and ADR 0031 (connectivities as types; planned number). The *Problem* section +> nominal types) and ADR 0031 (connectivities as types). The *Problem* section > and the constraint catalogue in the appendix > [[personal/egparedes/connectivities-as-types/connectivities-as-types_research|Tag and name constraints — full catalogue]] > describe gt4py `main` (`b3c53fa7e`, v1.2.2), the tree the stack is based on. @@ -152,11 +152,12 @@ what is one idea — *a mapping between two index spaces, plus a name for it*. | --- | --- | --- | | `DimensionIndex` | a dimension is a subclass, an index along it an instance (ADR 0030); the root — mesh locations, axes and local dimensions are all subclasses, so every `type[DimensionIndex]` annotation at the Python edge keeps its meaning | `Dimension` instances | | `DimensionRef` | an immutable, interned value naming a dimension class (module, qualname, `kind`, whether it is a Cartesian axis, staggered base); what type specifications, the IR and the backends carry instead of the class (see [Identity](#identity-is-the-qualified-python-name)) | `Dimension` instances below the frontend | +| `ConnectivityRef` | the immutable, interned value of a connectivity declaration (module, qualname, the `DimensionRef`s of its domain, codomain and local dimension, and its counts); what type specifications, `NeighborTableType` and the backends carry instead of the class | — (new) | | `DimensionRange` | a range on a dimension, `KDim.at(0, 10)`; a point is an index, `KDim(3)`. `field[KDim(5):KDim(10)]` is slice syntax for a range | `NamedRange` (`NamedIndex` for a point) | | `CartesianAxisIndex(AnyCartesianAxisIndex)` | a **declared Cartesian axis**: an index space with integer index arithmetic and exactly one staggered partner (see [Cartesian axis dimensions](#cartesian-axis-dimensions)). `AnyCartesianAxisIndex` is either cell class of such an axis, declared or derived | — (new; today `kind != LOCAL` is the nearest approximation, and it does not separate a Cartesian axis from a mesh location) | | `Staggered[D: CartesianAxisIndex]` | the axis's derived partner, at the half-integer positions of `D`; a real class, built once when `D` is declared (see [`Staggered[D]`](#staggeredd)) | the `_Staggered` name prefix | -| `LocalDimensionIndex(DimensionIndex)` | a local dimension: **owned** (declared nested in, or adopted by, its connectivity), or **owner-less** (optionally with `size=n`, which sets `max_neighbors = min_neighbors = n`); carries the neighbor counts | `Dimension(..., kind=LOCAL)`, `_CONST_DIM` | -| `NeighborConnectivity[Domain, Codomain]` | the **static part of a neighbor table's type**: the shift handle in DSL code and the provider key; contains its `Local`; holds no data and is never instantiated | `FieldOffset`, the `V2EDim` convention | +| `LocalDimensionIndex(DimensionIndex)` | a shorthand for a dimension of kind `LOCAL`, nested in its connectivity or declared on its own; a plain dimension, with no owner, sharers, counts or size (see [The local dimension](#the-local-dimension)) | `Dimension(..., kind=LOCAL)` | +| `NeighborConnectivity[Domain, Codomain]` | the **static part of a neighbor table's type**: the shift handle in DSL code and the provider key; contains its `Local` and carries the optional counts; compares by its `ConnectivityRef`; holds no data and is never instantiated | `FieldOffset`, the `V2EDim` convention | | `MultiDimensionIndex[D, *Ls]` | a position in the product of a primary and local dimensions, a tuple of indices; user-facing, nothing in the toolchain requires it | — (new; the iterator-embedded position dicts are keyed by dimension classes, not name strings) | A declaration is not a concept beside the neighbor table: it is the half of @@ -213,15 +214,18 @@ derived from the declaration. It is built where a table is bound (`check_neighbor_table`, `offset_provider_to_type`) or given directly for ahead-of-time compilation (`table_types`), never authored next to the declaration. A table alone cannot name its declaration — a sharer's table has the owner's domain -dims and a different codomain — so the record is built from the provider key, -taking whichever of the local dimension's `owner` or `sharers` the key names. A +dims and a different codomain — so it is bound where both are known: by +`check_neighbor_table`, or by `offset_provider_to_type(provider, declarations)`, +which binds the table under each declaration's `offset_tag` to it. A table bound under a name no declaration answers to (hand-written IR) still gets a `NeighborTableType`; what falls back is its `connectivity` field, which then holds the structural base `ConnectivityType` rather than a declaration, so `dtype`, `skip_value` and `max_neighbors` survive for compilation to consume. That structural type is also what `NeighborTable.__gt_type__()` returns and what types -general connectivity values such as the index field of `as_offset`. It is what fingerprints a compiled variant: the owner's and a sharer's -record over one table fingerprint differently. +general connectivity values such as the index field of `as_offset`. Below the +frontend the toolchain is called with the runtime provider only, so it types tables +structurally there; both forms give a backend the same domain, codomain, dtype, skip +value and count (ADR 0031). `ts.ShiftType` is what `V2E`, `V2E[1]`, `I + 1`, `K + 0.5` and `as_offset(K, f)` type as during FOAST deduction, and what the lowering reads to emit `OffsetLiteral` @@ -266,12 +270,9 @@ class CartesianAxisIndex(AnyCartesianAxisIndex): ... # a *declared* axis; `Staggered` takes these -class LocalDimensionIndex(DimensionIndex): # kind is LOCAL; `kind=LOCAL` elsewhere is an error - owner: ClassVar[type[NeighborConnectivity] | None] # None: owner-less; set by the owner - sharers: ClassVar[tuple[type[NeighborConnectivity], ...]] # later declarations over it - max_neighbors: ClassVar[int | None] # the counts live here, not on the connectivity - min_neighbors: ClassVar[int | None] # min == max <=> no skip values - def __init_subclass__(cls, *, size: int | None = None): ... # size: max = min = size +class LocalDimensionIndex(DimensionIndex): # kind is LOCAL; a subclass with another kind + ... # is an error. A plain dimension: no owner, + # sharers, counts or size (ADR 0031) class MultiDimensionIndex[D: DimensionIndex, *Ls](tuple[D, *Ls]): ... # shape checked at runtime @@ -286,15 +287,25 @@ Staggered[KDim] # KDim's derived partner; # ── connectivities (ADR 0031) ───────────────────────────────────────────── +@dataclass(frozen=True) +class ConnectivityRef: # interned; what the toolchain carries + module: str; qualname: str + domain: DimensionRef; codomain: DimensionRef; local: DimensionRef + max_neighbors: int | None; min_neighbors: int | None + owns_local: bool # property: `local` is `.Local` + offset_tag: Tag # property: local.tag if owns_local else tag + + class ConnectivityMeta(type): tag: Tag # the declaration's qualified name offset_tag: Tag # how the IR names it, see "Identity" domain: Dimension; codomain: Dimension # read from the base subscription + def __eq__(cls, other): ... # equal ConnectivityRefs: same connectivity + def __hash__(cls) -> int: ... # from the ref def __call__(cls, *a, **kw) -> NoReturn: ... # no instances - def __getitem__(cls, item): ... # V2E[1] = bound_table()[Local(1)] in embedded; - # NC[V, E] forwarded to __class_getitem__ - def __gt_type__(cls) -> ts.ShiftType: ... # Shift[offset_tag: Codomain -> (Domain, Local)] - def bound_table(cls) -> NeighborTable: ... # the table bound in the current embedded run + def __getitem__(cls, item): ... # V2E[1]: the frontend's neighbor selector in + # embedded; NC[V, E] -> __class_getitem__ + # typed by `type_translation.from_value`: Shift[offset_tag: Codomain -> (Domain, Local)] class NeighborConnectivity[Domain: DimensionIndex, Codomain: DimensionIndex]( @@ -303,7 +314,7 @@ class NeighborConnectivity[Domain: DimensionIndex, Codomain: DimensionIndex]( # every subclass declares `Local` (a nested class or a TypeAlias); it is # deliberately *not* annotated here, see "The local dimension" def __init_subclass__(cls, *, max_neighbors=None, min_neighbors=None): ... - # writes Local.owner and the counts onto Local; subclassing a declaration is an error + # builds the ConnectivityRef; writes nothing onto Local; the body holds Local only def check_neighbor_table(connectivity, table_or_type) -> NeighborTableType: ... # A6–A8 as one check @@ -330,7 +341,7 @@ class C2CE(NeighborConnectivity[C, CE]): # a flattened sparse pattern: Local: typing.TypeAlias = C2E.Local # shares C2E's neighbor axis -class LsqUnk(LocalDimensionIndex, size=3): ... # owner-less local axis +class LsqUnk(LocalDimensionIndex): ... # a local axis declared on its own @field_operator @@ -380,7 +391,8 @@ stated as rules: tag is the qualified name, which must be unique and lets the class be pickled. A plain call of the metaclass is rejected too, as a guard against accidents. The body of a dimension class is empty apart from a docstring and `kind`, since a class - rebuilt from its ref has nothing else. + rebuilt from its ref has nothing else; that of a connectivity holds its `Local` + and a docstring, since its ref is all the toolchain sees. 3. **No registry; a dimension pickles as its ref.** A `copyreg` reduction on the dimension metaclasses (`Staggered[D]` included) pickles every dimension class as its `DimensionRef`. Loading returns the already loaded class with that ref (a @@ -389,7 +401,9 @@ stated as rules: `__main__` (REPL, notebook, `python -c`) reaches a compile worker like any other. By-value picklers such as `cloudpickle` cannot rebuild a dimension. The process-pool runner still compiles in the calling thread, with a warning, a job - that references another class of an interactive `__main__`. + that references another class of an interactive `__main__`. A connectivity + declaration has no reducer: it pickles by reference, like any class, and the + toolchain carries its `ConnectivityRef`, pickled by value, instead. 4. **Fingerprints are the `DimensionRef`.** A dimension is deconstructed as its ref only — qualified name, `kind`, whether it is a Cartesian axis and, for a staggered one, its base — so a synthesized stand-in fingerprints like the class, a re-run @@ -398,8 +412,8 @@ stated as rules: all: `Staggered[K]` is built from `K` and its tag embeds the base tag, so a different base is a different dimension. The axis level is included because the frontend cache uses this fingerprint and index arithmetic depends on it. A connectivity - declaration is fingerprinted *additionally* by its domain, codomain, `Local` and - counts. Either way the ADR 0023 cache invalidates on module renames. + declaration is fingerprinted by its `ConnectivityRef`: qualified name, the refs of + its domain, codomain and local dimension, and its counts. Either way the ADR 0023 cache invalidates on module renames. 5. **Codegen names need injective mangling.** `codegen_name(tag)` is a prefix escape (`_`→`_u`, `.`→`_d`, `:`→`_c`, `[`→`_l`, `]`→`_r`); the obvious alternative is not injective. @@ -411,11 +425,13 @@ stated as rules: Rules 3–6 in full — pickling, the fingerprint deconstructors, the exhaustive mangling test and the `_Staggered` history — are in [[personal/egparedes/connectivities-as-types/connectivities-as-types_identity|the identity appendix]]. 7. **The IR names a connectivity by its `offset_tag`.** That is its local - dimension's tag when it declares the local dimension: shifts, reductions + dimension's tag when it *owns* the local dimension, i.e. declares it as its + nested `Local` (`ConnectivityRef.owns_local`): shifts, reductions and sparse arguments then all find the table under **one** string, so the backends' A3/A4 lookups are correct without touching them. A connectivity - *sharing* another one's local dimension is named by its own tag, since the - local tag already names the owner's table; for that case the backends have + *sharing* another one's local dimension, or *adopting* one declared on its own, + is named by its own tag, since the local tag already names the owner's table + and two adopters would collide on it; for that case the backends have a fallback lookup, `connectivity_key_over` (see *The local dimension*). 8. **Dimension classes compare by ref.** `I == J` is a `bool`, `True` iff their `DimensionRef`s are equal; `hash` follows. So a redefined class (a re-run cell, @@ -430,13 +446,12 @@ stated as rules: `if domain:` call sites, where truthiness today means "has a dimension". Class-keyed providers hold only classes and tag strings, and a `str` compares unequal to a class, so they are not affected. -9. **Same-named declarations are different connectivities.** Two - declarations with the same qualified name from different modules, or a - redefinition, are simply different classes; no warning is issued, and - `check_neighbor_table` hints "was the declaration redefined?" when a table - built for one is bound to the other. Dimensions differ here (rule 8): a - redefinition with an equal ref is the same dimension; two different refs with one - tag in a program are an error. +9. **Declarations compare by `ConnectivityRef`**, as dimensions do by theirs + (rule 8); `hash` and the fingerprint follow. A declaration re-run unchanged (a + notebook cell) is the same connectivity; one re-run with other dimensions or + counts is a different one, so artifacts compiled for the old one are not reused. + Two different declarations under one `offset_tag` in a program are an error, as + are two different dimension refs with one tag. ### Cartesian axis dimensions @@ -499,26 +514,16 @@ The self-type costs two definition-site suppressions, one per checker; P4 of [`staggered_probe.py`](staggered_probe.py) pins it down and [[personal/egparedes/connectivities-as-types/connectivities-as-types_typing|the typing appendix]] records both diagnostics. -`kind` **shrinks.** It carries four jobs today: `LOCAL` marks a neighbor axis; +`kind` **should shrink.** It carries four jobs today: `LOCAL` marks a neighbor axis; `order_dimensions` sorts by `(kind, as_non_staggered(dim).value)`, so it decides memory layout order (constraint F4; #2899 sorts by kind rank, then base qualname, then base tag, so the module only breaks ties between equal qualnames); `order_dimensions` also uses it to enforce at most one `LOCAL` dimension; and `VERTICAL` names the scan axis and, by -convention, the undecomposed one. The first and third are now class facts — -`kind == LOCAL` iff `issubclass(d, LocalDimensionIndex)` — so **`LOCAL` leaves the -enum**: `kind` becomes `HORIZONTAL | VERTICAL`, annotated -`ClassVar[DimensionKind | None]`, and a local dimension's `kind` is `None` — -passing `kind=` when declaring one is a `TypeError`. `None` rather than -`HORIZONTAL` so that every existing `kind == HORIZONTAL` / `kind != VERTICAL` -comparison in gtfn, the nanobind bindings and DaCe keeps its exact current -meaning instead of silently counting a sparse field's local axis as horizontal. -Because `None` is not orderable against the enum, `order_dimensions` computes the -rank explicitly — horizontal, then local, then vertical — rather than sorting on -`kind` directly; **the order must not move**, or sparse-field layout moves with -it. A helper `common.is_local_dimension(dim)` replaces the `kind is LOCAL` checks, -and the printed form (`Local[local]`) and the DaCe map variable -(`i__gtx_localdim`) are derived from the class (PR B, where -`LocalDimensionIndex` lands). What is left is the layout key and the "vertical" +convention, the undecomposed one. The first stays a `kind` fact (ADR 0031): a +dimension is local iff its `kind` is `LOCAL`, because a stand-in synthesized from a +ref cannot subclass the user's `LocalDimensionIndex`, so localness has to be data on +the ref, and the kind already is. `LocalDimensionIndex` is a shorthand for it; a +subclass with another `kind=` is a `TypeError`. What could still leave `kind` is the layout key and the "vertical" role, which belong to the field and to the program respectively — see [Open questions](#open-questions--follow-ups). @@ -595,10 +600,9 @@ The connectivity *type* conceptually depends on the *table*: two different tables assign different neighbors to the same domain element. The model: - The class `V2E` is a **declaration**. Its static part — `V2E.domain`, - `V2E.codomain`, `V2E.Local`, and *optionally* the counts - `V2E.Local.max_neighbors` / `V2E.Local.min_neighbors` (they are stored on - the local dimension; `V2E.max_neighbors` does not exist) — is what - compilation sees. Declared counts are a constraint on the table; undeclared + `V2E.codomain`, `V2E.Local`, and *optionally* the counts `max_neighbors` / + `min_neighbors` (class keywords, kept in its `ConnectivityRef`; the local + dimension carries none) — is what compilation sees. Declared counts are a constraint on the table; undeclared ones are simply taken from the bound table's `NeighborTableType` when a variant is compiled. Binding never writes anything back to the class. - Why the counts are not static-only. Two in-tree and in-ICON facts: the @@ -636,6 +640,21 @@ tables assign different neighbors to the same domain element. The model: connectivity tag* are unchanged; those keyed by a *local dimension* (reductions, sparse and list arguments) find the table through `connectivity_key_over`. +- **Checked where declarations meet.** A declaration does not know the others, + so they are checked when the frontend lowers a program (`past_to_gtir`): it + calls `offset_provider_to_type(provider, declarations)` with the declarations + the program references — the `NeighborConnectivity` classes among its closure + variables, collected through the field operators it calls, and those reached + through a module or another namespace (`a(mesh.V2E)`). That checks the table + under each declaration's `offset_tag` with `check_neighbor_table`, rejects two + different declarations under one `offset_tag`, and requires declarations over one + local dimension to have one domain and equal declared counts. For every local + dimension, with or without declarations, `check_shared_local_dimensions` requires + the tables over it to have the same domain, width and, all or none, skip values; + `connectivity_key_over` runs it for the one dimension it looks up, which is how + embedded execution notices. Where the skip values are is not checked (ADR 0031). + Embedded execution checks tables against declarations only once providers are + keyed by the declaration (PR C). - **Validated at the boundary.** `check_offset_provider` runs at *every* entry point, including the iterator `fendef`, `FieldOperatorFromFoast` and the DaCe orchestration's `CompilationOptions.connectivities`. Its result is remembered @@ -645,8 +664,7 @@ tables assign different neighbors to the same domain element. The model: replaced at the same address. Reading the tables — comparing skip positions, below — happens only where a program is compiled, not on the call path. It calls `check_neighbor_table` per declaration, which checks the domain - `(Domain, Local)` and the codomain by class identity (with a hint when a - declaration looks redefined), an integral dtype, `max_neighbors` equal to + `(Domain, Local)` and the codomain by ref, an integral dtype, `max_neighbors` equal to the table's width and `min_neighbors` not above it if declared, and — only when `min_neighbors` is declared — that the table has a skip value iff `min_neighbors <` its width. Skip values are judged on the table's *type*: @@ -666,7 +684,8 @@ tables assign different neighbors to the same domain element. The model: - `V2E.Local` **must be given explicitly** in the class body — a nested `class Local(LocalDimensionIndex): ...`, or an existing local dimension to adopt or share (below); `__init_subclass__` verifies it (a missing `Local` - is a `TypeError`) and sets `Local.owner`. There is no generated form. This + is a `TypeError`) and builds the declaration's `ConnectivityRef`; nothing is + written onto `Local`. There is no generated form. This is settled by running both checkers on [`typing_probe.py`](typing_probe.py): an explicitly declared nested `Local` is a real, distinct type under mypy `--strict` and @@ -676,7 +695,7 @@ tables assign different neighbors to the same domain element. The model: annotated `ClassVar[type[LocalDimensionIndex]]` on the base is rejected by both as *not valid as a type* — the very error class ADR 0030 exists to remove. Two lines per connectivity buy a real type; ICON4Py has 16 - declarations. Its tag is `.Local`, unique by construction. + declarations. Its tag is `.Local`, unique by construction. - `Local` is **not** passed through the base subscription (`NeighborConnectivity[V, "V2E.Local", E]`): mypy accepts that string forward reference, pyright reports `Class definition for "V2E" depends on @@ -690,10 +709,23 @@ tables assign different neighbors to the same domain element. The model: parameters: Python has no integer-valued type parameters, and nothing static needs the count — what must be in the type is *which* local dimension. -- **Owner-less local dimensions** exist: `class LsqUnk(LocalDimensionIndex, size=3)` - has `owner = None`, `min == max == size`, no skip values, and never appears - in the provider — unless a connectivity later adopts it, which makes it - owned. `size` is optional; an owner-less local without it has no counts. ICON4Py needs this today: `LsqUnkDim` (`dimension.py:18`, +- **A local dimension is a plain dimension** (ADR 0031): it records no owner, no + sharers, no counts and no size, since a class rebuilt from its ref would lose + them. A declaration *owns* the `Local` nested in it; one that *shares* + another's (`Local: TypeAlias = C2E.Local`) or *adopts* one declared on its own + (`Local: TypeAlias = LsqCoeff`) is named by its own tag (Identity, rule 7). + Connectivities over one local dimension must have the same domain and neighbor + structure (count, and skip values at the same positions); their codomains are + free. This is checked where declarations meet (Binding model), not when they are + declared. +- **`DimensionKind.LOCAL` stays.** `LocalDimensionIndex` is a shorthand for it, not + the test: a dimension is local iff its `kind` is `LOCAL`, so a + `DimensionIndex, kind=LOCAL` class, a `DimensionRef` and a stand-in synthesized + from it are local too. Localness as a class is a rejected alternative in ADR + 0031, since a stand-in cannot subclass the user's base classes. +- **Local dimensions declared on their own** exist: `class LsqUnk(LocalDimensionIndex)` + indexes no table, has no size of its own, and never appears in the provider — + unless a connectivity adopts it. ICON4Py needs this today: `LsqUnkDim` (`dimension.py:18`, LOCAL kind, "number of least-squares unknowns") is the middle axis of a coefficient field over `(CellDim, LsqUnkDim, C2E2CDim)` and indexes no table; `RBFDimension` is an enum of stencil sizes that plays the same role. @@ -701,12 +733,11 @@ tables assign different neighbors to the same domain element. The model: not a connectivity; declaring them non-LOCAL instead would make them domain dimensions requiring a range in every program domain and would change ICON4Py's memory layout for those fields. (Backend support for sparse fields - over an owner-less axis *other than* `ConstList` is not part of the stack: + over such an axis *other than* `ConstList` is not part of the stack: such a field still needs some bound table over its axis.) - `_CONST_DIM` is replaced by `iterator.builtins.ConstList`, one class used by iterator - embedded and the DaCe lowering. #2899 declares it as a `DimensionIndex` of kind - `LOCAL`; #2907 is to make it an owner-less `LocalDimensionIndex, size=1`, refused as - an adopted `Local`. (Type inference still + embedded and the DaCe lowering, declared as a `DimensionIndex` of kind `LOCAL`. It + indexes no table and is never in a provider. (Type inference still represents a constant list as `ListType(offset_type=None)`.) - `neighbor_sum(..., axis=V2E.Local)` — the local axis stays **explicit**. `axis=V2E` as sugar is deliberately not offered; it would blur the two @@ -737,11 +768,11 @@ tables assign different neighbors to the same domain element. The model: | Layer | Before | After | | --- | --- | --- | | Frontend declaration | `Dimension(LOCAL)` + `FieldOffset` + provider key | one class | -| Frontend types | `ts.OffsetType(source, target)`, tag dropped | `ts.ShiftType(domain, codomain, tag)` produced by the class (`__gt_type__`), `tag` set to `offset_tag`; `V2E.Local` in DSL code types as the local dimension | +| Frontend types | `ts.OffsetType(source, target)`, tag dropped | `ts.ShiftType(codomain, domain, tag)` from the declaration's `ConnectivityRef` (`type_translation.from_value`), `tag` set to `offset_tag`; `V2E.Local` in DSL code types as the local dimension | | FOAST → GTIR | shift tag = **Python variable name** | tag = `offset_tag`; the variable name is irrelevant (GridTools/gt4py#2898) | | ITIR | `OffsetLiteral(str)` + dict lookup; `AxisLiteral(value, kind)` | `OffsetLiteral(offset_tag)`, unchanged node; `AxisLiteral(dim: DimensionRef)`, with `value` and `kind` derived | | ITIR types | `ListType.offset_type: Dimension` | unchanged (already the local dim) | -| Embedded field | `get_offset(provider, axis.value)` | table over the local dimension (`connectivity_key_over`); `V2E.bound_table()` | +| Embedded field | `get_offset(provider, axis.value)` | table over the local dimension (`connectivity_key_over`); `V2E[i]` through a neighbor selector the frontend registers | | Embedded iterator | positions keyed by name strings; `SparseTag` | positions keyed by dimension classes; `SparseAxis(dim)` | | gtfn | `dim.value` lookups; `TagDefinition` per tag and per `neighbor_dim` | still a `TagDefinition` per offset tag (and per differing `neighbor_dim`, i.e. for sharers), named by `codegen_name(tag)`; sparse-argument lookups through `connectivity_key_over` | | DaCe | ~10 `offset_type.value` lookups; `Dimension(offset, LOCAL)` synthesized | `codegen_name` for array/symbol names; `connectivity_key_over`; a local dimension sized from its own table (`local_dimension_size`); no synthesis | @@ -754,9 +785,7 @@ tables assign different neighbors to the same domain element. The model: at the strict entry points); the `_Staggered` prefix and its string sniffing (replaced by the `Staggered[D]` class and a small `[]` tag grammar); `_CONST_DIM` as a magic name; the separate `value` and `kind` fields of `AxisLiteral`; -`SparseTag`; `NamedIndex` and the dimension half of the mypy plugin; -`DimensionIndex(kind=LOCAL)` as a way to declare a local dimension, and the -`LOCAL` member of `DimensionKind` itself (derived from `LocalDimensionIndex`); and the +`SparseTag`; `NamedIndex` and the dimension half of the mypy plugin; and the convention that `V2EDim = Dimension("V2E", LOCAL)` must sit next to `V2E = FieldOffset("V2E", ...)`; the names `ts.OffsetType` (now `ts.ShiftType`, with `domain`/`codomain` instead of the inverted @@ -768,7 +797,8 @@ re-fielded `ts.OffsetType`): the frontend shift type and the runtime connectivity objects (see [What stays, and why](#what-stays-and-why)); `iterator.runtime.offset("...")` (the iterator-level API names offsets by string, like the IR); and -string-keyed providers *below* the entry points. +string-keyed providers *below* the entry points; `DimensionKind.LOCAL`, which +marks a local dimension (ADR 0031). The Cartesian `FieldOffset` goes together with the unstructured one: Cartesian shifts were already `Dim + i`, and `as_offset` takes the @@ -777,7 +807,7 @@ dimension, `as_offset(KDim, field)`. ## Alternatives considered -Eight alternatives are recorded in [[personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives|the alternatives appendix]], +Nine alternatives are recorded in [[personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives|the alternatives appendix]], two more on the spelling of `Local` in [[personal/egparedes/connectivities-as-types/connectivities-as-types_typing|the typing appendix]] §4, and the six concerning the axis levels and `Staggered[D]` in [[personal/egparedes/connectivities-as-types/connectivities-as-types_staggering|the staggering appendix]] §6. The three a reviewer is most likely to @@ -802,7 +832,7 @@ raise, with why each loses: `Staggered[D]` ([above](#staggeredd)); its semantics are unchanged, and [Cartesian axis dimensions](#cartesian-axis-dimensions) states the structure they encode. - **ADR 0030 (Dimensions as nominal types)** and **ADR 0031 (Connectivities - as types; planned number)** record this design in the gt4py tree. + as types)** record this design in the gt4py tree. - **ADR 0023 (build cache).** Fingerprints depend on qualified names, so the cache invalidates on module renames (Identity, rule 4). @@ -841,9 +871,9 @@ with the reasoning, so that a later reader does not reopen them. establishes as a pattern rather than an obstacle. See [[personal/egparedes/connectivities-as-types/connectivities-as-types_staggering|the staggering appendix]]. Not in this stack. -6. **`kind`'s remaining two jobs.** Once `LOCAL` leaves the enum, `kind` is a - layout sort key and a name for the scan axis — properties of the field and of - the program, not of the dimension. Every candidate *addition* belongs to the +6. **`kind`'s other two jobs.** Besides marking a local dimension (`LOCAL` stays, + ADR 0031), `kind` is a layout sort key and a name for the scan axis — properties + of the field and of the program, not of the dimension. Every candidate *addition* belongs to the grid, the program or the range, so `kind` should shrink rather than grow. The argument is in [[personal/egparedes/connectivities-as-types/connectivities-as-types_staggering|the staggering appendix]] §7, and SGRID's treatment of the vertical is external evidence for it @@ -888,13 +918,14 @@ green in CI on its own and based on the previous one, on top of two preparation GridTools/gt4py#3087 (`connectivities-as-types-1-preparation`: open named slices, the `cartesian_shift` helper and other preparations) and GridTools/gt4py#3088 (`connectivities-as-types-1b-mechanical-renames`: `NamedRange` → `DimensionRange`), -both below #2899. #2907 and the PRs above it still sit on an earlier state of #2899, -without `DimensionRef`: +both below #2899. #2907 is re-implemented on #2899 (head `07a7f65e3`); #2910 and #2912 +still sit on an earlier state of #2899, without `DimensionRef`, and their rows are +planned design: | PR | Branch | What | | --- | --- | --- | | A: GridTools/gt4py#2899 | `connectivities-as-types-2-dimension-classes` | `feat[next]`: a concrete dimension is a class identified by its qualified name (ADR 0030); `DimensionRef` values below the frontend, also in `AxisLiteral`, so nothing is imported from a tag; `codegen_name`; `CartesianAxisIndex` / `AnyCartesianAxisIndex` (both exported from `gtx`) and `Staggered[D: CartesianAxisIndex]`, with `__add__`/`__sub__` restricted to an axis statically and at runtime; `Dimension.at`; dimension classes equal by ref and pickled as refs (`synthesize_dimension`); `NamedIndex` and the dimension half of the mypy plugin removed; mypy typing case `cartesian_axis_levels`; `iterator.builtins.ConstList` (still of kind `LOCAL`) replaces the `_CONST_DIM` aliases; offset tag = local dimension tag = provider key in the tree | -| B: GridTools/gt4py#2907 | `connectivities-as-types-3-neighbor-connectivity` | `feat[next]`: `NeighborConnectivity[Domain, Codomain]`, `LocalDimensionIndex` (and `DimensionKind.LOCAL` removed: a local's `kind` is `None`, localness comes from `common.is_local_dimension`, and `order_dimensions` ranks horizontal/local/vertical explicitly), `check_neighbor_table`, `local_dimension_of`, declaration fingerprinting; usable in the DSL; shared local dimensions, in the declarations and in the backends (`connectivity_key_over`, DaCe `local_dimension_size`); `NeighborTableType` and `ts.ShiftType`; pyright in the typing nox session, with `reportUnnecessaryTypeIgnoreComment: error` so a rejection that stops firing fails the run; ADR 0031 (planned number) | +| B: GridTools/gt4py#2907 | `connectivities-as-types-3-neighbor-connectivity` | `feat[next]`, additive (`FieldOffset` and string-keyed providers keep working): `NeighborConnectivity[Domain, Codomain]` with the counts on the declaration and its `ConnectivityRef`, by which declarations compare, hash and are fingerprinted; `LocalDimensionIndex`, a shorthand for kind `LOCAL` (which stays); owner and sharers by nesting, `offset_tag`; `check_neighbor_table`, `local_dimension_of`; programs check their tables against the declarations they reference, also through a module (`mesh.V2E`), and tables over one local dimension must agree in structure on every backend; `connectivity_key_over`, DaCe `local_dimension_size`; `NeighborTableType`, `TableTypes` and `ts.ShiftType`; pyright in the typing nox session; ADR 0031 | | C: GridTools/gt4py#2910 | `connectivities-as-types-6-class-keyed-providers` | `feat[next]!`: the tree and docs declare connectivities as classes; class-keyed offset providers with `check_offset_provider` at every entry point; `FieldOffset` removed; `as_offset(dim, field)` restricted to an `AnyCartesianAxisIndex`; `table_types` replaces `offset_provider_type`; migration script | | D: GridTools/gt4py#2912 | `connectivities-as-types-8-typed-positions` | `refactor[next]`: `MultiDimensionIndex` and typed embedded positions | diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md index 3e2a42e..89adb0b 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_alternatives.md @@ -51,6 +51,12 @@ because skip-value presence is configuration-dependent in ICON, so a static `min_neighbors` forces either duplicate classes or always-on skip handling. Declared counts stay available as a constraint; see [[personal/egparedes/connectivities-as-types/connectivities-as-types#binding-model|Binding model]]. -**Owner-less local axes as non-LOCAL dimensions.** Rejected: they would +**Owner, sharers and counts on the local dimension** (`Local.owner`, +`Local.sharers`, `LocalDimensionIndex(size=3)`), written when a declaration is +created. It lets a declaration check its sharers on the spot, but makes a local +dimension mutable state that a re-run notebook cell has to re-own, and puts data on +a dimension that a synthesized stand-in (ADR 0030) cannot carry (ADR 0031). + +**Local axes declared on their own as non-LOCAL dimensions.** Rejected: they would become domain dimensions with a range in every program domain and lose the sparse storage treatment, changing ICON4Py's layout for `LsqUnkDim` fields. diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_conventions.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_conventions.md index 3e6edb8..046b80b 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_conventions.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_conventions.md @@ -80,7 +80,7 @@ enumerates as 2ⁿ location names, and it does not stop at three axes. | Convention feature | This design | Verdict | | --- | --- | --- | | Connectivities named by entity pair (`face_node_connectivity`) | `NeighborConnectivity[Domain, Codomain]` — `face_node_connectivity` ≡ `NeighborConnectivity[Face, Node]` | isomorphic. The `Domain`/`Codomain` naming matches UGRID's reading direction, where `source`/`target` did not | -| `_FillValue` required wherever an entry may be absent — ragged valence, but also a missing boundary neighbour in `edge_face_connectivity` / `face_face_connectivity`; `nMaxMesh2_face_nodes` | `skip_value` and `max_neighbors` on `NeighborTableType`, and the optional `min_neighbors` on the declaration's `Local` | strictly more informative. ICON's icosahedron carries 12 pentagons among hexagons, so `V2E` is `min_neighbors=5, max_neighbors=6`; UGRID can only record max 6 plus fill. That is the sketch's example verbatim | +| `_FillValue` required wherever an entry may be absent — ragged valence, but also a missing boundary neighbour in `edge_face_connectivity` / `face_face_connectivity`; `nMaxMesh2_face_nodes` | `skip_value` and `max_neighbors` on `NeighborTableType`, and the optional `min_neighbors` on the declaration | strictly more informative. ICON's icosahedron carries 12 pentagons among hexagons, so `V2E` is `min_neighbors=5, max_neighbors=6`; UGRID can only record max 6 plus fill. That is the sketch's example verbatim | | `vertical_dimensions` uses **the same** padding syntax as `face_dimensions` | — | the vertical is just another axis pair. SGRID needs no "vertical kind", which supports the conclusion that `DimensionKind.VERTICAL` is a layout and scan artefact, not geometry (main note, open question 6) | | `face_dimensions` specifies a padding **per axis** | a per-axis alignment, never grid-wide | supports the shape of the alignment follow-up (open question 5): a class keyword on the axis | | 3D topology forbidden for layered grids; use 2D + `vertical_dimensions` | horizontal topology plus a separate vertical axis | validates the existing split | diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_dependent-typing.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_dependent-typing.md index 81f1f26..786451f 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_dependent-typing.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_dependent-typing.md @@ -282,7 +282,7 @@ proved. | --- | --- | --- | | `Vert` — index type of a mesh entity | `Dimension("Vertex")`, identity by `(value, kind)` | the class `V(DimensionIndex)`; identity is the class (a **brand**, §7) | | `Fin` — local slot, depends on `g` *and* `v` | `V2EDim = Dimension("V2E", LOCAL)`, a free name | `V2E.Local`: depends on the **declaration** `V2E` (nominally, by nesting), not on `g` or `v` | -| `degree(g, v)` bounded by the padded row length | `max_neighbors` on the table's type | `max_neighbors` / `min_neighbors`: optional class keywords stored on `V2E.Local`, else taken from the table | +| `degree(g, v)` bounded by the padded row length | `max_neighbors` on the table's type | `max_neighbors` / `min_neighbors`: optional class keywords on the declaration (its `ConnectivityRef`), else taken from the table | | `Option`-valued slots of a padded ragged row | `skip_value` (−1) in the table | same; if `min_neighbors` is declared, skip values must be present iff `min_neighbors < max_neighbors` | | `NeighborOrder` — the enumeration | a `NeighborTable` / `NdArrayConnectivityField` | unchanged: the table *is* the enumeration and, in §6's inverted presentation, the graph | | `(v : Vert) -> Fin -> double` — slot-addressed field | `Field[Dims[V, V2EDim], float]` | `Field[Dims[V, V2E.Local], float]` | @@ -366,13 +366,14 @@ relaxation of "one table per declaration per binding context". `C2CE` (cell → `C2E.Local` so that its results combine with `C2E`-shaped sparse fields. Sharing a slot type across two connectivities is only sound if both tables enumerate each cell's fiber in the same order and pad it in the same places. -The type checker cannot see this; the bind-time check (`check_offset_provider`) -requires tables over one shared local dimension to have the same width and -skip-value presence and — where a program is compiled — skip values at the -same positions, and reductions over the shared axis take that structure from any -bound table over it. Note what this does *not* check: that the two tables list -each cell's neighbors in the same *order* — §6's bijection — which is again a -property of the mesh generator. +The type checker cannot see this; the bind-time check +(`check_shared_local_dimensions`, run by `offset_provider_to_type` and +`connectivity_key_over`) requires tables over one shared local dimension to have +the same domain, width and skip-value presence, and reductions over the shared axis +take that structure from any bound table over it. Note what this does *not* check: +where the skip values are, and that the two tables list each cell's neighbors in +the same *order* — §6's bijection — which are again properties of the mesh +generator (ADR 0031 leaves them to the user). ### Evidence lifetime diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md index 54f61b1..d83f889 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_identity.md @@ -39,8 +39,8 @@ status: draft cached stages or artifacts. `Staggered[D]` goes through its base and inherits this; its base cannot be flipped in place, since the class is built from its base and its tag embeds the base tag. A connectivity - declaration is fingerprinted *additionally* by its domain, codomain, `Local` and - counts. Consequently the ADR 0023 build cache invalidates on module renames. + declaration is fingerprinted by its `ConnectivityRef`: qualified name, the refs of + its domain, codomain and local dimension, and its counts. Consequently the ADR 0023 build cache invalidates on module renames. 5. **Codegen names need injective mangling.** `codegen_name(tag)` is a prefix escape — `_`→`_u`, `.`→`_d`, `:`→`_c`, `[`→`_l`, `]`→`_r` — used by gtfn, DaCe, the roundtrip backend and the nanobind bindings. There is no inverse: DaCe gets the diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md index 544cc3e..db1731e 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_slides.md @@ -27,7 +27,7 @@ npx -y @marp-team/marp-cli@4 --no-stdin \ One declaration for offset, local dimension and provider key -ADR 0030 (dimensions) · ADR 0031 (connectivities; planned number) +ADR 0030 (dimensions) · ADR 0031 (connectivities) > **Appendix** to [Connectivities as types](connectivities-as-types), summarising the note it is published alongside; where the two disagree the note is authoritative. Every slide links the section it compresses, and the deck adds no facts of its own. Rendering instructions are on the slide before this one. @@ -85,8 +85,9 @@ The class *contains* its local dimension and *is* its own provider key. Nothing - dimension classes with equal `DimensionRef`s are the same dimension: a re-run cell is no new dimension - below the frontend a dimension is a **`DimensionRef` value**: nothing is imported from a tag -- a dimension pickles as its ref, so notebook dimensions reach compile workers; `` dimensions are rejected, and a redefined connectivity is a *different* connectivity -- the IR names a connectivity by its `offset_tag` = its local dimension's tag, so shifts, reductions and sparse arguments find one table under **one** string +- a dimension pickles as its ref, so notebook dimensions reach compile workers; `` dimensions are rejected +- a connectivity compares by its `ConnectivityRef`: re-run unchanged it is the same connectivity, with other dimensions or counts a different one +- the IR names a connectivity by its `offset_tag` = the tag of its nested `Local` (a sharer: its own tag), so shifts, reductions and sparse arguments find one table under **one** string → [Identity](connectivities-as-types#identity-is-the-qualified-python-name) @@ -152,7 +153,7 @@ In *n* dimensions the grid is the product complex, so `Dims[...]` is one stagger ## What it deletes -`FieldOffset` · bare-name provider keys · the `_Staggered` name prefix · `_CONST_DIM` as a magic name · `SparseTag` · `NamedIndex` · the dimension half of the mypy plugin · `DimensionKind.LOCAL` · the `V2EDim`-next-to-`V2E` convention +`FieldOffset` · bare-name provider keys · the `_Staggered` name prefix · `_CONST_DIM` as a magic name · `SparseTag` · `NamedIndex` · the dimension half of the mypy plugin · the `V2EDim`-next-to-`V2E` convention Of ten cross-object identity constraints: **six dissolve**, three collapse into one bind-time check, one remains. @@ -166,7 +167,7 @@ Of ten cross-object identity constraints: **six dissolve**, three collapse into | --- | --- | | #3087, #3088 | preparations, `NamedRange` → `DimensionRange` | | A #2899 | dimensions as classes, `DimensionRef`, `Staggered[D]`, ADR 0030 | -| B #2907 | `NeighborConnectivity`, `LocalDimensionIndex`, ADR 0031 (planned) | +| B #2907 | `NeighborConnectivity`, `ConnectivityRef`, `LocalDimensionIndex` (kind `LOCAL` stays), shared local dimensions, ADR 0031 | | C #2910 | class-keyed providers, `FieldOffset` removed, migration script | | D #2912 | `MultiDimensionIndex`, typed embedded positions | diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md index a26ee00..46f997d 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_staggering.md @@ -245,8 +245,8 @@ Numbered as in the main note's *Open questions*. fingerprints a dimension by its `DimensionRef`, so an alignment would be one more field of the ref. Not in this stack. -6. **`kind`'s remaining two jobs.** Once `LOCAL` leaves the enum, `kind` is a - layout sort key and a name for the scan axis. Layout is a property of the field, +6. **`kind`'s other two jobs.** Besides marking a local dimension (`LOCAL` stays, + ADR 0031), `kind` is a layout sort key and a name for the scan axis. Layout is a property of the field, not of the dimension, and that coupling is why dimension *names* currently determine memory layout (F4); what `order_dimensions` actually wants is an *order* — innermost to outermost, `I, J, K` for a box, `(CellDim, KDim)` for diff --git a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_typing.md b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_typing.md index 77b8438..2ae9a35 100644 --- a/content/personal/egparedes/connectivities-as-types/connectivities-as-types_typing.md +++ b/content/personal/egparedes/connectivities-as-types/connectivities-as-types_typing.md @@ -41,34 +41,28 @@ suppresses for its overload pairs. The cost is that `conn.Local` is not an attribute the checkers know for a *generic* `conn`: library code reads it through `common.local_dimension_of(conn)`, and code that must name a local dimension - generically uses a `TypeVar` bound to `LocalDimensionIndex`. This is checked + generically uses a `TypeVar` bound to `DimensionIndex`. This is checked for both checkers in CI: the mypy cases in `typing_tests/test_next.yaml`, and a pyright run over `typing_tests/pyright_probes.py` in the same nox session (pyright is what catches the annotation regression; mypy accepts it). - A declaration can instead **adopt** a module-level local dimension, written - `Local: typing.TypeAlias = V2EDim`; the local keeps its own tag, which is then - the connectivity's `offset_tag`. This is also how the migration script - rewrites existing `FieldOffset`s without renaming anything. Adopting is *not* - side-effect free: the adopter becomes the local's `owner` and writes its - counts onto the module-level class, and ownership is first-come — the first - connectivity declared over a local dimension owns it, later ones share it and - are recorded in its `sharers`. A - declaration *redefined* under the same tag (a re-run notebook cell) takes - ownership over again rather than becoming a sharer, and the counts it repeats - are then checked against the local dimension's own `size=`, not against what - the stale owner wrote. `ConstList` cannot be adopted: it belongs to no - connectivity. + `Local: typing.TypeAlias = V2EDim`. Only a nested `Local` is owned, so an + adopter is named by its own tag, its `offset_tag`, and its table is bound under + that key. Adopting writes nothing onto the local dimension, which records no + owner, sharers or counts (ADR 0031). - A connectivity can **share** another one's local dimension (`class C2CE(NeighborConnectivity[C, CE]): Local: typing.TypeAlias = C2E.Local`). ICON4Py's flattened sparse offsets (`C2CE`, `E2ECV`, `E2EC`, `C2CEC`) need exactly this, because their results must combine with `C2E`-shaped sparse fields. The - owner stays the first declaration over the local (here `C2E`); the sharer - must have the same domain (its codomain is free), any counts it repeats must - equal the owner's, and reductions over the shared axis take the neighbor - structure from any bound table over it (`connectivity_key_over`: the owner's - key if bound, else the smallest bound key over that local, which raises - `KeyError` if there is none). + owner is the declaration the `Local` is nested in (here `C2E`); the sharer + must have the same domain and neighbor structure (its codomain is free), and + counts declared by both must be equal. A declaration does not know the others, + so this is checked where declarations meet, when a program is lowered + (`offset_provider_to_type`). Reductions over the shared axis take the neighbor + structure from any bound table over it (`connectivity_key_over`: the one keyed + by the local dimension's tag if bound, else the smallest bound key over that + local, which raises `KeyError` if there is none). - **Write an adopted or shared `Local` as a `TypeAlias`.** `Local: TypeAlias = C2E.Local` is what keeps mypy treating `C2CE.Local` as a type; with a plain assignment it is "not valid as a type" there (pyright accepts either, but @@ -87,7 +81,7 @@ connectivity). They **cannot be reconciled for a type checker**: making and pyright treating `Field[V, V2E.Local]` and `Field[V, Local[V2E]]` as incompatible in both directions. One spelling has to win, and this proposal picks `V2E.Local`: the nested form is what makes the tag unique with no -registry, and the counts belong to the owner. The cost is honest and falls +registry, and the counts belong to the declaration. The cost is honest and falls on the chain proposals: their mypy-verified encodings (`static_hops.py`: `Local[NeighborTable[O, C]]`, `Local[ConnT]`) are built on subscripting `Local`, and a `TypeVar` cannot be subscripted for a nested