如何在 sagemaker 管道内的 sagemaker 处理步骤/作业中安装需求?

问题描述 投票:0回答:1

我已经在 sagemaker 管道中设置了处理作业,并且我的项目具有以下文件

projectA
  - run.py
  - requirements.txt 

在运行脚本之前我需要安装一些依赖项,这些依赖项列在requirements.txt中。我不确定,如何设置处理步骤,以便它在运行我的脚本之前安装要求。

有什么想法吗?

from sagemaker.processing import ScriptProcessor
from sagemaker.workflow.steps import ProcessingStep

script_processor = ScriptProcessor(
    instance_type='ml.t3.medium', 
    instance_count=1, 
     ...
    command = ['python']
)

processing_step = ProcessingStep(
  name='p_step',
  processor= script_processor,
  code = './run.py',
  inputs = [
  ...]
)

python-3.x amazon-sagemaker amazon-sagemaker-studio
1个回答
0
投票

根据我对 SageMaker 管道和 SageMaker 处理作业的了解,有 2 种方法来管理依赖项 - 您可以创建一个映像并在定义

image_uri
对象时在
ScriptProcessor
中指定它,或者在作业运行时安装它们。这是第二种方法的方法。

我提供以下示例(它使用

SKLearnProcessor
类来完成任务):

1.定义加工作业:

sklearn_processor = SKLearnProcessor(
        framework_version="1.2-1",
        instance_type=instance_type_preprocessing.default_value,
        instance_count=instance_count.default_value,
        role=role_pipeline,
        sagemaker_session=pipeline_session,
)
  1. 定义以下作业步骤参数:

step_args = sklearn_processor.run(
        inputs=[
            ProcessingInput(
                input_name="raw-data",
                source=input_data,
                destination="/opt/ml/processing/input",
            ),
            ProcessingInput(
                input_name="preprocessor",
                source=os.path.join(BASE_DIR, "my_job/requirements/"),
                destination="/opt/ml/processing/input/code/requirements/",
            ),
        outputs=[
            ProcessingOutput(
                output_name="train",
                source="/opt/ml/processing/artifacts/ml_modelling/train",
                destination=Join(
                    on="/",
                    values=[
                        "s3:/",
                        default_bucket,
                        runtime_context,
                        pipeline_name,
                        ExecutionVariables.PIPELINE_EXECUTION_ID,
                        "PreprocessShortFare",
                        "output",
                        "train",
                    ],
                ),
            ),
        ],
        code=os.path.join(BASE_DIR, "my_job/preprocess.py"),
    )

输入中的第二项应指出requirements.txt 文件,我建议您将所有内容捆绑在 my_job 目录中。

  1. 然后,在作业的入口点脚本中,在导入所需的依赖项之前将以下内容放入其中:
import traceback
import os
import sys
import subprocess

subprocess.check_call(
    [
       sys.executable,
       "-m",
       "pip",
       "install",
       "-r",
       "/opt/ml/processing/input/code/requirements/requirements.txt",
    ]
)

4.继续正常添加依赖项的导入语句。

此方法的注意事项:仅当您信任requirements.txt 文件中的内容并且您不想构建映像并将其推送到 ECR 时才执行此操作。

如果这解决了您的问题和/或您对代码有疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.