serve icon indicating copy to clipboard operation
serve copied to clipboard

Processing requests to different models in parallel is slower than sequentially

Open sermakarevich opened this issue 6 years ago • 14 comments

Hi, this is a question, not a bug report.

We have torchserve deployed with 5 different models, 1 worker for every model, instance has 12 threads . The goal is to query all models at the same time.

When we do this with python multiprocessing.Pool - it takes multiple times longer than querying every model sequentially one by one. Same thing when we send queries from bash - backend time grows from 211 to 3898.

If we add time.sleep(random.random() / 2) to request function - inference goes fast with multiprocessing. It must be something with the way the server process concurrent requests. But playing with number_of_netty_threads, netty_client_threads, job_queue_size, max_request_size did not work.

Any hints or links to docs?

sermakarevich avatar Jun 25 '20 13:06 sermakarevich

instance has 12 threads

Do you mean 12 cores?? or netty threads??

How many concurrent requests/model you are sending? Also, can you attach a sampler to reproduced this.

codinnvrends avatar Jun 25 '20 13:06 codinnvrends

12 cores, yes 5 concurrent request - 1 for each model will try to create a sampler

sermakarevich avatar Jun 25 '20 13:06 sermakarevich

@dhaniram-kshirsagar this should work single request Backend response time: 400 concurrent requests Backend response time: up to 2000

mkdir model_store
wget https://download.pytorch.org/models/densenet161-8d451a50.pth
for i in `seq 0 10`; do
	torch-model-archiver --model-name densenet161_${i} --version 1.0 --model-file ./serve/examples/image_classifier/densenet_161/model.py --serialized-file densenet161-8d451a50.pth --export-path model_store --extra-files ./serve/examples/image_classifier/index_to_name.json --handler image_classifier
done

touch ts_config
echo "default_workers_per_model=1" >> ts_config

torchserve --start --model-store ./model_store/ --ncs --ts-config ./ts_config --models all

curl -O https://s3.amazonaws.com/model-server/inputs/kitten.jpg


for i in `seq 0 10`; do
	curl http://127.0.0.1:8080/predictions/densenet161_${i} -T kitten.jpg & done


for i in `seq 0 10`; do
	curl http://127.0.0.1:8080/predictions/densenet161_${i} -T kitten.jpg
done

sermakarevich avatar Jun 25 '20 13:06 sermakarevich

I think I have found one possilble reason. Its pytorch's default parallelism. Every model worker process spawns its own subprocesses which cause conflicts. MKL_NUM_THREADS=1 torchserve --start looks like partially solved the issue.

However I would expect 10 queries to different models should be executed in ~ same time as a request to a single model. But it's not.

UPDT: in my real example the slowest single model response is 0.4s, querying all models at once (exactly 1 per core) takes 2s+.

sermakarevich avatar Jun 25 '20 14:06 sermakarevich

@dhaniram-kshirsagar the other strange thing here is that model's memoryUsage double its size after a request. model archive size: 106MB memoryUsage after load: 175-220 MB after an inference request (or a couple of) memoryUsage spike to ~400MB

in a pure python I can control the process size to be less than 200 MB always.

image image

sermakarevich avatar Jun 25 '20 17:06 sermakarevich

@sermakarevich As you might know, torchserve starts a python process for every worker of a model registered with it. In your case, you are registering 11 models with 1 worker/model which are equal to launching 11 python processes. When you try to run concurrent requests against each of those 11 models, process switching results into slow response time. We tried with a 36 core machine, overall response time improves however response time ratio for a request and concurrent requests is almost same!

Regarding increase in size, there is missing with torch.no_grad(): before prediction call in default handlers. This will be fixed in next release. Workaround -> Extend default handler and override the inference method with the above change. This WIP PR will take care of this fix #432

codinnvrends avatar Jul 01 '20 17:07 codinnvrends

@dhaniram-kshirsagar thanks for the explanation - it makes sense.

sermakarevich avatar Jul 10 '20 17:07 sermakarevich

@sermakarevich As you might know, torchserve starts a python process for every worker of a model registered with it. In your case, you are registering 11 models with 1 worker/model which are equal to launching 11 python processes. When you try to run concurrent requests against each of those 11 models, process switching results into slow response time. We tried with a 36 core machine, overall response time improves however response time ratio for a request and concurrent requests is almost same!

@dhaniram-kshirsagar I'm spawning multiple worker threads for a single model (default_workers_per_model=8), I can see that GPU memory is holding 8 models but still 8 concurrent requests take 8*one response time, could you please share what config file you're using ?

PMA65 avatar May 22 '21 14:05 PMA65

Hi @PMA65, I meet the same trouble with you. I found that even if I use multiple works per model, the time of concurrent requests increases exponentially. Did you solve this problem ?

Jeozhao avatar Feb 28 '22 12:02 Jeozhao

@Jeozhao no I didn't find a solution for this, I think memory isn't the only thing that matters, you can fit 2 models in memory but that doesn't mean the GPU cores can execute those 2 with same latency as 1 model

PMA65 avatar Feb 28 '22 14:02 PMA65

@PMA65 @Jeozhao @sermakarevich

I came over this thread while deploying torch serve for my own application. I thought, that I want to help anyone else who has similar issues.

My journey was a little bit different from a starting point. I actually started out with the benchmark scripts that are available in the repository. Basically, I deployed my vision model by adapting the benchmark script and wanted to see the effect of having multiple job workers.

Ironically, even at the beginning of using the benchmark I had almost the same performance independent of the amount of workers. However I discovered after setting: export OMP_NUM_THREADS=1 , suddenly I gained 5x in performance with 5 workers. I don't understand the reason behind it - but it is how it is ;) (related to another issue where someone recommended settings this flag)

After this I became hopeful that I could transition by writing my own scripts (hence I came across this issue) and achieve the same performance.

Initially, I used a python script with multiple processes to send the requests - however I noticed really low performance. The encountered performance was similar to what the others wrote in this issue. (almost no gains) I then discovered this article of benchmarking requests:

https://klaviyo.tech/a-deep-dive-into-high-performance-http-requests-for-python-engineers-2546772c50ae

A few insights: don't use multiple processes unless you have massive amounts of requests, spawning processes take a long time, it is much smarter to use async threading. (see my provided example)

import asyncio
import aiohttp
import numpy as np

class SupportsBenchmarking:
    pass

class BenchmarkAsynchronousAsyncClient(SupportsBenchmarking):
    @staticmethod
    async def _make_request(session, url: str, file_path: str):
            # Add file to multipart writer
            with open(file_path, 'rb') as file:
                data = file

            # Send PUT request with the multipart data
            async with session.put(url, data=[]) as resp:
                if resp.status != 200:
                    print(await resp.text())
                    print("ERROR: ", resp.status)
                else:
                    response_json = await resp.text()
                    return response_json
    @classmethod
    async def _run(cls, url: str, num_requests: int, file_path: str):
        async with aiohttp.ClientSession() as session:
            tasks = [cls._make_request(session, url, file_path) for _ in range(num_requests)]
            results = await asyncio.gather(*tasks)
            return results
    @classmethod
    def run(cls, url: str, num_requests: int, file_path: str):
        results = asyncio.run(cls._run(url, num_requests, file_path))
     return results
url ="http://127.0.0.1:8080/predictions/mymodel"
num_requests = 1000
file_path = 'img.jpg'

import time
start = time.time()
results = BenchmarkAsynchronousAsyncClient.run(url, num_requests, file_path)
end = time.time()
print(len(results))
print("Time",end-start)

With this above code response, I am getting exactly the same timing result as with the benchmark code from this repository. I wished the TorchServe team would have provided these kind of request examples in the first place for Python. It would have saved me and everyone a lot of time debugging of what is wrong.

So, now I have a performance increase of 5-6x with using 5 workers instead of 1 - which is really great.

Also one more tip, always check if your GPU is actually fully utilized using nvidia-smi - this is a good indication whether the issue is request related or hardware bound.

Edit: So no one is getting confused. I am not forwarding the image in this example, since an image array is actually generated in the preprocessing stage in my case for testing purposes within the handler of torch serve. Hence in my case, no need to forward the image as a data element to the put request.

lschaupp avatar Jun 18 '24 20:06 lschaupp

@lschaupp I found this explanation good for the behavior you are seeing. https://stackoverflow.com/a/43897781

If you would like to send a PR with your benchmarking script as an example and make it configurable , please do send it. Will be happy to review and merge.

agunapal avatar Jun 19 '24 00:06 agunapal

@agunapal happy to provide an python example once I am done iterating over it - i have made already a bunch of improvements over the original post.

Would not really call it benchmarking script, but rather an python request example to overcome issues that users would suffer from.

I would also recommend to add the export flag to the "Get started" guide since it massively changed things for me. Also thank you for providing the information on why this happens.

I have now actually finalized a first prototype (incorporated the above part as part of my backend), and the results translated pretty much.

lschaupp avatar Jun 19 '24 17:06 lschaupp

Hi @lschaupp I am curious if you also enabled this in your experiments. We have seen a drastic improvement with this configuration. https://github.com/pytorch/serve/blob/master/docs/performance_guide.md#torchserve-on-cpu-

agunapal avatar Jun 19 '24 18:06 agunapal