src/safetensors.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "brotensor/safetensors.h" | ||
| 2 | |||
| 3 | #include "brotensor/ops/elementwise.h" | ||
| 4 | #include "brotensor/runtime.h" | ||
| 5 | #include "brotensor/tensor.h" | ||
| 6 | |||
| 7 | #include <cstdint> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <cstring> | ||
| 10 | #include <limits> | ||
| 11 | #include <stdexcept> | ||
| 12 | #include <string> | ||
| 13 | #include <unordered_set> | ||
| 14 | #include <utility> | ||
| 15 | #include <vector> | ||
| 16 | |||
| 17 | #ifdef _WIN32 | ||
| 18 | #define WIN32_LEAN_AND_MEAN | ||
| 19 | #define NOMINMAX | ||
| 20 | #include <windows.h> | ||
| 21 | #else | ||
| 22 | #include <fcntl.h> | ||
| 23 | #include <sys/mman.h> | ||
| 24 | #include <sys/stat.h> | ||
| 25 | #include <unistd.h> | ||
| 26 | #endif | ||
| 27 | |||
| 28 | namespace brotensor::safetensors { | ||
| 29 | |||
| 30 | // ─── Dtype helpers ───────────────────────────────────────────────────────── | ||
| 31 | |||
| 32 | 25 | const char* dtype_name(Dtype d) { | |
| 33 | 25 | switch (d) { | |
| 34 | 9 | case Dtype::F32: return "F32"; | |
| 35 | 5 | case Dtype::F16: return "F16"; | |
| 36 | 2 | case Dtype::BF16: return "BF16"; | |
| 37 | 2 | case Dtype::I32: return "I32"; | |
| 38 | 2 | case Dtype::I64: return "I64"; | |
| 39 | 2 | case Dtype::U8: return "U8"; | |
| 40 | 1 | case Dtype::BOOL: return "BOOL"; | |
| 41 | 1 | case Dtype::Unknown: | |
| 42 | 2 | default: return "Unknown"; | |
| 43 | } | ||
| 44 | 25 | } | |
| 45 | |||
| 46 | 172 | int dtype_size_bytes(Dtype d) { | |
| 47 | 172 | switch (d) { | |
| 48 | 91 | case Dtype::F32: return 4; | |
| 49 | 32 | case Dtype::F16: return 2; | |
| 50 | 15 | case Dtype::BF16: return 2; | |
| 51 | 4 | case Dtype::I32: return 4; | |
| 52 | 3 | case Dtype::I64: return 8; | |
| 53 | 20 | case Dtype::U8: return 1; | |
| 54 | 3 | case Dtype::BOOL: return 1; | |
| 55 | 4 | default: return 0; | |
| 56 | } | ||
| 57 | 172 | } | |
| 58 | |||
| 59 | 122 | static Dtype parse_dtype(std::string_view s) { | |
| 60 | 122 | if (s == "F32") return Dtype::F32; | |
| 61 | 46 | if (s == "F16") return Dtype::F16; | |
| 62 | 24 | if (s == "BF16") return Dtype::BF16; | |
| 63 | 13 | if (s == "I32") return Dtype::I32; | |
| 64 | 12 | if (s == "I64") return Dtype::I64; | |
| 65 | 11 | if (s == "U8") return Dtype::U8; | |
| 66 | 2 | if (s == "BOOL") return Dtype::BOOL; | |
| 67 | 1 | return Dtype::Unknown; | |
| 68 | 122 | } | |
| 69 | |||
| 70 | 101 | int64_t TensorView::numel() const { | |
| 71 | 101 | int64_t n = 1; | |
| 72 | 268 | for (int64_t d : shape) { | |
| 73 | 170 | if (d < 0) | |
| 74 | 2 | throw std::runtime_error("safetensors: negative dimension in tensor shape"); | |
| 75 | 168 | if (d != 0 && n > INT64_MAX / d) | |
| 76 | 1 | throw std::runtime_error("safetensors: tensor element count overflows int64"); | |
| 77 | 167 | n *= d; | |
| 78 | } | ||
| 79 | 98 | return n; | |
| 80 | ✗ | } | |
| 81 | |||
| 82 | // ─── Minimal JSON parser ─────────────────────────────────────────────────── | ||
| 83 | // | ||
| 84 | // Safetensors headers use a strict subset of JSON: top-level object whose | ||
| 85 | // values are either an object {dtype, shape, data_offsets} or the | ||
| 86 | // __metadata__ string->string object. We parse exactly that and reject | ||
| 87 | // anything that doesn't match. No nested escapes beyond \\, \", \n, \t are | ||
| 88 | // expected in tensor names; we handle them defensively anyway. | ||
| 89 | |||
| 90 | namespace { | ||
| 91 | |||
| 92 | struct Parser { | ||
| 93 | const char* p; | ||
| 94 | const char* end; | ||
| 95 | |||
| 96 | 10 | [[noreturn]] void fail(const std::string& msg) const { | |
| 97 | 10 | throw std::runtime_error("safetensors: parse error: " + msg); | |
| 98 | 10 | } | |
| 99 | |||
| 100 | 4847 | void skip_ws() { | |
| 101 | 9781 | while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) ++p; | |
| 102 | 4847 | } | |
| 103 | |||
| 104 | 2606 | bool eat(char c) { | |
| 105 | 2606 | skip_ws(); | |
| 106 | 2606 | if (p < end && *p == c) { ++p; return true; } | |
| 107 | 731 | return false; | |
| 108 | 2606 | } | |
| 109 | 1618 | void expect(char c) { | |
| 110 | 1618 | if (!eat(c)) fail(std::string("expected '") + c + "'"); | |
| 111 | 1618 | } | |
| 112 | |||
| 113 | // Four hex digits at q -> value, or -1 if any is not a hex digit. | ||
| 114 | ✗ | static int hex4(const char* q) { | |
| 115 | ✗ | int v = 0; | |
| 116 | ✗ | for (int i = 0; i < 4; ++i) { | |
| 117 | ✗ | const char c = q[i]; | |
| 118 | int d; | ||
| 119 | ✗ | if (c >= '0' && c <= '9') d = c - '0'; | |
| 120 | ✗ | else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; | |
| 121 | ✗ | else if (c >= 'A' && c <= 'F') d = c - 'A' + 10; | |
| 122 | ✗ | else return -1; | |
| 123 | ✗ | v = (v << 4) | d; | |
| 124 | ✗ | } | |
| 125 | ✗ | return v; | |
| 126 | ✗ | } | |
| 127 | |||
| 128 | ✗ | static void append_utf8(std::string& out, uint32_t cp) { | |
| 129 | ✗ | if (cp < 0x80) { | |
| 130 | ✗ | out += static_cast<char>(cp); | |
| 131 | ✗ | } else if (cp < 0x800) { | |
| 132 | ✗ | out += static_cast<char>(0xC0 | (cp >> 6)); | |
| 133 | ✗ | out += static_cast<char>(0x80 | (cp & 0x3F)); | |
| 134 | ✗ | } else if (cp < 0x10000) { | |
| 135 | ✗ | out += static_cast<char>(0xE0 | (cp >> 12)); | |
| 136 | ✗ | out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); | |
| 137 | ✗ | out += static_cast<char>(0x80 | (cp & 0x3F)); | |
| 138 | ✗ | } else { | |
| 139 | ✗ | out += static_cast<char>(0xF0 | (cp >> 18)); | |
| 140 | ✗ | out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F)); | |
| 141 | ✗ | out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); | |
| 142 | ✗ | out += static_cast<char>(0x80 | (cp & 0x3F)); | |
| 143 | } | ||
| 144 | ✗ | } | |
| 145 | |||
| 146 | 753 | std::string parse_string() { | |
| 147 | 753 | skip_ws(); | |
| 148 | 755 | if (p >= end || *p != '"') fail("expected string"); | |
| 149 | 752 | ++p; | |
| 150 | 752 | std::string out; | |
| 151 | 5398 | while (p < end && *p != '"') { | |
| 152 | 4647 | if (*p == '\\' && p + 1 < end) { | |
| 153 | 17 | char e = p[1]; | |
| 154 | // \uXXXX carries a UTF-16 code unit, possibly the high half of | ||
| 155 | // a surrogate pair. It must be decoded and re-emitted as UTF-8: | ||
| 156 | // safetensors headers are UTF-8 JSON, \u is what most writers | ||
| 157 | // emit for a non-ASCII tensor name, and it is what our own | ||
| 158 | // json_escape_append emits for control characters — so without | ||
| 159 | // this we reject both third-party files and our own output. | ||
| 160 | 17 | if (e == 'u') { | |
| 161 | ✗ | if (p + 6 > end) fail("truncated \\u escape in string"); | |
| 162 | ✗ | int hi = hex4(p + 2); | |
| 163 | ✗ | if (hi < 0) fail("bad hex digit in \\u escape"); | |
| 164 | ✗ | p += 6; | |
| 165 | ✗ | uint32_t cp = static_cast<uint32_t>(hi); | |
| 166 | ✗ | if (hi >= 0xD800 && hi <= 0xDBFF) { | |
| 167 | ✗ | if (p + 6 > end || p[0] != '\\' || p[1] != 'u') | |
| 168 | ✗ | fail("unpaired high surrogate in string"); | |
| 169 | ✗ | const int lo = hex4(p + 2); | |
| 170 | ✗ | if (lo < 0) fail("bad hex digit in \\u escape"); | |
| 171 | ✗ | if (lo < 0xDC00 || lo > 0xDFFF) | |
| 172 | ✗ | fail("unpaired high surrogate in string"); | |
| 173 | ✗ | cp = 0x10000u + ((static_cast<uint32_t>(hi) - 0xD800u) << 10) | |
| 174 | ✗ | + (static_cast<uint32_t>(lo) - 0xDC00u); | |
| 175 | ✗ | p += 6; | |
| 176 | ✗ | } else if (hi >= 0xDC00 && hi <= 0xDFFF) { | |
| 177 | ✗ | fail("unpaired low surrogate in string"); | |
| 178 | } | ||
| 179 | ✗ | append_utf8(out, cp); | |
| 180 | ✗ | continue; // p is already past the escape | |
| 181 | } | ||
| 182 | 17 | switch (e) { | |
| 183 | 3 | case '"': out += '"'; break; | |
| 184 | 2 | case '\\': out += '\\'; break; | |
| 185 | 1 | case '/': out += '/'; break; | |
| 186 | 2 | case 'n': out += '\n'; break; | |
| 187 | 2 | case 't': out += '\t'; break; | |
| 188 | 2 | case 'r': out += '\r'; break; | |
| 189 | 2 | case 'b': out += '\b'; break; | |
| 190 | 2 | case 'f': out += '\f'; break; | |
| 191 | 1 | default: fail("unsupported escape in string"); | |
| 192 | } | ||
| 193 | 16 | p += 2; | |
| 194 | 16 | } else { | |
| 195 | 4630 | out += *p++; | |
| 196 | } | ||
| 197 | } | ||
| 198 | 751 | if (p >= end) fail("unterminated string"); | |
| 199 | 750 | ++p; | |
| 200 | 750 | return out; | |
| 201 | 753 | } | |
| 202 | |||
| 203 | 426 | int64_t parse_int() { | |
| 204 | 426 | skip_ws(); | |
| 205 | 426 | bool neg = false; | |
| 206 | 426 | if (p < end && *p == '-') { neg = true; ++p; } | |
| 207 | 427 | if (p >= end || *p < '0' || *p > '9') fail("expected integer"); | |
| 208 | 425 | int64_t v = 0; | |
| 209 | 1015 | while (p < end && *p >= '0' && *p <= '9') { | |
| 210 | 591 | const int digit = *p - '0'; | |
| 211 | 591 | if (v > (INT64_MAX - digit) / 10) fail("integer out of range"); | |
| 212 | 590 | v = v * 10 + digit; | |
| 213 | 590 | ++p; | |
| 214 | } | ||
| 215 | 424 | return neg ? -v : v; | |
| 216 | 2 | } | |
| 217 | |||
| 218 | // Skip an arbitrary JSON value (used for __metadata__ entries we don't | ||
| 219 | // care about, and as a defensive fallback). | ||
| 220 | 49 | void skip_value() { | |
| 221 | 49 | skip_ws(); | |
| 222 | 50 | if (p >= end) fail("unexpected EOF"); | |
| 223 | 49 | if (*p == '"') { (void)parse_string(); return; } | |
| 224 | 48 | if (*p == '{' || *p == '[') { | |
| 225 | 45 | char open = *p++, close = (open == '{') ? '}' : ']'; | |
| 226 | 45 | int depth = 1; | |
| 227 | 248 | while (p < end && depth > 0) { | |
| 228 | 203 | if (*p == '"') { (void)parse_string(); continue; } | |
| 229 | 110 | if (*p == open) ++depth; | |
| 230 | 109 | else if (*p == close) --depth; | |
| 231 | 110 | ++p; | |
| 232 | } | ||
| 233 | 45 | if (depth > 0) fail("unterminated container"); | |
| 234 | 44 | return; | |
| 235 | } | ||
| 236 | // number / true / false / null | ||
| 237 | 15 | while (p < end && *p != ',' && *p != '}' && *p != ']' && | |
| 238 | 18 | *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') ++p; | |
| 239 | 49 | } | |
| 240 | }; | ||
| 241 | |||
| 242 | 246 | struct Entry { | |
| 243 | 123 | Dtype dtype = Dtype::Unknown; | |
| 244 | std::vector<int64_t> shape; | ||
| 245 | 123 | uint64_t off_start = 0; | |
| 246 | 123 | uint64_t off_end = 0; | |
| 247 | }; | ||
| 248 | |||
| 249 | 123 | Entry parse_entry(Parser& ps) { | |
| 250 | 123 | Entry e; | |
| 251 | 123 | ps.expect('{'); | |
| 252 | 123 | bool first = true; | |
| 253 | 123 | bool seen_dtype = false; | |
| 254 | 123 | bool seen_shape = false; | |
| 255 | 123 | bool seen_offsets = false; | |
| 256 | 484 | while (true) { | |
| 257 | 484 | ps.skip_ws(); | |
| 258 | 484 | if (ps.eat('}')) break; | |
| 259 | 367 | if (!first) ps.expect(','); | |
| 260 | 367 | first = false; | |
| 261 | 367 | std::string key = ps.parse_string(); | |
| 262 | 367 | ps.expect(':'); | |
| 263 | 367 | if (key == "dtype") { | |
| 264 | 123 | if (seen_dtype) throw std::runtime_error("safetensors: duplicate 'dtype' in entry"); | |
| 265 | 122 | seen_dtype = true; | |
| 266 | 122 | std::string v = ps.parse_string(); | |
| 267 | 122 | e.dtype = parse_dtype(v); | |
| 268 | 122 | if (e.dtype == Dtype::Unknown) { | |
| 269 | 1 | throw std::runtime_error("safetensors: unsupported dtype '" + v + "'"); | |
| 270 | } | ||
| 271 | 366 | } else if (key == "shape") { | |
| 272 | 120 | if (seen_shape) throw std::runtime_error("safetensors: duplicate 'shape' in entry"); | |
| 273 | 120 | seen_shape = true; | |
| 274 | 120 | ps.expect('['); | |
| 275 | 120 | bool sfirst = true; | |
| 276 | 309 | while (true) { | |
| 277 | 309 | ps.skip_ws(); | |
| 278 | 309 | if (ps.eat(']')) break; | |
| 279 | 191 | if (!sfirst) ps.expect(','); | |
| 280 | 191 | sfirst = false; | |
| 281 | 191 | e.shape.push_back(ps.parse_int()); | |
| 282 | } | ||
| 283 | 242 | } else if (key == "data_offsets") { | |
| 284 | 118 | if (seen_offsets) throw std::runtime_error("safetensors: duplicate 'data_offsets' in entry"); | |
| 285 | 118 | seen_offsets = true; | |
| 286 | 118 | ps.expect('['); | |
| 287 | 118 | int64_t off_s = ps.parse_int(); | |
| 288 | 118 | ps.expect(','); | |
| 289 | 117 | int64_t off_e = ps.parse_int(); | |
| 290 | 117 | ps.expect(']'); | |
| 291 | 117 | if (off_s < 0 || off_e < 0) { | |
| 292 | 1 | throw std::runtime_error("safetensors: negative data_offsets"); | |
| 293 | } | ||
| 294 | 116 | e.off_start = static_cast<uint64_t>(off_s); | |
| 295 | 116 | e.off_end = static_cast<uint64_t>(off_e); | |
| 296 | 116 | } else { | |
| 297 | // Unknown field — skip its value defensively. | ||
| 298 | 6 | ps.skip_value(); | |
| 299 | } | ||
| 300 | 367 | } | |
| 301 | 117 | if (!seen_dtype || !seen_shape || !seen_offsets) { | |
| 302 | 3 | throw std::runtime_error( | |
| 303 | "safetensors: entry missing required field (dtype, shape, or data_offsets)"); | ||
| 304 | } | ||
| 305 | 114 | return e; | |
| 306 | 129 | } | |
| 307 | |||
| 308 | } // namespace | ||
| 309 | |||
| 310 | // ─── mmap (platform) ─────────────────────────────────────────────────────── | ||
| 311 | |||
| 312 | namespace { | ||
| 313 | |||
| 314 | 322 | struct Mapping { | |
| 315 | 322 | void* file = nullptr; | |
| 316 | 322 | void* mapping = nullptr; | |
| 317 | 322 | void* base = nullptr; | |
| 318 | 322 | std::size_t size = 0; | |
| 319 | }; | ||
| 320 | |||
| 321 | 322 | Mapping map_file(const std::string& path) { | |
| 322 | 322 | Mapping m; | |
| 323 | #ifdef _WIN32 | ||
| 324 | HANDLE fh = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, | ||
| 325 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 326 | if (fh == INVALID_HANDLE_VALUE) { | ||
| 327 | throw std::runtime_error("safetensors: cannot open '" + path + "'"); | ||
| 328 | } | ||
| 329 | LARGE_INTEGER sz; | ||
| 330 | if (!GetFileSizeEx(fh, &sz)) { | ||
| 331 | CloseHandle(fh); | ||
| 332 | throw std::runtime_error("safetensors: GetFileSizeEx failed for '" + path + "'"); | ||
| 333 | } | ||
| 334 | HANDLE mh = CreateFileMappingA(fh, nullptr, PAGE_READONLY, 0, 0, nullptr); | ||
| 335 | if (!mh) { | ||
| 336 | CloseHandle(fh); | ||
| 337 | throw std::runtime_error("safetensors: CreateFileMapping failed for '" + path + "'"); | ||
| 338 | } | ||
| 339 | void* base = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0); | ||
| 340 | if (!base) { | ||
| 341 | CloseHandle(mh); | ||
| 342 | CloseHandle(fh); | ||
| 343 | throw std::runtime_error("safetensors: MapViewOfFile failed for '" + path + "'"); | ||
| 344 | } | ||
| 345 | m.file = fh; | ||
| 346 | m.mapping = mh; | ||
| 347 | m.base = base; | ||
| 348 | m.size = static_cast<std::size_t>(sz.QuadPart); | ||
| 349 | #else | ||
| 350 | 322 | int fd = ::open(path.c_str(), O_RDONLY); | |
| 351 | 322 | if (fd < 0) throw std::runtime_error("safetensors: cannot open '" + path + "'"); | |
| 352 | 317 | struct stat st{}; | |
| 353 | 317 | if (fstat(fd, &st) != 0) { | |
| 354 | ✗ | ::close(fd); | |
| 355 | ✗ | throw std::runtime_error("safetensors: fstat failed for '" + path + "'"); | |
| 356 | } | ||
| 357 | 317 | if (st.st_size <= 0) { | |
| 358 | 2 | ::close(fd); | |
| 359 | 2 | return m; | |
| 360 | } | ||
| 361 | 315 | void* base = ::mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); | |
| 362 | 315 | if (base == MAP_FAILED) { | |
| 363 | ✗ | ::close(fd); | |
| 364 | ✗ | throw std::runtime_error("safetensors: mmap failed for '" + path + "'"); | |
| 365 | } | ||
| 366 | 315 | m.file = reinterpret_cast<void*>(static_cast<intptr_t>(fd)); | |
| 367 | 315 | m.mapping = nullptr; | |
| 368 | 315 | m.base = base; | |
| 369 | 315 | m.size = static_cast<std::size_t>(st.st_size); | |
| 370 | #endif | ||
| 371 | 315 | return m; | |
| 372 | 322 | } | |
| 373 | |||
| 374 | 334 | void unmap_file(Mapping& m) noexcept { | |
| 375 | #ifdef _WIN32 | ||
| 376 | if (m.base) UnmapViewOfFile(m.base); | ||
| 377 | if (m.mapping) CloseHandle(m.mapping); | ||
| 378 | if (m.file) CloseHandle(m.file); | ||
| 379 | #else | ||
| 380 | 334 | if (m.base && m.size) ::munmap(m.base, m.size); | |
| 381 | 334 | if (m.file) ::close(static_cast<int>(reinterpret_cast<intptr_t>(m.file))); | |
| 382 | #endif | ||
| 383 | 334 | m = Mapping{}; | |
| 384 | 334 | } | |
| 385 | |||
| 386 | } // namespace | ||
| 387 | |||
| 388 | // ─── File ────────────────────────────────────────────────────────────────── | ||
| 389 | |||
| 390 | 202 | File::~File() { release_(); } | |
| 391 | |||
| 392 | 30 | File::File(File&& other) noexcept | |
| 393 | 15 | : file_(other.file_), mapping_(other.mapping_), base_(other.base_), | |
| 394 | 15 | file_size_(other.file_size_), | |
| 395 | 30 | tensors_(std::move(other.tensors_)), index_(std::move(other.index_)) { | |
| 396 | 15 | other.file_ = other.mapping_ = other.base_ = nullptr; | |
| 397 | 15 | other.file_size_ = 0; | |
| 398 | 30 | } | |
| 399 | |||
| 400 | 2 | File& File::operator=(File&& other) noexcept { | |
| 401 | 2 | if (this != &other) { | |
| 402 | 2 | release_(); | |
| 403 | 2 | file_ = other.file_; | |
| 404 | 2 | mapping_ = other.mapping_; | |
| 405 | 2 | base_ = other.base_; | |
| 406 | 2 | file_size_ = other.file_size_; | |
| 407 | 2 | tensors_ = std::move(other.tensors_); | |
| 408 | 2 | index_ = std::move(other.index_); | |
| 409 | 2 | other.file_ = other.mapping_ = other.base_ = nullptr; | |
| 410 | 2 | other.file_size_ = 0; | |
| 411 | 2 | } | |
| 412 | 2 | return *this; | |
| 413 | } | ||
| 414 | |||
| 415 | 103 | void File::release_() noexcept { | |
| 416 | 103 | Mapping m{file_, mapping_, base_, file_size_}; | |
| 417 | 103 | unmap_file(m); | |
| 418 | 103 | file_ = mapping_ = base_ = nullptr; | |
| 419 | 103 | file_size_ = 0; | |
| 420 | 103 | tensors_.clear(); | |
| 421 | 103 | index_.clear(); | |
| 422 | 103 | } | |
| 423 | |||
| 424 | 317 | File File::open(const std::string& path) { | |
| 425 | 317 | Mapping m = map_file(path); | |
| 426 | 317 | if (m.size < 8) { | |
| 427 | 10 | unmap_file(m); | |
| 428 | 72 | throw std::runtime_error("safetensors: file too small: '" + path + "'"); | |
| 429 | } | ||
| 430 | 307 | const uint8_t* bytes = static_cast<const uint8_t*>(m.base); | |
| 431 | 307 | uint64_t header_size = 0; | |
| 432 | 307 | std::memcpy(&header_size, bytes, 8); // little-endian; platforms we target are LE | |
| 433 | 307 | if (header_size > m.size - 8) { | |
| 434 | 221 | unmap_file(m); | |
| 435 | 221 | throw std::runtime_error("safetensors: header_size exceeds file"); | |
| 436 | } | ||
| 437 | 86 | const char* hdr_begin = reinterpret_cast<const char*>(bytes + 8); | |
| 438 | 86 | const char* hdr_end = hdr_begin + header_size; | |
| 439 | 86 | const uint8_t* payload_base = bytes + 8 + header_size; | |
| 440 | 86 | std::size_t payload_size = m.size - 8 - header_size; | |
| 441 | |||
| 442 | 86 | File f; | |
| 443 | 86 | f.file_ = m.file; | |
| 444 | 86 | f.mapping_ = m.mapping; | |
| 445 | 86 | f.base_ = m.base; | |
| 446 | 86 | f.file_size_ = m.size; | |
| 447 | |||
| 448 | 86 | Parser ps{hdr_begin, hdr_end}; | |
| 449 | try { | ||
| 450 | 86 | ps.expect('{'); | |
| 451 | 85 | bool first = true; | |
| 452 | 85 | bool seen_metadata = false; | |
| 453 | 195 | while (true) { | |
| 454 | 195 | ps.skip_ws(); | |
| 455 | 195 | if (ps.eat('}')) break; | |
| 456 | 170 | if (!first) ps.expect(','); | |
| 457 | 170 | first = false; | |
| 458 | 170 | std::string name = ps.parse_string(); | |
| 459 | 167 | ps.expect(':'); | |
| 460 | 166 | if (name == "__metadata__") { | |
| 461 | 43 | if (seen_metadata) { | |
| 462 | ✗ | throw std::runtime_error("safetensors: duplicate '__metadata__' key"); | |
| 463 | } | ||
| 464 | 43 | seen_metadata = true; | |
| 465 | 43 | ps.skip_value(); | |
| 466 | 42 | continue; | |
| 467 | } | ||
| 468 | 123 | Entry e = parse_entry(ps); | |
| 469 | 114 | if (e.off_end < e.off_start || e.off_end > payload_size) { | |
| 470 | 84 | throw std::runtime_error( | |
| 471 | 42 | "safetensors: tensor '" + name + "' has out-of-range data_offsets"); | |
| 472 | } | ||
| 473 | 72 | TensorView tv; | |
| 474 | 72 | tv.name = name; | |
| 475 | 72 | tv.dtype = e.dtype; | |
| 476 | 72 | tv.shape = std::move(e.shape); | |
| 477 | 72 | tv.data = payload_base + e.off_start; | |
| 478 | 72 | tv.nbytes = static_cast<std::size_t>(e.off_end - e.off_start); | |
| 479 | |||
| 480 | 72 | const uint64_t numel_u = static_cast<uint64_t>(tv.numel()); | |
| 481 | 71 | const uint64_t dsz_u = static_cast<uint64_t>(dtype_size_bytes(tv.dtype)); | |
| 482 | 71 | if (dsz_u == 0 || numel_u > std::numeric_limits<std::size_t>::max() / dsz_u) { | |
| 483 | 2 | throw std::runtime_error( | |
| 484 | 1 | "safetensors: tensor '" + name + | |
| 485 | "' byte size overflows size_t"); | ||
| 486 | } | ||
| 487 | 70 | const std::size_t expected = static_cast<std::size_t>(numel_u * dsz_u); | |
| 488 | 70 | if (expected != tv.nbytes) { | |
| 489 | 2 | throw std::runtime_error( | |
| 490 | 1 | "safetensors: tensor '" + name + | |
| 491 | "' nbytes/shape mismatch"); | ||
| 492 | } | ||
| 493 | 69 | if (!f.index_.emplace(tv.name, f.tensors_.size()).second) { | |
| 494 | 2 | throw std::runtime_error( | |
| 495 | 1 | "safetensors: duplicate tensor name '" + name + "'"); | |
| 496 | } | ||
| 497 | 68 | f.tensors_.push_back(std::move(tv)); | |
| 498 | 167 | } | |
| 499 | 25 | ps.skip_ws(); | |
| 500 | 25 | if (ps.p != ps.end) { | |
| 501 | 1 | ps.fail("unexpected trailing data after header object"); | |
| 502 | } | ||
| 503 | 86 | } catch (...) { | |
| 504 | // f's destructor will unmap. | ||
| 505 | 62 | throw; | |
| 506 | 62 | } | |
| 507 | 24 | return f; | |
| 508 | 158 | } | |
| 509 | |||
| 510 | 54 | const TensorView* File::find(std::string_view name) const { | |
| 511 | 54 | auto it = index_.find(name); | |
| 512 | 54 | if (it == index_.end()) return nullptr; | |
| 513 | 47 | return &tensors_[it->second]; | |
| 514 | 54 | } | |
| 515 | |||
| 516 | 5 | const TensorView& File::get(std::string_view name) const { | |
| 517 | 5 | const TensorView* v = find(name); | |
| 518 | 5 | if (!v) { | |
| 519 | 4 | throw std::runtime_error( | |
| 520 | 2 | "safetensors: no tensor named '" + std::string(name) + "'"); | |
| 521 | } | ||
| 522 | 3 | return *v; | |
| 523 | 2 | } | |
| 524 | |||
| 525 | // ─── Upload ──────────────────────────────────────────────────────────────── | ||
| 526 | |||
| 527 | 19 | void upload(const TensorView& view, int rows, int cols, brotensor::Tensor& dst) { | |
| 528 | 19 | if (rows <= 0 || cols <= 0) { | |
| 529 | 4 | throw std::runtime_error("safetensors::upload: rows/cols must be positive"); | |
| 530 | } | ||
| 531 | 17 | const std::size_t expected = | |
| 532 | 34 | static_cast<std::size_t>(rows) * static_cast<std::size_t>(cols) * | |
| 533 | 17 | static_cast<std::size_t>(dtype_size_bytes(view.dtype)); | |
| 534 | 17 | if (expected != view.nbytes) { | |
| 535 | 2 | throw std::runtime_error( | |
| 536 | 1 | "safetensors::upload: byte count mismatch for tensor '" + view.name + "'"); | |
| 537 | } | ||
| 538 | 16 | if (view.dtype == Dtype::F32) { | |
| 539 | 11 | dst = brotensor::Tensor::from_host(reinterpret_cast<const float*>(view.data), rows, cols); | |
| 540 | 16 | } else if (view.dtype == Dtype::F16) { | |
| 541 | 3 | dst = brotensor::Tensor::from_host_fp16( | |
| 542 | 3 | reinterpret_cast<const uint16_t*>(view.data), rows, cols); | |
| 543 | 5 | } else if (view.dtype == Dtype::BF16) { | |
| 544 | 1 | dst = brotensor::Tensor::from_host_bf16( | |
| 545 | 1 | reinterpret_cast<const uint16_t*>(view.data), rows, cols); | |
| 546 | 1 | } else { | |
| 547 | 2 | throw std::runtime_error( | |
| 548 | 1 | std::string("safetensors::upload: unsupported dtype ") + | |
| 549 | 1 | dtype_name(view.dtype) + " for tensor '" + view.name + "'"); | |
| 550 | } | ||
| 551 | 17 | } | |
| 552 | |||
| 553 | 9 | void upload_fp16(const TensorView& view, int rows, int cols, brotensor::Tensor& dst) { | |
| 554 | 9 | if (rows <= 0 || cols <= 0) { | |
| 555 | 3 | throw std::runtime_error("safetensors::upload_fp16: rows/cols must be positive"); | |
| 556 | } | ||
| 557 | 8 | const std::size_t n = static_cast<std::size_t>(rows) * static_cast<std::size_t>(cols); | |
| 558 | 8 | const std::size_t expected = n * static_cast<std::size_t>(dtype_size_bytes(view.dtype)); | |
| 559 | 8 | if (expected != view.nbytes) { | |
| 560 | 2 | throw std::runtime_error( | |
| 561 | 1 | "safetensors::upload_fp16: byte count mismatch for tensor '" + view.name + "'"); | |
| 562 | } | ||
| 563 | 7 | if (view.dtype == Dtype::F16) { | |
| 564 | 1 | dst = brotensor::Tensor::from_host_fp16( | |
| 565 | 1 | reinterpret_cast<const uint16_t*>(view.data), rows, cols); | |
| 566 | 7 | } else if (view.dtype == Dtype::F32) { | |
| 567 | 5 | const float* src = reinterpret_cast<const float*>(view.data); | |
| 568 | 5 | std::vector<uint16_t> tmp(n); | |
| 569 | 35 | for (std::size_t i = 0; i < n; ++i) { | |
| 570 | 30 | tmp[i] = brotensor::fp32_to_fp16_bits(src[i]); | |
| 571 | 30 | } | |
| 572 | 5 | dst = brotensor::Tensor::from_host_fp16(tmp.data(), rows, cols); | |
| 573 | 5 | } else { | |
| 574 | 2 | throw std::runtime_error( | |
| 575 | 1 | std::string("safetensors::upload_fp16: unsupported dtype ") + | |
| 576 | 1 | dtype_name(view.dtype) + " for tensor '" + view.name + "'"); | |
| 577 | } | ||
| 578 | 8 | } | |
| 579 | |||
| 580 | 23 | void upload_as(const TensorView& view, int rows, int cols, | |
| 581 | brotensor::Dtype want, brotensor::Tensor& dst) { | ||
| 582 | 23 | if (rows <= 0 || cols <= 0) { | |
| 583 | 3 | throw std::runtime_error("safetensors::upload_as: rows/cols must be positive"); | |
| 584 | } | ||
| 585 | 22 | const std::size_t n = static_cast<std::size_t>(rows) * static_cast<std::size_t>(cols); | |
| 586 | 22 | const std::size_t expected = n * static_cast<std::size_t>(dtype_size_bytes(view.dtype)); | |
| 587 | 22 | if (expected != view.nbytes) { | |
| 588 | 2 | throw std::runtime_error( | |
| 589 | 1 | "safetensors::upload_as: byte count mismatch for tensor '" + view.name + "'"); | |
| 590 | } | ||
| 591 | 21 | if (view.dtype != Dtype::F16 && view.dtype != Dtype::F32 && | |
| 592 | 8 | view.dtype != Dtype::BF16) { | |
| 593 | 2 | throw std::runtime_error( | |
| 594 | 1 | std::string("safetensors::upload_as: unsupported source dtype ") + | |
| 595 | 1 | dtype_name(view.dtype) + " for tensor '" + view.name + "'"); | |
| 596 | } | ||
| 597 | |||
| 598 | // Decode any source element to FP32. | ||
| 599 | 20 | const float* src32 = reinterpret_cast<const float*>(view.data); | |
| 600 | 20 | const uint16_t* src16 = reinterpret_cast<const uint16_t*>(view.data); | |
| 601 | |||
| 602 | // GPU fast path: when the on-disk dtype differs from the compute dtype | ||
| 603 | // (e.g. BF16 checkpoints with an FP16 compute policy), upload the raw bytes | ||
| 604 | // at the source dtype and cast on-device. The host convert-then-upload path | ||
| 605 | // below is a single-threaded scalar loop over every element — for a 2.6B-param | ||
| 606 | // encoder that is ~13 s, versus a ~0.1 s device cast after the same H2D copy. | ||
| 607 | 20 | if (brotensor::default_device() != brotensor::Device::CPU) { | |
| 608 | 2 | brotensor::Tensor raw; | |
| 609 | 2 | switch (view.dtype) { | |
| 610 | ✗ | case Dtype::F32: raw = brotensor::Tensor::from_host(src32, rows, cols); break; | |
| 611 | 2 | case Dtype::F16: raw = brotensor::Tensor::from_host_fp16(src16, rows, cols); break; | |
| 612 | ✗ | default: raw = brotensor::Tensor::from_host_bf16(src16, rows, cols); break; | |
| 613 | } | ||
| 614 | 2 | if (raw.dtype == want) { | |
| 615 | 2 | dst = std::move(raw); | |
| 616 | 2 | } else { | |
| 617 | ✗ | brotensor::cast(raw, dst, want); | |
| 618 | } | ||
| 619 | return; | ||
| 620 | 2 | } | |
| 621 | 80 | auto at_f32 = [&](std::size_t i) -> float { | |
| 622 | 62 | switch (view.dtype) { | |
| 623 | 12 | case Dtype::F32: return src32[i]; | |
| 624 | 26 | case Dtype::F16: return brotensor::fp16_bits_to_fp32(src16[i]); | |
| 625 | 24 | default: return brotensor::bf16_bits_to_fp32(src16[i]); | |
| 626 | } | ||
| 627 | 62 | }; | |
| 628 | |||
| 629 | 18 | switch (want) { | |
| 630 | case brotensor::Dtype::FP32: { | ||
| 631 | 10 | if (view.dtype == Dtype::F32) { | |
| 632 | 2 | dst = brotensor::Tensor::from_host(src32, rows, cols); | |
| 633 | 2 | return; | |
| 634 | } | ||
| 635 | 8 | std::vector<float> tmp(n); | |
| 636 | 46 | for (std::size_t i = 0; i < n; ++i) tmp[i] = at_f32(i); | |
| 637 | 8 | dst = brotensor::Tensor::from_host(tmp.data(), rows, cols); | |
| 638 | return; | ||
| 639 | 8 | } | |
| 640 | case brotensor::Dtype::FP16: { | ||
| 641 | 3 | if (view.dtype == Dtype::F16) { | |
| 642 | 1 | dst = brotensor::Tensor::from_host_fp16(src16, rows, cols); | |
| 643 | 1 | return; | |
| 644 | } | ||
| 645 | 2 | std::vector<uint16_t> tmp(n); | |
| 646 | 14 | for (std::size_t i = 0; i < n; ++i) { | |
| 647 | 12 | tmp[i] = brotensor::fp32_to_fp16_bits(at_f32(i)); | |
| 648 | 12 | } | |
| 649 | 2 | dst = brotensor::Tensor::from_host_fp16(tmp.data(), rows, cols); | |
| 650 | return; | ||
| 651 | 2 | } | |
| 652 | case brotensor::Dtype::BF16: { | ||
| 653 | 4 | if (view.dtype == Dtype::BF16) { | |
| 654 | 2 | dst = brotensor::Tensor::from_host_bf16(src16, rows, cols); | |
| 655 | 2 | return; | |
| 656 | } | ||
| 657 | 2 | std::vector<uint16_t> tmp(n); | |
| 658 | 14 | for (std::size_t i = 0; i < n; ++i) { | |
| 659 | 12 | tmp[i] = brotensor::fp32_to_bf16_bits(at_f32(i)); | |
| 660 | 12 | } | |
| 661 | 2 | dst = brotensor::Tensor::from_host_bf16(tmp.data(), rows, cols); | |
| 662 | return; | ||
| 663 | 2 | } | |
| 664 | default: | ||
| 665 | 1 | throw std::runtime_error( | |
| 666 | "safetensors::upload_as: target dtype must be FP32/FP16/BF16"); | ||
| 667 | } | ||
| 668 | 21 | } | |
| 669 | |||
| 670 | 9 | void upload_compute(const TensorView& view, int rows, int cols, | |
| 671 | brotensor::Tensor& dst) { | ||
| 672 | // The compute dtype follows the active brotensor device: FP32 on the CPU | ||
| 673 | // backend, FP16 on a GPU backend. BF16 in particular is the on-disk dtype | ||
| 674 | // of Flux-family weights; CPU has no BF16 arithmetic, so it is widened to | ||
| 675 | // FP32 there rather than carried through as BF16. | ||
| 676 | 9 | upload_as(view, rows, cols, brotensor::compute_dtype(), dst); | |
| 677 | 9 | } | |
| 678 | |||
| 679 | 4 | void upload_compute_checked(const TensorView& view, int rows, int cols, | |
| 680 | brotensor::Tensor& dst, const std::string& name) { | ||
| 681 | 4 | if (view.dtype != Dtype::F16 && view.dtype != Dtype::F32 && | |
| 682 | 2 | view.dtype != Dtype::BF16) { | |
| 683 | 3 | throw std::runtime_error( | |
| 684 | 1 | name + " ('" + view.name + "'): expected F16, F32, or BF16, got " + | |
| 685 | 1 | dtype_name(view.dtype)); | |
| 686 | } | ||
| 687 | 3 | const int64_t expected = | |
| 688 | 3 | static_cast<int64_t>(rows) * static_cast<int64_t>(cols); | |
| 689 | 3 | if (view.numel() != expected) { | |
| 690 | 2 | throw std::runtime_error( | |
| 691 | 2 | name + " ('" + view.name + "'): shape mismatch (expected " + | |
| 692 | 3 | std::to_string(rows) + "x" + std::to_string(cols) + ", got " + | |
| 693 | 2 | std::to_string(view.numel()) + " elements)"); | |
| 694 | } | ||
| 695 | 2 | upload_compute(view, rows, cols, dst); | |
| 696 | 4 | } | |
| 697 | |||
| 698 | // ─── Writer ──────────────────────────────────────────────────────────────── | ||
| 699 | |||
| 700 | namespace { | ||
| 701 | |||
| 702 | 39 | const char* dtype_safetensors_name(Dtype d) { | |
| 703 | 39 | switch (d) { | |
| 704 | 20 | case Dtype::F32: return "F32"; | |
| 705 | 5 | case Dtype::F16: return "F16"; | |
| 706 | 2 | case Dtype::BF16: return "BF16"; | |
| 707 | 1 | case Dtype::I32: return "I32"; | |
| 708 | 1 | case Dtype::I64: return "I64"; | |
| 709 | 9 | case Dtype::U8: return "U8"; | |
| 710 | 1 | case Dtype::BOOL: return "BOOL"; | |
| 711 | ✗ | default: throw std::runtime_error("safetensors::write: unsupported dtype"); | |
| 712 | } | ||
| 713 | 39 | } | |
| 714 | |||
| 715 | 39 | void json_escape_append(std::string& out, const std::string& s) { | |
| 716 | 221 | for (char c : s) { | |
| 717 | 182 | switch (c) { | |
| 718 | 1 | case '"': out += "\\\""; break; | |
| 719 | 1 | case '\\': out += "\\\\"; break; | |
| 720 | 1 | case '\n': out += "\\n"; break; | |
| 721 | 1 | case '\t': out += "\\t"; break; | |
| 722 | 1 | case '\r': out += "\\r"; break; | |
| 723 | 1 | case '\b': out += "\\b"; break; | |
| 724 | 1 | case '\f': out += "\\f"; break; | |
| 725 | default: | ||
| 726 | 175 | if (static_cast<unsigned char>(c) < 0x20) { | |
| 727 | char buf[8]; | ||
| 728 | 2 | std::snprintf(buf, sizeof(buf), "\\u%04x", | |
| 729 | 1 | static_cast<unsigned>(static_cast<unsigned char>(c))); | |
| 730 | 1 | out += buf; | |
| 731 | 1 | } else { | |
| 732 | 174 | out += c; | |
| 733 | } | ||
| 734 | 175 | } | |
| 735 | } | ||
| 736 | 39 | } | |
| 737 | |||
| 738 | } // namespace | ||
| 739 | |||
| 740 | 29 | void write_file(const std::string& path, const std::vector<WriteEntry>& entries) { | |
| 741 | // Validate + compute offsets. | ||
| 742 | 29 | std::vector<uint64_t> off_start(entries.size()), off_end(entries.size()); | |
| 743 | 29 | uint64_t cursor = 0; | |
| 744 | 29 | std::unordered_set<std::string> seen_names; | |
| 745 | 70 | for (std::size_t i = 0; i < entries.size(); ++i) { | |
| 746 | 48 | const WriteEntry& e = entries[i]; | |
| 747 | 48 | if (e.name.empty()) { | |
| 748 | 1 | throw std::runtime_error("safetensors::write: empty tensor name"); | |
| 749 | } | ||
| 750 | 47 | if (!seen_names.insert(e.name).second) { | |
| 751 | 3 | throw std::runtime_error("safetensors::write: duplicate tensor name '" + | |
| 752 | 1 | e.name + "'"); | |
| 753 | } | ||
| 754 | 46 | if (!e.host_data && e.bytes > 0) { | |
| 755 | 1 | throw std::runtime_error("safetensors::write: '" + e.name + "' null data"); | |
| 756 | } | ||
| 757 | 45 | int dsz = dtype_size_bytes(e.dtype); | |
| 758 | 45 | if (dsz <= 0) { | |
| 759 | 2 | throw std::runtime_error("safetensors::write: '" + e.name + "' bad dtype"); | |
| 760 | } | ||
| 761 | // Same overflow guard the reader applies in TensorView::numel() — an | ||
| 762 | // unchecked product here is signed-overflow UB, not a clean throw. | ||
| 763 | 43 | int64_t n = 1; | |
| 764 | 113 | for (int64_t d : e.shape) { | |
| 765 | 71 | if (d < 0) throw std::runtime_error("safetensors::write: '" + e.name + "' negative shape"); | |
| 766 | 70 | if (d != 0 && n > INT64_MAX / d) | |
| 767 | ✗ | throw std::runtime_error("safetensors::write: '" + e.name + "' element count overflows int64"); | |
| 768 | 70 | n *= d; | |
| 769 | } | ||
| 770 | 42 | const uint64_t n_u = static_cast<uint64_t>(n); | |
| 771 | 42 | const uint64_t dsz_u = static_cast<uint64_t>(dsz); | |
| 772 | 42 | if (n_u > std::numeric_limits<std::size_t>::max() / dsz_u) { | |
| 773 | ✗ | throw std::runtime_error("safetensors::write: '" + e.name + "' byte count overflows size_t"); | |
| 774 | } | ||
| 775 | 42 | std::size_t expected = static_cast<std::size_t>(n_u * dsz_u); | |
| 776 | 42 | if (expected != e.bytes) { | |
| 777 | 2 | throw std::runtime_error("safetensors::write: '" + e.name + | |
| 778 | 1 | "' byte count mismatch (shape=" + std::to_string(expected) + | |
| 779 | 1 | " bytes=" + std::to_string(e.bytes) + ")"); | |
| 780 | } | ||
| 781 | 41 | if (e.bytes > UINT64_MAX - cursor) { | |
| 782 | ✗ | throw std::runtime_error("safetensors::write: '" + e.name + "' offset overflows uint64"); | |
| 783 | } | ||
| 784 | 41 | off_start[i] = cursor; | |
| 785 | 41 | cursor += e.bytes; | |
| 786 | 41 | off_end[i] = cursor; | |
| 787 | 41 | } | |
| 788 | |||
| 789 | // Build JSON header. | ||
| 790 | 22 | std::string hdr; | |
| 791 | 22 | hdr.reserve(256 * entries.size() + 16); | |
| 792 | 22 | hdr += '{'; | |
| 793 | 61 | for (std::size_t i = 0; i < entries.size(); ++i) { | |
| 794 | 39 | if (i) hdr += ','; | |
| 795 | 39 | hdr += '"'; | |
| 796 | 39 | json_escape_append(hdr, entries[i].name); | |
| 797 | 39 | hdr += "\":{\"dtype\":\""; | |
| 798 | 39 | hdr += dtype_safetensors_name(entries[i].dtype); | |
| 799 | 39 | hdr += "\",\"shape\":["; | |
| 800 | 106 | for (std::size_t j = 0; j < entries[i].shape.size(); ++j) { | |
| 801 | 67 | if (j) hdr += ','; | |
| 802 | 67 | hdr += std::to_string(entries[i].shape[j]); | |
| 803 | 67 | } | |
| 804 | 39 | hdr += "],\"data_offsets\":["; | |
| 805 | 39 | hdr += std::to_string(off_start[i]); | |
| 806 | 39 | hdr += ','; | |
| 807 | 39 | hdr += std::to_string(off_end[i]); | |
| 808 | 39 | hdr += "]}"; | |
| 809 | 39 | } | |
| 810 | 22 | hdr += '}'; | |
| 811 | // Pad header to 8-byte alignment so payload tensor starts are aligned. | ||
| 812 | 85 | while ((hdr.size() % 8) != 0) hdr += ' '; | |
| 813 | |||
| 814 | 22 | uint64_t header_size = static_cast<uint64_t>(hdr.size()); | |
| 815 | |||
| 816 | // Write file. | ||
| 817 | #ifdef _WIN32 | ||
| 818 | FILE* fp = nullptr; | ||
| 819 | fopen_s(&fp, path.c_str(), "wb"); | ||
| 820 | #else | ||
| 821 | // open(..., 0644) rather than fopen: fopen requests 0666 and leans on the | ||
| 822 | // caller's umask to take the write bits back off. A process that has | ||
| 823 | // cleared its umask — a daemon, a container entrypoint — then writes a | ||
| 824 | // world-writable checkpoint, which anyone on the box can swap under us. | ||
| 825 | // Ask for 0644 outright; umask can only ever narrow it further. | ||
| 826 | 22 | const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); | |
| 827 | 22 | FILE* fp = (fd < 0) ? nullptr : ::fdopen(fd, "wb"); | |
| 828 | 22 | if (fd >= 0 && !fp) ::close(fd); // fdopen failed: the fd is still ours | |
| 829 | #endif | ||
| 830 | 22 | if (!fp) throw std::runtime_error("safetensors::write: cannot open '" + path + "'"); | |
| 831 | |||
| 832 | 21 | auto wfail = [&](const std::string& what) { | |
| 833 | ✗ | std::fclose(fp); | |
| 834 | ✗ | throw std::runtime_error("safetensors::write: " + what + " '" + path + "'"); | |
| 835 | ✗ | }; | |
| 836 | |||
| 837 | 21 | if (std::fwrite(&header_size, 1, 8, fp) != 8) wfail("header_size write failed"); | |
| 838 | 21 | if (std::fwrite(hdr.data(), 1, hdr.size(), fp) != hdr.size()) wfail("header write failed"); | |
| 839 | 59 | for (const WriteEntry& e : entries) { | |
| 840 | 38 | if (e.bytes == 0) continue; | |
| 841 | 37 | if (std::fwrite(e.host_data, 1, e.bytes, fp) != e.bytes) wfail("payload write failed"); | |
| 842 | } | ||
| 843 | 21 | std::fclose(fp); | |
| 844 | 36 | } | |
| 845 | |||
| 846 | } // namespace brotensor::safetensors | ||
| 847 |