File size: 5,236 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared helpers for the MOSS-Image OpenVINO port (CT 140, /opt/mossimage).

Layout:
  /opt/mossimage/hf/{sft,base}   original HF files (safetensors, configs, tokenizer)
  /opt/mossimage/models/...      OpenVINO IRs
  /opt/mossimage/cache           OpenVINO GPU/CPU model caches
  /opt/mossimage/work            reference tensors, test images, logs
"""
import json
import os
import struct
import time

import numpy as np

ROOT = "/opt/mossimage"
HF = {"sft": f"{ROOT}/hf/sft", "base": f"{ROOT}/hf/base"}
MODELS = f"{ROOT}/models"
CACHE = f"{ROOT}/cache"
WORK = f"{ROOT}/work"
TE_DIR = f"{HF['sft']}/text_encoder"  # byte-identical in Base and SFT
VAE_DIR = f"{HF['sft']}/vae"          # byte-identical in Base and SFT

TE_LAYERS = 32
TE_PARTS = 4  # 8 decoder layers per part (pattern L L L F x2 per part)


class Timer:
    def __init__(self, label):
        self.label = label

    def __enter__(self):
        self.t = time.time()
        return self

    def __exit__(self, *a):
        self.dt = time.time() - self.t
        print(f"[time] {self.label}: {self.dt:.2f}s", flush=True)


def rss_gb():
    with open("/proc/self/status") as f:
        for line in f:
            if line.startswith("VmRSS"):
                return int(line.split()[1]) / 1048576
            if line.startswith("VmHWM"):
                pass
    return 0.0


def hwm_gb():
    with open("/proc/self/status") as f:
        for line in f:
            if line.startswith("VmHWM"):
                return int(line.split()[1]) / 1048576
    return 0.0


def host_memfree_gb():
    d = {}
    with open("/proc/meminfo") as f:
        for line in f:
            k, v = line.split(":")
            d[k] = int(v.split()[0]) / 1048576
    return d


# ---------------------------------------------------------------- safetensors
class ST:
    """Minimal lazy safetensors reader over a sharded checkpoint (numpy, bf16 via uint16)."""

    def __init__(self, folder, index_name):
        self.folder = folder
        idx = json.load(open(os.path.join(folder, index_name)))
        self.map = idx["weight_map"]
        self._hdr = {}

    def header(self, shard):
        if shard not in self._hdr:
            with open(os.path.join(self.folder, shard), "rb") as f:
                n = struct.unpack("<Q", f.read(8))[0]
                h = json.loads(f.read(n))
            h.pop("__metadata__", None)
            self._hdr[shard] = (h, 8 + n)
        return self._hdr[shard]

    def keys(self):
        return list(self.map)

    def raw(self, key):
        shard = self.map[key]
        h, off = self.header(shard)
        t = h[key]
        s, e = t["data_offsets"]
        with open(os.path.join(self.folder, shard), "rb") as f:
            f.seek(off + s)
            buf = f.read(e - s)
        return t["dtype"], t["shape"], buf

    def get_f32(self, key):
        """Tensor as float32 numpy."""
        dt, shape, buf = self.raw(key)
        if dt == "BF16":
            a = np.frombuffer(buf, dtype=np.uint16).astype(np.uint32) << 16
            return a.view(np.float32).reshape(shape)
        if dt == "F32":
            return np.frombuffer(buf, dtype=np.float32).reshape(shape).copy()
        if dt == "F16":
            return np.frombuffer(buf, dtype=np.float16).reshape(shape).astype(np.float32)
        raise ValueError(dt)


# ---------------------------------------------------------------- text encoder glue
def text_rope(L, head_rot=64, theta=1.0e7):
    """cos/sin for text-only mrope (all 3 position channels equal): [1, L, head_rot] float32.

    Equivalent to Qwen3_5TextRotaryEmbedding for pure text: partial_rotary_factor 0.25 of head_dim 256 = 64 dims,
    interleaved mrope overwrites H/W channels with identical values, then cat(freqs, freqs).
    """
    inv = 1.0 / (theta ** (np.arange(0, head_rot, 2, dtype=np.float32) / head_rot))
    freqs = np.arange(L, dtype=np.float32)[:, None] * inv[None, :]
    emb = np.concatenate([freqs, freqs], -1)
    return np.cos(emb)[None].astype(np.float32), np.sin(emb)[None].astype(np.float32)


def render_prompt(tokenizer, text):
    """Exactly the pipeline's encode_prompt formatting (chat template, thinking on, generation prompt)."""
    formatted = tokenizer.apply_chat_template(
        [{"role": "user", "content": text}], tokenize=False, add_generation_prompt=True, enable_thinking=True
    )
    return formatted


# ---------------------------------------------------------------- image metrics
def psnr(a, b, peak=255.0):
    a = a.astype(np.float64)
    b = b.astype(np.float64)
    mse = np.mean((a - b) ** 2)
    return float("inf") if mse == 0 else 10 * np.log10(peak * peak / mse)


def cmp(ref, got, name=""):
    ref = np.asarray(ref, dtype=np.float64).ravel()
    got = np.asarray(got, dtype=np.float64).ravel()
    cos = float(ref @ got / (np.linalg.norm(ref) * np.linalg.norm(got) + 1e-30))
    mx = float(np.abs(ref - got).max())
    rel = float(np.linalg.norm(ref - got) / (np.linalg.norm(ref) + 1e-30))
    finite = bool(np.isfinite(got).all())
    r = {"name": name, "cos": round(cos, 6), "max_abs": round(mx, 5), "rel_l2": round(rel, 6), "ref_absmax": round(float(np.abs(ref).max()), 3), "finite": finite}
    print("[cmp]", json.dumps(r), flush=True)
    return r