GLM-OCR / code /tt_glmocr /tt /mk_dec /sampler_host.py
changh95's picture
tt-model push glm-ocr (container)
aa204f5 verified
Raw History Blame Contribute Delete
5.29 kB
# SPDX-License-Identifier: Apache-2.0
"""Host build of the shared device sampler (``kernels/sampler.hpp``) via ctypes: the bit-exact reference of the
device samplers (mk_cp, mk_talker). See ``SAMPLER.md``.
The library is compiled on first use with the system ``g++`` (``-O2 -std=c++17``) into
``$GLMOCR_MKS_CACHE`` (default ``~/.cache/tt_glmocr``), keyed by a hash of the sources. No device, no ttnn.
"""
from __future__ import annotations
import ctypes
import hashlib
import os
import struct
import subprocess
import tempfile
from typing import Optional, Sequence, Tuple
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
KDIR = os.path.join(HERE, "kernels")
SOURCES = ("sampler.hpp", "sampler_host.cpp")
K_MAX = 64
_LIB = None
def f32_bits(x: float) -> int:
return struct.unpack("<I", struct.pack("<f", float(x)))[0]
def _build() -> str:
h = hashlib.sha256()
for s in SOURCES:
with open(os.path.join(KDIR, s), "rb") as f:
h.update(f.read())
cache = os.environ.get("GLMOCR_MKS_CACHE", os.path.join(os.path.expanduser("~"), ".cache", "tt_glmocr"))
os.makedirs(cache, exist_ok=True)
so = os.path.join(cache, f"libmks_{h.hexdigest()[:16]}.so")
if not os.path.exists(so):
fd, tmp = tempfile.mkstemp(suffix=".so", dir=cache)
os.close(fd)
subprocess.check_call(["g++", "-O2", "-std=c++17", "-shared", "-fPIC", "-o", tmp,
os.path.join(KDIR, "sampler_host.cpp")])
os.replace(tmp, so)
return so
def lib():
global _LIB
if _LIB is None:
L = ctypes.CDLL(_build())
u32, i64, u64 = ctypes.c_uint32, ctypes.c_int64, ctypes.c_uint64
p32 = ctypes.POINTER(ctypes.c_uint32)
L.mks_key.argtypes, L.mks_key.restype = [u32], u32
L.mks_key_fixed.argtypes, L.mks_key_fixed.restype = [u32], i64
L.mks_scaled_gap.argtypes, L.mks_scaled_gap.restype = [u64, u32], u64
L.mks_weight_x.argtypes, L.mks_weight_x.restype = [u64], u32
L.mks_weight.argtypes, L.mks_weight.restype = [i64, i64, u32], u32
L.mks_top_p_q24.argtypes, L.mks_top_p_q24.restype = [u32], u32
L.mks_philox.argtypes, L.mks_philox.restype = [p32, u32, u32, p32], None
L.mks_u24.argtypes, L.mks_u24.restype = [u32, u32, u32, u32], u32
L.mks_talker_process.argtypes = [p32, u32, u32, p32, u32, u32, u32, u32]
L.mks_talker_process.restype = None
L.mks_local_sorted.argtypes, L.mks_local_sorted.restype = [p32, u32, u32, p32, u32], u32
L.mks_sample.argtypes = [p32, u32, u32, u32, u32, u32, u32, u32, u32, u32, p32]
L.mks_sample.restype = u32
_LIB = L
return _LIB
def _p32(a: np.ndarray):
return a.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
def philox(counter: Sequence[int], key: Tuple[int, int]) -> Tuple[int, int, int, int]:
c = np.asarray(counter, dtype=np.uint32)
out = np.zeros(4, dtype=np.uint32)
lib().mks_philox(_p32(c), int(key[0]) & 0xFFFFFFFF, int(key[1]) & 0xFFFFFFFF, _p32(out))
return tuple(int(x) for x in out)
def u24(seed: int, frame: int, codebook: int) -> int:
"""U = Philox x0 >> 8 for (seed, frame, codebook); u = (U + 0.5) 2^-24."""
s = int(seed) & 0xFFFFFFFFFFFFFFFF
return int(lib().mks_u24(s & 0xFFFFFFFF, s >> 32, int(frame), int(codebook)))
def sample(scores, do_sample: bool, inv_temperature: float = 1.0, top_k: int = 0, top_p: float = 1.0,
u24_value: int = 0, k_max: int = K_MAX, slice_size: int = 32, cap: Optional[int] = None):
"""Device selection on fp32 ``scores`` (after the talker processors; raw logits for the sub-talker), distributed
over slices of ``slice_size`` ids with local lists of ``cap`` entries (default max(slice, k_max)).
Returns ``(token, info)`` with info = dict(kept_k, kept_p, rank, z)."""
s = np.ascontiguousarray(np.asarray(scores, dtype=np.float32).reshape(-1)).view(np.uint32)
cap = max(slice_size, k_max) if cap is None else cap
info = np.zeros(5, dtype=np.uint32)
tok = lib().mks_sample(_p32(s), s.size, slice_size, int(bool(do_sample)), f32_bits(inv_temperature), int(top_k),
f32_bits(top_p), int(u24_value), int(k_max), int(cap), _p32(info))
return int(tok), dict(kept_k=int(info[0]), kept_p=int(info[1]), rank=int(info[2]),
z=int(info[3]) | (int(info[4]) << 32))
def talker_process(logits, seen_ids, step: int, repetition_penalty: float = 1.05, min_new_tokens: int = 2,
eos_id: int = 2150, id0: int = 0) -> np.ndarray:
"""Talker processors (sampler.hpp talker_process) on fp32 logits of ids id0.. -> new fp32 array."""
s = np.ascontiguousarray(np.asarray(logits, dtype=np.float32).reshape(-1)).copy().view(np.uint32)
seen = np.zeros(64, dtype=np.uint32)
for i in set(int(x) for x in seen_ids):
if 0 <= i < 2048:
seen[i >> 5] |= np.uint32(1 << (i & 31))
lib().mks_talker_process(_p32(s), s.size, int(id0), _p32(seen), int(step), int(min_new_tokens), int(eos_id),
f32_bits(repetition_penalty))
return s.view(np.float32)
def weight(x24: int) -> int:
"""W(x) = round(2^30 exp(-x 2^-24)) as the device computes it."""
return int(lib().mks_weight_x(int(x24)))