File size: 7,824 Bytes
04ecd36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env python3
"""Makes Strata's pre-quantized DFlash 2 file (format "strata-dflash2-q1", variant "mix") from the original incoai/Inkling-2-Mini-DFlash2 model.safetensors with numpy only.

    python -I make_mix_from_original.py model.safetensors Inkling-2-Mini-DFlash2-mix.safetensors

The Strata engine writes the same file itself (STRATA_INK_DFLASH2_DUMP, on the GPU); this script repeats its arithmetic in float32 so that the file can be checked or remade without a GPU. The
result must have SHA-256 cf7dbb08560dfd99544af0cdbab2915406fc571f516b19aff0fe113b9458d387 and 551,600,700 bytes.

mix = attention matrices (q_proj, o_proj) as int8 with one float32 scale per row (scale = rowmax / 127; q = round-half-even(x / scale), clamped to +-127);
      feed-forward matrices (gate_proj, up_proj, down_proj) as SF4: E2M1 values packed two to a byte (first value in the low nibble), a UE4M3 scale per 16 values
      (block max / (6 * w_outer), rounded to E4M3), one float32 w_outer = tensor max / (6 * 448); everything else as in the original (norms and convolution base kernels widened to float32).
"""
import json
import struct
import sys

import numpy as np

HID, FF, QD, KVD, DYN, RANK, LAYERS, HD = 2304, 6912, 4096, 1024, 576, 256, 5, 128
VOCAB = 200058   # the engine's vocabulary; the checkpoint's codebooks have more rows, the unused ones are left out


def read_safetensors(path):
    f = open(path, "rb")
    n = struct.unpack("<Q", f.read(8))[0]
    hdr = json.loads(f.read(n))
    base = 8 + n

    def get(name):
        t = hdr[name]
        a, b = t["data_offsets"]
        f.seek(base + a)
        raw = np.frombuffer(f.read(b - a), dtype=np.uint16 if t["dtype"] == "BF16" else np.float32)
        return raw.reshape(t["shape"]), t["dtype"]
    return get


def bf16_to_f32(u16):
    return (u16.astype(np.uint32) << 16).view(np.float32)


def f32_of(get, name):
    a, dt = get(name)
    return bf16_to_f32(a) if dt == "BF16" else a.astype(np.float32)


def q8_rows(w_bf16):
    w = bf16_to_f32(w_bf16)
    am = np.max(np.abs(w), axis=1)
    sc = np.where(am > 0, am * np.float32(1.0 / 127.0), np.float32(0)).astype(np.float32)
    inv = np.where(sc > 0, np.float32(1.0) / np.where(sc > 0, sc, 1), np.float32(0)).astype(np.float32)
    q = np.clip(np.rint(w * inv[:, None]), -127, 127).astype(np.int8)
    return q.reshape(-1), sc


def e4m3_byte(x):
    """x >= 0 (float32, at most 448) -> the E4M3 (finite, bias 7) code that round-to-nearest-even gives, and its value as float32."""
    x = x.astype(np.float64)
    m, e = np.frexp(x)                         # x = m * 2^e, m in [0.5, 1)
    e = np.maximum(e - 1, -6)                  # exponent of the leading bit, subnormals share 2^-6
    step = np.ldexp(1.0, e - 3)
    q = np.rint(x / step) * step               # exact: division by a power of two
    q = np.minimum(q, 448.0)
    m2, e2 = np.frexp(q)
    e2 = e2 - 1
    sub = q < 2.0 ** -6
    code = np.where(sub, np.rint(q / 2.0 ** -9), ((e2 + 7) << 3) + np.rint((q / np.ldexp(1.0, e2) - 1.0) * 8.0))
    code = np.where(q == 0, 0, code).astype(np.uint8)
    return code, q.astype(np.float32)


def e2m1_code(x):
    """float32 -> 4-bit E2M1 code, round to nearest even (a tie goes to the even code), saturating at 6, the sign bit kept (also on -0)."""
    a = np.abs(x)
    mid = np.array([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], dtype=np.float32)     # midpoints of 0 0.5 1 1.5 2 3 4 6
    even_at_tie = np.array([0, 2, 2, 4, 4, 6, 6])
    lo = np.searchsorted(mid, a, side="left")      # midpoints strictly below a = the code of a that is not a tie
    hi = np.searchsorted(mid, a, side="right")     # midpoints at or below a; hi > lo means a is exactly a midpoint
    code = np.where(hi > lo, even_at_tie[np.minimum(lo, 6)], lo)
    return code.astype(np.uint8) | np.where(np.signbit(x), 8, 0).astype(np.uint8)


def sf4(w_bf16):
    """-> packed (N, K/2) uint8, block scales (N, K/16) uint8, w_outer float32."""
    N, K = w_bf16.shape
    w = bf16_to_f32(w_bf16)
    amax = np.max(np.abs(w))
    w_outer = np.float32(max(np.float32(amax) / np.float32(6.0 * 448.0), np.float32(1e-12)))
    blocks = w.reshape(N, K // 16, 16)
    am = np.max(np.abs(blocks), axis=2)
    sc_f = np.minimum(am / (w_outer * np.float32(6.0)), np.float32(448.0)).astype(np.float32)
    sc_byte, sc_val = e4m3_byte(sc_f)
    sc_byte = np.where(am > 0, sc_byte, 0).astype(np.uint8)
    sc_val = np.where(am > 0, sc_val, 0).astype(np.float32)
    denom = (w_outer * sc_val).astype(np.float32)
    inv = np.where(denom > 0, np.float32(1.0) / np.where(denom > 0, denom, 1), np.float32(0)).astype(np.float32)
    v = (blocks * inv[:, :, None]).astype(np.float32).reshape(N, K)
    code = e2m1_code(v)
    packed = (code[:, 0::2] | (code[:, 1::2] << 4)).astype(np.uint8)
    return packed, sc_byte, w_outer


def main(src, dst):
    get = read_safetensors(src)
    items = []   # (name, dtype, shape, bytes)

    def add(name, dtype, shape, arr):
        items.append((name, dtype, list(shape), np.ascontiguousarray(arr).tobytes()))

    def bf(name, shape):
        a, dt = get(name)
        assert dt == "BF16" and list(a.shape) == list(shape), (name, dt, a.shape)
        add(name, "BF16", shape, a)

    def f32(name, shape):
        add(name, "F32", shape, f32_of(get, name))

    bf("fc.weight", (HID, 4 * HID))
    f32("hidden_norm.weight", (HID,))
    f32("norm.weight", (HID,))
    bf("candidate_selector.hidden_projection.weight", (RANK, HID))
    for nm in ("candidate_selector.predecessor_codebook", "candidate_selector.successor_codebook"):
        a, dt = get(nm)
        assert dt == "BF16" and a.shape[1] == RANK and a.shape[0] >= VOCAB
        add(nm, "BF16", (VOCAB, RANK), a[:VOCAB])
    for l in range(LAYERS):
        p = "layers.%d." % l
        bf(p + "self_attn.k_proj.weight", (KVD, HID))
        bf(p + "self_attn.v_proj.weight", (KVD, HID))
        bf(p + "attention_conv.kernel_projection.weight", (DYN, HID))
        bf(p + "mlp_conv.kernel_projection.weight", (DYN, HID))
        f32(p + "attention_conv.base_kernel", (2, 2, HID))
        f32(p + "mlp_conv.base_kernel", (2, 2, HID))
        f32(p + "input_layernorm.weight", (HID,))
        f32(p + "post_attention_layernorm.weight", (HID,))
        f32(p + "self_attn.q_norm.weight", (HD,))
        f32(p + "self_attn.k_norm.weight", (HD,))
        for nm, N, K, kind in (("self_attn.q_proj.weight", QD, HID, "q8"), ("self_attn.o_proj.weight", HID, QD, "q8"),
                               ("mlp.gate_proj.weight", FF, HID, "sf4"), ("mlp.up_proj.weight", FF, HID, "sf4"), ("mlp.down_proj.weight", HID, FF, "sf4")):
            a, dt = get(p + nm)
            assert dt == "BF16" and list(a.shape) == [N, K], (nm, a.shape)
            if kind == "q8":
                q, sc = q8_rows(a)
                add(p + nm + ".q", "I8", (N * K,), q)
                add(p + nm + ".s", "F32", (N,), sc)
            else:
                pk, sb, wo = sf4(a)
                add(p + nm + ".q", "U8", (N * K // 2,), pk)
                add(p + nm + ".s", "U8", (N * K // 16,), sb)
                add(p + nm + ".o", "F32", (1,), np.array([wo], dtype=np.float32))
        print("layer", l, "done", file=sys.stderr)
    js = '{"__metadata__":{"format":"strata-dflash2-q1","variant":"mix"}'
    off = 0
    for name, dtype, shape, raw in items:
        js += ',"%s":{"dtype":"%s","shape":[%s],"data_offsets":[%d,%d]}' % (name, dtype, ",".join(str(s) for s in shape), off, off + len(raw))
        off += len(raw)
    js += "}"
    js += " " * ((-len(js)) % 8)
    with open(dst, "wb") as o:
        o.write(struct.pack("<Q", len(js)))
        o.write(js.encode("ascii"))
        for _, _, _, raw in items:
            o.write(raw)
    print("wrote", dst, 8 + len(js) + off, "bytes")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])