Skip to content

ENH: Add lazy copy to concat and round #50501

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

Merged
merged 28 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
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
27 changes: 24 additions & 3 deletions pandas/core/reshape/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

import numpy as np

from pandas._config import get_option
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
from pandas._config import get_option
from pandas._config import get_option, using_copy_on_write

Copy link
Member Author

Choose a reason for hiding this comment

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

Ah this is annoying, I thought that ci should fail, but makes sense that the import continues to work through there...


from pandas._typing import (
Axis,
AxisInt,
Expand Down Expand Up @@ -47,6 +49,8 @@
get_unanimous_names,
)
from pandas.core.internals import concatenate_managers
from pandas.core.internals.construction import dict_to_mgr
from pandas.core.internals.managers import _using_copy_on_write

if TYPE_CHECKING:
from pandas import (
Expand Down Expand Up @@ -155,7 +159,7 @@ def concat(
names=None,
verify_integrity: bool = False,
sort: bool = False,
copy: bool = True,
copy: bool | None = None,
) -> DataFrame | Series:
"""
Concatenate pandas objects along a particular axis.
Expand Down Expand Up @@ -363,6 +367,12 @@ def concat(
0 1 2
1 3 4
"""
if copy is None:
if _using_copy_on_write():
copy = False
else:
copy = True

op = _Concatenator(
objs,
axis=axis,
Expand Down Expand Up @@ -584,7 +594,16 @@ def get_result(self):
cons = sample._constructor_expanddim

index, columns = self.new_axes
df = cons(data, index=index, copy=self.copy)
mgr = dict_to_mgr(
data,
index,
None,
copy=self.copy,
typ=get_option("mode.data_manager"),
)
if _using_copy_on_write() and not self.copy:
mgr = mgr.copy(deep=False)
df = cons(mgr, copy=self.copy)
Copy link
Member

Choose a reason for hiding this comment

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

This might be doing a second copy now? (in case of copy=True)

I am also wondering if we could do mgr = cons(data ...)._mgr instead. That gives some overhead, but I worry a bit that not using cons for parsing the dict of Series might impact behaviour of subclasses.
(have to think through it for the geopandas case)

Copy link
Member Author

Choose a reason for hiding this comment

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

Good point, set copy to false here

df.columns = columns
return df.__finalize__(self, method="concat")

Expand All @@ -611,8 +630,10 @@ def get_result(self):
new_data = concatenate_managers(
mgrs_indexers, self.new_axes, concat_axis=self.bm_axis, copy=self.copy
)
if not self.copy:
if not self.copy and not _using_copy_on_write():
new_data._consolidate_inplace()
elif _using_copy_on_write() and not self.copy:
new_data = new_data.copy(deep=False)
Copy link
Member

Choose a reason for hiding this comment

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

I would expect that concatenate_managers already takes care of setting up references. Of course, concatenate_managers is only used here, so it if it easier to implement this way, that's fine as well (but maybe add a comment about it that concatenate_managers basically returned a view and didn't yet set up new_data.refs)

Copy link
Member

Choose a reason for hiding this comment

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

It might also not be sufficient this way for keeping track of the reference from parent to child. Because new_data here will reference this intermediate BlockManager, but not the original BlockManager from the concat input. So the manager of the parent dataframes are not referenced by any result.

Copy link
Member

Choose a reason for hiding this comment

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

Checking out this branch, I can confirm that is indeed an issue with the current implementation:

In [1]: pd.options.mode.copy_on_write = True

In [2]: df = DataFrame({"b": ["a"] * 3})
   ...: df2 = DataFrame({"a": ["a"] * 3})

In [3]: result = pd.concat([df, df2], axis=1)

In [4]: result
Out[4]: 
   b  a
0  a  a
1  a  a
2  a  a

In [8]: df._mgr._has_no_reference(0)
Out[8]: True

In [9]: df.iloc[0, 0] = 'c'

In [10]: result
Out[10]: 
   b  a
0  c  a
1  a  a
2  a  a

Copy link
Member Author

Choose a reason for hiding this comment

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

Pushed the logic down and added your case as test. Works now


cons = sample._constructor
return cons(new_data).__finalize__(self, method="concat")
Expand Down
57 changes: 57 additions & 0 deletions pandas/tests/copy_view/test_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import numpy as np

from pandas import (
DataFrame,
Series,
concat,
)
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array


def test_concat_frames(using_copy_on_write):
df = DataFrame({"b": ["a"] * 3})
df2 = DataFrame({"a": ["a"] * 3})
df_orig = df.copy()
result = concat([df, df2], axis=1)

if using_copy_on_write:
assert np.shares_memory(get_array(result, "b"), get_array(df, "b"))
assert np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
else:
assert not np.shares_memory(get_array(result, "b"), get_array(df, "b"))
assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a"))

result.iloc[0, 0] = "d"
if using_copy_on_write:
assert not np.shares_memory(get_array(result, "b"), get_array(df, "b"))
assert np.shares_memory(get_array(result, "a"), get_array(df2, "a"))

result.iloc[0, 1] = "d"
if using_copy_on_write:
assert not np.shares_memory(get_array(result, "a"), get_array(df2, "a"))
tm.assert_frame_equal(df, df_orig)


def test_concat_series(using_copy_on_write):
ser = Series([1, 2], name="a")
ser2 = Series([3, 4], name="b")
ser_orig = ser.copy()
result = concat([ser, ser2], axis=1)

if using_copy_on_write:
assert np.shares_memory(get_array(result, "a"), ser.values)
assert np.shares_memory(get_array(result, "b"), ser2.values)
else:
assert not np.shares_memory(get_array(result, "a"), ser.values)
assert not np.shares_memory(get_array(result, "b"), ser2.values)

result.iloc[0, 0] = 100
if using_copy_on_write:
assert not np.shares_memory(get_array(result, "a"), ser.values)
assert np.shares_memory(get_array(result, "b"), ser2.values)

result.iloc[0, 1] = 1000
if using_copy_on_write:
assert not np.shares_memory(get_array(result, "b"), ser2.values)
tm.assert_series_equal(ser, ser_orig)
17 changes: 17 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,23 @@ def test_reindex_like(using_copy_on_write):
tm.assert_frame_equal(df, df_orig)


def test_round(using_copy_on_write):
df = DataFrame({"a": [1, 2], "b": "c"})
df2 = df.round()
df_orig = df.copy()

if using_copy_on_write:
assert np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
else:
assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))

df2.iloc[0, 1] = "d"
if using_copy_on_write:
assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b"))
tm.assert_frame_equal(df, df_orig)


def test_reorder_levels(using_copy_on_write):
index = MultiIndex.from_tuples(
[(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"]
Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/io/pytables/test_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
timedelta_range,
)
import pandas._testing as tm
from pandas.core.internals.managers import _using_copy_on_write
from pandas.tests.io.pytables.common import (
_maybe_remove,
ensure_clean_store,
Expand Down Expand Up @@ -1009,6 +1010,7 @@ def test_to_hdf_with_object_column_names(tmp_path, setup_path):
assert len(result)


@pytest.mark.skipif(_using_copy_on_write(), reason="strides buggy with cow")
def test_hdfstore_strides(setup_path):
Copy link
Member

Choose a reason for hiding this comment

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

Is this caused by the concat changes?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah strides changed from 8 to 16, this is really weird

Copy link
Member

@jorisvandenbossche jorisvandenbossche Jan 16, 2023

Choose a reason for hiding this comment

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

Looking into this a little bit, I think the issue is that in

pandas/pandas/io/pytables.py

Lines 3207 to 3212 in a0071f9

if len(dfs) > 0:
out = concat(dfs, axis=1)
out = out.reindex(columns=items, copy=False)
return out
return DataFrame(columns=axes[0], index=axes[1])

where we are creating the DataFrame, with the changes in this PR that concat won't copy if CoW is enabled. But it seems that the data from the HDF store always come back as F contiguous, while in pandas we want it as C contiguous for optimal performance.
Maybe we should just add a copy=True in the concat call in the mentioned snippet. That's already the default for non-CoW so won't change anything, and for CoW enabled also ensures we get the desired memory layout (at the expense of an extra copy while reading in, but to fix that, that can be a follow-up optimization investigating why the HDF store always returns F contiguous arrays)

Also commented about that on the related issue (that triggered adding this test): #22073

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah this seems to fix it

# GH22073
df = DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/reshape/concat/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_append_concat(self):
assert isinstance(result.index, PeriodIndex)
assert result.index[0] == s1.index[0]

def test_concat_copy(self, using_array_manager):
def test_concat_copy(self, using_array_manager, using_copy_on_write):
df = DataFrame(np.random.randn(4, 3))
df2 = DataFrame(np.random.randint(0, 10, size=4).reshape(4, 1))
df3 = DataFrame({5: "foo"}, index=range(4))
Expand Down Expand Up @@ -81,7 +81,7 @@ def test_concat_copy(self, using_array_manager):
result = concat([df, df2, df3, df4], axis=1, copy=False)
for arr in result._mgr.arrays:
if arr.dtype.kind == "f":
if using_array_manager:
if using_array_manager or using_copy_on_write:
# this is a view on some array in either df or df4
assert any(
np.shares_memory(arr, other)
Expand Down