diff --git a/mlx/export.cpp b/mlx/export.cpp index bcc0ad161c..55ccbe1874 100644 --- a/mlx/export.cpp +++ b/mlx/export.cpp @@ -702,6 +702,7 @@ FunctionExporter::FunctionExporter( fun(std::move(fun)), ftable(std::make_shared(shapeless)), metadata_(std::move(metadata)) { + os.open(); if (!os.is_open()) { throw std::runtime_error("[export_function] Failed to open " + file); } diff --git a/mlx/io/load.cpp b/mlx/io/load.cpp index 7df825e903..0f82a9e5d4 100644 --- a/mlx/io/load.cpp +++ b/mlx/io/load.cpp @@ -149,6 +149,10 @@ void save(std::shared_ptr 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()) { diff --git a/mlx/io/load.h b/mlx/io/load.h index ad1f827b52..70842cac9d 100644 --- a/mlx/io/load.h +++ b/mlx/io/load.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #ifdef _MSC_VER @@ -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; }; @@ -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; } @@ -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) { @@ -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(INT32_MAX))); if (m <= 0) { @@ -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 diff --git a/mlx/io/safetensors.cpp b/mlx/io/safetensors.cpp index 75c8a6ddc2..319579c48f 100644 --- a/mlx/io/safetensors.cpp +++ b/mlx/io/safetensors.cpp @@ -221,6 +221,20 @@ void save_safetensors( std::shared_ptr out_stream, std::unordered_map a, std::unordered_map metadata /* = {} */) { + { + std::vector 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()) { @@ -238,16 +252,6 @@ void save_safetensors( } parent["__metadata__"] = _metadata; - { - std::vector 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; diff --git a/python/tests/test_load.py b/python/tests/test_load.py index f5947de471..d9ad9751c1 100644 --- a/python/tests/test_load.py +++ b/python/tests/test_load.py @@ -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):