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