Text-to-Image
Diffusers
Safetensors
GGUF
English
TeverationPipeline
teveration
image-to-image
depth-estimation
image-segmentation
ternary
quantized
jeveration
qwen3.5
bonsai
comfyui
custom_code
conversational
Run this model with HF Jobs
Run DmitrofNET/Teveration-1 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/DmitrofNET/Teveration-1. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/DmitrofNET/Teveration-1 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use DmitrofNET/Teveration-1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use DmitrofNET/Teveration-1 with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("DmitrofNET/Teveration-1", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use DmitrofNET/Teveration-1 with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf DmitrofNET/Teveration-1 # Run inference directly in the terminal: llama cli -hf DmitrofNET/Teveration-1
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf DmitrofNET/Teveration-1 # Run inference directly in the terminal: llama cli -hf DmitrofNET/Teveration-1
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf DmitrofNET/Teveration-1 # Run inference directly in the terminal: ./build/bin/llama cli -hf DmitrofNET/Teveration-1
Use Docker
docker model run hf.co/DmitrofNET/Teveration-1
- Llama new
- LM Studio
- Jan
- Draw Things
- DiffusionBee
- Ollama
How to use DmitrofNET/Teveration-1 with Ollama:
ollama run hf.co/DmitrofNET/Teveration-1
- Unsloth Desktop
- Pi
How to use DmitrofNET/Teveration-1 with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf DmitrofNET/Teveration-1
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "DmitrofNET/Teveration-1" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use DmitrofNET/Teveration-1 with Docker Model Runner:
docker model run hf.co/DmitrofNET/Teveration-1
- Lemonade
How to use DmitrofNET/Teveration-1 with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull DmitrofNET/Teveration-1
Run and chat with the model
lemonade run user.Teveration-1-{{QUANT_TAG}}List all available models
lemonade list
- Hermes Agent
How to use DmitrofNET/Teveration-1 with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf DmitrofNET/Teveration-1
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default DmitrofNET/Teveration-1
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use DmitrofNET/Teveration-1 with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf DmitrofNET/Teveration-1
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "DmitrofNET/Teveration-1" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
File size: 25,137 Bytes
acea903 26079fa acea903 59b858c 037cc48 59b858c 037cc48 acea903 59b858c acea903 037cc48 59b858c 037cc48 acea903 037cc48 acea903 037cc48 acea903 59b858c acea903 59b858c acea903 037cc48 | 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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | """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-<quality>.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-<quality>.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.<part>.", tensors PART_PREFIX), and "single.<part>.*" 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: <os>-<arch>-<backend>"""
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-<quality>.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)
|