Skip to content

Fix asMTLBuffer crash on zero-size arrays - #522

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
sandeepvijayarao09:fix-asmtlbuffer-empty
Nov 17, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
sandeepvijayarao09:fix-asmtlbuffer-empty

Conversation

@sandeepvijayarao09

Copy link
Copy Markdown
Contributor

Proposed changes

Fixes #520.

An array with a logical size of 0 has no backing data pointer, so asMTLBuffer(device:noCopy:) crashed by force-unwrapping nil on the noCopy path (MLXArray+Metal.swift:27). The copy path force-unwrapped the buffer's base address the same way. Metal cannot create a zero-length buffer in any case.

asMTLBuffer now returns nil for zero-size arrays, which its optional return type already allows, and the copy path skips a nil base address. The doc comment says so. This follows the asArray / asData fix in #486.

The new test asMTLBufferEmpty() covers an empty-constructed array, an empty slice (ones([1, 200])[128...]) and a zero-length dimension, on both the copy and noCopy paths.

Tested on macOS arm64 (Xcode 27.2, Swift 6.4.2):

  • Without the fix: the new test traps with Fatal error: Unexpectedly found nil while unwrapping an Optional value at MLXArray+Metal.swift:27
  • With the fix: it passes, and the full MLXTests suite passes (311 tests in 28 suites)

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

An array with a logical size of 0 has no backing data pointer, so
asMTLBuffer(device:noCopy:) crashed by force-unwrapping nil on the
noCopy path. The copy path force-unwrapped the buffer base address
the same way. Metal cannot create a zero-length buffer in any case.

asMTLBuffer now returns nil for empty arrays, which its optional
return type already allows, and the copy path skips a nil base
address. This follows the asArray / asData fix in ml-explore#486.

Adds a test for the empty-constructed, empty-slice, and zero-dimension
cases on both the copy and noCopy paths.

Fixes ml-explore#520

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thank you! Justing waiting on CI.

@davidkoski
davidkoski merged commit 00afc1d into ml-explore:main Nov 17, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MLXArray.asMTLBuffer(noCopy: true) traps on an array with no elements (force-unwrapped null data pointer)

2 participants