Skip to content

tf.data: ensure Dataset.from_tensor_slices and from_tensors convert host arrays on CPU - #129229

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
JohnnyWilson16:fix/from-tensor-slices-cpu-allocation
Nov 2, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
JohnnyWilson16:fix/from-tensor-slices-cpu-allocation

Conversation

@JohnnyWilson16

@JohnnyWilson16 JohnnyWilson16 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #71744.

When executing in eager mode with GPU devices active, calling tf.data.Dataset.from_tensor_slices or tf.data.Dataset.from_tensors on host NumPy arrays or Python primitives converted inputs on the active default device (e.g., /device:GPU:0), allocating accelerator memory during dataset construction even though tf.data input tensors run on host CPU memory.

Changes

  • Scoped structure.normalize_element(element) inside with ops.device("/device:CPU:0"): in _TensorSliceDataset.__init__ (tensorflow/python/data/ops/from_tensor_slices_op.py).
  • Scoped structure.normalize_element(element) inside with ops.device("/device:CPU:0"): in _TensorDataset.__init__ (tensorflow/python/data/ops/from_tensors_op.py).
  • Pre-allocated tf.Tensor objects already residing on a device remain unaffected because ops.convert_to_tensor returns identical tensors unmodified.
  • Constructed datasets via DatasetV2 in unit tests to ensure _tensors is accessible and tested across both TF1 and TF2 test combinations.
  • Removed deprecated test_util.is_gpu_available() checks and entered /device:GPU:0 scope unconditionally across host placement unit tests.
  • Added # pylint: disable=protected-access annotations and verified dataset consumption via assertDatasetProduces.
  • Added graph-mode regression test testFromTensorSlicesExistingTensorPlacementPreserved ensuring pre-existing tensor placement on GPU is preserved.
  • Added missing "//tensorflow/python/framework:ops" dependency to from_tensor_slices_test target in tensorflow/python/data/kernel_tests/BUILD.

Verification & Testing Note

  • Eager-mode GPU verification note: Local development and test verification was conducted in a CPU environment with graph-mode device placement simulation. The changes and tests rely on upstream Kokoro GPU CI runners to execute the physical CUDA device allocation path.
  • Syntax verification: Passed via python3 -m py_compile across all modified Python modules and tests.
  • Test targets:
    • bazel test //tensorflow/python/data/kernel_tests:from_tensor_slices_test
    • bazel test //tensorflow/python/data/kernel_tests:from_tensors_test

When executing in eager mode with GPU devices present, calling
Dataset.from_tensor_slices or Dataset.from_tensors converts input NumPy
arrays and Python primitives on the current active default device
(e.g. /device:GPU:0), consuming accelerator VRAM for input sources that
operate on host CPU memory.

This scopes structure.normalize_element within an explicit CPU:0 device
context in _TensorSliceDataset.__init__ and _TensorDataset.__init__,
preventing unintended VRAM allocations during dataset construction.

Fixes tensorflow#71744.
@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Oct 17, 2026
@google-cla

google-cla Bot commented Oct 17, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request ensures that element normalization in Dataset.from_tensor_slices and Dataset.from_tensors is explicitly executed on the CPU device (/device:CPU:0), preventing unintended GPU placement. It also introduces corresponding unit tests to verify host placement. The review feedback suggests refactoring both of the new test cases to eliminate duplicate assertion loops across the conditional branches, which improves code readability and maintainability.

@keerthanakadiri
keerthanakadiri requested a review from a team October 19, 2026 05:00
@keerthanakadiri keerthanakadiri self-assigned this Oct 19, 2026
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 19, 2026
@keerthanakadiri keerthanakadiri added the python Pull requests that update Python code label Oct 19, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 19, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Oct 19, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The production changes in tensorflow/python/data/ops/from_tensor_slices_op.py and tensorflow/python/data/ops/from_tensors_op.py are sound, as only host-input normalization is scoped to /device:CPU:0 while preserving existing tensor placements and outer device context fields. However, the new tests and metadata require the following changes before this PR can be merged:

  1. Use DatasetV2 in the new host-placement tests (tensorflow/python/data/kernel_tests/from_tensor_slices_test.py and tensorflow/python/data/kernel_tests/from_tensors_test.py):
    test_base.default_test_combinations() runs each test under both tf_api_version=1 and tf_api_version=2. Under the TF1 API, dataset_ops.Dataset.from_tensor_slices(...) and dataset_ops.Dataset.from_tensors(...) return a DatasetV1Adapter wrapper rather than _TensorSliceDataset or _TensorDataset. Because DatasetV1Adapter does not expose _tensors, both new tests fail with AttributeError: 'DatasetV1Adapter' object has no attribute '_tensors' in the TF1 test combinations. Please construct the datasets via dataset_ops.DatasetV2.from_tensor_slices(x) and dataset_ops.DatasetV2.from_tensors(x) so that _tensors is tested across both TF1 and TF2 combinations.

  2. Remove the deprecated test_util.is_gpu_available() check and test_util imports (tensorflow/python/data/kernel_tests/from_tensor_slices_test.py and tensorflow/python/data/kernel_tests/from_tensors_test.py):
    test_util.is_gpu_available() is deprecated, and the conditional branch is unnecessary because entering with ops.device("/device:GPU:0"): succeeds even on CPU-only machines in both eager and graph modes. Entering the /device:GPU:0 scope unconditionally also strengthens the graph-mode assertion on CPU-only test runners. Please remove the from tensorflow.python.framework import test_util import and the if test_util.is_gpu_available(): conditional in both test files, and always construct the dataset inside with ops.device("/device:GPU:0"):.

  3. Consume the datasets and annotate protected access in both new tests (tensorflow/python/data/kernel_tests/from_tensor_slices_test.py and tensorflow/python/data/kernel_tests/from_tensors_test.py):
    Please add # pylint: disable=protected-access on the for t in dataset._tensors: lines and verify dataset consumption with self.assertDatasetProduces(...) after checking t.device.

For tensorflow/python/data/kernel_tests/from_tensor_slices_test.py:

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorSlicesHostPlacement(self):
    x = np.arange(10, dtype=np.int64)
    with ops.device("/device:GPU:0"):
      dataset = dataset_ops.DatasetV2.from_tensor_slices(x)
    for t in dataset._tensors:  # pylint: disable=protected-access
      self.assertIn("CPU", t.device)
    self.assertDatasetProduces(dataset, expected_output=list(x))

For tensorflow/python/data/kernel_tests/from_tensors_test.py:

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsHostPlacement(self):
    x = np.array([1, 2, 3], dtype=np.int64)
    with ops.device("/device:GPU:0"):
      dataset = dataset_ops.DatasetV2.from_tensors(x)
    for t in dataset._tensors:  # pylint: disable=protected-access
      self.assertIn("CPU", t.device)
    self.assertDatasetProduces(dataset, expected_output=[x])
  1. Add a graph-mode test verifying that pre-existing device placement on a tf.Tensor is preserved (tensorflow/python/data/kernel_tests/from_tensor_slices_test.py):
    To cover the guarantee that pre-allocated tf.Tensor objects keep their device placement, please add a graph-mode test in tensorflow/python/data/kernel_tests/from_tensor_slices_test.py:
  @combinations.generate(test_base.graph_only_combinations())
  def testFromTensorSlicesExistingTensorPlacementPreserved(self):
    with ops.device("/device:GPU:0"):
      x = ops.convert_to_tensor(np.arange(10, dtype=np.int64))
    dataset = dataset_ops.DatasetV2.from_tensor_slices(x)
    for t in dataset._tensors:  # pylint: disable=protected-access
      self.assertIn("GPU", t.device)
  1. Add the missing BUILD dependency (tensorflow/python/data/kernel_tests/BUILD):
    Because tensorflow/python/data/kernel_tests/from_tensor_slices_test.py now imports from tensorflow.python.framework import ops and from_tensor_slices_test uses tf_py_strict_test, please add "//tensorflow/python/framework:ops", to the deps list of from_tensor_slices_test in tensorflow/python/data/kernel_tests/BUILD.

  2. Update the PR title and description:
    Please update the PR title so it mentions both Dataset.from_tensor_slices and Dataset.from_tensors, and note in the PR description whether the eager-mode GPU path was verified on a machine with a GPU device.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 19, 2026
…ndency

- Construct datasets via DatasetV2 in from_tensor_slices_test and
  from_tensors_test to support TF1 and TF2 test combinations.
- Remove deprecated test_util.is_gpu_available() check and enter
  /device:GPU:0 device context unconditionally.
- Verify dataset output with assertDatasetProduces and add pylint
  protected-access annotations for _tensors checks.
- Add graph-mode test testFromTensorSlicesExistingTensorPlacementPreserved
  to ensure pre-allocated tensor device placement remains intact.
- Add //tensorflow/python/framework:ops to from_tensor_slices_test deps
  in tensorflow/python/data/kernel_tests/BUILD.
@JohnnyWilson16 JohnnyWilson16 changed the title tf.data: ensure Dataset.from_tensor_slices converts host arrays on CPU tf.data: ensure Dataset.from_tensor_slices and from_tensors convert host arrays on CPU Oct 19, 2026
@JohnnyWilson16

Copy link
Copy Markdown
Contributor Author

@dmiltr3 All requested changes have been addressed in commit 2d1ff2b:

  1. DatasetV2 in host-placement tests: Updated from_tensor_slices_test.py and from_tensors_test.py to construct datasets via dataset_ops.DatasetV2.from_tensor_slices and dataset_ops.DatasetV2.from_tensors, ensuring _tensors attribute accessibility across both TF1 and TF2 test combinations.
  2. Removed deprecated test_util: Removed from tensorflow.python.framework import test_util and the deprecated test_util.is_gpu_available() conditional branches across both test files; datasets are now unconditionally constructed within with ops.device("/device:GPU:0"):.
  3. Dataset consumption & lint annotations: Added # pylint: disable=protected-access to dataset._tensors loops and asserted dataset output via self.assertDatasetProduces(...).
  4. Graph-mode existing placement test: Added testFromTensorSlicesExistingTensorPlacementPreserved with @combinations.generate(test_base.graph_only_combinations()) in from_tensor_slices_test.py to verify that pre-allocated tf.Tensor device placement on GPU remains intact.
  5. BUILD dependency: Added "//tensorflow/python/framework:ops" to from_tensor_slices_test's deps in tensorflow/python/data/kernel_tests/BUILD.
  6. PR Title and Description: Updated the PR title to include both Dataset.from_tensor_slices and from_tensors, and added a note detailing CPU local verification with graph device simulation alongside reliance on Kokoro CI for physical GPU execution.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you for addressing all of the feedback from the previous review round.

The updates to tensorflow/python/data/kernel_tests/from_tensor_slices_test.py, tensorflow/python/data/kernel_tests/from_tensors_test.py, tensorflow/python/data/kernel_tests/BUILD, and the PR title and description look good and are ready to merge.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 19, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 19, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Oct 23, 2026
copybara-service Bot pushed a commit that referenced this pull request Nov 2, 2026
`--xla_dump_fusion_visualization` previously built a temporary SQLite database on disk (`fusions.db`), compressed each unique DOT graph with GZIP before inserting it as a BLOB, memory-mapped the database file, and DEFLATE-compressed it a second time into the output `.pyz` zipapp, only for `viewer_server.py` to unpack `fusions.db` back to a temporary directory on startup. That pulled the entire SQLite library (~1.83 MB stripped) into binaries linking `hlo_graph_dumper` solely to index an append-only list of frames and integer-keyed DOT graphs.

- Write `metadata.json` and `graphs/<i>.dot` directly into `tsl::io::ZipWriter` in `xla/service/hlo_graph_dumper.cc` and serve them directly from `zipfile.ZipFile` in `xla/service/fusion_explorer/viewer_server.py`, dropping the SQLite dependency.
- Iterate visited instructions in deterministic BFS discovery order in `MakeNodeRadiusAroundFilter` rather than iterating over `absl::flat_hash_map`.
- Packaging is ~1.3x faster on multi-step fusion traces by avoiding temporary database file I/O and double compression, and viewer startup is ~2.3x faster with lower disk and memory overhead because `viewer.html` and `metadata.json` are read once in memory while individual DOT graphs are read on demand without extracting a database file.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#129229 from JohnnyWilson16:fix/from-tensor-slices-cpu-allocation 2d1ff2b
PiperOrigin-RevId: 1008630090
@copybara-service
copybara-service Bot merged commit df4c918 into tensorflow:master Nov 2, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug python Pull requests that update Python code ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.data.Dataset.from_tensor_slices allocates GPU RAM

4 participants