StyleGAN - Official TensorFlow Implementation
The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:
Picture: These people are not real – they were produced by our generator that allows control over different aspects of the image.
This repository contains the official TensorFlow implementation of the following paper:
A Style-Based Generator Architecture for Generative Adversarial Networks
Tero Karras (NVIDIA), Samuli Laine (NVIDIA), Timo Aila (NVIDIA)
Abstract: We propose an alternative generator architecture for generative adversarial networks, borrowing from style transfer literature. The new architecture leads to an automatically learned, unsupervised separation of high-level attributes (e.g., pose and identity when trained on human faces) and stochastic variation in the generated images (e.g., freckles, hair), and it enables intuitive, scale-specific control of the synthesis. The new generator improves the state-of-the-art in terms of traditional distribution quality metrics, leads to demonstrably better interpolation properties, and also better disentangles the latent factors of variation. To quantify interpolation quality and disentanglement, we propose two new, automated methods that are applicable to any generator architecture. Finally, we introduce a new, highly varied and high-quality dataset of human faces.
★★★ NEW: StyleGAN2 is available at https://github.com/NVlabs/stylegan2 ★★★
Material related to our paper is available via the following links:
Additional material can be found on Google Drive:
| Path | Description | :--- | :---------- | StyleGAN | Main folder. | ├ stylegan-paper.pdf | High-quality version of the paper PDF. | ├ stylegan-video.mp4 | High-quality version of the result video. | ├ images | Example images produced using our generator. | │ ├ representative-images | High-quality images to be used in articles, blog posts, etc. | │ └ 100k-generated-images | 100,000 generated images for different amounts of truncation. | │ ├ ffhq-1024x1024 | Generated using Flickr-Faces-HQ dataset at 1024×1024. | │ ├ bedrooms-256x256 | Generated using LSUN Bedroom dataset at 256×256. | │ ├ cars-512x384 | Generated using LSUN Car dataset at 512×384. | │ └ cats-256x256 | Generated using LSUN Cat dataset at 256×256. | ├ videos | Example videos produced using our generator. | │ └ high-quality-video-clips | Individual segments of the result video as high-quality MP4. | ├ ffhq-dataset | Raw data for the Flickr-Faces-HQ dataset. | └ networks | Pre-trained networks as pickled instances of dnnlib.tflib.Network. | ├ stylegan-ffhq-1024x1024.pkl | StyleGAN trained with Flickr-Faces-HQ dataset at 1024×1024. | ├ stylegan-celebahq-1024x1024.pkl | StyleGAN trained with CelebA-HQ dataset at 1024×1024. | ├ stylegan-bedrooms-256x256.pkl | StyleGAN trained with LSUN Bedroom dataset at 256×256. | ├ stylegan-cars-512x384.pkl | StyleGAN trained with LSUN Car dataset at 512×384. | ├ stylegan-cats-256x256.pkl | StyleGAN trained with LSUN Cat dataset at 256×256. | └ metrics | Auxiliary networks for the quality and disentanglement metrics. | ├ inception_v3_features.pkl | Standard Inception-v3 classifier that outputs a raw feature vector. | ├ vgg16_zhang_perceptual.pkl | Standard LPIPS metric to estimate perceptual similarity. | ├ celebahq-classifier-00-male.pkl | Binary classifier trained to detect a single attribute of CelebA-HQ. | └ ⋯ | Please see the file listing for remaining networks.
All material, excluding the Flickr-Faces-HQ dataset, is made available under Creative Commons BY-NC 4.0 license by NVIDIA Corporation. You can use, redistribute, and adapt the material for non-commercial purposes, as long as you give appropriate credit by citing our paper and indicating any changes that you've made.
For license information regarding the FFHQ dataset, please refer to the Flickr-Faces-HQ repository.
are derived from the pre-trained Inception-v3 network by Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. The network was originally shared under Apache 2.0 license on the TensorFlow Models repository.
are derived from the pre-trained VGG-16 network by Karen Simonyan and Andrew Zisserman. The network was originally shared under Creative Commons BY 4.0 license on the Very Deep Convolutional Networks for Large-Scale Visual Recognition project page.
is further derived from the pre-trained LPIPS weights by Richard Zhang, Phillip Isola, Alexei A. Efros, Eli Shechtman, and Oliver Wang. The weights were originally shared under BSD 2-Clause "Simplified" License on the PerceptualSimilarity repository.
A minimal example of using a pre-trained StyleGAN generator is given in pretrained_example.py. When executed, the script downloads a pre-trained StyleGAN generator from Google Drive and uses it to generate an image:
\> python pretrained\_example.py Downloading https://drive.google.com/uc?id=1MEGjdvVpUsu1jB4zrXZN7Y4kBBOzizDQ .... done Gs Params OutputShape WeightShape --- --- --- --- latents\_in - (?, 512) - ... images\_out - (?, 3, 1024, 1024) - --- --- --- --- Total 26219627 \> ls results example.png # https://drive.google.com/uc?id=1UDLT\_zb-rof9kKH0GwiJW\_bS9MoZi8oP
A more advanced example is given in generate_figures.py. The script reproduces the figures from our paper in order to illustrate style mixing, noise inputs, and truncation: ```
python generate_figures.py results/figure02-uncurated-ffhq.png # https://drive.google.com/uc?id=1U3r1xgcD7o-Fd0SBRpq8PXYajm7_30cu results/figure03-style-mixing.png # https://drive.google.com/uc?id=1U-nlMDtpnf1RcYkaFQtbh5oxnhA97hy6 results/figure04-noise-detail.png # https://drive.google.com/uc?id=1UX3m39u_DTU6eLnEW6MqGzbwPFt2R9cG results/figure05-noise-components.png # https://drive.google.com/uc?id=1UQKPcvYVeWMRccGMbs2pPD9PVv1QDyp_results/figure08-truncation-trick.png # https://drive.google.com/uc?id=1ULea0C12zGlxdDQFNLXOWZCHi3QNfk_v results/figure10-uncurated-bedrooms.png # https://drive.google.com/uc?id=1UEBnms1XMfj78OHj3_cx80mUf\_m9DUJr results/figure11-uncurated-cars.png # https://drive.google.com/uc?id=1UO-4JtAs64Kun5vIj10UXqAJ1d5Ir1Ke results/figure12-uncurated-cats.png # https://drive.google.com/uc?id=1USnJc14prlu3QAYxstrtlfXC9sDWPA-W ```
The pre-trained networks are stored as standard pickle files on Google Drive:
# Load pre-trained network. url = 'https://drive.google.com/uc?id=1MEGjdvVpUsu1jB4zrXZN7Y4kBBOzizDQ' # karras2019stylegan-ffhq-1024x1024.pkl with dnnlib.util.open\_url(url, cache\_dir=config.cache\_dir) as f: \_G, \_D, Gs = pickle.load(f) # \_G = Instantaneous snapshot of the generator. Mainly useful for resuming a previous training run. # \_D = Instantaneous snapshot of the discriminator. Mainly useful for resuming a previous training run. # Gs = Long-term average of the generator. Yields higher-quality results than the instantaneous snapshot.
The above code downloads the file and unpickles it to yield 3 instances of dnnlib.tflib.Network. To generate images, you will typically want to use
– the other two networks are provided for completeness. In order for
to work, you will need to have the
source directory in your PYTHONPATH and a
set as default. The session can initialized by calling
There are three ways to use the pre-trained generator:
for immediate-mode operation where the inputs and outputs are numpy arrays: ``` # Pick latent vector. rnd = np.random.RandomState(5) latents = rnd.randn(1, Gs.input_shape)
The first argument is a batch of latent vectors of shape
. The second argument is reserved for class labels (not used by StyleGAN). The remaining keyword arguments are optional and can be used to further modify the operation (see below). The output is a batch of images, whose format is dictated by the
to incorporate the generator as a part of a larger TensorFlow expression:
latents = tf.random\_normal([self.minibatch\_per\_gpu] + Gs\_clone.input\_shape[1:]) images = Gs\_clone.get\_output\_for(latents, None, is\_validation=True, randomize\_noise=True) images = tflib.convert\_images\_to\_uint8(images) result\_expr.append(inception\_clone.get\_output\_for(images))
The above code is from metrics/frechet_inception_distance.py. It generates a batch of random images and feeds them directly to the Inception-v3 network without having to convert the data to numpy arrays in between. 2.
to access individual sub-networks of the generator. Similar to
, the sub-networks are represented as independent instances of dnnlib.tflib.Network:
src\_latents = np.stack(np.random.RandomState(seed).randn(Gs.input\_shape) for seed in src\_seeds) src\_dlatents = Gs.components.mapping.run(src\_latents, None) # [seed, layer, component] src\_images = Gs.components.synthesis.run(src\_dlatents, randomize\_noise=False, \*\*synthesis\_kwargs)
The above code is from generate_figures.py. It first transforms a batch of latent vectors into the intermediate W space using the mapping network and then turns these vectors into a batch of images using the synthesis network. The
array stores a separate copy of the same w vector for each layer of the synthesis network to facilitate style mixing.
The exact details of the generator are defined in training/networks_stylegan.py (see
). The following keyword arguments can be specified to modify the behavior when calling
control the truncation trick that that is performed by default when using
(ψ=0.7, cutoff=8). It can be disabled by setting
, and the image quality can be further improved at the cost of variation by setting e.g.
. Note that truncation is always disabled when using the sub-networks directly. The average w needed to manually perform the truncation trick can be looked up using
determines whether to use re-randomize the noise inputs for each generated image (
, default) or whether to use specific noise values for the entire minibatch (
). The specific values can be accessed via the
instances that are found using
[var for name, var in Gs.components.synthesis.vars.items() if name.startswith('noise')]
When using the mapping network directly, you can specify
to disable the automatic duplication of
Runtime performance can be fine-tuned via
. The former disables support for progressive growing, which is not needed for a fully-trained generator, and the latter performs all computation using half-precision floating point arithmetic.
The training and evaluation scripts operate on datasets stored as multi-resolution TFRecords. Each dataset is represented by a directory containing the same image data in several resolutions to enable efficient streaming. There is a separate *.tfrecords file for each resolution, and if the dataset contains labels, they are stored in a separate file as well. By default, the scripts expect to find the datasets at
. The directory can be changed by editing config.py:
result\_dir = 'results' data\_dir = 'datasets' cache\_dir = 'cache'
To obtain the FFHQ dataset (
), please refer to the Flickr-Faces-HQ repository.
To obtain the CelebA-HQ dataset (
), please refer to the Progressive GAN repository.
To obtain other datasets, including LSUN, please consult their corresponding project pages. The datasets can be converted to multi-resolution TFRecords using the provided dataset_tool.py:
\> python dataset\_tool.py create\_lsun datasets/lsun-bedroom-full ~/lsun/bedroom\_lmdb --resolution 256 \> python dataset\_tool.py create\_lsun\_wide datasets/lsun-car-512x384 ~/lsun/car\_lmdb --width 512 --height 384 \> python dataset\_tool.py create\_lsun datasets/lsun-cat-full ~/lsun/cat\_lmdb --resolution 256 \> python dataset\_tool.py create\_cifar10 datasets/cifar10 ~/cifar10 \> python dataset\_tool.py create\_from\_images datasets/custom-dataset ~/custom-images
Once the datasets are set up, you can train your own StyleGAN networks as follows:
is configured to train the highest-quality StyleGAN (configuration F in Table 1) for the FFHQ dataset at 1024×1024 resolution using 8 GPUs. Please note that we have used 8 GPUs in all of our experiments. Training with fewer GPUs may not produce identical results – if you wish to compare against our technique, we strongly recommend using the same number of GPUs.
Expected training times for the default configuration using Tesla V100 GPUs:
| GPUs | 1024×1024 | 512×512 | 256×256 | | :--- | :-------------- | :------------ | :------------ | | 1 | 41 days 4 hours | 24 days 21 hours | 14 days 22 hours | | 2 | 21 days 22 hours | 13 days 7 hours | 9 days 5 hours | | 4 | 11 days 8 hours | 7 days 0 hours | 4 days 21 hours | | 8 | 6 days 14 hours | 4 days 10 hours | 3 days 8 hours |
The quality and disentanglement metrics used in our paper can be evaluated using run_metrics.py. By default, the script will evaluate the Fréchet Inception Distance (
) for the pre-trained FFHQ generator and write the results into a newly created directory under
. The exact behavior can be changed by uncommenting or editing specific lines in run_metrics.py.
Expected evaluation time and results for the pre-trained FFHQ generator using one Tesla V100 GPU:
| Metric | Time | Result | Description | :----- | :--- | :----- | :---------- | fid50k | 16 min | 4.4159 | Fréchet Inception Distance using 50,000 images. | ppl_zfull | 55 min | 664.8854 | Perceptual Path Length for full paths in Z. | ppl_wfull | 55 min | 233.3059 | Perceptual Path Length for full paths in W. | ppl_zend | 55 min | 666.1057 | Perceptual Path Length for path endpoints in Z. | ppl_wend | 55 min | 197.2266 | Perceptual Path Length for path endpoints in W. | ls | 10 hours | z: 165.0106
w: 3.7447 | Linear Separability in Z and W.
Please note that the exact results may vary from run to run due to the non-deterministic nature of TensorFlow.
We thank Jaakko Lehtinen, David Luebke, and Tuomas Kynkäänniemi for in-depth discussions and helpful comments; Janne Hellsten, Tero Kuosmanen, and Pekka Jänis for compute infrastructure and help with the code release.