Skip to content
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

feat(python): Reduce scan_csv() (and friends') memory usage when using BytesIO #20649

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

itamarst
Copy link
Contributor

@itamarst itamarst commented Jan 9, 2025

When using scan_csv() on a BytesIO(), the hope is that it won't make a whole copy of the data if possible, e.g. by doing filtering as it reads. In fact, it currently does make a copy, making memory usage that much higher.

This PR fixes that, by using BytesIO.getvalue() instead of BytesIO.read(). I assume this will also help other scan_* functions since it's just generic infrastructure code.

To demonstrate, below is a standalone version of the test in the PR. When run with released 1.19:

Peak allocated during scan (MB) 75.24

When run with this branch:

Peak allocated during scan (MB) 0.17

Here's the script:

import io
import time
import tracemalloc
import polars as pl

tracemalloc.start()

# Create CSV that is ~70-85 MB in size:
f = io.BytesIO()
df = pl.DataFrame({"mydata": pl.int_range(0, 10_000_000, eager=True)})
df.write_csv(f)
assert 70_000_000 < f.tell() < 85_000_000
f.seek(0, 0)

current_mem = tracemalloc.get_traced_memory()[0]

# A lazy scan shouldn't make a full copy of the data:
assert (
    pl.scan_csv(f).filter(pl.col("mydata") == 9_999).collect(new_streaming=True).item()
    == 9_999
)

print(
    "Peak allocated during scan (MB)",
    (tracemalloc.get_traced_memory()[1] - current_mem) / (1024 * 1024),
)
time.sleep(1)
tracemalloc.stop()

@itamarst itamarst changed the title Reduce scan_csv() (and friends') memory usage when using BytesIO feat(python): Reduce scan_csv() (and friends') memory usage when using BytesIO Jan 9, 2025
@github-actions github-actions bot added enhancement New feature or an improvement of an existing feature python Related to Python Polars and removed title needs formatting labels Jan 9, 2025
@itamarst itamarst marked this pull request as ready for review January 9, 2025 16:43
Copy link

codecov bot commented Jan 9, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 79.86%. Comparing base (2e0b3a3) to head (b422136).
Report is 12 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #20649      +/-   ##
==========================================
+ Coverage   79.02%   79.86%   +0.84%     
==========================================
  Files        1557     1557              
  Lines      220551   220752     +201     
  Branches     2514     2527      +13     
==========================================
+ Hits       174283   176312    +2029     
+ Misses      45695    43862    -1833     
- Partials      573      578       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@coastalwhite
Copy link
Collaborator

I was a bit worried that this would break if you changed the backing buffer afterwards. But it seems to not do that, so very nice work 😄

Pretty sure previously, if StringIO had reached this point (which it wouldn't in
practice) you'd end up trying to load a _path_ matching the StringIO's contents...
let Ok(bytes) = py_f.call_method0("getvalue") else {
return py_f;
};
if bytes.downcast::<PyBytes>().is_ok() || bytes.downcast::<PyString>().is_ok() {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am fairly certain the StringIO path wasn't hit in existing usage of this function, and it's wrong because the caller expects strings to be paths... and doesn't match the function name, either.

memory_usage = memory_usage_without_pyarrow

# Create CSV that is ~70-85 MB in size:
f = io.BytesIO()
Copy link
Member

Choose a reason for hiding this comment

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

Can we test this with a little bit less data. I assume it is noticeable with less.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or an improvement of an existing feature python Related to Python Polars
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants