MCPcopy Create free account
hub / github.com/0xShug0/audio.cpp / write_safetensors_file

Function write_safetensors_file

src/framework/io/safetensors.cpp:352–411  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

350 if (pos < header.size() && header[pos] == '}') {
351 ++pos;
352 break;
353 }
354 }
355
356 return index;
357}
358
359void write_safetensors_file(
360 const std::filesystem::path & path,
361 const std::vector<SafeTensorWriteEntry> & entries) {
362 if (entries.empty()) {
363 throw std::runtime_error("safetensors writer requires at least one tensor");
364 }
365
366 std::unordered_set<std::string> names;
367 std::vector<std::pair<size_t, size_t>> offsets;
368 offsets.reserve(entries.size());
369 size_t cursor = 0;
370 for (const auto & entry : entries) {
371 if (entry.name.empty() || entry.dtype.empty()) {
372 throw std::runtime_error("safetensors writer received an unnamed tensor or dtype");
373 }
374 if (!names.insert(entry.name).second) {
375 throw std::runtime_error("safetensors writer received duplicate tensor: " + entry.name);
376 }
377 for (int64_t dim : entry.shape) {
378 if (dim < 0) {
379 throw std::runtime_error("safetensors writer received negative shape dimension: " + entry.name);
380 }
381 }
382 offsets.emplace_back(cursor, cursor + entry.data.size());
383 cursor += entry.data.size();
384 }
385
386 std::ostringstream header_stream;
387 header_stream << "{";
388 for (size_t i = 0; i < entries.size(); ++i) {
389 if (i != 0) {
390 header_stream << ",";
391 }
392 header_stream << "\"" << escape_json_string(entries[i].name) << "\":{";
393 header_stream << "\"dtype\":\"" << escape_json_string(entries[i].dtype) << "\",";
394 header_stream << "\"shape\":" << shape_to_json(entries[i].shape) << ",";
395 header_stream << "\"data_offsets\":[" << offsets[i].first << "," << offsets[i].second << "]";
396 header_stream << "}";
397 }
398 header_stream << "}";
399
400 std::string header = header_stream.str();
401 header.append((8 - (header.size() % 8)) % 8, ' ');
402
403 const auto parent = path.parent_path();
404 if (!parent.empty()) {
405 std::filesystem::create_directories(parent);
406 }
407 std::ofstream output(path, std::ios::binary | std::ios::trunc);
408 if (!output) {
409 throw std::runtime_error("failed to open safetensors output file: " + path.string());

Callers 1

save_voice_state_assetsFunction · 0.85

Calls 8

escape_json_stringFunction · 0.85
shape_to_jsonFunction · 0.85
write_u64_leFunction · 0.85
strMethod · 0.80
emptyMethod · 0.45
sizeMethod · 0.45
writeMethod · 0.45
dataMethod · 0.45

Tested by

no test coverage detected