|
| 1 | +""" |
| 2 | +ModelHandler defines an example model handler for load and inference requests for MXNet CPU models |
| 3 | +""" |
| 4 | +from collections import namedtuple |
| 5 | +import glob |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import os |
| 9 | +import re |
| 10 | + |
| 11 | +import mxnet as mx |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +class ModelHandler(object): |
| 15 | + """ |
| 16 | + A sample Model handler implementation. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self): |
| 20 | + self.initialized = False |
| 21 | + self.mx_model = None |
| 22 | + self.shapes = None |
| 23 | + |
| 24 | + def get_model_files_prefix(self, model_dir): |
| 25 | + """ |
| 26 | + Get the model prefix name for the model artifacts (symbol and parameter file). |
| 27 | + This assume model artifact directory contains a symbol file, parameter file, |
| 28 | + model shapes file and a synset file defining the labels |
| 29 | +
|
| 30 | + :param model_dir: Path to the directory with model artifacts |
| 31 | + :return: prefix string for model artifact files |
| 32 | + """ |
| 33 | + sym_file_suffix = "-symbol.json" |
| 34 | + checkpoint_prefix_regex = "{}/*{}".format(model_dir, sym_file_suffix) # Ex output: /opt/ml/models/resnet-18/model/*-symbol.json |
| 35 | + checkpoint_prefix_filename = glob.glob(checkpoint_prefix_regex)[0] # Ex output: /opt/ml/models/resnet-18/model/resnet18-symbol.json |
| 36 | + checkpoint_prefix = os.path.basename(checkpoint_prefix_filename).split(sym_file_suffix)[0] # Ex output: resnet18 |
| 37 | + logging.info("Prefix for the model artifacts: {}".format(checkpoint_prefix)) |
| 38 | + return checkpoint_prefix |
| 39 | + |
| 40 | + def get_input_data_shapes(self, model_dir, checkpoint_prefix): |
| 41 | + """ |
| 42 | + Get the model input data shapes and return the list |
| 43 | +
|
| 44 | + :param model_dir: Path to the directory with model artifacts |
| 45 | + :param checkpoint_prefix: Model files prefix name |
| 46 | + :return: prefix string for model artifact files |
| 47 | + """ |
| 48 | + shapes_file_path = os.path.join(model_dir, "{}-{}".format(checkpoint_prefix, "shapes.json")) |
| 49 | + if not os.path.isfile(shapes_file_path): |
| 50 | + raise RuntimeError("Missing {} file.".format(shapes_file_path)) |
| 51 | + |
| 52 | + with open(shapes_file_path) as f: |
| 53 | + self.shapes = json.load(f) |
| 54 | + |
| 55 | + data_shapes = [] |
| 56 | + |
| 57 | + for input_data in self.shapes: |
| 58 | + data_name = input_data["name"] |
| 59 | + data_shape = input_data["shape"] |
| 60 | + data_shapes.append((data_name, tuple(data_shape))) |
| 61 | + |
| 62 | + return data_shapes |
| 63 | + |
| 64 | + def initialize(self, context): |
| 65 | + """ |
| 66 | + Initialize model. This will be called during model loading time |
| 67 | + :param context: Initial context contains model server system properties. |
| 68 | + :return: |
| 69 | + """ |
| 70 | + self.initialized = True |
| 71 | + properties = context.system_properties |
| 72 | + # Contains the url parameter passed to the load request |
| 73 | + model_dir = properties.get("model_dir") |
| 74 | + gpu_id = properties.get("gpu_id") |
| 75 | + |
| 76 | + checkpoint_prefix = self.get_model_files_prefix(model_dir) |
| 77 | + |
| 78 | + # Read the model input data shapes |
| 79 | + data_shapes = self.get_input_data_shapes(model_dir, checkpoint_prefix) |
| 80 | + |
| 81 | + # Load MXNet model |
| 82 | + try: |
| 83 | + ctx = mx.cpu() # Set the context on CPU |
| 84 | + sym, arg_params, aux_params = mx.model.load_checkpoint(checkpoint_prefix, 0) # epoch set to 0 |
| 85 | + self.mx_model = mx.mod.Module(symbol=sym, context=ctx, label_names=None) |
| 86 | + self.mx_model.bind(for_training=False, data_shapes=data_shapes, |
| 87 | + label_shapes=self.mx_model._label_shapes) |
| 88 | + self.mx_model.set_params(arg_params, aux_params, allow_missing=True) |
| 89 | + with open("synset.txt", 'r') as f: |
| 90 | + self.labels = [l.rstrip() for l in f] |
| 91 | + except (mx.base.MXNetError, RuntimeError) as memerr: |
| 92 | + if re.search('Failed to allocate (.*) Memory', str(memerr), re.IGNORECASE): |
| 93 | + logging.error("Memory allocation exception: {}".format(memerr)) |
| 94 | + raise MemoryError |
| 95 | + raise |
| 96 | + |
| 97 | + def preprocess(self, request): |
| 98 | + """ |
| 99 | + Transform raw input into model input data. |
| 100 | + :param request: list of raw requests |
| 101 | + :return: list of preprocessed model input data |
| 102 | + """ |
| 103 | + # Take the input data and pre-process it make it inference ready |
| 104 | + |
| 105 | + img_list = [] |
| 106 | + for idx, data in enumerate(request): |
| 107 | + # Read the bytearray of the image from the input |
| 108 | + img_arr = data.get('body') |
| 109 | + |
| 110 | + # Input image is in bytearray, convert it to MXNet NDArray |
| 111 | + img = mx.img.imdecode(img_arr) |
| 112 | + if img is None: |
| 113 | + return None |
| 114 | + |
| 115 | + # convert into format (batch, RGB, width, height) |
| 116 | + img = mx.image.imresize(img, 224, 224) # resize |
| 117 | + img = img.transpose((2, 0, 1)) # Channel first |
| 118 | + img = img.expand_dims(axis=0) # batchify |
| 119 | + img_list.append(img) |
| 120 | + |
| 121 | + return img_list |
| 122 | + |
| 123 | + def inference(self, model_input): |
| 124 | + """ |
| 125 | + Internal inference methods |
| 126 | + :param model_input: transformed model input data list |
| 127 | + :return: list of inference output in NDArray |
| 128 | + """ |
| 129 | + # Do some inference call to engine here and return output |
| 130 | + Batch = namedtuple('Batch', ['data']) |
| 131 | + self.mx_model.forward(Batch(model_input)) |
| 132 | + prob = self.mx_model.get_outputs()[0].asnumpy() |
| 133 | + return prob |
| 134 | + |
| 135 | + def postprocess(self, inference_output): |
| 136 | + """ |
| 137 | + Return predict result in as list. |
| 138 | + :param inference_output: list of inference output |
| 139 | + :return: list of predict results |
| 140 | + """ |
| 141 | + # Take output from network and post-process to desired format |
| 142 | + prob = np.squeeze(inference_output) |
| 143 | + a = np.argsort(prob)[::-1] |
| 144 | + return [['probability=%f, class=%s' %(prob[i], self.labels[i]) for i in a[0:5]]] |
| 145 | + |
| 146 | + def handle(self, data, context): |
| 147 | + """ |
| 148 | + Call preprocess, inference and post-process functions |
| 149 | + :param data: input data |
| 150 | + :param context: mms context |
| 151 | + """ |
| 152 | + |
| 153 | + model_input = self.preprocess(data) |
| 154 | + model_out = self.inference(model_input) |
| 155 | + return self.postprocess(model_out) |
| 156 | + |
| 157 | +_service = ModelHandler() |
| 158 | + |
| 159 | + |
| 160 | +def handle(data, context): |
| 161 | + if not _service.initialized: |
| 162 | + _service.initialize(context) |
| 163 | + |
| 164 | + if data is None: |
| 165 | + return None |
| 166 | + |
| 167 | + return _service.handle(data, context) |
0 commit comments