torch.utils 的源代码
import os.path as _osp
import torch
from .throughput_benchmark import ThroughputBenchmark
from .cpp_backtrace import get_cpp_backtrace
from .backend_registration import rename_privateuse1_backend, generate_methods_for_privateuse1_backend
from . import deterministic
from . import collect_env
import weakref
import copyreg
[docs]def set_module(obj, mod):
"""
为给定的对象设置模块属性,以便更好地打印
"""
if not isinstance(mod, str):
raise TypeError("The mod argument should be a string")
obj.__module__ = mod
if torch._running_with_deploy():
# 在torch_deploy解释器中无效,冻结模块不存在路径
cmake_prefix_path = None
else:
cmake_prefix_path = _osp.join(_osp.dirname(_osp.dirname(__file__)), 'share', 'cmake')
[docs]def swap_tensors(t1, t2):
"""
此函数交换两个Tensor对象的内容。
从高层次来看,这将使t1拥有t2的内容,同时保留其身份。
如果t1和t2具有不同的插槽,这将不起作用。
"""
# 确保没有弱引用
if weakref.getweakrefs(t1):
raise RuntimeError("Cannot swap t1 because it has weakref associated with it")
if weakref.getweakrefs(t2):
raise RuntimeError("Cannot swap t2 because it has weakref associated with it")
t1_slots = set(copyreg._slotnames(t1.__class__)) # type: ignore[attr-defined]
t2_slots = set(copyreg._slotnames(t2.__class__)) # type: ignore[attr-defined]
if t1_slots != t2_slots:
raise RuntimeError("Cannot swap t1 and t2 if they have different slots")
def swap_attr(name):
tmp = getattr(t1, name)
setattr(t1, name, (getattr(t2, name)))
setattr(t2, name, tmp)
# 交换类型
# 请注意,如果插槽不匹配,这将失败
swap_attr("__class__")
# 交换动态属性
swap_attr("__dict__")
# 交换插槽
for slot in t1_slots:
if hasattr(t1, slot) and hasattr(t2, slot):
swap_attr(slot)
elif hasattr(t1, slot):
setattr(t2, slot, (getattr(t1, slot)))
delattr(t1, slot)
elif hasattr(t2, slot):
setattr(t1, slot, (getattr(t2, slot)))
delattr(t2, slot)
# 交换它们指向的at::Tensor
torch._C._swap_tensor_impl(t1, t2)