Java index out of bounds exception when running many requests through server
Context
Trying to loadtest a torch serve model to gauge performance on a custom handler.
- torchserve version: 0.2.0
- torch version: 1.6.0
- java version: openjdk 11.0.8
- Operating System and version: Debian via the python 3.7-buster image.
Your Environment
- Are you planning to deploy it using docker container? [yes/no]: yes
- Is it a CPU or GPU environment?: CPU
- Using a default/custom handler? custom
- What kind of model is it e.g. vision, text, audio?: feed forward for custom input.
- Are you planning to use local models from model-store or public url being used e.g. from S3 bucket etc.? from model store
- Provide config.properties, logs [ts.log] and parameters used for model registration/update APIs: number of netty threads=32
Expected Behavior
Expected torch serve not to throw this error or understand what properties of the environment I could change to address it. It only seems to happen on medium load.
Current Behavior
With a load of ~5rps and varying batch size and CPU memory and count allocations the server will throw an errors in ~4%+ of requests.
Failure Logs [if any]
2020-10-17 00:16:41,887 [INFO ] epollEventLoopGroup-5-3 org.pytorch.serve.wlm.WorkerThread - 9002 Worker disconnected. WORKER_MODEL_LOADED
2020-10-17 00:16:41,887 [ERROR] epollEventLoopGroup-5-3 org.pytorch.serve.wlm.WorkerThread - Unknown exception
io.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException: readerIndex(1021) + length(4) exceeds writerIndex(1024): PooledUnsafeDirectByteBuf(ridx: 1021, widx: 1024, cap: 1024)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:471)
at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:404)
at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:371)
at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:354)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1405)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:901)
at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:818)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:384)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IndexOutOfBoundsException: readerIndex(1021) + length(4) exceeds writerIndex(1024): PooledUnsafeDirectByteBuf(ridx: 1021, widx: 1024, cap: 1024)
at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1477)
at io.netty.buffer.AbstractByteBuf.readInt(AbstractByteBuf.java:810)
at org.pytorch.serve.util.codec.ModelResponseDecoder.decode(ModelResponseDecoder.java:56)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)
Thank you in advance for any help you can provide!
@adumit:
From the above logs, it looks like the model response size exceeds the configured limit of 1024 bytes. Have you updated the 'max_response_size' in config.properties? The default value is 6553500 bytes.
Could you share your config.properties and minimal reproducer?
Thanks for helping out @harshbafna!
I tried increasing the 'max_response_size' config to 10x the 6553500 bytes and no luck. I had previously not changed the 'max_response_size' property. It seems, to me, that the 1024 bytes is coming from some other setting.
I'm having a bit of a hard time working up a minimal reproducible example since this error only appears to occur under load. But, here are the settings I'm using for the config.properties:
install_py_dep_per_model=true inference_address=http://0.0.0.0:8080 management_address=http://0.0.0.0:8081 number_of_netty_threads=32 model_store=/home/model-server/model-store max_response_size=65535000
Could you help me understand how the bytes error with regards to the reader/writer in netty thread relates to the response size? Or how I might work to debug this further?
@adumit: Could you share your model handler and a sample expected response from the handler?
Could you help me understand how the bytes error with regards to the reader/writer in the netty thread relates to the response size? Or how I might work to debug this further?
The java frontend layer communicates over netty channels to the backend worker processes and expects the total length of the backend response to be not more than configured max_response_size.
The exception is getting thrown when the custom netty message decoder tries to extract the HTTP status code from the backend response.
The code for predict response creation at the backend can be found here
This has been reported a few times before at different code segments of the message decoder, but we have never been able to reproduce this; even while running inference requests with 100 concurrent users.
Questions:
- Are you using batching with your model? If yes then share the configured batch_size & max_batch_delay.
- Are you using the same input or different inputs with each request for your load test?
- Can the prediction request fail for some inputs that you are using for concurrent requests?
@harshbafna unfortunately, I'm unable to share my model handler and expected response at this time. Still checking to see if I can get an equivalent error here with a more generic implementation.
To answer your questions:
- I have tried a few different batching parameters. Currently, I was at "batch_size" = 4 with max_batch_delay=25. Have tried varying batch_sizes from 8 to 32 though.
- I was using the same input for each request to the model.
- I do not expect the prediction request to ever fail here.
Thanks for walking me through the message decoder. I'll have to spend a bit more time there, but I wasn't seeing how the 1024 bytes connected to the max_response_size there. I'm wondering if it's that the resulting error from something to do with the backend process is larger than 1024 bytes and is breaking the process there?
One other piece that may be relevant here - in the handler, I'm reading in some other external pickle files that I've included as "extra_files" in the .mar. They're read in as class attributes to the custom ModelHandler. These are used in the pre-processing steps.
One other piece that may be relevant here - in the handler, I'm reading in some other external pickle files that I've included as "extra_files" in the .mar. They're read in as class attributes to the custom ModelHandler. These are used in the pre-processing steps.
That should not be a problem. Mostly the message returned from the backend python process (model worker) to the frontend is malformed. Hence, it fails while converting the byte buffer to message. In your case, it fails when it is trying to extract the HTTP code (int value) where it expects to read 1024 bytes in total but got one extra byte (readerIndex(1021) + length(4) exceeds writerIndex(1024))
unfortunately, I'm unable to share my model handler and expected response at this time
It would be really difficult for me to identify the root cause without any reproducer. I have been experimenting with different models, different batch_sizes, and different loads but could not reproduce this scenario.
I see. So would that just be what is returned from the handle method? In that case, that part is pretty generic. I'm taking as input a softmaxed tensor and running the following post_process:
def postprocess(self, inference_output):
topk_probs_batch, topk_indices_batch = inference_output.topk(10, dim=-1)
output_batch = []
for topk_indices, topk_probs in zip(topk_indices_batch, topk_probs_batch):
output = [{"class": self.mapping[str(idx)], "probability": prob}
for idx, prob in zip(topk_indices.tolist(), topk_probs.tolist())]
output_batch.append(output)
return output_batch
Whereas the handle method is simply:
def handle(self, data, context):
input_batch = self.preprocess(data)
logits, softmaxed = self.inference(input_batch)
return self.postprocess(softmaxed)
@adumit: Thanks for sharing the snippets from your model handler. This indeed looks pretty generic post-processing.
Could you share the following more info so that I match the exact environment and try reproducing this issue:
- Model configuration for which the issue always reproduces: number of workers, batch_size, max_batch_delay
- TorchServe is installed from source or binaries?
- Any chance of a special character in your mapping file? ( Just want to rule out any corner case possibility :-) )
Absolutely.
batch_size: 4 (tried 8, and 32 as well and see the errors) number_of_workers: 3 max_batch_delay: 25 (tried 50 and the default of 100 as well)
TorchServe installed via pip.
Good thing to check on the special character! The only non-alpha numeric characters in my mapping file are: single quotes (maybe an issue?), "(", ")", "+", "-", "/", ":", "<", and ">". Happy to test removing any of those if they could be a source of error.
I will also note that it only appears to occur under load of >~5rps. I have yet to see the error running single requests repeatedly.
@harshbafna here's one more part of the error, apologies for not sending it earlier. It occurs with the other part I described above and I had assumed it was part of the overall Java error. But, in case it's not I logged it out below.
[DEBUG] W-9000-predictor org.pytorch.serve.wlm.WorkerThread - Backend worker monitoring thread interrupted or backend worker process died.
java.lang.InterruptedException
at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2056)
at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2133)
at java.base/java.util.concurrent.ArrayBlockingQueue.poll(ArrayBlockingQueue.java:432)
at org.pytorch.serve.wlm.WorkerThread.run(WorkerThread.java:129)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - Traceback (most recent call last):
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - File "/usr/local/lib/python3.7/site-packages/ts/model_service_worker.py", line 176, in <module>
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - worker.run_server()
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - File "/usr/local/lib/python3.7/site-packages/ts/model_service_worker.py", line 148, in run_server
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - self.handle_connection(cl_socket)
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - File "/usr/local/lib/python3.7/site-packages/ts/model_service_worker.py", line 105, in handle_connection
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - cmd, msg = retrieve_msg(cl_socket)
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - File "/usr/local/lib/python3.7/site-packages/ts/protocol/otf_message_handler.py", line 29, in retrieve_msg
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - cmd = _retrieve_buffer(conn, 1)
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - File "/usr/local/lib/python3.7/site-packages/ts/protocol/otf_message_handler.py", line 153, in _retrieve_buffer
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - pkt = conn.recv(length)
[INFO ] W-9000-predictor-stdout org.pytorch.serve.wlm.WorkerLifeCycle - ConnectionResetError: [Errno 104] Connection reset by peer
Good thing to check on the special character! The only non-alpha numeric characters in my mapping file are: single quotes (maybe an issue?), "(", ")", "+", "-", "/", ":", "<", and ">". Happy to test removing any of those if they could be a source of error.
Could you add a simple logging.info() statement to see if there is any specific character observed in the final output from the handler when the error occurs?
I will also note that it only appears to occur under load of >~5rps. I have yet to see the error running single requests repeatedly.
Could you also test this same load with batch_size=1? This will mean that there is an independent frontend-backend communication for every inference request. If the issue is still reproducible then we can narrow down on the parameters.
here's one more part of the error, apologies for not sending it earlier. It occurs with the other part I described above and I had assumed it was part of the overall Java error. But, in case it's not I logged it out below.
This is just the aftereffect of the first error; frontend (java) closes the netty channel when it encounters the error.
I will test the batch_size=1 now.
As far as the logging.info() statement, looks like I should be adding that to the Java codebase. Am I mistaken and I can add that into the python piece or no? Will I need to recompile once I've added it in?
And thanks for confirming on the after effect.
As far as the
logging.info()statement, looks like I should be adding that to the Java codebase. Am I mistaken and I can add that into the python piece or no? Will I need to recompile once I've added it in?
You can add it to your handler using python's logging module, the frontend code captures the standard out from the backend worker. You will just need to rebuild the mar file with the updated handler.
@harshbafna good call on the batch size check.. batch_size=1 appears to totally fix the issue. The model is small enough to run sub 50ms latency without batching. I'll test with the logging statement next and batch_size > 1.
Fine to close this issue if you'd like to stop investigating for now as this solves my immediate need. However, I'm also more than happy to continue helping try and uncover what is causing the netty thread issue for larger batch sizes. Let me know.
I'm also more than happy to continue helping try and uncover what is causing the netty thread issue for larger batch sizes
It would be great if you could help bring this to closure :-).
So I re-ran with a batch size > 1 and the logging enabled. I am seeing some non-alpha numeric characters for the batch output: ":", ")", "(", ">", and "-" are all present in the output. However, these are also present in the batch_size=1 run. Not sure if this could cause the issue. Other than that, the shapes of the outputs all look correct batch-wise.
When I run it through the model for just a single request, the one-batch request also looks the same with the 0-th dimension just being length 1 instead of batch_size.
I am doing the dimension handling myself. For example, when I handling the input data, I run a for-loop over the items in the batch in my pre-processing (assuming each item is a request body) and then torch.cat along dimension 0 for them. So then the output tensors have shape [batch-size, D], which I pass along.
@adumit Thanks for the update. I don't see any problem with the way you are running your pre-processing function. From whatever behaviours we have seen so far, its some corner case while forming the batched response.
I couldn't spend more time this week investigating the root cause. I will try a few more permutation and combinations next week. Please do update in case you observe any specific behaviour.
@harshbafna I am also facing the same issue. Issue occurs when doing batched inference , Also the issue is intermittent but is reproducible in 1/5 times whenever i try sending any concurrent requests. Please let me know if you need any logs or the code to reproduce this.
2020-11-11 14:21:25,783 [ERROR] epollEventLoopGroup-5-7 org.pytorch.serve.wlm.WorkerThread - Unknown exception
io.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException: readerIndex(2048) + length(4) exceeds writerIndex(2048): PooledUnsafeDirectByteBuf(ridx: 2048, widx: 2048, cap: 2048)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:471)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:792)
at io.netty.channel.epoll.EpollDomainSocketChannel$EpollDomainUnsafe.epollInReady(EpollDomainSocketChannel.java:138)
at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:475)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IndexOutOfBoundsException: readerIndex(2048) + length(4) exceeds writerIndex(2048): PooledUnsafeDirectByteBuf(ridx: 2048, widx: 2048, cap: 2048)
at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1477)
at io.netty.buffer.AbstractByteBuf.readInt(AbstractByteBuf.java:810)
at org.pytorch.serve.util.codec.ModelResponseDecoder.decode(ModelResponseDecoder.java:56)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)
... 16 more
@harshbafna can you please provide an update on this one ? This is blocking us from using torchserve
@punshriv: I have been running busy with the next release activities and haven't been able to spend much time on this. Also, we couldn't reproduce this at our end due to the lack of user models. It would be great if you could share your model's mar file.
There is another open PR from @jettify which fixes a small socket communication-related issue between frontend and model-workers. Could try this fix and see if it resolves the issue.
PR: https://github.com/pytorch/serve/pull/765
@harshbafna sure thanks will will try with PR 765 and also provide the mar file soon