Repository navigation
Add torch._C._has_storage_data and use it in Tensor deepcopy and pickling (#203963) - #203963
Closed
aelavender wants to merge 1 commit into
Closed
aelavender wants to merge 1 commit into
aelavender wants to merge 1 commit into
Conversation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):
tensor.data_ptr() != 0tensor.storage_offset != 0: a wrapper subclass that also implementsstorage_offsetreturns a small but nonzero integer. Also materializes copy-on-write tensors.tensor.untyped_storage().data_ptr() != 0RuntimeErrorif the Storage is a placeholder -- happens for DTensor, FakeTensor, etc.tensor.untyped_storage().data_ptr() != 0but catch theRuntimeErrorNotably, 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 astorch._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__andTensor.__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__andTensor._reduce_ex_internaluseself.data_ptr() == 0to mean "this is a wrapper subclass whose storage holds no data".data_ptr()isstorage.data() + itemsize * storage_offset, and returns nullptr whennumel() == 0, so the heuristic is wrong in both directions:_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 aTwoTensorat offset 4), so the wrapper is treated as a real-storage tensor.TwoTensor,LoggingTensorandFunctionalTensorpropagate inner offsets, and DTensor copies its local tensor's offset, soDTensor.from_local(base[2:6], ...)hits this. Then:copy.deepcopyraisesAttempted to call copy_() on an invalid python storage.torch.saveandpickle.dumpsraiseAttempted to access the data pointer on an invalid python storage.multiprocessing.reduction.ForkingPickler.dumpssegfaults, because the storage reducer shares a null pointer.numel() == 0that views a non-empty storage reportsdata_ptr() == 0, sotorch.saveserializes 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 throughmutable_data(), which materializes copy-on-write storages.Fix
Add a private binding
torch._C._has_storage_data(t), next totorch._C._has_storage. It returns True iffthas a storage whose data pointer is non-null. It reaches the storage throughunsafe_storage()and reads the pointer through the existingStorageImpl::_mutable_data_ptr_no_checks(), astorch._C._is_cow_tensoralready does. Despite the name, nothing is mutated: the accessor only returns theDataPtr, and the binding only compares it with null. Tensors without storage (sparse, functorch batched tensors) return False throughhas_storage().Which accessor:
Tensor.data_ptr()andUntypedStorage.data_ptr()use them. They materialize COW storages, and they raise for storages markedthrow_on_mutable_data_ptr, which FakeTensor and FunctionalTensor set (Cannot access data pointer of Tensor (e.g. FakeTensor, FunctionalTensor)). That raise is whycopy.deepcopyof a strict-export-v2 graph module failed (see the test change below).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.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 usesnot torch._C._has_storage_data(self)in place ofself.data_ptr() == 0, and_reduce_ex_internalusestorch._C._has_storage(self) and not torch._C._has_storage_data(self). Nothing changes for plain tensors, meta tensors orFunctionalTensor, which the conditions around these checks handle, nor for fake tensors in_reduce_ex_internal. Behaviour changes:_rebuild_wrapper_subclassin pickling) instead of failing, and empty views of real storage keep their storage.__deepcopy__, a fake tensor view at a nonzero storage offset now takes theclone()path, like fake tensors at offset 0 and meta tensors. Before, itsdata_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.__deepcopy__, tensors for whichdata_ptr()used to raise (fake tensors when unsafe data pointer access is disabled, subclasses of tensors with no storage such as MKLDNN) now take theclone()path._reduce_ex_internalalso requirestorch._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 withNotImplementedError: Cannot access storage of OpaqueTensorImplfrom the storage path.Note [Invalid Python Storages] now points to the new binding.
Config snapshots no longer deep-copy custom passes:
get_serializable_config_copy()instead ofget_config_copy(). These copies are only serialized to JSON, and the serializable copy skips the_save_config_ignoreentries before deep-copying: the custom pass hooks for inductor, andjoint_custom_passfor functorch.get_patched_config_dict()deep-copies only the serializable entries and holds the_save_config_ignoreentries by reference. It backsget_compiler_config(), whose snapshottorch.compile()takes when it wraps a function, and Inductor's fbcode-onlypt2_configslog, 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:test/distributed/tensor/test_compile_on_one_rank.py,test_iota_device_fix_rank_agnostic_under_cooruses a pass that keeps FX nodes, and through them the fake tensors in their graph's metadata.data_ptr()raises for fake tensors created under Dynamo. The logging code swallows the error, andtorch.compile()raises it when the pass already holds nodes from an earlier compile._has_storage_data, the fake tensor's deepcopy succeeds and continues into itsFakeTensorMode, whose converter keys a dict byStorageWeakRef. Copying aStorageWeakRefduplicates 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:
trace.upload_tar,aot_inductor.repro_level,aot_inductor.dump_aoti_minifier,_fuse_ddp_communication_passesandcudagraph_policy, and the logged functorch config no longer includesactivation_memory_budget_runtime_estimatorandactivation_memory_budget_solver._post_fusion_custom_passandcustom_partitioner_fnare not in_save_config_ignore, so these copies still deep-copy them. Adding them would also changesave_config()and the config sent to subprocess compiles, so that is left out of this change.Alternatives considered
StorageImpl::data():_has_storage_datawould then raise for storages whose access is forbidden and for CUDA COW storages inside a foreign capture, instead of answering.StorageImpl::_data_ptr_no_checks() const: morec10API for no extra safety.DataPtr::get()isvoid* get() const, so it would still hand out a writable pointer.bool StorageImpl::has_data() const: const-correct and exposes no pointer, but adds ac10method. 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.storage_offset() == 0as well: still wrong for empty views of real storage, and does not express what callers want.UntypedStorageinstead 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) andtorch.utils._cuda_debugare fixed in follow-up commits.Test Plan:
New tests:
test_torch.pyTestTorchDeviceType.test_has_storage_data: True for dense tensors, views, an empty view of a non-empty storage (whosedata_ptr()is 0) andnn.Parameter; False forTwoTensorat offsets 0 and 4, fake, meta,torch.empty(0), sparse and vmap-batched tensors. Runs on CPU and CUDA (onlyNativeDeviceTypes, as istest_has_storage_data_ignores_data_access_checks).test_torch.pyTestTorchDeviceType.test_has_storage_data_does_not_materialize_cow: a lazy clone stays COW after the call.test_torch.pyTestTorchDeviceType.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_datareturns True and False. It also covers a fake tensor made underFakeTensorModewith unsafe data pointer access disabled:data_ptr()raises and_has_storage_datareturns False.test_torch.pyTestTorchDeviceType.test_has_storage_data_ignores_cow_read_check_in_cuda_graph_capture(CUDA only, skipped without CUDA graph support): inside atorch.cuda.graphcapture,const_data_ptr()of a COW clone made before the capture raisesMaterialize COW graph inputs ...while_has_storage_datareturns True and the clone stays COW.test/export/test_export.py: removestesting.expectedFailureStrictV2fromtest_custom_tag_metadata_re_export.copy.deepcopy(ep.graph_module)reaches a FakeTensor that strict export v2 leaves in the graph module, andTensor.__deepcopy__raises atself.data_ptr() == 0withCannot access data pointer of Tensor (e.g. FakeTensor, FunctionalTensor).test_serialization.pyTestSubclassSerialization.test_wrapper_subclass_with_storage_offset_roundtrip:deepcopy,torch.save/torch.load,pickleandForkingPicklerround trips of aTwoTensorat storage offset 4. The result is rebuilt as a wrapper (_has_storage_datais False) and, except afterdeepcopy, keeps the storage offset.test_serialization.pyTestSubclassSerialization.test_storageless_subclass_is_not_saved_as_wrapper:torch.saveof a_make_subclasssubclass with__torch_dispatch__around an MKLDNN tensor (no storage) raisesNotImplementedError. Without thetorch._C._has_storage(self)guard in_reduce_ex_internal,torch.savesucceeds and the data is lost (the test fails withNotImplementedError not raised).test_serialization.pyTestSubclassSerialization.test_empty_view_of_real_storage_subclass_keeps_storage: a_make_subclasstensor with__torch_dispatch__viewingbase[2:2]keeps its storage and offset throughtorch.save.test/distributed/tensor/test_dtensor.pyDTensorStorageOffsetTest: the same four round trips forDTensor.from_local(base[2:6], ...)on a world-size-1 fake process group, with the same checks, and_has_storage_dataon it.test/dynamo/test_utils.pyTestInductorConfigParsingForLogging.test_inductor_config_logging_does_not_copy_custom_passes: with a custom pass set aspost_grad_custom_pre_pass,_scrubbed_inductor_config_for_logging()does not deep-copy it, and the logged JSON has nopost_grad_custom_pre_passkey. It fails withget_config_copy().test_inductor_config_parsing_non_conforming_itemsnow mocksget_serializable_config_copy.test/dynamo/test_utils.pyTestFunctorchConfigParsingForLogging.test_functorch_config_logging_does_not_copy_joint_custom_pass: with ajoint_custom_passset,_functorch_config_for_logging()does not deep-copy it, and the logged JSON has nojoint_custom_passkey. It fails withget_config_copy().test_functorch_config_noneandtest_functorch_config_runtime_errornow mockget_serializable_config_copy.test/inductor/test_custom_post_grad_passes.pytest_custom_pass_is_not_deep_copied:torch.compilewith a custom pass set aspost_grad_custom_pre_passruns the pass but never deep-copies it, andget_compiler_config()returns that same pass object. In an fbcode build it fails with the oldget_patched_config_dict(): the pass is deep-copied twice, once for thetorch.compile()snapshot and once for thept2_configslog.get_compiler_config()tests (test/inductor/test_config.pytest_get_compiler_config,test/inductor/test_compile_options.pytest_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'storch/_tensor.pyandtorch/_dynamo/utils.pyedits applied (_has_storage_dataemulated in Python):torch/_dynamo/utils.pyedit, every test passes and the process then aborts at exit (exit 134 or 139, 3 of 3 runs;malloc(): unsorted double linked list corruptedwith CI's disabled tests excluded, as in CI).pt2_configsblock forced on, and Dynamo's logging already changed: with the oldget_patched_config_dict(),test_iota_device_fix_rank_agnostic_under_coor_index_device_cpuaborts 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).torch.compile()wraps another function, on the same nightly: on main, the secondtorch.compile()raisesRuntimeError: Cannot access data pointer of Tensor(2 of 2 runs). With_has_storage_dataand the logging changes but the oldget_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