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 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
aa42037
Implemented NumbaExecutionEngine
arthurlw May 23, 2025
db9f3b0
whatsnew
arthurlw May 23, 2025
4cb240d
precommit
arthurlw May 23, 2025
97d9063
Match function arguments
arthurlw May 24, 2025
69e0e35
Fix CI
arthurlw May 24, 2025
7365079
updated whatsnew
arthurlw May 28, 2025
c605857
Updated conditions and delegate method to numba.jit
arthurlw May 29, 2025
24a0615
Added try and except to catch ImportError
arthurlw Jun 3, 2025
b7a2ecb
Use import_optional_dependency to load Numba
arthurlw Jun 10, 2025
545db65
Merge branch 'main' into numba_execution_engine
arthurlw Jun 10, 2025
6f4fb50
Updated engine handling: normalizing numba to a fake decorator and up…
arthurlw Jun 17, 2025
221cf7c
Added check for empty engine_kwargs
arthurlw Jun 17, 2025
ed8dc7f
Moved checks from Apply.apply to NumbaExecutionEngine.apply
arthurlw Jun 17, 2025
65b9d32
Fixed CI, removed unused numba checks, updated raw=false condition, u…
arthurlw Jun 18, 2025
2703f86
Implement and refactor raw=False logic into NumbaExecutionEngine.apply
arthurlw Jun 19, 2025
347463e
Fix CI, update validate_values_for_numba params
arthurlw Jun 19, 2025
77eb146
Adjust error messages
arthurlw Jun 19, 2025
90f264f
Remove Numba-specific logic from FrameApply, added Series import to v…
arthurlw Jun 19, 2025
f8f1166
pre-commit
arthurlw Jun 19, 2025
bc2939b
Updated with reviewer suggestions and added axis normalizing
arthurlw Jun 21, 2025
176753b
Updated executor to accept decorator
arthurlw Jun 21, 2025
cf3e392
Fix CI and pre-commit
arthurlw Jun 21, 2025
a4bac18
Silence pyright warning for untyped decorator
arthurlw Jun 22, 2025
ca91e89
Revert elif to if
arthurlw Jun 22, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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`)
- :meth:`pandas.api.interchange.from_dataframe` now uses the `PyCapsule Interface <https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html>`_ if available, only falling back to the Dataframe Interchange Protocol if that fails (:issue:`60739`)
- 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`)
Expand Down
76 changes: 62 additions & 14 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
cast,
)

import numba
Copy link
Member

Choose a reason for hiding this comment

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

numba is not a required pandas dependency, I think this will make import pandas raise an ImportError for users with no numba installed, even if they don't call any numba functionality.

I think we've got an import_optional_dependency function that we call inside the functions where numba is used to avoid this problem.

import numpy as np

from pandas._libs.internals import BlockValuesRefs
Expand Down Expand Up @@ -178,6 +179,60 @@ 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.")
Copy link
Member

Choose a reason for hiding this comment

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

This is the error when users write something like df.map(func, engine=numba.jit). I think it'll be easier to understand for users if the message is something like The Numba engine is not implemented for the map method 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.
"""
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(
Copy link
Member

Choose a reason for hiding this comment

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

I personally wouldn't abbreviate to nb, it's not super clear imho. Just calling this numba_looper seems better. nb is often used for notebook, and probably other things.

func,
**get_jit_arguments(engine_kwargs),
Copy link
Member

Choose a reason for hiding this comment

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

I think we can make this simpler if you change generate_apply_looper to receive the decorator instead. I checked and it doesn't seem like generate_apply_looper is used elsewhere, so the change should be quite straightforward.

What you are doing now is to extract the nogil... from the numba.jit decorator, and then inside of generate_apply_looper the decorator is created again with the nogil... The idea is to just pass decorator and use it there, so you can forget about engine_kwargs.

Copy link
Member Author

Choose a reason for hiding this comment

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

I also noticed that generate_numba_apply_func and apply_with_numba for when raw=false also re-created the JIT decorator manually. Will update these functions in the next commit

)
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 @@ -1094,23 +1149,16 @@ def wrapper(*args, **kwargs):
return wrapper

if engine == "numba":
args, kwargs = prepare_function_arguments(
self.func, # type: ignore[arg-type]
if not hasattr(numba.jit, "__pandas_udf__"):
numba.jit.__pandas_udf__ = NumbaExecutionEngine
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
Loading