How to perform a shallow copy of the torch module?

Hello,
I want to copy perform a “shallow” copy of the “torch” module .The reason for that is that I want to modify the torch.Tensor module, by adding to it some custom behavior, in specific context.

Here is the code that I tried so far (I works by replacing torch by the os library)


import sys
import importlib.util

SPEC_torch = importlib.util.find_spec('torch')
torch1 = importlib.util.module_from_spec(SPEC_torch)
SPEC_torch.loader.exec_module(torch1)
sys.modules['torch1'] = torch1

torch2 = importlib.util.module_from_spec(SPEC_torch)
SPEC_torch.loader.exec_module(torch2)
sys.modules['torch2'] = torch2
del SPEC_torch

assert torch1 is not torch2

Though, when executing the line torch1 = importlib.util.module_from_spec(SPEC_torch), pytorch fails
with the following output "NameError: name '_C' is not defined"

I found an issue that reference this problem, but with a different context “Error during import torch, NameError: name '_C' is not defined · Issue #1633 · pytorch/pytorch · GitHub”, and whose proposed solutions, does not resolve mine.

I also tried to modify , the attributes of torch.Tensor after applying a deepcopy on it, but it resulted on the modification of the original torch.Tensor class, which is not the targeted behavior … (maybe it is linked to the fact that torch.Tensor is a builtin class).

I am looking for a solution which is thread_safe ( the proposed method would be thread safe, because we have a duplicate class of torch.Tensor, which could be concurrentialy used with the original “torch.Tensor”'s class ), and which works with the routines of torch.nn.functionnal (defining a new class of torch.Tensor with the “type” method doesn’t enable this features,unfortunatly).

Thank you again for your time.

I don’t know how to solve your original error but:

sounds as if extending the tensor class might fit your use case.