-
Notifications
You must be signed in to change notification settings - Fork 28.5k
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
[SPARK-43082][CONNECT][PYTHON] Arrow-optimized Python UDFs in Spark Connect #40725
Closed
Closed
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
63bb36b
_create_arrow_py_udf
xinrong-meng d702b67
in Connect
xinrong-meng 01f7190
tests
xinrong-meng 0fb7712
- debug
xinrong-meng f46d006
docstrings
xinrong-meng 3abeef4
TEST
xinrong-meng f6fc6e1
TEST
xinrong-meng 63ef94e
rmv duplicate test
xinrong-meng 86938d5
tearDownClass
xinrong-meng f5aef18
rmv f from _create_arrow_py_udf
xinrong-meng f313063
UserWarning
xinrong-meng 5e78632
finally super tearDownClass
xinrong-meng ac86bf1
fallback to regular udf
xinrong-meng 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 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 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
48 changes: 48 additions & 0 deletions
48
python/pyspark/sql/tests/connect/test_parity_arrow_python_udf.py
This file contains 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,48 @@ | ||
# | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# 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. | ||
# | ||
|
||
import unittest | ||
|
||
from pyspark.sql.tests.connect.test_parity_udf import UDFParityTests | ||
from pyspark.sql.tests.test_arrow_python_udf import PythonUDFArrowTestsMixin | ||
|
||
|
||
class ArrowPythonUDFParityTests(UDFParityTests, PythonUDFArrowTestsMixin): | ||
@classmethod | ||
def setUpClass(cls): | ||
super(ArrowPythonUDFParityTests, cls).setUpClass() | ||
cls.spark.conf.set("spark.sql.execution.pythonUDF.arrow.enabled", "true") | ||
|
||
xinrong-meng marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@classmethod | ||
def tearDownClass(cls): | ||
try: | ||
cls.spark.conf.unset("spark.sql.execution.pythonUDF.arrow.enabled") | ||
finally: | ||
super(ArrowPythonUDFParityTests, cls).tearDownClass() | ||
|
||
|
||
if __name__ == "__main__": | ||
import unittest | ||
from pyspark.sql.tests.connect.test_parity_arrow_python_udf import * # noqa: F401 | ||
|
||
try: | ||
import xmlrunner # type: ignore[import] | ||
|
||
testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2) | ||
except ImportError: | ||
testRunner = None | ||
unittest.main(testRunner=testRunner, verbosity=2) |
This file contains 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 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 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 |
---|---|---|
|
@@ -75,6 +75,7 @@ def _create_udf( | |
name: Optional[str] = None, | ||
deterministic: bool = True, | ||
) -> "UserDefinedFunctionLike": | ||
"""Create a regular(non-Arrow-optimized) Python UDF.""" | ||
# Set the name of the UserDefinedFunction object to be the name of function f | ||
udf_obj = UserDefinedFunction( | ||
f, returnType=returnType, name=name, evalType=evalType, deterministic=deterministic | ||
|
@@ -88,6 +89,7 @@ def _create_py_udf( | |
evalType: int, | ||
useArrow: Optional[bool] = None, | ||
) -> "UserDefinedFunctionLike": | ||
"""Create a regular/Arrow-optimized Python UDF.""" | ||
# The following table shows the results when the type coercion in Arrow is needed, that is, | ||
# when the user-specified return type(SQL Type) of the UDF and the actual instance(Python | ||
# Value(Type)) that the UDF returns are different. | ||
|
@@ -138,49 +140,62 @@ def _create_py_udf( | |
and not isinstance(return_type, MapType) | ||
and not isinstance(return_type, ArrayType) | ||
) | ||
if is_arrow_enabled and is_output_atomic_type and is_func_with_args: | ||
require_minimum_pandas_version() | ||
require_minimum_pyarrow_version() | ||
|
||
import pandas as pd | ||
from pyspark.sql.pandas.functions import _create_pandas_udf # type: ignore[attr-defined] | ||
|
||
# "result_func" ensures the result of a Python UDF to be consistent with/without Arrow | ||
# optimization. | ||
# Otherwise, an Arrow-optimized Python UDF raises "pyarrow.lib.ArrowTypeError: Expected a | ||
# string or bytes dtype, got ..." whereas a non-Arrow-optimized Python UDF returns | ||
# successfully. | ||
result_func = lambda pdf: pdf # noqa: E731 | ||
if type(return_type) == StringType: | ||
result_func = lambda r: str(r) if r is not None else r # noqa: E731 | ||
elif type(return_type) == BinaryType: | ||
result_func = lambda r: bytes(r) if r is not None else r # noqa: E731 | ||
|
||
def vectorized_udf(*args: pd.Series) -> pd.Series: | ||
if any(map(lambda arg: isinstance(arg, pd.DataFrame), args)): | ||
raise NotImplementedError( | ||
"Struct input type are not supported with Arrow optimization " | ||
"enabled in Python UDFs. Disable " | ||
"'spark.sql.execution.pythonUDF.arrow.enabled' to workaround." | ||
) | ||
return pd.Series(result_func(f(*a)) for a in zip(*args)) | ||
|
||
# Regular UDFs can take callable instances too. | ||
vectorized_udf.__name__ = f.__name__ if hasattr(f, "__name__") else f.__class__.__name__ | ||
vectorized_udf.__module__ = ( | ||
f.__module__ if hasattr(f, "__module__") else f.__class__.__module__ | ||
) | ||
vectorized_udf.__doc__ = f.__doc__ | ||
pudf = _create_pandas_udf(vectorized_udf, returnType, None) | ||
# Keep the attributes as if this is a regular Python UDF. | ||
pudf.func = f | ||
pudf.returnType = return_type | ||
pudf.evalType = regular_udf.evalType | ||
return pudf | ||
if is_arrow_enabled: | ||
if is_output_atomic_type and is_func_with_args: | ||
return _create_arrow_py_udf(regular_udf) | ||
else: | ||
warnings.warn( | ||
"Arrow optimization for Python UDFs cannot be enabled.", | ||
UserWarning, | ||
) | ||
return regular_udf | ||
else: | ||
return regular_udf | ||
|
||
|
||
def _create_arrow_py_udf(regular_udf): # type: ignore | ||
"""Create an Arrow-optimized Python UDF out of a regular Python UDF.""" | ||
require_minimum_pandas_version() | ||
require_minimum_pyarrow_version() | ||
|
||
import pandas as pd | ||
from pyspark.sql.pandas.functions import _create_pandas_udf | ||
|
||
f = regular_udf.func | ||
return_type = regular_udf.returnType | ||
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. it seems that the 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. And |
||
|
||
# "result_func" ensures the result of a Python UDF to be consistent with/without Arrow | ||
# optimization. | ||
# Otherwise, an Arrow-optimized Python UDF raises "pyarrow.lib.ArrowTypeError: Expected a | ||
# string or bytes dtype, got ..." whereas a non-Arrow-optimized Python UDF returns | ||
# successfully. | ||
result_func = lambda pdf: pdf # noqa: E731 | ||
if type(return_type) == StringType: | ||
result_func = lambda r: str(r) if r is not None else r # noqa: E731 | ||
elif type(return_type) == BinaryType: | ||
result_func = lambda r: bytes(r) if r is not None else r # noqa: E731 | ||
|
||
def vectorized_udf(*args: pd.Series) -> pd.Series: | ||
if any(map(lambda arg: isinstance(arg, pd.DataFrame), args)): | ||
raise NotImplementedError( | ||
"Struct input type are not supported with Arrow optimization " | ||
"enabled in Python UDFs. Disable " | ||
"'spark.sql.execution.pythonUDF.arrow.enabled' to workaround." | ||
) | ||
return pd.Series(result_func(f(*a)) for a in zip(*args)) | ||
|
||
# Regular UDFs can take callable instances too. | ||
vectorized_udf.__name__ = f.__name__ if hasattr(f, "__name__") else f.__class__.__name__ | ||
vectorized_udf.__module__ = f.__module__ if hasattr(f, "__module__") else f.__class__.__module__ | ||
vectorized_udf.__doc__ = f.__doc__ | ||
pudf = _create_pandas_udf(vectorized_udf, return_type, None) | ||
# Keep the attributes as if this is a regular Python UDF. | ||
pudf.func = f | ||
pudf.returnType = return_type | ||
pudf.evalType = regular_udf.evalType | ||
return pudf | ||
|
||
|
||
class UserDefinedFunction: | ||
""" | ||
User defined function in Python | ||
|
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.
There is duplicated code in
_create_py_udf
between Spark Connect Python Client and vanilla PySpark, except for fetching the active SparkSession.However, for a clear code path separation and abstraction, I decided not to refactor it for now.