-
Notifications
You must be signed in to change notification settings - Fork 3.8k
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
[python-package] Adding support for polars for input data #6204
Comments
Thanks for using LightGBM and for taking the time for writing this up. I support Are you interested in contributing this? |
As a side note, passing data from polars without copying any data is the entire reason my PRs exist 😄 polars has a |
amazing!!! In the future, please share that context with us when proposing changes here. It helps us to make informed choices about how much time and energy to put into reviewing, and how to weight the costs of the new addition against the added maintenance burden. @borchero are you interested in adding |
Sure, will do next time 😄 since there already was an open Arrow PR, I didn't think about going into "motivation" too much 👀
The plan to pass polars to Arrow in our company's application code would have simply been to call
🙏🏼🙏🏼 |
The way I see it is that 2024 will be the year of polars adoption by major python ML packages. The easier you will make it for users to use it, the better the user experience will be overall. I am glad to hear that this is being considered and my issue wasn't rejected at first glance. |
On a different note, I tried to use LightGBM directly in rust https://github.com/detrin/lightgbm-rust and I will perhaps use it for use-case for testing. The pyarrow option is interesting, I will try it as well. Thanks @borchero could you link the PR here? |
This is a great point @borchero. Taking on I'm not that familiar with If not and it's literally just I guess as a first test, I'd want to understand how Because if it's a copy... then having Consider something like this (pseudo-code, this won't run): import polars as pl
import lightgbm as lgb
df = pl.read_csv("data.csv")
dtrain = lgb.Dataset(
df[["feature_1", "feature_2"]],
label=df["label"]
)
lgb.train(train_set=dtrain, ...) If I think that's result in higher peak memory usage than instead doing something like the following and passing in Arrow data directly import polars as pl
import lightgbm as lgb
df = pl.read_csv("data.csv").to_arrow()
dtrain = lgb.Dataset(
df[["feature_1", "feature_2"]],
label=df["label"]
)
lgb.train(train_set=dtrain, ...) Other things that might justify adding support for directly passing
|
Polars internally keeps memory according to the arrow memory format. When you call Moving data in and out of polars via arrow is zero-copy. Moving data in and out of polars via numpy can be zero-copy (it depends on the data type, null data and dimensions) |
Does this imply that potentially LigthGBM could use it even in my snippet above without allocating any new memory on the heap? |
@detrin not for your training data, i.e. not for polars data frames. Polars uses column-wise storage, i.e. each of your columns is represented by a contiguous chunk of memory (but data for each column is potentially in different locations of the heap). The only interface that is currently available to pass data to LightGBM from Python is via NumPy (disregarding the option to pass data as files), which uses a single array (=single chunk of memory) to store your data and uses row-wise storage. This means that each row is represented by a contiguous chunk of memory and rows are furthermore concatenated such that you end up with a single array. As you can see, Polars' data representation is quite different to the NumPy data representation and, thus, data needs to be copied. Side-note: to not require two copies, you should call The way to resolve this issue is to extend LightGBM's API, i.e. to allow other data formats to be passed from the Python API. Arrow is a natural choice since it is being used ever more and is the backing memory format for pandas. In fact, it allows you to pass data from any tool that provides data as Arrow to LightGBM without copying any data. |
This is not true. The Python package supports all of these formats for raw data:
Start reading from here and you can see all those options: LightGBM/python-package/lightgbm/basic.py Line 2010 in 516bde9
|
Also for reference https://numpy.org/doc/1.21/reference/arrays.ndarray.html#internal-memory-layout-of-an-ndarray. It says
"stored in a contiguous block of memory in row-major order" is not exactly the same as "row-wise", just wanted to add that link as it's a great reference for thinking about these concepts. |
Ah sorry about the misunderstanding! I think I phrased this a little too freely. I meant data formats that are useful for passing a Polars dataframe. Pandas is essentially treated the same as NumPy but adds a few more metadata. The other options are largely irrelevant for this particular instance.
Yep, thanks! Once one has read through the NumPy docs, one also understands the statement that "polars' |
So, if I understand it correctly as of now there is now way how to pass data from polars to LightGBM without copying the data in memory. For the project I am working on I might use CLI as a workaround. |
Yes, you will have (at least) one copy of your data in memory along with the LightGBM-internal representation of your data that is optimized for building the tree.
Potentially, a viable temporary alternative might also be to pass data via files (?) |
Is it possible directly in python? I could then output data into temp file and load it in python by LightGBM. |
See @jameslamb's comment above for LightGBM's "API":
You could e.g. write your data to CSV. Obviously, this introduces some performance hit. |
Shameless plug: |
@jameslamb I just thought again about adding documentation about how to pass I thought about adding a note on the |
Hey thanks for reviving this @borchero . A lot has changed since the initial discussion. There's now a I wonder... could we add direct, transparent support for def _is_polars(arr) -> bool:
return "polars." in str(arr.__class__) and callable(getattr(arr, "to_arrow", None))
# ... in any method where LightGBM accepts raw data ...
if _is_polars(data):
data = data.to_arrow() Because if we did that, then we wouldn't need to document specific methods that have to be called on |
This related discussion is also worth cross-linking: dmlc/xgboost#10554 |
Hi @jameslamb, Hope it's ok for me to jump in here - I contribute to pandas and Polars, and have fixed up several issues related to the interchange protocol mentioned in dmlc/xgboost#10452 The interchange protocol provides a standardised way of converting between dataframe libraries, but has several limitations which may affect you, so I recommend not using it:
If all you need to do is convert to pyarrow, then I'd suggest you just do if (pl := sys.modules.get('polars', None) is not None and isinstance(data, pl.DataFrame):
data = data.to_arrow() If instead you need to perform dataframe operations in a library-agnostic manner, then Narwhals, an extremely lightweight compatibility layer between dataframe libraries which has zero dependencies, may be of interest to you (Altair recently adopted it for this purpose, see vega/altair#3452, as did scikit-lego) I'd be interested to see how I could be of help here, as I'd love to see Polars support in LightGBM happen 😍 - if it may be useful to have a longer chat about how it would work, feel free to book some time in https://calendly.com/marcogorelli |
@ritchie46 pointed out this discussion to me, and I wanted to highlight recent work around the Arrow PyCapsule Interface. It's a way for Python packages to exchange Arrow data safely without prior knowledge of each other. If the input object has an You can use: import pyarrow as pa
assert hasattr(input_obj, "__arrow_c_stream__")
table = pa.table(input_obj)
# pass table into existing API Alternatively, this also presents an opportunity to access a stream of Arrow data without materializing it in memory all at once. You can use the following to only materialize a single Arrow batch at a time: import pyarrow as pa
assert hasattr(input_obj, "__arrow_c_stream__")
reader = pa.RecordBatchReader.from_stream(input_obj)
for arrow_chunk in reader:
# do something If the source is itself a stream (as opposed to a " The PyCapsule Interface could also let you remove the pyarrow dependency if you so desired. |
Thank you both for the information! I'm definitely supportive of having Both approaches mentioned above (@MarcoGorelli's and @kylebarron 's) look interesting for us to pursue here as a first step. Hopefully someone will be able to look into this soon (maybe @borchero or @jmoralez are interested?). We'd also welcome contributions from anyone involved in this thread who has the time and interest, and would be happy to talk through specifics over a draft PR. We have a lot more work to do here than hands to do it... we haven't even added support for pyarrow columns in For a bit more context.... The main place where that does happen with If you want to see what I mean by that, some of the relevant code is here: LightGBM/python-package/lightgbm/basic.py Line 807 in d67ecf9
LightGBM/python-package/lightgbm/basic.py Line 855 in d67ecf9
LightGBM/python-package/lightgbm/basic.py Line 867 in d67ecf9
|
Thanks for your response 🙏 ! Quick note on the two approaches: Narwhals exposes the PyCapsule interface (narwhals-dev/narwhals#786), and includes a fallback to PyArrow (thanks Kyle for having suggested it! 🙌 ) which arguably makes it easier to use than looking for
|
Some positive news regarding polars adoption: Kaggle has made a push in that direction. The API in some visible competitions accept both pandas and polars df as solution (see here - in that case the pandas version seems bugged, making polars the only viable solution). From what I understand polars inputs are not directly supported yet. What would be the best alternative to make it works ? (avoiding memory duplicates + categorical support). |
@borchero what's the current set of blockers on polars integration? How can I help? |
I only now got the opportunity to think about @kylebarron's and @MarcoGorelli's proposals in more detail. I think the premise of PyCapsule is very appealing, esp. since it seems to have official support from Apache Arrow. I would personally prefer this over a solution involving narwhals (esp. as narwhals -- even though it markets itself as "lightweight" -- is much more heavyweight in comparison). Given my -- so far limited -- understanding of PyCapsule, I would propose the following next steps:
@Ic3fr0g if you want to help with this support, I would be very happy to review a PR implementing (1) :) @lcrmorin you can already use LightGBM with |
Can you elaborate on how narwhals is much more heavyweight? The wheel is 225kB and it doesn't have any dependencies. Your proposal seems to focus specifically on arrow, so we'd have two implementations to convert dataframes to the required LightGBM format, one for pandas and one for arrow. I think narwhals would allow us to have a single one.
This seems way more complex than what we do right now for pandas, which is mapping categorical values to their integer codes. I think it would be a lot easier doing that for arrow as well. |
Thanks @borchero for looking into this! Personally I'm much more excited about Polars support than about spreading Narwhals, so I'm really happy that this might be happening @jmoralez I think it depends on what someone does with dataframes - if all someone needs to do is to convert to PyArrow table, then I agree that Narwhals is more heavyweight than just doing if hasattr(df_user, '__arrow_c_stream__'):
df_pyarrow = pa.table(df_user) The use case for Narwhals is more for when you want to do everything with the user's input library without converting to PyArrow / pandas - for example, when working from Python. But if LightGBM has the chance to operate on the underlying data anyway from C++, then there's probably no need for Narwhals here |
I don't think it's "heavyweight" in any general way. As @MarcoGorelli already pointed out though -- according to my proposal -- we'd only need a way to export data to PyArrow for which we don't need any additional dependency :)
According to this comment, newer versions of pandas also have support for Arrow PyCapsule (at least for data frames) which would allow us to unify conversion for both polars and pandas data frames. [Maybe this would also easily enable us to support pandas pyarrow columns?] Of course, we'd still have to keep around the old implementation as long as we want to support older versions of pandas -- this might not be required when using narwhals (?).
Iirc, a categorical column in Arrow consists of an array with |
pandas relies on PyArrow to export the PyCapsule Interface, so even if you were to access the underlying data directly in C++, it would still mean requiring PyArrow as a depdency. Which sounds fine to me, just checking this is understood
True, but you could just copy this part from Narwhals and this one and do def convert_to_pyarrow_table(native_frame):
try:
import pyarrow as pa # ignore-banned-import
except ModuleNotFoundError as exc:
msg = f"PyArrow>=14.0.0 is required"
raise ModuleNotFoundError(msg) from exc
if parse_version(pa.__version__) < (14, 0):
msg = f"PyArrow>=14.0.0 is required"
raise ModuleNotFoundError(msg) from None
if not hasattr(native_frame, "__arrow_c_stream__"):
if (pd := sys.modules.get('pandas', None)) is not None and isinstance(native_frame, pd.DataFrame):
# Keep supporting old pandas versions which didn't export the PyCapsule Interface
return pa.Table.from_pandas(native_frame)
msg = f"Given object of type {type(native_frame)} does not support PyCapsule Interface"
raise TypeError(msg)
return pa.table(native_frame) If you then already have logic to deal with PyArrow Tables directly, then this should allow for supporting any dataframe library which implements the PyCapsule Interface, as well as simplifying (I think?) how you support pandas The downside would be requiring PyArrow, and it's your decision whether or not that's acceptable (my impression is that the upsides outweigh the downsides here) |
I'm not as familiar with usage of PyCapsules from C/Cython (I do all my Python binding from Rust), but I from my perspective it seems best to directly access the Arrow stream from C, in a very similar way to how you access pyarrow data now.
I don't think your C code would need |
This sounds interesting. Unfortunately, I'm lacking a little experience with Python/C bindings and the setup in this repository, in particular. Specifically, I have no idea where I could add code to have the "bindings" call the release callback (this would have to be C code as far as I understand it). |
It looks like existing support for Arrow is in https://github.com/microsoft/LightGBM/blob/master/python-package/lightgbm/basic.py. In particular LightGBM/python-package/lightgbm/basic.py Lines 418 to 443 in 83c0ff3
using cffi. This is what I'm referring to as your "binding code" because it's the glue between the Python environment and the underlying C code. Then you pass that _ArrowCArray somewhere on to be interpreted later.
This binding code could be updated to directly access a stream according to the C Stream interface. You just have to call |
This interpretation is generally correct. Your bindings code would be responsible for extracting the underlying pointers and handing them to your C code, at which point you would be free to operate on the underlying pointer in pure C. What this boils down to at the bindings level is some sort of call to |
Summary
I think polars library is on the path to replace the majority of pandas use-cases. It is already being adopted by the community. We use it internally in my company for new projects and we try not to use pandas at all.
Motivation
Polars is blazingly fast and it has several times a lower memory footprint. There is no need to use extra memory to convert data into numpy or pandas to be used for training in LightGBM.
Description
I would like the following to be working, where
data_train
anddata_test
are instances ofpl.DataFrame
as of now I have to convert it into numpy matrices
The text was updated successfully, but these errors were encountered: