sagemaker-core 1.0.62__py3-none-any.whl → 2.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. sagemaker/__init__.py +2 -0
  2. sagemaker/core/__init__.py +16 -0
  3. sagemaker/core/_studio.py +116 -0
  4. sagemaker/core/_version.py +11 -0
  5. sagemaker/core/accept_types.py +131 -0
  6. sagemaker/core/analytics.py +744 -0
  7. sagemaker/core/apiutils/__init__.py +13 -0
  8. sagemaker/core/apiutils/_base_types.py +228 -0
  9. sagemaker/core/apiutils/_boto_functions.py +130 -0
  10. sagemaker/core/apiutils/_utils.py +34 -0
  11. sagemaker/core/base_deserializers.py +35 -0
  12. sagemaker/core/base_serializers.py +35 -0
  13. sagemaker/core/clarify/__init__.py +2898 -0
  14. sagemaker/core/collection.py +467 -0
  15. sagemaker/core/common_utils.py +2399 -0
  16. sagemaker/core/compute_resource_requirements/__init__.py +18 -0
  17. sagemaker/core/compute_resource_requirements/resource_requirements.py +94 -0
  18. sagemaker/core/config/__init__.py +181 -0
  19. sagemaker/core/config/config.py +238 -0
  20. sagemaker/core/config/config_manager.py +595 -0
  21. sagemaker/core/config/config_schema.py +1220 -0
  22. sagemaker/core/config/config_utils.py +297 -0
  23. {sagemaker_core/main → sagemaker/core}/config_schema.py +408 -3
  24. sagemaker/core/constants.py +73 -0
  25. sagemaker/core/content_types.py +137 -0
  26. sagemaker/core/debugger/__init__.py +39 -0
  27. sagemaker/core/debugger/debugger.py +945 -0
  28. sagemaker/core/debugger/framework_profile.py +292 -0
  29. sagemaker/core/debugger/metrics_config.py +468 -0
  30. sagemaker/core/debugger/profiler.py +42 -0
  31. sagemaker/core/debugger/profiler_config.py +190 -0
  32. sagemaker/core/debugger/profiler_constants.py +40 -0
  33. sagemaker/core/debugger/utils.py +148 -0
  34. sagemaker/core/deprecations.py +254 -0
  35. sagemaker/core/deserializers/__init__.py +10 -0
  36. sagemaker/core/deserializers/base.py +424 -0
  37. sagemaker/core/deserializers/implementations.py +157 -0
  38. sagemaker/core/drift_check_baselines.py +106 -0
  39. sagemaker/core/enums.py +51 -0
  40. sagemaker/core/environment_variables.py +101 -0
  41. sagemaker/core/exceptions.py +108 -0
  42. sagemaker/core/experiments/__init__.py +53 -0
  43. sagemaker/core/experiments/_api_types.py +251 -0
  44. sagemaker/core/experiments/_environment.py +124 -0
  45. sagemaker/core/experiments/_helper.py +294 -0
  46. sagemaker/core/experiments/_metrics.py +333 -0
  47. sagemaker/core/experiments/_run_context.py +58 -0
  48. sagemaker/core/experiments/_utils.py +216 -0
  49. sagemaker/core/experiments/experiment.py +247 -0
  50. sagemaker/core/experiments/run.py +970 -0
  51. sagemaker/core/experiments/trial.py +296 -0
  52. sagemaker/core/experiments/trial_component.py +387 -0
  53. sagemaker/core/explainer/__init__.py +24 -0
  54. sagemaker/core/explainer/clarify_explainer_config.py +298 -0
  55. sagemaker/core/explainer/explainer_config.py +44 -0
  56. sagemaker/core/fw_utils.py +1220 -0
  57. sagemaker/core/git_utils.py +415 -0
  58. sagemaker/core/helper/pipeline_variable.py +82 -0
  59. sagemaker/core/helper/session_helper.py +2977 -0
  60. sagemaker/core/hyperparameters.py +172 -0
  61. sagemaker/core/image_retriever/__init__.py +3 -0
  62. sagemaker/core/image_retriever/image_retriever.py +640 -0
  63. sagemaker/core/image_retriever/image_retriever_utils.py +509 -0
  64. sagemaker/core/image_retriever/test.py +7 -0
  65. sagemaker/core/image_uri_config/autogluon.json +1335 -0
  66. sagemaker/core/image_uri_config/blazingtext.json +50 -0
  67. sagemaker/core/image_uri_config/chainer.json +104 -0
  68. sagemaker/core/image_uri_config/clarify.json +39 -0
  69. sagemaker/core/image_uri_config/coach-mxnet.json +70 -0
  70. sagemaker/core/image_uri_config/coach-tensorflow.json +186 -0
  71. sagemaker/core/image_uri_config/data-wrangler.json +91 -0
  72. sagemaker/core/image_uri_config/debugger.json +34 -0
  73. sagemaker/core/image_uri_config/detailed-profiler.json +18 -0
  74. sagemaker/core/image_uri_config/djl-deepspeed.json +385 -0
  75. sagemaker/core/image_uri_config/djl-fastertransformer.json +167 -0
  76. sagemaker/core/image_uri_config/djl-lmi.json +136 -0
  77. sagemaker/core/image_uri_config/djl-neuronx.json +258 -0
  78. sagemaker/core/image_uri_config/djl-tensorrtllm.json +262 -0
  79. sagemaker/core/image_uri_config/factorization-machines.json +50 -0
  80. sagemaker/core/image_uri_config/forecasting-deepar.json +50 -0
  81. sagemaker/core/image_uri_config/huggingface-llm-neuronx.json +770 -0
  82. sagemaker/core/image_uri_config/huggingface-llm.json +1267 -0
  83. sagemaker/core/image_uri_config/huggingface-neuron.json +52 -0
  84. sagemaker/core/image_uri_config/huggingface-neuronx.json +686 -0
  85. sagemaker/core/image_uri_config/huggingface-tei-cpu.json +298 -0
  86. sagemaker/core/image_uri_config/huggingface-tei.json +298 -0
  87. sagemaker/core/image_uri_config/huggingface-training-compiler.json +195 -0
  88. sagemaker/core/image_uri_config/huggingface-vllm-neuronx.json +38 -0
  89. sagemaker/core/image_uri_config/huggingface.json +2287 -0
  90. sagemaker/core/image_uri_config/hyperpod-recipes-neuron.json +52 -0
  91. sagemaker/core/image_uri_config/image-classification-neo.json +43 -0
  92. sagemaker/core/image_uri_config/image-classification.json +50 -0
  93. sagemaker/core/image_uri_config/inferentia-mxnet.json +88 -0
  94. sagemaker/core/image_uri_config/inferentia-pytorch.json +127 -0
  95. sagemaker/core/image_uri_config/inferentia-tensorflow.json +88 -0
  96. sagemaker/core/image_uri_config/instance_gpu_info.json +782 -0
  97. sagemaker/core/image_uri_config/ipinsights.json +50 -0
  98. sagemaker/core/image_uri_config/kmeans.json +50 -0
  99. sagemaker/core/image_uri_config/knn.json +50 -0
  100. sagemaker/core/image_uri_config/lda.json +26 -0
  101. sagemaker/core/image_uri_config/linear-learner.json +50 -0
  102. sagemaker/core/image_uri_config/model-monitor.json +42 -0
  103. sagemaker/core/image_uri_config/mxnet.json +1154 -0
  104. sagemaker/core/image_uri_config/neo-mxnet.json +64 -0
  105. sagemaker/core/image_uri_config/neo-pytorch.json +341 -0
  106. sagemaker/core/image_uri_config/neo-tensorflow.json +109 -0
  107. sagemaker/core/image_uri_config/ntm.json +50 -0
  108. sagemaker/core/image_uri_config/object-detection.json +50 -0
  109. sagemaker/core/image_uri_config/object2vec.json +50 -0
  110. sagemaker/core/image_uri_config/pca.json +50 -0
  111. sagemaker/core/image_uri_config/pytorch-neuron.json +43 -0
  112. sagemaker/core/image_uri_config/pytorch-smp.json +218 -0
  113. sagemaker/core/image_uri_config/pytorch-training-compiler.json +80 -0
  114. sagemaker/core/image_uri_config/pytorch.json +3101 -0
  115. sagemaker/core/image_uri_config/randomcutforest.json +50 -0
  116. sagemaker/core/image_uri_config/ray-pytorch.json +46 -0
  117. sagemaker/core/image_uri_config/ray-tensorflow.json +194 -0
  118. sagemaker/core/image_uri_config/sagemaker-base-python.json +46 -0
  119. sagemaker/core/image_uri_config/sagemaker-distribution.json +37 -0
  120. sagemaker/core/image_uri_config/sagemaker-geospatial.json +13 -0
  121. sagemaker/core/image_uri_config/sagemaker-tritonserver.json +252 -0
  122. sagemaker/core/image_uri_config/semantic-segmentation.json +50 -0
  123. sagemaker/core/image_uri_config/seq2seq.json +50 -0
  124. sagemaker/core/image_uri_config/sklearn.json +494 -0
  125. sagemaker/core/image_uri_config/spark.json +280 -0
  126. sagemaker/core/image_uri_config/sparkml-serving.json +97 -0
  127. sagemaker/core/image_uri_config/stabilityai.json +53 -0
  128. sagemaker/core/image_uri_config/tensorflow.json +5086 -0
  129. sagemaker/core/image_uri_config/vw.json +25 -0
  130. sagemaker/core/image_uri_config/xgboost-neo.json +43 -0
  131. sagemaker/core/image_uri_config/xgboost.json +972 -0
  132. sagemaker/core/image_uris.py +816 -0
  133. sagemaker/core/inference_config.py +144 -0
  134. sagemaker/core/inference_recommender/__init__.py +18 -0
  135. sagemaker/core/inference_recommender/inference_recommender_mixin.py +622 -0
  136. sagemaker/core/inputs.py +366 -0
  137. sagemaker/core/instance_group.py +61 -0
  138. sagemaker/core/instance_types.py +164 -0
  139. sagemaker/core/instance_types_gpu_info.py +43 -0
  140. sagemaker/core/interactive_apps/__init__.py +41 -0
  141. sagemaker/core/interactive_apps/base_interactive_app.py +204 -0
  142. sagemaker/core/interactive_apps/detail_profiler_app.py +139 -0
  143. sagemaker/core/interactive_apps/tensorboard.py +149 -0
  144. sagemaker/core/iterators.py +197 -0
  145. sagemaker/core/job.py +380 -0
  146. sagemaker/core/jumpstart/__init__.py +156 -0
  147. sagemaker/core/jumpstart/accessors.py +390 -0
  148. sagemaker/core/jumpstart/artifacts/__init__.py +69 -0
  149. sagemaker/core/jumpstart/artifacts/environment_variables.py +252 -0
  150. sagemaker/core/jumpstart/artifacts/hyperparameters.py +120 -0
  151. sagemaker/core/jumpstart/artifacts/image_uris.py +139 -0
  152. sagemaker/core/jumpstart/artifacts/incremental_training.py +87 -0
  153. sagemaker/core/jumpstart/artifacts/instance_types.py +223 -0
  154. sagemaker/core/jumpstart/artifacts/kwargs.py +289 -0
  155. sagemaker/core/jumpstart/artifacts/metric_definitions.py +117 -0
  156. sagemaker/core/jumpstart/artifacts/model_packages.py +202 -0
  157. sagemaker/core/jumpstart/artifacts/model_uris.py +252 -0
  158. sagemaker/core/jumpstart/artifacts/payloads.py +96 -0
  159. sagemaker/core/jumpstart/artifacts/predictors.py +540 -0
  160. sagemaker/core/jumpstart/artifacts/resource_names.py +86 -0
  161. sagemaker/core/jumpstart/artifacts/resource_requirements.py +162 -0
  162. sagemaker/core/jumpstart/artifacts/script_uris.py +172 -0
  163. sagemaker/core/jumpstart/cache.py +663 -0
  164. sagemaker/core/jumpstart/configs.py +50 -0
  165. sagemaker/core/jumpstart/constants.py +198 -0
  166. sagemaker/core/jumpstart/deserializers.py +81 -0
  167. sagemaker/core/jumpstart/document.py +76 -0
  168. sagemaker/core/jumpstart/enums.py +168 -0
  169. sagemaker/core/jumpstart/exceptions.py +236 -0
  170. sagemaker/core/jumpstart/factory/utils.py +833 -0
  171. sagemaker/core/jumpstart/filters.py +597 -0
  172. sagemaker/core/jumpstart/hub/constants.py +16 -0
  173. sagemaker/core/jumpstart/hub/hub.py +291 -0
  174. sagemaker/core/jumpstart/hub/interfaces.py +936 -0
  175. sagemaker/core/jumpstart/hub/parser_utils.py +70 -0
  176. sagemaker/core/jumpstart/hub/parsers.py +288 -0
  177. sagemaker/core/jumpstart/hub/types.py +35 -0
  178. sagemaker/core/jumpstart/hub/utils.py +260 -0
  179. sagemaker/core/jumpstart/models.py +501 -0
  180. sagemaker/core/jumpstart/notebook_utils.py +575 -0
  181. sagemaker/core/jumpstart/parameters.py +20 -0
  182. sagemaker/core/jumpstart/payload_utils.py +239 -0
  183. sagemaker/core/jumpstart/region_config.json +171 -0
  184. sagemaker/core/jumpstart/search.py +171 -0
  185. sagemaker/core/jumpstart/serializers.py +81 -0
  186. sagemaker/core/jumpstart/session_utils.py +234 -0
  187. sagemaker/core/jumpstart/types.py +3044 -0
  188. sagemaker/core/jumpstart/utils.py +1731 -0
  189. sagemaker/core/jumpstart/validators.py +257 -0
  190. sagemaker/core/lambda_helper.py +312 -0
  191. sagemaker/core/lineage/__init__.py +42 -0
  192. sagemaker/core/lineage/_api_types.py +239 -0
  193. sagemaker/core/lineage/_utils.py +49 -0
  194. sagemaker/core/lineage/action.py +345 -0
  195. sagemaker/core/lineage/artifact.py +646 -0
  196. sagemaker/core/lineage/association.py +190 -0
  197. sagemaker/core/lineage/context.py +505 -0
  198. sagemaker/core/lineage/lineage_trial_component.py +191 -0
  199. sagemaker/core/lineage/query.py +732 -0
  200. sagemaker/core/lineage/visualizer.py +346 -0
  201. sagemaker/core/local/__init__.py +18 -0
  202. sagemaker/core/local/data.py +423 -0
  203. sagemaker/core/local/entities.py +678 -0
  204. sagemaker/core/local/exceptions.py +17 -0
  205. sagemaker/core/local/image.py +1243 -0
  206. sagemaker/core/local/local_session.py +739 -0
  207. sagemaker/core/local/utils.py +246 -0
  208. sagemaker/core/logs.py +181 -0
  209. sagemaker/core/metadata_properties.py +56 -0
  210. sagemaker/core/metric_definitions.py +91 -0
  211. sagemaker/core/mlflow/__init__.py +38 -0
  212. sagemaker/core/mlflow/forward_sagemaker_metrics.py +44 -0
  213. sagemaker/core/model_card/__init__.py +26 -0
  214. sagemaker/core/model_life_cycle.py +51 -0
  215. sagemaker/core/model_metrics.py +160 -0
  216. sagemaker/core/model_monitor/__init__.py +66 -0
  217. sagemaker/core/model_monitor/clarify_model_monitoring.py +1497 -0
  218. sagemaker/core/model_monitor/cron_expression_generator.py +82 -0
  219. sagemaker/core/model_monitor/data_capture_config.py +115 -0
  220. sagemaker/core/model_monitor/data_quality_monitoring_config.py +66 -0
  221. sagemaker/core/model_monitor/dataset_format.py +102 -0
  222. sagemaker/core/model_monitor/model_monitoring.py +4266 -0
  223. sagemaker/core/model_monitor/monitoring_alert.py +76 -0
  224. sagemaker/core/model_monitor/monitoring_files.py +506 -0
  225. sagemaker/core/model_monitor/utils.py +793 -0
  226. sagemaker/core/model_registry.py +480 -0
  227. sagemaker/core/model_uris.py +97 -0
  228. sagemaker/core/modules/__init__.py +19 -0
  229. sagemaker/core/modules/configs.py +239 -0
  230. sagemaker/core/modules/constants.py +37 -0
  231. sagemaker/core/modules/distributed.py +182 -0
  232. sagemaker/core/modules/local_core/local_container.py +605 -0
  233. sagemaker/core/modules/templates.py +83 -0
  234. sagemaker/core/modules/train/__init__.py +14 -0
  235. sagemaker/core/modules/train/container_drivers/__init__.py +14 -0
  236. sagemaker/core/modules/train/container_drivers/common/__init__.py +14 -0
  237. sagemaker/core/modules/train/container_drivers/common/utils.py +205 -0
  238. sagemaker/core/modules/train/container_drivers/distributed_drivers/__init__.py +14 -0
  239. sagemaker/core/modules/train/container_drivers/distributed_drivers/basic_script_driver.py +81 -0
  240. sagemaker/core/modules/train/container_drivers/distributed_drivers/mpi_driver.py +123 -0
  241. sagemaker/core/modules/train/container_drivers/distributed_drivers/mpi_utils.py +302 -0
  242. sagemaker/core/modules/train/container_drivers/distributed_drivers/torchrun_driver.py +129 -0
  243. sagemaker/core/modules/train/container_drivers/scripts/__init__.py +14 -0
  244. sagemaker/core/modules/train/container_drivers/scripts/environment.py +305 -0
  245. sagemaker/core/modules/train/sm_recipes/__init__.py +0 -0
  246. sagemaker/core/modules/train/sm_recipes/utils.py +330 -0
  247. sagemaker/core/modules/types.py +19 -0
  248. sagemaker/core/modules/utils.py +194 -0
  249. sagemaker/core/network.py +185 -0
  250. sagemaker/core/parameter.py +173 -0
  251. sagemaker/core/payloads.py +185 -0
  252. sagemaker/core/processing.py +1599 -0
  253. sagemaker/core/remote_function/__init__.py +19 -0
  254. sagemaker/core/remote_function/checkpoint_location.py +47 -0
  255. sagemaker/core/remote_function/client.py +1310 -0
  256. sagemaker/core/remote_function/core/__init__.py +0 -0
  257. sagemaker/core/remote_function/core/_custom_dispatch_table.py +72 -0
  258. sagemaker/core/remote_function/core/pipeline_variables.py +347 -0
  259. sagemaker/core/remote_function/core/serialization.py +410 -0
  260. sagemaker/core/remote_function/core/stored_function.py +223 -0
  261. sagemaker/core/remote_function/custom_file_filter.py +128 -0
  262. sagemaker/core/remote_function/errors.py +102 -0
  263. sagemaker/core/remote_function/invoke_function.py +167 -0
  264. sagemaker/core/remote_function/job.py +2121 -0
  265. sagemaker/core/remote_function/logging_config.py +38 -0
  266. sagemaker/core/remote_function/runtime_environment/__init__.py +14 -0
  267. sagemaker/core/remote_function/runtime_environment/bootstrap_runtime_environment.py +605 -0
  268. sagemaker/core/remote_function/runtime_environment/mpi_utils_remote.py +252 -0
  269. sagemaker/core/remote_function/runtime_environment/runtime_environment_manager.py +554 -0
  270. sagemaker/core/remote_function/runtime_environment/spark_app.py +18 -0
  271. sagemaker/core/remote_function/spark_config.py +149 -0
  272. sagemaker/core/resource_requirements.py +168 -0
  273. {sagemaker_core/main → sagemaker/core}/resources.py +19098 -10895
  274. sagemaker/core/s3/__init__.py +41 -0
  275. sagemaker/core/s3/client.py +367 -0
  276. sagemaker/core/s3/utils.py +175 -0
  277. sagemaker/core/script_uris.py +93 -0
  278. sagemaker/core/serializers/__init__.py +11 -0
  279. sagemaker/core/serializers/base.py +510 -0
  280. sagemaker/core/serializers/implementations.py +159 -0
  281. sagemaker/core/serializers/utils.py +223 -0
  282. sagemaker/core/serverless_inference_config.py +63 -0
  283. sagemaker/core/session_settings.py +55 -0
  284. sagemaker/core/shapes/__init__.py +3 -0
  285. sagemaker/core/shapes/model_card_shapes.py +159 -0
  286. {sagemaker_core/main → sagemaker/core/shapes}/shapes.py +5810 -1806
  287. sagemaker/core/spark/__init__.py +16 -0
  288. sagemaker/core/spark/defaults.py +16 -0
  289. sagemaker/core/spark/processing.py +1380 -0
  290. sagemaker/core/telemetry/__init__.py +23 -0
  291. sagemaker/core/telemetry/constants.py +82 -0
  292. sagemaker/core/telemetry/telemetry_logging.py +285 -0
  293. sagemaker/core/tools/__init__.py +1 -0
  294. {sagemaker_core → sagemaker/core}/tools/codegen.py +4 -4
  295. {sagemaker_core → sagemaker/core}/tools/constants.py +23 -15
  296. {sagemaker_core → sagemaker/core}/tools/data_extractor.py +1 -1
  297. {sagemaker_core → sagemaker/core}/tools/method.py +1 -1
  298. sagemaker/core/tools/model_card/generate_model_card_from_schema.py +562 -0
  299. {sagemaker_core → sagemaker/core}/tools/resources_codegen.py +165 -98
  300. {sagemaker_core → sagemaker/core}/tools/resources_extractor.py +5 -13
  301. {sagemaker_core → sagemaker/core}/tools/shapes_codegen.py +16 -17
  302. {sagemaker_core → sagemaker/core}/tools/shapes_extractor.py +29 -67
  303. {sagemaker_core → sagemaker/core}/tools/templates.py +39 -17
  304. sagemaker/core/training/__init__.py +14 -0
  305. sagemaker/core/training/configs.py +345 -0
  306. sagemaker/core/training/constants.py +37 -0
  307. sagemaker/core/training/utils.py +77 -0
  308. sagemaker/core/training_compiler/__init__.py +16 -0
  309. sagemaker/core/training_compiler/config.py +197 -0
  310. sagemaker/core/training_compiler_config.py +197 -0
  311. sagemaker/core/transformer.py +793 -0
  312. sagemaker/core/user_agent.py +76 -0
  313. sagemaker/core/utilities/__init__.py +24 -0
  314. sagemaker/core/utilities/cache.py +169 -0
  315. sagemaker/core/utilities/search_expression.py +133 -0
  316. sagemaker/core/utils/__init__.py +48 -0
  317. sagemaker/core/utils/code_injection/__init__.py +0 -0
  318. {sagemaker_core/main → sagemaker/core/utils}/code_injection/codec.py +2 -2
  319. {sagemaker_core/main → sagemaker/core/utils}/code_injection/shape_dag.py +5979 -176
  320. {sagemaker_core/main → sagemaker/core/utils}/exceptions.py +8 -8
  321. sagemaker_core/main/default_configs_helper.py → sagemaker/core/utils/intelligent_defaults_helper.py +5 -6
  322. {sagemaker_core/main → sagemaker/core/utils}/logs.py +1 -2
  323. {sagemaker_core/main → sagemaker/core/utils}/utils.py +27 -22
  324. sagemaker/core/workflow/__init__.py +152 -0
  325. sagemaker/core/workflow/conditions.py +313 -0
  326. sagemaker/core/workflow/entities.py +58 -0
  327. sagemaker/core/workflow/execution_variables.py +89 -0
  328. sagemaker/core/workflow/functions.py +193 -0
  329. sagemaker/core/workflow/parameters.py +222 -0
  330. sagemaker/core/workflow/pipeline_context.py +394 -0
  331. sagemaker/core/workflow/pipeline_definition_config.py +31 -0
  332. sagemaker/core/workflow/properties.py +285 -0
  333. sagemaker/core/workflow/step_outputs.py +65 -0
  334. sagemaker/core/workflow/utilities.py +514 -0
  335. sagemaker/lineage/__init__.py +33 -0
  336. sagemaker/lineage/action.py +28 -0
  337. sagemaker/lineage/artifact.py +28 -0
  338. sagemaker/lineage/context.py +28 -0
  339. sagemaker/lineage/lineage_trial_component.py +28 -0
  340. {sagemaker_core-1.0.62.dist-info → sagemaker_core-2.3.1.dist-info}/METADATA +28 -9
  341. sagemaker_core-2.3.1.dist-info/RECORD +351 -0
  342. sagemaker_core-2.3.1.dist-info/top_level.txt +1 -0
  343. sagemaker_core/_version.py +0 -3
  344. sagemaker_core/helper/session_helper.py +0 -769
  345. sagemaker_core/resources/__init__.py +0 -1
  346. sagemaker_core/shapes/__init__.py +0 -1
  347. sagemaker_core/tools/__init__.py +0 -1
  348. sagemaker_core-1.0.62.dist-info/RECORD +0 -35
  349. sagemaker_core-1.0.62.dist-info/top_level.txt +0 -1
  350. {sagemaker_core → sagemaker/core/helper}/__init__.py +0 -0
  351. {sagemaker_core/helper → sagemaker/core/jumpstart/factory}/__init__.py +0 -0
  352. {sagemaker_core/main → sagemaker/core/jumpstart/hub}/__init__.py +0 -0
  353. {sagemaker_core/main/code_injection → sagemaker/core/modules/local_core}/__init__.py +0 -0
  354. {sagemaker_core/main → sagemaker/core/utils}/code_injection/base.py +0 -0
  355. {sagemaker_core/main → sagemaker/core/utils}/code_injection/constants.py +0 -0
  356. {sagemaker_core/main → sagemaker/core/utils}/user_agent.py +0 -0
  357. {sagemaker_core-1.0.62.dist-info → sagemaker_core-2.3.1.dist-info}/WHEEL +0 -0
  358. {sagemaker_core-1.0.62.dist-info → sagemaker_core-2.3.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,1599 @@
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 related to the ``Processor`` class.
14
+
15
+ which is used for Amazon SageMaker Processing Jobs. These jobs let users perform
16
+ data pre-processing, post-processing, feature engineering, data validation, and model evaluation,
17
+ and interpretation on Amazon SageMaker.
18
+ """
19
+ from __future__ import absolute_import
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ import pathlib
25
+ import re
26
+ from typing import Dict, List, Optional, Union
27
+ import time
28
+ from copy import copy
29
+ from textwrap import dedent
30
+ from six.moves.urllib.parse import urlparse
31
+ from six.moves.urllib.request import url2pathname
32
+ from sagemaker.core.network import NetworkConfig
33
+ from sagemaker.core import s3
34
+ from sagemaker.core.apiutils._base_types import ApiObject
35
+ from sagemaker.core.config.config_schema import (
36
+ PROCESSING_JOB_ENABLE_NETWORK_ISOLATION_PATH,
37
+ PROCESSING_JOB_ENVIRONMENT_PATH,
38
+ PROCESSING_JOB_INTER_CONTAINER_ENCRYPTION_PATH,
39
+ PROCESSING_JOB_KMS_KEY_ID_PATH,
40
+ PROCESSING_JOB_ROLE_ARN_PATH,
41
+ PROCESSING_JOB_SECURITY_GROUP_IDS_PATH,
42
+ PROCESSING_JOB_SUBNETS_PATH,
43
+ PROCESSING_JOB_VOLUME_KMS_KEY_ID_PATH,
44
+ PROCESSING_JOB_INPUTS_PATH,
45
+ PROCESSING_JOB_NETWORK_CONFIG_PATH,
46
+ PROCESSING_OUTPUT_CONFIG_PATH,
47
+ PROCESSING_JOB_PROCESSING_RESOURCES_PATH,
48
+ SAGEMAKER,
49
+ PROCESSING_JOB,
50
+ TAGS,
51
+ )
52
+ from sagemaker.core.local.local_session import LocalSession
53
+ from sagemaker.core.helper.session_helper import Session
54
+ from sagemaker.core.shapes import ProcessingInput, ProcessingOutput, ProcessingS3Input
55
+ from sagemaker.core.resources import ProcessingJob
56
+ from sagemaker.core.workflow.pipeline_context import PipelineSession
57
+ from sagemaker.core.common_utils import (
58
+ Tags,
59
+ base_name_from_image,
60
+ check_and_get_run_experiment_config,
61
+ format_tags,
62
+ name_from_base,
63
+ resolve_class_attribute_from_config,
64
+ resolve_value_from_config,
65
+ resolve_nested_dict_value_from_config,
66
+ update_list_of_dicts_with_values_from_config,
67
+ update_nested_dictionary_with_values_from_config,
68
+ _get_initial_job_state,
69
+ _wait_until,
70
+ _flush_log_streams,
71
+ _logs_init,
72
+ LogState,
73
+ _check_job_status,
74
+ )
75
+ from sagemaker.core.workflow import is_pipeline_variable
76
+ from sagemaker.core.helper.pipeline_variable import PipelineVariable
77
+ from sagemaker.core.workflow.execution_variables import ExecutionVariables
78
+ from sagemaker.core.workflow.functions import Join
79
+ from sagemaker.core.workflow.pipeline_context import runnable_by_pipeline
80
+
81
+ from sagemaker.core._studio import _append_project_tags
82
+ from sagemaker.core.config.config_utils import _append_sagemaker_config_tags
83
+ from sagemaker.core.utils.utils import serialize
84
+
85
+ logger = logging.getLogger(__name__)
86
+
87
+
88
+ class Processor(object):
89
+ """Handles Amazon SageMaker Processing tasks."""
90
+
91
+ JOB_CLASS_NAME = "processing-job"
92
+
93
+ def __init__(
94
+ self,
95
+ role: str = None,
96
+ image_uri: Union[str, PipelineVariable] = None,
97
+ instance_count: Union[int, PipelineVariable] = None,
98
+ instance_type: Union[str, PipelineVariable] = None,
99
+ entrypoint: Optional[List[Union[str, PipelineVariable]]] = None,
100
+ volume_size_in_gb: Union[int, PipelineVariable] = 30,
101
+ volume_kms_key: Optional[Union[str, PipelineVariable]] = None,
102
+ output_kms_key: Optional[Union[str, PipelineVariable]] = None,
103
+ max_runtime_in_seconds: Optional[Union[int, PipelineVariable]] = None,
104
+ base_job_name: Optional[str] = None,
105
+ sagemaker_session: Optional[Session] = None,
106
+ env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
107
+ tags: Optional[Tags] = None,
108
+ network_config: Optional[NetworkConfig] = None,
109
+ ):
110
+ """Initializes a ``Processor`` instance.
111
+
112
+ The ``Processor`` handles Amazon SageMaker Processing tasks.
113
+
114
+ Args:
115
+ role (str or PipelineVariable): An AWS IAM role name or ARN. Amazon SageMaker Processing
116
+ uses this role to access AWS resources, such as
117
+ data stored in Amazon S3.
118
+ image_uri (str or PipelineVariable): The URI of the Docker image to use for the
119
+ processing jobs.
120
+ instance_count (int or PipelineVariable): The number of instances to run
121
+ a processing job with.
122
+ instance_type (str or PipelineVariable): The type of EC2 instance to use for
123
+ processing, for example, 'ml.c4.xlarge'.
124
+ entrypoint (list[str] or list[PipelineVariable]): The entrypoint for the
125
+ processing job (default: None). This is in the form of a list of strings
126
+ that make a command.
127
+ volume_size_in_gb (int or PipelineVariable): Size in GB of the EBS volume
128
+ to use for storing data during processing (default: 30).
129
+ volume_kms_key (str or PipelineVariable): A KMS key for the processing
130
+ volume (default: None).
131
+ output_kms_key (str or PipelineVariable): The KMS key ID for processing job
132
+ outputs (default: None).
133
+ max_runtime_in_seconds (int or PipelineVariable): Timeout in seconds (default: None).
134
+ After this amount of time, Amazon SageMaker terminates the job,
135
+ regardless of its current status. If `max_runtime_in_seconds` is not
136
+ specified, the default value is 24 hours.
137
+ base_job_name (str): Prefix for processing job name. If not specified,
138
+ the processor generates a default job name, based on the
139
+ processing image name and current timestamp.
140
+ sagemaker_session (:class:`~sagemaker.session.Session`):
141
+ Session object which manages interactions with Amazon SageMaker and
142
+ any other AWS services needed. If not specified, the processor creates
143
+ one using the default AWS configuration chain.
144
+ env (dict[str, str] or dict[str, PipelineVariable]): Environment variables
145
+ to be passed to the processing jobs (default: None).
146
+ tags (Optional[Tags]): Tags to be passed to the processing job (default: None).
147
+ For more, see https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
148
+ network_config (:class:`~sagemaker.network.NetworkConfig`):
149
+ A :class:`~sagemaker.network.NetworkConfig`
150
+ object that configures network isolation, encryption of
151
+ inter-container traffic, security group IDs, and subnets.
152
+ """
153
+ self.image_uri = image_uri
154
+ self.instance_count = instance_count
155
+ self.instance_type = instance_type
156
+ self.entrypoint = entrypoint
157
+ self.volume_size_in_gb = volume_size_in_gb
158
+ self.max_runtime_in_seconds = max_runtime_in_seconds
159
+ self.base_job_name = base_job_name
160
+ self.tags = format_tags(tags)
161
+
162
+ self.jobs = []
163
+ self.latest_job = None
164
+ self._current_job_name = None
165
+ self.arguments = None
166
+
167
+ if self.instance_type in ("local", "local_gpu"):
168
+ if not isinstance(sagemaker_session, LocalSession):
169
+ # Until Local Mode Processing supports local code, we need to disable it:
170
+ sagemaker_session = LocalSession(disable_local_code=True)
171
+
172
+ self.sagemaker_session = sagemaker_session or Session()
173
+ self.output_kms_key = resolve_value_from_config(
174
+ output_kms_key, PROCESSING_JOB_KMS_KEY_ID_PATH, sagemaker_session=self.sagemaker_session
175
+ )
176
+ self.volume_kms_key = resolve_value_from_config(
177
+ volume_kms_key,
178
+ PROCESSING_JOB_VOLUME_KMS_KEY_ID_PATH,
179
+ sagemaker_session=self.sagemaker_session,
180
+ )
181
+ self.network_config = resolve_class_attribute_from_config(
182
+ NetworkConfig,
183
+ network_config,
184
+ "subnets",
185
+ PROCESSING_JOB_SUBNETS_PATH,
186
+ sagemaker_session=self.sagemaker_session,
187
+ )
188
+ self.network_config = resolve_class_attribute_from_config(
189
+ NetworkConfig,
190
+ self.network_config,
191
+ "security_group_ids",
192
+ PROCESSING_JOB_SECURITY_GROUP_IDS_PATH,
193
+ sagemaker_session=self.sagemaker_session,
194
+ )
195
+ self.network_config = resolve_class_attribute_from_config(
196
+ NetworkConfig,
197
+ self.network_config,
198
+ "enable_network_isolation",
199
+ PROCESSING_JOB_ENABLE_NETWORK_ISOLATION_PATH,
200
+ sagemaker_session=self.sagemaker_session,
201
+ )
202
+ self.network_config = resolve_class_attribute_from_config(
203
+ NetworkConfig,
204
+ self.network_config,
205
+ "encrypt_inter_container_traffic",
206
+ PROCESSING_JOB_INTER_CONTAINER_ENCRYPTION_PATH,
207
+ sagemaker_session=self.sagemaker_session,
208
+ )
209
+ self.role = resolve_value_from_config(
210
+ role, PROCESSING_JOB_ROLE_ARN_PATH, sagemaker_session=self.sagemaker_session
211
+ )
212
+ if not self.role:
213
+ # Originally IAM role was a required parameter.
214
+ # Now we marked that as Optional because we can fetch it from SageMakerConfig
215
+ # Because of marking that parameter as optional, we should validate if it is None, even
216
+ # after fetching the config.
217
+ raise ValueError("An AWS IAM role is required to create a Processing job.")
218
+
219
+ self.env = resolve_value_from_config(
220
+ env, PROCESSING_JOB_ENVIRONMENT_PATH, sagemaker_session=self.sagemaker_session
221
+ )
222
+
223
+ @runnable_by_pipeline
224
+ def run(
225
+ self,
226
+ inputs: Optional[List[ProcessingInput]] = None,
227
+ outputs: Optional[List[ProcessingOutput]] = None,
228
+ arguments: Optional[List[Union[str, PipelineVariable]]] = None,
229
+ wait: bool = True,
230
+ logs: bool = True,
231
+ job_name: Optional[str] = None,
232
+ experiment_config: Optional[Dict[str, str]] = None,
233
+ kms_key: Optional[str] = None,
234
+ ):
235
+ """Runs a processing job.
236
+
237
+ Args:
238
+ inputs (list[:class:`~sagemaker.core.shapes.ProcessingInput`]): Input files for
239
+ the processing job. These must be provided as
240
+ :class:`~sagemaker.core.shapes.ProcessingInput` objects (default: None).
241
+ outputs (list[:class:`~sagemaker.core.shapes.ProcessingOutput`]): Outputs for
242
+ the processing job. These can be specified as either path strings or
243
+ :class:`~sagemaker.core.shapes.ProcessingOutput` objects (default: None).
244
+ arguments (list[str] or list[PipelineVariable]): A list of string arguments
245
+ to be passed to a processing job (default: None).
246
+ wait (bool): Whether the call should wait until the job completes (default: True).
247
+ logs (bool): Whether to show the logs produced by the job.
248
+ Only meaningful when ``wait`` is True (default: True).
249
+ job_name (str): Processing job name. If not specified, the processor generates
250
+ a default job name, based on the base job name and current timestamp.
251
+ experiment_config (dict[str, str]): Experiment management configuration.
252
+ Optionally, the dict can contain three keys:
253
+ 'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
254
+ The behavior of setting these keys is as follows:
255
+ * If `ExperimentName` is supplied but `TrialName` is not a Trial will be
256
+ automatically created and the job's Trial Component associated with the Trial.
257
+ * If `TrialName` is supplied and the Trial already exists the job's Trial Component
258
+ will be associated with the Trial.
259
+ * If both `ExperimentName` and `TrialName` are not supplied the trial component
260
+ will be unassociated.
261
+ * `TrialComponentDisplayName` is used for display in Studio.
262
+ * Both `ExperimentName` and `TrialName` will be ignored if the Processor instance
263
+ is built with :class:`~sagemaker.workflow.pipeline_context.PipelineSession`.
264
+ However, the value of `TrialComponentDisplayName` is honored for display in Studio.
265
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
266
+ user code file (default: None).
267
+ Returns:
268
+ None or pipeline step arguments in case the Processor instance is built with
269
+ :class:`~sagemaker.workflow.pipeline_context.PipelineSession`
270
+ Raises:
271
+ ValueError: if ``logs`` is True but ``wait`` is False.
272
+ """
273
+ if logs and not wait:
274
+ raise ValueError(
275
+ """Logs can only be shown if wait is set to True.
276
+ Please either set wait to True or set logs to False."""
277
+ )
278
+
279
+ normalized_inputs, normalized_outputs = self._normalize_args(
280
+ job_name=job_name,
281
+ arguments=arguments,
282
+ inputs=inputs,
283
+ kms_key=kms_key,
284
+ outputs=outputs,
285
+ )
286
+
287
+ experiment_config = check_and_get_run_experiment_config(experiment_config)
288
+ self.latest_job = self._start_new(
289
+ inputs=normalized_inputs,
290
+ outputs=normalized_outputs,
291
+ experiment_config=experiment_config,
292
+ )
293
+
294
+ if not isinstance(self.sagemaker_session, PipelineSession):
295
+ self.jobs.append(self.latest_job)
296
+ if wait:
297
+ self.latest_job.wait(logs=logs)
298
+
299
+ def _extend_processing_args(self, inputs, outputs, **kwargs): # pylint: disable=W0613
300
+ """Extend inputs and outputs based on extra parameters"""
301
+ return inputs, outputs
302
+
303
+ def _normalize_args(
304
+ self,
305
+ job_name=None,
306
+ arguments=None,
307
+ inputs=None,
308
+ outputs=None,
309
+ code=None,
310
+ kms_key=None,
311
+ ):
312
+ """Normalizes the arguments so that they can be passed to the job run
313
+
314
+ Args:
315
+ job_name (str): Name of the processing job to be created. If not specified, one
316
+ is generated, using the base name given to the constructor, if applicable
317
+ (default: None).
318
+ arguments (list[str]): A list of string arguments to be passed to a
319
+ processing job (default: None).
320
+ inputs (list[:class:`~sagemaker.core.shapes.ProcessingInput`]): Input files for
321
+ the processing job. These must be provided as
322
+ :class:`~sagemaker.core.shapes.ProcessingInput` objects (default: None).
323
+ outputs (list[:class:`~sagemaker.core.shapes.ProcessingOutput`]): Outputs for
324
+ the processing job. These can be specified as either path strings or
325
+ :class:`~sagemaker.core.shapes.ProcessingOutput` objects (default: None).
326
+ code (str): This can be an S3 URI or a local path to a file with the framework
327
+ script to run (default: None). A no op in the base class.
328
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
329
+ user code file (default: None).
330
+ """
331
+ if code and is_pipeline_variable(code):
332
+ raise ValueError(
333
+ "code argument has to be a valid S3 URI or local file path "
334
+ + "rather than a pipeline variable"
335
+ )
336
+
337
+ self._current_job_name = self._generate_current_job_name(job_name=job_name)
338
+
339
+ inputs_with_code = self._include_code_in_inputs(inputs, code, kms_key)
340
+ normalized_inputs = self._normalize_inputs(inputs_with_code, kms_key)
341
+ normalized_outputs = self._normalize_outputs(outputs)
342
+ self.arguments = arguments
343
+
344
+ return normalized_inputs, normalized_outputs
345
+
346
+ def _include_code_in_inputs(self, inputs, _code, _kms_key):
347
+ """A no op in the base class to include code in the processing job inputs.
348
+
349
+ Args:
350
+ inputs (list[:class:`~sagemaker.core.shapes.ProcessingInput`]): Input files for
351
+ the processing job. These must be provided as
352
+ :class:`~sagemaker.core.shapes.ProcessingInput` objects.
353
+ _code (str): This can be an S3 URI or a local path to a file with the framework
354
+ script to run (default: None). A no op in the base class.
355
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
356
+ user code file (default: None).
357
+
358
+ Returns:
359
+ list[:class:`~sagemaker.core.shapes.ProcessingInput`]: inputs
360
+ """
361
+ return inputs
362
+
363
+ def _generate_current_job_name(self, job_name=None):
364
+ """Generates the job name before running a processing job.
365
+
366
+ Args:
367
+ job_name (str): Name of the processing job to be created. If not
368
+ specified, one is generated, using the base name given to the
369
+ constructor if applicable.
370
+
371
+ Returns:
372
+ str: The supplied or generated job name.
373
+ """
374
+ if job_name is not None:
375
+ return job_name
376
+ # Honor supplied base_job_name or generate it.
377
+ if self.base_job_name:
378
+ base_name = self.base_job_name
379
+ else:
380
+ base_name = base_name_from_image(
381
+ self.image_uri, default_base_name=Processor.JOB_CLASS_NAME
382
+ )
383
+
384
+ # Replace invalid characters with hyphens to comply with AWS naming constraints
385
+ base_name = re.sub(r"[^a-zA-Z0-9-]", "-", base_name)
386
+ return name_from_base(base_name)
387
+
388
+ def _normalize_inputs(self, inputs=None, kms_key=None):
389
+ """Ensures that all the ``ProcessingInput`` objects have names and S3 URIs.
390
+
391
+ Args:
392
+ inputs (list[sagemaker.core.shapes.ProcessingInput]): A list of ``ProcessingInput``
393
+ objects to be normalized (default: None). If not specified,
394
+ an empty list is returned.
395
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
396
+ user code file (default: None).
397
+
398
+ Returns:
399
+ list[sagemaker.core.shapes.ProcessingInput]: The list of normalized
400
+ ``ProcessingInput`` objects.
401
+
402
+ Raises:
403
+ TypeError: if the inputs are not ``ProcessingInput`` objects.
404
+ """
405
+ from sagemaker.core.workflow.utilities import _pipeline_config
406
+
407
+ # Initialize a list of normalized ProcessingInput objects.
408
+ normalized_inputs = []
409
+ if inputs is not None:
410
+ # Iterate through the provided list of inputs.
411
+ for count, file_input in enumerate(inputs, 1):
412
+ if not isinstance(file_input, ProcessingInput):
413
+ raise TypeError("Your inputs must be provided as ProcessingInput objects.")
414
+ # Generate a name for the ProcessingInput if it doesn't have one.
415
+ if file_input.input_name is None:
416
+ file_input.input_name = "input-{}".format(count)
417
+
418
+ if file_input.dataset_definition:
419
+ normalized_inputs.append(file_input)
420
+ continue
421
+ if file_input.s3_input and is_pipeline_variable(file_input.s3_input.s3_uri):
422
+ normalized_inputs.append(file_input)
423
+ continue
424
+ # If the s3_uri is not an s3_uri, create one.
425
+ parse_result = urlparse(file_input.s3_input.s3_uri)
426
+ if parse_result.scheme != "s3":
427
+ if _pipeline_config:
428
+ desired_s3_uri = s3.s3_path_join(
429
+ "s3://",
430
+ self.sagemaker_session.default_bucket(),
431
+ self.sagemaker_session.default_bucket_prefix,
432
+ _pipeline_config.pipeline_name,
433
+ _pipeline_config.step_name,
434
+ "input",
435
+ file_input.input_name,
436
+ )
437
+ else:
438
+ desired_s3_uri = s3.s3_path_join(
439
+ "s3://",
440
+ self.sagemaker_session.default_bucket(),
441
+ self.sagemaker_session.default_bucket_prefix,
442
+ self._current_job_name,
443
+ "input",
444
+ file_input.input_name,
445
+ )
446
+ s3_uri = s3.S3Uploader.upload(
447
+ local_path=file_input.s3_input.s3_uri,
448
+ desired_s3_uri=desired_s3_uri,
449
+ sagemaker_session=self.sagemaker_session,
450
+ kms_key=kms_key,
451
+ )
452
+ file_input.s3_input.s3_uri = s3_uri
453
+ normalized_inputs.append(file_input)
454
+ return normalized_inputs
455
+
456
+ def _normalize_outputs(self, outputs=None):
457
+ """Ensures that all the outputs are ``ProcessingOutput`` objects with names and S3 URIs.
458
+
459
+ Args:
460
+ outputs (list[sagemaker.core.shapes.ProcessingOutput]): A list
461
+ of outputs to be normalized (default: None). Can be either strings or
462
+ ``ProcessingOutput`` objects. If not specified,
463
+ an empty list is returned.
464
+
465
+ Returns:
466
+ list[sagemaker.core.shapes.ProcessingOutput]: The list of normalized
467
+ ``ProcessingOutput`` objects.
468
+
469
+ Raises:
470
+ TypeError: if the outputs are not ``ProcessingOutput`` objects.
471
+ """
472
+ # Initialize a list of normalized ProcessingOutput objects.
473
+ from sagemaker.core.workflow.utilities import _pipeline_config
474
+
475
+ normalized_outputs = []
476
+ if outputs is not None:
477
+ # Iterate through the provided list of outputs.
478
+ for count, output in enumerate(outputs, 1):
479
+ if not isinstance(output, ProcessingOutput):
480
+ raise TypeError("Your outputs must be provided as ProcessingOutput objects.")
481
+ # Generate a name for the ProcessingOutput if it doesn't have one.
482
+ if output.output_name is None:
483
+ output.output_name = "output-{}".format(count)
484
+ if output.s3_output and is_pipeline_variable(output.s3_output.s3_uri):
485
+ normalized_outputs.append(output)
486
+ continue
487
+ # If the output's s3_uri is not an s3_uri, create one.
488
+ parse_result = urlparse(output.s3_output.s3_uri)
489
+ if parse_result.scheme != "s3":
490
+ if _pipeline_config:
491
+ s3_uri = Join(
492
+ on="/",
493
+ values=[
494
+ "s3:/",
495
+ self.sagemaker_session.default_bucket(),
496
+ *(
497
+ # don't include default_bucket_prefix if it is None or ""
498
+ [self.sagemaker_session.default_bucket_prefix]
499
+ if self.sagemaker_session.default_bucket_prefix
500
+ else []
501
+ ),
502
+ _pipeline_config.pipeline_name,
503
+ ExecutionVariables.PIPELINE_EXECUTION_ID,
504
+ _pipeline_config.step_name,
505
+ "output",
506
+ output.output_name,
507
+ ],
508
+ )
509
+ else:
510
+ s3_uri = s3.s3_path_join(
511
+ "s3://",
512
+ self.sagemaker_session.default_bucket(),
513
+ self.sagemaker_session.default_bucket_prefix,
514
+ self._current_job_name,
515
+ "output",
516
+ output.output_name,
517
+ )
518
+ output.s3_output.s3_uri = s3_uri
519
+ normalized_outputs.append(output)
520
+ return normalized_outputs
521
+
522
+ def _start_new(self, inputs, outputs, experiment_config):
523
+ """Starts a new processing job and returns ProcessingJob instance."""
524
+ from sagemaker.core.workflow.pipeline_context import PipelineSession
525
+
526
+ process_args = self._get_process_args(inputs, outputs, experiment_config)
527
+
528
+ logger.debug("Job Name: %s", process_args["job_name"])
529
+ logger.debug("Inputs: %s", process_args["inputs"])
530
+ logger.debug("Outputs: %s", process_args["output_config"]["Outputs"])
531
+
532
+ tags = _append_project_tags(format_tags(process_args["tags"]))
533
+ tags = _append_sagemaker_config_tags(
534
+ self.sagemaker_session, tags, "{}.{}.{}".format(SAGEMAKER, PROCESSING_JOB, TAGS)
535
+ )
536
+
537
+ network_config = resolve_nested_dict_value_from_config(
538
+ process_args["network_config"],
539
+ ["EnableInterContainerTrafficEncryption"],
540
+ PROCESSING_JOB_INTER_CONTAINER_ENCRYPTION_PATH,
541
+ sagemaker_session=self.sagemaker_session,
542
+ )
543
+
544
+ union_key_paths_for_dataset_definition = [
545
+ ["DatasetDefinition", "S3Input"],
546
+ [
547
+ "DatasetDefinition.AthenaDatasetDefinition",
548
+ "DatasetDefinition.RedshiftDatasetDefinition",
549
+ ],
550
+ ]
551
+ update_list_of_dicts_with_values_from_config(
552
+ process_args["inputs"],
553
+ PROCESSING_JOB_INPUTS_PATH,
554
+ union_key_paths=union_key_paths_for_dataset_definition,
555
+ sagemaker_session=self.sagemaker_session,
556
+ )
557
+
558
+ role_arn = resolve_value_from_config(
559
+ process_args["role_arn"],
560
+ PROCESSING_JOB_ROLE_ARN_PATH,
561
+ sagemaker_session=self.sagemaker_session,
562
+ )
563
+
564
+ inferred_network_config = update_nested_dictionary_with_values_from_config(
565
+ network_config,
566
+ PROCESSING_JOB_NETWORK_CONFIG_PATH,
567
+ sagemaker_session=self.sagemaker_session,
568
+ )
569
+ inferred_output_config = update_nested_dictionary_with_values_from_config(
570
+ process_args["output_config"],
571
+ PROCESSING_OUTPUT_CONFIG_PATH,
572
+ sagemaker_session=self.sagemaker_session,
573
+ )
574
+ inferred_resources_config = update_nested_dictionary_with_values_from_config(
575
+ process_args["resources"],
576
+ PROCESSING_JOB_PROCESSING_RESOURCES_PATH,
577
+ sagemaker_session=self.sagemaker_session,
578
+ )
579
+ environment = resolve_value_from_config(
580
+ direct_input=process_args["environment"],
581
+ config_path=PROCESSING_JOB_ENVIRONMENT_PATH,
582
+ default_value=None,
583
+ sagemaker_session=self.sagemaker_session,
584
+ )
585
+
586
+ process_request = _get_process_request(
587
+ inputs=process_args["inputs"],
588
+ output_config=inferred_output_config,
589
+ job_name=process_args["job_name"],
590
+ resources=inferred_resources_config,
591
+ stopping_condition=process_args["stopping_condition"],
592
+ app_specification=process_args["app_specification"],
593
+ environment=environment,
594
+ network_config=inferred_network_config,
595
+ role_arn=role_arn,
596
+ tags=tags,
597
+ experiment_config=experiment_config,
598
+ )
599
+
600
+ # convert Unassigned() type in sagemaker-core to None
601
+ serialized_request = serialize(process_request)
602
+
603
+ if isinstance(self.sagemaker_session, PipelineSession):
604
+ self.sagemaker_session._intercept_create_request(serialized_request, None, "process")
605
+ return
606
+
607
+ def submit(request):
608
+ try:
609
+ logger.info("Creating processing-job with name %s", process_args["job_name"])
610
+ logger.debug("process request: %s", json.dumps(request, indent=4))
611
+ self.sagemaker_session.sagemaker_client.create_processing_job(**request)
612
+ except Exception as e:
613
+ troubleshooting = (
614
+ "https://docs.aws.amazon.com/sagemaker/latest/dg/"
615
+ "sagemaker-python-sdk-troubleshooting.html"
616
+ "#sagemaker-python-sdk-troubleshooting-create-processing-job"
617
+ )
618
+ logger.error(
619
+ "Please check the troubleshooting guide for common errors: %s", troubleshooting
620
+ )
621
+ raise e
622
+
623
+ self.sagemaker_session._intercept_create_request(serialized_request, submit, "process")
624
+
625
+ from sagemaker.core.utils.code_injection.codec import transform
626
+
627
+ transformed = transform(serialized_request, "CreateProcessingJobRequest")
628
+ # Remove tags from transformed dict as ProcessingJob resource doesn't accept it
629
+ transformed.pop("tags", None)
630
+ return ProcessingJob(**transformed)
631
+
632
+ def _get_process_args(self, inputs, outputs, experiment_config):
633
+ """Gets a dict of arguments for a new Amazon SageMaker processing job."""
634
+ process_request_args = {}
635
+ process_request_args["inputs"] = [_processing_input_to_request_dict(inp) for inp in inputs]
636
+ process_request_args["output_config"] = {
637
+ "Outputs": [_processing_output_to_request_dict(output) for output in outputs]
638
+ }
639
+ if self.output_kms_key is not None:
640
+ process_request_args["output_config"]["KmsKeyId"] = self.output_kms_key
641
+ process_request_args["experiment_config"] = experiment_config
642
+ process_request_args["job_name"] = self._current_job_name
643
+ process_request_args["resources"] = {
644
+ "ClusterConfig": {
645
+ "InstanceType": self.instance_type,
646
+ "InstanceCount": self.instance_count,
647
+ "VolumeSizeInGB": self.volume_size_in_gb,
648
+ }
649
+ }
650
+ if self.volume_kms_key is not None:
651
+ process_request_args["resources"]["ClusterConfig"][
652
+ "VolumeKmsKeyId"
653
+ ] = self.volume_kms_key
654
+ if self.max_runtime_in_seconds is not None:
655
+ process_request_args["stopping_condition"] = {
656
+ "MaxRuntimeInSeconds": self.max_runtime_in_seconds
657
+ }
658
+ else:
659
+ process_request_args["stopping_condition"] = None
660
+ process_request_args["app_specification"] = {"ImageUri": self.image_uri}
661
+ if self.arguments is not None:
662
+ process_request_args["app_specification"]["ContainerArguments"] = self.arguments
663
+ if self.entrypoint is not None:
664
+ process_request_args["app_specification"]["ContainerEntrypoint"] = self.entrypoint
665
+ process_request_args["environment"] = self.env
666
+ if self.network_config is not None:
667
+ process_request_args["network_config"] = self.network_config._to_request_dict()
668
+ else:
669
+ process_request_args["network_config"] = None
670
+ process_request_args["role_arn"] = (
671
+ self.role
672
+ if is_pipeline_variable(self.role)
673
+ else self.sagemaker_session.expand_role(self.role)
674
+ )
675
+ process_request_args["tags"] = self.tags
676
+ return process_request_args
677
+
678
+
679
+ class ScriptProcessor(Processor):
680
+ """Handles Amazon SageMaker processing tasks for jobs using a machine learning framework."""
681
+
682
+ def __init__(
683
+ self,
684
+ role: Optional[Union[str, PipelineVariable]] = None,
685
+ image_uri: Union[str, PipelineVariable] = None,
686
+ command: List[str] = None,
687
+ instance_count: Union[int, PipelineVariable] = None,
688
+ instance_type: Union[str, PipelineVariable] = None,
689
+ volume_size_in_gb: Union[int, PipelineVariable] = 30,
690
+ volume_kms_key: Optional[Union[str, PipelineVariable]] = None,
691
+ output_kms_key: Optional[Union[str, PipelineVariable]] = None,
692
+ max_runtime_in_seconds: Optional[Union[int, PipelineVariable]] = None,
693
+ base_job_name: Optional[str] = None,
694
+ sagemaker_session: Optional[Session] = None,
695
+ env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
696
+ tags: Optional[Tags] = None,
697
+ network_config: Optional[NetworkConfig] = None,
698
+ ):
699
+ """Initializes a ``ScriptProcessor`` instance.
700
+
701
+ The ``ScriptProcessor`` handles Amazon SageMaker Processing tasks for jobs
702
+ using a machine learning framework, which allows for providing a script to be
703
+ run as part of the Processing Job.
704
+
705
+ Args:
706
+ role (str or PipelineVariable): An AWS IAM role name or ARN. Amazon SageMaker Processing
707
+ uses this role to access AWS resources, such as
708
+ data stored in Amazon S3.
709
+ image_uri (str or PipelineVariable): The URI of the Docker image to use for the
710
+ processing jobs.
711
+ command ([str]): The command to run, along with any command-line flags.
712
+ Example: ["python3", "-v"].
713
+ instance_count (int or PipelineVariable): The number of instances to run
714
+ a processing job with.
715
+ instance_type (str or PipelineVariable): The type of EC2 instance to use for
716
+ processing, for example, 'ml.c4.xlarge'.
717
+ volume_size_in_gb (int or PipelineVariable): Size in GB of the EBS volume
718
+ to use for storing data during processing (default: 30).
719
+ volume_kms_key (str or PipelineVariable): A KMS key for the processing
720
+ volume (default: None).
721
+ output_kms_key (str or PipelineVariable): The KMS key ID for processing
722
+ job outputs (default: None).
723
+ max_runtime_in_seconds (int or PipelineVariable): Timeout in seconds (default: None).
724
+ After this amount of time, Amazon SageMaker terminates the job,
725
+ regardless of its current status. If `max_runtime_in_seconds` is not
726
+ specified, the default value is 24 hours.
727
+ base_job_name (str): Prefix for processing name. If not specified,
728
+ the processor generates a default job name, based on the
729
+ processing image name and current timestamp.
730
+ sagemaker_session (:class:`~sagemaker.session.Session`):
731
+ Session object which manages interactions with Amazon SageMaker and
732
+ any other AWS services needed. If not specified, the processor creates
733
+ one using the default AWS configuration chain.
734
+ env (dict[str, str] or dict[str, PipelineVariable])): Environment variables to
735
+ be passed to the processing jobs (default: None).
736
+ tags (Optional[Tags]): Tags to be passed to the processing job (default: None).
737
+ For more, see https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
738
+ network_config (:class:`~sagemaker.network.NetworkConfig`):
739
+ A :class:`~sagemaker.network.NetworkConfig`
740
+ object that configures network isolation, encryption of
741
+ inter-container traffic, security group IDs, and subnets.
742
+ """
743
+ self._CODE_CONTAINER_BASE_PATH = "/opt/ml/processing/input/"
744
+ self._CODE_CONTAINER_INPUT_NAME = "code"
745
+
746
+ if (
747
+ not command
748
+ and image_uri
749
+ and ("sklearn" in str(image_uri) or "scikit-learn" in str(image_uri))
750
+ ):
751
+ command = ["python3"]
752
+
753
+ self.command = command
754
+
755
+ super(ScriptProcessor, self).__init__(
756
+ role=role,
757
+ image_uri=image_uri,
758
+ instance_count=instance_count,
759
+ instance_type=instance_type,
760
+ volume_size_in_gb=volume_size_in_gb,
761
+ volume_kms_key=volume_kms_key,
762
+ output_kms_key=output_kms_key,
763
+ max_runtime_in_seconds=max_runtime_in_seconds,
764
+ base_job_name=base_job_name,
765
+ sagemaker_session=sagemaker_session,
766
+ env=env,
767
+ tags=format_tags(tags),
768
+ network_config=network_config,
769
+ )
770
+
771
+ @runnable_by_pipeline
772
+ def run(
773
+ self,
774
+ code: str,
775
+ inputs: Optional[List[ProcessingInput]] = None,
776
+ outputs: Optional[List[ProcessingOutput]] = None,
777
+ arguments: Optional[List[Union[str, PipelineVariable]]] = None,
778
+ wait: bool = True,
779
+ logs: bool = True,
780
+ job_name: Optional[str] = None,
781
+ experiment_config: Optional[Dict[str, str]] = None,
782
+ kms_key: Optional[str] = None,
783
+ ):
784
+ """Runs a processing job.
785
+
786
+ Args:
787
+ code (str): This can be an S3 URI or a local path to
788
+ a file with the framework script to run.
789
+ inputs (list[:class:`~sagemaker.core.shapes.ProcessingInput`]): Input files for
790
+ the processing job. These must be provided as
791
+ :class:`~sagemaker.core.shapes.ProcessingInput` objects (default: None).
792
+ outputs (list[:class:`~sagemaker.core.shapes.ProcessingOutput`]): Outputs for
793
+ the processing job. These can be specified as either path strings or
794
+ :class:`~sagemaker.core.shapes.ProcessingOutput` objects (default: None).
795
+ arguments (list[str]): A list of string arguments to be passed to a
796
+ processing job (default: None).
797
+ wait (bool): Whether the call should wait until the job completes (default: True).
798
+ logs (bool): Whether to show the logs produced by the job.
799
+ Only meaningful when wait is True (default: True).
800
+ job_name (str): Processing job name. If not specified, the processor generates
801
+ a default job name, based on the base job name and current timestamp.
802
+ experiment_config (dict[str, str]): Experiment management configuration.
803
+ Optionally, the dict can contain three keys:
804
+ 'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
805
+ The behavior of setting these keys is as follows:
806
+ * If `ExperimentName` is supplied but `TrialName` is not a Trial will be
807
+ automatically created and the job's Trial Component associated with the Trial.
808
+ * If `TrialName` is supplied and the Trial already exists the job's Trial Component
809
+ will be associated with the Trial.
810
+ * If both `ExperimentName` and `TrialName` are not supplied the trial component
811
+ will be unassociated.
812
+ * `TrialComponentDisplayName` is used for display in Studio.
813
+ * Both `ExperimentName` and `TrialName` will be ignored if the Processor instance
814
+ is built with :class:`~sagemaker.workflow.pipeline_context.PipelineSession`.
815
+ However, the value of `TrialComponentDisplayName` is honored for display in Studio.
816
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
817
+ user code file (default: None).
818
+ Returns:
819
+ None or pipeline step arguments in case the Processor instance is built with
820
+ :class:`~sagemaker.workflow.pipeline_context.PipelineSession`
821
+ """
822
+ normalized_inputs, normalized_outputs = self._normalize_args(
823
+ job_name=job_name,
824
+ arguments=arguments,
825
+ inputs=inputs,
826
+ outputs=outputs,
827
+ code=code,
828
+ kms_key=kms_key,
829
+ )
830
+
831
+ experiment_config = check_and_get_run_experiment_config(experiment_config)
832
+ self.latest_job = self._start_new(
833
+ inputs=normalized_inputs,
834
+ outputs=normalized_outputs,
835
+ experiment_config=experiment_config,
836
+ )
837
+
838
+ from sagemaker.core.workflow.pipeline_context import PipelineSession
839
+
840
+ if not isinstance(self.sagemaker_session, PipelineSession):
841
+ self.jobs.append(self.latest_job)
842
+ if wait:
843
+ self.latest_job.wait(logs=logs)
844
+
845
+ def _include_code_in_inputs(self, inputs, code, kms_key=None):
846
+ """Converts code to appropriate input and includes in input list.
847
+
848
+ Side effects include:
849
+ * uploads code to S3 if the code is a local file.
850
+ * sets the entrypoint attribute based on the command and user script name from code.
851
+
852
+ Args:
853
+ inputs (list[:class:`~sagemaker.core.shapes.ProcessingInput`]): Input files for
854
+ the processing job. These must be provided as
855
+ :class:`~sagemaker.core.shapes.ProcessingInput` objects.
856
+ code (str): This can be an S3 URI or a local path to a file with the framework
857
+ script to run (default: None).
858
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
859
+ user code file (default: None).
860
+
861
+ Returns:
862
+ list[:class:`~sagemaker.core.shapes.ProcessingInput`]: inputs together with the
863
+ code as `ProcessingInput`.
864
+ """
865
+ user_code_s3_uri = self._handle_user_code_url(code, kms_key)
866
+ user_script_name = self._get_user_code_name(code)
867
+
868
+ inputs_with_code = self._convert_code_and_add_to_inputs(inputs, user_code_s3_uri)
869
+
870
+ self._set_entrypoint(self.command, user_script_name)
871
+ return inputs_with_code
872
+
873
+ def _get_user_code_name(self, code):
874
+ """Gets the basename of the user's code from the URL the customer provided.
875
+
876
+ Args:
877
+ code (str): A URL to the user's code.
878
+
879
+ Returns:
880
+ str: The basename of the user's code.
881
+
882
+ """
883
+ code_url = urlparse(code)
884
+ return os.path.basename(code_url.path)
885
+
886
+ def _handle_user_code_url(self, code, kms_key=None):
887
+ """Gets the S3 URL containing the user's code.
888
+
889
+ Inspects the scheme the customer passed in ("s3://" for code in S3, "file://" or nothing
890
+ for absolute or local file paths. Uploads the code to S3 if the code is a local file.
891
+
892
+ Args:
893
+ code (str): A URL to the customer's code.
894
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
895
+ user code file (default: None).
896
+
897
+ Returns:
898
+ str: The S3 URL to the customer's code.
899
+
900
+ Raises:
901
+ ValueError: if the code isn't found, is a directory, or
902
+ does not have a valid URL scheme.
903
+ """
904
+ code_url = urlparse(code)
905
+ if code_url.scheme == "s3":
906
+ user_code_s3_uri = code
907
+ elif code_url.scheme == "" or code_url.scheme == "file":
908
+ # Validate that the file exists locally and is not a directory.
909
+ code_path = url2pathname(code_url.path)
910
+ if not os.path.exists(code_path):
911
+ raise ValueError(
912
+ """code {} wasn't found. Please make sure that the file exists.
913
+ """.format(
914
+ code
915
+ )
916
+ )
917
+ if not os.path.isfile(code_path):
918
+ raise ValueError(
919
+ """code {} must be a file, not a directory. Please pass a path to a file.
920
+ """.format(
921
+ code
922
+ )
923
+ )
924
+ user_code_s3_uri = self._upload_code(code_path, kms_key)
925
+ else:
926
+ raise ValueError(
927
+ "code {} url scheme {} is not recognized. Please pass a file path or S3 url".format(
928
+ code, code_url.scheme
929
+ )
930
+ )
931
+ return user_code_s3_uri
932
+
933
+ def _upload_code(self, code, kms_key=None):
934
+ """Uploads a code file or directory specified as a string and returns the S3 URI.
935
+
936
+ Args:
937
+ code (str): A file or directory to be uploaded to S3.
938
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
939
+ user code file (default: None).
940
+
941
+ Returns:
942
+ str: The S3 URI of the uploaded file or directory.
943
+
944
+ """
945
+ from sagemaker.core.workflow.utilities import _pipeline_config
946
+
947
+ if _pipeline_config and _pipeline_config.code_hash:
948
+ desired_s3_uri = s3.s3_path_join(
949
+ "s3://",
950
+ self.sagemaker_session.default_bucket(),
951
+ self.sagemaker_session.default_bucket_prefix,
952
+ _pipeline_config.pipeline_name,
953
+ self._CODE_CONTAINER_INPUT_NAME,
954
+ _pipeline_config.code_hash,
955
+ )
956
+ else:
957
+ desired_s3_uri = s3.s3_path_join(
958
+ "s3://",
959
+ self.sagemaker_session.default_bucket(),
960
+ self.sagemaker_session.default_bucket_prefix,
961
+ self._current_job_name,
962
+ "input",
963
+ self._CODE_CONTAINER_INPUT_NAME,
964
+ )
965
+ return s3.S3Uploader.upload(
966
+ local_path=code,
967
+ desired_s3_uri=desired_s3_uri,
968
+ kms_key=kms_key,
969
+ sagemaker_session=self.sagemaker_session,
970
+ )
971
+
972
+ def _convert_code_and_add_to_inputs(self, inputs, s3_uri):
973
+ """Creates a ``ProcessingInput`` object from an S3 URI and adds it to the list of inputs.
974
+
975
+ Args:
976
+ inputs (list[sagemaker.core.shapes.ProcessingInput]):
977
+ List of ``ProcessingInput`` objects.
978
+ s3_uri (str): S3 URI of the input to be added to inputs.
979
+
980
+ Returns:
981
+ list[sagemaker.core.shapes.ProcessingInput]: A new list of ``ProcessingInput`` objects,
982
+ with the ``ProcessingInput`` object created from ``s3_uri`` appended to the list.
983
+
984
+ """
985
+
986
+ code_file_input = ProcessingInput(
987
+ input_name=self._CODE_CONTAINER_INPUT_NAME,
988
+ s3_input=ProcessingS3Input(
989
+ s3_uri=s3_uri,
990
+ local_path=str(
991
+ pathlib.PurePosixPath(
992
+ self._CODE_CONTAINER_BASE_PATH, self._CODE_CONTAINER_INPUT_NAME
993
+ )
994
+ ),
995
+ s3_data_type="S3Prefix",
996
+ s3_input_mode="File",
997
+ ),
998
+ )
999
+ return (inputs or []) + [code_file_input]
1000
+
1001
+ def _set_entrypoint(self, command, user_script_name):
1002
+ """Sets the entrypoint based on the user's script and corresponding executable.
1003
+
1004
+ Args:
1005
+ user_script_name (str): A filename with an extension.
1006
+ """
1007
+ user_script_location = str(
1008
+ pathlib.PurePosixPath(
1009
+ self._CODE_CONTAINER_BASE_PATH,
1010
+ self._CODE_CONTAINER_INPUT_NAME,
1011
+ user_script_name,
1012
+ )
1013
+ )
1014
+ self.entrypoint = command + [user_script_location]
1015
+
1016
+
1017
+ class FrameworkProcessor(ScriptProcessor):
1018
+ """Handles Amazon SageMaker processing tasks using ModelTrainer for code packaging."""
1019
+
1020
+ framework_entrypoint_command = ["/bin/bash"]
1021
+
1022
+ def __init__(
1023
+ self,
1024
+ image_uri: Union[str, PipelineVariable],
1025
+ role: Optional[Union[str, PipelineVariable]] = None,
1026
+ instance_count: Union[int, PipelineVariable] = None,
1027
+ instance_type: Union[str, PipelineVariable] = None,
1028
+ command: Optional[List[str]] = None,
1029
+ volume_size_in_gb: Union[int, PipelineVariable] = 30,
1030
+ volume_kms_key: Optional[Union[str, PipelineVariable]] = None,
1031
+ output_kms_key: Optional[Union[str, PipelineVariable]] = None,
1032
+ code_location: Optional[str] = None,
1033
+ max_runtime_in_seconds: Optional[Union[int, PipelineVariable]] = None,
1034
+ base_job_name: Optional[str] = None,
1035
+ sagemaker_session: Optional[Session] = None,
1036
+ env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
1037
+ tags: Optional[Tags] = None,
1038
+ network_config: Optional[NetworkConfig] = None,
1039
+ ):
1040
+ """Initializes a ``FrameworkProcessor`` instance.
1041
+
1042
+ The ``FrameworkProcessor`` handles Amazon SageMaker Processing tasks using
1043
+ ModelTrainer for code packaging instead of Framework estimators.
1044
+
1045
+ Args:
1046
+ image_uri (str or PipelineVariable): The URI of the Docker image to use for the
1047
+ processing jobs.
1048
+ role (str or PipelineVariable): An AWS IAM role name or ARN. Amazon SageMaker
1049
+ Processing uses this role to access AWS resources, such as data stored
1050
+ in Amazon S3.
1051
+ instance_count (int or PipelineVariable): The number of instances to run a
1052
+ processing job with.
1053
+ instance_type (str or PipelineVariable): The type of EC2 instance to use for
1054
+ processing, for example, 'ml.c4.xlarge'.
1055
+ command ([str]): The command to run, along with any command-line flags
1056
+ to *precede* the ```code script```. Example: ["python3", "-v"]. If not
1057
+ provided, ["python"] will be chosen (default: None).
1058
+ volume_size_in_gb (int or PipelineVariable): Size in GB of the EBS volume
1059
+ to use for storing data during processing (default: 30).
1060
+ volume_kms_key (str or PipelineVariable): A KMS key for the processing volume
1061
+ (default: None).
1062
+ output_kms_key (str or PipelineVariable): The KMS key ID for processing job outputs
1063
+ (default: None).
1064
+ code_location (str): The S3 prefix URI where custom code will be
1065
+ uploaded (default: None). The code file uploaded to S3 is
1066
+ 'code_location/job-name/source/sourcedir.tar.gz'. If not specified, the
1067
+ default ``code location`` is 's3://{sagemaker-default-bucket}'
1068
+ max_runtime_in_seconds (int or PipelineVariable): Timeout in seconds (default: None).
1069
+ After this amount of time, Amazon SageMaker terminates the job,
1070
+ regardless of its current status. If `max_runtime_in_seconds` is not
1071
+ specified, the default value is 24 hours.
1072
+ base_job_name (str): Prefix for processing name. If not specified,
1073
+ the processor generates a default job name, based on the
1074
+ processing image name and current timestamp (default: None).
1075
+ sagemaker_session (:class:`~sagemaker.session.Session`):
1076
+ Session object which manages interactions with Amazon SageMaker and
1077
+ any other AWS services needed. If not specified, the processor creates
1078
+ one using the default AWS configuration chain (default: None).
1079
+ env (dict[str, str] or dict[str, PipelineVariable]): Environment variables to
1080
+ be passed to the processing jobs (default: None).
1081
+ tags (Optional[Tags]): Tags to be passed to the processing job (default: None).
1082
+ For more, see https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
1083
+ network_config (:class:`~sagemaker.network.NetworkConfig`):
1084
+ A :class:`~sagemaker.network.NetworkConfig`
1085
+ object that configures network isolation, encryption of
1086
+ inter-container traffic, security group IDs, and subnets (default: None).
1087
+ """
1088
+ if not command:
1089
+ command = ["python"]
1090
+
1091
+ super().__init__(
1092
+ role=role,
1093
+ image_uri=image_uri,
1094
+ command=command,
1095
+ instance_count=instance_count,
1096
+ instance_type=instance_type,
1097
+ volume_size_in_gb=volume_size_in_gb,
1098
+ volume_kms_key=volume_kms_key,
1099
+ output_kms_key=output_kms_key,
1100
+ max_runtime_in_seconds=max_runtime_in_seconds,
1101
+ base_job_name=base_job_name,
1102
+ sagemaker_session=sagemaker_session,
1103
+ env=env,
1104
+ tags=format_tags(tags),
1105
+ network_config=network_config,
1106
+ )
1107
+
1108
+ # This subclass uses the "code" input for actual payload and the ScriptProcessor parent's
1109
+ # functionality for uploading just a small entrypoint script to invoke it.
1110
+ self._CODE_CONTAINER_INPUT_NAME = "entrypoint"
1111
+
1112
+ self.code_location = (
1113
+ code_location[:-1] if (code_location and code_location.endswith("/")) else code_location
1114
+ )
1115
+
1116
+ def _package_code(
1117
+ self,
1118
+ entry_point,
1119
+ source_dir,
1120
+ requirements,
1121
+ job_name,
1122
+ kms_key,
1123
+ ):
1124
+ """Package and upload code to S3."""
1125
+ import tarfile
1126
+ import tempfile
1127
+
1128
+ # If source_dir is not provided, use the directory containing entry_point
1129
+ if source_dir is None:
1130
+ if os.path.isabs(entry_point):
1131
+ source_dir = os.path.dirname(entry_point)
1132
+ else:
1133
+ source_dir = os.path.dirname(os.path.abspath(entry_point))
1134
+
1135
+ # Resolve source_dir to absolute path
1136
+ if not os.path.isabs(source_dir):
1137
+ source_dir = os.path.abspath(source_dir)
1138
+
1139
+ if not os.path.exists(source_dir):
1140
+ raise ValueError(f"source_dir does not exist: {source_dir}")
1141
+
1142
+ # Create tar.gz with source_dir contents
1143
+ with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as tmp:
1144
+ with tarfile.open(tmp.name, "w:gz") as tar:
1145
+ # Add all files from source_dir to the root of the tar
1146
+ for item in os.listdir(source_dir):
1147
+ item_path = os.path.join(source_dir, item)
1148
+ tar.add(item_path, arcname=item)
1149
+
1150
+ # Upload to S3
1151
+ s3_uri = s3.s3_path_join(
1152
+ "s3://",
1153
+ self.sagemaker_session.default_bucket(),
1154
+ self.sagemaker_session.default_bucket_prefix or "",
1155
+ job_name,
1156
+ "source",
1157
+ "sourcedir.tar.gz",
1158
+ )
1159
+
1160
+ # Upload the tar file directly to S3
1161
+ s3.S3Uploader.upload_string_as_file_body(
1162
+ body=open(tmp.name, "rb").read(),
1163
+ desired_s3_uri=s3_uri,
1164
+ kms_key=kms_key,
1165
+ sagemaker_session=self.sagemaker_session,
1166
+ )
1167
+
1168
+ os.unlink(tmp.name)
1169
+ return s3_uri
1170
+
1171
+ @runnable_by_pipeline
1172
+ def run(
1173
+ self,
1174
+ code: str,
1175
+ source_dir: Optional[str] = None,
1176
+ requirements: Optional[str] = None,
1177
+ inputs: Optional[List[ProcessingInput]] = None,
1178
+ outputs: Optional[List["ProcessingOutput"]] = None,
1179
+ arguments: Optional[List[Union[str, PipelineVariable]]] = None,
1180
+ wait: bool = True,
1181
+ logs: bool = True,
1182
+ job_name: Optional[str] = None,
1183
+ experiment_config: Optional[Dict[str, str]] = None,
1184
+ kms_key: Optional[str] = None,
1185
+ ):
1186
+ """Runs a processing job.
1187
+
1188
+ Args:
1189
+ code (str): This can be an S3 URI or a local path to a file with the
1190
+ framework script to run.
1191
+ source_dir (str): Path (absolute, relative or an S3 URI) to a directory
1192
+ with any other processing source code dependencies aside from the entry
1193
+ point file (default: None).
1194
+ requirements (str): Path to a requirements.txt file relative to source_dir
1195
+ (default: None).
1196
+ inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
1197
+ the processing job. These must be provided as
1198
+ :class:`~sagemaker.processing.ProcessingInput` objects (default: None).
1199
+ outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): Outputs for
1200
+ the processing job. These can be specified as either path strings or
1201
+ :class:`~sagemaker.processing.ProcessingOutput` objects (default: None).
1202
+ arguments (list[str] or list[PipelineVariable]): A list of string arguments
1203
+ to be passed to a processing job (default: None).
1204
+ wait (bool): Whether the call should wait until the job completes (default: True).
1205
+ logs (bool): Whether to show the logs produced by the job.
1206
+ Only meaningful when wait is True (default: True).
1207
+ job_name (str): Processing job name. If not specified, the processor generates
1208
+ a default job name, based on the base job name and current timestamp.
1209
+ experiment_config (dict[str, str]): Experiment management configuration.
1210
+ kms_key (str): The ARN of the KMS key that is used to encrypt the
1211
+ user code file (default: None).
1212
+ Returns:
1213
+ None or pipeline step arguments in case the Processor instance is built with
1214
+ :class:`~sagemaker.workflow.pipeline_context.PipelineSession`
1215
+ """
1216
+ s3_runproc_sh, inputs, job_name = self._pack_and_upload_code(
1217
+ code,
1218
+ source_dir,
1219
+ requirements,
1220
+ job_name,
1221
+ inputs,
1222
+ kms_key,
1223
+ )
1224
+
1225
+ # Submit a processing job.
1226
+ return super().run(
1227
+ code=s3_runproc_sh,
1228
+ inputs=inputs,
1229
+ outputs=outputs,
1230
+ arguments=arguments,
1231
+ wait=wait,
1232
+ logs=logs,
1233
+ job_name=job_name,
1234
+ experiment_config=experiment_config,
1235
+ kms_key=kms_key,
1236
+ )
1237
+
1238
+ def _pack_and_upload_code(
1239
+ self,
1240
+ code,
1241
+ source_dir,
1242
+ requirements,
1243
+ job_name,
1244
+ inputs,
1245
+ kms_key=None,
1246
+ ):
1247
+ """Pack local code bundle and upload to Amazon S3."""
1248
+ if code.startswith("s3://"):
1249
+ return code, inputs, job_name
1250
+
1251
+ if job_name is None:
1252
+ job_name = self._generate_current_job_name(job_name)
1253
+
1254
+ # Package and upload code
1255
+ s3_payload = self._package_code(
1256
+ entry_point=code,
1257
+ source_dir=source_dir,
1258
+ requirements=requirements,
1259
+ job_name=job_name,
1260
+ kms_key=kms_key,
1261
+ )
1262
+
1263
+ inputs = self._patch_inputs_with_payload(inputs, s3_payload)
1264
+
1265
+ entrypoint_s3_uri = s3_payload.replace("sourcedir.tar.gz", "runproc.sh")
1266
+
1267
+ script = os.path.basename(code)
1268
+ evaluated_kms_key = kms_key if kms_key else self.output_kms_key
1269
+ s3_runproc_sh = self._create_and_upload_runproc(
1270
+ script, evaluated_kms_key, entrypoint_s3_uri
1271
+ )
1272
+
1273
+ return s3_runproc_sh, inputs, job_name
1274
+
1275
+ def _patch_inputs_with_payload(self, inputs, s3_payload) -> List[ProcessingInput]:
1276
+ """Add payload sourcedir.tar.gz to processing input."""
1277
+ if inputs is None:
1278
+ inputs = []
1279
+
1280
+ # make a shallow copy of user inputs
1281
+ patched_inputs = copy(inputs)
1282
+
1283
+ # Extract the directory path from the s3_payload (remove the filename)
1284
+ s3_code_dir = s3_payload.rsplit("/", 1)[0] + "/"
1285
+
1286
+ patched_inputs.append(
1287
+ ProcessingInput(
1288
+ input_name="code",
1289
+ s3_input=ProcessingS3Input(
1290
+ s3_uri=s3_code_dir,
1291
+ local_path="/opt/ml/processing/input/code/",
1292
+ s3_data_type="S3Prefix",
1293
+ s3_input_mode="File",
1294
+ ),
1295
+ )
1296
+ )
1297
+ return patched_inputs
1298
+
1299
+ def _set_entrypoint(self, command, user_script_name):
1300
+ """Framework processor override for setting processing job entrypoint."""
1301
+ user_script_location = str(
1302
+ pathlib.PurePosixPath(
1303
+ self._CODE_CONTAINER_BASE_PATH, self._CODE_CONTAINER_INPUT_NAME, user_script_name
1304
+ )
1305
+ )
1306
+ self.entrypoint = self.framework_entrypoint_command + [user_script_location]
1307
+
1308
+ def _create_and_upload_runproc(self, user_script, kms_key, entrypoint_s3_uri):
1309
+ """Create runproc shell script and upload to S3 bucket."""
1310
+ from sagemaker.core.workflow.utilities import _pipeline_config, hash_object
1311
+
1312
+ if _pipeline_config and _pipeline_config.pipeline_name:
1313
+ runproc_file_str = self._generate_framework_script(user_script)
1314
+ runproc_file_hash = hash_object(runproc_file_str)
1315
+ s3_uri = s3.s3_path_join(
1316
+ "s3://",
1317
+ self.sagemaker_session.default_bucket(),
1318
+ self.sagemaker_session.default_bucket_prefix,
1319
+ _pipeline_config.pipeline_name,
1320
+ "code",
1321
+ runproc_file_hash,
1322
+ "runproc.sh",
1323
+ )
1324
+ s3_runproc_sh = s3.S3Uploader.upload_string_as_file_body(
1325
+ runproc_file_str,
1326
+ desired_s3_uri=s3_uri,
1327
+ kms_key=kms_key,
1328
+ sagemaker_session=self.sagemaker_session,
1329
+ )
1330
+ else:
1331
+ s3_runproc_sh = s3.S3Uploader.upload_string_as_file_body(
1332
+ self._generate_framework_script(user_script),
1333
+ desired_s3_uri=entrypoint_s3_uri,
1334
+ kms_key=kms_key,
1335
+ sagemaker_session=self.sagemaker_session,
1336
+ )
1337
+
1338
+ return s3_runproc_sh
1339
+
1340
+ def _generate_framework_script(self, user_script: str) -> str:
1341
+ """Generate the framework entrypoint file (as text) for a processing job."""
1342
+ return dedent(
1343
+ """\
1344
+ #!/bin/bash
1345
+
1346
+ # Exit on any error. SageMaker uses error code to mark failed job.
1347
+ set -e
1348
+
1349
+ cd /opt/ml/processing/input/code/
1350
+
1351
+ # Debug: List files before extraction
1352
+ echo "Files in /opt/ml/processing/input/code/ before extraction:"
1353
+ ls -la
1354
+
1355
+ # Extract source code
1356
+ if [ -f sourcedir.tar.gz ]; then
1357
+ tar -xzf sourcedir.tar.gz
1358
+ echo "Files after extraction:"
1359
+ ls -la
1360
+ else
1361
+ echo "ERROR: sourcedir.tar.gz not found!"
1362
+ exit 1
1363
+ fi
1364
+
1365
+ if [[ -f 'requirements.txt' ]]; then
1366
+ # Some py3 containers has typing, which may breaks pip install
1367
+ pip uninstall --yes typing
1368
+
1369
+ pip install -r requirements.txt
1370
+ fi
1371
+
1372
+ {entry_point_command} {entry_point} "$@"
1373
+ """
1374
+ ).format(
1375
+ entry_point_command=" ".join(self.command),
1376
+ entry_point=user_script,
1377
+ )
1378
+
1379
+
1380
+ class FeatureStoreOutput(ApiObject):
1381
+ """Configuration for processing job outputs in Amazon SageMaker Feature Store."""
1382
+
1383
+ feature_group_name: Optional[str] = None
1384
+
1385
+
1386
+ def _processing_input_to_request_dict(processing_input):
1387
+ """Convert ProcessingInput to request dictionary format."""
1388
+ app_managed = getattr(processing_input, "app_managed", False)
1389
+ request_dict = {
1390
+ "InputName": processing_input.input_name,
1391
+ "AppManaged": app_managed if app_managed is not None else False,
1392
+ }
1393
+
1394
+ if processing_input.s3_input:
1395
+ request_dict["S3Input"] = {
1396
+ "S3Uri": processing_input.s3_input.s3_uri,
1397
+ "LocalPath": processing_input.s3_input.local_path,
1398
+ "S3DataType": processing_input.s3_input.s3_data_type or "S3Prefix",
1399
+ "S3InputMode": processing_input.s3_input.s3_input_mode or "File",
1400
+ "S3DataDistributionType": processing_input.s3_input.s3_data_distribution_type
1401
+ or "FullyReplicated",
1402
+ "S3CompressionType": processing_input.s3_input.s3_compression_type or "None",
1403
+ }
1404
+
1405
+ return request_dict
1406
+
1407
+
1408
+ def _processing_output_to_request_dict(processing_output):
1409
+ """Convert ProcessingOutput to request dictionary format."""
1410
+ app_managed = getattr(processing_output, "app_managed", False)
1411
+ request_dict = {
1412
+ "OutputName": processing_output.output_name,
1413
+ "AppManaged": app_managed if app_managed is not None else False,
1414
+ }
1415
+
1416
+ if processing_output.s3_output:
1417
+ request_dict["S3Output"] = {
1418
+ "S3Uri": processing_output.s3_output.s3_uri,
1419
+ "LocalPath": processing_output.s3_output.local_path,
1420
+ "S3UploadMode": processing_output.s3_output.s3_upload_mode,
1421
+ }
1422
+
1423
+ return request_dict
1424
+
1425
+
1426
+ def _get_process_request(
1427
+ inputs,
1428
+ output_config,
1429
+ job_name,
1430
+ resources,
1431
+ stopping_condition,
1432
+ app_specification,
1433
+ environment,
1434
+ network_config,
1435
+ role_arn,
1436
+ tags,
1437
+ experiment_config=None,
1438
+ ):
1439
+ """Constructs a request compatible for an Amazon SageMaker processing job.
1440
+
1441
+ Args:
1442
+ inputs ([dict]): List of up to 10 ProcessingInput dictionaries.
1443
+ output_config (dict): A config dictionary, which contains a list of up
1444
+ to 10 ProcessingOutput dictionaries, as well as an optional KMS key ID.
1445
+ job_name (str): The name of the processing job. The name must be unique
1446
+ within an AWS Region in an AWS account. Names should have minimum
1447
+ length of 1 and maximum length of 63 characters.
1448
+ resources (dict): Encapsulates the resources, including ML instances
1449
+ and storage, to use for the processing job.
1450
+ stopping_condition (dict[str,int]): Specifies a limit to how long
1451
+ the processing job can run, in seconds.
1452
+ app_specification (dict[str,str]): Configures the processing job to
1453
+ run the given image. Details are in the processing container
1454
+ specification.
1455
+ environment (dict): Environment variables to start the processing
1456
+ container with.
1457
+ network_config (dict): Specifies networking options, such as network
1458
+ traffic encryption between processing containers, whether to allow
1459
+ inbound and outbound network calls to and from processing containers,
1460
+ and VPC subnets and security groups to use for VPC-enabled processing
1461
+ jobs.
1462
+ role_arn (str): The Amazon Resource Name (ARN) of an IAM role that
1463
+ Amazon SageMaker can assume to perform tasks on your behalf.
1464
+ tags ([dict[str,str]]): A list of dictionaries containing key-value
1465
+ pairs.
1466
+ experiment_config (dict[str, str]): Experiment management configuration.
1467
+ Optionally, the dict can contain three keys:
1468
+ 'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
1469
+ The behavior of setting these keys is as follows:
1470
+ * If `ExperimentName` is supplied but `TrialName` is not a Trial will be
1471
+ automatically created and the job's Trial Component associated with the Trial.
1472
+ * If `TrialName` is supplied and the Trial already exists the job's Trial Component
1473
+ will be associated with the Trial.
1474
+ * If both `ExperimentName` and `TrialName` are not supplied the trial component
1475
+ will be unassociated.
1476
+ * `TrialComponentDisplayName` is used for display in Studio.
1477
+
1478
+ Returns:
1479
+ Dict: a processing job request dict
1480
+ """
1481
+ process_request = {
1482
+ "ProcessingJobName": job_name,
1483
+ "ProcessingResources": resources,
1484
+ "AppSpecification": app_specification,
1485
+ "RoleArn": role_arn,
1486
+ }
1487
+
1488
+ if inputs:
1489
+ process_request["ProcessingInputs"] = inputs
1490
+
1491
+ if output_config["Outputs"]:
1492
+ process_request["ProcessingOutputConfig"] = output_config
1493
+
1494
+ if environment is not None:
1495
+ process_request["Environment"] = environment
1496
+
1497
+ if network_config is not None:
1498
+ process_request["NetworkConfig"] = network_config
1499
+
1500
+ if stopping_condition is not None:
1501
+ process_request["StoppingCondition"] = stopping_condition
1502
+
1503
+ if tags is not None:
1504
+ process_request["Tags"] = tags
1505
+
1506
+ if experiment_config:
1507
+ process_request["ExperimentConfig"] = experiment_config
1508
+
1509
+ return process_request
1510
+
1511
+
1512
+ def logs_for_processing_job(sagemaker_session, job_name, wait=False, poll=10):
1513
+ """Display logs for a given processing job, optionally tailing them until the is complete.
1514
+
1515
+ Args:
1516
+ job_name (str): Name of the processing job to display the logs for.
1517
+ wait (bool): Whether to keep looking for new log entries until the job completes
1518
+ (default: False).
1519
+ poll (int): The interval in seconds between polling for new log entries and job
1520
+ completion (default: 5).
1521
+
1522
+ Raises:
1523
+ ValueError: If the processing job fails.
1524
+ """
1525
+
1526
+ description = _wait_until(
1527
+ lambda: ProcessingJob.get(
1528
+ processing_job_name=job_name, session=sagemaker_session.boto_session
1529
+ )
1530
+ .refresh()
1531
+ .__dict__,
1532
+ poll,
1533
+ )
1534
+
1535
+ instance_count, stream_names, positions, client, log_group, dot, color_wrap = _logs_init(
1536
+ sagemaker_session.boto_session, description, job="Processing"
1537
+ )
1538
+
1539
+ state = _get_initial_job_state(description, "ProcessingJobStatus", wait)
1540
+
1541
+ # The loop below implements a state machine that alternates between checking the job status
1542
+ # and reading whatever is available in the logs at this point. Note, that if we were
1543
+ # called with wait == False, we never check the job status.
1544
+ #
1545
+ # If wait == TRUE and job is not completed, the initial state is TAILING
1546
+ # If wait == FALSE, the initial state is COMPLETE (doesn't matter if the job really is
1547
+ # complete).
1548
+ #
1549
+ # The state table:
1550
+ #
1551
+ # STATE ACTIONS CONDITION NEW STATE
1552
+ # ---------------- ---------------- ----------------- ----------------
1553
+ # TAILING Read logs, Pause, Get status Job complete JOB_COMPLETE
1554
+ # Else TAILING
1555
+ # JOB_COMPLETE Read logs, Pause Any COMPLETE
1556
+ # COMPLETE Read logs, Exit N/A
1557
+ #
1558
+ # Notes:
1559
+ # - The JOB_COMPLETE state forces us to do an extra pause and read any items that got to
1560
+ # Cloudwatch after the job was marked complete.
1561
+ last_describe_job_call = time.time()
1562
+ while True:
1563
+ _flush_log_streams(
1564
+ stream_names,
1565
+ instance_count,
1566
+ client,
1567
+ log_group,
1568
+ job_name,
1569
+ positions,
1570
+ dot,
1571
+ color_wrap,
1572
+ )
1573
+ if state == LogState.COMPLETE:
1574
+ break
1575
+
1576
+ time.sleep(poll)
1577
+
1578
+ if state == LogState.JOB_COMPLETE:
1579
+ state = LogState.COMPLETE
1580
+ elif time.time() - last_describe_job_call >= 30:
1581
+ description = (
1582
+ ProcessingJob.get(
1583
+ processing_job_name=job_name, session=sagemaker_session.boto_session
1584
+ )
1585
+ .refresh()
1586
+ .__dict__
1587
+ )
1588
+ last_describe_job_call = time.time()
1589
+
1590
+ status = description["ProcessingJobStatus"]
1591
+
1592
+ if status in ("Completed", "Failed", "Stopped"):
1593
+ print()
1594
+ state = LogState.JOB_COMPLETE
1595
+
1596
+ if wait:
1597
+ _check_job_status(job_name, description, "ProcessingJobStatus")
1598
+ if dot:
1599
+ print()