coremltools icon indicating copy to clipboard operation
coremltools copied to clipboard

CoreML export fails with TypeError for models using int() on shape-derived tensors (numpy 2.x)

Open davidnichols-ops opened this issue 4 months ago • 4 comments

Bug

CoreML export fails with TypeError: only 0-dimensional arrays can be converted to Python scalars for models that use int() on shape-derived tensors during PyTorch tracing (e.g., YOLO11x, YOLO26x, and any model with attention layers that compute N = H * W and pass it through int()).

Reproduction

from ultralytics import YOLO
model = YOLO('yolo26x.pt')
model.export(format='mlpackage', nms=False)
# TypeError: only 0-dimensional arrays can be converted to Python scalars

Minimal repro:

import torch
import coremltools as ct

class Model(torch.nn.Module):
    def forward(self, x):
        h = x.shape[2]
        w = x.shape[3]
        n = int(h * w)  # triggers _int op on (1,)-shaped tensor
        return x.reshape(x.shape[0], x.shape[1], n)

model = Model()
traced = torch.jit.trace(model, torch.randn(1, 3, 20, 20))
ct.convert(traced)  # TypeError

Root cause

PR #2632 fixed _cast in coremltools/converters/mil/frontend/torch/ops.py to use .squeeze() for compile-time constant casting. However, the same numpy 2.x incompatibility exists in 8 other locations where int()/float()/bool() is called directly on .val attributes that may hold 1-D numpy arrays:

  • softplus: beta and threshold parameters
  • pad: constant fill value
  • upsample_linear1d / upsample_bilinear2d: align_corners parameter
  • getitem: list/tuple index
  • threshold: alpha computation (threshold_val.val - alpha.val)
  • resize_nearest_neighbor: target_size_width / target_size_height

Additionally, the .squeeze() fix from #2632 fails on Python scalars (e.g., True has no .squeeze() method), which causes a regression in upsample_linear1d where align_corners can be a Python bool.

Proposed fix

Use np.asarray(val).item() instead, which safely handles:

  • Python scalars (bool, int, float)
  • 0-d numpy arrays
  • 1-D numpy arrays with one element
  • Multi-dim numpy arrays with one element

Environment

  • coremltools 9.0
  • numpy 2.x
  • Python 3.13
  • PyTorch 2.7.0
  • macOS (Apple Silicon M4)

Related

  • Fix PR: #2754
  • Original partial fix: #2632

davidnichols-ops avatar Jul 08 '26 02:07 davidnichols-ops

You need to provide tensor input information in order to convert. Replace the last line with:

ct.convert(traced, inputs=[ct.TensorType(name="x", shape=(1, 3, 20, 20))])

TobyRoseman avatar Jul 08 '26 21:07 TobyRoseman

@TobyRoseman The suggested fix (inputs=[ct.TensorType(...)]) does not resolve this issue. I verified this in a completely fresh venv (uv venv --python 3.13, clean install of coremltools==9.0, torch==2.7.0, numpy==2.5.1 from PyPI).

Evidence

Minimal repro WITH the suggested inputs fix:

import torch
import coremltools as ct

class Model(torch.nn.Module):
    def forward(self, x):
        h = x.shape[2]
        w = x.shape[3]
        n = int(h * w)  # triggers _int op on (1,)-shaped tensor
        return x.reshape(x.shape[0], x.shape[1], n)

model = Model()
model.eval()
traced = torch.jit.trace(model, torch.randn(1, 3, 20, 20))
mlmodel = ct.convert(traced, inputs=[ct.TensorType(name="x", shape=(1, 3, 20, 20))])

Result — same TypeError:

ERROR - converting 'int' op (located at: '5'):
Converting PyTorch Frontend ==> MIL Ops:  27%|██▋       | 3/11 [00:00<00:00, 1446.98 ops/s]
Traceback (most recent call last):
  File ".../coremltools/converters/mil/frontend/torch/ops.py", line 3066, in _int
    _cast(context, node, int, "int32")
  File ".../coremltools/converters/mil/frontend/torch/ops.py", line 3048, in _cast
    res = mb.const(val=dtype(x.val), name=node.name)
                       ~~~~~^^^^^^
TypeError: only 0-dimensional arrays can be converted to Python scalars

The error is in _cast() at ops.py:3048 — dtype(x.val) where x.val is a 1-D numpy array (np.array([400])). This is a frontend op translation error, not an input validation error. Adding inputs=[] just gets you past input validation into the crash.

Full YOLO26x export (the real-world repro):

Ultralytics 8.4.90 Python-3.13.13 torch-2.7.0 CPU (Apple M4)
CoreML: starting export with coremltools 9.0...
ERROR - converting 'int' op (located at: '10/m/0/attn/951'):
Converting PyTorch Frontend ==> MIL Ops:  42%|████▏     | 576/1378 [00:00<00:00, 11121.22 ops/s]
CoreML: export failure 5.4s: only 0-dimensional arrays can be converted to Python scalars

This crashes at op 576/1378 — the attention module's int(H * W) call. Every YOLO model with attention (YOLO11x, YOLO26x, etc.) is affected.

Root cause

PR #2632 fixed _cast to use .squeeze() for this case, but that fix has not shipped to PyPI — coremltools==9.0 on PyPI still has dtype(x.val) without .squeeze(). Additionally, the same numpy 2.x incompatibility exists in 8 other locations across the torch frontend that #2632 did not address:

Function Field Code
softplus beta, threshold float(inputs[N].val)
pad value float(value.val)
upsample_linear1d align_corners bool(inputs[2].val)
upsample_bilinear2d align_corners bool(inputs[2].val)
getitem index int(inputs[1].val)
threshold alpha float(threshold_val.val - alpha.val)
resize_nearest_neighbor target_size_* int(self.target_size_*.val)

PR #2754 fixes all 9 sites using np.asarray(val).item(), which handles Python scalars, 0-d arrays, 1-d arrays, and multi-dim arrays uniformly.

Environment

coremltools==9.0 (PyPI, fresh install)
numpy==2.5.1
torch==2.7.0
Python 3.13.13
macOS 26 Tahoe (Apple Silicon M4)

This issue is not resolved. Please reopen.

davidnichols-ops avatar Jul 08 '26 22:07 davidnichols-ops

You need to use tip of main, not the 9.0 release.

TobyRoseman avatar Jul 08 '26 22:07 TobyRoseman

@TobyRoseman You're right — I verified on a fresh venv with tip of main that the bug is fixed by #2632's .squeeze() change. YOLO26x converts all 1378 ops without TypeError. The issue was filed against the 9.0 PyPI release, which predates the fix. Closing this as a duplicate of #2632.

Thanks for the quick response.

davidnichols-ops avatar Jul 08 '26 22:07 davidnichols-ops