Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions mlx/io/load.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,6 @@ void save(std::shared_ptr<io::Writer> out_stream, array a) {
a = contiguous(a, true);
a.eval();

if (a.nbytes() == 0) {
throw std::invalid_argument("[save] cannot serialize an empty array");
}

////////////////////////////////////////////////////////
// Check file
if (!out_stream->good() || !out_stream->is_open()) {
Expand Down Expand Up @@ -212,7 +208,11 @@ void save(std::shared_ptr<io::Writer> out_stream, array a) {

out_stream->write(magic_ver_len.str().c_str(), magic_ver_len.str().length());
out_stream->write(header.str().c_str(), header.str().length());
out_stream->write(a.data<char>(), a.nbytes());
// An empty array has no data to write, and asking for its pointer is not
// meaningful, so stop after the header.
if (a.nbytes() > 0) {
out_stream->write(a.data<char>(), a.nbytes());
}
}

/** Save array to file in .npy format */
Expand Down
13 changes: 5 additions & 8 deletions mlx/io/safetensors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -250,13 +250,6 @@ void save_safetensors(

size_t offset = 0;
for (auto& [key, arr] : a) {
if (arr.nbytes() == 0) {
std::ostringstream msg;
msg << "[save_safetensors] Cannot serialize an empty array ('" << key
<< "')";
throw std::invalid_argument(msg.str());
}

json child;
child["dtype"] = dtype_to_safetensor_str(arr.dtype());
child["shape"] = arr.shape();
Expand All @@ -270,7 +263,11 @@ void save_safetensors(
out_stream->write(reinterpret_cast<char*>(&header_len), 8);
out_stream->write(header.c_str(), header_len);
for (auto& [key, arr] : a) {
out_stream->write(arr.data<char>(), arr.nbytes());
// An empty tensor contributes a zero length span and has no data pointer
// worth asking for.
if (arr.nbytes() > 0) {
out_stream->write(arr.data<char>(), arr.nbytes());
}
}
}

Expand Down
28 changes: 28 additions & 0 deletions python/tests/test_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,34 @@ def test_load_donation(self):

self.assertEqual(load_only, load_with_binary)

def test_save_and_load_empty(self):
for i, shape in enumerate([(0,), (0, 3), (3, 0), (2, 0, 4)]):
with self.subTest(shape=shape):
save_arr = mx.zeros(shape)

npy_file = os.path.join(self.test_dir, f"empty_{i}.npy")
mx.save(npy_file, save_arr)
self.assertEqual(mx.load(npy_file).shape, shape)
# numpy can read what we wrote
self.assertEqual(np.load(npy_file).shape, shape)

st_file = os.path.join(self.test_dir, f"empty_{i}.safetensors")
mx.save_safetensors(st_file, {"x": save_arr})
self.assertEqual(mx.load(st_file)["x"].shape, shape)

# An empty array alongside a normal one round trips both
npz_file = os.path.join(self.test_dir, "empty.npz")
mx.savez(npz_file, x=mx.zeros((0, 3)), y=mx.ones((2, 2)))
loaded = mx.load(npz_file)
self.assertEqual(loaded["x"].shape, (0, 3))
self.assertTrue(mx.array_equal(loaded["y"], mx.ones((2, 2))))

st_file = os.path.join(self.test_dir, "empty_mixed.safetensors")
mx.save_safetensors(st_file, {"x": mx.zeros((0, 3)), "y": mx.ones((2, 2))})
loaded = mx.load(st_file)
self.assertEqual(loaded["x"].shape, (0, 3))
self.assertTrue(mx.array_equal(loaded["y"], mx.ones((2, 2))))


if __name__ == "__main__":
mlx_tests.MLXTestRunner()
Loading