MCPcopy Create free account
hub / github.com/pytorch/pytorch / __deepcopy__

Method __deepcopy__

torch/_tensor.py:82–210  ·  view source on GitHub ↗
(self, memo)

Source from the content-addressed store, hash-verified

80# otherwise, it will not show up in autocomplete.
81class Tensor(torch._C.TensorBase):
82 def __deepcopy__(self, memo):
83 if has_torch_function_unary(self):
84 return handle_torch_function(Tensor.__deepcopy__, (self,), self, memo)
85 if not self.is_leaf:
86 raise RuntimeError(
87 "Only Tensors created explicitly by the user "
88 "(graph leaves) support the deepcopy protocol at the moment. "
89 "If you were attempting to deepcopy a module, this may be because "
90 "of a torch.nn.utils.weight_norm usage, "
91 "see https://github.com/pytorch/pytorch/pull/103001"
92 )
93 if id(self) in memo:
94 return memo[id(self)]
95 with torch.no_grad():
96 # TODO: skipping storage copy is wrong for meta, as meta
97 # does accurate alias tracking; however, the code below
98 # doesn't work because of
99 # https://github.com/pytorch/pytorch/issues/47442
100 # Update the test in test_serialization if you remove 'meta' from here
101 if (
102 self.is_sparse
103 or self.device.type
104 in ["lazy", "xla", "mtia", "mps", "ort", "meta", "ipu"]
105 or (
106 not torch._C._has_storage(self)
107 and self.device.type == torch._C._get_privateuse1_backend_name()
108 )
109 or (type(self) is not Tensor and self.data_ptr() == 0)
110 ):
111 new_tensor = self.clone()
112 if type(new_tensor) is not type(self):
113 raise RuntimeError(
114 "The default implementation of __deepcopy__() for wrapper subclasses "
115 "only works for subclass types that implement clone() and for which "
116 "cloning returns another instance of the same subclass. You should either "
117 "properly implement clone() for your subclass or override __deepcopy__() "
118 "if it is intended behavior for clone() to return an instance of a "
119 "different type."
120 )
121 else:
122 new_storage = self._typed_storage()._deepcopy(memo)
123 if self.is_quantized:
124 # quantizer_params can be different type based on torch attribute
125 quantizer_params: Union[
126 Tuple[torch.qscheme, float, int],
127 Tuple[torch.qscheme, Tensor, Tensor, int],
128 ]
129 if self.qscheme() == torch.per_tensor_affine:
130 quantizer_params = (
131 self.qscheme(),
132 self.q_scale(),
133 self.q_zero_point(),
134 )
135 elif self.qscheme() in (
136 torch.per_channel_affine,
137 torch.per_channel_affine_float_qparams,
138 ):
139 quantizer_params = (

Callers

nothing calls this directly

Calls 11

_typed_storageMethod · 0.95
handle_torch_functionFunction · 0.90
_deepcopyMethod · 0.80
storage_offsetMethod · 0.80
data_ptrMethod · 0.45
cloneMethod · 0.45
sizeMethod · 0.45
strideMethod · 0.45
new_emptyMethod · 0.45
negMethod · 0.45
requires_grad_Method · 0.45

Tested by

no test coverage detected