From 61abb990abeadddf8b8e168089a8e4b2b97fa61d Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 21:05:41 +0200 Subject: [PATCH] core/format: a torch.save checkpoint beside the safetensors, read as data -- stored zip entries mapped, the pickle run by a weights-only machine that refuses any other global or opcode by name; hfget fetches a .pth that is not the weights again (Fish Audio drama-3's codec) --- core/format/checkpoint.cpp | 54 +++- core/format/checkpoint.h | 3 + core/format/torch_zip.cpp | 633 +++++++++++++++++++++++++++++++++++++ core/format/torch_zip.h | 64 ++++ scripts/hfget.sh | 7 +- spec.md | 8 + tests/hf_model_test.cpp | 35 ++ tests/torch_zip_test.cpp | 341 ++++++++++++++++++++ 8 files changed, 1142 insertions(+), 3 deletions(-) create mode 100644 core/format/torch_zip.cpp create mode 100644 core/format/torch_zip.h create mode 100644 tests/torch_zip_test.cpp diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index f195e778..fb5a4029 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -852,7 +852,10 @@ int Checkpoint::open_safetensors(const std::string& path) { RAD_TRY(meta_merge_generation_config(md, &meta_)); RAD_TRY(meta_merge_preprocessor_configs(md, &meta_)); if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_; - if (!is_file && !is_index) RAD_TRY(add_companions()); + if (!is_file && !is_index) { + RAD_TRY(add_companions()); + RAD_TRY(add_torch_files()); + } /* FP8's block, where the checkpoint states one. */ if (const char* bs = meta_.get("quantization_config.weight_block_size")) { long long r = 0, c = 0; @@ -895,6 +898,55 @@ int Checkpoint::add_companions() { return RAD_OK; } +/* PyTorch checkpoints beside the safetensors (torch_zip.h): a model whose part ships only as a + * torch.save file, such as Fish Audio drama-3's codec.pth, read as data, never unpickled. Each is + * read under `.`, in name order. A file the weights-only reader refuses (a pickled training + * state, an optimiser) is not an error of the checkpoint, only of a plugin that maps its tensors, + * which then finds them absent; the warning says why. A torch copy of the model's own weights + * (`pytorch_model*.pth`, `consolidated*.pth`) is passed over, as the safetensors are read. */ +int Checkpoint::add_torch_files() { + std::vector files; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) { + if (!de.is_regular_file(ec)) continue; + const std::string f = de.path().filename().string(); + if (f.size() <= 4 || f.compare(f.size() - 4, 4, ".pth") != 0) continue; + if (f.rfind("pytorch_model", 0) == 0 || f.rfind("consolidated", 0) == 0) continue; + files.push_back(f); + } + std::sort(files.begin(), files.end()); + for (const std::string& f : files) { + auto tz = std::make_unique(); + std::string why; + const std::string path = dir_ + "/" + f; + if (tz->open(path, &why) < 0) { + RAD_WARN("%s: not read (%s); a plugin that maps its tensors will not find them", + path.c_str(), why.c_str()); + continue; + } + const std::string prefix = f.substr(0, f.size() - 4) + "."; + for (const TorchTensor& t : tz->tensors()) { + if (index_.count(prefix + t.name)) { + RAD_ERR("%s: '%s%s' is already in the checkpoint", path.c_str(), prefix.c_str(), + t.name.c_str()); + return RAD_E_FORMAT; + } + SrcTensor s; + s.name = prefix + t.name; + s.rad_dtype = t.dtype; + s.shape = t.shape; + s.data = t.data; + s.bytes = (int64_t)t.bytes; + index_.emplace(s.name, tensors_.size()); + tensors_.push_back(std::move(s)); + } + RAD_INFO("%s: %zu tensors under '%s', read from the pickle as data", path.c_str(), + tz->tensors().size(), prefix.c_str()); + torch_.push_back(std::move(tz)); + } + return RAD_OK; +} + /* Which published quantisation this is, from quantization_config alone; import_piece checks the * tensors weight by weight, refusing a file at the first weight that disagrees. */ void Checkpoint::detect_import() { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 3846d1cb..e79bbda6 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -24,6 +24,7 @@ #include "../rad_internal.h" #include "../rad_core.h" #include "safetensors.h" +#include "torch_zip.h" #include "../text/gguf.h" #include @@ -187,6 +188,7 @@ private: int open_diffusers(); int open_sgm(); int add_companions(); + int add_torch_files(); int open_gguf(const std::string& path); void detect_import(); @@ -195,6 +197,7 @@ private: GgufFile gguf_; MetaOwn meta_; std::vector> shards_; + std::vector> torch_; std::vector tensors_; std::unordered_map index_; std::unordered_map index_shard_; /* name -> shards_ position */ diff --git a/core/format/torch_zip.cpp b/core/format/torch_zip.cpp new file mode 100644 index 00000000..8e1a0eec --- /dev/null +++ b/core/format/torch_zip.cpp @@ -0,0 +1,633 @@ +/* torch_zip.cpp -- the zip directory and the weights-only pickle machine (torch_zip.h). */ +#include "torch_zip.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace { + +/* ================================================================== the zip directory */ +struct Entry { + const uint8_t* data = nullptr; + uint64_t bytes = 0; +}; + +uint16_t u16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); } +uint32_t u32(const uint8_t* p) { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +uint64_t u64(const uint8_t* p) { return (uint64_t)u32(p) | ((uint64_t)u32(p + 4) << 32); } + +/* Every stored entry, by name. torch.save writes ZIP64 records past 4 GiB and pads each local + * header's extra field so a storage starts 64-byte aligned, which is why the data offset is read + * from the local header rather than assumed from the central one. */ +int zip_entries(const uint8_t* b, uint64_t n, std::unordered_map* out, + std::string* why) { + auto no = [&](const std::string& w) { + *why = w; + return RAD_E_FORMAT; + }; + if (n < 22) return no("too short to be a zip archive"); + /* The end-of-central-directory record: the last signature within a comment's reach. */ + int64_t eocd = -1; + const uint64_t lo = n > 22 + 65535 ? n - 22 - 65535 : 0; + for (uint64_t at = n - 22 + 1; at-- > lo;) + if (u32(b + at) == 0x06054b50) { + eocd = (int64_t)at; + break; + } + if (eocd < 0) return no("no zip end-of-central-directory record"); + if (u16(b + eocd + 4) != 0 || u16(b + eocd + 6) != 0) return no("a multi-disk zip archive"); + uint64_t count = u16(b + eocd + 10), cd_size = u32(b + eocd + 12), cd_off = u32(b + eocd + 16); + if (count == 0xffff || cd_size == 0xffffffffu || cd_off == 0xffffffffu) { + if (eocd < 20 || u32(b + eocd - 20) != 0x07064b50) + return no("a ZIP64 archive without its end-record locator"); + const uint64_t z = u64(b + eocd - 20 + 8); + if (n < 56 || z > n - 56 || u32(b + z) != 0x06064b50) + return no("a ZIP64 end record outside the file"); + count = u64(b + z + 32); + cd_size = u64(b + z + 40); + cd_off = u64(b + z + 48); + } + if (cd_off > n || cd_size > n - cd_off) return no("the central directory lies outside the file"); + if (count > ((uint64_t)1 << 20)) return no("more than a million zip entries"); + uint64_t at = cd_off; + const uint64_t end = cd_off + cd_size; + for (uint64_t i = 0; i < count; ++i) { + if (end - at < 46 || at > end || u32(b + at) != 0x02014b50) + return no("a malformed central directory entry"); + const uint16_t flags = u16(b + at + 8), method = u16(b + at + 10); + uint64_t csize = u32(b + at + 20), usize = u32(b + at + 24); + const uint64_t nl = u16(b + at + 28), el = u16(b + at + 30), cl = u16(b + at + 32); + uint64_t loff = u32(b + at + 42); + if (46 + nl + el + cl > end - at) return no("a central directory entry runs past its end"); + const std::string name((const char*)b + at + 46, (size_t)nl); + /* The ZIP64 extra field: an 8-byte value for each 32-bit field at its maximum, in order. */ + const uint8_t* ex = b + at + 46 + nl; + for (uint64_t e = 0; e + 4 <= el;) { + const uint64_t id = u16(ex + e), sz = u16(ex + e + 2); + if (e + 4 + sz > el) return no("a malformed extra field in '" + name + "'"); + if (id == 1) { + uint64_t f = e + 4; + const uint64_t fe = e + 4 + sz; + auto take = [&](uint64_t* v) { + if (*v != 0xffffffffu) return true; + if (f + 8 > fe) return false; + *v = u64(ex + f); + f += 8; + return true; + }; + if (!take(&usize) || !take(&csize) || !take(&loff)) + return no("a short ZIP64 extra field in '" + name + "'"); + } + e += 4 + sz; + } + if (flags & 1) return no("'" + name + "' is encrypted"); + if (method != 0) + return no("'" + name + "' is compressed (method " + std::to_string(method) + + "); torch.save stores its entries, and a compressed storage cannot be mapped"); + if (csize != usize) return no("'" + name + "' is stored with two different sizes"); + if (n < 30 || loff > n - 30 || u32(b + loff) != 0x04034b50) + return no("'" + name + "' has no local header where the directory places it"); + const uint64_t data = loff + 30 + u16(b + loff + 26) + u16(b + loff + 28); + if (data > n || usize > n - data) return no("'" + name + "' runs past the end of the file"); + if (!out->emplace(name, Entry{ b + data, usize }).second) + return no("'" + name + "' is in the archive twice"); + at += 46 + nl + el + cl; + } + return RAD_OK; +} + +/* ================================================================== the pickle machine */ +/* A value of the weights-only subset. Containers hold indices into the machine's pool, so a value + * reached twice through the memo is one value. */ +struct V { + enum K : uint8_t { None, Bool, Int, Float, Str, Bytes, Tuple, List, Dict, Global, Storage, + Tensor } k = None; + int64_t i = 0; /* Int, Bool; Storage: numel */ + double f = 0; + std::string s; /* Str, Bytes, Global's "module.name", Storage's key */ + std::vector a; /* Tuple, List; Dict: keys and values interleaved */ + uint32_t dtype = 0; /* Storage */ + std::string cls; /* Storage: its class */ + size_t storage = 0; /* Tensor */ + int64_t offset = 0; /* Tensor, in elements */ + std::vector shape, stride; /* Tensor */ +}; + +/* The storages torch writes a state dict's tensors into, and the dtype each holds. Doubles and + * complex storages have no RAD dtype and are refused by name where they appear. */ +uint32_t storage_dtype(const std::string& g) { + static const struct { const char* name; uint32_t dt; } kS[] = { + { "torch.FloatStorage", RAD_F32 }, { "torch.HalfStorage", RAD_F16 }, + { "torch.BFloat16Storage", RAD_BF16 }, { "torch.LongStorage", RAD_I64 }, + { "torch.IntStorage", RAD_I32 }, { "torch.ShortStorage", RAD_I16 }, + { "torch.CharStorage", RAD_I8 }, { "torch.ByteStorage", RAD_U8 }, + { "torch.BoolStorage", RAD_BOOL }, + }; + for (const auto& s : kS) + if (g == s.name) return s.dt; + return RAD_DT_INVALID; +} + +/* torch's weights-only allow-list, the part a state dict uses. */ +bool allowed_global(const std::string& g) { + return g == "collections.OrderedDict" || g == "torch._utils._rebuild_tensor_v2" || + g == "torch._utils._rebuild_parameter" || storage_dtype(g) != RAD_DT_INVALID; +} + +class Machine { +public: + Machine(const uint8_t* p, uint64_t n) : p_(p), n_(n) {} + + /* The pickle's result, or a negative status with `why`. */ + int run(size_t* result, std::string* why); + const V& at(size_t i) const { return pool_[i]; } + +private: + static constexpr size_t kMaxPool = (size_t)1 << 23; + static constexpr size_t kMaxStack = (size_t)1 << 20; + static constexpr uint64_t kMaxStr = (uint64_t)1 << 20; + + int no(const std::string& w) { + why_ = w + " at byte " + std::to_string(at_) + " of the pickle"; + return RAD_E_FORMAT; + } + bool need(uint64_t k) const { return n_ - at_ >= k; } + size_t add(V v) { + pool_.push_back(std::move(v)); + return pool_.size() - 1; + } + bool pop(size_t* v) { + if (stack_.size() <= (marks_.empty() ? 0 : marks_.back())) return false; + *v = stack_.back(); + stack_.pop_back(); + return true; + } + /* The items above the last mark, and the mark gone. */ + bool pop_mark(std::vector* items) { + if (marks_.empty()) return false; + const size_t m = marks_.back(); + marks_.pop_back(); + items->assign(stack_.begin() + (std::ptrdiff_t)m, stack_.end()); + stack_.resize(m); + return true; + } + int push(size_t v) { + if (stack_.size() >= kMaxStack || pool_.size() >= kMaxPool) + return no("the pickle builds more than its bounds allow"); + stack_.push_back(v); + return RAD_OK; + } + int str(uint64_t len, V::K k) { + if (len > kMaxStr || !need(len)) return no("a string past its bound or the pickle's end"); + V v; + v.k = k; + v.s.assign((const char*)p_ + at_, (size_t)len); + at_ += len; + return push(add(std::move(v))); + } + int integer(int64_t x) { + V v; + v.k = V::Int; + v.i = x; + return push(add(std::move(v))); + } + int global(const std::string& mod, const std::string& name) { + const std::string g = mod + "." + name; + if (!allowed_global(g)) + return no("the global '" + g + "', which a weights-only checkpoint does not name; " + "nothing in the file is run, so it is refused"); + V v; + v.k = V::Global; + v.s = g; + return push(add(std::move(v))); + } + int reduce(); + int persistent_id(); + + const uint8_t* p_; + uint64_t n_; + uint64_t at_ = 0; + std::vector pool_; + std::vector stack_, marks_; + std::unordered_map memo_; + std::string why_; +}; + +int Machine::persistent_id() { + size_t pid; + if (!pop(&pid)) return no("BINPERSID with nothing to read"); + const V& t = pool_[pid]; + /* ('storage', , key, location, numel) */ + if (t.k != V::Tuple || t.a.size() != 5 || pool_[t.a[0]].k != V::Str || + pool_[t.a[0]].s != "storage" || pool_[t.a[1]].k != V::Global || + pool_[t.a[2]].k != V::Str || pool_[t.a[4]].k != V::Int) + return no("a persistent id that is not a storage"); + V s; + s.k = V::Storage; + s.cls = pool_[t.a[1]].s; + s.dtype = storage_dtype(s.cls); + s.s = pool_[t.a[2]].s; + s.i = pool_[t.a[4]].i; + if (s.dtype == RAD_DT_INVALID) return no("the storage class '" + s.cls + "'"); + if (s.i < 0) return no("a storage of negative size"); + return push(add(std::move(s))); +} + +int Machine::reduce() { + size_t args, fn; + if (!pop(&args) || !pop(&fn)) return no("REDUCE without its callable and arguments"); + if (pool_[fn].k != V::Global) return no("REDUCE of something that is not a global"); + if (pool_[args].k != V::Tuple) return no("REDUCE with arguments that are not a tuple"); + const std::string g = pool_[fn].s; + const std::vector a = pool_[args].a; + if (g == "collections.OrderedDict") { + if (!a.empty()) return no("an OrderedDict built from arguments"); + V d; + d.k = V::Dict; + return push(add(std::move(d))); + } + if (g == "torch._utils._rebuild_tensor_v2") { + /* (storage, storage_offset, size, stride, requires_grad, backward_hooks[, metadata]) */ + if (a.size() < 4 || pool_[a[0]].k != V::Storage || pool_[a[1]].k != V::Int || + pool_[a[2]].k != V::Tuple || pool_[a[3]].k != V::Tuple) + return no("_rebuild_tensor_v2 with arguments that are not a tensor's"); + V t; + t.k = V::Tensor; + t.storage = a[0]; + t.offset = pool_[a[1]].i; + for (size_t d : pool_[a[2]].a) { + if (pool_[d].k != V::Int || pool_[d].i < 0) return no("a tensor size that is not one"); + t.shape.push_back(pool_[d].i); + } + for (size_t d : pool_[a[3]].a) { + if (pool_[d].k != V::Int) return no("a tensor stride that is not one"); + t.stride.push_back(pool_[d].i); + } + if (t.shape.size() != t.stride.size() || t.shape.size() > RAD_MAX_RANK) + return no("a tensor whose size and stride disagree, or of rank past " + + std::to_string(RAD_MAX_RANK)); + return push(add(std::move(t))); + } + if (g == "torch._utils._rebuild_parameter") { + /* (data, requires_grad, backward_hooks): the parameter is its tensor. */ + if (a.empty() || pool_[a[0]].k != V::Tensor) return no("_rebuild_parameter of a non-tensor"); + return push(a[0]); + } + return no("a call of '" + g + "'"); +} + +int Machine::run(size_t* result, std::string* why) { + auto fail = [&](int st) { + *why = why_; + return st; + }; + auto line = [&](std::string* out) { + const uint8_t* e = (const uint8_t*)std::memchr(p_ + at_, '\n', (size_t)(n_ - at_)); + if (!e || (uint64_t)(e - (p_ + at_)) > 4096) return false; + out->assign((const char*)p_ + at_, (size_t)(e - (p_ + at_))); + at_ = (uint64_t)(e - p_) + 1; + return true; + }; + int st = RAD_OK; + while (at_ < n_) { + const uint8_t op = p_[at_++]; + switch (op) { + case 0x80: /* PROTO */ + if (!need(1) || p_[at_] < 2 || p_[at_] > 5) return fail(no("a pickle protocol other than 2..5")); + ++at_; + break; + case 0x95: /* FRAME: a length hint */ + if (!need(8)) return fail(no("a truncated FRAME")); + at_ += 8; + break; + case 'c': { /* GLOBAL "module\nname\n" */ + std::string mod, name; + if (!line(&mod) || !line(&name)) return fail(no("a malformed GLOBAL")); + st = global(mod, name); + break; + } + case 0x93: { /* STACK_GLOBAL */ + size_t nm, md; + if (!pop(&nm) || !pop(&md) || pool_[nm].k != V::Str || pool_[md].k != V::Str) + return fail(no("STACK_GLOBAL without a module and a name")); + st = global(pool_[md].s, pool_[nm].s); + break; + } + case 'q': case 'r': case 0x94: { /* BINPUT, LONG_BINPUT, MEMOIZE */ + uint32_t k; + if (op == 'q') { + if (!need(1)) return fail(no("a truncated BINPUT")); + k = p_[at_++]; + } else if (op == 'r') { + if (!need(4)) return fail(no("a truncated LONG_BINPUT")); + k = u32(p_ + at_); + at_ += 4; + } else { + k = (uint32_t)memo_.size(); + } + if (stack_.empty()) return fail(no("a memo store with nothing to store")); + if (memo_.size() >= kMaxStack) return fail(no("a memo past its bound")); + memo_[k] = stack_.back(); + break; + } + case 'h': case 'j': { /* BINGET, LONG_BINGET */ + uint32_t k; + if (op == 'h') { + if (!need(1)) return fail(no("a truncated BINGET")); + k = p_[at_++]; + } else { + if (!need(4)) return fail(no("a truncated LONG_BINGET")); + k = u32(p_ + at_); + at_ += 4; + } + auto it = memo_.find(k); + if (it == memo_.end()) return fail(no("a memo read of an empty slot")); + st = push(it->second); + break; + } + case '(': /* MARK */ + if (marks_.size() >= kMaxStack) return fail(no("marks past their bound")); + marks_.push_back(stack_.size()); + break; + case ')': { /* EMPTY_TUPLE */ + V t; + t.k = V::Tuple; + st = push(add(std::move(t))); + break; + } + case 't': case 0x85: case 0x86: case 0x87: { /* TUPLE, TUPLE1..3 */ + V t; + t.k = V::Tuple; + if (op == 't') { + if (!pop_mark(&t.a)) return fail(no("TUPLE without a mark")); + } else { + const int k = op - 0x84; + t.a.resize((size_t)k); + for (int j = k - 1; j >= 0; --j) + if (!pop(&t.a[(size_t)j])) return fail(no("a short tuple")); + } + st = push(add(std::move(t))); + break; + } + case ']': case '}': { /* EMPTY_LIST, EMPTY_DICT */ + V c; + c.k = op == ']' ? V::List : V::Dict; + st = push(add(std::move(c))); + break; + } + case 'a': case 'e': { /* APPEND, APPENDS */ + std::vector items(1); + if (op == 'a') { + if (!pop(&items[0])) return fail(no("APPEND with nothing to append")); + } else if (!pop_mark(&items)) { + return fail(no("APPENDS without a mark")); + } + if (stack_.empty() || pool_[stack_.back()].k != V::List) + return fail(no("APPEND to something that is not a list")); + V& l = pool_[stack_.back()]; + l.a.insert(l.a.end(), items.begin(), items.end()); + break; + } + case 's': case 'u': { /* SETITEM, SETITEMS */ + std::vector kv(2); + if (op == 's') { + if (!pop(&kv[1]) || !pop(&kv[0])) return fail(no("SETITEM without a pair")); + } else if (!pop_mark(&kv) || kv.size() % 2) { + return fail(no("SETITEMS without whole pairs")); + } + if (stack_.empty() || pool_[stack_.back()].k != V::Dict) + return fail(no("a SETITEM on something that is not a dict")); + V& d = pool_[stack_.back()]; + d.a.insert(d.a.end(), kv.begin(), kv.end()); + break; + } + case 'b': { /* BUILD: an OrderedDict's state (a state dict's _metadata), ignored */ + size_t state; + if (!pop(&state)) return fail(no("BUILD without a state")); + if (stack_.empty() || pool_[stack_.back()].k != V::Dict) + return fail(no("BUILD of something other than a dict")); + break; + } + case 'X': case 0x8c: case 0x8d: case 'B': case 'C': case 0x8e: { + /* BINUNICODE, SHORT_BINUNICODE, BINUNICODE8, BINBYTES, SHORT_BINBYTES, BINBYTES8 */ + uint64_t len; + const int w = (op == 0x8c || op == 'C') ? 1 : (op == 0x8d || op == 0x8e) ? 8 : 4; + if (!need((uint64_t)w)) return fail(no("a truncated string length")); + len = w == 1 ? p_[at_] : w == 4 ? u32(p_ + at_) : u64(p_ + at_); + at_ += (uint64_t)w; + st = str(len, (op == 'B' || op == 'C' || op == 0x8e) ? V::Bytes : V::Str); + break; + } + case 'J': /* BININT */ + if (!need(4)) return fail(no("a truncated BININT")); + st = integer((int32_t)u32(p_ + at_)); + at_ += 4; + break; + case 'K': /* BININT1 */ + if (!need(1)) return fail(no("a truncated BININT1")); + st = integer(p_[at_++]); + break; + case 'M': /* BININT2 */ + if (!need(2)) return fail(no("a truncated BININT2")); + st = integer(u16(p_ + at_)); + at_ += 2; + break; + case 0x8a: { /* LONG1: little-endian two's complement of up to 8 bytes here */ + if (!need(1)) return fail(no("a truncated LONG1")); + const uint64_t k = p_[at_++]; + if (k > 8 || !need(k)) return fail(no("a LONG1 wider than 64 bits")); + uint64_t v = 0; + for (uint64_t j = 0; j < k; ++j) v |= (uint64_t)p_[at_ + j] << (8 * j); + if (k > 0 && k < 8 && (p_[at_ + k - 1] & 0x80)) v |= ~(uint64_t)0 << (8 * k); + at_ += k; + st = integer((int64_t)v); + break; + } + case 'G': { /* BINFLOAT, big-endian */ + if (!need(8)) return fail(no("a truncated BINFLOAT")); + uint64_t v = 0; + for (int j = 0; j < 8; ++j) v = (v << 8) | p_[at_ + j]; + at_ += 8; + V f; + f.k = V::Float; + std::memcpy(&f.f, &v, 8); + st = push(add(std::move(f))); + break; + } + case 0x88: case 0x89: { /* NEWTRUE, NEWFALSE */ + V v; + v.k = V::Bool; + v.i = op == 0x88; + st = push(add(std::move(v))); + break; + } + case 'N': + st = push(add(V{})); + break; + case 'Q': + st = persistent_id(); + break; + case 'R': + st = reduce(); + break; + case '.': { /* STOP */ + size_t r; + if (!pop(&r)) return fail(no("STOP with nothing to return")); + *result = r; + return RAD_OK; + } + default: { + char hex[8]; + std::snprintf(hex, sizeof hex, "0x%02x", op); + return fail(no(std::string("the opcode ") + hex + + ", which a weights-only checkpoint does not use")); + } + } + if (st < 0) return fail(st); + } + return fail(no("no STOP before the pickle's end")); +} + +/* A state dict's tensors, nested dicts flattened to dotted names. */ +void walk(const Machine& m, size_t d, const std::string& prefix, + std::vector>* out) { + const V& v = m.at(d); + for (size_t j = 0; j + 1 < v.a.size(); j += 2) { + const V& k = m.at(v.a[j]); + if (k.k != V::Str) continue; + const V& x = m.at(v.a[j + 1]); + if (x.k == V::Tensor) out->emplace_back(prefix + k.s, v.a[j + 1]); + else if (x.k == V::Dict) walk(m, v.a[j + 1], prefix + k.s + ".", out); + } +} + +} /* namespace */ + +/* ================================================================== the file */ +TorchZipFile::~TorchZipFile() { close(); } + +void TorchZipFile::close() { + if (map_) ::munmap(map_, (size_t)bytes_); + if (fd_ >= 0) ::close(fd_); + map_ = nullptr; + base_ = nullptr; + bytes_ = 0; + fd_ = -1; + tensors_.clear(); +} + +int TorchZipFile::open(const std::string& path, std::string* why) { + close(); + path_ = path; + fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd_ < 0) { + *why = std::strerror(errno); + return RAD_E_IO; + } + struct stat st{}; + if (::fstat(fd_, &st) != 0) { + *why = std::strerror(errno); + close(); + return RAD_E_IO; + } + bytes_ = (uint64_t)st.st_size; + void* m = bytes_ ? ::mmap(nullptr, (size_t)bytes_, PROT_READ, MAP_PRIVATE, fd_, 0) : MAP_FAILED; + if (m == MAP_FAILED) { + *why = bytes_ ? std::string("mmap: ") + std::strerror(errno) : std::string("empty file"); + close(); + return bytes_ ? RAD_E_IO : RAD_E_FORMAT; + } + map_ = (uint8_t*)m; + base_ = map_; + const int s = parse(why); + if (s < 0) close(); + return s; +} + +int TorchZipFile::open_bytes(const uint8_t* data, uint64_t bytes, std::string* why) { + close(); + path_ = "(memory)"; + base_ = data; + bytes_ = bytes; + return parse(why); +} + +int TorchZipFile::parse(std::string* why) { + std::unordered_map ent; + RAD_TRY(zip_entries(base_, bytes_, &ent, why)); + /* The archive's one directory: the one holding data.pkl. */ + std::string dir; + int n_pkl = 0; + for (const auto& [name, e] : ent) { + const size_t sl = name.find('/'); + if (sl != std::string::npos && name.compare(sl, std::string::npos, "/data.pkl") == 0) { + dir = name.substr(0, sl + 1); + ++n_pkl; + } + } + if (n_pkl != 1) { + *why = n_pkl ? "more than one data.pkl" : "no /data.pkl: not a torch.save checkpoint"; + return RAD_E_FORMAT; + } + if (auto it = ent.find(dir + "byteorder"); it != ent.end() && + std::string((const char*)it->second.data, (size_t)it->second.bytes) != "little") { + *why = "a big-endian checkpoint"; + return RAD_E_FORMAT; + } + const Entry& pk = ent[dir + "data.pkl"]; + Machine m(pk.data, pk.bytes); + size_t root = 0; + RAD_TRY(m.run(&root, why)); + if (m.at(root).k != V::Dict) { + *why = "the pickle's result is not a state dict"; + return RAD_E_FORMAT; + } + std::vector> found; + walk(m, root, "", &found); + for (const auto& [name, ti] : found) { + const V& t = m.at(ti); + const V& s = m.at(t.storage); + auto it = ent.find(dir + "data/" + s.s); + if (it == ent.end()) { + *why = "'" + name + "' reads storage '" + s.s + "', which the archive does not hold"; + return RAD_E_FORMAT; + } + const int64_t esz = (int64_t)rad_dtype_bits(s.dtype) / 8; + int64_t numel = 1, want = 1; + bool contig = true; + for (size_t d = t.shape.size(); d-- > 0;) { + if (t.shape[d] != 1 && t.stride[d] != want) contig = false; + want *= t.shape[d]; + numel *= t.shape[d]; + } + if (!contig) { + *why = "'" + name + "' is not contiguous in its storage"; + return RAD_E_FORMAT; + } + if (t.offset < 0 || numel > s.i - t.offset || + (uint64_t)((t.offset + numel) * esz) > it->second.bytes) { + *why = "'" + name + "' does not fit its storage '" + s.s + "'"; + return RAD_E_FORMAT; + } + if (numel == 0) continue; + TorchTensor tt; + tt.name = name; + tt.dtype = s.dtype; + tt.storage = s.cls; + tt.shape = t.shape; + tt.data = it->second.data + t.offset * esz; + tt.bytes = (uint64_t)(numel * esz); + tensors_.push_back(std::move(tt)); + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/format/torch_zip.h b/core/format/torch_zip.h new file mode 100644 index 00000000..a0ef7d1a --- /dev/null +++ b/core/format/torch_zip.h @@ -0,0 +1,64 @@ +/* torch_zip.h -- a PyTorch checkpoint (torch.save's zip format) as tensors, read without running + * any of its pickle. + * + * A .pth from torch.save is a zip archive of stored entries: `/data.pkl`, a pickle of the + * state dict whose tensors name their bytes by a persistent id, `/data/` holding + * each storage's raw little-endian bytes, and `/byteorder`. Fish Audio's codec ships this + * way (drama-3's codec.pth), with no safetensors copy. + * + * Unpickling would run whatever the file names. This reads the pickle as data instead: a small + * machine over the opcodes a weights-only file uses, whose only callables are the ones torch's own + * `weights_only` loader allows a state dict (collections.OrderedDict, + * torch._utils._rebuild_tensor_v2 and _rebuild_parameter) and whose only classes are the typed + * storages. Any other global, any other opcode, a compressed or encrypted entry, or a storage that + * does not hold its tensor is refused by name. Every read is bounds-checked and the machine's + * stack, memo and object counts are capped. + * + * Storages are mmapped, not copied; a tensor must be contiguous in its storage. Nested dicts + * flatten to dotted names, and values that are not tensors (an epoch count) are skipped. + */ +#pragma once +#include "../rad_internal.h" + +#include +#include + +namespace rad { + +struct TorchTensor { + std::string name; + uint32_t dtype = RAD_DT_INVALID; + std::string storage; /* the torch storage class, for diagnostics */ + std::vector shape; /* row-major */ + const uint8_t* data = nullptr; + uint64_t bytes = 0; +}; + +class TorchZipFile { +public: + TorchZipFile() = default; + ~TorchZipFile(); + TorchZipFile(const TorchZipFile&) = delete; + TorchZipFile& operator=(const TorchZipFile&) = delete; + + /* RAD_OK, or a negative RAD_E_* with `why` saying what was refused. */ + int open(const std::string& path, std::string* why); + /* The same over bytes the caller keeps alive (a test's archive in memory). */ + int open_bytes(const uint8_t* data, uint64_t bytes, std::string* why); + void close(); + + const std::vector& tensors() const { return tensors_; } + const std::string& path() const { return path_; } + +private: + int parse(std::string* why); + + int fd_ = -1; + uint8_t* map_ = nullptr; + const uint8_t* base_ = nullptr; + uint64_t bytes_ = 0; + std::string path_; + std::vector tensors_; +}; + +} /* namespace rad */ diff --git a/scripts/hfget.sh b/scripts/hfget.sh index 62d9d6fb..1951cd0d 100755 --- a/scripts/hfget.sh +++ b/scripts/hfget.sh @@ -20,7 +20,10 @@ # earlier copy on 3 and refuses on the rest. # # Duplicate weight formats are skipped: when the listing holds any .safetensors, other weight -# formats (pickle .bin, ONNX, GGUF, ...) are not fetched. +# formats (pickle .bin, ONNX, GGUF, ...) are not fetched. A .pth is a duplicate only when it is the +# model's own weights again (`pytorch_model*.pth`, `consolidated*.pth`); any other is a part the +# safetensors do not hold (Fish Audio drama-3's codec.pth) and is fetched, as the checkpoint reader +# reads it (core/format/torch_zip.h). # # HFGET_JOBS concurrent transfers, default 4. These are long sequential reads: a few streams # saturate the link and more only make the destination seek. @@ -107,7 +110,7 @@ done echo "hfget: $page page(s) of listing" have_st=$(printf '%s' "$listing" | jq '[.[] | select(.path | endswith(".safetensors"))] | length') sel='.[] | select(.type == "file")' -[ "$have_st" -gt 0 ] && sel="$sel"' | select((.path | test("\\.(bin|pth|msgpack|h5|onnx|onnx_data|gguf)$")) | not)' +[ "$have_st" -gt 0 ] && sel="$sel"' | select((.path | test("\\.(bin|msgpack|h5|onnx|onnx_data|gguf)$") or test("(^|/)(pytorch_model|consolidated)[^/]*\\.pth$")) | not)' list=$(mktemp "${TMPDIR:-/tmp}/hfget.XXXXXX") trap 'rm -f "$list" "$dest/.hfget-manifest.tmp"' EXIT INT TERM diff --git a/spec.md b/spec.md index 1ace7bff..52a4e17f 100644 --- a/spec.md +++ b/spec.md @@ -637,6 +637,14 @@ same path runs. Trivial means served as stored: `fp4_e2m1*e8m0[1x32]`, byte for byte; - GGUF `F32`, `F16` and `BF16`. +**A torch.save file beside the safetensors is read as data** (`core/format/torch_zip.h`), for a +model part that ships only that way (Fish Audio drama-3's `codec.pth`): its tensors join the +namespace under `.`. The zip's stored entries are mapped, and its pickle is read by a machine +over the weights-only subset (the state dict's `OrderedDict`, `_rebuild_tensor_v2`, +`_rebuild_parameter` and the typed storages), so nothing in the file runs; any other global or +opcode is refused by name, and the file is then left out with a warning. A torch copy of the +model's own weights (`pytorch_model*.pth`, `consolidated*.pth`) is passed over. + **Nothing is quantised at load.** A served form that needs quantisation (Flash-Next's int4 experts, an fp8 `lm_head` from a bf16 one) is converted ahead of time (ยง4.4). A direct load has no file tier, no mapped tier (a checkpoint is neither grouped by movement unit nor aligned for diff --git a/tests/hf_model_test.cpp b/tests/hf_model_test.cpp index 512d1547..0990868a 100644 --- a/tests/hf_model_test.cpp +++ b/tests/hf_model_test.cpp @@ -219,6 +219,41 @@ TEST(a_restart_serves_the_complete_copy_when_the_hub_cannot_be_reached) { } } +/* A hub whose repo holds safetensors beside a torch copy of the same weights and a codec that only + * ships as a .pth: the copies (pytorch_model*.pth, a pickle .bin) are skipped, the codec is + * fetched, since the checkpoint reader reads it (core/format/torch_zip.h). */ +const char* kCodecRepo = + "#!/bin/sh\n" + "out=''; url=''; prev=''\n" + "for a in \"$@\"; do\n" + " [ \"$prev\" = -o ] && out=\"$a\"\n" + " case \"$a\" in https://*) url=\"$a\";; esac\n" + " prev=\"$a\"\n" + "done\n" + "case \"$url\" in *api/models*)\n" + " printf '[{\"type\":\"file\",\"path\":\"model.safetensors\",\"size\":3}," + "{\"type\":\"file\",\"path\":\"codec.pth\",\"size\":3}," + "{\"type\":\"file\",\"path\":\"pytorch_model.pth\",\"size\":3}," + "{\"type\":\"file\",\"path\":\"pytorch_model.bin\",\"size\":3}]'; exit 0;; esac\n" + "[ -n \"$out\" ] && printf abc > \"$out\"\n" + "exit 0\n"; + +TEST(a_pth_that_is_not_the_weights_again_is_fetched_beside_the_safetensors) { + NEED_ARTIFACT(hfget_beside_this_binary()); + if (!on_path("jq")) SKIP("no jq on PATH, which hfget.sh needs"); + TempDir root; + REQUIRE(!root.path.empty()); + FakeCurl curl(kCodecRepo); + const std::string cmd = "sh '" + hfget_beside_this_binary() + + "' radiance-test-owner/radiance-test-model '" + root.path + + "' >/dev/null 2>&1"; + CHECK_EQ(std::system(cmd.c_str()), 0); + CHECK(fs::exists(root.path + "/model.safetensors")); + CHECK(fs::exists(root.path + "/codec.pth")); + CHECK(!fs::exists(root.path + "/pytorch_model.pth")); + CHECK(!fs::exists(root.path + "/pytorch_model.bin")); +} + /* With no --download-dir and neither XDG_CACHE_HOME nor HOME there is nowhere to fetch to, which * is refused by name before anything runs. */ TEST(a_repo_id_with_nowhere_to_fetch_to_is_refused) { diff --git a/tests/torch_zip_test.cpp b/tests/torch_zip_test.cpp new file mode 100644 index 00000000..edafee81 --- /dev/null +++ b/tests/torch_zip_test.cpp @@ -0,0 +1,341 @@ +/* torch_zip_test.cpp -- a PyTorch checkpoint read as data (core/format/torch_zip.h). + * + * Each case writes a torch.save archive the way torch lays one out (stored zip entries, a protocol + * 2 pickle of the state dict naming its storages by persistent id) with a small writer of the same + * subset, then reads it back: the tensors' names, dtypes, shapes and bytes, a nested dict, a + * parameter, a ZIP64 directory. The refusals are the point as much as the reads: a global outside + * the weights-only allow-list (the shape every malicious pickle has), an opcode it does not use, a + * compressed or truncated entry and a tensor its storage does not hold are each refused by name, + * with nothing run. + * + * RAD_TEST_TORCH_PTH, when set, names a real checkpoint (Fish Audio's codec.pth) that is opened as + * well; the case is skipped without it. + */ +#include "rad_test.h" +#include "format/torch_zip.h" +#include "format/checkpoint.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rad; + +namespace { + +/* ------------------------------------------------------------------ the pickle */ +struct Pkl { + std::string b; + void op(char c) { b += c; } + void u32(uint32_t v) { for (int i = 0; i < 4; ++i) b += (char)((v >> (8 * i)) & 0xff); } + void str(const std::string& s) { op('X'); u32((uint32_t)s.size()); b += s; } + void global(const std::string& mod, const std::string& name) { op('c'); b += mod + "\n" + name + "\n"; } + void integer(int64_t v) { + if (v >= 0 && v < 256) { op('K'); b += (char)v; } + else { op('J'); u32((uint32_t)(int32_t)v); } + } + void tuple_of(const std::vector& v) { op('('); for (int64_t x : v) integer(x); op('t'); } + void ordered_dict() { global("collections", "OrderedDict"); op(')'); op('R'); } +}; + +struct Tensor { + std::string name, storage_cls, key; + std::vector shape, stride; + int64_t offset = 0, numel = 0; /* the storage's elements */ + bool parameter = false; +}; + +/* One tensor's _rebuild_tensor_v2 call, optionally wrapped as a parameter. */ +void put_tensor(Pkl& p, const Tensor& t, const std::string& storage_mod = "torch") { + if (t.parameter) p.global("torch._utils", "_rebuild_parameter"); + p.global("torch._utils", "_rebuild_tensor_v2"); + p.op('('); + p.op('('); + p.str("storage"); + p.global(storage_mod, t.storage_cls); + p.str(t.key); + p.str("cpu"); + p.integer(t.numel); + p.op('t'); + p.op('Q'); + p.integer(t.offset); + p.tuple_of(t.shape); + p.tuple_of(t.stride); + p.op((char)0x89); /* requires_grad False */ + p.ordered_dict(); + p.op('t'); + p.op('R'); + if (t.parameter) { + /* (tensor, requires_grad, hooks): the tensor is below; build the argument tuple around it. */ + p.op((char)0x89); + p.ordered_dict(); + p.op((char)0x87); /* TUPLE3 */ + p.op('R'); + } +} + +/* A state dict of `ts`, and `nested` under "generator." as a second dict. */ +std::string state_dict(const std::vector& ts, const std::vector& nested = {}) { + Pkl p; + p.op((char)0x80); + p.b += (char)2; + p.ordered_dict(); + p.op('('); + for (const Tensor& t : ts) { + p.str(t.name); + put_tensor(p, t); + } + if (!nested.empty()) { + p.str("generator"); + p.ordered_dict(); + p.op('('); + for (const Tensor& t : nested) { + p.str(t.name); + put_tensor(p, t); + } + p.op('u'); + } + p.str("epoch"); /* a value that is not a tensor: skipped */ + p.integer(7); + p.op('u'); + /* The state dict's _metadata, as torch writes it: BUILD with a dict state. */ + p.op('}'); + p.op('b'); + p.op('.'); + return p.b; +} + +/* ------------------------------------------------------------------ the zip */ +struct ZipEntry { std::string name, data; uint16_t method = 0; }; + +void le(std::string* s, uint64_t v, int bytes) { + for (int i = 0; i < bytes; ++i) s->push_back((char)((v >> (8 * i)) & 0xff)); +} + +/* Stored entries, each local header's extra field padded so the data starts 64-byte aligned (as + * torch.save aligns storages), then the central directory, ZIP64 records when asked. */ +std::string zip_of(const std::vector& es, bool zip64 = false) { + std::string out, cd; + for (const ZipEntry& e : es) { + const uint64_t off = out.size(); + const uint64_t base = off + 30 + e.name.size() + 4; + const uint64_t pad = (64 - base % 64) % 64; + le(&out, 0x04034b50, 4); le(&out, 20, 2); le(&out, 0, 2); le(&out, e.method, 2); + le(&out, 0, 4); le(&out, 0, 4); + le(&out, e.data.size(), 4); le(&out, e.data.size(), 4); + le(&out, e.name.size(), 2); le(&out, 4 + pad, 2); + out += e.name; + le(&out, 0xcafe, 2); le(&out, pad, 2); out.append((size_t)pad, '\0'); + out += e.data; + std::string ex; + uint32_t loff32 = (uint32_t)off; + if (zip64) { + le(&ex, 1, 2); le(&ex, 8, 2); le(&ex, off, 8); + loff32 = 0xffffffffu; + } + le(&cd, 0x02014b50, 4); le(&cd, 45, 2); le(&cd, 45, 2); le(&cd, 0, 2); le(&cd, e.method, 2); + le(&cd, 0, 4); le(&cd, 0, 4); + le(&cd, e.data.size(), 4); le(&cd, e.data.size(), 4); + le(&cd, e.name.size(), 2); le(&cd, ex.size(), 2); le(&cd, 0, 2); + le(&cd, 0, 2); le(&cd, 0, 2); le(&cd, 0, 4); le(&cd, loff32, 4); + cd += e.name + ex; + } + const uint64_t cd_off = out.size(); + out += cd; + if (zip64) { + const uint64_t z = out.size(); + le(&out, 0x06064b50, 4); le(&out, 44, 8); le(&out, 45, 2); le(&out, 45, 2); + le(&out, 0, 4); le(&out, 0, 4); le(&out, es.size(), 8); le(&out, es.size(), 8); + le(&out, cd.size(), 8); le(&out, cd_off, 8); + le(&out, 0x07064b50, 4); le(&out, 0, 4); le(&out, z, 8); le(&out, 1, 4); + } + le(&out, 0x06054b50, 4); le(&out, 0, 2); le(&out, 0, 2); + le(&out, zip64 ? 0xffff : es.size(), 2); le(&out, zip64 ? 0xffff : es.size(), 2); + le(&out, zip64 ? 0xffffffffu : cd.size(), 4); le(&out, zip64 ? 0xffffffffu : cd_off, 4); + le(&out, 0, 2); + return out; +} + +std::string floats(std::initializer_list v) { + std::string s(v.size() * 4, '\0'); + std::memcpy(s.data(), v.begin(), s.size()); + return s; +} + +/* The archive of `pkl` with the storages "0" and "1": 6 and 4 floats. */ +std::string archive(const std::string& pkl, bool zip64 = false, uint16_t method = 0) { + return zip_of({ { "ck/data.pkl", pkl, method }, { "ck/byteorder", "little" }, + { "ck/data/0", floats({ 1, 2, 3, 4, 5, 6 }) }, + { "ck/data/1", floats({ 7, 8, 9, 10 }) } }, + zip64); +} + +std::vector two() { + return { Tensor{ "a.weight", "FloatStorage", "0", { 2, 3 }, { 3, 1 }, 0, 6 }, + Tensor{ "a.bias", "FloatStorage", "1", { 2 }, { 1 }, 2, 4, true } }; +} + +const TorchTensor* by_name(const TorchZipFile& f, const std::string& n) { + for (const TorchTensor& t : f.tensors()) + if (t.name == n) return &t; + return nullptr; +} + +float f32_at(const TorchTensor& t, int i) { + float v; + std::memcpy(&v, t.data + 4 * i, 4); + return v; +} + +} /* namespace */ + +/* The tensors as torch.save wrote them: names, dtype, shape, the bytes at the storage offset, a + * parameter's tensor, a nested dict's names dotted and an integer skipped; in a plain and a ZIP64 + * directory. */ +TEST(a_state_dict_reads_back_as_its_tensors) { + for (bool z64 : { false, true }) { + const std::string bytes = archive(state_dict(two(), { Tensor{ "x", "FloatStorage", "0", + { 3 }, { 1 }, 3, 6 } }), + z64); + TorchZipFile f; + std::string why; + REQUIRE_EQ(f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why), (int)RAD_OK); + CHECK_EQ(f.tensors().size(), (size_t)3); + const TorchTensor* w = by_name(f, "a.weight"); + REQUIRE(w != nullptr); + CHECK_EQ(w->dtype, (uint32_t)RAD_F32); + CHECK(w->shape == std::vector({ 2, 3 })); + CHECK_EQ(w->bytes, (uint64_t)24); + CHECK_EQ(f32_at(*w, 5), 6.0f); + CHECK_EQ((uintptr_t)w->data % 64, (uintptr_t)bytes.data() % 64); /* mapped in place */ + const TorchTensor* bias = by_name(f, "a.bias"); + REQUIRE(bias != nullptr); + CHECK_EQ(f32_at(*bias, 0), 9.0f); /* storage 1 from element 2 */ + CHECK_EQ(f32_at(*bias, 1), 10.0f); + const TorchTensor* x = by_name(f, "generator.x"); + REQUIRE(x != nullptr); + CHECK_EQ(f32_at(*x, 0), 4.0f); + } +} + +/* What a malicious or foreign file holds is refused by name before anything is read past it: a + * global outside the allow-list (os.system, builtins.eval), a storage class that is not one, an + * opcode the subset does not use, a compressed entry, a pickle cut short, and a tensor that runs + * past its storage or is not contiguous in it. */ +TEST(anything_outside_the_weights_only_subset_is_refused_by_name) { + auto refused = [](const std::string& bytes, const char* want) { + TorchZipFile f; + std::string why; + const int st = f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why); + CHECK(st < 0); + CHECK(has(why, want)); + if (!has(why, want)) std::fprintf(stderr, " want %s, why: %s\n", want, why.c_str()); + }; + { + Pkl p; + p.op((char)0x80); p.b += (char)2; + p.global("os", "system"); + p.op('('); p.str("echo pwned"); p.op('t'); p.op('R'); p.op('.'); + refused(archive(p.b), "'os.system'"); + } + { + Pkl p; + p.op((char)0x80); p.b += (char)2; + p.str("builtins"); p.str("eval"); p.op((char)0x93); + p.op('.'); + refused(archive(p.b), "'builtins.eval'"); + } + { + std::vector ts = two(); + ts[0].storage_cls = "DoubleStorage"; + refused(archive(state_dict(ts)), "torch.DoubleStorage"); + } + { + std::string pk = state_dict(two()); + pk.insert(pk.size() - 1, 1, 'i'); /* INST, an old way to build any object */ + refused(archive(pk), "opcode 0x69"); + } + refused(archive(state_dict(two()), false, 8), "compressed"); + { + const std::string pk = state_dict(two()); + refused(archive(pk.substr(0, pk.size() / 2)), "pickle"); + } + { + std::vector ts = two(); + ts[1].shape = { 3 }; /* three floats from element 2 of a 4-float storage */ + refused(archive(state_dict(ts)), "does not fit its storage"); + } + { + std::vector ts = two(); + ts[0].stride = { 1, 2 }; /* a transposed view */ + refused(archive(state_dict(ts)), "not contiguous"); + } + refused(zip_of({ { "data.pkl", state_dict(two()) } }), "no /data.pkl"); + refused(std::string("PK\x03\x04 is a local header, and this is not an archive"), + "end-of-central-directory"); +} + +/* A .pth beside the safetensors joins the checkpoint under its stem, so a plugin maps + * `codec.`; a torch copy of the model's own weights is passed over, and a file the reader + * refuses is left out with a warning rather than failing the checkpoint. */ +TEST(a_pth_beside_the_safetensors_joins_the_checkpoint_under_its_stem) { + std::string d = radtest::tmp_path("tz.XXXXXX"); + REQUIRE(mkdtemp(d.data()) != nullptr); + auto write = [&](const std::string& name, const std::string& bytes) { + FILE* f = std::fopen((d + "/" + name).c_str(), "wb"); + REQUIRE(f != nullptr); + std::fwrite(bytes.data(), 1, bytes.size(), f); + std::fclose(f); + }; + /* A one-tensor safetensors model and its config. */ + { + std::string hdr = "{\"w\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}"; + while (hdr.size() % 8) hdr += ' '; + std::string st; + le(&st, hdr.size(), 8); + st += hdr + floats({ 1 }); + write("model.safetensors", st); + write("config.json", "{\"model_type\": \"tiny\"}"); + } + write("codec.pth", archive(state_dict(two()))); + write("pytorch_model.pth", archive(state_dict(two()))); + { + Pkl p; + p.op((char)0x80); p.b += (char)2; + p.global("os", "system"); + p.op('.'); + write("optimizer.pth", archive(p.b)); + } + Checkpoint ck; + REQUIRE_EQ(ck.open(d), (int)RAD_OK); + CHECK(ck.find("w") != nullptr); + const SrcTensor* w = ck.find("codec.a.weight"); + REQUIRE(w != nullptr); + CHECK_EQ(w->rad_dtype, (uint32_t)RAD_F32); + CHECK(w->shape == std::vector({ 2, 3 })); + CHECK(ck.find("codec.a.bias") != nullptr); + CHECK(ck.find("pytorch_model.a.weight") == nullptr); + CHECK(ck.find("optimizer.a.weight") == nullptr); + std::filesystem::remove_all(d); +} + +/* A real torch.save checkpoint, when one is named: every tensor's bytes inside the file. */ +TEST(a_real_checkpoint_named_by_the_environment_reads) { + const char* p = std::getenv("RAD_TEST_TORCH_PTH"); + if (!p || !*p) SKIP("RAD_TEST_TORCH_PTH names no checkpoint"); + TorchZipFile f; + std::string why; + REQUIRE_EQ(f.open(p, &why), (int)RAD_OK); + CHECK(!f.tensors().empty()); + uint64_t bytes = 0; + for (const TorchTensor& t : f.tensors()) bytes += t.bytes; + std::fprintf(stderr, " %s: %zu tensors, %.1f MiB\n", p, f.tensors().size(), + (double)bytes / (1 << 20)); +} + +RAD_TEST_MAIN()