Skip to content

Commit

Permalink
Consistent cached lazy load. (#11068)
Browse files Browse the repository at this point in the history
- Use cache.
- Consistent naming.
  • Loading branch information
trivialfis authored Dec 7, 2024
1 parent d761e41 commit 6d55fac
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
4 changes: 4 additions & 0 deletions python-package/xgboost/compat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# pylint: disable=invalid-name,unused-import
"""For compatibility and optional dependencies."""
import functools
import importlib.util
import logging
import sys
Expand Down Expand Up @@ -84,6 +85,7 @@ class XGBRegressorBase: # type: ignore[no-redef]
_logger = logging.getLogger(__name__)


@functools.cache
def is_cudf_available() -> bool:
"""Check cuDF package available or not"""
if importlib.util.find_spec("cudf") is None:
Expand All @@ -97,6 +99,7 @@ def is_cudf_available() -> bool:
return False


@functools.cache
def is_cupy_available() -> bool:
"""Check cupy package available or not"""
if importlib.util.find_spec("cupy") is None:
Expand All @@ -109,6 +112,7 @@ def is_cupy_available() -> bool:
return False


@functools.cache
def import_cupy() -> types.ModuleType:
"""Import cupy."""
if not is_cupy_available():
Expand Down
7 changes: 4 additions & 3 deletions python-package/xgboost/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,8 @@ def _is_cudf_pandas(data: DataType) -> bool:
)


def _get_cudf_cat_predicate() -> Callable[[Any], bool]:
@functools.cache
def _lazy_load_cudf_is_cat() -> Callable[[Any], bool]:
try:
from cudf import CategoricalDtype

Expand All @@ -895,7 +896,7 @@ def _cudf_array_interfaces(data: DataType, cat_codes: list) -> bytes:
array interface is finished.
"""
is_categorical_dtype = _get_cudf_cat_predicate()
is_categorical_dtype = _lazy_load_cudf_is_cat()
interfaces = []

def append(interface: dict) -> None:
Expand Down Expand Up @@ -933,7 +934,7 @@ def _transform_cudf_df(
except ImportError:
from pandas.api.types import is_bool_dtype

is_categorical_dtype = _get_cudf_cat_predicate()
is_categorical_dtype = _lazy_load_cudf_is_cat()
# Work around https://github.com/dmlc/xgboost/issues/10181
if _is_cudf_ser(data):
if is_bool_dtype(data.dtype):
Expand Down

0 comments on commit 6d55fac

Please sign in to comment.