xenocodec 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- xeno_py/__init__.py +7 -0
- xeno_py/bf16.py +10 -0
- xeno_py/tensors.py +72 -0
- xeno_py/v7.py +69 -0
- xeno_py/vectordb.py +36 -0
- xeno_py/xeno_core.dll +0 -0
- xeno_py/xeno_cross.h +150 -0
- xenocodec-0.3.0.dist-info/METADATA +59 -0
- xenocodec-0.3.0.dist-info/RECORD +11 -0
- xenocodec-0.3.0.dist-info/WHEEL +5 -0
- xenocodec-0.3.0.dist-info/top_level.txt +1 -0
xeno_py/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# xeno_py — XENO lossless codec for numpy / safetensors / vector search.
|
|
2
|
+
from .v7 import compress_bf16, decompress_bf16, lib
|
|
3
|
+
from .tensors import save, load
|
|
4
|
+
from .vectordb import VectorDB
|
|
5
|
+
|
|
6
|
+
__all__ = ["compress_bf16", "decompress_bf16", "save", "load", "VectorDB", "lib"]
|
|
7
|
+
__version__ = "0.3.0"
|
xeno_py/bf16.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""BF16 <-> float32 (round-to-nearest-even, identical to the C core bijection)."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
def f32_to_bf16(a):
|
|
5
|
+
u = a.view(np.uint32) if a.flags.c_contiguous else np.ascontiguousarray(a).view(np.uint32)
|
|
6
|
+
rounded = (u + 0x7FFF + ((u >> 16) & 1)).astype(np.uint32)
|
|
7
|
+
return (rounded >> 16).astype(np.uint16)
|
|
8
|
+
|
|
9
|
+
def bf16_to_f32(b):
|
|
10
|
+
return (b.astype(np.uint32) << 16).view(np.float32)
|
xeno_py/tensors.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Compressed tensor I/O: .xn16 container (magic XN16, v1).
|
|
2
|
+
|
|
3
|
+
Layout: magic|ver u32|n u64|off_len u32|off blob|payload — BF16 uint16 elements.
|
|
4
|
+
save() accepts float32 (converted to BF16 with round-to-nearest-even, the same
|
|
5
|
+
bijection the C core uses) or uint16 passthrough; load() returns float32 always.
|
|
6
|
+
"""
|
|
7
|
+
import struct
|
|
8
|
+
import numpy as np
|
|
9
|
+
from .v7 import compress_bf16, decompress_bf16, BLK
|
|
10
|
+
from .bf16 import f32_to_bf16, bf16_to_f32
|
|
11
|
+
|
|
12
|
+
MAGIC = b"XN16"
|
|
13
|
+
|
|
14
|
+
def save(path, arr):
|
|
15
|
+
a = np.ascontiguousarray(arr)
|
|
16
|
+
if a.dtype == np.float32:
|
|
17
|
+
raw = f32_to_bf16(a)
|
|
18
|
+
elif a.dtype == np.uint16:
|
|
19
|
+
raw = a
|
|
20
|
+
else:
|
|
21
|
+
raise TypeError(f"unsupported dtype {a.dtype} (use float32 or uint16/BF16)")
|
|
22
|
+
payload, off = compress_bf16(raw)
|
|
23
|
+
n = a.size
|
|
24
|
+
hdr = MAGIC + struct.pack("<IQI", 1, n, len(off))
|
|
25
|
+
with open(path, "wb") as f:
|
|
26
|
+
f.write(hdr); f.write(off); f.write(payload.tobytes())
|
|
27
|
+
return path
|
|
28
|
+
|
|
29
|
+
def load(path):
|
|
30
|
+
with open(path, "rb") as f: blob = f.read()
|
|
31
|
+
if blob[:4] != MAGIC: raise ValueError("not an XN16 file")
|
|
32
|
+
ver, n, offlen = struct.unpack("<IQI", blob[4:20])
|
|
33
|
+
if ver != 1: raise ValueError(f"XN16 version {ver}")
|
|
34
|
+
off = blob[20:20 + offlen]
|
|
35
|
+
payload = np.frombuffer(blob[20 + offlen:], dtype=np.uint8)
|
|
36
|
+
raw = decompress_bf16(payload, off, ((n + BLK - 1) // BLK) * BLK)[:n]
|
|
37
|
+
return bf16_to_f32(raw)
|
|
38
|
+
|
|
39
|
+
def safetensors_save(path, tensors: dict):
|
|
40
|
+
"""Minimal safetensors writer, BF16 payloads XN16-compressed inside one file."""
|
|
41
|
+
import json
|
|
42
|
+
meta, blobs, pos = {}, b"", 0
|
|
43
|
+
for name, arr in tensors.items():
|
|
44
|
+
a = np.ascontiguousarray(arr, dtype=np.float32)
|
|
45
|
+
raw = f32_to_bf16(a)
|
|
46
|
+
payload, off = compress_bf16(raw)
|
|
47
|
+
import io
|
|
48
|
+
body = off + payload.tobytes()
|
|
49
|
+
meta[name] = {"dtype": "XN16<F32", "shape": list(a.shape), "offsets": (pos, len(body))}
|
|
50
|
+
blobs += body; pos += len(body)
|
|
51
|
+
hdr = json.dumps(meta, separators=(",", ":")).encode()
|
|
52
|
+
with open(path, "wb") as f:
|
|
53
|
+
f.write(struct.pack("<Q", len(hdr))); f.write(hdr); f.write(blobs)
|
|
54
|
+
|
|
55
|
+
def safetensors_load(path):
|
|
56
|
+
import json
|
|
57
|
+
with open(path, "rb") as f:
|
|
58
|
+
(hlen,) = struct.unpack("<Q", f.read(8)); hdr = json.loads(f.read(hlen)); blob = f.read()
|
|
59
|
+
out = {}
|
|
60
|
+
for name, m in hdr.items():
|
|
61
|
+
a, b = m["offsets"]; body = blob[a:b]
|
|
62
|
+
n = 1
|
|
63
|
+
for d in m["shape"]: n *= d
|
|
64
|
+
offlen = len(body) - (len(body) - ((n + BLK - 1) // BLK)) # recomputed below instead
|
|
65
|
+
# off table length is nblk*8 with nblk=ceil(pad_n/BLK); recover from payload start:
|
|
66
|
+
# we stored off then payload; parse by trying consistent split via stored n
|
|
67
|
+
nblk = (n + BLK - 1) // BLK
|
|
68
|
+
off = body[: nblk * 8]
|
|
69
|
+
payload = np.frombuffer(body[nblk * 8:], dtype=np.uint8)
|
|
70
|
+
raw = decompress_bf16(payload, off, nblk * BLK)[:n]
|
|
71
|
+
out[name] = bf16_to_f32(raw).reshape(m["shape"])
|
|
72
|
+
return out
|
xeno_py/v7.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""ctypes bindings to the XENO v7 BF16 codec (core/xeno_core.h).
|
|
2
|
+
|
|
3
|
+
Loads the prebuilt xeno_core.dll / libxeno_core.so shipped with the package,
|
|
4
|
+
falling back to the repo core/ directory, then to a local gcc build cache.
|
|
5
|
+
"""
|
|
6
|
+
import ctypes, os, subprocess, sys, tempfile
|
|
7
|
+
|
|
8
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
9
|
+
_REPO = os.path.dirname(os.path.dirname(_HERE)) # package source inside the xeno repo
|
|
10
|
+
_LIBNAME = "xeno_core.dll" if sys.platform == "win32" else "libxeno_core.so"
|
|
11
|
+
CORE_HDR = os.path.join(_HERE, "xeno_cross.h")
|
|
12
|
+
|
|
13
|
+
def _candidates():
|
|
14
|
+
for d in (os.path.join(_HERE, "_build"), _HERE, os.path.join(_REPO, "core")):
|
|
15
|
+
p = os.path.join(d, _LIBNAME)
|
|
16
|
+
if os.path.exists(p):
|
|
17
|
+
yield p
|
|
18
|
+
|
|
19
|
+
def _build():
|
|
20
|
+
"""Linux fallback: compile the bundled header-only codec on first import."""
|
|
21
|
+
if not os.path.exists(CORE_HDR):
|
|
22
|
+
raise FileNotFoundError("xeno_core binary not found and xeno_cross.h is not bundled")
|
|
23
|
+
cc = os.environ.get("CC", "gcc")
|
|
24
|
+
for d in (os.path.join(_HERE, "_build"), os.path.join(tempfile.gettempdir(), "xeno_py_build")):
|
|
25
|
+
try:
|
|
26
|
+
os.makedirs(d, exist_ok=True)
|
|
27
|
+
tmp_c = os.path.join(d, "xeno_api.c")
|
|
28
|
+
out = os.path.join(d, _LIBNAME)
|
|
29
|
+
with open(tmp_c, "w") as f: f.write('#include "xeno_cross.h"\n')
|
|
30
|
+
subprocess.check_call([cc, "-O3", "-mavx2", "-mbmi2", "-mfma", "-fopenmp",
|
|
31
|
+
"-shared", "-fPIC", "-I", _HERE, tmp_c, "-o", out, "-lm"])
|
|
32
|
+
return out
|
|
33
|
+
except OSError:
|
|
34
|
+
continue
|
|
35
|
+
raise RuntimeError("no writable build directory for the XENO codec")
|
|
36
|
+
|
|
37
|
+
def load():
|
|
38
|
+
"""Return the loaded xeno_core shared library."""
|
|
39
|
+
p = next(iter(_candidates()), None) or _build()
|
|
40
|
+
lib = ctypes.CDLL(p)
|
|
41
|
+
lib.xeno_compress_bf16.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p]
|
|
42
|
+
lib.xeno_compress_bf16.restype = ctypes.c_size_t
|
|
43
|
+
lib.xeno_decompress_bf16.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p]
|
|
44
|
+
lib.xeno_decompress_bf16.restype = None
|
|
45
|
+
return lib
|
|
46
|
+
|
|
47
|
+
lib = load()
|
|
48
|
+
BLK = 16384
|
|
49
|
+
|
|
50
|
+
def compress_bf16(w):
|
|
51
|
+
"""Compress a uint16 BF16 array (n multiple of 16384, padded by callers). -> (bytes, offsets)"""
|
|
52
|
+
import numpy as np
|
|
53
|
+
w = np.ascontiguousarray(w, dtype=np.uint16)
|
|
54
|
+
n = w.size
|
|
55
|
+
if n % BLK: w = np.pad(w, (0, BLK - n % BLK)); n = w.size
|
|
56
|
+
nblk = n // BLK
|
|
57
|
+
off = np.zeros(nblk, dtype=np.uint64 if ctypes.sizeof(ctypes.c_size_t) == 8 else np.uint32)
|
|
58
|
+
out = np.empty(nblk * (24 + BLK // 2 + BLK * 4) + 64, dtype=np.uint8)
|
|
59
|
+
csz = int(lib.xeno_compress_bf16(w.ctypes.data, n, out.ctypes.data, off.ctypes.data))
|
|
60
|
+
return out[:csz].copy(), off[: nblk].astype(np.uint64).tobytes()
|
|
61
|
+
|
|
62
|
+
def decompress_bf16(payload, off_bytes, n):
|
|
63
|
+
"""Inverse of compress_bf16. n = original element count."""
|
|
64
|
+
import numpy as np
|
|
65
|
+
nblk = len(off_bytes) // 8
|
|
66
|
+
off = np.frombuffer(off_bytes, dtype=np.uint64)
|
|
67
|
+
out = np.empty(nblk * BLK, dtype=np.uint16)
|
|
68
|
+
lib.xeno_decompress_bf16(payload.ctypes.data, off.ctypes.data, nblk * BLK, out.ctypes.data)
|
|
69
|
+
return out[:n]
|
xeno_py/vectordb.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""XENO-VectorDB: cosine top-k over BF16 vectors stored compressed (~75% RAM).
|
|
2
|
+
|
|
3
|
+
Vectors are normalized once, kept on disk/RAM as XN16 blocks, materialized to
|
|
4
|
+
float32 only for the search pass (the C-level GEMV-on-compressed path lives in
|
|
5
|
+
core/xeno_core.h / usecases/ and is exposed later).
|
|
6
|
+
"""
|
|
7
|
+
import numpy as np
|
|
8
|
+
from .tensors import save, load
|
|
9
|
+
from .bf16 import f32_to_bf16
|
|
10
|
+
from io import BytesIO
|
|
11
|
+
|
|
12
|
+
class VectorDB:
|
|
13
|
+
def __init__(self, dim):
|
|
14
|
+
if dim % 16: raise ValueError("dim must be a multiple of 16")
|
|
15
|
+
self.dim = dim; self.names = []; self._rows = np.zeros((0, dim), np.float32)
|
|
16
|
+
|
|
17
|
+
def add(self, name, vec):
|
|
18
|
+
v = np.asarray(vec, np.float32).reshape(-1)
|
|
19
|
+
if v.size != self.dim: raise ValueError("dim mismatch")
|
|
20
|
+
n = np.linalg.norm(v)
|
|
21
|
+
self.names.append(name)
|
|
22
|
+
self._rows = np.vstack([self._rows, (v / n if n else v)[None, :]])
|
|
23
|
+
|
|
24
|
+
def commit(self, path):
|
|
25
|
+
"""Freeze current rows into one compressed blob; search reads from it."""
|
|
26
|
+
save(path, self._rows.astype(np.float32))
|
|
27
|
+
self.path = path
|
|
28
|
+
|
|
29
|
+
def search(self, q, k=5, path=None):
|
|
30
|
+
p = path or getattr(self, "path", None)
|
|
31
|
+
rows = load(p) if p else self._rows.reshape(-1) # flat float32
|
|
32
|
+
rows = np.asarray(rows).reshape(-1, self.dim) # decompress ~GB/s, then BLAS
|
|
33
|
+
q = np.asarray(q, np.float32).reshape(-1); q = q / (np.linalg.norm(q) or 1.0)
|
|
34
|
+
sims = rows @ q
|
|
35
|
+
idx = np.argsort(-sims)[:k]
|
|
36
|
+
return [(self.names[i], float(sims[i])) for i in idx]
|
xeno_py/xeno_core.dll
ADDED
|
Binary file
|
xeno_py/xeno_cross.h
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* xeno_cross.h — Noyau XENO-CPU v7 Cross-Platform (Windows + Linux) avec Assembleur x86_64 Adaptatif
|
|
3
|
+
*
|
|
4
|
+
* Compilation Windows (MSYS2 / MinGW-w64) en DLL pour Python/C++/Unreal :
|
|
5
|
+
* gcc -O3 -march=native -mavx2 -mbmi2 -mfma -fopenmp -shared xeno_lib.c -o xeno_core.dll -lm
|
|
6
|
+
* Compilation Windows en EXE :
|
|
7
|
+
* gcc -O3 -march=native -mavx2 -mbmi2 -mfma -fopenmp xeno_lib.c -o xeno_test.exe -lm
|
|
8
|
+
* Compilation Linux :
|
|
9
|
+
* gcc -O3 -march=native -mavx2 -mbmi2 -mfma -fopenmp xeno_lib.c -o xeno_test -lm
|
|
10
|
+
*/
|
|
11
|
+
#ifndef XENO_CROSS_H
|
|
12
|
+
#define XENO_CROSS_H
|
|
13
|
+
|
|
14
|
+
#include <stdio.h>
|
|
15
|
+
#include <stdlib.h>
|
|
16
|
+
#include <stdint.h>
|
|
17
|
+
#include <string.h>
|
|
18
|
+
#include <math.h>
|
|
19
|
+
#include <immintrin.h>
|
|
20
|
+
#include <omp.h>
|
|
21
|
+
|
|
22
|
+
#ifdef _WIN32
|
|
23
|
+
#define WIN32_LEAN_AND_MEAN
|
|
24
|
+
#include <windows.h>
|
|
25
|
+
#include <malloc.h>
|
|
26
|
+
#define XENO_API __declspec(dllexport)
|
|
27
|
+
static inline void *xeno_alloc(size_t align, size_t sz) { return _aligned_malloc((sz + align - 1) & ~(align - 1), align); }
|
|
28
|
+
static inline void xeno_free(void *p) { _aligned_free(p); }
|
|
29
|
+
static inline double xeno_now_sec(void) {
|
|
30
|
+
LARGE_INTEGER freq, cnt;
|
|
31
|
+
QueryPerformanceFrequency(&freq);
|
|
32
|
+
QueryPerformanceCounter(&cnt);
|
|
33
|
+
return (double)cnt.QuadPart / (double)freq.QuadPart;
|
|
34
|
+
}
|
|
35
|
+
#else
|
|
36
|
+
#include <time.h>
|
|
37
|
+
#define XENO_API __attribute__((visibility("default")))
|
|
38
|
+
static inline void *xeno_alloc(size_t align, size_t sz) { return aligned_alloc(align, (sz + align - 1) & ~(align - 1)); }
|
|
39
|
+
static inline void xeno_free(void *p) { free(p); }
|
|
40
|
+
static inline double xeno_now_sec(void) {
|
|
41
|
+
struct timespec ts;
|
|
42
|
+
clock_gettime(CLOCK_MONOTONIC, &ts);
|
|
43
|
+
return ts.tv_sec + ts.tv_nsec * 1e-9;
|
|
44
|
+
}
|
|
45
|
+
#endif
|
|
46
|
+
|
|
47
|
+
#define XENO_V7_BLK 16384
|
|
48
|
+
typedef struct { uint8_t lut16[16]; uint32_t n_exc, exc_off, total_bytes; } __attribute__((packed)) XenoV7Hdr;
|
|
49
|
+
typedef struct { uint16_t idx; uint8_t exp_val; } __attribute__((packed)) XenoV7Exc;
|
|
50
|
+
|
|
51
|
+
static inline uint16_t xeno_f32_to_bf16(float f) { uint32_t u; memcpy(&u,&f,4); u+=0x7FFF+((u>>16)&1); return (uint16_t)(u>>16); }
|
|
52
|
+
static inline float xeno_bf16_to_f32(uint16_t b) { uint32_t u=(uint32_t)b<<16; float f; memcpy(&f,&u,4); return f; }
|
|
53
|
+
|
|
54
|
+
static inline size_t xeno_v7_enc_blk(const uint16_t *restrict w, uint8_t *restrict out, const uint8_t lut16[16], const __m256i vl[15]) {
|
|
55
|
+
XenoV7Hdr *h=(XenoV7Hdr*)out; memcpy(h->lut16,lut16,16);
|
|
56
|
+
uint8_t *nib=out+sizeof(XenoV7Hdr), *sm=nib+(XENO_V7_BLK/2); XenoV7Exc *ex=(XenoV7Exc*)(sm+XENO_V7_BLK); uint32_t ne=0;
|
|
57
|
+
const __m256i mff=_mm256_set1_epi16(0x00FF),m80=_mm256_set1_epi16(0x0080),m7f=_mm256_set1_epi16(0x007F),v15=_mm256_set1_epi8(15);
|
|
58
|
+
for(uint32_t i=0;i<XENO_V7_BLK;i+=32){
|
|
59
|
+
__m256i w0=_mm256_loadu_si256((const __m256i*)(w+i)), w1=_mm256_loadu_si256((const __m256i*)(w+i+16));
|
|
60
|
+
__m256i e32=_mm256_permute4x64_epi64(_mm256_packus_epi16(_mm256_and_si256(_mm256_srli_epi16(w0,7),mff),_mm256_and_si256(_mm256_srli_epi16(w1,7),mff)),0xD8);
|
|
61
|
+
__m256i s32=_mm256_permute4x64_epi64(_mm256_packus_epi16(_mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(w0,8),m80),_mm256_and_si256(w0,m7f)),_mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(w1,8),m80),_mm256_and_si256(w1,m7f))),0xD8);
|
|
62
|
+
_mm256_storeu_si256((__m256i*)(sm+i),s32); __m256i mt=_mm256_setzero_si256(), ac=_mm256_setzero_si256();
|
|
63
|
+
#pragma GCC unroll 15
|
|
64
|
+
for(int k=0;k<15;k++){ __m256i eq=_mm256_cmpeq_epi8(e32,vl[k]); mt=_mm256_or_si256(mt,eq); ac=_mm256_or_si256(ac,_mm256_and_si256(eq,_mm256_set1_epi8((char)k))); }
|
|
65
|
+
__m256i cd=_mm256_or_si256(ac,_mm256_andnot_si256(mt,v15)); uint32_t em=(uint32_t)(~_mm256_movemask_epi8(mt));
|
|
66
|
+
if(__builtin_expect(em!=0,0)){ uint8_t te[32]; _mm256_storeu_si256((__m256i*)te,e32); while(em){ int b=__builtin_ctz(em); ex[ne].idx=(uint16_t)(i+b); ex[ne].exp_val=te[b]; ne++; em&=em-1; } }
|
|
67
|
+
_mm_storeu_si128((__m128i*)(nib+(i>>1)), _mm_or_si128(_mm256_castsi256_si128(cd), _mm_slli_epi16(_mm256_extracti128_si256(cd,1),4)));
|
|
68
|
+
}
|
|
69
|
+
h->n_exc=ne; h->exc_off=(uint32_t)(sizeof(XenoV7Hdr)+(XENO_V7_BLK/2)+XENO_V7_BLK); h->total_bytes=h->exc_off+ne*(uint32_t)sizeof(XenoV7Exc); return h->total_bytes;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Décodeur ASM x86_64 écrit à la main (GCC/Clang/MinGW ; repli intrinsics AVX2 sinon).
|
|
73
|
+
// non_temporal : >16 MiB (DRAM) -> vmovntdq + prefetcht0 (0 RFO) ; sinon vmovdqu (cache L3).
|
|
74
|
+
static inline void xeno_v7_dec_blk_fast(const uint8_t *restrict in, uint16_t *restrict wo, int non_temporal) {
|
|
75
|
+
const XenoV7Hdr *h=(const XenoV7Hdr*)in; const uint8_t *nib=in+sizeof(XenoV7Hdr), *sm=nib+(XENO_V7_BLK/2);
|
|
76
|
+
#if defined(__GNUC__) || defined(__clang__)
|
|
77
|
+
static const uint8_t __attribute__((aligned(32))) c_m0f[16] = {15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15};
|
|
78
|
+
static const uint16_t __attribute__((aligned(32))) c_m80[16] = {0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80};
|
|
79
|
+
static const uint16_t __attribute__((aligned(32))) c_m7f[16] = {0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F};
|
|
80
|
+
uint64_t cnt=XENO_V7_BLK/32; uint8_t *ob=(uint8_t*)wo; const uint8_t *np=nib,*sp=sm;
|
|
81
|
+
if (non_temporal && (((uintptr_t)wo & 31u) == 0)) {
|
|
82
|
+
__asm__ volatile (
|
|
83
|
+
"vbroadcasti128 (%[lut]),%%ymm0\n\tvmovdqa (%[m0f]),%%xmm1\n\tvmovdqa (%[m80]),%%ymm2\n\tvmovdqa (%[m7f]),%%ymm3\n\t.p2align 4\n\t1:\n\t"
|
|
84
|
+
"prefetcht0 256(%[nib])\n\tprefetcht0 512(%[sm])\n\t"
|
|
85
|
+
"vmovdqu (%[nib]),%%xmm4\n\tvpsrlw $4,%%xmm4,%%xmm5\n\tvpand %%xmm1,%%xmm4,%%xmm4\n\tvpand %%xmm1,%%xmm5,%%xmm5\n\t"
|
|
86
|
+
"vinserti128 $1,%%xmm5,%%ymm4,%%ymm4\n\tvpshufb %%ymm4,%%ymm0,%%ymm4\n\t"
|
|
87
|
+
"vpmovzxbw %%xmm4,%%ymm5\n\tvextracti128 $1,%%ymm4,%%xmm4\n\tvpmovzxbw %%xmm4,%%ymm6\n\t"
|
|
88
|
+
"vpmovzxbw (%[sm]),%%ymm7\n\tvpmovzxbw 16(%[sm]),%%ymm8\n\t"
|
|
89
|
+
"vpand %%ymm2,%%ymm7,%%ymm9\n\tvpsllw $8,%%ymm9,%%ymm9\n\tvpand %%ymm3,%%ymm7,%%ymm7\n\tvpsllw $7,%%ymm5,%%ymm5\n\tvpor %%ymm7,%%ymm5,%%ymm5\n\tvpor %%ymm9,%%ymm5,%%ymm5\n\t"
|
|
90
|
+
"vpand %%ymm2,%%ymm8,%%ymm10\n\tvpsllw $8,%%ymm10,%%ymm10\n\tvpand %%ymm3,%%ymm8,%%ymm8\n\tvpsllw $7,%%ymm6,%%ymm6\n\tvpor %%ymm8,%%ymm6,%%ymm6\n\tvpor %%ymm10,%%ymm6,%%ymm6\n\t"
|
|
91
|
+
"vmovntdq %%ymm5,(%[out])\n\tvmovntdq %%ymm6,32(%[out])\n\t"
|
|
92
|
+
"add $16,%[nib]\n\tadd $32,%[sm]\n\tadd $64,%[out]\n\tdec %[cnt]\n\tjnz 1b\n\t"
|
|
93
|
+
: [nib]"+r"(np),[sm]"+r"(sp),[out]"+r"(ob),[cnt]"+r"(cnt)
|
|
94
|
+
: [lut]"r"(h->lut16),[m0f]"r"(c_m0f),[m80]"r"(c_m80),[m7f]"r"(c_m7f)
|
|
95
|
+
: "ymm0","ymm1","ymm2","ymm3","ymm4","ymm5","ymm6","ymm7","ymm8","ymm9","ymm10","cc","memory");
|
|
96
|
+
_mm_sfence();
|
|
97
|
+
} else {
|
|
98
|
+
__asm__ volatile (
|
|
99
|
+
"vbroadcasti128 (%[lut]),%%ymm0\n\tvmovdqa (%[m0f]),%%xmm1\n\tvmovdqa (%[m80]),%%ymm2\n\tvmovdqa (%[m7f]),%%ymm3\n\t.p2align 4\n\t1:\n\t"
|
|
100
|
+
"vmovdqu (%[nib]),%%xmm4\n\tvpsrlw $4,%%xmm4,%%xmm5\n\tvpand %%xmm1,%%xmm4,%%xmm4\n\tvpand %%xmm1,%%xmm5,%%xmm5\n\t"
|
|
101
|
+
"vinserti128 $1,%%xmm5,%%ymm4,%%ymm4\n\tvpshufb %%ymm4,%%ymm0,%%ymm4\n\t"
|
|
102
|
+
"vpmovzxbw %%xmm4,%%ymm5\n\tvextracti128 $1,%%ymm4,%%xmm4\n\tvpmovzxbw %%xmm4,%%ymm6\n\t"
|
|
103
|
+
"vpmovzxbw (%[sm]),%%ymm7\n\tvpmovzxbw 16(%[sm]),%%ymm8\n\t"
|
|
104
|
+
"vpand %%ymm2,%%ymm7,%%ymm9\n\tvpsllw $8,%%ymm9,%%ymm9\n\tvpand %%ymm3,%%ymm7,%%ymm7\n\tvpsllw $7,%%ymm5,%%ymm5\n\tvpor %%ymm7,%%ymm5,%%ymm5\n\tvpor %%ymm9,%%ymm5,%%ymm5\n\t"
|
|
105
|
+
"vpand %%ymm2,%%ymm8,%%ymm10\n\tvpsllw $8,%%ymm10,%%ymm10\n\tvpand %%ymm3,%%ymm8,%%ymm8\n\tvpsllw $7,%%ymm6,%%ymm6\n\tvpor %%ymm8,%%ymm6,%%ymm6\n\tvpor %%ymm10,%%ymm6,%%ymm6\n\t"
|
|
106
|
+
"vmovdqu %%ymm5,(%[out])\n\tvmovdqu %%ymm6,32(%[out])\n\t"
|
|
107
|
+
"add $16,%[nib]\n\tadd $32,%[sm]\n\tadd $64,%[out]\n\tdec %[cnt]\n\tjnz 1b\n\t"
|
|
108
|
+
: [nib]"+r"(np),[sm]"+r"(sp),[out]"+r"(ob),[cnt]"+r"(cnt)
|
|
109
|
+
: [lut]"r"(h->lut16),[m0f]"r"(c_m0f),[m80]"r"(c_m80),[m7f]"r"(c_m7f)
|
|
110
|
+
: "ymm0","ymm1","ymm2","ymm3","ymm4","ymm5","ymm6","ymm7","ymm8","ymm9","ymm10","cc","memory");
|
|
111
|
+
}
|
|
112
|
+
#else
|
|
113
|
+
(void)non_temporal;
|
|
114
|
+
__m256i lut=_mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)h->lut16));
|
|
115
|
+
const __m128i m0f=_mm_set1_epi8(0x0F); const __m256i m80=_mm256_set1_epi16(0x0080), m7f=_mm256_set1_epi16(0x007F);
|
|
116
|
+
for(uint32_t i=0;i<XENO_V7_BLK;i+=32){
|
|
117
|
+
__m128i nb=_mm_loadu_si128((const __m128i*)(nib+(i>>1)));
|
|
118
|
+
__m256i e32=_mm256_shuffle_epi8(lut,_mm256_set_m128i(_mm_and_si128(_mm_srli_epi16(nb,4),m0f),_mm_and_si128(nb,m0f)));
|
|
119
|
+
__m256i s32=_mm256_loadu_si256((const __m256i*)(sm+i));
|
|
120
|
+
__m256i el=_mm256_cvtepu8_epi16(_mm256_castsi256_si128(e32)), eh=_mm256_cvtepu8_epi16(_mm256_extracti128_si256(e32,1));
|
|
121
|
+
__m256i sl=_mm256_cvtepu8_epi16(_mm256_castsi256_si128(s32)), sh=_mm256_cvtepu8_epi16(_mm256_extracti128_si256(s32,1));
|
|
122
|
+
_mm256_storeu_si256((__m256i*)(wo+i), _mm256_or_si256(_mm256_slli_epi16(_mm256_and_si256(sl,m80),8),_mm256_or_si256(_mm256_slli_epi16(el,7),_mm256_and_si256(sl,m7f))));
|
|
123
|
+
_mm256_storeu_si256((__m256i*)(wo+i+16), _mm256_or_si256(_mm256_slli_epi16(_mm256_and_si256(sh,m80),8),_mm256_or_si256(_mm256_slli_epi16(eh,7),_mm256_and_si256(sh,m7f))));
|
|
124
|
+
}
|
|
125
|
+
#endif
|
|
126
|
+
if(__builtin_expect(h->n_exc>0,0)){ const XenoV7Exc *ex=(const XenoV7Exc*)(in+h->exc_off); for(uint32_t k=0;k<h->n_exc;k++){ uint16_t id=ex[k].idx,s=sm[id]; wo[id]=(uint16_t)(((s&0x80)<<8)|((uint16_t)ex[k].exp_val<<7)|(s&0x7F)); } }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// API DLL/SO callable depuis Python ctypes / C++ / Unreal / Rust
|
|
130
|
+
XENO_API size_t xeno_compress_bf16(const uint16_t *w, size_t n_weights, uint8_t *out_buf, size_t *offsets_out) {
|
|
131
|
+
size_t nblk = n_weights / XENO_V7_BLK;
|
|
132
|
+
uint32_t cnt[256]={0}; size_t samp = n_weights>262144?262144:n_weights;
|
|
133
|
+
for(size_t i=0;i<samp;i++) cnt[(w[i]>>7)&0xFF]++;
|
|
134
|
+
uint8_t lut[16]={0}; __m256i vl[15];
|
|
135
|
+
for(int k=0;k<15;k++){ int b=0; for(int s=1;s<256;s++) if(cnt[s]>cnt[b]) b=s; lut[k]=(uint8_t)b; vl[k]=_mm256_set1_epi8((char)b); cnt[b]=0; }
|
|
136
|
+
size_t stride=sizeof(XenoV7Hdr)+XENO_V7_BLK/2+XENO_V7_BLK*4; // pire cas: chaque u16 une exception (3 o)
|
|
137
|
+
uint8_t *tmp=xeno_alloc(64, nblk*stride); size_t *sz=malloc(nblk*sizeof(size_t));
|
|
138
|
+
#pragma omp parallel for schedule(static)
|
|
139
|
+
for(size_t b=0;b<nblk;b++) sz[b]=xeno_v7_enc_blk(w+b*XENO_V7_BLK, tmp+b*stride, lut, vl);
|
|
140
|
+
size_t tot=0; for(size_t b=0;b<nblk;b++){ offsets_out[b]=tot; memcpy(out_buf+tot, tmp+b*stride, sz[b]); tot+=sz[b]; }
|
|
141
|
+
xeno_free(tmp); free(sz); return tot;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
XENO_API void xeno_decompress_bf16(const uint8_t *in_buf, const size_t *offsets, size_t n_weights, uint16_t *w_out) {
|
|
145
|
+
size_t nblk = n_weights / XENO_V7_BLK;
|
|
146
|
+
int nt = ((n_weights * 2) > (16ULL * 1024 * 1024)) ? 1 : 0; // Adaptatif L3 vs Non-Temporal DRAM
|
|
147
|
+
#pragma omp parallel for schedule(static)
|
|
148
|
+
for(size_t b=0;b<nblk;b++) xeno_v7_dec_blk_fast(in_buf + offsets[b], w_out + b*XENO_V7_BLK, nt);
|
|
149
|
+
}
|
|
150
|
+
#endif
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: xenocodec
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: XENO lossless compression for AI weights: BF16 at ~75%, bit-exact, 100 GB/s-class SIMD decode
|
|
5
|
+
Author: Romain Abdel-Aal
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Topic :: System :: Archiving :: Compression
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Provides-Extra: numpy
|
|
12
|
+
Requires-Dist: numpy; extra == "numpy"
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: numpy; extra == "dev"
|
|
15
|
+
Requires-Dist: pytest; extra == "dev"
|
|
16
|
+
|
|
17
|
+
# xeno_py
|
|
18
|
+
|
|
19
|
+
PyPI distribution: **`xenocodec`** (`pip install xenocodec`, then `import xeno_py`).
|
|
20
|
+
|
|
21
|
+
Python bindings for the XENO v7 BF16 codec (`core/xeno_cross.h`), plus a small
|
|
22
|
+
compressed tensor container and a vector index.
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import numpy as np, xeno_py
|
|
26
|
+
w = np.random.randn(16384 * 4).astype(np.float32) # any float32 tensor
|
|
27
|
+
xeno_py.save("w.xn16", w) # BF16 + XENO v7, bit-exact
|
|
28
|
+
back = xeno_py.load("w.xn16") # float32 (BF16 projection)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
What it is, honestly:
|
|
32
|
+
|
|
33
|
+
- `compress_bf16` / `decompress_bf16` are **lossless on the BF16 payload**: the
|
|
34
|
+
roundtrip is `memcmp == 0` on uint16 BF16 values.
|
|
35
|
+
- `save` / `load` convert float32 to BF16 first (round-to-nearest-even), so a
|
|
36
|
+
float32 tensor comes back as its BF16 projection, not bit-identical float32.
|
|
37
|
+
That projection is the only loss, and it is the same bijection the C core uses.
|
|
38
|
+
- The ratio (~75% of raw BF16 on weight-like data) depends on the exponent
|
|
39
|
+
distribution; random uniform BF16 compresses poorly, as it should.
|
|
40
|
+
- Measured here (2 MiB, best of 3): gaussian weights XENO 75.13% vs zlib -9
|
|
41
|
+
79.46% / lzma 71.76%; uniform random BF16 XENO 216.21% vs zlib 100.03%.
|
|
42
|
+
v7 is a weight format with no raw-block escape, so it **expands**
|
|
43
|
+
incompressible input: it is not a general-purpose compressor. Use the XN27
|
|
44
|
+
auto codec (`bin/xeno.exe`) for arbitrary files.
|
|
45
|
+
- `VectorDB` keeps normalized vectors compressed on disk and materializes them
|
|
46
|
+
for the search pass. The GEMV-on-compressed path is not wired here yet.
|
|
47
|
+
|
|
48
|
+
The package loads a prebuilt `xeno_core.dll` shipped inside `xeno_py/` on
|
|
49
|
+
Windows. On Linux it compiles the bundled header-only `xeno_cross.h` with gcc on
|
|
50
|
+
first import (AVX2 + OpenMP required), caching the `.so` next to the package or
|
|
51
|
+
in the system temp dir. In the repo it also falls back to `core/`.
|
|
52
|
+
|
|
53
|
+
Install from the repo: `pip install ./xeno_py` (needs numpy for the tensor API).
|
|
54
|
+
|
|
55
|
+
Benchmark (bit-exactness is asserted, ratio is compared to zlib -9 and lzma):
|
|
56
|
+
|
|
57
|
+
```powershell
|
|
58
|
+
python xeno_py/benchmarks/bench.py
|
|
59
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
xeno_py/__init__.py,sha256=x5yEafEcY4aUECFvAqBVm1ND1UggwtH9khQG8yvyPYQ,295
|
|
2
|
+
xeno_py/bf16.py,sha256=rsZfmSdu5T-6qTmgn7h3ySpSBaZD4kFuDHa_kgIG-x8,403
|
|
3
|
+
xeno_py/tensors.py,sha256=l0lqCMrtV8nDgm34V1hXtA56QluqGdCMmFSYotMPlGk,2919
|
|
4
|
+
xeno_py/v7.py,sha256=MEz_bqMCl0LrL-s1VlZ2Y5ADbq7uslAqP5DmoiiqQEk,3130
|
|
5
|
+
xeno_py/vectordb.py,sha256=QtrmLNAX77UUysfpfFxrLMEnGyXPrBYdM4SXb5z7CbE,1528
|
|
6
|
+
xeno_py/xeno_core.dll,sha256=veJcal9zCjevL87UBcM7MOVJS36A_AaYdjcZ1Dy8Zd4,45932
|
|
7
|
+
xeno_py/xeno_cross.h,sha256=KPfKVWm4S-dtgdDhQ5BbToaA_CIGQ-DfXysl73E46bc,10825
|
|
8
|
+
xenocodec-0.3.0.dist-info/METADATA,sha256=z12h0gQ1xrv7a2SCjnzA50GcpMTIudjEKVjOzD-pCFw,2635
|
|
9
|
+
xenocodec-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
xenocodec-0.3.0.dist-info/top_level.txt,sha256=TZc63J3tYCe0vfM0Ojvr3-12PzKNeQ-vsQdiwRABXBs,8
|
|
11
|
+
xenocodec-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
xeno_py
|