- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的目标是序列化经过 pytorch 训练的模型,并将其加载到定义神经网络的原始类不可用的环境中。为实现这一目标,我决定使用 TorchScript,因为它似乎是唯一可行的方法。
我有一个多任务模型(类型 nn.Module),使用每个任务通用的主体(也是 nn.Module,只是几个线性层)和一组线性头部模型,每个任务一个。我将头部模型存储在名为 _task_head_models
的字典 Dict[int, nn.Module]
中,并在我的模块类中创建了一个临时转发方法来选择正确的头部在预测时间:
def forward(self, x: torch.Tensor, task_id: int = 0) -> torch.Tensor:
if task_id not in self._task_head_models.keys():
raise ValueError(
f"The task id {task_id} is not valid. Valid task ids are {self._task_head_models.keys()}."
)
return self._task_head_models[task_id](self._model(x))
在我不尝试使用 torchscript 序列化它之前,它工作正常。当我尝试 torch.jit.script(mymodule)
时,我得到:
Module 'MyModule' has no attribute '_task_head_models' (This attribute exists on the Python module, but we failed to convert Python type: 'dict' to a TorchScript type. Cannot infer concrete type of torch.nn.Module. Its type was inferred; try adding a type annotation for the attribute.)
似乎不对劲的是,我的模块包含一个 Dict
,而不是错误消息中提到的 dict
。暂时忘记这一点,目前还不清楚为什么会这样。语言引用中似乎支持字典:https://docs.w3cub.com/pytorch/jit_language_reference.html
我还尝试使用 ModuleDict 而不是 Dict(将键类型更改为 str),但这似乎也不起作用:无法提取字符串文字索引。 ModuleDict 索引仅支持字符串文字。支持 ModuleDict 的枚举,例如'for k, v in self.items(): ...':
最佳答案
如果Dict
_task_head_models
中的项目不多,我想使用if-else
分支可以帮到你。示例代码如下:
import torch
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self._task_head0 = torch.nn.Linear(3, 24)
self._task_head1 = torch.nn.Linear(3, 24)
def forward(self, x: torch.Tensor, task_id: int = 0) -> torch.Tensor:
if task_id == 0:
return self._task_head0(x)
elif task_id == 1:
return self._task_head1(x)
else:
raise ValueError(
f"The task id {task_id} is not valid. Valid task ids are 0,1."
)
关于python - 模型包含多个头的 TorchScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73290107/
我的目标是序列化经过 pytorch 训练的模型,并将其加载到定义神经网络的原始类不可用的环境中。为实现这一目标,我决定使用 TorchScript,因为它似乎是唯一可行的方法。 我有一个多任务模型(
我正在使用 PyTorch 1.4,需要在 forward 中的循环内导出带有卷积的模型: class MyCell(torch.nn.Module): def __init__(self):
我试图让一些现有的 pytorch 模型支持 TorchScript jit 编译器,但我遇到了非原始类型成员的问题。 这个小例子说明了这个问题: import torch @torch.jit.sc
我正在尝试转换 PyTorch FOMM模型到 TorchScript。一旦我开始用 @torch.jit.script 注释一些类我有一个错误: OSError: Can't get source
我准备将pytorch模块转换为ScriptModule,然后在c++中加载它,但我被这个错误阻止了 This attribute exists on the Python module, but w
我正在按以下方式加载 torchscript 模型: model = torch.jit.load("model.pt").to(device) 此模型的子模块被标识为 RecursiveScript
我使用 colab 环境使用 PyTorch 训练了一个自定义模型。我成功地将训练好的模型保存到 Google Drive,名称为 model_final.pth .我要转换 model_final.
我将 pytorch 预训练模型 (.pt) 转换为 torchscript 模型 (.pt),以便在 Swift 5(ios-iphone6s、xcode 11)中使用它。在 Swift 中,模型的
我是一名优秀的程序员,十分优秀!