okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
2.7 KiB66 linesraw
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3"""tools/ds4/st.py - every tensor of a DeepSeek-V4.1 model directory, read in place.
4
5    st = SafeTensors(Path("~/models/DSV4").expanduser())
6    st.t["layers.0.attn.wq_a.trellis"]   -> (file, dtype, shape, absolute offset, bytes)
7    st.raw(name), st.f32(name)            -> numpy views / float32 copies
8
9The index's own files come first; any other .safetensors in the directory (the Engram shards 47 / 48 of the base
10repo, model-0004[78]-of-00048.safetensors) only adds names the index does not have.
11"""
12from __future__ import annotations
13
14import json
15import pathlib
16import struct
17
18import numpy as np
19
20DTYPE_BYTES = {"F32": 4, "F16": 2, "BF16": 2, "I32": 4, "I16": 2, "F8_E4M3": 1, "F8_E8M0": 1, "U8": 1, "I8": 1,
21               "I64": 8}
22
23
24class SafeTensors:
25    def __init__(self, d: pathlib.Path):
26        self.dir = pathlib.Path(d)
27        ix = json.loads((self.dir / "model.safetensors.index.json").read_text())["weight_map"]
28        primary = sorted(set(ix.values()))
29        others = sorted(p.name for p in self.dir.glob("*.safetensors") if p.name not in primary)
30        self.files: list[str] = []
31        self.t: dict[str, tuple] = {}
32        self.mm: dict[str, np.memmap] = {}
33        for fn in primary + others:
34            p = self.dir / fn
35            with p.open("rb") as f:
36                n = struct.unpack("<Q", f.read(8))[0]
37                h = json.loads(f.read(n))
38            base = 8 + n
39            self.files.append(fn)
40            for k, v in h.items():
41                if k == "__metadata__" or k in self.t:
42                    continue
43                a, b = v["data_offsets"]
44                self.t[k] = (fn, v["dtype"], tuple(v["shape"]), base + a, b - a)
45            self.mm[fn] = np.memmap(p, dtype=np.uint8, mode="r")
46
47    def has(self, name: str) -> bool:
48        return name in self.t
49
50    def raw(self, name: str) -> np.ndarray:
51        fn, _, _, off, nb = self.t[name]
52        return self.mm[fn][off:off + nb]
53
54    def f32(self, name: str) -> np.ndarray:
55        """The tensor as float32 (exact for F32/F16/BF16), shaped as stored."""
56        _, dt, shape, _, _ = self.t[name]
57        r = self.raw(name)
58        if dt == "F32":
59            a = r.view("<f4")
60        elif dt == "F16":
61            a = r.view("<f2").astype(np.float32)
62        elif dt == "BF16":
63            a = (r.view("<u2").astype(np.uint32) << 16).view(np.float32)
64        else:
65            raise ValueError("%s is %s, not a float tensor" % (name, dt))
66        return a.reshape(shape)