Skip to content

[python-package] make some imports lazy: 'dask', 'graphviz', 'joblib', 'matplotlib', 'psutil' - #7340

Merged
jameslamb merged 14 commits into
masterfrom
python/lazy-imports
Jun 26, 2026
Merged

jameslamb merged 14 commits into
masterfrom
python/lazy-imports

Conversation

@jameslamb

Copy link
Copy Markdown
Member

Contributes to #7327

For years, lightgbm has handled optional dependencies and compatibility patches in compat.py. This has served the project well by standardizing the way those things are handled and reducing repetition.

But thinking hard about import times, I realized a significant drawback of this approach... centralizing all those things means that all those optional dependencies are eagerly loaded by the first lightgbm import. In other words, if dask or matplotlib is installed in the environment, import lightgbm will cause it to be imported, even if your code doesn't need it.

That memory usage and time might not be meaningful for training workloads, but it definitely could be for inference-only workloads.

This is the first in a series of PRs aimed at addressing that. It proposes making the following imports lazy:

  • dask
  • graphviz
  • joblib
  • matplotlib
  • psutil

Notes for Reviewers

Impact + How I tested this

Created a script that times a cold (first-time) and cached (not first time) import lightgbm.

import-timings.sh (click me)
# !/bin/bash

set -e -u -o pipefail

refresh-env() {
    echo "refreshing env"
    # macOS has a system called 'GateKeeper' that scans every .dylib the first time it's loaded.
    # recreating the venv forces reinstallation which most closely simulates a cold start on macOS
    deactivate > /dev/null 2>&1 || true
    rm -rf ./{build,dist,.import-testing,lib_lightgbm.*,lightgbm-python}

    echo "  * creating venv"
    python -m venv .import-testing > /dev/null 2>&1
    source .import-testing/bin/activate

    echo "  * building wheel"
    sh build-python.sh --nomp bdist_wheel > /dev/null 2>&1

    echo "  * installing 'lightgbm' and dependencies"
    pip uninstall --yes lightgbm > /dev/null 2>&1
    pip install "$(echo ./dist/lightgbm*.whl)[arrow,dask,pandas,plotting,scikit-learn]" > /dev/null 2>&1

    echo "  * deleting pycache files"
    # removing the pycache files and clearing OS cache help ensure a worst-case load time
    find .import-testing -type d -name '__pycache__' -exec rm -rf '{}' \; > /dev/null 2>&1 || true

    echo ""
    echo "done refreshing env"
    echo ""
}

echo "--- cold import ---"
refresh-env
time python -c "import lightgbm"

echo "--- warm import ---"
time python -c "import lightgbm"

echo "--- profiling ---"
python -X importtime -c "import lightgbm" 2>&1 | sort -t'|' -k2 -rn | head -100

Compared to the baseline from #7327, as of this PR the first import lightgbm on my M2 Mac is about 4 seconds faster.

baseline this PR
cold 0m29.743s 0m25.334s
warm 0m1.207s 0m0.797s

I don't think much of that is attributable to dropping pyarrow imports in #7275, as I still see pyarrow in the output of python -X importtime.

I calculated where import lightgbm is spending its time like this:

python -X importtime -c "import lightgbm" 2>&1 | sort -t'|' -k2 -rn | head -100
output (click me)
--- profiling ---
import time:       322 |     701563 | lightgbm
import time:      2198 |     690676 |   lightgbm.basic
import time:       119 |     571229 |     lightgbm.compat
import time:       134 |     543162 |       sklearn
import time:       289 |     541146 |         sklearn.base
import time:        13 |     539789 |           sklearn.utils._metadata_requests
import time:       103 |     539777 |             sklearn.utils
import time:        88 |     535018 |               sklearn.utils._chunking
import time:       347 |     534931 |                 sklearn.utils._param_validation
import time:       259 |     534584 |                   sklearn.utils.validation
import time:       290 |     506763 |                     sklearn.utils._array_api
import time:       293 |     448287 |                       sklearn.utils.fixes
import time:       332 |     268461 |                         scipy.stats
import time:     35143 |     181909 |                           scipy.stats._stats_py
import time:       227 |     167404 |                         pandas
import time:       129 |      91399 |                           pandas.core.api
import time:       156 |      81064 |                             scipy.stats.distributions
import time:       237 |      62001 |     scipy.sparse
import time:     30875 |      52843 |                               scipy.stats._continuous_distns
import time:        78 |      48025 |                             pandas.core.groupby
import time:      1054 |      47947 |                               pandas.core.groupby.generic
import time:       172 |      46613 |       scipy.sparse._csr
import time:       226 |      46265 |                       scipy.special
import time:       257 |      46090 |         scipy.sparse._compressed
import time:       293 |      45539 |           scipy._lib._util
import time:       473 |      45246 |             scipy._lib._array_api
import time:       544 |      39884 |               scipy._external.array_api_compat.numpy
import time:        89 |      38065 |                             pandas.core.arrays
import time:       209 |      36510 |                             scipy.optimize
import time:        92 |      32341 |                               pandas.core.arrays.arrow
import time:       472 |      28445 |                           pandas.core.config_init
import time:      3509 |      28088 |                                 pandas.core.frame
import time:       424 |      27915 |                             pandas.errors
import time:       918 |      27573 |                           scipy.stats._mgc
import time:       121 |      27517 |                           pandas.compat
import time:        12 |      27492 |                               pandas._libs.tslibs
import time:        68 |      27480 |                                 pandas._libs
import time:       146 |      26731 |                             pandas.compat.pyarrow
import time:       122 |      26655 |                             scipy.ndimage
import time:       235 |      26585 |                               pyarrow
import time:     21797 |      26219 |                               scipy.ndimage._support_alternative_backends
import time:       997 |      26145 |                                   pandas._libs.interval
import time:     24998 |      25571 |                                 pyarrow.lib
import time:       876 |      24801 |                         scipy.special._ufuncs
import time:      1360 |      23955 |                                     pandas._libs.hashtable
import time:     13974 |      23949 |                           scipy.stats._morestats
import time:       870 |      23528 |     numpy
import time:       837 |      22596 |                                       pandas._libs.missing
import time:       357 |      22103 |                           scipy.special._ellip_harm_2
import time:       142 |      21995 |                     joblib
import time:       156 |      21756 |                                 pandas.core.arrays.arrow.accessors
import time:         8 |      21746 |                             scipy.linalg.cython_lapack
import time:       212 |      21738 |                               scipy.linalg
import time:        94 |      21730 |       sklearn.model_selection
import time:     17685 |      21600 |                                   pyarrow.compute
import time:        12 |      21054 |                                         pandas._libs.tslibs.nattype
import time:        98 |      21043 |                                           pandas._libs.tslibs
import time:       191 |      19654 |                                 scipy.interpolate
import time:       587 |      19376 |         sklearn.model_selection._classification_threshold
import time:       118 |      19068 |                               scipy.optimize._linprog
import time:      1069 |      18693 |                                   pandas.core.generic
import time:      2212 |      18195 |                               scipy.stats._distn_infrastructure
import time:       115 |      17916 |           sklearn.metrics
import time:     17647 |      17890 |                         scipy.special._support_alternative_backends
import time:       157 |      17396 |     narwhals
import time:       965 |      16449 |                                 pandas.core.groupby.groupby
import time:       828 |      15987 |                                             pandas._libs.tslibs.conversion
import time:         9 |      15770 |                             scipy.spatial.distance
import time:       133 |      15761 |                               scipy.spatial
import time:       102 |      14798 |             sklearn.metrics.cluster
import time:       155 |      14780 |       numpy.__config__
import time:        12 |      14625 |         numpy._core._multiarray_umath
import time:       227 |      14614 |           numpy._core
import time:       137 |      13826 |                                 scipy.optimize._linprog_ip
import time:       246 |      13586 |                                   scipy.optimize._linprog_util
import time:       128 |      13571 |               sklearn.metrics.cluster._unsupervised
import time:       337 |      13444 |                 sklearn.metrics.pairwise
import time:       103 |      13340 |                                     scipy.optimize._remove_redundancy
import time:        87 |      13238 |                                       scipy.linalg.interpolative
import time:       630 |      13151 |                                         scipy.linalg._decomp_interpolative
import time:     13005 |      13005 |                                   pandas.core.groupby.numba_
import time:        98 |      12975 |                 numpy.testing
import time:        99 |      12773 |                 numpy.f2py
import time:       176 |      12572 |                   numpy.f2py.f2py2e
import time:       103 |      12522 |                                           scipy.fft
import time:        63 |      12208 |                   sklearn.metrics._pairwise_distances_reduction
import time:       193 |      12146 |                     sklearn.metrics._pairwise_distances_reduction._dispatcher
import time:      1619 |      11593 |                                               pandas._libs.tslibs.offsets
import time:       789 |      10494 |                                 pandas.core.arrays.arrow.array
import time:       186 |      10103 |       scipy
import time:      1135 |       9916 |                                                 pandas._libs.tslibs.timestamps
import time:       135 |       9233 |                         scipy.sparse.linalg
import time:       106 |       9211 |                   numpy.testing._private.extbuild
import time:       948 |       9106 |                     numpy.testing._private.utils
import time:       521 |       9103 |                       sklearn.externals.array_api_compat.numpy
import time:      1600 |       8903 |                                   scipy.interpolate._interpolate
import time:        94 |       8874 |                       joblib._cloudpickle_wrapper
import time:       831 |       8870 |                                     pandas.core.indexing
import time:       253 |       8819 |                     numpy.f2py.capi_maps
import time:        82 |       8748 |                                 scipy.spatial.transform

Compare that to the baseline from #7327 and you'll see that some of the most expensive imports like matplotlib and PIL have dropped out entirely. The remaining time is dominated by lightgbm itself, scikit-learn, and `scipy.

A note about macOS

macOS has a system called "GateKeeper" that scans every .dylib the first time it's loaded: https://support.apple.com/en-us/102445

Python libraries primarily pull in shared libraries (.dylib) through the following:

  • their own first-part shared library (e.g. lib_lightgbm.dylib)
  • extension modules, e.g. built with Cython
  • dynamic dependencies of either of those (e.g. libgomp.dylib)

So these import timings above from my Mac probably don't give a good indication about the timings you could expect on Linux or Windows... but they DO give a rough idea of the impact of these changes, and an exact enumeration of which modules are imported when you import lightgbm.

This also partially explains why the first "cold" import takes so much longer than subsequent imports.

Why label this breaking?

I tried to make this fully backwards-compatible and not break any user code. But it could change the import order in user code, and we've seen issues that import-order dependent here before (e.g. #6509 and #6595).

Proposing calling it breaking to make this change more visible in release notes.

@jameslamb jameslamb changed the title WIP: [python-package] make some imports lazy: 'dask', 'graphviz', 'joblib', 'matplotlib', 'psutil' [python-package] make some imports lazy: 'dask', 'graphviz', 'joblib', 'matplotlib', 'psutil' Jun 23, 2026
@jameslamb
jameslamb marked this pull request as ready for review June 23, 2026 20:41
@jameslamb

Copy link
Copy Markdown
Member Author

@jmoralez could you help review this one if you have time? I recall talking with you about compat.py here in the past, and you've been around for much of its evolution (especially with the Dask changes).

@jmoralez jmoralez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks! Totally support this

Comment thread python-package/lightgbm/dask.py Resolved
Co-authored-by: José Morales <jmoralz92@gmail.com>
@jameslamb

Copy link
Copy Markdown
Member Author

Great, thanks for the quick review!

I'm gonna try to apply this treatment to the scikit-learn dependency too, but that'll be trickier because it's used for base classes (not just inside function calls).

Let's see if the impact of what I come up with is worth the complexity. I'll push what I come up with so you can at least see it, either way.

@jameslamb
jameslamb merged commit 5c40066 into master Jun 26, 2026
60 checks passed
@jameslamb
jameslamb deleted the python/lazy-imports branch June 26, 2026 03:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants