Skip to content

Concat clears divisions when it shouldn't #8845

Open

Description

@jorloplaz

What happened:

When concatenating row-wise dataframes ([ddf1, ddf2, ..., ddfN]) that do not have any overlap, but that naturally follow each other (so ddf1.divisions[-1] == ddf2.divisions[0], and ddf2.divisions[-1] == ddf3.divisions[0], and so on), dd.multi.concat clears divisions when it shouldn't.

What you expected to happen:

The concatenated result should have divisions ([ddf1.divisions[0], ..., ddf1.divisions[-2], ddf2.divisions[0], ..., ddf2.divisions[-2], ddf3.divisions[0], ..., ddfN.divisions[-2], ddfN.divisions[-1]]).

Minimal Complete Verifiable Example:

import dask.dataframe as dd
import pandas as pd

# Initial data
df = pd.DataFrame({
    "date": pd.date_range("2019-01-01", "2019-01-10"), 
    "col1": range(0, 10), 
    "col2": range(9, -1, -1)
}) 

# To Dask, but it's not partitioned properly...
ddf = dd.from_pandas(df, npartitions=10)           # this causes 9 partitions instead of 10!
if ddf.npartitions != 10:
    print(f"ddf has {ddf.npartitions} partitions instead of 10!")         # print instead of raising error, but why does this happen?
    print(ddf.divisions)                   # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),  but a 10 should have been added as divisions[-1]!

# Index by date forcing 10 partitions
ddf = ddf.set_index("date", divisions=tuple(pd.date_range("2019-01-01", "2019-01-11")))     # note the 11th here!
assert ddf.npartitions == 10, "After repartitioning doesn't have 10 partitions!"
assert ddf.known_divisions, "Divisions should be known!"
assert list(ddf.divisions[:-1]) == df["date"].to_list(), "There should be one division per day!"    # note last one omitted!

# Concatenate its partitions (Dask dataframes themselves) row-wise
dfs = [p for p in ddf.partitions]
res = dd.concat(dfs, axis=0)
if ddf.npartitions != 10:
    print(f"concatenated has {res.npartitions} partitions instead of 10!")
assert res.known_divisions, "Should have kept divisions!"         # this raises AssertionError

Anything else we need to know?:

Looking into concat code, I think the solution is really simple. Here is the conflictive part:

if all(df.known_divisions for df in dasks):
    # each DataFrame's division must be greater than previous one
    if all(
        dfs[i].divisions[-1] < dfs[i + 1].divisions[0]
        for i in range(len(dfs) - 1)
    ):
        divisions = []
        for df in dfs[:-1]:
            # remove last to concatenate with next
            divisions += df.divisions[:-1]
        divisions += dfs[-1].divisions
        return stack_partitions(dfs, divisions, join=join, ignore_order=ignore_order, **kwargs)
    elif interleave_partitions:
        return concat_indexed_dataframes(dfs, join=join, ignore_order=ignore_order, **kwargs)
    else:
        divisions = [None] * (sum(df.npartitions for df in dfs) + 1)
        return stack_partitions(dfs, divisions, join=join, ignore_order=ignore_order, **kwargs)

The thing is that the check in all uses a strict <, but if would suffice with <=, because it's fine that the beginning of the next frame equals the last division of the previous frame, since that last division is NOT included in the previous frame.

To prove this, if I call stack_partitions properly in the example above, things work:

from dask.dataframe.multi import stack_partitions
res = stack_partitions(dfs, divisions=tuple(pd.date_range("2019-01-01", "2019-01-11")), join="inner", ignore_order=False)
assert res.known_divisions, "Should have kept divisions!"         # this is fine
assert list(res.divisions[:-1]) == df["date"].to_list(), "There should be one division per day!"      # this is fine too

I don't know if this has been addressed in #8517 (@jsignell @gjoseph92), but in my opinion the example above proves that there's space for improvement:

  • The delicate point is that divisions[-1] by definition is a value that is NOT present in data (it should be the first value NOT to include), so it cannot be properly inferred unless it's a very easy case (e.g. a range).
  • Because of this, from_pandas in the above example yields 9 partitions instead of 10 (with the last partition having 2 rows), even if the most natural way to partition that is 1 row per partition. This is a consequence of the fact that divisions[-1] cannot be inferred, plus the fact that from_pandas doesn't accept a divisions argument!
  • Because of this, if I do afterwards set_index without specifying proper divisions, it keeps on having 9 partitions, and partition_quantiles yields a strange result:
ddf.divisions
(Timestamp('2019-01-01 00:00:00'), Timestamp('2019-01-01 21:36:00'), Timestamp('2019-01-02 19:12:00'), Timestamp('2019-01-03 16:48:00'), Timestamp('2019-01-04 14:24:00'), Timestamp('2019-01-05 12:00:00'), Timestamp('2019-01-06 09:36:00'), Timestamp('2019-01-07 07:12:00'), Timestamp('2019-01-08 04:48:00'), Timestamp('2019-01-09 02:24:00'), Timestamp('2019-01-10 00:00:00'))

So I suggest this course of action:

  1. Change the code of concat with <=.
  2. See if there are other parts of code where this same error could be present.
  3. Think about whether divisions[-1] is really necessary. Do we need to have it?
    • For searching, I think it should suffice to know that partitions[i] has values in its index in the interval [divisions[i], divisions[i+1]), for all partitions except the last one. The last one we know it starts in divisions[-2], but it's open-ended.
    • However, this raises a symmetry question in the 1st partition. Perhaps there should be two divisions arrays:
      • Beginning of partitions: this would be the current [divisions[0], ..., divisions[-2]], which is the same as [partitions[0].index[0], ..., partitions[-1].index[0]].
      • End of partitions: this would be last values actually present in each partition's index: [partitions[0].index[-1], ..., partitions[-1].index[-1]].
    • So that we know that the i-th partition has values in the closed (not semi-open) interval [beginning[i], end[i]].
    • As a side effect, these 2 arrays have the same length than partitions, instead of the current situation where len(divisions) == len(partitions) + 1.
  4. If we ignore the previous point and stick to one divisions array whose size is npartitions + 1, in my opinion:
    • from_pandas should accept a divisions argument.
    • If it doesn't receive divisions and turns out that the resulting npartitions isn't the one requested by the user, at least raise a warning. In the example above, the user should know that instead of 10 partitions it decided to take 9!

Environment:

  • Dask version: 2022.02.1
  • Python version: 3.9.10
  • Operating System: Ubuntu
  • Install method (conda, pip, source): Pip

Activity

  1. added
    needs triage
    on Mar 25, 2022
  2. aomirolis commented on Mar 26, 2022

    @aomirolis
    Contributor

    Hi, I am new to this project but I would like to work on this issue.

  3. jorloplaz commented on Mar 28, 2022

    @jorloplaz
    ContributorAuthor

    Thank you @aomirolis . In this particular case if some core developer can confirm that the only place to change is where I suggest in dd.concat (points 1 and 2) and that my understanding is correct, I don't mind doing it myself. It'd be just a single change, and perhaps some test checking that things work.

    Regarding the divisions discussion and passing divisions to from_pandas (points 3 and 4), I'd also like to receive some feedback. Perhaps we could move those to specific feature demands.

  4. bryanwweber commented on Mar 28, 2022

    @bryanwweber
    Contributor

    that do not have any overlap, but that naturally follow each other (so ddf1.divisions[-1] == ddf2.divisions[0], and ddf2.divisions[-1] == ddf3.divisions[0]

    This implies to me that they do have overlap, since the last element of ddf1 is the same as the first element of ddf2. Can you clarify about that?

  5. jorloplaz commented on Mar 28, 2022

    @jorloplaz
    ContributorAuthor

    They don't, because for the i-th partition, divisions[i+1] is supposed to be the first element that is NOT included in the index of the i-th dataframe. See for example the documentation of set_index, when it says:

    divisions: list, optional
    The “dividing lines” used to split the new index into partitions. For divisions=[0, 10, 50, 100], there would be three output partitions, where the new index contained [0, 10), [10, 50), and [50, 100), respectively.

    However, in the specific doc about partitions, it claims:

    Divisions includes the minimum value of every partition’s index and the maximum value of the last partition’s index.

    Which I interpret as divisions[-1] is actually a value included in the last partition. But this means an asymmetry:

    • All partitions are semi-open, so that their index values are in the semi-open range between divisions[i] (inclusive) and divisions[i+1] (exclusive).
    • Except for the last one, which ranges from divisions[-2] (inclusive) to divisions[-1] (also inclusive).

    So in the example above, last partition would lie in [50, 100] and not in [50, 100). This is why I suggest to unify things so that there's no ambiguity, either with:

    • 2 separate division arrays, one for the minimum value of each partition, and another one with the maximum value of each partition.
    • Not being ambiguous about whether divisions[-1] is present in data or not. If it's a value that must be present in data, an error should be raised if setting divisions[-1] to a value that isn't really there. And if it's a value that isn't there, one has the problem that it can't be automatically inferred from data...

    In any case, this doesn't affect the example I chose where concat doesn't work as expected, because the ambiguous behavior happens only for the last partition. All other partitions are clearly left-closed and right-open. You can play with data of your own to verify this is so.

  6. jsignell commented on Mar 28, 2022

    @jsignell
    Member

    Thanks for writing this up and thinking about how this can be better @jorloplaz.

    I tend to agree that keeping track of min and max would be more useful than keeping track of divisions. The more I have thought about divisions the more I am convinced that it is not reasonable to enforce that all partitions except the last one are unique. For instance it makes it impossible to split a partition where all the index values are the same into two partitions.

    In terms of your original suggestions:

    1. Change the code of concat with <=.

    How we calculate divisions internally is we calculate the min and max of every partition and then we take all the mins and the last max. So it seems a little risky to drop the =.

    1. See if there are other parts of code where this same error could be present.

    I'm sure there are.

    1. Think about whether divisions[-1] is really necessary. Do we need to have it?

    This is a very interesting idea. But I don't really get how it would help in this case since if we only know the lower bound then there is no way to keep the divisions since we can't say anything about the overlap.

    4a. from_pandas should accept a divisions argument.

    This seems totally reasonable.

    4b. If it doesn't receive divisions and turns out that the resulting npartitions isn't the one requested by the user, at least raise a warning.

    This also seems reasonable.

    @aomirolis - this issue is pretty involved and it's going to take a while to arrive at a solution 😄 . I recommend looking for a "good first issue" tag if you are interested in contributing sometime in the near future.

  7. added and removed
    needs triage
    on Mar 28, 2022
  8. jorloplaz commented on Mar 29, 2022

    @jorloplaz
    ContributorAuthor

    Thanks for revising @jsignell . I think the problem here is that we're mixing several concepts into one issue. Let me try to decompose them, basing on your comments:

    The more I have thought about divisions the more I am convinced that it is not reasonable to enforce that all partitions except the last one are unique.

    Well, my understanding is that we ensure uniqueness in order to accelerate searches, e.g., when indexing with loc. In my mind this is doing a kind of bisect_left of the value we're searching in the divisions list, then we know in which partition to look for that particular value, and then it's just calling loc on the particular dataframe that lies inside that partition. Is this so?

    For instance it makes it impossible to split a partition where all the index values are the same into two partitions.

    True, but I think this is reasonable, because of the above. If several partitions could hold the same index value, then you wouldn't know easily in which ones to look for it, or you should look in all of them in a parallel way... Not sure if that's really convenient.

    Anyway, if it turns out that all the index values are the same, that column doesn't really make sense as an index, does it? At least in SQL terms of what an index should be.

    What can indeed happen is that as a result of this uniqueness, partition sizes are quite imbalanced in the dask dataframe, in the sense that there are partitions with many more rows than others. This is why in my company we coded a custom solution to try to rebalance this, by looking at index.value_counts() and making partitions as equally row-sized as possible, while also maintaining uniqueness (remember my comment here).

    In short, I think that uniqueness is a good idea, but it has to be complemented with some smart rebalancing so that partition lens are reasonably similar.

    Turning back to the concat problem:

    How we calculate divisions internally is we calculate the min and max of every partition and then we take all the mins and the last max. So it seems a little risky to drop the =.

    In this case I'm trying to concatenate several dataframes, each of which has data for a different day. And those are consecutive days, so clearly the resulting divisions should be the concatenation of the divisions of each dataframe.

    In other words, for my example it'd be absolutely correct that the execution flow entered the if all(...) and then called stack_partitions. But it doesn't because there's a < in the condition and not a <=!

    The thing is that there's an inconsistency in divisions that is causing these troubles:

    • If Dask infers them internally, it's true that it's as you say: all the mins and the last max. Note that in this case divisions[-1] is included in the last partition.
    • If we set them manually (e.g., divisions passed on to set_index), it isn't checked that divisions[-1] is really the max of the last partition. Actually, the doc encourages that it's a value that isn't there!

    I reproduce my example here. Notice how I passed '2019-01-11' to be divisions[-1], and it's set directly in the dataframe. But the max is '2019-01-10'!

    >>> ddf.compute()
                col1  col2
    date                  
    2019-01-01     0     9
    2019-01-02     1     8
    2019-01-03     2     7
    2019-01-04     3     6
    2019-01-05     4     5
    2019-01-06     5     4
    2019-01-07     6     3
    2019-01-08     7     2
    2019-01-09     8     1
    2019-01-10     9     0
    >>> ddf.divisions
    (Timestamp('2019-01-01 00:00:00'), Timestamp('2019-01-02 00:00:00'), Timestamp('2019-01-03 00:00:00'), Timestamp('2019-01-04 00:00:00'), Timestamp('2019-01-05 00:00:00'), Timestamp('2019-01-06 00:00:00'), Timestamp('2019-01-07 00:00:00'), Timestamp('2019-01-08 00:00:00'), Timestamp('2019-01-09 00:00:00'), Timestamp('2019-01-10 00:00:00'), Timestamp('2019-01-11 00:00:00'))

    So, the decomposition of this issue I think is:

    1. Establishing whether divisions[-1] should be the max of the last partition or not:
      • If it should be, then the current concat code with < is correct. If there's no overlap, it should hold that dfs[i].divisions[-1] < dfs[i+1].divisions[0] and we can close this issue when we've covered points 2 and 3 below.
      • If it shouldn't be, then it would suffice with <=.
    2. If it should be, then when passing divisions as in set_index, an error should be raised if what is passed doesn't comply with this logic of "the min of each partition and the last max". In particular, the last division passed should be a value that is present in the data!
    3. Once this logic is guaranteed, make from_pandas support a divisions argument.
    4. (Independently from all the above) Reconsidering whether divisions should be a single or a double array, and whether partitions should be unique or not.

    Do you agree?

  9. added
    needs attention
    on May 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dataframeneeds attention

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions