Skip to content

Implemented NumbaExecutionEngine #61487

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
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Other enhancements
^^^^^^^^^^^^^^^^^^
- :class:`pandas.api.typing.FrozenList` is available for typing the outputs of :attr:`MultiIndex.names`, :attr:`MultiIndex.codes` and :attr:`MultiIndex.levels` (:issue:`58237`)
- :class:`pandas.api.typing.SASReader` is available for typing the output of :func:`read_sas` (:issue:`55689`)
- :meth:`DataFrame.apply` accepts Numba as an engine by passing the JIT decorator directly, e.g. ``df.apply(func, engine=numba.jit)`` (:issue:`61458`)
- Added :meth:`.Styler.to_typst` to write Styler objects to file, buffer or string in Typst format (:issue:`57617`)
- Added missing :meth:`pandas.Series.info` to API reference (:issue:`60926`)
- :class:`pandas.api.typing.NoDefault` is available for typing ``no_default``
Expand Down
120 changes: 88 additions & 32 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,84 @@ def apply(
"""


class NumbaExecutionEngine(BaseExecutionEngine):
"""
Numba-based execution engine for pandas apply and map operations.
"""

@staticmethod
def map(
data: np.ndarray | Series | DataFrame,
func,
args: tuple,
kwargs: dict,
decorator: Callable | None,
skip_na: bool,
):
"""
Elementwise map for the Numba engine. Currently not supported.
"""
raise NotImplementedError("Numba map is not implemented yet.")

@staticmethod
def apply(
data: np.ndarray | Series | DataFrame,
func,
args: tuple,
kwargs: dict,
decorator: Callable,
axis: int | str,
):
"""
Apply `func` along the given axis using Numba.
"""

if is_list_like(func):
raise NotImplementedError(
"the 'numba' engine doesn't support lists of callables yet"
)

if isinstance(func, str):
raise NotImplementedError(
"the 'numba' engine doesn't support using "
"a string as the callable function"
)

elif isinstance(func, np.ufunc):
raise NotImplementedError(
"the 'numba' engine doesn't support "
"using a numpy ufunc as the callable function"
)

# check for data typing
if not isinstance(data, np.ndarray):
if len(data.columns) == 0 and len(data.index) == 0:
return data.copy() # mimic apply_empty_result()
return FrameApply.apply_standard()

engine_kwargs: dict[str, bool] | None = (
decorator if isinstance(decorator, dict) else None
)

looper_args, looper_kwargs = prepare_function_arguments(
func,
args,
kwargs,
num_required_args=1,
)
# error: Argument 1 to "__call__" of "_lru_cache_wrapper" has
# incompatible type "Callable[..., Any] | str | list[Callable
# [..., Any] | str] | dict[Hashable,Callable[..., Any] | str |
# list[Callable[..., Any] | str]]"; expected "Hashable"
nb_looper = generate_apply_looper(
func,
**get_jit_arguments(engine_kwargs),
)
result = nb_looper(data, axis, *looper_args)
# If we made the result 2-D, squeeze it back to 1-D
return np.squeeze(result)


def frame_apply(
obj: DataFrame,
func: AggFuncType,
Expand Down Expand Up @@ -957,10 +1035,6 @@ def apply(self) -> DataFrame | Series:

# dispatch to handle list-like or dict-like
if is_list_like(self.func):
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support lists of callables yet"
)
return self.apply_list_or_dict_like()

# all empty
Expand All @@ -969,31 +1043,17 @@ def apply(self) -> DataFrame | Series:

# string dispatch
if isinstance(self.func, str):
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support using "
"a string as the callable function"
)
return self.apply_str()

# ufunc
elif isinstance(self.func, np.ufunc):
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support "
"using a numpy ufunc as the callable function"
)
with np.errstate(all="ignore"):
results = self.obj._mgr.apply("apply", func=self.func)
# _constructor will retain self.index and self.columns
return self.obj._constructor_from_mgr(results, axes=results.axes)

# broadcasting
if self.result_type == "broadcast":
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support result_type='broadcast'"
)
return self.apply_broadcast(self.obj)

# one axis empty
Expand Down Expand Up @@ -1094,23 +1154,19 @@ def wrapper(*args, **kwargs):
return wrapper

if engine == "numba":
args, kwargs = prepare_function_arguments(
self.func, # type: ignore[arg-type]
numba = import_optional_dependency("numba")

if not hasattr(numba.jit, "__pandas_udf__"):
numba.jit.__pandas_udf__ = NumbaExecutionEngine
Comment on lines +1159 to +1160
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I think it'd be a simpler approach is to implement this logic here:

https://github.com/pandas-dev/pandas/blob/main/pandas/core/frame.py#L10563

There, now we are considering two cases:

  • No engine (default engine) or string engine (numba engine)
  • engine with __pandas_udf__

I would simplify that and just support engines with the engine interface __pandas_udf__:

  • No engine
  • __pandas_udf__

Since we want to support engine="numba" for now, for compatibility reasons, what I would do is immediately after DataFrame.apply is called, convert the "numba" string to a "fake" numba decorator with the __pandas_udf__ containing the the NumaExecutionEngine class. Something like:

def apply(...):
    if engine == "numba":
        numba = import_optional_dependency("numba")
        numba_jit = numba.jit(**engine_kwargs)
        numba_jit.__pandas_udf__ = NumbaExecutionEngine

From this point, all the code can pretend engine is going to be None for the default Python engine, or a __pandas_udf__ class, which should make things significantly.

The challenge is that numba and the default engine share some code, and with this approach they'll be running independently. The default engine won't know anything about an engine parameter, and the numba engine will run NumbaExecutionEngine.apply. If we don't want to repeat code, we'll probably have to restructure a bit the code, so some functions are generic and called by both engines.

When we move the default engine to a PythonExecutionEngine class, maybe it's a good idea to have the base class with the code reused by different engines. But I think that change is to big to address in a single PR, so I'd see what can be done for now that it's not too big of a change.

Does this approach makes sense to you?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes this makes sense thank you


result = numba.jit.__pandas_udf__.apply(
self.values,
self.func,
self.args,
self.kwargs,
num_required_args=1,
)
# error: Argument 1 to "__call__" of "_lru_cache_wrapper" has
# incompatible type "Callable[..., Any] | str | list[Callable
# [..., Any] | str] | dict[Hashable,Callable[..., Any] | str |
# list[Callable[..., Any] | str]]"; expected "Hashable"
nb_looper = generate_apply_looper(
self.func, # type: ignore[arg-type]
**get_jit_arguments(engine_kwargs),
engine_kwargs,
self.axis,
)
result = nb_looper(self.values, self.axis, *args)
# If we made the result 2-D, squeeze it back to 1-D
result = np.squeeze(result)
else:
result = np.apply_along_axis(
wrap_function(self.func),
Expand Down
21 changes: 12 additions & 9 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@
roperator,
)
from pandas.core.accessor import Accessor
from pandas.core.apply import reconstruct_and_relabel_result
from pandas.core.apply import NumbaExecutionEngine, reconstruct_and_relabel_result
from pandas.core.array_algos.take import take_2d_multi
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import (
Expand Down Expand Up @@ -10616,14 +10616,17 @@ def apply(
significant amount of time to run. Fast functions are unlikely to run faster
with JIT compilation.
"""
if engine is None or isinstance(engine, str):
from pandas.core.apply import frame_apply

if engine is None:
engine = "python"
if engine == "numba":
numba = import_optional_dependency("numba")
if engine_kwargs is not None:
numba_jit = numba.jit(**engine_kwargs)
else:
numba_jit = numba.jit()
numba_jit.__pandas_udf__ = NumbaExecutionEngine
engine = numba_jit

if engine not in ["python", "numba"]:
raise ValueError(f"Unknown engine '{engine}'")
if engine is None or engine == "python":
from pandas.core.apply import frame_apply

op = frame_apply(
self,
Expand All @@ -10632,7 +10635,7 @@ def apply(
raw=raw,
result_type=result_type,
by_row=by_row,
engine=engine,
engine="python",
engine_kwargs=engine_kwargs,
args=args,
kwargs=kwargs,
Expand Down
Loading