Package: service-streamer
Service StreamerBoosting your Web Services of Deep Learning Applications.中文READMEWhat is Service Streamer ?•Highlights•Installation•Develop BERT Service in 5 Minutes•API•Benchmark•FAQ•• Made by ShannonAI • :globe_with_meridians:http://www.shannonai.com/What is Service Streamer ?A mini-batch collects data samples and is usually used in deep learning models. In this way, models can utilize the parallel computing capability of GPUs. However, requests from users for web services are usually discrete. If using conventional loop server or threaded server, GPUs will be idle dealing with one request at a time. And the latency time will be linearly increasing when there are concurrent user requests.ServiceStreamer is a middleware for web service of machine learning applications. Queue requests from users are sampled into mini-batches. ServiceStreamer can significantly enhance the overall performance of the system by improving GPU utilization.Highlights:hatching_chick:Easy to use: Minor changes can speed up the model ten times.:zap:Fast processing speed: Low latency for online inference of machine learning models.:octopus:Good expandability: Easy to be applied to multi-GPU scenarios for handling enormous requests.:crossed_swords:Applicability: Used with any web frameworks and/or deep learning frameworks.InstallationInstall ServiceStream by usingpip，requiresPython >= 3.5:pipinstallservice_streamerDevelop BERT Service in 5 MinutesWe provide a step-by-step tutorial for you to bring BERT online in 5 minutes. The service processes 1400 sentences per second.Text Infillingis a task in natural language processing: given a sentence with several words randomly removed, the model predicts those words removed through the given context.BERThas attracted a lot of attention in these two years and it achieves State-Of-The-Art results across many nlp tasks. BERT utilizes "Masked Language Model (MLM)" as one of the pre-training objectives. MLM models randomly mask some of the tokens from the input, and the objective is to predict the original vocabulary id of the masked word based on its context. MLM has similarities with text infilling. It is natural to introduce BERT to text infilling task.First, we define a model for text filling taskbert_model.py. Thepredictfunction accepts a batch of sentences and returns predicted position results of the[MASK]token.classTextInfillingModel(object):...batch=["twinkle twinkle [MASK] star.","Happy birthday to [MASK].",'the answer to life, the [MASK], and everything.']model=TextInfillingModel()outputs=model.predict(batch)print(outputs)# ['little', 'you', 'universe']Note: Please download pre-trained BERT model at first.Second, utilizeFlaskto pack predicting interfaces to Web service.flask_example.pymodel=TextInfillingModel()@app.route("/naive",methods=["GET","POST"])defnaive_predict():ifrequest.method=="GET":inputs=request.args.getlist("s")else:inputs=request.form.getlist("s")outputs=model.predict(inputs)returnjsonify(outputs)app.run(port=5005)Please runflask_example.py, then you will get a vanilla Web server.curl-XPOSThttp://localhost:5005/naive-d's=Happy birthday to [MASK].'["you"]At this time, your web server can only serve 12 requests per second. Please seebenchmarkfor more details.Third, encapsulate model functions throughservice_streamer. Three lines of code make the prediction speed of BERT service reach 200+ sentences per second (16x faster).fromservice_streamerimportThreadedStreamerstreamer=ThreadedStreamer(model.predict,batch_size=64,max_latency=0.1)@app.route("/stream",methods=["POST"])defstream_predict():inputs=request.form.getlist("s")outputs=streamer.predict(inputs)returnjsonify(outputs)app.run(port=5005,debug=False)Runflask_example.pyand test the performance withwrk../wrk-t2-c128-d20s--timeout=10s-sexample/benchmark.luahttp://127.0.0.1:5005/stream
...
Requests/sec:200.31Finally, encapsulate models throughStreamerand start service workers on multiple GPUs.Streamerfurther accelerates inference speed and achieves 1000+ sentences per second (80x faster).fromservice_streamerimportManagedModel,StreamerclassManagedBertModel(ManagedModel):definit_model(self):self.model=TextInfillingModel()defpredict(self,batch):returnself.model.predict(batch)streamer=Streamer(ManagedBertModel,batch_size=64,max_latency=0.1,worker_num=8,cuda_devices=(0,1,2,3))app.run(port=5005,debug=False)8 gpu workers can be started and evenly distributed on 4 GPUs.APIQuick StartIn general, the inference speed will be faster by utilizing parallel computing.outputs=model.predict(batch_inputs)ServiceStreameris a middleware for web service of machine learning applications. Queue requests from users are scheduled into mini-batches and forward into GPU workers. ServiceStreamer sacrifices a certain delay (default maximum is 0.1s) and enhance the overall performance by improving the ratio of GPU utilization.fromservice_streamerimportThreadedStreamer# Encapsulate batch_predict function with Streamerstreamer=ThreadedStreamer(model.predict,batch_size=64,max_latency=0.1)# Replace model.predict with streamer.predictoutputs=streamer.predict(batch_inputs)Start web server on multi-threading (or coordination). Your server can usually achieve 10x (batch_size/batch_per_request) times faster by adding a few lines of code.Distributed GPU workerThe performance of web server (QPS) in practice is much higher than that of GPU model. We also support one web server with multiple GPU worker processes.fromservice_streamerimportStreamer# Spawn releases 4 gpu worker processesstreamer=Streamer(model.predict,64,0.1,worker_num=4)outputs=streamer.predict(batch)Streamerusesspawnsubprocesses to run gpu workers by default.Streameruses interprocess queues to communicate and queue. It can distribute a large number of requests to multiple workers for processing.Then the prediction results of the model are returned to the corresponding web server in batches. And results are forwarded to the corresponding http response.+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.116                Driver Version: 390.116                   |
|-------------------------------+----------------------+----------------------+
...
+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      7574      C   /home/liuxin/nlp/venv/bin/python            1889MiB |
|    1      7575      C   /home/liuxin/nlp/venv/bin/python            1889MiB |
|    2      7576      C   /home/liuxin/nlp/venv/bin/python            1889MiB |
|    3      7577      C   /home/liuxin/nlp/venv/bin/python            1889MiB |
+-----------------------------------------------------------------------------+The above method is simple to define, but the main process initialization model takes up an extra portion of memory. And the model can only run on the same GPU.
Therefore, we have provided theManagedModelclass to facilitate model lazy initialization and migration while supporting multiple GPUs.fromservice_streamerimportManagedModelclassManagedBertModel(ManagedModel):definit_model(self):self.model=Model()defpredict(self,batch):returnself.model.predict(batch)# Spawn produces 4 gpu worker processes, which are evenly distributed on 0/1/2/3 GPUstreamer=Streamer(ManagedBertModel,64,0.1,worker_num=4,cuda_devices=(0,1,2,3))outputs=streamer.predict(batch)Distributed Web ServerSome cpu-intensive calculations, such as image and text preprocessing, need to be done first in web server. The preprocessed data is then forward into GPU worker for predictions. CPU resources often become performance bottlenecks in practice. Therefore, we also provide the mode of multi-web servers matching (single or multiple) gpu workers.UseRedisStreamto specify a unique Redis address for all web servers and gpu workers.# default parameters can be omitted and localhost:6379 is used.streamer=RedisStreamer(redis_broker="172.22.22.22:6379")We make use ofgunicornoruwsgito implement reverse proxy and load balancing.cdexample
gunicorn-credis_streamer_gunicorn.pyflask_example:appEach request will be load balanced to each web server for cpu preprocessing, and then evenly distributed to gpu worker for model prediction.Future APIYou might be familiar withfutureif you have used any concurrent library.
You can use the Future API directly if you want to useservice_streamerfor queueing requests or distributed GPU computing and using scenario is not web service.fromservice_streamerimportThreadedStreamerstreamer=ThreadedStreamer(model.predict,64,0.1)xs=[]foriinrange(200):future=streamer.submit([["How","are","you","?"],["Fine","."],["Thank","you","."]])xs.append(future)# Get all instances of future object and wait for asynchronous responses.forfutureinxs:outputs=future.result()print(outputs)BenchmarkBenchmarkWe utilizewrkto conduct benchmark test.Test examples and scripts can be found inexample.Environmentgpu: Titan Xpcuda: 9.0pytorch: 1.1Single GPU process# start flask threaded serverpythonexample/flask_example.py# benchmark naive api without service_streamer./wrk-t4-c128-d20s--timeout=10s-sscripts/streamer.luahttp://127.0.0.1:5005/naive# benchmark stream api with service_streamer./wrk-t4-c128-d20s--timeout=10s-sscripts/streamer.luahttp://127.0.0.1:5005/streamNaiveThreaedStreamerStreamerRedisStreamerqps12.78207.59321.70372.45latency8440ms603.35ms392.66ms340.74msMultiple GPU processesThe performance loss of the communications and load balancing mechanism of multi-gpu workers are verified compared with a single web server process.We adopt gevent server because multi-threaded Flask server has become a performance bottleneck. Please refer to theflask_multigpu_example.py./wrk-t8-c512-d20s--timeout=10s-sscripts/streamer.luahttp://127.0.0.1:5005/streamgpu_worker_numNaiveThreadedStreamerStreamerRedisStreamer111.62211.02362.69365.802N/AN/A488.40609.634N/AN/A494.201034.57Threaded StreamerDue to the limitation of Python GIL, multi-worker is meaningless. We conduct comparison studies using single GPU worker.StreamerPerformance improvement is not linear when it is greater than 2 gpu worker.
The utilization rate of CPU reaches 100. The bottleneck is CPU at this time and the performance issue of flask is the obstacle.Utilize Future API to start multiple GPU processesWe adoptFuture APIto conduct multi-GPU benchmeark test locally in order to reduce the performance influence of web server. Please refer to code example infuture_example.pygpu_worker_numBatchedThreadedStreamerStreamerRedisStreamer1422.883401.01399.26384.792N/AN/A742.16714.7814N/AN/A1400.121356.47It can be seen that the performance ofservice_streameris almost linearly related to the number of gpu workers. Communications of inter-process inservice_streameris more efficient than redis.FAQQ:using a model trained fromallennlp,setworker_num=4ofStreamerduring inference, what's the reason that 16-core cpu is full and speed is slower thanStreamerwithworker_num=1?A:for multi-process inference, if the model process data using numpy with multi-thread, it may cause cpu overheads, resulting in a multi-core computing speed that slower than a single core. This kind of problem may occur when using third-party libraries such as alennlp, spacy, etc. It could be solved by settingnumpy threadsenvironment variables.importosos.environ["MKL_NUM_THREADS"]="1"# export MKL_NUM_THREADS=1os.environ["NUMEXPR_NUM_THREADS"]="1"# export NUMEXPR_NUM_THREADS=1os.environ["OMP_NUM_THREADS"]="1"# export OMP_NUM_THREADS=1importnumpymake sure putting environment variables beforeimport numpy.Q:When using RedisStreamer, if there are only one redis broker and more than one model, the input batches may have different structure. How to deal with such situation?A:Specify the prefix when initializing worker and streamer, each streamer will use a unique channel.example of initialiazing workers:fromservice_streamerimportrun_redis_workers_foreverfrombert_modelimportManagedBertModelif__name__=="__main__":frommultiprocessingimportfreeze_supportfreeze_support()run_redis_workers_forever(ManagedBertModel,64,prefix='channel_1')run_redis_workers_forever(ManagedBertModel,64,prefix='channel_2')example of using streamer to have result:fromservice_streamerimportRedisStreamerstreamer_1=RedisStreaemr(prefix='channel_1')streamer_2=RedisStreaemr(prefix='channel_2')# predictoutput_1=streamer_1.predict(batch)output_2=streamer_2.predict(batch)