Repository navigation
tf.data: ensure Dataset.from_tensor_slices and from_tensors convert host arrays on CPU - #129229
Conversation
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.
|
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. |
There was a problem hiding this comment.
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.
dmiltr3
left a comment
There was a problem hiding this comment.
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:
-
Use
DatasetV2in the new host-placement tests (tensorflow/python/data/kernel_tests/from_tensor_slices_test.pyandtensorflow/python/data/kernel_tests/from_tensors_test.py):
test_base.default_test_combinations()runs each test under bothtf_api_version=1andtf_api_version=2. Under the TF1 API,dataset_ops.Dataset.from_tensor_slices(...)anddataset_ops.Dataset.from_tensors(...)return aDatasetV1Adapterwrapper rather than_TensorSliceDatasetor_TensorDataset. BecauseDatasetV1Adapterdoes not expose_tensors, both new tests fail withAttributeError: 'DatasetV1Adapter' object has no attribute '_tensors'in the TF1 test combinations. Please construct the datasets viadataset_ops.DatasetV2.from_tensor_slices(x)anddataset_ops.DatasetV2.from_tensors(x)so that_tensorsis tested across both TF1 and TF2 combinations. -
Remove the deprecated
test_util.is_gpu_available()check andtest_utilimports (tensorflow/python/data/kernel_tests/from_tensor_slices_test.pyandtensorflow/python/data/kernel_tests/from_tensors_test.py):
test_util.is_gpu_available()is deprecated, and the conditional branch is unnecessary because enteringwith ops.device("/device:GPU:0"):succeeds even on CPU-only machines in both eager and graph modes. Entering the/device:GPU:0scope unconditionally also strengthens the graph-mode assertion on CPU-only test runners. Please remove thefrom tensorflow.python.framework import test_utilimport and theif test_util.is_gpu_available():conditional in both test files, and always construct the dataset insidewith ops.device("/device:GPU:0"):. -
Consume the datasets and annotate protected access in both new tests (
tensorflow/python/data/kernel_tests/from_tensor_slices_test.pyandtensorflow/python/data/kernel_tests/from_tensors_test.py):
Please add# pylint: disable=protected-accesson thefor t in dataset._tensors:lines and verify dataset consumption withself.assertDatasetProduces(...)after checkingt.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])- Add a graph-mode test verifying that pre-existing device placement on a
tf.Tensoris preserved (tensorflow/python/data/kernel_tests/from_tensor_slices_test.py):
To cover the guarantee that pre-allocatedtf.Tensorobjects keep their device placement, please add a graph-mode test intensorflow/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)-
Add the missing BUILD dependency (
tensorflow/python/data/kernel_tests/BUILD):
Becausetensorflow/python/data/kernel_tests/from_tensor_slices_test.pynow importsfrom tensorflow.python.framework import opsandfrom_tensor_slices_testusestf_py_strict_test, please add"//tensorflow/python/framework:ops",to thedepslist offrom_tensor_slices_testintensorflow/python/data/kernel_tests/BUILD. -
Update the PR title and description:
Please update the PR title so it mentions bothDataset.from_tensor_slicesandDataset.from_tensors, and note in the PR description whether the eager-mode GPU path was verified on a machine with a GPU device.
…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.
|
@dmiltr3 All requested changes have been addressed in commit 2d1ff2b:
|
dmiltr3
left a comment
There was a problem hiding this comment.
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.
`--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
Summary
Fixes #71744.
When executing in eager mode with GPU devices active, calling
tf.data.Dataset.from_tensor_slicesortf.data.Dataset.from_tensorson 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 thoughtf.datainput tensors run on host CPU memory.Changes
structure.normalize_element(element)insidewith ops.device("/device:CPU:0"):in_TensorSliceDataset.__init__(tensorflow/python/data/ops/from_tensor_slices_op.py).structure.normalize_element(element)insidewith ops.device("/device:CPU:0"):in_TensorDataset.__init__(tensorflow/python/data/ops/from_tensors_op.py).tf.Tensorobjects already residing on a device remain unaffected becauseops.convert_to_tensorreturns identical tensors unmodified.DatasetV2in unit tests to ensure_tensorsis accessible and tested across both TF1 and TF2 test combinations.test_util.is_gpu_available()checks and entered/device:GPU:0scope unconditionally across host placement unit tests.# pylint: disable=protected-accessannotations and verified dataset consumption viaassertDatasetProduces.testFromTensorSlicesExistingTensorPlacementPreservedensuring pre-existing tensor placement on GPU is preserved."//tensorflow/python/framework:ops"dependency tofrom_tensor_slices_testtarget intensorflow/python/data/kernel_tests/BUILD.Verification & Testing Note
python3 -m py_compileacross all modified Python modules and tests.bazel test //tensorflow/python/data/kernel_tests:from_tensor_slices_testbazel test //tensorflow/python/data/kernel_tests:from_tensors_test