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
1 change: 1 addition & 0 deletions mlx/export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,7 @@ FunctionExporter::FunctionExporter(
fun(std::move(fun)),
ftable(std::make_shared<FunctionTable>(shapeless)),
metadata_(std::move(metadata)) {
os.open();
if (!os.is_open()) {
throw std::runtime_error("[export_function] Failed to open " + file);
}
Expand Down
4 changes: 4 additions & 0 deletions mlx/io/load.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@ void save(std::shared_ptr<io::Writer> out_stream, array a) {
a = contiguous(a, true);
a.eval();

// Open only after the inputs are evaluated: opening a FileWriter
// truncates the file and lazy inputs may still read from it.
out_stream->open();

////////////////////////////////////////////////////////
// Check file
if (!out_stream->good() || !out_stream->is_open()) {
Expand Down
41 changes: 30 additions & 11 deletions mlx/io/load.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <memory>
#include <mutex>
#include <sstream>
#include <utility>

#include <fcntl.h>
#ifdef _MSC_VER
Expand Down Expand Up @@ -54,6 +55,8 @@ class Writer {
std::ios_base::seekdir way = std::ios_base::beg) = 0;
virtual void write(const char* data, size_t n) = 0;
virtual std::string label() const = 0;
virtual void open() {}

virtual ~Writer() = default;
};

Expand Down Expand Up @@ -121,24 +124,31 @@ class FileWriter : public Writer {
public:
explicit FileWriter() {}
explicit FileWriter(std::string file_path)
: fd_(open(
file_path.c_str(),
O_CREAT | O_WRONLY | O_TRUNC | O_BINARY,
0644)),
label_(std::move(file_path)) {}
: file_path_(std::move(file_path)) {}

FileWriter(const FileWriter&) = delete;
FileWriter& operator=(const FileWriter&) = delete;
FileWriter(FileWriter&& other) {
std::swap(fd_, other.fd_);
FileWriter(FileWriter&& other)
: fd_(std::exchange(other.fd_, -1)),
file_path_(std::move(other.file_path_)) {
other.file_path_.clear();
}

~FileWriter() override {
if (fd_ != 0) {
if (fd_ >= 0) {
close(fd_);
}
}

// Kept separate from construction so lazy inputs can be evaluated first,
// they may still read from the file.
void open() override {
if (fd_ < 0 && !file_path_.empty()) {
fd_ = ::open(
file_path_.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, 0644);
}
}

bool is_open() const override {
return fd_ >= 0;
}
Expand All @@ -148,11 +158,13 @@ class FileWriter : public Writer {
}

size_t tell() override {
check_open();
return lseek(fd_, 0, SEEK_CUR);
}

void seek(int64_t off, std::ios_base::seekdir way = std::ios_base::beg)
override {
check_open();
if (way == std::ios_base::beg) {
lseek(fd_, off, SEEK_SET);
} else if (way == std::ios_base::end) {
Expand All @@ -163,6 +175,7 @@ class FileWriter : public Writer {
}

void write(const char* data, size_t n) override {
check_open();
while (n != 0) {
auto m = ::write(fd_, data, std::min(n, static_cast<size_t>(INT32_MAX)));
if (m <= 0) {
Expand All @@ -176,12 +189,18 @@ class FileWriter : public Writer {
}

std::string label() const override {
return "file " + label_;
return "file " + file_path_;
}

private:
int fd_{0};
std::string label_;
void check_open() const {
if (!is_open()) {
throw std::runtime_error("[write] File " + file_path_ + " is not open.");
}
}

int fd_{-1};
std::string file_path_;
};

} // namespace io
Expand Down
24 changes: 14 additions & 10 deletions mlx/io/safetensors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,20 @@ void save_safetensors(
std::shared_ptr<io::Writer> out_stream,
std::unordered_map<std::string, array> a,
std::unordered_map<std::string, std::string> metadata /* = {} */) {
{
std::vector<array> to_eval;
to_eval.reserve(a.size());
for (auto& p : a) {
p.second = contiguous(p.second);
to_eval.push_back(p.second);
}
eval(std::move(to_eval));
}

// Open only after the inputs are evaluated: opening a FileWriter
// truncates the file and lazy inputs may still read from it.
out_stream->open();

////////////////////////////////////////////////////////
// Check file
if (!out_stream->good() || !out_stream->is_open()) {
Expand All @@ -238,16 +252,6 @@ void save_safetensors(
}
parent["__metadata__"] = _metadata;

{
std::vector<array> to_eval;
to_eval.reserve(a.size());
for (auto& p : a) {
p.second = contiguous(p.second);
to_eval.push_back(p.second);
}
eval(std::move(to_eval));
}

size_t offset = 0;
for (auto& [key, arr] : a) {
json child;
Expand Down
18 changes: 18 additions & 0 deletions python/tests/test_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,24 @@ def test_async_load_npy_read_error_across_streams(self):
except Exception:
pass

def test_save_over_lazily_loaded_safetensors(self):
# The save must eval the lazy input before truncating the file it was
# loaded from. Shift the data so stale content cannot pass.
save_file = os.path.join(self.test_dir, "resave.safetensors")
mx.save_safetensors(save_file, {"a": mx.ones((4, 4))})
a = mx.load(save_file, stream=mx.cpu)["a"]
mx.save_safetensors(save_file, {"a": a + 1})
out = mx.load(save_file, stream=mx.cpu)["a"]
self.assertTrue(np.array_equal(np.array(out), 2 * np.ones((4, 4))))

def test_save_over_lazily_loaded_npy(self):
save_file = os.path.join(self.test_dir, "resave.npy")
mx.save(save_file, mx.ones((4, 4)))
a = mx.load(save_file, stream=mx.cpu)
mx.save(save_file, a + 2)
out = mx.load(save_file, stream=mx.cpu)
self.assertTrue(np.array_equal(np.array(out), 3 * np.ones((4, 4))))

def test_save_and_load_safetensors(self):
test_file = os.path.join(self.test_dir, "test.safetensors")
with self.assertRaises(Exception):
Expand Down
Loading