PyTorch转ScriptModule的问题记录

本文详细记录了在将PyTorch模型转换为ScriptModule过程中遇到的各种错误及解决办法,包括类型错误、索引错误、Attribute错误、不支持的操作等。提供了解决这些问题的具体方法和代码示例。
摘要由CSDN通过智能技术生成

本文记录了转ScriptModule时遇到的一系列问题

如何转ScriptModule?

这里有提到背景

https://blog.csdn.net/ReadyShowShow/article/details/137275857

遇到的坑

Expected a value of type ‘Tensor’ for argument ‘self’ but instead found type ‘Optional[Tensor]’.

数据类型为可None类型,但算子不接受None,需要去掉类型的可None。

xs:Optional[torch.Tensor] = None
assert xs is not None
x = xs / 10

Expected integer literal for index but got a variable or non-integer. ModuleList/Sequential indexing is only supported with integer literals. For example, ‘i = 4; self.layersi’ will fail because i is not a literal. Enumeration is supported, e.g. ‘for index, v in enumerate(self): out = v(inp)’:

Attribute 1 is not of annotated type

通常是由 ModuleList 或者 ModuleDict 的遍历或取元素引起的。

3 种解法:
第一种是推荐做法: 直接使用遍历

m = nn.ModuleList()
m.append()
for index, v in enumerate(m):
  out = v(inp)

第二种是无法直接遍历,必须用下标取值。但是自定义的module,可以把继承torch.nn.Module改为继承torch.jit.ScriptModule,下标取值后的类型明确需要,且显示调用forward

class  MultiHeadAttention(torch.jit.ScriptModule):
	def __init__(self):
	  ...
	@torch.jit.script_method
    def forward(self, ):
      ...

m = nn.ModuleList()
m.append(MultiHeadAttention())

for i in range(m):
  l:MultiHeadAttention = m[i] # 明确类型
  r = l.forward(xxx)

第三种也是无法直接遍历,必须用下标

  • 25
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值