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
34 changes: 25 additions & 9 deletions mlx/io/safetensors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::pair<const std::string*, const array*>> 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<size_t>{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<size_t>{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<char*>(&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<char>(), arr.nbytes());
if (arr->nbytes() > 0) {
out_stream->write(arr->data<char>(), arr->nbytes());
}
}
}
Expand Down
51 changes: 51 additions & 0 deletions tests/load_tests.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright © 2023 Apple Inc.

#include <algorithm>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <limits>
Expand Down Expand Up @@ -46,6 +48,55 @@ TEST_CASE("test save_safetensors") {
CHECK(array_equal(test2, ones({2, 2})).item<bool>());
}

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<std::string, array> 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<char*>(&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<std::pair<size_t, size_t>> 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,
Expand Down