Приведенный ниже пример представляет собой абстрактную версию проблемы. Предположим, некоторая библиотека, которую я не могу изменить, определяет классы SomeClass и LibraryModule, где последний является модулем PyTorch.
Код: Выделить всё
LibraryModuleОсновной метод Код: Выделить всё
import torch
import torch.nn as nn
class SomeClass:
"""A utility class in a library I cannot modify"""
def __init__(self, x):
self.x = x
class LibraryModule(nn.Module):
"""A module provided in a library I cannot modify"""
def __init__(self, in_features, out_features):
super().__init__()
self.linear = nn.Linear(in_features, out_features)
def compute(self, x, some_class_object: SomeClass):
"""
Main function of my module; like forward, but takes a non-tensor argument
"""
return self.linear(x) * some_class_object.x
Код: Выделить всё
script = torch.jit.script(LibraryModule(3, 2))
print(script.compute(torch.tensor([10, 20, 30]), SomeClass(2)))
Код: Выделить всё
File "torchscript.py", line 25, in
print(script.compute(torch.tensor([10, 20, 30]), SomeClass(2)))
^^^^^^^^^^^^^^
File "\Lib\site-packages\torch\jit\_script.py", line 826, in __getattr__
return super().__getattr__(attr)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "Lib\site-packages\torch\jit\_script.py", line 533, in __getattr__
return super().__getattr__(attr)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "Lib\site-packages\torch\nn\modules\module.py", line 1931, in __getattr__
raise AttributeError(
AttributeError: 'RecursiveScriptModule' object has no attribute 'compute'. Did you mean: 'compile'?
Код: Выделить всё
compute_script = torch.jit.script(LibraryModule(3, 2).compute)
print(compute_script(torch.tensor([10, 20, 30]), SomeClass(2)))
Код: Выделить всё
RuntimeError:
'Tensor (inferred)' object has no attribute or method 'linear'.:
File "torchscript.py", line 21
Main function of my module; like forward, but takes a non-tensor argument
"""
return self.linear(x) * some_class_object.x
~~~~~~~~~~~
Подробнее здесь: [url]https://stackoverflow.com/questions/79280126/torchscript-failure-recursivescriptmodule-object-has-no-attribute[/url]
Мобильная версия