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.
File size: 28,135 Bytes
acea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26079fa
acea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59b858c
 
 
 
037cc48
 
59b858c
037cc48
 
 
 
 
acea903
 
59b858c
acea903
037cc48
 
 
 
59b858c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
037cc48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acea903
 
 
 
037cc48
 
 
acea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
037cc48
 
 
 
acea903
59b858c
acea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59b858c
 
 
 
 
 
 
 
 
 
acea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
037cc48
acea903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
"""Teveration 1 as a diffusers pipeline.

    from diffusers import DiffusionPipeline
    pipe = DiffusionPipeline.from_pretrained("DmitrofNET/Teveration-1", custom_pipeline="DmitrofNET/Teveration-1", trust_remote_code=True)
    image = pipe("A lighthouse on a rocky cliff under a stormy sky.", seed=0).images[0]
    image = pipe(image=photo, task="ghibli").images[0]                 # hed, depth, colorize, anime, ghibli, watercolor
    maps = pipe.dense_predict(photo)                                   # {"seg", "depth", "normal"}

The pipeline holds no PyTorch modules: the model runs in the Teveration engine (GGUF, weights packed in memory), which is
downloaded for this machine on first use. `pipe.to(...)` is accepted and ignored; choose the device with
`pipe.set_device("auto" | "cuda" | "vulkan" | "cpu")` before the first call.
"""
import numpy as np
from diffusers import DiffusionPipeline
from diffusers.pipelines.pipeline_utils import ImagePipelineOutput

# ---- the engine binding (teveration/engine.py of the GitHub repository) ----

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)



class TeverationPipeline(DiffusionPipeline):
    def __init__(self):
        super().__init__()
        self._engine, self._device, self._model_dir, self._quality = None, "auto", None, "balanced"

    def set_device(self, device="auto", model_dir=None, quality="balanced"):
        """device: auto, cuda, vulkan or cpu; quality: small, balanced or high (which adapter file)"""
        self._device, self._model_dir, self._quality = device, model_dir, quality
        if self._engine is not None:
            self._engine.close()
            self._engine = None
        return self

    @property
    def engine(self):
        if self._engine is None:
            folder = self._model_dir or local_model(getattr(self.config, "_name_or_path", None))
            self._engine = Teveration(model=folder, device=self._device, quality=self._quality)
        return self._engine

    def to(self, *args, **kwargs):                   # nothing lives in PyTorch
        return self

    def __call__(self, prompt=None, image=None, task=None, num_images_per_prompt=1, seed=None, generator=None, output_type="pil",
                 return_dict=True, **unused):
        """text-to-image: prompt (str or list). image-to-image: image + task (+ prompt as the caption for hed / depth).
        seed: int; or generator: a torch.Generator whose state gives the seed. output_type: "pil" or "np"."""
        if seed is None:
            if generator is not None:
                import torch
                seed = int(torch.randint(0, 2 ** 31 - 1, (1,), generator=generator).item())
            else:
                seed = int(np.random.randint(0, 2 ** 31 - 1))
        if image is not None:
            assert task is not None, "image-to-image needs task= (hed, depth, colorize, anime, ghibli, watercolor)"
            caption = prompt if isinstance(prompt, str) else (prompt[0] if prompt else "")
            images = self.engine.image_to_image(image, task, captions=caption or "", seed=seed)
        else:
            prompts = [prompt] if isinstance(prompt, str) else list(prompt)
            images = self.engine.text_to_image([p for p in prompts for _ in range(num_images_per_prompt)], seed=seed)
        if output_type == "pil":
            images = self.numpy_to_pil(images.astype(np.float32) / 255.0)
        elif output_type != "np":
            raise ValueError("output_type must be 'pil' or 'np'")
        else:
            images = images.astype(np.float32) / 255.0
        return ImagePipelineOutput(images=images) if return_dict else (images,)

    def dense_predict(self, image):
        """segmentation (13 indoor classes), depth in meters and surface normals of one or more pictures"""
        return self.engine.dense_predict(image)