"""Runtime environment setup. MUST be imported before torch, everywhere. Two jobs, both invisible when they work and silent when they don't: 1. IMPORT ORDER. On HF ZeroGPU the `spaces` package installs a CUDA emulation layer, and it only takes effect if it is imported BEFORE torch. embed.py and detect.py both do `import torch` at module scope, so if `spaces` has not been imported by then, `torch.cuda.is_available()` returns False, DEVICE resolves to "cpu", and the app runs a ~105-second CPU pass instead of a ~5-second GPU one. No exception, no warning - just a demo that feels broken. Importing this module first is the guard. 2. THREAD PINNING. PyTorch reads the HOST core count, not the container's cgroup quota. In a 2-vCPU container on a many-core host it spawns dozens of OMP threads that spend most of their time spinning against each other. Worth 2-4x on the CPU stages. Import it as the very first project import in any module that touches torch: import runtime # noqa: F401 - must precede torch import torch """ import os # Must be set before torch/OpenMP initialise, so they go at true module top. os.environ.setdefault("OMP_NUM_THREADS", "2") os.environ.setdefault("MKL_NUM_THREADS", "2") os.environ.setdefault("OMP_WAIT_POLICY", "PASSIVE") # 3. HUB DOWNLOAD BACKEND. huggingface_hub defaults to the xet transfer backend, which needs # to write its own chunk store and logs under HF_HOME/xet. On a Spaces container that # directory is not writable by the app user (uid 1000), and any weight NOT already staged # by `preload_from_hub` dies at import with a bare # OSError: I/O error: Permission denied (os error 13) # raised from deep inside xet-core - which names no path and does not mention permissions # as the cause. This surfaced only after the DINOv3 swap: preload skips gated repos, so # DINOv3 was the first weight the app had to fetch for itself at runtime. # The classic HTTP path writes only into the normal cache and works, so prefer it. Set # with setdefault so a host that has a working xet setup can opt back in. os.environ.setdefault("HF_HUB_DISABLE_XET", "1") # 4. MATPLOTLIB CACHE. Same unwritable directory, milder symptom: matplotlib cannot create # /home/user/.cache/matplotlib, falls back to a fresh temp dir, and rebuilds its font # index on EVERY cold start (it says so in a warning, then does it anyway). Pointing it # at /tmp up front keeps the fallback but stops the warning and the guesswork. os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib" if os.name != "nt" else os.path.join(os.environ.get("TEMP", "."), "matplotlib")) ON_SPACES = bool(os.environ.get("SPACE_ID")) try: # BEFORE torch - see docstring import spaces # type: ignore HAS_SPACES = True except ImportError: spaces = None # type: ignore HAS_SPACES = False def GPU(func=None, *, duration=120): """`spaces.GPU` on a ZeroGPU Space, a transparent no-op anywhere else. Only wrap tensor forward passes. OpenCV, MediaPipe, sklearn and plotly must stay OUTSIDE it: they cannot use the GPU, and on ZeroGPU every second inside the decorator is charged against the VISITOR's daily quota. `duration` may be an int OR a callable taking the same arguments as the wrapped function. Prefer the callable whenever runtime scales with the input, which here it always does - the work is per image. A fixed worst-case number is wrong in both directions at once: * too high and ZeroGPU refuses the call outright ("requested GPU duration is larger than the maximum allowed"), because the request is checked against the VISITOR's tier cap, not against what the job would really have used; * too high also blocks on quota, since remaining quota is compared with what you REQUESTED rather than what you spend - a 3-second job declaring 180 s locks out anyone with under 3 minutes left; * and a smaller declared duration is ranked higher in the queue. So the declaration should track the actual work, not sit at a comfortable ceiling. """ def wrap(f): if HAS_SPACES: return spaces.GPU(duration=duration)(f) return f return wrap(func) if func is not None else wrap def cuda_available() -> bool: """Safe to call: `spaces` (if present) has already been imported above, so touching torch here cannot trip its 'CUDA initialized before importing spaces' guard. This lives in runtime.py rather than config.py for exactly that reason. An earlier version put the check in config.py, which is imported by cluster.py - and since app.py imports cluster before embed, torch got initialised before runtime ran, and the Space died on import with that error. Anything that touches torch at import time belongs here, behind the spaces import. """ try: import torch return bool(torch.cuda.is_available()) except Exception: return False # OWLv2 pads every image to 960x960 = 3600 tokens with no cheaper option, so it is ~24x # DINOv3 per image: seconds on a GPU, ~31 MINUTES per 50 images on 2-3 vCPU. On a CPU-only # host the mode must be unreachable rather than merely slow. DETECTION_AVAILABLE = (os.environ.get("ALLOW_CPU_DETECTION") == "1") or cuda_available() def pin_threads() -> None: """Call once after torch is imported. Safe to call repeatedly.""" try: import torch torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "2"))) torch.set_num_interop_threads(1) except Exception: pass # set_num_interop_threads raises if called after parallel work has started try: import cv2 cv2.setNumThreads(1) # stop OpenCV fighting the torch pool for the same 2 cores except Exception: pass def describe() -> str: try: import torch dev = "cuda" if torch.cuda.is_available() else "cpu" return (f"spaces={'yes' if HAS_SPACES else 'no'} · on_spaces=" f"{'yes' if ON_SPACES else 'no'} · torch={torch.__version__} · device={dev}") except Exception as exc: return f"torch unavailable: {exc}"