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,2121 @@
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
+ """Helper classes that interact with SageMaker Training service."""
14
+ from __future__ import absolute_import
15
+
16
+ import dataclasses
17
+ import json
18
+ import os
19
+ import re
20
+ import shutil
21
+ import sys
22
+ import time
23
+ from io import BytesIO
24
+ from typing import Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING
25
+ from urllib.parse import urlparse
26
+
27
+ import botocore
28
+ from botocore.exceptions import ClientError
29
+
30
+ from sagemaker.core.config.config_schema import (
31
+ REMOTE_FUNCTION_ENVIRONMENT_VARIABLES,
32
+ REMOTE_FUNCTION_IMAGE_URI,
33
+ REMOTE_FUNCTION_DEPENDENCIES,
34
+ REMOTE_FUNCTION_PRE_EXECUTION_COMMANDS,
35
+ REMOTE_FUNCTION_PRE_EXECUTION_SCRIPT,
36
+ REMOTE_FUNCTION_INCLUDE_LOCAL_WORKDIR,
37
+ REMOTE_FUNCTION_INSTANCE_TYPE,
38
+ REMOTE_FUNCTION_JOB_CONDA_ENV,
39
+ REMOTE_FUNCTION_ROLE_ARN,
40
+ REMOTE_FUNCTION_S3_ROOT_URI,
41
+ REMOTE_FUNCTION_S3_KMS_KEY_ID,
42
+ REMOTE_FUNCTION_VOLUME_KMS_KEY_ID,
43
+ REMOTE_FUNCTION_TAGS,
44
+ REMOTE_FUNCTION_VPC_CONFIG_SUBNETS,
45
+ REMOTE_FUNCTION_VPC_CONFIG_SECURITY_GROUP_IDS,
46
+ REMOTE_FUNCTION_ENABLE_INTER_CONTAINER_TRAFFIC_ENCRYPTION,
47
+ )
48
+ from sagemaker.core.experiments._run_context import _RunContext
49
+ from sagemaker.core.experiments.run import Run
50
+ from sagemaker.core.image_uris import get_base_python_image_uri
51
+ from sagemaker.core import image_uris
52
+ from sagemaker.core.remote_function.checkpoint_location import CheckpointLocation
53
+ from sagemaker.core.helper.session_helper import get_execution_role, expand_role, Session
54
+ from sagemaker.core.common_utils import (
55
+ name_from_base,
56
+ _tmpdir,
57
+ resolve_value_from_config,
58
+ format_tags,
59
+ Tags,
60
+ )
61
+ from sagemaker.core.s3 import s3_path_join, S3Uploader
62
+
63
+ from sagemaker.core.remote_function.core.stored_function import StoredFunction, _SerializedData
64
+ from sagemaker.core.remote_function.core.pipeline_variables import Context
65
+
66
+ from sagemaker.core.remote_function.runtime_environment.runtime_environment_manager import (
67
+ RuntimeEnvironmentManager,
68
+ _DependencySettings,
69
+ )
70
+ from sagemaker.core.remote_function import logging_config
71
+ from sagemaker.core.remote_function.spark_config import SparkConfig
72
+ from sagemaker.core.remote_function.custom_file_filter import (
73
+ CustomFileFilter,
74
+ copy_workdir,
75
+ resolve_custom_file_filter_from_config_file,
76
+ )
77
+
78
+ # Lazy import to avoid circular dependency - DelayedReturn is in MLOps which depends on Core
79
+ # from sagemaker.mlops.workflow.function_step import DelayedReturn
80
+ from sagemaker.core.workflow.step_outputs import get_step
81
+ from sagemaker.core import exceptions
82
+ from sagemaker.core import network as vpc_utils
83
+
84
+ from sagemaker.core import logs as sagemaker_logs
85
+
86
+ from sagemaker.core.common_utils import (
87
+ _wait_until,
88
+ secondary_training_status_changed,
89
+ secondary_training_status_message,
90
+ )
91
+ from sagemaker.core.config.config_utils import _append_sagemaker_config_tags
92
+
93
+ if TYPE_CHECKING:
94
+ from sagemaker.core.helper.pipeline_variable import PipelineVariable
95
+
96
+ # runtime script names
97
+ BOOTSTRAP_SCRIPT_NAME = "bootstrap_runtime_environment.py"
98
+ MPI_UTILS_SCRIPT_NAME = "mpi_utils_remote.py"
99
+ ENTRYPOINT_SCRIPT_NAME = "job_driver.sh"
100
+ PRE_EXECUTION_SCRIPT_NAME = "pre_exec.sh"
101
+ RUNTIME_MANAGER_SCRIPT_NAME = "runtime_environment_manager.py"
102
+ SPARK_APP_SCRIPT_NAME = "spark_app.py"
103
+
104
+ # training channel names
105
+ RUNTIME_SCRIPTS_CHANNEL_NAME = "sagemaker_remote_function_bootstrap"
106
+ REMOTE_FUNCTION_WORKSPACE = "sm_rf_user_ws"
107
+ JOB_REMOTE_FUNCTION_WORKSPACE = "sagemaker_remote_function_workspace"
108
+ SCRIPT_AND_DEPENDENCIES_CHANNEL_NAME = "pre_exec_script_and_dependencies"
109
+
110
+ # Spark config channel and file name
111
+ SPARK_CONF_CHANNEL_NAME = "conf"
112
+ SPARK_CONF_FILE_NAME = "configuration.json"
113
+
114
+ # Spark submitted files workspace names on S3
115
+ SPARK_SUBMIT_JARS_WORKSPACE = "sm_rf_spark_jars"
116
+ SPARK_SUBMIT_PY_FILES_WORKSPACE = "sm_rf_spark_py_files"
117
+ SPARK_SUBMIT_FILES_WORKSPACE = "sm_rf_spark_data_files"
118
+ SPARK_CONF_WORKSPACE = "sm_rf_spark_conf"
119
+
120
+ # default spark version
121
+ DEFAULT_SPARK_VERSION = "3.3"
122
+ DEFAULT_SPARK_CONTAINER_VERSION = "v1"
123
+
124
+ SPARK_NAME = "spark"
125
+
126
+ # run context dictionary keys
127
+ KEY_EXPERIMENT_NAME = "experiment_name"
128
+ KEY_RUN_NAME = "run_name"
129
+
130
+ JOBS_CONTAINER_ENTRYPOINT = [
131
+ "/bin/bash",
132
+ f"/opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{ENTRYPOINT_SCRIPT_NAME}",
133
+ ]
134
+
135
+ SPARK_APP_SCRIPT_PATH = f"/opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{SPARK_APP_SCRIPT_NAME}"
136
+
137
+ ENTRYPOINT_SCRIPT = f"""
138
+ #!/bin/bash
139
+
140
+ # Entry point for bootstrapping runtime environment and invoking remote function
141
+
142
+ set -eu
143
+
144
+ PERSISTENT_CACHE_DIR=${{SAGEMAKER_MANAGED_WARMPOOL_CACHE_DIRECTORY:-/opt/ml/cache}}
145
+ export CONDA_PKGS_DIRS=${{PERSISTENT_CACHE_DIR}}/sm_remotefunction_user_dependencies_cache/conda/pkgs
146
+ printf "INFO: CONDA_PKGS_DIRS is set to '$CONDA_PKGS_DIRS'\\n"
147
+ export PIP_CACHE_DIR=${{PERSISTENT_CACHE_DIR}}/sm_remotefunction_user_dependencies_cache/pip
148
+ printf "INFO: PIP_CACHE_DIR is set to '$PIP_CACHE_DIR'\\n"
149
+
150
+ printf "INFO: /opt/ml/input/config/resourceconfig.json:\\n"
151
+ cat /opt/ml/input/config/resourceconfig.json
152
+
153
+ printf "INFO: Bootstraping runtime environment.\\n"
154
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{BOOTSTRAP_SCRIPT_NAME} "$@"
155
+ source /opt/ml/input/sm_training.env
156
+
157
+ if [ -d {JOB_REMOTE_FUNCTION_WORKSPACE} ]
158
+ then
159
+ if [ -f "remote_function_conda_env.txt" ]
160
+ then
161
+ cp remote_function_conda_env.txt {JOB_REMOTE_FUNCTION_WORKSPACE}/remote_function_conda_env.txt
162
+ fi
163
+ printf "INFO: Changing workspace to {JOB_REMOTE_FUNCTION_WORKSPACE}.\\n"
164
+ cd {JOB_REMOTE_FUNCTION_WORKSPACE}
165
+ fi
166
+
167
+ if [ -f "remote_function_conda_env.txt" ]
168
+ then
169
+ conda_env=$(cat remote_function_conda_env.txt)
170
+
171
+ if which mamba >/dev/null; then
172
+ conda_exe="mamba"
173
+ else
174
+ conda_exe="conda"
175
+ fi
176
+
177
+ printf "INFO: Invoking remote function inside conda environment: $conda_env.\\n"
178
+ printf "INFO: $conda_exe run -n $conda_env python -m sagemaker.train.remote_function.invoke_function \\n"
179
+ $conda_exe run -n $conda_env python -m sagemaker.train.remote_function.invoke_function "$@"
180
+ else
181
+ printf "INFO: No conda env provided. Invoking remote function\\n"
182
+ printf "INFO: python -m sagemaker.train.remote_function.invoke_function \\n"
183
+ python -m sagemaker.train.remote_function.invoke_function "$@"
184
+ fi
185
+ """
186
+
187
+ ENTRYPOINT_MPIRUN_SCRIPT = f"""
188
+ #!/bin/bash
189
+
190
+ # Entry point for bootstrapping runtime environment and invoking remote function with mpirun
191
+
192
+ set -eu
193
+
194
+ PERSISTENT_CACHE_DIR=${{SAGEMAKER_MANAGED_WARMPOOL_CACHE_DIRECTORY:-/opt/ml/cache}}
195
+ export CONDA_PKGS_DIRS=${{PERSISTENT_CACHE_DIR}}/sm_remotefunction_user_dependencies_cache/conda/pkgs
196
+ printf "INFO: CONDA_PKGS_DIRS is set to '$CONDA_PKGS_DIRS'\\n"
197
+ export PIP_CACHE_DIR=${{PERSISTENT_CACHE_DIR}}/sm_remotefunction_user_dependencies_cache/pip
198
+ printf "INFO: PIP_CACHE_DIR is set to '$PIP_CACHE_DIR'\\n"
199
+
200
+ printf "INFO: /opt/ml/input/config/resourceconfig.json:\\n"
201
+ cat /opt/ml/input/config/resourceconfig.json
202
+
203
+ printf "INFO: Bootstraping runtime environment.\\n"
204
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{BOOTSTRAP_SCRIPT_NAME} "$@"
205
+ source /opt/ml/input/sm_training.env
206
+
207
+ if [ -d {JOB_REMOTE_FUNCTION_WORKSPACE} ]
208
+ then
209
+ if [ -f "remote_function_conda_env.txt" ]
210
+ then
211
+ cp remote_function_conda_env.txt {JOB_REMOTE_FUNCTION_WORKSPACE}/remote_function_conda_env.txt
212
+ fi
213
+ printf "INFO: Changing workspace to {JOB_REMOTE_FUNCTION_WORKSPACE}.\\n"
214
+ cd {JOB_REMOTE_FUNCTION_WORKSPACE}
215
+ fi
216
+
217
+ if [ -f "remote_function_conda_env.txt" ]
218
+ then
219
+ conda_env=$(cat remote_function_conda_env.txt)
220
+
221
+ if which mamba >/dev/null; then
222
+ conda_exe="mamba"
223
+ else
224
+ conda_exe="conda"
225
+ fi
226
+
227
+ if [ "$SM_CURRENT_HOST" = "$SM_MASTER_ADDR" ]; then
228
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{MPI_UTILS_SCRIPT_NAME}
229
+
230
+ printf "INFO: Invoking remote function with mpirun inside conda environment: $conda_env.\\n"
231
+ printf "INFO: $conda_exe run -n $conda_env mpirun --host $SM_HOSTS_LIST -np $SM_NPROC_PER_NODE \
232
+ --allow-run-as-root --display-map --tag-output -mca btl_tcp_if_include $SM_NETWORK_INTERFACE_NAME \
233
+ -mca plm_rsh_no_tree_spawn 1 -mca pml ob1 -mca btl ^openib -mca orte_abort_on_non_zero_status 1 \
234
+ -mca btl_vader_single_copy_mechanism none -mca plm_rsh_num_concurrent $SM_HOST_COUNT \
235
+ -x NCCL_SOCKET_IFNAME=$SM_NETWORK_INTERFACE_NAME -x LD_LIBRARY_PATH -x PATH \
236
+
237
+ python -m mpi4py -m sagemaker.train.remote_function.invoke_function \\n"
238
+ $conda_exe run -n $conda_env mpirun --host $SM_HOSTS_LIST -np $SM_NPROC_PER_NODE \
239
+ --allow-run-as-root --display-map --tag-output -mca btl_tcp_if_include $SM_NETWORK_INTERFACE_NAME \
240
+ -mca plm_rsh_no_tree_spawn 1 -mca pml ob1 -mca btl ^openib -mca orte_abort_on_non_zero_status 1 \
241
+ -mca btl_vader_single_copy_mechanism none -mca plm_rsh_num_concurrent $SM_HOST_COUNT \
242
+ -x NCCL_SOCKET_IFNAME=$SM_NETWORK_INTERFACE_NAME -x LD_LIBRARY_PATH -x PATH \
243
+ $SM_FI_PROVIDER $SM_NCCL_PROTO $SM_FI_EFA_USE_DEVICE_RDMA \
244
+ python -m mpi4py -m sagemaker.train.remote_function.invoke_function "$@"
245
+
246
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{MPI_UTILS_SCRIPT_NAME} --job_ended 1
247
+ else
248
+ printf "INFO: This is the instance $SM_CURRENT_HOST. mpirun command terminated\\n"
249
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{MPI_UTILS_SCRIPT_NAME}
250
+ fi
251
+ else
252
+ if [ "$SM_CURRENT_HOST" = "$SM_MASTER_ADDR" ]; then
253
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{MPI_UTILS_SCRIPT_NAME}
254
+
255
+ printf "INFO: No conda env provided. Invoking remote function with mpirun\\n"
256
+ printf "INFO: mpirun --host $SM_HOSTS_LIST -np $SM_NPROC_PER_NODE \
257
+ --allow-run-as-root --display-map --tag-output -mca btl_tcp_if_include $SM_NETWORK_INTERFACE_NAME \
258
+ -mca plm_rsh_no_tree_spawn 1 -mca pml ob1 -mca btl ^openib -mca orte_abort_on_non_zero_status 1 \
259
+ -mca btl_vader_single_copy_mechanism none -mca plm_rsh_num_concurrent $SM_HOST_COUNT \
260
+ -x NCCL_SOCKET_IFNAME=$SM_NETWORK_INTERFACE_NAME -x LD_LIBRARY_PATH -x PATH \
261
+ $SM_FI_PROVIDER $SM_NCCL_PROTO $SM_FI_EFA_USE_DEVICE_RDMA \
262
+ python -m mpi4py -m sagemaker.train.remote_function.invoke_function \\n"
263
+
264
+ mpirun --host $SM_HOSTS_LIST -np $SM_NPROC_PER_NODE \
265
+ --allow-run-as-root --display-map --tag-output -mca btl_tcp_if_include $SM_NETWORK_INTERFACE_NAME \
266
+ -mca plm_rsh_no_tree_spawn 1 -mca pml ob1 -mca btl ^openib -mca orte_abort_on_non_zero_status 1 \
267
+ -mca btl_vader_single_copy_mechanism none -mca plm_rsh_num_concurrent $SM_HOST_COUNT \
268
+ -x NCCL_SOCKET_IFNAME=$SM_NETWORK_INTERFACE_NAME -x LD_LIBRARY_PATH -x PATH \
269
+ $SM_FI_PROVIDER $SM_NCCL_PROTO $SM_FI_EFA_USE_DEVICE_RDMA \
270
+ python -m mpi4py -m sagemaker.train.remote_function.invoke_function "$@"
271
+
272
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{MPI_UTILS_SCRIPT_NAME} --job_ended 1
273
+ else
274
+ printf "INFO: This is the instance $SM_CURRENT_HOST.\\n"
275
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{MPI_UTILS_SCRIPT_NAME}
276
+ fi
277
+ fi
278
+ """
279
+
280
+ ENTRYPOINT_TORCHRUN_SCRIPT = f"""
281
+ #!/bin/bash
282
+
283
+ # Entry point for bootstrapping runtime environment and invoking remote function with torchrun
284
+
285
+ set -eu
286
+
287
+ PERSISTENT_CACHE_DIR=${{SAGEMAKER_MANAGED_WARMPOOL_CACHE_DIRECTORY:-/opt/ml/cache}}
288
+ export CONDA_PKGS_DIRS=${{PERSISTENT_CACHE_DIR}}/sm_remotefunction_user_dependencies_cache/conda/pkgs
289
+ printf "INFO: CONDA_PKGS_DIRS is set to '$CONDA_PKGS_DIRS'\\n"
290
+ export PIP_CACHE_DIR=${{PERSISTENT_CACHE_DIR}}/sm_remotefunction_user_dependencies_cache/pip
291
+ printf "INFO: PIP_CACHE_DIR is set to '$PIP_CACHE_DIR'\\n"
292
+
293
+ printf "INFO: /opt/ml/input/config/resourceconfig.json:\\n"
294
+ cat /opt/ml/input/config/resourceconfig.json
295
+
296
+ printf "INFO: Bootstraping runtime environment.\\n"
297
+ python /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{BOOTSTRAP_SCRIPT_NAME} "$@"
298
+ source /opt/ml/input/sm_training.env
299
+
300
+ if [ -d {JOB_REMOTE_FUNCTION_WORKSPACE} ]
301
+ then
302
+ if [ -f "remote_function_conda_env.txt" ]
303
+ then
304
+ cp remote_function_conda_env.txt {JOB_REMOTE_FUNCTION_WORKSPACE}/remote_function_conda_env.txt
305
+ fi
306
+ printf "INFO: Changing workspace to {JOB_REMOTE_FUNCTION_WORKSPACE}.\\n"
307
+ cd {JOB_REMOTE_FUNCTION_WORKSPACE}
308
+ fi
309
+
310
+ if [ -f "remote_function_conda_env.txt" ]
311
+ then
312
+ conda_env=$(cat remote_function_conda_env.txt)
313
+
314
+ if which mamba >/dev/null; then
315
+ conda_exe="mamba"
316
+ else
317
+ conda_exe="conda"
318
+ fi
319
+
320
+ printf "INFO: Invoking remote function with torchrun inside conda environment: $conda_env.\\n"
321
+ printf "INFO: $conda_exe run -n $conda_env torchrun --nnodes $SM_HOST_COUNT --nproc_per_node $SM_NPROC_PER_NODE \
322
+ --master_addr $SM_MASTER_ADDR --master_port $SM_MASTER_PORT --node_rank $SM_CURRENT_HOST_RANK \
323
+ -m sagemaker.train.remote_function.invoke_function \\n"
324
+
325
+ $conda_exe run -n $conda_env torchrun --nnodes $SM_HOST_COUNT --nproc_per_node $SM_NPROC_PER_NODE \
326
+ --master_addr $SM_MASTER_ADDR --master_port $SM_MASTER_PORT --node_rank $SM_CURRENT_HOST_RANK \
327
+ -m sagemaker.train.remote_function.invoke_function "$@"
328
+ else
329
+ printf "INFO: No conda env provided. Invoking remote function with torchrun\\n"
330
+ printf "INFO: torchrun --nnodes $SM_HOST_COUNT --nproc_per_node $SM_NPROC_PER_NODE --master_addr $SM_MASTER_ADDR \
331
+ --master_port $SM_MASTER_PORT --node_rank $SM_CURRENT_HOST_RANK -m sagemaker.train.remote_function.invoke_function \\n"
332
+
333
+ torchrun --nnodes $SM_HOST_COUNT --nproc_per_node $SM_NPROC_PER_NODE --master_addr $SM_MASTER_ADDR \
334
+ --master_port $SM_MASTER_PORT --node_rank $SM_CURRENT_HOST_RANK -m sagemaker.train.remote_function.invoke_function "$@"
335
+ fi
336
+ """
337
+
338
+ SPARK_ENTRYPOINT_SCRIPT = f"""
339
+ #!/bin/bash
340
+
341
+ # Entry point for bootstrapping runtime environment and invoking remote function for Spark
342
+
343
+ set -eu
344
+
345
+ printf "INFO: Bootstraping Spark runtime environment.\\n"
346
+
347
+ python3 /opt/ml/input/data/{RUNTIME_SCRIPTS_CHANNEL_NAME}/{BOOTSTRAP_SCRIPT_NAME} "$@"
348
+
349
+ # Spark Container entry point script to initiate the spark application
350
+ smspark-submit "$@"
351
+ """
352
+
353
+ _STATUS_CODE_TABLE = {
354
+ "COMPLETED": "Completed",
355
+ "INPROGRESS": "InProgress",
356
+ "IN_PROGRESS": "InProgress",
357
+ "FAILED": "Failed",
358
+ "STOPPED": "Stopped",
359
+ "STOPPING": "Stopping",
360
+ "STARTING": "Starting",
361
+ "PENDING": "Pending",
362
+ }
363
+
364
+ logger = logging_config.get_logger()
365
+
366
+
367
+ class LogState(object):
368
+ """Placeholder docstring"""
369
+
370
+ STARTING = 1
371
+ WAIT_IN_PROGRESS = 2
372
+ TAILING = 3
373
+ JOB_COMPLETE = 4
374
+ COMPLETE = 5
375
+
376
+
377
+ class _JobSettings:
378
+ """Helper class that processes the job settings.
379
+
380
+ It validates the job settings and provides default values if necessary.
381
+ """
382
+
383
+ def __init__(
384
+ self,
385
+ *,
386
+ dependencies: str = None,
387
+ pre_execution_commands: List[str] = None,
388
+ pre_execution_script: str = None,
389
+ environment_variables: Dict[str, Union[str, "PipelineVariable"]] = None,
390
+ image_uri: Union[str, "PipelineVariable"] = None,
391
+ include_local_workdir: bool = None,
392
+ custom_file_filter: Optional[Union[Callable[[str, List], List], CustomFileFilter]] = None,
393
+ instance_count: Union[int, "PipelineVariable"] = 1,
394
+ instance_type: Union[str, "PipelineVariable"] = None,
395
+ job_conda_env: Union[str, "PipelineVariable"] = None,
396
+ job_name_prefix: str = None,
397
+ keep_alive_period_in_seconds: Union[int, "PipelineVariable"] = 0,
398
+ max_retry_attempts: Union[int, "PipelineVariable"] = 1,
399
+ max_runtime_in_seconds: Union[int, "PipelineVariable"] = 24 * 60 * 60,
400
+ role: str = None,
401
+ s3_kms_key: Union[str, "PipelineVariable"] = None,
402
+ s3_root_uri: str = None,
403
+ sagemaker_session: Session = None,
404
+ security_group_ids: List[Union[str, "PipelineVariable"]] = None,
405
+ subnets: List[Union[str, "PipelineVariable"]] = None,
406
+ tags: Optional[Tags] = None,
407
+ volume_kms_key: Union[str, "PipelineVariable"] = None,
408
+ volume_size: Union[int, "PipelineVariable"] = 30,
409
+ encrypt_inter_container_traffic: Union[bool, "PipelineVariable"] = None,
410
+ spark_config: SparkConfig = None,
411
+ use_spot_instances=False,
412
+ max_wait_time_in_seconds=None,
413
+ disable_output_compression: bool = False,
414
+ use_torchrun: bool = False,
415
+ use_mpirun: bool = False,
416
+ nproc_per_node: Optional[int] = None,
417
+ ):
418
+ """Initialize a _JobSettings instance which configures the remote job.
419
+
420
+ Args:
421
+ dependencies (str): Either the path to a dependencies file or the reserved keyword
422
+ ``auto_capture``. Defaults to ``None``.
423
+ If ``dependencies`` is provided, the value must be one of the following:
424
+
425
+ * A path to a conda environment.yml file. The following conditions apply.
426
+
427
+ * If job_conda_env is set, then the conda environment is updated by installing
428
+ dependencies from the yaml file and the function is invoked within that
429
+ conda environment. For this to succeed, the specified conda environment must
430
+ already exist in the image.
431
+ * If the environment variable ``SAGEMAKER_JOB_CONDA_ENV`` is set in the image,
432
+ then the conda environment is updated by installing dependencies from the
433
+ yaml file and the function is invoked within that conda environment. For
434
+ this to succeed, the conda environment name must already be set in
435
+ ``SAGEMAKER_JOB_CONDA_ENV``, and ``SAGEMAKER_JOB_CONDA_ENV`` must already
436
+ exist in the image.
437
+ * If none of the previous conditions are met, a new conda environment named
438
+ ``sagemaker-runtime-env`` is created and the function annotated with the remote
439
+ decorator is invoked in that conda environment.
440
+
441
+ * A path to a requirements.txt file. The following conditions apply.
442
+
443
+ * If ``job_conda_env`` is set in the remote decorator, dependencies are installed
444
+ within that conda environment and the function annotated with the remote decorator
445
+ is invoked in the same conda environment. For this to succeed, the specified
446
+ conda environment must already exist in the image.
447
+ * If an environment variable ``SAGEMAKER_JOB_CONDA_ENV`` is set in the image,
448
+ dependencies are installed within that conda environment and the function
449
+ annotated with the remote decorator is invoked in the same. For this to succeed,
450
+ the conda environment name must already be set in ``SAGEMAKER_JOB_CONDA_ENV``, and
451
+ ``SAGEMAKER_JOB_CONDA_ENV`` must already exist in the image.
452
+ * If none of the above conditions are met, conda is not used. Dependencies are
453
+ installed at the system level, without any virtual environment, and the function
454
+ annotated with the remote decorator is invoked using the Python runtime available
455
+ in the system path.
456
+
457
+ * The parameter dependencies is set to ``auto_capture``. SageMaker will automatically
458
+ generate an env_snapshot.yml corresponding to the current active conda environment’s
459
+ snapshot. You do not need to provide a dependencies file. The following conditions
460
+ apply:
461
+
462
+ * You must run the remote function within an active conda environment.
463
+ * When installing the dependencies on the training job, the same conditions
464
+ as when dependencies is set to a path to a conda environment file apply.
465
+ These conditions are as follows:
466
+
467
+ * If job_conda_env is set, then the conda environment is updated by installing
468
+ dependencies from the yaml file and the function is invoked within that
469
+ conda environment. For this to succeed, the specified conda environment must
470
+ already exist in the image.
471
+ * If the environment variable ``SAGEMAKER_JOB_CONDA_ENV`` is set in the image,
472
+ then the conda environment is updated by installing dependencies from the yaml
473
+ file and the function is invoked within that conda environment. For this to
474
+ succeed, the conda environment name must already be set in
475
+ ``SAGEMAKER_JOB_CONDA_ENV``, and ``SAGEMAKER_JOB_CONDA_ENV`` must already exist
476
+ in the image.
477
+ * If none of the previous conditions are met, a new conda environment with name
478
+ ``sagemaker-runtime-env`` is created and the function annotated with the
479
+ remote decorator is invoked in that conda environment.
480
+
481
+ * ``None``. SageMaker will assume that there are no dependencies to install while
482
+ executing the remote annotated function in the training job.
483
+
484
+ pre_execution_commands (List[str]): List of commands to be executed prior to executing
485
+ remote function. Only one of ``pre_execution_commands`` or ``pre_execution_script``
486
+ can be specified at the same time. Defaults to None.
487
+
488
+ pre_execution_script (str): Path to script file to be executed prior to executing
489
+ remote function. Only one of ``pre_execution_commands`` or ``pre_execution_script``
490
+ can be specified at the same time. Defaults to None.
491
+
492
+ environment_variables (dict[str, str] or dict[str, PipelineVariable]): The environment
493
+ variables used inside the decorator function. Defaults to ``None``.
494
+
495
+ image_uri (str, PipelineVariable): The universal resource identifier (URI) location of
496
+ a Docker image on Amazon Elastic Container Registry (ECR). Defaults to the following
497
+ based on where the SDK is running:
498
+
499
+ * For users who specify ``spark_config`` and want to run the function in a Spark
500
+ application, the ``image_uri`` should be ``None``. A SageMaker Spark image will
501
+ be used for training, otherwise a ``ValueError`` is thrown.
502
+ * For users on SageMaker Studio notebooks, the image used as the kernel image for
503
+ the notebook is used.
504
+ * For other users, it is resolved to base python image with the same python version
505
+ as the environment running the local code.
506
+
507
+ If no compatible image is found, a ValueError is thrown.
508
+
509
+ include_local_workdir (bool): A flag to indicate that the remote function should include
510
+ local directories. Set to ``True`` if the remote function code imports local modules
511
+ and methods that are not available via PyPI or conda. Default value is ``False``.
512
+
513
+ custom_file_filter (Callable[[str, List], List], CustomFileFilter): Either a function
514
+ that filters job dependencies to be uploaded to S3 or a ``CustomFileFilter`` object
515
+ that specifies the local directories and files to be included in the remote function.
516
+ If a callable is passed in, that function is passed to the ``ignore`` argument of
517
+ ``shutil.copytree``. Defaults to ``None``, which means only python
518
+ files are accepted and uploaded to S3.
519
+
520
+ instance_count (int, PipelineVariable): The number of instances to use. Defaults to 1.
521
+
522
+ instance_type (str, PipelineVariable): The Amazon Elastic Compute Cloud (EC2) instance
523
+ type to use to run the SageMaker job. e.g. ml.c4.xlarge. If not provided,
524
+ a ValueError is thrown.
525
+
526
+ job_conda_env (str, PipelineVariable): The name of the conda environment to activate
527
+ during job's runtime. Defaults to ``None``.
528
+
529
+ job_name_prefix (str, PipelineVariable): The prefix used to create the underlying
530
+ SageMaker job.
531
+
532
+ keep_alive_period_in_seconds (int, PipelineVariable): The duration in seconds to retain
533
+ and reuse provisioned infrastructure after the completion of a training job, also
534
+ known as SageMaker managed warm pools. The use of warm pools reduces the latency time
535
+ spent to provision new resources. The default value for
536
+ ``keep_alive_period_in_seconds`` is 0.
537
+ NOTE: Additional charges associated with warm pools may apply. Using this parameter
538
+ also activates a new persistent cache feature, which will further reduce job start up
539
+ latency than over using SageMaker managed warm pools alone by caching the package
540
+ source downloaded in the previous runs.
541
+
542
+ max_retry_attempts (int, PipelineVariable): The max number of times the job is retried
543
+ on ``InternalServerFailure`` Error from SageMaker service. Defaults to 1.
544
+
545
+ max_runtime_in_seconds (int, PipelineVariable): The upper limit in seconds to be used
546
+ for training. After this specified amount of time, SageMaker terminates the job
547
+ regardless of its current status. Defaults to 1 day or (86400 seconds).
548
+
549
+ role (str): The IAM role (either name or full ARN) used to run your SageMaker training
550
+ job. Defaults to:
551
+
552
+ * the SageMaker default IAM role if the SDK is running in SageMaker Notebooks or
553
+ SageMaker Studio Notebooks.
554
+ * if not above, a ValueError is thrown.
555
+
556
+ s3_kms_key (str): The key used to encrypt the input and output data.
557
+ Default to ``None``.
558
+
559
+ s3_root_uri (str): The root S3 folder to which the code archives and data are
560
+ uploaded to. Defaults to ``s3://<sagemaker-default-bucket>``.
561
+
562
+ sagemaker_session (sagemaker.core.helper.session.Session): The underlying SageMaker session to
563
+ which SageMaker service calls are delegated to (default: None). If not provided,
564
+ one is created using a default configuration chain.
565
+
566
+ security_group_ids (List[str, PipelineVariable]): A list of security group IDs.
567
+ Defaults to ``None`` and the training job is created without VPC config.
568
+
569
+ subnets (List[str, PipelineVariable]): A list of subnet IDs. Defaults to ``None``
570
+ and the job is created without VPC config.
571
+
572
+ tags (Optional[Tags]): Tags attached to the job. Defaults to ``None``
573
+ and the training job is created without tags.
574
+
575
+ volume_kms_key (str, PipelineVariable): An Amazon Key Management Service (KMS) key
576
+ used to encrypt an Amazon Elastic Block Storage (EBS) volume attached to the
577
+ training instance. Defaults to ``None``.
578
+
579
+ volume_size (int, PipelineVariable): The size in GB of the storage volume for storing
580
+ input and output data during training. Defaults to ``30``.
581
+
582
+ encrypt_inter_container_traffic (bool, PipelineVariable): A flag that specifies
583
+ whether traffic between training containers is encrypted for the training job.
584
+ Defaults to ``False``.
585
+
586
+ spark_config (SparkConfig): Configurations to the Spark application that runs on
587
+ Spark image. If ``spark_config`` is specified, a SageMaker Spark image uri
588
+ will be used for training. Note that ``image_uri`` can not be specified at the
589
+ same time otherwise a ``ValueError`` is thrown. Defaults to ``None``.
590
+
591
+ use_spot_instances (bool, PipelineVariable): Specifies whether to use SageMaker
592
+ Managed Spot instances for training. If enabled then the ``max_wait`` arg should
593
+ also be set. Defaults to ``False``.
594
+
595
+ max_wait_time_in_seconds (int): Timeout in seconds waiting for spot training job.
596
+ After this amount of time Amazon SageMaker will stop waiting for managed spot
597
+ training job to complete. Defaults to ``None``.
598
+
599
+ disable_output_compression (bool): Optional. When set to true, Model is uploaded to
600
+ Amazon S3 without compression after training finishes.
601
+
602
+ use_torchrun (bool): Specifies whether to use torchrun for distributed training.
603
+ Defaults to ``False``.
604
+
605
+ use_mpirun (bool): Specifies whether to use mpirun for distributed training.
606
+ Defaults to ``False``.
607
+
608
+ nproc_per_node (int): Optional. Specifies the number of processes per node for
609
+ distributed training. Defaults to ``None``.
610
+ This is defined automatically configured on the instance type.
611
+ """
612
+ self.sagemaker_session = sagemaker_session or Session()
613
+ self.environment_variables = resolve_value_from_config(
614
+ direct_input=environment_variables,
615
+ config_path=REMOTE_FUNCTION_ENVIRONMENT_VARIABLES,
616
+ default_value={},
617
+ sagemaker_session=self.sagemaker_session,
618
+ )
619
+ self.environment_variables.update(
620
+ {"AWS_DEFAULT_REGION": self.sagemaker_session.boto_region_name}
621
+ )
622
+
623
+ if spark_config and image_uri:
624
+ raise ValueError("spark_config and image_uri cannot be specified at the same time!")
625
+
626
+ if spark_config and job_conda_env:
627
+ raise ValueError("Remote Spark jobs do not support job_conda_env.")
628
+
629
+ if spark_config and dependencies == "auto_capture":
630
+ raise ValueError(
631
+ "Remote Spark jobs do not support automatically capturing dependencies."
632
+ )
633
+
634
+ _image_uri = resolve_value_from_config(
635
+ direct_input=image_uri,
636
+ config_path=REMOTE_FUNCTION_IMAGE_URI,
637
+ sagemaker_session=self.sagemaker_session,
638
+ )
639
+
640
+ if spark_config:
641
+ self.image_uri = self._get_default_spark_image(self.sagemaker_session)
642
+ logger.info(
643
+ "Set the image uri as %s because value of spark_config is "
644
+ "indicating this is a remote spark job.",
645
+ self.image_uri,
646
+ )
647
+ elif _image_uri:
648
+ self.image_uri = _image_uri
649
+ else:
650
+ self.image_uri = self._get_default_image(self.sagemaker_session)
651
+
652
+ self.dependencies = resolve_value_from_config(
653
+ direct_input=dependencies,
654
+ config_path=REMOTE_FUNCTION_DEPENDENCIES,
655
+ sagemaker_session=self.sagemaker_session,
656
+ )
657
+
658
+ self.pre_execution_commands = resolve_value_from_config(
659
+ direct_input=pre_execution_commands,
660
+ config_path=REMOTE_FUNCTION_PRE_EXECUTION_COMMANDS,
661
+ sagemaker_session=self.sagemaker_session,
662
+ )
663
+
664
+ self.pre_execution_script = resolve_value_from_config(
665
+ direct_input=pre_execution_script,
666
+ config_path=REMOTE_FUNCTION_PRE_EXECUTION_SCRIPT,
667
+ sagemaker_session=self.sagemaker_session,
668
+ )
669
+
670
+ if self.pre_execution_commands is not None and self.pre_execution_script is not None:
671
+ raise ValueError(
672
+ "Only one of pre_execution_commands or pre_execution_script can be specified!"
673
+ )
674
+
675
+ self.include_local_workdir = resolve_value_from_config(
676
+ direct_input=include_local_workdir,
677
+ config_path=REMOTE_FUNCTION_INCLUDE_LOCAL_WORKDIR,
678
+ default_value=False,
679
+ sagemaker_session=self.sagemaker_session,
680
+ )
681
+
682
+ self.custom_file_filter = resolve_custom_file_filter_from_config_file(
683
+ custom_file_filter, self.sagemaker_session
684
+ )
685
+
686
+ self.instance_type = resolve_value_from_config(
687
+ direct_input=instance_type,
688
+ config_path=REMOTE_FUNCTION_INSTANCE_TYPE,
689
+ sagemaker_session=self.sagemaker_session,
690
+ )
691
+ if not self.instance_type:
692
+ raise ValueError("instance_type is a required parameter!")
693
+
694
+ self.instance_count = instance_count
695
+ self.volume_size = volume_size
696
+ self.max_runtime_in_seconds = max_runtime_in_seconds
697
+ self.max_retry_attempts = max_retry_attempts
698
+ self.keep_alive_period_in_seconds = keep_alive_period_in_seconds
699
+ self.spark_config = spark_config
700
+ self.use_spot_instances = use_spot_instances
701
+ self.max_wait_time_in_seconds = max_wait_time_in_seconds
702
+ self.job_conda_env = resolve_value_from_config(
703
+ direct_input=job_conda_env,
704
+ config_path=REMOTE_FUNCTION_JOB_CONDA_ENV,
705
+ sagemaker_session=self.sagemaker_session,
706
+ )
707
+ self.job_name_prefix = job_name_prefix
708
+ self.encrypt_inter_container_traffic = resolve_value_from_config(
709
+ direct_input=encrypt_inter_container_traffic,
710
+ config_path=REMOTE_FUNCTION_ENABLE_INTER_CONTAINER_TRAFFIC_ENCRYPTION,
711
+ default_value=False,
712
+ sagemaker_session=self.sagemaker_session,
713
+ )
714
+ self.enable_network_isolation = False
715
+
716
+ _role = resolve_value_from_config(
717
+ direct_input=role,
718
+ config_path=REMOTE_FUNCTION_ROLE_ARN,
719
+ sagemaker_session=self.sagemaker_session,
720
+ )
721
+ if _role:
722
+ self.role = expand_role(self.sagemaker_session.boto_session, _role)
723
+ else:
724
+ self.role = get_execution_role(self.sagemaker_session)
725
+
726
+ self.s3_root_uri = resolve_value_from_config(
727
+ direct_input=s3_root_uri,
728
+ config_path=REMOTE_FUNCTION_S3_ROOT_URI,
729
+ default_value=s3_path_join(
730
+ "s3://",
731
+ self.sagemaker_session.default_bucket(),
732
+ self.sagemaker_session.default_bucket_prefix,
733
+ ),
734
+ sagemaker_session=self.sagemaker_session,
735
+ )
736
+
737
+ self.s3_kms_key = resolve_value_from_config(
738
+ direct_input=s3_kms_key,
739
+ config_path=REMOTE_FUNCTION_S3_KMS_KEY_ID,
740
+ sagemaker_session=self.sagemaker_session,
741
+ )
742
+ self.volume_kms_key = resolve_value_from_config(
743
+ direct_input=volume_kms_key,
744
+ config_path=REMOTE_FUNCTION_VOLUME_KMS_KEY_ID,
745
+ sagemaker_session=self.sagemaker_session,
746
+ )
747
+
748
+ _subnets = resolve_value_from_config(
749
+ direct_input=subnets,
750
+ config_path=REMOTE_FUNCTION_VPC_CONFIG_SUBNETS,
751
+ sagemaker_session=self.sagemaker_session,
752
+ )
753
+ _security_group_ids = resolve_value_from_config(
754
+ direct_input=security_group_ids,
755
+ config_path=REMOTE_FUNCTION_VPC_CONFIG_SECURITY_GROUP_IDS,
756
+ sagemaker_session=self.sagemaker_session,
757
+ )
758
+ vpc_config = vpc_utils.to_dict(subnets=_subnets, security_group_ids=_security_group_ids)
759
+ self.vpc_config = vpc_utils.sanitize(vpc_config)
760
+
761
+ tags = format_tags(tags)
762
+ self.tags = _append_sagemaker_config_tags(
763
+ self.sagemaker_session, tags, REMOTE_FUNCTION_TAGS
764
+ )
765
+
766
+ self.disable_output_compression = disable_output_compression
767
+ self.use_torchrun = use_torchrun
768
+ self.use_mpirun = use_mpirun
769
+ self.nproc_per_node = nproc_per_node
770
+
771
+ @staticmethod
772
+ def _get_default_image(session):
773
+ """Return Studio notebook image, if in Studio env. Else, base python.
774
+
775
+ Args:
776
+ session (Session): Boto session.
777
+
778
+ Returns:
779
+ Default SageMaker base python image.
780
+ """
781
+
782
+ if (
783
+ "SAGEMAKER_INTERNAL_IMAGE_URI" in os.environ
784
+ and os.environ["SAGEMAKER_INTERNAL_IMAGE_URI"]
785
+ ):
786
+ return os.environ["SAGEMAKER_INTERNAL_IMAGE_URI"]
787
+
788
+ py_version = str(sys.version_info[0]) + str(sys.version_info[1])
789
+
790
+ if py_version not in ["310", "38"]:
791
+ raise ValueError(
792
+ "Default image is supported only for Python versions 3.8 and 3.10. If you "
793
+ "are using any other python version, you must provide a compatible image_uri."
794
+ )
795
+
796
+ region = session.boto_region_name
797
+ image_uri = get_base_python_image_uri(region=region, py_version=py_version)
798
+
799
+ return image_uri
800
+
801
+ @staticmethod
802
+ def _get_default_spark_image(session):
803
+ """Return the Spark image.
804
+
805
+ Args:
806
+ session (Session): Boto session.
807
+
808
+ Returns:
809
+ SageMaker Spark container image uri.
810
+ """
811
+
812
+ region = session.boto_region_name
813
+
814
+ py_version = str(sys.version_info[0]) + str(sys.version_info[1])
815
+
816
+ if py_version not in ["39"]:
817
+ raise ValueError(
818
+ "The SageMaker Spark image for remote job only supports Python version 3.9. "
819
+ )
820
+
821
+ image_uri = image_uris.retrieve(
822
+ framework=SPARK_NAME,
823
+ region=region,
824
+ version=DEFAULT_SPARK_VERSION,
825
+ instance_type=None,
826
+ py_version=f"py{py_version}",
827
+ container_version=DEFAULT_SPARK_CONTAINER_VERSION,
828
+ )
829
+
830
+ return image_uri
831
+
832
+
833
+ class _Job:
834
+ """Helper class that interacts with the SageMaker training service."""
835
+
836
+ def __init__(self, job_name: str, s3_uri: str, sagemaker_session: Session):
837
+ """Initialize a _Job object.
838
+
839
+ Args:
840
+ job_name (str): The training job name.
841
+ s3_uri (str): The training job output S3 uri.
842
+ sagemaker_session (Session): SageMaker boto session.
843
+ """
844
+ self.job_name = job_name
845
+ self.s3_uri = s3_uri
846
+ self.sagemaker_session = sagemaker_session
847
+ self._last_describe_response = None
848
+
849
+ @staticmethod
850
+ def from_describe_response(describe_training_job_response, sagemaker_session):
851
+ """Construct a _Job from a describe_training_job_response object.
852
+
853
+ Args:
854
+ describe_training_job_response (Dict): Describe training job response.
855
+ sagemaker_session (Session): SageMaker boto session.
856
+
857
+ Returns:
858
+ the _Job object.
859
+ """
860
+ job_name = describe_training_job_response["TrainingJobName"]
861
+ s3_uri = describe_training_job_response["OutputDataConfig"]["S3OutputPath"]
862
+
863
+ job = _Job(job_name, s3_uri, sagemaker_session)
864
+ job._last_describe_response = describe_training_job_response
865
+ return job
866
+
867
+ @staticmethod
868
+ def start(job_settings: _JobSettings, func, func_args, func_kwargs, run_info=None):
869
+ """Start a training job.
870
+
871
+ Args:
872
+ job_settings (_JobSettings): the job settings.
873
+ func: the function to be executed.
874
+ func_args: the positional arguments to the function.
875
+ func_kwargs: the keyword arguments to the function
876
+
877
+ Returns:
878
+ the _Job object.
879
+ """
880
+ job_name = _Job._get_job_name(job_settings, func)
881
+ s3_base_uri = s3_path_join(job_settings.s3_root_uri, job_name)
882
+
883
+ training_job_request = _Job.compile(
884
+ job_settings=job_settings,
885
+ job_name=job_name,
886
+ s3_base_uri=s3_base_uri,
887
+ func=func,
888
+ func_args=func_args,
889
+ func_kwargs=func_kwargs,
890
+ run_info=run_info,
891
+ )
892
+
893
+ logger.info("Creating job: %s", job_name)
894
+
895
+ job_settings.sagemaker_session.sagemaker_client.create_training_job(**training_job_request)
896
+
897
+ return _Job(
898
+ job_name,
899
+ s3_base_uri,
900
+ job_settings.sagemaker_session,
901
+ )
902
+
903
+ @staticmethod
904
+ def compile(
905
+ job_settings: _JobSettings,
906
+ job_name: str,
907
+ s3_base_uri: str,
908
+ func: Callable,
909
+ func_args: tuple,
910
+ func_kwargs: dict,
911
+ run_info=None,
912
+ serialized_data: _SerializedData = None,
913
+ ) -> dict:
914
+ """Build the artifacts and generate the training job request."""
915
+ from sagemaker.core.workflow.properties import Properties
916
+ from sagemaker.core.workflow.parameters import Parameter
917
+ from sagemaker.core.workflow.functions import Join
918
+ from sagemaker.core.workflow.execution_variables import (
919
+ ExecutionVariables,
920
+ ExecutionVariable,
921
+ )
922
+ from sagemaker.core.workflow.utilities import load_step_compilation_context
923
+
924
+ step_compilation_context = load_step_compilation_context()
925
+
926
+ jobs_container_entrypoint = JOBS_CONTAINER_ENTRYPOINT[:]
927
+
928
+ # serialize function and arguments
929
+ if step_compilation_context is None:
930
+ stored_function = StoredFunction(
931
+ sagemaker_session=job_settings.sagemaker_session,
932
+ s3_base_uri=s3_base_uri,
933
+ s3_kms_key=job_settings.s3_kms_key,
934
+ )
935
+ stored_function.save(func, *func_args, **func_kwargs)
936
+ else:
937
+ stored_function = StoredFunction(
938
+ sagemaker_session=job_settings.sagemaker_session,
939
+ s3_base_uri=s3_base_uri,
940
+ s3_kms_key=job_settings.s3_kms_key,
941
+ context=Context(
942
+ step_name=step_compilation_context.step_name,
943
+ func_step_s3_dir=step_compilation_context.pipeline_build_time,
944
+ ),
945
+ )
946
+
947
+ stored_function.save_pipeline_step_function(serialized_data)
948
+
949
+ stopping_condition = {
950
+ "MaxRuntimeInSeconds": job_settings.max_runtime_in_seconds,
951
+ }
952
+ if job_settings.max_wait_time_in_seconds is not None:
953
+ stopping_condition["MaxWaitTimeInSeconds"] = job_settings.max_wait_time_in_seconds
954
+
955
+ request_dict = dict(
956
+ TrainingJobName=job_name,
957
+ RoleArn=job_settings.role,
958
+ StoppingCondition=stopping_condition,
959
+ RetryStrategy={"MaximumRetryAttempts": job_settings.max_retry_attempts},
960
+ )
961
+
962
+ _update_job_request_with_checkpoint_config(func_args, func_kwargs, request_dict)
963
+
964
+ if job_settings.tags:
965
+ request_dict["Tags"] = job_settings.tags
966
+
967
+ # generate other build artifacts including workspace, requirements.txt
968
+ request_dict["InputDataConfig"] = _generate_input_data_config(
969
+ job_settings=job_settings, s3_base_uri=s3_base_uri
970
+ )
971
+
972
+ if step_compilation_context:
973
+ # Path format: base/step_name/build_timestamp/execution_id/results
974
+ # This matches the path construction in stored_function.py
975
+ s3_output_path = Join(
976
+ on="/",
977
+ values=[
978
+ s3_base_uri,
979
+ step_compilation_context.step_name,
980
+ step_compilation_context.pipeline_build_time,
981
+ ExecutionVariables.PIPELINE_EXECUTION_ID,
982
+ "results",
983
+ ],
984
+ )
985
+ output_config = {"S3OutputPath": s3_output_path}
986
+ else:
987
+ output_config = {"S3OutputPath": s3_base_uri}
988
+ if job_settings.s3_kms_key is not None:
989
+ output_config["KmsKeyId"] = job_settings.s3_kms_key
990
+ if job_settings.disable_output_compression:
991
+ output_config["CompressionType"] = "NONE"
992
+ request_dict["OutputDataConfig"] = output_config
993
+
994
+ container_args = ["--s3_base_uri", s3_base_uri]
995
+ container_args.extend(["--region", job_settings.sagemaker_session.boto_region_name])
996
+ container_args.extend(
997
+ ["--client_python_version", RuntimeEnvironmentManager()._current_python_version()]
998
+ )
999
+ container_args.extend(
1000
+ [
1001
+ "--client_sagemaker_pysdk_version",
1002
+ RuntimeEnvironmentManager()._current_sagemaker_pysdk_version(),
1003
+ ]
1004
+ )
1005
+ container_args.extend(
1006
+ [
1007
+ "--dependency_settings",
1008
+ _DependencySettings.from_dependency_file_path(
1009
+ job_settings.dependencies
1010
+ ).to_string(),
1011
+ ]
1012
+ )
1013
+ if job_settings.use_torchrun:
1014
+ container_args.extend(["--distribution", "torchrun"])
1015
+ elif job_settings.use_mpirun:
1016
+ container_args.extend(["--distribution", "mpirun"])
1017
+ if job_settings.nproc_per_node is not None and int(job_settings.nproc_per_node) > 0:
1018
+ container_args.extend(["--user_nproc_per_node", str(job_settings.nproc_per_node)])
1019
+ if job_settings.s3_kms_key:
1020
+ container_args.extend(["--s3_kms_key", job_settings.s3_kms_key])
1021
+
1022
+ if job_settings.job_conda_env:
1023
+ container_args.extend(["--job_conda_env", job_settings.job_conda_env])
1024
+
1025
+ if step_compilation_context:
1026
+ # TODO: remove the duplicates in the list
1027
+ container_args.extend(["--pipeline_step_name", step_compilation_context.step_name])
1028
+ container_args.extend(
1029
+ ["--pipeline_execution_id", ExecutionVariables.PIPELINE_EXECUTION_ID]
1030
+ )
1031
+ container_args.extend(
1032
+ ["--func_step_s3_dir", step_compilation_context.pipeline_build_time]
1033
+ )
1034
+ container_args.extend(["--property_references"])
1035
+ container_args.extend(
1036
+ [
1037
+ ExecutionVariables.PIPELINE_EXECUTION_ID.expr["Get"],
1038
+ ExecutionVariables.PIPELINE_EXECUTION_ID.to_string(),
1039
+ ]
1040
+ )
1041
+ for arg in func_args + tuple(func_kwargs.values()):
1042
+ if isinstance(arg, (Parameter, ExecutionVariable, Properties)):
1043
+ container_args.extend([arg.expr["Get"], arg.to_string()])
1044
+
1045
+ # Lazy import to avoid circular dependency
1046
+ try:
1047
+ from sagemaker.mlops.workflow.function_step import DelayedReturn
1048
+
1049
+ if isinstance(arg, DelayedReturn):
1050
+ # The uri is a Properties object
1051
+ uri = get_step(arg)._properties.OutputDataConfig.S3OutputPath
1052
+ container_args.extend([uri.expr["Get"], uri.to_string()])
1053
+ except ImportError:
1054
+ # MLOps not installed, skip DelayedReturn handling
1055
+ pass
1056
+
1057
+ if run_info is not None:
1058
+ container_args.extend(["--run_in_context", json.dumps(dataclasses.asdict(run_info))])
1059
+ elif _RunContext.get_current_run() is not None:
1060
+ container_args.extend(
1061
+ ["--run_in_context", _convert_run_to_json(_RunContext.get_current_run())]
1062
+ )
1063
+
1064
+ algorithm_spec = dict(
1065
+ TrainingImage=job_settings.image_uri,
1066
+ TrainingInputMode="File",
1067
+ ContainerEntrypoint=jobs_container_entrypoint,
1068
+ ContainerArguments=container_args,
1069
+ )
1070
+
1071
+ request_dict["AlgorithmSpecification"] = algorithm_spec
1072
+
1073
+ resource_config = dict(
1074
+ VolumeSizeInGB=job_settings.volume_size,
1075
+ InstanceCount=job_settings.instance_count,
1076
+ InstanceType=job_settings.instance_type,
1077
+ )
1078
+ if job_settings.volume_kms_key is not None:
1079
+ resource_config["VolumeKmsKeyId"] = job_settings.volume_kms_key
1080
+ if job_settings.keep_alive_period_in_seconds is not None:
1081
+ resource_config["KeepAlivePeriodInSeconds"] = job_settings.keep_alive_period_in_seconds
1082
+
1083
+ request_dict["ResourceConfig"] = resource_config
1084
+
1085
+ if job_settings.enable_network_isolation is not None:
1086
+ request_dict["EnableNetworkIsolation"] = job_settings.enable_network_isolation
1087
+
1088
+ if job_settings.encrypt_inter_container_traffic is not None:
1089
+ request_dict["EnableInterContainerTrafficEncryption"] = (
1090
+ job_settings.encrypt_inter_container_traffic
1091
+ )
1092
+
1093
+ if job_settings.vpc_config:
1094
+ request_dict["VpcConfig"] = job_settings.vpc_config
1095
+
1096
+ request_dict["EnableManagedSpotTraining"] = job_settings.use_spot_instances
1097
+
1098
+ request_dict["Environment"] = job_settings.environment_variables
1099
+
1100
+ extended_request = _extend_spark_config_to_request(request_dict, job_settings, s3_base_uri)
1101
+ extended_request = _extend_mpirun_to_request(extended_request, job_settings)
1102
+ extended_request = _extend_torchrun_to_request(extended_request, job_settings)
1103
+
1104
+ return extended_request
1105
+
1106
+ def describe(self):
1107
+ """Describe the underlying sagemaker training job.
1108
+
1109
+ Returns:
1110
+ Dict: Describe training job response.
1111
+ """
1112
+ if self._last_describe_response is not None and self._last_describe_response[
1113
+ "TrainingJobStatus"
1114
+ ] in ["Completed", "Failed", "Stopped"]:
1115
+ return self._last_describe_response
1116
+
1117
+ self._last_describe_response = (
1118
+ self.sagemaker_session.sagemaker_client.describe_training_job(
1119
+ TrainingJobName=self.job_name
1120
+ )
1121
+ )
1122
+
1123
+ return self._last_describe_response
1124
+
1125
+ def stop(self):
1126
+ """Stop the underlying sagemaker training job."""
1127
+ self.sagemaker_session.sagemaker_client.stop_training_job(TrainingJobName=self.job_name)
1128
+
1129
+ def wait(self, timeout: int = None):
1130
+ """Wait for the underlying sagemaker job to finish and displays its logs .
1131
+
1132
+ This method blocks on the sagemaker job completing for up to the timeout value (if
1133
+ specified). If timeout is ``None``, this method will block until the job is completed.
1134
+
1135
+ Args:
1136
+ timeout (int): Timeout in seconds to wait until the job is completed. ``None`` by
1137
+ default.
1138
+
1139
+ Returns: None
1140
+ """
1141
+
1142
+ self._last_describe_response = _logs_for_job(
1143
+ sagemaker_session=self.sagemaker_session,
1144
+ job_name=self.job_name,
1145
+ wait=True,
1146
+ timeout=timeout,
1147
+ )
1148
+
1149
+ @staticmethod
1150
+ def _get_job_name(job_settings, func):
1151
+ """Get the underlying SageMaker job name from job_name_prefix or func.
1152
+
1153
+ Args:
1154
+ job_settings (_JobSettings): the job settings.
1155
+ func: the function to be executed.
1156
+
1157
+ Returns:
1158
+ str : the training job name.
1159
+ """
1160
+ from sagemaker.core.workflow.utilities import load_step_compilation_context
1161
+
1162
+ step_complication_context = load_step_compilation_context()
1163
+
1164
+ job_name_prefix = job_settings.job_name_prefix
1165
+ if not job_name_prefix:
1166
+ job_name_prefix = func.__name__
1167
+ # remove all special characters in the beginning of function name
1168
+ job_name_prefix = re.sub(r"^[^a-zA-Z0-9]+", "", job_name_prefix)
1169
+ # convert all remaining special characters to '-'
1170
+ job_name_prefix = re.sub(r"[^a-zA-Z0-9-]", "-", job_name_prefix)
1171
+
1172
+ if step_complication_context:
1173
+ return job_name_prefix
1174
+ return name_from_base(job_name_prefix)
1175
+
1176
+
1177
+ def _prepare_and_upload_runtime_scripts(
1178
+ spark_config: SparkConfig,
1179
+ s3_base_uri: str,
1180
+ s3_kms_key: str,
1181
+ sagemaker_session: Session,
1182
+ use_torchrun: bool = False,
1183
+ use_mpirun: bool = False,
1184
+ ):
1185
+ """Copy runtime scripts to a folder and upload to S3.
1186
+
1187
+ In case of remote function, s3_base_uri is s3_root_uri + function_name.
1188
+ In case of pipeline, s3_base_uri is s3_root_uri + pipeline_name. The runtime scripts are
1189
+ uploaded only once per pipeline.
1190
+
1191
+ Args:
1192
+ spark_config (SparkConfig): remote Spark job configurations.
1193
+
1194
+ s3_base_uri (str): S3 location that the runtime scripts will be uploaded to.
1195
+
1196
+ s3_kms_key (str): kms key used to encrypt the files uploaded to S3.
1197
+
1198
+ sagemaker_session (str): SageMaker boto client session.
1199
+
1200
+ use_torchrun (bool): Whether to use torchrun or not.
1201
+
1202
+ use_mpirun (bool): Whether to use mpirun or not.
1203
+
1204
+ nproc_per_node (Optional[int]): Number of processes per node
1205
+ """
1206
+
1207
+ from sagemaker.core.workflow.utilities import load_step_compilation_context
1208
+
1209
+ step_compilation_context = load_step_compilation_context()
1210
+
1211
+ if step_compilation_context and not step_compilation_context.upload_runtime_scripts:
1212
+ return s3_path_join(s3_base_uri, RUNTIME_SCRIPTS_CHANNEL_NAME)
1213
+
1214
+ with _tmpdir() as bootstrap_scripts:
1215
+
1216
+ # write entrypoint script to tmpdir
1217
+ entrypoint_script_path = os.path.join(bootstrap_scripts, ENTRYPOINT_SCRIPT_NAME)
1218
+ entry_point_script = ENTRYPOINT_SCRIPT
1219
+ if spark_config:
1220
+ entry_point_script = SPARK_ENTRYPOINT_SCRIPT
1221
+ spark_script_path = os.path.join(
1222
+ os.path.dirname(__file__), "runtime_environment", SPARK_APP_SCRIPT_NAME
1223
+ )
1224
+ shutil.copy2(spark_script_path, bootstrap_scripts)
1225
+
1226
+ if use_torchrun:
1227
+ entry_point_script = ENTRYPOINT_TORCHRUN_SCRIPT
1228
+
1229
+ if use_mpirun:
1230
+ entry_point_script = ENTRYPOINT_MPIRUN_SCRIPT
1231
+
1232
+ with open(entrypoint_script_path, "w", newline="\n") as file:
1233
+ file.writelines(entry_point_script)
1234
+
1235
+ bootstrap_script_path = os.path.join(
1236
+ os.path.dirname(__file__), "runtime_environment", BOOTSTRAP_SCRIPT_NAME
1237
+ )
1238
+ mpi_utils_path = os.path.join(
1239
+ os.path.dirname(__file__), "runtime_environment", MPI_UTILS_SCRIPT_NAME
1240
+ )
1241
+ runtime_manager_script_path = os.path.join(
1242
+ os.path.dirname(__file__), "runtime_environment", RUNTIME_MANAGER_SCRIPT_NAME
1243
+ )
1244
+
1245
+ # copy runtime scripts to tmpdir
1246
+ shutil.copy2(bootstrap_script_path, bootstrap_scripts)
1247
+ shutil.copy2(mpi_utils_path, bootstrap_scripts)
1248
+ shutil.copy2(runtime_manager_script_path, bootstrap_scripts)
1249
+
1250
+ upload_path = S3Uploader.upload(
1251
+ bootstrap_scripts,
1252
+ s3_path_join(s3_base_uri, RUNTIME_SCRIPTS_CHANNEL_NAME),
1253
+ s3_kms_key,
1254
+ sagemaker_session,
1255
+ )
1256
+
1257
+ if step_compilation_context:
1258
+ step_compilation_context.upload_runtime_scripts = False
1259
+ return upload_path
1260
+
1261
+
1262
+ def _generate_input_data_config(job_settings: _JobSettings, s3_base_uri: str):
1263
+ """Generates input data config"""
1264
+ from sagemaker.core.workflow.utilities import load_step_compilation_context
1265
+
1266
+ step_compilation_context = load_step_compilation_context()
1267
+
1268
+ bootstrap_scripts_s3uri = _prepare_and_upload_runtime_scripts(
1269
+ spark_config=job_settings.spark_config,
1270
+ s3_base_uri=s3_base_uri,
1271
+ s3_kms_key=job_settings.s3_kms_key,
1272
+ sagemaker_session=job_settings.sagemaker_session,
1273
+ use_torchrun=job_settings.use_torchrun,
1274
+ use_mpirun=job_settings.use_mpirun,
1275
+ )
1276
+
1277
+ input_data_config = [
1278
+ dict(
1279
+ ChannelName=RUNTIME_SCRIPTS_CHANNEL_NAME,
1280
+ DataSource={
1281
+ "S3DataSource": {
1282
+ "S3Uri": bootstrap_scripts_s3uri,
1283
+ "S3DataType": "S3Prefix",
1284
+ }
1285
+ },
1286
+ )
1287
+ ]
1288
+
1289
+ local_dependencies_path = RuntimeEnvironmentManager().snapshot(job_settings.dependencies)
1290
+
1291
+ if step_compilation_context:
1292
+ with _tmpdir() as tmp_dir:
1293
+ script_and_dependencies_s3uri = _prepare_dependencies_and_pre_execution_scripts(
1294
+ local_dependencies_path=local_dependencies_path,
1295
+ pre_execution_commands=job_settings.pre_execution_commands,
1296
+ pre_execution_script_local_path=job_settings.pre_execution_script,
1297
+ s3_base_uri=s3_base_uri,
1298
+ s3_kms_key=job_settings.s3_kms_key,
1299
+ sagemaker_session=job_settings.sagemaker_session,
1300
+ tmp_dir=tmp_dir,
1301
+ )
1302
+
1303
+ if script_and_dependencies_s3uri:
1304
+ input_data_config.append(
1305
+ dict(
1306
+ ChannelName=SCRIPT_AND_DEPENDENCIES_CHANNEL_NAME,
1307
+ DataSource={
1308
+ "S3DataSource": {
1309
+ "S3Uri": script_and_dependencies_s3uri,
1310
+ "S3DataType": "S3Prefix",
1311
+ }
1312
+ },
1313
+ )
1314
+ )
1315
+
1316
+ user_workspace_s3uri = _prepare_and_upload_workspace(
1317
+ local_dependencies_path=local_dependencies_path,
1318
+ include_local_workdir=job_settings.include_local_workdir,
1319
+ pre_execution_commands=job_settings.pre_execution_commands,
1320
+ pre_execution_script_local_path=job_settings.pre_execution_script,
1321
+ s3_base_uri=s3_base_uri,
1322
+ s3_kms_key=job_settings.s3_kms_key,
1323
+ sagemaker_session=job_settings.sagemaker_session,
1324
+ custom_file_filter=job_settings.custom_file_filter,
1325
+ )
1326
+
1327
+ if user_workspace_s3uri:
1328
+ input_data_config.append(
1329
+ dict(
1330
+ ChannelName=(
1331
+ REMOTE_FUNCTION_WORKSPACE
1332
+ if not step_compilation_context
1333
+ else step_compilation_context.pipeline_build_time
1334
+ ),
1335
+ DataSource={
1336
+ "S3DataSource": {
1337
+ "S3Uri": user_workspace_s3uri,
1338
+ "S3DataType": "S3Prefix",
1339
+ }
1340
+ },
1341
+ )
1342
+ )
1343
+
1344
+ return input_data_config
1345
+
1346
+
1347
+ def _prepare_dependencies_and_pre_execution_scripts(
1348
+ local_dependencies_path: str,
1349
+ pre_execution_commands: List[str],
1350
+ pre_execution_script_local_path: str,
1351
+ s3_base_uri: str,
1352
+ s3_kms_key: str,
1353
+ sagemaker_session: Session,
1354
+ tmp_dir: str,
1355
+ ):
1356
+ """Prepare pre-execution scripts and dependencies and upload them to s3.
1357
+
1358
+ If pre execution commands are provided, a new bash file will be created
1359
+ with those commands in tmp directory.
1360
+ If pre execution script is provided, it copies that file from local file path
1361
+ to tmp directory.
1362
+ If local dependencies file is provided, it copies that file from local file path
1363
+ to tmp directory.
1364
+ If under pipeline context, tmp directory with copied dependencies and scripts is
1365
+ uploaded to S3.
1366
+ """
1367
+ from sagemaker.core.workflow.utilities import load_step_compilation_context
1368
+
1369
+ if not (local_dependencies_path or pre_execution_commands or pre_execution_script_local_path):
1370
+ return None
1371
+
1372
+ if local_dependencies_path:
1373
+ dst_path = shutil.copy2(local_dependencies_path, tmp_dir)
1374
+ logger.info("Copied dependencies file at '%s' to '%s'", local_dependencies_path, dst_path)
1375
+
1376
+ if pre_execution_commands or pre_execution_script_local_path:
1377
+ pre_execution_script = os.path.join(tmp_dir, PRE_EXECUTION_SCRIPT_NAME)
1378
+ if pre_execution_commands:
1379
+ with open(pre_execution_script, "w") as target_script:
1380
+ commands = [cmd + "\n" for cmd in pre_execution_commands]
1381
+ target_script.writelines(commands)
1382
+ logger.info(
1383
+ "Generated pre-execution script from commands to '%s'", pre_execution_script
1384
+ )
1385
+ else:
1386
+ shutil.copy2(pre_execution_script_local_path, pre_execution_script)
1387
+ logger.info(
1388
+ "Copied pre-execution commands from script at '%s' to '%s'",
1389
+ pre_execution_script_local_path,
1390
+ pre_execution_script,
1391
+ )
1392
+
1393
+ step_compilation_context = load_step_compilation_context()
1394
+ if step_compilation_context:
1395
+ upload_path = S3Uploader.upload(
1396
+ tmp_dir,
1397
+ s3_path_join(
1398
+ s3_base_uri,
1399
+ step_compilation_context.step_name,
1400
+ step_compilation_context.pipeline_build_time,
1401
+ SCRIPT_AND_DEPENDENCIES_CHANNEL_NAME,
1402
+ ),
1403
+ s3_kms_key,
1404
+ sagemaker_session,
1405
+ )
1406
+ logger.info(
1407
+ "Successfully uploaded dependencies and pre execution scripts to '%s'", upload_path
1408
+ )
1409
+ return upload_path
1410
+ return None
1411
+
1412
+
1413
+ def _prepare_and_upload_workspace(
1414
+ local_dependencies_path: str,
1415
+ include_local_workdir: bool,
1416
+ pre_execution_commands: List[str],
1417
+ pre_execution_script_local_path: str,
1418
+ s3_base_uri: str,
1419
+ s3_kms_key: str,
1420
+ sagemaker_session: Session,
1421
+ custom_file_filter: Optional[Union[Callable[[str, List], List], CustomFileFilter]] = None,
1422
+ ) -> str:
1423
+ """Prepare and upload the workspace to S3.
1424
+
1425
+ Under pipeline context, only workdir is packaged in the workspace folder and uploaded to s3.
1426
+ Under remote function context, workdir along with pre execution scripts and dependencies
1427
+ are packaged together into the workspace folder and uploaded to S3.
1428
+ """
1429
+ from sagemaker.core.workflow.utilities import load_step_compilation_context
1430
+
1431
+ step_compilation_context = load_step_compilation_context()
1432
+
1433
+ if not (
1434
+ local_dependencies_path
1435
+ or include_local_workdir
1436
+ or pre_execution_commands
1437
+ or pre_execution_script_local_path
1438
+ ):
1439
+ return None
1440
+
1441
+ func_step_s3_dir = None
1442
+ if step_compilation_context:
1443
+ func_step_s3_dir = step_compilation_context.pipeline_build_time
1444
+ if not include_local_workdir:
1445
+ return None
1446
+ if not step_compilation_context.upload_workspace:
1447
+ return s3_path_join(s3_base_uri, REMOTE_FUNCTION_WORKSPACE, func_step_s3_dir)
1448
+
1449
+ with _tmpdir() as tmp_dir:
1450
+ tmp_workspace_dir = os.path.join(tmp_dir, "temp_workspace/")
1451
+ os.mkdir(tmp_workspace_dir)
1452
+ # TODO Remove the following hack to avoid dir_exists error in the copy_tree call below.
1453
+ tmp_workspace = os.path.join(tmp_workspace_dir, JOB_REMOTE_FUNCTION_WORKSPACE)
1454
+
1455
+ if include_local_workdir:
1456
+ copy_workdir(tmp_workspace, custom_file_filter)
1457
+ logger.info("Copied user workspace to '%s'", tmp_workspace)
1458
+
1459
+ if not os.path.isdir(tmp_workspace):
1460
+ # create the directory if no workdir_path was provided in the input.
1461
+ os.mkdir(tmp_workspace)
1462
+
1463
+ if not step_compilation_context:
1464
+ _prepare_dependencies_and_pre_execution_scripts(
1465
+ local_dependencies_path=local_dependencies_path,
1466
+ pre_execution_commands=pre_execution_commands,
1467
+ pre_execution_script_local_path=pre_execution_script_local_path,
1468
+ s3_base_uri=s3_base_uri,
1469
+ s3_kms_key=s3_kms_key,
1470
+ sagemaker_session=sagemaker_session,
1471
+ tmp_dir=tmp_workspace,
1472
+ )
1473
+
1474
+ workspace_archive_path = os.path.join(tmp_dir, "workspace")
1475
+ workspace_archive_path = shutil.make_archive(
1476
+ workspace_archive_path, "zip", tmp_workspace_dir
1477
+ )
1478
+ logger.info("Successfully created workdir archive at '%s'", workspace_archive_path)
1479
+
1480
+ upload_path = S3Uploader.upload(
1481
+ workspace_archive_path,
1482
+ s3_path_join(s3_base_uri, REMOTE_FUNCTION_WORKSPACE, func_step_s3_dir),
1483
+ s3_kms_key,
1484
+ sagemaker_session,
1485
+ )
1486
+ logger.info("Successfully uploaded workdir to '%s'", upload_path)
1487
+ if step_compilation_context:
1488
+ step_compilation_context.upload_workspace = False
1489
+ return upload_path
1490
+
1491
+
1492
+ def _convert_run_to_json(run: Run) -> str:
1493
+ """Convert current run into json string"""
1494
+ run_info = _RunInfo(run.experiment_name, run.run_name)
1495
+ return json.dumps(dataclasses.asdict(run_info))
1496
+
1497
+
1498
+ def _prepare_and_upload_spark_dependent_files(
1499
+ spark_config: SparkConfig,
1500
+ s3_base_uri: str,
1501
+ s3_kms_key: str,
1502
+ sagemaker_session: Session,
1503
+ ) -> Tuple:
1504
+ """Upload the Spark dependencies to S3 if present.
1505
+
1506
+ Args:
1507
+ spark_config (SparkConfig): The remote Spark job configurations.
1508
+ s3_base_uri (str): The S3 location that the Spark dependencies will be uploaded to.
1509
+ s3_kms_key (str): The kms key used to encrypt the files uploaded to S3.
1510
+ sagemaker_session (str): SageMaker boto client session.
1511
+ """
1512
+ if not spark_config:
1513
+ return None, None, None, None
1514
+
1515
+ submit_jars_s3_paths = _upload_spark_submit_deps(
1516
+ spark_config.submit_jars,
1517
+ SPARK_SUBMIT_JARS_WORKSPACE,
1518
+ s3_base_uri,
1519
+ s3_kms_key,
1520
+ sagemaker_session,
1521
+ )
1522
+ submit_py_files_s3_paths = _upload_spark_submit_deps(
1523
+ spark_config.submit_py_files,
1524
+ SPARK_SUBMIT_PY_FILES_WORKSPACE,
1525
+ s3_base_uri,
1526
+ s3_kms_key,
1527
+ sagemaker_session,
1528
+ )
1529
+ submit_files_s3_path = _upload_spark_submit_deps(
1530
+ spark_config.submit_files,
1531
+ SPARK_SUBMIT_FILES_WORKSPACE,
1532
+ s3_base_uri,
1533
+ s3_kms_key,
1534
+ sagemaker_session,
1535
+ )
1536
+ config_file_s3_uri = _upload_serialized_spark_configuration(
1537
+ s3_base_uri, s3_kms_key, spark_config.configuration, sagemaker_session
1538
+ )
1539
+
1540
+ return submit_jars_s3_paths, submit_py_files_s3_paths, submit_files_s3_path, config_file_s3_uri
1541
+
1542
+
1543
+ def _upload_spark_submit_deps(
1544
+ submit_deps: List[str],
1545
+ workspace_name: str,
1546
+ s3_base_uri: str,
1547
+ s3_kms_key: str,
1548
+ sagemaker_session: Session,
1549
+ ) -> str:
1550
+ """Upload the Spark submit dependencies to S3.
1551
+
1552
+ Args:
1553
+ submit_deps (List[str]): A list of path which points to the Spark dependency files.
1554
+ The path can be either a local path or S3 uri. For example ``/local/deps.jar`` or
1555
+ ``s3://<your-bucket>/deps.jar``.
1556
+
1557
+ workspace_name (str): workspace name for Spark dependency.
1558
+ s3_base_uri (str): S3 location that the Spark dependencies will be uploaded to.
1559
+ s3_kms_key (str): kms key used to encrypt the files uploaded to S3.
1560
+ sagemaker_session (str): SageMaker boto client session.
1561
+
1562
+ Returns:
1563
+ str : The concatenated path of all dependencies which will be passed to Spark.
1564
+ """
1565
+ spark_opt_s3_uris = []
1566
+ if not submit_deps:
1567
+ return None
1568
+
1569
+ if not workspace_name or not s3_base_uri:
1570
+ raise ValueError("workspace_name or s3_base_uri may not be empty.")
1571
+
1572
+ for dep_path in submit_deps:
1573
+ dep_url = urlparse(dep_path)
1574
+
1575
+ if dep_url.scheme in ["s3", "s3a"]:
1576
+ spark_opt_s3_uris.append(dep_path)
1577
+ elif not dep_url.scheme or dep_url.scheme == "file":
1578
+ if not os.path.isfile(dep_path):
1579
+ raise ValueError(f"submit_deps path {dep_path} is not a valid local file.")
1580
+
1581
+ upload_path = S3Uploader.upload(
1582
+ local_path=dep_path,
1583
+ desired_s3_uri=s3_path_join(s3_base_uri, workspace_name),
1584
+ kms_key=s3_kms_key,
1585
+ sagemaker_session=sagemaker_session,
1586
+ )
1587
+
1588
+ spark_opt_s3_uris.append(upload_path)
1589
+ logger.info("Uploaded the local file %s to %s", dep_path, upload_path)
1590
+ return str.join(",", spark_opt_s3_uris)
1591
+
1592
+
1593
+ def _upload_serialized_spark_configuration(
1594
+ s3_base_uri: str, s3_kms_key: str, configuration: Dict, sagemaker_session: Session
1595
+ ) -> str:
1596
+ """Upload the Spark configuration json to S3"""
1597
+ if not configuration:
1598
+ return None
1599
+
1600
+ serialized_configuration = BytesIO(json.dumps(configuration).encode("utf-8"))
1601
+ config_file_s3_uri = s3_path_join(s3_base_uri, SPARK_CONF_WORKSPACE, SPARK_CONF_FILE_NAME)
1602
+
1603
+ S3Uploader.upload_string_as_file_body(
1604
+ body=serialized_configuration,
1605
+ desired_s3_uri=config_file_s3_uri,
1606
+ kms_key=s3_kms_key,
1607
+ sagemaker_session=sagemaker_session,
1608
+ )
1609
+
1610
+ logger.info("Uploaded spark configuration json %s to %s", configuration, config_file_s3_uri)
1611
+
1612
+ return config_file_s3_uri
1613
+
1614
+
1615
+ def _extend_mpirun_to_request(
1616
+ request_dict: Dict,
1617
+ job_settings: _JobSettings,
1618
+ ) -> Dict:
1619
+ """Extend the create training job request with mpirun configuration.
1620
+
1621
+ Args:
1622
+ request_dict (Dict): create training job request dict.
1623
+ job_settings (_JobSettings): the job settings.
1624
+ """
1625
+ use_mpirun = job_settings.use_mpirun
1626
+ instance_count = job_settings.instance_count
1627
+
1628
+ if not use_mpirun:
1629
+ return request_dict
1630
+
1631
+ if instance_count == 1:
1632
+ return request_dict
1633
+
1634
+ extended_request = request_dict.copy()
1635
+
1636
+ for input_channel in extended_request["InputDataConfig"]:
1637
+ s3_data_source = input_channel["DataSource"].get("S3DataSource", None)
1638
+ if s3_data_source:
1639
+ s3_data_source["S3DataDistributionType"] = "FullyReplicated"
1640
+
1641
+ return extended_request
1642
+
1643
+
1644
+ def _extend_torchrun_to_request(
1645
+ request_dict: Dict,
1646
+ job_settings: _JobSettings,
1647
+ ) -> Dict:
1648
+ """Extend the create training job request with torchrun configuration.
1649
+
1650
+ Args:
1651
+ request_dict (Dict): create training job request dict.
1652
+ job_settings (_JobSettings): the job settings.
1653
+ """
1654
+ use_torchrun = job_settings.use_torchrun
1655
+ instance_count = job_settings.instance_count
1656
+
1657
+ if not use_torchrun:
1658
+ return request_dict
1659
+
1660
+ if instance_count == 1:
1661
+ return request_dict
1662
+
1663
+ extended_request = request_dict.copy()
1664
+
1665
+ for input_channel in extended_request["InputDataConfig"]:
1666
+ s3_data_source = input_channel["DataSource"].get("S3DataSource", None)
1667
+ if s3_data_source:
1668
+ s3_data_source["S3DataDistributionType"] = "FullyReplicated"
1669
+
1670
+ return extended_request
1671
+
1672
+
1673
+ def _extend_spark_config_to_request(
1674
+ request_dict: Dict,
1675
+ job_settings: _JobSettings,
1676
+ s3_base_uri: str,
1677
+ ) -> Dict:
1678
+ """Extend the create training job request with spark configurations.
1679
+
1680
+ Args:
1681
+ request_dict (Dict): create training job request dict.
1682
+ job_settings (_JobSettings): the job settings.
1683
+ s3_base_uri (str): S3 location that the Spark dependencies will be uploaded to.
1684
+ """
1685
+ spark_config = job_settings.spark_config
1686
+
1687
+ if not spark_config:
1688
+ return request_dict
1689
+
1690
+ extended_request = request_dict.copy()
1691
+ container_entrypoint = extended_request["AlgorithmSpecification"]["ContainerEntrypoint"]
1692
+
1693
+ (
1694
+ submit_jars_s3_paths,
1695
+ submit_py_files_s3_paths,
1696
+ submit_files_s3_path,
1697
+ config_file_s3_uri,
1698
+ ) = _prepare_and_upload_spark_dependent_files(
1699
+ spark_config=spark_config,
1700
+ s3_base_uri=s3_base_uri,
1701
+ s3_kms_key=job_settings.s3_kms_key,
1702
+ sagemaker_session=job_settings.sagemaker_session,
1703
+ )
1704
+
1705
+ input_data_config = extended_request["InputDataConfig"]
1706
+
1707
+ if config_file_s3_uri:
1708
+ input_data_config.append(
1709
+ dict(
1710
+ ChannelName=SPARK_CONF_CHANNEL_NAME,
1711
+ DataSource={
1712
+ "S3DataSource": {
1713
+ "S3Uri": config_file_s3_uri,
1714
+ "S3DataType": "S3Prefix",
1715
+ }
1716
+ },
1717
+ )
1718
+ )
1719
+
1720
+ for input_channel in extended_request["InputDataConfig"]:
1721
+ s3_data_source = input_channel["DataSource"].get("S3DataSource", None)
1722
+ if s3_data_source:
1723
+ s3_data_source["S3DataDistributionType"] = "FullyReplicated"
1724
+
1725
+ if spark_config.spark_event_logs_uri:
1726
+ container_entrypoint.extend(
1727
+ ["--spark-event-logs-s3-uri", spark_config.spark_event_logs_uri]
1728
+ )
1729
+
1730
+ if submit_jars_s3_paths:
1731
+ container_entrypoint.extend(["--jars", submit_jars_s3_paths])
1732
+
1733
+ if submit_py_files_s3_paths:
1734
+ container_entrypoint.extend(["--py-files", submit_py_files_s3_paths])
1735
+
1736
+ if submit_files_s3_path:
1737
+ container_entrypoint.extend(["--files", submit_files_s3_path])
1738
+
1739
+ if spark_config:
1740
+ container_entrypoint.extend([SPARK_APP_SCRIPT_PATH])
1741
+
1742
+ return extended_request
1743
+
1744
+
1745
+ def _update_job_request_with_checkpoint_config(args, kwargs, request_dict):
1746
+ """Extend job request with checkpoint config based on CheckpointLocation in function args.
1747
+
1748
+ Args:
1749
+ args (tuple): The positional arguments of the remote function.
1750
+ kwargs (Dict): The keyword arguments of the remote function.
1751
+ request_dict (Dict): create training job request dict.
1752
+ """
1753
+ checkpoint_location_index_in_args = None
1754
+ checkpoint_location_key_in_kwargs = None
1755
+ checkpoint_location_count = 0
1756
+
1757
+ for index, arg in enumerate(args):
1758
+ if isinstance(arg, CheckpointLocation):
1759
+ checkpoint_location_index_in_args = index
1760
+ checkpoint_location_count += 1
1761
+
1762
+ for key, value in kwargs.items():
1763
+ if isinstance(value, CheckpointLocation):
1764
+ checkpoint_location_key_in_kwargs = key
1765
+ checkpoint_location_count += 1
1766
+
1767
+ if checkpoint_location_count < 1:
1768
+ return
1769
+
1770
+ if checkpoint_location_count > 1:
1771
+ raise ValueError(
1772
+ "Remote function cannot have more than one argument of type CheckpointLocation."
1773
+ )
1774
+
1775
+ if checkpoint_location_index_in_args is not None:
1776
+ checkpoint_location_arg = args[checkpoint_location_index_in_args]
1777
+ else:
1778
+ checkpoint_location_arg = kwargs[checkpoint_location_key_in_kwargs]
1779
+
1780
+ checkpoint_s3_uri = checkpoint_location_arg._s3_uri
1781
+ checkpoint_local_path = checkpoint_location_arg._local_path
1782
+
1783
+ request_dict["CheckpointConfig"] = {
1784
+ "LocalPath": checkpoint_local_path,
1785
+ "S3Uri": checkpoint_s3_uri,
1786
+ }
1787
+
1788
+
1789
+ @dataclasses.dataclass
1790
+ class _RunInfo:
1791
+ """Data class to hold information of the run object from context."""
1792
+
1793
+ experiment_name: str
1794
+ run_name: str
1795
+
1796
+
1797
+ def _get_initial_job_state(description, status_key, wait):
1798
+ """Placeholder docstring"""
1799
+ status = description[status_key]
1800
+ job_already_completed = status in ("Completed", "Failed", "Stopped")
1801
+ return LogState.TAILING if wait and not job_already_completed else LogState.COMPLETE
1802
+
1803
+
1804
+ def _logs_for_job( # noqa: C901 - suppress complexity warning for this method
1805
+ sagemaker_session, job_name, wait=False, poll=10, log_type="All", timeout=None
1806
+ ):
1807
+ """Display logs for a given training job, optionally tailing them until job is complete.
1808
+
1809
+ If the output is a tty or a Jupyter cell, it will be color-coded
1810
+ based on which instance the log entry is from.
1811
+
1812
+ Args:
1813
+ sagemaker_session (sagemaker.core.helper.session.Session): A SageMaker Session
1814
+ object, used for SageMaker interactions.
1815
+ job_name (str): Name of the training job to display the logs for.
1816
+ wait (bool): Whether to keep looking for new log entries until the job completes
1817
+ (default: False).
1818
+ poll (int): The interval in seconds between polling for new log entries and job
1819
+ completion (default: 5).
1820
+ log_type ([str]): A list of strings specifying which logs to print. Acceptable
1821
+ strings are "All", "None", "Training", or "Rules". To maintain backwards
1822
+ compatibility, boolean values are also accepted and converted to strings.
1823
+ timeout (int): Timeout in seconds to wait until the job is completed. ``None`` by
1824
+ default.
1825
+ Returns:
1826
+ Last call to sagemaker DescribeTrainingJob
1827
+ Raises:
1828
+ exceptions.CapacityError: If the training job fails with CapacityError.
1829
+ exceptions.UnexpectedStatusException: If waiting and the training job fails.
1830
+ """
1831
+ sagemaker_client = sagemaker_session.sagemaker_client
1832
+ request_end_time = time.time() + timeout if timeout else None
1833
+ description = _wait_until(
1834
+ lambda: sagemaker_client.describe_training_job(TrainingJobName=job_name)
1835
+ )
1836
+ print(secondary_training_status_message(description, None), end="")
1837
+
1838
+ instance_count, stream_names, positions, client, log_group, dot, color_wrap = _logs_init(
1839
+ sagemaker_session.boto_session, description, job="Training"
1840
+ )
1841
+
1842
+ state = _get_initial_job_state(description, "TrainingJobStatus", wait)
1843
+
1844
+ # The loop below implements a state machine that alternates between checking the job status
1845
+ # and reading whatever is available in the logs at this point. Note, that if we were
1846
+ # called with wait == False, we never check the job status.
1847
+ #
1848
+ # If wait == TRUE and job is not completed, the initial state is TAILING
1849
+ # If wait == FALSE, the initial state is COMPLETE (doesn't matter if the job really is
1850
+ # complete).
1851
+ #
1852
+ # The state table:
1853
+ #
1854
+ # STATE ACTIONS CONDITION NEW STATE
1855
+ # ---------------- ---------------- ----------------- ----------------
1856
+ # TAILING Read logs, Pause, Get status Job complete JOB_COMPLETE
1857
+ # Else TAILING
1858
+ # JOB_COMPLETE Read logs, Pause Any COMPLETE
1859
+ # COMPLETE Read logs, Exit N/A
1860
+ #
1861
+ # Notes:
1862
+ # - The JOB_COMPLETE state forces us to do an extra pause and read any items that got to
1863
+ # Cloudwatch after the job was marked complete.
1864
+ last_describe_job_call = time.time()
1865
+ last_description = description
1866
+ last_debug_rule_statuses = None
1867
+ last_profiler_rule_statuses = None
1868
+
1869
+ while True:
1870
+ _flush_log_streams(
1871
+ stream_names,
1872
+ instance_count,
1873
+ client,
1874
+ log_group,
1875
+ job_name,
1876
+ positions,
1877
+ dot,
1878
+ color_wrap,
1879
+ )
1880
+ if timeout and time.time() > request_end_time:
1881
+ print("Timeout Exceeded. {} seconds elapsed.".format(timeout))
1882
+ break
1883
+
1884
+ if state == LogState.COMPLETE:
1885
+ break
1886
+
1887
+ time.sleep(poll)
1888
+
1889
+ if state == LogState.JOB_COMPLETE:
1890
+ state = LogState.COMPLETE
1891
+ elif time.time() - last_describe_job_call >= 30:
1892
+ description = sagemaker_client.describe_training_job(TrainingJobName=job_name)
1893
+ last_describe_job_call = time.time()
1894
+
1895
+ if secondary_training_status_changed(description, last_description):
1896
+ print()
1897
+ print(secondary_training_status_message(description, last_description), end="")
1898
+ last_description = description
1899
+
1900
+ status = description["TrainingJobStatus"]
1901
+
1902
+ if status in ("Completed", "Failed", "Stopped"):
1903
+ print()
1904
+ state = LogState.JOB_COMPLETE
1905
+
1906
+ # Print prettified logs related to the status of SageMaker Debugger rules.
1907
+ debug_rule_statuses = description.get("DebugRuleEvaluationStatuses", {})
1908
+ if (
1909
+ debug_rule_statuses
1910
+ and _rule_statuses_changed(debug_rule_statuses, last_debug_rule_statuses)
1911
+ and (log_type in {"All", "Rules"})
1912
+ ):
1913
+ for status in debug_rule_statuses:
1914
+ rule_log = (
1915
+ f"{status['RuleConfigurationName']}: {status['RuleEvaluationStatus']}"
1916
+ )
1917
+ print(rule_log)
1918
+
1919
+ last_debug_rule_statuses = debug_rule_statuses
1920
+
1921
+ # Print prettified logs related to the status of SageMaker Profiler rules.
1922
+ profiler_rule_statuses = description.get("ProfilerRuleEvaluationStatuses", {})
1923
+ if (
1924
+ profiler_rule_statuses
1925
+ and _rule_statuses_changed(profiler_rule_statuses, last_profiler_rule_statuses)
1926
+ and (log_type in {"All", "Rules"})
1927
+ ):
1928
+ for status in profiler_rule_statuses:
1929
+ rule_log = (
1930
+ f"{status['RuleConfigurationName']}: {status['RuleEvaluationStatus']}"
1931
+ )
1932
+ print(rule_log)
1933
+
1934
+ last_profiler_rule_statuses = profiler_rule_statuses
1935
+
1936
+ if wait:
1937
+ _check_job_status(job_name, description, "TrainingJobStatus")
1938
+ if dot:
1939
+ print()
1940
+ # Customers are not billed for hardware provisioning, so billable time is less than
1941
+ # total time
1942
+ training_time = description.get("TrainingTimeInSeconds")
1943
+ billable_time = description.get("BillableTimeInSeconds")
1944
+ if training_time is not None:
1945
+ print("Training seconds:", training_time * instance_count)
1946
+ if billable_time is not None:
1947
+ print("Billable seconds:", billable_time * instance_count)
1948
+ if description.get("EnableManagedSpotTraining"):
1949
+ saving = (1 - float(billable_time) / training_time) * 100
1950
+ print("Managed Spot Training savings: {:.1f}%".format(saving))
1951
+ return last_description
1952
+
1953
+
1954
+ def _check_job_status(job, desc, status_key_name):
1955
+ """Check to see if the job completed successfully.
1956
+
1957
+ If not, construct and raise a exceptions. (UnexpectedStatusException).
1958
+
1959
+ Args:
1960
+ job (str): The name of the job to check.
1961
+ desc (dict[str, str]): The result of ``describe_training_job()``.
1962
+ status_key_name (str): Status key name to check for.
1963
+
1964
+ Raises:
1965
+ exceptions.CapacityError: If the training job fails with CapacityError.
1966
+ exceptions.UnexpectedStatusException: If the training job fails.
1967
+ """
1968
+ status = desc[status_key_name]
1969
+ # If the status is capital case, then convert it to Camel case
1970
+ status = _STATUS_CODE_TABLE.get(status, status)
1971
+
1972
+ if status == "Stopped":
1973
+ logger.warning(
1974
+ "Job ended with status 'Stopped' rather than 'Completed'. "
1975
+ "This could mean the job timed out or stopped early for some other reason: "
1976
+ "Consider checking whether it completed as you expect."
1977
+ )
1978
+ elif status != "Completed":
1979
+ reason = desc.get("FailureReason", "(No reason provided)")
1980
+ job_type = status_key_name.replace("JobStatus", " job")
1981
+ troubleshooting = (
1982
+ "https://docs.aws.amazon.com/sagemaker/latest/dg/"
1983
+ "sagemaker-python-sdk-troubleshooting.html"
1984
+ )
1985
+ message = (
1986
+ "Error for {job_type} {job_name}: {status}. Reason: {reason}. "
1987
+ "Check troubleshooting guide for common errors: {troubleshooting}"
1988
+ ).format(
1989
+ job_type=job_type,
1990
+ job_name=job,
1991
+ status=status,
1992
+ reason=reason,
1993
+ troubleshooting=troubleshooting,
1994
+ )
1995
+ if "CapacityError" in str(reason):
1996
+ raise exceptions.CapacityError(
1997
+ message=message,
1998
+ allowed_statuses=["Completed", "Stopped"],
1999
+ actual_status=status,
2000
+ )
2001
+ raise exceptions.UnexpectedStatusException(
2002
+ message=message,
2003
+ allowed_statuses=["Completed", "Stopped"],
2004
+ actual_status=status,
2005
+ )
2006
+
2007
+
2008
+ def _flush_log_streams(
2009
+ stream_names, instance_count, client, log_group, job_name, positions, dot, color_wrap
2010
+ ):
2011
+ """Placeholder docstring"""
2012
+ if len(stream_names) < instance_count:
2013
+ # Log streams are created whenever a container starts writing to stdout/err, so this list
2014
+ # may be dynamic until we have a stream for every instance.
2015
+ try:
2016
+ streams = client.describe_log_streams(
2017
+ logGroupName=log_group,
2018
+ logStreamNamePrefix=job_name + "/",
2019
+ orderBy="LogStreamName",
2020
+ limit=min(instance_count, 50),
2021
+ )
2022
+ stream_names = [s["logStreamName"] for s in streams["logStreams"]]
2023
+
2024
+ while "nextToken" in streams:
2025
+ streams = client.describe_log_streams(
2026
+ logGroupName=log_group,
2027
+ logStreamNamePrefix=job_name + "/",
2028
+ orderBy="LogStreamName",
2029
+ limit=50,
2030
+ )
2031
+
2032
+ stream_names.extend([s["logStreamName"] for s in streams["logStreams"]])
2033
+
2034
+ positions.update(
2035
+ [
2036
+ (s, sagemaker_logs.Position(timestamp=0, skip=0))
2037
+ for s in stream_names
2038
+ if s not in positions
2039
+ ]
2040
+ )
2041
+ except ClientError as e:
2042
+ # On the very first training job run on an account, there's no log group until
2043
+ # the container starts logging, so ignore any errors thrown about that
2044
+ err = e.response.get("Error", {})
2045
+ if err.get("Code", None) != "ResourceNotFoundException":
2046
+ raise
2047
+
2048
+ if len(stream_names) > 0:
2049
+ if dot:
2050
+ print("")
2051
+ dot = False
2052
+ for idx, event in sagemaker_logs.multi_stream_iter(
2053
+ client, log_group, stream_names, positions
2054
+ ):
2055
+ color_wrap(idx, event["message"])
2056
+ ts, count = positions[stream_names[idx]]
2057
+ if event["timestamp"] == ts:
2058
+ positions[stream_names[idx]] = sagemaker_logs.Position(timestamp=ts, skip=count + 1)
2059
+ else:
2060
+ positions[stream_names[idx]] = sagemaker_logs.Position(
2061
+ timestamp=event["timestamp"], skip=1
2062
+ )
2063
+ else:
2064
+ dot = True
2065
+ print(".", end="")
2066
+ sys.stdout.flush()
2067
+
2068
+
2069
+ def _rule_statuses_changed(current_statuses, last_statuses):
2070
+ """Checks the rule evaluation statuses for SageMaker Debugger and Profiler rules."""
2071
+ if not last_statuses:
2072
+ return True
2073
+
2074
+ for current, last in zip(current_statuses, last_statuses):
2075
+ if (current["RuleConfigurationName"] == last["RuleConfigurationName"]) and (
2076
+ current["RuleEvaluationStatus"] != last["RuleEvaluationStatus"]
2077
+ ):
2078
+ return True
2079
+
2080
+ return False
2081
+
2082
+
2083
+ def _get_initial_job_state(description, status_key, wait):
2084
+ """Placeholder docstring"""
2085
+ status = description[status_key]
2086
+ job_already_completed = status in ("Completed", "Failed", "Stopped")
2087
+ return LogState.TAILING if wait and not job_already_completed else LogState.COMPLETE
2088
+
2089
+
2090
+ def _logs_init(boto_session, description, job):
2091
+ """Placeholder docstring"""
2092
+ if job == "Training":
2093
+ if "InstanceGroups" in description["ResourceConfig"]:
2094
+ instance_count = 0
2095
+ for instanceGroup in description["ResourceConfig"]["InstanceGroups"]:
2096
+ instance_count += instanceGroup["InstanceCount"]
2097
+ else:
2098
+ instance_count = description["ResourceConfig"]["InstanceCount"]
2099
+ elif job == "Transform":
2100
+ instance_count = description["TransformResources"]["InstanceCount"]
2101
+ elif job == "Processing":
2102
+ instance_count = description["ProcessingResources"]["ClusterConfig"]["InstanceCount"]
2103
+ elif job == "AutoML":
2104
+ instance_count = 0
2105
+
2106
+ stream_names = [] # The list of log streams
2107
+ positions = {} # The current position in each stream, map of stream name -> position
2108
+
2109
+ # Increase retries allowed (from default of 4), as we don't want waiting for a training job
2110
+ # to be interrupted by a transient exception.
2111
+ config = botocore.config.Config(retries={"max_attempts": 15})
2112
+ client = boto_session.client("logs", config=config)
2113
+ log_group = "/aws/sagemaker/" + job + "Jobs"
2114
+
2115
+ dot = False
2116
+
2117
+ from sagemaker.core.logs import ColorWrap
2118
+
2119
+ color_wrap = ColorWrap()
2120
+
2121
+ return instance_count, stream_names, positions, client, log_group, dot, color_wrap