aqualaguna's picture
Add files using upload-large-folder tool
565b868 verified
Raw History Blame Contribute Delete
5.24 kB
"""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