Repository navigation
feat[next]: call-site scan builtin #2920
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -163,6 +163,64 @@ def _no_implicit_conversion_diagnostic(left: foast.Expr, right: foast.Expr) -> d | |
| } | ||
|
|
||
|
|
||
| def _is_scan_builtin(expr: foast.Expr) -> bool: | ||
| return isinstance(expr, foast.Name) and expr.id == "scan" | ||
|
|
||
|
|
||
| def _is_literal(expr: foast.Expr) -> bool: | ||
| match expr: | ||
| case foast.Constant(): | ||
| return True | ||
| case foast.TupleExpr(): | ||
| return all(_is_literal(el) for el in expr.elts) | ||
| case foast.UnaryOp(): | ||
| return _is_literal(expr.operand) | ||
| case foast.Call(func=foast.Name(type=ts.ConstructorType())): | ||
| return all(_is_literal(arg) for arg in expr.args) | ||
| return False | ||
|
Comment on lines
+166
to
+180
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. move to foast_passes/utils.py |
||
|
|
||
|
|
||
| def _check_scan_pass( | ||
| location: eve.SourceLocation, | ||
| name: str, | ||
| pass_type: ts.FunctionType, | ||
| forward_type: ts.TypeSpec, | ||
| init_type: ts.TypeSpec, | ||
| ) -> None: | ||
| if not (isinstance(forward_type, ts.ScalarType) and forward_type.kind == ts.ScalarKind.BOOL): | ||
| raise errors.DSLError( | ||
| location, f"Argument 'forward' to scan operator '{name}' must be a boolean." | ||
| ) | ||
| if not all( | ||
| type_info.is_arithmetic(type_) or type_info.is_logical(type_) | ||
| for type_ in type_info.primitive_constituents(init_type) | ||
| ): | ||
| raise errors.DSLError( | ||
| location, | ||
| f"Argument 'init' to scan operator '{name}' must " | ||
| "be an arithmetic type or a logical type or a composite of arithmetic and logical types.", | ||
| ) | ||
| if not pass_type.pos_or_kw_args: | ||
| raise errors.DSLError( | ||
| location, | ||
| f"Scan operator '{name}' must have at least one argument (the carry).", | ||
| ) | ||
| carry_arg_name = next(iter(pass_type.pos_or_kw_args.keys())) | ||
| carry_type = pass_type.pos_or_kw_args[carry_arg_name] | ||
| if carry_type != pass_type.returns: | ||
| raise errors.DSLError( | ||
| location, | ||
| f"Argument '{carry_arg_name}' to scan operator '{name}' must have same type as its return: " | ||
| f"expected '{pass_type.returns}', got '{carry_type}'.", | ||
| ) | ||
| elif init_type != carry_type: | ||
| raise errors.DSLError( | ||
| location, | ||
| f"Argument 'init' to scan operator '{name}' must have same type as '{carry_arg_name}' argument: " | ||
| f"expected '{carry_type}', got '{init_type}'.", | ||
| ) | ||
|
|
||
|
|
||
| class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator): | ||
| """ | ||
| Deduce and check types of FOAST expressions and symbols. | ||
|
|
@@ -250,51 +308,115 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S | |
| f"Argument 'axis' to scan operator '{node.id}' must be a vertical dimension.", | ||
| ) | ||
| new_forward = self.visit(node.forward, **kwargs) | ||
| if not new_forward.type.kind == ts.ScalarKind.BOOL: | ||
| raise errors.DSLError( | ||
| node.location, f"Argument 'forward' to scan operator '{node.id}' must be a boolean." | ||
| ) | ||
| new_init = self.visit(node.init, **kwargs) | ||
| if not all( | ||
| type_info.is_arithmetic(type_) or type_info.is_logical(type_) | ||
| for type_ in type_info.primitive_constituents(new_init.type) | ||
| ): | ||
| new_definition = self.visit(node.definition, **kwargs) | ||
| _check_scan_pass( | ||
| node.location, node.id, new_definition.type, new_forward.type, new_init.type | ||
| ) | ||
|
|
||
| new_type = ts_ffront.ScanOperatorType( | ||
| axis=new_axis.type.dim, definition=new_definition.type | ||
| ) | ||
| return foast.ScanOperator( | ||
| id=node.id, | ||
| axis=new_axis, | ||
| forward=new_forward, | ||
| init=new_init, | ||
| definition=new_definition, | ||
| type=new_type, | ||
| location=node.location, | ||
| ) | ||
|
|
||
| def _visit_scan_call( | ||
| self, node: foast.Call, scan_arg_types: list[ts.TypeSpec], **kwargs: Any | ||
| ) -> foast.Call: | ||
| """Type `scan(pass, axis=..., forward=..., init=...)`, the callee of a call-site scan.""" | ||
| new_func = self.visit(node.func, **kwargs) | ||
| if len(node.args) != 1: | ||
| raise errors.DSLError( | ||
| node.location, | ||
| f"Argument 'init' to scan operator '{node.id}' must " | ||
| "be an arithmetic type or a logical type or a composite of arithmetic and logical types.", | ||
| f"'scan' takes exactly one positional argument (the scan pass), got {len(node.args)}.", | ||
| ) | ||
| new_definition = self.visit(node.definition, **kwargs) | ||
| new_def_type = new_definition.type | ||
| if not new_def_type.pos_or_kw_args: | ||
| if unexpected := set(node.kwargs) - {"axis", "forward", "init"}: | ||
| raise errors.DSLError( | ||
| node.location, | ||
| f"Scan operator '{node.id}' must have at least one argument (the carry).", | ||
| f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.", | ||
| ) | ||
| carry_arg_name = next(iter(new_def_type.pos_or_kw_args.keys())) | ||
| carry_type = new_def_type.pos_or_kw_args[carry_arg_name] | ||
| if carry_type != new_def_type.returns: | ||
| new_pass = self.visit(node.args[0], **kwargs) | ||
| if not isinstance(new_pass.type, ts_ffront.FieldOperatorType): | ||
| raise errors.DSLError( | ||
| node.location, | ||
| f"Argument '{carry_arg_name}' to scan operator '{node.id}' must have same type as its return: " | ||
| f"expected '{new_def_type.returns}', got '{carry_type}'.", | ||
| new_pass.location, | ||
| f"The scan pass must be a field operator, got '{new_pass.type}'.", | ||
| ) | ||
| elif new_init.type != carry_type: | ||
| pass_type = new_pass.type.definition | ||
| pass_name = str(new_pass) | ||
|
|
||
| new_kwargs = { | ||
| "forward": foast.Constant(value=True, location=node.location), | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. defaults should come from lowering
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed. Type deduction shouldn't rewrite the node with materialised defaults. Recommendation: leave absent kwargs absent in FOAST and insert the literals in 🤖 Written by an agent on behalf of @havogt |
||
| "init": foast.Constant(value=0.0, location=node.location), | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. does init have a default value?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Currently yes: Recommendation: make 🤖 Written by an agent on behalf of @havogt
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In a separate PR we should remove the default from init.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed. #2920 keeps Recommendation: do it in the same follow-up that makes 🤖 Written by an agent on behalf of @havogt |
||
| **node.kwargs, | ||
| } | ||
| new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in new_kwargs.items()} | ||
| for name in ("forward", "init"): | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. init should be runtime
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Dropping this check alone doesn't work. GTIR stencils must be closed, and a non-literal There is an approach that works without any GTIR or backend change, and it is already implemented on the stacked branch Recommendation: keep #2920 compile-time and make runtime 🤖 Written by an agent on behalf of @havogt |
||
| if not _is_literal(new_kwargs[name]): | ||
| raise errors.DSLError( | ||
| new_kwargs[name].location, | ||
| f"Argument '{name}' to 'scan' must be a compile-time constant.", | ||
| ) | ||
| _check_scan_pass( | ||
| node.location, pass_name, pass_type, new_kwargs["forward"].type, new_kwargs["init"].type | ||
| ) | ||
| if not all( | ||
| isinstance(t, ts.ScalarType) | ||
| for param in [*pass_type.pos_or_kw_args.values(), pass_type.returns] | ||
| for t in type_info.primitive_constituents(param) | ||
| ): | ||
| raise errors.DSLError( | ||
| node.location, | ||
| f"Argument 'init' to scan operator '{node.id}' must have same type as '{carry_arg_name}' argument: " | ||
| f"expected '{carry_type}', got '{new_init.type}'.", | ||
| new_pass.location, | ||
| f"The scan pass '{pass_name}' must take and return scalars or tuples of scalars.", | ||
| ) | ||
| if pass_type.pos_only_args or pass_type.kw_only_args: | ||
| raise errors.DSLError( | ||
| new_pass.location, | ||
| f"The scan pass '{pass_name}' must not have positional-only or keyword-only arguments.", | ||
| ) | ||
|
|
||
| new_type = ts_ffront.ScanOperatorType(axis=new_axis.type.dim, definition=new_def_type) | ||
| return foast.ScanOperator( | ||
| id=node.id, | ||
| axis=new_axis, | ||
| forward=new_forward, | ||
| init=new_init, | ||
| definition=new_definition, | ||
| type=new_type, | ||
| if "axis" in new_kwargs: | ||
| axis_type = new_kwargs["axis"].type | ||
| if not isinstance(axis_type, ts.DimensionType): | ||
| raise errors.DSLError( | ||
| new_kwargs["axis"].location, "Argument 'axis' to 'scan' must be a dimension." | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. have only one check of the kwargs shared between scan_call and ScanOperator.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed. Recommendation: fold the axis check into the shared helper so it covers all three kwargs, e.g. 🤖 Written by an agent on behalf of @havogt |
||
| ) | ||
| axis = axis_type.dim | ||
| if axis.kind != DimensionKind.VERTICAL: | ||
| raise errors.DSLError( | ||
| new_kwargs["axis"].location, | ||
| "Argument 'axis' to 'scan' must be a vertical dimension.", | ||
| ) | ||
| else: | ||
| vertical_dims = { | ||
| dim | ||
| for arg_type in scan_arg_types | ||
| for el in type_info.primitive_constituents(arg_type) | ||
| for dim in type_info.extract_dims(el) | ||
| if dim.kind == DimensionKind.VERTICAL | ||
| } | ||
| if len(vertical_dims) != 1: | ||
| found = ", ".join(sorted(f"'{d.value}'" for d in vertical_dims)) or "none" | ||
| raise errors.DSLError( | ||
| node.location, | ||
| "Cannot infer the 'axis' of 'scan' from its arguments, expected exactly one " | ||
| f"vertical dimension, found {found}.", | ||
| hints=["Pass the axis explicitly, e.g. 'scan(..., axis=KDim)'."], | ||
| ) | ||
| (axis,) = vertical_dims | ||
|
|
||
| return foast.Call( | ||
| func=new_func, | ||
| args=[new_pass], | ||
| kwargs=new_kwargs, | ||
| location=node.location, | ||
| type=ts_ffront.ScanOperatorType(axis=axis, definition=pass_type), | ||
| ) | ||
|
|
||
| def visit_Name(self, node: foast.Name, **kwargs: Any) -> foast.Name: | ||
|
|
@@ -757,9 +879,22 @@ def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> foast.TupleEx | |
| return foast.TupleExpr(elts=new_elts, type=new_type, location=node.location) | ||
|
|
||
| def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: | ||
| new_func = self.visit(node.func, **kwargs) | ||
| if _is_scan_builtin(node.func): | ||
| raise errors.DSLError( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can we remove this limitation
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not in this PR, in my view. Allowing
GTIR already supports this, and Recommendation: keep the limitation in #2920 and lift it in the HOF PR, together with removing the scan-specific special cases at L890 and L917. Relaxing it here would grow the scan-specific code that the HOF PR then throws away. 🤖 Written by an agent on behalf of @havogt |
||
| node.location, | ||
| "'scan' creates a scan operator which must be called directly: " | ||
| "'scan(scan_pass, ...)(args)'.", | ||
| ) | ||
| new_args = self.visit(node.args, **kwargs) | ||
| new_kwargs = self.visit(node.kwargs, **kwargs) | ||
| if isinstance(node.func, foast.Call) and _is_scan_builtin(node.func.func): | ||
| new_func = self._visit_scan_call( | ||
| node.func, | ||
| scan_arg_types=[arg.type for arg in [*new_args, *new_kwargs.values()]], | ||
| **kwargs, | ||
| ) | ||
| else: | ||
| new_func = self.visit(node.func, **kwargs) | ||
|
|
||
| func_type = new_func.type | ||
| arg_types = [arg.type for arg in new_args] | ||
|
|
@@ -779,6 +914,9 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: | |
| if not isinstance( | ||
| new_func, | ||
| (foast.FunctionDefinition, foast.FieldOperator, foast.ScanOperator, foast.Name), | ||
| ) and not ( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. mention here that scan is the only higher order function (if it applies here).
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, it applies. Recommendation: add a one-line comment on the clause: " 🤖 Written by an agent on behalf of @havogt |
||
| isinstance(new_func, foast.Call) | ||
| and isinstance(new_func.type, ts_ffront.ScanOperatorType) | ||
| ): | ||
| raise errors.DSLError(node.location, "Functions can only be called directly.") | ||
| elif isinstance(new_func.type, ts.FieldType): | ||
|
|
@@ -811,6 +949,7 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: | |
| f"Expression of type '{new_func.type}' is not callable, must be a 'Function', 'FieldOperator', 'ScanOperator' or 'Field'.", | ||
| ) | ||
|
|
||
| assert isinstance(func_type, ts.CallableType) | ||
| # ensure signature is valid | ||
| try: | ||
| type_info.accepts_args( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -351,7 +351,11 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr: | |
| return current_expr | ||
|
|
||
| def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: | ||
| if type_info.type_class(node.func.type) is ts.FieldType: | ||
| if isinstance(node.func, foast.Call) and isinstance( | ||
| node.func.type, ts_ffront.ScanOperatorType | ||
| ): | ||
| return self._visit_scan_call(node, **kwargs) | ||
| elif type_info.type_class(node.func.type) is ts.FieldType: | ||
| return self._visit_shift(node, **kwargs) | ||
| elif isinstance(node.func, foast.Name) and node.func.id in fbuiltins.MATH_BUILTIN_NAMES: | ||
| return self._visit_math_built_in(node, **kwargs) | ||
|
|
@@ -393,6 +397,26 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: | |
| f"Call to object of type '{type(node.func.type).__name__}' not understood." | ||
| ) | ||
|
|
||
| def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: | ||
| # `scan(scan_pass, forward=..., init=...)(*args)` | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is there overlap between this and visitScanOperator
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes. Both end in
After Recommendation: extract one helper, e.g. 🤖 Written by an agent on behalf of @havogt |
||
| scan_call = node.func | ||
| assert isinstance(scan_call, foast.Call) | ||
| assert isinstance(scan_call.type, ts_ffront.ScanOperatorType) | ||
| scan_pass = self.visit(scan_call.args[0], **kwargs) | ||
| forward = self.visit(scan_call.kwargs["forward"], **kwargs) | ||
| init = self.visit(scan_call.kwargs["init"], **kwargs) | ||
|
|
||
| lowered_args, lowered_kwargs = type_info.canonicalize_arguments( | ||
| scan_call.type, self.visit(node.args, **kwargs), self.visit(node.kwargs, **kwargs) | ||
| ) | ||
| stencil_args = [*lowered_args, *lowered_kwargs.values()] | ||
| carry = next(self.uid_generator["__scan_carry"]) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why do we need to generate the name? and not use the name of the first parameter of the scanpass.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is no real need. The λ is a fresh scope, and its only free symbol is the reference to the pass itself. A collision would only happen if a pass parameter had the same name as the pass, which isn't worth guarding against. Recommendation: use the pass's own parameter names, 🤖 Written by an agent on behalf of @havogt
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. let's keep as is |
||
| params = [next(self.uid_generator["__scan_arg"]) for _ in stencil_args] | ||
| definition = im.lambda_(carry, *params)( | ||
| im.call(scan_pass)(carry, *(im.deref(param) for param in params)) | ||
| ) | ||
| return im.as_fieldop(im.scan(definition, forward, init))(*stencil_args) | ||
|
|
||
| def _visit_astype(self, node: foast.Call, **kwargs: Any) -> itir.Expr: | ||
| # Note: the type to convert to is uniquely identified by its GT4Py type (`ConstructorType`), | ||
| # not by e.g. its name. | ||
|
|
||
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.
don't we have a similar check somewhere else on foast level?
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.
There are similar checks, but none we can reuse:
func_to_foast._verify_builtin_type_constructor: Python-AST level, acceptsConstantor±Constant, for type-constructor arguments.foast_to_gtir._visit_type_constr: the same shape again, raised only at lowering.foast_passes/utils.expr_to_index:±intconstants for tuple indices.None of them handles tuples or constructor calls, which a tuple
initneeds.Recommendation: keep
_is_literalhere for now and delete it in the runtime-initPR. Then onlyforwardneeds the check, and that is a plainisinstance(..., foast.Constant).forward=FWDwith a closure variable still works, becauseClosureVarFoldingturns it into aConstantbefore type deduction (func_to_foast.py:187-190).🤖 Written by an agent on behalf of @havogt