はじめる

YOLOモデルによるスレッドセーフな推論

Pythonスレッド間でUltralytics YOLOの推論を安全に実行するには、1つのインスタンスを複数のスレッドで共有せず、各スレッド内で個別のYOLOモデルをインスタンス化してください。単一のモデルを共有すると、競合状態が発生して内部状態が破損し、予測できない結果につながります。これは、Pythonのthreadingモジュールが同じオブジェクトに対してスレッドを並行して実行するためです。このガイドでは、共有がうまくいかない理由、安全なスレッドごとのパターン、およびインスタンスを共有する必要がある場合に使うThreadingLockedデコレーターについて説明します。

モデルの共有が失敗する理由、スレッドセーフなパターン、またはThreadingLockedデコレーターに移動します。



視聴: PythonでUltralytics YOLOモデルを使ったスレッドセーフな推論を行う方法 | マルチスレッド 🚀

Pythonのスレッド処理について#

Pythonのスレッドを使用すると、プログラムで複数の処理を並行して実行できます。ただし、Pythonのグローバルインタープリターロック(GIL)により、一度にPythonバイトコードを実行できるスレッドは1つだけです。

Single-thread vs multi-thread inference

制約のように思えるかもしれませんが、スレッドでも並行処理は可能です。特に、I/Oバウンドの処理や、YOLOの基盤となるCライブラリが実行する処理のようにGILを解放する処理を使う場合に有効です。

モデルインスタンスを共有する危険性#

YOLOモデルをスレッドの外でインスタンス化し、そのインスタンスを複数のスレッドで共有すると、並行アクセスによってモデルの内部状態が一貫性なく変更され、競合状態が発生する可能性があります。モデルやそのコンポーネントがスレッドセーフを前提としていない状態を保持する場合、特に問題となります。

スレッドセーフではない例: 単一のモデルインスタンス#

Pythonでスレッドを使う場合、並行処理の問題につながるパターンを把握することが重要です。避けるべきなのは、単一のYOLO26モデルインスタンスを複数のスレッドで共有することです。

# 危険: 単一のモデルインスタンスをスレッド間で共有
from threading import Thread

from ultralytics import YOLO

# スレッドの外でモデルをインスタンス化
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)
    # 結果を処理する

# 同じモデルインスタンスを共有するスレッドを開始
Thread(target=predict, args=("image1.jpg",)).start()
Thread(target=predict, args=("image2.jpg",)).start()

上記の例では、2つのスレッドがshared_modelを共有しています。各predictの呼び出しはconf、iou、imgszなどの引数を個別に保持しますが、同じpredictorを使用する呼び出しはそのロックの背後で一度に1つずつ実行されるため、スレッドの並列性はほとんど向上しません。トラッカーの状態、YOLOEのset_classes語彙、SAM、FastSAM、YOLOEのプロンプトなど、インスタンス上に保持される状態はすべてのスレッドで共有されるため、それらを扱う場合は各スレッドに専用のインスタンスを用意してください。

安全な例: スレッドごとに専用のインスタンスを用意#

各スレッドがそれぞれのインスタンスを所有し、別のスレッドと共有しない限り、モデルインスタンスを複数用意しても問題ありません。以下のインスタンスがスレッドの開始前に作成されていても問題ありません。安全でないのは、1つのインスタンスを複数のスレッドで共有するパターンだけです。

# 安全: 各スレッドが専用のモデルインスタンスを使用
from threading import Thread

from ultralytics import YOLO

# スレッドごとに1つのモデルをインスタンス化
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)
    # 結果を処理する

# 各スレッドが個別の専用モデルインスタンスを使用
Thread(target=predict, args=(model_1, "image1.jpg")).start()
Thread(target=predict, args=(model_2, "image2.jpg")).start()

各スレッドが専用のインスタンスを使用するため、スレッドが破損させる可能性のある共有モデル状態はありません。次に示すように各スレッド内でモデルをインスタンス化する方法は、インスタンスが誤って共有されないようにする最も簡単な方法です。

スレッドセーフな推論#

スレッドセーフな推論を実行するには、各スレッド内で個別のYOLOモデルをインスタンス化してください。これにより各スレッドが分離された独自のモデルインスタンスを持ち、競合状態のリスクを排除できます。

スレッドセーフな例#

安全な並列推論のために、各スレッド内でYOLOモデルをインスタンス化する方法は次のとおりです。

# 安全: 各スレッド内で単一のモデルをインスタンス化
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)
    # 結果を処理する

# それぞれが独自のモデルインスタンスを持つスレッドを開始する
Thread(target=thread_safe_predict, args=("image1.jpg",)).start()
Thread(target=thread_safe_predict, args=("image2.jpg",)).start()

この例では、各スレッドが独自のYOLOインスタンスを作成します。これにより、スレッドが別のスレッドのモデル状態に干渉するのを防ぎ、各スレッドが他のスレッドとの予期しない相互作用なしに、安全に推論を実行できます。

ThreadingLockedデコレーターの使用#

Ultralyticsには、関数のスレッドセーフな実行を保証するために使用できるThreadingLockedデコレーターが用意されています。このデコレーターはロックを使用し、一度に1つのスレッドだけがデコレートされた関数を実行できるようにします。

from ultralytics import YOLO
from ultralytics.utils import ThreadingLocked

# モデルインスタンスを作成
model = YOLO("yolo26n.pt")

# 予測関数をデコレートしてスレッドセーフにする
@ThreadingLocked()
def thread_safe_predict(image_path):
    """Thread-safe prediction using a shared model instance."""
    results = model.predict(image_path)
    return results

# これで、この関数を複数のスレッドから安全に呼び出せます

ThreadingLockedデコレーターは、モデルインスタンスをスレッド間で共有する必要があるものの、一度にアクセスできるスレッドを1つに制限したい場合に特に便利です。

メモリと並行性のトレードオフ

ロックをかけたモデルインスタンスを1つ共有すると、各スレッドでモデルを読み込む場合と比べてメモリを節約できますが、スレッドがロックの取得を順番に待つため、並行性は低下します。メモリに余裕があり最大限の並列性を求める場合はスレッドごとのパターンを優先し、モデルのメモリ使用量がボトルネックになる場合はThreadingLockedを使用してください。

結論#

YOLOモデルをPythonのthreadingで使用する場合は、各スレッドに専用のモデルインスタンスを用意し、1つのインスタンスをスレッド間で共有しないでください。使用するスレッド内でモデルをインスタンス化するのが最も簡単な方法です。これにより競合状態を回避し、推論タスクの信頼性を維持できます。

さらに高度なシナリオに対応し、マルチスレッド推論の性能を最適化するには、multiprocessingによるプロセスベースの並列処理や、専用のワーカープロセスを備えたタスクキューの活用を検討してください。

よくある質問#

  • マルチスレッドのPython環境でUltralytics YOLOモデルを使用する際の競合状態を防ぐには、各スレッド内で個別のYOLOモデルをインスタンス化します。各スレッドが独立したモデルインスタンスを持つため、モデルの状態が同時に変更されるのを防げます。

    例:

    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)
        # 結果を処理する
    
    Thread(target=thread_safe_predict, args=("image1.jpg",)).start()
    Thread(target=thread_safe_predict, args=("image2.jpg",)).start()
  • PythonでYOLOモデルの推論を安全にマルチスレッドで実行するには、次のベストプラクティスに従ってください。

    1. 単一のモデルインスタンスをスレッド間で共有するのではなく、各スレッド内でYOLOモデルをインスタンス化してください。
    2. グローバルインタープリターロック(GIL)に関連する問題を避けて並列処理を行うには、Pythonのmultiprocessingモジュールを使用してください。
    3. YOLOの基盤となるCライブラリ(PyTorch、OpenCV)は、負荷の高い計算中にGILを自動的に解放するため、スレッドでも推論を並行して実行できることを覚えておいてください。
    4. メモリが懸念事項となる場合は、共有モデルインスタンスにThreadingLockedデコレーターを使用することを検討してください。

    スレッドセーフなモデルインスタンス化の例:

    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)
        # 結果を処理する
    
    # 複数のスレッドを開始
    Thread(target=thread_safe_predict, args=("image1.jpg",)).start()
    Thread(target=thread_safe_predict, args=("image2.jpg",)).start()

    詳しい説明については、スレッドセーフな推論のセクションを参照してください。

  • 競合状態を防ぐには、各スレッドに独自のYOLOモデルインスタンスを用意する必要があります。単一のモデルインスタンスを複数のスレッドで共有すると、同時アクセスによって予測できない動作やモデルの内部状態の変更が発生する可能性があります。個別のインスタンスを使用すれば、スレッドを分離できるため、マルチスレッドタスクの信頼性と安全性が高まります。

    詳しい手順については、スレッドセーフではない例: 単一のモデルインスタンスとスレッドセーフな例のセクションを確認してください。

  • Pythonのグローバルインタープリターロック(GIL)により、一度にPythonバイトコードを実行できるスレッドは1つだけとなるため、CPUバウンドのマルチスレッドタスクでは性能が制限されることがあります。ただし、I/Oバウンドの処理や、YOLOの基盤となるCライブラリのようにGILを解放するライブラリを使用する処理では、並行性を実現できます。性能をさらに高めるには、Pythonのmultiprocessingモジュールを使ったプロセスベースの並列処理を検討してください。

    Pythonのスレッド処理について詳しくは、Pythonのスレッド処理についてのセクションをご覧ください。

  • はい、Pythonのmultiprocessingモジュールを使用すると、YOLOモデルの推論を並列実行する際の安全性が高まり、多くの場合、効率も向上します。プロセスベースの並列処理ではメモリ空間が分離されるため、グローバルインタープリターロック(GIL)を回避し、並行処理の問題が発生するリスクを低減できます。各プロセスは独自のYOLOモデルインスタンスを持ち、それぞれ独立して動作します。

コメント12

質問したり、結果を共有したり、ほかの人をサポートしたりできます。

  1. amani784GitHub

    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?

  2. warptengoodGitHub

    I have a few questions:

    1. Does the rules about thread-safety apply in the same way to TensorRT/ONNX inference of YOLO?
    2. Should I have the shared model for all threads when using TensorRT YOLO? (In case the answer for the 1st question is 'No'.)
    3. Is it true that it is better to have stream parameter to be set to False when performing inference on TensorRT (in predict())
    4. How torch.cuda.Stream() affects the performance of multi-threading/multi-processing when used on predict()/track() functions?
    5. 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

    1. Glenn JocherUltralytics

      @KenesYerassyl Thank you for your great questions about thread safety with TensorRT/ONNX models. Let me address each one:

      1. 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.

      2. For TensorRT models, it's generally safer to use separate engine instances per thread or use a thread locking mechanism like our ThreadingLocked decorator. TensorRT engines maintain internal state during inference that can cause issues with concurrent access.

      3. Setting stream=False for 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.

      4. 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.

      5. 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.

  3. mrbulbGitHub

    Hello, is there any example code that uses Python's multiprocessing for YOLO model inference?

    1. 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!

  4. ghostGitHub

    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 ?

  5. abysshalGitHub

    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?

    1. Glenn JocherUltralytics(編集済み)

      @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:

      1. 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.

      2. 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 await for I/O-bound operations and ensuring that any libraries you use within the predict function are also compatible with asyncio.

      3. 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 YOLO model 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 the ThreadingLocked decorator (see the thread-safe inference guide).

      4. 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.

      5. 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.

      6. Testing: Test your application under load to ensure that it behaves correctly with concurrent requests. You can use tools like locust or ab (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