2단계: SageMaker Python SDK를 사용하여 분산 교육 작업 시작 - 아마존 SageMaker

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

2단계: SageMaker Python SDK를 사용하여 분산 교육 작업 시작

수정된 스크립트로 분산 훈련 작업을 실행하려면 준비된 훈련 스크립트를 진입점 스크립트로 지정하고 분산 훈련 구성을 지정하여 SageMaker Python SDK의 프레임워크 또는 일반 추정기를 사용하십시오. 1단계: SMDDP 집단 연산을 사용하도록 교육 스크립트 조정

이 페이지에서는 SageMaker Python SDK를 두 가지 방법으로 사용하는 방법을 안내합니다.

교육 데이터 세트는 교육 작업을 시작하는 Amazon S3 또는 Amazon FSx for AWS 리전 Lustre에 저장해야 합니다. Jupyter 노트북을 사용하는 경우 동일한 노트북에서 실행되는 SageMaker 노트북 인스턴스 또는 Studio Classic 앱이 있어야 합니다. SageMaker AWS 리전훈련 데이터를 저장하는 방법에 대한 자세한 내용은 SageMaker Python SDK 데이터 입력 문서를 참조하십시오.

작은 정보

교육 성능을 향상시키려면 Amazon S3 대신 Amazon FSx for Lustre를 사용하는 것이 좋습니다. Amazon FSx는 Amazon S3보다 처리량이 많고 지연 시간은 더 짧습니다.

작은 정보

EFA 지원 인스턴스 유형에서 분산 교육을 제대로 실행하려면 VPC의 보안 그룹이 보안 그룹 자체에서 들어오고 나가는 모든 인바운드 및 아웃바운드 트래픽을 허용하도록 설정하여 인스턴스 간 트래픽을 활성화해야 합니다. 보안 그룹 규칙을 설정하는 방법을 알아보려면 Amazon EC2 사용 설명서의 1단계: EFA 지원 보안 그룹 준비를 참조하십시오.

교육 스크립트의 분산 교육 작업을 실행하는 방법에 대한 지침을 보려면 다음 주제 중 하나를 선택하십시오. 교육 작업을 시작한 후에는 Amazon을 사용하여 Amazon SageMaker 디버거를 사용하여 모델 성능을 디버깅하고 개선하십시오. 시스템 사용률과 모델 성능을 모니터링할 수 CloudWatch 있습니다.

기술 세부 정보에 대해 자세히 알아보려면 다음 주제의 지침을 따르면서 Amazon SageMaker 데이터 병렬화 라이브러리 예제를 시작해 보는 것도 좋습니다.

Python SageMaker SDK에서 프레임워크 추정기 사용하기

SageMaker 프레임워크 추정기 또는 에 distribution 인수를 추가하여 분산 훈련을 시작할 수 있습니다. PyTorchTensorFlow 자세한 내용을 보려면 다음 선택 항목 중에서 SageMaker 분산 데이터 병렬화 (SMDDP) 라이브러리가 지원하는 프레임워크 중 하나를 선택하십시오.

PyTorch

분산 교육을 시작하는 데 사용할 수 있는 런처 옵션은 다음과 같습니다. PyTorch

  • pytorchddp— 이 옵션은 에서 PyTorch 분산 교육을 실행하는 데 필요한 환경 변수를 mpirun 실행하고 설정합니다. SageMaker 이 옵션을 사용하려면 다음 사전을 distribution 파라미터에 전달하십시오.

    { "pytorchddp": { "enabled": True } }
  • torch_distributed— 이 옵션은 에서 PyTorch 분산 학습을 실행하는 데 필요한 환경 변수를 torchrun 실행하고 설정합니다 SageMaker. 이 옵션을 사용하려면 다음 사전을 distribution 파라미터에 전달하십시오.

    { "torch_distributed": { "enabled": True } }
  • smdistributed— 이 옵션도 mpirun 실행되지만 이 옵션을 사용하면 smddprun 에서 PyTorch 분산 학습을 실행하는 데 필요한 환경 변수가 설정됩니다 SageMaker.

    { "smdistributed": { "dataparallel": { "enabled": True } } }

NCCL을 AllGather SMDDP로 대체하기로 선택한 경우 세 가지 옵션을 AllGather 모두 사용할 수 있습니다. 사용 사례에 맞는 옵션을 하나 선택하세요.

NCCL을 AllReduce AllReduce SMDDP로 대체하기로 선택한 경우 mpirun 기반 옵션 중 하나를 선택해야 합니다. 또는. smdistributed pytorchddp 다음과 같이 MPI 옵션을 더 추가할 수도 있습니다.

{ "pytorchddp": { "enabled": True, "custom_mpi_options": "-verbose -x NCCL_DEBUG=VERSION" } }
{ "smdistributed": { "dataparallel": { "enabled": True, "custom_mpi_options": "-verbose -x NCCL_DEBUG=VERSION" } } }

다음 코드 샘플은 분산된 훈련 옵션이 있는 PyTorch 추정기의 기본 구조를 보여줍니다.

from sagemaker.pytorch import PyTorch pt_estimator = PyTorch( base_job_name="training_job_name_prefix", source_dir="subdirectory-to-your-code", entry_point="adapted-training-script.py", role="SageMakerRole", py_version="py310", framework_version="2.0.1",     # For running a multi-node distributed training job, specify a value greater than 1     # Example: 2,3,4,..8 instance_count=2,     # Instance types supported by the SageMaker data parallel library: # ml.p4d.24xlarge, ml.p4de.24xlarge instance_type="ml.p4d.24xlarge", # Activate distributed training with SMDDP distribution={ "pytorchddp": { "enabled": True } } # mpirun, activates SMDDP AllReduce OR AllGather # distribution={ "torch_distributed": { "enabled": True } } # torchrun, activates SMDDP AllGather # distribution={ "smdistributed": { "dataparallel": { "enabled": True } } } # mpirun, activates SMDDP AllReduce OR AllGather ) pt_estimator.fit("s3://bucket/path/to/training/data")
참고

PyTorch 라이트닝 및 라이트닝 볼트와 같은 유틸리티 라이브러리는 DLC에 사전 설치되어 있지 않습니다. SageMaker PyTorch 다음 requirements.txt 파일을 생성하고 훈련 스크립트를 저장하는 소스 디렉터리에 저장합니다.

# requirements.txt pytorch-lightning lightning-bolts

예를 들어 트리 구조의 디렉터리는 다음과 같아야 합니다.

├── pytorch_training_launcher_jupyter_notebook.ipynb └── sub-folder-for-your-code ├── adapted-training-script.py └── requirements.txt

교육 스크립트 및 작업 제출과 함께 requirements.txt 파일을 배치할 소스 디렉터리를 지정하는 방법에 대한 자세한 내용은 Amazon SageMaker Python SDK 설명서의 타사 라이브러리 사용을 참조하십시오.

SMDDP 공동 작업 활성화 및 올바른 분산 교육 시작 프로그램 옵션 사용에 대한 고려 사항
  • AllReduceSMDDP와 SMDDP는 현재 상호 호환되지 AllGather 않습니다.

  • AllReduceSMDDP는 mpirun 기반 런처인 smdistributed or를 사용할 때 기본적으로 활성화되며 pytorchddp NCCL이 사용됩니다. AllGather

  • torch_distributed런처를 사용할 때 AllGather SMDDP는 기본적으로 활성화되며 NCCL로 대체됩니다. AllReduce

  • 다음과 같이 추가 환경 변수를 설정하여 mpirun 기반 런처를 사용할 때도 SMDDP를 활성화할 AllGather 수 있습니다.

    export SMDATAPARALLEL_OPTIMIZE_SDP=true
TensorFlow
중요

SMDDP 라이브러리는 v2.11.0 이후 버전의 DLC에 대한 지원을 TensorFlow 중단했으며 더 이상 DLC에서 사용할 수 없습니다. TensorFlow SMDDP 라이브러리가 설치된 이전 TensorFlow DLC를 찾으려면 을 참조하십시오. TensorFlow(사용되지 않음)

from sagemaker.tensorflow import TensorFlow tf_estimator = TensorFlow( base_job_name = "training_job_name_prefix", entry_point="adapted-training-script.py", role="SageMakerRole", framework_version="2.11.0", py_version="py38",     # For running a multi-node distributed training job, specify a value greater than 1 # Example: 2,3,4,..8 instance_count=2,     # Instance types supported by the SageMaker data parallel library: # ml.p4d.24xlargeml.p3dn.24xlarge, and ml.p3.16xlarge instance_type="ml.p3.16xlarge",     # Training using the SageMaker data parallel distributed training strategy distribution={ "smdistributed": { "dataparallel": { "enabled": True } } } ) tf_estimator.fit("s3://bucket/path/to/training/data")

SageMaker 일반 추정기를 사용하여 사전 빌드된 컨테이너를 확장합니다.

SageMaker 사전 빌드된 컨테이너를 사용자 지정하거나 확장하여 사전 빌드된 SageMaker Docker 이미지가 지원하지 않는 알고리즘 또는 모델에 대한 추가 기능 요구 사항을 처리할 수 있습니다. 사전 빌드된 컨테이너를 확장하는 방법에 대한 예제는 사전 빌드된 컨테이너 확장을 참조하세요.

미리 빌드된 컨테이너를 확장하거나 라이브러리를 사용하도록 자체 컨테이너를 조정하려면 지원되는 프레임워크에 나열된 이미지 중 하나를 사용해야 합니다.

참고

TensorFlow 2.4.1 및 PyTorch 1.8.1부터 SageMaker 프레임워크 DLC는 EFA 지원 인스턴스 유형을 지원합니다. TensorFlow 2.4.1 이상 및 1.8.1 이상이 포함된 DLC 이미지를 사용하는 것이 좋습니다. PyTorch

예를 들어 를 사용하는 PyTorch 경우 Dockerfile에는 다음과 유사한 명령문이 포함되어야 합니다. FROM

# SageMaker PyTorch image FROM 763104351884.dkr.ecr.<aws-region>.amazonaws.com/pytorch-training:<image-tag> ENV PATH="/opt/ml/code:${PATH}" # this environment variable is used by the SageMaker PyTorch container to determine our user code directory. ENV SAGEMAKER_SUBMIT_DIRECTORY /opt/ml/code # /opt/ml and all subdirectories are utilized by SageMaker, use the /code subdirectory to store your user code. COPY train.py /opt/ml/code/train.py # Defines cifar10.py as script entrypoint ENV SAGEMAKER_PROGRAM train.py

SageMaker Training 툴킷과 SageMaker 분산 데이터 병렬 라이브러리의 바이너리 파일을 SageMaker 사용하여 사용할 Docker 컨테이너를 추가로 사용자 지정할 수 있습니다. 자세한 내용은 다음 섹션의 지침을 참조하세요.

SageMaker 분산 데이터 병렬 라이브러리를 사용하여 자체 Docker 컨테이너를 만드세요.

학습용 Docker 컨테이너를 직접 빌드하고 SageMaker 데이터 병렬 라이브러리를 사용하려면 Dockerfile에 분산 SageMaker 병렬 라이브러리의 올바른 종속성 및 바이너리 파일을 포함해야 합니다. 이 섹션에서는 data parallel 라이브러리 사용 시 분산 교육을 위한 최소한의 종속성 집합으로 완전한 Dockerfile을 만드는 방법에 대한 지침을 제공합니다. SageMaker

참고

SageMaker 데이터 병렬 라이브러리를 바이너리로 사용하는 이 사용자 지정 Docker 옵션은 에서만 사용할 PyTorch 수 있습니다.

SageMaker 교육 툴킷과 데이터 병렬 라이브러리를 사용하여 Dockerfile을 만들려면
  1. NVIDIA CUDA의 도커 이미지로 시작하세요. CUDA 런타임 및 개발 도구 (헤더 및 라이브러리) 가 포함된 CuDNN 개발자 버전을 사용하여 소스 코드에서 빌드하십시오. PyTorch

    FROM nvidia/cuda:11.3.1-cudnn8-devel-ubuntu20.04
    작은 정보

    공식 AWS 딥 러닝 컨테이너 (DLC) 이미지는 NVIDIA CUDA 기본 이미지를 기반으로 구축됩니다. 나머지 지침을 따르면서 미리 빌드된 DLC 이미지를 참조로 사용하려면 Dockerfiles용AWS PyTorch Deep Learning Containers를 참조하십시오.

  2. 다음 인수를 추가하여 패키지 및 기타 패키지의 버전을 지정하십시오. PyTorch 또한 Amazon S3 플러그인과 같은 AWS 리소스를 사용할 SageMaker 데이터 병렬 라이브러리 및 기타 소프트웨어에 대한 Amazon S3 버킷 경로를 지정하십시오.

    다음 코드 예제에 제공된 라이브러리 이외의 타사 라이브러리 버전을 사용하려면 AWS Deep Learning Container의 공식 Dockerfile에서 테스트되고 호환되며 애플리케이션에 적합한 버전을 찾는 PyTorch 것이 좋습니다.

    SMDATAPARALLEL_BINARY인수의 URL을 찾으려면 에서 조회 테이블을 참조하십시오. 지원되는 프레임워크

    ARG PYTORCH_VERSION=1.10.2 ARG PYTHON_SHORT_VERSION=3.8 ARG EFA_VERSION=1.14.1 ARG SMDATAPARALLEL_BINARY=https://smdataparallel.s3.amazonaws.com/binary/pytorch/${PYTORCH_VERSION}/cu113/2022-02-18/smdistributed_dataparallel-1.4.0-cp38-cp38-linux_x86_64.whl ARG PT_S3_WHL_GPU=https://aws-s3-plugin.s3.us-west-2.amazonaws.com/binaries/0.0.1/1c3e69e/awsio-0.0.1-cp38-cp38-manylinux1_x86_64.whl ARG CONDA_PREFIX="/opt/conda" ARG BRANCH_OFI=1.1.3-aws
  3. 다음 환경 변수를 설정하여 SageMaker 교육 구성요소를 제대로 빌드하고 데이터 병렬 라이브러리를 실행하십시오. 다음 단계에서 구성 요소에 이러한 변수를 사용합니다.

    # Set ENV variables required to build PyTorch ENV TORCH_CUDA_ARCH_LIST="7.0+PTX 8.0" ENV TORCH_NVCC_FLAGS="-Xfatbin -compress-all" ENV NCCL_VERSION=2.10.3 # Add OpenMPI to the path. ENV PATH /opt/amazon/openmpi/bin:$PATH # Add Conda to path ENV PATH $CONDA_PREFIX/bin:$PATH # Set this enviroment variable for SageMaker to launch SMDDP correctly. ENV SAGEMAKER_TRAINING_MODULE=sagemaker_pytorch_container.training:main # Add enviroment variable for processes to be able to call fork() ENV RDMAV_FORK_SAFE=1 # Indicate the container type ENV DLC_CONTAINER_TYPE=training # Add EFA and SMDDP to LD library path ENV LD_LIBRARY_PATH="/opt/conda/lib/python${PYTHON_SHORT_VERSION}/site-packages/smdistributed/dataparallel/lib:$LD_LIBRARY_PATH" ENV LD_LIBRARY_PATH=/opt/amazon/efa/lib/:$LD_LIBRARY_PATH
  4. 후속 단계에서 패키지를 다운로드하고 빌드하려면 curl, wget, git를 설치하거나 업데이트하세요.

    RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \ apt-get update && apt-get install -y --no-install-recommends \ curl \ wget \ git \ && rm -rf /var/lib/apt/lists/*
  5. Amazon EC2 네트워크 통신을 위한 EFA(Elastic Fabric Adapter) 소프트웨어를 설치합니다.

    RUN DEBIAN_FRONTEND=noninteractive apt-get update RUN mkdir /tmp/efa \ && cd /tmp/efa \ && curl --silent -O https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_VERSION}.tar.gz \ && tar -xf aws-efa-installer-${EFA_VERSION}.tar.gz \ && cd aws-efa-installer \ && ./efa_installer.sh -y --skip-kmod -g \ && rm -rf /tmp/efa
  6. 패키지 관리를 처리하려면 Conda를 설치하세요.

    RUN curl -fsSL -v -o ~/miniconda.sh -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \ chmod +x ~/miniconda.sh && \ ~/miniconda.sh -b -p $CONDA_PREFIX && \ rm ~/miniconda.sh && \ $CONDA_PREFIX/bin/conda install -y python=${PYTHON_SHORT_VERSION} conda-build pyyaml numpy ipython && \ $CONDA_PREFIX/bin/conda clean -ya
  7. 가져오기, 빌드, 설치 PyTorch 및 해당 종속성 AWS OFI NCCL 플러그인과의 호환성을 보장하려면 NCCL 버전을 제어해야 하기 때문에 소스 PyTorch 코드에서 빌드합니다.

    1. PyTorch 공식 dockerfile의 단계에 따라 빌드 종속성을 설치하고 ccache를 설정하여 재컴파일 속도를 높이세요.

      RUN DEBIAN_FRONTEND=noninteractive \ apt-get install -y --no-install-recommends \ build-essential \ ca-certificates \ ccache \ cmake \ git \ libjpeg-dev \ libpng-dev \ && rm -rf /var/lib/apt/lists/* # Setup ccache RUN /usr/sbin/update-ccache-symlinks RUN mkdir /opt/ccache && ccache --set-config=cache_dir=/opt/ccache
    2. 설치의 공통 종속성 및 Linux 종속성. PyTorch

      # Common dependencies for PyTorch RUN conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses # Linux specific dependency for PyTorch RUN conda install -c pytorch magma-cuda113
    3. PyTorch GitHub리포지토리를 복제합니다.

      RUN --mount=type=cache,target=/opt/ccache \ cd / \ && git clone --recursive https://github.com/pytorch/pytorch -b v${PYTORCH_VERSION}
    4. 특정 NCCL 버전을 설치하고 빌드하세요. 이렇게 하려면 PyTorch 의 기본 NCCL 폴더 (/pytorch/third_party/nccl) 에 있는 콘텐츠를 NVIDIA 저장소의 특정 NCCL 버전으로 교체하십시오. NCCL 버전은 이 가이드의 3단계에서 설정되었습니다.

      RUN cd /pytorch/third_party/nccl \ && rm -rf nccl \ && git clone https://github.com/NVIDIA/nccl.git -b v${NCCL_VERSION}-1 \ && cd nccl \ && make -j64 src.build CUDA_HOME=/usr/local/cuda NVCC_GENCODE="-gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_80,code=sm_80" \ && make pkg.txz.build \ && tar -xvf build/pkg/txz/nccl_*.txz -C $CONDA_PREFIX --strip-components=1
    5. 빌드 PyTorch 및 설치. 이 프로세스를 완료하는 데 보통 1시간이 조금 넘게 걸립니다. 이전 단계에서 다운로드한 NCCL 버전을 사용하여 빌드됩니다.

      RUN cd /pytorch \ && CMAKE_PREFIX_PATH="$(dirname $(which conda))/../" \ python setup.py install \ && rm -rf /pytorch
  8. AWS OFI NCCL 플러그인을 빌드하고 설치합니다. 이를 통해 SageMaker 데이터 병렬 라이브러리에 대한 libfabric 지원이 가능합니다.

    RUN DEBIAN_FRONTEND=noninteractive apt-get update \ && apt-get install -y --no-install-recommends \ autoconf \ automake \ libtool RUN mkdir /tmp/efa-ofi-nccl \ && cd /tmp/efa-ofi-nccl \ && git clone https://github.com/aws/aws-ofi-nccl.git -b v${BRANCH_OFI} \ && cd aws-ofi-nccl \ && ./autogen.sh \ && ./configure --with-libfabric=/opt/amazon/efa \ --with-mpi=/opt/amazon/openmpi \ --with-cuda=/usr/local/cuda \ --with-nccl=$CONDA_PREFIX \ && make \ && make install \ && rm -rf /tmp/efa-ofi-nccl
  9. 빌드 및 설치 TorchVision.

    RUN pip install --no-cache-dir -U \ packaging \ mpi4py==3.0.3 RUN cd /tmp \ && git clone https://github.com/pytorch/vision.git -b v0.9.1 \ && cd vision \ && BUILD_VERSION="0.9.1+cu111" python setup.py install \ && cd /tmp \ && rm -rf vision
  10. OpenSSH를 설치 및 구성합니다. MPI가 컨테이너 간에 통신하려면 OpenSSH가 필요합니다. 확인 여부를 묻지 않고 OpenSSH가 컨테이너와 통신할 수 있도록 허용합니다.

    RUN apt-get update \ && apt-get install -y --allow-downgrades --allow-change-held-packages --no-install-recommends \ && apt-get install -y --no-install-recommends openssh-client openssh-server \ && mkdir -p /var/run/sshd \ && cat /etc/ssh/ssh_config | grep -v StrictHostKeyChecking > /etc/ssh/ssh_config.new \ && echo " StrictHostKeyChecking no" >> /etc/ssh/ssh_config.new \ && mv /etc/ssh/ssh_config.new /etc/ssh/ssh_config \ && rm -rf /var/lib/apt/lists/* # Configure OpenSSH so that nodes can communicate with each other RUN mkdir -p /var/run/sshd && \ sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd RUN rm -rf /root/.ssh/ && \ mkdir -p /root/.ssh/ && \ ssh-keygen -q -t rsa -N '' -f /root/.ssh/id_rsa && \ cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys \ && printf "Host *\n StrictHostKeyChecking no\n" >> /root/.ssh/config
  11. PT S3 플러그인을 설치하면 Amazon S3의 데이터 세트에 효율적으로 액세스할 수 있습니다.

    RUN pip install --no-cache-dir -U ${PT_S3_WHL_GPU} RUN mkdir -p /etc/pki/tls/certs && cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt
  12. libboost 라이브러리를 설치합니다. 이 패키지는 데이터 SageMaker 병렬 라이브러리의 비동기 IO 기능을 네트워킹하는 데 필요합니다.

    WORKDIR / RUN wget https://sourceforge.net/projects/boost/files/boost/1.73.0/boost_1_73_0.tar.gz/download -O boost_1_73_0.tar.gz \ && tar -xzf boost_1_73_0.tar.gz \ && cd boost_1_73_0 \ && ./bootstrap.sh \ && ./b2 threading=multi --prefix=${CONDA_PREFIX} -j 64 cxxflags=-fPIC cflags=-fPIC install || true \ && cd .. \ && rm -rf boost_1_73_0.tar.gz \ && rm -rf boost_1_73_0 \ && cd ${CONDA_PREFIX}/include/boost
  13. 교육을 위해 다음 SageMaker 도구를 설치하십시오. PyTorch

    WORKDIR /root RUN pip install --no-cache-dir -U \ smclarify \ "sagemaker>=2,<3" \ sagemaker-experiments==0.* \ sagemaker-pytorch-training
  14. 마지막으로 SageMaker 데이터 병렬 바이너리와 나머지 종속성을 설치합니다.

    RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \ apt-get update && apt-get install -y --no-install-recommends \ jq \ libhwloc-dev \ libnuma1 \ libnuma-dev \ libssl1.1 \ libtool \ hwloc \ && rm -rf /var/lib/apt/lists/* RUN SMDATAPARALLEL_PT=1 pip install --no-cache-dir ${SMDATAPARALLEL_BINARY}
  15. Dockerfile 생성을 완료한 후에는 자체 교육 컨테이너 조정을 참조하여 Docker 컨테이너를 빌드하고 Amazon ECR에서 호스팅하고 Python SDK를 사용하여 교육 작업을 실행하는 방법을 알아보십시오. SageMaker

다음 예제 코드는 이전 코드 블록을 모두 결합한 후의 완전한 Dockerfile을 보여줍니다.

# This file creates a docker image with minimum dependencies to run SageMaker data parallel training FROM nvidia/cuda:11.3.1-cudnn8-devel-ubuntu20.04 # Set appropiate versions and location for components ARG PYTORCH_VERSION=1.10.2 ARG PYTHON_SHORT_VERSION=3.8 ARG EFA_VERSION=1.14.1 ARG SMDATAPARALLEL_BINARY=https://smdataparallel.s3.amazonaws.com/binary/pytorch/${PYTORCH_VERSION}/cu113/2022-02-18/smdistributed_dataparallel-1.4.0-cp38-cp38-linux_x86_64.whl ARG PT_S3_WHL_GPU=https://aws-s3-plugin.s3.us-west-2.amazonaws.com/binaries/0.0.1/1c3e69e/awsio-0.0.1-cp38-cp38-manylinux1_x86_64.whl ARG CONDA_PREFIX="/opt/conda" ARG BRANCH_OFI=1.1.3-aws # Set ENV variables required to build PyTorch ENV TORCH_CUDA_ARCH_LIST="3.7 5.0 7.0+PTX 8.0" ENV TORCH_NVCC_FLAGS="-Xfatbin -compress-all" ENV NCCL_VERSION=2.10.3 # Add OpenMPI to the path. ENV PATH /opt/amazon/openmpi/bin:$PATH # Add Conda to path ENV PATH $CONDA_PREFIX/bin:$PATH # Set this enviroment variable for SageMaker to launch SMDDP correctly. ENV SAGEMAKER_TRAINING_MODULE=sagemaker_pytorch_container.training:main # Add enviroment variable for processes to be able to call fork() ENV RDMAV_FORK_SAFE=1 # Indicate the container type ENV DLC_CONTAINER_TYPE=training # Add EFA and SMDDP to LD library path ENV LD_LIBRARY_PATH="/opt/conda/lib/python${PYTHON_SHORT_VERSION}/site-packages/smdistributed/dataparallel/lib:$LD_LIBRARY_PATH" ENV LD_LIBRARY_PATH=/opt/amazon/efa/lib/:$LD_LIBRARY_PATH # Install basic dependencies to download and build other dependencies RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \ apt-get update && apt-get install -y --no-install-recommends \ curl \ wget \ git \ && rm -rf /var/lib/apt/lists/* # Install EFA. # This is required for SMDDP backend communication RUN DEBIAN_FRONTEND=noninteractive apt-get update RUN mkdir /tmp/efa \ && cd /tmp/efa \ && curl --silent -O https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_VERSION}.tar.gz \ && tar -xf aws-efa-installer-${EFA_VERSION}.tar.gz \ && cd aws-efa-installer \ && ./efa_installer.sh -y --skip-kmod -g \ && rm -rf /tmp/efa # Install Conda RUN curl -fsSL -v -o ~/miniconda.sh -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \ chmod +x ~/miniconda.sh && \ ~/miniconda.sh -b -p $CONDA_PREFIX && \ rm ~/miniconda.sh && \ $CONDA_PREFIX/bin/conda install -y python=${PYTHON_SHORT_VERSION} conda-build pyyaml numpy ipython && \ $CONDA_PREFIX/bin/conda clean -ya # Install PyTorch. # Start with dependencies listed in official PyTorch dockerfile # https://github.com/pytorch/pytorch/blob/master/Dockerfile RUN DEBIAN_FRONTEND=noninteractive \ apt-get install -y --no-install-recommends \ build-essential \ ca-certificates \ ccache \ cmake \ git \ libjpeg-dev \ libpng-dev && \ rm -rf /var/lib/apt/lists/* # Setup ccache RUN /usr/sbin/update-ccache-symlinks RUN mkdir /opt/ccache && ccache --set-config=cache_dir=/opt/ccache # Common dependencies for PyTorch RUN conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses # Linux specific dependency for PyTorch RUN conda install -c pytorch magma-cuda113 # Clone PyTorch RUN --mount=type=cache,target=/opt/ccache \ cd / \ && git clone --recursive https://github.com/pytorch/pytorch -b v${PYTORCH_VERSION} # Note that we need to use the same NCCL version for PyTorch and OFI plugin. # To enforce that, install NCCL from source before building PT and OFI plugin. # Install NCCL. # Required for building OFI plugin (OFI requires NCCL's header files and library) RUN cd /pytorch/third_party/nccl \ && rm -rf nccl \ && git clone https://github.com/NVIDIA/nccl.git -b v${NCCL_VERSION}-1 \ && cd nccl \ && make -j64 src.build CUDA_HOME=/usr/local/cuda NVCC_GENCODE="-gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_80,code=sm_80" \ && make pkg.txz.build \ && tar -xvf build/pkg/txz/nccl_*.txz -C $CONDA_PREFIX --strip-components=1 # Build and install PyTorch. RUN cd /pytorch \ && CMAKE_PREFIX_PATH="$(dirname $(which conda))/../" \ python setup.py install \ && rm -rf /pytorch RUN ccache -C # Build and install OFI plugin. \ # It is required to use libfabric. RUN DEBIAN_FRONTEND=noninteractive apt-get update \ && apt-get install -y --no-install-recommends \ autoconf \ automake \ libtool RUN mkdir /tmp/efa-ofi-nccl \ && cd /tmp/efa-ofi-nccl \ && git clone https://github.com/aws/aws-ofi-nccl.git -b v${BRANCH_OFI} \ && cd aws-ofi-nccl \ && ./autogen.sh \ && ./configure --with-libfabric=/opt/amazon/efa \ --with-mpi=/opt/amazon/openmpi \ --with-cuda=/usr/local/cuda \ --with-nccl=$CONDA_PREFIX \ && make \ && make install \ && rm -rf /tmp/efa-ofi-nccl # Build and install Torchvision RUN pip install --no-cache-dir -U \ packaging \ mpi4py==3.0.3 RUN cd /tmp \ && git clone https://github.com/pytorch/vision.git -b v0.9.1 \ && cd vision \ && BUILD_VERSION="0.9.1+cu111" python setup.py install \ && cd /tmp \ && rm -rf vision # Install OpenSSH. # Required for MPI to communicate between containers, allow OpenSSH to talk to containers without asking for confirmation RUN apt-get update \ && apt-get install -y --allow-downgrades --allow-change-held-packages --no-install-recommends \ && apt-get install -y --no-install-recommends openssh-client openssh-server \ && mkdir -p /var/run/sshd \ && cat /etc/ssh/ssh_config | grep -v StrictHostKeyChecking > /etc/ssh/ssh_config.new \ && echo " StrictHostKeyChecking no" >> /etc/ssh/ssh_config.new \ && mv /etc/ssh/ssh_config.new /etc/ssh/ssh_config \ && rm -rf /var/lib/apt/lists/* # Configure OpenSSH so that nodes can communicate with each other RUN mkdir -p /var/run/sshd && \ sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd RUN rm -rf /root/.ssh/ && \ mkdir -p /root/.ssh/ && \ ssh-keygen -q -t rsa -N '' -f /root/.ssh/id_rsa && \ cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys \ && printf "Host *\n StrictHostKeyChecking no\n" >> /root/.ssh/config # Install PT S3 plugin. # Required to efficiently access datasets in Amazon S3 RUN pip install --no-cache-dir -U ${PT_S3_WHL_GPU} RUN mkdir -p /etc/pki/tls/certs && cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt # Install libboost from source. # This package is needed for smdataparallel functionality (for networking asynchronous IO). WORKDIR / RUN wget https://sourceforge.net/projects/boost/files/boost/1.73.0/boost_1_73_0.tar.gz/download -O boost_1_73_0.tar.gz \ && tar -xzf boost_1_73_0.tar.gz \ && cd boost_1_73_0 \ && ./bootstrap.sh \ && ./b2 threading=multi --prefix=${CONDA_PREFIX} -j 64 cxxflags=-fPIC cflags=-fPIC install || true \ && cd .. \ && rm -rf boost_1_73_0.tar.gz \ && rm -rf boost_1_73_0 \ && cd ${CONDA_PREFIX}/include/boost # Install SageMaker PyTorch training. WORKDIR /root RUN pip install --no-cache-dir -U \ smclarify \ "sagemaker>=2,<3" \ sagemaker-experiments==0.* \ sagemaker-pytorch-training # Install SageMaker data parallel binary (SMDDP) # Start with dependencies RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \ apt-get update && apt-get install -y --no-install-recommends \ jq \ libhwloc-dev \ libnuma1 \ libnuma-dev \ libssl1.1 \ libtool \ hwloc \ && rm -rf /var/lib/apt/lists/* # Install SMDDP RUN SMDATAPARALLEL_PT=1 pip install --no-cache-dir ${SMDATAPARALLEL_BINARY}
작은 정보

사용자 지정 Dockerfile을 확장하여 모델 SageMaker 병렬 라이브러리를 통합하려면 을 참조하십시오. 분산 모델 병렬 라이브러리를 사용하여 자체 Docker 컨테이너를 만드세요. SageMaker