https://arxiv.org/abs/1912.04958을 기반으로 STYLEGAN2의 간단한 pytorch 구현 명령 줄에서 완전히 훈련 할 수있는 코딩이 필요하지 않습니다.
아래는 존재하지 않는 꽃입니다.
이 손도 마찬가지입니다
이 도시도
이 유명인도 (@yoniker에 의해 훈련)
GPU와 CUDA가 설치된 기계가 필요합니다. 그런 다음 이와 같이 패키지를 설치하십시오
$ pip install stylegan2_pytorchWindows 시스템을 사용하는 경우 다음 명령이 작동한다고보고되었습니다.
$ conda install pytorch torchvision -c python
$ pip install stylegan2_pytorch$ stylegan2_pytorch --data /path/to/images 그게 다야. 샘플 이미지는 results/default 에 저장되며 모델은 models/default 에 주기적으로 저장됩니다.
프로젝트 이름을 지정할 수 있습니다
$ stylegan2_pytorch --data /path/to/images --name my-project-name중간 결과 및 모델 체크 포인트를 다음과 함께 저장 해야하는 위치를 지정할 수도 있습니다.
$ stylegan2_pytorch --data /path/to/images --name my-project-name --results_dir /path/to/results/dir --models_dir /path/to/models/dir 더 많은 메모리 비용으로 네트워크 용량 (기본값 16 )을 늘리면 생성 결과를 향상시킬 수 있습니다.
$ stylegan2_pytorch --data /path/to/images --network-capacity 256 기본적으로 교육이 차단되면 마지막 체크 포인트 파일에서 자동으로 재개됩니다. 새 설정으로 다시 시작하려면 new 플래그를 추가하십시오.
$ stylegan2_pytorch --new --data /path/to/images --name my-project-name --image-size 512 --batch-size 1 --gradient-accumulate-every 16 --network-capacity 10훈련을 마치면 최신 체크 포인트에서 같은 이미지를 생성 할 수 있습니다.
$ stylegan2_pytorch --generate잠복 공간에서 두 개의 임의의 지점을 통해 보간 비디오를 생성합니다.
$ stylegan2_pytorch --generate-interpolation --interpolation-num-steps 100보간의 각 개별 프레임을 저장합니다
$ stylegan2_pytorch --generate-interpolation --save-frames이전 체크 포인트에 더 나은 생성기가 포함되어 있다면 (종종 발전기가 훈련 끝을 향해 저하되기 시작하면) 이전 체크 포인트에서 다른 플래그로로드 할 수 있습니다.
$ stylegan2_pytorch --generate --load-from {checkpoint number} Stylegan과 Biggan에 사용되는 기술은 잠재 값을 잘라서 값이 평균에 가깝게 떨어집니다. 절단 값이 작을수록 샘플이 샘플 품종 비용으로 더 잘 나타납니다. 값은 일반적으로 0.5 와 1 사이의 --trunc-psi 로 이것을 제어 할 수 있습니다. 기본값으로 0.75 로 설정됩니다
$ stylegan2_pytorch --generate --trunc-psi 0.5여러 GPU가있는 기계가 하나 인 경우 리포지토리는 교육을 위해 모든 것을 활용하는 방법을 제공합니다. 다수의 GPU를 사용하면 각 배치가 사용 가능한 GPU 사이에 골고루 나뉩니다. 예를 들어, 배치 크기가 32 인 2 gpus의 경우 각 GPU는 16 개의 샘플을 볼 수 있습니다.
당신은 단순히 --multi-gpus 깃발을 추가하면 다른 모든 사람들이 처리됩니다. 특정 GPU로 제한하려면 CUDA_VISIBLE_DEVICES 환경을 사용하여 사용할 수있는 장치를 제어 할 수 있습니다. (예 : CUDA_VISIBLE_DEVICES=0,2,3 장치 0, 2, 3 만 사용할 수 있습니다)
$ stylegan2_pytorch --data ./data --multi-gpus --batch-size 32 --gradient-accumulate-every 1과거에는 Gans가 잘 생성하는 방법을 배우기 위해 많은 데이터가 필요했습니다. Faces 모델은 Flickr에서 70k 고품질 이미지를 예로 들어 보았습니다.
그러나 2020 년 5 월 한 달 동안 전 세계의 연구원들은 독립적으로 단순한 기술로 수렴하여 그 수를 1-2k 로 줄였습니다. 그 간단한 아이디어는 훈련 중에 차별자로 들어가는 모든 이미지를 생성하거나 실제적인 모든 이미지를 차별적으로 강화하는 것이 었습니다.
만약 충분한 확률로 증가한다면, 증강은 세대에 '누출'되지 않을 것이다.
낮은 데이터 설정에서 간단한 플래그로 기능을 사용할 수 있습니다.
# find a suitable probability between 0. -> 0.7 at maximum
$ stylegan2_pytorch --data ./data --aug-prob 0.25 기본적으로 사용 된 증강은 translation 및 cutout 입니다. color 추가하려면 --aug-types 인수로 그렇게 할 수 있습니다.
# make sure there are no spaces between items!
$ stylegan2_pytorch --data ./data --aug-prob 0.25 --aug-types [translation,cutout,color]원하는 세 가지 조합으로 사용자 정의 할 수 있습니다. 차별화 가능한 증강 코드는 여기에서 복사되어 약간 수정되었습니다.
두 신경망 사이의 적대 게임이 무너질 때까지 가능한 한 오랫동안 (우리는이 발산이라고 부릅니다). 기본적으로 128x128 이미지의 경우 훈련 단계 수는 150000 으로 설정되지만, 훈련이 끝날 때까지 GAN이 분기되지 않거나 더 높은 해상도로 훈련을 받고 있다면이 숫자가 더 높아지기를 원할 것입니다.
$ stylegan2_pytorch --data ./data --image-size 512 --num-train-steps 1000000이 프레임 워크를 사용하면 판별 자의 지정된 층 (및 생성기의 대칭 층)에 효율적인 형태의 자체 소송을 추가 할 수 있으며 결과를 크게 향상시킬 수 있습니다. 더 많은 관심을 끌수록 더 좋습니다!
# add self attention after the output of layer 1
$ stylegan2_pytorch - - data . / data - - attn - layers 1 # add self attention after the output of layers 1 and 2
# do not put a space after the comma in the list!
$ stylegan2_pytorch - - data . / data - - attn - layers [ 1 , 2 ]투명한 이미지에 대한 교육
$ stylegan2_pytorch --data ./transparent/images/path --transparentGPU 메모리가 많을수록 이미지 생성이 더 크고 좋습니다. NVIDIA는 1024x1024 이미지를 훈련시키기 위해 최대 16GB를 갖는 것을 권장했습니다. 그보다 적은 경우 모델에 맞도록 연주 할 수있는 몇 가지 설정이 있습니다.
$ stylegan2_pytorch --data /path/to/data
--batch-size 3
--gradient-accumulate-every 5
--network-capacity 16 배치 크기- batch-size 1로 줄일 수 있지만, 네트워크가 보는 미니 배치가 너무 작지 않도록 gradient-accumulate-every 상당하게 증가시켜야합니다. 이것은 평신도에게 혼란 스러울 수 있으므로, 앞으로 gradient-accumulate-every 의 선택을 어떻게 자동화 할 것인지 생각해 볼 것입니다.
네트워크 용량 - 메모리 요구 사항을 줄이기 위해 신경망 용량을 줄일 수 있습니다. 이것이 세대 성능을 저하시키는 것으로 나타났습니다.
이 중 어느 것도 작동하지 않으면 'Lightweight'Gan에 정착 할 수있어, 이로 인해 품질이 상충되어 합리적인 시간 내에 더 큰 해상도로 훈련 할 수 있습니다.
다음은 Amazon Web Services를 사용하여 배포하는 데 도움이 될 수있는 몇 가지 단계입니다. 이를 사용하려면 GPU 지원 EC2 인스턴스를 제공해야합니다. 적절한 인스턴스 유형은 P2 또는 P3 시리즈입니다. I (iboates)는 P2.xlarge (가장 저렴한 옵션)를 시도했으며 실제로 Google Colab을 사용하는 것보다 느리게 느 렸습니다. 더 강력한 인스턴스 유형이 더 좋을지 모르지만 더 비쌉니다. 당신은 그들에 대해 더 많이 읽을 수 있습니다.
sudo snap install aws-cli --classic
aws configure그러면 AWS Access Keys를 입력해야하며 AWS Management Console> 프로필> 내 보안 자격 증명> 액세스 키에서 관리 콘솔에서 검색 할 수 있습니다.
그런 다음이 명령을 실행하거나 쉘 스크립트에 넣고 다음을 실행하십시오.
mkdir data
curl -O https://bootstrap.pypa.io/get-pip.py
sudo apt-get install python3-distutils
python3 get-pip.py
pip3 install stylegan2_pytorch
export PATH= $PATH :/home/ubuntu/.local/bin
aws s3 sync s3:// < Your bucket name > ~ /data
cd data
tar -xf ../train.tar.gz 이제 stylegan2_pytorch [args] 간단히 통화하여 훈련 할 수 있어야합니다.
참고 :
screen 창 에서이 작업을 실행해야합니다. GetSeclectic 덕분에 FID 점수를 정기적으로 계산할 수 있습니다! 다시 말하지만, 아래에 표시된 것처럼 하나의 추가 인수로 매우 간단하게 만들었습니다.
먼저 pytorch_fid 패키지를 설치하십시오
$ pip install pytorch-fid그 뒤에
$ stylegan2_pytorch --data ./data --calculate-fid-every 5000 FID 결과는 ./results/{name}/fid_scores.txt name }/fid_scores.txt로 기록됩니다
프로그래밍 방식으로 이미지를 샘플링하려면 다음의 간단한 ModelLoader 클래스를 사용하여 수행 할 수 있습니다.
import torch
from torchvision . utils import save_image
from stylegan2_pytorch import ModelLoader
loader = ModelLoader (
base_dir = '/path/to/directory' , # path to where you invoked the command line tool
name = 'default' # the project name, defaults to 'default'
)
noise = torch . randn ( 1 , 512 ). cuda () # noise
styles = loader . noise_to_styles ( noise , trunc_psi = 0.7 ) # pass through mapping network
images = loader . styles_to_images ( styles ) # call the generator on intermediate style vectors
save_image ( images , './sample.jpg' ) # save your images, or do whatever you desire손실을 오픈 소스 실험 추적기 (AIM)에 기록하려면 그렇게 추가 깃발을 전달하면됩니다.
$ stylegan2_pytorch --data ./data --log그런 다음 Docker가 설치되어 있는지 확인해야합니다. AIM에 대한 지침에 따라 터미널에서 다음을 실행합니다.
$ aim up그런 다음 주소로 브라우저를 열면

새로운 논문은 단순히 판별자가 가짜로 간주되는 샘플로부터 구배 기여를 제로화함으로써 발전기가 새로운 최신 기술을 달성하여 훨씬 더 잘 배우는 증거를 만들어 냈습니다.
$ stylegan2_pytorch - - data . / data - - top - k - training감마는 전체 배치 크기에서 50%의 표적 분율 (수정 가능한 하이퍼 파라미터)으로 천천히 감소하는 붕괴 일정입니다.
$ stylegan2_pytorch - - data . / data - - top - k - training - - generate - top - k - frac 0.5 - - generate - top - k - gamma 0.99 최근 논문은 판별기의 중간 표현이 벡터가 양자화되면 개선 된 결과를보고했다. 나는 극적인 변화를 발견하지 못했지만 이것을 기능으로 추가하기로 결정 했으므로 다른 마음이 조사 할 수 있습니다. 사용하려면 벡터 Quantize를 원하는 레이어를 지정해야합니다. 기본 사전 크기는 256 이며 조정 가능합니다.
# feature quantize layers 1 and 2, with a dictionary size of 512 each
# do not put a space after the comma in the list!
$ stylegan2_pytorch - - data . / data - - fq - layers [ 1 , 2 ] - - fq - dict - size 512나는 차별자에 대한 대조적 인 학습을 시도했으며 (일반적인 GAN 훈련과 함께) 향상된 안정성과 최종 결과의 품질을 관찰했습니다. 아래 그림과 같이 간단한 플래그 로이 실험 기능을 켜질 수 있습니다.
$ stylegan2_pytorch - - data . / data - - cl - reg이것은 훈련을 안정화시키기 위해 상대 론적 간 종이에서 제안되었습니다. 나는 혼합 된 결과를 가지고 있었지만 그것을 실험하고자하는 사람들을위한 기능을 포함 할 것입니다.
$ stylegan2_pytorch - - data . / data - - rel - disc - loss 기본적으로 Stylegan 아키텍처 스타일은 점차적으로 샘플링 될 때 지속적인 학습 된 4x4 블록을 스타일로 만들어냅니다. 이것은 4x4 블록을 대신 스타일 벡터 w 에서 배운 실험적인 기능입니다.
$ stylegan2_pytorch - - data . / data - - no - const최근 논문은 실제 로짓과 가짜 로짓 사이의 새로운 대조적 손실이 다른 유형의 손실에 비해 품질을 향상시킬 수 있다고 제안했다. (이 저장소의 기본값은 힌지 손실이며 논문은 약간의 개선을 보여줍니다)
$ stylegan2_pytorch - - data . / data - - dual - contrast - loss Stylegan2 + UNET 판별 자
나는 UNET 차별기로 정말 좋은 결과를 얻었지만 건축 적으로 변화가 너무 커서이 저장소의 옵션으로 맞았습니다. 완벽을 목표로한다면 자유롭게 시도하십시오.
다른 Gan Architecture (Biggan)에게 왕실 치료를 원한다면 내 이메일에 자유롭게 연락하십시오. 당신의 피치를 듣게되어 기쁩니다.
Tensorflow 2.0에 대한 감동적인 간단한 항구에 대해 Matthew Mann에게 감사합니다.
@article { Karras2019stylegan2 ,
title = { Analyzing and Improving the Image Quality of {StyleGAN} } ,
author = { Tero Karras and Samuli Laine and Miika Aittala and Janne Hellsten and Jaakko Lehtinen and Timo Aila } ,
journal = { CoRR } ,
volume = { abs/1912.04958 } ,
year = { 2019 } ,
} @misc { zhao2020feature ,
title = { Feature Quantization Improves GAN Training } ,
author = { Yang Zhao and Chunyuan Li and Ping Yu and Jianfeng Gao and Changyou Chen } ,
year = { 2020 }
} @misc { chen2020simple ,
title = { A Simple Framework for Contrastive Learning of Visual Representations } ,
author = { Ting Chen and Simon Kornblith and Mohammad Norouzi and Geoffrey Hinton } ,
year = { 2020 }
} @article {,
title = { Oxford 102 Flowers } ,
author = { Nilsback, M-E. and Zisserman, A., 2008 } ,
abstract = { A 102 category dataset consisting of 102 flower categories, commonly occuring in the United Kingdom. Each class consists of 40 to 258 images. The images have large scale, pose and light variations. }
} @article { afifi201911k ,
title = { 11K Hands: gender recognition and biometric identification using a large dataset of hand images } ,
author = { Afifi, Mahmoud } ,
journal = { Multimedia Tools and Applications }
} @misc { zhang2018selfattention ,
title = { Self-Attention Generative Adversarial Networks } ,
author = { Han Zhang and Ian Goodfellow and Dimitris Metaxas and Augustus Odena } ,
year = { 2018 } ,
eprint = { 1805.08318 } ,
archivePrefix = { arXiv }
} @article { shen2019efficient ,
author = { Zhuoran Shen and
Mingyuan Zhang and
Haiyu Zhao and
Shuai Yi and
Hongsheng Li } ,
title = { Efficient Attention: Attention with Linear Complexities } ,
journal = { CoRR } ,
year = { 2018 } ,
url = { http://arxiv.org/abs/1812.01243 } ,
} @article { zhao2020diffaugment ,
title = { Differentiable Augmentation for Data-Efficient GAN Training } ,
author = { Zhao, Shengyu and Liu, Zhijian and Lin, Ji and Zhu, Jun-Yan and Han, Song } ,
journal = { arXiv preprint arXiv:2006.10738 } ,
year = { 2020 }
} @misc { zhao2020image ,
title = { Image Augmentations for GAN Training } ,
author = { Zhengli Zhao and Zizhao Zhang and Ting Chen and Sameer Singh and Han Zhang } ,
year = { 2020 } ,
eprint = { 2006.02595 } ,
archivePrefix = { arXiv }
} @misc { karras2020training ,
title = { Training Generative Adversarial Networks with Limited Data } ,
author = { Tero Karras and Miika Aittala and Janne Hellsten and Samuli Laine and Jaakko Lehtinen and Timo Aila } ,
year = { 2020 } ,
eprint = { 2006.06676 } ,
archivePrefix = { arXiv } ,
primaryClass = { cs.CV }
} @misc { jolicoeurmartineau2018relativistic ,
title = { The relativistic discriminator: a key element missing from standard GAN } ,
author = { Alexia Jolicoeur-Martineau } ,
year = { 2018 } ,
eprint = { 1807.00734 } ,
archivePrefix = { arXiv } ,
primaryClass = { cs.LG }
} @misc { sinha2020topk ,
title = { Top-k Training of GANs: Improving GAN Performance by Throwing Away Bad Samples } ,
author = { Samarth Sinha and Zhengli Zhao and Anirudh Goyal and Colin Raffel and Augustus Odena } ,
year = { 2020 } ,
eprint = { 2002.06224 } ,
archivePrefix = { arXiv } ,
primaryClass = { stat.ML }
} @misc { yu2021dual ,
title = { Dual Contrastive Loss and Attention for GANs } ,
author = { Ning Yu and Guilin Liu and Aysegul Dundar and Andrew Tao and Bryan Catanzaro and Larry Davis and Mario Fritz } ,
year = { 2021 } ,
eprint = { 2103.16748 } ,
archivePrefix = { arXiv } ,
primaryClass = { cs.CV }
}