Skip to content

Allow saving empty arrays to npy and safetensors - #4080

Merged
zcbenz merged 2 commits into
ml-explore:mainfrom
ayaangazali:save-empty-arrays
Aug 9, 2026
Merged

zcbenz merged 2 commits into
ml-explore:mainfrom
ayaangazali:save-empty-arrays

Conversation

@ayaangazali

Copy link
Copy Markdown
Contributor

Proposed changes

mlx can read empty arrays but cannot write them:

>>> mx.save("a.npy", mx.zeros((0, 3)))
ValueError: [save] cannot serialize an empty array
>>> mx.save_safetensors("a.safetensors", {"x": mx.zeros((0, 3))})
ValueError: [save_safetensors] Cannot serialize an empty array ('x')

The readers already handle them at every shape. numpy writes the same files, and mx.load reads them back correctly today:

>>> np.save("a.npy", np.zeros((0, 3), dtype=np.float32))
>>> mx.load("a.npy").shape
(0, 3)

So an array that mlx is happy to load is one it refuses to have produced. That bites when a shape is data dependent, for example saving a batch of matched indices that happens to be empty for one input, since the whole checkpoint call fails rather than that one entry being empty.

Both guards are nbytes() == 0 early throws that date to the initial commit with no comment. Removed them. The writers needed nothing else:

>>> for s in [(0,), (0, 3), (3, 0), (2, 0, 4)]:
...     mx.save("a.npy", mx.zeros(s))
...     print(s, mx.load("a.npy").shape, np.load("a.npy").shape)
(0,) (0,) (0,)
(0, 3) (0, 3) (0, 3)
(3, 0) (3, 0) (3, 0)
(2, 0, 4) (2, 0, 4) (2, 0, 4)

For safetensors the header comes out well formed, with a zero length span, and the reference safetensors package reads the file mlx produced:

{'x': {'data_offsets': [16, 16], 'dtype': 'F32', 'shape': [0, 3]},
 'y': {'data_offsets': [0, 16],  'dtype': 'F32', 'shape': [2, 2]}}

Reading in the other direction works too: mlx loads an empty tensor written by safetensors.numpy.save_file.

save_gguf is untouched. It already writes empty weights and reads them back, and its separate guard on empty metadata arrays still throws, which is what tests/load_tests.cpp:237 checks.

If these guards were deliberate rather than leftover, say so and I will close this. I could not find a reason for them in the code or history, and the asymmetry with both the readers and save_gguf is what made me think it was an oversight.

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)

CPU only build (MLX_BUILD_METAL=OFF) at 8d66629. test_load.py, test_ops.py and test_array.py pass; the new test raises ValueError on main. No existing test asserted either removed message.


freshman contributor, i use Claude Code alongside my own poking. i went looking for places where mlx and numpy disagree on zero-size input and this one stood out because the read path was already complete, so it was only the writer holding it back. the safetensors cross-check against the reference package was the part i most wanted to be sure of before sending this.

@ayaangazali

Copy link
Copy Markdown
Contributor Author

Pushed a fix for the CI failure.

zipfile.BadZipFile: Bad CRC-32 for file 'x.npy'
  File "python/tests/test_load.py", line 545, in test_save_and_load_empty
    loaded = mx.load(npz_file)

save ended with out_stream->write(a.data<char>(), a.nbytes()) unconditionally. For an empty array that reaches PyFileWriter::write (load.cpp:378), which builds PyMemoryView_FromMemory(data, 0, PyBUF_READ) and hands it to the zipfile member handle. So the last thing written into the archive entry was a memoryview over a data pointer that an empty array has no reason to provide. Now the data span is skipped when there is nothing in it, and the same guard is applied in the safetensors writer, which had the identical unconditional write.

Being straight about the evidence: this reproduces only on the GPU builds. The three cuda x86_64 jobs and Test macOS failed, the cpu jobs passed, and I could not reproduce it on my CPU only box either before or after the change, so I could not watch this specific fix turn the failure green locally. What I could confirm locally is that the archive is still well formed and that the non-empty paths are unchanged, including saving through a Python file object, which is the same PyFileWriter route the npz members take. If it comes back red I will keep digging rather than guess again.

@zcbenz
zcbenz merged commit 1f9fed2 into ml-explore:main Aug 9, 2026
28 checks passed
@BrewTestBot BrewTestBot mentioned this pull request Aug 18, 2026
1 task done
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.

2 participants