forked from mlflow/mlflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1825 lines (1589 loc) · 79 KB
/
__init__.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
The ``mlflow.sagemaker`` module provides an API for deploying MLflow models to Amazon SageMaker.
"""
import os
from subprocess import Popen
import urllib.parse
import sys
import tarfile
import logging
import time
import platform
import mlflow
import mlflow.version
from mlflow import pyfunc, mleap
from mlflow.exceptions import MlflowException
from mlflow.models import Model
from mlflow.models.model import MLMODEL_FILE_NAME
from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST, INVALID_PARAMETER_VALUE
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
from mlflow.utils import get_unique_resource_id
from mlflow.utils.annotations import experimental
from mlflow.utils.file_utils import TempDir
from mlflow.models.container import SUPPORTED_FLAVORS as SUPPORTED_DEPLOYMENT_FLAVORS
from mlflow.models.container import DEPLOYMENT_CONFIG_KEY_FLAVOR_NAME, SERVING_ENVIRONMENT
DEFAULT_IMAGE_NAME = "mlflow-pyfunc"
DEPLOYMENT_MODE_ADD = "add"
DEPLOYMENT_MODE_REPLACE = "replace"
DEPLOYMENT_MODE_CREATE = "create"
DEPLOYMENT_MODES = [DEPLOYMENT_MODE_CREATE, DEPLOYMENT_MODE_ADD, DEPLOYMENT_MODE_REPLACE]
IMAGE_NAME_ENV_VAR = "MLFLOW_SAGEMAKER_DEPLOY_IMG_URL"
# Deprecated as of MLflow 1.0.
DEPRECATED_IMAGE_NAME_ENV_VAR = "SAGEMAKER_DEPLOY_IMG_URL"
DEFAULT_BUCKET_NAME_PREFIX = "mlflow-sagemaker"
DEFAULT_SAGEMAKER_INSTANCE_TYPE = "ml.m4.xlarge"
DEFAULT_SAGEMAKER_INSTANCE_COUNT = 1
SAGEMAKER_SERVING_ENVIRONMENT = "SageMaker"
_logger = logging.getLogger(__name__)
_full_template = "{account}.dkr.ecr.{region}.amazonaws.com/{image}:{version}"
def _get_preferred_deployment_flavor(model_config):
"""
Obtains the flavor that MLflow would prefer to use when deploying the model.
If the model does not contain any supported flavors for deployment, an exception
will be thrown.
:param model_config: An MLflow model object
:return: The name of the preferred deployment flavor for the specified model
"""
if mleap.FLAVOR_NAME in model_config.flavors:
return mleap.FLAVOR_NAME
elif pyfunc.FLAVOR_NAME in model_config.flavors:
return pyfunc.FLAVOR_NAME
else:
raise MlflowException(
message=(
"The specified model does not contain any of the supported flavors for"
" deployment. The model contains the following flavors: {model_flavors}."
" Supported flavors: {supported_flavors}".format(
model_flavors=model_config.flavors.keys(),
supported_flavors=SUPPORTED_DEPLOYMENT_FLAVORS,
)
),
error_code=RESOURCE_DOES_NOT_EXIST,
)
def _validate_deployment_flavor(model_config, flavor):
"""
Checks that the specified flavor is a supported deployment flavor
and is contained in the specified model. If one of these conditions
is not met, an exception is thrown.
:param model_config: An MLflow Model object
:param flavor: The deployment flavor to validate
"""
if flavor not in SUPPORTED_DEPLOYMENT_FLAVORS:
raise MlflowException(
message=(
"The specified flavor: `{flavor_name}` is not supported for deployment."
" Please use one of the supported flavors: {supported_flavor_names}".format(
flavor_name=flavor, supported_flavor_names=SUPPORTED_DEPLOYMENT_FLAVORS
)
),
error_code=INVALID_PARAMETER_VALUE,
)
elif flavor not in model_config.flavors:
raise MlflowException(
message=(
"The specified model does not contain the specified deployment flavor:"
" `{flavor_name}`. Please use one of the following deployment flavors"
" that the model contains: {model_flavors}".format(
flavor_name=flavor, model_flavors=model_config.flavors.keys()
)
),
error_code=RESOURCE_DOES_NOT_EXIST,
)
def push_image_to_ecr(image=DEFAULT_IMAGE_NAME):
"""
Push local Docker image to AWS ECR.
The image is pushed under currently active AWS account and to the currently active AWS region.
:param image: Docker image name.
"""
import boto3
_logger.info("Pushing image to ECR")
client = boto3.client("sts")
caller_id = client.get_caller_identity()
account = caller_id["Account"]
my_session = boto3.session.Session()
region = my_session.region_name or "us-west-2"
fullname = _full_template.format(
account=account, region=region, image=image, version=mlflow.version.VERSION
)
_logger.info("Pushing docker image %s to %s", image, fullname)
ecr_client = boto3.client("ecr")
try:
ecr_client.describe_repositories(repositoryNames=[image])["repositories"]
except ecr_client.exceptions.RepositoryNotFoundException:
ecr_client.create_repository(repositoryName=image)
print("Created new ECR repository: {repository_name}".format(repository_name=image))
# TODO: it would be nice to translate the docker login, tag and push to python api.
# x = ecr_client.get_authorization_token()['authorizationData'][0]
# docker_login_cmd = "docker login -u AWS -p {token} {url}".format(token=x['authorizationToken']
# ,url=x['proxyEndpoint'])
docker_login_cmd = (
"aws ecr get-login-password"
" | docker login --username AWS "
" --password-stdin "
"{account}.dkr.ecr.{region}.amazonaws.com".format(account=account, region=region)
)
os_command_separator = ";\n"
if platform.system() == "Windows":
os_command_separator = " && "
docker_tag_cmd = "docker tag {image} {fullname}".format(image=image, fullname=fullname)
docker_push_cmd = "docker push {}".format(fullname)
cmd = os_command_separator.join([docker_login_cmd, docker_tag_cmd, docker_push_cmd])
_logger.info("Executing: %s", cmd)
os.system(cmd)
def deploy(
app_name,
model_uri,
execution_role_arn=None,
assume_role_arn=None,
bucket=None,
image_url=None,
region_name="us-west-2",
mode=DEPLOYMENT_MODE_CREATE,
archive=False,
instance_type=DEFAULT_SAGEMAKER_INSTANCE_TYPE,
instance_count=DEFAULT_SAGEMAKER_INSTANCE_COUNT,
vpc_config=None,
flavor=None,
synchronous=True,
timeout_seconds=1200,
):
"""
Deploy an MLflow model on AWS SageMaker.
The currently active AWS account must have correct permissions set up.
This function creates a SageMaker endpoint. For more information about the input data
formats accepted by this endpoint, see the
:ref:`MLflow deployment tools documentation <sagemaker_deployment>`.
:param app_name: Name of the deployed application.
:param model_uri: The location, in URI format, of the MLflow model to deploy to SageMaker.
For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
- ``models:/<model_name>/<model_version>``
- ``models:/<model_name>/<stage>``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/concepts.html#
artifact-locations>`_.
:param execution_role_arn: The name of an IAM role granting the SageMaker service permissions to
access the specified Docker image and S3 bucket containing MLflow
model artifacts. If unspecified, the currently-assumed role will be
used. This execution role is passed to the SageMaker service when
creating a SageMaker model from the specified MLflow model. It is
passed as the ``ExecutionRoleArn`` parameter of the `SageMaker
CreateModel API call <https://docs.aws.amazon.com/sagemaker/latest/
dg/API_CreateModel.html>`_. This role is *not* assumed for any other
call. For more information about SageMaker execution roles for model
creation, see
https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html.
:param assume_role_arn: The name of an IAM cross-account role to be assumed to deploy SageMaker
to another AWS account. If unspecified, SageMaker will be deployed to
the the currently active AWS account.
:param bucket: S3 bucket where model artifacts will be stored. Defaults to a
SageMaker-compatible bucket name.
:param image_url: URL of the ECR-hosted Docker image the model should be deployed into, produced
by ``mlflow sagemaker build-and-push-container``. This parameter can also
be specified by the environment variable ``MLFLOW_SAGEMAKER_DEPLOY_IMG_URL``.
:param region_name: Name of the AWS region to which to deploy the application.
:param mode: The mode in which to deploy the application. Must be one of the following:
``mlflow.sagemaker.DEPLOYMENT_MODE_CREATE``
Create an application with the specified name and model. This fails if an
application of the same name already exists.
``mlflow.sagemaker.DEPLOYMENT_MODE_REPLACE``
If an application of the specified name exists, its model(s) is replaced with
the specified model. If no such application exists, it is created with the
specified name and model.
``mlflow.sagemaker.DEPLOYMENT_MODE_ADD``
Add the specified model to a pre-existing application with the specified name,
if one exists. If the application does not exist, a new application is created
with the specified name and model. NOTE: If the application **already exists**,
the specified model is added to the application's corresponding SageMaker
endpoint with an initial weight of zero (0). To route traffic to the model,
update the application's associated endpoint configuration using either the
AWS console or the ``UpdateEndpointWeightsAndCapacities`` function defined in
https://docs.aws.amazon.com/sagemaker/latest/dg/API_UpdateEndpointWeightsAndCapacities.html.
:param archive: If ``True``, any pre-existing SageMaker application resources that become
inactive (i.e. as a result of deploying in
``mlflow.sagemaker.DEPLOYMENT_MODE_REPLACE`` mode) are preserved.
These resources may include unused SageMaker models and endpoint configurations
that were associated with a prior version of the application endpoint. If
``False``, these resources are deleted. In order to use ``archive=False``,
``deploy()`` must be executed synchronously with ``synchronous=True``.
:param instance_type: The type of SageMaker ML instance on which to deploy the model. For a list
of supported instance types, see
https://aws.amazon.com/sagemaker/pricing/instance-types/.
:param instance_count: The number of SageMaker ML instances on which to deploy the model.
:param vpc_config: A dictionary specifying the VPC configuration to use when creating the
new SageMaker model associated with this application. The acceptable values
for this parameter are identical to those of the ``VpcConfig`` parameter in
the `SageMaker boto3 client's create_model method
<https://boto3.readthedocs.io/en/latest/reference/services/sagemaker.html
#SageMaker.Client.create_model>`_. For more information, see
https://docs.aws.amazon.com/sagemaker/latest/dg/API_VpcConfig.html.
.. code-block:: python
:caption: Example
import mlflow.sagemaker as mfs
vpc_config = {
'SecurityGroupIds': [
'sg-123456abc',
],
'Subnets': [
'subnet-123456abc',
]
}
mfs.deploy(..., vpc_config=vpc_config)
:param flavor: The name of the flavor of the model to use for deployment. Must be either
``None`` or one of mlflow.sagemaker.SUPPORTED_DEPLOYMENT_FLAVORS. If ``None``,
a flavor is automatically selected from the model's available flavors. If the
specified flavor is not present or not supported for deployment, an exception
will be thrown.
:param synchronous: If ``True``, this function will block until the deployment process succeeds
or encounters an irrecoverable failure. If ``False``, this function will
return immediately after starting the deployment process. It will not wait
for the deployment process to complete; in this case, the caller is
responsible for monitoring the health and status of the pending deployment
via native SageMaker APIs or the AWS console.
:param timeout_seconds: If ``synchronous`` is ``True``, the deployment process will return after
the specified number of seconds if no definitive result (success or
failure) is achieved. Once the function returns, the caller is
responsible for monitoring the health and status of the pending
deployment using native SageMaker APIs or the AWS console. If
``synchronous`` is ``False``, this parameter is ignored.
"""
import boto3
if (not archive) and (not synchronous):
raise MlflowException(
message=(
"Resources must be archived when `deploy()` is executed in non-synchronous mode."
" Either set `synchronous=True` or `archive=True`."
),
error_code=INVALID_PARAMETER_VALUE,
)
if mode not in DEPLOYMENT_MODES:
raise MlflowException(
message="`mode` must be one of: {deployment_modes}".format(
deployment_modes=",".join(DEPLOYMENT_MODES)
),
error_code=INVALID_PARAMETER_VALUE,
)
model_path = _download_artifact_from_uri(model_uri)
model_config_path = os.path.join(model_path, MLMODEL_FILE_NAME)
if not os.path.exists(model_config_path):
raise MlflowException(
message=(
"Failed to find {} configuration within the specified model's" " root directory."
).format(MLMODEL_FILE_NAME),
error_code=INVALID_PARAMETER_VALUE,
)
model_config = Model.load(model_config_path)
if flavor is None:
flavor = _get_preferred_deployment_flavor(model_config)
else:
_validate_deployment_flavor(model_config, flavor)
_logger.info("Using the %s flavor for deployment!", flavor)
if assume_role_arn is None:
assume_role_credentials = dict()
else:
assume_role_credentials = _assume_role_and_get_credentials(assume_role_arn=assume_role_arn)
s3_client = boto3.client("s3", region_name=region_name, **assume_role_credentials)
sage_client = boto3.client("sagemaker", region_name=region_name, **assume_role_credentials)
endpoint_exists = _find_endpoint(endpoint_name=app_name, sage_client=sage_client) is not None
if endpoint_exists and mode == DEPLOYMENT_MODE_CREATE:
raise MlflowException(
message=(
"You are attempting to deploy an application with name: {application_name} in"
" '{mode_create}' mode. However, an application with the same name already"
" exists. If you want to update this application, deploy in '{mode_add}' or"
" '{mode_replace}' mode.".format(
application_name=app_name,
mode_create=DEPLOYMENT_MODE_CREATE,
mode_add=DEPLOYMENT_MODE_ADD,
mode_replace=DEPLOYMENT_MODE_REPLACE,
)
),
error_code=INVALID_PARAMETER_VALUE,
)
model_name = _get_sagemaker_model_name(endpoint_name=app_name)
if not image_url:
image_url = _get_default_image_url(region_name=region_name)
if not execution_role_arn:
execution_role_arn = _get_assumed_role_arn(**assume_role_credentials)
if not bucket:
_logger.info("No model data bucket specified, using the default bucket")
bucket = _get_default_s3_bucket(region_name, **assume_role_credentials)
model_s3_path = _upload_s3(
local_model_path=model_path,
bucket=bucket,
prefix=model_name,
region_name=region_name,
s3_client=s3_client,
**assume_role_credentials,
)
if endpoint_exists:
deployment_operation = _update_sagemaker_endpoint(
endpoint_name=app_name,
model_name=model_name,
model_s3_path=model_s3_path,
model_uri=model_uri,
image_url=image_url,
flavor=flavor,
instance_type=instance_type,
instance_count=instance_count,
vpc_config=vpc_config,
mode=mode,
role=execution_role_arn,
sage_client=sage_client,
s3_client=s3_client,
)
else:
deployment_operation = _create_sagemaker_endpoint(
endpoint_name=app_name,
model_name=model_name,
model_s3_path=model_s3_path,
model_uri=model_uri,
image_url=image_url,
flavor=flavor,
instance_type=instance_type,
instance_count=instance_count,
vpc_config=vpc_config,
role=execution_role_arn,
sage_client=sage_client,
)
if synchronous:
_logger.info("Waiting for the deployment operation to complete...")
operation_status = deployment_operation.await_completion(timeout_seconds=timeout_seconds)
if operation_status.state == _SageMakerOperationStatus.STATE_SUCCEEDED:
_logger.info(
'The deployment operation completed successfully with message: "%s"',
operation_status.message,
)
else:
raise MlflowException(
"The deployment operation failed with the following error message:"
' "{error_message}"'.format(error_message=operation_status.message)
)
if not archive:
deployment_operation.clean_up()
def delete(
app_name,
region_name="us-west-2",
assume_role_arn=None,
archive=False,
synchronous=True,
timeout_seconds=300,
):
"""
Delete a SageMaker application.
:param app_name: Name of the deployed application.
:param region_name: Name of the AWS region in which the application is deployed.
:param assume_role_arn: The name of an IAM cross-account role to be assumed to deploy SageMaker
to another AWS account. If unspecified, SageMaker will be deployed to
the the currently active AWS account.
:param archive: If ``True``, resources associated with the specified application, such
as its associated models and endpoint configuration, are preserved.
If ``False``, these resources are deleted. In order to use
``archive=False``, ``delete()`` must be executed synchronously with
``synchronous=True``.
:param synchronous: If `True`, this function blocks until the deletion process succeeds
or encounters an irrecoverable failure. If `False`, this function
returns immediately after starting the deletion process. It will not wait
for the deletion process to complete; in this case, the caller is
responsible for monitoring the status of the deletion process via native
SageMaker APIs or the AWS console.
:param timeout_seconds: If `synchronous` is `True`, the deletion process returns after the
specified number of seconds if no definitive result (success or failure)
is achieved. Once the function returns, the caller is responsible
for monitoring the status of the deletion process via native SageMaker
APIs or the AWS console. If `synchronous` is False, this parameter
is ignored.
"""
import boto3
if (not archive) and (not synchronous):
raise MlflowException(
message=(
"Resources must be archived when `deploy()` is executed in non-synchronous mode."
" Either set `synchronous=True` or `archive=True`."
),
error_code=INVALID_PARAMETER_VALUE,
)
if assume_role_arn is None:
assume_role_credentials = dict()
else:
assume_role_credentials = _assume_role_and_get_credentials(assume_role_arn=assume_role_arn)
s3_client = boto3.client("s3", region_name=region_name, **assume_role_credentials)
sage_client = boto3.client("sagemaker", region_name=region_name, **assume_role_credentials)
endpoint_info = sage_client.describe_endpoint(EndpointName=app_name)
endpoint_arn = endpoint_info["EndpointArn"]
sage_client.delete_endpoint(EndpointName=app_name)
_logger.info("Deleted endpoint with arn: %s", endpoint_arn)
def status_check_fn():
endpoint_info = _find_endpoint(endpoint_name=app_name, sage_client=sage_client)
if endpoint_info is not None:
return _SageMakerOperationStatus.in_progress(
"Deletion is still in progress. Current endpoint status: {endpoint_status}".format(
endpoint_status=endpoint_info["EndpointStatus"]
)
)
else:
return _SageMakerOperationStatus.succeeded(
"The SageMaker endpoint was deleted successfully."
)
def cleanup_fn():
_logger.info("Cleaning up unused resources...")
config_name = endpoint_info["EndpointConfigName"]
config_info = sage_client.describe_endpoint_config(EndpointConfigName=config_name)
config_arn = config_info["EndpointConfigArn"]
sage_client.delete_endpoint_config(EndpointConfigName=config_name)
_logger.info("Deleted associated endpoint configuration with arn: %s", config_arn)
for pv in config_info["ProductionVariants"]:
model_name = pv["ModelName"]
model_arn = _delete_sagemaker_model(model_name, sage_client, s3_client)
_logger.info("Deleted associated model with arn: %s", model_arn)
delete_operation = _SageMakerOperation(status_check_fn=status_check_fn, cleanup_fn=cleanup_fn)
if synchronous:
_logger.info("Waiting for the delete operation to complete...")
operation_status = delete_operation.await_completion(timeout_seconds=timeout_seconds)
if operation_status.state == _SageMakerOperationStatus.STATE_SUCCEEDED:
_logger.info(
'The deletion operation completed successfully with message: "%s"',
operation_status.message,
)
else:
raise MlflowException(
"The deletion operation failed with the following error message:"
' "{error_message}"'.format(error_message=operation_status.message)
)
if not archive:
delete_operation.clean_up()
@experimental
def deploy_transform_job(
job_name,
model_uri,
s3_input_data_type,
s3_input_uri,
content_type,
s3_output_path,
compression_type="None",
split_type="Line",
accept="text/csv",
assemble_with="Line",
input_filter="$",
output_filter="$",
join_resource="None",
execution_role_arn=None,
assume_role_arn=None,
bucket=None,
image_url=None,
region_name="us-west-2",
instance_type=DEFAULT_SAGEMAKER_INSTANCE_TYPE,
instance_count=DEFAULT_SAGEMAKER_INSTANCE_COUNT,
vpc_config=None,
flavor=None,
archive=False,
synchronous=True,
timeout_seconds=1200,
):
"""
Deploy an MLflow model on AWS SageMaker and create the corresponding batch transform job.
The currently active AWS account must have correct permissions set up.
:param job_name: Name of the deployed Sagemaker batch transform job.
:param model_uri: The location, in URI format, of the MLflow model to deploy to SageMaker.
For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
- ``models:/<model_name>/<model_version>``
- ``models:/<model_name>/<stage>``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/concepts.html#
artifact-locations>`_.
:param s3_input_data_type: Input data type for the transform job.
:param s3_input_uri: S3 key name prefix or a manifest of the input data.
:param content_type: The multipurpose internet mail extension (MIME) type of the data.
:param s3_output_path: The S3 path to store the output results of the Sagemaker transform job.
:param compression_type: The compression type of the transform data.
:param split_type: The method to split the transform job's data files into smaller batches.
:param accept: The multipurpose internet mail extension (MIME) type of the output data.
:param assemble_with: The method to assemble the results of the transform job as
a single S3 object.
:param input_filter: A JSONPath expression used to select a portion of the input data for
the transform job.
:param output_filter: A JSONPath expression used to select a portion of the output data from
the transform job.
:param join_resource: The source of the data to join with the transformed data.
:param execution_role_arn: The name of an IAM role granting the SageMaker service permissions to
access the specified Docker image and S3 bucket containing MLflow
model artifacts. If unspecified, the currently-assumed role will be
used. This execution role is passed to the SageMaker service when
creating a SageMaker model from the specified MLflow model. It is
passed as the ``ExecutionRoleArn`` parameter of the `SageMaker
CreateModel API call <https://docs.aws.amazon.com/sagemaker/latest/
dg/API_CreateModel.html>`_. This role is *not* assumed for any other
call. For more information about SageMaker execution roles for model
creation, see
https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html.
:param assume_role_arn: The name of an IAM cross-account role to be assumed to deploy SageMaker
to another AWS account. If unspecified, SageMaker will be deployed to
the the currently active AWS account.
:param bucket: S3 bucket where model artifacts will be stored. Defaults to a
SageMaker-compatible bucket name.
:param image_url: URL of the ECR-hosted Docker image the model should be deployed into, produced
by ``mlflow sagemaker build-and-push-container``. This parameter can also
be specified by the environment variable ``MLFLOW_SAGEMAKER_DEPLOY_IMG_URL``.
:param region_name: Name of the AWS region to which to deploy the application.
:param instance_type: The type of SageMaker ML instance on which to deploy the model. For a list
of supported instance types, see
https://aws.amazon.com/sagemaker/pricing/instance-types/.
:param instance_count: The number of SageMaker ML instances on which to deploy the model.
:param vpc_config: A dictionary specifying the VPC configuration to use when creating the
new SageMaker model associated with this batch transform job. The acceptable
values for this parameter are identical to those of the ``VpcConfig``
parameter in the `SageMaker boto3 client's create_model method
<https://boto3.readthedocs.io/en/latest/reference/services/sagemaker.html
#SageMaker.Client.create_model>`_. For more information, see
https://docs.aws.amazon.com/sagemaker/latest/dg/API_VpcConfig.html.
.. code-block:: python
:caption: Example
import mlflow.sagemaker as mfs
vpc_config = {
'SecurityGroupIds': [
'sg-123456abc',
],
'Subnets': [
'subnet-123456abc',
]
}
mfs.deploy_transform_job(..., vpc_config=vpc_config)
:param flavor: The name of the flavor of the model to use for deployment. Must be either
``None`` or one of mlflow.sagemaker.SUPPORTED_DEPLOYMENT_FLAVORS. If ``None``,
a flavor is automatically selected from the model's available flavors. If the
specified flavor is not present or not supported for deployment, an exception
will be thrown.
:param archive: If ``True``, resources like Sagemaker models and model artifacts in S3 are
preserved after the finished batch transform job. If ``False``, these resources
are deleted. In order to use ``archive=False``, ``deploy_transform_job()`` must
be executed synchronously with ``synchronous=True``.
:param synchronous: If ``True``, this function will block until the deployment process succeeds
or encounters an irrecoverable failure. If ``False``, this function will
return immediately after starting the deployment process. It will not wait
for the deployment process to complete; in this case, the caller is
responsible for monitoring the health and status of the pending deployment
via native SageMaker APIs or the AWS console.
:param timeout_seconds: If ``synchronous`` is ``True``, the deployment process will return after
the specified number of seconds if no definitive result (success or
failure) is achieved. Once the function returns, the caller is
responsible for monitoring the health and status of the pending
deployment using native SageMaker APIs or the AWS console. If
``synchronous`` is ``False``, this parameter is ignored.
"""
import boto3
if (not archive) and (not synchronous):
raise MlflowException(
message=(
"Resources must be archived when `deploy_transform_job()`"
" is executed in non-synchronous mode."
" Either set `synchronous=True` or `archive=True`."
),
error_code=INVALID_PARAMETER_VALUE,
)
model_path = _download_artifact_from_uri(model_uri)
model_config_path = os.path.join(model_path, MLMODEL_FILE_NAME)
if not os.path.exists(model_config_path):
raise MlflowException(
message=(
"Failed to find {} configuration within the specified model's" " root directory."
).format(MLMODEL_FILE_NAME),
error_code=INVALID_PARAMETER_VALUE,
)
model_config = Model.load(model_config_path)
if flavor is None:
flavor = _get_preferred_deployment_flavor(model_config)
else:
_validate_deployment_flavor(model_config, flavor)
_logger.info("Using the %s flavor for deployment!", flavor)
if assume_role_arn is None:
assume_role_credentials = dict()
else:
assume_role_credentials = _assume_role_and_get_credentials(assume_role_arn=assume_role_arn)
s3_client = boto3.client("s3", region_name=region_name, **assume_role_credentials)
sage_client = boto3.client("sagemaker", region_name=region_name, **assume_role_credentials)
transform_job_exists = (
_find_transform_job(job_name=job_name, sage_client=sage_client) is not None
)
if transform_job_exists:
raise MlflowException(
message=(
"You are attempting to deploy a batch transform job with name: {job_name}."
"However, a batch transform job with the same name already exists.".format(
job_name=job_name
)
),
error_code=INVALID_PARAMETER_VALUE,
)
model_name = _get_sagemaker_transform_model_name(job_name=job_name)
if not image_url:
image_url = _get_default_image_url(region_name=region_name)
if not execution_role_arn:
execution_role_arn = _get_assumed_role_arn(**assume_role_credentials)
if not bucket:
_logger.info("No model data bucket specified, using the default bucket")
bucket = _get_default_s3_bucket(region_name, **assume_role_credentials)
model_s3_path = _upload_s3(
local_model_path=model_path,
bucket=bucket,
prefix=model_name,
region_name=region_name,
s3_client=s3_client,
**assume_role_credentials,
)
deployment_operation = _create_sagemaker_transform_job(
job_name=job_name,
model_name=model_name,
model_s3_path=model_s3_path,
model_uri=model_uri,
image_url=image_url,
flavor=flavor,
vpc_config=vpc_config,
role=execution_role_arn,
sage_client=sage_client,
s3_client=s3_client,
instance_type=instance_type,
instance_count=instance_count,
s3_input_data_type=s3_input_data_type,
s3_input_uri=s3_input_uri,
content_type=content_type,
compression_type=compression_type,
split_type=split_type,
s3_output_path=s3_output_path,
accept=accept,
assemble_with=assemble_with,
input_filter=input_filter,
output_filter=output_filter,
join_resource=join_resource,
)
if synchronous:
_logger.info("Waiting for the batch transform job to complete...")
operation_status = deployment_operation.await_completion(timeout_seconds=timeout_seconds)
if operation_status.state == _SageMakerOperationStatus.STATE_SUCCEEDED:
_logger.info(
'The batch transform job completed successfully with message: "%s"',
operation_status.message,
)
else:
raise MlflowException(
"The batch transform job failed with the following error message:"
' "{error_message}"'.format(error_message=operation_status.message)
)
if not archive:
deployment_operation.clean_up()
@experimental
def terminate_transform_job(
job_name,
region_name="us-west-2",
assume_role_arn=None,
archive=False,
synchronous=True,
timeout_seconds=300,
):
"""
Terminate a SageMaker batch transform job.
:param job_name: Name of the deployed Sagemaker batch transform job.
:param region_name: Name of the AWS region in which the batch transform job is deployed.
:param assume_role_arn: The name of an IAM cross-account role to be assumed to deploy SageMaker
to another AWS account. If unspecified, SageMaker will be deployed to
the the currently active AWS account.
:param archive: If ``True``, resources associated with the specified batch transform job,
such as its associated models and model artifacts, are preserved.
If ``False``, these resources are deleted. In order to use ``archive=False``,
``terminate_transform_job()`` must be executed synchronously
with ``synchronous=True``.
:param synchronous: If `True`, this function blocks until the termination process succeeds
or encounters an irrecoverable failure. If `False`, this function
returns immediately after starting the termination process. It will not
wait for the termination process to complete; in this case, the caller is
responsible for monitoring the status of the termination process via native
SageMaker APIs or the AWS console.
:param timeout_seconds: If `synchronous` is `True`, the termination process returns after the
specified number of seconds if no definitive result (success or failure)
is achieved. Once the function returns, the caller is responsible
for monitoring the status of the termination process via native
SageMaker APIs or the AWS console. If `synchronous` is False, this
parameter is ignored.
"""
import boto3
if (not archive) and (not synchronous):
raise MlflowException(
message=(
"Resources must be archived when `terminate_transform_job()`"
" is executed in non-synchronous mode."
" Either set `synchronous=True` or `archive=True`."
),
error_code=INVALID_PARAMETER_VALUE,
)
if assume_role_arn is None:
assume_role_credentials = dict()
else:
assume_role_credentials = _assume_role_and_get_credentials(assume_role_arn=assume_role_arn)
s3_client = boto3.client("s3", region_name=region_name, **assume_role_credentials)
sage_client = boto3.client("sagemaker", region_name=region_name, **assume_role_credentials)
transform_job_info = sage_client.describe_transform_job(TransformJobName=job_name)
transform_job_arn = transform_job_info["TransformJobArn"]
sage_client.stop_transform_job(TransformJobName=job_name)
_logger.info("Terminated batch transform job with arn: %s", transform_job_arn)
def status_check_fn():
transform_job_info = _find_transform_job(job_name=job_name, sage_client=sage_client)
if transform_job_info["TransformJobStatus"] == "Stopping":
return _SageMakerOperationStatus.in_progress(
"Termination is still in progress. Current batch transform job status:\
{transform_job_status}".format(
transform_job_status=transform_job_info["TransformJobStatus"]
)
)
elif transform_job_info["TransformJobStatus"] == "Stopped":
return _SageMakerOperationStatus.succeeded(
"The SageMaker batch transform job was terminated successfully."
)
def cleanup_fn():
_logger.info("Cleaning up unused resources...")
model_name = transform_job_info["ModelName"]
model_arn = _delete_sagemaker_model(model_name, sage_client, s3_client)
_logger.info("Deleted associated model with arn: %s", model_arn)
stop_operation = _SageMakerOperation(status_check_fn=status_check_fn, cleanup_fn=cleanup_fn)
if synchronous:
_logger.info("Waiting for the termination operation to complete...")
operation_status = stop_operation.await_completion(timeout_seconds=timeout_seconds)
if operation_status.state == _SageMakerOperationStatus.STATE_SUCCEEDED:
_logger.info(
'The termination operation completed successfully with message: "%s"',
operation_status.message,
)
else:
raise MlflowException(
"The termination operation failed with the following error message:"
' "{error_message}"'.format(error_message=operation_status.message)
)
if not archive:
stop_operation.clean_up()
@experimental
def push_model_to_sagemaker(
model_name,
model_uri,
execution_role_arn=None,
assume_role_arn=None,
bucket=None,
image_url=None,
region_name="us-west-2",
vpc_config=None,
flavor=None,
):
"""
Push an MLflow model to AWS SageMaker model registry.
The currently active AWS account must have correct permissions set up.
:param model_name: Name of the Sagemaker model.
:param model_uri: The location, in URI format, of the MLflow model to deploy to SageMaker.
For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
- ``models:/<model_name>/<model_version>``
- ``models:/<model_name>/<stage>``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/concepts.html#
artifact-locations>`_.
:param execution_role_arn: The name of an IAM role granting the SageMaker service permissions to
access the specified Docker image and S3 bucket containing MLflow
model artifacts. If unspecified, the currently-assumed role will be
used. This execution role is passed to the SageMaker service when
creating a SageMaker model from the specified MLflow model. It is
passed as the ``ExecutionRoleArn`` parameter of the `SageMaker
CreateModel API call <https://docs.aws.amazon.com/sagemaker/latest/
dg/API_CreateModel.html>`_. This role is *not* assumed for any other
call. For more information about SageMaker execution roles for model
creation, see
https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html.
:param assume_role_arn: The name of an IAM cross-account role to be assumed to deploy SageMaker
to another AWS account. If unspecified, SageMaker will be deployed to
the the currently active AWS account.
:param bucket: S3 bucket where model artifacts will be stored. Defaults to a
SageMaker-compatible bucket name.
:param image_url: URL of the ECR-hosted Docker image the model should be deployed into, produced
by ``mlflow sagemaker build-and-push-container``. This parameter can also
be specified by the environment variable ``MLFLOW_SAGEMAKER_DEPLOY_IMG_URL``.
:param region_name: Name of the AWS region to which to deploy the application.
:param vpc_config: A dictionary specifying the VPC configuration to use when creating the
new SageMaker model. The acceptable values for this parameter are identical
to those of the ``VpcConfig`` parameter in the `SageMaker boto3 client's
create_model method
<https://boto3.readthedocs.io/en/latest/reference/services/sagemaker.html
#SageMaker.Client.create_model>`_. For more information, see
https://docs.aws.amazon.com/sagemaker/latest/dg/API_VpcConfig.html.
.. code-block:: python
:caption: Example
import mlflow.sagemaker as mfs
vpc_config = {
'SecurityGroupIds': [
'sg-123456abc',
],
'Subnets': [
'subnet-123456abc',
]
}
mfs.push_model_to_sagemaker(..., vpc_config=vpc_config)
:param flavor: The name of the flavor of the model to use for deployment. Must be either
``None`` or one of mlflow.sagemaker.SUPPORTED_DEPLOYMENT_FLAVORS. If ``None``,
a flavor is automatically selected from the model's available flavors. If the
specified flavor is not present or not supported for deployment, an exception
will be thrown.
"""
import boto3
model_path = _download_artifact_from_uri(model_uri)
model_config_path = os.path.join(model_path, MLMODEL_FILE_NAME)
if not os.path.exists(model_config_path):
raise MlflowException(
message=(
"Failed to find {} configuration within the specified model's" " root directory."
).format(MLMODEL_FILE_NAME),
error_code=INVALID_PARAMETER_VALUE,
)
model_config = Model.load(model_config_path)
if flavor is None:
flavor = _get_preferred_deployment_flavor(model_config)
else:
_validate_deployment_flavor(model_config, flavor)
_logger.info("Using the %s flavor for deployment!", flavor)
if assume_role_arn is None:
assume_role_credentials = dict()
else:
assume_role_credentials = _assume_role_and_get_credentials(assume_role_arn=assume_role_arn)
s3_client = boto3.client("s3", region_name=region_name, **assume_role_credentials)
sage_client = boto3.client("sagemaker", region_name=region_name, **assume_role_credentials)
if _does_model_exist(model_name=model_name, sage_client=sage_client):
raise MlflowException(
message=(
"You are attempting to create a Sagemaker model with name: {model_name}."
"However, a model with the same name already exists.".format(model_name=model_name)
),
error_code=INVALID_PARAMETER_VALUE,
)
if not image_url:
image_url = _get_default_image_url(region_name=region_name)
if not execution_role_arn:
execution_role_arn = _get_assumed_role_arn(**assume_role_credentials)
if not bucket:
_logger.info("No model data bucket specified, using the default bucket")
bucket = _get_default_s3_bucket(region_name, **assume_role_credentials)
model_s3_path = _upload_s3(
local_model_path=model_path,
bucket=bucket,
prefix=model_name,
region_name=region_name,
s3_client=s3_client,
**assume_role_credentials,
)
model_response = _create_sagemaker_model(
model_name=model_name,
model_s3_path=model_s3_path,