"""Teveration 1 in Python: a thin binding of the C++ engine (libteveration), which runs the GGUF files. from teveration import Teveration tev = Teveration() # downloads the model and the engine on first use images = tev.text_to_image(["A lighthouse on a rocky cliff under a stormy sky."], seed=0) # uint8 [B, 512, 512, 3] images = tev.image_to_image(pictures, "colorize") # tasks: hed, depth, colorize, anime, ghibli, watercolor maps = tev.dense_predict(pictures) # {"seg", "depth", "normal"} The weights stay packed in memory (ternary backbone, 4-bit adapter and head), so the model needs about its file size in RAM or VRAM, on any GPU the engine has a backend for (CUDA, Vulkan, Metal) or on the CPU. """ import ctypes import json import os import platform import sys import urllib.request import zipfile import numpy as np VERSION = "1.0.1" HF_REPO = "DmitrofNET/Teveration-1" GH_RELEASE = f"https://github.com/DmitrofNETDev/Teveration-1/releases/download/v{VERSION}/" GGUF = {"backbone": "Teveration-1-backbone-PTQ1_0.gguf", "image": "Teveration-1-image-Q4_0.gguf", "mmproj": "Teveration-1-mmproj-Q8_0.gguf"} # the low-rank path comes in three precisions; the rest of the model is the same ADAPTERS = {"small": "Teveration-1-adapter-Q4_0.gguf", "balanced": "Teveration-1-adapter-Q6_mix.gguf", "high": "Teveration-1-adapter-Q8_0.gguf"} I2I_TASKS = ("hed", "depth", "colorize", "anime", "ghibli", "watercolor") NYU13 = ("bed", "books", "ceiling", "chair", "floor", "furniture", "objects", "picture", "sofa", "table", "tv", "wall", "window") def cache_dir(): return os.environ.get("TEVERATION_HOME") or os.path.join(os.path.expanduser("~"), ".cache", "teveration") def _download(url, path, what): os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".part" have = os.path.getsize(tmp) if os.path.exists(tmp) else 0 req = urllib.request.Request(url, headers={"Range": f"bytes={have}-", "User-Agent": "teveration"} if have else {"User-Agent": "teveration"}) print(f"teveration: downloading {what}", file=sys.stderr, flush=True) with urllib.request.urlopen(req) as r, open(tmp, "ab" if have and r.status == 206 else "wb") as f: while True: chunk = r.read(1 << 22) if not chunk: break f.write(chunk) os.replace(tmp, path) def locate_model(model=None, vision=True, quality="balanced"): """-> (path, quality): the one-file model, or a folder with the four parts. model: a one-file model (Teveration-1-.gguf), a folder that holds one, a folder with the four parts, or None: then the one-file model of this quality is downloaded from Hugging Face.""" model = model or os.environ.get("TEVERATION_MODEL") if model and os.path.isfile(model): return model, _kv_get(gguf_header(model), "single.quality") or quality if model and os.path.isdir(model): names = [n for k, n in list(GGUF.items()) + [("adapter", ADAPTERS[quality])] if vision or k != "mmproj"] if all(os.path.exists(os.path.join(model, n)) for n in names): return model, quality if model is None: try: # the standard Hugging Face cache, shared with every other tool from huggingface_hub import hf_hub_download return hf_hub_download(HF_REPO, SINGLE[quality]), quality except ImportError: model = os.path.join(cache_dir(), "model") path = os.path.join(model, SINGLE[quality]) if not os.path.exists(path): _download(f"https://huggingface.co/{HF_REPO}/resolve/main/{SINGLE[quality]}", path, SINGLE[quality]) return path, quality def resolve_model(model=None, vision=True, quality="balanced"): """-> (folder with the model's four parts, quality): for engines older than 1.0.1, which cannot read a one-file model in place. The parts of a one-file model are written to the cache.""" path, quality = locate_model(model, vision, quality) return (path, quality) if os.path.isdir(path) else unpack_single(path, vision) def reads_single(lib): """True when this engine library reads one-file models in place (1.0.1 on)""" import mmap with open(lib, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: return m.find(b"tev_load_file") >= 0 def find_model(folder=None, vision=True, quality="balanced"): """the folder that holds the model's parts for the engine; a missing model is downloaded from Hugging Face""" return resolve_model(folder, vision, quality)[0] # ---- one-file models --------------------------------------------------------------------------------------------------------- # Teveration-1-.gguf holds the four parts in one GGUF: the backbone's metadata and tensors under their own names, the # other parts under a prefix (metadata "part..", tensors PART_PREFIX), and "single..*" says where each part's data is. SINGLE = {"small": "Teveration-1-small.gguf", "balanced": "Teveration-1-balanced.gguf", "high": "Teveration-1-high.gguf"} PART_PREFIX = {"backbone": "", "image": "img.", "adapter": "adp.", "mmproj": "mmp."} _SCALAR = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8} def _gguf_str(s): b = s.encode() return len(b).to_bytes(8, "little") + b def gguf_header(path): """the header of a GGUF file: {"kv": [(key, raw type + value bytes)], "tensors": [(name, raw dims + type bytes, offset)], "data": where the tensor data starts, "align", "size", "version"}""" size, want = os.path.getsize(path), 1 << 24 while True: with open(path, "rb") as f: b = f.read(want) try: return _gguf_parse(b, size) except IndexError: if want >= size: raise ValueError(f"{path} is not a complete GGUF file") from None want *= 8 def _gguf_parse(b, size): u32 = lambda p: int.from_bytes(b[p:p + 4], "little") # noqa: E731 u64 = lambda p: int.from_bytes(b[p:p + 8], "little") # noqa: E731 def need(p): if p > len(b): raise IndexError return p def string(p): n = u64(need(p + 8) - 8) return b[p + 8:need(p + 8 + n)].decode(), p + 8 + n def value(p, t): if t in _SCALAR: return p + _SCALAR[t] if t == 8: return need(p + 8) + u64(p) if t != 9: raise ValueError(f"unknown GGUF value type {t}") et, n = u32(need(p + 12) - 12), u64(p + 4) p += 12 if et in _SCALAR: return p + _SCALAR[et] * n for _ in range(n): p = value(p, et) return p if b[:4] != b"GGUF": raise ValueError("not a GGUF file") version, nt, nkv, p, kv, tensors, align = u32(4), u64(8), u64(16), 24, [], [], 32 for _ in range(nkv): key, p = string(p) end = need(value(need(p + 4), u32(p))) if key == "general.alignment": align = u32(p + 4) kv.append((key, b[p:end])) p = end for _ in range(nt): name, p = string(p) end = need(p + 4 + 8 * u32(need(p + 4) - 4) + 4 + 8) tensors.append((name, b[p:end - 8], u64(end - 8))) p = end return {"kv": kv, "tensors": tensors, "data": -(-p // align) * align, "align": align, "size": size, "version": version} def _kv_get(h, key): for k, raw in h["kv"]: if k == key: t = int.from_bytes(raw[:4], "little") return raw[12:].decode() if t == 8 else int.from_bytes(raw[4:], "little") return None def is_single(path): """True for a one-file model""" try: return bool(path) and os.path.isfile(path) and _kv_get(gguf_header(path), "single.version") is not None except (ValueError, OSError): return False def _gguf_write_head(f, version, kv, tensors, align): f.write(b"GGUF" + version.to_bytes(4, "little") + len(tensors).to_bytes(8, "little") + len(kv).to_bytes(8, "little")) for key, raw in kv: f.write(_gguf_str(key) + raw) for name, raw, off in tensors: f.write(_gguf_str(name) + raw + off.to_bytes(8, "little")) f.write(b"\0" * (-f.tell() % align)) def _copy(src, dst, start, n): src.seek(start) while n > 0: chunk = src.read(min(n, 1 << 24)) if not chunk: raise ValueError("the file is shorter than its header says") dst.write(chunk) n -= len(chunk) def unpack_single(path, vision=True): """A one-file model -> the folder with its parts as the engine loads them (written once, to the cache), and its quality.""" h = gguf_header(path) quality = _kv_get(h, "single.quality") st = os.stat(path) root = os.path.join(cache_dir(), "parts") folder = os.path.join(root, f"{os.path.basename(path)[:-5]}-{st.st_size:x}-p{st.st_mtime_ns:x}") names = dict(GGUF, adapter=ADAPTERS[quality]) todo = [p for p in PART_PREFIX if (vision or p != "mmproj") and not os.path.exists(os.path.join(folder, names[p]))] if not todo: return folder, quality if os.path.isdir(root): # parts of an older copy of the same file import shutil for d in os.listdir(root): if d.startswith(os.path.basename(path)[:-5] + "-") and "-p" in d and os.path.join(root, d) != folder: shutil.rmtree(os.path.join(root, d), ignore_errors=True) os.makedirs(folder, exist_ok=True) print(f"teveration: unpacking {os.path.basename(path)} (once)", file=sys.stderr, flush=True) others = tuple(v for v in PART_PREFIX.values() if v) with open(path, "rb") as src: for part in todo: pre, kpre = PART_PREFIX[part], f"part.{part}." if part == "backbone": kv = [(k, r) for k, r in h["kv"] if not k.startswith(("part.", "single."))] tensors = [t for t in h["tensors"] if not t[0].startswith(others)] else: kv = [(k[len(kpre):], r) for k, r in h["kv"] if k.startswith(kpre)] tensors = [t for t in h["tensors"] if t[0].startswith(pre)] start, size = _kv_get(h, f"single.{part}.offset"), _kv_get(h, f"single.{part}.size") tmp = os.path.join(folder, names[part] + ".part") with open(tmp, "wb") as f: _gguf_write_head(f, h["version"], kv, [(n[len(pre):], r, o - start) for n, r, o in tensors], h["align"]) _copy(src, f, h["data"] + start, size) os.replace(tmp, os.path.join(folder, names[part])) return folder, quality def local_model(path): """path if it is a folder that already holds the GGUF files (a clone or snapshot of the repository), else None""" if path and os.path.isdir(path) and (os.path.exists(os.path.join(path, GGUF["backbone"])) or any(os.path.exists(os.path.join(path, n)) for n in SINGLE.values())): return path return path if path and os.path.isfile(path) and path.endswith(".gguf") else None def _lib_name(): return {"Windows": "libteveration.dll", "Darwin": "libteveration.dylib"}.get(platform.system(), "libteveration.so") def _has_nvidia(): if platform.system() == "Windows": return os.path.exists(os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "nvcuda.dll")) return os.path.exists("/proc/driver/nvidia/version") def engine_variant(device="auto"): """which prebuilt engine fits this machine: --""" system, machine = platform.system(), platform.machine().lower() arch = "arm64" if machine in ("arm64", "aarch64") else "x64" if system == "Darwin": return f"macos-{arch}-metal" name = "win" if system == "Windows" else "linux" if device == "auto": device = "cuda" if _has_nvidia() else "vulkan" return f"{name}-{arch}-{ {'cuda': 'cuda', 'vulkan': 'vulkan', 'cpu': 'cpu'}[device] }" def find_library(device="auto"): """libteveration: $TEVERATION_LIB, next to this package (teveration/bin), the cache, or the release of this version""" env = os.environ.get("TEVERATION_LIB") if env: return env here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bin", _lib_name()) if os.path.exists(here): return here variant = engine_variant(device) folder = os.path.join(cache_dir(), "engine", f"{VERSION}-{variant}") path = os.path.join(folder, _lib_name()) if not os.path.exists(path): archive = os.path.join(folder, "engine.zip") _download(f"{GH_RELEASE}teveration-{VERSION}-{variant}.zip", archive, f"the engine ({variant})") with zipfile.ZipFile(archive) as z: z.extractall(folder) os.remove(archive) return path def _cuda_runtime(lib): """The CUDA build needs NVIDIA's runtime libraries (cudart, cublas). They are found next to the engine, in a CUDA Toolkit, or in a PyTorch / nvidia-* pip install; on Windows, when they are nowhere, the release's copy is fetched.""" folder = os.path.dirname(os.path.abspath(lib)) if platform.system() == "Windows": if any(os.path.exists(os.path.join(d, "cublas64_12.dll")) for d in _dll_dirs(lib)): return if os.path.dirname(folder).startswith(os.path.join(cache_dir(), "engine")) or folder.startswith(os.path.join(cache_dir(), "engine")): archive = os.path.join(folder, "cudart.zip") _download(GH_RELEASE + "cudart-win-x64-cuda12.zip", archive, "the CUDA runtime libraries") with zipfile.ZipFile(archive) as z: z.extractall(folder) os.remove(archive) elif platform.system() == "Linux": for p in sys.path: # pip's nvidia-cublas-cu12 / nvidia-cuda-runtime-cu12, as PyTorch installs them for sub, name in (("cuda_runtime", "libcudart.so.12"), ("cublas", "libcublasLt.so.12"), ("cublas", "libcublas.so.12")): f = os.path.join(p, "nvidia", sub, "lib", name) if os.path.exists(f): try: ctypes.CDLL(f, mode=ctypes.RTLD_GLOBAL) except OSError: pass def _dll_dirs(lib): """Windows: where the engine's dependencies may live (its own folder, CUDA, the CUDA runtime that ships with PyTorch)""" dirs = [os.path.dirname(os.path.abspath(lib))] for var in ("CUDA_PATH",): if os.environ.get(var): dirs.append(os.path.join(os.environ[var], "bin")) for p in sys.path: d = os.path.join(p, "torch", "lib") if os.path.isdir(d): dirs.append(d) return [d for d in dirs if os.path.isdir(d)] def _as_images(x, size=None): """a picture or a batch of pictures (numpy uint8, PIL, torch) -> list of contiguous uint8 [H, W, 3]""" if hasattr(x, "convert"): x = [x] if hasattr(x, "detach"): x = x.detach().cpu().numpy() if isinstance(x, np.ndarray) and x.ndim == 3: x = x[None] out = [] for im in x: if hasattr(im, "convert"): im = np.asarray(im.convert("RGB")) im = np.asarray(im) if im.dtype != np.uint8: im = (np.clip(im.astype(np.float32), 0, 1) * 255).round().astype(np.uint8) out.append(np.ascontiguousarray(im[..., :3])) return out class Teveration: def __init__(self, model=None, device="auto", threads=0, vision=True, quality="balanced", lib=None): """model: a Teveration-1-.gguf file or a folder with one (default: download to the cache); device: auto, cuda, vulkan or cpu; vision: load the vision tower too (needed for image_to_image and dense_predict, about 0.4 GB); quality: small (2.6 GB), balanced (2.8 GB) or high (3.1 GB): the precision of the low-rank path. A file given as model decides the quality itself.""" assert quality in ADAPTERS, f"quality must be one of {tuple(ADAPTERS)}" self.path, self.quality = locate_model(model, vision, quality) self.lib = L = self._open(lib, device) c, u8p, i32p, f32p = ctypes.c_char_p, ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_int32), ctypes.POINTER(ctypes.c_float) L.tev_load.restype = ctypes.c_void_p L.tev_load.argtypes = [c, c, c, c, ctypes.c_int, ctypes.c_int] L.tev_free.argtypes = [ctypes.c_void_p] for name in ("tev_last_error", "tev_version"): getattr(L, name).restype = c for name in ("tev_backend", "tev_dense_classes"): getattr(L, name).restype = c getattr(L, name).argtypes = [ctypes.c_void_p] L.tev_text_to_image_ex.argtypes = [ctypes.c_void_p, c, ctypes.c_uint64, f32p, ctypes.c_int, f32p, u8p, i32p, f32p] L.tev_image_to_image_ex.argtypes = [ctypes.c_void_p, u8p, ctypes.c_int, ctypes.c_int, c, c, ctypes.c_uint64, f32p, ctypes.c_int, f32p, u8p, i32p, f32p] L.tev_dense_predict.argtypes = [ctypes.c_void_p, u8p, ctypes.c_int, ctypes.c_int, u8p, f32p, f32p] L.tev_decode.argtypes = [ctypes.c_void_p, i32p, c, u8p] L.tev_decode_source.argtypes = [ctypes.c_void_p, i32p, u8p, c, c, u8p] gpu = 0 if device == "cpu" else 1 if os.path.isfile(self.path) and hasattr(L, "tev_load_file"): # read in place: nothing is unpacked L.tev_load_file.restype = ctypes.c_void_p L.tev_load_file.argtypes = [c, ctypes.c_int, ctypes.c_int, ctypes.c_int] self.folder = os.path.dirname(self.path) self.h = L.tev_load_file(self.path.encode(), int(bool(vision)), gpu, int(threads)) else: # a folder with the parts, or an engine before 1.0.1 self.folder, quality = resolve_model(self.path, vision, self.quality) p = lambda key: os.path.join(self.folder, ADAPTERS[quality] if key == "adapter" else GGUF[key]).encode() # noqa: E731 self.h = L.tev_load(p("backbone"), p("adapter"), p("image"), p("mmproj") if vision else None, gpu, int(threads)) if not self.h: raise RuntimeError("teveration: " + L.tev_last_error().decode(errors="replace")) self.backend = L.tev_backend(self.h).decode() self.vision = vision def _open(self, lib, device): """load the engine library; with device="auto" a backend whose runtime is missing falls back to the next one""" fixed = lib or os.environ.get("TEVERATION_LIB") order = [device] if (fixed or device != "auto" or platform.system() == "Darwin") else (["cuda"] if _has_nvidia() else []) + ["vulkan", "cpu"] last = None for d in order: try: path = fixed or find_library(d) if "cuda" in engine_variant(d) or fixed: _cuda_runtime(path) if platform.system() == "Windows": self._dirs = [os.add_dll_directory(x) for x in _dll_dirs(path)] return ctypes.CDLL(path) except OSError as err: # also urllib's errors: the archive of this backend is not there last = err print(f"teveration: the {d} engine could not be loaded ({err}); trying the next backend", file=sys.stderr) raise RuntimeError(f"teveration: no engine could be loaded: {last}") def close(self): if getattr(self, "h", None): self.lib.tev_free(self.h) self.h = None def __del__(self): try: self.close() except Exception: # noqa: BLE001 pass def _check(self, rc): if rc != 0: raise RuntimeError("teveration: " + self.lib.tev_last_error().decode(errors="replace")) @staticmethod def _ptr(a, t): return None if a is None else a.ctypes.data_as(ctypes.POINTER(t)) # ---- tasks ---------------------------------------------------------------------------------------------------------------- def text_to_image(self, prompts, seed=0, state=None, k_masked=0, u=None, return_codes=False, return_logits=False, decode=True): """prompt or list of prompts -> uint8 [B, 512, 512, 3]; picture i uses seed + i. state [B, 128, 64], k_masked [B], u [B, 128]: the random draws from outside (evaluation).""" prompts = [prompts] if isinstance(prompts, str) else list(prompts) n = len(prompts) images = np.zeros((n, 512, 512, 3), np.uint8) codes = np.zeros((n, 128), np.int32) logits = np.zeros((n, 128, 8192), np.float32) if return_logits else None for i, prompt in enumerate(prompts): st = None if state is None else np.ascontiguousarray(state[i], np.float32) uu = None if u is None else np.ascontiguousarray(u[i], np.float32) self._check(self.lib.tev_text_to_image_ex( self.h, prompt.encode(), int(seed) + i, self._ptr(st, ctypes.c_float), int(np.atleast_1d(k_masked)[i if np.ndim(k_masked) else 0]), self._ptr(uu, ctypes.c_float), self._ptr(images[i], ctypes.c_uint8) if decode else None, self._ptr(codes[i], ctypes.c_int32), self._ptr(logits[i], ctypes.c_float) if return_logits else None)) out = (images,) + ((codes,) if return_codes else ()) + ((logits,) if return_logits else ()) return out[0] if len(out) == 1 else out def image_to_image(self, sources, task, captions=None, seed=0, state=None, k_masked=0, u=None, return_codes=False, return_logits=False, decode=True): """pictures of any size (resized and centre-cropped to 512) -> uint8 [B, 512, 512, 3]; captions for hed / depth""" assert task in I2I_TASKS, f"task must be one of {I2I_TASKS}" sources = _as_images(sources) n = len(sources) captions = [captions] * n if isinstance(captions, str) else (list(captions) if captions is not None else [""] * n) images = np.zeros((n, 512, 512, 3), np.uint8) codes = np.zeros((n, 128), np.int32) logits = np.zeros((n, 128, 8192), np.float32) if return_logits else None for i, src in enumerate(sources): st = None if state is None else np.ascontiguousarray(state[i], np.float32) uu = None if u is None else np.ascontiguousarray(u[i], np.float32) self._check(self.lib.tev_image_to_image_ex( self.h, self._ptr(src, ctypes.c_uint8), src.shape[1], src.shape[0], task.encode(), captions[i].encode(), int(seed) + i, self._ptr(st, ctypes.c_float), int(np.atleast_1d(k_masked)[i if np.ndim(k_masked) else 0]), self._ptr(uu, ctypes.c_float), self._ptr(images[i], ctypes.c_uint8) if decode else None, self._ptr(codes[i], ctypes.c_int32), self._ptr(logits[i], ctypes.c_float) if return_logits else None)) out = (images,) + ((codes,) if return_codes else ()) + ((logits,) if return_logits else ()) return out[0] if len(out) == 1 else out def dense_predict(self, pictures): """pictures of one size [B, H, W, 3] -> {"seg": class indices uint8 [B, H, W] (see NYU13), "depth": meters float32 [B, H, W], "normal": unit vectors float32 [B, H, W, 3]}""" pictures = _as_images(pictures) segs, depths, normals = [], [], [] for pic in pictures: h, w = pic.shape[:2] seg, depth, normal = np.zeros((h, w), np.uint8), np.zeros((h, w), np.float32), np.zeros((h, w, 3), np.float32) self._check(self.lib.tev_dense_predict(self.h, self._ptr(pic, ctypes.c_uint8), w, h, self._ptr(seg, ctypes.c_uint8), self._ptr(depth, ctypes.c_float), self._ptr(normal, ctypes.c_float))) segs.append(seg) depths.append(depth) normals.append(normal) return {"seg": np.stack(segs), "depth": np.stack(depths), "normal": np.stack(normals)} def decode(self, codes, texts, sources=None, task=None, captions=None): """the decoder half: codes [B, 128] + the texts the decoder reads -> uint8 [B, 512, 512, 3]; with sources (512 x 512, grey for colorize) and a task it is the image-to-image decoder""" codes = np.ascontiguousarray(codes, np.int32) images = np.zeros((len(codes), 512, 512, 3), np.uint8) for i in range(len(codes)): if sources is None: self._check(self.lib.tev_decode(self.h, self._ptr(codes[i], ctypes.c_int32), texts[i].encode(), self._ptr(images[i], ctypes.c_uint8))) else: src = np.ascontiguousarray(sources[i], np.uint8) self._check(self.lib.tev_decode_source(self.h, self._ptr(codes[i], ctypes.c_int32), self._ptr(src, ctypes.c_uint8), task.encode(), (captions[i] if captions else "").encode(), self._ptr(images[i], ctypes.c_uint8))) return images def info(): return json.dumps({"version": VERSION, "engine": engine_variant(), "cache": cache_dir(), "files": SINGLE}, indent=1)