콘텐츠로 건너뛰기

멀티GPU 교육

이 가이드는 단일 또는 여러 대의 컴퓨터에서 YOLOv5 🚀로 데이터 세트를 훈련하기 위해 여러 GPU를 올바르게 사용하는 방법을 설명합니다.

시작하기 전에

리포지토리를 복제하고 요구사항.txt를 설치합니다. Python>=3.8.0 환경을 포함하여 PyTorch>=1.8. 모델데이터 세트는 최신 YOLOv5 릴리스에서 자동으로 다운로드됩니다.

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

💡 프로 팁! 도커 이미지 는 모든 멀티GPU 교육에 권장됩니다. 참조 Docker 빠른 시작 가이드 도커 풀

💡 프로 팁! torch.distributed.run 대체 torch.distributed.launch in PyTorch>=1.9. 참조 문서 를 참조하세요.

교육

훈련을 시작할 사전 훈련된 모델을 선택합니다. 여기서는 가장 작고 빠른 모델인 YOLOv5s를 선택합니다. 모든 모델에 대한 전체 비교는 README 표를 참조하세요. 이 모델을 COCO 데이터 세트의 Multi-GPU 로 훈련합니다.

YOLOv5 모델

싱글 GPU

python train.py  --batch 64 --data coco.yaml --weights yolov5s.pt --device 0

다음과 같은 방법으로 device 를 사용하여 데이터 병렬 모드에서 여러 GPU를 사용할 수 있습니다.

python train.py  --batch 64 --data coco.yaml --weights yolov5s.pt --device 0,1

이 방법은 1개만 사용하는 것에 비해 속도가 느리고 훈련 속도가 거의 빨라지지 않습니다 GPU.

다음을 통과해야 합니다. python -m torch.distributed.run --nproc_per_node를 입력한 후 일반적인 인수를 입력합니다.

python -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --weights yolov5s.pt --device 0,1

--nproc_per_node 는 사용할 GPU 개수를 지정합니다. 위의 예에서는 2입니다. --batch 는 총 배치 크기입니다. 각 GPU 에 균등하게 나뉩니다. 위의 예에서는 GPU 당 64/2=32입니다.

위의 코드는 GPU를 사용합니다. 0... (N-1).

특정 GPU 사용(확장하려면 클릭) 장치` 뒤에 특정 GPU를 전달하기만 하면 됩니다. 예를 들어, 아래 코드에서는 GPU `2,3`을 사용합니다.
python -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights '' --device 2,3
SyncBatchNorm 사용(클릭하여 확장) [SyncBatchNorm](https://pytorch.org/docs/master/generated/torch.nn.SyncBatchNorm.html) could increase [accuracy](https://www.ultralytics.com/glossary/accuracy) for multiple gpu training, however, it will slow down training by a significant factor. It is **only** available for Multiple GPU DistributedDataParallel training. It is best used when the batch-size on **each** GPU is small (<= 8). To use SyncBatchNorm, simple pass `--sync-bn` to the command like below,
python -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights '' --sync-bn
여러 컴퓨터 사용(확장하려면 클릭) This is **only** available for Multiple GPU DistributedDataParallel training. Before we continue, make sure the files on all machines are the same, dataset, codebase, etc. Afterward, make sure the machines can communicate to each other. You will have to choose a master machine(the machine that the others will talk to). Note down its address(`master_addr`) and choose a port(`master_port`). I will use `master_addr = 192.168.1.1` and `master_port = 1234` for the example below. To use it, you can do as the following,
# On master machine 0
python -m torch.distributed.run --nproc_per_node G --nnodes N --node_rank 0 --master_addr "192.168.1.1" --master_port 1234 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights ''
# On machine R
python -m torch.distributed.run --nproc_per_node G --nnodes N --node_rank R --master_addr "192.168.1.1" --master_port 1234 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights ''
where `G` is number of GPU per machine, `N` is the number of machines, and `R` is the machine number from `0...(N-1)`. Let's say I have two machines with two GPUs each, it would be `G = 2` , `N = 2`, and `R = 1` for the above. Training will not start until 모두 'N'대의 머신이 연결되어 있습니다. 출력은 마스터 머신에만 표시됩니다!

참고

  • Windows 지원은 테스트되지 않았으며 Linux를 권장합니다.
  • --batch 는 GPU 수의 배수여야 합니다.
  • GPU 0은 EMA를 유지하고 체크포인트 등을 담당하므로 다른 GPU보다 약간 더 많은 메모리를 차지합니다.
  • 다음과 같은 경우 RuntimeError: Address already in use로 표시되는 경우 한 번에 여러 개의 교육을 실행하고 있기 때문일 수 있습니다. 이 문제를 해결하려면 다른 포트 번호를 추가하여 --master_port 아래와 같이,
python -m torch.distributed.run --master_port 1234 --nproc_per_node 2 ...

결과

DDP profiling results on an AWS EC2 P4d instance with 8x A100 SXM4-40GB for YOLOv5l for 1 COCO epoch.

프로파일링 코드
# prepare
t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/coco:/usr/src/coco $t
pip3 install torch==1.9.0+cu111 torchvision==0.10.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html
cd .. && rm -rf app && git clone https://github.com/ultralytics/yolov5 -b master app && cd app
cp data/coco.yaml data/coco_profile.yaml

# profile
python train.py --batch-size 16 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0
python -m torch.distributed.run --nproc_per_node 2 train.py --batch-size 32 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1
python -m torch.distributed.run --nproc_per_node 4 train.py --batch-size 64 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1,2,3
python -m torch.distributed.run --nproc_per_node 8 train.py --batch-size 128 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1,2,3,4,5,6,7
GPU
A100
배치 크기CUDA_mem
device0 (G)
COCO
기차
COCO
val
1x1626GB20:390:55
2x3226GB11:430:57
4x6426GB5:570:55
8x12826GB3:090:57

자주 묻는 질문

오류가 발생하면 먼저 아래 체크리스트를 읽어보세요! (시간을 절약할 수 있습니다)

체크리스트(확장하려면 클릭)
  • 이 게시물을 제대로 읽으셨나요?
  • 코드베이스를 다시 복제해 보셨나요? 코드는 매일 변경됩니다.
  • 오류를 검색해 보셨나요? 누군가 이미 이 리포지토리나 다른 리포지토리에서 이 문제를 발견하여 해결책을 가지고 있을 수 있습니다.
  • 상단에 나열된 모든 요구 사항(올바른 Python 및 Pytorch 버전 포함)을 설치했나요?
  • 아래 '환경' 섹션에 나열된 다른 환경에서도 시도해 보셨나요?
  • coco128 또는 coco2017과 같은 다른 데이터셋으로 시도해 보셨나요? 그러면 근본 원인을 더 쉽게 찾을 수 있습니다.
위의 내용을 모두 검토했다면 템플릿에 따라 최대한 자세히 설명하여 자유롭게 이슈를 제기하세요.

지원 환경

Ultralytics 는 바로 사용할 수 있는 다양한 환경을 제공하며, 각 환경에는 다음과 같은 필수 종속성이 사전 설치되어 있습니다. CUDA, CUDNN, Python, 및 PyTorch와 같은 필수 종속 요소를 설치하여 프로젝트를 시작할 수 있습니다.

프로젝트 상태

YOLOv5 CI

이 배지는 모든 YOLOv5 GitHub Actions 지속적 통합(CI) 테스트가 성공적으로 통과되었음을 나타냅니다. 이러한 CI 테스트는 교육, 검증, 추론, 내보내기벤치마크 등 다양한 주요 측면에서 YOLOv5 의 기능과 성능을 엄격하게 확인합니다. 24시간마다 그리고 새로운 커밋이 있을 때마다 테스트를 수행하여 macOS, Windows 및 Ubuntu에서 일관되고 안정적인 작동을 보장합니다.

크레딧

모든 작업을 도와주신 @MagicFrogSJTU와 모든 과정을 안내해 주신 @glenn-jocher에게 감사의 말씀을 전합니다.

📅 Created 11 months ago ✏️ Updated 4 days ago

댓글