Skip to content

Fix batch(by_column=..., drop_last_batch=True) dropping complete groups - #9048

Open
MaiAditya wants to merge 2 commits into
huggingface:mainfrom
MaiAditya:fix/batch-by-column-drop-last
Open

MaiAditya wants to merge 2 commits into
huggingface:mainfrom
MaiAditya:fix/batch-by-column-drop-last

Conversation

@MaiAditya

Copy link
Copy Markdown

Fixes #9028

With by_column, drop_last_batch was passed to the inner map over input rows, so it dropped the last batch_size input rows instead of an output batch. Dataset.batch then lost complete groups (and every row for a single-group dataset), while IterableDataset.batch dropped or truncated the trailing group(s) (e.g. it returned [5, 6, 7] for the group [5, 6, 7, 8]).

This PR stops forwarding drop_last_batch in the by_column branch of both Dataset.batch and IterableDataset.batch, and notes it in the docstrings. With by_column, a batch is a whole group and batch_size only sets the accumulation chunk size (as the docs already say), so no output batch is ever incomplete and there is nothing to drop. Both types now return the same groups with and without drop_last_batch:

                     before (Dataset / IterableDataset)                after (both)
A  [0,0,0,1,1,2,2,2,3,3]  [[0,1,2],[3,4]] / [[0,1,2],[3,4],[5,6,7]]     [[0,1,2],[3,4],[5,6,7],[8,9]]
B  [0,0,0,1,1,2,2,2,2,3]  [[0,1,2],[3,4]] / [[0,1,2],[3,4],[5,6,7]]     [[0,1,2],[3,4],[5,6,7,8],[9]]
single group  [0]*6       [] / [[0,1,2,3]]                              [[0,1,2,3,4,5]]

(batch_size=4, values are the row ids.)

drop_last_batch is still part of the Dataset.batch fingerprint, so True and False write separate (identical) cache files.

Why this option over the others listed in the issue:

  • Dropping the final group unconditionally would turn the single-group case (raised by @1OF1Research) into an empty dataset, and would drop a group that is complete, which doesn't match "drop the last incomplete batch".
  • Raising when both arguments are given would break code that passes drop_last_batch generically, for a combination that can simply be well defined.

If you'd prefer one of those instead, I'm happy to switch.

Tests: added test_dataset_batch_by_column_with_drop_last_batch, parametrized over Dataset and IterableDataset (same pattern as test_dataset_batch_by_column_with_nulls), covering both cases from the issue, a single group larger than batch_size, and a length that is an exact multiple of batch_size. The new test fails on main and passes here; pytest tests/test_arrow_dataset.py tests/test_iterable_dataset.py -k batch passes and make quality is clean.

With by_column, drop_last_batch was forwarded to the inner map over
input rows, so it dropped the last input batch instead of an output
batch. Dataset then lost complete groups (the buffered group is only
flushed on the last row), and IterableDataset returned a truncated
group. Groups are always complete, so drop_last_batch no longer drops
anything with by_column, and both dataset types agree.

Fixes huggingface#9028
@JonnyFaeth

Copy link
Copy Markdown

One additional boundary I checked on 6c12105: an indexed view whose entire length is below batch_size. With three rows selected in non-physical order, two grouping keys and a ClassLabel feature, the parent returns unbatched scalar rows for Dataset and no rows for IterableDataset when drop_last_batch=True. This branch returns the expected three complete singleton groups, preserving order and label names; False remains a passing control.

Four new cases pass (parent: two failures/two controls). Existing batching tests in both modules: 192 passed, 4 skipped, plus one existing torch-construction warning. Windows/Python 3.12, local data; Ruff passes. Codex-assisted reproducer:

import pytest
from datasets import Dataset, Features, Value, ClassLabel


@pytest.mark.parametrize("streaming", [False, True])
@pytest.mark.parametrize("drop_last", [False, True])
def test_grouped_short_indexed_view(tmp_path, streaming, drop_last):
    features = Features(
        {
            "id": Value("int64"),
            "group": Value("string"),
            "label": ClassLabel(names=["left", "right"]),
        }
    )
    ds = Dataset.from_dict(
        {
            "id": [0, 1, 2, 3, 4, 5],
            "group": ["unused", "a", "unused", "a", "unused", "b"],
            "label": [0, 0, 0, 1, 0, 1],
        },
        features=features,
    )
    ds = ds.select([5, 1, 3])
    assert ds._indices is not None
    if streaming:
        ds = ds.to_iterable_dataset()
    batched = ds.batch(
        by_column=["group", "label"], batch_size=4, drop_last_batch=drop_last
    )
    rows = list(batched)
    assert [row["id"] for row in rows] == [[5], [1], [3]]
    assert [row["label"] for row in rows] == [[1], [0], [1]]
    assert batched.features["label"].feature.names == ["left", "right"]

@MaiAditya

Copy link
Copy Markdown
Author

Thanks @JonnyFaeth, that's a useful boundary. On main a selected view shorter than batch_size gives unbatched scalar rows for Dataset and nothing for IterableDataset with drop_last_batch=True, so I added it as a case in test_dataset_batch_by_column_with_drop_last_batch (it runs both modes): a three-row select([5, 1, 3]) view, which now comes back as [[5], [1, 3]] in both.

@MaiAditya

Copy link
Copy Markdown
Author

Gentle ping on this one when you have a moment. The branch merges cleanly with main, and the CI workflows are still waiting for approval since this is my first PR here. Happy to adjust anything if needed. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

batch(by_column=..., drop_last_batch=True) drops complete groups in Dataset and returns a truncated group in IterableDataset

2 participants