Refactor torch handlers (especially BaseHandler) for better reusability and functionality
LONG issue following
(Hi all, PM for Google Cloud AI Platform) The Torchserve handler classes need a refactor so it's easier for developer to use and for us to provide functionality. This refactor is a prerequisite to enabling Torchserve on Google Cloud. I've implemented a version in this commit: https://github.com/htappen/serve/commit/7f8fe9eb72efb3fbc9020a6bc37f8ff27f459a2e
Thoughts very much welcome! I'd like to get this pulled into master in the next release.
Problem statement
Although BaseHandler provides good functionality for initialization, it offers no reusability functionality for the model handling pipeline or steps along the way. This makes it challenging to develop new examples and core handlers, as well as providing useful shared functionality to all handlers. We sorely need a refactor for healthy future development. A number of other RFCs all depend on this refactor.
Proposal
Several points should be addressed in this refactor. None of them should change the existing interface and, thus, be backwards compatible.
Add a default handler implementation
Most Handler code involves a bunch of boilerplate around handlers. Besides being confusing and burdensome to constantly copy it, having such boilerplate prevents Torchserve from offering new functionality in the handler pipeline. See ImageClassifier, TextClassifier for examples.
So, instead of each handler needing to copy this boilerplate:
_service = None
...
def handle(data, context):
try:
if not _service.initialized:
_service.initialize(context)
if data is None:
return None
data = _service.preprocess(data)
data = _service.inference(data)
data = _service.postprocess(data)
return data
except Exception as e:
raise e
we should instead add the handle code to BaseHandler:
_singleton_handler = None
class BaseHandler(ABC)
...
@classmethod
def get_default_handler(cls):
def handle(data, context):
global _singleton_handler
if _singleton_handler is None:
_singleton_handler = cls(context)
return _singleton_handler._handle(data, context)
return handle
def _handle(self, data, context):
if data is None:
return None
processed = self.preprocess(data)
predictions = self.inference(processed)
output = self.postprocess(predictions)
return output
That way, in new handlers, customers need simply add much smaller boilerplate:
handler = <MyClass>.get_default_handler()
Clarify the interface for preprocess, inference, and postprocess
Without a clear purpose for each of these methods, it's confusing to know what code should go where (and if we even need all 3 of them). You can see some of this confusion in the examples: MNist and ResNet-152-Batch both map from scores to labels, but do so in different methods (inference vs postprocess)
The goal of this and the next points is for data scientists to have to override as little as possible of the existing methods (so they can reuse our really good code) but, when necessary, for it to be as clear, extensible and easy to use as possible.
I propose this pipeline
preprocess:- Input: a
listofbytes,list,strordictobjects - Output: a
Torch.tensoron the CPU - Function: Convert from raw Python objects into a Tensor that can, without any further processing, be fed into the model.
- Input: a
inference:- Input: a
Torch.tensoron the CPU - Output: a
Torch.tensoron the CPU - Function:
- Marshal torch tensor to a device
- Call the torch module
- Marshal results back to CPU
- Input: a
postprocess:- Input: a
Torch.tensoron the CPU - Output: a
listofbytes,list,strordictobjects - Function: Convert from the model output to native Python objects
- Input: a
Consider adding (type hints)[https://docs.python.org/3/library/typing.html] to further clarify the interface
Provide default implementations for preprocess, inference, and postprocess
Implement those interfaces so users don't always have to. Fortunately, most of the code is scattered among the built-in handlers and examples.
Make the built-in classes accept batches
TextClassifier and ImageClassifier only return predictions for the first item. Let's get them all to support batching
Move utility functions to the base class
Useful functionality is repeated on many classes. Instead, we should move these into the base class:
- Mapping labels to class names
- topk for classifiers
Refactor examples & built-in handlers to use the new functionality
The built-in handlers have a number of override methods that may be unnecessary after the BaseHandler refactor. Some examples, like Transformer, use almost none of the BaseHandler functionality and will thus need a major refactor.
In particular, we should focus on reusing the functionality that's added into BaseHandler. For example, the examples and built-in handlers should avoid overriding inference.
Backwards incompatible proposals
These changes can bring more consistency and simplicity, but risk breaking some downstream consumers:
Make all Classifiers have a consistent output signature
Today, ImageClassifer returns [{ label: probability, ... }, ...] if an class name mapping is present. TextClassifier returns [label, ...]. We should have them both return the same thing
Remove topk from ImageClassifier
Remove the initialize method and initialized property
The extra initialize method doesn't seem to do anything that can't be in __init__. Having an extra method further complicates building derived classes because a data scientist needs to know this non-standard method and property.
Instead, do initialization in the constructor (__init__ method). Use the handler object = None to single that initialization isn't finished.
Implementation
I can offer a refactor of at least one example later.
Thanks, @htappen for the proposal!
It looks like, the majority of the proposed changes are in place with different approaches. However, the documentation needs to be calibrated to remove confusion around writing custom handlers and/or extending default handlers. In fact, we already have a PR #432 in progress where we are addressing code reusability aspects. Even examples are getting refactored. Also, we already have an issue to track documentation of default handler #404 to document details around default handlers.
One of the thing I noticed is, we are already handling the singleton aspect via our backend framework however the boilerplate code related to handle method can be improvised as suggested.
Default batch support in default handlers will be a good addition however leaving it for discussion here.
Hi Dhaniram, thanks for getting back to me. I do see a bit of progress in the PR you mention, but it still stops short of actually building a reusable class or interface. Looks like other PRs are also adding to the fragmentation and duplication: https://github.com/pytorch/serve/pull/283, https://github.com/pytorch/serve/pull/418, https://github.com/pytorch/serve/pull/432.
Lack of reusability makes it hard to implement platform-wide features, like one outlined here: https://github.com/pytorch/serve/issues/436. It also makes it hard for a new developer of a handler (even somebody tweaking an existing one) to know how to use it. I really think we need to put more things into practice.
I'm happy to write the PR myself, as I think this is critical to Torchserve's success and usage in other model platforms like Seldon, KFServing, and Google Cloud.
Are there at least certain points in the above doc I can issue a PR for now? We can do partial and work our way to more?
Sure @htappen, let us first complete that PR and documentation fix and then you can fork from our branch and add some of these enhancements. We should be completing the changes by this week.
Thanks so much! I'll check back in next week.
On Tue, Jun 9, 2020 at 10:10 AM dhaniram-kshirsagar < [email protected]> wrote:
Sure @htappen https://github.com/htappen, let us first complete that PR and documentation fix and then you can fork from our branch and add some of these enhancements. We should be completing the changes by this week.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/pytorch/serve/issues/434#issuecomment-641453844, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABF7MVLVZTB6ALKNZSQBGUDRVZUJDANCNFSM4NWVANXQ .
@htappen Thanks for waiting on this. I have made the required changes to Base, Default, and Example handlers. I have also corrected the custom handler doc. Please refer to #432.
Unfortunately, there were mistakes in default handler and initial examples that got blindly pasted in other examples as well. Please look at this updated custom handler doc.
Essentially, following code will work however is wrong.
class IrisClassifier(object):
def initialize(self, context):
pass
def handle(self, data, context)
pass
_service = IrisClassifier()
def handle(data, context):
logger.debug(context)
if not _service.initialized:
_service.initialize(context)
if data is None:
return None
data = _service.inference(data)
data = _service.postprocess(data)
return data
In above handler code, we are mixing two worlds i.e. module-level 'handle' /entry point method and a class level entry point. Basically, in the following code, we don't need any singleton as the existing framework takes care of creating one for you. Also, you don't need a module-level handle method if you have already provided the handle(self, data, context) method in your entry point class.
Following is correct way of writing handle with 'class' level entry point-
class IrisClassifier(object):
def initialize(self, context):
#initialize your model
def handle(self, data, context)
#Do Pre-Infer-Post
return prediction
As I was doing this correction and made pre-infer-post methods concrete in base class, It seemed natural to add handle method in the base handler. I took your idea of having handle in base handler itself!!
Following are pending items from your proposal -
- Make the built-in classes accept batches
- Mapping labels to class names
- Transformer to base class - If you look at #432, we had already refactored and moved generic xformer code to default handler image_classifier however you are welcome to further generalized it by having some generic version in visionhandler/basehandler
I am also going to add comment/suggestion to your other propsal with respect to backward compatibility and less breaking changes.
Thanks for replying! I've been out on leave for a few days, and I'll take a closer look by end of week.
On Tue, Jun 16, 2020 at 10:50 AM dhaniram-kshirsagar < [email protected]> wrote:
@htappen https://github.com/htappen Thanks for waiting on this. I have made the required changes to Base, Default, and Example handlers. I have also corrected the custom handler doc. Please refer to #432 https://github.com/pytorch/serve/pull/432.
Unfortunately, there were mistakes in default handler and initial examples that got blindly pasted in other examples as well. Please look at this updated custom handler https://github.com/pytorch/serve/blob/8cd6722e47fb1dc203ed3cb7d9611c11fd5030ca/docs/custom_service.md doc.
Essentially, following code will work however is wrong.
class IrisClassifier(object): def initialize(self, context): pass
def handle(self, data, context) pass_service = IrisClassifier()
def handle(data, context): logger.debug(context)
if not _service.initialized: _service.initialize(context) if data is None: return None data = _service.inference(data) data = _service.postprocess(data) return dataIn above handler code, we are mixing two worlds i.e. module-level 'handle' /entry point method and a class level entry point. Basically, in the following code, we don't need any singleton as the existing framework takes care of creating one for you. Also, you don't need a module-level handle method if you have already provided the handle(self, data, context) method in your entry point class.
Following is correct way of writing handle with 'class' level entry point-
class IrisClassifier(object): def initialize(self, context): #initialize your model
def handle(self, data, context) #Do Pre-Infer-Post return predictionAs I was doing this correction and made pre-infer-post methods concrete in base class, It seemed natural to add handle method in the base handler. I took your idea of having handle in base handler itself!!
Following are pending items from your proposal -
- Make the built-in classes accept batches
- Mapping labels to class names
- Transformer to base class - If you look at #432 https://github.com/pytorch/serve/pull/432, we had already refactored and moved generic xformer code to default handler image_classifier however you are welcome to further generalized it by having some generic version in visionhandler/basehandler
I am also going to add comment/suggestion to your other propsal with respect to backward compatibility and less breaking changes.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/pytorch/serve/issues/434#issuecomment-644914902, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABF7MVIGNA5NWN34GUJCAOLRW6WFLANCNFSM4NWVANXQ .
I like that new handle method. Looks great!
I added comments to the changelist. It's getting there, but still needs some work.
Replied to your comments on PR#432 last week itself. Will you be able to create PR against that branch for your comments on improving base handler.
Great, I'm working on two PRs -- one for improving BaseHandler, then a 2nd for adding in RequestEnvelope
Thanks, Henry
On Wed, Jul 1, 2020 at 3:49 AM dhaniram-kshirsagar [email protected] wrote:
Replied to your comments on PR#432 last week itself. Will you be able to create PR against that branch for your comments on improving base handler.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/pytorch/serve/issues/434#issuecomment-652345820, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABF7MVLP5HZS243T6LOSPJLRZMICNANCNFSM4NWVANXQ .
Great, I'm working on two PRs -- one for improving BaseHandler, then a 2nd for adding in RequestEnvelope Thanks, Henry … On Wed, Jul 1, 2020 at 3:49 AM dhaniram-kshirsagar @.***> wrote: Replied to your comments on PR#432 last week itself. Will you be able to create PR against that branch for your comments on improving base handler. — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#434 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABF7MVLP5HZS243T6LOSPJLRZMICNANCNFSM4NWVANXQ .
By when PR for this i.e. changes for base_handler.py per comments in PR #432 will be available? We plan to close this by 10th july for 0.2.0 release.
OK I'm working on a few test cases, which is taking a bit longer
On Mon, Jul 6, 2020, 5:20 AM dhaniram-kshirsagar [email protected] wrote:
Great, I'm working on two PRs -- one for improving BaseHandler, then a 2nd for adding in RequestEnvelope Thanks, Henry … <#m_-1487197694561326597_> On Wed, Jul 1, 2020 at 3:49 AM dhaniram-kshirsagar @.***> wrote: Replied to your comments on PR#432 last week itself. Will you be able to create PR against that branch for your comments on improving base handler. — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#434 (comment) https://github.com/pytorch/serve/issues/434#issuecomment-652345820>, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABF7MVLP5HZS243T6LOSPJLRZMICNANCNFSM4NWVANXQ .
By when PR for this i.e. changes for base_handler.py per comments in PR #432 https://github.com/pytorch/serve/pull/432 will be available? We plan to close this by 10th july for 0.2.0 release.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/pytorch/serve/issues/434#issuecomment-654200311, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABF7MVLEBY3JPPOIAUCEETDR2G6SDANCNFSM4NWVANXQ .
@htappen Thanks for your PR!! I have merged to PR #432.