Threads and streams¶
The simple rule is one detector and one EASI per thread. The rest of this page explains
why, and what is safe to share.
import threading
from easi import EASI, UltralyticsAdapter
def worker(frames):
detector = UltralyticsAdapter("yolo11n.pt", conf=0.25) # this thread's own network
engine = EASI(slice_size=640, overlap_ratio=0.2)
for frame in frames:
det = engine.predict(frame, detector)
threads = [threading.Thread(target=worker, args=(s,)) for s in streams]
- Never share an
UltralyticsAdapterbetween threads. An adapter holds its network and, on CUDA, a replayed CUDA graph with fixed input buffers, so two threads must not call the same adapter at once (Ultralytics' own thread-safe inference guide says the same for its models). This follows from the code; it was not stress-tested on a GPU. easi.predictreuses models. The same model name (or Ultralytics object) gets the same adapter in every call, from any thread, so do not call it from several threads with an Ultralytics model: build one adapter and oneEASIper thread instead.easi.clear_cache()forgets the kept models, for example between runs that try manyconfvalues.- Sharing one
EASIalso works with a stateless detector:tests/test_threads.pyruns four threads, with oneEASIeach and with one sharedEASI, and gets the same boxes as a sequential run. - Keep a fixed
batch_sizewith threads (the default, 8).batch_size="auto"measures GPU memory on the first call per detector and tile size, and that measurement is device-wide: other threads' work on the same GPU skews it, sharedEASIor not. - CPU thread count. While it fuses on the CPU,
EASIsets PyTorch's thread count to 1 and restores it afterwards (the test checks it comes back). The setting is process-wide: during a fusion, other threads' CPU PyTorch work also runs on one thread, and a fusion that starts while another thread holds the setting at 1 may run on the restored, larger count. That costs speed, never results. Do not calltorch.set_num_threadsfrom another thread whileEASIruns. - CPU inference with Ultralytics models. Importing Ultralytics leaves PyTorch on one thread.
Before its first CPU call,
UltralyticsAdapterraises a count of 1 to Ultralytics' own default (at most 8), asmodel.predict()does. To run on one thread, setOMP_NUM_THREADS=1before starting Python and importeasibeforeultralytics, or calltorch.set_num_threads(1)after the first frame. - Frame upload is a plain copy per call, with no shared buffer between threads (a buffer
registered with
easi.register_frame_bufferis copied by DMA; writing to it while another thread uploads from it is the caller's race, as with any shared array). - Threads do not speed up the CPU part. The merge is Python-bound: on cached detections (Mac)
two threads took 152% and four 263% of the sequential time. For more throughput on one GPU, run
one process per stream, or give each thread its own CUDA stream (
torch.cuda.stream; not benchmarked here).