Skip to content

Add torch._C._has_storage_data and use it in Tensor deepcopy and pickling (#203963) - #203963

Closed
aelavender wants to merge 1 commit into
pytorch:mainfrom
aelavender:export-D130296831
Closed

aelavender wants to merge 1 commit into
pytorch:mainfrom
aelavender:export-D130296831

Conversation

@aelavender

@aelavender aelavender commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Human Summary

Issue: #203866

There's not a clean way, and many problematic ways, of checking whether or not a tensor subclass owns data (vs. a wrapper subclass that does not own data directly):

Method Why it's problematic
tensor.data_ptr() != 0 Incorrect if tensor.storage_offset != 0: a wrapper subclass that also implements storage_offset returns a small but nonzero integer. Also materializes copy-on-write tensors.
tensor.untyped_storage().data_ptr() != 0 Throws RuntimeError if the Storage is a placeholder -- happens for DTensor, FakeTensor, etc.
tensor.untyped_storage().data_ptr() != 0 but catch the RuntimeError Works, but materializes COW tensors

Notably, the first one is used in Tensor.__reduce_ex__, meaning anything that pickled such a tensor (multiprocessing, torch.save(), DCP) hit the bug.

Fix

Add a method torch._C._has_storage_data -- basically the same as torch._C._has_storage, but also checks that the storage's data_ptr is not null. This avoids materializing COWs: we're just checking if data exists, not trying to read it.

Have the Tensor.__reduce_ex__ and Tensor.__deepcopy__ use it. Applications (DCP) to be fixed in subsequent change.

Related change

Fixing this exposes a bug in Inductor, which is also fixed here. Inductor previously tried to deepcopy its full config for the purpose of logging, including custom passes, which would then deepcopy fake tensors. Previously this would error out and get swallowed; after this change, it would duplicate StorageWeakRefs, which leads to a double-free bug when the second copy of the weak ref goes out of scope. Fix is to avoid doing the unnecessary deepcopy in the first place, and only copy the serializable fields.


Agent details (AI-generated, drafted with an AI coding assistant)

Bug

Tensor.__deepcopy__ and Tensor._reduce_ex_internal use self.data_ptr() == 0 to mean "this is a wrapper subclass whose storage holds no data". data_ptr() is storage.data() + itemsize * storage_offset, and returns nullptr when numel() == 0, so the heuristic is wrong in both directions:

  • A wrapper subclass (_make_wrapper_subclass, DTensor) gets a placeholder storage with a null data pointer. With a nonzero storage offset, data_ptr() is a small nonzero integer (e.g. 16 for a TwoTensor at offset 4), so the wrapper is treated as a real-storage tensor. TwoTensor, LoggingTensor and FunctionalTensor propagate inner offsets, and DTensor copies its local tensor's offset, so DTensor.from_local(base[2:6], ...) hits this. Then:
    • copy.deepcopy raises Attempted to call copy_() on an invalid python storage.
    • torch.save and pickle.dumps raise Attempted to access the data pointer on an invalid python storage.
    • multiprocessing.reduction.ForkingPickler.dumps segfaults, because the storage reducer shares a null pointer.
  • A real-storage subclass with numel() == 0 that views a non-empty storage reports data_ptr() == 0, so torch.save serializes it as an empty wrapper and drops its storage.

t.untyped_storage().data_ptr() is not a usable replacement: it raises for non-empty placeholder storages (Note [Invalid Python Storages]) and goes through mutable_data(), which materializes copy-on-write storages.

Fix

Add a private binding torch._C._has_storage_data(t), next to torch._C._has_storage. It returns True iff t has a storage whose data pointer is non-null. It reaches the storage through unsafe_storage() and reads the pointer through the existing StorageImpl::_mutable_data_ptr_no_checks(), as torch._C._is_cow_tensor already does. Despite the name, nothing is mutated: the accessor only returns the DataPtr, and the binding only compares it with null. Tensors without storage (sparse, functorch batched tensors) return False through has_storage().

Which accessor:

  • The mutable accessors must be avoided. Tensor.data_ptr() and UntypedStorage.data_ptr() use them. They materialize COW storages, and they raise for storages marked throw_on_mutable_data_ptr, which FakeTensor and FunctionalTensor set (Cannot access data pointer of Tensor (e.g. FakeTensor, FunctionalTensor)). That raise is why copy.deepcopy of a strict-export-v2 graph module failed (see the test change below).
  • The checked const accessor StorageImpl::data_ptr() avoids both, and would fix every call site in this stack.
  • _mutable_data_ptr_no_checks() also skips the const accessor's two checks, so the query never raises:
    • throw_on_immutable_data_ptr: storages whose data access PyTorch forbids, e.g. CUDA graph outputs overwritten by a later replay.
    • For CUDA COW storages, check_cow_read. It raises after _cow_record_done(), or inside a CUDA graph capture other than the one the clone was made in, and it takes a device guard to query the capture id.
      For such storages the binding reports whether memory is allocated (True for a real storage whose access is forbidden); the caller gets the access error when it reads the data.

__deepcopy__ now uses not torch._C._has_storage_data(self) in place of self.data_ptr() == 0, and _reduce_ex_internal uses torch._C._has_storage(self) and not torch._C._has_storage_data(self). Nothing changes for plain tensors, meta tensors or FunctionalTensor, which the conditions around these checks handle, nor for fake tensors in _reduce_ex_internal. Behaviour changes:

  • Offset wrappers now take the wrapper path (clone in deepcopy, _rebuild_wrapper_subclass in pickling) instead of failing, and empty views of real storage keep their storage.
  • In __deepcopy__, a fake tensor view at a nonzero storage offset now takes the clone() path, like fake tensors at offset 0 and meta tensors. Before, its data_ptr() was the null pointer plus the offset, so it took the storage path, which keeps the offset and memo-based aliasing with other deepcopied tensors. The copy now has offset 0 and no longer shares storage with a deepcopied base.
  • In __deepcopy__, tensors for which data_ptr() used to raise (fake tensors when unsafe data pointer access is disabled, subclasses of tensors with no storage such as MKLDNN) now take the clone() path.
  • _reduce_ex_internal also requires torch._C._has_storage(self) for the wrapper path. Every wrapper subclass has a placeholder storage, so this excludes only tensors with no storage at all, which would otherwise be saved as a wrapper without their data. They still fail to pickle, now with NotImplementedError: Cannot access storage of OpaqueTensorImpl from the storage path.

Note [Invalid Python Storages] now points to the new binding.

Config snapshots no longer deep-copy custom passes:

  • Dynamo's compilation metrics log the inductor and functorch configs from get_serializable_config_copy() instead of get_config_copy(). These copies are only serialized to JSON, and the serializable copy skips the _save_config_ignore entries before deep-copying: the custom pass hooks for inductor, and joint_custom_pass for functorch.
  • get_patched_config_dict() deep-copies only the serializable entries and holds the _save_config_ignore entries by reference. It backs get_compiler_config(), whose snapshot torch.compile() takes when it wraps a function, and Inductor's fbcode-only pt2_configs log, which runs on every compile. get_compiler_config() still returns every key; a custom pass in it is now the configured object rather than a deep copy.

Why this is needed with _has_storage_data:

  • Deep-copying a custom pass can reach arbitrary objects. In test/distributed/tensor/test_compile_on_one_rank.py, test_iota_device_fix_rank_agnostic_under_coor uses a pass that keeps FX nodes, and through them the fake tensors in their graph's metadata.
  • On main, these copies stop at the first fake tensor: data_ptr() raises for fake tensors created under Dynamo. The logging code swallows the error, and torch.compile() raises it when the pass already holds nodes from an earlier compile.
  • With _has_storage_data, the fake tensor's deepcopy succeeds and continues into its FakeTensorMode, whose converter keys a dict by StorageWeakRef. Copying a StorageWeakRef duplicates its raw weak pointer, so the weak reference is released twice and the process crashes at exit with heap corruption. That bug predates this change and will be fixed separately.

Side effects:

  • Besides the custom passes, the logged inductor config no longer includes trace.upload_tar, aot_inductor.repro_level, aot_inductor.dump_aoti_minifier, _fuse_ddp_communication_passes and cudagraph_policy, and the logged functorch config no longer includes activation_memory_budget_runtime_estimator and activation_memory_budget_solver.
  • _post_fusion_custom_pass and custom_partitioner_fn are not in _save_config_ignore, so these copies still deep-copy them. Adding them would also change save_config() and the config sent to subprocess compiles, so that is left out of this change.

Alternatives considered

  • Reading the pointer through the checked const StorageImpl::data(): _has_storage_data would then raise for storages whose access is forbidden and for CUDA COW storages inside a foreign capture, instead of answering.
  • A new const accessor StorageImpl::_data_ptr_no_checks() const: more c10 API for no extra safety. DataPtr::get() is void* get() const, so it would still hand out a writable pointer.
  • A new bool StorageImpl::has_data() const: const-correct and exposes no pointer, but adds a c10 method. The Python binding is the same either way, so it can be added later if C++ code needs the same check.
  • try: t.untyped_storage().data_ptr() in Python: raises by design for wrappers and materializes COW storages.
  • Checking storage_offset() == 0 as well: still wrong for empty views of real storage, and does not express what callers want.
  • A method on UntypedStorage instead of a tensor-level function: from Python, t.untyped_storage() already allocates a storage wrapper object, and every caller asks the question about a tensor. A storage method can be added later if needed.

The distributed call sites that use the same heuristic (DCP staging, _create_cpu_state_dict) and torch.utils._cuda_debug are fixed in follow-up commits.

Test Plan:
New tests:

  • test_torch.py TestTorchDeviceType.test_has_storage_data: True for dense tensors, views, an empty view of a non-empty storage (whose data_ptr() is 0) and nn.Parameter; False for TwoTensor at offsets 0 and 4, fake, meta, torch.empty(0), sparse and vmap-batched tensors. Runs on CPU and CUDA (onlyNativeDeviceTypes, as is test_has_storage_data_ignores_data_access_checks).
  • test_torch.py TestTorchDeviceType.test_has_storage_data_does_not_materialize_cow: a lazy clone stays COW after the call.
  • test_torch.py TestTorchDeviceType.test_has_storage_data_ignores_data_access_checks: for a real and a meta storage marked with _set_storage_data_ptr_access_error_msg, const_data_ptr() raises while _has_storage_data returns True and False. It also covers a fake tensor made under FakeTensorMode with unsafe data pointer access disabled: data_ptr() raises and _has_storage_data returns False.
  • test_torch.py TestTorchDeviceType.test_has_storage_data_ignores_cow_read_check_in_cuda_graph_capture (CUDA only, skipped without CUDA graph support): inside a torch.cuda.graph capture, const_data_ptr() of a COW clone made before the capture raises Materialize COW graph inputs ... while _has_storage_data returns True and the clone stays COW.
  • test/export/test_export.py: removes testing.expectedFailureStrictV2 from test_custom_tag_metadata_re_export.
    • On the parent commit it is an expected failure. copy.deepcopy(ep.graph_module) reaches a FakeTensor that strict export v2 leaves in the graph module, and Tensor.__deepcopy__ raises at self.data_ptr() == 0 with Cannot access data pointer of Tensor (e.g. FakeTensor, FunctionalTensor).
    • With this change it passes. CI reported it as an unexpected success.
  • test_serialization.py TestSubclassSerialization.test_wrapper_subclass_with_storage_offset_roundtrip: deepcopy, torch.save/torch.load, pickle and ForkingPickler round trips of a TwoTensor at storage offset 4. The result is rebuilt as a wrapper (_has_storage_data is False) and, except after deepcopy, keeps the storage offset.
  • test_serialization.py TestSubclassSerialization.test_storageless_subclass_is_not_saved_as_wrapper: torch.save of a _make_subclass subclass with __torch_dispatch__ around an MKLDNN tensor (no storage) raises NotImplementedError. Without the torch._C._has_storage(self) guard in _reduce_ex_internal, torch.save succeeds and the data is lost (the test fails with NotImplementedError not raised).
  • test_serialization.py TestSubclassSerialization.test_empty_view_of_real_storage_subclass_keeps_storage: a _make_subclass tensor with __torch_dispatch__ viewing base[2:2] keeps its storage and offset through torch.save.
  • test/distributed/tensor/test_dtensor.py DTensorStorageOffsetTest: the same four round trips for DTensor.from_local(base[2:6], ...) on a world-size-1 fake process group, with the same checks, and _has_storage_data on it.
  • test/dynamo/test_utils.py TestInductorConfigParsingForLogging.test_inductor_config_logging_does_not_copy_custom_passes: with a custom pass set as post_grad_custom_pre_pass, _scrubbed_inductor_config_for_logging() does not deep-copy it, and the logged JSON has no post_grad_custom_pre_pass key. It fails with get_config_copy(). test_inductor_config_parsing_non_conforming_items now mocks get_serializable_config_copy.
  • test/dynamo/test_utils.py TestFunctorchConfigParsingForLogging.test_functorch_config_logging_does_not_copy_joint_custom_pass: with a joint_custom_pass set, _functorch_config_for_logging() does not deep-copy it, and the logged JSON has no joint_custom_pass key. It fails with get_config_copy(). test_functorch_config_none and test_functorch_config_runtime_error now mock get_serializable_config_copy.
  • test/inductor/test_custom_post_grad_passes.py test_custom_pass_is_not_deep_copied: torch.compile with a custom pass set as post_grad_custom_pre_pass runs the pass but never deep-copies it, and get_compiler_config() returns that same pass object. In an fbcode build it fails with the old get_patched_config_dict(): the pass is deep-copied twice, once for the torch.compile() snapshot and once for the pt2_configs log.
  • Existing get_compiler_config() tests (test/inductor/test_config.py test_get_compiler_config, test/inductor/test_compile_options.py test_torch_compile_routed_option) pass.
  • test/distributed/tensor/test_compile_on_one_rank.py, on a 2.16.0.dev20261108+cu132 nightly with this change's torch/_tensor.py and torch/_dynamo/utils.py edits applied (_has_storage_data emulated in Python):
    • Without the torch/_dynamo/utils.py edit, every test passes and the process then aborts at exit (exit 134 or 139, 3 of 3 runs; malloc(): unsorted double linked list corrupted with CI's disabled tests excluded, as in CI).
    • With it, the process exits 0: 2 of 2 full runs (158 passed), and 1 of 1 with CI's disabled tests excluded (142 passed).
    • With the fbcode-only pt2_configs block forced on, and Dynamo's logging already changed: with the old get_patched_config_dict(), test_iota_device_fix_rank_agnostic_under_coor_index_device_cpu aborts at exit in 5 of 6 runs (its fake tensors are deep-copied in all 6). With this change it exits 0 in 2 of 2 runs, and the file with CI's disabled tests excluded exits 0 (142 passed).
  • A pass that still holds FX nodes from the iota test's compile when torch.compile() wraps another function, on the same nightly: on main, the second torch.compile() raises RuntimeError: Cannot access data pointer of Tensor (2 of 2 runs). With _has_storage_data and the logging changes but the old get_patched_config_dict(), it succeeds and the process then aborts at exit with heap corruption (2 of 2). With this change it succeeds and the process exits 0 (2 of 2).

Differential Revision: D130296831

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98

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

Labels

ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged meta-exported module: dynamo module: inductor ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (dtensor) release notes category topic: bug fixes topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants