-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmodel_monitoring.py
4164 lines (3663 loc) · 183 KB
/
model_monitoring.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
# Copyright 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.
"""This module contains code related to Amazon SageMaker Model Monitoring.
These classes assist with suggesting baselines and creating monitoring schedules for
data captured by SageMaker Endpoints.
"""
from __future__ import print_function, absolute_import
import copy
import json
import os
import pathlib
import logging
import uuid
from typing import Union, Optional, Dict, List
import attr
from six import string_types
from six.moves.urllib.parse import urlparse
from botocore.exceptions import ClientError
from sagemaker import image_uris, s3
from sagemaker.config.config_schema import (
SAGEMAKER,
MONITORING_SCHEDULE,
TAGS,
MONITORING_JOB_SUBNETS_PATH,
MONITORING_JOB_ENABLE_NETWORK_ISOLATION_PATH,
MONITORING_JOB_ENVIRONMENT_PATH,
MONITORING_SCHEDULE_INTER_CONTAINER_ENCRYPTION_PATH,
MONITORING_JOB_VOLUME_KMS_KEY_ID_PATH,
MONITORING_JOB_SECURITY_GROUP_IDS_PATH,
MONITORING_JOB_OUTPUT_KMS_KEY_ID_PATH,
MONITORING_JOB_ROLE_ARN_PATH,
)
from sagemaker.exceptions import UnexpectedStatusException
from sagemaker.model_monitor.monitoring_files import Constraints, ConstraintViolations, Statistics
from sagemaker.model_monitor.monitoring_alert import (
MonitoringAlertSummary,
MonitoringAlertHistorySummary,
MonitoringAlertActions,
ModelDashboardIndicatorAction,
)
from sagemaker.model_monitor.data_quality_monitoring_config import DataQualityMonitoringConfig
from sagemaker.model_monitor.dataset_format import MonitoringDatasetFormat
from sagemaker.network import NetworkConfig
from sagemaker.processing import Processor, ProcessingInput, ProcessingJob, ProcessingOutput
from sagemaker.session import Session
from sagemaker.utils import (
name_from_base,
retries,
resolve_value_from_config,
resolve_class_attribute_from_config,
format_tags,
)
from sagemaker.lineage._utils import get_resource_name_from_arn
from sagemaker.model_monitor.cron_expression_generator import CronExpressionGenerator
DEFAULT_REPOSITORY_NAME = "sagemaker-model-monitor-analyzer"
STATISTICS_JSON_DEFAULT_FILE_NAME = "statistics.json"
CONSTRAINTS_JSON_DEFAULT_FILE_NAME = "constraints.json"
CONSTRAINT_VIOLATIONS_JSON_DEFAULT_FILE_NAME = "constraint_violations.json"
_CONTAINER_BASE_PATH = "/opt/ml/processing"
_CONTAINER_INPUT_PATH = "input"
_CONTAINER_ENDPOINT_INPUT_PATH = "endpoint"
_BASELINE_DATASET_INPUT_NAME = "baseline_dataset_input"
_RECORD_PREPROCESSOR_SCRIPT_INPUT_NAME = "record_preprocessor_script_input"
_POST_ANALYTICS_PROCESSOR_SCRIPT_INPUT_NAME = "post_analytics_processor_script_input"
_CONTAINER_OUTPUT_PATH = "output"
_DEFAULT_OUTPUT_NAME = "monitoring_output"
_MODEL_MONITOR_S3_PATH = "model-monitor"
_BASELINING_S3_PATH = "baselining"
_MONITORING_S3_PATH = "monitoring"
_RESULTS_S3_PATH = "results"
_INPUT_S3_PATH = "input"
_SUGGESTION_JOB_BASE_NAME = "baseline-suggestion-job"
_MONITORING_SCHEDULE_BASE_NAME = "monitoring-schedule"
_DATASET_SOURCE_PATH_ENV_NAME = "dataset_source"
_DATASET_FORMAT_ENV_NAME = "dataset_format"
_OUTPUT_PATH_ENV_NAME = "output_path"
_RECORD_PREPROCESSOR_SCRIPT_ENV_NAME = "record_preprocessor_script"
_POST_ANALYTICS_PROCESSOR_SCRIPT_ENV_NAME = "post_analytics_processor_script"
_PUBLISH_CLOUDWATCH_METRICS_ENV_NAME = "publish_cloudwatch_metrics"
_ANALYSIS_TYPE_ENV_NAME = "analysis_type"
_PROBLEM_TYPE_ENV_NAME = "problem_type"
_GROUND_TRUTH_ATTRIBUTE_ENV_NAME = "ground_truth_attribute"
_INFERENCE_ATTRIBUTE_ENV_NAME = "inference_attribute"
_PROBABILITY_ATTRIBUTE_ENV_NAME = "probability_attribute"
_PROBABILITY_THRESHOLD_ATTRIBUTE_ENV_NAME = "probability_threshold_attribute"
_CATEGORICAL_DRIFT_METHOD_ENV_NAME = "categorical_drift_method"
# Setting _LOGGER for backward compatibility, in case users import it...
logger = _LOGGER = logging.getLogger(__name__)
framework_name = "model-monitor"
class ModelMonitor(object):
"""Sets up Amazon SageMaker Monitoring Schedules and baseline suggestions.
Use this class when you want to provide your own container image containing the code
you'd like to run, in order to produce your own statistics and constraint validation files.
For a more guided experience, consider using the DefaultModelMonitor class instead.
"""
def __init__(
self,
role=None,
image_uri=None,
instance_count=1,
instance_type="ml.m5.xlarge",
entrypoint=None,
volume_size_in_gb=30,
volume_kms_key=None,
output_kms_key=None,
max_runtime_in_seconds=None,
base_job_name=None,
sagemaker_session=None,
env=None,
tags=None,
network_config=None,
):
"""Initializes a ``Monitor`` instance.
The Monitor handles baselining datasets and creating Amazon SageMaker Monitoring Schedules
to monitor SageMaker endpoints.
Args:
role (str): An AWS IAM role. The Amazon SageMaker jobs use this role.
image_uri (str): The uri of the image to use for the jobs started by
the Monitor.
instance_count (int): The number of instances to run
the jobs with.
instance_type (str): Type of EC2 instance to use for
the job, for example, 'ml.m5.xlarge'.
entrypoint ([str]): The entrypoint for the job.
volume_size_in_gb (int): Size in GB of the EBS volume
to use for storing data during processing (default: 30).
volume_kms_key (str): A KMS key for the job's volume.
output_kms_key (str): The KMS key id for the job's outputs.
max_runtime_in_seconds (int): Timeout in seconds. After this amount of
time, Amazon SageMaker terminates the job regardless of its current status.
Default: 3600
base_job_name (str): Prefix for the job name. If not specified,
a default name is generated based on the training image name and
current timestamp.
sagemaker_session (sagemaker.session.Session): Session object which
manages interactions with Amazon SageMaker APIs and any other
AWS services needed. If not specified, one is created using
the default AWS configuration chain.
env (dict): Environment variables to be passed to the job.
tags (Optional[Tags]): List of tags to be passed to the job.
network_config (sagemaker.network.NetworkConfig): A NetworkConfig
object that configures network isolation, encryption of
inter-container traffic, security group IDs, and subnets.
"""
self.image_uri = image_uri
self.instance_count = instance_count
self.instance_type = instance_type
self.entrypoint = entrypoint
self.volume_size_in_gb = volume_size_in_gb
self.max_runtime_in_seconds = max_runtime_in_seconds
self.base_job_name = base_job_name
self.sagemaker_session = sagemaker_session or Session()
self.tags = format_tags(tags)
self.baselining_jobs = []
self.latest_baselining_job = None
self.arguments = None
self.latest_baselining_job_name = None
self.monitoring_schedule_name = None
self.job_definition_name = None
self.role = resolve_value_from_config(
role, MONITORING_JOB_ROLE_ARN_PATH, sagemaker_session=self.sagemaker_session
)
if not self.role:
# Originally IAM role was a required parameter.
# Now we marked that as Optional because we can fetch it from SageMakerConfig
# Because of marking that parameter as optional, we should validate if it is None, even
# after fetching the config.
raise ValueError("An AWS IAM role is required to create a Monitoring Schedule.")
self.volume_kms_key = resolve_value_from_config(
volume_kms_key,
MONITORING_JOB_VOLUME_KMS_KEY_ID_PATH,
sagemaker_session=self.sagemaker_session,
)
self.output_kms_key = resolve_value_from_config(
output_kms_key,
MONITORING_JOB_OUTPUT_KMS_KEY_ID_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
network_config,
"subnets",
MONITORING_JOB_SUBNETS_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
self.network_config,
"security_group_ids",
MONITORING_JOB_SECURITY_GROUP_IDS_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
self.network_config,
"enable_network_isolation",
MONITORING_JOB_ENABLE_NETWORK_ISOLATION_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
self.network_config,
"encrypt_inter_container_traffic",
MONITORING_SCHEDULE_INTER_CONTAINER_ENCRYPTION_PATH,
sagemaker_session=self.sagemaker_session,
)
self.env = resolve_value_from_config(
env,
MONITORING_JOB_ENVIRONMENT_PATH,
default_value=None,
sagemaker_session=self.sagemaker_session,
)
def run_baseline(
self, baseline_inputs, output, arguments=None, wait=True, logs=True, job_name=None
):
"""Run a processing job meant to baseline your dataset.
Args:
baseline_inputs ([sagemaker.processing.ProcessingInput]): Input files for the processing
job. These must be provided as ProcessingInput objects.
output (sagemaker.processing.ProcessingOutput): Destination of the constraint_violations
and statistics json files.
arguments ([str]): A list of string arguments to be passed to a processing job.
wait (bool): Whether the call should wait until the job completes (default: True).
logs (bool): Whether to show the logs produced by the job.
Only meaningful when wait is True (default: True).
job_name (str): Processing job name. If not specified, the processor generates
a default job name, based on the image name and current timestamp.
"""
self.latest_baselining_job_name = self._generate_baselining_job_name(job_name=job_name)
self.arguments = arguments
normalized_baseline_inputs = self._normalize_baseline_inputs(
baseline_inputs=baseline_inputs
)
normalized_output = self._normalize_processing_output(output=output)
baselining_processor = Processor(
role=self.role,
image_uri=self.image_uri,
instance_count=self.instance_count,
instance_type=self.instance_type,
entrypoint=self.entrypoint,
volume_size_in_gb=self.volume_size_in_gb,
volume_kms_key=self.volume_kms_key,
output_kms_key=self.output_kms_key,
max_runtime_in_seconds=self.max_runtime_in_seconds,
base_job_name=self.base_job_name,
sagemaker_session=self.sagemaker_session,
env=self.env,
tags=self.tags,
network_config=self.network_config,
)
baselining_processor.run(
inputs=normalized_baseline_inputs,
outputs=[normalized_output],
arguments=self.arguments,
wait=wait,
logs=logs,
job_name=self.latest_baselining_job_name,
)
self.latest_baselining_job = BaseliningJob.from_processing_job(
processing_job=baselining_processor.latest_job
)
self.baselining_jobs.append(self.latest_baselining_job)
def create_monitoring_schedule(
self,
endpoint_input=None,
output=None,
statistics=None,
constraints=None,
monitor_schedule_name=None,
schedule_cron_expression=None,
batch_transform_input=None,
arguments=None,
data_analysis_start_time=None,
data_analysis_end_time=None,
):
"""Creates a monitoring schedule to monitor an Amazon SageMaker Endpoint.
If constraints and statistics are provided, or if they are able to be retrieved from a
previous baselining job associated with this monitor, those will be used.
If constraints and statistics cannot be automatically retrieved, baseline_inputs will be
required in order to kick off a baselining job.
Args:
endpoint_input (str or sagemaker.model_monitor.EndpointInput): The endpoint to monitor.
This can either be the endpoint name or an EndpointInput. (default: None)
output (sagemaker.model_monitor.MonitoringOutput): The output of the monitoring
schedule. (default: None)
statistics (sagemaker.model_monitor.Statistic or str): If provided alongside
constraints, these will be used for monitoring the endpoint. This can be a
sagemaker.model_monitor.Statistic object or an S3 uri pointing to a statistic
JSON file. (default: None)
constraints (sagemaker.model_monitor.Constraints or str): If provided alongside
statistics, these will be used for monitoring the endpoint. This can be a
sagemaker.model_monitor.Constraints object or an S3 uri pointing to a constraints
JSON file. (default: None)
monitor_schedule_name (str): Schedule name. If not specified, the processor generates
a default job name, based on the image name and current timestamp. (default: None)
schedule_cron_expression (str): The cron expression that dictates the frequency that
this job runs at. See sagemaker.model_monitor.CronExpressionGenerator for valid
expressions. Default: Daily. (default: None)
batch_transform_input (sagemaker.model_monitor.BatchTransformInput): Inputs to
run the monitoring schedule on the batch transform
(default: None)
arguments ([str]): A list of string arguments to be passed to a processing job.
data_analysis_start_time (str): Start time for the data analysis window
for the one time monitoring schedule (NOW), e.g. "-PT1H" (default: None)
data_analysis_end_time (str): End time for the data analysis window
for the one time monitoring schedule (NOW), e.g. "-PT1H" (default: None)
"""
if self.monitoring_schedule_name is not None:
message = (
"It seems that this object was already used to create an Amazon Model "
"Monitoring Schedule. To create another, first delete the existing one "
"using my_monitor.delete_monitoring_schedule()."
)
logger.warning(message)
raise ValueError(message)
if not output:
raise ValueError("output can not be None.")
if (batch_transform_input is not None) ^ (endpoint_input is None):
message = (
"Need to have either batch_transform_input or endpoint_input to create an "
"Amazon Model Monitoring Schedule. "
"Please provide only one of the above required inputs"
)
logger.error(message)
raise ValueError(message)
self._check_monitoring_schedule_cron_validity(
schedule_cron_expression=schedule_cron_expression,
data_analysis_start_time=data_analysis_start_time,
data_analysis_end_time=data_analysis_end_time,
)
self.monitoring_schedule_name = self._generate_monitoring_schedule_name(
schedule_name=monitor_schedule_name
)
if batch_transform_input is not None:
normalized_monitoring_input = batch_transform_input._to_request_dict()
else:
normalized_monitoring_input = self._normalize_endpoint_input(
endpoint_input=endpoint_input
)._to_request_dict()
normalized_monitoring_output = self._normalize_monitoring_output_fields(output=output)
statistics_object, constraints_object = self._get_baseline_files(
statistics=statistics, constraints=constraints, sagemaker_session=self.sagemaker_session
)
statistics_s3_uri = None
if statistics_object is not None:
statistics_s3_uri = statistics_object.file_s3_uri
constraints_s3_uri = None
if constraints_object is not None:
constraints_s3_uri = constraints_object.file_s3_uri
monitoring_output_config = {
"MonitoringOutputs": [normalized_monitoring_output._to_request_dict()]
}
if self.output_kms_key is not None:
monitoring_output_config["KmsKeyId"] = self.output_kms_key
self.monitoring_schedule_name = (
monitor_schedule_name
or self._generate_monitoring_schedule_name(schedule_name=monitor_schedule_name)
)
network_config_dict = None
if self.network_config is not None:
network_config_dict = self.network_config._to_request_dict()
if arguments is not None:
self.arguments = arguments
try:
self.sagemaker_session.create_monitoring_schedule(
monitoring_schedule_name=self.monitoring_schedule_name,
schedule_expression=schedule_cron_expression,
statistics_s3_uri=statistics_s3_uri,
constraints_s3_uri=constraints_s3_uri,
monitoring_inputs=[normalized_monitoring_input],
monitoring_output_config=monitoring_output_config,
instance_count=self.instance_count,
instance_type=self.instance_type,
volume_size_in_gb=self.volume_size_in_gb,
volume_kms_key=self.volume_kms_key,
image_uri=self.image_uri,
entrypoint=self.entrypoint,
arguments=self.arguments,
record_preprocessor_source_uri=None,
post_analytics_processor_source_uri=None,
max_runtime_in_seconds=self.max_runtime_in_seconds,
environment=self.env,
network_config=network_config_dict,
role_arn=self.sagemaker_session.expand_role(self.role),
tags=self.tags,
data_analysis_start_time=data_analysis_start_time,
data_analysis_end_time=data_analysis_end_time,
)
except Exception:
self.monitoring_schedule_name = None
raise
def update_monitoring_schedule(
self,
endpoint_input=None,
output=None,
statistics=None,
constraints=None,
schedule_cron_expression=None,
instance_count=None,
instance_type=None,
entrypoint=None,
volume_size_in_gb=None,
volume_kms_key=None,
output_kms_key=None,
arguments=None,
max_runtime_in_seconds=None,
env=None,
network_config=None,
role=None,
image_uri=None,
batch_transform_input=None,
data_analysis_start_time=None,
data_analysis_end_time=None,
):
"""Updates the existing monitoring schedule.
If more options than schedule_cron_expression are to be updated, a new job definition will
be created to hold them. The old job definition will not be deleted.
Args:
endpoint_input (str or sagemaker.model_monitor.EndpointInput): The endpoint to monitor.
This can either be the endpoint name or an EndpointInput.
output (sagemaker.model_monitor.MonitoringOutput): The output of the monitoring
schedule.
statistics (sagemaker.model_monitor.Statistic or str): If provided alongside
constraints, these will be used for monitoring the endpoint. This can be a
sagemaker.model_monitor.Statistics object or an S3 uri pointing to a statistics
JSON file.
constraints (sagemaker.model_monitor.Constraints or str): If provided alongside
statistics, these will be used for monitoring the endpoint. This can be a
sagemaker.model_monitor.Constraints object or an S3 uri pointing to a constraints
JSON file.
schedule_cron_expression (str): The cron expression that dictates the frequency that
this job runs at. See sagemaker.model_monitor.CronExpressionGenerator for valid
expressions.
instance_count (int): The number of instances to run
the jobs with.
instance_type (str): Type of EC2 instance to use for
the job, for example, 'ml.m5.xlarge'.
entrypoint (str): The entrypoint for the job.
volume_size_in_gb (int): Size in GB of the EBS volume
to use for storing data during processing (default: 30).
volume_kms_key (str): A KMS key for the job's volume.
output_kms_key (str): The KMS key id for the job's outputs.
arguments ([str]): A list of string arguments to be passed to a processing job.
max_runtime_in_seconds (int): Timeout in seconds. After this amount of
time, Amazon SageMaker terminates the job regardless of its current status.
Default: 3600
env (dict): Environment variables to be passed to the job.
network_config (sagemaker.network.NetworkConfig): A NetworkConfig
object that configures network isolation, encryption of
inter-container traffic, security group IDs, and subnets.
role (str): An AWS IAM role name or ARN. The Amazon SageMaker jobs use this role.
image_uri (str): The uri of the image to use for the jobs started by
the Monitor.
batch_transform_input (sagemaker.model_monitor.BatchTransformInput): Inputs to
run the monitoring schedule on the batch transform (default: None)
data_analysis_start_time (str): Start time for the data analysis window
for the one time monitoring schedule (NOW), e.g. "-PT1H" (default: None)
data_analysis_end_time (str): End time for the data analysis window
for the one time monitoring schedule (NOW), e.g. "-PT1H" (default: None)
"""
monitoring_inputs = None
if (batch_transform_input is not None) and (endpoint_input is not None):
message = (
"Cannot update both batch_transform_input and endpoint_input to update an "
"Amazon Model Monitoring Schedule. "
"Please provide atmost one of the above required inputs"
)
logger.error(message)
raise ValueError(message)
if endpoint_input is not None:
monitoring_inputs = [
self._normalize_endpoint_input(endpoint_input=endpoint_input)._to_request_dict()
]
elif batch_transform_input is not None:
monitoring_inputs = [batch_transform_input._to_request_dict()]
monitoring_output_config = None
if output is not None:
normalized_monitoring_output = self._normalize_monitoring_output_fields(output=output)
monitoring_output_config = {
"MonitoringOutputs": [normalized_monitoring_output._to_request_dict()]
}
statistics_object, constraints_object = self._get_baseline_files(
statistics=statistics, constraints=constraints, sagemaker_session=self.sagemaker_session
)
statistics_s3_uri = None
if statistics_object is not None:
statistics_s3_uri = statistics_object.file_s3_uri
constraints_s3_uri = None
if constraints_object is not None:
constraints_s3_uri = constraints_object.file_s3_uri
if instance_type is not None:
self.instance_type = instance_type
if instance_count is not None:
self.instance_count = instance_count
if entrypoint is not None:
self.entrypoint = entrypoint
if volume_size_in_gb is not None:
self.volume_size_in_gb = volume_size_in_gb
if volume_kms_key is not None:
self.volume_kms_key = volume_kms_key
if output_kms_key is not None:
self.output_kms_key = output_kms_key
monitoring_output_config["KmsKeyId"] = self.output_kms_key
if arguments is not None:
self.arguments = arguments
if max_runtime_in_seconds is not None:
self.max_runtime_in_seconds = max_runtime_in_seconds
if env is not None:
self.env = env
if network_config is not None:
self.network_config = network_config
if role is not None:
self.role = role
if image_uri is not None:
self.image_uri = image_uri
network_config_dict = None
if self.network_config is not None:
network_config_dict = self.network_config._to_request_dict()
# Do not need to check config because that check is done inside
# self.sagemaker_session.update_monitoring_schedule
self.sagemaker_session.update_monitoring_schedule(
monitoring_schedule_name=self.monitoring_schedule_name,
schedule_expression=schedule_cron_expression,
statistics_s3_uri=statistics_s3_uri,
constraints_s3_uri=constraints_s3_uri,
monitoring_inputs=monitoring_inputs,
monitoring_output_config=monitoring_output_config,
instance_count=instance_count,
instance_type=instance_type,
volume_size_in_gb=volume_size_in_gb,
volume_kms_key=volume_kms_key,
image_uri=image_uri,
entrypoint=entrypoint,
arguments=arguments,
max_runtime_in_seconds=max_runtime_in_seconds,
environment=env,
network_config=network_config_dict,
role_arn=self.sagemaker_session.expand_role(self.role),
data_analysis_start_time=data_analysis_start_time,
data_analysis_end_time=data_analysis_end_time,
)
self._wait_for_schedule_changes_to_apply()
def start_monitoring_schedule(self):
"""Starts the monitoring schedule."""
self.sagemaker_session.start_monitoring_schedule(
monitoring_schedule_name=self.monitoring_schedule_name
)
self._wait_for_schedule_changes_to_apply()
def stop_monitoring_schedule(self):
"""Stops the monitoring schedule."""
self.sagemaker_session.stop_monitoring_schedule(
monitoring_schedule_name=self.monitoring_schedule_name
)
self._wait_for_schedule_changes_to_apply()
def delete_monitoring_schedule(self):
"""Deletes the monitoring schedule (subclass is responsible for deleting job definition)"""
# DO NOT call super which erases schedule name and makes wait impossible.
self.sagemaker_session.delete_monitoring_schedule(
monitoring_schedule_name=self.monitoring_schedule_name
)
if self.job_definition_name is not None:
# Job definition is locked by schedule so need to wait for the schedule to be deleted
try:
self._wait_for_schedule_changes_to_apply()
except self.sagemaker_session.sagemaker_client.exceptions.ResourceNotFound:
# OK the schedule is gone
pass
self.monitoring_schedule_name = None
def baseline_statistics(self, file_name=STATISTICS_JSON_DEFAULT_FILE_NAME):
"""Returns a Statistics object representing the statistics json file
Object is generated by the latest baselining job.
Args:
file_name (str): The name of the .json statistics file
Returns:
sagemaker.model_monitor.Statistics: The Statistics object representing the file that
was generated by the job.
"""
return self.latest_baselining_job.baseline_statistics(
file_name=file_name, kms_key=self.output_kms_key
)
def suggested_constraints(self, file_name=CONSTRAINTS_JSON_DEFAULT_FILE_NAME):
"""Returns a Statistics object representing the constraints json file.
Object is generated by the latest baselining job
Args:
file_name (str): The name of the .json constraints file
Returns:
sagemaker.model_monitor.Constraints: The Constraints object representing the file that
was generated by the job.
"""
return self.latest_baselining_job.suggested_constraints(
file_name=file_name, kms_key=self.output_kms_key
)
def latest_monitoring_statistics(self, file_name=STATISTICS_JSON_DEFAULT_FILE_NAME):
"""Returns the sagemaker.model_monitor.
Statistics generated by the latest monitoring execution.
Args:
file_name (str): The name of the statistics file to be retrieved. Only override if
generating a custom file name.
Returns:
sagemaker.model_monitoring.Statistics: The Statistics object representing the file
generated by the latest monitoring execution.
"""
executions = self.list_executions()
if len(executions) == 0:
logger.warning(
"No executions found for schedule. monitoring_schedule_name: %s",
self.monitoring_schedule_name,
)
return None
latest_monitoring_execution = executions[-1]
return latest_monitoring_execution.statistics(file_name=file_name)
def latest_monitoring_constraint_violations(
self, file_name=CONSTRAINT_VIOLATIONS_JSON_DEFAULT_FILE_NAME
):
"""Returns the sagemaker.model_monitor.
ConstraintViolations generated by the latest monitoring execution.
Args:
file_name (str): The name of the constraint violdations file to be retrieved. Only
override if generating a custom file name.
Returns:
sagemaker.model_monitoring.ConstraintViolations: The ConstraintViolations object
representing the file generated by the latest monitoring execution.
"""
executions = self.list_executions()
if len(executions) == 0:
logger.warning(
"No executions found for schedule. monitoring_schedule_name: %s",
self.monitoring_schedule_name,
)
return None
latest_monitoring_execution = executions[-1]
return latest_monitoring_execution.constraint_violations(file_name=file_name)
def describe_latest_baselining_job(self):
"""Describe the latest baselining job kicked off by the suggest workflow."""
if self.latest_baselining_job is None:
raise ValueError("No suggestion jobs were kicked off.")
return self.latest_baselining_job.describe()
def describe_schedule(self):
"""Describes the schedule that this object represents.
Returns:
dict: A dictionary response with the monitoring schedule description.
"""
return self.sagemaker_session.describe_monitoring_schedule(
monitoring_schedule_name=self.monitoring_schedule_name
)
def list_executions(self):
"""Get the list of the latest monitoring executions in descending order of "ScheduledTime".
Statistics or violations can be called following this example:
Example:
>>> my_executions = my_monitor.list_executions()
>>> second_to_last_execution_statistics = my_executions[-1].statistics()
>>> second_to_last_execution_violations = my_executions[-1].constraint_violations()
Returns:
[sagemaker.model_monitor.MonitoringExecution]: List of MonitoringExecutions in
descending order of "ScheduledTime".
"""
monitoring_executions_dict = self.sagemaker_session.list_monitoring_executions(
monitoring_schedule_name=self.monitoring_schedule_name
)
if len(monitoring_executions_dict["MonitoringExecutionSummaries"]) == 0:
logger.warning(
"No executions found for schedule. monitoring_schedule_name: %s",
self.monitoring_schedule_name,
)
return []
processing_job_arns = [
execution_dict["ProcessingJobArn"]
for execution_dict in monitoring_executions_dict["MonitoringExecutionSummaries"]
if execution_dict.get("ProcessingJobArn") is not None
]
monitoring_executions = [
MonitoringExecution.from_processing_arn(
sagemaker_session=self.sagemaker_session, processing_job_arn=processing_job_arn
)
for processing_job_arn in processing_job_arns
]
monitoring_executions.reverse()
return monitoring_executions
def get_latest_execution_logs(self, wait=False):
"""Get the processing job logs for the most recent monitoring execution
Args:
wait (bool): Whether the call should wait until the job completes (default: False).
Raises:
ValueError: If no execution job or processing job for the last execution has run
Returns: None
"""
monitoring_executions = self.sagemaker_session.list_monitoring_executions(
monitoring_schedule_name=self.monitoring_schedule_name
)
if len(monitoring_executions["MonitoringExecutionSummaries"]) == 0:
raise ValueError("No execution jobs were kicked off.")
if "ProcessingJobArn" not in monitoring_executions["MonitoringExecutionSummaries"][0]:
raise ValueError("Processing Job did not run for the last execution")
job_arn = monitoring_executions["MonitoringExecutionSummaries"][0]["ProcessingJobArn"]
self.sagemaker_session.logs_for_processing_job(
job_name=get_resource_name_from_arn(job_arn), wait=wait
)
def update_monitoring_alert(
self,
monitoring_alert_name: str,
data_points_to_alert: Optional[int],
evaluation_period: Optional[int],
):
"""Update the monitoring schedule alert.
Args:
monitoring_alert_name (str): The name of the monitoring alert to update.
data_points_to_alert (int): The data point to alert.
evaluation_period (int): The period to evaluate the alert status.
Returns: None
"""
if self.monitoring_schedule_name is None:
message = "Nothing to update, please create a schedule first."
logger.error(message)
raise ValueError(message)
if not data_points_to_alert and not evaluation_period:
raise ValueError("Got no alert property to update.")
self.sagemaker_session.update_monitoring_alert(
monitoring_schedule_name=self.monitoring_schedule_name,
monitoring_alert_name=monitoring_alert_name,
data_points_to_alert=data_points_to_alert,
evaluation_period=evaluation_period,
)
def list_monitoring_alerts(
self, next_token: Optional[str] = None, max_results: Optional[int] = 10
):
"""List the monitoring alerts.
Args:
next_token (Optional[str]): The pagination token. Default: None
max_results (Optional[int]): The maximum number of results to return.
Must be between 1 and 100. Default: 10
Returns:
List[MonitoringAlertSummary]: list of monitoring alert history.
str: Next token.
"""
if self.monitoring_schedule_name is None:
message = "No alert to list, please create a schedule first."
logger.warning(message)
return [], None
monitoring_alert_dict: Dict = self.sagemaker_session.list_monitoring_alerts(
monitoring_schedule_name=self.monitoring_schedule_name,
next_token=next_token,
max_results=max_results,
)
monitoring_alerts: List[MonitoringAlertSummary] = []
for monitoring_alert in monitoring_alert_dict["MonitoringAlertSummaries"]:
monitoring_alerts.append(
MonitoringAlertSummary(
alert_name=monitoring_alert["MonitoringAlertName"],
creation_time=monitoring_alert["CreationTime"],
last_modified_time=monitoring_alert["LastModifiedTime"],
alert_status=monitoring_alert["AlertStatus"],
data_points_to_alert=monitoring_alert["DatapointsToAlert"],
evaluation_period=monitoring_alert["EvaluationPeriod"],
actions=MonitoringAlertActions(
model_dashboard_indicator=ModelDashboardIndicatorAction(
enabled=monitoring_alert["Actions"]["ModelDashboardIndicator"][
"Enabled"
],
)
),
)
)
next_token = (
monitoring_alert_dict["NextToken"] if "NextToken" in monitoring_alert_dict else None
)
return monitoring_alerts, next_token
def list_monitoring_alert_history(
self,
monitoring_alert_name: Optional[str] = None,
sort_by: Optional[str] = "CreationTime",
sort_order: Optional[str] = "Descending",
next_token: Optional[str] = None,
max_results: Optional[int] = 10,
creation_time_before: Optional[str] = None,
creation_time_after: Optional[str] = None,
status_equals: Optional[str] = None,
):
"""Lists the alert history associated with the given schedule_name and alert_name.
Args:
monitoring_alert_name (Optional[str]): The name of the alert_name to filter on.
If not provided, does not filter on it. Default: None.
sort_by (Optional[str]): sort_by (str): The field to sort by.
Can be one of: "Name", "CreationTime"
Default: "CreationTime".
sort_order (Optional[str]): The sort order. Can be one of: "Ascending", "Descending".
Default: "Descending".
next_token (Optional[str]): The pagination token. Default: None.
max_results (Optional[int]): The maximum number of results to return.
Must be between 1 and 100. Default: 10.
creation_time_before (Optional[str]): A filter to filter alert history before a time
Default: None.
creation_time_after (Optional[str]): A filter to filter alert history after a time
Default: None.
status_equals (Optional[str]): A filter to filter alert history by status
Default: None.
Returns:
List[MonitoringAlertHistorySummary]: list of monitoring alert history.
str: Next token.
"""
if self.monitoring_schedule_name is None:
message = "No alert history to list, please create a schedule first."
logger.warning(message)
return [], None
monitoring_alert_history_dict: Dict = self.sagemaker_session.list_monitoring_alert_history(
monitoring_schedule_name=self.monitoring_schedule_name,
monitoring_alert_name=monitoring_alert_name,
sort_by=sort_by,
sort_order=sort_order,
next_token=next_token,
max_results=max_results,
status_equals=status_equals,
creation_time_before=creation_time_before,
creation_time_after=creation_time_after,
)
monitoring_alert_history: List[MonitoringAlertHistorySummary] = []
for monitoring_alert_history_summary in monitoring_alert_history_dict[
"MonitoringAlertHistory"
]:
monitoring_alert_history.append(
MonitoringAlertHistorySummary(
alert_name=monitoring_alert_history_summary["MonitoringAlertName"],
creation_time=monitoring_alert_history_summary["CreationTime"],
alert_status=monitoring_alert_history_summary["AlertStatus"],
)
)
next_token = (
monitoring_alert_history_dict["NextToken"]
if "NextToken" in monitoring_alert_history_dict
else None
)
return monitoring_alert_history, next_token
@classmethod
def attach(cls, monitor_schedule_name, sagemaker_session=None):
"""Set this object's schedule name point to the Amazon Sagemaker Monitoring Schedule name.
This allows subsequent describe_schedule or list_executions calls to point
to the given schedule.
Args:
monitor_schedule_name (str): The name of the schedule to attach to.
sagemaker_session (sagemaker.session.Session): Session object which
manages interactions with Amazon SageMaker APIs and any other
AWS services needed. If not specified, one is created using
the default AWS configuration chain.
"""
sagemaker_session = sagemaker_session or Session()
schedule_desc = sagemaker_session.describe_monitoring_schedule(
monitoring_schedule_name=monitor_schedule_name
)
monitoring_job_definition = schedule_desc["MonitoringScheduleConfig"][
"MonitoringJobDefinition"
]
role = monitoring_job_definition["RoleArn"]
image_uri = monitoring_job_definition["MonitoringAppSpecification"].get("ImageUri")
cluster_config = monitoring_job_definition["MonitoringResources"]["ClusterConfig"]
instance_count = cluster_config.get("InstanceCount")
instance_type = cluster_config["InstanceType"]
volume_size_in_gb = cluster_config["VolumeSizeInGB"]
volume_kms_key = cluster_config.get("VolumeKmsKeyId")
entrypoint = monitoring_job_definition["MonitoringAppSpecification"].get(