ابدأ

استدلال آمن لمؤشرات الترابط باستخدام نماذج YOLO

لتشغيل الاستدلال باستخدام Ultralytics YOLO بأمان عبر مؤشرات ترابط Python، أنشئ نموذجًا منفصلًا YOLO داخل كل مؤشر ترابط بدلًا من مشاركة مثيل واحد بينها. تؤدي مشاركة نموذج واحد إلى حالات تسابق تُفسد حالته الداخلية وتنتج نتائج غير متوقعة، لأن وحدة threading في Python تشغّل مؤشرات الترابط بالتزامن على الكائن نفسه. يشرح هذا الدليل سبب فشل المشاركة، ويعرض النمط الآمن لكل مؤشر ترابط، ويتناول المزيّن ThreadingLocked للحالات التي يتعين فيها مشاركة مثيل.

انتقل إلى سبب فشل مشاركة النموذج، أو النمط الآمن لمؤشرات الترابط، أو المزيّن ThreadingLocked.



شاهد: كيفية تنفيذ استدلال آمن مع الخيوط باستخدام نماذج Ultralytics YOLO في Python | تعدد الخيوط 🚀

فهم مؤشرات ترابط Python#

تتيح خيوط Python لبرنامجك تنفيذ عمليات متعددة بالتزامن. إلا أن قفل المفسر العام (GIL) في Python يعني أنه لا يمكن سوى لخيط واحد تنفيذ شيفرة بايت Python في كل مرة.

Single-thread vs multi-thread inference

على الرغم من أن ذلك يبدو قيدًا، فإن مؤشرات الترابط لا تزال تتيح التزامن، ولا سيما في العمليات المحدودة بالإدخال/الإخراج أو عند استخدام عمليات تحرّر GIL، مثل العمليات التي تنفذها مكتبات YOLO الأساسية المكتوبة بلغة C.

مخاطر مشاركة مثيلات النماذج#

قد يؤدي إنشاء نموذج 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()

في المثال أعلاه، يشترك الخيطان في shared_model. ويحتفظ كل استدعاء لـpredict بوسائطه الخاصة، مثل conf وiou وimgsz، لكن الاستدعاءات التي تستخدم المتنبئ نفسه تُنفَّذ بالتتابع خلف قفله، لذا لا تحقق الخيوط إلا قدرًا ضئيلًا من التوازي. وتظل الحالة المخزنة في المثيل، مثل حالة أداة التتبّع، أو مفردات YOLOE set_classes، أو مطالبات SAM وFastSAM وYOLOE، مشتركة بين جميع الخيوط؛ لذا خصّص مثيلًا مستقلًا لكل خيط.

مثال آمن: مثيل مخصص لكل مؤشر ترابط#

لا بأس باستخدام مثيلات منفصلة متعددة للنموذج، ما دام كل مؤشر ترابط يملك مثيله ولا يشاركه مطلقًا مع مؤشر ترابط آخر. ولا يهم أن المثيلات أدناه أُنشئت قبل بدء مؤشرات الترابط؛ فالنمط غير الآمن الوحيد هو مشاركة مثيل واحد بين مؤشرات الترابط:

# ⁨آمن: يستخدم كل مؤشر ترابط مثيل نموذج مخصصًا له⁩
from threading import Thread

from ultralytics import YOLO

# ⁨أنشئ نموذجًا واحدًا لكل مؤشر ترابط⁩
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 يمكن استخدامه لضمان تنفيذ الدوال بأمان مع مؤشرات الترابط. يستخدم هذا المزيّن قفلًا لضمان ألا ينفّذ الدالة المزينة سوى مؤشر ترابط واحد في كل مرة.

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 مفيدًا على نحو خاص عندما تحتاج إلى مشاركة مثيل نموذج بين مؤشرات الترابط، مع ضمان ألا يتمكن من الوصول إليه سوى مؤشر ترابط واحد في كل مرة.

المفاضلة بين الذاكرة والتزامن

توفّر مشاركة مثيل نموذج واحد محمي بقفل استهلاك الذاكرة مقارنةً بتحميل نموذج في كل مؤشر ترابط، لكنها تقلّل التزامن لأن مؤشرات الترابط تنتظر دورها بالتتابع عند القفل. فضّل نمط المثيل لكل مؤشر ترابط عندما تتوفر لديك ذاكرة كافية وتريد أقصى قدر من التوازي، واستخدم ThreadingLocked عندما تكون ذاكرة النموذج هي عنق الزجاجة.

الخلاصة#

عند استخدام نماذج YOLO مع threading في Python، خصّص لكل مؤشر ترابط مثيل نموذج مستقلًا، ولا تشارك مثيلًا واحدًا مطلقًا بين مؤشرات الترابط. ويُعد إنشاء النموذج داخل مؤشر الترابط الذي يستخدمه أبسط طريقة لضمان ذلك، وتجنّب حالات التسابق والحفاظ على موثوقية مهام الاستدلال.

للسيناريوهات الأكثر تقدمًا ولتحسين أداء الاستدلال متعدد مؤشرات الترابط، فكّر في استخدام التوازي القائم على العمليات عبر multiprocessing، أو الاستفادة من قائمة انتظار مهام مع عمليات عاملة مخصصة.

الأسئلة الشائعة#

  • لتجنب حالات التسابق عند استخدام نماذج Ultralytics YOLO في بيئة Python متعددة الخيوط، أنشئ نموذج 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()
  • لتشغيل استدلال نماذج YOLO بأمان باستخدام مؤشرات ترابط متعددة في Python، اتبع أفضل الممارسات التالية:

    1. أنشئ نماذج YOLO داخل كل مؤشر ترابط بدلًا من مشاركة مثيل نموذج واحد بين مؤشرات الترابط.
    2. استخدم وحدة multiprocessing في Python للمعالجة المتوازية، لتجنّب المشكلات المرتبطة بقفل المفسّر العام (GIL).
    3. تذكّر أن مكتبات C الأساسية في YOLO (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 خاص به لتجنّب حالات التسابق. فعندما يُشارك مثيل نموذج واحد بين مؤشرات ترابط متعددة، قد يؤدي الوصول المتزامن إلى سلوك غير متوقع وتغييرات في الحالة الداخلية للنموذج. ويضمن استخدام مثيلات منفصلة عزل مؤشرات الترابط، ما يجعل مهامك متعددة مؤشرات الترابط موثوقة وآمنة.

    للحصول على إرشادات مفصّلة، راجع قسمي مثال غير آمن لمؤشرات الترابط: مثيل نموذج واحد ومثال آمن لمؤشرات الترابط.

  • لا يسمح قفل المفسّر العام (GIL) في Python إلا لمؤشر ترابط واحد بتنفيذ شيفرة Python الثنائية في كل مرة، ما قد يحد من أداء المهام متعددة مؤشرات الترابط والمقيّدة بوحدة CPU. لكن يمكنك تحقيق التزامن في العمليات المحدودة بالإدخال/الإخراج أو العمليات التي تستخدم مكتبات تحرّر GIL، مثل مكتبات C الأساسية في YOLO. لتحسين الأداء، فكّر في استخدام التوازي القائم على العمليات عبر وحدة multiprocessing في Python.

    لمزيد من المعلومات حول مؤشرات الترابط في Python، راجع قسم فهم مؤشرات ترابط Python.

  • نعم، يُعد استخدام وحدة multiprocessing في Python أكثر أمانًا وغالبًا أكثر كفاءة لتشغيل استدلال نماذج 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