File size: 21,909 Bytes
b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 d5afa0d b7e49b8 | 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 | # SPDX-License-Identifier: Apache-2.0
"""The configuration surface of the DepthPro2 package: weights pins, model sizes, resolution buckets and presets,
video window / overlap, engines, and their validation. Shared by the Python API (``api.py``) and the HTTP server
(``server/app.py``). Standard library only (no torch, no numpy, no ttnn), so the server imports without them.
Everything here is fixed when a model is built (the device programs are compiled for it), read from explicit
arguments first, then from the environment (``DEPTHPRO2_*``), then the defaults:
| setting | env | default | meaning |
| --- | --- | --- | --- |
| size | ``DEPTHPRO2_SIZE`` | ``L`` (serve profiles s / b / l / h) | ``S``, ``B``, ``L`` or ``H`` (H+) |
| resolutions | ``DEPTHPRO2_RESOLUTIONS`` | ``vga,vga_portrait`` | comma-separated ``HxW`` buckets or presets |
| window | ``DEPTHPRO2_WINDOW`` | 16 | video clip length T (buffered) / cache size (unbuffered), 1..16 |
| overlap | ``DEPTHPRO2_OVERLAP`` | 4 (clamped to window - 1 when unset) | frames shared by consecutive buffered clips |
| video modes | ``DEPTHPRO2_VIDEO_MODES`` | ``auto`` | ``buffered``, ``unbuffered``, both, or ``auto``: both when the |
| | | | unbuffered key-value caches fit :data:`KV_BUDGET_BYTES` (all buckets x streams), else buffered |
| KV streams | ``DEPTHPRO2_KV_STREAMS`` | 1 | unbuffered video streams open at once (one KV cache per bucket each) |
| clip lengths | ``DEPTHPRO2_CLIP_LENGTHS`` | ``auto`` (1 and window) | clip lengths T compiled besides the window, or ``all`` |
| FOV | ``DEPTHPRO2_FOV`` | 1 | load and warm the focal-length (FOV) estimator |
| engine | ``DEPTHPRO2_ENGINE`` | ``enc=mk,dec=mk,fov=mk`` | per stage ``mk`` (persistent megakernel) or ``ttnn`` (the tt-nn |
| | | | fallback, e.g. ``dec=ttnn``); stages not named keep the default |
| precision | ``DEPTHPRO2_PRECISION`` | the device module's default | ``bf16`` or ``bfp8`` (only if the device module offers it) |
| encoder precision | ``DEPTHPRO2_ENC_PRECISION`` | ``high`` | encoder megakernel numerics: ``high`` (the megakernel's |
| | | | per-size defaults: on L, fp32 LayerNorm output into QKV / FC1 and hi / lo prefix keys) or ``fast`` (the |
| | | | plain bf16 encoder everywhere; only L changes, ``high`` costs L 5-18 % more encoder time); S, B, H+ and |
| | | | the focal-length trunk run the same either way |
A *bucket* is a native input size ``(H, W)``; the device program runs at the padded size ``(ceil32(H), ceil32(W))``
(replicate padding, exactly like the official code). A request of exactly a bucket's size runs natively; any other
size is resized (bilinear, antialias) to the bucket with the nearest aspect ratio and the outputs are resized back.
"""
from __future__ import annotations
import math
import os
import re
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
__all__ = [
"MODEL_NAME", "PACKAGE_REPO", "ENV_PREFIX", "SIZES", "SIZE_NAMES", "PROFILES", "WEIGHTS", "FOCAL", "ALLOW_PATTERNS",
"DEFAULT_SIZE", "PRESETS", "DEFAULT_RESOLUTIONS", "DEFAULT_WINDOW", "WINDOW_RANGE", "DEFAULT_OVERLAP",
"VIDEO_MODES", "DEFAULT_VIDEO_MODES", "DEFAULT_ENGINE", "KV_BUDGET_BYTES", "KV_STREAMS_RANGE", "ENGINE_STAGES", "ENGINE_KINDS", "PRECISIONS", "BUCKET_SIDE",
"INPUT_MULTIPLE", "DepthConfig", "resolve_config", "normalize_size", "parse_resolutions", "parse_engine",
"parse_video_modes", "parse_clip_lengths", "padded_hw", "choose_bucket", "weights_pin", "parse_auxiliary_weights",
"LICENSE_NOTICE", "WEIGHTS_LICENSE", "ENC_PRECISIONS", "DEFAULT_ENC_PRECISION", "MK_ENC_OPTS_ENV",
"MK_ENC_FAST_OPTS", "mk_enc_options",
]
MODEL_NAME = "depthpro2"
PACKAGE_REPO = "changh95/DepthPro2"
ENV_PREFIX = "DEPTHPRO2"
INPUT_MULTIPLE = 32
#: model sizes (the official presets depthpro2-s / -b / -l / -h; H is "H+", a ViT-H+ with a SwiGLU MLP)
SIZES = ("S", "B", "L", "H")
SIZE_NAMES = {"S": "DepthPro2-S", "B": "DepthPro2-B", "L": "DepthPro2-L", "H": "DepthPro2-H+"}
#: serve profile name -> size
PROFILES = {"s": "S", "b": "B", "l": "L", "h": "H"}
_SIZE_ALIASES = {"s": "S", "small": "S", "b": "B", "base": "B", "l": "L", "large": "L", "h": "H", "h+": "H",
"huge": "H", "huge_plus": "H", "hplus": "H"}
#: the weights: Apple's Hugging Face repos, pinned to the commits this package was validated with (pointers only;
#: nothing is redistributed). ``(repo, revision)``.
FOCAL = "focal"
WEIGHTS: Dict[str, Tuple[str, str]] = {
FOCAL: ("apple/DepthPro2-focal", "622659d44a2002cf9ae4333f2569afa938290d9a"),
"S": ("apple/DepthPro2-S", "903a1c1ade918831d138adcc4aedbcc8f4da0078"),
"B": ("apple/DepthPro2-B", "85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04"),
"L": ("apple/DepthPro2-L", "849dc5461267e0bc006ec63ab46920ea1ed98702"),
"H": ("apple/DepthPro2-H", "68426c789f75a7c760273e857222625b4fe69576"),
}
#: the files the package reads from each repo (plus the licence and the model card, kept with the weights)
ALLOW_PATTERNS = ["model.safetensors", "config.json", "LICENSE", "README.md"]
WEIGHTS_LICENSE = ("Apple Machine Learning Research Model License Agreement (research purposes only; "
"https://huggingface.co/apple/DepthPro2/blob/main/LICENSE)")
#: the attribution notice the Apple Machine Learning Research Model License requires on redistribution of the model
#: or of model derivatives
LICENSE_NOTICE = ("Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model "
"License Agreement.")
DEFAULT_SIZE = "L"
#: resolution presets: name -> native (H, W). 720p / 1080p are not multiples of 32: they run padded, like the
#: official code (720 x 1280 -> 736 x 1280 on the device, 1080 x 1920 -> 1088 x 1920).
PRESETS: Dict[str, Tuple[int, int]] = {
"qvga": (240, 320), "qvga_portrait": (320, 240),
"vga": (480, 640), "vga_portrait": (640, 480),
"square": (512, 512),
"720p": (720, 1280), "720p_portrait": (1280, 720),
"1080p": (1080, 1920), "1080p_portrait": (1920, 1080),
}
DEFAULT_RESOLUTIONS = "vga,vga_portrait"
BUCKET_SIDE = (32, 4096) # a bucket's height and width, in pixels
MAX_BUCKETS = 8
DEFAULT_WINDOW = 16 # the official DEFAULT_WINDOW
WINDOW_RANGE = (1, 16)
DEFAULT_OVERLAP = 4 # the official DEFAULT_OVERLAP
VIDEO_MODES = ("buffered", "unbuffered")
DEFAULT_VIDEO_MODES = ("buffered", "unbuffered") # with "auto" (the default): unbuffered only if its caches fit
#: device DRAM the unbuffered key-value caches may take with video modes "auto" (the p150 has 32 GB; the weights take
#: up to 2.2 GB (H+), the compiled programs' activations up to ~1.3 GB at 1080p T=16)
KV_BUDGET_BYTES = 4 << 30
KV_STREAMS_RANGE = (1, 8)
#: encoder megakernel numerics (``DEPTHPRO2_ENC_PRECISION``): ``high`` keeps the megakernel's per-size defaults
#: (L: fp32 LayerNorm output as the QKV / FC1 operand, prefix / register keys in hi / lo; every other size and the
#: focal-length trunk: bf16); ``fast`` turns those off everywhere (the v1 encoder), which changes L only.
ENC_PRECISIONS = ("high", "fast")
DEFAULT_ENC_PRECISION = "high"
#: the encoder megakernel's option variable, and the options ``fast`` sets in it (``high`` removes these two keys so
#: the per-size defaults apply; other keys are kept)
MK_ENC_OPTS_ENV = "DEPTHPRO2_MK_ENC_OPTS"
MK_ENC_FAST_OPTS = (("inx32", "0"), ("klo", "0"))
ENGINE_STAGES = ("enc", "dec", "fov")
ENGINE_KINDS = ("mk", "ttnn")
#: the shipped engines: the encoder, the decoder and the focal-length estimator's trunk as persistent megakernels
#: (gated and soaked; each faster than its tt-nn fallback, which ``DEPTHPRO2_ENGINE`` selects per stage)
DEFAULT_ENGINE: Dict[str, str] = {"enc": "mk", "dec": "mk", "fov": "mk"}
PRECISIONS = ("bf16", "bfp8")
_HW_RE = re.compile(r"^\s*(\d+)\s*[xX*]\s*(\d+)\s*$")
_TRUE = ("1", "true", "yes", "on")
_FALSE = ("0", "false", "no", "off")
def normalize_size(size: Any) -> str:
"""``"l"`` / ``"L"`` / ``"large"`` / ``"h+"`` ... -> one of :data:`SIZES`. ``ValueError`` otherwise."""
if isinstance(size, str):
key = size.strip()
if key.upper() in SIZES:
return key.upper()
if key.lower() in _SIZE_ALIASES:
return _SIZE_ALIASES[key.lower()]
low = key.lower().replace("depthpro2-", "").replace("apple/", "")
if low in _SIZE_ALIASES:
return _SIZE_ALIASES[low]
raise ValueError(f"size={size!r}: one of {list(SIZES)} (or a serve profile {list(PROFILES)})")
def padded_hw(height: int, width: int) -> Tuple[int, int]:
"""The device input size of a native size: both sides rounded up to a multiple of 32."""
return height + (-height % INPUT_MULTIPLE), width + (-width % INPUT_MULTIPLE)
def parse_resolutions(value: Any) -> Tuple[Tuple[int, int], ...]:
"""``"480x640,vga_portrait"`` / ``[(480, 640), "720p"]`` -> native ``(H, W)`` buckets, in order, duplicates
dropped. Each side in :data:`BUCKET_SIDE`; at most :data:`MAX_BUCKETS`. ``ValueError`` names the bad token."""
if value is None:
value = DEFAULT_RESOLUTIONS
tokens: List[Any]
if isinstance(value, str):
tokens = [t for t in (s.strip() for s in value.split(",")) if t]
elif isinstance(value, (list, tuple)) and len(value) == 2 and all(isinstance(v, int) for v in value):
tokens = [tuple(value)]
else:
tokens = list(value)
out: List[Tuple[int, int]] = []
for tok in tokens:
if isinstance(tok, str):
key = tok.strip().lower()
if key in PRESETS:
hw = PRESETS[key]
else:
m = _HW_RE.match(tok)
if not m:
raise ValueError(f"resolution {tok!r}: HxW (e.g. 480x640) or a preset {sorted(PRESETS)}")
hw = (int(m.group(1)), int(m.group(2)))
elif isinstance(tok, (list, tuple)) and len(tok) == 2:
try:
hw = (int(tok[0]), int(tok[1]))
except (TypeError, ValueError):
raise ValueError(f"resolution {tok!r}: two integers (H, W)") from None
if isinstance(tok[0], bool) or isinstance(tok[1], bool):
raise ValueError(f"resolution {tok!r}: two integers (H, W)")
else:
raise ValueError(f"resolution {tok!r}: HxW, a preset name or an (H, W) pair")
lo, hi = BUCKET_SIDE
if not (lo <= hw[0] <= hi and lo <= hw[1] <= hi):
raise ValueError(f"resolution {hw[0]}x{hw[1]}: each side must be {lo}..{hi} pixels")
if hw not in out:
out.append(hw)
if not out:
raise ValueError("no resolution given: at least one HxW bucket or preset")
if len(out) > MAX_BUCKETS:
raise ValueError(f"{len(out)} resolutions: at most {MAX_BUCKETS} buckets (each is compiled and warmed)")
return tuple(out)
def parse_engine(value: Any) -> Dict[str, str]:
"""The engine of every stage: ``None`` / ``""`` -> :data:`DEFAULT_ENGINE`; ``"mk"`` / ``"ttnn"`` -> every stage;
``"enc=ttnn,fov=ttnn"`` -> those stages, the others as in :data:`DEFAULT_ENGINE`; a dict is checked the same way."""
if value is None or (isinstance(value, str) and not value.strip()):
return dict(DEFAULT_ENGINE)
if isinstance(value, Mapping):
items = [(str(k).strip().lower(), str(v).strip().lower()) for k, v in value.items()]
else:
text = str(value).strip().lower()
if text in ENGINE_KINDS:
return {s: text for s in ENGINE_STAGES}
items = []
for part in text.split(","):
if not part.strip():
continue
if "=" not in part:
raise ValueError(f"engine {value!r}: 'mk', 'ttnn' or stage=kind pairs like 'enc=mk,dec=ttnn,fov=mk'")
k, _, v = part.partition("=")
items.append((k.strip(), v.strip()))
out: Dict[str, str] = dict(DEFAULT_ENGINE)
for k, v in items:
if k not in ENGINE_STAGES:
raise ValueError(f"engine stage {k!r}: one of {list(ENGINE_STAGES)}")
if v not in ENGINE_KINDS:
raise ValueError(f"engine {k}={v!r}: one of {list(ENGINE_KINDS)}")
out[k] = v
return out
def parse_video_modes(value: Any) -> Tuple[str, ...]:
"""``"buffered"`` / ``"unbuffered"`` / both -> the modes; None, ``""`` or ``"auto"`` -> both (see
:func:`video_modes_auto`)."""
if video_modes_auto(value):
return DEFAULT_VIDEO_MODES
toks = [t.strip().lower() for t in (value.split(",") if isinstance(value, str) else value) if str(t).strip()]
bad = [t for t in toks if t not in VIDEO_MODES]
if bad or not toks:
raise ValueError(f"video modes {value!r}: 'buffered', 'unbuffered' or both")
return tuple(m for m in VIDEO_MODES if m in toks)
def video_modes_auto(value: Any) -> bool:
"""Whether a video-modes setting is ``auto`` (unset counts as auto)."""
return value is None or (isinstance(value, str) and value.strip().lower() in ("", "auto"))
def parse_clip_lengths(value: Any, window: int) -> Tuple[int, ...]:
"""The clip lengths T the device programs are compiled for: always 1 (images) and ``window`` (video clips),
plus ``value``: ``"auto"`` / None (nothing more), ``"all"`` (every T in 1..window) or a list of integers."""
base = {1, window}
if value is None or (isinstance(value, str) and value.strip().lower() in ("", "auto")):
return tuple(sorted(base))
if isinstance(value, str) and value.strip().lower() == "all":
return tuple(range(1, window + 1))
toks = value.split(",") if isinstance(value, str) else list(value)
for t in toks:
try:
n = int(str(t).strip(), 10)
except ValueError:
raise ValueError(f"clip lengths {value!r}: 'auto', 'all' or integers 1..{window}") from None
if not 1 <= n <= window:
raise ValueError(f"clip length {n}: 1..{window} (the window)")
base.add(n)
return tuple(sorted(base))
def _int(value: Any, name: str, lo: int, hi: int) -> int:
if isinstance(value, bool):
raise ValueError(f"{name}={value!r}: an integer {lo}..{hi}")
if isinstance(value, str):
try:
value = int(value.strip(), 10)
except ValueError:
raise ValueError(f"{name}={value!r}: an integer {lo}..{hi}") from None
if not isinstance(value, int) or not lo <= value <= hi:
raise ValueError(f"{name}={value!r}: an integer {lo}..{hi}")
return value
def _bool(value: Any, name: str) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, int) and value in (0, 1):
return bool(value)
if isinstance(value, str) and value.strip().lower() in _TRUE + _FALSE:
return value.strip().lower() in _TRUE
raise ValueError(f"{name}={value!r}: 1 / 0 (true / false)")
@dataclass(frozen=True)
class DepthConfig:
"""The load-time configuration of one model instance (the device programs are compiled for it)."""
size: str = DEFAULT_SIZE
resolutions: Tuple[Tuple[int, int], ...] = ((480, 640), (640, 480))
window: int = DEFAULT_WINDOW
overlap: int = DEFAULT_OVERLAP
video_modes: Tuple[str, ...] = DEFAULT_VIDEO_MODES
video_modes_auto: bool = True # unbuffered is dropped at build when its caches do not fit KV_BUDGET_BYTES
kv_streams: int = 1
clip_lengths: Tuple[int, ...] = (1, DEFAULT_WINDOW)
fov: bool = True
engine: Optional[Dict[str, str]] = field(default_factory=lambda: dict(DEFAULT_ENGINE))
precision: Optional[str] = None
enc_precision: str = DEFAULT_ENC_PRECISION
@property
def device_buckets(self) -> List[Tuple[int, int]]:
"""The padded device input sizes ``(Hp, Wp)`` of the buckets, unique, in order."""
out: List[Tuple[int, int]] = []
for hw in self.resolutions:
p = padded_hw(*hw)
if p not in out:
out.append(p)
return out
def as_env(self) -> Dict[str, str]:
"""The ``DEPTHPRO2_*`` values that reproduce this configuration."""
env = {"SIZE": self.size, "RESOLUTIONS": ",".join(f"{h}x{w}" for h, w in self.resolutions),
"WINDOW": str(self.window), "OVERLAP": str(self.overlap),
"VIDEO_MODES": "auto" if self.video_modes_auto else ",".join(self.video_modes),
"KV_STREAMS": str(self.kv_streams),
"CLIP_LENGTHS": ",".join(str(t) for t in self.clip_lengths), "FOV": "1" if self.fov else "0"}
if self.engine:
env["ENGINE"] = ",".join(f"{k}={v}" for k, v in self.engine.items())
if self.precision:
env["PRECISION"] = self.precision
env["ENC_PRECISION"] = self.enc_precision
return {f"{ENV_PREFIX}_{k}": v for k, v in env.items()}
def resolve_config(size: Any = None, *, resolutions: Any = None, window: Any = None, overlap: Any = None,
video_modes: Any = None, clip_lengths: Any = None, fov: Any = None, engine: Any = None,
kv_streams: Any = None, precision: Any = None, enc_precision: Any = None,
env: Optional[Mapping[str, str]] = None) -> DepthConfig:
"""Explicit values > ``DEPTHPRO2_*`` environment > defaults. Raises ``ValueError`` naming the setting (and the
environment variable it came from) for anything out of range, so a bad value refuses to start."""
env = os.environ if env is None else env
p = ENV_PREFIX
def pick(v: Any, key: str) -> Tuple[Any, str]:
if v is not None:
return v, key.lower()
raw = (env.get(f"{p}_{key}") or "").strip()
return (raw if raw else None), f"{p}_{key}"
def wrap(fn, v, src):
try:
return fn(v)
except ValueError as e:
raise ValueError(f"{src}: {e}") from None
v, src = pick(size, "SIZE")
sz = wrap(normalize_size, v if v is not None else DEFAULT_SIZE, src)
v, src = pick(resolutions, "RESOLUTIONS")
res = wrap(parse_resolutions, v, src)
v, src = pick(window, "WINDOW")
win = wrap(lambda x: _int(x, "window", *WINDOW_RANGE), v if v is not None else DEFAULT_WINDOW, src)
v, src = pick(overlap, "OVERLAP")
if v is None:
ov = min(DEFAULT_OVERLAP, win - 1)
else:
ov = wrap(lambda x: _int(x, "overlap", 0, max(0, win - 1)), v, src)
v, src = pick(video_modes, "VIDEO_MODES")
modes = wrap(parse_video_modes, v, src)
auto = video_modes_auto(v)
v, src = pick(kv_streams, "KV_STREAMS")
kvs = wrap(lambda x: _int(x, "kv_streams", *KV_STREAMS_RANGE), v if v is not None else 1, src)
v, src = pick(clip_lengths, "CLIP_LENGTHS")
clips = wrap(lambda x: parse_clip_lengths(x, win), v, src)
v, src = pick(fov, "FOV")
fv = wrap(lambda x: _bool(x, "fov"), v if v is not None else True, src)
v, src = pick(engine, "ENGINE")
eng = wrap(parse_engine, v, src)
v, src = pick(precision, "PRECISION")
prec = None
if v is not None:
prec = str(v).strip().lower()
if prec not in PRECISIONS:
raise ValueError(f"{src}={v!r}: one of {list(PRECISIONS)}")
v, src = pick(enc_precision, "ENC_PRECISION")
encp = DEFAULT_ENC_PRECISION if v is None else str(v).strip().lower()
if encp not in ENC_PRECISIONS:
raise ValueError(f"{src}={v!r}: one of {list(ENC_PRECISIONS)}")
return DepthConfig(size=sz, resolutions=res, window=win, overlap=ov, video_modes=modes, video_modes_auto=auto,
kv_streams=kvs, clip_lengths=clips,
fov=fv, engine=eng, precision=prec, enc_precision=encp)
def mk_enc_options(enc_precision: str, current: Optional[str] = None) -> str:
"""The ``DEPTHPRO2_MK_ENC_OPTS`` value that gives ``enc_precision`` (``high`` / ``fast``): ``current`` (the
variable's present value) without its ``inx32`` / ``klo`` keys, plus :data:`MK_ENC_FAST_OPTS` for ``fast``. Set
before any encoder megakernel is built (it reads the variable when a program is built)."""
if enc_precision not in ENC_PRECISIONS:
raise ValueError(f"enc_precision={enc_precision!r}: one of {list(ENC_PRECISIONS)}")
names = {k for k, _ in MK_ENC_FAST_OPTS}
keep = [kv.strip() for kv in (current or "").split(",")
if "=" in kv and kv.split("=", 1)[0].strip() not in names]
if enc_precision == "fast":
keep += [f"{k}={v}" for k, v in MK_ENC_FAST_OPTS]
return ",".join(keep)
def choose_bucket(height: int, width: int, buckets: Sequence[Tuple[int, int]]) -> Tuple[Tuple[int, int], bool]:
"""The bucket for a ``height x width`` input and whether it runs natively (exactly a bucket's size). Otherwise
the bucket of the nearest aspect ratio (|log aspect| distance), ties broken by the nearest area, then by order."""
hw = (int(height), int(width))
if hw in buckets:
return hw, True
a = math.log(hw[1] / hw[0])
area = math.log(hw[0] * hw[1])
def key(i_b):
i, (bh, bw) = i_b
return (round(abs(math.log(bw / bh) - a), 9), round(abs(math.log(bh * bw) - area), 9), i)
return min(enumerate(buckets), key=key)[1], False
def weights_pin(key: str) -> Tuple[str, str]:
"""``(repo, revision)`` of a size (``"S"``..``"H"``) or of the focal estimator (``"focal"``)."""
return WEIGHTS[FOCAL if key == FOCAL else normalize_size(key)]
def parse_auxiliary_weights(value: Optional[str]) -> Dict[str, Optional[str]]:
"""tt-model's ``TT_AUXILIARY_WEIGHTS`` (``repo@rev,repo@rev``; a bare ``repo`` when unpinned) -> ``{repo: rev}``."""
out: Dict[str, Optional[str]] = {}
for part in (value or "").split(","):
part = part.strip()
if not part:
continue
repo, _, rev = part.partition("@")
out[repo.strip()] = rev.strip() or None
return out
def iter_presets() -> Iterable[Tuple[str, Tuple[int, int]]]:
return PRESETS.items()
|