-
Notifications
You must be signed in to change notification settings - Fork 57
feat[next]: Tracer support part 1: tree_map #2586
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SF-N
wants to merge
47
commits into
GridTools:main
Choose a base branch
from
SF-N:tracer_support_tree_map
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
1b4707c
Tracer prototype
SF-N 902f8a3
Merge branch 'main' into tracer_support
SF-N 02f881f
Introduce GTIR tree_map builtin and transform to make_tuple, also sup…
SF-N 0ec4692
Run pre-commit and fix some tests
SF-N ab84ecc
Run CollapseTuple after UnrollTreeMap
SF-N 36d6956
Merge branch 'main' into tracer_support_tree_map
SF-N 152300e
Address review comments
SF-N d459b0e
Address further review comments
SF-N 97af81e
Apply review comments
SF-N 8d75708
Merge branch 'main' into tracer_support_tree_map
SF-N 067bc29
Merge branch 'main' into tracer_support_tree_map
SF-N 32e5b2d
Rename map_ -> map_list
SF-N a7175d7
Run pre-commit
SF-N 4f89818
Merge branch 'main' into tracer_support_tree_map
SF-N 2779fd0
Refactor tree_map_tuple and add map_tuple with unrolling support
SF-N 80f3273
Rename
SF-N 454e15f
Minor fix
SF-N 8a1febd
Merge branch 'main' into tracer_support_tree_map
SF-N 31b969a
Remove unnecessary CollapseTuple loop
SF-N c7fc102
Reposition UnrollTupleMaps and simplify CollapseTuple usage
SF-N 7993b9c
Merge branch 'main' into tracer_support_tree_map
SF-N b7f8ba9
Refactor tree_map unrolling
SF-N 3d38868
Cleanup
SF-N 7d5c86c
Revert "Cleanup"
SF-N 747f36e
Revert "Refactor tree_map unrolling"
SF-N b767700
Cleanup
SF-N e91f1f1
Merge branch 'origin-main' into tracer_support_tree_map
SF-N 7b270a3
Address review comment
SF-N d3d4e46
Remove CollapseTuple pass after UnrollTupleMaps
SF-N d0272df
Remove program wrapper in tests
SF-N 56f234e
Merge branch 'tracer_support_tree_map' of github.com:SF-N/gt4py into …
SF-N b7bb0b2
Fix test
SF-N 158d540
Merge branch 'main' into tracer_support_tree_map
SF-N 7d8f56c
Also allow itir.Expr in UnrollTupleMaps and run tye_inference when ne…
SF-N 7808b0f
Merge branch 'tracer_support_tree_map' of github.com:SF-N/gt4py into …
SF-N 556178f
Merge branch 'main' into tracer_support_tree_map
SF-N aed9577
Merge branch 'main' into tracer_support_tree_map
SF-N bbf0679
Merge branch 'main' into tracer_support_tree_map
SF-N 5102336
Merge branch 'main' into tracer_support_tree_map
SF-N c6d5a2d
Address review comments
SF-N 242343f
Merge branch 'main' into tracer_support_tree_map
SF-N 06d56ee
Merge branch 'tracer_support_tree_map' of github.com:SF-N/gt4py into …
SF-N 3f24c06
Update test
SF-N 904623b
Run pre-commit
SF-N a2da186
Merge branch 'main' into tracer_support_tree_map
SF-N 9205669
Remove special casing from UnrollTupleMaps and update tests
SF-N 349d239
Merge branch 'main' into tracer_support_tree_map
SF-N File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
120 changes: 120 additions & 0 deletions
120
src/gt4py/next/iterator/transforms/unroll_tuple_maps.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| # GT4Py - GridTools Framework | ||
| # | ||
| # Copyright (c) 2014-2024, ETH Zurich | ||
| # All rights reserved. | ||
| # | ||
| # Please, refer to the LICENSE file in the root directory. | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
| import dataclasses | ||
| import functools | ||
| from typing import TypeVar | ||
|
|
||
| from gt4py import eve | ||
| from gt4py.next import common, utils | ||
| from gt4py.next.iterator import ir as itir | ||
| from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm, ir_makers as im | ||
| from gt4py.next.iterator.type_system import inference as itir_inference | ||
| from gt4py.next.type_system import type_info, type_specifications as ts | ||
|
|
||
|
|
||
| def _tree_map_tuple_body( | ||
| f: itir.Expr, tup_exprs: list[itir.Expr], tup_types: list[ts.TupleType] | ||
| ) -> itir.Expr: | ||
| """Recursively unroll `tree_map_tuple(f)(t1, ..., tN)` into `make_tuple` calls.""" | ||
|
|
||
| expected_structure = type_info.tuple_structure(tup_types[0]) | ||
| if any(type_info.tuple_structure(tup_type) != expected_structure for tup_type in tup_types[1:]): | ||
| raise TypeError("'tree_map_tuple' requires all arguments to have the same tuple structure.") | ||
|
|
||
| @utils.tree_map( | ||
| collection_type=ts.TupleType, | ||
| result_collection_constructor=lambda _, elts: im.make_tuple(*elts), | ||
| with_path_arg=True, | ||
| ) | ||
| def mapper(*args): | ||
| *_el_types, path = args | ||
| return im.call(f)( | ||
| *( | ||
| functools.reduce(lambda expr, i: im.tuple_get(i, expr), path, tup_expr) | ||
| for tup_expr in tup_exprs | ||
| ) | ||
| ) | ||
|
|
||
| return mapper(*tup_types) | ||
|
|
||
|
|
||
| def _map_tuple_body( | ||
| f: itir.Expr, tup_exprs: list[itir.Expr], tup_types: list[ts.TupleType] | ||
| ) -> itir.Expr: | ||
| """Unroll `map_tuple(f)(t)` over top-level elements only (no recursion).""" | ||
| (tup_expr,) = tup_exprs | ||
| (tup_type,) = tup_types | ||
| return im.make_tuple( | ||
| *(im.call(f)(im.tuple_get(i, tup_expr)) for i in range(len(tup_type.types))) | ||
| ) | ||
|
|
||
|
|
||
| _UNROLLERS = { | ||
| "tree_map_tuple": _tree_map_tuple_body, | ||
| "map_tuple": _map_tuple_body, | ||
| } | ||
|
|
||
|
|
||
| ProgramOrExpr = TypeVar("ProgramOrExpr", bound=itir.Program | itir.Expr) | ||
|
|
||
|
|
||
| @dataclasses.dataclass | ||
| class UnrollTupleMaps(eve.NodeTranslator): | ||
| """Unroll tuple-map ITIR builtins (`tree_map_tuple`, `map_tuple`) into `make_tuple`.""" | ||
|
|
||
| PRESERVED_ANNEX_ATTRS = ("domain",) | ||
|
|
||
| uids: utils.IDGeneratorPool | ||
|
|
||
| @classmethod | ||
| def apply( | ||
| cls, | ||
| node: ProgramOrExpr, | ||
| *, | ||
| uids: utils.IDGeneratorPool | None, | ||
| offset_provider_type: common.OffsetProviderType | None = None, | ||
| ) -> ProgramOrExpr: | ||
| if node.type is None: | ||
| node = itir_inference.infer( | ||
| node, | ||
| offset_provider_type=offset_provider_type or {}, | ||
| allow_undeclared_symbols=not isinstance(node, itir.Program), | ||
| ) | ||
| if uids is None: | ||
| uids = utils.IDGeneratorPool() | ||
| return cls(uids=uids).visit(node) | ||
|
|
||
| def visit_FunCall(self, node: itir.FunCall): | ||
| node = self.generic_visit(node) | ||
|
|
||
| if not cpm.is_call_to(node.fun, ("map_tuple", "tree_map_tuple")): | ||
| return node | ||
|
|
||
| assert isinstance(node.fun, itir.FunCall) | ||
| f = node.fun.args[0] | ||
| tup_args = node.args | ||
|
|
||
| tup_types: list[ts.TupleType] = [] | ||
| for tup in tup_args: | ||
| itir_inference.reinfer(tup) | ||
| assert isinstance(tup.type, ts.TupleType) | ||
| tup_types.append(tup.type) | ||
|
|
||
| # Introduce a `let` binding for every argument to avoid duplicating (potentially | ||
| # expensive) sub-expressions across leaf projections. We deliberately do not simplify | ||
| # the result here: the regular `CollapseTuple` pass that runs later in the pipeline | ||
| # inlines the trivial bindings back and folds any `tuple_get(i, make_tuple(...))` | ||
| # patterns, so re-implementing that logic here would only duplicate work. | ||
| let_bindings = [(next(self.uids["_utm"]), tup) for tup in tup_args] | ||
| substituted_exprs: list[itir.Expr] = [im.ref(ref_name) for ref_name, _ in let_bindings] | ||
|
|
||
| body = _UNROLLERS[node.fun.fun.id](f, substituted_exprs, tup_types) | ||
|
|
||
| result = im.let(*let_bindings)(body) | ||
| itir_inference.reinfer(result) | ||
| return result | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we should make
map_tuplesupport multiple args liketree_map_tuple.Open question: Does using multiple args in the lowering improve what collapse tuple can do before the
tree_map_tuplecan do? Then let's use that path even for the... for tuple in ...in the frontend.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tuple[0]+tuple[1] for tuple in nested_tupleor
let(tuple, {a, b})(tuple[0]+tuple[1]) for a, b in {nested_tuple[0], nested_tuple[1]}Another dimension:
a+b for a, b in nested_tupleThe interesting parts are what is the advantage / disadvantage in the lowering & unroll pass.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All examples single-arg
map_tuple(op)(n)over eg.gn : ((Field[[IDim], float64], Field[[IDim], float64]),(Field[[IDim], float64],Field[[IDim], float64])), and they collapse to the identical result:t[0] + t[1] for t in n:lowered:
map_tuple(λ(t) → t[0] + t[1])(n)before collapse:
(λ(_utm_0) → {(λ(t) → t[0] + t[1])(_utm_0[0]),(λ(t) → t[0] + t[1])(_utm_0[1])})(n)after collapse:
{n[0][0] + n[0][1], n[1][0] + n[1][1]}let(tup, {a, b})(tup[0] + tup[1]) for a, b in {n[0], n[1]}:lowered:
map_tuple(λ(t) → (λ(a) → (λ(b) → (λ(tup) → tup[0] + tup[1])({a, b}))(t[1]))(t[0]))({n[0], n[1]})before collapse:
(λ(_utm_0) → {(λ(t) → (λ(a) → (λ(b) → (λ(tup) → tup[0] + tup[1])({a, b}))(t[1]))(t[0]))(_utm_0[0]), (λ(t) → (λ(a) → (λ(b) → (λ(tup) → tup[0] + tup[1])({a, b}))(t[1]))(t[0]))(_utm_0[1])})({n[0], n[1]})after collapse:
{n[0][0] + n[0][1], n[1][0] + n[1][1]}a + b for a, b in n:lowered:
map_tuple(λ(t) → (λ(a) → (λ(b) → a + b)(t[1]))(t[0]))(n)before collapse:
(λ(_utm_0) → {(λ(t) → (λ(a) → (λ(b) → a + b)(t[1]))(t[0]))(_utm_0[0]), (λ(t) → (λ(a) → (λ(b) → a + b)(t[1]))(t[0]))(_utm_0[1])})(n)after collapse:
{n[0][0] + n[0][1], n[1][0] + n[1][1]}All three collapse to the same result, so the choice only affects the intermediate size that the unroll+collapse passes must remove.
There is no use-case for multi-arg map_tuple so far and also not in #PR2487 , whereas for tree_map_tuple the multi-arg use-case is
where(cond, a, b).Nevertheless, I tried implementing multi-arg map_tuple and no changes in the lowering were necessary, only small changes in the type_synthesizer, ir_makers and in the unroll_tuple_maps replacing
by
The only benefit would be in the case
map_tuple(λa,b → a+b)(g(), h())vsmap_tuple(λt → t[0]+t[1])(zip(g(),h()))where g()/h() would be evaluated 2× in the former and 4x in the latter. But usually a comprehension has a single source, so there is nothing independent to combine.So, I reverted the changes again and would keep map_tuple single-arg.