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
4.5 KiB106 linesraw
1"""tools/image/gate/test_safetensors_lite.py - TEST-ONLY: src/image/vae/safetensors_lite.hpp (the VAE decoder's file
2reader) on files written here: names, dtypes, shapes, offsets, the bytes of a tensor, __metadata__ skipped, escaped
3strings, and the refusals (bad length, broken JSON).  Builds a small C++ program with the host compiler; skipped when
4there is none.
5
6    python -m pytest tools/image/gate/test_safetensors_lite.py"""
7import json
8import shutil
9import struct
10import subprocess
11import tempfile
12import unittest
13from pathlib import Path
14
15ROOT = Path(__file__).resolve().parents[3]
16CXX = shutil.which("g++") or shutil.which("clang++")
17
18PROGRAM = r'''
19#include "safetensors_lite.hpp"
20#include <cstring>
21#include <cstdio>
22int main(int argc, char** argv) {
23    strata::image::StFile f;
24    std::string err = strata::image::st_read_header(argv[1], f);
25    if (!err.empty()) { std::printf("ERR %s\n", err.c_str()); return 1; }
26    for (auto& kv : f.tensors) {
27        std::printf("T %s %s", kv.first.c_str(), kv.second.dtype.c_str());
28        for (auto s : kv.second.shape) std::printf(" %lld", (long long) s);
29        std::vector<unsigned char> b;
30        err = strata::image::st_read_tensor(argv[1], f, kv.second, b);
31        if (!err.empty()) { std::printf(" READERR %s\n", err.c_str()); return 1; }
32        std::printf(" |");
33        for (auto c : b) std::printf(" %02x", c);
34        std::printf("\n");
35    }
36    for (int th : {1, 3, 16}) {   // the whole data section in parallel parts: the same bytes as the tensor reads
37        std::unique_ptr<unsigned char[]> all;
38        size_t size = 0;
39        err = strata::image::st_read_all_parallel(argv[1], f, all, size, th);
40        if (!err.empty()) { std::printf("PARERR %s\n", err.c_str()); return 1; }
41        for (auto& kv : f.tensors) {
42            std::vector<unsigned char> b;
43            strata::image::st_read_tensor(argv[1], f, kv.second, b);
44            if (b.size() && std::memcmp(b.data(), all.get() + kv.second.begin, b.size()) != 0) { std::printf("PARDIFF\n"); return 1; }
45        }
46    }
47    return 0;
48}
49'''
50
51
52def write_st(path: Path, header: dict, data: bytes, raw_header: bytes = None):
53    h = raw_header if raw_header is not None else json.dumps(header).encode()
54    path.write_bytes(struct.pack("<Q", len(h)) + h + data)
55
56
57@unittest.skipUnless(CXX, "no host C++ compiler")
58class SafetensorsLite(unittest.TestCase):
59    @classmethod
60    def setUpClass(cls):
61        cls.tmp = tempfile.TemporaryDirectory()
62        d = Path(cls.tmp.name)
63        (d / "t.cpp").write_text(PROGRAM)
64        cls.exe = d / "st_test"
65        subprocess.run([CXX, "-std=c++17", "-O1", "-pthread", "-I", str(ROOT / "src" / "image" / "vae"), str(d / "t.cpp"), "-o",
66                        str(cls.exe)], check=True)
67
68    @classmethod
69    def tearDownClass(cls):
70        cls.tmp.cleanup()
71
72    def run_on(self, header, data, raw_header=None):
73        p = Path(self.tmp.name) / "m.safetensors"
74        write_st(p, header, data, raw_header)
75        r = subprocess.run([str(self.exe), str(p)], capture_output=True, text=True)
76        return r.returncode, r.stdout
77
78    def test_tensors_and_metadata(self):
79        hdr = {"__metadata__": {"format": "pt", "nested": {"a": [1, 2, {"b": "c}"}]}},
80               "decoder.conv_in.weight": {"dtype": "BF16", "shape": [2, 1, 1, 1], "data_offsets": [0, 4]},
81               "x\\\"y": {"dtype": "F32", "shape": [1], "data_offsets": [4, 8]}}
82        rc, out = self.run_on(hdr, bytes([1, 2, 3, 4, 0, 0, 128, 63]))
83        self.assertEqual(rc, 0, out)
84        lines = sorted(out.splitlines())
85        self.assertIn("T decoder.conv_in.weight BF16 2 1 1 1 | 01 02 03 04", lines)
86        self.assertIn('T x\\"y F32 1 | 00 00 80 3f', lines)
87        self.assertEqual(len(lines), 2)
88
89    def test_empty_shape_scalar(self):
90        rc, out = self.run_on({"s": {"dtype": "F32", "shape": [], "data_offsets": [0, 4]}}, bytes(4))
91        self.assertEqual((rc, out.strip()), (0, "T s F32 | 00 00 00 00"))
92
93    def test_refusals(self):
94        rc, out = self.run_on(None, b"", raw_header=b'{"a": {"dtype": "F32", "shape": [1], "data_offsets": [4, 0]}}')
95        self.assertEqual(rc, 1)
96        self.assertIn("bad data_offsets", out)
97        rc, out = self.run_on(None, b"", raw_header=b'{"a": {"dtype": "F32"')
98        self.assertEqual(rc, 1)
99        self.assertTrue(out.startswith("ERR header"), out)
100        rc, out = self.run_on({"a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 8]}}, bytes(4))
101        self.assertEqual(rc, 1)
102        self.assertIn("short read", out)
103
104
105if __name__ == "__main__":
106    unittest.main()