-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmodel.py
285 lines (251 loc) · 12 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
"""Placeholder docstring"""
from __future__ import absolute_import
import logging
import packaging.version
import sagemaker
from sagemaker import image_uris
from sagemaker.deserializers import NumpyDeserializer
from sagemaker.fw_utils import (
model_code_key_prefix,
python_deprecation_warning,
validate_version_or_image_args,
)
from sagemaker.model import FrameworkModel, MODEL_SERVER_WORKERS_PARAM_NAME
from sagemaker.pytorch import defaults
from sagemaker.predictor import Predictor
from sagemaker.serializers import NumpySerializer
logger = logging.getLogger("sagemaker")
class PyTorchPredictor(Predictor):
"""A Predictor for inference against PyTorch Endpoints.
This is able to serialize Python lists, dictionaries, and numpy arrays to
multidimensional tensors for PyTorch inference.
"""
def __init__(
self,
endpoint_name,
sagemaker_session=None,
serializer=NumpySerializer(),
deserializer=NumpyDeserializer(),
):
"""Initialize an ``PyTorchPredictor``.
Args:
endpoint_name (str): The name of the endpoint to perform inference
on.
sagemaker_session (sagemaker.session.Session): Session object which
manages interactions with Amazon SageMaker APIs and any other
AWS services needed. If not specified, the estimator creates one
using the default AWS configuration chain.
serializer (sagemaker.serializers.BaseSerializer): Optional. Default
serializes input data to .npy format. Handles lists and numpy
arrays.
deserializer (sagemaker.deserializers.BaseDeserializer): Optional.
Default parses the response from .npy format to numpy array.
"""
super(PyTorchPredictor, self).__init__(
endpoint_name,
sagemaker_session,
serializer=serializer,
deserializer=deserializer,
)
class PyTorchModel(FrameworkModel):
"""An PyTorch SageMaker ``Model`` that can be deployed to a SageMaker ``Endpoint``."""
_framework_name = "pytorch"
_LOWEST_MMS_VERSION = "1.2"
def __init__(
self,
model_data,
role,
entry_point,
framework_version=None,
py_version=None,
image_uri=None,
predictor_cls=PyTorchPredictor,
model_server_workers=None,
**kwargs
):
"""Initialize a PyTorchModel.
Args:
model_data (str): The S3 location of a SageMaker model data
``.tar.gz`` file.
role (str): An AWS IAM role (either name or full ARN). The Amazon
SageMaker training jobs and APIs that create Amazon SageMaker
endpoints use this role to access training data and model
artifacts. After the endpoint is created, the inference code
might use the IAM role, if it needs to access an AWS resource.
entry_point (str): Path (absolute or relative) to the Python source
file which should be executed as the entry point to model
hosting. If ``source_dir`` is specified, then ``entry_point``
must point to a file located at the root of ``source_dir``.
framework_version (str): PyTorch version you want to use for
executing your model training code. Defaults to None. Required
unless ``image_uri`` is provided.
py_version (str): Python version you want to use for executing your
model training code. Defaults to ``None``. Required unless
``image_uri`` is provided.
image_uri (str): A Docker image URI (default: None). If not specified, a
default image for PyTorch will be used. If ``framework_version``
or ``py_version`` are ``None``, then ``image_uri`` is required. If
also ``None``, then a ``ValueError`` will be raised.
predictor_cls (callable[str, sagemaker.session.Session]): A function
to call to create a predictor with an endpoint name and
SageMaker ``Session``. If specified, ``deploy()`` returns the
result of invoking this function on the created endpoint name.
model_server_workers (int): Optional. The number of worker processes
used by the inference server. If None, server will use one
worker per vCPU.
**kwargs: Keyword arguments passed to the superclass
:class:`~sagemaker.model.FrameworkModel` and, subsequently, its
superclass :class:`~sagemaker.model.Model`.
.. tip::
You can find additional parameters for initializing this class at
:class:`~sagemaker.model.FrameworkModel` and
:class:`~sagemaker.model.Model`.
"""
validate_version_or_image_args(framework_version, py_version, image_uri)
if py_version == "py2":
logger.warning(
python_deprecation_warning(self._framework_name, defaults.LATEST_PY2_VERSION)
)
self.framework_version = framework_version
self.py_version = py_version
super(PyTorchModel, self).__init__(
model_data, image_uri, role, entry_point, predictor_cls=predictor_cls, **kwargs
)
self.model_server_workers = model_server_workers
def register(
self,
content_types,
response_types,
inference_instances,
transform_instances,
model_package_name=None,
model_package_group_name=None,
image_uri=None,
model_metrics=None,
metadata_properties=None,
marketplace_cert=False,
approval_status=None,
description=None,
):
"""Creates a model package for creating SageMaker models or listing on Marketplace.
Args:
content_types (list): The supported MIME types for the input data.
response_types (list): The supported MIME types for the output data.
inference_instances (list): A list of the instance types that are used to
generate inferences in real-time.
transform_instances (list): A list of the instance types on which a transformation
job can be run or on which an endpoint can be deployed.
model_package_name (str): Model Package name, exclusive to `model_package_group_name`,
using `model_package_name` makes the Model Package un-versioned (default: None).
model_package_group_name (str): Model Package Group name, exclusive to
`model_package_name`, using `model_package_group_name` makes the Model Package
versioned (default: None).
image_uri (str): Inference image uri for the container. Model class' self.image will
be used if it is None (default: None).
model_metrics (ModelMetrics): ModelMetrics object (default: None).
metadata_properties (MetadataProperties): MetadataProperties object (default: None).
marketplace_cert (bool): A boolean value indicating if the Model Package is certified
for AWS Marketplace (default: False).
approval_status (str): Model Approval Status, values can be "Approved", "Rejected",
or "PendingManualApproval" (default: "PendingManualApproval").
description (str): Model Package description (default: None).
Returns:
A `sagemaker.model.ModelPackage` instance.
"""
instance_type = inference_instances[0]
self._init_sagemaker_session_if_does_not_exist(instance_type)
if image_uri:
self.image_uri = image_uri
if not self.image_uri:
self.image_uri = self.serving_image_uri(
region_name=self.sagemaker_session.boto_session.region_name,
instance_type=instance_type,
)
return super(PyTorchModel, self).register(
content_types,
response_types,
inference_instances,
transform_instances,
model_package_name,
model_package_group_name,
image_uri,
model_metrics,
metadata_properties,
marketplace_cert,
approval_status,
description,
)
def prepare_container_def(self, instance_type=None, accelerator_type=None):
"""A container definition with framework configuration set in model environment variables.
Args:
instance_type (str): The EC2 instance type to deploy this Model to.
For example, 'ml.p2.xlarge'.
accelerator_type (str): The Elastic Inference accelerator type to
deploy to the instance for loading and making inferences to the
model.
Returns:
dict[str, str]: A container definition object usable with the
CreateModel API.
"""
deploy_image = self.image_uri
if not deploy_image:
if instance_type is None:
raise ValueError(
"Must supply either an instance type (for choosing CPU vs GPU) or an image URI."
)
region_name = self.sagemaker_session.boto_session.region_name
deploy_image = self.serving_image_uri(
region_name, instance_type, accelerator_type=accelerator_type
)
deploy_key_prefix = model_code_key_prefix(self.key_prefix, self.name, deploy_image)
self._upload_code(deploy_key_prefix, repack=self._is_mms_version())
deploy_env = dict(self.env)
deploy_env.update(self._framework_env_vars())
if self.model_server_workers:
deploy_env[MODEL_SERVER_WORKERS_PARAM_NAME.upper()] = str(self.model_server_workers)
return sagemaker.container_def(
deploy_image, self.repacked_model_data or self.model_data, deploy_env
)
def serving_image_uri(self, region_name, instance_type, accelerator_type=None):
"""Create a URI for the serving image.
Args:
region_name (str): AWS region where the image is uploaded.
instance_type (str): SageMaker instance type. Used to determine device type
(cpu/gpu/family-specific optimized).
accelerator_type (str): The Elastic Inference accelerator type to
deploy to the instance for loading and making inferences to the
model.
Returns:
str: The appropriate image URI based on the given parameters.
"""
return image_uris.retrieve(
self._framework_name,
region_name,
version=self.framework_version,
py_version=self.py_version,
instance_type=instance_type,
accelerator_type=accelerator_type,
image_scope="inference",
)
def _is_mms_version(self):
"""Determines if the framework corresponds to an and using MMS.
Whether the framework version corresponds to an inference image using
the Multi-Model Server (https://github.com/awslabs/multi-model-server).
Returns:
bool: If the framework version corresponds to an image using MMS.
"""
lowest_mms_version = packaging.version.Version(self._LOWEST_MMS_VERSION)
framework_version = packaging.version.Version(self.framework_version)
return framework_version >= lowest_mms_version