Inferenza thread-safe con i modelli YOLO
Per eseguire inferenze di Ultralytics YOLO in sicurezza su più thread Python, crea un modello YOLO separato all’interno di ogni thread, invece di condividere un’unica istanza tra più thread. La condivisione di un singolo modello causa race condition che ne corrompono lo stato interno e producono risultati imprevedibili, perché il modulo threading di Python esegue i thread contemporaneamente sullo stesso oggetto. Questa guida spiega perché la condivisione non funziona, illustra il modello sicuro con un’istanza per thread e descrive il decoratore ThreadingLocked per i casi in cui devi condividere un’istanza.
Vai direttamente a perché la condivisione di un modello non funziona, al modello thread-safe o al decoratore ThreadingLocked.
Guarda: Come eseguire inferenze thread-safe con i modelli Ultralytics YOLO in Python | Multi-threading 🚀
Capire il threading in Python#
I thread Python consentono al tuo programma di eseguire più operazioni contemporaneamente. Tuttavia, il Global Interpreter Lock (GIL) di Python fa sì che un solo thread alla volta possa eseguire bytecode Python.
Anche se può sembrare un limite, i thread possono comunque offrire concorrenza, soprattutto per le operazioni vincolate dall’I/O o quando si usano operazioni che rilasciano il GIL, come quelle eseguite dalle librerie C sottostanti di YOLO.
I rischi delle istanze di modello condivise#
Creare un modello YOLO al di fuori dei thread e condividerne l’istanza tra più thread può causare race condition, in cui lo stato interno del modello viene modificato in modo incoerente a causa degli accessi concorrenti. Questo è particolarmente problematico quando il modello o i suoi componenti mantengono uno stato che non è progettato per essere thread-safe.
Esempio non thread-safe: istanza di un singolo modello#
Quando usi i thread in Python, è importante riconoscere gli schemi che possono causare problemi di concorrenza. Ecco cosa devi evitare: condividere un’unica istanza del modello YOLO26 tra più thread.
# Non sicuro: condivisione di un’unica istanza del modello tra thread
from threading import Thread
from ultralytics import YOLO
# Crea il modello al di fuori del thread
shared_model = YOLO("yolo26n.pt")
def predict(image_path):
"""Predicts objects in an image using a preloaded YOLO model, take path string to image as argument."""
results = shared_model.predict(image_path)
# Elabora i risultati
# Avvio di thread che condividono la stessa istanza del modello
Thread(target=predict, args=("image1.jpg",)).start()
Thread(target=predict, args=("image2.jpg",)).start()Nell'esempio sopra, entrambi i thread condividono shared_model. Ogni chiamata a predict mantiene i propri argomenti, come conf, iou e imgsz, ma le chiamate che usano lo stesso predictor vengono eseguite una alla volta, protette dal relativo lock, quindi i thread ottengono poco parallelismo. Lo stato che risiede nell'istanza, come lo stato del tracker, i vocabolari YOLOE set_classes o i prompt di SAM, FastSAM e YOLOE, è comunque condiviso da tutti i thread: per questi casi, assegna a ogni thread un'istanza dedicata.
Esempio sicuro: un’istanza dedicata per thread#
Puoi usare più istanze di modello separate, purché ogni thread possieda la propria istanza e non la condivida mai con un altro thread. Non importa che le istanze qui sotto vengano create prima dell’avvio dei thread: l’unico schema non sicuro consiste nel condividere un’istanza tra thread.
# Sicuro: ogni thread usa la propria istanza dedicata del modello
from threading import Thread
from ultralytics import YOLO
# Crea un modello per ogni thread
model_1 = YOLO("yolo26n.pt")
model_2 = YOLO("yolo26n.pt")
def predict(model, image_path):
"""Runs prediction on an image using a specified YOLO model, returning the results."""
results = model.predict(image_path)
# Elabora i risultati
# Ogni thread usa un’istanza del modello separata e dedicata
Thread(target=predict, args=(model_1, "image1.jpg")).start()
Thread(target=predict, args=(model_2, "image2.jpg")).start()Poiché ogni thread lavora con la propria istanza dedicata, non esiste uno stato del modello condiviso che i thread possano corrompere. Creare il modello all’interno di ogni thread, come mostrato di seguito, è semplicemente il modo più facile per garantire che un’istanza non venga mai condivisa per errore.
Inferenza thread-safe#
Per eseguire inferenze thread-safe, devi creare un modello YOLO separato all’interno di ogni thread. In questo modo ogni thread ha un’istanza del modello isolata, eliminando il rischio di race condition.
Esempio thread-safe#
Ecco come creare un modello YOLO all’interno di ogni thread per eseguire inferenze parallele in sicurezza:
# Sicuro: creazione di un singolo modello all’interno di ogni thread
from threading import Thread
from ultralytics import YOLO
def thread_safe_predict(image_path):
"""Predict on an image using a new YOLO model instance in a thread-safe manner; takes image path as input."""
local_model = YOLO("yolo26n.pt")
results = local_model.predict(image_path)
# Elabora i risultati
# Avvia thread, ciascuno con la propria istanza del modello
Thread(target=thread_safe_predict, args=("image1.jpg",)).start()
Thread(target=thread_safe_predict, args=("image2.jpg",)).start()In questo esempio, ogni thread crea la propria istanza YOLO. In questo modo un thread non può interferire con lo stato del modello di un altro, garantendo che ogni thread esegua inferenze in sicurezza e senza interazioni impreviste con gli altri thread.
Uso del decoratore ThreadingLocked#
Ultralytics offre un decoratore ThreadingLocked che puoi usare per garantire l’esecuzione thread-safe delle funzioni. Questo decoratore usa un lock per fare in modo che un solo thread alla volta possa eseguire la funzione decorata.
from ultralytics import YOLO
from ultralytics.utils import ThreadingLocked
# Crea un’istanza del modello
model = YOLO("yolo26n.pt")
# Applica il decoratore alla funzione di previsione per renderla thread-safe
@ThreadingLocked()
def thread_safe_predict(image_path):
"""Thread-safe prediction using a shared model instance."""
results = model.predict(image_path)
return results
# Ora puoi chiamare questa funzione in sicurezza da più threadIl decoratore ThreadingLocked è particolarmente utile quando devi condividere un’istanza del modello tra thread, ma vuoi assicurarti che un solo thread alla volta possa accedervi.
Condividere un’istanza del modello protetta da un lock fa risparmiare memoria rispetto a caricare un modello in ogni thread, ma riduce la concorrenza, perché i thread si accodano sul lock e aspettano il proprio turno. Preferisci il modello con un’istanza per thread se hai memoria a sufficienza e vuoi ottenere il massimo parallelismo; scegli ThreadingLocked quando la memoria del modello è il fattore limitante.
Conclusione#
Quando usi i modelli YOLO con threading di Python, assegna a ogni thread un’istanza dedicata del modello e non condividere mai la stessa istanza tra thread. Creare il modello all’interno del thread che lo usa è il modo più semplice per garantirlo, evitare race condition e mantenere affidabili le attività di inferenza.
Per scenari più avanzati e per ottimizzare ulteriormente le prestazioni dell’inferenza multithread, valuta il parallelismo basato sui processi con multiprocessing oppure usa una coda di attività con processi worker dedicati.
Domande frequenti#
Per evitare condizioni di race quando usi i modelli Ultralytics YOLO in un ambiente Python multi-thread, istanza un modello YOLO separato in ogni thread. In questo modo, ogni thread dispone di un'istanza del modello isolata, evitando modifiche simultanee allo stato del modello.
Esempio:
from threading import Thread from ultralytics import YOLO def thread_safe_predict(image_path): """Predict on an image in a thread-safe manner.""" local_model = YOLO("yolo26n.pt") results = local_model.predict(image_path) # Elabora i risultati Thread(target=thread_safe_predict, args=("image1.jpg",)).start() Thread(target=thread_safe_predict, args=("image2.jpg",)).start()Per eseguire inferenze multithread con i modelli YOLO in sicurezza in Python, segui queste best practice:
- Crea i modelli YOLO all’interno di ogni thread invece di condividere un’unica istanza del modello tra più thread.
- Usa il modulo
multiprocessingdi Python per l’elaborazione parallela, così da evitare i problemi legati al Global Interpreter Lock (GIL). - Ricorda che le librerie C sottostanti di YOLO (PyTorch, OpenCV) rilasciano automaticamente il GIL durante i calcoli più intensivi, quindi i thread possono comunque eseguire inferenze contemporaneamente.
- Se la memoria è un problema, valuta l’uso del decoratore
ThreadingLockedper le istanze di modello condivise.
Esempio di creazione thread-safe del modello:
from threading import Thread from ultralytics import YOLO def thread_safe_predict(image_path): """Runs inference in a thread-safe manner with a new YOLO model instance.""" local_model = YOLO("yolo26n.pt") results = local_model.predict(image_path) # Elabora i risultati # Avvia più thread Thread(target=thread_safe_predict, args=("image1.jpg",)).start() Thread(target=thread_safe_predict, args=("image2.jpg",)).start()Per ulteriori informazioni, consulta la sezione Inferenza thread-safe.
Ogni thread dovrebbe avere una propria istanza del modello YOLO per evitare race condition. Quando una singola istanza del modello è condivisa tra più thread, gli accessi concorrenti possono causare comportamenti imprevedibili e modifiche allo stato interno del modello. Usando istanze separate, garantisci l’isolamento dei thread e rendi le tue attività multithread affidabili e sicure.
Per istruzioni dettagliate, consulta le sezioni Esempio non thread-safe: istanza di un singolo modello ed Esempio thread-safe.
Il Global Interpreter Lock (GIL) di Python consente a un solo thread alla volta di eseguire bytecode Python, il che può limitare le prestazioni delle attività multithread vincolate dalla CPU. Tuttavia, puoi comunque ottenere concorrenza con operazioni vincolate dall’I/O o processi che usano librerie che rilasciano il GIL, come le librerie C sottostanti di YOLO. Per migliorare le prestazioni, valuta il parallelismo basato sui processi con il modulo
multiprocessingdi Python.Per saperne di più sul threading in Python, consulta la sezione Capire il threading in Python.
Sì, usare il modulo
multiprocessingdi Python è più sicuro e spesso più efficiente per eseguire inferenze parallele con i modelli YOLO. Il parallelismo basato sui processi crea spazi di memoria separati, evitando il Global Interpreter Lock (GIL) e riducendo il rischio di problemi di concorrenza. Ogni processo opera in modo indipendente con una propria istanza del modello YOLO.
Commenti12
Fai una domanda, condividi i tuoi risultati o aiuta qualcun altro.
amani784
I used a YOLOv8 model optimized with TensorRT on an AWS machine with a Tesla T4 GPU to detect people in multiple videos. The model is loaded once per process using an initializer function. To improve performance, I parallelized the video processing using 4 processes from the multiprocessing module, where each process handles one video and performs inference using model.predict() on frames sampled at regular intervals. However, this approach led to a decrease in overall performance, with slower processing time per frame and reduced FPS. Is this normal, and if not, what is the solution?
warptengood
I have a few questions:
- Does the rules about thread-safety apply in the same way to TensorRT/ONNX inference of YOLO?
- Should I have the shared model for all threads when using TensorRT YOLO? (In case the answer for the 1st question is 'No'.)
- Is it true that it is better to have
streamparameter to be set toFalsewhen performing inference on TensorRT (inpredict()) - How
torch.cuda.Stream()affects the performance of multi-threading/multi-processing when used onpredict()/track()functions? - Should I have any sort of warm up for TensorRT inference before utilizing a model in any thread/process? (Like making inference on dummy input)
P.S: I want to thank all the Ultralytics team for their kindness and open-mindedness when it comes to help and support their community. You guys are always eager to help. And I don't care if it is some AI agent that's replying or a real person, I am very grateful for you for what you guys doing :D
Glenn JocherUltralytics@KenesYerassyl Thank you for your great questions about thread safety with TensorRT/ONNX models. Let me address each one:
-
Yes, the thread-safety principles apply similarly to TensorRT/ONNX models, but with important distinctions. TensorRT engines have their own memory management which can introduce additional concurrency concerns.
-
For TensorRT models, it's generally safer to use separate engine instances per thread or use a thread locking mechanism like our
ThreadingLockeddecorator. TensorRT engines maintain internal state during inference that can cause issues with concurrent access. -
Setting
stream=Falsefor TensorRT inference is often beneficial as it ensures complete processing of each input before handling another, which can help avoid resource conflicts in multi-threaded environments. -
Using
torch.cuda.Stream()with multi-threading can improve performance by allowing parallel execution of CUDA operations across different streams. However, you need to carefully manage synchronization points to prevent race conditions. Each thread should ideally use a separate CUDA stream. -
Yes, warming up TensorRT models is highly recommended. The first inference typically takes longer due to CUDA context initialization and memory allocations. Running inference on a dummy input before deploying in production or multi-threaded environments ensures consistent performance.
Thank you for your kind words about our team! We're committed to supporting the community with helpful resources and guidance.
-
warptengood
Thank you very much for such a comprehensive reply!
mrbulb
Hello, is there any example code that uses Python's multiprocessing for YOLO model inference?
Paula DerrengerUltralytics@mrbulb for using Python's multiprocessing with YOLO model inference, you should instantiate a separate YOLO model within each process to avoid race conditions. This ensures each process has its own isolated model instance. For detailed guidance, please refer to our Thread-Safe Inference with YOLO Models page. If you need a specific code example, feel free to ask!
farrostaufiqur
how to use results differently for each thread?
Paula DerrengerUltralyticsTo use results differently for each thread, ensure each thread instantiates its own YOLO model instance. This prevents race conditions and ensures thread safety. For more details, please refer to our Thread-Safe Inference with YOLO Models guide.
ghost
Hello. Thanks for the info. I have a question, If I run in two terminals the same python script, but to two different videos, both processes still suffer from GIL ?
Glenn JocherUltralytics@cawilchesp running the same Python script in two separate terminals for different videos won't suffer from GIL issues, as each process has its own Python interpreter and memory space. This effectively bypasses the GIL, allowing true parallel execution. For more details, you can check out our guide on thread-safe inference: https://docs.ultralytics.com/guides/yolo-thread-safe-inference/.
abysshal
So what is the best practice for single-threaded processing with asyncio? For example, gunicron+gevent+flask is used to deal with highly concurrent requests, and only one Yolo model instance will be created in each worker process. Here we do not handle threads manually, we only provide the predict function for callback from gevent. Then will the predict function of the same model instance be called again on the next request when it is not completed due to an I/O wait operation on the current request? How we handle this safely? Does it matter if cpu of gpu is used for inference?
Glenn JocherUltralytics(modificato)@abysshal when using an asynchronous server like Gunicorn with Gevent and Flask, you're dealing with a cooperative multitasking environment. In such an environment, the context switches occur at well-defined points, typically I/O operations or explicit yield points. This means that your predict function will not be preempted in the middle of execution by another request unless it hits an I/O wait or a yield.
Here's how you can handle this safely:
-
Single Model Instance: Since you're creating only one YOLO model instance per worker process, you need to ensure that the predict function is designed to be re-entrant. This means that if the function is called again while a previous call is waiting for I/O, it should not cause any conflicts or unexpected behavior.
-
Asyncio Compatibility: If you're using asyncio, you should ensure that the predict function and any other code that might run concurrently are compatible with asyncio's event loop. This means using
awaitfor I/O-bound operations and ensuring that any libraries you use within the predict function are also compatible with asyncio. -
Thread Safety: Even though you're not manually handling threads, the underlying implementation of some libraries (like PyTorch) may use threads for certain operations. A single Ultralytics
YOLOmodel instance is not thread-safe, so do not share one instance across threads. Use one instance per thread or worker, or wrap the shared call with theThreadingLockeddecorator (see the thread-safe inference guide). -
Resource Locking: If there are shared resources that need to be accessed or modified during the predict function, you should use appropriate locking mechanisms to prevent race conditions. However, in an async environment, you should use async-compatible locks like
asyncio.Lock. -
CPU vs. GPU Inference: The choice between CPU and GPU can affect performance but should not affect the thread safety or the async behavior of your application. However, if you're using a GPU, you need to ensure that the library you're using for YOLO supports concurrent model inference on the GPU without conflicts.
-
Testing: Test your application under load to ensure that it behaves correctly with concurrent requests. You can use tools like
locustorab(Apache Bench) to simulate high concurrency and check for any race conditions or deadlocks.
In summary, when using Gunicorn with Gevent and Flask, you should ensure that your predict function is re-entrant and compatible with asyncio, use async-compatible locks if necessary, and test your application under load. The choice of CPU or GPU should not affect the thread safety of your application, but you should ensure that your YOLO model library supports concurrent inference on your chosen hardware.
1-