From c3b922bb40e456c45e6a775514e5454cafa452f6 Mon Sep 17 00:00:00 2001 From: rcfa <1831995+rcfa@users.noreply.github.com> Date: Mon, 31 Aug 2026 16:10:17 +0200 Subject: [PATCH] save_safetensors: write files the mmap loader can actually map `tensor_from_mmap` shares the mapping only when a tensor's absolute byte offset is a multiple of its dtype width, and copies into a freshly allocated aligned buffer otherwise. `save_safetensors` did nothing to avoid the copy: it wrote the header unpadded, so the data section began at 8 + strlen(json), and then packed the tensors back to back in the order of the map. On macOS, eight small tensors written that way started their data section at byte 508, and loading the file with MLX_SAFETENSORS_MMAP=1 copied four of them ("realigned 4 unaligned tensor(s) (38 bytes)"). An earlier measurement on a 95 GB bundle found 1,775 of 2,999 tensors on the copy path: 59.3 GB of extra anonymous memory on top of the mapping. Pad the header with spaces to a multiple of 8, and write the tensors widest dtype first, ties by name; the reference safetensors writer also writes the widest dtypes first. A tensor's size is a multiple of its dtype width, and the widths are powers of two up to 8, so each tensor then starts at a multiple of its own width: the order aligns every tensor without padding between them. Padding between tensors would not do: the format forbids holes ("The byte buffer needs to be entirely indexed, and cannot contain holes"), and the reference reader rejects a file with a gap ("invalid offset for tensor"). The header may be padded with spaces; that costs at most 7 bytes a file. The tensors' order in the data section changes. The header still maps each name to its offsets; MLX's readers and the reference reader find tensors by name. The old order was the hash map's, which differed between macOS and Linux. tests/load_tests.cpp gains a case that saves odd-sized tensors of every width, an empty one among them, and checks from the file's header that the data section starts at a multiple of 8, that every tensor's offset is a multiple of its width, and that the spans tile the data with no hole up to the end of the file. On main it fails the first two checks. With this change, files with every dtype save_safetensors writes start their data section at a multiple of 8, with no tensor misaligned and no gap. MLX reads every tensor back unchanged on macOS, with the mmap loader (which copies nothing) and without it, and on Linux; the reference reader, Hugging Face's safetensors 0.8.0, reads every file with the same values. The layout no longer depends on the map's iteration order: macOS and Linux write the same bytes. --- mlx/io/safetensors.cpp | 34 ++++++++++++++++++++-------- tests/load_tests.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 9 deletions(-) diff --git a/mlx/io/safetensors.cpp b/mlx/io/safetensors.cpp index f5342cf682..c218c4904d 100644 --- a/mlx/io/safetensors.cpp +++ b/mlx/io/safetensors.cpp @@ -1397,25 +1397,41 @@ void save_safetensors( } parent["__metadata__"] = _metadata; - size_t offset = 0; + // Widest element first, as the reference writer does: each size is a multiple + // of a power-of-two width, so every tensor lands aligned and without a hole. + std::vector> order; + order.reserve(a.size()); for (auto& [key, arr] : a) { + order.emplace_back(&key, &arr); + } + std::sort(order.begin(), order.end(), [](const auto& l, const auto& r) { + auto lw = size_of(l.second->dtype()); + auto rw = size_of(r.second->dtype()); + return lw != rw ? lw > rw : *l.first < *r.first; + }); + + size_t offset = 0; + for (auto& [key, arr] : order) { json child; - child["dtype"] = dtype_to_safetensor_str(arr.dtype()); - child["shape"] = arr.shape(); - child["data_offsets"] = std::vector{offset, offset + arr.nbytes()}; - parent[key] = child; - offset += arr.nbytes(); + child["dtype"] = dtype_to_safetensor_str(arr->dtype()); + child["shape"] = arr->shape(); + child["data_offsets"] = std::vector{offset, offset + arr->nbytes()}; + parent[*key] = child; + offset += arr->nbytes(); } + // Pad the header with spaces, which the format allows, so that the data + // section starts at a multiple of 8, the widest element size. auto header = parent.dump(); + header.append((8 - (8 + header.length()) % 8) % 8, ' '); uint64_t header_len = header.length(); out_stream->write(reinterpret_cast(&header_len), 8); out_stream->write(header.c_str(), header_len); - for (auto& [key, arr] : a) { + for (auto& [key, arr] : order) { // 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(), arr.nbytes()); + if (arr->nbytes() > 0) { + out_stream->write(arr->data(), arr->nbytes()); } } } diff --git a/tests/load_tests.cpp b/tests/load_tests.cpp index aa37a375a8..0aa930ecf5 100644 --- a/tests/load_tests.cpp +++ b/tests/load_tests.cpp @@ -1,5 +1,7 @@ // Copyright © 2023 Apple Inc. +#include +#include #include #include #include @@ -46,6 +48,55 @@ TEST_CASE("test save_safetensors") { CHECK(array_equal(test2, ones({2, 2})).item()); } +TEST_CASE("test save_safetensors aligns tensors without holes") { + // Odd sizes of every width: packed in the map's order, each tensor would + // shift the ones after it off their alignment. + std::unordered_map map = { + {"bool", astype(array({1, 0, 1}), bool_)}, + {"int8", astype(arange(5), int8)}, + {"float16", astype(arange(3), float16)}, + {"bfloat16", astype(arange(5), bfloat16)}, + {"float32", astype(arange(3), float32)}, + {"int64", astype(arange(3), int64)}, + {"complex64", astype(arange(3), complex64)}, + {"empty", zeros({0}, float32)}, + }; + std::string file_path = get_temp_file("test_aligned.safetensors"); + save_safetensors(file_path, map); + + std::ifstream in(file_path, std::ios::binary | std::ios::ate); + const size_t file_size = in.tellg(); + in.seekg(0); + uint64_t header_len = 0; + in.read(reinterpret_cast(&header_len), 8); + std::string header(header_len, ' '); + in.read(header.data(), header_len); + const size_t data_start = 8 + header_len; + CHECK_EQ(data_start % 8, 0); + + std::vector> spans; + for (auto& [key, arr] : map) { + CAPTURE(key); + std::string field = "\"" + key + "\":{\"data_offsets\":["; + auto at = header.find(field); + REQUIRE(at != std::string::npos); + char* end = nullptr; + size_t begin = std::strtoull(header.c_str() + at + field.size(), &end, 10); + size_t stop = std::strtoull(end + 1, nullptr, 10); + CHECK_EQ(stop - begin, arr.nbytes()); + CHECK_EQ((data_start + begin) % arr.itemsize(), 0); + spans.emplace_back(begin, stop); + } + // The format allows no holes: the spans tile the data up to the file's end. + std::sort(spans.begin(), spans.end()); + size_t offset = 0; + for (auto& [begin, stop] : spans) { + CHECK_EQ(begin, offset); + offset = stop; + } + CHECK_EQ(data_start + offset, file_size); +} + // Helper to write a raw safetensors file from a JSON header and data buffer void write_raw_safetensors( const std::string& path,