coremltools icon indicating copy to clipboard operation
coremltools copied to clipboard

PyTorch convert function for op 'len' not implemented.

Open yuxiaohui78 opened this issue 1 year ago • 2 comments

🐞Describing the bug

I just used torch.jit.script to script model and convert it. It had a 'not implemented' error for 'len' function.

Stack Trace

File "/Users/xxx/lib/python3.7/site-packages/coremltools/converters/mil/frontend/torch/load.py", line 99, in _perform_torch_convert prog = converter.convert() File "/Users/xxx/lib/python3.7/site-packages/coremltools/converters/mil/frontend/torch/converter.py", line 519, in convert convert_nodes(self.context, self.graph) File "/Users/xxx/lib/python3.7/site-packages/coremltools/converters/mil/frontend/torch/ops.py", line 80, in convert_nodes f"PyTorch convert function for op '{op_lookup}' not implemented." RuntimeError: PyTorch convert function for op 'len' not implemented.

To Reproduce

import torch 
import torch.nn as nn
import numpy as np
import coremltools as ct  

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

    def forward(self, x):

        b = len (x)

        r = x *b
        return r
               
def main():
	
    input_tensor = torch.randn(2,4,2)

    model = Net().to(torch.device("cpu"))
    model.eval()
    
    output = model(input_tensor)
    print (input_tensor)
    print (output)
    
    print ("========script model=======")
    trace = torch.jit.script(model, input_tensor)
    
    input_image = ct.TensorType(
           name='input_image',
           shape=input_tensor.shape
       )
       
    print ("========convert to coreml model=======")
    mlmodel = ct.convert(
           trace,
           inputs=[input_image],
       )

    mlmodel.save("test.mlpackage")
    
        
if __name__ == '__main__':
    main()


System environment (please complete the following information):

  • coremltools version: 7.1
  • OS: Ubuntu 20.04 (Both Linux and MacOS have the same issue. )
  • Pytorch 2.1.0

yuxiaohui78 avatar Dec 29 '23 20:12 yuxiaohui78

Thanks for the self contained example code. I can reproduce your issue.

Our support for untraced PyTorch models is only "experimental". You should have received an error message saying that.

If you trace your model prior to conversion, everything works fine (i.e. use torch.jit.trace rather than torch.jit.script).

TobyRoseman avatar Jan 02 '24 17:01 TobyRoseman

RuntimeError: PyTorch convert function for op 'all' not implemented.

Yaodada12 avatar Jan 03 '24 06:01 Yaodada12