python-decorators - 为什么我不能使用类来对 `torch.jit.script` 装饰器下的函数的参数进行类型注释?
问题描述
这段代码编译得很好:
import torch
import torch.nn as nn
class Foo(nn.Module):
def __init__(self):
super(Foo, self).__init__()
self.x = 0
def forward(self, X):
X *= self.x
self.x += 1
return X
# @torch.jit.script
def bar(f: Foo):
return f.x
但是,如果我取消注释该# @torch.jit.script
行,我会收到此错误:
Traceback (most recent call last):
File "test1.py", line 18, in <module>
def bar(f: Foo):
File "/anaconda3/envs/pytorch/lib/python3.7/site-packages/torch/jit/__init__.py", line 1103, in script
fn = torch._C._jit_script_compile(qualified_name, ast, _rcb, get_default_args(obj))
RuntimeError:
Unknown type name 'Foo':
at test1.py:18:12
@torch.jit.script
def bar(f: Foo):
~~~ <--- HERE
return f.x
如果我将类型注释更改为int
:
@torch.jit.script
# def bar(f: Foo):
# return f.x
def bar(f: int):
return f
然后编译再次工作。
有谁知道我需要做什么,以允许我的自定义类定义在类型注释中用于位于torch.jit.script
装饰器下的函数的参数?
解决方案
只有此处文档中的类型列表可以用作函数的参数:
https://pytorch.org/docs/stable/jit_language_reference.html#supported-type
nn.Module
s 在 TorchScript 中进行了一些特殊处理以使其工作,但目前不支持将它们作为参数。
推荐阅读
- javascript - 一次显示一个下拉菜单并关闭其他下拉菜单
- c# - 将数字拆分为列表/数组(例如 1998 到 1,9,9,8)
- javascript - 如何处理“阅读更多或更少”使用危险的SetInnerHTML加载内容
- android - CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera) 已过时
- python - 不确定 asyncio 的工作原理以及我如何从持续运行的异步文件夹看门狗函数返回信息
- azure-devops - Azure Devops:chromedriver 不是有效的 Win32 应用程序
- firebase - 使用带有 Flutter Web App 的 http 包发布到 Cloud Firestore 及其 REST API
- c++ - 无法执行它给出错误的 else 语句
- javascript - nuxtjs Fontawesome 一些图标无法显示
- css - 使用 :is() 的 CSS 选择器有什么无效的