hc99 commited on
Commit
476455e
·
verified ·
1 Parent(s): 9a8ce03

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/aws__sagemaker-python-sdk/.codecov.yml +2 -0
  2. testbed/aws__sagemaker-python-sdk/.coveragerc +4 -0
  3. testbed/aws__sagemaker-python-sdk/.dictionary +38 -0
  4. testbed/aws__sagemaker-python-sdk/.flake8 +5 -0
  5. testbed/aws__sagemaker-python-sdk/.gitignore +34 -0
  6. testbed/aws__sagemaker-python-sdk/.pydocstylerc +4 -0
  7. testbed/aws__sagemaker-python-sdk/.pylintrc +438 -0
  8. testbed/aws__sagemaker-python-sdk/.readthedocs.yaml +22 -0
  9. testbed/aws__sagemaker-python-sdk/CHANGELOG.md +0 -0
  10. testbed/aws__sagemaker-python-sdk/CODE_OF_CONDUCT.md +4 -0
  11. testbed/aws__sagemaker-python-sdk/CONTRIBUTING.md +264 -0
  12. testbed/aws__sagemaker-python-sdk/LICENSE.txt +193 -0
  13. testbed/aws__sagemaker-python-sdk/MANIFEST.in +13 -0
  14. testbed/aws__sagemaker-python-sdk/NOTICE.txt +2 -0
  15. testbed/aws__sagemaker-python-sdk/README.rst +240 -0
  16. testbed/aws__sagemaker-python-sdk/VERSION +1 -0
  17. testbed/aws__sagemaker-python-sdk/mypy.ini +2 -0
  18. testbed/aws__sagemaker-python-sdk/setup.cfg +15 -0
  19. testbed/aws__sagemaker-python-sdk/setup.py +107 -0
  20. testbed/aws__sagemaker-python-sdk/src/sagemaker/__init__.py +65 -0
  21. testbed/aws__sagemaker-python-sdk/src/sagemaker/_studio.py +113 -0
  22. testbed/aws__sagemaker-python-sdk/src/sagemaker/algorithm.py +589 -0
  23. testbed/aws__sagemaker-python-sdk/src/sagemaker/analytics.py +744 -0
  24. testbed/aws__sagemaker-python-sdk/src/sagemaker/clarify.py +0 -0
  25. testbed/aws__sagemaker-python-sdk/src/sagemaker/content_types.py +23 -0
  26. testbed/aws__sagemaker-python-sdk/src/sagemaker/deprecations.py +245 -0
  27. testbed/aws__sagemaker-python-sdk/src/sagemaker/deserializers.py +324 -0
  28. testbed/aws__sagemaker-python-sdk/src/sagemaker/drift_check_baselines.py +106 -0
  29. testbed/aws__sagemaker-python-sdk/src/sagemaker/environment_variables.py +51 -0
  30. testbed/aws__sagemaker-python-sdk/src/sagemaker/estimator.py +0 -0
  31. testbed/aws__sagemaker-python-sdk/src/sagemaker/exceptions.py +65 -0
  32. testbed/aws__sagemaker-python-sdk/src/sagemaker/git_utils.py +343 -0
  33. testbed/aws__sagemaker-python-sdk/src/sagemaker/hyperparameters.py +111 -0
  34. testbed/aws__sagemaker-python-sdk/src/sagemaker/inputs.py +277 -0
  35. testbed/aws__sagemaker-python-sdk/src/sagemaker/instance_group.py +61 -0
  36. testbed/aws__sagemaker-python-sdk/src/sagemaker/job.py +329 -0
  37. testbed/aws__sagemaker-python-sdk/src/sagemaker/metadata_properties.py +56 -0
  38. testbed/aws__sagemaker-python-sdk/src/sagemaker/model.py +1604 -0
  39. testbed/aws__sagemaker-python-sdk/src/sagemaker/model_metrics.py +160 -0
  40. testbed/aws__sagemaker-python-sdk/src/sagemaker/multidatamodel.py +345 -0
  41. testbed/aws__sagemaker-python-sdk/src/sagemaker/network.py +74 -0
  42. testbed/aws__sagemaker-python-sdk/src/sagemaker/pipeline.py +463 -0
  43. testbed/aws__sagemaker-python-sdk/src/sagemaker/predictor.py +560 -0
  44. testbed/aws__sagemaker-python-sdk/src/sagemaker/tensorflow/model.py +482 -0
  45. testbed/aws__sagemaker-python-sdk/src/sagemaker/tensorflow/training_compiler/config.py +111 -0
  46. testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/__init__.py +43 -0
  47. testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/callback_step.py +145 -0
  48. testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/entities.py +114 -0
  49. testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/fail_step.py +73 -0
  50. testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/functions.py +112 -0
testbed/aws__sagemaker-python-sdk/.codecov.yml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ignore:
2
+ - "**/tensorflow/tensorflow_serving/.*"
testbed/aws__sagemaker-python-sdk/.coveragerc ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [run]
2
+ concurrency = threading
3
+ omit = sagemaker/tests/*
4
+ timid = True
testbed/aws__sagemaker-python-sdk/.dictionary ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ args
2
+ arn
3
+ autoscaling
4
+ aws
5
+ bool
6
+ boolean
7
+ boto
8
+ botocore
9
+ clienterror
10
+ cloudwatch
11
+ cron
12
+ config
13
+ dataset
14
+ datasets
15
+ datetime
16
+ desc
17
+ docstring
18
+ entrypoint
19
+ env
20
+ iam
21
+ hyperparameter
22
+ hyperparameters
23
+ jupyter
24
+ kms
25
+ kwargs
26
+ neo
27
+ noqa
28
+ rc
29
+ runtime
30
+ sagemaker
31
+ stdout
32
+ str
33
+ subdirectories
34
+ subnet
35
+ subnets
36
+ unexpectedstatusexception
37
+ uri
38
+ vpc
testbed/aws__sagemaker-python-sdk/.flake8 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [flake8]
2
+ application_import_names = sagemaker, tests
3
+ import-order-style = google
4
+ per-file-ignores =
5
+ tests/unit/test_tuner.py: F405
testbed/aws__sagemaker-python-sdk/.gitignore ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .idea
2
+ build
3
+ src/*.egg-info
4
+ .cache
5
+ .coverage
6
+ sagemaker_venv*
7
+ *.egg-info
8
+ .tox
9
+ **/__pycache__
10
+ **/.ipynb_checkpoints
11
+ dist/
12
+ **/tensorflow-examples.tar.gz
13
+ **/*.pyc
14
+ **.pyc
15
+ scratch*.py
16
+ .eggs
17
+ *.egg
18
+ examples/tensorflow/distributed_mnist/data
19
+ *.iml
20
+ doc/_build
21
+ doc/_static
22
+ doc/_templates
23
+ **/.DS_Store
24
+ venv/
25
+ *~
26
+ .pytest_cache/
27
+ *.swp
28
+ .docker/
29
+ env/
30
+ .vscode/
31
+ **/tmp
32
+ .python-version
33
+ **/_repack_model.py
34
+ **/_repack_script_launcher.sh
testbed/aws__sagemaker-python-sdk/.pydocstylerc ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [pydocstyle]
2
+ inherit = false
3
+ ignore = D104,D107,D202,D203,D213,D214,D400,D401,D404,D406,D407,D411,D413,D414,D415,D417
4
+ match = (?!record_pb2).*\.py
testbed/aws__sagemaker-python-sdk/.pylintrc ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This config based on a few of Google's pylint configurations:
2
+ # * https://chromium.googlesource.com/chromium/tools/depot_tools.git/+/refs/heads/master/pylintrc
3
+ # * https://github.com/google/seq2seq/blob/master/pylintrc
4
+ # * https://github.com/google/pygtrie/blob/master/.pylintrc
5
+
6
+ [MASTER]
7
+
8
+ # Specify a configuration file.
9
+ #rcfile=
10
+
11
+ # Python code to execute, usually for sys.path manipulation such as
12
+ # pygtk.require().
13
+ #init-hook=
14
+
15
+ # Profiled execution.
16
+ profile=no
17
+
18
+ # Add files or directories to the blacklist. They should be base names, not
19
+ # paths.
20
+ ignore=CVS,tensorflow_serving
21
+
22
+ # Add files or directories matching the regex patterns to the blacklist.
23
+ # The regex matches against base names, not paths.
24
+ # Regex patterns can be comma(and newline)-separated
25
+ ignore-patterns=
26
+ .*_pb2.py, # Ignore all files generated by the protocol buffer compiler
27
+
28
+ # Pickle collected data for later comparisons.
29
+ persistent=yes
30
+
31
+ # List of plugins (as comma separated values of python modules names) to load,
32
+ # usually to register additional checkers.
33
+ load-plugins=
34
+
35
+ # Use multiple processes to speed up Pylint.
36
+ jobs=1
37
+
38
+ # Allow loading of arbitrary C extensions. Extensions are imported into the
39
+ # active Python interpreter and may run arbitrary code.
40
+ unsafe-load-any-extension=no
41
+
42
+ # A comma-separated list of package or module names from where C extensions may
43
+ # be loaded. Extensions are loading into the active Python interpreter and may
44
+ # run arbitrary code
45
+ extension-pkg-whitelist=numpy
46
+
47
+ # Allow optimization of some AST trees. This will activate a peephole AST
48
+ # optimizer, which will apply various small optimizations. For instance, it can
49
+ # be used to obtain the result of joining multiple strings with the addition
50
+ # operator. Joining a lot of strings can lead to a maximum recursion error in
51
+ # Pylint and this flag can prevent that. It has one side effect, the resulting
52
+ # AST will be different than the one from reality. This option is deprecated
53
+ # and it will be removed in Pylint 2.0.
54
+ optimize-ast=no
55
+
56
+ [MESSAGES CONTROL]
57
+
58
+ # Only show warnings with the listed confidence levels. Leave empty to show
59
+ # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
60
+ confidence=
61
+
62
+ # Enable the message, report, category or checker with the given id(s). You can
63
+ # either give multiple identifier separated by comma (,) or put this option
64
+ # multiple time (only on the command line, not in the configuration file where
65
+ # it should appear only once). See also the "--disable" option for examples.
66
+ #enable=
67
+
68
+ # Disable the message, report, category or checker with the given id(s). You
69
+ # can either give multiple identifiers separated by comma (,) or put this
70
+ # option multiple times (only on the command line, not in the configuration
71
+ # file where it should appear only once).You can also use "--disable=all" to
72
+ # disable everything first and then reenable specific checks. For example, if
73
+ # you want to run only the similarities checker, you can use "--disable=all
74
+ # --enable=similarities". If you want to run only the classes checker, but have
75
+ # no Warning level messages displayed, use"--disable=all --enable=classes
76
+ # --disable=W"
77
+ disable=
78
+ C0330, # Black disagrees with and explicitly violates this: https://github.com/python/black/issues/48
79
+ abstract-method, # TODO: Fix abstract methods
80
+ arguments-differ,
81
+ cyclic-import, # TODO: Resolve cyclic imports
82
+ fixme,
83
+ invalid-name,
84
+ import-error, # Since we run Pylint before any of our builds in tox, this will always fail
85
+ import-outside-toplevel,
86
+ no-self-use, # TODO: Convert methods to functions where appropriate
87
+ protected-access, # TODO: Fix access
88
+ signature-differs, # TODO: fix kwargs
89
+ too-many-arguments,
90
+ too-many-branches, # TODO: Simplify or ignore as appropriate
91
+ too-many-instance-attributes,
92
+ too-many-lines,
93
+ too-many-locals,
94
+ useless-object-inheritance, # TODO: Enable this check and fix code once Python 2 is no longer supported.
95
+ super-with-arguments,
96
+ raise-missing-from,
97
+
98
+ [REPORTS]
99
+ # Set the output format. Available formats are text, parseable, colorized, msvs
100
+ # (visual studio) and html. You can also give a reporter class, eg
101
+ # mypackage.mymodule.MyReporterClass.
102
+ output-format=colorized
103
+
104
+ # Put messages in a separate file for each module / package specified on the
105
+ # command line instead of printing them on stdout. Reports (if any) will be
106
+ # written in a file name "pylint_global.[txt|html]". This option is deprecated
107
+ # and it will be removed in Pylint 2.0.
108
+ files-output=no
109
+
110
+ # Tells whether to display a full report or only the messages
111
+ reports=no
112
+
113
+ # Python expression which should return a note less than 10 (10 is the highest
114
+ # note). You have access to the variables errors warning, statement which
115
+ # respectively contain the number of errors / warnings messages and the total
116
+ # number of statements analyzed. This is used by the global evaluation report
117
+ # (RP0004).
118
+ evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
119
+
120
+ # Add a comment according to your evaluation note. This is used by the global
121
+ # evaluation report (RP0004).
122
+ comment=no
123
+
124
+ [BASIC]
125
+
126
+ # Good variable names which should always be accepted, separated by a comma
127
+ good-names=i,j,k,ex,Run,_
128
+
129
+ # Bad variable names which should always be refused, separated by a comma
130
+ bad-names=foo,bar,baz,toto,tutu,tata
131
+
132
+ # Colon-delimited sets of names that determine each other's naming style when
133
+ # the name regexes allow several styles.
134
+ name-group=
135
+
136
+ # Include a hint for the correct naming format with invalid-name
137
+ include-naming-hint=no
138
+
139
+ # List of decorators that produce properties, such as abc.abstractproperty. Add
140
+ # to this list to register other decorators that produce valid properties.
141
+ property-classes=abc.abstractproperty
142
+
143
+ # Regular expression matching correct variable names
144
+ variable-rgx=[a-z_][a-z0-9_]{2,30}$
145
+
146
+ # Naming hint for variable names
147
+ variable-name-hint=[a-z_][a-z0-9_]{2,30}$
148
+
149
+ # Required attributes for module, separated by a comma
150
+ #required-attributes=
151
+
152
+ # Regular expression matching correct class attribute names
153
+ class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
154
+
155
+ # Naming hint for class attribute names
156
+ class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
157
+
158
+ # Regular expression matching correct argument names
159
+ argument-rgx=[a-z_][a-z0-9_]{2,30}$
160
+
161
+ # Naming hint for argument names
162
+ argument-name-hint=[a-z_][a-z0-9_]{2,30}$
163
+
164
+ # Regular expression matching correct module names
165
+ module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
166
+
167
+ # Naming hint for module names
168
+ module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
169
+
170
+ # Regular expression matching correct constant names
171
+ const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
172
+
173
+ # Naming hint for constant names
174
+ const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
175
+
176
+ # Regular expression matching correct inline iteration names
177
+ inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
178
+
179
+ # Naming hint for inline iteration names
180
+ inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
181
+
182
+ # Regular expression matching correct method names
183
+ method-rgx=[a-z_][a-z0-9_]{2,30}$
184
+
185
+ # Naming hint for method names
186
+ method-name-hint=[a-z_][a-z0-9_]{2,30}$
187
+
188
+ # Regular expression matching correct function names
189
+ function-rgx=[a-z_][a-z0-9_]{2,30}$
190
+
191
+ # Naming hint for function names
192
+ function-name-hint=[a-z_][a-z0-9_]{2,30}$
193
+
194
+ # Regular expression matching correct attribute names
195
+ attr-rgx=[a-z_][a-z0-9_]{2,30}$
196
+
197
+ # Naming hint for attribute names
198
+ attr-name-hint=[a-z_][a-z0-9_]{2,30}$
199
+
200
+ # Regular expression matching correct class names
201
+ class-rgx=[A-Z_][a-zA-Z0-9]+$
202
+
203
+ # Naming hint for class names
204
+ class-name-hint=[A-Z_][a-zA-Z0-9]+$
205
+
206
+ # Regular expression which should only match function or class names that do
207
+ # not require a docstring.
208
+ no-docstring-rgx=^test_
209
+
210
+ # Minimum line length for functions/classes that require docstrings, shorter
211
+ # ones are exempt.
212
+ docstring-min-length=-1
213
+
214
+ # List of builtins function names that should not be used, separated by a comma.
215
+ # XXX: Should we ban map() & filter() for list comprehensions?
216
+ # exit & quit are for the interactive interpreter shell only.
217
+ # https://docs.python.org/3/library/constants.html#constants-added-by-the-site-module
218
+ bad-functions=
219
+ apply,
220
+ exit,
221
+ input,
222
+ quit,
223
+
224
+ [ELIF]
225
+
226
+ # Maximum number of nested blocks for function / method body
227
+ max-nested-blocks=5
228
+
229
+ [FORMAT]
230
+ # Maximum number of characters on a single line.
231
+ max-line-length=100
232
+
233
+ # Regexp for a line that is allowed to be longer than the limit. Can only be a single regex.
234
+ # The following matches any semblance of a url of any sort.
235
+ ignore-long-lines=^\s*.*(# )?(<?https?:\/\/)?[-a-zA-Z0-9@:%%._\+~#=><]{1,256}\.[a-zA-Z0-9()]{1,6}\b[-a-zA-Z0-9()@:%%_\+.~#?&\/\/=<>]*\S*>?$
236
+
237
+ # Allow the body of an if to be on the same line as the test if there is no
238
+ # else.
239
+ single-line-if-stmt=n
240
+
241
+ # List of optional constructs for which whitespace checking is disabled. `dict-
242
+ # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
243
+ # `trailing-comma` allows a space between comma and closing bracket: (a, ).
244
+ # `empty-line` allows space-only lines.
245
+ no-space-check=trailing-comma,dict-separator
246
+
247
+ # Maximum number of lines in a module
248
+ max-module-lines=1000
249
+
250
+ # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
251
+ # tab).
252
+ indent-string=' '
253
+
254
+ # Number of spaces of indent required inside a hanging or continued line.
255
+ indent-after-paren=4
256
+
257
+ # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
258
+ expected-line-ending-format=LF
259
+
260
+ [LOGGING]
261
+
262
+ # Logging modules to check that the string format arguments are in logging
263
+ # function parameter format
264
+ logging-modules=logging
265
+
266
+ [MISCELLANEOUS]
267
+
268
+ # List of note tags to take in consideration, separated by a comma.
269
+ notes=FIXME,XXX,TODO
270
+
271
+ [SIMILARITIES]
272
+
273
+ # Minimum lines number of a similarity.
274
+ min-similarity-lines=20
275
+
276
+ # Ignore comments when computing similarities.
277
+ ignore-comments=yes
278
+
279
+ # Ignore docstrings when computing similarities.
280
+ ignore-docstrings=yes
281
+
282
+ # Ignore imports when computing similarities.
283
+ ignore-imports=no
284
+
285
+ [SPELLING]
286
+
287
+ # Spelling dictionary name. Available dictionaries: none. To make it working
288
+ # install python-enchant package.
289
+ spelling-dict=
290
+
291
+ # List of comma separated words that should not be checked.
292
+ spelling-ignore-words=
293
+
294
+ # A path to a file that contains private dictionary; one word per line.
295
+ spelling-private-dict-file=.dictionary
296
+
297
+ # Tells whether to store unknown words to indicated private dictionary in
298
+ # --spelling-private-dict-file option instead of raising a message.
299
+ spelling-store-unknown-words=no
300
+
301
+
302
+ [TYPECHECK]
303
+
304
+ # Tells whether missing members accessed in mixin class should be ignored. A
305
+ # mixin class is detected if its name ends with "mixin" (case insensitive).
306
+ ignore-mixin-members=yes
307
+
308
+ # List of module names for which member attributes should not be checked
309
+ # (useful for modules/projects where namespaces are manipulated during runtime
310
+ # and thus existing member attributes cannot be deduced by static analysis. It
311
+ # supports qualified module names, as well as Unix pattern matching.
312
+ ignored-modules=distutils
313
+
314
+ # List of class names for which member attributes should not be checked (useful
315
+ # for classes with dynamically set attributes). This supports the use of
316
+ # qualified names.
317
+ ignored-classes=optparse.Values,thread._local,_thread._local,matplotlib.cm,tensorflow.python,tensorflow,tensorflow.train.Example,RunOptions,sagemaker.workflow.properties.Properties
318
+
319
+ # List of members which are set dynamically and missed by pylint inference
320
+ # system, and so shouldn't trigger E1101 when accessed. Python regular
321
+ # expressions are accepted.
322
+ generated-members=set_shape,np.float32
323
+
324
+ # List of decorators that produce context managers, such as
325
+ # contextlib.contextmanager. Add to this list to register other decorators that
326
+ # produce valid context managers.
327
+ contextmanager-decorators=contextlib.contextmanager
328
+
329
+ [VARIABLES]
330
+
331
+ # Tells whether we should check for unused import in __init__ files.
332
+ init-import=no
333
+
334
+ # A regular expression matching the name of dummy variables (i.e. expectedly
335
+ # not used).
336
+ dummy-variables-rgx=_|unused_
337
+
338
+ # List of additional names supposed to be defined in builtins. Remember that
339
+ # you should avoid to define new builtins when possible.
340
+ additional-builtins=
341
+
342
+ # List of strings which can identify a callback function by name. A callback
343
+ # name must start or end with one of those strings.
344
+ callbacks=cb_,_cb
345
+
346
+ # List of qualified module names which can have objects that can redefine
347
+ # builtins.
348
+ redefining-builtins-modules=six.moves,future.builtins
349
+
350
+
351
+ [CLASSES]
352
+
353
+ # List of method names used to declare (i.e. assign) instance attributes.
354
+ defining-attr-methods=__init__,__new__,setUp
355
+
356
+ # List of valid names for the first argument in a class method.
357
+ valid-classmethod-first-arg=cls
358
+
359
+ # List of valid names for the first argument in a metaclass class method.
360
+ valid-metaclass-classmethod-first-arg=mcs
361
+
362
+ # List of member names, which should be excluded from the protected access
363
+ # warning.
364
+ exclude-protected=_asdict,_fields,_replace,_source,_make
365
+
366
+
367
+ [DESIGN]
368
+
369
+ # Maximum number of arguments for function / method
370
+ max-args=10
371
+
372
+ # Argument names that match this expression will be ignored. Default to name
373
+ # with leading underscore
374
+ ignored-argument-names=_.*
375
+
376
+ # Maximum number of locals for function / method body
377
+ max-locals=30
378
+
379
+ # Maximum number of return / yield for function / method body
380
+ max-returns=6
381
+
382
+ # Maximum number of branch for function / method body
383
+ max-branches=12
384
+
385
+ # Maximum number of statements in function / method body
386
+ max-statements=100
387
+
388
+ # Maximum number of parents for a class (see R0901).
389
+ max-parents=7
390
+
391
+ # Maximum number of attributes for a class (see R0902).
392
+ max-attributes=10
393
+
394
+ # Minimum number of public methods for a class (see R0903).
395
+ min-public-methods=0
396
+
397
+ # Maximum number of public methods for a class (see R0904).
398
+ max-public-methods=20
399
+
400
+ # Maximum number of boolean expressions in a if statement
401
+ max-bool-expr=5
402
+
403
+
404
+ [IMPORTS]
405
+
406
+ # Deprecated modules which should not be used, separated by a comma
407
+ deprecated-modules=optparse
408
+
409
+ # Create a graph of every (i.e. internal and external) dependencies in the
410
+ # given file (report RP0402 must not be disabled)
411
+ import-graph=
412
+
413
+ # Create a graph of external dependencies in the given file (report RP0402 must
414
+ # not be disabled)
415
+ ext-import-graph=
416
+
417
+ # Create a graph of internal dependencies in the given file (report RP0402 must
418
+ # not be disabled)
419
+ int-import-graph=
420
+
421
+ # Force import order to recognize a module as part of the standard
422
+ # compatibility libraries.
423
+ known-standard-library=
424
+
425
+ # Force import order to recognize a module as part of a third party library.
426
+ known-third-party=boto3,botocore,enchant
427
+
428
+ # Analyse import fallback blocks. This can be used to support both Python 2 and
429
+ # 3 compatible code, which means that the block might have code that exists
430
+ # only in one or another interpreter, leading to false positives when analysed.
431
+ analyse-fallback-blocks=no
432
+
433
+
434
+ [EXCEPTIONS]
435
+
436
+ # Exceptions that will emit a warning when being caught. Defaults to
437
+ # "Exception"
438
+ overgeneral-exceptions=Exception
testbed/aws__sagemaker-python-sdk/.readthedocs.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ReadTheDocs environment customization to allow us to use conda to install
2
+ # libraries which have C dependencies for the doc build. See:
3
+ # https://docs.readthedocs.io/en/latest/config-file/v2.html
4
+
5
+ version: 2
6
+
7
+ build:
8
+ os: ubuntu-20.04
9
+ tools:
10
+ python: "3.9"
11
+
12
+
13
+ python:
14
+ install:
15
+ - method: pip
16
+ path: .
17
+ - requirements: doc/requirements.txt
18
+
19
+
20
+ sphinx:
21
+ configuration: doc/conf.py
22
+ fail_on_warning: true # http://www.sphinx-doc.org/en/master/man/sphinx-build.html#id6
testbed/aws__sagemaker-python-sdk/CHANGELOG.md ADDED
The diff for this file is too large to render. See raw diff
 
testbed/aws__sagemaker-python-sdk/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ## Code of Conduct
2
+ This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3
+ For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4
+ opensource-codeofconduct@amazon.com with any additional questions or comments.
testbed/aws__sagemaker-python-sdk/CONTRIBUTING.md ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing Guidelines
2
+
3
+ Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4
+ documentation, we greatly value feedback and contributions from our community.
5
+
6
+ Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7
+ information to effectively respond to your bug report or contribution.
8
+
9
+
10
+ ## Table of Contents
11
+
12
+ * [Report Bugs/Feature Requests](#report-bugsfeature-requests)
13
+ * [Contribute via Pull Requests (PRs)](#contribute-via-pull-requests-prs)
14
+ * [Set up Your Development Environment *[Optional, but Recommended]*](#set-up-your-development-environment-optional-but-recommended)
15
+ * [Pull Down the Code](#pull-down-the-code)
16
+ * [Run the Unit Tests](#run-the-unit-tests)
17
+ * [Run the Integration Tests](#run-the-integration-tests)
18
+ * [Make and Test Your Change](#make-and-test-your-change)
19
+ * [Commit Your Change](#commit-your-change)
20
+ * [Send a Pull Request](#send-a-pull-request)
21
+ * [Documentation Guidelines](#documentation-guidelines)
22
+ * [Overviews](#overviews)
23
+ * [API References (docstrings)](#api-references-docstrings)
24
+ * [Build and Test Documentation](#build-and-test-documentation)
25
+ * [Find Contributions to Work On](#find-contributions-to-work-on)
26
+ * [Code of Conduct](#code-of-conduct)
27
+ * [Security Issue Notifications](#security-issue-notifications)
28
+ * [Licensing](#licensing)
29
+
30
+ ## Report Bugs/Feature Requests
31
+
32
+ We welcome you to use the GitHub issue tracker to report bugs or suggest features.
33
+
34
+ When filing an issue, please check [existing open](https://github.com/aws/sagemaker-python-sdk/issues) and [recently closed](https://github.com/aws/sagemaker-python-sdk/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20) issues to make sure somebody else hasn't already
35
+ reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
36
+
37
+ * A reproducible test case or series of steps.
38
+ * The version of our code being used.
39
+ * Any modifications you've made relevant to the bug.
40
+ * A description of your environment or deployment.
41
+
42
+
43
+ ## Contribute via Pull Requests (PRs)
44
+
45
+ Contributions via pull requests are much appreciated.
46
+
47
+ Before sending us a pull request, please ensure that:
48
+
49
+ * You are working against the latest source on the *master* branch.
50
+ * You check the existing open and recently merged pull requests to make sure someone else hasn't already addressed the problem.
51
+ * You open an issue to discuss any significant work - we would hate for your time to be wasted.
52
+
53
+
54
+ ### Set up Your Development Environment *[Optional, but Recommended]*
55
+
56
+ 1. Set up the Cloud9 environment:
57
+ 1. Instance type: You'll need at least 4 GB of RAM to avoid running into memory issues. We recommend at least a t3.medium to run the unit tests. A larger host will reduce the chance of encountering resource limits.
58
+ 1. Follow the instructions at [Creating a Cloud9 EC2 Environment](https://docs.aws.amazon.com/cloud9/latest/user-guide/create-environment.html#create-environment-main) to set up a Cloud9 EC2 environment.
59
+ 1. Expand the storage of the EC2 instance from 10GB to 20GB:
60
+ 1. Because you'll need a minimum of 11GB of disk storage on the EC2 instance to run the repository's unit tests, you'll need to expand your EC2 volume size. We recommend at least 20GB. A larger volume will reduce the chance of encountering resource limits.
61
+ 1. Follow the instructions at [Modifying an EBS Volume Using Elastic Volumes (Console)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/requesting-ebs-volume-modifications.html#modify-ebs-volume) to increase the EBS volume size associated with the newly created EC2 instance.
62
+ 1. Wait 5-10min for the new EBS volume increase to finalize.
63
+ 1. Allow EC2 to claim the additional space by stopping and then starting your EC2 host.
64
+
65
+
66
+ ### Pull Down the Code
67
+
68
+ 1. If you do not already have one, create a GitHub account by following the prompts at [Join Github](https://github.com/join).
69
+ 1. Create a fork of this repository on GitHub. You should end up with a fork at `https://github.com/<username>/sagemaker-python-sdk`.
70
+ 1. Follow the instructions at [Fork a Repo](https://help.github.com/en/articles/fork-a-repo) to fork a GitHub repository.
71
+ 1. Clone your fork of the repository: `git clone https://github.com/<username>/sagemaker-python-sdk` where `<username>` is your github username.
72
+
73
+
74
+ ### Run the Unit Tests
75
+
76
+ 1. Install tox using `pip install tox`
77
+ 1. Install coverage using `pip install .[test]`
78
+ 1. cd into the sagemaker-python-sdk folder: `cd sagemaker-python-sdk` or `cd /environment/sagemaker-python-sdk`
79
+ 1. Run the following tox command and verify that all code checks and unit tests pass: `tox tests/unit`
80
+
81
+ You can also run a single test with the following command: `tox -e py310 -- -s -vv <path_to_file><file_name>::<test_function_name>`
82
+ * Note that the coverage test will fail if you only run a single test, so make sure to surround the command with `export IGNORE_COVERAGE=-` and `unset IGNORE_COVERAGE`
83
+ * Example: `export IGNORE_COVERAGE=- ; tox -e py310 -- -s -vv tests/unit/test_estimator.py::test_sagemaker_model_s3_uri_invalid ; unset IGNORE_COVERAGE`
84
+
85
+
86
+ ### Run the Integration Tests
87
+
88
+ Our CI system runs integration tests (the ones in the `tests/integ` directory), in parallel, for every Pull Request.
89
+ You should only worry about manually running any new integration tests that you write, or integration tests that test an area of code that you've modified.
90
+
91
+ 1. Follow the instructions at [Set Up the AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/polly/latest/dg/setup-aws-cli.html).
92
+ 1. To run a test, specify the test file and method you want to run per the following command: `tox -e py310 -- -s -vv <path_to_file><file_name>::<test_function_name>`
93
+ * Note that the coverage test will fail if you only run a single test, so make sure to surround the command with `export IGNORE_COVERAGE=-` and `unset IGNORE_COVERAGE`
94
+ * Example: `export IGNORE_COVERAGE=- ; tox -e py310 -- -s -vv tests/integ/test_tf_script_mode.py::test_mnist ; unset IGNORE_COVERAGE`
95
+
96
+ If you are writing or modifying a test that creates a SageMaker job (training, tuner, or transform) or endpoint, it's important to assign a concurrency-friendly `job_name` (or `endpoint_name`), or your tests may fail randomly due to name collisions. We have a helper method `sagemaker.utils.unique_name_from_base(base, max_length)` that makes test-friendly names. You can find examples of how to use it [here](https://github.com/aws/sagemaker-python-sdk/blob/3816a5658d3737c9767e01bc8d37fc3ed5551593/tests/integ/test_tfs.py#L37) and
97
+ [here](https://github.com/aws/sagemaker-python-sdk/blob/3816a5658d3737c9767e01bc8d37fc3ed5551593/tests/integ/test_tuner.py#L616), or by searching for "unique\_name\_from\_base" in our test code.
98
+
99
+
100
+ ### Make and Test Your Change
101
+
102
+ 1. Create a new git branch:
103
+ ```shell
104
+ git checkout -b my-fix-branch master
105
+ ```
106
+ 1. Make your changes, **including unit tests** and, if appropriate, integration tests.
107
+ 1. Include unit tests when you contribute new features or make bug fixes, as they help to:
108
+ 1. Prove that your code works correctly.
109
+ 1. Guard against future breaking changes to lower the maintenance cost.
110
+ 1. Please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
111
+ 1. Run all the unit tests as per [Run the Unit Tests](#run-the-unit-tests), and verify that all checks and tests pass.
112
+ 1. Note that this also runs tools that may be necessary for the automated build to pass (ex: code reformatting by 'black').
113
+ 1. If your changes include documentation changes, please see the [Documentation Guidelines](#documentation-guidelines).
114
+ 1. If you include integration tests, do not mark them as canaries if they will not run in all regions.
115
+
116
+
117
+ ### Commit Your Change
118
+
119
+ We use commit messages to update the project version number and generate changelog entries, so it's important for them to follow the right format. Valid commit messages include a prefix, separated from the rest of the message by a colon and a space. Here are a few examples:
120
+
121
+ ```
122
+ feature: support VPC config for hyperparameter tuning
123
+ fix: fix flake8 errors
124
+ documentation: add MXNet documentation
125
+ ```
126
+
127
+ Valid prefixes are listed in the table below.
128
+
129
+ | Prefix | Use for... |
130
+ |----------------:|:-----------------------------------------------------------------------------------------------|
131
+ | `breaking` | Incompatible API changes. |
132
+ | `deprecation` | Deprecating an existing API or feature, or removing something that was previously deprecated. |
133
+ | `feature` | Adding a new feature. |
134
+ | `fix` | Bug fixes. |
135
+ | `change` | Any other code change. |
136
+ | `documentation` | Documentation changes. |
137
+
138
+ Some of the prefixes allow abbreviation ; `break`, `feat`, `depr`, and `doc` are all valid. If you omit a prefix, the commit will be treated as a `change`.
139
+
140
+ For the rest of the message, use imperative style and keep things concise but informative. See [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/) for guidance.
141
+
142
+
143
+ ### Send a Pull Request
144
+
145
+ GitHub provides additional document on [Creating a Pull Request](https://help.github.com/articles/creating-a-pull-request/).
146
+
147
+ Please remember to:
148
+ * Use commit messages (and PR titles) that follow the guidelines under [Commit Your Change](#commit-your-change).
149
+ * Send us a pull request, answering any default questions in the pull request interface.
150
+ * Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
151
+
152
+
153
+ ## Documentation Guidelines
154
+
155
+ We use reStructuredText (RST) for most of our documentation. For a quick primer on the syntax,
156
+ see [the Sphinx documentation](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html).
157
+
158
+ In this repository, we have two main categories of documentation: overviews and API references.
159
+ "How to" tutorials are housed in the [Amazon SageMaker Examples repository](https://github.com/awslabs/amazon-sagemaker-examples).
160
+ Overviews and API references are discussed in more detail below.
161
+
162
+ Here are some general guidelines to follow when writing either kind of documentation:
163
+ * Use present tense.
164
+ * 👍 "The estimator fits a model."
165
+ * 👎 "The estimator will fit a model."
166
+ * When referring to an AWS product, use its full name in the first invocation.
167
+ (This applies only to prose; use what makes sense when it comes to writing code, etc.)
168
+ * 👍 "Amazon S3"
169
+ * 👎 "s3"
170
+ * Provide links to other ReadTheDocs pages, AWS documentation, etc. when helpful.
171
+ Try to not duplicate documentation when you can reference it instead.
172
+ * Use meaningful text in a link.
173
+ * 👍 You can learn more about [hyperparameter tuning with SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html) in the SageMaker docs.
174
+ * 👎 Read more about it [here](#).
175
+
176
+
177
+ ### Overviews
178
+
179
+ This section refers to documentation that discusses a specific topic or feature to
180
+ help the reader deepen their understanding, and may include short snippets of how to do specific tasks.
181
+ Examples include "[Amazon SageMaker Debugger](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html)"
182
+ and "[Use MXNet with the SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/using_mxnet.html)."
183
+
184
+ The goal of these documents is to explain basic usage.
185
+ This includes the general purpose of the topic or feature,
186
+ and common ways to use the SageMaker Python SDK in that context.
187
+
188
+ This type of documentation should not be a step-by-step tutorial.
189
+ That is better suited for the [example notebooks](https://github.com/awslabs/amazon-sagemaker-examples).
190
+ Instead, keep the content focused on the unique aspects of the feature.
191
+ For example, if one is writing specifically about deploying models,
192
+ there is no need to also include instructions on how to train a model first.
193
+ In this case, consider linking to existing documentation about training models and any other prerequisites.
194
+
195
+ Lastly, in addition to the general guidelines listed above:
196
+ * Use the imperative mood for headings.
197
+ * 👍 "Prepare a Training Script"
198
+ * 👎 "Preparing a Training Script"
199
+ * Don’t refer to features as "new" - they might be at the time of writing, but they won’t always be!
200
+
201
+ ### API References (docstrings)
202
+
203
+ The API references are generated from docstrings.
204
+ A docstring is the comment in the source code that describes a module, class, function, or variable.
205
+
206
+ ```python
207
+ def foo():
208
+ """This comment is a docstring for the function foo."""
209
+ ```
210
+
211
+ We use [Google-style docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html).
212
+ There should be a docstring for every public module, class, and function.
213
+ For functions, make sure your docstring covers all of the arguments, exceptions, and any other relevant information.
214
+ When possible, link to classes and functions, e.g. use ":class:~\`sagemaker.session.Session\`" over just "Session."
215
+
216
+ If a parameter of a function has a default value, please note what the default is.
217
+ If that default value is `None`, it can also be helpful to explain what happens when the parameter is `None`.
218
+ If `**kwargs` is part of the function signature, link to the parent class(es) or method(s) so that the reader knows where to find the available parameters.
219
+
220
+ For an example file with docstrings, see [the `processing` module](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/processing.py).
221
+
222
+ To have a class's docstrings included in the API reference, it needs to be included in one of the files in the `doc/` folder.
223
+ For example, see the [Processing API reference](https://github.com/aws/sagemaker-python-sdk/blob/master/doc/processing.rst).
224
+
225
+
226
+ ### Build and Test Documentation
227
+
228
+ To build the Sphinx docs, run the following command in the `doc/` directory:
229
+
230
+ ```shell
231
+ make html
232
+ ```
233
+
234
+ You can then find the generated HTML files in `doc/_build/html/`.
235
+
236
+ To check both the README and API documentation for build errors, you can run the following:
237
+
238
+ ```shell
239
+ tox -e twine,sphinx
240
+ ```
241
+
242
+
243
+ ## Find Contributions to Work On
244
+
245
+ Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws/sagemaker-python-sdk/labels/help%20wanted) issues is a great place to start.
246
+
247
+
248
+ ## Code of Conduct
249
+
250
+ This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
251
+ For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
252
+ opensource-codeofconduct@amazon.com with any additional questions or comments.
253
+
254
+
255
+ ## Security Issue Notifications
256
+
257
+ If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
258
+
259
+
260
+ ## Licensing
261
+
262
+ See the [LICENSE](https://github.com/aws/sagemaker-python-sdk/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
263
+
264
+ We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.
testbed/aws__sagemaker-python-sdk/LICENSE.txt ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+
4
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5
+
6
+ 1. Definitions.
7
+
8
+ "License" shall mean the terms and conditions for use, reproduction,
9
+ and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by
12
+ the copyright owner that is granting the License.
13
+
14
+ "Legal Entity" shall mean the union of the acting entity and all
15
+ other entities that control, are controlled by, or are under common
16
+ control with that entity. For the purposes of this definition,
17
+ "control" means (i) the power, direct or indirect, to cause the
18
+ direction or management of such entity, whether by contract or
19
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity
23
+ exercising permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications,
26
+ including but not limited to software source code, documentation
27
+ source, and configuration files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical
30
+ transformation or translation of a Source form, including but
31
+ not limited to compiled object code, generated documentation,
32
+ and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or
35
+ Object form, made available under the License, as indicated by a
36
+ copyright notice that is included in or attached to the work
37
+ (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding those notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ ======================================================================================
178
+ Amazon SageMaker Examples Subcomponents:
179
+
180
+ The Amazon SageMaker Examples project contains subcomponents with separate
181
+ copyright notices and license terms. Your use of the source code for the
182
+ these subcomponents is subject to the terms and conditions of the following
183
+ licenses. See licenses/ for text of these licenses.
184
+
185
+ If a folder hierarchy is listed as subcomponent, separate listings of
186
+ further subcomponents (files or folder hierarchies) part of the hierarchy
187
+ take precedence.
188
+
189
+ =======================================================================================
190
+ 2-clause BSD license
191
+ =======================================================================================
192
+ _static/kendrasearchtools.js
193
+ _templates/search.html
testbed/aws__sagemaker-python-sdk/MANIFEST.in ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recursive-include src/sagemaker *.py
2
+
3
+ include src/sagemaker/image_uri_config/*.json
4
+ recursive-include requirements *
5
+
6
+ include VERSION
7
+ include LICENSE.txt
8
+ include README.rst
9
+
10
+ prune tests
11
+
12
+ recursive-exclude * __pycache__
13
+ recursive-exclude * *.py[co]
testbed/aws__sagemaker-python-sdk/NOTICE.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Amazon SageMaker Python SDK
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
testbed/aws__sagemaker-python-sdk/README.rst ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. image:: https://github.com/aws/sagemaker-python-sdk/raw/master/branding/icon/sagemaker-banner.png
2
+ :height: 100px
3
+ :alt: SageMaker
4
+
5
+ ====================
6
+ SageMaker Python SDK
7
+ ====================
8
+
9
+ .. image:: https://img.shields.io/pypi/v/sagemaker.svg
10
+ :target: https://pypi.python.org/pypi/sagemaker
11
+ :alt: Latest Version
12
+
13
+ .. image:: https://img.shields.io/pypi/pyversions/sagemaker.svg
14
+ :target: https://pypi.python.org/pypi/sagemaker
15
+ :alt: Supported Python Versions
16
+
17
+ .. image:: https://img.shields.io/badge/code_style-black-000000.svg
18
+ :target: https://github.com/python/black
19
+ :alt: Code style: black
20
+
21
+ .. image:: https://readthedocs.org/projects/sagemaker/badge/?version=stable
22
+ :target: https://sagemaker.readthedocs.io/en/stable/
23
+ :alt: Documentation Status
24
+
25
+ SageMaker Python SDK is an open source library for training and deploying machine learning models on Amazon SageMaker.
26
+
27
+ With the SDK, you can train and deploy models using popular deep learning frameworks **Apache MXNet** and **TensorFlow**.
28
+ You can also train and deploy models with **Amazon algorithms**,
29
+ which are scalable implementations of core machine learning algorithms that are optimized for SageMaker and GPU training.
30
+ If you have **your own algorithms** built into SageMaker compatible Docker containers, you can train and host models using these as well.
31
+
32
+ For detailed documentation, including the API reference, see `Read the Docs <https://sagemaker.readthedocs.io>`_.
33
+
34
+ Table of Contents
35
+ -----------------
36
+
37
+ #. `Installing SageMaker Python SDK <#installing-the-sagemaker-python-sdk>`__
38
+ #. `Using the SageMaker Python SDK <https://sagemaker.readthedocs.io/en/stable/overview.html>`__
39
+ #. `Using MXNet <https://sagemaker.readthedocs.io/en/stable/using_mxnet.html>`__
40
+ #. `Using TensorFlow <https://sagemaker.readthedocs.io/en/stable/using_tf.html>`__
41
+ #. `Using Chainer <https://sagemaker.readthedocs.io/en/stable/using_chainer.html>`__
42
+ #. `Using PyTorch <https://sagemaker.readthedocs.io/en/stable/using_pytorch.html>`__
43
+ #. `Using Scikit-learn <https://sagemaker.readthedocs.io/en/stable/using_sklearn.html>`__
44
+ #. `Using XGBoost <https://sagemaker.readthedocs.io/en/stable/using_xgboost.html>`__
45
+ #. `SageMaker Reinforcement Learning Estimators <https://sagemaker.readthedocs.io/en/stable/using_rl.html>`__
46
+ #. `SageMaker SparkML Serving <#sagemaker-sparkml-serving>`__
47
+ #. `Amazon SageMaker Built-in Algorithm Estimators <src/sagemaker/amazon/README.rst>`__
48
+ #. `Using SageMaker AlgorithmEstimators <https://sagemaker.readthedocs.io/en/stable/overview.html#using-sagemaker-algorithmestimators>`__
49
+ #. `Consuming SageMaker Model Packages <https://sagemaker.readthedocs.io/en/stable/overview.html#consuming-sagemaker-model-packages>`__
50
+ #. `BYO Docker Containers with SageMaker Estimators <https://sagemaker.readthedocs.io/en/stable/overview.html#byo-docker-containers-with-sagemaker-estimators>`__
51
+ #. `SageMaker Automatic Model Tuning <https://sagemaker.readthedocs.io/en/stable/overview.html#sagemaker-automatic-model-tuning>`__
52
+ #. `SageMaker Batch Transform <https://sagemaker.readthedocs.io/en/stable/overview.html#sagemaker-batch-transform>`__
53
+ #. `Secure Training and Inference with VPC <https://sagemaker.readthedocs.io/en/stable/overview.html#secure-training-and-inference-with-vpc>`__
54
+ #. `BYO Model <https://sagemaker.readthedocs.io/en/stable/overview.html#byo-model>`__
55
+ #. `Inference Pipelines <https://sagemaker.readthedocs.io/en/stable/overview.html#inference-pipelines>`__
56
+ #. `Amazon SageMaker Operators in Apache Airflow <https://sagemaker.readthedocs.io/en/stable/using_workflow.html>`__
57
+ #. `SageMaker Autopilot <src/sagemaker/automl/README.rst>`__
58
+ #. `Model Monitoring <https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_monitoring.html>`__
59
+ #. `SageMaker Debugger <https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html>`__
60
+ #. `SageMaker Processing <https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_processing.html>`__
61
+
62
+
63
+ Installing the SageMaker Python SDK
64
+ -----------------------------------
65
+
66
+ The SageMaker Python SDK is built to PyPI and can be installed with pip as follows:
67
+
68
+ ::
69
+
70
+ pip install sagemaker
71
+
72
+ You can install from source by cloning this repository and running a pip install command in the root directory of the repository:
73
+
74
+ ::
75
+
76
+ git clone https://github.com/aws/sagemaker-python-sdk.git
77
+ cd sagemaker-python-sdk
78
+ pip install .
79
+
80
+ Supported Operating Systems
81
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
82
+
83
+ SageMaker Python SDK supports Unix/Linux and Mac.
84
+
85
+ Supported Python Versions
86
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
87
+
88
+ SageMaker Python SDK is tested on:
89
+
90
+ - Python 3.7
91
+ - Python 3.8
92
+ - Python 3.9
93
+ - Python 3.10
94
+
95
+ AWS Permissions
96
+ ~~~~~~~~~~~~~~~
97
+
98
+ As a managed service, Amazon SageMaker performs operations on your behalf on the AWS hardware that is managed by Amazon SageMaker.
99
+ Amazon SageMaker can perform only operations that the user permits.
100
+ You can read more about which permissions are necessary in the `AWS Documentation <https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html>`__.
101
+
102
+ The SageMaker Python SDK should not require any additional permissions aside from what is required for using SageMaker.
103
+ However, if you are using an IAM role with a path in it, you should grant permission for ``iam:GetRole``.
104
+
105
+ Licensing
106
+ ~~~~~~~~~
107
+ SageMaker Python SDK is licensed under the Apache 2.0 License. It is copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. The license is available at:
108
+ http://aws.amazon.com/apache2.0/
109
+
110
+ Running tests
111
+ ~~~~~~~~~~~~~
112
+
113
+ SageMaker Python SDK has unit tests and integration tests.
114
+
115
+ You can install the libraries needed to run the tests by running :code:`pip install --upgrade .[test]` or, for Zsh users: :code:`pip install --upgrade .\[test\]`
116
+
117
+ **Unit tests**
118
+
119
+ We run unit tests with tox, which is a program that lets you run unit tests for multiple Python versions, and also make sure the
120
+ code fits our style guidelines. We run tox with `all of our supported Python versions <#supported-python-versions>`_, so to run unit tests
121
+ with the same configuration we do, you need to have interpreters for those Python versions installed.
122
+
123
+ To run the unit tests with tox, run:
124
+
125
+ ::
126
+
127
+ tox tests/unit
128
+
129
+ **Integrations tests**
130
+
131
+ To run the integration tests, the following prerequisites must be met
132
+
133
+ 1. AWS account credentials are available in the environment for the boto3 client to use.
134
+ 2. The AWS account has an IAM role named :code:`SageMakerRole`.
135
+ It should have the AmazonSageMakerFullAccess policy attached as well as a policy with `the necessary permissions to use Elastic Inference <https://docs.aws.amazon.com/sagemaker/latest/dg/ei-setup.html>`__.
136
+
137
+ We recommend selectively running just those integration tests you'd like to run. You can filter by individual test function names with:
138
+
139
+ ::
140
+
141
+ tox -- -k 'test_i_care_about'
142
+
143
+
144
+ You can also run all of the integration tests by running the following command, which runs them in sequence, which may take a while:
145
+
146
+ ::
147
+
148
+ tox -- tests/integ
149
+
150
+
151
+ You can also run them in parallel:
152
+
153
+ ::
154
+
155
+ tox -- -n auto tests/integ
156
+
157
+
158
+ Git Hooks
159
+ ~~~~~~~~~
160
+
161
+ to enable all git hooks in the .githooks directory, run these commands in the repository directory:
162
+
163
+ ::
164
+
165
+ find .git/hooks -type l -exec rm {} \;
166
+ find .githooks -type f -exec ln -sf ../../{} .git/hooks/ \;
167
+
168
+ To enable an individual git hook, simply move it from the .githooks/ directory to the .git/hooks/ directory.
169
+
170
+ Building Sphinx docs
171
+ ~~~~~~~~~~~~~~~~~~~~
172
+
173
+ Setup a Python environment, and install the dependencies listed in ``doc/requirements.txt``:
174
+
175
+ ::
176
+
177
+ # conda
178
+ conda create -n sagemaker python=3.7
179
+ conda activate sagemaker
180
+ conda install sphinx=3.1.1 sphinx_rtd_theme=0.5.0
181
+
182
+ # pip
183
+ pip install -r doc/requirements.txt
184
+
185
+
186
+ Clone/fork the repo, and install your local version:
187
+
188
+ ::
189
+
190
+ pip install --upgrade .
191
+
192
+ Then ``cd`` into the ``sagemaker-python-sdk/doc`` directory and run:
193
+
194
+ ::
195
+
196
+ make html
197
+
198
+ You can edit the templates for any of the pages in the docs by editing the .rst files in the ``doc`` directory and then running ``make html`` again.
199
+
200
+ Preview the site with a Python web server:
201
+
202
+ ::
203
+
204
+ cd _build/html
205
+ python -m http.server 8000
206
+
207
+ View the website by visiting http://localhost:8000
208
+
209
+ SageMaker SparkML Serving
210
+ -------------------------
211
+
212
+ With SageMaker SparkML Serving, you can now perform predictions against a SparkML Model in SageMaker.
213
+ In order to host a SparkML model in SageMaker, it should be serialized with ``MLeap`` library.
214
+
215
+ For more information on MLeap, see https://github.com/combust/mleap .
216
+
217
+ Supported major version of Spark: 2.4 (MLeap version - 0.9.6)
218
+
219
+ Here is an example on how to create an instance of ``SparkMLModel`` class and use ``deploy()`` method to create an
220
+ endpoint which can be used to perform prediction against your trained SparkML Model.
221
+
222
+ .. code:: python
223
+
224
+ sparkml_model = SparkMLModel(model_data='s3://path/to/model.tar.gz', env={'SAGEMAKER_SPARKML_SCHEMA': schema})
225
+ model_name = 'sparkml-model'
226
+ endpoint_name = 'sparkml-endpoint'
227
+ predictor = sparkml_model.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge', endpoint_name=endpoint_name)
228
+
229
+ Once the model is deployed, we can invoke the endpoint with a ``CSV`` payload like this:
230
+
231
+ .. code:: python
232
+
233
+ payload = 'field_1,field_2,field_3,field_4,field_5'
234
+ predictor.predict(payload)
235
+
236
+
237
+ For more information about the different ``content-type`` and ``Accept`` formats as well as the structure of the
238
+ ``schema`` that SageMaker SparkML Serving recognizes, please see `SageMaker SparkML Serving Container`_.
239
+
240
+ .. _SageMaker SparkML Serving Container: https://github.com/aws/sagemaker-sparkml-serving-container
testbed/aws__sagemaker-python-sdk/VERSION ADDED
@@ -0,0 +1 @@
 
 
1
+ 2.113.1.dev0
testbed/aws__sagemaker-python-sdk/mypy.ini ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [mypy]
2
+ ignore_missing_imports = True
testbed/aws__sagemaker-python-sdk/setup.cfg ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Test args for pytest; disable stdout capturing by default.
2
+ [tool:pytest]
3
+ addopts =
4
+ -vv
5
+ testpaths = tests
6
+
7
+ [aliases]
8
+ test=pytest
9
+
10
+ [metadata]
11
+ description-file = README.rst
12
+ license_file = LICENSE.txt
13
+
14
+ [wheel]
15
+ universal = 1
testbed/aws__sagemaker-python-sdk/setup.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ import os
17
+ from glob import glob
18
+
19
+ from setuptools import find_packages, setup
20
+
21
+
22
+ def read(fname):
23
+ """
24
+ Args:
25
+ fname:
26
+ """
27
+ return open(os.path.join(os.path.dirname(__file__), fname)).read()
28
+
29
+
30
+ def read_version():
31
+ return read("VERSION").strip()
32
+
33
+
34
+ def read_requirements(filename):
35
+ """Reads requirements file which lists package dependencies.
36
+
37
+ Args:
38
+ filename: type(str) Relative file path of requirements.txt file
39
+
40
+ Returns:
41
+ list of dependencies extracted from file
42
+ """
43
+ with open(os.path.abspath(filename)) as fp:
44
+ deps = [line.strip() for line in fp.readlines()]
45
+ return deps
46
+
47
+
48
+ # Declare minimal set for installation
49
+ required_packages = [
50
+ "attrs>=20.3.0,<23",
51
+ "boto3>=1.20.21,<2.0",
52
+ "google-pasta",
53
+ "numpy>=1.9.0,<2.0",
54
+ "protobuf>=3.1,<4.0",
55
+ "protobuf3-to-dict>=0.1.5,<1.0",
56
+ "smdebug_rulesconfig==1.0.1",
57
+ "importlib-metadata>=1.4.0,<5.0",
58
+ "packaging>=20.0",
59
+ "pandas",
60
+ "pathos",
61
+ "schema",
62
+ ]
63
+
64
+ # Specific use case dependencies
65
+ # Keep format of *_requirements.txt to be tracked by dependabot
66
+ extras = {
67
+ "local": read_requirements("requirements/extras/local_requirements.txt"),
68
+ "scipy": read_requirements("requirements/extras/scipy_requirements.txt"),
69
+ }
70
+ # Meta dependency groups
71
+ extras["all"] = [item for group in extras.values() for item in group]
72
+ # Tests specific dependencies (do not need to be included in 'all')
73
+ extras["test"] = (extras["all"] + read_requirements("requirements/extras/test_requirements.txt"),)
74
+
75
+ setup(
76
+ name="sagemaker",
77
+ version=read_version(),
78
+ description="Open source library for training and deploying models on Amazon SageMaker.",
79
+ packages=find_packages("src"),
80
+ package_dir={"": "src"},
81
+ py_modules=[os.path.splitext(os.path.basename(path))[0] for path in glob("src/*.py")],
82
+ include_package_data=True,
83
+ long_description=read("README.rst"),
84
+ author="Amazon Web Services",
85
+ url="https://github.com/aws/sagemaker-python-sdk/",
86
+ license="Apache License 2.0",
87
+ keywords="ML Amazon AWS AI Tensorflow MXNet",
88
+ python_requires=">= 3.6",
89
+ classifiers=[
90
+ "Development Status :: 5 - Production/Stable",
91
+ "Intended Audience :: Developers",
92
+ "Natural Language :: English",
93
+ "License :: OSI Approved :: Apache Software License",
94
+ "Programming Language :: Python",
95
+ "Programming Language :: Python :: 3.7",
96
+ "Programming Language :: Python :: 3.8",
97
+ "Programming Language :: Python :: 3.9",
98
+ "Programming Language :: Python :: 3.10",
99
+ ],
100
+ install_requires=required_packages,
101
+ extras_require=extras,
102
+ entry_points={
103
+ "console_scripts": [
104
+ "sagemaker-upgrade-v2=sagemaker.cli.compatibility.v2.sagemaker_upgrade_v2:main",
105
+ ]
106
+ },
107
+ )
testbed/aws__sagemaker-python-sdk/src/sagemaker/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ import importlib_metadata
17
+
18
+ from sagemaker import estimator, parameter, tuner # noqa: F401
19
+ from sagemaker.amazon.kmeans import KMeans, KMeansModel, KMeansPredictor # noqa: F401
20
+ from sagemaker.amazon.pca import PCA, PCAModel, PCAPredictor # noqa: F401
21
+ from sagemaker.amazon.lda import LDA, LDAModel, LDAPredictor # noqa: F401
22
+ from sagemaker.amazon.linear_learner import ( # noqa: F401
23
+ LinearLearner,
24
+ LinearLearnerModel,
25
+ LinearLearnerPredictor,
26
+ )
27
+ from sagemaker.amazon.factorization_machines import ( # noqa: F401
28
+ FactorizationMachines,
29
+ FactorizationMachinesModel,
30
+ )
31
+ from sagemaker.amazon.factorization_machines import FactorizationMachinesPredictor # noqa: F401
32
+ from sagemaker.inputs import TrainingInput # noqa: F401
33
+ from sagemaker.amazon.ntm import NTM, NTMModel, NTMPredictor # noqa: F401
34
+ from sagemaker.amazon.randomcutforest import ( # noqa: F401
35
+ RandomCutForest,
36
+ RandomCutForestModel,
37
+ RandomCutForestPredictor,
38
+ )
39
+ from sagemaker.amazon.knn import KNN, KNNModel, KNNPredictor # noqa: F401
40
+ from sagemaker.amazon.object2vec import Object2Vec, Object2VecModel # noqa: F401
41
+ from sagemaker.amazon.ipinsights import ( # noqa: F401
42
+ IPInsights,
43
+ IPInsightsModel,
44
+ IPInsightsPredictor,
45
+ )
46
+
47
+ from sagemaker.algorithm import AlgorithmEstimator # noqa: F401
48
+ from sagemaker.analytics import TrainingJobAnalytics, HyperparameterTuningJobAnalytics # noqa: F401
49
+ from sagemaker.local.local_session import LocalSession # noqa: F401
50
+
51
+ from sagemaker.model import Model, ModelPackage # noqa: F401
52
+ from sagemaker.model_metrics import ModelMetrics, MetricsSource, FileSource # noqa: F401
53
+ from sagemaker.pipeline import PipelineModel # noqa: F401
54
+ from sagemaker.predictor import Predictor # noqa: F401
55
+ from sagemaker.processing import Processor, ScriptProcessor # noqa: F401
56
+ from sagemaker.session import Session # noqa: F401
57
+ from sagemaker.session import container_def, pipeline_container_def # noqa: F401
58
+ from sagemaker.session import get_model_package_args # noqa: F401
59
+ from sagemaker.session import production_variant # noqa: F401
60
+ from sagemaker.session import get_execution_role # noqa: F401
61
+
62
+ from sagemaker.automl.automl import AutoML, AutoMLJob, AutoMLInput # noqa: F401
63
+ from sagemaker.automl.candidate_estimator import CandidateEstimator, CandidateStep # noqa: F401
64
+
65
+ __version__ = importlib_metadata.version("sagemaker")
testbed/aws__sagemaker-python-sdk/src/sagemaker/_studio.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Provides internal tooling for studio environments."""
14
+ from __future__ import absolute_import
15
+
16
+ import json
17
+ import logging
18
+
19
+ from pathlib import Path
20
+
21
+ STUDIO_PROJECT_CONFIG = ".sagemaker-code-config"
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def _append_project_tags(tags=None, working_dir=None):
27
+ """Appends the project tag to the list of tags, if it exists.
28
+
29
+ Args:
30
+ working_dir: the working directory to start looking.
31
+ tags: the list of tags to append to.
32
+
33
+ Returns:
34
+ A possibly extended list of tags that includes the project id.
35
+ """
36
+ path = _find_config(working_dir)
37
+ if path is None:
38
+ return tags
39
+
40
+ config = _load_config(path)
41
+ if config is None:
42
+ return tags
43
+
44
+ additional_tags = _parse_tags(config)
45
+ if additional_tags is None:
46
+ return tags
47
+
48
+ all_tags = tags or []
49
+ additional_tags = [tag for tag in additional_tags if tag not in all_tags]
50
+ all_tags.extend(additional_tags)
51
+
52
+ return all_tags
53
+
54
+
55
+ def _find_config(working_dir=None):
56
+ """Gets project config on SageMaker Studio platforms, if it exists.
57
+
58
+ Args:
59
+ working_dir: the working directory to start looking.
60
+
61
+ Returns:
62
+ The project config path, if it exists. Otherwise None.
63
+ """
64
+ try:
65
+ wd = Path(working_dir) if working_dir else Path.cwd()
66
+
67
+ path = None
68
+ while path is None and not wd.match("/"):
69
+ candidate = wd / STUDIO_PROJECT_CONFIG
70
+ if Path.exists(candidate):
71
+ path = candidate
72
+ wd = wd.parent
73
+
74
+ return path
75
+ except Exception as e: # pylint: disable=W0703
76
+ logger.debug("Could not find the studio project config. %s", e)
77
+
78
+
79
+ def _load_config(path):
80
+ """Parse out the projectId attribute if it exists at path.
81
+
82
+ Args:
83
+ path: path to project config
84
+
85
+ Returns:
86
+ Project config Json, or None if it does not exist.
87
+ """
88
+ try:
89
+ with open(path, "r") as f:
90
+ content = f.read().strip()
91
+ config = json.loads(content)
92
+
93
+ return config
94
+ except Exception as e: # pylint: disable=W0703
95
+ logger.debug("Could not load project config. %s", e)
96
+
97
+
98
+ def _parse_tags(config):
99
+ """Parse out appropriate attributes and formats as tags.
100
+
101
+ Args:
102
+ config: project config dict
103
+
104
+ Returns:
105
+ List of tags
106
+ """
107
+ try:
108
+ return [
109
+ {"Key": "sagemaker:project-id", "Value": config["sagemakerProjectId"]},
110
+ {"Key": "sagemaker:project-name", "Value": config["sagemakerProjectName"]},
111
+ ]
112
+ except Exception as e: # pylint: disable=W0703
113
+ logger.debug("Could not parse project config. %s", e)
testbed/aws__sagemaker-python-sdk/src/sagemaker/algorithm.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Test docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import Optional, Union, Dict, List
17
+
18
+ import sagemaker
19
+ import sagemaker.parameter
20
+ from sagemaker import vpc_utils
21
+ from sagemaker.deserializers import BytesDeserializer
22
+ from sagemaker.deprecations import removed_kwargs
23
+ from sagemaker.estimator import EstimatorBase
24
+ from sagemaker.inputs import TrainingInput, FileSystemInput
25
+ from sagemaker.serializers import IdentitySerializer
26
+ from sagemaker.transformer import Transformer
27
+ from sagemaker.predictor import Predictor
28
+ from sagemaker.session import Session
29
+ from sagemaker.workflow.entities import PipelineVariable
30
+
31
+ from sagemaker.workflow import is_pipeline_variable
32
+
33
+
34
+ class AlgorithmEstimator(EstimatorBase):
35
+ """A generic Estimator to train using any algorithm object (with an ``algorithm_arn``).
36
+
37
+ The Algorithm can be your own, or any Algorithm from AWS
38
+ Marketplace that you have a valid subscription for. This class will perform
39
+ client-side validation on all the inputs.
40
+ """
41
+
42
+ # These Hyperparameter Types have a range definition.
43
+ _hyperpameters_with_range = ("Integer", "Continuous", "Categorical")
44
+
45
+ def __init__(
46
+ self,
47
+ algorithm_arn: str,
48
+ role: str,
49
+ instance_count: Optional[Union[int, PipelineVariable]] = None,
50
+ instance_type: Optional[Union[str, PipelineVariable]] = None,
51
+ volume_size: Union[int, PipelineVariable] = 30,
52
+ volume_kms_key: Optional[Union[str, PipelineVariable]] = None,
53
+ max_run: Union[int, PipelineVariable] = 24 * 60 * 60,
54
+ input_mode: Union[str, PipelineVariable] = "File",
55
+ output_path: Optional[Union[str, PipelineVariable]] = None,
56
+ output_kms_key: Optional[Union[str, PipelineVariable]] = None,
57
+ base_job_name: Optional[str] = None,
58
+ sagemaker_session: Optional[Session] = None,
59
+ hyperparameters: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
60
+ tags: Optional[List[Dict[str, Union[str, PipelineVariable]]]] = None,
61
+ subnets: Optional[List[Union[str, PipelineVariable]]] = None,
62
+ security_group_ids: Optional[List[Union[str, PipelineVariable]]] = None,
63
+ model_uri: Optional[str] = None,
64
+ model_channel_name: Union[str, PipelineVariable] = "model",
65
+ metric_definitions: Optional[List[Dict[str, Union[str, PipelineVariable]]]] = None,
66
+ encrypt_inter_container_traffic: Union[bool, PipelineVariable] = False,
67
+ use_spot_instances: Union[bool, PipelineVariable] = False,
68
+ max_wait: Optional[Union[int, PipelineVariable]] = None,
69
+ **kwargs # pylint: disable=W0613
70
+ ):
71
+ """Initialize an ``AlgorithmEstimator`` instance.
72
+
73
+ Args:
74
+ algorithm_arn (str): algorithm arn used for training. Can be just the name if your
75
+ account owns the algorithm.
76
+ role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker
77
+ training jobs and APIsthat create Amazon SageMaker endpoints use this role to
78
+ access training data and model artifacts. After the endpoint
79
+ is created, the inference code might use the IAM role, if it
80
+ needs to access an AWS resource.
81
+ instance_count (int or PipelineVariable): Number of Amazon EC2 instances to use
82
+ for training.
83
+ instance_type (str or PipelineVariable): Type of EC2 instance to use for training,
84
+ for example, 'ml.c4.xlarge'.
85
+ volume_size (int or PipelineVariable): Size in GB of the EBS volume to use for
86
+ storing input data during training (default: 30). Must be large enough to store
87
+ training data if File Mode is used (which is the default).
88
+ volume_kms_key (str or PipelineVariable): Optional. KMS key ID for encrypting
89
+ EBS volume attached to the training instance (default: None).
90
+ max_run (int or PipelineVariable): Timeout in seconds for training
91
+ (default: 24 * 60 * 60).
92
+ After this amount of time Amazon SageMaker terminates the
93
+ job regardless of its current status.
94
+ input_mode (str or PipelineVariable): The input mode that the algorithm supports
95
+ (default: 'File'). Valid modes:
96
+
97
+ * 'File' - Amazon SageMaker copies the training dataset from
98
+ the S3 location to a local directory.
99
+ * 'Pipe' - Amazon SageMaker streams data directly from S3 to
100
+ the container via a Unix-named pipe.
101
+
102
+ This argument can be overriden on a per-channel basis using
103
+ ``sagemaker.inputs.TrainingInput.input_mode``.
104
+
105
+ output_path (str or PipelineVariable): S3 location for saving the training result
106
+ (model artifacts and output files). If not specified,
107
+ results are stored to a default bucket. If
108
+ the bucket with the specific name does not exist, the
109
+ estimator creates the bucket during the
110
+ :meth:`~sagemaker.estimator.EstimatorBase.fit` method
111
+ execution.
112
+ output_kms_key (str or PipelineVariable): Optional. KMS key ID for encrypting the
113
+ training output (default: None). base_job_name (str): Prefix for
114
+ training job name when the
115
+ :meth:`~sagemaker.estimator.EstimatorBase.fit`
116
+ method launches. If not specified, the estimator generates a
117
+ default job name, based on the training image name and
118
+ current timestamp.
119
+ sagemaker_session (sagemaker.session.Session): Session object which manages
120
+ interactions with Amazon SageMaker APIs and any other AWS services needed. If
121
+ not specified, the estimator creates one using the default
122
+ AWS configuration chain.
123
+ tags (list[dict[str, str] or list[dict[str, PipelineVariable]]): List of tags for
124
+ labeling a training job. For more, see
125
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
126
+ subnets (list[str] or list[PipelineVariable]): List of subnet ids. If not specified
127
+ training job will be created without VPC config.
128
+ security_group_ids (list[str]): List of security group ids. If
129
+ not specified training job will be created without VPC config.
130
+ model_uri (str): URI where a pre-trained model is stored, either locally or in S3
131
+ (default: None). If specified, the estimator will create a channel pointing to
132
+ the model so the training job can download it. This model
133
+ can be a 'model.tar.gz' from a previous training job, or
134
+ other artifacts coming from a different source.
135
+ More information:
136
+ https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html#td-deserialization
137
+ model_channel_name (str or PipelineVariable): Name of the channel where 'model_uri'
138
+ will be downloaded (default: 'model'). metric_definitions
139
+ (list[dict]): A list of dictionaries that defines the metric(s)
140
+ used to evaluate the training jobs. Each dictionary contains two keys: 'Name' for
141
+ the name of the metric, and 'Regex' for the regular
142
+ expression used to extract the metric from the logs.
143
+ encrypt_inter_container_traffic (bool or PipelineVariable): Specifies whether traffic
144
+ between training containers is encrypted for the training job (default: ``False``).
145
+ use_spot_instances (bool or PipelineVariable): Specifies whether to use SageMaker
146
+ Managed Spot instances for training. If enabled then the
147
+ `max_wait` arg should also be set.
148
+
149
+ More information:
150
+ https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html
151
+ (default: ``False``).
152
+ max_wait (int or PipelineVariable): Timeout in seconds waiting for spot training
153
+ instances (default: None). After this amount of time Amazon
154
+ SageMaker will stop waiting for Spot instances to become
155
+ available (default: ``None``).
156
+ **kwargs: Additional kwargs. This is unused. It's only added for AlgorithmEstimator
157
+ to ignore the irrelevant arguments.
158
+ """
159
+ self.algorithm_arn = algorithm_arn
160
+ super(AlgorithmEstimator, self).__init__(
161
+ role,
162
+ instance_count=instance_count,
163
+ instance_type=instance_type,
164
+ volume_size=volume_size,
165
+ volume_kms_key=volume_kms_key,
166
+ max_run=max_run,
167
+ input_mode=input_mode,
168
+ output_path=output_path,
169
+ output_kms_key=output_kms_key,
170
+ base_job_name=base_job_name,
171
+ sagemaker_session=sagemaker_session,
172
+ tags=tags,
173
+ subnets=subnets,
174
+ security_group_ids=security_group_ids,
175
+ model_uri=model_uri,
176
+ model_channel_name=model_channel_name,
177
+ metric_definitions=metric_definitions,
178
+ encrypt_inter_container_traffic=encrypt_inter_container_traffic,
179
+ use_spot_instances=use_spot_instances,
180
+ max_wait=max_wait,
181
+ )
182
+
183
+ self.algorithm_spec = self.sagemaker_session.sagemaker_client.describe_algorithm(
184
+ AlgorithmName=algorithm_arn
185
+ )
186
+ self.validate_train_spec()
187
+ self.hyperparameter_definitions = self._parse_hyperparameters()
188
+
189
+ self._hyperparameters = {}
190
+ if hyperparameters:
191
+ self.set_hyperparameters(**hyperparameters)
192
+
193
+ def validate_train_spec(self):
194
+ """Placeholder docstring"""
195
+ train_spec = self.algorithm_spec["TrainingSpecification"]
196
+ algorithm_name = self.algorithm_spec["AlgorithmName"]
197
+
198
+ # Check that the input mode provided is compatible with the training input modes for the
199
+ # algorithm.
200
+ input_modes = self._algorithm_training_input_modes(train_spec["TrainingChannels"])
201
+ if not is_pipeline_variable(self.input_mode) and self.input_mode not in input_modes:
202
+ raise ValueError(
203
+ "Invalid input mode: %s. %s only supports: %s"
204
+ % (self.input_mode, algorithm_name, input_modes)
205
+ )
206
+
207
+ # Check that the training instance type is compatible with the algorithm.
208
+ supported_instances = train_spec["SupportedTrainingInstanceTypes"]
209
+ if (
210
+ not is_pipeline_variable(self.instance_type)
211
+ and self.instance_type not in supported_instances
212
+ ):
213
+ raise ValueError(
214
+ "Invalid instance_type: %s. %s supports the following instance types: %s"
215
+ % (self.instance_type, algorithm_name, supported_instances)
216
+ )
217
+
218
+ # Verify if distributed training is supported by the algorithm
219
+ if not is_pipeline_variable(self.instance_count) and (
220
+ self.instance_count > 1
221
+ and "SupportsDistributedTraining" in train_spec
222
+ and not train_spec["SupportsDistributedTraining"]
223
+ ):
224
+ raise ValueError(
225
+ "Distributed training is not supported by %s. "
226
+ "Please set instance_count=1" % algorithm_name
227
+ )
228
+
229
+ def set_hyperparameters(self, **kwargs):
230
+ """Placeholder docstring"""
231
+ for k, v in kwargs.items():
232
+ value = self._validate_and_cast_hyperparameter(k, v)
233
+ self._hyperparameters[k] = value
234
+
235
+ self._validate_and_set_default_hyperparameters()
236
+
237
+ def hyperparameters(self):
238
+ """Returns the hyperparameters as a dictionary to use for training.
239
+
240
+ The fit() method, that does the model training, calls this method to
241
+ find the hyperparameters you specified.
242
+ """
243
+ return self._hyperparameters
244
+
245
+ def training_image_uri(self):
246
+ """Returns the docker image to use for training.
247
+
248
+ The fit() method, that does the model training, calls this method to
249
+ find the image to use for model training.
250
+ """
251
+ raise RuntimeError("training_image_uri is never meant to be called on Algorithm Estimators")
252
+
253
+ def enable_network_isolation(self):
254
+ """Return True if this Estimator will need network isolation to run.
255
+
256
+ On Algorithm Estimators this depends on the algorithm being used. If
257
+ this is algorithm owned by your account it will be False. If this is an
258
+ an algorithm consumed from Marketplace it will be True.
259
+
260
+ Returns:
261
+ bool: Whether this Estimator needs network isolation or not.
262
+ """
263
+ return self._is_marketplace()
264
+
265
+ def create_model(
266
+ self,
267
+ role=None,
268
+ predictor_cls=None,
269
+ serializer=IdentitySerializer(),
270
+ deserializer=BytesDeserializer(),
271
+ vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT,
272
+ **kwargs
273
+ ):
274
+ """Create a model to deploy.
275
+
276
+ The serializer and deserializer are only used to define a default
277
+ Predictor. They are ignored if an explicit predictor class is passed in.
278
+ Other arguments are passed through to the Model class.
279
+
280
+ Args:
281
+ role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``,
282
+ which is also used during transform jobs. If not specified, the
283
+ role from the Estimator will be used.
284
+ predictor_cls (Predictor): The predictor class to use when
285
+ deploying the model.
286
+ serializer (:class:`~sagemaker.serializers.BaseSerializer`): A
287
+ serializer object, used to encode data for an inference endpoint
288
+ (default: :class:`~sagemaker.serializers.IdentitySerializer`).
289
+ deserializer (:class:`~sagemaker.deserializers.BaseDeserializer`): A
290
+ deserializer object, used to decode data from an inference
291
+ endpoint (default: :class:`~sagemaker.deserializers.BytesDeserializer`).
292
+ vpc_config_override (dict[str, list[str]]): Optional override for VpcConfig set on
293
+ the model. Default: use subnets and security groups from this Estimator.
294
+ * 'Subnets' (list[str]): List of subnet ids.
295
+ * 'SecurityGroupIds' (list[str]): List of security group ids.
296
+ **kwargs: Additional arguments for creating a :class:`~sagemaker.model.ModelPackage`.
297
+
298
+ .. tip::
299
+
300
+ You can find additional parameters for using this method at
301
+ :class:`~sagemaker.model.ModelPackage` and
302
+ :class:`~sagemaker.model.Model`.
303
+
304
+ Returns:
305
+ a Model ready for deployment.
306
+ """
307
+ removed_kwargs("content_type", kwargs)
308
+ removed_kwargs("accept", kwargs)
309
+
310
+ if predictor_cls is None:
311
+
312
+ def predict_wrapper(endpoint, session):
313
+ return Predictor(endpoint, session, serializer, deserializer)
314
+
315
+ predictor_cls = predict_wrapper
316
+
317
+ role = role or self.role
318
+
319
+ return sagemaker.ModelPackage(
320
+ role,
321
+ algorithm_arn=self.algorithm_arn,
322
+ model_data=self.model_data,
323
+ vpc_config=self.get_vpc_config(vpc_config_override),
324
+ sagemaker_session=self.sagemaker_session,
325
+ predictor_cls=predictor_cls,
326
+ **kwargs
327
+ )
328
+
329
+ def transformer(
330
+ self,
331
+ instance_count,
332
+ instance_type,
333
+ strategy=None,
334
+ assemble_with=None,
335
+ output_path=None,
336
+ output_kms_key=None,
337
+ accept=None,
338
+ env=None,
339
+ max_concurrent_transforms=None,
340
+ max_payload=None,
341
+ tags=None,
342
+ role=None,
343
+ volume_kms_key=None,
344
+ ):
345
+ """Return a ``Transformer`` that uses a SageMaker Model based on the training job.
346
+
347
+ It reuses the SageMaker Session and base job name used by the Estimator.
348
+
349
+ Args:
350
+ instance_count (int): Number of EC2 instances to use.
351
+ instance_type (str): Type of EC2 instance to use, for example,
352
+ 'ml.c4.xlarge'.
353
+ strategy (str): The strategy used to decide how to batch records in
354
+ a single request (default: None). Valid values: 'MultiRecord'
355
+ and 'SingleRecord'.
356
+ assemble_with (str): How the output is assembled (default: None).
357
+ Valid values: 'Line' or 'None'.
358
+ output_path (str): S3 location for saving the transform result. If
359
+ not specified, results are stored to a default bucket.
360
+ output_kms_key (str): Optional. KMS key ID for encrypting the
361
+ transform output (default: None).
362
+ accept (str): The accept header passed by the client to
363
+ the inference endpoint. If it is supported by the endpoint,
364
+ it will be the format of the batch transform output.
365
+ env (dict): Environment variables to be set for use during the
366
+ transform job (default: None).
367
+ max_concurrent_transforms (int): The maximum number of HTTP requests
368
+ to be made to each individual transform container at one time.
369
+ max_payload (int): Maximum size of the payload in a single HTTP
370
+ request to the container in MB.
371
+ tags (list[dict]): List of tags for labeling a transform job. If
372
+ none specified, then the tags used for the training job are used
373
+ for the transform job.
374
+ role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``,
375
+ which is also used during transform jobs. If not specified, the
376
+ role from the Estimator will be used.
377
+ volume_kms_key (str): Optional. KMS key ID for encrypting the volume
378
+ attached to the ML compute instance (default: None).
379
+ """
380
+ role = role or self.role
381
+
382
+ if self.latest_training_job is not None:
383
+ model = self.create_model(role=role)
384
+ model._create_sagemaker_model()
385
+ model_name = model.name
386
+ transform_env = {}
387
+ if env is not None:
388
+ transform_env = model.env.copy()
389
+ transform_env.update(env)
390
+ if self._is_marketplace():
391
+ transform_env = None
392
+
393
+ tags = tags or self.tags
394
+ else:
395
+ raise RuntimeError("No finished training job found associated with this estimator")
396
+
397
+ return Transformer(
398
+ model_name,
399
+ instance_count,
400
+ instance_type,
401
+ strategy=strategy,
402
+ assemble_with=assemble_with,
403
+ output_path=output_path,
404
+ output_kms_key=output_kms_key,
405
+ accept=accept,
406
+ max_concurrent_transforms=max_concurrent_transforms,
407
+ max_payload=max_payload,
408
+ env=transform_env,
409
+ tags=tags,
410
+ base_transform_job_name=self.base_job_name,
411
+ volume_kms_key=volume_kms_key,
412
+ sagemaker_session=self.sagemaker_session,
413
+ )
414
+
415
+ def _is_marketplace(self):
416
+ """Placeholder docstring"""
417
+ return "ProductId" in self.algorithm_spec
418
+
419
+ def _ensure_base_job_name(self):
420
+ """Set ``self.base_job_name`` if it is not set already."""
421
+ if self.base_job_name is None:
422
+ self.base_job_name = self.algorithm_arn.split("/")[-1]
423
+
424
+ def _prepare_for_training(self, job_name=None):
425
+ # Validate hyperparameters
426
+ # an explicit call to set_hyperparameters() will also validate the hyperparameters
427
+ # but it is possible that the user never called it.
428
+ self._validate_and_set_default_hyperparameters()
429
+
430
+ super(AlgorithmEstimator, self)._prepare_for_training(job_name)
431
+
432
+ def fit(
433
+ self,
434
+ inputs: Optional[Union[str, Dict, TrainingInput, FileSystemInput]] = None,
435
+ wait: bool = True,
436
+ logs: bool = True,
437
+ job_name: Optional[str] = None,
438
+ ):
439
+ """Placeholder docstring"""
440
+ if inputs:
441
+ self._validate_input_channels(inputs)
442
+
443
+ return super(AlgorithmEstimator, self).fit(inputs, wait, logs, job_name)
444
+
445
+ def _validate_input_channels(self, channels):
446
+ """Placeholder docstring"""
447
+ train_spec = self.algorithm_spec["TrainingSpecification"]
448
+ algorithm_name = self.algorithm_spec["AlgorithmName"]
449
+ training_channels = {c["Name"]: c for c in train_spec["TrainingChannels"]}
450
+
451
+ # check for unknown channels that the algorithm does not support
452
+ for c in channels:
453
+ if c not in training_channels:
454
+ raise ValueError(
455
+ "Unknown input channel: %s is not supported by: %s" % (c, algorithm_name)
456
+ )
457
+
458
+ # check for required channels that were not provided
459
+ for name, channel in training_channels.items():
460
+ if name not in channels and "IsRequired" in channel and channel["IsRequired"]:
461
+ raise ValueError("Required input channel: %s Was not provided." % (name))
462
+
463
+ def _validate_and_cast_hyperparameter(self, name, v):
464
+ """Placeholder docstring"""
465
+ algorithm_name = self.algorithm_spec["AlgorithmName"]
466
+
467
+ if name not in self.hyperparameter_definitions:
468
+ raise ValueError(
469
+ "Invalid hyperparameter: %s is not supported by %s" % (name, algorithm_name)
470
+ )
471
+
472
+ definition = self.hyperparameter_definitions[name]
473
+ if "class" in definition:
474
+ value = definition["class"].cast_to_type(v)
475
+ else:
476
+ value = v
477
+
478
+ if "range" in definition and not definition["range"].is_valid(value):
479
+ valid_range = definition["range"].as_tuning_range(name)
480
+ raise ValueError("Invalid value: %s Supported range: %s" % (value, valid_range))
481
+ return value
482
+
483
+ def _validate_and_set_default_hyperparameters(self):
484
+ """Placeholder docstring"""
485
+ # Check if all the required hyperparameters are set. If there is a default value
486
+ # for one, set it.
487
+ for name, definition in self.hyperparameter_definitions.items():
488
+ if name not in self._hyperparameters:
489
+ spec = definition["spec"]
490
+ if "DefaultValue" in spec:
491
+ self._hyperparameters[name] = spec["DefaultValue"]
492
+ elif "IsRequired" in spec and spec["IsRequired"]:
493
+ raise ValueError("Required hyperparameter: %s is not set" % name)
494
+
495
+ def _parse_hyperparameters(self):
496
+ """Placeholder docstring"""
497
+ definitions = {}
498
+
499
+ training_spec = self.algorithm_spec["TrainingSpecification"]
500
+ if "SupportedHyperParameters" in training_spec:
501
+ hyperparameters = training_spec["SupportedHyperParameters"]
502
+ for h in hyperparameters:
503
+ parameter_type = h["Type"]
504
+ name = h["Name"]
505
+ parameter_class, parameter_range = self._hyperparameter_range_and_class(
506
+ parameter_type, h
507
+ )
508
+
509
+ definitions[name] = {"spec": h}
510
+ if parameter_range:
511
+ definitions[name]["range"] = parameter_range
512
+ if parameter_class:
513
+ definitions[name]["class"] = parameter_class
514
+
515
+ return definitions
516
+
517
+ def _hyperparameter_range_and_class(self, parameter_type, hyperparameter):
518
+ """Placeholder docstring."""
519
+ if parameter_type in self._hyperpameters_with_range:
520
+ range_name = parameter_type + "ParameterRangeSpecification"
521
+
522
+ parameter_class = None
523
+ parameter_range = None
524
+
525
+ if parameter_type in ("Integer", "Continuous"):
526
+ # Integer and Continuous are handled the same way. We get the min and max values
527
+ # and just create an Instance of Parameter. Note that the range is optional for all
528
+ # the Parameter Types.
529
+ if parameter_type == "Integer":
530
+ parameter_class = sagemaker.parameter.IntegerParameter
531
+ else:
532
+ parameter_class = sagemaker.parameter.ContinuousParameter
533
+
534
+ if "Range" in hyperparameter:
535
+ min_value = parameter_class.cast_to_type(
536
+ hyperparameter["Range"][range_name]["MinValue"]
537
+ )
538
+ max_value = parameter_class.cast_to_type(
539
+ hyperparameter["Range"][range_name]["MaxValue"]
540
+ )
541
+ parameter_range = parameter_class(min_value, max_value)
542
+
543
+ elif parameter_type == "Categorical":
544
+ parameter_class = sagemaker.parameter.CategoricalParameter
545
+ if "Range" in hyperparameter:
546
+ values = hyperparameter["Range"][range_name]["Values"]
547
+ parameter_range = sagemaker.parameter.CategoricalParameter(values)
548
+ elif parameter_type == "FreeText":
549
+ pass
550
+ else:
551
+ raise ValueError(
552
+ "Invalid Hyperparameter type: %s. Valid ones are:"
553
+ "(Integer, Continuous, Categorical, FreeText)" % parameter_type
554
+ )
555
+
556
+ return parameter_class, parameter_range
557
+
558
+ def _algorithm_training_input_modes(self, training_channels):
559
+ """Placeholder docstring"""
560
+ current_input_modes = {"File", "Pipe"}
561
+ for channel in training_channels:
562
+ supported_input_modes = set(channel["SupportedInputModes"])
563
+ current_input_modes = current_input_modes & supported_input_modes
564
+
565
+ return current_input_modes
566
+
567
+ @classmethod
568
+ def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
569
+ """Convert the job description to init params that can be handled by the class constructor.
570
+
571
+ Args:
572
+ job_details (dict): the returned job details from a DescribeTrainingJob
573
+ API call.
574
+ model_channel_name (str): Name of the channel where pre-trained
575
+ model data will be downloaded.
576
+
577
+ Returns:
578
+ dict: The transformed init_params
579
+ """
580
+ init_params = super(AlgorithmEstimator, cls)._prepare_init_params_from_job_description(
581
+ job_details, model_channel_name
582
+ )
583
+
584
+ # This hyperparameter is added by Amazon SageMaker Automatic Model Tuning.
585
+ # It cannot be set through instantiating an estimator.
586
+ if "_tuning_objective_metric" in init_params["hyperparameters"]:
587
+ del init_params["hyperparameters"]["_tuning_objective_metric"]
588
+
589
+ return init_params
testbed/aws__sagemaker-python-sdk/src/sagemaker/analytics.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import print_function, absolute_import
15
+
16
+ from abc import ABCMeta, abstractmethod
17
+ from collections import defaultdict, OrderedDict
18
+ import datetime
19
+ import logging
20
+
21
+ from six import with_metaclass
22
+
23
+ from sagemaker.session import Session
24
+ from sagemaker.utils import DeferredError
25
+ from sagemaker.lineage import artifact
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ try:
30
+ import pandas as pd
31
+ except ImportError as e:
32
+ logger.warning("pandas failed to import. Analytics features will be impaired or broken.")
33
+ # Any subsequent attempt to use pandas will raise the ImportError
34
+ pd = DeferredError(e)
35
+
36
+ METRICS_PERIOD_DEFAULT = 60 # seconds
37
+
38
+
39
+ class AnalyticsMetricsBase(with_metaclass(ABCMeta, object)):
40
+ """Base class for tuning job or training job analytics classes.
41
+
42
+ Understands common functionality like persistence and caching.
43
+ """
44
+
45
+ def __init__(self):
46
+ """Initializes ``AnalyticsMetricsBase`` instance."""
47
+ self._dataframe = None
48
+
49
+ def export_csv(self, filename):
50
+ """Persists the analytics dataframe to a file.
51
+
52
+ Args:
53
+ filename (str): The name of the file to save to.
54
+ """
55
+ self.dataframe().to_csv(filename)
56
+
57
+ def dataframe(self, force_refresh=False):
58
+ """A pandas dataframe with lots of interesting results about this object.
59
+
60
+ Created by calling SageMaker List and Describe APIs and converting them into a
61
+ convenient tabular summary.
62
+
63
+ Args:
64
+ force_refresh (bool): Set to True to fetch the latest data from
65
+ SageMaker API.
66
+ """
67
+ if force_refresh:
68
+ self.clear_cache()
69
+ if self._dataframe is None:
70
+ self._dataframe = self._fetch_dataframe()
71
+ return self._dataframe
72
+
73
+ @abstractmethod
74
+ def _fetch_dataframe(self):
75
+ """Sub-class must calculate the dataframe and return it."""
76
+
77
+ def clear_cache(self):
78
+ """Clear the object of all local caches of API methods.
79
+
80
+ So that the next time any properties are accessed they will be refreshed from the service.
81
+ """
82
+ self._dataframe = None
83
+
84
+
85
+ class HyperparameterTuningJobAnalytics(AnalyticsMetricsBase):
86
+ """Fetch results about a hyperparameter tuning job and make them accessible for analytics."""
87
+
88
+ def __init__(self, hyperparameter_tuning_job_name, sagemaker_session=None):
89
+ """Initialize a ``HyperparameterTuningJobAnalytics`` instance.
90
+
91
+ Args:
92
+ hyperparameter_tuning_job_name (str): name of the
93
+ HyperparameterTuningJob to analyze.
94
+ sagemaker_session (sagemaker.session.Session): Session object which
95
+ manages interactions with Amazon SageMaker APIs and any other
96
+ AWS services needed. If not specified, one is created using the
97
+ default AWS configuration chain.
98
+ """
99
+ sagemaker_session = sagemaker_session or Session()
100
+ self._sage_client = sagemaker_session.sagemaker_client
101
+ self._tuning_job_name = hyperparameter_tuning_job_name
102
+ self._tuning_job_describe_result = None
103
+ self._training_job_summaries = None
104
+ super(HyperparameterTuningJobAnalytics, self).__init__()
105
+ self.clear_cache()
106
+
107
+ @property
108
+ def name(self):
109
+ """Name of the HyperparameterTuningJob being analyzed"""
110
+ return self._tuning_job_name
111
+
112
+ def __repr__(self):
113
+ """Human-readable representation override."""
114
+ return "<sagemaker.HyperparameterTuningJobAnalytics for %s>" % self.name
115
+
116
+ def clear_cache(self):
117
+ """Clear the object of all local caches of API methods."""
118
+ super(HyperparameterTuningJobAnalytics, self).clear_cache()
119
+ self._tuning_job_describe_result = None
120
+ self._training_job_summaries = None
121
+
122
+ def _fetch_dataframe(self):
123
+ """Return a pandas dataframe with all the training jobs.
124
+
125
+ This includes their hyperparameters, results, and metadata, as well as
126
+ a column to indicate if a training job was the best seen so far.
127
+ """
128
+
129
+ def reshape(training_summary):
130
+ # Helper method to reshape a single training job summary into a dataframe record
131
+ out = {}
132
+ for k, v in training_summary["TunedHyperParameters"].items():
133
+ # Something (bokeh?) gets confused with ints so convert to float
134
+ try:
135
+ v = float(v)
136
+ except (TypeError, ValueError):
137
+ pass
138
+ out[k] = v
139
+ out["TrainingJobName"] = training_summary["TrainingJobName"]
140
+ out["TrainingJobStatus"] = training_summary["TrainingJobStatus"]
141
+ out["FinalObjectiveValue"] = training_summary.get(
142
+ "FinalHyperParameterTuningJobObjectiveMetric", {}
143
+ ).get("Value")
144
+
145
+ start_time = training_summary.get("TrainingStartTime", None)
146
+ end_time = training_summary.get("TrainingEndTime", None)
147
+ out["TrainingStartTime"] = start_time
148
+ out["TrainingEndTime"] = end_time
149
+ if start_time and end_time:
150
+ out["TrainingElapsedTimeSeconds"] = (end_time - start_time).total_seconds()
151
+ if "TrainingJobDefinitionName" in training_summary:
152
+ out["TrainingJobDefinitionName"] = training_summary["TrainingJobDefinitionName"]
153
+ return out
154
+
155
+ # Run that helper over all the summaries.
156
+ df = pd.DataFrame([reshape(tjs) for tjs in self.training_job_summaries()])
157
+ return df
158
+
159
+ @property
160
+ def tuning_ranges(self):
161
+ """A dictionary describing the ranges of all tuned hyperparameters.
162
+
163
+ The keys are the names of the hyperparameter, and the values are the ranges.
164
+
165
+ The output can take one of two forms:
166
+
167
+ * If the 'TrainingJobDefinition' field is present in the job description, the output
168
+ is a dictionary constructed from 'ParameterRanges' in
169
+ 'HyperParameterTuningJobConfig' of the job description. The keys are the
170
+ parameter names, while the values are the parameter ranges.
171
+ Example:
172
+ >>> {
173
+ >>> "eta": {"MaxValue": "1", "MinValue": "0", "Name": "eta"},
174
+ >>> "gamma": {"MaxValue": "10", "MinValue": "0", "Name": "gamma"},
175
+ >>> "iterations": {"MaxValue": "100", "MinValue": "50", "Name": "iterations"},
176
+ >>> "num_layers": {"MaxValue": "30", "MinValue": "5", "Name": "num_layers"},
177
+ >>> }
178
+ * If the 'TrainingJobDefinitions' field (list) is present in the job description,
179
+ the output is a dictionary with keys as the 'DefinitionName' values from
180
+ all items in 'TrainingJobDefinitions', and each value would be a dictionary
181
+ constructed from 'HyperParameterRanges' in each item in 'TrainingJobDefinitions'
182
+ in the same format as above
183
+ Example:
184
+ >>> {
185
+ >>> "estimator_1": {
186
+ >>> "eta": {"MaxValue": "1", "MinValue": "0", "Name": "eta"},
187
+ >>> "gamma": {"MaxValue": "10", "MinValue": "0", "Name": "gamma"},
188
+ >>> },
189
+ >>> "estimator_2": {
190
+ >>> "framework": {"Values": ["TF", "MXNet"], "Name": "framework"},
191
+ >>> "gamma": {"MaxValue": "1.0", "MinValue": "0.2", "Name": "gamma"}
192
+ >>> }
193
+ >>> }
194
+
195
+ For more details about the 'TrainingJobDefinition' and 'TrainingJobDefinitions' fields
196
+ in job description, see
197
+ https://botocore.readthedocs.io/en/latest/reference/services/sagemaker.html#SageMaker.Client.create_hyper_parameter_tuning_job
198
+ """
199
+ description = self.description()
200
+
201
+ if "TrainingJobDefinition" in description:
202
+ return self._prepare_parameter_ranges(
203
+ description["HyperParameterTuningJobConfig"]["ParameterRanges"]
204
+ )
205
+
206
+ return {
207
+ training_job_definition["DefinitionName"]: self._prepare_parameter_ranges(
208
+ training_job_definition["HyperParameterRanges"]
209
+ )
210
+ for training_job_definition in description["TrainingJobDefinitions"]
211
+ }
212
+
213
+ def _prepare_parameter_ranges(self, parameter_ranges):
214
+ """Convert parameter ranges a dictionary using the parameter range names as the keys"""
215
+ out = {}
216
+ for _, ranges in parameter_ranges.items():
217
+ for param in ranges:
218
+ out[param["Name"]] = param
219
+ return out
220
+
221
+ def description(self, force_refresh=False):
222
+ """Call ``DescribeHyperParameterTuningJob`` for the hyperparameter tuning job.
223
+
224
+ Args:
225
+ force_refresh (bool): Set to True to fetch the latest data from
226
+ SageMaker API.
227
+
228
+ Returns:
229
+ dict: The Amazon SageMaker response for
230
+ ``DescribeHyperParameterTuningJob``.
231
+ """
232
+ if force_refresh:
233
+ self.clear_cache()
234
+ if not self._tuning_job_describe_result:
235
+ self._tuning_job_describe_result = self._sage_client.describe_hyper_parameter_tuning_job( # noqa: E501 # pylint: disable=line-too-long
236
+ HyperParameterTuningJobName=self.name
237
+ )
238
+ return self._tuning_job_describe_result
239
+
240
+ def training_job_summaries(self, force_refresh=False):
241
+ """A (paginated) list of everything from ``ListTrainingJobsForTuningJob``.
242
+
243
+ Args:
244
+ force_refresh (bool): Set to True to fetch the latest data from
245
+ SageMaker API.
246
+
247
+ Returns:
248
+ dict: The Amazon SageMaker response for
249
+ ``ListTrainingJobsForTuningJob``.
250
+ """
251
+ if force_refresh:
252
+ self.clear_cache()
253
+ if self._training_job_summaries is not None:
254
+ return self._training_job_summaries
255
+ output = []
256
+ next_args = {}
257
+ for count in range(100):
258
+ logger.debug("Calling list_training_jobs_for_hyper_parameter_tuning_job %d", count)
259
+ raw_result = self._sage_client.list_training_jobs_for_hyper_parameter_tuning_job(
260
+ HyperParameterTuningJobName=self.name, MaxResults=100, **next_args
261
+ )
262
+ new_output = raw_result["TrainingJobSummaries"]
263
+ output.extend(new_output)
264
+ logger.debug(
265
+ "Got %d more TrainingJobs. Total so far: %d",
266
+ len(new_output),
267
+ len(output),
268
+ )
269
+ if ("NextToken" in raw_result) and (len(new_output) > 0):
270
+ next_args["NextToken"] = raw_result["NextToken"]
271
+ else:
272
+ break
273
+ self._training_job_summaries = output
274
+ return output
275
+
276
+
277
+ class TrainingJobAnalytics(AnalyticsMetricsBase):
278
+ """Fetch training curve data from CloudWatch Metrics for a specific training job."""
279
+
280
+ CLOUDWATCH_NAMESPACE = "/aws/sagemaker/TrainingJobs"
281
+
282
+ def __init__(
283
+ self,
284
+ training_job_name,
285
+ metric_names=None,
286
+ sagemaker_session=None,
287
+ start_time=None,
288
+ end_time=None,
289
+ period=None,
290
+ ):
291
+ """Initialize a ``TrainingJobAnalytics`` instance.
292
+
293
+ Args:
294
+ training_job_name (str): name of the TrainingJob to analyze.
295
+ metric_names (list, optional): string names of all the metrics to
296
+ collect for this training job. If not specified, then it will
297
+ use all metric names configured for this job.
298
+ sagemaker_session (sagemaker.session.Session): Session object which
299
+ manages interactions with Amazon SageMaker APIs and any other
300
+ AWS services needed. If not specified, one is specified using
301
+ the default AWS configuration chain.
302
+ start_time:
303
+ end_time:
304
+ period:
305
+ """
306
+ sagemaker_session = sagemaker_session or Session()
307
+ self._sage_client = sagemaker_session.sagemaker_client
308
+ self._cloudwatch = sagemaker_session.boto_session.client("cloudwatch")
309
+ self._training_job_name = training_job_name
310
+ self._start_time = start_time
311
+ self._end_time = end_time
312
+ self._period = period or METRICS_PERIOD_DEFAULT
313
+
314
+ if metric_names:
315
+ self._metric_names = metric_names
316
+ else:
317
+ self._metric_names = self._metric_names_for_training_job()
318
+
319
+ super(TrainingJobAnalytics, self).__init__()
320
+ self.clear_cache()
321
+
322
+ @property
323
+ def name(self):
324
+ """Name of the TrainingJob being analyzed"""
325
+ return self._training_job_name
326
+
327
+ def __repr__(self):
328
+ """The human-readable representation override."""
329
+ return "<sagemaker.TrainingJobAnalytics for %s>" % self.name
330
+
331
+ def clear_cache(self):
332
+ """Clear the object of all local caches of API methods.
333
+
334
+ This is so that the next time any properties are accessed they will be
335
+ refreshed from the service.
336
+ """
337
+ super(TrainingJobAnalytics, self).clear_cache()
338
+ self._data = defaultdict(list)
339
+ self._time_interval = self._determine_timeinterval()
340
+
341
+ def _determine_timeinterval(self):
342
+ """Return a dict with two datetime objects.
343
+
344
+ The dict includes the `start_time` and `end_time`, covering the interval
345
+ of the training job.
346
+
347
+ Returns:
348
+ a dict with the `start_time` and `end_time`.
349
+ """
350
+ description = self._sage_client.describe_training_job(TrainingJobName=self.name)
351
+ start_time = self._start_time or description["TrainingStartTime"] # datetime object
352
+ # Incrementing end time by 1 min since CloudWatch drops seconds before finding the logs.
353
+ # This results in logs being searched in the time range in which the correct log line was
354
+ # not present.
355
+ # Example - Log time - 2018-10-22 08:25:55
356
+ # Here calculated end time would also be 2018-10-22 08:25:55 (without 1 min addition)
357
+ # CW will consider end time as 2018-10-22 08:25 and will not be able to search the
358
+ # correct log.
359
+ end_time = self._end_time or description.get(
360
+ "TrainingEndTime", datetime.datetime.utcnow()
361
+ ) + datetime.timedelta(minutes=1)
362
+
363
+ return {"start_time": start_time, "end_time": end_time}
364
+
365
+ def _fetch_dataframe(self):
366
+ for metric_name in self._metric_names:
367
+ self._fetch_metric(metric_name)
368
+ return pd.DataFrame(self._data)
369
+
370
+ def _fetch_metric(self, metric_name):
371
+ """Fetch all the values of a named metric, and add them to _data
372
+
373
+ Args:
374
+ metric_name: The metric name to fetch.
375
+ """
376
+ request = {
377
+ "Namespace": self.CLOUDWATCH_NAMESPACE,
378
+ "MetricName": metric_name,
379
+ "Dimensions": [{"Name": "TrainingJobName", "Value": self.name}],
380
+ "StartTime": self._time_interval["start_time"],
381
+ "EndTime": self._time_interval["end_time"],
382
+ "Period": self._period,
383
+ "Statistics": ["Average"],
384
+ }
385
+ raw_cwm_data = self._cloudwatch.get_metric_statistics(**request)["Datapoints"]
386
+ if len(raw_cwm_data) == 0:
387
+ logger.warning("Warning: No metrics called %s found", metric_name)
388
+ return
389
+
390
+ # Process data: normalize to starting time, and sort.
391
+ base_time = min(raw_cwm_data, key=lambda pt: pt["Timestamp"])["Timestamp"]
392
+ all_xy = []
393
+ for pt in raw_cwm_data:
394
+ y = pt["Average"]
395
+ x = (pt["Timestamp"] - base_time).total_seconds()
396
+ all_xy.append([x, y])
397
+ all_xy = sorted(all_xy, key=lambda x: x[0])
398
+
399
+ # Store everything in _data to make a dataframe from
400
+ for elapsed_seconds, value in all_xy:
401
+ self._add_single_metric(elapsed_seconds, metric_name, value)
402
+
403
+ def _add_single_metric(self, timestamp, metric_name, value):
404
+ """Store a single metric in the _data dict.
405
+
406
+ This can be converted to a dataframe.
407
+
408
+ Args:
409
+ timestamp: The timestamp of the metric.
410
+ metric_name: The name of the metric.
411
+ value: The value of the metric.
412
+ """
413
+ # note that this method is built this way to make it possible to
414
+ # support live-refreshing charts in Bokeh at some point in the future.
415
+ self._data["timestamp"].append(timestamp)
416
+ self._data["metric_name"].append(metric_name)
417
+ self._data["value"].append(value)
418
+
419
+ def _metric_names_for_training_job(self):
420
+ """Helper method to discover the metrics defined for a training job."""
421
+ training_description = self._sage_client.describe_training_job(
422
+ TrainingJobName=self._training_job_name
423
+ )
424
+
425
+ metric_definitions = training_description["AlgorithmSpecification"]["MetricDefinitions"]
426
+ metric_names = [md["Name"] for md in metric_definitions]
427
+
428
+ return metric_names
429
+
430
+
431
+ class ArtifactAnalytics(AnalyticsMetricsBase):
432
+ """Fetch artifact data and make them accessible for analytics."""
433
+
434
+ def __init__(
435
+ self,
436
+ sort_by=None,
437
+ sort_order=None,
438
+ source_uri=None,
439
+ artifact_type=None,
440
+ sagemaker_session=None,
441
+ ):
442
+ """Initialize a ``ArtifactAnalytics`` instance.
443
+
444
+ Args:
445
+ sort_by (str, optional): The name of the resource property used to sort
446
+ the set of artifacts. Currently only support for sort by Name
447
+ sort_order(str optional): How trial components are ordered, valid values are Ascending
448
+ and Descending. The default is Descending.
449
+ source_uri(dict optional): The artifact source uri for filtering.
450
+ artifact_type(dict optional): The artifact type for filtering.
451
+ sagemaker_session (obj, optional): Sagemaker session. Defaults to None.
452
+ """
453
+ self._sort_by = sort_by if sort_by == "Name" else None
454
+ self._sort_order = sort_order
455
+ self._source_uri = source_uri
456
+ self._artifact_type = artifact_type
457
+ self._sagemaker_session = sagemaker_session
458
+ super(ArtifactAnalytics, self).__init__()
459
+ self.clear_cache()
460
+
461
+ def __repr__(self):
462
+ """Human-readable representation override."""
463
+ return "<sagemaker.ArtifactAnalytics>"
464
+
465
+ def _reshape_source_type(self, artifact_source_types):
466
+ """Reshape artifact source type."""
467
+ out = OrderedDict()
468
+ for artifact_source_type in artifact_source_types:
469
+ out["ArtifactSourceType"] = artifact_source_type
470
+ return out
471
+
472
+ def _reshape(self, artifact_summary):
473
+ """Reshape artifact summary."""
474
+ out = OrderedDict()
475
+ out["ArtifactName"] = artifact_summary.artifact_name
476
+ out["ArtifactArn"] = artifact_summary.artifact_arn
477
+ out["ArtifactType"] = artifact_summary.artifact_type
478
+ out["ArtifactSourceUri"] = artifact_summary.source.source_uri
479
+ out["CreationTime"] = artifact_summary.creation_time
480
+ out["LastModifiedTime"] = artifact_summary.last_modified_time
481
+ return out
482
+
483
+ def _fetch_dataframe(self):
484
+ """Return a pandas dataframe with all artifacts."""
485
+ df = pd.DataFrame([self._reshape(artifact) for artifact in self._get_list_artifacts()])
486
+ return df
487
+
488
+ def _get_list_artifacts(self):
489
+ """List artifacts."""
490
+ artifacts = artifact.Artifact.list(
491
+ source_uri=self._source_uri,
492
+ artifact_type=self._artifact_type,
493
+ sort_by=self._sort_by,
494
+ sort_order=self._sort_order,
495
+ sagemaker_session=self._sagemaker_session,
496
+ )
497
+ return artifacts
498
+
499
+
500
+ class ExperimentAnalytics(AnalyticsMetricsBase):
501
+ """Fetch trial component data and make them accessible for analytics."""
502
+
503
+ MAX_TRIAL_COMPONENTS = 10000
504
+
505
+ def __init__(
506
+ self,
507
+ experiment_name=None,
508
+ search_expression=None,
509
+ sort_by=None,
510
+ sort_order=None,
511
+ metric_names=None,
512
+ parameter_names=None,
513
+ sagemaker_session=None,
514
+ input_artifact_names=None,
515
+ output_artifact_names=None,
516
+ ):
517
+ """Initialize a ``ExperimentAnalytics`` instance.
518
+
519
+ Args:
520
+ experiment_name (str, optional): Name of the experiment if you want to constrain the
521
+ search to only trial components belonging to an experiment.
522
+ search_expression (dict, optional): The search query to find the set of trial components
523
+ to use to populate the data frame.
524
+ sort_by (str, optional): The name of the resource property used to sort
525
+ the set of trial components.
526
+ sort_order(str optional): How trial components are ordered, valid values are Ascending
527
+ and Descending. The default is Descending.
528
+ metric_names (list, optional): string names of all the metrics to be shown in the
529
+ data frame. If not specified, all metrics will be shown of all trials.
530
+ parameter_names (list, optional): string names of the parameters to be shown in the
531
+ data frame. If not specified, all parameters will be shown of all trials.
532
+ sagemaker_session (sagemaker.session.Session): Session object which manages interactions
533
+ with Amazon SageMaker APIs and any other AWS services needed. If not specified,
534
+ one is created using the default AWS configuration chain.
535
+ input_artifact_names(dict optional):The input artifacts for the experiment. Examples of
536
+ input artifacts are datasets, algorithms, hyperparameters, source code, and instance
537
+ types.
538
+ output_artifact_names(dict optional): The output artifacts for the experiment. Examples
539
+ of output artifacts are metrics, snapshots, logs, and images.
540
+ """
541
+ sagemaker_session = sagemaker_session or Session()
542
+ self._sage_client = sagemaker_session.sagemaker_client
543
+
544
+ if not experiment_name and not search_expression:
545
+ raise ValueError("Either experiment_name or search_expression must be supplied.")
546
+
547
+ self._experiment_name = experiment_name
548
+ self._search_expression = search_expression
549
+ self._sort_by = sort_by
550
+ self._sort_order = sort_order
551
+ self._metric_names = metric_names
552
+ self._parameter_names = parameter_names
553
+ self._input_artifact_names = input_artifact_names
554
+ self._output_artifact_names = output_artifact_names
555
+ self._trial_components = None
556
+ super(ExperimentAnalytics, self).__init__()
557
+ self.clear_cache()
558
+
559
+ @property
560
+ def name(self):
561
+ """Name of the Experiment being analyzed."""
562
+ return self._experiment_name
563
+
564
+ def __repr__(self):
565
+ """The human-readable representation override."""
566
+ return "<sagemaker.ExperimentAnalytics for %s>" % self.name
567
+
568
+ def clear_cache(self):
569
+ """Clear the object of all local caches of API methods."""
570
+ super(ExperimentAnalytics, self).clear_cache()
571
+ self._trial_components = None
572
+
573
+ def _reshape_parameters(self, parameters):
574
+ """Reshape trial component parameters to a pandas column.
575
+
576
+ Args:
577
+ parameters: trial component parameters
578
+ Returns:
579
+ dict: Key: Parameter name, Value: Parameter value
580
+ """
581
+ out = OrderedDict()
582
+ for name, value in sorted(parameters.items()):
583
+ if self._parameter_names and name not in self._parameter_names:
584
+ continue
585
+ out[name] = value.get("NumberValue", value.get("StringValue"))
586
+ return out
587
+
588
+ def _reshape_metrics(self, metrics):
589
+ """Reshape trial component metrics to a pandas column.
590
+
591
+ Args:
592
+ metrics: trial component metrics
593
+ Returns:
594
+ dict: Key: Metric name, Value: Metric value
595
+ """
596
+ statistic_types = ["Min", "Max", "Avg", "StdDev", "Last", "Count"]
597
+ out = OrderedDict()
598
+ for metric_summary in metrics:
599
+ metric_name = metric_summary["MetricName"]
600
+ if self._metric_names and metric_name not in self._metric_names:
601
+ continue
602
+
603
+ for stat_type in statistic_types:
604
+ stat_value = metric_summary.get(stat_type)
605
+ if stat_value is not None:
606
+ out["{} - {}".format(metric_name, stat_type)] = stat_value
607
+ return out
608
+
609
+ def _reshape_artifacts(self, artifacts, _artifact_names):
610
+ """Reshape trial component input/output artifacts to a pandas column.
611
+
612
+ Args:
613
+ artifacts: trial component input/output artifacts
614
+ Returns:
615
+ dict: Key: artifacts name, Value: artifacts value
616
+ """
617
+ out = OrderedDict()
618
+ for name, value in sorted(artifacts.items()):
619
+ if _artifact_names and (name not in _artifact_names):
620
+ continue
621
+ out["{} - {}".format(name, "MediaType")] = value.get("MediaType")
622
+ out["{} - {}".format(name, "Value")] = value.get("Value")
623
+ return out
624
+
625
+ def _reshape_parents(self, parents):
626
+ """Reshape trial component parents to a pandas column.
627
+
628
+ Args:
629
+ parents: trial component parents (trials and experiments)
630
+ Returns:
631
+ dict: Key: artifacts name, Value: artifacts value
632
+ """
633
+ out = OrderedDict()
634
+ trials = []
635
+ experiments = []
636
+ for parent in parents:
637
+ trials.append(parent["TrialName"])
638
+ experiments.append(parent["ExperimentName"])
639
+ out["Trials"] = trials
640
+ out["Experiments"] = experiments
641
+ return out
642
+
643
+ def _reshape(self, trial_component):
644
+ """Reshape trial component data to pandas columns.
645
+
646
+ Args:
647
+ trial_component: dict representing a trial component
648
+ Returns:
649
+ dict: Key-Value pair representing the data in the pandas dataframe
650
+ """
651
+ out = OrderedDict()
652
+ for attribute in ["TrialComponentName", "DisplayName"]:
653
+ out[attribute] = trial_component.get(attribute, "")
654
+
655
+ source = trial_component.get("Source", "")
656
+ if source:
657
+ out["SourceArn"] = source["SourceArn"]
658
+
659
+ out.update(self._reshape_parameters(trial_component.get("Parameters", [])))
660
+ out.update(self._reshape_metrics(trial_component.get("Metrics", [])))
661
+ out.update(
662
+ self._reshape_artifacts(
663
+ trial_component.get("InputArtifacts", []), self._input_artifact_names
664
+ )
665
+ )
666
+ out.update(
667
+ self._reshape_artifacts(
668
+ trial_component.get("OutputArtifacts", []), self._output_artifact_names
669
+ )
670
+ )
671
+ out.update(self._reshape_parents(trial_component.get("Parents", [])))
672
+ return out
673
+
674
+ def _fetch_dataframe(self):
675
+ """Return a pandas dataframe includes all the trial_components."""
676
+
677
+ df = pd.DataFrame([self._reshape(component) for component in self._get_trial_components()])
678
+ return df
679
+
680
+ def _get_trial_components(self, force_refresh=False):
681
+ """Get all trial components matching the given search query expression.
682
+
683
+ Args:
684
+ force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
685
+
686
+ Returns:
687
+ list: List of dicts representing the trial components
688
+ """
689
+ if force_refresh:
690
+ self.clear_cache()
691
+ if self._trial_components is not None:
692
+ return self._trial_components
693
+
694
+ if not self._search_expression:
695
+ self._search_expression = {}
696
+
697
+ if self._experiment_name:
698
+ if not self._search_expression.get("Filters"):
699
+ self._search_expression["Filters"] = []
700
+
701
+ self._search_expression["Filters"].append(
702
+ {
703
+ "Name": "Parents.ExperimentName",
704
+ "Operator": "Equals",
705
+ "Value": self._experiment_name,
706
+ }
707
+ )
708
+
709
+ return self._search(self._search_expression, self._sort_by, self._sort_order)
710
+
711
+ def _search(self, search_expression, sort_by, sort_order):
712
+ """Perform a search query using SageMaker Search and return the matching trial components.
713
+
714
+ Args:
715
+ search_expression: Search expression to filter trial components.
716
+ sort_by: The name of the resource property used to sort the trial components.
717
+ sort_order: How trial components are ordered, valid values are Ascending
718
+ and Descending. The default is Descending.
719
+ Returns:
720
+ list: List of dict representing trial components.
721
+ """
722
+ trial_components = []
723
+
724
+ search_args = {
725
+ "Resource": "ExperimentTrialComponent",
726
+ "SearchExpression": search_expression,
727
+ }
728
+
729
+ if sort_by:
730
+ search_args["SortBy"] = sort_by
731
+
732
+ if sort_order:
733
+ search_args["SortOrder"] = sort_order
734
+
735
+ while len(trial_components) < self.MAX_TRIAL_COMPONENTS:
736
+ search_response = self._sage_client.search(**search_args)
737
+ components = [result["TrialComponent"] for result in search_response["Results"]]
738
+ trial_components.extend(components)
739
+ if "NextToken" in search_response and len(components) > 0:
740
+ search_args["NextToken"] = search_response["NextToken"]
741
+ else:
742
+ break
743
+
744
+ return trial_components
testbed/aws__sagemaker-python-sdk/src/sagemaker/clarify.py ADDED
The diff for this file is too large to render. See raw diff
 
testbed/aws__sagemaker-python-sdk/src/sagemaker/content_types.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Deprecated content type constants. Just use the mime type strings."""
14
+ from __future__ import absolute_import
15
+
16
+ import deprecations
17
+
18
+ deprecations.removed_warning("The sagemaker.content_types module")
19
+
20
+ CONTENT_TYPE_JSON = "application/json"
21
+ CONTENT_TYPE_CSV = "text/csv"
22
+ CONTENT_TYPE_OCTET_STREAM = "application/octet-stream"
23
+ CONTENT_TYPE_NPY = "application/x-npy"
testbed/aws__sagemaker-python-sdk/src/sagemaker/deprecations.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Module for deprecation abstractions."""
14
+ from __future__ import absolute_import
15
+
16
+ import logging
17
+ import warnings
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ V2_URL = "https://sagemaker.readthedocs.io/en/stable/v2.html"
22
+
23
+
24
+ def _warn(msg, sdk_version=None):
25
+ """Generic warning raiser referencing V2
26
+
27
+ Args:
28
+ phrase: The phrase to include in the warning.
29
+ sdk_version: the sdk version of removal of support.
30
+ """
31
+ _sdk_version = sdk_version if sdk_version is not None else "2"
32
+ full_msg = f"{msg} in sagemaker>={_sdk_version}.\nSee: {V2_URL} for details."
33
+ warnings.warn(full_msg, DeprecationWarning, stacklevel=2)
34
+ logger.warning(full_msg)
35
+
36
+
37
+ def removed_warning(phrase, sdk_version=None):
38
+ """Raise a warning for a no-op in sagemaker>=2
39
+
40
+ Args:
41
+ phrase: the prefix phrase of the warning message.
42
+ sdk_version: the sdk version of removal of support.
43
+ """
44
+ _warn(f"{phrase} is a no-op", sdk_version)
45
+
46
+
47
+ def renamed_warning(phrase):
48
+ """Raise a warning for a rename in sagemaker>=2
49
+
50
+ Args:
51
+ phrase: the prefix phrase of the warning message.
52
+ """
53
+ _warn(f"{phrase} has been renamed")
54
+
55
+
56
+ def deprecation_warn(name, date, msg=None):
57
+ """Raise a warning for soon to be deprecated feature in sagemaker>=2
58
+
59
+ Args:
60
+ name (str): Name of the feature
61
+ date (str): the date when the feature will be deprecated
62
+ msg (str): the prefix phrase of the warning message.
63
+ """
64
+ _warn(f"{name} will be deprecated on {date}.{msg}")
65
+
66
+
67
+ def deprecation_warning(date, msg=None):
68
+ """Decorator for raising deprecation warning for a feature in sagemaker>=2
69
+
70
+ Args:
71
+ date (str): the date when the feature will be deprecated
72
+ msg (str): the prefix phrase of the warning message.
73
+
74
+ Usage:
75
+ @deprecation_warning(msg="message", date="date")
76
+ def sample_function():
77
+ print("xxxx....")
78
+
79
+ @deprecation_warning(msg="message", date="date")
80
+ class SampleClass():
81
+ def __init__(self):
82
+ print("xxxx....")
83
+
84
+ """
85
+
86
+ def deprecate(obj):
87
+ def wrapper(*args, **kwargs):
88
+ deprecation_warn(obj.__name__, date, msg)
89
+ return obj(*args, **kwargs)
90
+
91
+ return wrapper
92
+
93
+ return deprecate
94
+
95
+
96
+ def renamed_kwargs(old_name, new_name, value, kwargs):
97
+ """Checks if the deprecated argument is in kwargs
98
+
99
+ Raises warning, if present.
100
+
101
+ Args:
102
+ old_name: name of deprecated argument
103
+ new_name: name of the new argument
104
+ value: value associated with new name, if supplied
105
+ kwargs: keyword arguments dict
106
+
107
+ Returns:
108
+ value of the keyword argument, if present
109
+ """
110
+ if old_name in kwargs:
111
+ value = kwargs.get(old_name, value)
112
+ kwargs[new_name] = value
113
+ renamed_warning(old_name)
114
+ return value
115
+
116
+
117
+ def removed_arg(name, arg):
118
+ """Checks if the deprecated argument is populated.
119
+
120
+ Raises warning, if not None.
121
+
122
+ Args:
123
+ name: name of deprecated argument
124
+ arg: the argument to check
125
+ """
126
+ if arg is not None:
127
+ removed_warning(name)
128
+
129
+
130
+ def removed_kwargs(name, kwargs):
131
+ """Checks if the deprecated argument is in kwargs
132
+
133
+ Raises warning, if present.
134
+
135
+ Args:
136
+ name: name of deprecated argument
137
+ kwargs: keyword arguments dict
138
+ """
139
+ if name in kwargs:
140
+ removed_warning(name)
141
+
142
+
143
+ def removed_function(name):
144
+ """A no-op deprecated function factory."""
145
+
146
+ def func(*args, **kwargs): # pylint: disable=W0613
147
+ removed_warning(f"The function {name}")
148
+
149
+ return func
150
+
151
+
152
+ def deprecated(sdk_version=None):
153
+ """Decorator for raising deprecated warning for a feature in sagemaker>=2
154
+
155
+ Args:
156
+ sdk_version (str): the sdk version of removal of support.
157
+
158
+ Usage:
159
+ @deprecated()
160
+ def sample_function():
161
+ print("xxxx....")
162
+
163
+ @deprecated(sdk_version="2.66")
164
+ class SampleClass():
165
+ def __init__(self):
166
+ print("xxxx....")
167
+
168
+ """
169
+
170
+ def deprecate(obj):
171
+ def wrapper(*args, **kwargs):
172
+ removed_warning(obj.__name__, sdk_version)
173
+ return obj(*args, **kwargs)
174
+
175
+ return wrapper
176
+
177
+ return deprecate
178
+
179
+
180
+ def deprecated_function(func, name):
181
+ """Wrap a function with a deprecation warning.
182
+
183
+ Args:
184
+ func: Function to wrap in a deprecation warning.
185
+ name: The name that has been deprecated.
186
+
187
+ Returns:
188
+ The modified function
189
+ """
190
+
191
+ def deprecate(*args, **kwargs):
192
+ renamed_warning(f"The {name}")
193
+ return func(*args, **kwargs)
194
+
195
+ return deprecate
196
+
197
+
198
+ def deprecated_serialize(instance, name):
199
+ """Modifies a serializer instance serialize method.
200
+
201
+ Args:
202
+ instance: Instance to modify serialize method.
203
+ name: The name that has been deprecated.
204
+
205
+ Returns:
206
+ The modified instance
207
+ """
208
+ instance.serialize = deprecated_function(instance.serialize, name)
209
+ return instance
210
+
211
+
212
+ def deprecated_deserialize(instance, name):
213
+ """Modifies a deserializer instance deserialize method.
214
+
215
+ Args:
216
+ instance: Instance to modify deserialize method.
217
+ name: The name that has been deprecated.
218
+
219
+ Returns:
220
+ The modified instance
221
+ """
222
+ instance.deserialize = deprecated_function(instance.deserialize, name)
223
+ return instance
224
+
225
+
226
+ def deprecated_class(cls, name):
227
+ """Returns a class based on super class with a deprecation warning.
228
+
229
+ Args:
230
+ cls: The class to derive with a deprecation warning on __init__
231
+ name: The name of the class.
232
+
233
+ Returns:
234
+ The modified class.
235
+ """
236
+
237
+ class DeprecatedClass(cls):
238
+ """Provides a warning for the class name."""
239
+
240
+ def __init__(self, *args, **kwargs):
241
+ """Provides a warning for the class name."""
242
+ renamed_warning(f"The class {name}")
243
+ super(DeprecatedClass, self).__init__(*args, **kwargs)
244
+
245
+ return DeprecatedClass
testbed/aws__sagemaker-python-sdk/src/sagemaker/deserializers.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Implements methods for deserializing data returned from an inference endpoint."""
14
+ from __future__ import absolute_import
15
+
16
+ import csv
17
+
18
+ import abc
19
+ import codecs
20
+ import io
21
+ import json
22
+
23
+ import numpy as np
24
+ from six import with_metaclass
25
+
26
+ from sagemaker.utils import DeferredError
27
+
28
+ try:
29
+ import pandas
30
+ except ImportError as e:
31
+ pandas = DeferredError(e)
32
+
33
+
34
+ class BaseDeserializer(abc.ABC):
35
+ """Abstract base class for creation of new deserializers.
36
+
37
+ Provides a skeleton for customization requiring the overriding of the method
38
+ deserialize and the class attribute ACCEPT.
39
+ """
40
+
41
+ @abc.abstractmethod
42
+ def deserialize(self, stream, content_type):
43
+ """Deserialize data received from an inference endpoint.
44
+
45
+ Args:
46
+ stream (botocore.response.StreamingBody): Data to be deserialized.
47
+ content_type (str): The MIME type of the data.
48
+
49
+ Returns:
50
+ object: The data deserialized into an object.
51
+ """
52
+
53
+ @property
54
+ @abc.abstractmethod
55
+ def ACCEPT(self):
56
+ """The content types that are expected from the inference endpoint."""
57
+
58
+
59
+ class SimpleBaseDeserializer(with_metaclass(abc.ABCMeta, BaseDeserializer)):
60
+ """Abstract base class for creation of new deserializers.
61
+
62
+ This class extends the API of :class:~`sagemaker.deserializers.BaseDeserializer` with more
63
+ user-friendly options for setting the ACCEPT content type header, in situations where it can be
64
+ provided at init and freely updated.
65
+ """
66
+
67
+ def __init__(self, accept="*/*"):
68
+ """Initialize a ``SimpleBaseDeserializer`` instance.
69
+
70
+ Args:
71
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
72
+ is expected from the inference endpoint (default: "*/*").
73
+ """
74
+ super(SimpleBaseDeserializer, self).__init__()
75
+ self.accept = accept
76
+
77
+ @property
78
+ def ACCEPT(self):
79
+ """The tuple of possible content types that are expected from the inference endpoint."""
80
+ if isinstance(self.accept, str):
81
+ return (self.accept,)
82
+ return self.accept
83
+
84
+
85
+ class StringDeserializer(SimpleBaseDeserializer):
86
+ """Deserialize data from an inference endpoint into a decoded string."""
87
+
88
+ def __init__(self, encoding="UTF-8", accept="application/json"):
89
+ """Initialize a ``StringDeserializer`` instance.
90
+
91
+ Args:
92
+ encoding (str): The string encoding to use (default: UTF-8).
93
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
94
+ is expected from the inference endpoint (default: "application/json").
95
+ """
96
+ super(StringDeserializer, self).__init__(accept=accept)
97
+ self.encoding = encoding
98
+
99
+ def deserialize(self, stream, content_type):
100
+ """Deserialize data from an inference endpoint into a decoded string.
101
+
102
+ Args:
103
+ stream (botocore.response.StreamingBody): Data to be deserialized.
104
+ content_type (str): The MIME type of the data.
105
+
106
+ Returns:
107
+ str: The data deserialized into a decoded string.
108
+ """
109
+ try:
110
+ return stream.read().decode(self.encoding)
111
+ finally:
112
+ stream.close()
113
+
114
+
115
+ class BytesDeserializer(SimpleBaseDeserializer):
116
+ """Deserialize a stream of bytes into a bytes object."""
117
+
118
+ def deserialize(self, stream, content_type):
119
+ """Read a stream of bytes returned from an inference endpoint.
120
+
121
+ Args:
122
+ stream (botocore.response.StreamingBody): A stream of bytes.
123
+ content_type (str): The MIME type of the data.
124
+
125
+ Returns:
126
+ bytes: The bytes object read from the stream.
127
+ """
128
+ try:
129
+ return stream.read()
130
+ finally:
131
+ stream.close()
132
+
133
+
134
+ class CSVDeserializer(SimpleBaseDeserializer):
135
+ """Deserialize a stream of bytes into a list of lists.
136
+
137
+ Consider using :class:~`sagemaker.deserializers.NumpyDeserializer` or
138
+ :class:~`sagemaker.deserializers.PandasDeserializer` instead, if you'd like to convert text/csv
139
+ responses directly into other data types.
140
+ """
141
+
142
+ def __init__(self, encoding="utf-8", accept="text/csv"):
143
+ """Initialize a ``CSVDeserializer`` instance.
144
+
145
+ Args:
146
+ encoding (str): The string encoding to use (default: "utf-8").
147
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
148
+ is expected from the inference endpoint (default: "text/csv").
149
+ """
150
+ super(CSVDeserializer, self).__init__(accept=accept)
151
+ self.encoding = encoding
152
+
153
+ def deserialize(self, stream, content_type):
154
+ """Deserialize data from an inference endpoint into a list of lists.
155
+
156
+ Args:
157
+ stream (botocore.response.StreamingBody): Data to be deserialized.
158
+ content_type (str): The MIME type of the data.
159
+
160
+ Returns:
161
+ list: The data deserialized into a list of lists representing the
162
+ contents of a CSV file.
163
+ """
164
+ try:
165
+ decoded_string = stream.read().decode(self.encoding)
166
+ return list(csv.reader(decoded_string.splitlines()))
167
+ finally:
168
+ stream.close()
169
+
170
+
171
+ class StreamDeserializer(SimpleBaseDeserializer):
172
+ """Directly return the data and content-type received from an inference endpoint.
173
+
174
+ It is the user's responsibility to close the data stream once they're done
175
+ reading it.
176
+ """
177
+
178
+ def deserialize(self, stream, content_type):
179
+ """Returns a stream of the response body and the MIME type of the data.
180
+
181
+ Args:
182
+ stream (botocore.response.StreamingBody): A stream of bytes.
183
+ content_type (str): The MIME type of the data.
184
+
185
+ Returns:
186
+ tuple: A two-tuple containing the stream and content-type.
187
+ """
188
+ return stream, content_type
189
+
190
+
191
+ class NumpyDeserializer(SimpleBaseDeserializer):
192
+ """Deserialize a stream of data in .npy or UTF-8 CSV/JSON format to a numpy array."""
193
+
194
+ def __init__(self, dtype=None, accept="application/x-npy", allow_pickle=True):
195
+ """Initialize a ``NumpyDeserializer`` instance.
196
+
197
+ Args:
198
+ dtype (str): The dtype of the data (default: None).
199
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
200
+ is expected from the inference endpoint (default: "application/x-npy").
201
+ allow_pickle (bool): Allow loading pickled object arrays (default: True).
202
+ """
203
+ super(NumpyDeserializer, self).__init__(accept=accept)
204
+ self.dtype = dtype
205
+ self.allow_pickle = allow_pickle
206
+
207
+ def deserialize(self, stream, content_type):
208
+ """Deserialize data from an inference endpoint into a NumPy array.
209
+
210
+ Args:
211
+ stream (botocore.response.StreamingBody): Data to be deserialized.
212
+ content_type (str): The MIME type of the data.
213
+
214
+ Returns:
215
+ numpy.ndarray: The data deserialized into a NumPy array.
216
+ """
217
+ try:
218
+ if content_type == "text/csv":
219
+ return np.genfromtxt(
220
+ codecs.getreader("utf-8")(stream), delimiter=",", dtype=self.dtype
221
+ )
222
+ if content_type == "application/json":
223
+ return np.array(json.load(codecs.getreader("utf-8")(stream)), dtype=self.dtype)
224
+ if content_type == "application/x-npy":
225
+ return np.load(io.BytesIO(stream.read()), allow_pickle=self.allow_pickle)
226
+ finally:
227
+ stream.close()
228
+
229
+ raise ValueError("%s cannot read content type %s." % (__class__.__name__, content_type))
230
+
231
+
232
+ class JSONDeserializer(SimpleBaseDeserializer):
233
+ """Deserialize JSON data from an inference endpoint into a Python object."""
234
+
235
+ def __init__(self, accept="application/json"):
236
+ """Initialize a ``JSONDeserializer`` instance.
237
+
238
+ Args:
239
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
240
+ is expected from the inference endpoint (default: "application/json").
241
+ """
242
+ super(JSONDeserializer, self).__init__(accept=accept)
243
+
244
+ def deserialize(self, stream, content_type):
245
+ """Deserialize JSON data from an inference endpoint into a Python object.
246
+
247
+ Args:
248
+ stream (botocore.response.StreamingBody): Data to be deserialized.
249
+ content_type (str): The MIME type of the data.
250
+
251
+ Returns:
252
+ object: The JSON-formatted data deserialized into a Python object.
253
+ """
254
+ try:
255
+ return json.load(codecs.getreader("utf-8")(stream))
256
+ finally:
257
+ stream.close()
258
+
259
+
260
+ class PandasDeserializer(SimpleBaseDeserializer):
261
+ """Deserialize CSV or JSON data from an inference endpoint into a pandas dataframe."""
262
+
263
+ def __init__(self, accept=("text/csv", "application/json")):
264
+ """Initialize a ``PandasDeserializer`` instance.
265
+
266
+ Args:
267
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
268
+ is expected from the inference endpoint (default: ("text/csv","application/json")).
269
+ """
270
+ super(PandasDeserializer, self).__init__(accept=accept)
271
+
272
+ def deserialize(self, stream, content_type):
273
+ """Deserialize CSV or JSON data from an inference endpoint into a pandas dataframe.
274
+
275
+ If the data is JSON, the data should be formatted in the 'columns' orient.
276
+ See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html
277
+
278
+ Args:
279
+ stream (botocore.response.StreamingBody): Data to be deserialized.
280
+ content_type (str): The MIME type of the data.
281
+
282
+ Returns:
283
+ pandas.DataFrame: The data deserialized into a pandas DataFrame.
284
+ """
285
+ if content_type == "text/csv":
286
+ return pandas.read_csv(stream)
287
+
288
+ if content_type == "application/json":
289
+ return pandas.read_json(stream)
290
+
291
+ raise ValueError("%s cannot read content type %s." % (__class__.__name__, content_type))
292
+
293
+
294
+ class JSONLinesDeserializer(SimpleBaseDeserializer):
295
+ """Deserialize JSON lines data from an inference endpoint."""
296
+
297
+ def __init__(self, accept="application/jsonlines"):
298
+ """Initialize a ``JSONLinesDeserializer`` instance.
299
+
300
+ Args:
301
+ accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that
302
+ is expected from the inference endpoint (default: ("text/csv","application/json")).
303
+ """
304
+ super(JSONLinesDeserializer, self).__init__(accept=accept)
305
+
306
+ def deserialize(self, stream, content_type):
307
+ """Deserialize JSON lines data from an inference endpoint.
308
+
309
+ See https://docs.python.org/3/library/json.html#py-to-json-table to
310
+ understand how JSON values are converted to Python objects.
311
+
312
+ Args:
313
+ stream (botocore.response.StreamingBody): Data to be deserialized.
314
+ content_type (str): The MIME type of the data.
315
+
316
+ Returns:
317
+ list: A list of JSON serializable objects.
318
+ """
319
+ try:
320
+ body = stream.read().decode("utf-8")
321
+ lines = body.rstrip().split("\n")
322
+ return [json.loads(line) for line in lines]
323
+ finally:
324
+ stream.close()
testbed/aws__sagemaker-python-sdk/src/sagemaker/drift_check_baselines.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """This file contains code related to drift check baselines"""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import Optional
17
+
18
+ from sagemaker.model_metrics import MetricsSource, FileSource
19
+
20
+
21
+ class DriftCheckBaselines(object):
22
+ """Accepts drift check baselines parameters for conversion to request dict."""
23
+
24
+ def __init__(
25
+ self,
26
+ model_statistics: Optional[MetricsSource] = None,
27
+ model_constraints: Optional[MetricsSource] = None,
28
+ model_data_statistics: Optional[MetricsSource] = None,
29
+ model_data_constraints: Optional[MetricsSource] = None,
30
+ bias_config_file: Optional[FileSource] = None,
31
+ bias_pre_training_constraints: Optional[MetricsSource] = None,
32
+ bias_post_training_constraints: Optional[MetricsSource] = None,
33
+ explainability_constraints: Optional[MetricsSource] = None,
34
+ explainability_config_file: Optional[FileSource] = None,
35
+ ):
36
+ """Initialize a ``DriftCheckBaselines`` instance and turn parameters into dict.
37
+
38
+ Args:
39
+ model_statistics (MetricsSource): A metric source object that represents
40
+ model statistics (default: None).
41
+ model_constraints (MetricsSource): A metric source object that represents
42
+ model constraints (default: None).
43
+ model_data_statistics (MetricsSource): A metric source object that represents
44
+ model data statistics (default: None).
45
+ model_data_constraints (MetricsSource): A metric source object that represents
46
+ model data constraints (default: None).
47
+ bias_config_file (FileSource): A file source object that represents bias config
48
+ (default: None).
49
+ bias_pre_training_constraints (MetricsSource):
50
+ A metric source object that represents Pre-training constraints (default: None).
51
+ bias_post_training_constraints (MetricsSource):
52
+ A metric source object that represents Post-training constraits (default: None).
53
+ explainability_constraints (MetricsSource):
54
+ A metric source object that represents explainability constraints (default: None).
55
+ explainability_config_file (FileSource): A file source object that represents
56
+ explainability config (default: None).
57
+ """
58
+ self.model_statistics = model_statistics
59
+ self.model_constraints = model_constraints
60
+ self.model_data_statistics = model_data_statistics
61
+ self.model_data_constraints = model_data_constraints
62
+ self.bias_config_file = bias_config_file
63
+ self.bias_pre_training_constraints = bias_pre_training_constraints
64
+ self.bias_post_training_constraints = bias_post_training_constraints
65
+ self.explainability_constraints = explainability_constraints
66
+ self.explainability_config_file = explainability_config_file
67
+
68
+ def _to_request_dict(self):
69
+ """Generates a request dictionary using the parameters provided to the class."""
70
+ drift_check_baselines_request = {}
71
+
72
+ model_quality = {}
73
+ if self.model_statistics is not None:
74
+ model_quality["Statistics"] = self.model_statistics._to_request_dict()
75
+ if self.model_constraints is not None:
76
+ model_quality["Constraints"] = self.model_constraints._to_request_dict()
77
+ if model_quality:
78
+ drift_check_baselines_request["ModelQuality"] = model_quality
79
+
80
+ model_data_quality = {}
81
+ if self.model_data_statistics is not None:
82
+ model_data_quality["Statistics"] = self.model_data_statistics._to_request_dict()
83
+ if self.model_data_constraints is not None:
84
+ model_data_quality["Constraints"] = self.model_data_constraints._to_request_dict()
85
+ if model_data_quality:
86
+ drift_check_baselines_request["ModelDataQuality"] = model_data_quality
87
+
88
+ bias = {}
89
+ if self.bias_config_file is not None:
90
+ bias["ConfigFile"] = self.bias_config_file._to_request_dict()
91
+ if self.bias_pre_training_constraints is not None:
92
+ bias["PreTrainingConstraints"] = self.bias_pre_training_constraints._to_request_dict()
93
+ if self.bias_post_training_constraints is not None:
94
+ bias["PostTrainingConstraints"] = self.bias_post_training_constraints._to_request_dict()
95
+ if bias:
96
+ drift_check_baselines_request["Bias"] = bias
97
+
98
+ explainability = {}
99
+ if self.explainability_constraints is not None:
100
+ explainability["Constraints"] = self.explainability_constraints._to_request_dict()
101
+ if self.explainability_config_file is not None:
102
+ explainability["ConfigFile"] = self.explainability_config_file._to_request_dict()
103
+ if explainability:
104
+ drift_check_baselines_request["Explainability"] = explainability
105
+
106
+ return drift_check_baselines_request
testbed/aws__sagemaker-python-sdk/src/sagemaker/environment_variables.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Accessors to retrieve environment variables for hosting containers."""
14
+
15
+ from __future__ import absolute_import
16
+
17
+ import logging
18
+ from typing import Dict
19
+
20
+ from sagemaker.jumpstart import utils as jumpstart_utils
21
+ from sagemaker.jumpstart import artifacts
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def retrieve_default(
27
+ region=None,
28
+ model_id=None,
29
+ model_version=None,
30
+ ) -> Dict[str, str]:
31
+ """Retrieves the default container environment variables for the model matching the arguments.
32
+
33
+ Args:
34
+ region (str): Optional. The AWS Region for which to retrieve the default environment
35
+ variables. (Default: None).
36
+ model_id (str): Optional. The model ID of the model for which to
37
+ retrieve the default environment variables. (Default: None).
38
+ model_version (str): Optional. The version of the model for which to retrieve the
39
+ default environment variables. (Default: None).
40
+ Returns:
41
+ dict: The variables to use for the model.
42
+
43
+ Raises:
44
+ ValueError: If the combination of arguments specified is not supported.
45
+ """
46
+ if not jumpstart_utils.is_jumpstart_model_input(model_id, model_version):
47
+ raise ValueError(
48
+ "Must specify `model_id` and `model_version` when retrieving environment variables."
49
+ )
50
+
51
+ return artifacts._retrieve_default_environment_variables(model_id, model_version, region)
testbed/aws__sagemaker-python-sdk/src/sagemaker/estimator.py ADDED
The diff for this file is too large to render. See raw diff
 
testbed/aws__sagemaker-python-sdk/src/sagemaker/exceptions.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Custom exception classes for Sagemaker SDK"""
14
+ from __future__ import absolute_import
15
+
16
+
17
+ class UnexpectedStatusException(ValueError):
18
+ """Raised when resource status is not expected and thus not allowed for further execution"""
19
+
20
+ def __init__(self, message, allowed_statuses, actual_status):
21
+ self.allowed_statuses = allowed_statuses
22
+ self.actual_status = actual_status
23
+ super(UnexpectedStatusException, self).__init__(message)
24
+
25
+
26
+ class CapacityError(UnexpectedStatusException):
27
+ """Raised when resource status is not expected and fails with a reason of CapacityError"""
28
+
29
+
30
+ class AsyncInferenceError(Exception):
31
+ """The base exception class for Async Inference exceptions."""
32
+
33
+ fmt = "An unspecified error occurred"
34
+
35
+ def __init__(self, **kwargs):
36
+ msg = self.fmt.format(**kwargs)
37
+ Exception.__init__(self, msg)
38
+ self.kwargs = kwargs
39
+
40
+
41
+ class ObjectNotExistedError(AsyncInferenceError):
42
+ """Raised when Amazon S3 object not exist in the given path"""
43
+
44
+ fmt = "Object not exist at {output_path}. {message}"
45
+
46
+ def __init__(self, message, output_path):
47
+ super().__init__(message=message, output_path=output_path)
48
+
49
+
50
+ class PollingTimeoutError(AsyncInferenceError):
51
+ """Raised when wait longer than expected and no result object in Amazon S3 bucket yet"""
52
+
53
+ fmt = "No result at {output_path} after polling for {seconds} seconds. {message}"
54
+
55
+ def __init__(self, message, output_path, seconds):
56
+ super().__init__(message=message, output_path=output_path, seconds=seconds)
57
+
58
+
59
+ class UnexpectedClientError(AsyncInferenceError):
60
+ """Raised when ClientError's error code is not expected"""
61
+
62
+ fmt = "Encountered unexpected client error: {message}"
63
+
64
+ def __init__(self, message):
65
+ super().__init__(message=message)
testbed/aws__sagemaker-python-sdk/src/sagemaker/git_utils.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ import os
17
+ import subprocess
18
+ import tempfile
19
+ import warnings
20
+ import six
21
+ from six.moves import urllib
22
+
23
+
24
+ def git_clone_repo(git_config, entry_point, source_dir=None, dependencies=None):
25
+ """Git clone repo containing the training code and serving code.
26
+
27
+ This method also validate ``git_config``, and set ``entry_point``,
28
+ ``source_dir`` and ``dependencies`` to the right file or directory in the
29
+ repo cloned.
30
+
31
+ Args:
32
+ git_config (dict[str, str]): Git configurations used for cloning files,
33
+ including ``repo``, ``branch``, ``commit``, ``2FA_enabled``,
34
+ ``username``, ``password`` and ``token``. The ``repo`` field is
35
+ required. All other fields are optional. ``repo`` specifies the Git
36
+ repository where your training script is stored. If you don't
37
+ provide ``branch``, the default value 'master' is used. If you don't
38
+ provide ``commit``, the latest commit in the specified branch is
39
+ used. ``2FA_enabled``, ``username``, ``password`` and ``token`` are
40
+ for authentication purpose. If ``2FA_enabled`` is not provided, we
41
+ consider 2FA as disabled.
42
+
43
+ For GitHub and GitHub-like repos, when SSH URLs are provided, it
44
+ doesn't matter whether 2FA is enabled or disabled; you should either
45
+ have no passphrase for the SSH key pairs, or have the ssh-agent
46
+ configured so that you will not be prompted for SSH passphrase when
47
+ you do 'git clone' command with SSH URLs. When https URLs are
48
+ provided: if 2FA is disabled, then either token or username+password
49
+ will be used for authentication if provided (token prioritized); if
50
+ 2FA is enabled, only token will be used for authentication if
51
+ provided. If required authentication info is not provided, python
52
+ SDK will try to use local credentials storage to authenticate. If
53
+ that fails either, an error message will be thrown.
54
+
55
+ For CodeCommit repos, 2FA is not supported, so '2FA_enabled' should
56
+ not be provided. There is no token in CodeCommit, so 'token' should
57
+ not be provided too. When 'repo' is an SSH URL, the requirements are
58
+ the same as GitHub-like repos. When 'repo' is an https URL,
59
+ username+password will be used for authentication if they are
60
+ provided; otherwise, python SDK will try to use either CodeCommit
61
+ credential helper or local credential storage for authentication.
62
+ entry_point (str): A relative location to the Python source file which
63
+ should be executed as the entry point to training or model hosting
64
+ in the Git repo.
65
+ source_dir (str): A relative location to a directory with other training
66
+ or model hosting source code dependencies aside from the entry point
67
+ file in the Git repo (default: None). Structure within this
68
+ directory are preserved when training on Amazon SageMaker.
69
+ dependencies (list[str]): A list of relative locations to directories
70
+ with any additional libraries that will be exported to the container
71
+ in the Git repo (default: []).
72
+
73
+ Returns:
74
+ dict: A dict that contains the updated values of entry_point, source_dir
75
+ and dependencies.
76
+
77
+ Raises:
78
+ CalledProcessError: If 1. failed to clone git repo
79
+ 2. failed to checkout the required branch
80
+ 3. failed to checkout the required commit
81
+ ValueError: If 1. entry point specified does not exist in the repo
82
+ 2. source dir specified does not exist in the repo
83
+ 3. dependencies specified do not exist in the repo
84
+ 4. wrong format is provided for git_config
85
+ """
86
+ if entry_point is None:
87
+ raise ValueError("Please provide an entry point.")
88
+ _validate_git_config(git_config)
89
+ dest_dir = tempfile.mkdtemp()
90
+ _generate_and_run_clone_command(git_config, dest_dir)
91
+
92
+ _checkout_branch_and_commit(git_config, dest_dir)
93
+
94
+ updated_paths = {
95
+ "entry_point": entry_point,
96
+ "source_dir": source_dir,
97
+ "dependencies": dependencies,
98
+ }
99
+
100
+ # check if the cloned repo contains entry point, source directory and dependencies
101
+ if source_dir:
102
+ if not os.path.isdir(os.path.join(dest_dir, source_dir)):
103
+ raise ValueError("Source directory does not exist in the repo.")
104
+ if not os.path.isfile(os.path.join(dest_dir, source_dir, entry_point)):
105
+ raise ValueError("Entry point does not exist in the repo.")
106
+ updated_paths["source_dir"] = os.path.join(dest_dir, source_dir)
107
+ else:
108
+ if os.path.isfile(os.path.join(dest_dir, entry_point)):
109
+ updated_paths["entry_point"] = os.path.join(dest_dir, entry_point)
110
+ else:
111
+ raise ValueError("Entry point does not exist in the repo.")
112
+ if dependencies is not None:
113
+ updated_paths["dependencies"] = []
114
+ for path in dependencies:
115
+ if os.path.exists(os.path.join(dest_dir, path)):
116
+ updated_paths["dependencies"].append(os.path.join(dest_dir, path))
117
+ else:
118
+ raise ValueError("Dependency {} does not exist in the repo.".format(path))
119
+ return updated_paths
120
+
121
+
122
+ def _validate_git_config(git_config):
123
+ """Validates the git configuration.
124
+
125
+ Checks all configuration values except 2FA_enabled are string types. The
126
+ 2FA_enabled configuration should be a boolean.
127
+
128
+ Args:
129
+ git_config: The configuration to validate.
130
+ """
131
+ if "repo" not in git_config:
132
+ raise ValueError("Please provide a repo for git_config.")
133
+ for key in git_config:
134
+ if key == "2FA_enabled":
135
+ if not isinstance(git_config["2FA_enabled"], bool):
136
+ raise ValueError("Please enter a bool type for 2FA_enabled'.")
137
+ elif not isinstance(git_config[key], six.string_types):
138
+ raise ValueError("'{}' must be a string.".format(key))
139
+
140
+
141
+ def _generate_and_run_clone_command(git_config, dest_dir):
142
+ """Check if a git_config param is valid.
143
+
144
+ If it is valid, create the command to git, clone the repo, and run it.
145
+
146
+ Args:
147
+ git_config ((dict[str, str]): Git configurations used for cloning files,
148
+ including ``repo``, ``branch`` and ``commit``.
149
+ dest_dir (str): The local directory to clone the Git repo into.
150
+
151
+ Raises:
152
+ CalledProcessError: If failed to clone git repo.
153
+ """
154
+ if git_config["repo"].startswith("https://git-codecommit") or git_config["repo"].startswith(
155
+ "ssh://git-codecommit"
156
+ ):
157
+ _clone_command_for_codecommit(git_config, dest_dir)
158
+ else:
159
+ _clone_command_for_github_like(git_config, dest_dir)
160
+
161
+
162
+ def _clone_command_for_github_like(git_config, dest_dir):
163
+ """Check if a git_config param representing a GitHub (or like) repo is valid.
164
+
165
+ If it is valid, create the command to git clone the repo, and run it.
166
+
167
+ Args:
168
+ git_config ((dict[str, str]): Git configurations used for cloning files,
169
+ including ``repo``, ``branch`` and ``commit``.
170
+ dest_dir (str): The local directory to clone the Git repo into.
171
+
172
+ Raises:
173
+ ValueError: If git_config['repo'] is in the wrong format.
174
+ CalledProcessError: If failed to clone git repo.
175
+ """
176
+ is_https = git_config["repo"].startswith("https://")
177
+ is_ssh = git_config["repo"].startswith("git@")
178
+ if not is_https and not is_ssh:
179
+ raise ValueError("Invalid Git url provided.")
180
+ if is_ssh:
181
+ _clone_command_for_ssh(git_config, dest_dir)
182
+ elif "2FA_enabled" in git_config and git_config["2FA_enabled"] is True:
183
+ _clone_command_for_github_like_https_2fa_enabled(git_config, dest_dir)
184
+ else:
185
+ _clone_command_for_github_like_https_2fa_disabled(git_config, dest_dir)
186
+
187
+
188
+ def _clone_command_for_ssh(git_config, dest_dir):
189
+ """Placeholder docstring"""
190
+ if "username" in git_config or "password" in git_config or "token" in git_config:
191
+ warnings.warn("SSH cloning, authentication information in git config will be ignored.")
192
+ _run_clone_command(git_config["repo"], dest_dir)
193
+
194
+
195
+ def _clone_command_for_github_like_https_2fa_disabled(git_config, dest_dir):
196
+ """Placeholder docstring"""
197
+ updated_url = git_config["repo"]
198
+ if "token" in git_config:
199
+ if "username" in git_config or "password" in git_config:
200
+ warnings.warn("Using token for authentication, " "other credentials will be ignored.")
201
+ updated_url = _insert_token_to_repo_url(url=git_config["repo"], token=git_config["token"])
202
+ elif "username" in git_config and "password" in git_config:
203
+ updated_url = _insert_username_and_password_to_repo_url(
204
+ url=git_config["repo"], username=git_config["username"], password=git_config["password"]
205
+ )
206
+ elif "username" in git_config or "password" in git_config:
207
+ warnings.warn("Credentials provided in git config will be ignored.")
208
+ _run_clone_command(updated_url, dest_dir)
209
+
210
+
211
+ def _clone_command_for_github_like_https_2fa_enabled(git_config, dest_dir):
212
+ """Placeholder docstring"""
213
+ updated_url = git_config["repo"]
214
+ if "token" in git_config:
215
+ if "username" in git_config or "password" in git_config:
216
+ warnings.warn("Using token for authentication, " "other credentials will be ignored.")
217
+ updated_url = _insert_token_to_repo_url(url=git_config["repo"], token=git_config["token"])
218
+ _run_clone_command(updated_url, dest_dir)
219
+
220
+
221
+ def _clone_command_for_codecommit(git_config, dest_dir):
222
+ """Check if a git_config param representing a CodeCommit repo is valid.
223
+
224
+ If it is, create the command to git clone the repo, and run it.
225
+
226
+ Args:
227
+ git_config ((dict[str, str]): Git configurations used for cloning files,
228
+ including ``repo``, ``branch`` and ``commit``.
229
+ dest_dir (str): The local directory to clone the Git repo into.
230
+
231
+ Raises:
232
+ ValueError: If git_config['repo'] is in the wrong format.
233
+ CalledProcessError: If failed to clone git repo.
234
+ """
235
+ is_https = git_config["repo"].startswith("https://git-codecommit")
236
+ is_ssh = git_config["repo"].startswith("ssh://git-codecommit")
237
+ if not is_https and not is_ssh:
238
+ raise ValueError("Invalid Git url provided.")
239
+ if "2FA_enabled" in git_config:
240
+ warnings.warn("CodeCommit does not support 2FA, '2FA_enabled' will be ignored.")
241
+ if "token" in git_config:
242
+ warnings.warn("There are no tokens in CodeCommit, the token provided will be ignored.")
243
+ if is_ssh:
244
+ _clone_command_for_ssh(git_config, dest_dir)
245
+ else:
246
+ _clone_command_for_codecommit_https(git_config, dest_dir)
247
+
248
+
249
+ def _clone_command_for_codecommit_https(git_config, dest_dir):
250
+ """Invoke the clone command for codecommit.
251
+
252
+ Args:
253
+ git_config: The git configuration.
254
+ dest_dir: The destination directory for the clone.
255
+ """
256
+ updated_url = git_config["repo"]
257
+ if "username" in git_config and "password" in git_config:
258
+ updated_url = _insert_username_and_password_to_repo_url(
259
+ url=git_config["repo"], username=git_config["username"], password=git_config["password"]
260
+ )
261
+ elif "username" in git_config or "password" in git_config:
262
+ warnings.warn("Credentials provided in git config will be ignored.")
263
+ _run_clone_command(updated_url, dest_dir)
264
+
265
+
266
+ def _run_clone_command(repo_url, dest_dir):
267
+ """Run the 'git clone' command with the repo url and the directory to clone the repo into.
268
+
269
+ Args:
270
+ repo_url (str): Git repo url to be cloned.
271
+ dest_dir: (str): Local path where the repo should be cloned into.
272
+
273
+ Raises:
274
+ CalledProcessError: If failed to clone git repo.
275
+ """
276
+ my_env = os.environ.copy()
277
+ if repo_url.startswith("https://"):
278
+ my_env["GIT_TERMINAL_PROMPT"] = "0"
279
+ subprocess.check_call(["git", "clone", repo_url, dest_dir], env=my_env)
280
+ elif repo_url.startswith("git@"):
281
+ with tempfile.NamedTemporaryFile() as sshnoprompt:
282
+ write_pipe = open(sshnoprompt.name, "w")
283
+ write_pipe.write("ssh -oBatchMode=yes $@")
284
+ write_pipe.close()
285
+ os.chmod(sshnoprompt.name, 0o511)
286
+ my_env["GIT_SSH"] = sshnoprompt.name
287
+ subprocess.check_call(["git", "clone", repo_url, dest_dir], env=my_env)
288
+
289
+
290
+ def _insert_token_to_repo_url(url, token):
291
+ """Insert the token to the Git repo url, to make a component of the git clone command.
292
+
293
+ This method can only be called when repo_url is an https url.
294
+
295
+ Args:
296
+ url (str): Git repo url where the token should be inserted into.
297
+ token (str): Token to be inserted.
298
+
299
+ Returns:
300
+ str: the component needed fot the git clone command.
301
+ """
302
+ index = len("https://")
303
+ if url.find(token) == index:
304
+ return url
305
+ return url.replace("https://", "https://" + token + "@")
306
+
307
+
308
+ def _insert_username_and_password_to_repo_url(url, username, password):
309
+ """Insert username and password to the Git repo url to make a component of git clone command.
310
+
311
+ This method can only be called when repo_url is an https url.
312
+
313
+ Args:
314
+ url (str): Git repo url where the token should be inserted into.
315
+ username (str): Username to be inserted.
316
+ password (str): Password to be inserted.
317
+
318
+ Returns:
319
+ str: the component needed for the git clone command.
320
+ """
321
+ password = urllib.parse.quote_plus(password)
322
+ # urllib parses ' ' as '+', but what we need is '%20' here
323
+ password = password.replace("+", "%20")
324
+ index = len("https://")
325
+ return url[:index] + username + ":" + password + "@" + url[index:]
326
+
327
+
328
+ def _checkout_branch_and_commit(git_config, dest_dir):
329
+ """Checkout the required branch and commit.
330
+
331
+ Args:
332
+ git_config (dict[str, str]): Git configurations used for cloning files,
333
+ including ``repo``, ``branch`` and ``commit``.
334
+ dest_dir (str): the directory where the repo is cloned
335
+
336
+ Raises:
337
+ CalledProcessError: If 1. failed to checkout the required branch 2.
338
+ failed to checkout the required commit
339
+ """
340
+ if "branch" in git_config:
341
+ subprocess.check_call(args=["git", "checkout", git_config["branch"]], cwd=str(dest_dir))
342
+ if "commit" in git_config:
343
+ subprocess.check_call(args=["git", "checkout", git_config["commit"]], cwd=str(dest_dir))
testbed/aws__sagemaker-python-sdk/src/sagemaker/hyperparameters.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Accessors to retrieve hyperparameters for training jobs."""
14
+
15
+ from __future__ import absolute_import
16
+
17
+ import logging
18
+ from typing import Dict, Optional
19
+
20
+ from sagemaker.jumpstart import utils as jumpstart_utils
21
+ from sagemaker.jumpstart import artifacts
22
+ from sagemaker.jumpstart.enums import HyperparameterValidationMode
23
+ from sagemaker.jumpstart.validators import validate_hyperparameters
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ def retrieve_default(
29
+ region=None,
30
+ model_id=None,
31
+ model_version=None,
32
+ include_container_hyperparameters=False,
33
+ ) -> Dict[str, str]:
34
+ """Retrieves the default training hyperparameters for the model matching the given arguments.
35
+
36
+ Args:
37
+ region (str): The AWS Region for which to retrieve the default hyperparameters.
38
+ Defaults to ``None``.
39
+ model_id (str): The model ID of the model for which to
40
+ retrieve the default hyperparameters. (Default: None).
41
+ model_version (str): The version of the model for which to retrieve the
42
+ default hyperparameters. (Default: None).
43
+ include_container_hyperparameters (bool): ``True`` if the container hyperparameters
44
+ should be returned. Container hyperparameters are not used to tune
45
+ the specific algorithm. They are used by SageMaker Training jobs to set up
46
+ the training container environment. For example, there is a container hyperparameter
47
+ that indicates the entrypoint script to use. These hyperparameters may be required
48
+ when creating a training job with boto3, however the ``Estimator`` classes
49
+ add required container hyperparameters to the job. (Default: False).
50
+ Returns:
51
+ dict: The hyperparameters to use for the model.
52
+
53
+ Raises:
54
+ ValueError: If the combination of arguments specified is not supported.
55
+ """
56
+ if not jumpstart_utils.is_jumpstart_model_input(model_id, model_version):
57
+ raise ValueError(
58
+ "Must specify `model_id` and `model_version` when retrieving hyperparameters."
59
+ )
60
+
61
+ return artifacts._retrieve_default_hyperparameters(
62
+ model_id, model_version, region, include_container_hyperparameters
63
+ )
64
+
65
+
66
+ def validate(
67
+ region: Optional[str] = None,
68
+ model_id: Optional[str] = None,
69
+ model_version: Optional[str] = None,
70
+ hyperparameters: Optional[dict] = None,
71
+ validation_mode: Optional[HyperparameterValidationMode] = None,
72
+ ) -> None:
73
+ """Validates hyperparameters for models.
74
+
75
+ Args:
76
+ region (str): The AWS Region for which to validate hyperparameters. (Default: None).
77
+ model_id (str): The model ID of the model for which to validate hyperparameters.
78
+ (Default: None).
79
+ model_version (str): The version of the model for which to validate hyperparameters.
80
+ (Default: None).
81
+ hyperparameters (dict): Hyperparameters to validate.
82
+ (Default: None).
83
+ validation_mode (HyperparameterValidationMode): Method of validation to use with
84
+ hyperparameters. If set to ``VALIDATE_PROVIDED``, only hyperparameters provided
85
+ to this function will be validated, the missing hyperparameters will be ignored.
86
+ If set to``VALIDATE_ALGORITHM``, all algorithm hyperparameters will be validated.
87
+ If set to ``VALIDATE_ALL``, all hyperparameters for the model will be validated.
88
+ (Default: None).
89
+
90
+ Raises:
91
+ JumpStartHyperparametersError: If the hyperparameter is not formatted correctly,
92
+ according to its specs in the model metadata.
93
+ ValueError: If the combination of arguments specified is not supported.
94
+
95
+ """
96
+
97
+ if not jumpstart_utils.is_jumpstart_model_input(model_id, model_version):
98
+ raise ValueError(
99
+ "Must specify `model_id` and `model_version` when validating hyperparameters."
100
+ )
101
+
102
+ if hyperparameters is None:
103
+ raise ValueError("Must specify hyperparameters.")
104
+
105
+ return validate_hyperparameters(
106
+ model_id=model_id,
107
+ model_version=model_version,
108
+ hyperparameters=hyperparameters,
109
+ validation_mode=validation_mode,
110
+ region=region,
111
+ )
testbed/aws__sagemaker-python-sdk/src/sagemaker/inputs.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Amazon SageMaker channel configurations for S3 data sources and file system data sources"""
14
+ from __future__ import absolute_import, print_function
15
+
16
+ from typing import Union, Optional, List
17
+ import attr
18
+
19
+ from sagemaker.workflow.entities import PipelineVariable
20
+
21
+ FILE_SYSTEM_TYPES = ["FSxLustre", "EFS"]
22
+ FILE_SYSTEM_ACCESS_MODES = ["ro", "rw"]
23
+
24
+
25
+ class TrainingInput(object):
26
+ """Amazon SageMaker channel configurations for S3 data sources.
27
+
28
+ Attributes:
29
+ config (dict[str, dict]): A SageMaker ``DataSource`` referencing
30
+ a SageMaker ``S3DataSource``.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ s3_data: Union[str, PipelineVariable],
36
+ distribution: Optional[Union[str, PipelineVariable]] = None,
37
+ compression: Optional[Union[str, PipelineVariable]] = None,
38
+ content_type: Optional[Union[str, PipelineVariable]] = None,
39
+ record_wrapping: Optional[Union[str, PipelineVariable]] = None,
40
+ s3_data_type: Union[str, PipelineVariable] = "S3Prefix",
41
+ instance_groups: Optional[List[Union[str, PipelineVariable]]] = None,
42
+ input_mode: Optional[Union[str, PipelineVariable]] = None,
43
+ attribute_names: Optional[List[Union[str, PipelineVariable]]] = None,
44
+ target_attribute_name: Optional[Union[str, PipelineVariable]] = None,
45
+ shuffle_config: Optional["ShuffleConfig"] = None,
46
+ ):
47
+ r"""Create a definition for input data used by an SageMaker training job.
48
+
49
+ See AWS documentation on the ``CreateTrainingJob`` API for more details
50
+ on the parameters.
51
+
52
+ Args:
53
+ s3_data (str or PipelineVariable): Defines the location of S3 data to train on.
54
+ distribution (str or PipelineVariable): Valid values: ``'FullyReplicated'``,
55
+ ``'ShardedByS3Key'`` (default: ``'FullyReplicated'``).
56
+ compression (str or PipelineVariable): Valid values: ``'Gzip'``, ``None``
57
+ (default: None). This is used only in Pipe input mode.
58
+ content_type (str or PipelineVariable): MIME type of the input data
59
+ (default: None).
60
+ record_wrapping (str or PipelineVariable): Valid values: 'RecordIO'
61
+ (default: None).
62
+ s3_data_type (str or PipelineVariable): Valid values: ``'S3Prefix'``,
63
+ ``'ManifestFile'``, ``'AugmentedManifestFile'``.
64
+ If ``'S3Prefix'``, ``s3_data`` defines a prefix of s3 objects to train on.
65
+ All objects with s3 keys beginning with ``s3_data`` will be used to train.
66
+ If ``'ManifestFile'`` or ``'AugmentedManifestFile'``,
67
+ then ``s3_data`` defines a
68
+ single S3 manifest file or augmented manifest file respectively,
69
+ listing the S3 data to train on. Both the ManifestFile and
70
+ AugmentedManifestFile formats are described at `S3DataSource
71
+ <https://docs.aws.amazon.com/sagemaker/latest/dg/API_S3DataSource.html>`_
72
+ in the `Amazon SageMaker API reference`.
73
+ instance_groups (list[str] or list[PipelineVariable]): Optional. A list of
74
+ instance group names in string format that you specified while configuring
75
+ a heterogeneous cluster using the :class:`sagemaker.instance_group.InstanceGroup`.
76
+ S3 data will be sent to all instance groups in the specified list.
77
+ For instructions on how to use InstanceGroup objects
78
+ to configure a heterogeneous cluster
79
+ through the SageMaker generic and framework estimator classes, see
80
+ `Train Using a Heterogeneous Cluster
81
+ <https://docs.aws.amazon.com/sagemaker/latest/dg/train-heterogeneous-cluster.html>`_
82
+ in the *Amazon SageMaker developer guide*.
83
+ (default: None)
84
+ input_mode (str or PipelineVariable): Optional override for this channel's input mode
85
+ (default: None). By default, channels will use the input mode defined on
86
+ ``sagemaker.estimator.EstimatorBase.input_mode``, but they will ignore
87
+ that setting if this parameter is set.
88
+
89
+ * None - Amazon SageMaker will use the input mode specified in the ``Estimator``
90
+ * 'File' - Amazon SageMaker copies the training dataset from the S3 location to
91
+ a local directory.
92
+ * 'Pipe' - Amazon SageMaker streams data directly from S3 to the container via
93
+ a Unix-named pipe.
94
+ * 'FastFile' - Amazon SageMaker streams data from S3 on demand instead of
95
+ downloading the entire dataset before training begins.
96
+
97
+ attribute_names (list[str] or list[PipelineVariable]): A list of one or more attribute
98
+ names to use that are found in a specified AugmentedManifestFile.
99
+ target_attribute_name (str or PipelineVariable): The name of the attribute will be
100
+ predicted (classified) in a SageMaker AutoML job. It is required if the input is
101
+ for SageMaker AutoML job.
102
+ shuffle_config (sagemaker.inputs.ShuffleConfig): If specified this configuration enables
103
+ shuffling on this channel. See the SageMaker API documentation for more info:
104
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_ShuffleConfig.html
105
+ """
106
+ self.config = {
107
+ "DataSource": {"S3DataSource": {"S3DataType": s3_data_type, "S3Uri": s3_data}}
108
+ }
109
+
110
+ if not (target_attribute_name or distribution):
111
+ distribution = "FullyReplicated"
112
+
113
+ if distribution is not None:
114
+ self.config["DataSource"]["S3DataSource"]["S3DataDistributionType"] = distribution
115
+
116
+ if compression is not None:
117
+ self.config["CompressionType"] = compression
118
+ if content_type is not None:
119
+ self.config["ContentType"] = content_type
120
+ if record_wrapping is not None:
121
+ self.config["RecordWrapperType"] = record_wrapping
122
+ if instance_groups is not None:
123
+ self.config["DataSource"]["S3DataSource"]["InstanceGroupNames"] = instance_groups
124
+ if input_mode is not None:
125
+ self.config["InputMode"] = input_mode
126
+ if attribute_names is not None:
127
+ self.config["DataSource"]["S3DataSource"]["AttributeNames"] = attribute_names
128
+ if target_attribute_name is not None:
129
+ self.config["TargetAttributeName"] = target_attribute_name
130
+ if shuffle_config is not None:
131
+ self.config["ShuffleConfig"] = {"Seed": shuffle_config.seed}
132
+
133
+
134
+ class ShuffleConfig(object):
135
+ """For configuring channel shuffling using a seed.
136
+
137
+ For more detail, see the AWS documentation:
138
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_ShuffleConfig.html
139
+ """
140
+
141
+ def __init__(self, seed):
142
+ """Create a ShuffleConfig.
143
+
144
+ Args:
145
+ seed (long): the long value used to seed the shuffled sequence.
146
+ """
147
+ self.seed = seed
148
+
149
+
150
+ @attr.s
151
+ class CreateModelInput(object):
152
+ """A class containing parameters which can be used to create a SageMaker Model
153
+
154
+ Parameters:
155
+ instance_type (str): type or EC2 instance will be used for model deployment.
156
+ accelerator_type (str): elastic inference accelerator type.
157
+ """
158
+
159
+ instance_type: str = attr.ib(default=None)
160
+ accelerator_type: str = attr.ib(default=None)
161
+
162
+
163
+ @attr.s
164
+ class TransformInput(object):
165
+ """Create a class containing all the parameters.
166
+
167
+ It can be used when calling ``sagemaker.transformer.Transformer.transform()``
168
+ """
169
+
170
+ data: str = attr.ib()
171
+ data_type: str = attr.ib(default="S3Prefix")
172
+ content_type: str = attr.ib(default=None)
173
+ compression_type: str = attr.ib(default=None)
174
+ split_type: str = attr.ib(default=None)
175
+ input_filter: str = attr.ib(default=None)
176
+ output_filter: str = attr.ib(default=None)
177
+ join_source: str = attr.ib(default=None)
178
+ model_client_config: dict = attr.ib(default=None)
179
+ batch_data_capture_config: dict = attr.ib(default=None)
180
+
181
+
182
+ class FileSystemInput(object):
183
+ """Amazon SageMaker channel configurations for file system data sources.
184
+
185
+ Attributes:
186
+ config (dict[str, dict]): A Sagemaker File System ``DataSource``.
187
+ """
188
+
189
+ def __init__(
190
+ self,
191
+ file_system_id,
192
+ file_system_type,
193
+ directory_path,
194
+ file_system_access_mode="ro",
195
+ content_type=None,
196
+ ):
197
+ """Create a new file system input used by an SageMaker training job.
198
+
199
+ Args:
200
+ file_system_id (str): An Amazon file system ID starting with 'fs-'.
201
+ file_system_type (str): The type of file system used for the input.
202
+ Valid values: 'EFS', 'FSxLustre'.
203
+ directory_path (str): Absolute or normalized path to the root directory (mount point) in
204
+ the file system.
205
+ Reference: https://docs.aws.amazon.com/efs/latest/ug/mounting-fs.html and
206
+ https://docs.aws.amazon.com/fsx/latest/LustreGuide/mount-fs-auto-mount-onreboot.html
207
+ file_system_access_mode (str): Permissions for read and write.
208
+ Valid values: 'ro' or 'rw'. Defaults to 'ro'.
209
+ """
210
+
211
+ if file_system_type not in FILE_SYSTEM_TYPES:
212
+ raise ValueError(
213
+ "Unrecognized file system type: %s. Valid values: %s."
214
+ % (file_system_type, ", ".join(FILE_SYSTEM_TYPES))
215
+ )
216
+
217
+ if file_system_access_mode not in FILE_SYSTEM_ACCESS_MODES:
218
+ raise ValueError(
219
+ "Unrecognized file system access mode: %s. Valid values: %s."
220
+ % (file_system_access_mode, ", ".join(FILE_SYSTEM_ACCESS_MODES))
221
+ )
222
+
223
+ self.config = {
224
+ "DataSource": {
225
+ "FileSystemDataSource": {
226
+ "FileSystemId": file_system_id,
227
+ "FileSystemType": file_system_type,
228
+ "DirectoryPath": directory_path,
229
+ "FileSystemAccessMode": file_system_access_mode,
230
+ }
231
+ }
232
+ }
233
+
234
+ if content_type:
235
+ self.config["ContentType"] = content_type
236
+
237
+
238
+ class BatchDataCaptureConfig(object):
239
+ """Configuration object passed in when create a batch transform job.
240
+
241
+ Specifies configuration related to batch transform job data capture for use with
242
+ Amazon SageMaker Model Monitoring
243
+ """
244
+
245
+ def __init__(
246
+ self,
247
+ destination_s3_uri: str,
248
+ kms_key_id: str = None,
249
+ generate_inference_id: bool = None,
250
+ ):
251
+ """Create new BatchDataCaptureConfig
252
+
253
+ Args:
254
+ destination_s3_uri (str): S3 Location to store the captured data
255
+ kms_key_id (str): The KMS key to use when writing to S3.
256
+ KmsKeyId can be an ID of a KMS key, ARN of a KMS key, alias of a KMS key,
257
+ or alias of a KMS key. The KmsKeyId is applied to all outputs.
258
+ (default: None)
259
+ generate_inference_id (bool): Flag to generate an inference id
260
+ (default: None)
261
+ """
262
+ self.destination_s3_uri = destination_s3_uri
263
+ self.kms_key_id = kms_key_id
264
+ self.generate_inference_id = generate_inference_id
265
+
266
+ def _to_request_dict(self):
267
+ """Generates a request dictionary using the parameters provided to the class."""
268
+ batch_data_capture_config = {
269
+ "DestinationS3Uri": self.destination_s3_uri,
270
+ }
271
+
272
+ if self.kms_key_id is not None:
273
+ batch_data_capture_config["KmsKeyId"] = self.kms_key_id
274
+ if self.generate_inference_id is not None:
275
+ batch_data_capture_config["GenerateInferenceId"] = self.generate_inference_id
276
+
277
+ return batch_data_capture_config
testbed/aws__sagemaker-python-sdk/src/sagemaker/instance_group.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Defines the InstanceGroup class that configures a heterogeneous cluster."""
14
+ from __future__ import absolute_import
15
+
16
+
17
+ class InstanceGroup(object):
18
+ """The class to create instance groups for a heterogeneous cluster."""
19
+
20
+ def __init__(
21
+ self,
22
+ instance_group_name=None,
23
+ instance_type=None,
24
+ instance_count=None,
25
+ ):
26
+ """It initializes an ``InstanceGroup`` instance.
27
+
28
+ You can create instance group object of the ``InstanceGroup`` class
29
+ by specifying the instance group configuration arguments.
30
+
31
+ For instructions on how to use InstanceGroup objects
32
+ to configure a heterogeneous cluster
33
+ through the SageMaker generic and framework estimator classes, see
34
+ `Train Using a Heterogeneous Cluster
35
+ <https://docs.aws.amazon.com/sagemaker/latest/dg/train-heterogeneous-cluster.html>`_
36
+ in the *Amazon SageMaker developer guide*.
37
+
38
+ Args:
39
+ instance_group_name (str): The name of the instance group.
40
+ instance_type (str): The instance type to use in the instance group.
41
+ instance_count (int): The number of instances to use in the instance group.
42
+
43
+ .. tip::
44
+
45
+ For more information about available values for the arguments,
46
+ see `InstanceGroup
47
+ <https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_InstanceGroup.html>`_
48
+ API in the `Amazon SageMaker API reference`.
49
+
50
+ """
51
+ self.instance_group_name = instance_group_name
52
+ self.instance_type = instance_type
53
+ self.instance_count = instance_count
54
+
55
+ def _to_request_dict(self):
56
+ """Generates a request dictionary using the parameters provided to the class."""
57
+ return {
58
+ "InstanceGroupName": self.instance_group_name,
59
+ "InstanceType": self.instance_type,
60
+ "InstanceCount": self.instance_count,
61
+ }
testbed/aws__sagemaker-python-sdk/src/sagemaker/job.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ from abc import abstractmethod
17
+ from six import string_types
18
+
19
+ from sagemaker.inputs import FileSystemInput, TrainingInput
20
+ from sagemaker.local import file_input
21
+ from sagemaker.workflow import is_pipeline_variable
22
+
23
+
24
+ class _Job(object):
25
+ """Handle creating, starting and waiting for Amazon SageMaker jobs to finish.
26
+
27
+ This class shouldn't be directly instantiated.
28
+
29
+ Subclasses must define a way to create, start and wait for an Amazon
30
+ SageMaker job.
31
+ """
32
+
33
+ def __init__(self, sagemaker_session, job_name):
34
+ """Placeholder docstring"""
35
+ self.sagemaker_session = sagemaker_session
36
+ self.job_name = job_name
37
+
38
+ @abstractmethod
39
+ def start_new(self, estimator, inputs):
40
+ """Create a new Amazon SageMaker job from the estimator.
41
+
42
+ Args:
43
+ estimator (sagemaker.estimator.EstimatorBase): Estimator object
44
+ created by the user.
45
+ inputs (str): Parameters used when called
46
+ :meth:`~sagemaker.estimator.EstimatorBase.fit`.
47
+
48
+ Returns:
49
+ sagemaker.job: Constructed object that captures all information
50
+ about the started job.
51
+ """
52
+
53
+ @abstractmethod
54
+ def wait(self):
55
+ """Wait for the Amazon SageMaker job to finish."""
56
+
57
+ @abstractmethod
58
+ def describe(self):
59
+ """Describe the job."""
60
+
61
+ @abstractmethod
62
+ def stop(self):
63
+ """Stop the job."""
64
+
65
+ @staticmethod
66
+ def _load_config(inputs, estimator, expand_role=True, validate_uri=True):
67
+ """Placeholder docstring"""
68
+ input_config = _Job._format_inputs_to_input_config(inputs, validate_uri)
69
+ role = (
70
+ estimator.sagemaker_session.expand_role(estimator.role)
71
+ if (expand_role and not is_pipeline_variable(estimator.role))
72
+ else estimator.role
73
+ )
74
+ output_config = _Job._prepare_output_config(estimator.output_path, estimator.output_kms_key)
75
+ resource_config = _Job._prepare_resource_config(
76
+ estimator.instance_count,
77
+ estimator.instance_type,
78
+ estimator.instance_groups,
79
+ estimator.volume_size,
80
+ estimator.volume_kms_key,
81
+ estimator.keep_alive_period_in_seconds,
82
+ )
83
+ stop_condition = _Job._prepare_stop_condition(estimator.max_run, estimator.max_wait)
84
+ vpc_config = estimator.get_vpc_config()
85
+
86
+ model_channel = _Job._prepare_channel(
87
+ input_config,
88
+ estimator.model_uri,
89
+ estimator.model_channel_name,
90
+ validate_uri,
91
+ content_type="application/x-sagemaker-model",
92
+ input_mode="File",
93
+ )
94
+ if model_channel:
95
+ input_config = [] if input_config is None else input_config
96
+ input_config.append(model_channel)
97
+
98
+ if estimator.enable_network_isolation():
99
+ code_channel = _Job._prepare_channel(
100
+ input_config, estimator.code_uri, estimator.code_channel_name, validate_uri
101
+ )
102
+
103
+ if code_channel:
104
+ input_config = [] if input_config is None else input_config
105
+ input_config.append(code_channel)
106
+
107
+ return {
108
+ "input_config": input_config,
109
+ "role": role,
110
+ "output_config": output_config,
111
+ "resource_config": resource_config,
112
+ "stop_condition": stop_condition,
113
+ "vpc_config": vpc_config,
114
+ }
115
+
116
+ @staticmethod
117
+ def _format_inputs_to_input_config(inputs, validate_uri=True):
118
+ """Placeholder docstring"""
119
+ if inputs is None:
120
+ return None
121
+
122
+ # Deferred import due to circular dependency
123
+ from sagemaker.amazon.amazon_estimator import RecordSet
124
+ from sagemaker.amazon.amazon_estimator import FileSystemRecordSet
125
+
126
+ if isinstance(inputs, (RecordSet, FileSystemRecordSet)):
127
+ inputs = inputs.data_channel()
128
+
129
+ input_dict = {}
130
+ if isinstance(inputs, string_types):
131
+ input_dict["training"] = _Job._format_string_uri_input(inputs, validate_uri)
132
+ elif isinstance(inputs, TrainingInput):
133
+ input_dict["training"] = inputs
134
+ elif isinstance(inputs, file_input):
135
+ input_dict["training"] = inputs
136
+ elif isinstance(inputs, dict):
137
+ for k, v in inputs.items():
138
+ input_dict[k] = _Job._format_string_uri_input(v, validate_uri)
139
+ elif isinstance(inputs, list):
140
+ input_dict = _Job._format_record_set_list_input(inputs)
141
+ elif isinstance(inputs, FileSystemInput):
142
+ input_dict["training"] = inputs
143
+ else:
144
+ msg = (
145
+ "Cannot format input {}. Expecting one of str, dict, TrainingInput or "
146
+ "FileSystemInput"
147
+ )
148
+ raise ValueError(msg.format(inputs))
149
+
150
+ channels = [
151
+ _Job._convert_input_to_channel(name, input) for name, input in input_dict.items()
152
+ ]
153
+
154
+ return channels
155
+
156
+ @staticmethod
157
+ def _convert_input_to_channel(channel_name, channel_s3_input):
158
+ """Placeholder docstring"""
159
+ channel_config = channel_s3_input.config.copy()
160
+ channel_config["ChannelName"] = channel_name
161
+ return channel_config
162
+
163
+ @staticmethod
164
+ def _format_string_uri_input(
165
+ uri_input,
166
+ validate_uri=True,
167
+ content_type=None,
168
+ input_mode=None,
169
+ compression=None,
170
+ target_attribute_name=None,
171
+ ):
172
+ """Placeholder docstring"""
173
+ s3_input_result = TrainingInput(
174
+ uri_input,
175
+ content_type=content_type,
176
+ input_mode=input_mode,
177
+ compression=compression,
178
+ target_attribute_name=target_attribute_name,
179
+ )
180
+ if isinstance(uri_input, str) and validate_uri and uri_input.startswith("s3://"):
181
+ return s3_input_result
182
+ if isinstance(uri_input, str) and validate_uri and uri_input.startswith("file://"):
183
+ return file_input(uri_input)
184
+ if isinstance(uri_input, str) and validate_uri:
185
+ raise ValueError(
186
+ 'URI input {} must be a valid S3 or FILE URI: must start with "s3://" or '
187
+ '"file://"'.format(uri_input)
188
+ )
189
+ if isinstance(uri_input, str):
190
+ return s3_input_result
191
+ if isinstance(uri_input, (TrainingInput, file_input, FileSystemInput)):
192
+ return uri_input
193
+ if is_pipeline_variable(uri_input):
194
+ return s3_input_result
195
+
196
+ raise ValueError(
197
+ "Cannot format input {}. Expecting one of str, TrainingInput, file_input or "
198
+ "FileSystemInput".format(uri_input)
199
+ )
200
+
201
+ @staticmethod
202
+ def _prepare_channel(
203
+ input_config,
204
+ channel_uri=None,
205
+ channel_name=None,
206
+ validate_uri=True,
207
+ content_type=None,
208
+ input_mode=None,
209
+ ):
210
+ """Placeholder docstring"""
211
+ if not channel_uri:
212
+ return None
213
+ if not channel_name:
214
+ raise ValueError(
215
+ "Expected a channel name if a channel URI {} is specified".format(channel_uri)
216
+ )
217
+
218
+ if input_config:
219
+ for existing_channel in input_config:
220
+ if existing_channel["ChannelName"] == channel_name:
221
+ raise ValueError("Duplicate channel {} not allowed.".format(channel_name))
222
+
223
+ channel_input = _Job._format_string_uri_input(
224
+ channel_uri, validate_uri, content_type, input_mode
225
+ )
226
+ channel = _Job._convert_input_to_channel(channel_name, channel_input)
227
+
228
+ return channel
229
+
230
+ @staticmethod
231
+ def _format_model_uri_input(model_uri, validate_uri=True):
232
+ """Placeholder docstring"""
233
+ if isinstance(model_uri, string_types) and validate_uri and model_uri.startswith("s3://"):
234
+ return TrainingInput(
235
+ model_uri,
236
+ input_mode="File",
237
+ distribution="FullyReplicated",
238
+ content_type="application/x-sagemaker-model",
239
+ )
240
+ if isinstance(model_uri, string_types) and validate_uri and model_uri.startswith("file://"):
241
+ return file_input(model_uri)
242
+ if isinstance(model_uri, string_types) and validate_uri:
243
+ raise ValueError(
244
+ 'Model URI must be a valid S3 or FILE URI: must start with "s3://" or ' '"file://'
245
+ )
246
+ if isinstance(model_uri, string_types):
247
+ return TrainingInput(
248
+ model_uri,
249
+ input_mode="File",
250
+ distribution="FullyReplicated",
251
+ content_type="application/x-sagemaker-model",
252
+ )
253
+ raise ValueError("Cannot format model URI {}. Expecting str".format(model_uri))
254
+
255
+ @staticmethod
256
+ def _format_record_set_list_input(inputs):
257
+ """Placeholder docstring"""
258
+ # Deferred import due to circular dependency
259
+ from sagemaker.amazon.amazon_estimator import FileSystemRecordSet, RecordSet
260
+
261
+ input_dict = {}
262
+ for record in inputs:
263
+ if not isinstance(record, (RecordSet, FileSystemRecordSet)):
264
+ raise ValueError("List compatible only with RecordSets or FileSystemRecordSets.")
265
+
266
+ if record.channel in input_dict:
267
+ raise ValueError("Duplicate channels not allowed.")
268
+ if isinstance(record, RecordSet):
269
+ input_dict[record.channel] = record.records_s3_input()
270
+ if isinstance(record, FileSystemRecordSet):
271
+ input_dict[record.channel] = record.file_system_input
272
+
273
+ return input_dict
274
+
275
+ @staticmethod
276
+ def _prepare_output_config(s3_path, kms_key_id):
277
+ """Placeholder docstring"""
278
+ config = {"S3OutputPath": s3_path}
279
+ if kms_key_id is not None:
280
+ config["KmsKeyId"] = kms_key_id
281
+ return config
282
+
283
+ @staticmethod
284
+ def _prepare_resource_config(
285
+ instance_count,
286
+ instance_type,
287
+ instance_groups,
288
+ volume_size,
289
+ volume_kms_key,
290
+ keep_alive_period_in_seconds,
291
+ ):
292
+ """Placeholder docstring"""
293
+ resource_config = {
294
+ "VolumeSizeInGB": volume_size,
295
+ }
296
+ if volume_kms_key is not None:
297
+ resource_config["VolumeKmsKeyId"] = volume_kms_key
298
+ if keep_alive_period_in_seconds is not None:
299
+ resource_config["KeepAlivePeriodInSeconds"] = keep_alive_period_in_seconds
300
+ if instance_groups is not None:
301
+ if instance_count is not None or instance_type is not None:
302
+ raise ValueError(
303
+ "instance_count and instance_type cannot be set when instance_groups is set"
304
+ )
305
+
306
+ resource_config["InstanceGroups"] = [
307
+ group._to_request_dict() for group in instance_groups
308
+ ]
309
+ else:
310
+ if instance_count is None or instance_type is None:
311
+ raise ValueError(
312
+ "instance_count and instance_type must be set if instance_groups is not set"
313
+ )
314
+ resource_config["InstanceCount"] = instance_count
315
+ resource_config["InstanceType"] = instance_type
316
+
317
+ return resource_config
318
+
319
+ @staticmethod
320
+ def _prepare_stop_condition(max_run, max_wait):
321
+ """Placeholder docstring"""
322
+ if max_wait:
323
+ return {"MaxRuntimeInSeconds": max_run, "MaxWaitTimeInSeconds": max_wait}
324
+ return {"MaxRuntimeInSeconds": max_run}
325
+
326
+ @property
327
+ def name(self):
328
+ """Placeholder docstring"""
329
+ return self.job_name
testbed/aws__sagemaker-python-sdk/src/sagemaker/metadata_properties.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """This file contains code related to metadata properties."""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import Optional, Union
17
+
18
+ from sagemaker.workflow.entities import PipelineVariable
19
+
20
+
21
+ class MetadataProperties(object):
22
+ """Accepts metadata properties parameters for conversion to request dict."""
23
+
24
+ def __init__(
25
+ self,
26
+ commit_id: Optional[Union[str, PipelineVariable]] = None,
27
+ repository: Optional[Union[str, PipelineVariable]] = None,
28
+ generated_by: Optional[Union[str, PipelineVariable]] = None,
29
+ project_id: Optional[Union[str, PipelineVariable]] = None,
30
+ ):
31
+ """Initialize a ``MetadataProperties`` instance and turn parameters into dict.
32
+
33
+ # TODO: flesh out docstrings
34
+ Args:
35
+ commit_id (str or PipelineVariable):
36
+ repository (str or PipelineVariable):
37
+ generated_by (str or PipelineVariable):
38
+ project_id (str or PipelineVariable):
39
+ """
40
+ self.commit_id = commit_id
41
+ self.repository = repository
42
+ self.generated_by = generated_by
43
+ self.project_id = project_id
44
+
45
+ def _to_request_dict(self):
46
+ """Generates a request dictionary using the parameters provided to the class."""
47
+ metadata_properties_request = dict()
48
+ if self.commit_id:
49
+ metadata_properties_request["CommitId"] = self.commit_id
50
+ if self.repository:
51
+ metadata_properties_request["Repository"] = self.repository
52
+ if self.generated_by:
53
+ metadata_properties_request["GeneratedBy"] = self.generated_by
54
+ if self.project_id:
55
+ metadata_properties_request["ProjectId"] = self.project_id
56
+ return metadata_properties_request
testbed/aws__sagemaker-python-sdk/src/sagemaker/model.py ADDED
@@ -0,0 +1,1604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ import abc
17
+ import json
18
+ import logging
19
+ import os
20
+ import copy
21
+ from typing import List, Dict, Optional, Union
22
+
23
+ import sagemaker
24
+ from sagemaker import (
25
+ fw_utils,
26
+ local,
27
+ s3,
28
+ session,
29
+ utils,
30
+ git_utils,
31
+ )
32
+ from sagemaker.session import Session
33
+ from sagemaker.model_metrics import ModelMetrics
34
+ from sagemaker.deprecations import removed_kwargs
35
+ from sagemaker.drift_check_baselines import DriftCheckBaselines
36
+ from sagemaker.metadata_properties import MetadataProperties
37
+ from sagemaker.predictor import PredictorBase
38
+ from sagemaker.serverless import ServerlessInferenceConfig
39
+ from sagemaker.transformer import Transformer
40
+ from sagemaker.jumpstart.utils import add_jumpstart_tags, get_jumpstart_base_name_if_jumpstart_model
41
+ from sagemaker.utils import (
42
+ unique_name_from_base,
43
+ update_container_with_inference_params,
44
+ to_string,
45
+ )
46
+ from sagemaker.async_inference import AsyncInferenceConfig
47
+ from sagemaker.predictor_async import AsyncPredictor
48
+ from sagemaker.workflow import is_pipeline_variable
49
+ from sagemaker.workflow.entities import PipelineVariable
50
+ from sagemaker.workflow.pipeline_context import runnable_by_pipeline, PipelineSession
51
+
52
+ LOGGER = logging.getLogger("sagemaker")
53
+
54
+ NEO_ALLOWED_FRAMEWORKS = set(
55
+ ["mxnet", "tensorflow", "keras", "pytorch", "onnx", "xgboost", "tflite"]
56
+ )
57
+
58
+ NEO_IOC_TARGET_DEVICES = ["ml_c4", "ml_c5", "ml_m4", "ml_m5", "ml_p2", "ml_p3", "ml_g4dn"]
59
+
60
+
61
+ class ModelBase(abc.ABC):
62
+ """An object that encapsulates a trained model.
63
+
64
+ Models can be deployed to compute services like a SageMaker ``Endpoint``
65
+ or Lambda. Deployed models can be used to perform real-time inference.
66
+ """
67
+
68
+ @abc.abstractmethod
69
+ def deploy(self, *args, **kwargs) -> PredictorBase:
70
+ """Deploy this model to a compute service."""
71
+
72
+ @abc.abstractmethod
73
+ def delete_model(self, *args, **kwargs) -> None:
74
+ """Destroy resources associated with this model."""
75
+
76
+
77
+ SCRIPT_PARAM_NAME = "sagemaker_program"
78
+ DIR_PARAM_NAME = "sagemaker_submit_directory"
79
+ CONTAINER_LOG_LEVEL_PARAM_NAME = "sagemaker_container_log_level"
80
+ JOB_NAME_PARAM_NAME = "sagemaker_job_name"
81
+ MODEL_SERVER_WORKERS_PARAM_NAME = "sagemaker_model_server_workers"
82
+ SAGEMAKER_REGION_PARAM_NAME = "sagemaker_region"
83
+ SAGEMAKER_OUTPUT_LOCATION = "sagemaker_s3_output"
84
+
85
+
86
+ class Model(ModelBase):
87
+ """A SageMaker ``Model`` that can be deployed to an ``Endpoint``."""
88
+
89
+ def __init__(
90
+ self,
91
+ image_uri: Union[str, PipelineVariable],
92
+ model_data: Optional[Union[str, PipelineVariable]] = None,
93
+ role: Optional[str] = None,
94
+ predictor_cls: Optional[callable] = None,
95
+ env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
96
+ name: Optional[str] = None,
97
+ vpc_config: Optional[Dict[str, List[Union[str, PipelineVariable]]]] = None,
98
+ sagemaker_session: Optional[Session] = None,
99
+ enable_network_isolation: Union[bool, PipelineVariable] = False,
100
+ model_kms_key: Optional[str] = None,
101
+ image_config: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
102
+ source_dir: Optional[str] = None,
103
+ code_location: Optional[str] = None,
104
+ entry_point: Optional[str] = None,
105
+ container_log_level: Union[int, PipelineVariable] = logging.INFO,
106
+ dependencies: Optional[List[str]] = None,
107
+ git_config: Optional[Dict[str, str]] = None,
108
+ ):
109
+ """Initialize an SageMaker ``Model``.
110
+
111
+ Args:
112
+ image_uri (str or PipelineVariable): A Docker image URI.
113
+ model_data (str or PipelineVariable): The S3 location of a SageMaker
114
+ model data ``.tar.gz`` file (default: None).
115
+ role (str): An AWS IAM role (either name or full ARN). The Amazon
116
+ SageMaker training jobs and APIs that create Amazon SageMaker
117
+ endpoints use this role to access training data and model
118
+ artifacts. After the endpoint is created, the inference code
119
+ might use the IAM role if it needs to access some AWS resources.
120
+ It can be null if this is being used to create a Model to pass
121
+ to a ``PipelineModel`` which has its own Role field. (default:
122
+ None)
123
+ predictor_cls (callable[string, sagemaker.session.Session]): A
124
+ function to call to create a predictor (default: None). If not
125
+ None, ``deploy`` will return the result of invoking this
126
+ function on the created endpoint name.
127
+ env (dict[str, str] or dict[str, PipelineVariable]): Environment variables
128
+ to run with ``image_uri`` when hosted in SageMaker (default: None).
129
+ name (str): The model name. If None, a default model name will be
130
+ selected on each ``deploy``.
131
+ vpc_config (dict[str, list[str]] or dict[str, list[PipelineVariable]]):
132
+ The VpcConfig set on the model (default: None)
133
+ * 'Subnets' (list[str]): List of subnet ids.
134
+ * 'SecurityGroupIds' (list[str]): List of security group ids.
135
+ sagemaker_session (sagemaker.session.Session): A SageMaker Session
136
+ object, used for SageMaker interactions (default: None). If not
137
+ specified, one is created using the default AWS configuration
138
+ chain.
139
+ enable_network_isolation (Boolean or PipelineVariable): Default False.
140
+ if True, enables network isolation in the endpoint, isolating the model
141
+ container. No inbound or outbound network calls can be made to
142
+ or from the model container.
143
+ model_kms_key (str): KMS key ARN used to encrypt the repacked
144
+ model archive file if the model is repacked
145
+ image_config (dict[str, str] or dict[str, PipelineVariable]): Specifies
146
+ whether the image of model container is pulled from ECR, or private
147
+ registry in your VPC. By default it is set to pull model container
148
+ image from ECR. (default: None).
149
+ source_dir (str): The absolute, relative, or S3 URI Path to a directory
150
+ with any other training source code dependencies aside from the entry
151
+ point file (default: None). If ``source_dir`` is an S3 URI, it must
152
+ point to a tar.gz file. Structure within this directory is preserved
153
+ when training on Amazon SageMaker. If 'git_config' is provided,
154
+ 'source_dir' should be a relative location to a directory in the Git repo.
155
+ If the directory points to S3, no code is uploaded and the S3 location
156
+ is used instead.
157
+
158
+ .. admonition:: Example
159
+
160
+ With the following GitHub repo directory structure:
161
+
162
+ >>> |----- README.md
163
+ >>> |----- src
164
+ >>> |----- inference.py
165
+ >>> |----- test.py
166
+
167
+ You can assign entry_point='inference.py', source_dir='src'.
168
+ code_location (str): Name of the S3 bucket where custom code is
169
+ uploaded (default: None). If not specified, the default bucket
170
+ created by ``sagemaker.session.Session`` is used.
171
+ entry_point (str): The absolute or relative path to the local Python
172
+ source file that should be executed as the entry point to
173
+ model hosting. (Default: None). If ``source_dir`` is specified, then ``entry_point``
174
+ must point to a file located at the root of ``source_dir``.
175
+ If 'git_config' is provided, 'entry_point' should be
176
+ a relative location to the Python source file in the Git repo.
177
+
178
+ Example:
179
+ With the following GitHub repo directory structure:
180
+
181
+ >>> |----- README.md
182
+ >>> |----- src
183
+ >>> |----- inference.py
184
+ >>> |----- test.py
185
+
186
+ You can assign entry_point='src/inference.py'.
187
+ container_log_level (int or PipelineVariable): Log level to use within the
188
+ container (default: logging.INFO). Valid values are defined in the Python
189
+ logging module.
190
+ dependencies (list[str]): A list of absolute or relative paths to directories
191
+ with any additional libraries that should be exported
192
+ to the container (default: []). The library folders are
193
+ copied to SageMaker in the same folder where the entrypoint is
194
+ copied. If 'git_config' is provided, 'dependencies' should be a
195
+ list of relative locations to directories with any additional
196
+ libraries needed in the Git repo. If the ```source_dir``` points
197
+ to S3, code will be uploaded and the S3 location will be used
198
+ instead.
199
+
200
+ .. admonition:: Example
201
+
202
+ The following call
203
+
204
+ >>> Model(entry_point='inference.py',
205
+ ... dependencies=['my/libs/common', 'virtual-env'])
206
+
207
+ results in the following structure inside the container:
208
+
209
+ >>> $ ls
210
+
211
+ >>> opt/ml/code
212
+ >>> |------ inference.py
213
+ >>> |------ common
214
+ >>> |------ virtual-env
215
+
216
+ This is not supported with "local code" in Local Mode.
217
+ git_config (dict[str, str]): Git configurations used for cloning
218
+ files, including ``repo``, ``branch``, ``commit``,
219
+ ``2FA_enabled``, ``username``, ``password`` and ``token``. The
220
+ ``repo`` field is required. All other fields are optional.
221
+ ``repo`` specifies the Git repository where your training script
222
+ is stored. If you don't provide ``branch``, the default value
223
+ 'master' is used. If you don't provide ``commit``, the latest
224
+ commit in the specified branch is used.
225
+
226
+ .. admonition:: Example
227
+
228
+ The following config:
229
+
230
+ >>> git_config = {'repo': 'https://github.com/aws/sagemaker-python-sdk.git',
231
+ >>> 'branch': 'test-branch-git-config',
232
+ >>> 'commit': '329bfcf884482002c05ff7f44f62599ebc9f445a'}
233
+
234
+ results in cloning the repo specified in 'repo', then
235
+ checking out the 'master' branch, and checking out the specified
236
+ commit.
237
+
238
+ ``2FA_enabled``, ``username``, ``password`` and ``token`` are
239
+ used for authentication. For GitHub (or other Git) accounts, set
240
+ ``2FA_enabled`` to 'True' if two-factor authentication is
241
+ enabled for the account, otherwise set it to 'False'. If you do
242
+ not provide a value for ``2FA_enabled``, a default value of
243
+ 'False' is used. CodeCommit does not support two-factor
244
+ authentication, so do not provide "2FA_enabled" with CodeCommit
245
+ repositories.
246
+
247
+ For GitHub and other Git repos, when SSH URLs are provided, it
248
+ doesn't matter whether 2FA is enabled or disabled. You should
249
+ either have no passphrase for the SSH key pairs or have the
250
+ ssh-agent configured so that you will not be prompted for the SSH
251
+ passphrase when you run the 'git clone' command with SSH URLs. When
252
+ HTTPS URLs are provided, if 2FA is disabled, then either ``token``
253
+ or ``username`` and ``password`` are be used for authentication if provided.
254
+ ``Token`` is prioritized. If 2FA is enabled, only ``token`` is used
255
+ for authentication if provided. If required authentication info
256
+ is not provided, the SageMaker Python SDK attempts to use local credentials
257
+ to authenticate. If that fails, an error message is thrown.
258
+
259
+ For CodeCommit repos, 2FA is not supported, so ``2FA_enabled``
260
+ should not be provided. There is no token in CodeCommit, so
261
+ ``token`` should also not be provided. When ``repo`` is an SSH URL,
262
+ the requirements are the same as GitHub repos. When ``repo``
263
+ is an HTTPS URL, ``username`` and ``password`` are used for
264
+ authentication if they are provided. If they are not provided,
265
+ the SageMaker Python SDK attempts to use either the CodeCommit
266
+ credential helper or local credential storage for authentication.
267
+
268
+ """
269
+ self.model_data = model_data
270
+ self.image_uri = image_uri
271
+ self.role = role
272
+ self.predictor_cls = predictor_cls
273
+ self.env = env or {}
274
+ self.name = name
275
+ self._base_name = None
276
+ self.vpc_config = vpc_config
277
+ self.sagemaker_session = sagemaker_session
278
+ self.endpoint_name = None
279
+ self._is_compiled_model = False
280
+ self._compilation_job_name = None
281
+ self._is_edge_packaged_model = False
282
+ self._enable_network_isolation = enable_network_isolation
283
+ self.model_kms_key = model_kms_key
284
+ self.image_config = image_config
285
+ self.entry_point = entry_point
286
+ self.source_dir = source_dir
287
+ self.dependencies = dependencies or []
288
+ self.git_config = git_config
289
+ self.container_log_level = container_log_level
290
+ if code_location:
291
+ self.bucket, self.key_prefix = s3.parse_s3_url(code_location)
292
+ else:
293
+ self.bucket, self.key_prefix = None, None
294
+ if self.git_config:
295
+ updates = git_utils.git_clone_repo(
296
+ self.git_config, self.entry_point, self.source_dir, self.dependencies
297
+ )
298
+ self.entry_point = updates["entry_point"]
299
+ self.source_dir = updates["source_dir"]
300
+ self.dependencies = updates["dependencies"]
301
+ self.uploaded_code = None
302
+ self.repacked_model_data = None
303
+
304
+ @runnable_by_pipeline
305
+ def register(
306
+ self,
307
+ content_types: List[Union[str, PipelineVariable]],
308
+ response_types: List[Union[str, PipelineVariable]],
309
+ inference_instances: Optional[List[Union[str, PipelineVariable]]] = None,
310
+ transform_instances: Optional[List[Union[str, PipelineVariable]]] = None,
311
+ model_package_name: Optional[Union[str, PipelineVariable]] = None,
312
+ model_package_group_name: Optional[Union[str, PipelineVariable]] = None,
313
+ image_uri: Optional[Union[str, PipelineVariable]] = None,
314
+ model_metrics: Optional[ModelMetrics] = None,
315
+ metadata_properties: Optional[MetadataProperties] = None,
316
+ marketplace_cert: bool = False,
317
+ approval_status: Optional[Union[str, PipelineVariable]] = None,
318
+ description: Optional[str] = None,
319
+ drift_check_baselines: Optional[DriftCheckBaselines] = None,
320
+ customer_metadata_properties: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
321
+ validation_specification: Optional[Union[str, PipelineVariable]] = None,
322
+ domain: Optional[Union[str, PipelineVariable]] = None,
323
+ task: Optional[Union[str, PipelineVariable]] = None,
324
+ sample_payload_url: Optional[Union[str, PipelineVariable]] = None,
325
+ framework: Optional[Union[str, PipelineVariable]] = None,
326
+ framework_version: Optional[Union[str, PipelineVariable]] = None,
327
+ nearest_model_name: Optional[Union[str, PipelineVariable]] = None,
328
+ data_input_configuration: Optional[Union[str, PipelineVariable]] = None,
329
+ ):
330
+ """Creates a model package for creating SageMaker models or listing on Marketplace.
331
+
332
+ Args:
333
+ content_types (list[str] or list[PipelineVariable]): The supported MIME types
334
+ for the input data.
335
+ response_types (list[str] or list[PipelineVariable]): The supported MIME types
336
+ for the output data.
337
+ inference_instances (list[str] or list[PipelineVariable]): A list of the instance
338
+ types that are used to generate inferences in real-time (default: None).
339
+ transform_instances (list[str] or list[PipelineVariable]): A list of the instance
340
+ types on which a transformation job can be run or on which an endpoint can be
341
+ deployed (default: None).
342
+ model_package_name (str or PipelineVariable): Model Package name, exclusive to
343
+ `model_package_group_name`, using `model_package_name` makes the Model Package
344
+ un-versioned (default: None).
345
+ model_package_group_name (str or PipelineVariable): Model Package Group name,
346
+ exclusive to `model_package_name`, using `model_package_group_name` makes
347
+ the Model Package versioned (default: None).
348
+ image_uri (str or PipelineVariable): Inference image uri for the container.
349
+ Model class' self.image will be used if it is None (default: None).
350
+ model_metrics (ModelMetrics): ModelMetrics object (default: None).
351
+ metadata_properties (MetadataProperties): MetadataProperties object (default: None).
352
+ marketplace_cert (bool): A boolean value indicating if the Model Package is certified
353
+ for AWS Marketplace (default: False).
354
+ approval_status (str or PipelineVariable): Model Approval Status, values can be
355
+ "Approved", "Rejected", or "PendingManualApproval"
356
+ (default: "PendingManualApproval").
357
+ description (str): Model Package description (default: None).
358
+ drift_check_baselines (DriftCheckBaselines): DriftCheckBaselines object (default: None).
359
+ customer_metadata_properties (dict[str, str] or dict[str, PipelineVariable]):
360
+ A dictionary of key-value paired metadata properties (default: None).
361
+ domain (str or PipelineVariable): Domain values can be "COMPUTER_VISION",
362
+ "NATURAL_LANGUAGE_PROCESSING", "MACHINE_LEARNING" (default: None).
363
+ task (str or PipelineVariable): Task values which are supported by Inference Recommender
364
+ are "FILL_MASK", "IMAGE_CLASSIFICATION", "OBJECT_DETECTION", "TEXT_GENERATION",
365
+ "IMAGE_SEGMENTATION", "CLASSIFICATION", "REGRESSION", "OTHER" (default: None).
366
+ sample_payload_url (str or PipelineVariable): The S3 path where the sample
367
+ payload is stored (default: None).
368
+ framework (str or PipelineVariable): Machine learning framework of the model package
369
+ container image (default: None).
370
+ framework_version (str or PipelineVariable): Framework version of the Model Package
371
+ Container Image (default: None).
372
+ nearest_model_name (str or PipelineVariable): Name of a pre-trained machine learning
373
+ benchmarked by Amazon SageMaker Inference Recommender (default: None).
374
+ data_input_configuration (str or PipelineVariable): Input object for the model
375
+ (default: None).
376
+
377
+ Returns:
378
+ A `sagemaker.model.ModelPackage` instance or pipeline step arguments
379
+ in case the Model instance is built with
380
+ :class:`~sagemaker.workflow.pipeline_context.PipelineSession`
381
+ """
382
+ if self.model_data is None:
383
+ raise ValueError("SageMaker Model Package cannot be created without model data.")
384
+ if image_uri is not None:
385
+ self.image_uri = image_uri
386
+
387
+ if model_package_group_name is not None:
388
+ container_def = self.prepare_container_def()
389
+ container_def = update_container_with_inference_params(
390
+ framework=framework,
391
+ framework_version=framework_version,
392
+ nearest_model_name=nearest_model_name,
393
+ data_input_configuration=data_input_configuration,
394
+ container_def=container_def,
395
+ )
396
+ else:
397
+ container_def = {
398
+ "Image": self.image_uri,
399
+ "ModelDataUrl": self.model_data,
400
+ }
401
+
402
+ model_pkg_args = sagemaker.get_model_package_args(
403
+ content_types,
404
+ response_types,
405
+ inference_instances=inference_instances,
406
+ transform_instances=transform_instances,
407
+ model_package_name=model_package_name,
408
+ model_package_group_name=model_package_group_name,
409
+ model_metrics=model_metrics,
410
+ metadata_properties=metadata_properties,
411
+ marketplace_cert=marketplace_cert,
412
+ approval_status=approval_status,
413
+ description=description,
414
+ container_def_list=[container_def],
415
+ drift_check_baselines=drift_check_baselines,
416
+ customer_metadata_properties=customer_metadata_properties,
417
+ validation_specification=validation_specification,
418
+ domain=domain,
419
+ sample_payload_url=sample_payload_url,
420
+ task=task,
421
+ )
422
+ model_package = self.sagemaker_session.create_model_package_from_containers(
423
+ **model_pkg_args
424
+ )
425
+ if isinstance(self.sagemaker_session, PipelineSession):
426
+ return None
427
+ return ModelPackage(
428
+ role=self.role,
429
+ model_data=self.model_data,
430
+ model_package_arn=model_package.get("ModelPackageArn"),
431
+ )
432
+
433
+ @runnable_by_pipeline
434
+ def create(
435
+ self,
436
+ instance_type: Optional[str] = None,
437
+ accelerator_type: Optional[str] = None,
438
+ serverless_inference_config: Optional[ServerlessInferenceConfig] = None,
439
+ tags: Optional[List[Dict[str, Union[str, PipelineVariable]]]] = None,
440
+ ):
441
+ """Create a SageMaker Model Entity
442
+
443
+ Args:
444
+ instance_type (str): The EC2 instance type that this Model will be
445
+ used for, this is only used to determine if the image needs GPU
446
+ support or not (default: None).
447
+ accelerator_type (str): Type of Elastic Inference accelerator to
448
+ attach to an endpoint for model loading and inference, for
449
+ example, 'ml.eia1.medium'. If not specified, no Elastic
450
+ Inference accelerator will be attached to the endpoint (default: None).
451
+ serverless_inference_config (ServerlessInferenceConfig):
452
+ Specifies configuration related to serverless endpoint. Instance type is
453
+ not provided in serverless inference. So this is used to find image URIs
454
+ (default: None).
455
+ tags (list[dict[str, str] or list[dict[str, PipelineVariable]]): The list of
456
+ tags to add to the model (default: None). Example::
457
+
458
+ tags = [{'Key': 'tagname', 'Value':'tagvalue'}]
459
+
460
+ For more information about tags, see
461
+ `boto3 documentation <https://boto3.amazonaws.com/v1/documentation/\
462
+ api/latest/reference/services/sagemaker.html#SageMaker.Client.add_tags>`_
463
+
464
+ Returns:
465
+ None or pipeline step arguments in case the Model instance is built with
466
+ :class:`~sagemaker.workflow.pipeline_context.PipelineSession`
467
+ """
468
+ # TODO: we should replace _create_sagemaker_model() with create()
469
+ self._create_sagemaker_model(
470
+ instance_type=instance_type,
471
+ accelerator_type=accelerator_type,
472
+ tags=tags,
473
+ serverless_inference_config=serverless_inference_config,
474
+ )
475
+
476
+ def _init_sagemaker_session_if_does_not_exist(self, instance_type=None):
477
+ """Set ``self.sagemaker_session`` to ``LocalSession`` or ``Session`` if it's not already.
478
+
479
+ The type of session object is determined by the instance type.
480
+ """
481
+ if self.sagemaker_session:
482
+ return
483
+
484
+ if instance_type in ("local", "local_gpu"):
485
+ self.sagemaker_session = local.LocalSession()
486
+ else:
487
+ self.sagemaker_session = session.Session()
488
+
489
+ def prepare_container_def(
490
+ self,
491
+ instance_type=None,
492
+ accelerator_type=None,
493
+ serverless_inference_config=None,
494
+ ): # pylint: disable=unused-argument
495
+ """Return a dict created by ``sagemaker.container_def()``.
496
+
497
+ It is used for deploying this model to a specified instance type.
498
+
499
+ Subclasses can override this to provide custom container definitions
500
+ for deployment to a specific instance type. Called by ``deploy()``.
501
+
502
+ Args:
503
+ instance_type (str): The EC2 instance type to deploy this Model to.
504
+ For example, 'ml.p2.xlarge'.
505
+ accelerator_type (str): The Elastic Inference accelerator type to
506
+ deploy to the instance for loading and making inferences to the
507
+ model. For example, 'ml.eia1.medium'.
508
+ serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig):
509
+ Specifies configuration related to serverless endpoint. Instance type is
510
+ not provided in serverless inference. So this is used to find image URIs.
511
+
512
+ Returns:
513
+ dict: A container definition object usable with the CreateModel API.
514
+ """
515
+ deploy_key_prefix = fw_utils.model_code_key_prefix(
516
+ self.key_prefix, self.name, self.image_uri
517
+ )
518
+ deploy_env = copy.deepcopy(self.env)
519
+ if self.source_dir or self.dependencies or self.entry_point or self.git_config:
520
+ is_repack = (
521
+ self.source_dir and self.entry_point and not (self.key_prefix or self.git_config)
522
+ )
523
+ self._upload_code(deploy_key_prefix, repack=is_repack)
524
+ deploy_env.update(self._script_mode_env_vars())
525
+ return sagemaker.container_def(
526
+ self.image_uri,
527
+ self.repacked_model_data or self.model_data,
528
+ deploy_env,
529
+ image_config=self.image_config,
530
+ )
531
+
532
+ def _upload_code(self, key_prefix: str, repack: bool = False) -> None:
533
+ """Uploads code to S3 to be used with script mode with SageMaker inference.
534
+
535
+ Args:
536
+ key_prefix (str): The S3 key associated with the ``code_location`` parameter of the
537
+ ``Model`` class.
538
+ repack (bool): Optional. Set to ``True`` to indicate that the source code and model
539
+ artifact should be repackaged into a new S3 object. (default: False).
540
+ """
541
+ local_code = utils.get_config_value("local.local_code", self.sagemaker_session.config)
542
+ bucket = self.bucket or self.sagemaker_session.default_bucket()
543
+ if (self.sagemaker_session.local_mode and local_code) or self.entry_point is None:
544
+ self.uploaded_code = None
545
+ elif not repack:
546
+ self.uploaded_code = fw_utils.tar_and_upload_dir(
547
+ session=self.sagemaker_session.boto_session,
548
+ bucket=bucket,
549
+ s3_key_prefix=key_prefix,
550
+ script=self.entry_point,
551
+ directory=self.source_dir,
552
+ dependencies=self.dependencies,
553
+ settings=self.sagemaker_session.settings,
554
+ )
555
+
556
+ if repack and self.model_data is not None and self.entry_point is not None:
557
+ if is_pipeline_variable(self.model_data):
558
+ # model is not yet there, defer repacking to later during pipeline execution
559
+ if not isinstance(self.sagemaker_session, PipelineSession):
560
+ logging.warning(
561
+ "The model_data is a Pipeline variable of type %s, "
562
+ "which should be used under `PipelineSession` and "
563
+ "leverage `ModelStep` to create or register model. "
564
+ "Otherwise some functionalities e.g. "
565
+ "runtime repack may be missing. For more, see: "
566
+ "https://sagemaker.readthedocs.io/en/stable/"
567
+ "amazon_sagemaker_model_building_pipeline.html#model-step",
568
+ type(self.model_data),
569
+ )
570
+ return
571
+ self.sagemaker_session.context.need_runtime_repack.add(id(self))
572
+ self.sagemaker_session.context.runtime_repack_output_prefix = "s3://{}/{}".format(
573
+ bucket, key_prefix
574
+ )
575
+ # Add the uploaded_code and repacked_model_data to update the container env
576
+ self.repacked_model_data = self.model_data
577
+ self.uploaded_code = fw_utils.UploadedCode(
578
+ s3_prefix=self.repacked_model_data,
579
+ script_name=os.path.basename(self.entry_point),
580
+ )
581
+ return
582
+ if local_code and self.model_data.startswith("file://"):
583
+ repacked_model_data = self.model_data
584
+ else:
585
+ repacked_model_data = "s3://" + "/".join([bucket, key_prefix, "model.tar.gz"])
586
+ self.uploaded_code = fw_utils.UploadedCode(
587
+ s3_prefix=repacked_model_data, script_name=os.path.basename(self.entry_point)
588
+ )
589
+
590
+ utils.repack_model(
591
+ inference_script=self.entry_point,
592
+ source_directory=self.source_dir,
593
+ dependencies=self.dependencies,
594
+ model_uri=self.model_data,
595
+ repacked_model_uri=repacked_model_data,
596
+ sagemaker_session=self.sagemaker_session,
597
+ kms_key=self.model_kms_key,
598
+ )
599
+
600
+ self.repacked_model_data = repacked_model_data
601
+
602
+ def _script_mode_env_vars(self):
603
+ """Returns a mapping of environment variables for script mode execution"""
604
+ script_name = None
605
+ dir_name = None
606
+ if self.uploaded_code:
607
+ script_name = self.uploaded_code.script_name
608
+ if self.repacked_model_data or self.enable_network_isolation():
609
+ dir_name = "/opt/ml/model/code"
610
+ else:
611
+ dir_name = self.uploaded_code.s3_prefix
612
+ elif self.entry_point is not None:
613
+ script_name = self.entry_point
614
+ if self.source_dir is not None:
615
+ dir_name = (
616
+ self.source_dir
617
+ if self.source_dir.startswith("s3://")
618
+ else "file://" + self.source_dir
619
+ )
620
+ return {
621
+ SCRIPT_PARAM_NAME.upper(): script_name or str(),
622
+ DIR_PARAM_NAME.upper(): dir_name or str(),
623
+ CONTAINER_LOG_LEVEL_PARAM_NAME.upper(): to_string(self.container_log_level),
624
+ SAGEMAKER_REGION_PARAM_NAME.upper(): self.sagemaker_session.boto_region_name,
625
+ }
626
+
627
+ def enable_network_isolation(self):
628
+ """Whether to enable network isolation when creating this Model
629
+
630
+ Returns:
631
+ bool: If network isolation should be enabled or not.
632
+ """
633
+ return self._enable_network_isolation
634
+
635
+ def _create_sagemaker_model(
636
+ self, instance_type=None, accelerator_type=None, tags=None, serverless_inference_config=None
637
+ ):
638
+ """Create a SageMaker Model Entity
639
+
640
+ Args:
641
+ instance_type (str): The EC2 instance type that this Model will be
642
+ used for, this is only used to determine if the image needs GPU
643
+ support or not.
644
+ accelerator_type (str): Type of Elastic Inference accelerator to
645
+ attach to an endpoint for model loading and inference, for
646
+ example, 'ml.eia1.medium'. If not specified, no Elastic
647
+ Inference accelerator will be attached to the endpoint.
648
+ tags (List[dict[str, str]]): Optional. The list of tags to add to
649
+ the model. Example: >>> tags = [{'Key': 'tagname', 'Value':
650
+ 'tagvalue'}] For more information about tags, see
651
+ https://boto3.amazonaws.com/v1/documentation
652
+ /api/latest/reference/services/sagemaker.html#SageMaker.Client.add_tags
653
+ serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig):
654
+ Specifies configuration related to serverless endpoint. Instance type is
655
+ not provided in serverless inference. So this is used to find image URIs.
656
+ """
657
+ container_def = self.prepare_container_def(
658
+ instance_type,
659
+ accelerator_type=accelerator_type,
660
+ serverless_inference_config=serverless_inference_config,
661
+ )
662
+
663
+ if not isinstance(self.sagemaker_session, PipelineSession):
664
+ # _base_name, model_name are not needed under PipelineSession.
665
+ # the model_data may be Pipeline variable
666
+ # which may break the _base_name generation
667
+ self._ensure_base_name_if_needed(
668
+ image_uri=container_def["Image"],
669
+ script_uri=self.source_dir,
670
+ model_uri=self.model_data,
671
+ )
672
+ self._set_model_name_if_needed()
673
+
674
+ enable_network_isolation = self.enable_network_isolation()
675
+
676
+ self._init_sagemaker_session_if_does_not_exist(instance_type)
677
+ create_model_args = dict(
678
+ name=self.name,
679
+ role=self.role,
680
+ container_defs=container_def,
681
+ vpc_config=self.vpc_config,
682
+ enable_network_isolation=enable_network_isolation,
683
+ tags=tags,
684
+ )
685
+ self.sagemaker_session.create_model(**create_model_args)
686
+
687
+ def _ensure_base_name_if_needed(self, image_uri, script_uri, model_uri):
688
+ """Create a base name from the image URI if there is no model name provided.
689
+
690
+ If a JumpStart script or model uri is used, select the JumpStart base name.
691
+ """
692
+ if self.name is None:
693
+ self._base_name = (
694
+ self._base_name
695
+ or get_jumpstart_base_name_if_jumpstart_model(script_uri, model_uri)
696
+ or utils.base_name_from_image(image_uri, default_base_name=Model.__name__)
697
+ )
698
+
699
+ def _set_model_name_if_needed(self):
700
+ """Generate a new model name if ``self._base_name`` is present."""
701
+ if self._base_name:
702
+ self.name = utils.name_from_base(self._base_name)
703
+
704
+ def _framework(self):
705
+ """Placeholder docstring"""
706
+ return getattr(self, "_framework_name", None)
707
+
708
+ def _get_framework_version(self):
709
+ """Placeholder docstring"""
710
+ return getattr(self, "framework_version", None)
711
+
712
+ def _edge_packaging_job_config(
713
+ self,
714
+ output_path,
715
+ role,
716
+ model_name,
717
+ model_version,
718
+ packaging_job_name,
719
+ compilation_job_name,
720
+ resource_key,
721
+ s3_kms_key,
722
+ tags,
723
+ ):
724
+ """Creates a request object for a packaging job.
725
+
726
+ Args:
727
+ output_path (str): where in S3 to store the output of the job
728
+ role (str): what role to use when executing the job
729
+ packaging_job_name (str): what to name the packaging job
730
+ compilation_job_name (str): what compilation job to source the model from
731
+ resource_key (str): the kms key to encrypt the disk with
732
+ s3_kms_key (str): the kms key to encrypt the output with
733
+ tags (list[dict]): List of tags for labeling an edge packaging job. For
734
+ more, see
735
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
736
+ Returns:
737
+ dict: the request object to use when creating a packaging job
738
+ """
739
+ output_model_config = {
740
+ "S3OutputLocation": output_path,
741
+ }
742
+ if s3_kms_key is not None:
743
+ output_model_config["KmsKeyId"] = s3_kms_key
744
+
745
+ return {
746
+ "output_model_config": output_model_config,
747
+ "role": role,
748
+ "tags": tags,
749
+ "model_name": model_name,
750
+ "model_version": model_version,
751
+ "job_name": packaging_job_name,
752
+ "compilation_job_name": compilation_job_name,
753
+ "resource_key": resource_key,
754
+ }
755
+
756
+ def _compilation_job_config(
757
+ self,
758
+ target_instance_type,
759
+ input_shape,
760
+ output_path,
761
+ role,
762
+ compile_max_run,
763
+ job_name,
764
+ framework,
765
+ tags,
766
+ target_platform_os=None,
767
+ target_platform_arch=None,
768
+ target_platform_accelerator=None,
769
+ compiler_options=None,
770
+ framework_version=None,
771
+ ):
772
+ """Placeholder Docstring"""
773
+ input_model_config = {
774
+ "S3Uri": self.model_data,
775
+ "DataInputConfig": json.dumps(input_shape)
776
+ if isinstance(input_shape, dict)
777
+ else input_shape,
778
+ "Framework": framework.upper(),
779
+ }
780
+
781
+ def multi_version_compilation_supported(
782
+ target_instance_type: str, framework: str, framework_version: str
783
+ ):
784
+ if target_instance_type and framework and framework_version:
785
+ framework = framework.lower()
786
+ multi_version_frameworks_support_mapping = {
787
+ "inferentia": ["pytorch", "tensorflow", "mxnet"],
788
+ "neo_ioc_targets": ["pytorch", "tensorflow"],
789
+ }
790
+ if target_instance_type in NEO_IOC_TARGET_DEVICES:
791
+ return framework in multi_version_frameworks_support_mapping["neo_ioc_targets"]
792
+ if target_instance_type == "ml_inf":
793
+ return framework in multi_version_frameworks_support_mapping["inferentia"]
794
+ return False
795
+
796
+ if multi_version_compilation_supported(target_instance_type, framework, framework_version):
797
+ input_model_config["FrameworkVersion"] = utils.get_short_version(framework_version)
798
+
799
+ role = self.sagemaker_session.expand_role(role)
800
+ output_model_config = {
801
+ "S3OutputLocation": output_path,
802
+ }
803
+
804
+ if target_instance_type is not None:
805
+ output_model_config["TargetDevice"] = target_instance_type
806
+ else:
807
+ if target_platform_os is None and target_platform_arch is None:
808
+ raise ValueError(
809
+ "target_instance_type or (target_platform_os and target_platform_arch) "
810
+ "should be provided"
811
+ )
812
+ target_platform = {
813
+ "Os": target_platform_os,
814
+ "Arch": target_platform_arch,
815
+ }
816
+ if target_platform_accelerator is not None:
817
+ target_platform["Accelerator"] = target_platform_accelerator
818
+ output_model_config["TargetPlatform"] = target_platform
819
+
820
+ if compiler_options is not None:
821
+ output_model_config["CompilerOptions"] = (
822
+ json.dumps(compiler_options)
823
+ if isinstance(compiler_options, dict)
824
+ else compiler_options
825
+ )
826
+
827
+ return {
828
+ "input_model_config": input_model_config,
829
+ "output_model_config": output_model_config,
830
+ "role": role,
831
+ "stop_condition": {"MaxRuntimeInSeconds": compile_max_run},
832
+ "tags": tags,
833
+ "job_name": job_name,
834
+ }
835
+
836
+ def package_for_edge(
837
+ self,
838
+ output_path,
839
+ model_name,
840
+ model_version,
841
+ role=None,
842
+ job_name=None,
843
+ resource_key=None,
844
+ s3_kms_key=None,
845
+ tags=None,
846
+ ):
847
+ """Package this ``Model`` with SageMaker Edge.
848
+
849
+ Creates a new EdgePackagingJob and wait for it to finish.
850
+ model_data will now point to the packaged artifacts.
851
+
852
+ Args:
853
+ output_path (str): Specifies where to store the packaged model
854
+ role (str): Execution role
855
+ model_name (str): the name to attach to the model metadata
856
+ model_version (str): the version to attach to the model metadata
857
+ job_name (str): The name of the edge packaging job
858
+ resource_key (str): the kms key to encrypt the disk with
859
+ s3_kms_key (str): the kms key to encrypt the output with
860
+ tags (list[dict]): List of tags for labeling an edge packaging job. For
861
+ more, see
862
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
863
+
864
+ Returns:
865
+ sagemaker.model.Model: A SageMaker ``Model`` object. See
866
+ :func:`~sagemaker.model.Model` for full details.
867
+ """
868
+ if self._compilation_job_name is None:
869
+ raise ValueError("You must first compile this model")
870
+ if job_name is None:
871
+ job_name = f"packaging{self._compilation_job_name[11:]}"
872
+ if role is None:
873
+ role = self.sagemaker_session.expand_role(role)
874
+
875
+ self._init_sagemaker_session_if_does_not_exist(None)
876
+ config = self._edge_packaging_job_config(
877
+ output_path,
878
+ role,
879
+ model_name,
880
+ model_version,
881
+ job_name,
882
+ self._compilation_job_name,
883
+ resource_key,
884
+ s3_kms_key,
885
+ tags,
886
+ )
887
+ self.sagemaker_session.package_model_for_edge(**config)
888
+ job_status = self.sagemaker_session.wait_for_edge_packaging_job(job_name)
889
+ self.model_data = job_status["ModelArtifact"]
890
+ self._is_edge_packaged_model = True
891
+
892
+ return self
893
+
894
+ def compile(
895
+ self,
896
+ target_instance_family,
897
+ input_shape,
898
+ output_path,
899
+ role,
900
+ tags=None,
901
+ job_name=None,
902
+ compile_max_run=15 * 60,
903
+ framework=None,
904
+ framework_version=None,
905
+ target_platform_os=None,
906
+ target_platform_arch=None,
907
+ target_platform_accelerator=None,
908
+ compiler_options=None,
909
+ ):
910
+ """Compile this ``Model`` with SageMaker Neo.
911
+
912
+ Args:
913
+ target_instance_family (str): Identifies the device that you want to
914
+ run your model after compilation, for example: ml_c5. For allowed
915
+ strings see
916
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_OutputConfig.html.
917
+ Alternatively, you can select an OS, Architecture and Accelerator using
918
+ ``target_platform_os``, ``target_platform_arch``,
919
+ and ``target_platform_accelerator``.
920
+ input_shape (dict): Specifies the name and shape of the expected
921
+ inputs for your trained model in json dictionary form, for
922
+ example: {'data': [1,3,1024,1024]}, or {'var1': [1,1,28,28],
923
+ 'var2': [1,1,28,28]}
924
+ output_path (str): Specifies where to store the compiled model
925
+ role (str): Execution role
926
+ tags (list[dict]): List of tags for labeling a compilation job. For
927
+ more, see
928
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
929
+ job_name (str): The name of the compilation job
930
+ compile_max_run (int): Timeout in seconds for compilation (default:
931
+ 15 * 60). After this amount of time Amazon SageMaker Neo
932
+ terminates the compilation job regardless of its current status.
933
+ framework (str): The framework that is used to train the original
934
+ model. Allowed values: 'mxnet', 'tensorflow', 'keras', 'pytorch',
935
+ 'onnx', 'xgboost'
936
+ framework_version (str): The version of framework, for example:
937
+ '1.5' for PyTorch
938
+ target_platform_os (str): Target Platform OS, for example: 'LINUX'.
939
+ For allowed strings see
940
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_OutputConfig.html.
941
+ It can be used instead of target_instance_family by setting target_instance
942
+ family to None.
943
+ target_platform_arch (str): Target Platform Architecture, for example: 'X86_64'.
944
+ For allowed strings see
945
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_OutputConfig.html.
946
+ It can be used instead of target_instance_family by setting target_instance
947
+ family to None.
948
+ target_platform_accelerator (str, optional): Target Platform Accelerator,
949
+ for example: 'NVIDIA'. For allowed strings see
950
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_OutputConfig.html.
951
+ It can be used instead of target_instance_family by setting target_instance
952
+ family to None.
953
+ compiler_options (dict, optional): Additional parameters for compiler.
954
+ Compiler Options are TargetPlatform / target_instance_family specific. See
955
+ https://docs.aws.amazon.com/sagemaker/latest/dg/API_OutputConfig.html for details.
956
+
957
+ Returns:
958
+ sagemaker.model.Model: A SageMaker ``Model`` object. See
959
+ :func:`~sagemaker.model.Model` for full details.
960
+ """
961
+ framework = framework or self._framework()
962
+ if framework is None:
963
+ raise ValueError(
964
+ "You must specify framework, allowed values {}".format(NEO_ALLOWED_FRAMEWORKS)
965
+ )
966
+ if framework not in NEO_ALLOWED_FRAMEWORKS:
967
+ raise ValueError(
968
+ "You must provide valid framework, allowed values {}".format(NEO_ALLOWED_FRAMEWORKS)
969
+ )
970
+ if job_name is None:
971
+ raise ValueError("You must provide a compilation job name")
972
+ if self.model_data is None:
973
+ raise ValueError("You must provide an S3 path to the compressed model artifacts.")
974
+
975
+ framework_version = framework_version or self._get_framework_version()
976
+
977
+ self._init_sagemaker_session_if_does_not_exist(target_instance_family)
978
+ config = self._compilation_job_config(
979
+ target_instance_family,
980
+ input_shape,
981
+ output_path,
982
+ role,
983
+ compile_max_run,
984
+ job_name,
985
+ framework,
986
+ tags,
987
+ target_platform_os,
988
+ target_platform_arch,
989
+ target_platform_accelerator,
990
+ compiler_options,
991
+ framework_version,
992
+ )
993
+ self.sagemaker_session.compile_model(**config)
994
+ job_status = self.sagemaker_session.wait_for_compilation_job(job_name)
995
+ self.model_data = job_status["ModelArtifacts"]["S3ModelArtifacts"]
996
+ if target_instance_family is not None:
997
+ if target_instance_family == "ml_eia2":
998
+ pass
999
+ elif target_instance_family.startswith("ml_"):
1000
+ self.image_uri = job_status.get("InferenceImage", None)
1001
+ self._is_compiled_model = True
1002
+ else:
1003
+ LOGGER.warning(
1004
+ "The instance type %s is not supported for deployment via SageMaker."
1005
+ "Please deploy the model manually.",
1006
+ target_instance_family,
1007
+ )
1008
+ else:
1009
+ LOGGER.warning(
1010
+ "Devices described by Target Platform OS, Architecture and Accelerator are not"
1011
+ "supported for deployment via SageMaker. Please deploy the model manually."
1012
+ )
1013
+
1014
+ self._compilation_job_name = job_name
1015
+
1016
+ return self
1017
+
1018
+ def deploy(
1019
+ self,
1020
+ initial_instance_count=None,
1021
+ instance_type=None,
1022
+ serializer=None,
1023
+ deserializer=None,
1024
+ accelerator_type=None,
1025
+ endpoint_name=None,
1026
+ tags=None,
1027
+ kms_key=None,
1028
+ wait=True,
1029
+ data_capture_config=None,
1030
+ async_inference_config=None,
1031
+ serverless_inference_config=None,
1032
+ **kwargs,
1033
+ ):
1034
+ """Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
1035
+
1036
+ Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an
1037
+ ``Endpoint`` from this ``Model``. If ``self.predictor_cls`` is not None,
1038
+ this method returns a the result of invoking ``self.predictor_cls`` on
1039
+ the created endpoint name.
1040
+
1041
+ The name of the created model is accessible in the ``name`` field of
1042
+ this ``Model`` after deploy returns
1043
+
1044
+ The name of the created endpoint is accessible in the
1045
+ ``endpoint_name`` field of this ``Model`` after deploy returns.
1046
+
1047
+ Args:
1048
+ initial_instance_count (int): The initial number of instances to run
1049
+ in the ``Endpoint`` created from this ``Model``. If not using
1050
+ serverless inference, then it need to be a number larger or equals
1051
+ to 1 (default: None)
1052
+ instance_type (str): The EC2 instance type to deploy this Model to.
1053
+ For example, 'ml.p2.xlarge', or 'local' for local mode. If not using
1054
+ serverless inference, then it is required to deploy a model.
1055
+ (default: None)
1056
+ serializer (:class:`~sagemaker.serializers.BaseSerializer`): A
1057
+ serializer object, used to encode data for an inference endpoint
1058
+ (default: None). If ``serializer`` is not None, then
1059
+ ``serializer`` will override the default serializer. The
1060
+ default serializer is set by the ``predictor_cls``.
1061
+ deserializer (:class:`~sagemaker.deserializers.BaseDeserializer`): A
1062
+ deserializer object, used to decode data from an inference
1063
+ endpoint (default: None). If ``deserializer`` is not None, then
1064
+ ``deserializer`` will override the default deserializer. The
1065
+ default deserializer is set by the ``predictor_cls``.
1066
+ accelerator_type (str): Type of Elastic Inference accelerator to
1067
+ deploy this model for model loading and inference, for example,
1068
+ 'ml.eia1.medium'. If not specified, no Elastic Inference
1069
+ accelerator will be attached to the endpoint. For more
1070
+ information:
1071
+ https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html
1072
+ endpoint_name (str): The name of the endpoint to create (default:
1073
+ None). If not specified, a unique endpoint name will be created.
1074
+ tags (List[dict[str, str]]): The list of tags to attach to this
1075
+ specific endpoint.
1076
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
1077
+ data on the storage volume attached to the instance hosting the
1078
+ endpoint.
1079
+ wait (bool): Whether the call should wait until the deployment of
1080
+ this model completes (default: True).
1081
+ data_capture_config (sagemaker.model_monitor.DataCaptureConfig): Specifies
1082
+ configuration related to Endpoint data capture for use with
1083
+ Amazon SageMaker Model Monitoring. Default: None.
1084
+ async_inference_config (sagemaker.model_monitor.AsyncInferenceConfig): Specifies
1085
+ configuration related to async endpoint. Use this configuration when trying
1086
+ to create async endpoint and make async inference. If empty config object
1087
+ passed through, will use default config to deploy async endpoint. Deploy a
1088
+ real-time endpoint if it's None. (default: None)
1089
+ serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig):
1090
+ Specifies configuration related to serverless endpoint. Use this configuration
1091
+ when trying to create serverless endpoint and make serverless inference. If
1092
+ empty object passed through, will use pre-defined values in
1093
+ ``ServerlessInferenceConfig`` class to deploy serverless endpoint. Deploy an
1094
+ instance based endpoint if it's None. (default: None)
1095
+ Raises:
1096
+ ValueError: If arguments combination check failed in these circumstances:
1097
+ - If no role is specified or
1098
+ - If serverless inference config is not specified and instance type and instance
1099
+ count are also not specified or
1100
+ - If a wrong type of object is provided as serverless inference config or async
1101
+ inference config
1102
+ Returns:
1103
+ callable[string, sagemaker.session.Session] or None: Invocation of
1104
+ ``self.predictor_cls`` on the created endpoint name, if ``self.predictor_cls``
1105
+ is not None. Otherwise, return None.
1106
+ """
1107
+ removed_kwargs("update_endpoint", kwargs)
1108
+ self._init_sagemaker_session_if_does_not_exist(instance_type)
1109
+
1110
+ tags = add_jumpstart_tags(
1111
+ tags=tags, inference_model_uri=self.model_data, inference_script_uri=self.source_dir
1112
+ )
1113
+
1114
+ if self.role is None:
1115
+ raise ValueError("Role can not be null for deploying a model")
1116
+
1117
+ is_async = async_inference_config is not None
1118
+ if is_async and not isinstance(async_inference_config, AsyncInferenceConfig):
1119
+ raise ValueError("async_inference_config needs to be a AsyncInferenceConfig object")
1120
+
1121
+ is_serverless = serverless_inference_config is not None
1122
+ if not is_serverless and not (instance_type and initial_instance_count):
1123
+ raise ValueError(
1124
+ "Must specify instance type and instance count unless using serverless inference"
1125
+ )
1126
+
1127
+ if is_serverless and not isinstance(serverless_inference_config, ServerlessInferenceConfig):
1128
+ raise ValueError(
1129
+ "serverless_inference_config needs to be a ServerlessInferenceConfig object"
1130
+ )
1131
+
1132
+ if instance_type and instance_type.startswith("ml.inf") and not self._is_compiled_model:
1133
+ LOGGER.warning(
1134
+ "Your model is not compiled. Please compile your model before using Inferentia."
1135
+ )
1136
+
1137
+ compiled_model_suffix = None if is_serverless else "-".join(instance_type.split(".")[:-1])
1138
+ if self._is_compiled_model and not is_serverless:
1139
+ self._ensure_base_name_if_needed(
1140
+ image_uri=self.image_uri, script_uri=self.source_dir, model_uri=self.model_data
1141
+ )
1142
+ if self._base_name is not None:
1143
+ self._base_name = "-".join((self._base_name, compiled_model_suffix))
1144
+
1145
+ self._create_sagemaker_model(
1146
+ instance_type, accelerator_type, tags, serverless_inference_config
1147
+ )
1148
+
1149
+ serverless_inference_config_dict = (
1150
+ serverless_inference_config._to_request_dict() if is_serverless else None
1151
+ )
1152
+ production_variant = sagemaker.production_variant(
1153
+ self.name,
1154
+ instance_type,
1155
+ initial_instance_count,
1156
+ accelerator_type=accelerator_type,
1157
+ serverless_inference_config=serverless_inference_config_dict,
1158
+ )
1159
+ if endpoint_name:
1160
+ self.endpoint_name = endpoint_name
1161
+ else:
1162
+ base_endpoint_name = self._base_name or utils.base_from_name(self.name)
1163
+ if self._is_compiled_model and not is_serverless:
1164
+ if not base_endpoint_name.endswith(compiled_model_suffix):
1165
+ base_endpoint_name = "-".join((base_endpoint_name, compiled_model_suffix))
1166
+ self.endpoint_name = utils.name_from_base(base_endpoint_name)
1167
+
1168
+ data_capture_config_dict = None
1169
+ if data_capture_config is not None:
1170
+ data_capture_config_dict = data_capture_config._to_request_dict()
1171
+
1172
+ async_inference_config_dict = None
1173
+ if is_async:
1174
+ if async_inference_config.output_path is None:
1175
+ async_inference_config = self._build_default_async_inference_config(
1176
+ async_inference_config
1177
+ )
1178
+ async_inference_config_dict = async_inference_config._to_request_dict()
1179
+
1180
+ self.sagemaker_session.endpoint_from_production_variants(
1181
+ name=self.endpoint_name,
1182
+ production_variants=[production_variant],
1183
+ tags=tags,
1184
+ kms_key=kms_key,
1185
+ wait=wait,
1186
+ data_capture_config_dict=data_capture_config_dict,
1187
+ async_inference_config_dict=async_inference_config_dict,
1188
+ )
1189
+
1190
+ if self.predictor_cls:
1191
+ predictor = self.predictor_cls(self.endpoint_name, self.sagemaker_session)
1192
+ if serializer:
1193
+ predictor.serializer = serializer
1194
+ if deserializer:
1195
+ predictor.deserializer = deserializer
1196
+ if is_async:
1197
+ return AsyncPredictor(predictor, self.name)
1198
+ return predictor
1199
+ return None
1200
+
1201
+ def _build_default_async_inference_config(self, async_inference_config):
1202
+ """Build default async inference config and return ``AsyncInferenceConfig``"""
1203
+ async_output_folder = unique_name_from_base(self.name)
1204
+ async_output_s3uri = "s3://{}/async-endpoint-outputs/{}".format(
1205
+ self.sagemaker_session.default_bucket(), async_output_folder
1206
+ )
1207
+ async_inference_config.output_path = async_output_s3uri
1208
+ return async_inference_config
1209
+
1210
+ def transformer(
1211
+ self,
1212
+ instance_count,
1213
+ instance_type,
1214
+ strategy=None,
1215
+ assemble_with=None,
1216
+ output_path=None,
1217
+ output_kms_key=None,
1218
+ accept=None,
1219
+ env=None,
1220
+ max_concurrent_transforms=None,
1221
+ max_payload=None,
1222
+ tags=None,
1223
+ volume_kms_key=None,
1224
+ ):
1225
+ """Return a ``Transformer`` that uses this Model.
1226
+
1227
+ Args:
1228
+ instance_count (int): Number of EC2 instances to use.
1229
+ instance_type (str): Type of EC2 instance to use, for example,
1230
+ 'ml.c4.xlarge'.
1231
+ strategy (str): The strategy used to decide how to batch records in
1232
+ a single request (default: None). Valid values: 'MultiRecord'
1233
+ and 'SingleRecord'.
1234
+ assemble_with (str): How the output is assembled (default: None).
1235
+ Valid values: 'Line' or 'None'.
1236
+ output_path (str): S3 location for saving the transform result. If
1237
+ not specified, results are stored to a default bucket.
1238
+ output_kms_key (str): Optional. KMS key ID for encrypting the
1239
+ transform output (default: None).
1240
+ accept (str): The accept header passed by the client to
1241
+ the inference endpoint. If it is supported by the endpoint,
1242
+ it will be the format of the batch transform output.
1243
+ env (dict): Environment variables to be set for use during the
1244
+ transform job (default: None).
1245
+ max_concurrent_transforms (int): The maximum number of HTTP requests
1246
+ to be made to each individual transform container at one time.
1247
+ max_payload (int): Maximum size of the payload in a single HTTP
1248
+ request to the container in MB.
1249
+ tags (list[dict]): List of tags for labeling a transform job. If
1250
+ none specified, then the tags used for the training job are used
1251
+ for the transform job.
1252
+ volume_kms_key (str): Optional. KMS key ID for encrypting the volume
1253
+ attached to the ML compute instance (default: None).
1254
+ """
1255
+ self._init_sagemaker_session_if_does_not_exist(instance_type)
1256
+
1257
+ self._create_sagemaker_model(instance_type, tags=tags)
1258
+ if self.enable_network_isolation():
1259
+ env = None
1260
+
1261
+ return Transformer(
1262
+ self.name,
1263
+ instance_count,
1264
+ instance_type,
1265
+ strategy=strategy,
1266
+ assemble_with=assemble_with,
1267
+ output_path=output_path,
1268
+ output_kms_key=output_kms_key,
1269
+ accept=accept,
1270
+ max_concurrent_transforms=max_concurrent_transforms,
1271
+ max_payload=max_payload,
1272
+ env=env,
1273
+ tags=tags,
1274
+ base_transform_job_name=self._base_name or self.name,
1275
+ volume_kms_key=volume_kms_key,
1276
+ sagemaker_session=self.sagemaker_session,
1277
+ )
1278
+
1279
+ def delete_model(self):
1280
+ """Delete an Amazon SageMaker Model.
1281
+
1282
+ Raises:
1283
+ ValueError: if the model is not created yet.
1284
+ """
1285
+ if self.name is None:
1286
+ raise ValueError(
1287
+ "The SageMaker model must be created first before attempting to delete."
1288
+ )
1289
+ self.sagemaker_session.delete_model(self.name)
1290
+
1291
+
1292
+ class FrameworkModel(Model):
1293
+ """A Model for working with an SageMaker ``Framework``.
1294
+
1295
+ This class hosts user-defined code in S3 and sets code location and
1296
+ configuration in model environment variables.
1297
+ """
1298
+
1299
+ def __init__(
1300
+ self,
1301
+ model_data: Union[str, PipelineVariable],
1302
+ image_uri: Union[str, PipelineVariable],
1303
+ role: str,
1304
+ entry_point: str,
1305
+ source_dir: Optional[str] = None,
1306
+ predictor_cls: Optional[callable] = None,
1307
+ env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
1308
+ name: Optional[str] = None,
1309
+ container_log_level: Union[int, PipelineVariable] = logging.INFO,
1310
+ code_location: Optional[str] = None,
1311
+ sagemaker_session: Optional[Session] = None,
1312
+ dependencies: Optional[List[str]] = None,
1313
+ git_config: Optional[Dict[str, str]] = None,
1314
+ **kwargs,
1315
+ ):
1316
+ """Initialize a ``FrameworkModel``.
1317
+
1318
+ Args:
1319
+ model_data (str or PipelineVariable): The S3 location of a SageMaker
1320
+ model data ``.tar.gz`` file.
1321
+ image_uri (str or PipelineVariable): A Docker image URI.
1322
+ role (str): An IAM role name or ARN for SageMaker to access AWS
1323
+ resources on your behalf.
1324
+ entry_point (str): Path (absolute or relative) to the Python source
1325
+ file which should be executed as the entry point to model
1326
+ hosting. If ``source_dir`` is specified, then ``entry_point``
1327
+ must point to a file located at the root of ``source_dir``.
1328
+ If 'git_config' is provided, 'entry_point' should be
1329
+ a relative location to the Python source file in the Git repo.
1330
+
1331
+ Example:
1332
+ With the following GitHub repo directory structure:
1333
+
1334
+ >>> |----- README.md
1335
+ >>> |----- src
1336
+ >>> |----- inference.py
1337
+ >>> |----- test.py
1338
+
1339
+ You can assign entry_point='src/inference.py'.
1340
+ source_dir (str): Path (absolute, relative or an S3 URI) to a directory
1341
+ with any other training source code dependencies aside from the entry
1342
+ point file (default: None). If ``source_dir`` is an S3 URI, it must
1343
+ point to a tar.gz file. Structure within this directory are preserved
1344
+ when training on Amazon SageMaker. If 'git_config' is provided,
1345
+ 'source_dir' should be a relative location to a directory in the Git repo.
1346
+ If the directory points to S3, no code will be uploaded and the S3 location
1347
+ will be used instead.
1348
+
1349
+ .. admonition:: Example
1350
+
1351
+ With the following GitHub repo directory structure:
1352
+
1353
+ >>> |----- README.md
1354
+ >>> |----- src
1355
+ >>> |----- inference.py
1356
+ >>> |----- test.py
1357
+
1358
+ You can assign entry_point='inference.py', source_dir='src'.
1359
+ predictor_cls (callable[string, sagemaker.session.Session]): A
1360
+ function to call to create a predictor (default: None). If not
1361
+ None, ``deploy`` will return the result of invoking this
1362
+ function on the created endpoint name.
1363
+ env (dict[str, str] or dict[str, PipelineVariable]): Environment variables to
1364
+ run with ``image_uri`` when hosted in SageMaker (default: None).
1365
+ name (str): The model name. If None, a default model name will be
1366
+ selected on each ``deploy``.
1367
+ container_log_level (int or PipelineVariable): Log level to use within
1368
+ the container (default: logging.INFO). Valid values are defined
1369
+ in the Python logging module.
1370
+ code_location (str): Name of the S3 bucket where custom code is
1371
+ uploaded (default: None). If not specified, default bucket
1372
+ created by ``sagemaker.session.Session`` is used.
1373
+ sagemaker_session (sagemaker.session.Session): A SageMaker Session
1374
+ object, used for SageMaker interactions (default: None). If not
1375
+ specified, one is created using the default AWS configuration
1376
+ chain.
1377
+ dependencies (list[str]): A list of paths to directories (absolute
1378
+ or relative) with any additional libraries that will be exported
1379
+ to the container (default: []). The library folders will be
1380
+ copied to SageMaker in the same folder where the entrypoint is
1381
+ copied. If 'git_config' is provided, 'dependencies' should be a
1382
+ list of relative locations to directories with any additional
1383
+ libraries needed in the Git repo. If the ```source_dir``` points
1384
+ to S3, code will be uploaded and the S3 location will be used
1385
+ instead.
1386
+
1387
+ .. admonition:: Example
1388
+
1389
+ The following call
1390
+
1391
+ >>> Model(entry_point='inference.py',
1392
+ ... dependencies=['my/libs/common', 'virtual-env'])
1393
+
1394
+ results in the following inside the container:
1395
+
1396
+ >>> $ ls
1397
+
1398
+ >>> opt/ml/code
1399
+ >>> |------ inference.py
1400
+ >>> |------ common
1401
+ >>> |------ virtual-env
1402
+
1403
+ This is not supported with "local code" in Local Mode.
1404
+ git_config (dict[str, str]): Git configurations used for cloning
1405
+ files, including ``repo``, ``branch``, ``commit``,
1406
+ ``2FA_enabled``, ``username``, ``password`` and ``token``. The
1407
+ ``repo`` field is required. All other fields are optional.
1408
+ ``repo`` specifies the Git repository where your training script
1409
+ is stored. If you don't provide ``branch``, the default value
1410
+ 'master' is used. If you don't provide ``commit``, the latest
1411
+ commit in the specified branch is used.
1412
+
1413
+ .. admonition:: Example
1414
+
1415
+ The following config:
1416
+
1417
+ >>> git_config = {'repo': 'https://github.com/aws/sagemaker-python-sdk.git',
1418
+ >>> 'branch': 'test-branch-git-config',
1419
+ >>> 'commit': '329bfcf884482002c05ff7f44f62599ebc9f445a'}
1420
+
1421
+ results in cloning the repo specified in 'repo', then
1422
+ checkout the 'master' branch, and checkout the specified
1423
+ commit.
1424
+
1425
+ ``2FA_enabled``, ``username``, ``password`` and ``token`` are
1426
+ used for authentication. For GitHub (or other Git) accounts, set
1427
+ ``2FA_enabled`` to 'True' if two-factor authentication is
1428
+ enabled for the account, otherwise set it to 'False'. If you do
1429
+ not provide a value for ``2FA_enabled``, a default value of
1430
+ 'False' is used. CodeCommit does not support two-factor
1431
+ authentication, so do not provide "2FA_enabled" with CodeCommit
1432
+ repositories.
1433
+
1434
+ For GitHub and other Git repos, when SSH URLs are provided, it
1435
+ doesn't matter whether 2FA is enabled or disabled; you should
1436
+ either have no passphrase for the SSH key pairs, or have the
1437
+ ssh-agent configured so that you will not be prompted for SSH
1438
+ passphrase when you do 'git clone' command with SSH URLs. When
1439
+ HTTPS URLs are provided: if 2FA is disabled, then either token
1440
+ or username+password will be used for authentication if provided
1441
+ (token prioritized); if 2FA is enabled, only token will be used
1442
+ for authentication if provided. If required authentication info
1443
+ is not provided, python SDK will try to use local credentials
1444
+ storage to authenticate. If that fails either, an error message
1445
+ will be thrown.
1446
+
1447
+ For CodeCommit repos, 2FA is not supported, so '2FA_enabled'
1448
+ should not be provided. There is no token in CodeCommit, so
1449
+ 'token' should not be provided too. When 'repo' is an SSH URL,
1450
+ the requirements are the same as GitHub-like repos. When 'repo'
1451
+ is an HTTPS URL, username+password will be used for
1452
+ authentication if they are provided; otherwise, python SDK will
1453
+ try to use either CodeCommit credential helper or local
1454
+ credential storage for authentication.
1455
+ **kwargs: Keyword arguments passed to the superclass
1456
+ :class:`~sagemaker.model.Model`.
1457
+
1458
+ .. tip::
1459
+
1460
+ You can find additional parameters for initializing this class at
1461
+ :class:`~sagemaker.model.Model`.
1462
+ """
1463
+ super(FrameworkModel, self).__init__(
1464
+ image_uri,
1465
+ model_data,
1466
+ role,
1467
+ predictor_cls=predictor_cls,
1468
+ env=env,
1469
+ name=name,
1470
+ sagemaker_session=sagemaker_session,
1471
+ source_dir=source_dir,
1472
+ code_location=code_location,
1473
+ entry_point=entry_point,
1474
+ container_log_level=container_log_level,
1475
+ dependencies=dependencies,
1476
+ git_config=git_config,
1477
+ **kwargs,
1478
+ )
1479
+
1480
+
1481
+ class ModelPackage(Model):
1482
+ """A SageMaker ``Model`` that can be deployed to an ``Endpoint``."""
1483
+
1484
+ def __init__(self, role, model_data=None, algorithm_arn=None, model_package_arn=None, **kwargs):
1485
+ """Initialize a SageMaker ModelPackage.
1486
+
1487
+ Args:
1488
+ role (str): An AWS IAM role (either name or full ARN). The Amazon
1489
+ SageMaker training jobs and APIs that create Amazon SageMaker
1490
+ endpoints use this role to access training data and model
1491
+ artifacts. After the endpoint is created, the inference code
1492
+ might use the IAM role, if it needs to access an AWS resource.
1493
+ model_data (str): The S3 location of a SageMaker model data
1494
+ ``.tar.gz`` file. Must be provided if algorithm_arn is provided.
1495
+ algorithm_arn (str): algorithm arn used to train the model, can be
1496
+ just the name if your account owns the algorithm. Must also
1497
+ provide ``model_data``.
1498
+ model_package_arn (str): An existing SageMaker Model Package arn,
1499
+ can be just the name if your account owns the Model Package.
1500
+ ``model_data`` is not required.
1501
+ **kwargs: Additional kwargs passed to the Model constructor.
1502
+ """
1503
+ super(ModelPackage, self).__init__(
1504
+ role=role, model_data=model_data, image_uri=None, **kwargs
1505
+ )
1506
+
1507
+ if model_package_arn and algorithm_arn:
1508
+ raise ValueError(
1509
+ "model_package_arn and algorithm_arn are mutually exclusive."
1510
+ "Both were provided: model_package_arn: %s algorithm_arn: %s"
1511
+ % (model_package_arn, algorithm_arn)
1512
+ )
1513
+
1514
+ if model_package_arn is None and algorithm_arn is None:
1515
+ raise ValueError(
1516
+ "either model_package_arn or algorithm_arn is required." " None was provided."
1517
+ )
1518
+
1519
+ self.algorithm_arn = algorithm_arn
1520
+ if self.algorithm_arn is not None:
1521
+ if model_data is None:
1522
+ raise ValueError("model_data must be provided with algorithm_arn")
1523
+ self.model_data = model_data
1524
+
1525
+ self.model_package_arn = model_package_arn
1526
+ self._created_model_package_name = None
1527
+
1528
+ def _create_sagemaker_model_package(self):
1529
+ """Placeholder docstring"""
1530
+ if self.algorithm_arn is None:
1531
+ raise ValueError("No algorithm_arn was provided to create a SageMaker Model Pacakge")
1532
+
1533
+ name = self.name or utils.name_from_base(self.algorithm_arn.split("/")[-1])
1534
+ description = "Model Package created from training with %s" % self.algorithm_arn
1535
+ self.sagemaker_session.create_model_package_from_algorithm(
1536
+ name, description, self.algorithm_arn, self.model_data
1537
+ )
1538
+ return name
1539
+
1540
+ def enable_network_isolation(self):
1541
+ """Whether to enable network isolation when creating a model out of this ModelPackage
1542
+
1543
+ Returns:
1544
+ bool: If network isolation should be enabled or not.
1545
+ """
1546
+ return self._is_marketplace()
1547
+
1548
+ def _is_marketplace(self):
1549
+ """Placeholder docstring"""
1550
+ model_package_name = self.model_package_arn or self._created_model_package_name
1551
+ if model_package_name is None:
1552
+ return True
1553
+
1554
+ # Models can lazy-init sagemaker_session until deploy() is called to support
1555
+ # LocalMode so we must make sure we have an actual session to describe the model package.
1556
+ sagemaker_session = self.sagemaker_session or sagemaker.Session()
1557
+
1558
+ model_package_desc = sagemaker_session.sagemaker_client.describe_model_package(
1559
+ ModelPackageName=model_package_name
1560
+ )
1561
+ for container in model_package_desc["InferenceSpecification"]["Containers"]:
1562
+ if "ProductId" in container:
1563
+ return True
1564
+ return False
1565
+
1566
+ def _create_sagemaker_model(self, *args, **kwargs): # pylint: disable=unused-argument
1567
+ """Create a SageMaker Model Entity
1568
+
1569
+ Args:
1570
+ args: Positional arguments coming from the caller. This class does not require
1571
+ any so they are ignored.
1572
+
1573
+ kwargs: Keyword arguments coming from the caller. This class does not require
1574
+ any so they are ignored.
1575
+ """
1576
+ if self.algorithm_arn:
1577
+ # When ModelPackage is created using an algorithm_arn we need to first
1578
+ # create a ModelPackage. If we had already created one then its fine to re-use it.
1579
+ if self._created_model_package_name is None:
1580
+ model_package_name = self._create_sagemaker_model_package()
1581
+ self.sagemaker_session.wait_for_model_package(model_package_name)
1582
+ self._created_model_package_name = model_package_name
1583
+ model_package_name = self._created_model_package_name
1584
+ else:
1585
+ # When a ModelPackageArn is provided we just create the Model
1586
+ model_package_name = self.model_package_arn
1587
+
1588
+ container_def = {"ModelPackageName": model_package_name}
1589
+
1590
+ self._ensure_base_name_if_needed(model_package_name.split("/")[-1])
1591
+ self._set_model_name_if_needed()
1592
+
1593
+ self.sagemaker_session.create_model(
1594
+ self.name,
1595
+ self.role,
1596
+ container_def,
1597
+ vpc_config=self.vpc_config,
1598
+ enable_network_isolation=self.enable_network_isolation(),
1599
+ )
1600
+
1601
+ def _ensure_base_name_if_needed(self, base_name):
1602
+ """Set the base name if there is no model name provided."""
1603
+ if self.name is None:
1604
+ self._base_name = base_name
testbed/aws__sagemaker-python-sdk/src/sagemaker/model_metrics.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """This file contains code related to model metrics, including metric source and file source."""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import Optional, Union
17
+
18
+ from sagemaker.workflow.entities import PipelineVariable
19
+
20
+
21
+ class ModelMetrics(object):
22
+ """Accepts model metrics parameters for conversion to request dict."""
23
+
24
+ def __init__(
25
+ self,
26
+ model_statistics: Optional["MetricsSource"] = None,
27
+ model_constraints: Optional["MetricsSource"] = None,
28
+ model_data_statistics: Optional["MetricsSource"] = None,
29
+ model_data_constraints: Optional["MetricsSource"] = None,
30
+ bias: Optional["MetricsSource"] = None,
31
+ explainability: Optional["MetricsSource"] = None,
32
+ bias_pre_training: Optional["MetricsSource"] = None,
33
+ bias_post_training: Optional["MetricsSource"] = None,
34
+ ):
35
+ """Initialize a ``ModelMetrics`` instance and turn parameters into dict.
36
+
37
+ Args:
38
+ model_statistics (MetricsSource): A metric source object that represents
39
+ model statistics (default: None).
40
+ model_constraints (MetricsSource): A metric source object that represents
41
+ model constraints (default: None).
42
+ model_data_statistics (MetricsSource): A metric source object that represents
43
+ model data statistics (default: None).
44
+ model_data_constraints (MetricsSource): A metric source object that represents
45
+ model data constraints (default: None).
46
+ bias (MetricsSource): A metric source object that represents bias report
47
+ (default: None).
48
+ explainability (MetricsSource): A metric source object that represents
49
+ explainability report (default: None).
50
+ bias_pre_training (MetricsSource): A metric source object that represents
51
+ Pre-training report (default: None).
52
+ bias_post_training (MetricsSource): A metric source object that represents
53
+ Post-training report (default: None).
54
+ """
55
+ self.model_statistics = model_statistics
56
+ self.model_constraints = model_constraints
57
+ self.model_data_statistics = model_data_statistics
58
+ self.model_data_constraints = model_data_constraints
59
+ self.bias = bias
60
+ self.bias_pre_training = bias_pre_training
61
+ self.bias_post_training = bias_post_training
62
+ self.explainability = explainability
63
+
64
+ def _to_request_dict(self):
65
+ """Generates a request dictionary using the parameters provided to the class."""
66
+ model_metrics_request = {}
67
+
68
+ model_quality = {}
69
+ if self.model_statistics is not None:
70
+ model_quality["Statistics"] = self.model_statistics._to_request_dict()
71
+ if self.model_constraints is not None:
72
+ model_quality["Constraints"] = self.model_constraints._to_request_dict()
73
+ if model_quality:
74
+ model_metrics_request["ModelQuality"] = model_quality
75
+
76
+ model_data_quality = {}
77
+ if self.model_data_statistics is not None:
78
+ model_data_quality["Statistics"] = self.model_data_statistics._to_request_dict()
79
+ if self.model_data_constraints is not None:
80
+ model_data_quality["Constraints"] = self.model_data_constraints._to_request_dict()
81
+ if model_data_quality:
82
+ model_metrics_request["ModelDataQuality"] = model_data_quality
83
+
84
+ bias = {}
85
+ if self.bias is not None:
86
+ bias["Report"] = self.bias._to_request_dict()
87
+ if self.bias_pre_training is not None:
88
+ bias["PreTrainingReport"] = self.bias_pre_training._to_request_dict()
89
+ if self.bias_post_training is not None:
90
+ bias["PostTrainingReport"] = self.bias_post_training._to_request_dict()
91
+ model_metrics_request["Bias"] = bias
92
+
93
+ explainability = {}
94
+ if self.explainability is not None:
95
+ explainability["Report"] = self.explainability._to_request_dict()
96
+ model_metrics_request["Explainability"] = explainability
97
+
98
+ return model_metrics_request
99
+
100
+
101
+ class MetricsSource(object):
102
+ """Accepts metrics source parameters for conversion to request dict."""
103
+
104
+ def __init__(
105
+ self,
106
+ content_type: Union[str, PipelineVariable],
107
+ s3_uri: Union[str, PipelineVariable],
108
+ content_digest: Optional[Union[str, PipelineVariable]] = None,
109
+ ):
110
+ """Initialize a ``MetricsSource`` instance and turn parameters into dict.
111
+
112
+ Args:
113
+ content_type (str or PipelineVariable): Specifies the type of content
114
+ in S3 URI
115
+ s3_uri (str or PipelineVariable): The S3 URI of the metric
116
+ content_digest (str or PipelineVariable): The digest of the metric
117
+ (default: None)
118
+ """
119
+ self.content_type = content_type
120
+ self.s3_uri = s3_uri
121
+ self.content_digest = content_digest
122
+
123
+ def _to_request_dict(self):
124
+ """Generates a request dictionary using the parameters provided to the class."""
125
+ metrics_source_request = {"ContentType": self.content_type, "S3Uri": self.s3_uri}
126
+ if self.content_digest is not None:
127
+ metrics_source_request["ContentDigest"] = self.content_digest
128
+ return metrics_source_request
129
+
130
+
131
+ class FileSource(object):
132
+ """Accepts file source parameters for conversion to request dict."""
133
+
134
+ def __init__(
135
+ self,
136
+ s3_uri: Union[str, PipelineVariable],
137
+ content_digest: Optional[Union[str, PipelineVariable]] = None,
138
+ content_type: Optional[Union[str, PipelineVariable]] = None,
139
+ ):
140
+ """Initialize a ``FileSource`` instance and turn parameters into dict.
141
+
142
+ Args:
143
+ s3_uri (str or PipelineVariable): The S3 URI of the metric
144
+ content_digest (str or PipelineVariable): The digest of the metric
145
+ (default: None)
146
+ content_type (str or PipelineVariable): Specifies the type of content
147
+ in S3 URI (default: None)
148
+ """
149
+ self.content_type = content_type
150
+ self.s3_uri = s3_uri
151
+ self.content_digest = content_digest
152
+
153
+ def _to_request_dict(self):
154
+ """Generates a request dictionary using the parameters provided to the class."""
155
+ file_source_request = {"S3Uri": self.s3_uri}
156
+ if self.content_digest is not None:
157
+ file_source_request["ContentDigest"] = self.content_digest
158
+ if self.content_type is not None:
159
+ file_source_request["ContentType"] = self.content_type
160
+ return file_source_request
testbed/aws__sagemaker-python-sdk/src/sagemaker/multidatamodel.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """This module contains code to create and manage SageMaker ``MultiDataModel``"""
14
+ from __future__ import absolute_import
15
+
16
+ import os
17
+ from typing import Union, Optional
18
+
19
+ from six.moves.urllib.parse import urlparse
20
+
21
+ import sagemaker
22
+ from sagemaker import local, s3
23
+ from sagemaker.deprecations import removed_kwargs
24
+ from sagemaker.model import Model
25
+ from sagemaker.session import Session
26
+ from sagemaker.utils import pop_out_unused_kwarg
27
+ from sagemaker.workflow.entities import PipelineVariable
28
+
29
+ MULTI_MODEL_CONTAINER_MODE = "MultiModel"
30
+
31
+
32
+ class MultiDataModel(Model):
33
+ """SageMaker ``MultiDataModel`` can be used to deploy multiple models to the same ``Endpoint``.
34
+
35
+ And also deploy additional models to an existing SageMaker multi-model ``Endpoint``
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ name: str,
41
+ model_data_prefix: str,
42
+ model: Optional[Model] = None,
43
+ image_uri: Optional[Union[str, PipelineVariable]] = None,
44
+ role: Optional[str] = None,
45
+ sagemaker_session: Optional[Session] = None,
46
+ **kwargs,
47
+ ):
48
+ """Initialize a ``MultiDataModel``.
49
+
50
+ Addition to these arguments, it supports all arguments supported by ``Model`` constructor.
51
+
52
+ Args:
53
+ name (str): The model name.
54
+ model_data_prefix (str): The S3 prefix where all the models artifacts (.tar.gz)
55
+ in a Multi-Model endpoint are located
56
+ model (sagemaker.Model): The Model object that would define the
57
+ SageMaker model attributes like vpc_config, predictors, etc.
58
+ If this is present, the attributes from this model are used when
59
+ deploying the ``MultiDataModel``. Parameters 'image_uri', 'role' and 'kwargs'
60
+ are not permitted when model parameter is set.
61
+ image_uri (str or PipelineVariable): A Docker image URI. It can be null if the 'model'
62
+ parameter is passed to during ``MultiDataModel`` initialization (default: None)
63
+ role (str): An AWS IAM role (either name or full ARN). The Amazon
64
+ SageMaker training jobs and APIs that create Amazon SageMaker
65
+ endpoints use this role to access training data and model
66
+ artifacts. After the endpoint is created, the inference code
67
+ might use the IAM role if it needs to access some AWS resources.
68
+ It can be null if this is being used to create a Model to pass
69
+ to a ``PipelineModel`` which has its own Role field or if the 'model' parameter
70
+ is passed to during ``MultiDataModel`` initialization (default: None)
71
+ sagemaker_session (sagemaker.session.Session): A SageMaker Session
72
+ object, used for SageMaker interactions (default: None). If not
73
+ specified, one is created using the default AWS configuration
74
+ chain.
75
+ **kwargs: Keyword arguments passed to the
76
+ :class:`~sagemaker.model.Model` initializer.
77
+
78
+ .. tip::
79
+
80
+ You can find additional parameters for initializing this class at
81
+ :class:`~sagemaker.model.Model`.
82
+ """
83
+ # Validate path
84
+ if not model_data_prefix.startswith("s3://"):
85
+ raise ValueError(
86
+ 'Expecting S3 model prefix beginning with "s3://". Received: "{}"'.format(
87
+ model_data_prefix
88
+ )
89
+ )
90
+
91
+ if model and (image_uri or role or kwargs):
92
+ raise ValueError(
93
+ "Parameters image_uri, role, and kwargs are not permitted when "
94
+ "model parameter is passed."
95
+ )
96
+
97
+ self.name = name
98
+ self.model_data_prefix = model_data_prefix
99
+ self.model = model
100
+ self.container_mode = MULTI_MODEL_CONTAINER_MODE
101
+ self.sagemaker_session = sagemaker_session or Session()
102
+
103
+ if self.sagemaker_session.s3_client is None:
104
+ self.s3_client = self.sagemaker_session.boto_session.client(
105
+ "s3", region_name=self.sagemaker_session.boto_session.region_name
106
+ )
107
+ else:
108
+ self.s3_client = self.sagemaker_session.s3_client
109
+
110
+ # Set the ``Model`` parameters if the model parameter is not specified
111
+ if not self.model:
112
+ pop_out_unused_kwarg("model_data", kwargs, self.model_data_prefix)
113
+ super(MultiDataModel, self).__init__(
114
+ image_uri,
115
+ self.model_data_prefix,
116
+ role,
117
+ name=self.name,
118
+ sagemaker_session=self.sagemaker_session,
119
+ **kwargs,
120
+ )
121
+
122
+ def prepare_container_def(
123
+ self, instance_type=None, accelerator_type=None, serverless_inference_config=None
124
+ ):
125
+ """Return a container definition set.
126
+
127
+ Definition set includes MultiModel mode, model data and other parameters
128
+ from the model (if available).
129
+
130
+ Subclasses can override this to provide custom container definitions
131
+ for deployment to a specific instance type. Called by ``deploy()``.
132
+
133
+ Returns:
134
+ dict[str, str]: A complete container definition object usable with the CreateModel API
135
+ """
136
+ # Copy the trained model's image URI and environment variables if they exist. Models trained
137
+ # with FrameworkEstimator set framework specific environment variables which need to be
138
+ # copied over
139
+ if self.model:
140
+ container_definition = self.model.prepare_container_def(instance_type, accelerator_type)
141
+ image_uri = container_definition["Image"]
142
+ environment = container_definition["Environment"]
143
+ else:
144
+ image_uri = self.image_uri
145
+ environment = self.env
146
+ return sagemaker.container_def(
147
+ image_uri,
148
+ env=environment,
149
+ model_data_url=self.model_data_prefix,
150
+ container_mode=self.container_mode,
151
+ )
152
+
153
+ def deploy(
154
+ self,
155
+ initial_instance_count,
156
+ instance_type,
157
+ serializer=None,
158
+ deserializer=None,
159
+ accelerator_type=None,
160
+ endpoint_name=None,
161
+ tags=None,
162
+ kms_key=None,
163
+ wait=True,
164
+ data_capture_config=None,
165
+ **kwargs,
166
+ ):
167
+ """Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
168
+
169
+ Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an
170
+ ``Endpoint`` from this ``Model``. If self.model is not None, then the ``Endpoint``
171
+ will be deployed with parameters in self.model (like vpc_config,
172
+ enable_network_isolation, etc). If self.model is None, then use the parameters
173
+ in ``MultiDataModel`` constructor will be used. If ``self.predictor_cls`` is not
174
+ None, this method returns a the result of invoking ``self.predictor_cls`` on
175
+ the created endpoint name.
176
+
177
+ The name of the created model is accessible in the ``name`` field of
178
+ this ``Model`` after deploy returns
179
+
180
+ The name of the created endpoint is accessible in the
181
+ ``endpoint_name`` field of this ``Model`` after deploy returns.
182
+
183
+ Args:
184
+ initial_instance_count (int): The initial number of instances to run
185
+ in the ``Endpoint`` created from this ``Model``.
186
+ instance_type (str): The EC2 instance type to deploy this Model to.
187
+ For example, 'ml.p2.xlarge', or 'local' for local mode.
188
+ serializer (:class:`~sagemaker.serializers.BaseSerializer`): A
189
+ serializer object, used to encode data for an inference endpoint
190
+ (default: None). If ``serializer`` is not None, then
191
+ ``serializer`` will override the default serializer. The
192
+ default serializer is set by the ``predictor_cls``.
193
+ deserializer (:class:`~sagemaker.deserializers.BaseDeserializer`): A
194
+ deserializer object, used to decode data from an inference
195
+ endpoint (default: None). If ``deserializer`` is not None, then
196
+ ``deserializer`` will override the default deserializer. The
197
+ default deserializer is set by the ``predictor_cls``.
198
+ accelerator_type (str): Type of Elastic Inference accelerator to
199
+ deploy this model for model loading and inference, for example,
200
+ 'ml.eia1.medium'. If not specified, no Elastic Inference
201
+ accelerator will be attached to the endpoint. For more
202
+ information:
203
+ https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html
204
+ endpoint_name (str): The name of the endpoint to create (default:
205
+ None). If not specified, a unique endpoint name will be created.
206
+ tags (List[dict[str, str]]): The list of tags to attach to this
207
+ specific endpoint.
208
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
209
+ data on the storage volume attached to the instance hosting the
210
+ endpoint.
211
+ wait (bool): Whether the call should wait until the deployment of
212
+ this model completes (default: True).
213
+ data_capture_config (sagemaker.model_monitor.DataCaptureConfig): Specifies
214
+ configuration related to Endpoint data capture for use with
215
+ Amazon SageMaker Model Monitoring. Default: None.
216
+
217
+ Returns:
218
+ callable[string, sagemaker.session.Session] or None: Invocation of
219
+ ``self.predictor_cls`` on the created endpoint name,
220
+ if ``self.predictor_cls``
221
+ is not None. Otherwise, return None.
222
+ """
223
+ removed_kwargs("update_endpoint", kwargs)
224
+ # Set model specific parameters
225
+ if self.model:
226
+ enable_network_isolation = self.model.enable_network_isolation()
227
+ role = self.model.role
228
+ vpc_config = self.model.vpc_config
229
+ predictor_cls = self.model.predictor_cls
230
+ else:
231
+ enable_network_isolation = self.enable_network_isolation()
232
+ role = self.role
233
+ vpc_config = self.vpc_config
234
+ predictor_cls = self.predictor_cls
235
+
236
+ if role is None:
237
+ raise ValueError("Role can not be null for deploying a model")
238
+
239
+ if instance_type == "local" and not isinstance(self.sagemaker_session, local.LocalSession):
240
+ self.sagemaker_session = local.LocalSession()
241
+
242
+ container_def = self.prepare_container_def(instance_type, accelerator_type=accelerator_type)
243
+ self.sagemaker_session.create_model(
244
+ self.name,
245
+ role,
246
+ container_def,
247
+ vpc_config=vpc_config,
248
+ enable_network_isolation=enable_network_isolation,
249
+ tags=tags,
250
+ )
251
+
252
+ production_variant = sagemaker.production_variant(
253
+ self.name, instance_type, initial_instance_count, accelerator_type=accelerator_type
254
+ )
255
+ if endpoint_name:
256
+ self.endpoint_name = endpoint_name
257
+ else:
258
+ self.endpoint_name = self.name
259
+
260
+ data_capture_config_dict = None
261
+ if data_capture_config is not None:
262
+ data_capture_config_dict = data_capture_config._to_request_dict()
263
+
264
+ self.sagemaker_session.endpoint_from_production_variants(
265
+ name=self.endpoint_name,
266
+ production_variants=[production_variant],
267
+ tags=tags,
268
+ kms_key=kms_key,
269
+ wait=wait,
270
+ data_capture_config_dict=data_capture_config_dict,
271
+ )
272
+
273
+ if predictor_cls:
274
+ predictor = predictor_cls(self.endpoint_name, self.sagemaker_session)
275
+ if serializer:
276
+ predictor.serializer = serializer
277
+ if deserializer:
278
+ predictor.deserializer = deserializer
279
+ return predictor
280
+ return None
281
+
282
+ def add_model(self, model_data_source, model_data_path=None):
283
+ """Adds a model to the ``MultiDataModel``.
284
+
285
+ It is done by uploading or copying the model_data_source artifact to the given
286
+ S3 path model_data_path relative to model_data_prefix
287
+
288
+ Args:
289
+ model_source: Valid local file path or S3 path of the trained model artifact
290
+ model_data_path: S3 path where the trained model artifact
291
+ should be uploaded relative to ``self.model_data_prefix`` path. (default: None).
292
+ If None, then the model artifact is uploaded to a path relative to model_data_prefix
293
+
294
+ Returns:
295
+ str: S3 uri to uploaded model artifact
296
+ """
297
+ parse_result = urlparse(model_data_source)
298
+
299
+ # If the model source is an S3 path, copy the model artifact to the destination S3 path
300
+ if parse_result.scheme == "s3":
301
+ source_bucket, source_model_data_path = s3.parse_s3_url(model_data_source)
302
+ copy_source = {"Bucket": source_bucket, "Key": source_model_data_path}
303
+
304
+ if not model_data_path:
305
+ model_data_path = source_model_data_path
306
+
307
+ # Construct the destination path
308
+ dst_url = s3.s3_path_join(self.model_data_prefix, model_data_path)
309
+ destination_bucket, destination_model_data_path = s3.parse_s3_url(dst_url)
310
+
311
+ # Copy the model artifact
312
+ self.s3_client.copy(copy_source, destination_bucket, destination_model_data_path)
313
+ return s3.s3_path_join("s3://", destination_bucket, destination_model_data_path)
314
+
315
+ # If the model source is a local path, upload the local model artifact to the destination
316
+ # S3 path
317
+ if os.path.exists(model_data_source):
318
+ destination_bucket, dst_prefix = s3.parse_s3_url(self.model_data_prefix)
319
+ if model_data_path:
320
+ dst_s3_uri = s3.s3_path_join(dst_prefix, model_data_path)
321
+ else:
322
+ dst_s3_uri = s3.s3_path_join(dst_prefix, os.path.basename(model_data_source))
323
+ self.s3_client.upload_file(model_data_source, destination_bucket, dst_s3_uri)
324
+ # return upload_path
325
+ return s3.s3_path_join("s3://", destination_bucket, dst_s3_uri)
326
+
327
+ # Raise error if the model source is of an unexpected type
328
+ raise ValueError(
329
+ "model_source must either be a valid local file path or s3 uri. Received: "
330
+ '"{}"'.format(model_data_source)
331
+ )
332
+
333
+ def list_models(self):
334
+ """Generates and returns relative paths to model archives.
335
+
336
+ Archives are stored at model_data_prefix S3 location.
337
+
338
+ Yields: Paths to model archives relative to model_data_prefix path.
339
+ """
340
+ bucket, url_prefix = s3.parse_s3_url(self.model_data_prefix)
341
+ file_keys = self.sagemaker_session.list_s3_files(bucket=bucket, key_prefix=url_prefix)
342
+ for file_key in file_keys:
343
+ # Return the model paths relative to the model_data_prefix
344
+ # Ex: "a/b/c.tar.gz" -> "b/c.tar.gz" where url_prefix = "a/"
345
+ yield file_key.replace(url_prefix, "")
testbed/aws__sagemaker-python-sdk/src/sagemaker/network.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """This file contains code related to network configuration.
14
+
15
+ It also includes encryption, network isolation, and VPC configurations.
16
+ """
17
+ from __future__ import absolute_import
18
+
19
+ from typing import Union, Optional, List
20
+
21
+ from sagemaker.workflow.entities import PipelineVariable
22
+
23
+
24
+ class NetworkConfig(object):
25
+ """Accepts network configuration parameters for conversion to request dict.
26
+
27
+ The `_to_request_dict` provides a method to turn the parameters into a dict.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ enable_network_isolation: Union[bool, PipelineVariable] = False,
33
+ security_group_ids: Optional[List[Union[str, PipelineVariable]]] = None,
34
+ subnets: Optional[List[Union[str, PipelineVariable]]] = None,
35
+ encrypt_inter_container_traffic: Optional[Union[bool, PipelineVariable]] = None,
36
+ ):
37
+ """Initialize a ``NetworkConfig`` instance.
38
+
39
+ NetworkConfig accepts network configuration parameters and provides a method to turn
40
+ these parameters into a dictionary.
41
+
42
+ Args:
43
+ enable_network_isolation (bool or PipelineVariable): Boolean that determines
44
+ whether to enable network isolation.
45
+ security_group_ids (list[str] or list[PipelineVariable]): A list of strings representing
46
+ security group IDs.
47
+ subnets (list[str] or list[PipelineVariable]): A list of strings representing subnets.
48
+ encrypt_inter_container_traffic (bool or PipelineVariable): Boolean that determines
49
+ whether to encrypt inter-container traffic. Default value is None.
50
+ """
51
+ self.enable_network_isolation = enable_network_isolation
52
+ self.security_group_ids = security_group_ids
53
+ self.subnets = subnets
54
+ self.encrypt_inter_container_traffic = encrypt_inter_container_traffic
55
+
56
+ def _to_request_dict(self):
57
+ """Generates a request dictionary using the parameters provided to the class."""
58
+ network_config_request = {"EnableNetworkIsolation": self.enable_network_isolation}
59
+
60
+ if self.encrypt_inter_container_traffic is not None:
61
+ network_config_request[
62
+ "EnableInterContainerTrafficEncryption"
63
+ ] = self.encrypt_inter_container_traffic
64
+
65
+ if self.security_group_ids is not None or self.subnets is not None:
66
+ network_config_request["VpcConfig"] = {}
67
+
68
+ if self.security_group_ids is not None:
69
+ network_config_request["VpcConfig"]["SecurityGroupIds"] = self.security_group_ids
70
+
71
+ if self.subnets is not None:
72
+ network_config_request["VpcConfig"]["Subnets"] = self.subnets
73
+
74
+ return network_config_request
testbed/aws__sagemaker-python-sdk/src/sagemaker/pipeline.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import Optional, Dict, List, Union
17
+
18
+ import sagemaker
19
+ from sagemaker import ModelMetrics, Model
20
+ from sagemaker.drift_check_baselines import DriftCheckBaselines
21
+ from sagemaker.metadata_properties import MetadataProperties
22
+ from sagemaker.session import Session
23
+ from sagemaker.utils import (
24
+ name_from_image,
25
+ update_container_with_inference_params,
26
+ )
27
+ from sagemaker.transformer import Transformer
28
+ from sagemaker.workflow.entities import PipelineVariable
29
+ from sagemaker.workflow.pipeline_context import runnable_by_pipeline
30
+
31
+
32
+ class PipelineModel(object):
33
+ """A pipeline of SageMaker `Model` instances.
34
+
35
+ This pipeline can be deployed as an `Endpoint` on SageMaker.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ models: List[Model],
41
+ role: str,
42
+ predictor_cls: Optional[callable] = None,
43
+ name: Optional[str] = None,
44
+ vpc_config: Optional[Dict[str, List[Union[str, PipelineVariable]]]] = None,
45
+ sagemaker_session: Optional[Session] = None,
46
+ enable_network_isolation: Union[bool, PipelineVariable] = False,
47
+ ):
48
+ """Initialize a SageMaker `Model` instance.
49
+
50
+ The `Model` can be used to build an Inference Pipeline comprising of
51
+ multiple model containers.
52
+
53
+ Args:
54
+ models (list[sagemaker.Model]): For using multiple containers to
55
+ build an inference pipeline, you can pass a list of
56
+ ``sagemaker.Model`` objects in the order you want the inference
57
+ to happen.
58
+ role (str): An AWS IAM role (either name or full ARN). The Amazon
59
+ SageMaker training jobs and APIs that create Amazon SageMaker
60
+ endpoints use this role to access training data and model
61
+ artifacts. After the endpoint is created, the inference code
62
+ might use the IAM role, if it needs to access an AWS resource.
63
+ predictor_cls (callable[string, sagemaker.session.Session]): A
64
+ function to call to create a predictor (default: None). If not
65
+ None, ``deploy`` will return the result of invoking this
66
+ function on the created endpoint name.
67
+ name (str): The model name. If None, a default model name will be
68
+ selected on each ``deploy``.
69
+ vpc_config (dict[str, list[str]] or dict[str, list[PipelineVariable]]):
70
+ The VpcConfig set on the model (default: None)
71
+ * 'Subnets' (list[str]): List of subnet ids.
72
+ * 'SecurityGroupIds' (list[str]): List of security group ids.
73
+ sagemaker_session (sagemaker.session.Session): A SageMaker Session
74
+ object, used for SageMaker interactions (default: None). If not
75
+ specified, one is created using the default AWS configuration
76
+ chain.
77
+ enable_network_isolation (bool or PipelineVariable): Default False. if True,
78
+ enables network isolation in the endpoint, isolating the model
79
+ container. No inbound or outbound network calls can be made to
80
+ or from the model container.Boolean
81
+ """
82
+ self.models = models
83
+ self.role = role
84
+ self.predictor_cls = predictor_cls
85
+ self.name = name
86
+ self.vpc_config = vpc_config
87
+ self.sagemaker_session = sagemaker_session
88
+ self.enable_network_isolation = enable_network_isolation
89
+ self.endpoint_name = None
90
+
91
+ def pipeline_container_def(self, instance_type=None):
92
+ """The pipeline definition for deploying this model.
93
+
94
+ This is the dict created by ``sagemaker.pipeline_container_def()``.
95
+
96
+ The instance type to be used may be specified.
97
+
98
+ Subclasses can override this to provide custom container definitions
99
+ for deployment to a specific instance type. Called by ``deploy()``.
100
+
101
+ Args:
102
+ instance_type (str): The EC2 instance type to deploy this Model to.
103
+ For example, 'ml.p2.xlarge'.
104
+
105
+ Returns:
106
+ list[dict[str, str]]: A list of container definition objects usable
107
+ with the CreateModel API in the scenario of multiple containers
108
+ (Inference Pipeline).
109
+ """
110
+
111
+ return sagemaker.pipeline_container_def(self.models, instance_type)
112
+
113
+ def deploy(
114
+ self,
115
+ initial_instance_count,
116
+ instance_type,
117
+ serializer=None,
118
+ deserializer=None,
119
+ endpoint_name=None,
120
+ tags=None,
121
+ wait=True,
122
+ update_endpoint=False,
123
+ data_capture_config=None,
124
+ kms_key=None,
125
+ ):
126
+ """Deploy the ``Model`` to an ``Endpoint``.
127
+
128
+ It optionally return a ``Predictor``.
129
+
130
+ Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an
131
+ ``Endpoint`` from this ``Model``. If ``self.predictor_cls`` is not None,
132
+ this method returns a the result of invoking ``self.predictor_cls`` on
133
+ the created endpoint name.
134
+
135
+ The name of the created model is accessible in the ``name`` field of
136
+ this ``Model`` after deploy returns
137
+
138
+ The name of the created endpoint is accessible in the
139
+ ``endpoint_name`` field of this ``Model`` after deploy returns.
140
+
141
+ Args:
142
+ initial_instance_count (int): The initial number of instances to run
143
+ in the ``Endpoint`` created from this ``Model``.
144
+ instance_type (str): The EC2 instance type to deploy this Model to.
145
+ For example, 'ml.p2.xlarge'.
146
+ serializer (:class:`~sagemaker.serializers.BaseSerializer`): A
147
+ serializer object, used to encode data for an inference endpoint
148
+ (default: None). If ``serializer`` is not None, then
149
+ ``serializer`` will override the default serializer. The
150
+ default serializer is set by the ``predictor_cls``.
151
+ deserializer (:class:`~sagemaker.deserializers.BaseDeserializer`): A
152
+ deserializer object, used to decode data from an inference
153
+ endpoint (default: None). If ``deserializer`` is not None, then
154
+ ``deserializer`` will override the default deserializer. The
155
+ default deserializer is set by the ``predictor_cls``.
156
+ endpoint_name (str): The name of the endpoint to create (default:
157
+ None). If not specified, a unique endpoint name will be created.
158
+ tags (List[dict[str, str]]): The list of tags to attach to this
159
+ specific endpoint.
160
+ wait (bool): Whether the call should wait until the deployment of
161
+ model completes (default: True).
162
+ update_endpoint (bool): Flag to update the model in an existing
163
+ Amazon SageMaker endpoint. If True, this will deploy a new
164
+ EndpointConfig to an already existing endpoint and delete
165
+ resources corresponding to the previous EndpointConfig. If
166
+ False, a new endpoint will be created. Default: False
167
+ data_capture_config (sagemaker.model_monitor.DataCaptureConfig): Specifies
168
+ configuration related to Endpoint data capture for use with
169
+ Amazon SageMaker Model Monitoring. Default: None.
170
+ kms_key (str): The ARN, Key ID or Alias of the KMS key that is used to
171
+ encrypt the data on the storage volume attached to the instance hosting
172
+ the endpoint.
173
+
174
+ Returns:
175
+ callable[string, sagemaker.session.Session] or None: Invocation of
176
+ ``self.predictor_cls`` on the created endpoint name, if ``self.predictor_cls``
177
+ is not None. Otherwise, return None.
178
+ """
179
+ if not self.sagemaker_session:
180
+ self.sagemaker_session = Session()
181
+
182
+ containers = self.pipeline_container_def(instance_type)
183
+
184
+ self.name = self.name or name_from_image(containers[0]["Image"])
185
+ self.sagemaker_session.create_model(
186
+ self.name,
187
+ self.role,
188
+ containers,
189
+ vpc_config=self.vpc_config,
190
+ enable_network_isolation=self.enable_network_isolation,
191
+ )
192
+
193
+ production_variant = sagemaker.production_variant(
194
+ self.name, instance_type, initial_instance_count
195
+ )
196
+ self.endpoint_name = endpoint_name or self.name
197
+
198
+ data_capture_config_dict = None
199
+ if data_capture_config is not None:
200
+ data_capture_config_dict = data_capture_config._to_request_dict()
201
+
202
+ if update_endpoint:
203
+ endpoint_config_name = self.sagemaker_session.create_endpoint_config(
204
+ name=self.name,
205
+ model_name=self.name,
206
+ initial_instance_count=initial_instance_count,
207
+ instance_type=instance_type,
208
+ tags=tags,
209
+ kms_key=kms_key,
210
+ data_capture_config_dict=data_capture_config_dict,
211
+ )
212
+ self.sagemaker_session.update_endpoint(
213
+ self.endpoint_name, endpoint_config_name, wait=wait
214
+ )
215
+ else:
216
+ self.sagemaker_session.endpoint_from_production_variants(
217
+ name=self.endpoint_name,
218
+ production_variants=[production_variant],
219
+ tags=tags,
220
+ kms_key=kms_key,
221
+ wait=wait,
222
+ data_capture_config_dict=data_capture_config_dict,
223
+ )
224
+
225
+ if self.predictor_cls:
226
+ predictor = self.predictor_cls(self.endpoint_name, self.sagemaker_session)
227
+ if serializer:
228
+ predictor.serializer = serializer
229
+ if deserializer:
230
+ predictor.deserializer = deserializer
231
+ return predictor
232
+ return None
233
+
234
+ @runnable_by_pipeline
235
+ def create(self, instance_type: str):
236
+ """Create a SageMaker Model Entity
237
+
238
+ Args:
239
+ instance_type (str): The EC2 instance type that this Model will be
240
+ used for, this is only used to determine if the image needs GPU
241
+ support or not.
242
+ """
243
+ self._create_sagemaker_pipeline_model(instance_type)
244
+
245
+ def _create_sagemaker_pipeline_model(self, instance_type):
246
+ """Create a SageMaker Model Entity
247
+
248
+ Args:
249
+ instance_type (str): The EC2 instance type that this Model will be
250
+ used for, this is only used to determine if the image needs GPU
251
+ support or not.
252
+ """
253
+ if not self.sagemaker_session:
254
+ self.sagemaker_session = Session()
255
+
256
+ containers = self.pipeline_container_def(instance_type)
257
+
258
+ self.name = self.name or name_from_image(containers[0]["Image"])
259
+ create_model_args = dict(
260
+ name=self.name,
261
+ role=self.role,
262
+ container_defs=containers,
263
+ vpc_config=self.vpc_config,
264
+ enable_network_isolation=self.enable_network_isolation,
265
+ )
266
+ self.sagemaker_session.create_model(**create_model_args)
267
+
268
+ @runnable_by_pipeline
269
+ def register(
270
+ self,
271
+ content_types: List[Union[str, PipelineVariable]],
272
+ response_types: List[Union[str, PipelineVariable]],
273
+ inference_instances: Optional[List[Union[str, PipelineVariable]]] = None,
274
+ transform_instances: Optional[List[Union[str, PipelineVariable]]] = None,
275
+ model_package_name: Optional[Union[str, PipelineVariable]] = None,
276
+ model_package_group_name: Optional[Union[str, PipelineVariable]] = None,
277
+ image_uri: Optional[Union[str, PipelineVariable]] = None,
278
+ model_metrics: Optional[ModelMetrics] = None,
279
+ metadata_properties: Optional[MetadataProperties] = None,
280
+ marketplace_cert: bool = False,
281
+ approval_status: Optional[Union[str, PipelineVariable]] = None,
282
+ description: Optional[str] = None,
283
+ drift_check_baselines: Optional[DriftCheckBaselines] = None,
284
+ customer_metadata_properties: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
285
+ domain: Optional[Union[str, PipelineVariable]] = None,
286
+ sample_payload_url: Optional[Union[str, PipelineVariable]] = None,
287
+ task: Optional[Union[str, PipelineVariable]] = None,
288
+ framework: Optional[Union[str, PipelineVariable]] = None,
289
+ framework_version: Optional[Union[str, PipelineVariable]] = None,
290
+ nearest_model_name: Optional[Union[str, PipelineVariable]] = None,
291
+ data_input_configuration: Optional[Union[str, PipelineVariable]] = None,
292
+ ):
293
+ """Creates a model package for creating SageMaker models or listing on Marketplace.
294
+
295
+ Args:
296
+ content_types (list[str] or list[PipelineVariable]): The supported MIME types
297
+ for the input data.
298
+ response_types (list[str] or list[PipelineVariable]): The supported MIME types
299
+ for the output data.
300
+ inference_instances (list[str] or list[PipelineVariable]): A list of the instance
301
+ types that are used to generate inferences in real-time (default: None).
302
+ transform_instances (list[str] or list[PipelineVariable]): A list of the instance types
303
+ on which a transformation job can be run or on which an endpoint can be deployed
304
+ (default: None).
305
+ model_package_name (str or PipelineVariable): Model Package name, exclusive to
306
+ `model_package_group_name`, using `model_package_name` makes the Model Package
307
+ un-versioned (default: None).
308
+ model_package_group_name (str or PipelineVariable): Model Package Group name,
309
+ exclusive to `model_package_name`, using `model_package_group_name` makes
310
+ the Model Package versioned (default: None).
311
+ image_uri (str or PipelineVariable): Inference image uri for the container.
312
+ Model class' self.image will be used if it is None (default: None).
313
+ model_metrics (ModelMetrics): ModelMetrics object (default: None).
314
+ metadata_properties (MetadataProperties): MetadataProperties object (default: None).
315
+ marketplace_cert (bool): A boolean value indicating if the Model Package is certified
316
+ for AWS Marketplace (default: False).
317
+ approval_status (str or PipelineVariable): Model Approval Status, values can
318
+ be "Approved", "Rejected", or "PendingManualApproval"
319
+ (default: "PendingManualApproval").
320
+ description (str): Model Package description (default: None).
321
+ drift_check_baselines (DriftCheckBaselines): DriftCheckBaselines object (default: None).
322
+ customer_metadata_properties (dict[str, str] or dict[str, PipelineVariable]):
323
+ A dictionary of key-value paired metadata properties (default: None).
324
+ domain (str or PipelineVariable): Domain values can be "COMPUTER_VISION",
325
+ "NATURAL_LANGUAGE_PROCESSING", "MACHINE_LEARNING" (default: None).
326
+ sample_payload_url (str or PipelineVariable): The S3 path where the sample payload
327
+ is stored (default: None).
328
+ task (str or PipelineVariable): Task values which are supported by Inference Recommender
329
+ are "FILL_MASK", "IMAGE_CLASSIFICATION", "OBJECT_DETECTION", "TEXT_GENERATION",
330
+ "IMAGE_SEGMENTATION", "CLASSIFICATION", "REGRESSION", "OTHER" (default: None).
331
+ framework (str or PipelineVariable): Machine learning framework of the model package
332
+ container image (default: None).
333
+ framework_version (str or PipelineVariable): Framework version of the Model Package
334
+ Container Image (default: None).
335
+ nearest_model_name (str or PipelineVariable): Name of a pre-trained machine learning
336
+ benchmarked by Amazon SageMaker Inference Recommender (default: None).
337
+ data_input_configuration (str or PipelineVariable): Input object for the model
338
+ (default: None).
339
+
340
+ Returns:
341
+ A `sagemaker.model.ModelPackage` instance.
342
+ """
343
+ for model in self.models:
344
+ if model.model_data is None:
345
+ raise ValueError("SageMaker Model Package cannot be created without model data.")
346
+ if model_package_group_name is not None:
347
+ container_def = self.pipeline_container_def(
348
+ inference_instances[0] if inference_instances else None
349
+ )
350
+ container_def = update_container_with_inference_params(
351
+ framework=framework,
352
+ framework_version=framework_version,
353
+ nearest_model_name=nearest_model_name,
354
+ data_input_configuration=data_input_configuration,
355
+ container_list=container_def,
356
+ )
357
+ else:
358
+ container_def = [
359
+ {
360
+ "Image": image_uri or model.image_uri,
361
+ "ModelDataUrl": model.model_data,
362
+ }
363
+ for model in self.models
364
+ ]
365
+
366
+ model_pkg_args = sagemaker.get_model_package_args(
367
+ content_types,
368
+ response_types,
369
+ inference_instances=inference_instances,
370
+ transform_instances=transform_instances,
371
+ model_package_name=model_package_name,
372
+ model_package_group_name=model_package_group_name,
373
+ model_metrics=model_metrics,
374
+ metadata_properties=metadata_properties,
375
+ marketplace_cert=marketplace_cert,
376
+ approval_status=approval_status,
377
+ description=description,
378
+ container_def_list=container_def,
379
+ drift_check_baselines=drift_check_baselines,
380
+ customer_metadata_properties=customer_metadata_properties,
381
+ domain=domain,
382
+ sample_payload_url=sample_payload_url,
383
+ task=task,
384
+ )
385
+
386
+ self.sagemaker_session.create_model_package_from_containers(**model_pkg_args)
387
+
388
+ def transformer(
389
+ self,
390
+ instance_count,
391
+ instance_type,
392
+ strategy=None,
393
+ assemble_with=None,
394
+ output_path=None,
395
+ output_kms_key=None,
396
+ accept=None,
397
+ env=None,
398
+ max_concurrent_transforms=None,
399
+ max_payload=None,
400
+ tags=None,
401
+ volume_kms_key=None,
402
+ ):
403
+ """Return a ``Transformer`` that uses this Model.
404
+
405
+ Args:
406
+ instance_count (int): Number of EC2 instances to use.
407
+ instance_type (str): Type of EC2 instance to use, for example,
408
+ 'ml.c4.xlarge'.
409
+ strategy (str): The strategy used to decide how to batch records in
410
+ a single request (default: None). Valid values: 'MultiRecord'
411
+ and 'SingleRecord'.
412
+ assemble_with (str): How the output is assembled (default: None).
413
+ Valid values: 'Line' or 'None'.
414
+ output_path (str): S3 location for saving the transform result. If
415
+ not specified, results are stored to a default bucket.
416
+ output_kms_key (str): Optional. KMS key ID for encrypting the
417
+ transform output (default: None).
418
+ accept (str): The accept header passed by the client to
419
+ the inference endpoint. If it is supported by the endpoint,
420
+ it will be the format of the batch transform output.
421
+ env (dict): Environment variables to be set for use during the
422
+ transform job (default: None).
423
+ max_concurrent_transforms (int): The maximum number of HTTP requests
424
+ to be made to each individual transform container at one time.
425
+ max_payload (int): Maximum size of the payload in a single HTTP
426
+ request to the container in MB.
427
+ tags (list[dict]): List of tags for labeling a transform job. If
428
+ none specified, then the tags used for the training job are used
429
+ for the transform job.
430
+ volume_kms_key (str): Optional. KMS key ID for encrypting the volume
431
+ attached to the ML compute instance (default: None).
432
+ """
433
+ self._create_sagemaker_pipeline_model(instance_type)
434
+
435
+ return Transformer(
436
+ self.name,
437
+ instance_count,
438
+ instance_type,
439
+ strategy=strategy,
440
+ assemble_with=assemble_with,
441
+ output_path=output_path,
442
+ output_kms_key=output_kms_key,
443
+ accept=accept,
444
+ max_concurrent_transforms=max_concurrent_transforms,
445
+ max_payload=max_payload,
446
+ env=env,
447
+ tags=tags,
448
+ base_transform_job_name=self.name,
449
+ volume_kms_key=volume_kms_key,
450
+ sagemaker_session=self.sagemaker_session,
451
+ )
452
+
453
+ def delete_model(self):
454
+ """Delete the SageMaker model backing this pipeline model.
455
+
456
+ This does not delete the list of SageMaker models used in multiple containers to build
457
+ the inference pipeline.
458
+ """
459
+
460
+ if self.name is None:
461
+ raise ValueError("The SageMaker model must be created before attempting to delete.")
462
+
463
+ self.sagemaker_session.delete_model(self.name)
testbed/aws__sagemaker-python-sdk/src/sagemaker/predictor.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import print_function, absolute_import
15
+
16
+ import abc
17
+ from typing import Any, Tuple
18
+
19
+ from sagemaker.deprecations import (
20
+ deprecated_class,
21
+ deprecated_deserialize,
22
+ deprecated_serialize,
23
+ removed_kwargs,
24
+ renamed_kwargs,
25
+ renamed_warning,
26
+ )
27
+ from sagemaker.deserializers import ( # noqa: F401 # pylint: disable=unused-import
28
+ BytesDeserializer,
29
+ CSVDeserializer,
30
+ JSONDeserializer,
31
+ NumpyDeserializer,
32
+ StreamDeserializer,
33
+ StringDeserializer,
34
+ )
35
+ from sagemaker.model_monitor import (
36
+ DataCaptureConfig,
37
+ DefaultModelMonitor,
38
+ ModelBiasMonitor,
39
+ ModelExplainabilityMonitor,
40
+ ModelMonitor,
41
+ ModelQualityMonitor,
42
+ )
43
+ from sagemaker.serializers import (
44
+ CSVSerializer,
45
+ IdentitySerializer,
46
+ JSONSerializer,
47
+ NumpySerializer,
48
+ )
49
+ from sagemaker.session import production_variant, Session
50
+ from sagemaker.utils import name_from_base
51
+
52
+ from sagemaker.model_monitor.model_monitoring import DEFAULT_REPOSITORY_NAME
53
+
54
+ from sagemaker.lineage.context import EndpointContext
55
+
56
+
57
+ class PredictorBase(abc.ABC):
58
+ """An object that encapsulates a deployed model."""
59
+
60
+ @abc.abstractmethod
61
+ def predict(self, *args, **kwargs) -> Any:
62
+ """Perform inference on the provided data and return a prediction."""
63
+
64
+ @abc.abstractmethod
65
+ def delete_predictor(self, *args, **kwargs) -> None:
66
+ """Destroy resources associated with this predictor."""
67
+
68
+ @property
69
+ @abc.abstractmethod
70
+ def content_type(self) -> str:
71
+ """The MIME type of the data sent to the inference server."""
72
+
73
+ @property
74
+ @abc.abstractmethod
75
+ def accept(self) -> Tuple[str]:
76
+ """The content type(s) that are expected from the inference server."""
77
+
78
+
79
+ class Predictor(PredictorBase):
80
+ """Make prediction requests to an Amazon SageMaker endpoint."""
81
+
82
+ def __init__(
83
+ self,
84
+ endpoint_name,
85
+ sagemaker_session=None,
86
+ serializer=IdentitySerializer(),
87
+ deserializer=BytesDeserializer(),
88
+ **kwargs,
89
+ ):
90
+ """Initialize a ``Predictor``.
91
+
92
+ Behavior for serialization of input data and deserialization of
93
+ result data can be configured through initializer arguments. If not
94
+ specified, a sequence of bytes is expected and the API sends it in the
95
+ request body without modifications. In response, the API returns the
96
+ sequence of bytes from the prediction result without any modifications.
97
+
98
+ Args:
99
+ endpoint_name (str): Name of the Amazon SageMaker endpoint to which
100
+ requests are sent.
101
+ sagemaker_session (sagemaker.session.Session): A SageMaker Session
102
+ object, used for SageMaker interactions (default: None). If not
103
+ specified, one is created using the default AWS configuration
104
+ chain.
105
+ serializer (:class:`~sagemaker.serializers.BaseSerializer`): A
106
+ serializer object, used to encode data for an inference endpoint
107
+ (default: :class:`~sagemaker.serializers.IdentitySerializer`).
108
+ deserializer (:class:`~sagemaker.deserializers.BaseDeserializer`): A
109
+ deserializer object, used to decode data from an inference
110
+ endpoint (default: :class:`~sagemaker.deserializers.BytesDeserializer`).
111
+ """
112
+ removed_kwargs("content_type", kwargs)
113
+ removed_kwargs("accept", kwargs)
114
+ endpoint_name = renamed_kwargs("endpoint", "endpoint_name", endpoint_name, kwargs)
115
+ self.endpoint_name = endpoint_name
116
+ self.sagemaker_session = sagemaker_session or Session()
117
+ self.serializer = serializer
118
+ self.deserializer = deserializer
119
+ self._endpoint_config_name = None
120
+ self._model_names = None
121
+ self._context = None
122
+
123
+ def predict(
124
+ self,
125
+ data,
126
+ initial_args=None,
127
+ target_model=None,
128
+ target_variant=None,
129
+ inference_id=None,
130
+ ):
131
+ """Return the inference from the specified endpoint.
132
+
133
+ Args:
134
+ data (object): Input data for which you want the model to provide
135
+ inference. If a serializer was specified when creating the
136
+ Predictor, the result of the serializer is sent as input
137
+ data. Otherwise the data must be sequence of bytes, and the
138
+ predict method then sends the bytes in the request body as is.
139
+ initial_args (dict[str,str]): Optional. Default arguments for boto3
140
+ ``invoke_endpoint`` call. Default is None (no default
141
+ arguments).
142
+ target_model (str): S3 model artifact path to run an inference request on,
143
+ in case of a multi model endpoint. Does not apply to endpoints hosting
144
+ single model (Default: None)
145
+ target_variant (str): The name of the production variant to run an inference
146
+ request on (Default: None). Note that the ProductionVariant identifies the
147
+ model you want to host and the resources you want to deploy for hosting it.
148
+ inference_id (str): If you provide a value, it is added to the captured data
149
+ when you enable data capture on the endpoint (Default: None).
150
+
151
+ Returns:
152
+ object: Inference for the given input. If a deserializer was specified when creating
153
+ the Predictor, the result of the deserializer is
154
+ returned. Otherwise the response returns the sequence of bytes
155
+ as is.
156
+ """
157
+
158
+ request_args = self._create_request_args(
159
+ data, initial_args, target_model, target_variant, inference_id
160
+ )
161
+ response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
162
+ return self._handle_response(response)
163
+
164
+ def _handle_response(self, response):
165
+ """Placeholder docstring"""
166
+ response_body = response["Body"]
167
+ content_type = response.get("ContentType", "application/octet-stream")
168
+ return self.deserializer.deserialize(response_body, content_type)
169
+
170
+ def _create_request_args(
171
+ self,
172
+ data,
173
+ initial_args=None,
174
+ target_model=None,
175
+ target_variant=None,
176
+ inference_id=None,
177
+ ):
178
+ """Placeholder docstring"""
179
+ args = dict(initial_args) if initial_args else {}
180
+
181
+ if "EndpointName" not in args:
182
+ args["EndpointName"] = self.endpoint_name
183
+
184
+ if "ContentType" not in args:
185
+ args["ContentType"] = self.content_type
186
+
187
+ if "Accept" not in args:
188
+ args["Accept"] = ", ".join(self.accept)
189
+
190
+ if target_model:
191
+ args["TargetModel"] = target_model
192
+
193
+ if target_variant:
194
+ args["TargetVariant"] = target_variant
195
+
196
+ if inference_id:
197
+ args["InferenceId"] = inference_id
198
+
199
+ data = self.serializer.serialize(data)
200
+
201
+ args["Body"] = data
202
+ return args
203
+
204
+ def update_endpoint(
205
+ self,
206
+ initial_instance_count=None,
207
+ instance_type=None,
208
+ accelerator_type=None,
209
+ model_name=None,
210
+ tags=None,
211
+ kms_key=None,
212
+ data_capture_config_dict=None,
213
+ wait=True,
214
+ ):
215
+ """Update the existing endpoint with the provided attributes.
216
+
217
+ This creates a new EndpointConfig in the process. If ``initial_instance_count``,
218
+ ``instance_type``, ``accelerator_type``, or ``model_name`` is specified, then a new
219
+ ProductionVariant configuration is created; values from the existing configuration
220
+ are not preserved if any of those parameters are specified.
221
+
222
+ Args:
223
+ initial_instance_count (int): The initial number of instances to run in the endpoint.
224
+ This is required if ``instance_type``, ``accelerator_type``, or ``model_name`` is
225
+ specified. Otherwise, the values from the existing endpoint configuration's
226
+ ProductionVariants are used.
227
+ instance_type (str): The EC2 instance type to deploy the endpoint to.
228
+ This is required if ``initial_instance_count`` or ``accelerator_type`` is specified.
229
+ Otherwise, the values from the existing endpoint configuration's
230
+ ``ProductionVariants`` are used.
231
+ accelerator_type (str): The type of Elastic Inference accelerator to attach to
232
+ the endpoint, e.g. "ml.eia1.medium". If not specified, and
233
+ ``initial_instance_count``, ``instance_type``, and ``model_name`` are also ``None``,
234
+ the values from the existing endpoint configuration's ``ProductionVariants`` are
235
+ used. Otherwise, no Elastic Inference accelerator is attached to the endpoint.
236
+ model_name (str): The name of the model to be associated with the endpoint.
237
+ This is required if ``initial_instance_count``, ``instance_type``, or
238
+ ``accelerator_type`` is specified and if there is more than one model associated
239
+ with the endpoint. Otherwise, the existing model for the endpoint is used.
240
+ tags (list[dict[str, str]]): The list of tags to add to the endpoint
241
+ config. If not specified, the tags of the existing endpoint configuration are used.
242
+ If any of the existing tags are reserved AWS ones (i.e. begin with "aws"),
243
+ they are not carried over to the new endpoint configuration.
244
+ kms_key (str): The KMS key that is used to encrypt the data on the storage volume
245
+ attached to the instance hosting the endpoint If not specified,
246
+ the KMS key of the existing endpoint configuration is used.
247
+ data_capture_config_dict (dict): The endpoint data capture configuration
248
+ for use with Amazon SageMaker Model Monitoring. If not specified,
249
+ the data capture configuration of the existing endpoint configuration is used.
250
+
251
+ Raises:
252
+ ValueError: If there is not enough information to create a new ``ProductionVariant``:
253
+
254
+ - If ``initial_instance_count``, ``accelerator_type``, or ``model_name`` is
255
+ specified, but ``instance_type`` is ``None``.
256
+ - If ``initial_instance_count``, ``instance_type``, or ``accelerator_type`` is
257
+ specified and either ``model_name`` is ``None`` or there are multiple models
258
+ associated with the endpoint.
259
+ """
260
+ production_variants = None
261
+ current_model_names = self._get_model_names()
262
+
263
+ if initial_instance_count or instance_type or accelerator_type or model_name:
264
+ if instance_type is None or initial_instance_count is None:
265
+ raise ValueError(
266
+ "Missing initial_instance_count and/or instance_type. Provided values: "
267
+ "initial_instance_count={}, instance_type={}, accelerator_type={}, "
268
+ "model_name={}.".format(
269
+ initial_instance_count,
270
+ instance_type,
271
+ accelerator_type,
272
+ model_name,
273
+ )
274
+ )
275
+
276
+ if model_name is None:
277
+ if len(current_model_names) > 1:
278
+ raise ValueError(
279
+ "Unable to choose a default model for a new EndpointConfig because "
280
+ "the endpoint has multiple models: {}".format(
281
+ ", ".join(current_model_names)
282
+ )
283
+ )
284
+ model_name = current_model_names[0]
285
+ else:
286
+ self._model_names = [model_name]
287
+
288
+ production_variant_config = production_variant(
289
+ model_name,
290
+ instance_type,
291
+ initial_instance_count=initial_instance_count,
292
+ accelerator_type=accelerator_type,
293
+ )
294
+ production_variants = [production_variant_config]
295
+
296
+ current_endpoint_config_name = self._get_endpoint_config_name()
297
+ new_endpoint_config_name = name_from_base(current_endpoint_config_name)
298
+ self.sagemaker_session.create_endpoint_config_from_existing(
299
+ current_endpoint_config_name,
300
+ new_endpoint_config_name,
301
+ new_tags=tags,
302
+ new_kms_key=kms_key,
303
+ new_data_capture_config_dict=data_capture_config_dict,
304
+ new_production_variants=production_variants,
305
+ )
306
+ self.sagemaker_session.update_endpoint(
307
+ self.endpoint_name, new_endpoint_config_name, wait=wait
308
+ )
309
+ self._endpoint_config_name = new_endpoint_config_name
310
+
311
+ def _delete_endpoint_config(self):
312
+ """Delete the Amazon SageMaker endpoint configuration"""
313
+ current_endpoint_config_name = self._get_endpoint_config_name()
314
+ self.sagemaker_session.delete_endpoint_config(current_endpoint_config_name)
315
+
316
+ def delete_endpoint(self, delete_endpoint_config=True):
317
+ """Delete the Amazon SageMaker endpoint backing this predictor.
318
+
319
+ This also delete the endpoint configuration attached to it if
320
+ delete_endpoint_config is True.
321
+
322
+ Args:
323
+ delete_endpoint_config (bool, optional): Flag to indicate whether to
324
+ delete endpoint configuration together with endpoint. Defaults
325
+ to True. If True, both endpoint and endpoint configuration will
326
+ be deleted. If False, only endpoint will be deleted.
327
+ """
328
+ if delete_endpoint_config:
329
+ self._delete_endpoint_config()
330
+
331
+ self.sagemaker_session.delete_endpoint(self.endpoint_name)
332
+
333
+ delete_predictor = delete_endpoint
334
+
335
+ def delete_model(self):
336
+ """Deletes the Amazon SageMaker models backing this predictor."""
337
+ request_failed = False
338
+ failed_models = []
339
+ current_model_names = self._get_model_names()
340
+ for model_name in current_model_names:
341
+ try:
342
+ self.sagemaker_session.delete_model(model_name)
343
+ except Exception: # pylint: disable=broad-except
344
+ request_failed = True
345
+ failed_models.append(model_name)
346
+
347
+ if request_failed:
348
+ raise Exception(
349
+ "One or more models cannot be deleted, please retry. \n"
350
+ "Failed models: {}".format(", ".join(failed_models))
351
+ )
352
+
353
+ def enable_data_capture(self):
354
+ """Enables data capture by updating DataCaptureConfig.
355
+
356
+ This function updates the DataCaptureConfig for the Predictor's associated Amazon SageMaker
357
+ Endpoint to enable data capture. For a more customized experience, refer to
358
+ update_data_capture_config, instead.
359
+ """
360
+ self.update_data_capture_config(
361
+ data_capture_config=DataCaptureConfig(
362
+ enable_capture=True, sagemaker_session=self.sagemaker_session
363
+ )
364
+ )
365
+
366
+ def disable_data_capture(self):
367
+ """Disables data capture by updating DataCaptureConfig.
368
+
369
+ This function updates the DataCaptureConfig for the Predictor's associated Amazon SageMaker
370
+ Endpoint to disable data capture. For a more customized experience, refer to
371
+ update_data_capture_config, instead.
372
+ """
373
+ self.update_data_capture_config(
374
+ data_capture_config=DataCaptureConfig(
375
+ enable_capture=False, sagemaker_session=self.sagemaker_session
376
+ )
377
+ )
378
+
379
+ def update_data_capture_config(self, data_capture_config):
380
+ """Updates the DataCaptureConfig for the Predictor's associated Amazon SageMaker Endpoint.
381
+
382
+ Update is done using the provided DataCaptureConfig.
383
+
384
+ Args:
385
+ data_capture_config (sagemaker.model_monitor.DataCaptureConfig): The
386
+ DataCaptureConfig to update the predictor's endpoint to use.
387
+ """
388
+ endpoint_desc = self.sagemaker_session.sagemaker_client.describe_endpoint(
389
+ EndpointName=self.endpoint_name
390
+ )
391
+
392
+ new_config_name = name_from_base(base=self.endpoint_name)
393
+
394
+ data_capture_config_dict = None
395
+ if data_capture_config is not None:
396
+ data_capture_config_dict = data_capture_config._to_request_dict()
397
+
398
+ self.sagemaker_session.create_endpoint_config_from_existing(
399
+ existing_config_name=endpoint_desc["EndpointConfigName"],
400
+ new_config_name=new_config_name,
401
+ new_data_capture_config_dict=data_capture_config_dict,
402
+ )
403
+
404
+ self.sagemaker_session.update_endpoint(
405
+ endpoint_name=self.endpoint_name, endpoint_config_name=new_config_name
406
+ )
407
+
408
+ def list_monitors(self):
409
+ """Generates ModelMonitor objects (or DefaultModelMonitors).
410
+
411
+ Objects are generated based on the schedule(s) associated with the endpoint
412
+ that this predictor refers to.
413
+
414
+ Returns:
415
+ [sagemaker.model_monitor.model_monitoring.ModelMonitor]: A list of
416
+ ModelMonitor (or DefaultModelMonitor) objects.
417
+
418
+ """
419
+ monitoring_schedules_dict = self.sagemaker_session.list_monitoring_schedules(
420
+ endpoint_name=self.endpoint_name
421
+ )
422
+ if len(monitoring_schedules_dict["MonitoringScheduleSummaries"]) == 0:
423
+ print("No monitors found for endpoint. endpoint: {}".format(self.endpoint_name))
424
+ return []
425
+
426
+ monitors = []
427
+ for schedule_dict in monitoring_schedules_dict["MonitoringScheduleSummaries"]:
428
+ schedule_name = schedule_dict["MonitoringScheduleName"]
429
+ monitoring_type = schedule_dict.get("MonitoringType")
430
+ clazz = self._get_model_monitor_class(schedule_name, monitoring_type)
431
+ monitors.append(
432
+ clazz.attach(
433
+ monitor_schedule_name=schedule_name,
434
+ sagemaker_session=self.sagemaker_session,
435
+ )
436
+ )
437
+
438
+ return monitors
439
+
440
+ def _get_model_monitor_class(self, schedule_name, monitoring_type):
441
+ """Decide which ModelMonitor class the given schedule should attach to
442
+
443
+ Args:
444
+ schedule_name (str): The schedule to be attached.
445
+ monitoring_type (str): The monitoring type of the schedule
446
+
447
+ Returns:
448
+ sagemaker.model_monitor.ModelMonitor: ModelMonitor or a subclass of ModelMonitor.
449
+
450
+ Raises:
451
+ TypeError: If the class could not be decided (due to unknown monitoring type).
452
+ """
453
+ if monitoring_type == "ModelBias":
454
+ clazz = ModelBiasMonitor
455
+ elif monitoring_type == "ModelExplainability":
456
+ clazz = ModelExplainabilityMonitor
457
+ else:
458
+ schedule = self.sagemaker_session.describe_monitoring_schedule(
459
+ monitoring_schedule_name=schedule_name
460
+ )
461
+ embedded_job_definition = schedule["MonitoringScheduleConfig"].get(
462
+ "MonitoringJobDefinition"
463
+ )
464
+ if embedded_job_definition is not None: # legacy v1 schedule
465
+ image_uri = embedded_job_definition["MonitoringAppSpecification"]["ImageUri"]
466
+ if image_uri.endswith(DEFAULT_REPOSITORY_NAME):
467
+ clazz = DefaultModelMonitor
468
+ else:
469
+ clazz = ModelMonitor
470
+ elif monitoring_type == "DataQuality":
471
+ clazz = DefaultModelMonitor
472
+ elif monitoring_type == "ModelQuality":
473
+ clazz = ModelQualityMonitor
474
+ else:
475
+ raise TypeError("Unknown monitoring type: {}".format(monitoring_type))
476
+ return clazz
477
+
478
+ def endpoint_context(self):
479
+ """Retrieves the lineage context object representing the endpoint.
480
+
481
+ Examples:
482
+ .. code-block:: python
483
+
484
+ predictor = Predictor()
485
+ ...
486
+ context = predictor.endpoint_context()
487
+ models = context.models()
488
+
489
+ Returns:
490
+ ContextEndpoint: The context for the endpoint.
491
+ """
492
+ if self._context:
493
+ return self._context
494
+
495
+ # retrieve endpoint by name to get arn
496
+ response = self.sagemaker_session.sagemaker_client.describe_endpoint(
497
+ EndpointName=self.endpoint_name
498
+ )
499
+ endpoint_arn = response["EndpointArn"]
500
+
501
+ # list context by source uri using arn
502
+ contexts = list(
503
+ EndpointContext.list(sagemaker_session=self.sagemaker_session, source_uri=endpoint_arn)
504
+ )
505
+
506
+ if len(contexts) != 0:
507
+ # create endpoint context object
508
+ self._context = EndpointContext.load(
509
+ sagemaker_session=self.sagemaker_session,
510
+ context_name=contexts[0].context_name,
511
+ )
512
+
513
+ return self._context
514
+
515
+ def _get_endpoint_config_name(self):
516
+ """Placeholder docstring"""
517
+ if self._endpoint_config_name is not None:
518
+ return self._endpoint_config_name
519
+ endpoint_desc = self.sagemaker_session.sagemaker_client.describe_endpoint(
520
+ EndpointName=self.endpoint_name
521
+ )
522
+ self._endpoint_config_name = endpoint_desc["EndpointConfigName"]
523
+ return self._endpoint_config_name
524
+
525
+ def _get_model_names(self):
526
+ """Placeholder docstring"""
527
+ if self._model_names is not None:
528
+ return self._model_names
529
+ current_endpoint_config_name = self._get_endpoint_config_name()
530
+ endpoint_config = self.sagemaker_session.sagemaker_client.describe_endpoint_config(
531
+ EndpointConfigName=current_endpoint_config_name
532
+ )
533
+ production_variants = endpoint_config["ProductionVariants"]
534
+ self._model_names = [d["ModelName"] for d in production_variants]
535
+ return self._model_names
536
+
537
+ @property
538
+ def content_type(self):
539
+ """The MIME type of the data sent to the inference endpoint."""
540
+ return self.serializer.CONTENT_TYPE
541
+
542
+ @property
543
+ def accept(self):
544
+ """The content type(s) that are expected from the inference endpoint."""
545
+ return self.deserializer.ACCEPT
546
+
547
+ @property
548
+ def endpoint(self):
549
+ """Deprecated attribute. Please use endpoint_name."""
550
+ renamed_warning("The endpoint attribute")
551
+ return self.endpoint_name
552
+
553
+
554
+ csv_serializer = deprecated_serialize(CSVSerializer(), "csv_serializer")
555
+ json_serializer = deprecated_serialize(JSONSerializer(), "json_serializer")
556
+ npy_serializer = deprecated_serialize(NumpySerializer(), "npy_serializer")
557
+ csv_deserializer = deprecated_deserialize(CSVDeserializer(), "csv_deserializer")
558
+ json_deserializer = deprecated_deserialize(JSONDeserializer(), "json_deserializer")
559
+ numpy_deserializer = deprecated_deserialize(NumpyDeserializer(), "numpy_deserializer")
560
+ RealTimePredictor = deprecated_class(Predictor, "RealTimePredictor")
testbed/aws__sagemaker-python-sdk/src/sagemaker/tensorflow/model.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Classes for using TensorFlow on Amazon SageMaker for inference."""
14
+ from __future__ import absolute_import
15
+
16
+ import logging
17
+ from typing import Union, Optional, List, Dict
18
+
19
+ import sagemaker
20
+ from sagemaker import image_uris, s3, ModelMetrics
21
+ from sagemaker.deserializers import JSONDeserializer
22
+ from sagemaker.deprecations import removed_kwargs
23
+ from sagemaker.drift_check_baselines import DriftCheckBaselines
24
+ from sagemaker.metadata_properties import MetadataProperties
25
+ from sagemaker.predictor import Predictor
26
+ from sagemaker.serializers import JSONSerializer
27
+ from sagemaker.workflow import is_pipeline_variable
28
+ from sagemaker.workflow.entities import PipelineVariable
29
+ from sagemaker.workflow.pipeline_context import PipelineSession
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class TensorFlowPredictor(Predictor):
35
+ """A ``Predictor`` implementation for inference against TensorFlow Serving endpoints."""
36
+
37
+ def __init__(
38
+ self,
39
+ endpoint_name,
40
+ sagemaker_session=None,
41
+ serializer=JSONSerializer(),
42
+ deserializer=JSONDeserializer(),
43
+ model_name=None,
44
+ model_version=None,
45
+ **kwargs,
46
+ ):
47
+ """Initialize a ``TensorFlowPredictor``.
48
+
49
+ See :class:`~sagemaker.predictor.Predictor` for more info about parameters.
50
+
51
+ Args:
52
+ endpoint_name (str): The name of the endpoint to perform inference
53
+ on.
54
+ sagemaker_session (sagemaker.session.Session): Session object which
55
+ manages interactions with Amazon SageMaker APIs and any other
56
+ AWS services needed. If not specified, the estimator creates one
57
+ using the default AWS configuration chain.
58
+ serializer (callable): Optional. Default serializes input data to
59
+ json. Handles dicts, lists, and numpy arrays.
60
+ deserializer (callable): Optional. Default parses the response using
61
+ ``json.load(...)``.
62
+ model_name (str): Optional. The name of the SavedModel model that
63
+ should handle the request. If not specified, the endpoint's
64
+ default model will handle the request.
65
+ model_version (str): Optional. The version of the SavedModel model
66
+ that should handle the request. If not specified, the latest
67
+ version of the model will be used.
68
+ """
69
+ removed_kwargs("content_type", kwargs)
70
+ removed_kwargs("accept", kwargs)
71
+ super(TensorFlowPredictor, self).__init__(
72
+ endpoint_name,
73
+ sagemaker_session,
74
+ serializer,
75
+ deserializer,
76
+ )
77
+
78
+ attributes = []
79
+ if model_name:
80
+ attributes.append("tfs-model-name={}".format(model_name))
81
+ if model_version:
82
+ attributes.append("tfs-model-version={}".format(model_version))
83
+ self._model_attributes = ",".join(attributes) if attributes else None
84
+
85
+ def classify(self, data):
86
+ """Placeholder docstring."""
87
+ return self._classify_or_regress(data, "classify")
88
+
89
+ def regress(self, data):
90
+ """Placeholder docstring."""
91
+ return self._classify_or_regress(data, "regress")
92
+
93
+ def _classify_or_regress(self, data, method):
94
+ """Placeholder docstring."""
95
+ if method not in ["classify", "regress"]:
96
+ raise ValueError("invalid TensorFlow Serving method: {}".format(method))
97
+
98
+ if self.content_type != "application/json":
99
+ raise ValueError("The {} api requires json requests.".format(method))
100
+
101
+ args = {"CustomAttributes": "tfs-method={}".format(method)}
102
+
103
+ return self.predict(data, args)
104
+
105
+ def predict(self, data, initial_args=None):
106
+ """Placeholder docstring."""
107
+ args = dict(initial_args) if initial_args else {}
108
+ if self._model_attributes:
109
+ if "CustomAttributes" in args:
110
+ args["CustomAttributes"] += "," + self._model_attributes
111
+ else:
112
+ args["CustomAttributes"] = self._model_attributes
113
+
114
+ return super(TensorFlowPredictor, self).predict(data, args)
115
+
116
+
117
+ class TensorFlowModel(sagemaker.model.FrameworkModel):
118
+ """A ``FrameworkModel`` implementation for inference with TensorFlow Serving."""
119
+
120
+ _framework_name = "tensorflow"
121
+ LOG_LEVEL_PARAM_NAME = "SAGEMAKER_TFS_NGINX_LOGLEVEL"
122
+ LOG_LEVEL_MAP = {
123
+ logging.DEBUG: "debug",
124
+ logging.INFO: "info",
125
+ logging.WARNING: "warn",
126
+ logging.ERROR: "error",
127
+ logging.CRITICAL: "crit",
128
+ }
129
+ LATEST_EIA_VERSION = [2, 3]
130
+
131
+ def __init__(
132
+ self,
133
+ model_data: Union[str, PipelineVariable],
134
+ role: str,
135
+ entry_point: Optional[str] = None,
136
+ image_uri: Optional[Union[str, PipelineVariable]] = None,
137
+ framework_version: Optional[str] = None,
138
+ container_log_level: Optional[int] = None,
139
+ predictor_cls: callable = TensorFlowPredictor,
140
+ **kwargs,
141
+ ):
142
+ """Initialize a Model.
143
+
144
+ Args:
145
+ model_data (str or PipelineVariable): The S3 location of a SageMaker model data
146
+ ``.tar.gz`` file.
147
+ role (str): An AWS IAM role (either name or full ARN). The Amazon
148
+ SageMaker training jobs and APIs that create Amazon SageMaker
149
+ endpoints use this role to access training data and model
150
+ artifacts. After the endpoint is created, the inference code
151
+ might use the IAM role, if it needs to access an AWS resource.
152
+ entry_point (str): Path (absolute or relative) to the Python source
153
+ file which should be executed as the entry point to model
154
+ hosting. If ``source_dir`` is specified, then ``entry_point``
155
+ must point to a file located at the root of ``source_dir``.
156
+ image_uri (str or PipelineVariable): A Docker image URI (default: None).
157
+ If not specified, a default image for TensorFlow Serving will be used.
158
+ If ``framework_version`` is ``None``, then ``image_uri`` is required.
159
+ If ``image_uri`` is also ``None``, then a ``ValueError``
160
+ will be raised.
161
+ framework_version (str): Optional. TensorFlow Serving version you
162
+ want to use. Defaults to ``None``. Required unless ``image_uri`` is
163
+ provided.
164
+ container_log_level (int): Log level to use within the container
165
+ (default: logging.ERROR). Valid values are defined in the Python
166
+ logging module.
167
+ predictor_cls (callable[str, sagemaker.session.Session]): A function
168
+ to call to create a predictor with an endpoint name and
169
+ SageMaker ``Session``. If specified, ``deploy()`` returns the
170
+ result of invoking this function on the created endpoint name.
171
+ **kwargs: Keyword arguments passed to the superclass
172
+ :class:`~sagemaker.model.FrameworkModel` and, subsequently, its
173
+ superclass :class:`~sagemaker.model.Model`.
174
+
175
+ .. tip::
176
+
177
+ You can find additional parameters for initializing this class at
178
+ :class:`~sagemaker.model.FrameworkModel` and
179
+ :class:`~sagemaker.model.Model`.
180
+ """
181
+ if framework_version is None and image_uri is None:
182
+ raise ValueError(
183
+ "Both framework_version and image_uri were None. "
184
+ "Either specify framework_version or specify image_uri."
185
+ )
186
+ self.framework_version = framework_version
187
+
188
+ super(TensorFlowModel, self).__init__(
189
+ model_data=model_data,
190
+ role=role,
191
+ image_uri=image_uri,
192
+ predictor_cls=predictor_cls,
193
+ entry_point=entry_point,
194
+ **kwargs,
195
+ )
196
+ self._container_log_level = container_log_level
197
+
198
+ def register(
199
+ self,
200
+ content_types: List[Union[str, PipelineVariable]],
201
+ response_types: List[Union[str, PipelineVariable]],
202
+ inference_instances: Optional[List[Union[str, PipelineVariable]]] = None,
203
+ transform_instances: Optional[List[Union[str, PipelineVariable]]] = None,
204
+ model_package_name: Optional[Union[str, PipelineVariable]] = None,
205
+ model_package_group_name: Optional[Union[str, PipelineVariable]] = None,
206
+ image_uri: Optional[Union[str, PipelineVariable]] = None,
207
+ model_metrics: Optional[ModelMetrics] = None,
208
+ metadata_properties: Optional[MetadataProperties] = None,
209
+ marketplace_cert: bool = False,
210
+ approval_status: Optional[Union[str, PipelineVariable]] = None,
211
+ description: Optional[str] = None,
212
+ drift_check_baselines: Optional[DriftCheckBaselines] = None,
213
+ customer_metadata_properties: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
214
+ domain: Optional[Union[str, PipelineVariable]] = None,
215
+ sample_payload_url: Optional[Union[str, PipelineVariable]] = None,
216
+ task: Optional[Union[str, PipelineVariable]] = None,
217
+ framework: Optional[Union[str, PipelineVariable]] = None,
218
+ framework_version: Optional[Union[str, PipelineVariable]] = None,
219
+ nearest_model_name: Optional[Union[str, PipelineVariable]] = None,
220
+ data_input_configuration: Optional[Union[str, PipelineVariable]] = None,
221
+ ):
222
+ """Creates a model package for creating SageMaker models or listing on Marketplace.
223
+
224
+ Args:
225
+ content_types (list[str] or list[PipelineVariable]): The supported MIME types
226
+ for the input data.
227
+ response_types (list[str] or list[PipelineVariable]): The supported MIME types
228
+ for the output data.
229
+ inference_instances (list[str] or list[PipelineVariable]): A list of the instance
230
+ types that are used to generate inferences in real-time (default: None).
231
+ transform_instances (list[str] or list[PipelineVariable]): A list of the instance
232
+ types on which a transformation job can be run or on which an endpoint can
233
+ be deployed (default: None).
234
+ model_package_name (str or PipelineVariable): Model Package name, exclusive to
235
+ `model_package_group_name`, using `model_package_name` makes the Model Package
236
+ un-versioned (default: None).
237
+ model_package_group_name (str or PipelineVariable): Model Package Group name,
238
+ exclusive to `model_package_name`, using `model_package_group_name` makes the
239
+ Model Package versioned (default: None).
240
+ image_uri (str or PipelineVariable): Inference image uri for the container. Model class'
241
+ self.image will be used if it is None (default: None).
242
+ model_metrics (ModelMetrics): ModelMetrics object (default: None).
243
+ metadata_properties (MetadataProperties): MetadataProperties object (default: None).
244
+ marketplace_cert (bool): A boolean value indicating if the Model Package is certified
245
+ for AWS Marketplace (default: False).
246
+ approval_status (str or PipelineVariable): Model Approval Status, values can be
247
+ "Approved", "Rejected", or "PendingManualApproval"
248
+ (default: "PendingManualApproval").
249
+ description (str): Model Package description (default: None).
250
+ drift_check_baselines (DriftCheckBaselines): DriftCheckBaselines object (default: None).
251
+ customer_metadata_properties (dict[str, str] or dict[str, PipelineVariable]):
252
+ A dictionary of key-value paired metadata properties (default: None).
253
+ domain (str or PipelineVariable): Domain values can be "COMPUTER_VISION",
254
+ "NATURAL_LANGUAGE_PROCESSING", "MACHINE_LEARNING" (default: None).
255
+ sample_payload_url (str or PipelineVariable): The S3 path where the sample payload
256
+ is stored (default: None).
257
+ task (str or PipelineVariable): Task values which are supported by Inference Recommender
258
+ are "FILL_MASK", "IMAGE_CLASSIFICATION", "OBJECT_DETECTION", "TEXT_GENERATION",
259
+ "IMAGE_SEGMENTATION", "CLASSIFICATION", "REGRESSION", "OTHER" (default: None).
260
+ framework (str or PipelineVariable): Machine learning framework of the model package
261
+ container image (default: None).
262
+ framework_version (str or PipelineVariable): Framework version of the Model Package
263
+ Container Image (default: None).
264
+ nearest_model_name (str or PipelineVariable): Name of a pre-trained machine learning
265
+ benchmarked by Amazon SageMaker Inference Recommender (default: None).
266
+ data_input_configuration (str or PipelineVariable): Input object for the model
267
+ (default: None).
268
+
269
+ Returns:
270
+ A `sagemaker.model.ModelPackage` instance.
271
+ """
272
+ instance_type = inference_instances[0] if inference_instances else None
273
+ self._init_sagemaker_session_if_does_not_exist(instance_type)
274
+
275
+ if image_uri:
276
+ self.image_uri = image_uri
277
+ if not self.image_uri:
278
+ self.image_uri = self.serving_image_uri(
279
+ region_name=self.sagemaker_session.boto_session.region_name,
280
+ instance_type=instance_type,
281
+ )
282
+ if not is_pipeline_variable(framework):
283
+ framework = (framework or self._framework_name).upper()
284
+ return super(TensorFlowModel, self).register(
285
+ content_types,
286
+ response_types,
287
+ inference_instances,
288
+ transform_instances,
289
+ model_package_name,
290
+ model_package_group_name,
291
+ image_uri,
292
+ model_metrics,
293
+ metadata_properties,
294
+ marketplace_cert,
295
+ approval_status,
296
+ description,
297
+ drift_check_baselines=drift_check_baselines,
298
+ customer_metadata_properties=customer_metadata_properties,
299
+ domain=domain,
300
+ sample_payload_url=sample_payload_url,
301
+ task=task,
302
+ framework=framework,
303
+ framework_version=framework_version or self.framework_version,
304
+ nearest_model_name=nearest_model_name,
305
+ data_input_configuration=data_input_configuration,
306
+ )
307
+
308
+ def deploy(
309
+ self,
310
+ initial_instance_count=None,
311
+ instance_type=None,
312
+ serializer=None,
313
+ deserializer=None,
314
+ accelerator_type=None,
315
+ endpoint_name=None,
316
+ tags=None,
317
+ kms_key=None,
318
+ wait=True,
319
+ data_capture_config=None,
320
+ update_endpoint=None,
321
+ async_inference_config=None,
322
+ serverless_inference_config=None,
323
+ ):
324
+ """Deploy a Tensorflow ``Model`` to a SageMaker ``Endpoint``."""
325
+
326
+ if accelerator_type and not self._eia_supported():
327
+ msg = "The TensorFlow version %s doesn't support EIA." % self.framework_version
328
+ raise AttributeError(msg)
329
+
330
+ return super(TensorFlowModel, self).deploy(
331
+ initial_instance_count=initial_instance_count,
332
+ instance_type=instance_type,
333
+ serializer=serializer,
334
+ deserializer=deserializer,
335
+ accelerator_type=accelerator_type,
336
+ endpoint_name=endpoint_name,
337
+ tags=tags,
338
+ kms_key=kms_key,
339
+ wait=wait,
340
+ data_capture_config=data_capture_config,
341
+ async_inference_config=async_inference_config,
342
+ serverless_inference_config=serverless_inference_config,
343
+ update_endpoint=update_endpoint,
344
+ )
345
+
346
+ def _eia_supported(self):
347
+ """Return true if TF version is EIA enabled"""
348
+ framework_version = [int(s) for s in self.framework_version.split(".")][:2]
349
+ return (
350
+ framework_version != [2, 1]
351
+ and framework_version != [2, 2]
352
+ and framework_version <= self.LATEST_EIA_VERSION
353
+ )
354
+
355
+ def prepare_container_def(
356
+ self, instance_type=None, accelerator_type=None, serverless_inference_config=None
357
+ ):
358
+ """Prepare the container definition.
359
+
360
+ Args:
361
+ instance_type: Instance type of the container.
362
+ accelerator_type: Accelerator type, if applicable.
363
+ serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig):
364
+ Specifies configuration related to serverless endpoint. Instance type is
365
+ not provided in serverless inference. So this is used to find image URIs.
366
+
367
+ Returns:
368
+ A container definition for deploying a ``Model`` to an ``Endpoint``.
369
+ """
370
+ if not self.image_uri:
371
+ if instance_type is None and serverless_inference_config is None:
372
+ raise ValueError(
373
+ "Must supply either an instance type (for choosing CPU vs GPU) or an image URI."
374
+ )
375
+
376
+ image_uri = self._get_image_uri(
377
+ instance_type, accelerator_type, serverless_inference_config=serverless_inference_config
378
+ )
379
+ env = self._get_container_env()
380
+ key_prefix = sagemaker.fw_utils.model_code_key_prefix(self.key_prefix, self.name, image_uri)
381
+ bucket = self.bucket or self.sagemaker_session.default_bucket()
382
+
383
+ if self.entry_point and not is_pipeline_variable(self.model_data):
384
+ model_data = s3.s3_path_join("s3://", bucket, key_prefix, "model.tar.gz")
385
+
386
+ sagemaker.utils.repack_model(
387
+ self.entry_point,
388
+ self.source_dir,
389
+ self.dependencies,
390
+ self.model_data,
391
+ model_data,
392
+ self.sagemaker_session,
393
+ kms_key=self.model_kms_key,
394
+ )
395
+ elif self.entry_point and is_pipeline_variable(self.model_data):
396
+ # model is not yet there, defer repacking to later during pipeline execution
397
+ if isinstance(self.sagemaker_session, PipelineSession):
398
+ self.sagemaker_session.context.need_runtime_repack.add(id(self))
399
+ self.sagemaker_session.context.runtime_repack_output_prefix = "s3://{}/{}".format(
400
+ bucket, key_prefix
401
+ )
402
+ else:
403
+ logging.warning(
404
+ "The model_data is a Pipeline variable of type %s, "
405
+ "which should be used under `PipelineSession` and "
406
+ "leverage `ModelStep` to create or register model. "
407
+ "Otherwise some functionalities e.g. "
408
+ "runtime repack may be missing. For more, see: "
409
+ "https://sagemaker.readthedocs.io/en/stable/"
410
+ "amazon_sagemaker_model_building_pipeline.html#model-step",
411
+ type(self.model_data),
412
+ )
413
+ model_data = self.model_data
414
+ else:
415
+ model_data = self.model_data
416
+
417
+ return sagemaker.container_def(image_uri, model_data, env)
418
+
419
+ def _get_container_env(self):
420
+ """Placeholder docstring."""
421
+ if not self._container_log_level:
422
+ return self.env
423
+
424
+ if self._container_log_level not in self.LOG_LEVEL_MAP:
425
+ logging.warning("ignoring invalid container log level: %s", self._container_log_level)
426
+ return self.env
427
+
428
+ env = dict(self.env)
429
+ env[self.LOG_LEVEL_PARAM_NAME] = self.LOG_LEVEL_MAP[self._container_log_level]
430
+ return env
431
+
432
+ def _get_image_uri(
433
+ self,
434
+ instance_type,
435
+ accelerator_type=None,
436
+ region_name=None,
437
+ serverless_inference_config=None,
438
+ ):
439
+ """Placeholder docstring."""
440
+ if self.image_uri:
441
+ return self.image_uri
442
+
443
+ logger.info(
444
+ "image_uri is not presented, retrieving image_uri based on instance_type, "
445
+ "framework etc."
446
+ )
447
+ return image_uris.retrieve(
448
+ self._framework_name,
449
+ region_name or self.sagemaker_session.boto_region_name,
450
+ version=self.framework_version,
451
+ instance_type=instance_type,
452
+ accelerator_type=accelerator_type,
453
+ image_scope="inference",
454
+ serverless_inference_config=serverless_inference_config,
455
+ )
456
+
457
+ def serving_image_uri(
458
+ self, region_name, instance_type, accelerator_type=None, serverless_inference_config=None
459
+ ): # pylint: disable=unused-argument
460
+ """Create a URI for the serving image.
461
+
462
+ Args:
463
+ region_name (str): AWS region where the image is uploaded.
464
+ instance_type (str): SageMaker instance type. Used to determine device type
465
+ (cpu/gpu/family-specific optimized).
466
+ accelerator_type (str): The Elastic Inference accelerator type to
467
+ deploy to the instance for loading and making inferences to the
468
+ model (default: None). For example, 'ml.eia1.medium'.
469
+ serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig):
470
+ Specifies configuration related to serverless endpoint. Instance type is
471
+ not provided in serverless inference. So this is used to determine device type.
472
+
473
+ Returns:
474
+ str: The appropriate image URI based on the given parameters.
475
+
476
+ """
477
+ return self._get_image_uri(
478
+ instance_type=instance_type,
479
+ accelerator_type=accelerator_type,
480
+ region_name=region_name,
481
+ serverless_inference_config=serverless_inference_config,
482
+ )
testbed/aws__sagemaker-python-sdk/src/sagemaker/tensorflow/training_compiler/config.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Configuration for the SageMaker Training Compiler."""
14
+ from __future__ import absolute_import
15
+ import logging
16
+ from packaging.specifiers import SpecifierSet
17
+ from packaging.version import Version
18
+
19
+ from sagemaker.training_compiler.config import TrainingCompilerConfig as BaseConfig
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class TrainingCompilerConfig(BaseConfig):
25
+ """The SageMaker Training Compiler configuration class."""
26
+
27
+ SUPPORTED_INSTANCE_CLASS_PREFIXES = ["p3", "g4dn", "p4", "g5"]
28
+ MIN_SUPPORTED_VERSION = "2.9"
29
+
30
+ def __init__(
31
+ self,
32
+ enabled=True,
33
+ debug=False,
34
+ ):
35
+ """This class initializes a ``TrainingCompilerConfig`` instance.
36
+
37
+ `Amazon SageMaker Training Compiler
38
+ <https://docs.aws.amazon.com/sagemaker/latest/dg/training-compiler.html>`_
39
+ is a feature of SageMaker Training
40
+ and speeds up training jobs by optimizing model execution graphs.
41
+
42
+ You can compile TensorFlow models
43
+ by passing the object of this configuration class to the ``compiler_config``
44
+ parameter of the :class:`~sagemaker.tensorflow.TensorFlow`
45
+ estimator.
46
+
47
+ Args:
48
+ enabled (bool): Optional. Switch to enable SageMaker Training Compiler.
49
+ The default is ``True``.
50
+ debug (bool): Optional. Whether to dump detailed logs for debugging.
51
+ This comes with a potential performance slowdown.
52
+ The default is ``False``.
53
+
54
+ **Example**: The following code shows the basic usage of the
55
+ :class:`sagemaker.tensorflow.TrainingCompilerConfig()` class
56
+ to run a TensorFlow training job with the compiler.
57
+
58
+ .. code-block:: python
59
+
60
+ from sagemaker.tensorflow import TensorFlow, TrainingCompilerConfig
61
+
62
+ tensorflow_estimator=TensorFlow(
63
+ ...
64
+ compiler_config=TrainingCompilerConfig()
65
+ )
66
+
67
+ .. seealso::
68
+
69
+ For more information about how to enable SageMaker Training Compiler
70
+ for various training settings such as using TensorFlow-based models,
71
+ PyTorch-based models, and distributed training,
72
+ see `Enable SageMaker Training Compiler
73
+ <https://docs.aws.amazon.com/sagemaker/latest/dg/training-compiler-enable.html>`_
74
+ in the `Amazon SageMaker Training Compiler developer guide
75
+ <https://docs.aws.amazon.com/sagemaker/latest/dg/training-compiler.html>`_.
76
+
77
+ """
78
+
79
+ super(TrainingCompilerConfig, self).__init__(enabled=enabled, debug=debug)
80
+
81
+ @classmethod
82
+ def validate(
83
+ cls,
84
+ estimator,
85
+ ):
86
+ """Checks if SageMaker Training Compiler is configured correctly.
87
+
88
+ Args:
89
+ estimator (str): A estimator object
90
+ If SageMaker Training Compiler is enabled, it will validate whether
91
+ the estimator is configured to be compatible with Training Compiler.
92
+
93
+ Raises:
94
+ ValueError: Raised if the requested configuration is not compatible
95
+ with SageMaker Training Compiler.
96
+ """
97
+
98
+ super(TrainingCompilerConfig, cls).validate(estimator)
99
+
100
+ if estimator.framework_version:
101
+ if Version(estimator.framework_version) in SpecifierSet(
102
+ f"< {cls.MIN_SUPPORTED_VERSION}"
103
+ ):
104
+ error_helper_string = (
105
+ "SageMaker Training Compiler only supports TensorFlow version "
106
+ ">= {} but received {}"
107
+ )
108
+ error_helper_string = error_helper_string.format(
109
+ cls.MIN_SUPPORTED_VERSION, estimator.framework_version
110
+ )
111
+ raise ValueError(error_helper_string)
testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Defines Types etc. used in workflow."""
14
+ from __future__ import absolute_import
15
+
16
+ from sagemaker.workflow.entities import Expression
17
+ from sagemaker.workflow.parameters import ParameterString
18
+
19
+
20
+ def is_pipeline_variable(var: object) -> bool:
21
+ """Check if the variable is a pipeline variable
22
+
23
+ Args:
24
+ var (object): The variable to be verified.
25
+ Returns:
26
+ bool: True if it is, False otherwise.
27
+ """
28
+
29
+ # Currently Expression is on top of all kinds of pipeline variables
30
+ # as well as PipelineExperimentConfigProperty and PropertyFile
31
+ # TODO: We should deprecate the Expression and replace it with PipelineVariable
32
+ return isinstance(var, Expression)
33
+
34
+
35
+ def is_pipeline_parameter_string(var: object) -> bool:
36
+ """Check if the variable is a pipeline parameter string
37
+
38
+ Args:
39
+ var (object): The variable to be verified.
40
+ Returns:
41
+ bool: True if it is, False otherwise.
42
+ """
43
+ return isinstance(var, ParameterString)
testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/callback_step.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """The step definitions for workflow."""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import List, Dict, Union, Optional
17
+ from enum import Enum
18
+
19
+ import attr
20
+
21
+ from sagemaker.workflow.entities import (
22
+ RequestType,
23
+ )
24
+ from sagemaker.workflow.properties import (
25
+ Properties,
26
+ )
27
+ from sagemaker.workflow.entities import (
28
+ DefaultEnumMeta,
29
+ )
30
+ from sagemaker.workflow.step_collections import StepCollection
31
+ from sagemaker.workflow.steps import Step, StepTypeEnum, CacheConfig
32
+
33
+
34
+ class CallbackOutputTypeEnum(Enum, metaclass=DefaultEnumMeta):
35
+ """CallbackOutput type enum."""
36
+
37
+ String = "String"
38
+ Integer = "Integer"
39
+ Boolean = "Boolean"
40
+ Float = "Float"
41
+
42
+
43
+ @attr.s
44
+ class CallbackOutput:
45
+ """Output for a callback step.
46
+
47
+ Attributes:
48
+ output_name (str): The output name
49
+ output_type (CallbackOutputTypeEnum): The output type
50
+ """
51
+
52
+ output_name: str = attr.ib(default=None)
53
+ output_type: CallbackOutputTypeEnum = attr.ib(default=CallbackOutputTypeEnum.String)
54
+
55
+ def to_request(self) -> RequestType:
56
+ """Get the request structure for workflow service calls."""
57
+ return {
58
+ "OutputName": self.output_name,
59
+ "OutputType": self.output_type.value,
60
+ }
61
+
62
+ def expr(self, step_name) -> Dict[str, str]:
63
+ """The 'Get' expression dict for a `CallbackOutput`."""
64
+ return CallbackOutput._expr(self.output_name, step_name)
65
+
66
+ @classmethod
67
+ def _expr(cls, name, step_name):
68
+ """An internal classmethod for the 'Get' expression dict for a `CallbackOutput`.
69
+
70
+ Args:
71
+ name (str): The name of the callback output.
72
+ step_name (str): The name of the step the callback step associated
73
+ with this output belongs to.
74
+ """
75
+ return {"Get": f"Steps.{step_name}.OutputParameters['{name}']"}
76
+
77
+
78
+ class CallbackStep(Step):
79
+ """Callback step for workflow."""
80
+
81
+ def __init__(
82
+ self,
83
+ name: str,
84
+ sqs_queue_url: str,
85
+ inputs: dict,
86
+ outputs: List[CallbackOutput],
87
+ display_name: str = None,
88
+ description: str = None,
89
+ cache_config: CacheConfig = None,
90
+ depends_on: Optional[List[Union[str, Step, StepCollection]]] = None,
91
+ ):
92
+ """Constructs a CallbackStep.
93
+
94
+ Args:
95
+ name (str): The name of the callback step.
96
+ sqs_queue_url (str): An SQS queue URL for receiving callback messages.
97
+ inputs (dict): Input arguments that will be provided
98
+ in the SQS message body of callback messages.
99
+ outputs (List[CallbackOutput]): Outputs that can be provided when completing a callback.
100
+ display_name (str): The display name of the callback step.
101
+ description (str): The description of the callback step.
102
+ cache_config (CacheConfig): A `sagemaker.workflow.steps.CacheConfig` instance.
103
+ depends_on (List[Union[str, Step, StepCollection]]): A list of `Step`/`StepCollection`
104
+ names or `Step` instances or `StepCollection` instances that this `CallbackStep`
105
+ depends on.
106
+ """
107
+ super(CallbackStep, self).__init__(
108
+ name, display_name, description, StepTypeEnum.CALLBACK, depends_on
109
+ )
110
+ self.sqs_queue_url = sqs_queue_url
111
+ self.outputs = outputs
112
+ self.cache_config = cache_config
113
+ self.inputs = inputs
114
+
115
+ root_prop = Properties(step_name=name)
116
+
117
+ property_dict = {}
118
+ for output in outputs:
119
+ property_dict[output.output_name] = Properties(
120
+ step_name=name, path=f"OutputParameters['{output.output_name}']"
121
+ )
122
+
123
+ root_prop.__dict__["Outputs"] = property_dict
124
+ self._properties = root_prop
125
+
126
+ @property
127
+ def arguments(self) -> RequestType:
128
+ """The arguments dict that is used to define the callback step."""
129
+ return self.inputs
130
+
131
+ @property
132
+ def properties(self):
133
+ """A Properties object representing the output parameters of the callback step."""
134
+ return self._properties
135
+
136
+ def to_request(self) -> RequestType:
137
+ """Updates the dictionary with cache configuration."""
138
+ request_dict = super().to_request()
139
+ if self.cache_config:
140
+ request_dict.update(self.cache_config.config)
141
+
142
+ request_dict["SqsQueueUrl"] = self.sqs_queue_url
143
+ request_dict["OutputParameters"] = list(map(lambda op: op.to_request(), self.outputs))
144
+
145
+ return request_dict
testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/entities.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Defines the base entities used in workflow."""
14
+ from __future__ import absolute_import
15
+
16
+ import abc
17
+
18
+ from enum import EnumMeta
19
+ from typing import Any, Dict, List, Union
20
+
21
+ PrimitiveType = Union[str, int, bool, float, None]
22
+ RequestType = Union[Dict[str, Any], List[Dict[str, Any]]]
23
+
24
+
25
+ class Entity(abc.ABC):
26
+ """Base object for workflow entities.
27
+
28
+ Entities must implement the to_request method.
29
+ """
30
+
31
+ @abc.abstractmethod
32
+ def to_request(self) -> RequestType:
33
+ """Get the request structure for workflow service calls."""
34
+
35
+
36
+ class DefaultEnumMeta(EnumMeta):
37
+ """An EnumMeta which defaults to the first value in the Enum list."""
38
+
39
+ default = object()
40
+
41
+ def __call__(cls, *args, value=default, **kwargs):
42
+ """Defaults to the first value in the Enum list."""
43
+ if value is DefaultEnumMeta.default:
44
+ return next(iter(cls))
45
+ return super().__call__(value, *args, **kwargs)
46
+
47
+ factory = __call__
48
+
49
+
50
+ class Expression(abc.ABC):
51
+ """Base object for expressions.
52
+
53
+ Expressions must implement the expr property.
54
+ """
55
+
56
+ @property
57
+ @abc.abstractmethod
58
+ def expr(self) -> RequestType:
59
+ """Get the expression structure for workflow service calls."""
60
+
61
+
62
+ class PipelineVariable(Expression):
63
+ """Base object for pipeline variables
64
+
65
+ PipelineVariable subclasses must implement the expr property. Its subclasses include:
66
+ :class:`~sagemaker.workflow.parameters.Parameter`,
67
+ :class:`~sagemaker.workflow.properties.Properties`,
68
+ :class:`~sagemaker.workflow.functions.Join`,
69
+ :class:`~sagemaker.workflow.functions.JsonGet`,
70
+ :class:`~sagemaker.workflow.execution_variables.ExecutionVariable`.
71
+ """
72
+
73
+ def __add__(self, other: Union[Expression, PrimitiveType]):
74
+ """Add function for PipelineVariable
75
+
76
+ Args:
77
+ other (Union[Expression, PrimitiveType]): The other object to be concatenated.
78
+
79
+ Always raise an error since pipeline variables do not support concatenation
80
+ """
81
+
82
+ raise TypeError("Pipeline variables do not support concatenation.")
83
+
84
+ def __str__(self):
85
+ """Override built-in String function for PipelineVariable"""
86
+ raise TypeError(
87
+ "Pipeline variables do not support __str__ operation. "
88
+ "Please use `.to_string()` to convert it to string type in execution time"
89
+ "or use `.expr` to translate it to Json for display purpose in Python SDK."
90
+ )
91
+
92
+ def __int__(self):
93
+ """Override built-in Integer function for PipelineVariable"""
94
+ raise TypeError("Pipeline variables do not support __int__ operation.")
95
+
96
+ def __float__(self):
97
+ """Override built-in Float function for PipelineVariable"""
98
+ raise TypeError("Pipeline variables do not support __float__ operation.")
99
+
100
+ def to_string(self):
101
+ """Prompt the pipeline to convert the pipeline variable to String in runtime"""
102
+ from sagemaker.workflow.functions import Join
103
+
104
+ return Join(on="", values=[self])
105
+
106
+ @property
107
+ @abc.abstractmethod
108
+ def expr(self) -> RequestType:
109
+ """Get the expression structure for workflow service calls."""
110
+
111
+ @property
112
+ @abc.abstractmethod
113
+ def _referenced_steps(self) -> List[str]:
114
+ """List of step names that this function depends on."""
testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/fail_step.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """The `Step` definitions for SageMaker Pipelines Workflows."""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import List, Union, Optional
17
+
18
+ from sagemaker.workflow.entities import (
19
+ RequestType,
20
+ PipelineVariable,
21
+ )
22
+ from sagemaker.workflow.step_collections import StepCollection
23
+ from sagemaker.workflow.steps import Step, StepTypeEnum
24
+
25
+
26
+ class FailStep(Step):
27
+ """`FailStep` for SageMaker Pipelines Workflows."""
28
+
29
+ def __init__(
30
+ self,
31
+ name: str,
32
+ error_message: Union[str, PipelineVariable] = None,
33
+ display_name: str = None,
34
+ description: str = None,
35
+ depends_on: Optional[List[Union[str, Step, StepCollection]]] = None,
36
+ ):
37
+ """Constructs a `FailStep`.
38
+
39
+ Args:
40
+ name (str): The name of the `FailStep`. A name is required and must be
41
+ unique within a pipeline.
42
+ error_message (str or PipelineVariable):
43
+ An error message defined by the user.
44
+ Once the `FailStep` is reached, the execution fails and the
45
+ error message is set as the failure reason (default: None).
46
+ display_name (str): The display name of the `FailStep`.
47
+ The display name provides better UI readability. (default: None).
48
+ description (str): The description of the `FailStep` (default: None).
49
+ depends_on (List[Union[str, Step, StepCollection]]): A list of `Step`/`StepCollection`
50
+ names or `Step` instances or `StepCollection` instances that this `FailStep`
51
+ depends on.
52
+ If a listed `Step` name does not exist, an error is returned (default: None).
53
+ """
54
+ super(FailStep, self).__init__(
55
+ name, display_name, description, StepTypeEnum.FAIL, depends_on
56
+ )
57
+ self.error_message = error_message if error_message is not None else ""
58
+
59
+ @property
60
+ def arguments(self) -> RequestType:
61
+ """The arguments dictionary that is used to define the `FailStep`."""
62
+ return dict(ErrorMessage=self.error_message)
63
+
64
+ @property
65
+ def properties(self):
66
+ """A `Properties` object is not available for the `FailStep`.
67
+
68
+ Executing a `FailStep` will terminate the pipeline.
69
+ `FailStep` properties should not be referenced.
70
+ """
71
+ raise RuntimeError(
72
+ "FailStep is a terminal step and the Properties object is not available for it."
73
+ )
testbed/aws__sagemaker-python-sdk/src/sagemaker/workflow/functions.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """The step definitions for workflow."""
14
+ from __future__ import absolute_import
15
+
16
+ from typing import List, Union
17
+
18
+ import attr
19
+
20
+ from sagemaker.workflow.entities import PipelineVariable
21
+ from sagemaker.workflow.properties import PropertyFile
22
+
23
+
24
+ @attr.s
25
+ class Join(PipelineVariable):
26
+ """Join together properties.
27
+
28
+ Examples:
29
+ Build a Amazon S3 Uri with bucket name parameter and pipeline execution Id and use it
30
+ as training input::
31
+
32
+ bucket = ParameterString('bucket', default_value='my-bucket')
33
+
34
+ TrainingInput(
35
+ s3_data=Join(on='/', ['s3:/', bucket, ExecutionVariables.PIPELINE_EXECUTION_ID]),
36
+ content_type="text/csv")
37
+
38
+ Attributes:
39
+ values (List[Union[PrimitiveType, Parameter, Expression]]):
40
+ The primitive type values, parameters, step properties, expressions to join.
41
+ on (str): The string to join the values on (Defaults to "").
42
+ """
43
+
44
+ on: str = attr.ib(factory=str)
45
+ values: List = attr.ib(factory=list)
46
+
47
+ def to_string(self) -> PipelineVariable:
48
+ """Prompt the pipeline to convert the pipeline variable to String in runtime
49
+
50
+ As Join is treated as String in runtime, no extra actions are needed.
51
+ """
52
+ return self
53
+
54
+ @property
55
+ def expr(self):
56
+ """The expression dict for a `Join` function."""
57
+
58
+ return {
59
+ "Std:Join": {
60
+ "On": self.on,
61
+ "Values": [
62
+ value.expr if hasattr(value, "expr") else value for value in self.values
63
+ ],
64
+ },
65
+ }
66
+
67
+ @property
68
+ def _referenced_steps(self) -> List[str]:
69
+ """List of step names that this function depends on."""
70
+ steps = []
71
+ for value in self.values:
72
+ if isinstance(value, PipelineVariable):
73
+ steps.extend(value._referenced_steps)
74
+ return steps
75
+
76
+
77
+ @attr.s
78
+ class JsonGet(PipelineVariable):
79
+ """Get JSON properties from PropertyFiles.
80
+
81
+ Attributes:
82
+ step_name (str): The step name from which to get the property file.
83
+ property_file (Union[PropertyFile, str]): Either a PropertyFile instance
84
+ or the name of a property file.
85
+ json_path (str): The JSON path expression to the requested value.
86
+ """
87
+
88
+ step_name: str = attr.ib()
89
+ property_file: Union[PropertyFile, str] = attr.ib()
90
+ json_path: str = attr.ib()
91
+
92
+ @property
93
+ def expr(self):
94
+ """The expression dict for a `JsonGet` function."""
95
+ if not isinstance(self.step_name, str) or not self.step_name:
96
+ raise ValueError("Please give a valid step name as a string")
97
+
98
+ if isinstance(self.property_file, PropertyFile):
99
+ name = self.property_file.name
100
+ else:
101
+ name = self.property_file
102
+ return {
103
+ "Std:JsonGet": {
104
+ "PropertyFile": {"Get": f"Steps.{self.step_name}.PropertyFiles.{name}"},
105
+ "Path": self.json_path,
106
+ }
107
+ }
108
+
109
+ @property
110
+ def _referenced_steps(self) -> List[str]:
111
+ """List of step names that this function depends on."""
112
+ return [self.step_name]