Inference an toàn luồng với các model YOLO
Để chạy inference Ultralytics YOLO an toàn trên các luồng Python, hãy khởi tạo một model YOLO riêng bên trong mỗi luồng thay vì chia sẻ một instance giữa các luồng. Việc chia sẻ một model duy nhất gây ra race condition, làm hỏng trạng thái nội bộ và tạo ra kết quả khó đoán, vì module threading của Python chạy đồng thời các luồng trên cùng một đối tượng. Hướng dẫn này giải thích vì sao việc chia sẻ không an toàn, trình bày cách thực hiện an toàn với từng luồng riêng và giới thiệu decorator ThreadingLocked cho trường hợp bạn bắt buộc phải chia sẻ một instance.
Chuyển đến phần vì sao chia sẻ model không an toàn, cách làm an toàn cho luồng hoặc decorator ThreadingLocked.
Xem: Cách thực hiện inference an toàn đa luồng với model Ultralytics YOLO trong Python | Multi-threading 🚀
Tìm hiểu về luồng trong Python#
Luồng Python cho phép chương trình chạy đồng thời nhiều thao tác. Tuy nhiên, Global Interpreter Lock (GIL) của Python khiến mỗi thời điểm chỉ có một luồng thực thi được bytecode Python.
Dù có vẻ đây là một hạn chế, luồng vẫn có thể hỗ trợ xử lý đồng thời, đặc biệt với các thao tác phụ thuộc I/O hoặc các thao tác giải phóng GIL, chẳng hạn như những thao tác do các thư viện C nền tảng của YOLO thực hiện.
Rủi ro khi dùng chung instance model#
Khởi tạo model YOLO bên ngoài các luồng rồi chia sẻ instance đó giữa nhiều luồng có thể dẫn đến race condition, khi trạng thái nội bộ của model bị thay đổi không nhất quán do các truy cập đồng thời. Điều này đặc biệt có vấn đề khi model hoặc các thành phần của model lưu giữ trạng thái không được thiết kế để an toàn luồng.
Ví dụ không an toàn luồng: Một instance model#
Khi sử dụng luồng trong Python, cần nhận biết các mẫu có thể dẫn đến vấn đề đồng thời. Sau đây là điều bạn nên tránh: chia sẻ một instance model YOLO26 duy nhất giữa nhiều luồng.
# Không an toàn: Chia sẻ một instance model duy nhất giữa các luồng
from threading import Thread
from ultralytics import YOLO
# Khởi tạo model bên ngoài luồng
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)
# # Xử lý kết quả
# Khởi chạy các luồng dùng chung cùng một instance model
Thread(target=predict, args=("image1.jpg",)).start()
Thread(target=predict, args=("image2.jpg",)).start()Trong ví dụ trên, cả hai luồng dùng chung shared_model. Mỗi lần gọi predict giữ các đối số riêng như conf, iou và imgsz, nhưng các lần gọi sử dụng cùng một predictor sẽ chạy lần lượt theo lock của predictor đó, nên các luồng hầu như không được tăng mức độ song song. Trạng thái được lưu trên instance, chẳng hạn như trạng thái tracker, các bộ từ vựng set_classes của YOLOE hoặc prompt của SAM, FastSAM và YOLOE, vẫn được chia sẻ giữa mọi luồng, vì vậy hãy tạo một instance riêng cho mỗi luồng trong những trường hợp đó.
Ví dụ an toàn: Mỗi luồng có một instance riêng#
Có thể dùng nhiều instance model riêng biệt miễn là mỗi luồng sở hữu instance của mình và không bao giờ chia sẻ instance đó với luồng khác. Việc các instance bên dưới được tạo trước khi khởi chạy luồng không quan trọng — mẫu duy nhất không an toàn là chia sẻ một instance giữa các luồng:
# An toàn: mỗi luồng dùng instance model riêng của mình
from threading import Thread
from ultralytics import YOLO
# Khởi tạo một model cho mỗi luồng
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)
# # Xử lý kết quả
# Mỗi luồng sử dụng một instance model riêng biệt
Thread(target=predict, args=(model_1, "image1.jpg")).start()
Thread(target=predict, args=(model_2, "image2.jpg")).start()Vì mỗi luồng làm việc với instance riêng, không có trạng thái model dùng chung để các luồng làm hỏng. Khởi tạo model bên trong từng luồng như minh họa tiếp theo đơn giản là cách dễ nhất để đảm bảo instance không vô tình bị chia sẻ.
Suy luận an toàn luồng#
Để chạy inference an toàn luồng, bạn nên khởi tạo một model YOLO riêng trong mỗi luồng. Cách này đảm bảo mỗi luồng có instance model tách biệt, loại bỏ nguy cơ xảy ra race condition.
Ví dụ an toàn luồng#
Sau đây là cách khởi tạo model YOLO bên trong mỗi luồng để chạy inference song song an toàn:
# An toàn: Khởi tạo một model riêng bên trong mỗi luồng
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)
# # Xử lý kết quả
# # Khởi chạy các luồng, mỗi luồng có một instance model riêng
Thread(target=thread_safe_predict, args=("image1.jpg",)).start()
Thread(target=thread_safe_predict, args=("image2.jpg",)).start()Trong ví dụ này, mỗi luồng tạo instance YOLO riêng. Cách này ngăn các luồng ảnh hưởng đến trạng thái model của nhau, nhờ đó đảm bảo mỗi luồng chạy inference an toàn và không gây tương tác ngoài dự kiến với các luồng khác.
Sử dụng decorator ThreadingLocked#
Ultralytics cung cấp decorator ThreadingLocked, có thể dùng để đảm bảo các hàm được thực thi an toàn luồng. Decorator này sử dụng khóa để đảm bảo tại mỗi thời điểm chỉ có một luồng thực thi hàm được trang trí.
from ultralytics import YOLO
from ultralytics.utils import ThreadingLocked
# Tạo một instance model
model = YOLO("yolo26n.pt")
# Trang trí hàm dự đoán để đảm bảo an toàn luồng
@ThreadingLocked()
def thread_safe_predict(image_path):
"""Thread-safe prediction using a shared model instance."""
results = model.predict(image_path)
return results
# Giờ đây, bạn có thể gọi hàm này an toàn từ nhiều luồngDecorator ThreadingLocked đặc biệt hữu ích khi bạn cần chia sẻ một instance model giữa các luồng nhưng muốn đảm bảo mỗi lần chỉ có một luồng truy cập instance đó.
Chia sẻ một instance model có khóa tiết kiệm bộ nhớ so với việc tải model trong từng luồng, nhưng giảm tính đồng thời vì các luồng phải lần lượt chờ khóa. Nếu có đủ bộ nhớ và muốn đạt mức song song tối đa, hãy ưu tiên mẫu mỗi luồng một model; nếu bộ nhớ model là nút thắt cổ chai, hãy dùng ThreadingLocked.
Kết luận#
Khi sử dụng model YOLO với threading của Python, hãy cấp cho mỗi luồng một instance model riêng và tuyệt đối không chia sẻ một instance giữa các luồng. Khởi tạo model bên trong luồng sử dụng model là cách đơn giản nhất để đảm bảo điều này, tránh race condition và giữ cho các tác vụ inference đáng tin cậy.
Đối với các kịch bản nâng cao hơn và để tối ưu thêm hiệu năng inference đa luồng, hãy cân nhắc dùng song song hóa dựa trên tiến trình với multiprocessing hoặc sử dụng hàng đợi tác vụ với các tiến trình worker riêng.
Câu hỏi thường gặp#
Để ngăn điều kiện tranh chấp khi dùng model Ultralytics YOLO trong môi trường Python đa luồng, hãy khởi tạo một model YOLO riêng trong mỗi luồng. Cách này đảm bảo mỗi luồng có một instance model tách biệt, tránh việc trạng thái model bị sửa đổi đồng thời.
Ví dụ:
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) # # Xử lý kết quả Thread(target=thread_safe_predict, args=("image1.jpg",)).start() Thread(target=thread_safe_predict, args=("image2.jpg",)).start()Để chạy inference model YOLO đa luồng an toàn trong Python, hãy làm theo các phương pháp tốt nhất sau:
- Khởi tạo model YOLO trong từng luồng thay vì chia sẻ một instance model duy nhất giữa các luồng.
- Sử dụng module
multiprocessingcủa Python để xử lý song song, tránh các vấn đề liên quan đến Global Interpreter Lock (GIL). - Hãy nhớ rằng các thư viện C nền tảng của YOLO (PyTorch, OpenCV) tự động giải phóng GIL trong quá trình tính toán nặng, vì vậy các luồng vẫn có thể chạy inference đồng thời.
- Khi cần tiết kiệm bộ nhớ, hãy cân nhắc dùng decorator
ThreadingLockedcho các instance model được chia sẻ.
Ví dụ khởi tạo model an toàn luồng:
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) # # Xử lý kết quả # Khởi chạy nhiều luồng Thread(target=thread_safe_predict, args=("image1.jpg",)).start() Thread(target=thread_safe_predict, args=("image2.jpg",)).start()Để biết thêm thông tin, hãy tham khảo phần Inference an toàn luồng.
Mỗi luồng nên có instance model YOLO riêng để tránh race condition. Khi một instance model duy nhất được chia sẻ giữa nhiều luồng, các truy cập đồng thời có thể dẫn đến hành vi khó đoán và làm thay đổi trạng thái nội bộ của model. Dùng các instance riêng biệt giúp cô lập luồng, nhờ đó các tác vụ đa luồng đáng tin cậy và an toàn.
Để xem hướng dẫn chi tiết, hãy tham khảo các phần Ví dụ không an toàn luồng: Một instance model và Ví dụ an toàn luồng.
Global Interpreter Lock (GIL) của Python chỉ cho phép một luồng thực thi bytecode Python tại một thời điểm, điều này có thể hạn chế hiệu năng của các tác vụ đa luồng phụ thuộc CPU. Tuy nhiên, bạn vẫn có thể xử lý đồng thời các thao tác phụ thuộc I/O hoặc các tiến trình dùng thư viện giải phóng GIL, chẳng hạn như các thư viện C nền tảng của YOLO. Để tăng hiệu năng, hãy cân nhắc dùng song song hóa dựa trên tiến trình với module
multiprocessingcủa Python.Để tìm hiểu thêm về luồng trong Python, hãy xem phần Tìm hiểu về luồng trong Python.
Có, sử dụng module
multiprocessingcủa Python an toàn hơn và thường hiệu quả hơn khi chạy inference model YOLO song song. Song song hóa dựa trên tiến trình tạo các không gian bộ nhớ riêng biệt, tránh Global Interpreter Lock (GIL) và giảm nguy cơ gặp vấn đề đồng thời. Mỗi tiến trình hoạt động độc lập với instance model YOLO riêng.
Bình luận12
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
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(đã chỉnh sửa)@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-