hero-api / cpu_worker.py
AkshatSG's picture
Deploy Hero API
251e920 verified
Raw History Blame Contribute Delete
1.75 kB
"""CPU copy of the detector in its own process, used when a scan can't run on the ZeroGPU GPU.
It has to be a separate process: loading the models on the CPU inside the main server process breaks every later
ZeroGPU call ("No CUDA GPUs are available"). Protocol: one JSON object per line on stdin ({"text": ...}), one JSON
result per line on stdout ({"ok": true, "result": {...}} or {"ok": false, "error": "..."}). Prints READY when loaded.
"""
import json, os, sys
os.environ["CUDA_VISIBLE_DEVICES"] = "" # never touch the GPU from this process
out = sys.stdout
sys.stdout = sys.stderr # library chatter goes to the log, not the protocol stream
import torch
from detector import Detector
def usable_cpus():
"""CPUs this container may really use. os.cpu_count() reports the whole host (often dozens of cores) while a
Space gets a few; that many threads fighting over a few cores makes PyTorch many times slower."""
try:
quota, period = open("/sys/fs/cgroup/cpu.max").read().split()
if quota != "max": return max(1, int(int(quota) / int(period)))
except Exception: pass
try: return len(os.sched_getaffinity(0))
except Exception: return os.cpu_count() or 1
n = usable_cpus()
torch.set_num_threads(n)
print(f"CPU fallback: {n} threads (host reports {os.cpu_count()})", flush=True)
det = Detector(device="cpu")
det.detect("Warm up the models before taking requests. " * 12)
out.write("READY\n"); out.flush()
for line in sys.stdin:
try:
r = det.detect(json.loads(line)["text"])
out.write(json.dumps({"ok": True, "result": r}) + "\n")
except Exception as e:
out.write(json.dumps({"ok": False, "error": repr(e)[:300]}) + "\n")
out.flush()