커스텀 컨테이너를 사용하여 ML 모델 학습

AI Platform Training은 커스텀 컨테이너에서의 학습을 지원하므로, 사용자는 ML 프레임워크 또는 알고리즘이 사전 설치된 자체 Docker 컨테이너를 가져와 AI Platform Training에서 실행할 수 있습니다. 이 가이드에서는 AI Platform Training에서 커스텀 컨테이너를 사용하여 PyTorch 모델을 학습하는 방법을 단계별로 소개합니다.

개요

이 시작 가이드에서는 MNIST 데이터세트를 기반으로 필기 입력 숫자를 분류하는 기본 모델을 사용해 AI Platform Training에서 커스텀 컨테이너를 사용한 학습 프로세스를 보여줍니다.

이 가이드에서는 다음 단계를 설명합니다.

  • 프로젝트 및 로컬 환경 설정
  • 커스텀 컨테이너 만들기
    • Dockerfile 작성
    • Docker 이미지를 로컬에서 빌드 및 테스트
  • 이미지를 Container Registry로 내보내기
  • 커스텀 컨테이너 학습 작업 제출
  • 초매개변수 미세 조정 작업 제출
  • 커스텀 컨테이너와 함께 GPU 사용

시작하기 전에

이 시작 가이드에서는 Google Cloud CLI가 설치된 환경을 사용하세요.

선택사항: 커스텀 컨테이너를 사용한 학습에 대한 개념 정보를 살펴보세요.

다음 단계에 따라 GCP 계정을 설정하고, 필요한 API를 사용 설정하고, Cloud SDK를 설치 및 활성화합니다.

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API AI Platform Training & Prediction, Compute Engine and Container Registry 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. API AI Platform Training & Prediction, Compute Engine and Container Registry 사용 설정

    API 사용 설정

  10. Google Cloud CLI를 설치합니다.
  11. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  12. Docker를 설치합니다.

    Ubuntu나 Debian과 같은 Linux 기반 운영체제를 사용하는 경우 sudo를 사용하지 않고 Docker를 실행할 수 있도록 사용자 이름을 docker 그룹에 추가합니다.

    sudo usermod -a -G docker ${USER}

    사용자를 docker 그룹에 추가하고 나면 시스템을 다시 시작해야 할 수도 있습니다.

  13. Docker를 엽니다. Docker가 실행 중인지 확인하려면 다음 Docker 명령어를 실행합니다. 현재 시간과 날짜가 반환됩니다.
    docker run busybox date
  14. Docker의 사용자 인증 정보 도우미로 gcloud를 사용합니다.
    gcloud auth configure-docker
  15. 선택사항: GPU를 사용하여 컨테이너를 로컬에서 실행하려면 nvidia-docker를 설치합니다.

Cloud Storage 버킷 설정

이 섹션에서는 새 버킷을 만드는 방법을 설명합니다. 기존 버킷을 사용할 수도 있지만 해당 버킷이 AI Platform 작업을 실행하려는 리전과 동일한 리전에 있어야 합니다. 또한 해당 버킷이 AI Platform Training을 실행하는 데 사용 중인 프로젝트에 속하지 않는 경우 명시적으로 AI Platform Training 서비스 계정에 대한 액세스 권한을 부여해야 합니다.

  1. 새 버킷의 이름을 지정합니다. 이름은 Cloud Storage의 모든 버킷에서 중복되지 않아야 합니다.

    BUCKET_NAME="YOUR_BUCKET_NAME"

    예를 들어 프로젝트 이름에 -aiplatform을 추가하여 사용합니다.

    PROJECT_ID=$(gcloud config list project --format "value(core.project)")
    BUCKET_NAME=${PROJECT_ID}-aiplatform
  2. 만든 버킷 이름을 확인합니다.

    echo $BUCKET_NAME
  3. 버킷 리전을 선택하고 REGION 환경 변수를 설정합니다.

    AI Platform Training 작업을 실행할 리전과 동일한 리전을 사용합니다. AI Platform Training 서비스에 사용 가능한 리전을 참조하세요.

    예를 들어 다음 코드는 REGION을 생성하고 us-central1로 설정합니다.

    REGION=us-central1
  4. 새 버킷을 만듭니다.

    gsutil mb -l $REGION gs://$BUCKET_NAME

이 가이드의 코드 다운로드

  1. 다음 명령어를 입력하여 AI Platform Training 샘플 zip 파일을 다운로드합니다.

    wget https://github.com/GoogleCloudPlatform/cloudml-samples/archive/master.zip
    
  2. 파일의 압축을 풀어 cloudml-samples-master 디렉터리를 만듭니다.

    unzip master.zip
    
  3. cloudml-samples-master > pytorch > containers > quickstart > mnist 디렉터리로 이동합니다. 이 둘러보기의 명령어는 mnist 디렉터리에서 실행되어야 합니다.

    cd cloudml-samples-master/pytorch/containers/quickstart/mnist
    

커스텀 컨테이너 만들기

커스텀 컨테이너를 만들려면 먼저 학습 작업에 필요한 종속 항목을 설치하기 위해 Dockerfile을 정의합니다. 그런 다음 Docker 이미지를 로컬에서 빌드 및 테스트하여 확인한 후 AI Platform Training과 함께 사용합니다.

Dockerfile 작성

이 가이드에서 제공하는 샘플 Dockerfile은 다음 단계를 수행합니다.

  1. Python 종속 항목이 기본 제공되는 Python 2.7 기본 이미지를 사용합니다.
  2. 초매개변수를 미세 조정하기 위해 PyTorch, gcloud CLI, cloudml-hypertune을 포함한 추가 종속 항목을 설치합니다.
  3. 학습 애플리케이션의 코드를 컨테이너에 복사합니다.
  4. 컨테이너 시작 시 AI Platform Training이 학습 코드를 실행할 진입점을 구성합니다.

필요에 따라 Dockerfile에 추가 논리를 포함할 수 있습니다. Dockerfile 작성에 대해 자세히 알아보세요.

# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Dockerfile
FROM python:2.7.16-jessie
WORKDIR /root

# Installs pytorch and torchvision.
RUN pip install torch==1.0.0 torchvision==0.2.1

# Installs cloudml-hypertune for hyperparameter tuning.
# It’s not needed if you don’t want to do hyperparameter tuning.
RUN pip install cloudml-hypertune

# Installs google cloud sdk, this is mostly for using gsutil to export model.
RUN wget -nv \
    https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz && \
    mkdir /root/tools && \
    tar xvzf google-cloud-sdk.tar.gz -C /root/tools && \
    rm google-cloud-sdk.tar.gz && \
    /root/tools/google-cloud-sdk/install.sh --usage-reporting=false \
        --path-update=false --bash-completion=false \
        --disable-installation-options && \
    rm -rf /root/.config/* && \
    ln -s /root/.config /config && \
    # Remove the backup directory that gcloud creates
    rm -rf /root/tools/google-cloud-sdk/.install/.backup

# Path configuration
ENV PATH $PATH:/root/tools/google-cloud-sdk/bin
# Make sure gsutil will use the default service account
RUN echo '[GoogleCompute]\nservice_account = default' > /etc/boto.cfg

# Copies the trainer code
RUN mkdir /root/trainer
COPY trainer/mnist.py /root/trainer/mnist.py

# Sets up the entry point to invoke the trainer.
ENTRYPOINT ["python", "trainer/mnist.py"]

Docker 이미지를 로컬에서 빌드 및 테스트

  1. 환경 변수를 사용하여 올바른 이미지 URI를 만들고 Docker 이미지를 빌드합니다. -t 플래그는 원하는 IMAGE_REPO_NAMEIMAGE_TAG로 이미지의 이름과 태그를 지정합니다. 이미지에 다른 이름과 태그를 선택할 수 있습니다.

    export PROJECT_ID=$(gcloud config list project --format "value(core.project)")
    export IMAGE_REPO_NAME=mnist_pytorch_custom_container
    export IMAGE_TAG=mnist_pytorch_cpu
    export IMAGE_URI=gcr.io/$PROJECT_ID/$IMAGE_REPO_NAME:$IMAGE_TAG
    
    docker build -f Dockerfile -t $IMAGE_URI ./
    
  2. 새 컨테이너에서 로컬로 실행하여 이미지를 확인합니다. --epochs 플래그가 트레이너 스크립트에 전달됩니다.

    docker run $IMAGE_URI --epochs 1
    

이미지를 Container Registry로 내보내기

로컬 실행이 작동하면 프로젝트의 Container Registry로 Docker 이미지를 푸시할 수 있습니다.

아직 실행하지 않았다면 먼저 gcloud auth configure-docker를 실행합니다.

docker push $IMAGE_URI

작업 제출 및 모니터링

  1. 작업 요청에 대한 환경 변수를 정의합니다.

    • MODEL_DIR은 학습이 완료된 후 저장된 모델 파일이 저장되는 Cloud Storage 버킷 내의 새로운 타임스탬프 디렉터리의 이름을 지정합니다.
    • REGION은 AI Platform Training 학습에 사용되는 유효한 리전을 지정합니다.
    export MODEL_DIR=pytorch_model_$(date +%Y%m%d_%H%M%S)
    export REGION=us-central1
    export JOB_NAME=custom_container_job_$(date +%Y%m%d_%H%M%S)
    
  2. gcloud CLI를 사용하여 AI Platform Training에 학습 작업을 제출합니다. --master-image-uri 플래그를 사용하여 URI를 Docker 이미지로 전달합니다.

    gcloud ai-platform jobs submit training $JOB_NAME \
      --region $REGION \
      --master-image-uri $IMAGE_URI \
      -- \
      --model-dir=gs://$BUCKET_NAME/$MODEL_DIR \
      --epochs=10
    
  3. 작업을 제출한 후에는 작업 상태와 스트림 로그를 모니터링할 수 있습니다.

    gcloud ai-platform jobs describe $JOB_NAME
    gcloud ai-platform jobs stream-logs $JOB_NAME
    

초매개변수 미세 조정 작업 제출

초매개변수 미세 조정 작업을 위해 수행할 몇 가지 조정이 있습니다. 샘플 코드의 다음 영역을 기록합니다.

  • 샘플 Dockerfile에는 커스텀 컨테이너에 패키지를 설치하기 위한 cloudml-hypertune 패키지가 포함되어 있습니다.
  • 샘플 코드(mnist.py):
    • cloudml-hypertune을 사용하고 도우미 함수 report_hyperparameter_tuning_metric을 호출하여 각 시도 결과를 보고합니다. 작업이 초매개변수 미세 조정 작업으로 제출되지 않은 경우 외에는 샘플 코드가 평가 후에 초매개변수 미세 조정 결과를 보고합니다.
    • 각 초매개변수에 대한 명령줄 인수를 추가하고 argparse로 인수 파싱을 처리합니다.
  • 작업 요청의 HyperparameterSpec 객체에는 TrainingInput이 포함됩니다. 이 경우, 모델 손실을 최소화하기 위해 --lr--momentum을 조정합니다.
  1. 초매개변수 사양을 정의하는 config.yaml 파일을 만듭니다. MODEL_DIRJOB_NAME을 재정의합니다. 아직 수행하지 않은 경우 REGION을 정의합니다.

    export MODEL_DIR=pytorch_hptuning_model_$(date +%Y%m%d_%H%M%S)
    export REGION=us-central1
    export JOB_NAME=custom_container_job_hptuning_$(date +%Y%m%d_%H%M%S)
    
    # Creates a YAML file with job request.
    cat > config.yaml <<EOF
    trainingInput:
      hyperparameters:
        goal: MINIMIZE
        hyperparameterMetricTag: "my_loss"
        maxTrials: 20
        maxParallelTrials: 5
        enableTrialEarlyStopping: True
        params:
        - parameterName: lr
          type: DOUBLE
          minValue: 0.0001
          maxValue: 0.1
        - parameterName: momentum
          type: DOUBLE
          minValue: 0.2
          maxValue: 0.8
    EOF
    
  2. 초매개변수 미세 조정 작업을 AI Platform Training에 제출합니다.

    gcloud ai-platform jobs submit training $JOB_NAME \
      --scale-tier BASIC \
      --region $REGION \
      --master-image-uri $IMAGE_URI \
      --config config.yaml \
      -- \
      --epochs=5 \
      --model-dir="gs://$BUCKET_NAME/$MODEL_DIR"
    

커스텀 컨테이너와 함께 GPU 사용

GPU를 사용하여 커스텀 컨테이너 작업을 제출하려면 이전에 사용한 Docker 이미지와 다른 Docker 이미지를 빌드해야 합니다. 여기서는 다음 요구사항을 충족하는 GPU용 Dockerfile 예가 제공됩니다.

  • 컨테이너에 CUDA 도구와 cuDNN을 사전 설치합니다. 이를 처리하는 권장 방법은 nvidia/cuda 이미지를 기본 이미지로 사용하는 것입니다. CUDA 도구와 cuDNN이 사전 설치되어 있고 관련 환경 변수를 올바르게 설정하는 데 유용하기 때문입니다.
  • wget, curl, pip, 학습 애플리케이션에 필요한 기타 종속 항목을 추가로 설치합니다.
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.\n",
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Dockerfile-gpu
FROM nvidia/cuda:9.0-cudnn7-runtime

# Installs necessary dependencies.
RUN apt-get update && apt-get install -y --no-install-recommends \
         wget \
         curl \
         python-dev && \
     rm -rf /var/lib/apt/lists/*

# Installs pip.
RUN curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py && \
    python get-pip.py && \
    pip install setuptools && \
    rm get-pip.py

WORKDIR /root

# Installs pytorch and torchvision.
RUN pip install torch==1.0.0 torchvision==0.2.1

# Installs cloudml-hypertune for hyperparameter tuning.
# It’s not needed if you don’t want to do hyperparameter tuning.
RUN pip install cloudml-hypertune

# Installs google cloud sdk, this is mostly for using gsutil to export model.
RUN wget -nv \
    https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz && \
    mkdir /root/tools && \
    tar xvzf google-cloud-sdk.tar.gz -C /root/tools && \
    rm google-cloud-sdk.tar.gz && \
    /root/tools/google-cloud-sdk/install.sh --usage-reporting=false \
        --path-update=false --bash-completion=false \
        --disable-installation-options && \
    rm -rf /root/.config/* && \
    ln -s /root/.config /config && \
    # Remove the backup directory that gcloud creates
    rm -rf /root/tools/google-cloud-sdk/.install/.backup

# Path configuration
ENV PATH $PATH:/root/tools/google-cloud-sdk/bin
# Make sure gsutil will use the default service account
RUN echo '[GoogleCompute]\nservice_account = default' > /etc/boto.cfg

# Copies the trainer code
RUN mkdir /root/trainer
COPY trainer/mnist.py /root/trainer/mnist.py

# Sets up the entry point to invoke the trainer.
ENTRYPOINT ["python", "trainer/mnist.py"]

로컬에서 GPU Docker 이미지 빌드 및 테스트

  1. GPU Dockerfile을 사용하여 GPU 학습 작업을 위한 새 이미지를 빌드합니다. CPU 이미지를 재정의하지 않으려면 IMAGE_REPO_NAMEIMAGE_TAG를 이 가이드의 앞부분에서 사용한 이름과 다른 이름으로 다시 정의해야 합니다.

    export PROJECT_ID=$(gcloud config list project --format "value(core.project)")
    export IMAGE_REPO_NAME=mnist_pytorch_gpu_container
    export IMAGE_TAG=mnist_pytorch_gpu
    export IMAGE_URI=gcr.io/$PROJECT_ID/$IMAGE_REPO_NAME:$IMAGE_TAG
    
    docker build -f Dockerfile-gpu -t $IMAGE_URI ./
    
  2. 머신에서 GPU를 사용할 수 있고 nvidia-docker를 설치한 경우, 로컬에서 실행하여 이미지를 확인할 수 있습니다.

    docker run --runtime=nvidia $IMAGE_URI --epochs 1
    
  3. Container Registry로 Docker 이미지를 푸시합니다. 아직 실행하지 않았다면 먼저 gcloud auth configure-docker를 실행합니다.

    docker push $IMAGE_URI
    

작업 제출

이 예에서는 기본 GPU 확장 등급을 사용하여 학습 작업 요청을 제출합니다. GPU를 사용한 학습에 대해서는 기타 머신 옵션을 참조하세요.

  1. MODEL_DIRJOB_NAME을 재정의합니다. 아직 수행하지 않은 경우 REGION을 정의합니다.

    export MODEL_DIR=pytorch_model_gpu_$(date +%Y%m%d_%H%M%S)
    export REGION=us-central1
    export JOB_NAME=custom_container_job_gpu_$(date +%Y%m%d_%H%M%S)
    
  2. gcloud CLI를 사용하여 AI Platform Training에 학습 작업을 제출합니다. --master-image-uri 플래그를 사용하여 URI를 Docker 이미지로 전달합니다.

    gcloud ai-platform jobs submit training $JOB_NAME \
      --scale-tier BASIC_GPU \
      --region $REGION \
      --master-image-uri $IMAGE_URI \
      -- \
      --epochs=5 \
      --model-dir=gs://$BUCKET_NAME/$MODEL_DIR
    

다음 단계