pymatting: Too long time on the first import. How can I shift this time to installation?

First of all, sorry if this is a duplicate. I spent a minute searching related issues and didn’t found.

So you know, that the first import is slow. The thing that I want to ask is how can I shift this time to installation? I think this is very native to think about compilation as a part of the installation. In the end, we don’t spend an hour when calling import numpy, even if it was installed from sources. It compiles during installation, not during the first import.

I’m searching for a simple solution for me. Of course, I can solve this by adding an extra step after the installation of the requirements for my application: python -c "import pymatting". But I don’t want to worry about if pymatting or other libraries were installed since I even don’t use it directly and had no idea before that the start of the application could be that slow.

I fully understand that there could be no instruments for my request. In this case, let’s redirect this request to Numba and see what they say.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 2
  • Comments: 15

Most upvoted comments

It might be a bit slower than the original, but all tests passed.

rembg only uses PyMatting for foreground estimation, which is relatively fast. EDIT: Apparently, rembg uses both estimate_alpha_cf and `estimate_foreground_ml´.

If you are using the computationally expensive alpha estimation methods of PyMatting, it would take an unreasonable amount of time without Numba.

Thank you. By doing a quick search I found the answer. It’s because the cache is CPU related so if I change from a first manchine to an other one it would not hit the cache. That’s said that strange that there is a difference in docker but as using GCP it’s possible they have some custom behavior for handling hardware ressources. If I come with a solution will post it here.

Do you have any idea why ?

Sorry, no idea, but I guess your issue is probably related to Numba. They have a very active discourse group. Maybe someone there knows the answer: https://numba.discourse.group/

Share with you an option for Docker build. It helped me reduce import time at runtime and move importing to the build process:

ENV NUMBA_CPU_NAME=generic
ENV NUMBA_CACHE_DIR=/numba_cache
RUN mkdir -p $NUMBA_CACHE_DIR  && chmod -R 777 $NUMBA_CACHE_DIR

RUN python3 -c "import pymatting"

What if cancelling numba‘s binarize optimization at all? So that this awesome tool can be more accessible and applicable for everyone. If numba decides to take 1 hour (as it did to me till now) to complie a temporary cache, I would certainly expect numba to output a intel-optimized ubuntu.iso to match such effort. Seems to me the existence of such a numba is to push python developers to use pure c + cmake to better save time.