Skip to content

Reuse unchanged columns in Dataset.map when input_columns is specified - #9080

Open
GuilhermeLopesBertacini wants to merge 1 commit into
huggingface:mainfrom
GuilhermeLopesBertacini:feat/issue-6013-map-reuse-unchanged-columns
Open

GuilhermeLopesBertacini wants to merge 1 commit into
huggingface:mainfrom
GuilhermeLopesBertacini:feat/issue-6013-map-reuse-unchanged-columns

Conversation

@GuilhermeLopesBertacini

Copy link
Copy Markdown

Fixes #6013

Summary

When input_columns is specified in Dataset.map (and shard._indices is None), columns not passed to function and not returned by function are guaranteed unchanged. Instead of rewriting those columns to the new Arrow cache file on disk, map now omits them from ArrowWriter and reattaches them horizontally via concat_tables(..., axis=1) and update_metadata_with_features.

Details

  • Added _get_reusable_columns and _merge_reused_columns helpers in src/datasets/arrow_dataset.py.
  • Updated Dataset._map_single to exclude unchanged unrequested columns from inputs_to_merge and writer_features, and merge them back in original column order after finalizing the mapped shard.
  • Updated load_processed_shard_from_cache inside Dataset.map so cache hits against partial cache files reattach unchanged columns transparently (compatible with num_proc > 1, batched=True, remove_columns, and chained map calls).
  • Added test_map_input_columns_reuses_unchanged_columns in tests/test_arrow_dataset.py verifying disk cache size reduction (<20% of source file when modifying small columns alongside a large column), cache hits, and multiprocessing chained maps.

Testing

  • Ran pytest tests/test_arrow_dataset.py -k "test_map" -v (44 passed, 10 skipped — optional jax/polars/tf/torch framework tests skipped)
  • Ran ruff check and ruff format --check on modified files (All checks passed!)

@JonnyFaeth

Copy link
Copy Markdown

I reproduced a row-alignment regression on ff4bc66 when a batched map shrinks its input while an unrequested column remains. For example, value=[0,1,2,3], label=[zero,one,two,three], input_columns=[value], and returning value[1::2]. Previously Arrow rejects the unequal column lengths. Here the label column is removed from writer validation and _merge_reused_columns slices the original column to the shorter output, allowing incorrect row associations.

The attached tests cover both memory and explicit disk-cache output, plus a valid shrinking-map control that removes label. Parent: 3 passed. PR: 2 failed, 1 passed (no ArrowInvalid for either retained-column case). The narrow fix checks batch lengths before excluding reused columns; the new cases plus existing batched/input_columns/remove_columns tests give 9 passed, 470 deselected.

Ruff check/format and diff checks pass. Windows CPU; a broader test_map selection stalled and was interrupted, so I am not claiming full map-suite or multiprocessing validation. Codex assisted with investigation, the patch and tests.

diff --git a/src/datasets/arrow_dataset.py b/src/datasets/arrow_dataset.py
index b9a0c18cf..f43b509bc 100644
--- a/src/datasets/arrow_dataset.py
+++ b/src/datasets/arrow_dataset.py
@@ -4039,6 +4039,11 @@ class Dataset(DatasetInfoMixin, IndexableMixin, TensorflowDatasetMixin):
                     )
                     reused_cols_set = set(reused_cols)
                 if reused_cols:
+                    if batched and any(len(value) != len(pa_inputs) for value in processed_inputs.values()):
+                        raise pa.ArrowInvalid(
+                            "Mapped batch length differs from retained source columns. "
+                            "Remove or return those columns when changing the number of examples."
+                        )
                     inputs_to_merge = {k: v for k, v in inputs_to_merge.items() if k not in reused_cols_set}
                 # The .map() transform *updates* the dataset:
                 # the output dictionary contains both the input data and the output data.
diff --git a/tests/test_map_reuse_alignment.py b/tests/test_map_reuse_alignment.py
new file mode 100644
--- /dev/null
+++ b/tests/test_map_reuse_alignment.py
@@ -0,0 +1,20 @@
+import pyarrow as pa
+import pytest
+
+from datasets import Dataset
+
+
+@pytest.mark.parametrize("on_disk", [False, True])
+def test_map_input_columns_rejects_unaligned_retained_column(tmp_path, on_disk):
+    dataset = Dataset.from_dict({"value": [0, 1, 2, 3], "label": ["zero", "one", "two", "three"]})
+    kwargs = {"cache_file_name": str(tmp_path / "mapped.arrow")} if on_disk else {"keep_in_memory": True}
+    with pytest.raises(pa.ArrowInvalid):
+        dataset.map(lambda values: {"value": values[1::2]}, input_columns=["value"], batched=True, **kwargs)
+
+
+def test_map_input_columns_can_shrink_when_other_columns_removed():
+    dataset = Dataset.from_dict({"value": [0, 1, 2, 3], "label": ["zero", "one", "two", "three"]})
+    result = dataset.map(
+        lambda values: {"value": values[1::2]}, input_columns=["value"], batched=True, remove_columns=["label"]
+    )
+    assert result.to_dict() == {"value": [1, 3]}

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.

[FR] map should reuse unchanged columns from the previous dataset to avoid disk usage

2 participants