|
| 1 | +#include "infini_train/include/core/ccl/ccl_utils.h" |
| 2 | + |
| 3 | +#include <chrono> |
| 4 | +#include <cstdio> |
| 5 | +#include <filesystem> |
| 6 | +#include <fstream> |
| 7 | +#include <iterator> |
| 8 | +#include <thread> |
| 9 | + |
| 10 | +#include "glog/logging.h" |
| 11 | + |
| 12 | +namespace infini_train::core { |
| 13 | +namespace { |
| 14 | +std::string UniqueIdFileName(const std::string &name, bool tmp = false) { |
| 15 | + return "cclUniqueId_" + name + (tmp ? ".tmp" : ".bin"); |
| 16 | +} |
| 17 | +} // namespace |
| 18 | + |
| 19 | +void WriteUniqueIdFile(const CclUniqueId &unique_id, const std::string &pg_name) { |
| 20 | + const std::string tmp_path = UniqueIdFileName(pg_name, true); |
| 21 | + |
| 22 | + std::ofstream ofs(tmp_path, std::ios::binary); |
| 23 | + CHECK(ofs.good()) << "Failed to open unique_id tmp file for write: " << tmp_path; |
| 24 | + const size_t size = unique_id.Size(); |
| 25 | + ofs.write(reinterpret_cast<const char *>(unique_id.Data()), static_cast<std::streamsize>(size)); |
| 26 | + ofs.close(); |
| 27 | + |
| 28 | + std::rename(tmp_path.c_str(), UniqueIdFileName(pg_name).c_str()); |
| 29 | +} |
| 30 | + |
| 31 | +void ReadUniqueIdFile(CclUniqueId *unique_id, const std::string &pg_name) { |
| 32 | + CHECK_NOTNULL(unique_id); |
| 33 | + const std::string file_path = UniqueIdFileName(pg_name); |
| 34 | + |
| 35 | + while (!std::filesystem::exists(file_path)) { std::this_thread::sleep_for(std::chrono::microseconds(1000)); } |
| 36 | + |
| 37 | + std::ifstream ifs(file_path, std::ios::binary); |
| 38 | + CHECK(ifs.good()) << "Failed to open unique_id file for read: " << file_path; |
| 39 | + |
| 40 | + std::string bytes((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); |
| 41 | + ifs.close(); |
| 42 | + |
| 43 | + CHECK_EQ(bytes.size(), unique_id->Size()) |
| 44 | + << "Mismatched unique_id size in file. expected=" << unique_id->Size() << ", got=" << bytes.size(); |
| 45 | + unique_id->Load(bytes.data(), bytes.size()); |
| 46 | +} |
| 47 | + |
| 48 | +void CleanupUniqueIdFile(const std::string &pg_name) { |
| 49 | + const std::string file_path = UniqueIdFileName(pg_name); |
| 50 | + if (std::filesystem::exists(file_path)) { |
| 51 | + std::filesystem::remove(file_path); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +} // namespace infini_train::core |
0 commit comments