apple / coremltools

Core ML tools contain supporting tools for Core ML model conversion, editing, and validation.
https://coremltools.readme.io
BSD 3-Clause "New" or "Revised" License
4.25k stars 614 forks source link

How to support Python build-in functions like len()? #1340

Open karpov3 opened 2 years ago

karpov3 commented 2 years ago

❓How to support Python build-in functions like len()?

System Information

I am trying to convert my model in Core ML with Coremltools. I had some issue that I replicated in this simple example.


import torch
import torch.nn as nn
import coremltools

class SimpleTest(nn.Module):
    def forward(self, x):
        value = len(x)
        return torch.tensor(value)

simple_model = SimpleTest()

scripted_model = torch.jit.script(simple_model)
mlmodel = coremltools.converters.convert(scripted_model, inputs=[coremltools.TensorType(shape=(400,))], debug=True)

I have this error.

Screenshot 2021-11-13 at 08 06 00

debug=True info

the following model ops are IMPLEMENTED:
  constant
  tensor
the following model ops are MISSING:
  len

How can I use Python len() funcion inside the model?

TobyRoseman commented 2 years ago

coremltools.converters.mil.mil.ops.defs.control_flow.list_length is probably the right mil op to use here.

JRGit4UE commented 2 years ago

<newbie> .. how would I add the mil op to the TorchScript side ??

#  coremltools 5.1.0
from coremltools.converters.mil.mil.ops.defs.control_flow import list_length
list_length([ ]) #TypeError: __init__() takes 1 positional argument but 2 were given

</newbie>

karpov3 commented 2 years ago

@TobyRoseman thank you for your suggestion. I'm wondering if there is some example how to use it? In my case i have this error that i don't know how to manage.

Screenshot 2021-12-01 at 10 47 58 Screenshot 2021-12-01 at 10 48 13