

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 로컬 코드를 SageMaker 훈련 작업으로 실행
<a name="train-remote-decorator"></a>

로컬 기계 학습(ML) Python 코드를 대규모 단일 노드 Amazon SageMaker 훈련 작업 또는 다중 병렬 작업으로 실행할 수 있습니다. 다음 코드 예제와 같이 @remote 데코레이터로 코드에 주석을 달면 됩니다. 원격 함수에서는 [분산 훈련](https://docs.aws.amazon.com/sagemaker/latest/dg/distributed-training.html)(여러 인스턴스에 걸침)이 지원되지 않습니다.

```
@remote(**settings)
def divide(x, y):
    return x / y
```

SageMaker Python SDK는 기존 작업 영역 환경, 관련된 모든 데이터 처리 코드 및 데이터세트를 SageMaker 훈련 플랫폼에서 실행되는 SageMaker 훈련 작업으로 자동 변환합니다. 또한 영구 캐시 기능을 활성화하면 이전에 다운로드한 종속성 패키지를 캐싱하여 작업 시작 지연 시간을 더욱 줄일 수 있습니다. 이 작업 지연 시간 감소는 SageMaker AI 관리형 웜 풀만 사용할 때의 지연 시간 감소보다 큽니다. 자세한 내용은 [영구 캐시 사용](train-warm-pools.md#train-warm-pools-persistent-cache) 단원을 참조하십시오.

**참고**  
원격 함수에서는 분산 훈련 작업이 지원되지 않습니다.

다음 섹션에서는 @remote 데코레이터로 로컬 ML 코드에 주석을 달고 사용 사례에 맞게 환경을 조정하는 방법을 보여줍니다. 여기에는 환경을 사용자 지정하고 SageMaker 실험과 통합하는 것이 포함됩니다.

**Topics**
+ [

## 환경 설정
](#train-remote-decorator-env)
+ [

# 원격 함수 간접 호출
](train-remote-decorator-invocation.md)
+ [

# 구성 파일
](train-remote-decorator-config.md)
+ [

# 런타임 환경 사용자 지정
](train-remote-decorator-customize.md)
+ [

# 컨테이너 이미지 호환성
](train-remote-decorator-container.md)
+ [

# Amazon SageMaker Experiments를 사용하여 파라미터 및 지표 로깅하기
](train-remote-decorator-experiments.md)
+ [

# @remote 데코레이터와 함께 모듈식 코드 사용하기
](train-remote-decorator-modular.md)
+ [

# 런타임 종속성을 위한 프라이빗 리포지토리
](train-remote-decorator-private.md)
+ [

# 예제 노트북
](train-remote-decorator-examples.md)

## 환경 설정
<a name="train-remote-decorator-env"></a>

다음 세 가지 옵션 중 하나를 선택하여 환경을 설정합니다.

### Amazon SageMaker Studio Classic에서 코드 실행
<a name="train-remote-decorator-env-studio"></a>

SageMaker 노트북을 만들고 SageMaker Studio Classic 이미지에서 사용 가능한 이미지를 첨부하여 SageMaker Studio Classic에서 로컬 ML 코드에 주석을 달고 실행할 수 있습니다. 다음 지침은 SageMaker 노트북을 만들고 SageMaker Python SDK를 설치하며 데코레이터로 코드에 주석을 다는 데 도움이 됩니다.

1. 다음과 같이 SageMaker 노트북을 만들고 SageMaker Studio Classic에서 이미지를 첨부합니다.

   1. *Amazon SageMaker AI 개발자 안내서*의 [Amazon SageMaker Studio Classic 시작](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html)에 있는 지침을 따릅니다.

   1. 왼쪽 탐색 창에서 **Studio**를 선택합니다. 그러면 새 창이 열립니다.

   1. **시작하기** 대화 상자의 아래쪽 화살표에서 사용자 프로필을 선택합니다. 새 창이 열립니다.

   1. **Open Studio Classic**을 선택합니다.

   1. 기본 작업 영역에서 **런처 열기**를 선택합니다. 그러면 새 페이지가 열립니다.

   1. 기본 작업 영역에서 **노트북 생성**을 선택합니다.

   1. **환경 변경** 대화 상자의 **이미지** 옆에 있는 아래쪽 화살표에서 **Base Python 3.0**을 선택합니다.

      @remote 데코레이터는 SageMaker Studio Classic 노트북에 첨부된 이미지를 자동으로 감지하고 이를 사용하여 SageMaker 훈련 작업을 실행합니다. `image_uri`가 데코레이터 또는 구성 파일에서 인수로 지정된 경우 감지된 이미지 대신 `image_uri`에서 지정된 값이 사용됩니다.

      SageMaker Studio Classic에서 노트북을 생성하는 방법에 대한 자세한 내용은 [Amazon SageMaker Studio Classic 노트북 생성 또는 열기](https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks-create-open.html#notebooks-create-file-menu)의 **파일 메뉴에서 노트북 생성** 섹션을 참조하세요.

      사용 가능한 이미지 목록은 [지원되는 도커 이미지](https://docs.aws.amazon.com/sagemaker/latest/dg/train-remote-decorator-container.html)를 참조하세요.

1. SageMaker Python SDK를 설치합니다.

   SageMaker Studio Classic 노트북 내에서 @remote 함수를 사용하여 코드에 주석을 달려면 SageMaker Python SDK가 설치되어 있어야 합니다. 다음 코드 예제처럼 SageMaker Python SDK를 설치합니다.

   ```
   !pip install sagemaker
   ```

1. @remote 데코레이터를 사용하여 SageMaker 훈련 작업에서 함수를 실행할 수 있습니다.

   로컬 ML 코드를 실행하려면 먼저 종속 파일을 생성하여 SageMaker AI에 로컬 코드의 위치를 지정하도록 합니다. 이렇게 하려면 다음 단계를 따릅니다.

   1. SageMaker Studio Classic 런처 기본 작업 영역의 **유틸리티 및 파일**에서 **텍스트 파일**을 선택합니다. 그러면 텍스트 파일 `untitled.txt.`가 있는 새 탭이 열립니다.

      SageMaker Studio Classic 사용자 인터페이스(UI)에 대한 자세한 내용은 [Amazon SageMaker Studio Classic UI 개요](https://docs.aws.amazon.com//sagemaker/latest/dg/studio-ui.html)를 참조하세요.

   1. `untitled.txt `을 `requirements.txt`로 바꿉니다.

   1. SageMaker AI 라이브러리와 함께 코드에 필요한 모든 종속성을 `requirements.txt`에 추가합니다.

      예제 `divide` 함수에서 `requirements.txt`의 최소 코드 예제가 다음 섹션에 다음과 같이 제공됩니다.

      ```
      sagemaker
      ```

   1. 다음과 같이 종속 파일을 전달하여 원격 데코레이터로 코드를 실행합니다.

      ```
      from sagemaker.remote_function import remote
      
      @remote(instance_type="ml.m5.xlarge", dependencies='./requirements.txt')
      def divide(x, y):
          return x / y
      
      divide(2, 3.0)
      ```

      추가 코드 예제는 샘플 노트북 [quick\$1start.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-remote-function/quick_start/quick_start.ipynb)를 참조하세요.

      이미 SageMaker Studio Classic 노트북을 실행하고 있는 경우 **2의 지침에 따라 Python SDK를 설치하세요. SageMaker Python SDK를 설치**하고 커널을 다시 시작해야 합니다. 자세한 내용은 *Amazon SageMaker AI 개발자 안내서*의 [SageMaker Studio Classic 노트북 도구 모음 사용](https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks-menu.html)을 참조하세요.

### Amazon SageMaker Studio에서 코드 실행
<a name="train-remote-decorator-env-notebook"></a>

SageMaker 노트북 인스턴스에서 로컬 ML 코드에 주석을 달 수 있습니다. 다음 지침은 사용자 지정 커널로 노트북 인스턴스를 생성하고 SageMaker Python SDK를 설치하며 데코레이터로 코드에 주석을 다는 방법을 보여줍니다.

1. 사용자 지정 `conda` 커널을 사용하여 노트북 인스턴스를 생성합니다.

   SageMaker 훈련 작업 내에서 사용할 @remote 데코레이터로 로컬 ML 코드에 주석을 달 수 있습니다. 먼저 Python 버전 3.7 이상(최대 3.10.x)의 커널을 사용하도록 SageMaker 노트북 인스턴스를 생성하고 사용자 지정해야 합니다. 이렇게 하려면 다음 단계를 따릅니다.

   1. [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)에서 SageMaker AI 콘솔을 엽니다.

   1. 왼쪽 탐색 패널에서 **노트북**을 선택하여 옵션을 확장합니다.

   1. 확장된 옵션에서 **노트북 인스턴스**를 선택합니다.

   1. **노트북 인스턴스 생성** 버튼을 선택합니다. 그러면 새 페이지가 열립니다.

   1. **노트북 인스턴스 이름**의 경우 최대 63자로 공백 없이 이름을 입력합니다. 유효한 문자: **A-Z**, **a-z**, **0-9** 및 **.****:****\$1****=****@**** \$1****%****-**(하이픈).

   1. **노트북 인스턴스 설정** 대화 상자에서 **추가 구성** 옆의 오른쪽 화살표를 확장합니다.

   1. **수명 주기 구성 - 선택 사항**에서 아래쪽 화살표를 확장한 후 **새 수명 주기 구성 생성**을 선택합니다. 그러면 새 대화 상자가 열립니다.

   1. **이름**에 구성 설정 이름을 입력합니다.

   1. **스크립트** 대화 상자의 **노트북 시작** 탭에서 텍스트 상자의 기존 콘텐츠를 다음과 같은 스크립트로 바꿉니다.

      ```
      #!/bin/bash
      
      set -e
      
      sudo -u ec2-user -i <<'EOF'
      unset SUDO_UID
      WORKING_DIR=/home/ec2-user/SageMaker/custom-miniconda/
      source "$WORKING_DIR/miniconda/bin/activate"
      for env in $WORKING_DIR/miniconda/envs/*; do
          BASENAME=$(basename "$env")
          source activate "$BASENAME"
          python -m ipykernel install --user --name "$BASENAME" --display-name "Custom ($BASENAME)"
      done
      EOF
      
      echo "Restarting the Jupyter server.."
      # restart command is dependent on current running Amazon Linux and JupyterLab
      CURR_VERSION_AL=$(cat /etc/system-release)
      CURR_VERSION_JS=$(jupyter --version)
      
      if [[ $CURR_VERSION_JS == *$"jupyter_core     : 4.9.1"* ]] && [[ $CURR_VERSION_AL == *$" release 2018"* ]]; then
       sudo initctl restart jupyter-server --no-wait
      else
       sudo systemctl --no-block restart jupyter-server.service
      fi
      ```

   1. **스크립트** 대화 상자의 **노트북 생성** 탭에서 텍스트 상자의 기존 콘텐츠를 다음과 같은 스크립트로 바꿉니다.

      ```
      #!/bin/bash
      
      set -e
      
      sudo -u ec2-user -i <<'EOF'
      unset SUDO_UID
      # Install a separate conda installation via Miniconda
      WORKING_DIR=/home/ec2-user/SageMaker/custom-miniconda
      mkdir -p "$WORKING_DIR"
      wget https://repo.anaconda.com/miniconda/Miniconda3-4.6.14-Linux-x86_64.sh -O "$WORKING_DIR/miniconda.sh"
      bash "$WORKING_DIR/miniconda.sh" -b -u -p "$WORKING_DIR/miniconda" 
      rm -rf "$WORKING_DIR/miniconda.sh"
      # Create a custom conda environment
      source "$WORKING_DIR/miniconda/bin/activate"
      KERNEL_NAME="custom_python310"
      PYTHON="3.10"
      conda create --yes --name "$KERNEL_NAME" python="$PYTHON" pip
      conda activate "$KERNEL_NAME"
      pip install --quiet ipykernel
      # Customize these lines as necessary to install the required packages
      EOF
      ```

   1. 창 오른쪽 하단에 있는 **구성 생성** 버튼을 선택합니다.

   1. 창 오른쪽 하단에 있는 **노트북 인스턴스 생성** 버튼을 선택합니다.

   1. 노트북 인스턴스 **상태**가 **대기 중**에서 **서비스 중**으로 변경될 때까지 기다립니다.

1. 노트북 인스턴스에서 Jupyter notebook을 생성합니다.

   다음 지침은 새로 만든 SageMaker 인스턴스에서 Python 3.10을 사용하여 Jupyter notebook을 만드는 방법을 보여줍니다.

   1. 이전 단계의 노트북 인스턴스 **상태**가 **서비스 중**일 때 다음을 수행합니다.

      1. 새로 만든 노트북 인스턴스 **이름**이 들어 있는 행의 **작업**에서 **Jupyter 열기**를 선택합니다. 그러면 새 Jupyter 서버가 열립니다.

   1. Jupyter 서버의 오른쪽 상단 메뉴에서 **새로 만들기**를 선택합니다.

   1. 아래쪽 화살표에서 **conda\$1custom\$1python310**을 선택합니다. 이렇게 하면 Python 3.10 커널을 사용하는 새로운 Jupyter notebook이 만들어집니다. 이제 이 새로운 Jupyter notebook을 로컬 Jupyter notebook과 비슷하게 사용할 수 있습니다.

1. SageMaker Python SDK를 설치합니다.

   가상 환경을 실행한 후 다음 코드 예제를 사용하여 SageMaker Python SDK를 설치합니다.

   ```
   !pip install sagemaker
   ```

1. @remote 데코레이터를 사용하여 SageMaker 훈련 작업에서 함수를 실행할 수 있습니다.

   SageMaker 노트북 내에서 @remote 데코레이터로 로컬 ML 코드에 주석을 달면 SageMaker 훈련에서 자동으로 코드 함수를 해석하여 이를 SageMaker 훈련 작업으로 실행합니다. 다음을 따라 노트북을 설정합니다.

   1. 1단계인 **사용자 지정 커널로 SageMaker 노트북 인스턴스 생성하기**에서 만든 SageMaker 노트북 인스턴스의 노트북 메뉴에서 커널 이름을 선택합니다.

      자세한 내용은 [이미지 또는 커널 변경](https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks-run-and-manage-change-image.html)을 참조하세요.

   1. 아래쪽 화살표에서 3.7 이상의 Python 버전을 사용하는 사용자 지정 `conda` 커널을 선택합니다.

      예를 들어 `conda_custom_python310` 선택 시 Python 3.10용 커널이 선택됩니다.

   1. **선택**을 선택하세요.

   1. 커널 상태가 유휴로 표시될 때까지 기다립니다. 이는 커널이 시작되었음을 나타냅니다.

   1. Jupyter 서버 홈 오른쪽 상단 메뉴에서 **새로 만들기**를 선택합니다.

   1. 아래쪽 화살표 옆에서 **텍스트 파일**을 선택합니다. 그러면 새 텍스트 파일 `untitled.txt.`가 생성됩니다.

   1. `untitled.txt`을 `requirements.txt`로 이름을 변경하고 `sagemaker`과 함께 코드에 필요한 모든 종속성을 추가합니다.

   1. 아래와 같이 종속 파일을 전달하여 원격 데코레이터로 코드를 실행합니다.

      ```
      from sagemaker.remote_function import remote
      
      @remote(instance_type="ml.m5.xlarge", dependencies='./requirements.txt')
      def divide(x, y):
          return x / y
      
      divide(2, 3.0)
      ```

      추가 코드 예제는 샘플 노트북 [quick\$1start.ipnyb](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-remote-function/quick_start/quick_start.ipynb)를 참조하세요.

### 로컬 IDE 내에서 코드를 실행합니다.
<a name="train-remote-decorator-env-ide"></a>

선호하는 로컬 IDE 내에서 @remote 데코레이터를 사용하여 로컬 ML 코드에 주석을 달 수 있습니다. 다음 단계에서는 필수 사전 조건, Python SDK를 설치하는 방법, @remote 데코레이터로 코드에 주석을 다는 방법을 보여줍니다.

1. 다음과 같이 AWS Command Line Interface (AWS CLI)를 설정하고 역할을 생성하여 사전 조건을 설치합니다.
   + [Amazon SageMaker AI 사전 조건 설정](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-set-up.html#gs-cli-prereq)의 **AWS CLI 사전 조건** 섹션 지침에 따라 SageMaker AI 도메인에 온보딩합니다.
   + [SageMaker AI 역할](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html)의 **실행 역할 생성** 섹션에 따라 IAM 역할을 생성합니다.

1. PyCharm 또는 `conda`를 사용하거나 Python 버전 3.7 이상(최대 3.10.x)을 사용하여 가상 환경을 만듭니다.
   + 다음과 같이 PyCharm을 사용하여 가상 환경을 설정합니다.

     1. 기본 메뉴에서 **파일**을 선택합니다.

     1. **새 프로젝트**를 선택합니다.

     1. **새 환경 사용** 아래의 아래쪽 화살표에서 **Conda**를 선택합니다.

     1. **Python 버전** 필드에서 아래쪽 화살표를 사용하여 3.7 이상의 Python 버전을 선택합니다. 목록에 최대 3.10.x까지 있습니다.  
![\[\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/training-pycharm-ide.png)
   + Anaconda가 설치되어 있는 경우 다음과 같이 `conda`를 사용하여 가상 환경을 설정할 수 있습니다.
     + Anaconda 프롬프트 터미널 인터페이스를 엽니다.
     + Python 버전 3.7 이상(최대 3.10x)을 사용하여 새 `conda` 환경을 만들고 활성화합니다. 다음 코드 예제에서는 Python 버전 3.10을 사용하여 `conda` 환경을 생성하는 방법을 보여줍니다.

       ```
       conda create -n sagemaker_jobs_quick_start python=3.10 pip
       conda activate sagemaker_jobs_quick_start
       ```

1. SageMaker Python SDK를 설치합니다.

   선호하는 IDE에서 코드를 패키징하려면 Python 3.7 이상(최대 3.10x)을 사용하여 가상 환경을 설정해야 합니다. 호환되는 컨테이너 이미지도 필요합니다. 다음 코드 예제를 사용하여 SageMaker Python SDK를 설치합니다.

   ```
   pip install sagemaker
   ```

1. @remote 데코레이터 내부에 코드를 래핑합니다. SageMaker Python SDK는 코드 함수를 자동으로 해석하여 이를 SageMaker 훈련 작업으로 실행합니다. 다음 코드 예제에서는 필요한 라이브러리를 가져오고 SageMaker 세션을 설정하며 @remote 데코레이터로 함수에 주석을 다는 방법을 보여줍니다.

   필요한 종속성을 직접 제공하거나 활성 `conda` 환경의 종속성을 사용하여 코드를 실행할 수 있습니다.
   + 종속성을 직접 제공하려면 다음을 수행합니다.
     + 코드가 있는 작업 디렉터리에 `requirements.txt` 파일을 생성합니다.
     + SageMaker 라이브러리와 함께 코드에 필요한 모든 종속성을 추가합니다. 다음 섹션은 예제 `divide` 함수에서 `requirements.txt`의 최소 코드 예제를 제공합니다.

       ```
       sagemaker
       ```
     + 종속 파일을 전달하여 @remote 데코레이터로 코드를 실행합니다. 다음 코드 예제에서 `The IAM role name`은 SageMaker에서 작업을 실행하는 데 사용하려는 AWS Identity and Access Management (IAM) 역할 ARN으로 바꿉니다.

       ```
       import boto3
       import sagemaker
       from sagemaker.remote_function import remote
       
       sm_session = sagemaker.Session(boto_session=boto3.session.Session(region_name="us-west-2"))
       settings = dict(
           sagemaker_session=sm_session,
           role=<The IAM role name>,
           instance_type="ml.m5.xlarge",
           dependencies='./requirements.txt'
       )
       
       @remote(**settings)
       def divide(x, y):
           return x / y
       
       
       if __name__ == "__main__":
           print(divide(2, 3.0))
       ```
   + 활성 `conda` 환경의 종속성을 사용하려면 다음과 같이 `dependencies` 파라미터 `auto_capture` 값을 사용합니다.

     ```
     import boto3
     import sagemaker
     from sagemaker.remote_function import remote
     
     sm_session = sagemaker.Session(boto_session=boto3.session.Session(region_name="us-west-2"))
     settings = dict(
         sagemaker_session=sm_session,
         role=<The IAM role name>,
         instance_type="ml.m5.xlarge",
         dependencies="auto_capture"
     )
     
     @remote(**settings)
     def divide(x, y):
         return x / y
     
     
     if __name__ == "__main__":
         print(divide(2, 3.0))
     ```
**참고**  
Jupyter notebook 내부에 이전 코드를 구현할 수도 있습니다. PyCharm Professional 에디션은 Jupyter를 기본적으로 지원합니다. 자세한 지침은 PyCharm 설명서의 [Jupyter notebook 지원](https://www.jetbrains.com/help/pycharm/ipython-notebook-support.html)을 참조하세요.

# 원격 함수 간접 호출
<a name="train-remote-decorator-invocation"></a>

@remote 데코레이터 내에서 함수를 호출하려면 다음 방법 중 하나를 사용하세요.
+ [@remote 데코레이터를 사용하여 함수를 호출](#train-remote-decorator-invocation-decorator).
+ [`RemoteExecutor` API를 사용하여 함수 호출](#train-remote-decorator-invocation-api).

@remote 데코레이터 메서드를 사용하여 함수를 호출하는 경우 훈련 작업은 함수가 완료될 때까지 기다렸다가 새 작업을 시작합니다. 하지만 `RemoteExecutor` API를 사용하는 경우 둘 이상의 작업을 병렬로 실행할 수 있습니다. 다음 섹션에서는 함수를 호출하는 두 가지 방법을 모두 보여줍니다.

## @remote 데코레이터를 사용하여 함수를 호출
<a name="train-remote-decorator-invocation-decorator"></a>

@remote 데코레이터를 사용하여 함수에 주석을 달 수 있습니다. SageMaker AI는 데코레이터 내의 코드를 SageMaker 훈련 작업으로 변환합니다. 그러면 훈련 작업은 데코레이터 내에서 함수를 호출하고 작업이 완료될 때까지 기다립니다. 다음 코드 예시는 필수 라이브러리를 가져오고 SageMaker AI 인스턴스를 시작하며 @remote 데코레이터로 행렬 곱셈에 주석을 다는 방법을 보여줍니다.

```
from sagemaker.remote_function import remote
import numpy as np

@remote(instance_type="ml.m5.large")
def matrix_multiply(a, b):
    return np.matmul(a, b)
    
a = np.array([[1, 0],
             [0, 1]])
b = np.array([1, 2])

assert (matrix_multiply(a, b) == np.array([1,2])).all()
```

데코레이터는 다음과 같이 정의됩니다.

```
def remote(
    *,
    **kwarg):
        ...
```

데코레이팅된 함수를 호출하면 SageMaker Python SDK는 오류로 인해 발생한 모든 예외를 로컬 메모리로 로드합니다. 다음 코드 예제에서는 divide 함수에 대한 첫 번째 호출이 성공적으로 완료되고 그 결과가 로컬 메모리로 로드됩니다. divide 함수를 두 번째로 호출하면 코드가 오류를 반환하고 이 오류가 로컬 메모리로 로드됩니다.

```
from sagemaker.remote_function import remote
import pytest

@remote()
def divide(a, b):
    return a/b

# the underlying job is completed successfully 
# and the function return is loaded
assert divide(10, 5) == 2

# the underlying job fails with "AlgorithmError" 
# and the function exception is loaded into local memory 
with pytest.raises(ZeroDivisionError):
    divide(10, 0)
```

**참고**  
데코레이팅된 함수는 원격 작업으로 실행됩니다. 스레드가 중단되더라도 기본 작업은 중지되지 않습니다.

### 로컬 변수 값을 변경하는 방법
<a name="train-remote-decorator-invocation-decorator-value"></a>

데코레이터 함수는 원격 머신에서 실행됩니다. 데코레이팅된 함수 내에서 로컬이 아닌 변수 또는 입력 인수를 변경해도 로컬 값은 변경되지 않습니다.

다음 코드 예제에서는 데코레이터 함수 내에 목록과 딕셔너리가 추가됩니다. 이는 데코레이터 함수가 호출될 때 변경되지 않습니다.

```
a = []

@remote
def func():
    a.append(1)

# when func is invoked, a in the local memory is not modified        
func() 
func()

# a stays as []
    
a = {}
@remote
def func(a):
    # append new values to the input dictionary
    a["key-2"] = "value-2"
    
a = {"key": "value"}
func(a)

# a stays as {"key": "value"}
```

데코레이터 함수 내에서 선언된 로컬 변수 값을 변경하려면 함수에서 변수를 반환하세요. 다음 코드 예제는 함수에서 반환되는 로컬 변수 값이 변경되는 것을 보여줍니다.

```
a = {"key-1": "value-1"}

@remote
def func(a):
    a["key-2"] = "value-2"
    return a

a = func(a)

-> {"key-1": "value-1", "key-2": "value-2"}
```

### 데이터 직렬화 및 역직렬화
<a name="train-remote-decorator-invocation-input-output"></a>

원격 함수를 간접적으로 호출하면 SageMaker AI는 입력 및 출력 단계에서 함수 인수를 자동으로 직렬화합니다. 함수 인수와 반환은 [cloudpickle](https://github.com/cloudpipe/cloudpickle)을 사용하여 직렬화됩니다. SageMaker AI는 다음과 같은 Python 객체 및 함수의 직렬화를 지원합니다.
+ 딕셔너리, 리스트, 부동 소수, 정수, 문자열, 부울 값, 튜플 등 내장된 Python 객체
+ Numpy 배열
+ Pandas Dataframe
+ Scikit-learn 데이터세트 및 예측기
+ PyTorch 모델
+ TensorFlow 모델
+ XGBoost용 Booster 클래스

다음은 몇 가지 제한 사항과 함께 사용 가능합니다.
+ Dask DataFrame
+ XGBoost Dmatrix 클래스
+ TensorFlow 데이터 세트 및 하위 클래스
+ PyTorch 모델

다음 섹션에는 몇 가지 제한 사항이 있는 이전 Python 클래스를 원격 함수로 사용하는 모범 사례, SageMaker AI가 직렬화된 데이터를 저장하는 위치 및 이에 대한 액세스를 관리하는 방법에 대한 정보가 포함되어 있습니다.

#### 원격 데이터 직렬화 지원이 제한된 Python 클래스 모범 사례
<a name="train-remote-decorator-invocation-input-output-bestprac"></a>

이 섹션에 나열된 Python 클래스는 제한 사항과 함께 사용할 수 있습니다. 다음 섹션에서는 다음과 같은 Python 클래스를 사용하는 방법에 대한 모범 사례를 설명합니다.
+ [Dask](https://www.dask.org/) DataFrames
+ XGBoost DMatric 클래스
+ TensorFlow 데이터세트 및 하위 클래스
+ PyTorch 모델

##### DNS의 모범 사례
<a name="train-remote-decorator-invocation-input-output-bestprac-dask"></a>

[Dask](https://www.dask.org/)는 Python에서 병렬 컴퓨팅에 사용되는 오픈 소스 라이브러리입니다. 이 섹션에서는 다음을 보여줍니다.
+ Dask DataFrame을 원격 함수로 전달하는 방법
+ Dask DataFrame의 요약 통계를 Pandas DataFrame으로 변환하는 방법

##### Dask DataFrame을 원격 함수로 전달하는 방법
<a name="train-remote-decorator-invocation-input-output-bestprac-dask-pass"></a>

[Dask DataFrame](https://docs.dask.org/en/latest/dataframe.html)은 사용 가능한 메모리보다 더 많은 메모리가 필요한 데이터세트를 보유할 수 있기 때문에 대량 데이터세트를 처리하는 데 자주 사용됩니다. 이는 Dask DataFrame이 메모리에 로컬 데이터를 로드하지 않기 때문입니다. Dask DataFrame을 함수 인수로 원격 함수에 전달하면 Dask는 데이터 자체 대신 로컬 디스크 또는 클라우드 스토리지의 데이터에 대한 참조를 전달할 수 있습니다. 다음 코드는 빈 DataFrame에서 작동하게 될 원격 함수 내에 Dask DataFrame을 전달하는 예제를 보여줍니다.

```
#Do not pass a Dask DataFrame  to your remote function as follows
def clean(df: dask.DataFrame ):
    cleaned = df[] \ ...
```

Dask는 사용자가 DataFrame을 사용할 때만 메모리에 Dask DataFrame 데이터를 로드합니다. 원격 함수 내에서 Dask DataFrame을 사용하려면 데이터 경로를 제공해야 합니다. 그러면 Dask는 코드 실행 시 지정한 데이터 경로에서 직접 데이터세트를 읽습니다.

다음 코드 예제에서는 원격 함수 `clean` 내에서 Dask DataFrame을 사용하는 방법을 보여줍니다. 코드 예제에서는 Dask DataFrame 대신 `raw_data_path`가 clean으로 전달됩니다. 코드가 실행되면 `raw_data_path`에 지정된 Amazon S3 버킷의 위치에서 데이터세트를 직접 읽습니다. 그런 다음 `persist` 함수는 후속 `random_split` 함수를 쉽게 수행할 수 있도록 데이터세트를 메모리에 보관하고 Dask DataFrame API 함수를 사용하여 S3 버킷의 출력 데이터 경로에 다시 기록합니다.

```
import dask.dataframe as dd

@remote(
   instance_type='ml.m5.24xlarge',
   volume_size=300, 
   keep_alive_period_in_seconds=600)
#pass the data path to your remote function rather than the Dask DataFrame  itself
def clean(raw_data_path: str, output_data_path: str: split_ratio: list[float]):
    df = dd.read_parquet(raw_data_path) #pass the path to your DataFrame 
    cleaned = df[(df.column_a >= 1) & (df.column_a < 5)]\
        .drop(['column_b', 'column_c'], axis=1)\
        .persist() #keep the data in memory to facilitate the following random_split operation

    train_df, test_df = cleaned.random_split(split_ratio, random_state=10)

    train_df.to_parquet(os.path.join(output_data_path, 'train')
    test_df.to_parquet(os.path.join(output_data_path, 'test'))
    
clean("s3://amzn-s3-demo-bucket/raw/", "s3://amzn-s3-demo-bucket/cleaned/", split_ratio=[0.7, 0.3])
```

##### Dask DataFrame의 요약 통계를 Pandas DataFrame으로 변환하는 방법
<a name="train-remote-decorator-invocation-input-output-bestprac-dask-pd"></a>

Dask DataFrame의 요약 통계는 다음 예제 코드와 같이 `compute` 메서드를 호출하여 Pandas DataFrame으로 변환할 수 있습니다. 이 예제에서 S3 버킷에는 메모리 또는 Pandas 데이터 프레임에 담을 수 없는 대량 Dask DataFrame이 포함되어 있습니다. 다음 예제에서 원격 함수는 데이터세트를 스캔하고 출력 통계를 포함하는 Dask DataFrame을 `describe`에서 Pandas DataFrame으로 반환합니다.

```
executor = RemoteExecutor(
    instance_type='ml.m5.24xlarge',
    volume_size=300, 
    keep_alive_period_in_seconds=600)

future = executor.submit(lambda: dd.read_parquet("s3://amzn-s3-demo-bucket/raw/").describe().compute())

future.result()
```

##### XGBoost DMatric 클래스의 모범 사례
<a name="train-remote-decorator-invocation-input-output-bestprac-xgboost"></a>

DMatrix는 XGBoost에서 데이터를 로드하는 데 사용하는 내부 데이터 구조입니다. DMatrix 객체는 컴퓨팅 세션 간에 쉽게 이동할 수 있도록 피클링할 수 없습니다. DMatrix 인스턴스를 직접 전달하면 `SerializationError`로 실패하게 됩니다.

##### 원격 함수에 데이터 객체를 전달하고 XGBoost를 사용하여 훈련하는 방법
<a name="train-remote-decorator-invocation-input-output-bestprac-xgboost-pass"></a>

Pandas DataFrame을 DMatrix 인스턴스로 변환하고 이를 원격 함수의 훈련에 사용하려면 다음 코드 예제와 같이 원격 함수에 직접 전달합니다.

```
import xgboost as xgb

@remote
def train(df, params):
    #Convert a pandas dataframe into a DMatrix DataFrame and use it for training
    dtrain = DMatrix(df) 
    return xgb.train(dtrain, params)
```

##### TensorFlow 데이터세트 및 하위 클래스의 모범 사례
<a name="train-remote-decorator-invocation-input-output-bestprac-tf"></a>

TensorFlow 데이터세트 및 하위 클래스는 TensorFlow가 훈련 중에 데이터를 로드하는 데 사용하는 내부 객체입니다. TensorFlow 데이터세트 및 하위 클래스는 컴퓨팅 세션 간에 쉽게 이동할 수 있도록 피클링할 수 없습니다. Tensorflow 데이터세트 또는 하위 클래스를 직접 전달하면 `SerializationError`로 실패하게 됩니다. 다음 코드 예제와 같이 Tensorflow I/O API를 사용하여 스토리지에서 데이터를 로드합니다.

```
import tensorflow as tf
import tensorflow_io as tfio

@remote
def train(data_path: str, params):
    
    dataset = tf.data.TextLineDataset(tf.data.Dataset.list_files(f"{data_path}/*.txt"))
    ...
    
train("s3://amzn-s3-demo-bucket/data", {})
```

##### PyTorch 모델의 모범 사례
<a name="train-remote-decorator-invocation-input-output-bestprac-pytorch"></a>

PyTorch 모델은 직렬화할 수 있으며 로컬 환경과 원격 함수 간에 전달 가능합니다. 로컬 환경과 원격 환경의 디바이스 유형(예: GPU 및 CPU)이 다른 경우 훈련된 모델을 로컬 환경에 반환할 수 없습니다. 예를 들어 GPU가 없는 로컬 환경에서 다음 코드를 개발하고 GPU가 있는 인스턴스에서 실행할 경우 훈련된 모델을 직접 반환하면 `DeserializationError`가 발생합니다.

```
# Do not return a model trained on GPUs to a CPU-only environment as follows

@remote(instance_type='ml.g4dn.xlarge')
def train(...):
    if torch.cuda.is_available():
        device = torch.device("cuda")
    else:
        device = torch.device("cpu") # a device without GPU capabilities
    
    model = Net().to(device)
    
    # train the model
    ...
    
    return model
    
model = train(...) #returns a DeserializationError if run on a device with GPU
```

GPU 환경에서 훈련된 모델을 CPU 기능만 포함된 모델로 반환하려면 아래 코드 예제와 같이 PyTorch 모델 I/O API를 직접 사용합니다.

```
import s3fs

model_path = "s3://amzn-s3-demo-bucket/folder/"

@remote(instance_type='ml.g4dn.xlarge')
def train(...):
    if torch.cuda.is_available():
        device = torch.device("cuda")
    else:
        device = torch.device("cpu")
    
    model = Net().to(device)
    
    # train the model
    ...
    
    fs = s3fs.FileSystem()
    with fs.open(os.path.join(model_path, 'model.pt'), 'wb') as file:
        torch.save(model.state_dict(), file) #this writes the model in a device-agnostic way (CPU vs GPU)
    
train(...) #use the model to train on either CPUs or GPUs

model = Net()
fs = s3fs.FileSystem()with fs.open(os.path.join(model_path, 'model.pt'), 'rb') as file:
    model.load_state_dict(torch.load(file, map_location=torch.device('cpu')))
```

#### SageMaker AI가 직렬화된 데이터를 저장하는 위치
<a name="train-remote-decorator-invocation-input-output-storage"></a>

원격 함수를 간접적으로 호출하면 SageMaker AI는 입력 및 출력 단계에서 함수 인수를 자동으로 직렬화하고 값을 반환합니다. 직렬화된 이 데이터는 S3 버킷의 루트 디렉터리에 저장됩니다. 구성 파일에 루트 디렉터리 `<s3_root_uri>`를 지정합니다. 파라미터 `job_name`이 자동으로 생성됩니다.

루트 디렉터리 아래에 SageMaker AI는 `<job_name>` 폴더를 생성하는데 여기에는 현재 작업 디렉터리, 직렬화된 함수, 직렬화된 함수의 인수, 결과, 직렬화된 함수 간접 호출로 인해 발생한 모든 예외가 들어 있습니다.

`<job_name>` 아래 디렉터리 `workdir`에는 현재 작업 디렉터리의 압축 아카이브가 들어 있습니다. 압축 아카이브에는 작업 디렉터리의 모든 Python 파일과 `requirements.txt` 파일이 포함되어 있는데 이는 원격 함수를 실행하는 데 필요한 종속성을 지정합니다.

다음은 구성 파일에 지정하는 S3 버킷의 폴더 구조 예제입니다.

```
<s3_root_uri>/ # specified by s3_root_uri or S3RootUri
    <job_name>/ #automatically generated for you
        workdir/workspace.zip # archive of the current working directory (workdir)
        function/ # serialized function
        arguments/ # serialized function arguments
        results/ # returned output from the serialized function including the model
        exception/ # any exceptions from invoking the serialized function
```

S3 버킷에 지정하는 루트 디렉터리는 장기 스토리지용이 아닙니다. 직렬화된 데이터는 직렬화 중에 사용된 Python 버전 및 기계 학습(ML) 프레임워크 버전과 밀접하게 연결되어 있습니다. Python 버전 또는 ML 프레임워크를 업그레이드하면 직렬화된 데이터를 사용하지 못할 수 있습니다. 대신 다음을 수행합니다.
+ Python 버전과 ML 프레임워크에 구애받지 않는 형식으로 모델 및 모델 아티팩트를 저장합니다.
+ Python 또는 ML 프레임워크를 업그레이드하는 경우 장기 스토리지에서 모델 결과에 액세스할 수 있습니다.

**중요**  
지정된 시간이 지난 후 직렬화된 데이터를 삭제하려면 S3 버킷에 [수명 구성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-set-lifecycle-configuration-intro.html)을 설정합니다.

**참고**  
Python [pickle](https://docs.python.org/3/library/pickle.html) 모듈로 직렬화된 파일은 CSV, Parquet, JSON 등 다른 데이터 형식보다 이동성이 낮을 수 있습니다. 출처를 알 수 없는 피클된 파일을 로드하지 않도록 주의하세요.

원격 함수의 구성 파일에 포함할 내용에 대한 추가 정보는 [구성 파일](https://docs.aws.amazon.com/sagemaker/latest/dg/train-remote-decorator-config.html)을 참조하세요.

#### 직렬화된 데이터에 대한 액세스
<a name="train-remote-decorator-invocation-input-output-access"></a>

관리자는 직렬화된 데이터 설정을 제공할 수 있으며 여기에는 구성 파일에서의 위치 및 모든 암호화 설정이 포함됩니다. 기본적으로 직렬화된 데이터는 AWS Key Management Service (AWS KMS) 키로 암호화됩니다. 또한 관리자는 [버킷 정책](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html)을 사용하여 구성 파일에 지정한 루트 디렉터리의 액세스를 제한할 수 있습니다. 구성 파일은 여러 프로젝트 및 작업에서 공유하며 사용할 수 있습니다. 자세한 정보는 [구성 파일](https://docs.aws.amazon.com/sagemaker/latest/dg/train-remote-decorator-config.html)을 참조하세요.

## `RemoteExecutor` API를 사용하여 함수 호출
<a name="train-remote-decorator-invocation-api"></a>

`RemoteExecutor` API를 사용하여 함수를 호출할 수 있습니다. SageMaker AI Python SDK는 `RemoteExecutor` 직접 호출 내의 코드를 SageMaker AI 훈련 작업으로 변환합니다. 그러면 훈련 작업에서 함수를 비동기식 작업으로 호출하고 퓨처를 반환합니다. `RemoteExecutor` API를 사용하는 경우 둘 이상의 작업을 병렬로 실행할 수 있습니다. Python의 퓨처에 대한 자세한 내용은 [Future](https://docs.python.org/3/library/asyncio-future.html)를 참조하세요.

다음 코드 예시에서는 필수 라이브러리를 가져오고 함수를 정의하며 SageMaker AI 인스턴스를 시작하고 API를 사용하여 `2` 작업을 병렬로 실행하기 위한 요청을 제출하는 방법을 보여줍니다.

```
from sagemaker.remote_function import RemoteExecutor

def matrix_multiply(a, b):
    return np.matmul(a, b)


a = np.array([[1, 0],
             [0, 1]])
b = np.array([1, 2])

with RemoteExecutor(max_parallel_job=2, instance_type="ml.m5.large") as e:
    future = e.submit(matrix_multiply, a, b)

assert (future.result() == np.array([1,2])).all()
```

`RemoteExecutor` 클래스는 [Concurrent.Futures.Executor](https://docs.python.org/3/library/concurrent.futures.html) 라이브러리를 구현한 것입니다.

다음 코드 예제에서는 `RemoteExecutorAPI`를 사용하여 함수를 정의하고 호출하는 방법을 보여줍니다. 이 예제에서 `RemoteExecutor`는 총 `4`개 작업을 제출하지만 `2`개만 병렬로 제출합니다. 마지막 두 개 작업은 오버헤드를 최소화하면서 클러스터를 재사용합니다.

```
from sagemaker.remote_function.client import RemoteExecutor

def divide(a, b):
    return a/b 

with RemoteExecutor(max_parallel_job=2, keep_alive_period_in_seconds=60) as e:
    futures = [e.submit(divide, a, 2) for a in [3, 5, 7, 9]]

for future in futures:
    print(future.result())
```

`max_parallel_job` 파라미터는 컴퓨팅 리소스 할당을 최적화하지 않고 속도 제한 메커니즘으로만 사용됩니다. 이전 코드 예제에서 `RemoteExecutor`는 작업이 제출되기 전에 두 개의 병렬 작업을 위한 컴퓨팅 리소스를 예약하지 않습니다. `max_parallel_job` 또는 @remote 데코레이터의 기타 파라미터에 대한 자세한 내용은 [원격 함수 클래스 및 메서드 사양](https://sagemaker.readthedocs.io/en/stable/remote_function/sagemaker.remote_function.html)을 참조하세요.

### `RemoteExecutor` API의 퓨처 클래스
<a name="train-remote-decorator-invocation-api-future"></a>

퓨처 클래스는 반환 함수가 비동기식으로 호출될 때 훈련 작업의 반환 함수를 나타내는 퍼블릭 클래스입니다. 퓨처 클래스는 [Concurrent.futures.future](https://docs.python.org/3/library/concurrent.futures.html) 클래스를 구현합니다. 이 클래스는 기본 작업을 수행하고 데이터를 메모리로 로드하는 데 사용할 수 있습니다.

# 구성 파일
<a name="train-remote-decorator-config"></a>

Amazon SageMaker Python SDK는 AWS 인프라 기본 유형에 대한 기본값 설정을 지원합니다. 관리자가 이러한 기본값을 구성하면 지원되는 API를 호출할 때 SageMaker Python SDK가 이를 자동으로 전달합니다. 데코레이터 함수의 인수는 구성 파일 내에 넣을 수 있습니다. 이를 통해 인프라와 관련된 설정을 코드 베이스에서 분리할 수 있습니다. 원격 함수 및 메서드의 파라미터와 인수에 대한 자세한 내용은 [원격 함수 클래스 및 메서드 사양](https://sagemaker.readthedocs.io/en/stable/remote_function/sagemaker.remote_function.html)을 참조하세요.

네트워크 구성, IAM 역할, 입력용 Amazon S3 폴더, 출력 데이터 및 구성 파일 내 태그에 대한 인프라 설정을 수행할 수 있습니다. @remote 데코레이터 또는 `RemoteExecutor` API를 사용하여 함수를 호출할 때 구성 파일을 사용할 수 있습니다.

다음은 종속성, 리소스 및 기타 인수를 정의하는 예제 구성 파일입니다. 이 예제 구성 파일은 @remote 데코레이터 또는 RemoteExecutor API를 사용하여 시작된 함수를 호출하는 데 사용됩니다.

```
SchemaVersion: '1.0'
SageMaker:
  PythonSDK:
    Modules:
      RemoteFunction:
        Dependencies: 'path/to/requirements.txt'
        EnableInterContainerTrafficEncryption: true
        EnvironmentVariables: {'EnvVarKey': 'EnvVarValue'}
        ImageUri: '366666666666.dkr.ecr.us-west-2.amazonaws.com/my-image:latest'
        IncludeLocalWorkDir: true
        CustomFileFilter: 
          IgnoreNamePatterns:
          - "*.ipynb"
          - "data"
        InstanceType: 'ml.m5.large'
        JobCondaEnvironment: 'your_conda_env'
        PreExecutionCommands:
            - 'command_1'
            - 'command_2'
        PreExecutionScript: 'path/to/script.sh'
        RoleArn: 'arn:aws:iam::366666666666:role/MyRole'
        S3KmsKeyId: 'yourkmskeyid'
        S3RootUri: 's3://amzn-s3-demo-bucket/my-project'
        VpcConfig:
            SecurityGroupIds: 
            - 'sg123'
            Subnets: 
            - 'subnet-1234'
        Tags: [{'Key': 'yourTagKey', 'Value':'yourTagValue'}]
        VolumeKmsKeyId: 'yourkmskeyid'
```

@remote 데코레이터 및 `RemoteExecutor`가 다음 구성 파일에서 `Dependencies`을 검색합니다.
+ 관리자 정의 구성 파일.
+ 사용자 정의 구성 파일.

이러한 구성 파일의 기본 위치는 환경에 따라 다르고 환경과 관련이 있습니다. 다음 코드 예제에서는 관리자 및 사용자 구성 파일의 기본 위치를 반환합니다. 이러한 명령은 SageMaker Python SDK를 사용하는 것과 동일한 환경에서 실행해야 합니다.

```
import os
from platformdirs import site_config_dir, user_config_dir

#Prints the location of the admin config file
print(os.path.join(site_config_dir("sagemaker"), "config.yaml"))

#Prints the location of the user config file
print(os.path.join(user_config_dir("sagemaker"), "config.yaml"))
```

관리자 정의 구성 파일 및 사용자 정의 구성 파일 경로에 각각 `SAGEMAKER_ADMIN_CONFIG_OVERRIDE` 및 `SAGEMAKER_USER_CONFIG_OVERRIDE` 환경 변수를 설정하여 이러한 파일의 기본 위치를 재정의할 수 있습니다.

관리자 정의 구성 파일 및 사용자 정의 구성 파일 모두에 키가 있는 경우 사용자 정의 파일의 값이 사용됩니다.

# 런타임 환경 사용자 지정
<a name="train-remote-decorator-customize"></a>

선호하는 로컬 통합 개발 환경(IDE), SageMaker 노트북 또는 SageMaker Studio Classic 노트북을 사용하여 ML 코드를 작성하도록 런타임 환경을 사용자 지정할 수 있습니다. SageMaker AI는 함수 및 종속성을 SageMaker 훈련 작업으로 패키징하고 제출하는 데 도움을 줍니다. 이를 통해 SageMaker 훈련 서버의 용량에 액세스하여 훈련 작업을 실행할 수 있습니다.

원격 데코레이터와 함수를 호출하는 `RemoteExecutor` 메서드를 통해 사용자는 런타임 환경을 정의하고 사용자 지정할 수 있습니다. `requirements.txt` 파일 또는 conda 환경 YAML 파일을 사용할 수 있습니다.

conda 환경 YAML 파일 및 `requirements.txt` 파일을 모두 사용하여 런타임 환경을 사용자 지정하려면 다음 코드 예제를 참조하세요.

```
# specify a conda environment inside a yaml file
@remote(instance_type="ml.m5.large",
        image_uri = "my_base_python:latest", 
        dependencies = "./environment.yml")
def matrix_multiply(a, b):
    return np.matmul(a, b)

# use a requirements.txt file to import dependencies
@remote(instance_type="ml.m5.large",
        image_uri = "my_base_python:latest", 
        dependencies = './requirements.txt')
def matrix_multiply(a, b):
    return np.matmul(a, b)
```

또는 `dependencies`을 `auto_capture`로 설정하여 SageMaker Python SDK가 활성 conda 환경에 설치된 종속성을 캡처하도록 할 수 있습니다. `auto_capture`가 안정적으로 작동하려면 다음이 필요합니다.
+ 활성 conda 환경이 있어야 합니다. 잠재적인 종속성 충돌을 줄이려면 원격 작업에 `base` conda 환경을 사용하지 않는 것이 좋습니다. 또한 `base` conda 환경을 사용하지 않으면 원격 작업에서 환경을 더 빠르게 설정할 수 있습니다.
+ 파라미터 `--extra-index-url` 값과 함께 pip를 사용하여 종속 항목을 설치해서는 안 됩니다.
+ 로컬 개발 환경에서 conda로 설치한 패키지 및 pip로 설치한 패키지 간 종속성 충돌이 없어야 합니다.
+ 로컬 개발 환경에 Linux와 호환되지 않는 운영 체제별 종속성이 포함되어서는 안 됩니다.

`auto_capture`가 작동하지 않는 경우 이 섹션의 첫 번째 코딩 예제에 설명된 대로 종속성을 requirement.txt 또는 conda environment.yaml 파일로 전달하는 것이 좋습니다.

# 컨테이너 이미지 호환성
<a name="train-remote-decorator-container"></a>

다음 테이블은 @remote 데코레이터와 호환되는 SageMaker 훈련 이미지 목록을 보여줍니다.


| 이름 | Python 버전 | 이미지 URI - CPU | 이미지 URI - GPU | 
| --- | --- | --- | --- | 
|  데이터 과학  |  3.7(py37)  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  | 
|  데이터 과학 2.0  |  3.8(py38)  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  | 
|  데이터 과학 3.0  |  3.10(py310)  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  | 
|  Base Python 2.0  |  3.8(py38)  |  Python SDK는 개발 환경이 Python 3.8 런타임을 사용하고 있음을 감지하면 이 이미지를 선택합니다. 그렇지 않으면 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 Python SDK가 이 이미지를 자동으로 선택합니다.  |  SageMaker Studio Classic 노트북에만 해당합니다. Python SDK는 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 이미지 URI를 자동으로 선택합니다.  | 
|  Base Python 3.0  |  3.10(py310)  |  Python SDK는 개발 환경이 Python 3.8 런타임을 사용하고 있음을 감지하면 이 이미지를 선택합니다. 그렇지 않으면 SageMaker Studio Classic 노트북 커널 이미지로 사용될 때 Python SDK가 이 이미지를 자동으로 선택합니다.  |  SageMaker Studio Classic 노트북에만 해당합니다. Studio Classic 노트북 커널 이미지로 사용될 때 Python SDK가 이미지 URI를 자동으로 선택합니다.  | 
|  SageMaker 훈련용 DLC-TensorFlow 2.12.0  |  3.10(py310)  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.12.0-cpu-py310-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.12.0-gpu-py310-cu118-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-Tensorflow 2.11.0  |  3.9(py39)  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.11.0-cpu-py39-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.11.0-gpu-py39-cu112-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-TensorFlow 2.10.1  |  3.9(py39)  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.10.1-cpu-py39-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.10.1-gpu-py39-cu112-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-TensorFlow 2.9.2  |  3.9(py39)  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.9.2-cpu-py39-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.9.2-gpu-py39-cu112-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-TensorFlow 2.8.3  |  3.9(py39)  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.8.3-cpu-py39-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/tensorflow-training:2.8.3-gpu-py39-cu112-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-PyTorch 2.0.0  |  3.10(py310)  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.0.0-cpu-py310-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.0.0-gpu-py310-cu118-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-PyTorch 1.13.1  |  3.9(py39)  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.13.1-cpu-py39-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.13.1-gpu-py39-cu117-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-PyTorch 1.12.1  |  3.8(py38)  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.12.1-cpu-py38-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.12.1-gpu-py38-cu113-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-PyTorch 1.11.0  |  3.8(py38)  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.11.0-cpu-py38-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.11.0-gpu-py38-cu113-ubuntu20.04-sagemaker  | 
|  SageMaker 훈련용 DLC-PyTorch 1.9.0  |  3.8(py38)  |  763104351884.dkr.ecr.<region>.amazonaws.com/mxnet-training:1.9.0-cpu-py38-ubuntu20.04-sagemaker  |  763104351884.dkr.ecr.<region>.amazonaws.com/mxnet-training:1.9.0-gpu-py38-cu112-ubuntu20.04-sagemaker  | 

**참고**  
 AWS DLC(Deep Learning Containers) 이미지를 사용하여 로컬에서 작업을 실행하려면 [DLC 설명서에](https://github.com/aws/deep-learning-containers/blob/master/available_images.md) 있는 이미지 URIs를 사용합니다. DLC 이미지는 종속성에 `auto_capture` 값을 지원하지 않습니다.  
[SageMaker Studio에서 SageMaker AI 배포](https://github.com/aws/sagemaker-distribution#amazon-sagemaker-studio)를 사용하는 작업은 컨테이너에서 `sagemaker-user`라는 루트가 아닌 사용자로 실행됩니다. 이 사용자는 `/opt/ml` 및 `/tmp`에 액세스할 수 있는 전체 권한이 필요합니다. 다음 조각과 같이 `pre_execution_commands` 목록에 `sudo chmod -R 777 /opt/ml /tmp`를 추가하여 이 권한을 부여합니다.  

```
@remote(pre_execution_commands=["sudo chmod -R 777 /opt/ml /tmp"])
def func():
    pass
```

사용자 지정 이미지로 원격 함수를 실행할 수도 있습니다. 원격 함수와의 호환성을 위해 사용자 지정 이미지는 Python 버전 3.7.x\$13.10.x로 구축해야 합니다. 다음은 Python 3.10에서 도커 이미지를 사용하는 방법을 보여주는 최소한의 Dockerfile 예제입니다.

```
FROM python:3.10

#... Rest of the Dockerfile
```

이미지에 `conda` 환경을 만들고 이를 사용하여 작업을 실행하려면 환경 변수 `SAGEMAKER_JOB_CONDA_ENV`를 `conda` 환경 이름으로 설정합니다. 이미지에 `SAGEMAKER_JOB_CONDA_ENV` 값이 설정되어 있는 경우 원격 함수는 훈련 작업 런타임 중에 새 conda 환경을 만들 수 없습니다. Python 버전 3.10의 `conda` 환경을 사용하는 다음 Dockerfile 예제를 참조하세요.

```
FROM continuumio/miniconda3:4.12.0  

ENV SHELL=/bin/bash \
    CONDA_DIR=/opt/conda \
    SAGEMAKER_JOB_CONDA_ENV=sagemaker-job-env

RUN conda create -n $SAGEMAKER_JOB_CONDA_ENV \
   && conda install -n $SAGEMAKER_JOB_CONDA_ENV python=3.10 -y \
   && conda clean --all -f -y \
```

SageMaker AI에서 [mamba](https://mamba.readthedocs.io/en/latest/user_guide/mamba.html)를 사용하여 컨테이너 이미지에서 Python 가상 환경을 관리하려면 [miniforge에서 mamba 도구 키트](https://github.com/conda-forge/miniforge)를 설치합니다. mamba를 사용하려면 Dockerfile에 다음 코드 예제를 추가합니다. 그러면 SageMaker AI는 런타임 시 `mamba` 가용성을 감지하여 `conda` 대신 사용합니다.

```
#Mamba Installation
RUN curl -L -O "https://github.com/conda-forge/miniforge/releases/latest/download/Mambaforge-Linux-x86_64.sh" \
    && bash Mambaforge-Linux-x86_64.sh -b -p "/opt/conda"  \
    && /opt/conda/bin/conda init bash
```

원격 함수를 사용할 때 Amazon S3 버킷에서 사용자 지정 conda 채널을 사용하는 것은 mamba와 호환되지 않습니다. mamba를 사용하기로 결정한 경우 Amazon S3에서 사용자 지정 conda 채널을 사용하고 있지 않은지 확인하세요. 자세한 내용은 **Amazon S3를 사용하는 사용자 지정 conda 리포지토리**의 **사전 조건** 섹션을 참조하세요.

다음은 호환되는 도커 이미지를 생성하는 방법을 보여주는 모든 Dockerfile 예제입니다.

```
FROM python:3.10

RUN apt-get update -y \
    # Needed for awscli to work
    # See: https://github.com/aws/aws-cli/issues/1957#issuecomment-687455928
    && apt-get install -y groff unzip curl \
    && pip install --upgrade \
        'boto3>1.0<2' \
        'awscli>1.0<2' \
        'ipykernel>6.0.0<7.0.0' \
#Use ipykernel with --sys-prefix flag, so that the absolute path to 
    #/usr/local/share/jupyter/kernels/python3/kernel.json python is used
    # in kernelspec.json file
    && python -m ipykernel install --sys-prefix

#Install Mamba
RUN curl -L -O "https://github.com/conda-forge/miniforge/releases/latest/download/Mambaforge-Linux-x86_64.sh" \
    && bash Mambaforge-Linux-x86_64.sh -b -p "/opt/conda"  \
    && /opt/conda/bin/conda init bash

#cleanup
RUN apt-get clean \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf ${HOME}/.cache/pip \
    && rm Mambaforge-Linux-x86_64.sh

ENV SHELL=/bin/bash \
    PATH=$PATH:/opt/conda/bin
```

 이전 Dockerfile 예제를 실행하여 얻은 결과 이미지는 [SageMaker Studio Classic 커널 이미지](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-byoi.html)로도 사용할 수 있습니다.

# Amazon SageMaker Experiments를 사용하여 파라미터 및 지표 로깅하기
<a name="train-remote-decorator-experiments"></a>

이 가이드에서는 Amazon SageMaker Experiments를 사용하여 파라미터 및 지표를 로깅하는 방법을 알아봅니다. SageMaker AI 실험은 실행으로 구성되며 각 실행은 모델 훈련 단일 상호 작용에 대한 모든 입력, 파라미터, 구성, 결과로 구성됩니다.

@remote 데코레이터 또는 `RemoteExecutor` API를 사용하여 원격 함수의 파라미터 및 지표를 로깅할 수 있습니다.

원격 함수에서 파라미터 및 지표를 기록하려면 다음 방법 중 하나를 선택합니다.
+ SageMaker AI Experiments 라이브러리의 `Run`을 사용하여 원격 함수 내에서 실행되는 SageMaker AI 실험을 인스턴스화합니다. 자세한 내용은 [Amazon SageMaker AI 실험 생성](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments-create.html)을 참조하세요.
+ SageMaker AI Experiments 라이브러리의 원격 함수 내에서 `load_run` 함수를 사용합니다. 그러면 원격 함수 외부에서 선언된 `Run` 인스턴스가 로드됩니다.

다음 섹션에서는 이전에 나열한 메서드를 사용하여 SageMaker AI 실험 실행으로 계보를 생성하고 추적하는 방법을 보여줍니다. 이 섹션에서는 SageMaker 훈련에서 지원하지 않는 사례도 설명합니다.

## @remote 데코레이터를 사용하여 SageMaker Experiments와 통합하기
<a name="train-remote-decorator-experiments-remote"></a>

SageMaker AI에서 실험을 인스턴스화하거나 원격 함수 내에서 현재 SageMaker AI 실험을 로드할 수 있습니다. 다음 섹션에서는 두 가지 메서드를 사용하는 방법을 보여줍니다.

### SageMaker Experiments로 실험 생성
<a name="train-remote-decorator-experiments-remote-create"></a>

SageMaker AI 실험에서 실행되는 실험을 생성할 수 있습니다. 이렇게 하려면 실험 이름, 실행 이름 및 기타 파라미터를 원격 함수에 전달해야 합니다.

다음 코드 예제에서는 실험 이름, 실행 이름, 각 실행 중에 로깅할 파라미터를 가져옵니다. 파라미터 `param_1` 및 `param_2`는 시간이 지남에 따라 훈련 루프 내에 로깅됩니다. 일반적인 파라미터에는 배치 크기 또는 에포크가 포함될 수 있습니다. 이 예제에서 어떤 실행의 지표 `metric_a` 및 `metric_b`가 시간이 지남에 따라 훈련 루프 내에 로깅됩니다. 다른 일반적인 지표는 `accuracy` 또는 `loss`가 포함될 수 있습니다.

```
from sagemaker.remote_function import remote
from sagemaker.experiments.run import Run

# Define your remote function
@remote
def train(value_1, value_2, exp_name, run_name):
    ...
    ...
    #Creates the experiment
    with Run(
        experiment_name=exp_name,
        run_name=run_name,
    ) as run:
        ...
        #Define values for the parameters to log
        run.log_parameter("param_1", value_1)
        run.log_parameter("param_2", value_2) 
        ...
        #Define metrics to log
        run.log_metric("metric_a", 0.5)
        run.log_metric("metric_b", 0.1)


# Invoke your remote function        
train(1.0, 2.0, "my-exp-name", "my-run-name")
```

### @remote 데코레이터가 시작한 작업으로 현재 SageMaker Experiments 로드하기
<a name="train-remote-decorator-experiments-remote-current"></a>

SageMaker Experiments 라이브러리의 `load_run()` 함수를 사용하여 실행 컨텍스트에서 현재 실행 객체를 로드합니다. 원격 함수 내에서 `load_run()` 함수를 사용할 수도 있습니다. 다음 코드 예제와 같이 실행 객체에서 `with` 문을 통해 로컬에서 시작된 실행 객체를 로드합니다.

```
from sagemaker.experiments.run import Run, load_run

# Define your remote function
@remote
def train(value_1, value_2):
    ...
    ...
    with load_run() as run:
        run.log_metric("metric_a", value_1)
        run.log_metric("metric_b", value_2)


# Invoke your remote function
with Run(
    experiment_name="my-exp-name",
    run_name="my-run-name",
) as run:
    train(0.5, 1.0)
```

## `RemoteExecutor` API로 시작된 작업 내에서 현재 실행 중인 실험을 로드합니다.
<a name="train-remote-decorator-experiments-api"></a>

`RemoteExecutor` API로 작업을 시작한 경우 현재 SageMaker AI 실험 실행을 로드할 수도 있습니다. 다음 코드 예제는 SageMaker Experiments `load_run` 함수로 `RemoteExecutor` API를 사용하는 방법을 보여줍니다. 이렇게 하면 현재 SageMaker AI 실험 실행을 로드하고 `RemoteExecutor`에서 제출한 작업의 지표를 캡처할 수 있습니다.

```
from sagemaker.experiments.run import Run, load_run

def square(x):
    with load_run() as run:
        result = x * x
        run.log_metric("result", result)
    return result


with RemoteExecutor(
    max_parallel_job=2,
    instance_type="ml.m5.large"
) as e:
    with Run(
        experiment_name="my-exp-name",
        run_name="my-run-name",
    ):
        future_1 = e.submit(square, 2)
```

## @remote 데코레이터로 코드에 주석을 다는 동안 SageMaker Experiments가 지원되지 않는 사용
<a name="train-remote-decorator-experiments-unsupported"></a>

SageMaker AI는 @remote 함수에 `Run` 유형 객체를 전달하는 것 또는 글로벌 `Run` 객체를 사용하는 것을 지원하지 않습니다. 다음 예제는 `SerializationError`를 발생시키는 코드를 보여줍니다.

다음 코드 예제에서는 @remote 데코레이터에 `Run` 형식 객체를 전달하려고 할 때 오류가 발생합니다.

```
@remote
def func(run: Run):
    run.log_metrics("metric_a", 1.0)
    
with Run(...) as run:
    func(run) ---> SerializationError caused by NotImplementedError
```

다음 코드 예제에서는 원격 함수 외부에서 인스턴스화된 글로벌 `run` 객체를 사용하려고 합니다. 코드 예제에서 `train()` 함수는 `with Run` 컨텍스트 내부에서 정의하며 이는 글로벌 실행 객체를 참조합니다. `train()`을 호출하면 오류가 발생합니다.

```
with Run(...) as run:
    @remote
    def train(metric_1, value_1, metric_2, value_2):
        run.log_parameter(metric_1, value_1)
        run.log_parameter(metric_2, value_2)
    
    train("p1", 1.0, "p2", 0.5) ---> SerializationError caused by NotImplementedError
```

# @remote 데코레이터와 함께 모듈식 코드 사용하기
<a name="train-remote-decorator-modular"></a>

개발 중에 작업 공간을 쉽게 관리할 수 있도록 모듈로 코드를 구성하고 계속해서 @remote 함수를 사용하여 함수를 호출할 수 있습니다. 개발 환경에서 원격 작업 환경으로 로컬 모듈을 복제할 수도 있습니다. 이렇게 하려면 다음 코드 예제에서와 같이 파라미터 `include_local_workdir`를 `True`로 설정합니다.

```
@remote(
  include_local_workdir=True,
)
```

**참고**  
@remote 데코레이터 및 파라미터는 종속 파일이 아닌 기본 파일에 나타나야 합니다.

`include_local_workdir`가 `True`로 설정된 경우 SageMaker AI는 모든 Python 스크립트를 패키징하면서 프로세스 현재 디렉터리의 디렉터리 구조를 유지합니다. 또한 해당 작업의 작업 디렉터리에서 종속성을 사용할 수 있습니다.

예를 들어, MNIST 데이터세트를 처리하는 Python 스크립트가 스크립트와 종속 `main.py` 스크립트로 분할되어 있다고 가정해 보겠습니다. `main.py`는 종속 `pytorch_mnist.py` 스크립트를 호출합니다. 또한 `main.py` 스크립트에는 그림과 같이 종속성을 가져오는 코드가 포함되어 있습니다.

```
from mnist_impl.pytorch_mnist import ...
```

`main.py` 파일에는 `@remote` 데코레이터도 포함되어야 하며 `include_local_workdir` 파라미터를 `True`로 설정해야 합니다.

`include_local_workdir` 파라미터는 기본적으로 디렉터리의 모든 Python 스크립트를 포함합니다. 이 파라미터를 `custom_file_filter` 파라미터와 함께 사용하여 작업에 업로드할 파일을 사용자 지정할 수 있습니다. S3에 업로드할 작업 종속성을 필터링하는 함수 또는 원격 함수에서 무시할 로컬 디렉터리와 파일을 지정하는 `CustomFileFilter` 객체를 전달할 수 있습니다. `include_local_workdir`가 `True`로 설정된 경우에만 `custom_file_filter`를 사용할 수 있습니다. 그렇지 않으면 파라미터가 무시됩니다.

다음 예제에서는 `CustomFileFilter`를 사용하여 S3에 파일을 업로드할 때 `data` 이름이 지정된 모든 노트북 파일과 폴더 또는 파일을 무시합니다.

```
@remote(
   include_local_workdir=True,
   custom_file_filter=CustomFileFilter(
      ignore_name_patterns=[ # files or directories to ignore
        "*.ipynb", # all notebook files
        "data", # folter or file named data
      ]
   )
)
```

다음 예제에서는 전체 워크스페이스를 패키징하는 방법을 보여줍니다.

```
@remote(
   include_local_workdir=True,
   custom_file_filter=CustomFileFilter(
      ignore_pattern_names=[] # package whole workspace
   )
)
```

다음 예제에서는 함수를 사용하여 파일을 필터링하는 방법을 보여줍니다.

```
import os

def my_filter(path: str, files: List[str]) -> List[str]:
    to_ignore = []
   for file in files:
       if file.endswith(".txt") or file.endswith(".ipynb"):
           to_ignore.append(file)
   return to_ignore

@remote(
   include_local_workdir=True,
   custom_file_filter=my_filter
)
```

## 작업 디렉터리 구조화의 모범 사례
<a name="train-remote-decorator-modular-bestprac"></a>

다음 모범 사례는 모듈식 코드에서 `@remote` 데코레이터를 사용하는 동안 디렉터리 구조를 구성하는 방법을 제안합니다.
+ @remote 데코레이터를 작업 영역의 루트 수준 디렉터리에 있는 파일에 넣습니다.
+ 루트 수준의 로컬 모듈을 구성합니다.

다음 예제 이미지는 권장 디렉터리 구조를 보여줍니다. 이 예제 구조에서 `main.py` 스크립트는 루트 수준 디렉터리에 있습니다.

```
.
├── config.yaml
├── data/
├── main.py <----------------- @remote used here 
├── mnist_impl
│ ├── __pycache__/
│ │ └── pytorch_mnist.cpython-310.pyc
│ ├── pytorch_mnist.py <-------- dependency of main.py
├── requirements.txt
```

다음 예제 이미지는 @remote 데코레이터로 코드에 주석을 달 때 동작이 일관되지 않은 디렉터리 구조를 보여줍니다.

이 예제 구조에서 @remote 데코레이터가 포함된 `main.py` 스크립트는 루트 수준 디렉터리에 있지 **않습니다**. 다음 구조는 권장하지 **않습니다**.

```
.
├── config.yaml
├── entrypoint
│ ├── data
│ └── main.py <----------------- @remote used here
├── mnist_impl
│ ├── __pycache__
│ │ └── pytorch_mnist.cpython-310.pyc
│ └── pytorch_mnist.py <-------- dependency of main.py
├── requirements.txt
```

# 런타임 종속성을 위한 프라이빗 리포지토리
<a name="train-remote-decorator-private"></a>

사전 실행 명령 또는 스크립트를 사용하여 작업 환경에서 pip 또는 conda와 같은 종속성 관리자를 구성할 수 있습니다. 네트워크를 격리하려면 이 두 옵션 중 하나를 사용하여 종속성 관리자를 리디렉션하여 프라이빗 리포지토리에 액세스하고 VPC 내에서 원격 기능을 실행합니다. 사전 실행 명령 또는 스크립트는 원격 함수가 실행되기 전에 실행됩니다. @remote 데코레이터, `RemoteExecutor` API를 사용하여 또는 구성 파일 내에서 정의할 수 있습니다.

다음 섹션에서는 로 관리되는 프라이빗 Python 패키지 인덱스(PyPI) 리포지토리에 액세스하는 방법을 보여줍니다 AWS CodeArtifact. 이 섹션에서는 Amazon Simple Storage Service(S3)에서 호스팅되는 사용자 지정 conda 채널에 액세스하는 방법도 보여줍니다.

## AWS CodeArtifact로 관리되는 사용자 지정 PyPI 리포지토리를 사용하는 방법
<a name="train-remote-decorator-private-pypi"></a>

CodeArtifact를 사용하여 사용자 지정 PyPI 리포지토리를 관리하려면 다음과 같은 사전 조건이 필요합니다.
+ 프라이빗 PyPI 리포지토리가 이미 생성되어 있어야 합니다. AWS CodeArtifact 를 사용하여 프라이빗 패키지 리포지토리를 생성하고 관리할 수 있습니다. CodeArtifact에 대한 자세한 내용은 [CodeArtifact 사용 설명서](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html)를 참조하세요.
+ VPC는 CodeArtifact 리포지토리에 액세스할 수 있어야 합니다. VPC에서 CodeArtifact 리포지토리 연결을 허용하려면 다음을 수행해야 합니다.
  + [CodeArtifact의 VPC 엔드포인트를 생성합니다](https://docs.aws.amazon.com/codeartifact/latest/ug/create-vpc-endpoints.html).
  + VPC용 [Amazon S3 게이트웨이 엔드포인트를 생성](https://docs.aws.amazon.com/codeartifact/latest/ug/create-s3-gateway-endpoint.html)하여 CodeArtifact가 패키지 자산을 저장할 수 있도록 합니다.

다음 사전 실행 명령 예시는 CodeArtifact 리포지토리를 가리키도록 SageMaker AI 훈련 작업에서 pip를 구성하는 방법을 보여줍니다. 자세한 내용은 [CodeArtifact를 통한 pip 구성 및 사용](https://docs.aws.amazon.com/codeartifact/latest/ug/python-configure-pip.html)을 참조하세요.

```
# use a requirements.txt file to import dependencies
@remote(
    instance_type="ml.m5.large"
    image_uri = "my_base_python:latest", 
    dependencies = './requirements.txt',
    pre_execution_commands=[
        "aws codeartifact login --tool pip --domain my-org --domain-owner <000000000000> --repository my-codeartifact-python-repo --endpoint-url https://vpce-xxxxx.api.codeartifact.us-east-1.vpce.amazonaws.com"
    ]
)
def matrix_multiply(a, b):
    return np.matmul(a, b)
```

## Amazon S3에 호스팅된 사용자 지정 conda 채널을 사용하는 방법
<a name="train-remote-decorator-private-conda"></a>

Amazon S3를 사용하여 사용자 지정 conda 리포지토리를 관리하려면 다음과 같은 사전 조건이 필요합니다.
+ 프라이빗 conda 채널이 Amazon S3 버킷에 이미 설정되어 있어야 하고 모든 종속 패키지를 인덱싱하여 Amazon S3 버킷에 업로드해야 합니다. conda 패키지 인덱싱 방법에 대한 지침은 [사용자 지정 채널 생성](https://conda.io/projects/conda/en/latest/user-guide/tasks/create-custom-channels.html)을 참조하세요.
+ VPC는 Amazon S3 버킷에 대한 액세스 권한이 있어야 합니다. 자세한 내용은 [Amazon S3용 엔드포인트](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-s3.html)를 참조하세요.
+ 작업 이미지의 기본 conda 환경에 `boto3`이 설치되어 있어야 합니다. 환경을 확인하려면 Anaconda 프롬프트에 다음을 입력하여 생성된 결과 목록에 `boto3`이 나타나는지 확인합니다.

  ```
  conda list -n base
  ```
+ 작업 이미지는 [mamba](https://mamba.readthedocs.io/en/latest/installation.html)가 아닌 conda를 사용하여 설치해야 합니다. 환경을 점검하려면 이전 코드 프롬프트가 `mamba`를 반환하지 않는지 확인합니다.

다음 사전 실행 명령 예제는 Amazon S3의 프라이빗 채널을 가리키도록 SageMaker 훈련 작업에서 conda를 구성하는 방법을 보여줍니다. 사전 실행 명령은 기본 채널을 제거하고 `.condarc` conda 구성 파일에 사용자 지정 채널을 추가합니다.

```
# specify your dependencies inside a conda yaml file
@remote(
    instance_type="ml.m5.large"
    image_uri = "my_base_python:latest", 
    dependencies = "./environment.yml",
    pre_execution_commands=[
        "conda config --remove channels 'defaults'"
        "conda config --add channels 's3://my_bucket/my-conda-repository/conda-forge/'",
        "conda config --add channels 's3://my_bucket/my-conda-repository/main/'"
    ]
)
def matrix_multiply(a, b):
    return np.matmul(a, b)
```

# 예제 노트북
<a name="train-remote-decorator-examples"></a>

기존 작업 영역 환경의 훈련 코드, 관련된 모든 데이터 처리 코드 및 데이터세트를 SageMaker 훈련 작업으로 변환할 수 있습니다. 다음 노트북은 XGBoost 알고리즘과 Hugging Face를 사용하여 이미지 분류 문제의 환경, 작업 설정 등을 사용자 지정하는 방법을 보여줍니다.

[quick\$1start 노트북](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-remote-function/quick_start/quick_start.ipynb)에는 다음과 같은 코드 예제가 포함되어 있습니다.
+ 구성 파일을 사용하여 작업 설정을 사용자 지정하는 방법.
+ Python 함수를 작업으로 비동기 호출하는 방법.
+ 추가 종속성을 가져와 작업 런타임 환경을 사용자 지정하는 방법.
+ @remote 함수 메서드로 로컬 종속성을 사용하는 방법.

다음 노트북은 다양한 ML 문제 유형 및 구현에 대한 추가 코드 예제를 제공합니다.
+ 이미지 분류 문제에 @remote 데코레이터를 사용하는 코드 예제를 보려면 [pytorch\$1mnist.ipynb](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker-remote-function/pytorch_mnist_sample_notebook) 노트북을 엽니다. 이 분류 문제는 미국 수정국립표준기술연구소(MNIST) 샘플 데이터세트를 사용하여 수기 숫자를 인식합니다.
+ 스크립트의 이전 이미지 분류 문제에 @remote 데코레이터를 사용하는 코드 예제를 보려면 Pytorch MNIST 샘플 스크립트인 [train.py](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker-remote-function/pytorch_mnist_sample_script)를 참조하세요.
+ @remote 데코레이터로 XGBoost 알고리즘을 구현한 방법을 보려면 [xgboost\$1abalone.ipynb](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker-remote-function/xgboost_abalone) 노트북을 엽니다.
+ Hugging Face가 @remote 데코레이터와 통합하는 방법을 보려면 [huggingface.ipynb 노트북](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker-remote-function/huggingface_text_classification)을 엽니다.