Repository navigation
Allow saving empty arrays to npy and safetensors - #4080
Conversation
|
Pushed a fix for the CI failure.
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 |
Proposed changes
mlx can read empty arrays but cannot write them:
The readers already handle them at every shape. numpy writes the same files, and
mx.loadreads them back correctly today: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() == 0early throws that date to the initial commit with no comment. Removed them. The writers needed nothing else:For safetensors the header comes out well formed, with a zero length span, and the reference
safetensorspackage reads the file mlx produced:Reading in the other direction works too: mlx loads an empty tensor written by
safetensors.numpy.save_file.save_ggufis untouched. It already writes empty weights and reads them back, and its separate guard on empty metadata arrays still throws, which is whattests/load_tests.cpp:237checks.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_ggufis what made me think it was an oversight.Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesCPU only build (
MLX_BUILD_METAL=OFF) at 8d66629.test_load.py,test_ops.pyandtest_array.pypass; the new test raisesValueErroron 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.