Skip to content

Error Converting BiRefNet Model to Core ML: Handling DeformConv2d #3

@pierre1618

Description

@pierre1618

I'm trying to convert the BiRefNet (model) to Core ML but encountering some issues, particularly with the DeformConv2d layer. Here's the detailed setup and error I’m facing:

Setup

  1. Model Loading:
    I am using the following code to load and prepare the BiRefNet model:

    from models.birefnet import BiRefNet
    import torch
    import torchvision.transforms as transforms
    import coremltools as ct
    import DeformConv2dConvert
    
    # Load the model
    birefnet = BiRefNet.from_pretrained('zhengpeng7/BiRefNet')
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    birefnet.to(device)
    birefnet.eval()
    print('BiRefNet is ready to use.')
    
    # Define input transformation
    transform_image = transforms.Compose([
        transforms.Resize((1024, 1024)),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])
  2. Conversion Code:
    I am using the following code to convert the model to Core ML:

    import coremltools as ct
    from torchvision.ops.deform_conv import DeformConv2d
    import DeformConv2dConvert
    
    # Register DeformConv2dConvert
    DeformConv2dConvert.register_op()
    
    # Move model to CPU and trace
    birefnet.cpu()
    example_input = torch.randn(1, 3, 1024, 1024)
    traced_model = torch.jit.trace(birefnet, example_input)
    
    # Convert to Core ML
    coreml_model = ct.convert(
        traced_model,
        inputs=[ct.TensorType(name="input", shape=example_input.shape)],
        convert_to="neuralnetwork"
    )

Error Message

During the conversion process, I encounter the following error:

Saving value type of int64 into a builtin type of int32, might lose precision!
Saving value type of int64 into a builtin type of int32, might lose precision!

ERROR - converting 'torchvision::deform_conv2d' op (located at: 'squeeze_module/0/dec_att/aspp1/atrous_conv'):

Converting PyTorch Frontend ==> MIL Ops:  76%|█████████████████▍     | 6929/9165 [00:01<00:00, 3651.18 ops/s]

AssertionError: the `offset` param should be stored in the weights

Additional Details

  • Environment: Python 3.12, CoreMLTools v6.x, PyTorch v2.x.
  • DeformConv2dConvert: I have installed and registered the DeformConv2dConvert library, which handles the conversion of DeformConv2d layers.

Questions

  1. AssertionError: The conversion fails with an AssertionError related to the offset parameter. What could be causing this issue, and how can I resolve it?

Any help or suggestions on how to resolve these issues would be greatly appreciated. Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions