Spaces:
Sleeping
Sleeping
Download cpu_worker.py from arnaupq2/taurus-animated: direct link, hf CLI and curl.
- Browser
- Download file 3.73 kB
-
https://huggingface.co/spaces/arnaupq2/taurus-animated/resolve/main/cpu_worker.py
- Command line
-
hf download hf://spaces/arnaupq2/taurus-animated/cpu_worker.py
-
curl -L -o cpu_worker.py https://huggingface.co/spaces/arnaupq2/taurus-animated/resolve/main/cpu_worker.py
3.73 kB
| """Long-lived child process that runs every CPU stage of core.make_clip (Mask R-CNN, Grounding DINO, SAM, SegFormer, | |
| LaMa, OCR...). It exists so the Space's main process never runs torch on the CPU: ZeroGPU forks its GPU worker from | |
| that process, and CPU torch work there leaves the fork unable to initialise CUDA ("No CUDA GPUs are available"). | |
| Started by app.py: `python cpu_worker.py <port> <authkey hex>`. It never imports `spaces` or gradio. | |
| When core.make_clip needs the video model, this process hands the picture to app.py (which owns the GPU call) | |
| and waits for the frames. | |
| """ | |
| import faulthandler | |
| import os | |
| import sys | |
| import time | |
| def usable_cpus(): | |
| """The CPUs this container may really use: os.cpu_count() reports the whole host, and torch/onnx/OpenCV started | |
| with that many threads fight over a much smaller quota and crawl.""" | |
| n = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 2) | |
| for path in ("/sys/fs/cgroup/cpu.max",): | |
| try: | |
| quota, period = open(path).read().split()[:2] | |
| if quota != "max": | |
| n = min(n, max(1, int(int(quota) / int(period)))) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| try: # cgroup v1 | |
| quota, period = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read()), int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read()) | |
| if quota > 0: | |
| n = min(n, max(1, quota // period)) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| return max(1, n) | |
| CPUS = usable_cpus() | |
| # Before numpy / torch / onnxruntime are imported, which read these when they load. | |
| for _name in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS", "VECLIB_MAXIMUM_THREADS"): | |
| os.environ[_name] = str(CPUS) | |
| from multiprocessing.connection import Client # noqa: E402 | |
| BEGAN = time.time() | |
| def say(text): | |
| print(f"[cpu worker +{time.time() - BEGAN:.0f}s] {text}", flush=True) | |
| def main(port, authkey): | |
| conn = Client(("127.0.0.1", port), authkey=authkey) # connect first; the heavy imports come after | |
| import numpy as np | |
| import torch | |
| torch.set_num_threads(CPUS) | |
| torch.set_grad_enabled(False) | |
| import cv2 | |
| cv2.setNumThreads(CPUS) | |
| import core | |
| say(f"ready: {CPUS} usable CPUs (os.cpu_count() says {os.cpu_count()}), torch threads {torch.get_num_threads()}") | |
| while True: | |
| job = conn.recv() | |
| if job is None: | |
| return | |
| png, names, key, out, models = job | |
| def wan(image, seed): | |
| path = out + ".wan.npy" | |
| np.save(path, np.asarray(image, dtype=np.uint8)) | |
| say("handing the picture to the GPU process") | |
| conn.send(("wan", path, int(seed))) | |
| kind, payload = conn.recv() | |
| if kind != "frames": | |
| raise RuntimeError(payload) | |
| frames = np.load(payload) | |
| os.remove(payload) | |
| say(f"got {len(frames)} frames back") | |
| return list(frames) | |
| # If a stage hangs or crawls, the log shows where, every 60 s. | |
| faulthandler.dump_traceback_later(60, repeat=True, file=sys.stderr) | |
| try: | |
| for fraction, stage in core.make_clip(png, names, key, out, wan, *models): | |
| say(f"{fraction:.2f} {stage}") | |
| conn.send(("progress", float(fraction), stage)) | |
| conn.send(("done",)) | |
| except BaseException as error: # noqa: BLE001 - said to app.py, which says it to the phone | |
| conn.send(("error", f"{type(error).__name__}: {error}")) | |
| finally: | |
| faulthandler.cancel_dump_traceback_later() | |
| if __name__ == "__main__": | |
| main(int(sys.argv[1]), bytes.fromhex(sys.argv[2])) | |