okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
8.6 KiB210 linesraw
1// src/image/vae/safetensors_lite.hpp - read the tensor table of a .safetensors file (the format: an 8-byte little-endian
2// header length, a JSON object {name: {"dtype", "shape", "data_offsets": [begin, end]}, "__metadata__": {...}}, then the
3// data).  Only what a model file of ours needs: string keys, the three fields above, numbers and arrays of numbers; the
4// "__metadata__" object is skipped.  No third-party JSON code.  Header-only, host-only.
5#pragma once
6
7#include <cstdint>
8#include <cstdio>
9#include <map>
10#include <memory>
11#include <thread>
12#include <string>
13#include <vector>
14
15namespace strata::image {
16
17struct StTensor {
18    std::string dtype;               // "BF16", "F16", "F32", ...
19    std::vector<int64_t> shape;
20    uint64_t begin = 0, end = 0;     // byte offsets from the start of the data section
21};
22
23struct StFile {
24    std::map<std::string, StTensor> tensors;
25    uint64_t data_start = 0;         // file offset of the data section
26};
27
28namespace st_detail {
29struct Parser {
30    const std::string& s;
31    size_t i = 0;
32    std::string err;
33    explicit Parser(const std::string& t) : s(t) {}
34    void ws() { while (i < s.size() && (s[i] == ' ' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t')) ++i; }
35    bool eat(char c) { ws(); if (i < s.size() && s[i] == c) { ++i; return true; } return false; }
36    bool str(std::string& out) {
37        ws();
38        if (i >= s.size() || s[i] != '"') return fail("string expected");
39        ++i;
40        out.clear();
41        while (i < s.size() && s[i] != '"') {
42            if (s[i] == '\\') {
43                if (i + 1 >= s.size()) return fail("bad escape");
44                char e = s[i + 1];
45                if (e == 'u') {                          // names are ASCII; keep \uXXXX as-is (never matched)
46                    out += s.substr(i, 6);
47                    i += 6;
48                    continue;
49                }
50                out += (e == 'n') ? '\n' : (e == 't') ? '\t' : e;
51                i += 2;
52                continue;
53            }
54            out += s[i++];
55        }
56        if (i >= s.size()) return fail("unterminated string");
57        ++i;
58        return true;
59    }
60    bool num(int64_t& v) {
61        ws();
62        size_t j = i;
63        if (j < s.size() && s[j] == '-') ++j;
64        while (j < s.size() && s[j] >= '0' && s[j] <= '9') ++j;
65        if (j == i) return fail("number expected");
66        v = std::stoll(s.substr(i, j - i));
67        i = j;
68        return true;
69    }
70    bool skip_value() {               // any JSON value (for __metadata__ and unknown fields)
71        ws();
72        if (i >= s.size()) return fail("value expected");
73        char c = s[i];
74        if (c == '"') { std::string t; return str(t); }
75        if (c == '{' || c == '[') {
76            char close = c == '{' ? '}' : ']';
77            ++i;
78            if (eat(close)) return true;
79            do {
80                if (c == '{') { std::string k; if (!str(k) || !eat(':')) return fail("object"); }
81                if (!skip_value()) return false;
82            } while (eat(','));
83            return eat(close) || fail("unterminated container");
84        }
85        while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']') ++i;   // number, true, false, null
86        return true;
87    }
88    bool int_array(std::vector<int64_t>& out) {
89        out.clear();
90        if (!eat('[')) return fail("[ expected");
91        if (eat(']')) return true;
92        do { int64_t v; if (!num(v)) return false; out.push_back(v); } while (eat(','));
93        return eat(']') || fail("] expected");
94    }
95    bool fail(const char* m) { if (err.empty()) err = std::string(m) + " at byte " + std::to_string(i); return false; }
96};
97}  // namespace st_detail
98
99// Parse the header of `path` into `out`.  Returns an empty string on success, else the reason.
100inline std::string st_read_header(const std::string& path, StFile& out) {
101    FILE* f = std::fopen(path.c_str(), "rb");
102    if (!f) return "cannot open " + path;
103    unsigned char len8[8];
104    if (std::fread(len8, 1, 8, f) != 8) { std::fclose(f); return "short file " + path; }
105    uint64_t n = 0;
106    for (int k = 7; k >= 0; --k) n = (n << 8) | len8[k];
107    if (n == 0 || n > (64u << 20)) { std::fclose(f); return "implausible header length in " + path; }
108    std::string text(n, '\0');
109    if (std::fread(&text[0], 1, n, f) != n) { std::fclose(f); return "short header in " + path; }
110    std::fclose(f);
111    out = StFile{};
112    out.data_start = 8 + n;
113    st_detail::Parser p(text);
114    if (!p.eat('{')) return "header is not a JSON object";
115    if (p.eat('}')) return "";
116    do {
117        std::string name;
118        if (!p.str(name) || !p.eat(':')) return "header: " + p.err;
119        if (name == "__metadata__") { if (!p.skip_value()) return "header: " + p.err; continue; }
120        StTensor t;
121        if (!p.eat('{')) return "header: tensor entry is not an object";
122        if (!p.eat('}')) {
123            do {
124                std::string key;
125                if (!p.str(key) || !p.eat(':')) return "header: " + p.err;
126                if (key == "dtype") { if (!p.str(t.dtype)) return "header: " + p.err; }
127                else if (key == "shape") { if (!p.int_array(t.shape)) return "header: " + p.err; }
128                else if (key == "data_offsets") {
129                    std::vector<int64_t> o;
130                    if (!p.int_array(o) || o.size() != 2 || o[0] < 0 || o[1] < o[0]) return "header: bad data_offsets";
131                    t.begin = (uint64_t) o[0];
132                    t.end = (uint64_t) o[1];
133                } else if (!p.skip_value()) return "header: " + p.err;
134            } while (p.eat(','));
135            if (!p.eat('}')) return "header: } expected";
136        }
137        out.tensors[name] = t;
138    } while (p.eat(','));
139    if (!p.eat('}')) return "header: } expected at the end";
140    return "";
141}
142
143// Read the whole data section (one sequential read; the decoder converts from memory).
144inline std::string st_read_all(const std::string& path, const StFile& file, std::vector<unsigned char>& bytes) {
145    uint64_t end = 0;
146    for (const auto& kv : file.tensors) end = kv.second.end > end ? kv.second.end : end;
147    FILE* f = std::fopen(path.c_str(), "rb");
148    if (!f) return "cannot open " + path;
149    bytes.resize(end);
150#if defined(_WIN32)
151    int rc = _fseeki64(f, (long long) file.data_start, SEEK_SET);
152#else
153    int rc = fseeko(f, (off_t) file.data_start, SEEK_SET);
154#endif
155    size_t got = rc == 0 ? std::fread(bytes.data(), 1, bytes.size(), f) : 0;
156    std::fclose(f);
157    return got == bytes.size() ? "" : "short read in " + path;
158}
159
160// The same into a buffer that is not zero-filled first, read in `threads` parts at once (each part its own file
161// handle).  size = the data section's length.
162inline std::string st_read_all_parallel(const std::string& path, const StFile& file, std::unique_ptr<unsigned char[]>& buf,
163                                        size_t& size, int threads) {
164    uint64_t end = 0;
165    for (const auto& kv : file.tensors) end = kv.second.end > end ? kv.second.end : end;
166    size = (size_t) end;
167    buf.reset(new unsigned char[size ? size : 1]);
168    const int parts = threads < 1 ? 1 : (threads > 16 ? 16 : threads);
169    const size_t step = (size + parts - 1) / parts;
170    std::vector<std::string> errs((size_t) parts);
171    std::vector<std::thread> pool;
172    for (int p = 0; p < parts; ++p) {
173        pool.emplace_back([&, p]() {
174            const size_t b = (size_t) p * step, e = b + step < size ? b + step : size;
175            if (b >= e) return;
176            FILE* f = std::fopen(path.c_str(), "rb");
177            if (!f) { errs[(size_t) p] = "cannot open " + path; return; }
178#if defined(_WIN32)
179            int rc = _fseeki64(f, (long long) (file.data_start + b), SEEK_SET);
180#else
181            int rc = fseeko(f, (off_t) (file.data_start + b), SEEK_SET);
182#endif
183            size_t got = rc == 0 ? std::fread(buf.get() + b, 1, e - b, f) : 0;
184            std::fclose(f);
185            if (got != e - b) errs[(size_t) p] = "short read in " + path;
186        });
187    }
188    for (auto& t : pool) t.join();
189    for (const auto& e : errs)
190        if (!e.empty()) return e;
191    return "";
192}
193
194// Read the raw bytes of one tensor.
195inline std::string st_read_tensor(const std::string& path, const StFile& file, const StTensor& t,
196                                  std::vector<unsigned char>& bytes) {
197    FILE* f = std::fopen(path.c_str(), "rb");
198    if (!f) return "cannot open " + path;
199    bytes.resize(t.end - t.begin);
200#if defined(_WIN32)
201    int rc = _fseeki64(f, (long long) (file.data_start + t.begin), SEEK_SET);
202#else
203    int rc = fseeko(f, (off_t) (file.data_start + t.begin), SEEK_SET);
204#endif
205    size_t got = rc == 0 ? std::fread(bytes.data(), 1, bytes.size(), f) : 0;
206    std::fclose(f);
207    return got == bytes.size() ? "" : "short read in " + path;
208}
209
210}  // namespace strata::image