forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclarify.py
More file actions
2048 lines (1899 loc) · 99.7 KB
/
clarify.py
File metadata and controls
2048 lines (1899 loc) · 99.7 KB
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 configures the SageMaker Clarify bias and model explainability processor jobs.
SageMaker Clarify
==================
"""
from __future__ import absolute_import, print_function
import copy
import json
import logging
import os
import re
import tempfile
from abc import ABC, abstractmethod
from typing import List, Union, Dict, Optional, Any
from schema import Schema, And, Use, Or, Optional as SchemaOptional, Regex
from sagemaker import image_uris, s3, utils
from sagemaker.session import Session
from sagemaker.network import NetworkConfig
from sagemaker.processing import ProcessingInput, ProcessingOutput, Processor
logger = logging.getLogger(__name__)
ENDPOINT_NAME_PREFIX_PATTERN = "^[a-zA-Z0-9](-*[a-zA-Z0-9])"
ANALYSIS_CONFIG_SCHEMA_V1_0 = Schema(
{
SchemaOptional("version"): str,
"dataset_type": And(
str,
Use(str.lower),
lambda s: s
in (
"text/csv",
"application/jsonlines",
"application/sagemakercapturejson",
"application/x-parquet",
"application/x-image",
),
),
SchemaOptional("dataset_uri"): str,
SchemaOptional("headers"): [str],
SchemaOptional("label"): Or(str, int),
# this field indicates user provides predicted_label in dataset
SchemaOptional("predicted_label"): Or(str, int),
SchemaOptional("features"): str,
SchemaOptional("label_values_or_threshold"): [Or(int, float, str)],
SchemaOptional("probability_threshold"): float,
SchemaOptional("facet"): [
{
"name_or_index": Or(str, int),
SchemaOptional("value_or_threshold"): [Or(int, float, str)],
}
],
SchemaOptional("facet_dataset_uri"): str,
SchemaOptional("facet_headers"): [str],
SchemaOptional("predicted_label_dataset_uri"): str,
SchemaOptional("predicted_label_headers"): [str],
SchemaOptional("excluded_columns"): [Or(int, str)],
SchemaOptional("joinsource_name_or_index"): Or(str, int),
SchemaOptional("group_variable"): Or(str, int),
"methods": {
SchemaOptional("shap"): {
SchemaOptional("baseline"): Or(
# URI of the baseline data file
str,
# Inplace baseline data (a list of something)
[
Or(
# CSV row
[Or(int, float, str, None)],
# JSON row (any JSON object). As I write this only
# SageMaker JSONLines Dense Format ([1])
# is supported and the validation is NOT done
# by the schema but by the data loader.
# [1] https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html#cm-jsonlines
{object: object},
)
],
),
SchemaOptional("num_clusters"): int,
SchemaOptional("use_logit"): bool,
SchemaOptional("num_samples"): int,
SchemaOptional("agg_method"): And(
str, Use(str.lower), lambda s: s in ("mean_abs", "median", "mean_sq")
),
SchemaOptional("save_local_shap_values"): bool,
SchemaOptional("text_config"): {
"granularity": And(
str, Use(str.lower), lambda s: s in ("token", "sentence", "paragraph")
),
"language": And(
str,
Use(str.lower),
lambda s: s
in (
"chinese",
"zh",
"danish",
"da",
"dutch",
"nl",
"english",
"en",
"french",
"fr",
"german",
"de",
"greek",
"el",
"italian",
"it",
"japanese",
"ja",
"lithuanian",
"lt",
"multi-language",
"xx",
"norwegian bokmål",
"nb",
"polish",
"pl",
"portuguese",
"pt",
"romanian",
"ro",
"russian",
"ru",
"spanish",
"es",
"afrikaans",
"af",
"albanian",
"sq",
"arabic",
"ar",
"armenian",
"hy",
"basque",
"eu",
"bengali",
"bn",
"bulgarian",
"bg",
"catalan",
"ca",
"croatian",
"hr",
"czech",
"cs",
"estonian",
"et",
"finnish",
"fi",
"gujarati",
"gu",
"hebrew",
"he",
"hindi",
"hi",
"hungarian",
"hu",
"icelandic",
"is",
"indonesian",
"id",
"irish",
"ga",
"kannada",
"kn",
"kyrgyz",
"ky",
"latvian",
"lv",
"ligurian",
"lij",
"luxembourgish",
"lb",
"macedonian",
"mk",
"malayalam",
"ml",
"marathi",
"mr",
"nepali",
"ne",
"persian",
"fa",
"sanskrit",
"sa",
"serbian",
"sr",
"setswana",
"tn",
"sinhala",
"si",
"slovak",
"sk",
"slovenian",
"sl",
"swedish",
"sv",
"tagalog",
"tl",
"tamil",
"ta",
"tatar",
"tt",
"telugu",
"te",
"thai",
"th",
"turkish",
"tr",
"ukrainian",
"uk",
"urdu",
"ur",
"vietnamese",
"vi",
"yoruba",
"yo",
),
),
SchemaOptional("max_top_tokens"): int,
},
SchemaOptional("image_config"): {
SchemaOptional("num_segments"): int,
SchemaOptional("segment_compactness"): int,
SchemaOptional("feature_extraction_method"): str,
SchemaOptional("model_type"): str,
SchemaOptional("max_objects"): int,
SchemaOptional("iou_threshold"): float,
SchemaOptional("context"): float,
SchemaOptional("debug"): {
SchemaOptional("image_names"): [str],
SchemaOptional("class_ids"): [int],
SchemaOptional("sample_from"): int,
SchemaOptional("sample_to"): int,
},
},
SchemaOptional("seed"): int,
},
SchemaOptional("pre_training_bias"): {"methods": Or(str, [str])},
SchemaOptional("post_training_bias"): {"methods": Or(str, [str])},
SchemaOptional("pdp"): {
"grid_resolution": int,
SchemaOptional("features"): [Or(str, int)],
SchemaOptional("top_k_features"): int,
},
SchemaOptional("report"): {"name": str, SchemaOptional("title"): str},
},
SchemaOptional("predictor"): {
SchemaOptional("endpoint_name"): str,
SchemaOptional("endpoint_name_prefix"): And(str, Regex(ENDPOINT_NAME_PREFIX_PATTERN)),
SchemaOptional("model_name"): str,
SchemaOptional("target_model"): str,
SchemaOptional("instance_type"): str,
SchemaOptional("initial_instance_count"): int,
SchemaOptional("accelerator_type"): str,
SchemaOptional("content_type"): And(
str,
Use(str.lower),
lambda s: s
in (
"text/csv",
"application/jsonlines",
"image/jpeg",
"image/jpg",
"image/png",
"application/x-npy",
),
),
SchemaOptional("accept_type"): And(
str,
Use(str.lower),
lambda s: s in ("text/csv", "application/jsonlines", "application/json"),
),
SchemaOptional("label"): Or(str, int),
SchemaOptional("probability"): Or(str, int),
SchemaOptional("label_headers"): [Or(str, int)],
SchemaOptional("content_template"): Or(str, {str: str}),
SchemaOptional("custom_attributes"): str,
},
}
)
class DataConfig:
"""Config object related to configurations of the input and output dataset."""
def __init__(
self,
s3_data_input_path: str,
s3_output_path: str,
s3_analysis_config_output_path: Optional[str] = None,
label: Optional[str] = None,
headers: Optional[List[str]] = None,
features: Optional[List[str]] = None,
dataset_type: str = "text/csv",
s3_compression_type: str = "None",
joinsource: Optional[Union[str, int]] = None,
facet_dataset_uri: Optional[str] = None,
facet_headers: Optional[List[str]] = None,
predicted_label_dataset_uri: Optional[str] = None,
predicted_label_headers: Optional[List[str]] = None,
predicted_label: Optional[Union[str, int]] = None,
excluded_columns: Optional[Union[List[int], List[str]]] = None,
):
"""Initializes a configuration of both input and output datasets.
Args:
s3_data_input_path (str): Dataset S3 prefix/object URI.
s3_output_path (str): S3 prefix to store the output.
s3_analysis_config_output_path (str): S3 prefix to store the analysis config output.
If this field is None, then the ``s3_output_path`` will be used
to store the ``analysis_config`` output.
label (str): Target attribute of the model required by bias metrics.
Specified as column name or index for CSV dataset or as JSONPath for JSONLines.
*Required parameter* except for when the input dataset does not contain the label.
features (List[str]): JSONPath for locating the feature columns for bias metrics if the
dataset format is JSONLines.
dataset_type (str): Format of the dataset. Valid values are ``"text/csv"`` for CSV,
``"application/jsonlines"`` for JSONLines, and
``"application/x-parquet"`` for Parquet.
s3_compression_type (str): Valid options are "None" or ``"Gzip"``.
joinsource (str or int): The name or index of the column in the dataset that
acts as an identifier column (for instance, while performing a join).
This column is only used as an identifier, and not used for any other computations.
This is an optional field in all cases except:
* The dataset contains more than one file and `save_local_shap_values`
is set to true in :class:`~sagemaker.clarify.ShapConfig`, and/or
* When the dataset and/or facet dataset and/or predicted label dataset
are in separate files.
facet_dataset_uri (str): Dataset S3 prefix/object URI that contains facet attribute(s),
used for bias analysis on datasets without facets.
* If the dataset and the facet dataset are one single file each, then
the original dataset and facet dataset must have the same number of rows.
* If the dataset and facet dataset are in multiple files (either one), then
an index column, ``joinsource``, is required to join the two datasets.
Clarify will not use the ``joinsource`` column and columns present in the facet
dataset when calling model inference APIs.
facet_headers (list[str]): List of column names in the facet dataset.
predicted_label_dataset_uri (str): Dataset S3 prefix/object URI with predicted labels,
which are used directly for analysis instead of making model inference API calls.
* If the dataset and the predicted label dataset are one single file each, then the
original dataset and predicted label dataset must have the same number of rows.
* If the dataset and predicted label dataset are in multiple files (either one),
then an index column, ``joinsource``, is required to join the two datasets.
predicted_label_headers (list[str]): List of column names in the predicted label dataset
predicted_label (str or int): Predicted label of the target attribute of the model
required for running bias analysis. Specified as column name or index for CSV data.
Clarify uses the predicted labels directly instead of making model inference API
calls.
excluded_columns (list[int] or list[str]): A list of names or indices of the columns
which are to be excluded from making model inference API calls.
Raises:
ValueError: when the ``dataset_type`` is invalid, predicted label dataset parameters
are used with un-supported ``dataset_type``, or facet dataset parameters
are used with un-supported ``dataset_type``
"""
if dataset_type not in [
"text/csv",
"application/jsonlines",
"application/x-parquet",
"application/x-image",
]:
raise ValueError(
f"Invalid dataset_type '{dataset_type}'."
f" Please check the API documentation for the supported dataset types."
)
# parameters for analysis on datasets without facets are only supported for CSV datasets
if dataset_type != "text/csv":
if predicted_label:
raise ValueError(
f"The parameter 'predicted_label' is not supported"
f" for dataset_type '{dataset_type}'."
f" Please check the API documentation for the supported dataset types."
)
if excluded_columns:
raise ValueError(
f"The parameter 'excluded_columns' is not supported"
f" for dataset_type '{dataset_type}'."
f" Please check the API documentation for the supported dataset types."
)
if facet_dataset_uri or facet_headers:
raise ValueError(
f"The parameters 'facet_dataset_uri' and 'facet_headers'"
f" are not supported for dataset_type '{dataset_type}'."
f" Please check the API documentation for the supported dataset types."
)
if predicted_label_dataset_uri or predicted_label_headers:
raise ValueError(
f"The parameters 'predicted_label_dataset_uri' and 'predicted_label_headers'"
f" are not supported for dataset_type '{dataset_type}'."
f" Please check the API documentation for the supported dataset types."
)
self.s3_data_input_path = s3_data_input_path
self.s3_output_path = s3_output_path
self.s3_analysis_config_output_path = s3_analysis_config_output_path
self.s3_data_distribution_type = "FullyReplicated"
self.s3_compression_type = s3_compression_type
self.label = label
self.headers = headers
self.features = features
self.facet_dataset_uri = facet_dataset_uri
self.facet_headers = facet_headers
self.predicted_label_dataset_uri = predicted_label_dataset_uri
self.predicted_label_headers = predicted_label_headers
self.predicted_label = predicted_label
self.excluded_columns = excluded_columns
self.analysis_config = {
"dataset_type": dataset_type,
}
_set(features, "features", self.analysis_config)
_set(headers, "headers", self.analysis_config)
_set(label, "label", self.analysis_config)
_set(joinsource, "joinsource_name_or_index", self.analysis_config)
_set(facet_dataset_uri, "facet_dataset_uri", self.analysis_config)
_set(facet_headers, "facet_headers", self.analysis_config)
_set(
predicted_label_dataset_uri,
"predicted_label_dataset_uri",
self.analysis_config,
)
_set(predicted_label_headers, "predicted_label_headers", self.analysis_config)
_set(predicted_label, "predicted_label", self.analysis_config)
_set(excluded_columns, "excluded_columns", self.analysis_config)
def get_config(self):
"""Returns part of an analysis config dictionary."""
return copy.deepcopy(self.analysis_config)
class BiasConfig:
"""Config object with user-defined bias configurations of the input dataset."""
def __init__(
self,
label_values_or_threshold: Union[int, float, str],
facet_name: Union[str, int, List[str], List[int]],
facet_values_or_threshold: Optional[Union[int, float, str]] = None,
group_name: Optional[str] = None,
):
"""Initializes a configuration of the sensitive groups in the dataset.
Args:
label_values_or_threshold ([int or float or str]): List of label value(s) or threshold
to indicate positive outcome used for bias metrics.
The appropriate threshold depends on the problem type:
* Binary: The list has one positive value.
* Categorical:The list has one or more (but not all) categories
which are the positive values.
* Regression: The list should include one threshold that defines the **exclusive**
lower bound of positive values.
facet_name (str or int or list[str] or list[int]): Sensitive attribute column name
(or index in the input data) to use when computing bias metrics. It can also be a
list of names (or indexes) for computing metrics for multiple sensitive attributes.
facet_values_or_threshold ([int or float or str] or [[int or float or str]]):
The parameter controls the values of the sensitive group.
If ``facet_name`` is a scalar, then it can be None or a list.
Depending on the data type of the facet column, the values mean:
* Binary data: None means computing the bias metrics for each binary value.
Or add one binary value to the list, to compute its bias metrics only.
* Categorical data: None means computing the bias metrics for each category. Or add
one or more (but not all) categories to the list, to compute their
bias metrics v.s. the other categories.
* Continuous data: The list should include one and only one threshold which defines
the **exclusive** lower bound of a sensitive group.
If ``facet_name`` is a list, then ``facet_values_or_threshold`` can be None
if all facets are of binary or categorical type.
Otherwise, ``facet_values_or_threshold`` should be a list, and each element
is the value or threshold of the corresponding facet.
group_name (str): Optional column name or index to indicate a group column to be used
for the bias metric
`Conditional Demographic Disparity in Labels `(CDDL) <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-data-bias-metric-cddl.html>`_
or
`Conditional Demographic Disparity in Predicted Labels (CDDPL) <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-post-training-bias-metric-cddpl.html>`_.
Raises:
ValueError: If the number of ``facet_names`` doesn't equal number of ``facet values``
""" # noqa E501 # pylint: disable=c0301
if isinstance(facet_name, list):
assert len(facet_name) > 0, "Please provide at least one facet"
if facet_values_or_threshold is None:
facet_list = [
{"name_or_index": single_facet_name} for single_facet_name in facet_name
]
elif len(facet_values_or_threshold) == len(facet_name):
facet_list = []
for i, single_facet_name in enumerate(facet_name):
facet = {"name_or_index": single_facet_name}
if facet_values_or_threshold is not None:
_set(facet_values_or_threshold[i], "value_or_threshold", facet)
facet_list.append(facet)
else:
raise ValueError(
"The number of facet names doesn't match the number of facet values"
)
else:
facet = {"name_or_index": facet_name}
_set(facet_values_or_threshold, "value_or_threshold", facet)
facet_list = [facet]
self.analysis_config = {
"label_values_or_threshold": label_values_or_threshold,
"facet": facet_list,
}
_set(group_name, "group_variable", self.analysis_config)
def get_config(self):
"""Returns a dictionary of bias detection configurations, part of the analysis config"""
return copy.deepcopy(self.analysis_config)
class ModelConfig:
"""Config object related to a model and its endpoint to be created."""
def __init__(
self,
model_name: Optional[str] = None,
instance_count: Optional[int] = None,
instance_type: Optional[str] = None,
accept_type: Optional[str] = None,
content_type: Optional[str] = None,
content_template: Optional[str] = None,
custom_attributes: Optional[str] = None,
accelerator_type: Optional[str] = None,
endpoint_name_prefix: Optional[str] = None,
target_model: Optional[str] = None,
endpoint_name: Optional[str] = None,
):
r"""Initializes a configuration of a model and the endpoint to be created for it.
Args:
model_name (str): Model name (as created by
`CreateModel <https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html>`_.
Cannot be set when ``endpoint_name`` is set.
Must be set with ``instance_count``, ``instance_type``
instance_count (int): The number of instances of a new endpoint for model inference.
Cannot be set when ``endpoint_name`` is set.
Must be set with ``model_name``, ``instance_type``
instance_type (str): The type of
`EC2 instance <https://aws.amazon.com/ec2/instance-types/>`_
to use for model inference; for example, ``"ml.c5.xlarge"``.
Cannot be set when ``endpoint_name`` is set.
Must be set with ``instance_count``, ``model_name``
accept_type (str): The model output format to be used for getting inferences with the
shadow endpoint. Valid values are ``"text/csv"`` for CSV and
``"application/jsonlines"``. Default is the same as ``content_type``.
content_type (str): The model input format to be used for getting inferences with the
shadow endpoint. Valid values are ``"text/csv"`` for CSV and
``"application/jsonlines"``. Default is the same as ``dataset_format``.
content_template (str): A template string to be used to construct the model input from
dataset instances. It is only used when ``model_content_type`` is
``"application/jsonlines"``. The template should have one and only one placeholder,
``"features"``, which will be replaced by a features list to form the model
inference input.
custom_attributes (str): Provides additional information about a request for an
inference submitted to a model hosted at an Amazon SageMaker endpoint. The
information is an opaque value that is forwarded verbatim. You could use this
value, for example, to provide an ID that you can use to track a request or to
provide other metadata that a service endpoint was programmed to process. The value
must consist of no more than 1024 visible US-ASCII characters as specified in
Section 3.3.6.
`Field Value Components <https://tools.ietf.org/html/rfc7230#section-3.2.6>`_
of the Hypertext Transfer Protocol (HTTP/1.1).
accelerator_type (str): SageMaker
`Elastic Inference <https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html>`_
accelerator type to deploy to the model endpoint instance
for making inferences to the model.
endpoint_name_prefix (str): The endpoint name prefix of a new endpoint. Must follow
pattern ``^[a-zA-Z0-9](-\*[a-zA-Z0-9]``.
target_model (str): Sets the target model name when using a multi-model endpoint. For
more information about multi-model endpoints, see
https://docs.aws.amazon.com/sagemaker/latest/dg/multi-model-endpoints.html
endpoint_name (str): Sets the endpoint_name when re-uses an existing endpoint.
Cannot be set when ``model_name``, ``instance_count``,
and ``instance_type`` set
Raises:
ValueError: when the
- ``endpoint_name_prefix`` is invalid,
- ``accept_type`` is invalid,
- ``content_type`` is invalid,
- ``content_template`` has no placeholder "features"
- both [``endpoint_name``]
AND [``model_name``, ``instance_count``, ``instance_type``] are set
- both [``endpoint_name``] AND [``endpoint_name_prefix``] are set
"""
# validation
_model_endpoint_config_rule = (
all([model_name, instance_count, instance_type]),
all([endpoint_name]),
)
assert any(_model_endpoint_config_rule) and not all(_model_endpoint_config_rule)
if endpoint_name:
assert not endpoint_name_prefix
# main init logic
self.predictor_config = (
{
"model_name": model_name,
"instance_type": instance_type,
"initial_instance_count": instance_count,
}
if not endpoint_name
else {"endpoint_name": endpoint_name}
)
if endpoint_name_prefix:
if re.search("^[a-zA-Z0-9](-*[a-zA-Z0-9])", endpoint_name_prefix) is None:
raise ValueError(
"Invalid endpoint_name_prefix."
" Please follow pattern ^[a-zA-Z0-9](-*[a-zA-Z0-9])."
)
self.predictor_config["endpoint_name_prefix"] = endpoint_name_prefix
if accept_type is not None:
if accept_type not in ["text/csv", "application/jsonlines"]:
raise ValueError(
f"Invalid accept_type {accept_type}."
f" Please choose text/csv or application/jsonlines."
)
self.predictor_config["accept_type"] = accept_type
if content_type is not None:
if content_type not in [
"text/csv",
"application/jsonlines",
"image/jpeg",
"image/jpg",
"image/png",
"application/x-npy",
]:
raise ValueError(
f"Invalid content_type {content_type}."
f" Please choose text/csv or application/jsonlines."
)
self.predictor_config["content_type"] = content_type
if content_template is not None:
if "$features" not in content_template:
raise ValueError(
f"Invalid content_template {content_template}."
f" Please include a placeholder $features."
)
self.predictor_config["content_template"] = content_template
_set(custom_attributes, "custom_attributes", self.predictor_config)
_set(accelerator_type, "accelerator_type", self.predictor_config)
_set(target_model, "target_model", self.predictor_config)
def get_predictor_config(self):
"""Returns part of the predictor dictionary of the analysis config."""
return copy.deepcopy(self.predictor_config)
class ModelPredictedLabelConfig:
"""Config object to extract a predicted label from the model output."""
def __init__(
self,
label: Optional[Union[str, int]] = None,
probability: Optional[Union[str, int]] = None,
probability_threshold: Optional[float] = None,
label_headers: Optional[List[str]] = None,
):
"""Initializes a model output config to extract the predicted label or predicted score(s).
The following examples show different parameter configurations depending on the endpoint:
* **Regression task:**
The model returns the score, e.g. ``1.2``. We don't need to specify
anything. For json output, e.g. ``{'score': 1.2}``, we can set ``label='score'``.
* **Binary classification:**
* The model returns a single probability score. We want to classify as ``"yes"``
predictions with a probability score over ``0.2``.
We can set ``probability_threshold=0.2`` and ``label_headers="yes"``.
* The model returns ``{"probability": 0.3}``, for which we would like to apply a
threshold of ``0.5`` to obtain a predicted label in ``{0, 1}``.
In this case we can set ``label="probability"``.
* The model returns a tuple of the predicted label and the probability.
In this case we can set ``label = 0``.
* **Multiclass classification:**
* The model returns ``{'labels': ['cat', 'dog', 'fish'],
'probabilities': [0.35, 0.25, 0.4]}``. In this case we would set
``probability='probabilities'``, ``label='labels'``,
and infer the predicted label to be ``'fish'``.
* The model returns ``{'predicted_label': 'fish', 'probabilities': [0.35, 0.25, 0.4]}``.
In this case we would set the ``label='predicted_label'``.
* The model returns ``[0.35, 0.25, 0.4]``. In this case, we can set
``label_headers=['cat','dog','fish']`` and infer the predicted label to be ``'fish'``.
Args:
label (str or int): Index or JSONPath location in the model output for the prediction.
In case, this is a predicted label of the same type as the label in the dataset,
no further arguments need to be specified.
probability (str or int): Index or JSONPath location in the model output
for the predicted score(s).
probability_threshold (float): An optional value for binary prediction tasks in which
the model returns a probability, to indicate the threshold to convert the
prediction to a boolean value. Default is ``0.5``.
label_headers (list[str]): List of headers, each for a predicted score in model output.
For bias analysis, it is used to extract the label value with the highest score as
predicted label. For explainability jobs, it is used to beautify the analysis report
by replacing placeholders like ``'label0'``.
Raises:
TypeError: when the ``probability_threshold`` cannot be cast to a float
"""
self.label = label
self.probability = probability
self.probability_threshold = probability_threshold
self.label_headers = label_headers
if probability_threshold is not None:
try:
float(probability_threshold)
except ValueError:
raise TypeError(
f"Invalid probability_threshold {probability_threshold}. "
f"Please choose one that can be cast to float."
)
self.predictor_config = {}
_set(label, "label", self.predictor_config)
_set(probability, "probability", self.predictor_config)
_set(label_headers, "label_headers", self.predictor_config)
def get_predictor_config(self):
"""Returns ``probability_threshold`` and predictor config dictionary."""
return self.probability_threshold, copy.deepcopy(self.predictor_config)
class ExplainabilityConfig(ABC):
"""Abstract config class to configure an explainability method."""
@abstractmethod
def get_explainability_config(self):
"""Returns config."""
return None
class PDPConfig(ExplainabilityConfig):
"""Config class for Partial Dependence Plots (PDP).
`PDPs <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-partial-dependence-plots.html>`_
show the marginal effect (the dependence) a subset of features has on the predicted
outcome of an ML model.
When PDP is requested (by passing in a :class:`~sagemaker.clarify.PDPConfig` to the
``explainability_config`` parameter of :class:`~sagemaker.clarify.SageMakerClarifyProcessor`),
the Partial Dependence Plots are included in the output
`report <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-feature-attribute-baselines-reports.html>`__
and the corresponding values are included in the analysis output.
""" # noqa E501
def __init__(
self, features: Optional[List] = None, grid_resolution: int = 15, top_k_features: int = 10
):
"""Initializes PDP config.
Args:
features (None or list): List of feature names or indices for which partial dependence
plots are computed and plotted. When :class:`~sagemaker.clarify.ShapConfig`
is provided, this parameter is optional, as Clarify will compute the
partial dependence plots for top features based on
`SHAP <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-shapley-values.html>`__
attributions. When :class:`~sagemaker.clarify.ShapConfig` is not provided,
``features`` must be provided.
grid_resolution (int): When using numerical features, this integer represents the
number of buckets that the range of values must be divided into. This decides the
granularity of the grid in which the PDP are plotted.
top_k_features (int): Sets the number of top SHAP attributes used to compute
partial dependence plots.
""" # noqa E501
self.pdp_config = {
"grid_resolution": grid_resolution,
"top_k_features": top_k_features,
}
if features is not None:
self.pdp_config["features"] = features
def get_explainability_config(self):
"""Returns PDP config dictionary."""
return copy.deepcopy({"pdp": self.pdp_config})
class TextConfig:
"""Config object to handle text features for text explainability
`SHAP analysis <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-explainability.html>`__
breaks down longer text into chunks (e.g. tokens, sentences, or paragraphs)
and replaces them with the strings specified in the baseline for that feature.
The `shap value <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-shapley-values.html>`_
of a chunk then captures how much replacing it affects the prediction.
""" # noqa E501 # pylint: disable=c0301
_SUPPORTED_GRANULARITIES = ["token", "sentence", "paragraph"]
_SUPPORTED_LANGUAGES = [
"chinese",
"zh",
"danish",
"da",
"dutch",
"nl",
"english",
"en",
"french",
"fr",
"german",
"de",
"greek",
"el",
"italian",
"it",
"japanese",
"ja",
"lithuanian",
"lt",
"multi-language",
"xx",
"norwegian bokmål",
"nb",
"polish",
"pl",
"portuguese",
"pt",
"romanian",
"ro",
"russian",
"ru",
"spanish",
"es",
"afrikaans",
"af",
"albanian",
"sq",
"arabic",
"ar",
"armenian",
"hy",
"basque",
"eu",
"bengali",
"bn",
"bulgarian",
"bg",
"catalan",
"ca",
"croatian",
"hr",
"czech",
"cs",
"estonian",
"et",
"finnish",
"fi",
"gujarati",
"gu",
"hebrew",
"he",
"hindi",
"hi",
"hungarian",
"hu",
"icelandic",
"is",
"indonesian",
"id",
"irish",
"ga",
"kannada",
"kn",
"kyrgyz",
"ky",
"latvian",
"lv",
"ligurian",
"lij",
"luxembourgish",
"lb",
"macedonian",
"mk",
"malayalam",
"ml",
"marathi",
"mr",
"nepali",
"ne",
"persian",
"fa",
"sanskrit",
"sa",
"serbian",
"sr",
"setswana",
"tn",
"sinhala",
"si",
"slovak",
"sk",
"slovenian",
"sl",
"swedish",
"sv",
"tagalog",
"tl",
"tamil",
"ta",
"tatar",
"tt",
"telugu",
"te",
"thai",
"th",
"turkish",
"tr",
"ukrainian",
"uk",
"urdu",
"ur",
"vietnamese",
"vi",
"yoruba",
"yo",
]
def __init__(
self,
granularity: str,
language: str,
):
"""Initializes a text configuration.
Args:
granularity (str): Determines the granularity in which text features are broken down
to. Accepted values are ``"token"``, ``"sentence"``, or ``"paragraph"``.
Computes `shap values <https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-shapley-values.html>`_
for these units.
language (str): Specifies the language of the text features. Accepted values are
one of the following:
``"chinese"``, ``"danish"``, ``"dutch"``, ``"english"``, ``"french"``, ``"german"``,
``"greek"``, ``"italian"``, ``"japanese"``, ``"lithuanian"``, ``"multi-language"``,
``"norwegian bokmål"``, ``"polish"``, ``"portuguese"``, ``"romanian"``,
``"russian"``, ``"spanish"``, ``"afrikaans"``, ``"albanian"``, ``"arabic"``,
``"armenian"``, ``"basque"``, ``"bengali"``, ``"bulgarian"``, ``"catalan"``,
``"croatian"``, ``"czech"``, ``"estonian"``, ``"finnish"``, ``"gujarati"``,
``"hebrew"``, ``"hindi"``, ``"hungarian"``, ``"icelandic"``, ``"indonesian"``,
``"irish"``, ``"kannada"``, ``"kyrgyz"``, ``"latvian"``, ``"ligurian"``,
``"luxembourgish"``, ``"macedonian"``, ``"malayalam"``, ``"marathi"``, ``"nepali"``,
``"persian"``, ``"sanskrit"``, ``"serbian"``, ``"setswana"``, ``"sinhala"``,
``"slovak"``, ``"slovenian"``, ``"swedish"``, ``"tagalog"``, ``"tamil"``,
``"tatar"``, ``"telugu"``, ``"thai"``, ``"turkish"``, ``"ukrainian"``, ``"urdu"``,
``"vietnamese"``, ``"yoruba"``. Use "multi-language" for a mix of multiple
languages. The corresponding two-letter ISO codes are also accepted.
Raises:
ValueError: when ``granularity`` is not in list of supported values
or ``language`` is not in list of supported values
""" # noqa E501 # pylint: disable=c0301
if granularity not in TextConfig._SUPPORTED_GRANULARITIES:
raise ValueError(
f"Invalid granularity {granularity}. Please choose among "
f"{TextConfig._SUPPORTED_GRANULARITIES}"
)
if language not in TextConfig._SUPPORTED_LANGUAGES:
raise ValueError(
f"Invalid language {language}. Please choose among "
f"{TextConfig._SUPPORTED_LANGUAGES}"
)
self.text_config = {
"granularity": granularity,
"language": language,
}
def get_text_config(self):