-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat: Experimental transpilation of unannotated python callables #17419
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
Draft
TrevorBergeron
wants to merge
1
commit into
main
Choose a base branch
from
tbergeron_transpile_path
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.
Draft
Changes from all commits
Commits
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,31 +11,185 @@ | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| from __future__ import annotations | ||
|
|
||
| import dataclasses | ||
| import inspect | ||
| import typing | ||
|
|
||
| import bigframes.core.expression as ex | ||
| import bigframes.core.identifiers as ids | ||
| import bigframes.dtypes as dtypes | ||
| from bigframes._config import options | ||
| from bigframes.functions import Udf | ||
| from bigframes.functions.udf_def import BigqueryUdf, PythonUdf | ||
| from bigframes.operations import base_ops, remote_function_ops | ||
| from bigframes.operations import remote_function_ops | ||
|
|
||
|
|
||
| @dataclasses.dataclass(frozen=True) | ||
| class ArgumentSpec: | ||
| """ | ||
| Information about a single argument to a function | ||
| """ | ||
|
|
||
| name: str | ||
| default_value: typing.Any | ||
| is_varargs: bool | ||
|
|
||
|
|
||
| def func_to_op(op) -> base_ops.NaryOp: | ||
| @dataclasses.dataclass(frozen=True) | ||
| class CallableExpression(ex.Expression): | ||
| """ | ||
| Convert various bigframes, python functions into bigframes operations. | ||
| Encodes a calling convention and an expression to bind arguments to. | ||
| """ | ||
|
|
||
| expr: ex.Expression | ||
| arg_specs: typing.Sequence[ArgumentSpec] | ||
|
|
||
| @classmethod | ||
| def from_callable( | ||
| cls, func: typing.Callable, unpack_mode: bool = False | ||
| ) -> CallableExpression: | ||
| sig = inspect.signature(func) | ||
| arg_specs = [] | ||
| for name, param in sig.parameters.items(): | ||
| is_varargs = param.kind == inspect.Parameter.VAR_POSITIONAL | ||
| arg_specs.append( | ||
| ArgumentSpec( | ||
| name=name, | ||
| default_value=param.default, | ||
| is_varargs=is_varargs, | ||
| ) | ||
| ) | ||
|
|
||
| from bigframes.core.bytecode import dis_to_expr | ||
|
|
||
| expr = dis_to_expr(func, unpack_mode=unpack_mode) | ||
| return cls(expr=expr, arg_specs=arg_specs) | ||
|
|
||
| def apply(self, *args, **kwargs) -> ex.Expression: | ||
| """ | ||
| Apply the arguments to the expression. | ||
|
|
||
| All args are expected to be column references, or scalars. | ||
| """ | ||
| bindings = {} | ||
| pos_idx = 0 | ||
|
|
||
| def to_expr(val): | ||
| if isinstance(val, ex.Expression): | ||
| return val | ||
| return ex.const(val) | ||
|
|
||
| for spec in self.arg_specs: | ||
| if spec.is_varargs: | ||
| raise NotImplementedError( | ||
| "varargs in compiled python functions is not supported" | ||
| ) | ||
|
|
||
| This should handle anything that might be passed to eg map, combine, other pandas methods that take a function. | ||
| if pos_idx < len(args): | ||
| bindings[spec.name] = to_expr(args[pos_idx]) | ||
| pos_idx += 1 | ||
| elif spec.name in kwargs: | ||
| bindings[spec.name] = to_expr(kwargs[spec.name]) | ||
| elif spec.default_value is not inspect.Parameter.empty: | ||
| bindings[spec.name] = to_expr(spec.default_value) | ||
| else: | ||
| raise TypeError(f"missing required argument: '{spec.name}'") | ||
|
|
||
| It should raise a TypeError if the object is not a supported type. | ||
| if pos_idx < len(args): | ||
| raise TypeError( | ||
| f"too many positional arguments: expected {len(self.arg_specs)}, got {len(args)}" | ||
| ) | ||
|
|
||
| Args: | ||
| op: The object to convert. | ||
| return self.expr.bind_variables(bindings) | ||
|
Comment on lines
+76
to
+105
Contributor
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.
bindings = {}
pos_idx = 0
arg_names = {spec.name for spec in self.arg_specs}
# Validate unexpected keyword arguments
for key in kwargs:
if key not in arg_names:
raise TypeError(f"got an unexpected keyword argument '{key}'")
def to_expr(val):
if isinstance(val, ex.Expression):
return val
return ex.const(val)
for spec in self.arg_specs:
if spec.is_varargs:
raise NotImplementedError(
"varargs in compiled python functions is not supported"
)
if pos_idx < len(args):
if spec.name in kwargs:
raise TypeError(f"got multiple values for keyword argument '{spec.name}'")
bindings[spec.name] = to_expr(args[pos_idx])
pos_idx += 1
elif spec.name in kwargs:
bindings[spec.name] = to_expr(kwargs[spec.name])
elif spec.default_value is not inspect.Parameter.empty:
bindings[spec.name] = to_expr(spec.default_value)
else:
raise TypeError(f"missing required argument: '{spec.name}'")
if pos_idx < len(args):
raise TypeError(
f"too many positional arguments: expected {len(self.arg_specs)}, got {len(args)}"
)
return self.expr.bind_variables(bindings) |
||
|
|
||
| Returns: | ||
| A bigframes operations. | ||
| @property | ||
| def column_references(self) -> typing.Tuple[ids.ColumnId, ...]: | ||
| return self.expr.column_references | ||
|
|
||
| @property | ||
| def free_variables(self) -> typing.Tuple[typing.Hashable, ...]: | ||
| return self.expr.free_variables | ||
|
|
||
| @property | ||
| def is_const(self) -> bool: | ||
| return self.expr.is_const | ||
|
|
||
| @property | ||
| def is_resolved(self) -> bool: | ||
| return False | ||
|
|
||
| @property | ||
| def output_type(self) -> dtypes.ExpressionType: | ||
| raise ValueError( | ||
| "CallableExpression does not have a fixed output type until arguments are applied." | ||
| ) | ||
|
|
||
| def bind_refs( | ||
| self, | ||
| bindings: typing.Mapping[ids.ColumnId, ex.Expression], | ||
| allow_partial_bindings: bool = False, | ||
| ) -> CallableExpression: | ||
| return dataclasses.replace( | ||
| self, | ||
| expr=self.expr.bind_refs( | ||
| bindings, allow_partial_bindings=allow_partial_bindings | ||
| ), | ||
| ) | ||
|
|
||
| def bind_variables( | ||
| self, | ||
| bindings: typing.Mapping[typing.Hashable, ex.Expression], | ||
| allow_partial_bindings: bool = False, | ||
| ) -> CallableExpression: | ||
| arg_names = {spec.name for spec in self.arg_specs} | ||
| filtered_bindings = {k: v for k, v in bindings.items() if k not in arg_names} | ||
| return dataclasses.replace( | ||
| self, | ||
| expr=self.expr.bind_variables( | ||
| filtered_bindings, allow_partial_bindings=allow_partial_bindings | ||
| ), | ||
| ) | ||
|
|
||
| def transform_children( | ||
| self, t: typing.Callable[[ex.Expression], ex.Expression] | ||
| ) -> ex.Expression: | ||
| new_expr = t(self.expr) | ||
| if new_expr != self.expr: | ||
| return dataclasses.replace(self, expr=new_expr) | ||
| return self | ||
|
|
||
|
|
||
| def func_to_expr(op, unpack_mode: bool = False) -> CallableExpression: | ||
| """ | ||
| Convert various bigframes, python functions into bigframes CallableExpression. | ||
| """ | ||
| # TODO(b/517578802): Handle numpy ufuncs, builtin functions, etc. | ||
| if isinstance(op, Udf): | ||
| if isinstance(op.udf_def, BigqueryUdf): | ||
| return remote_function_ops.RemoteFunctionOp(function_def=op.udf_def) | ||
| bq_op = remote_function_ops.RemoteFunctionOp(function_def=op.udf_def) | ||
| elif isinstance(op.udf_def, PythonUdf): | ||
| return remote_function_ops.PythonUdfOp(function_def=op.udf_def) | ||
| bq_op = remote_function_ops.PythonUdfOp(function_def=op.udf_def) | ||
| else: | ||
| raise TypeError(f"Unsupported UDF definition: {op.udf_def}") | ||
|
|
||
| inputs_expr = tuple( | ||
| ex.free_var(arg.name) for arg in op.udf_def.signature.inputs | ||
| ) | ||
| expr = ex.OpExpression(bq_op, inputs_expr) | ||
|
|
||
| arg_specs = [ | ||
| ArgumentSpec( | ||
| name=arg.name, | ||
| default_value=inspect.Parameter.empty, | ||
| is_varargs=False, | ||
| ) | ||
| for arg in op.udf_def.signature.inputs | ||
| ] | ||
| return CallableExpression(expr=expr, arg_specs=arg_specs) | ||
|
|
||
| elif options.experiments.enable_python_transpiler and callable(op): | ||
| return CallableExpression.from_callable(op, unpack_mode=unpack_mode) | ||
|
|
||
| else: | ||
| raise TypeError(f"Unsupported function type: {op}") | ||
Oops, something went wrong.
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.
The manual binding of
argsandkwargslacks validation for extra positional arguments and unexpected keyword arguments. This can lead to crypticIndexErrorexceptions or silent correctness bugs where unexpected keyword arguments accidentally override free variables (columns) in the expression.