├── MANIFEST.in ├── full_requirements.txt ├── assets ├── output_0.png ├── output_1.png └── output_2.png ├── requirements.txt ├── pytorch_pretrained_biggan ├── __init__.py ├── config.py ├── file_utils.py ├── model.py ├── convert_tf_to_pytorch.py └── utils.py ├── scripts ├── convert_tf_hub_models.sh └── download_tf_hub_models.sh ├── LICENSE ├── .gitignore ├── setup.py └── README.md /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | -------------------------------------------------------------------------------- /full_requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow 2 | tensorflow-hub 3 | Pillow 4 | nltk 5 | libsixel-python -------------------------------------------------------------------------------- /assets/output_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/pytorch-pretrained-BigGAN/HEAD/assets/output_0.png -------------------------------------------------------------------------------- /assets/output_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/pytorch-pretrained-BigGAN/HEAD/assets/output_1.png -------------------------------------------------------------------------------- /assets/output_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huggingface/pytorch-pretrained-BigGAN/HEAD/assets/output_2.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # PyTorch 2 | torch>=0.4.1 3 | # progress bars in model download and training scripts 4 | tqdm 5 | # Accessing files from S3 directly. 6 | boto3 7 | # Used for downloading models over HTTP 8 | requests -------------------------------------------------------------------------------- /pytorch_pretrained_biggan/__init__.py: -------------------------------------------------------------------------------- 1 | from .config import BigGANConfig 2 | from .model import BigGAN 3 | from .file_utils import PYTORCH_PRETRAINED_BIGGAN_CACHE, cached_path 4 | from .utils import (truncated_noise_sample, save_as_images, 5 | convert_to_images, display_in_terminal, 6 | one_hot_from_int, one_hot_from_names) 7 | -------------------------------------------------------------------------------- /scripts/convert_tf_hub_models.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Thomas Wolf, Huggingface Inc. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | set -e 9 | set -x 10 | 11 | models="128 256 512" 12 | 13 | mkdir -p models/model_128 14 | mkdir -p models/model_256 15 | mkdir -p models/model_512 16 | 17 | # Convert TF Hub models. 18 | for model in $models 19 | do 20 | pytorch_pretrained_biggan --model_type $model --tf_model_path models/model_$model --pt_save_path models/model_$model 21 | done 22 | -------------------------------------------------------------------------------- /scripts/download_tf_hub_models.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Thomas Wolf, Huggingface Inc. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | set -e 9 | set -x 10 | 11 | models="128 256 512" 12 | 13 | mkdir -p models/model_128 14 | mkdir -p models/model_256 15 | mkdir -p models/model_512 16 | 17 | # Download TF Hub models. 18 | for model in $models 19 | do 20 | curl -L "https://tfhub.dev/deepmind/biggan-deep-$model/1?tf-hub-format=compressed" | tar -zxvC models/model_$model 21 | done 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Thomas Wolf 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # vscode 107 | .vscode/ 108 | 109 | # models 110 | models/ -------------------------------------------------------------------------------- /pytorch_pretrained_biggan/config.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """ 3 | BigGAN config. 4 | """ 5 | from __future__ import (absolute_import, division, print_function, unicode_literals) 6 | 7 | import copy 8 | import json 9 | 10 | class BigGANConfig(object): 11 | """ Configuration class to store the configuration of a `BigGAN`. 12 | Defaults are for the 128x128 model. 13 | layers tuple are (up-sample in the layer ?, input channels, output channels) 14 | """ 15 | def __init__(self, 16 | output_dim=128, 17 | z_dim=128, 18 | class_embed_dim=128, 19 | channel_width=128, 20 | num_classes=1000, 21 | layers=[(False, 16, 16), 22 | (True, 16, 16), 23 | (False, 16, 16), 24 | (True, 16, 8), 25 | (False, 8, 8), 26 | (True, 8, 4), 27 | (False, 4, 4), 28 | (True, 4, 2), 29 | (False, 2, 2), 30 | (True, 2, 1)], 31 | attention_layer_position=8, 32 | eps=1e-4, 33 | n_stats=51): 34 | """Constructs BigGANConfig. """ 35 | self.output_dim = output_dim 36 | self.z_dim = z_dim 37 | self.class_embed_dim = class_embed_dim 38 | self.channel_width = channel_width 39 | self.num_classes = num_classes 40 | self.layers = layers 41 | self.attention_layer_position = attention_layer_position 42 | self.eps = eps 43 | self.n_stats = n_stats 44 | 45 | @classmethod 46 | def from_dict(cls, json_object): 47 | """Constructs a `BigGANConfig` from a Python dictionary of parameters.""" 48 | config = BigGANConfig() 49 | for key, value in json_object.items(): 50 | config.__dict__[key] = value 51 | return config 52 | 53 | @classmethod 54 | def from_json_file(cls, json_file): 55 | """Constructs a `BigGANConfig` from a json file of parameters.""" 56 | with open(json_file, "r", encoding='utf-8') as reader: 57 | text = reader.read() 58 | return cls.from_dict(json.loads(text)) 59 | 60 | def __repr__(self): 61 | return str(self.to_json_string()) 62 | 63 | def to_dict(self): 64 | """Serializes this instance to a Python dictionary.""" 65 | output = copy.deepcopy(self.__dict__) 66 | return output 67 | 68 | def to_json_string(self): 69 | """Serializes this instance to a JSON string.""" 70 | return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" 71 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py 3 | 4 | To create the package for pypi. 5 | 6 | 1. Change the version in __init__.py and setup.py. 7 | 8 | 2. Commit these changes with the message: "Release: VERSION" 9 | 10 | 3. Add a tag in git to mark the release: "git tag VERSION -m'Adds tag VERSION for pypi' " 11 | Push the tag to git: git push --tags origin master 12 | 13 | 4. Build both the sources and the wheel. Do not change anything in setup.py between 14 | creating the wheel and the source distribution (obviously). 15 | 16 | For the wheel, run: "python setup.py bdist_wheel" in the top level allennlp directory. 17 | (this will build a wheel for the python version you use to build it - make sure you use python 3.x). 18 | 19 | For the sources, run: "python setup.py sdist" 20 | You should now have a /dist directory with both .whl and .tar.gz source versions of allennlp. 21 | 22 | 5. Check that everything looks correct by uploading the package to the pypi test server: 23 | 24 | twine upload dist/* -r pypitest 25 | (pypi suggest using twine as other methods upload files via plaintext.) 26 | 27 | Check that you can install it in a virtualenv by running: 28 | pip install -i https://testpypi.python.org/pypi allennlp 29 | 30 | 6. Upload the final version to actual pypi: 31 | twine upload dist/* -r pypi 32 | 33 | 7. Copy the release notes from RELEASE.md to the tag in github once everything is looking hunky-dory. 34 | 35 | """ 36 | from io import open 37 | from setuptools import find_packages, setup 38 | 39 | setup( 40 | name="pytorch_pretrained_biggan", 41 | version="0.1.0", 42 | author="Thomas Wolf", 43 | author_email="thomas@huggingface.co", 44 | description="PyTorch version of DeepMind's BigGAN model with pre-trained models", 45 | long_description=open("README.md", "r", encoding='utf-8').read(), 46 | long_description_content_type="text/markdown", 47 | keywords='BIGGAN GAN deep learning google deepmind', 48 | license='Apache', 49 | url="https://github.com/huggingface/pytorch-pretrained-BigGAN", 50 | packages=find_packages(exclude=["*.tests", "*.tests.*", 51 | "tests.*", "tests"]), 52 | install_requires=['torch>=0.4.1', 53 | 'numpy', 54 | 'boto3', 55 | 'requests', 56 | 'tqdm'], 57 | tests_require=['pytest'], 58 | entry_points={ 59 | 'console_scripts': [ 60 | "pytorch_pretrained_biggan=pytorch_pretrained_biggan.convert_tf_to_pytorch:main", 61 | ] 62 | }, 63 | classifiers=[ 64 | 'Intended Audience :: Science/Research', 65 | 'License :: OSI Approved :: Apache Software License', 66 | 'Programming Language :: Python :: 3', 67 | 'Topic :: Scientific/Engineering :: Artificial Intelligence', 68 | ], 69 | ) 70 | -------------------------------------------------------------------------------- /pytorch_pretrained_biggan/file_utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Utilities for working with the local dataset cache. 3 | This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp 4 | Copyright by the AllenNLP authors. 5 | """ 6 | from __future__ import (absolute_import, division, print_function, unicode_literals) 7 | 8 | import json 9 | import logging 10 | import os 11 | import shutil 12 | import tempfile 13 | from functools import wraps 14 | from hashlib import sha256 15 | import sys 16 | from io import open 17 | 18 | import boto3 19 | import requests 20 | from botocore.exceptions import ClientError 21 | from tqdm import tqdm 22 | 23 | try: 24 | from urllib.parse import urlparse 25 | except ImportError: 26 | from urlparse import urlparse 27 | 28 | try: 29 | from pathlib import Path 30 | PYTORCH_PRETRAINED_BIGGAN_CACHE = Path(os.getenv('PYTORCH_PRETRAINED_BIGGAN_CACHE', 31 | Path.home() / '.pytorch_pretrained_biggan')) 32 | except (AttributeError, ImportError): 33 | PYTORCH_PRETRAINED_BIGGAN_CACHE = os.getenv('PYTORCH_PRETRAINED_BIGGAN_CACHE', 34 | os.path.join(os.path.expanduser("~"), '.pytorch_pretrained_biggan')) 35 | 36 | logger = logging.getLogger(__name__) # pylint: disable=invalid-name 37 | 38 | 39 | def url_to_filename(url, etag=None): 40 | """ 41 | Convert `url` into a hashed filename in a repeatable way. 42 | If `etag` is specified, append its hash to the url's, delimited 43 | by a period. 44 | """ 45 | url_bytes = url.encode('utf-8') 46 | url_hash = sha256(url_bytes) 47 | filename = url_hash.hexdigest() 48 | 49 | if etag: 50 | etag_bytes = etag.encode('utf-8') 51 | etag_hash = sha256(etag_bytes) 52 | filename += '.' + etag_hash.hexdigest() 53 | 54 | return filename 55 | 56 | 57 | def filename_to_url(filename, cache_dir=None): 58 | """ 59 | Return the url and etag (which may be ``None``) stored for `filename`. 60 | Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. 61 | """ 62 | if cache_dir is None: 63 | cache_dir = PYTORCH_PRETRAINED_BIGGAN_CACHE 64 | if sys.version_info[0] == 3 and isinstance(cache_dir, Path): 65 | cache_dir = str(cache_dir) 66 | 67 | cache_path = os.path.join(cache_dir, filename) 68 | if not os.path.exists(cache_path): 69 | raise EnvironmentError("file {} not found".format(cache_path)) 70 | 71 | meta_path = cache_path + '.json' 72 | if not os.path.exists(meta_path): 73 | raise EnvironmentError("file {} not found".format(meta_path)) 74 | 75 | with open(meta_path, encoding="utf-8") as meta_file: 76 | metadata = json.load(meta_file) 77 | url = metadata['url'] 78 | etag = metadata['etag'] 79 | 80 | return url, etag 81 | 82 | 83 | def cached_path(url_or_filename, cache_dir=None): 84 | """ 85 | Given something that might be a URL (or might be a local path), 86 | determine which. If it's a URL, download the file and cache it, and 87 | return the path to the cached file. If it's already a local path, 88 | make sure the file exists and then return the path. 89 | """ 90 | if cache_dir is None: 91 | cache_dir = PYTORCH_PRETRAINED_BIGGAN_CACHE 92 | if sys.version_info[0] == 3 and isinstance(url_or_filename, Path): 93 | url_or_filename = str(url_or_filename) 94 | if sys.version_info[0] == 3 and isinstance(cache_dir, Path): 95 | cache_dir = str(cache_dir) 96 | 97 | parsed = urlparse(url_or_filename) 98 | 99 | if parsed.scheme in ('http', 'https', 's3'): 100 | # URL, so get it from the cache (downloading if necessary) 101 | return get_from_cache(url_or_filename, cache_dir) 102 | elif os.path.exists(url_or_filename): 103 | # File, and it exists. 104 | return url_or_filename 105 | elif parsed.scheme == '': 106 | # File, but it doesn't exist. 107 | raise EnvironmentError("file {} not found".format(url_or_filename)) 108 | else: 109 | # Something unknown 110 | raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename)) 111 | 112 | 113 | def split_s3_path(url): 114 | """Split a full s3 path into the bucket name and path.""" 115 | parsed = urlparse(url) 116 | if not parsed.netloc or not parsed.path: 117 | raise ValueError("bad s3 path {}".format(url)) 118 | bucket_name = parsed.netloc 119 | s3_path = parsed.path 120 | # Remove '/' at beginning of path. 121 | if s3_path.startswith("/"): 122 | s3_path = s3_path[1:] 123 | return bucket_name, s3_path 124 | 125 | 126 | def s3_request(func): 127 | """ 128 | Wrapper function for s3 requests in order to create more helpful error 129 | messages. 130 | """ 131 | 132 | @wraps(func) 133 | def wrapper(url, *args, **kwargs): 134 | try: 135 | return func(url, *args, **kwargs) 136 | except ClientError as exc: 137 | if int(exc.response["Error"]["Code"]) == 404: 138 | raise EnvironmentError("file {} not found".format(url)) 139 | else: 140 | raise 141 | 142 | return wrapper 143 | 144 | 145 | @s3_request 146 | def s3_etag(url): 147 | """Check ETag on S3 object.""" 148 | s3_resource = boto3.resource("s3") 149 | bucket_name, s3_path = split_s3_path(url) 150 | s3_object = s3_resource.Object(bucket_name, s3_path) 151 | return s3_object.e_tag 152 | 153 | 154 | @s3_request 155 | def s3_get(url, temp_file): 156 | """Pull a file directly from S3.""" 157 | s3_resource = boto3.resource("s3") 158 | bucket_name, s3_path = split_s3_path(url) 159 | s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) 160 | 161 | 162 | def http_get(url, temp_file): 163 | req = requests.get(url, stream=True) 164 | content_length = req.headers.get('Content-Length') 165 | total = int(content_length) if content_length is not None else None 166 | progress = tqdm(unit="B", total=total) 167 | for chunk in req.iter_content(chunk_size=1024): 168 | if chunk: # filter out keep-alive new chunks 169 | progress.update(len(chunk)) 170 | temp_file.write(chunk) 171 | progress.close() 172 | 173 | 174 | def get_from_cache(url, cache_dir=None): 175 | """ 176 | Given a URL, look for the corresponding dataset in the local cache. 177 | If it's not there, download it. Then return the path to the cached file. 178 | """ 179 | if cache_dir is None: 180 | cache_dir = PYTORCH_PRETRAINED_BIGGAN_CACHE 181 | if sys.version_info[0] == 3 and isinstance(cache_dir, Path): 182 | cache_dir = str(cache_dir) 183 | 184 | if not os.path.exists(cache_dir): 185 | os.makedirs(cache_dir) 186 | 187 | # Get eTag to add to filename, if it exists. 188 | if url.startswith("s3://"): 189 | etag = s3_etag(url) 190 | else: 191 | response = requests.head(url, allow_redirects=True) 192 | if response.status_code != 200: 193 | raise IOError("HEAD request failed for url {} with status code {}" 194 | .format(url, response.status_code)) 195 | etag = response.headers.get("ETag") 196 | 197 | filename = url_to_filename(url, etag) 198 | 199 | # get cache path to put the file 200 | cache_path = os.path.join(cache_dir, filename) 201 | 202 | if not os.path.exists(cache_path): 203 | # Download to temporary file, then copy to cache dir once finished. 204 | # Otherwise you get corrupt cache entries if the download gets interrupted. 205 | with tempfile.NamedTemporaryFile() as temp_file: 206 | logger.info("%s not found in cache, downloading to %s", url, temp_file.name) 207 | 208 | # GET file object 209 | if url.startswith("s3://"): 210 | s3_get(url, temp_file) 211 | else: 212 | http_get(url, temp_file) 213 | 214 | # we are copying the file before closing it, so flush to avoid truncation 215 | temp_file.flush() 216 | # shutil.copyfileobj() starts at the current position, so go to the start 217 | temp_file.seek(0) 218 | 219 | logger.info("copying %s to cache at %s", temp_file.name, cache_path) 220 | with open(cache_path, 'wb') as cache_file: 221 | shutil.copyfileobj(temp_file, cache_file) 222 | 223 | logger.info("creating metadata file for %s", cache_path) 224 | meta = {'url': url, 'etag': etag} 225 | meta_path = cache_path + '.json' 226 | with open(meta_path, 'w', encoding="utf-8") as meta_file: 227 | json.dump(meta, meta_file) 228 | 229 | logger.info("removing temp file %s", temp_file.name) 230 | 231 | return cache_path 232 | 233 | 234 | def read_set_from_file(filename): 235 | ''' 236 | Extract a de-duped collection (set) of text from a file. 237 | Expected file format is one item per line. 238 | ''' 239 | collection = set() 240 | with open(filename, 'r', encoding='utf-8') as file_: 241 | for line in file_: 242 | collection.add(line.rstrip()) 243 | return collection 244 | 245 | 246 | def get_file_extension(path, dot=True, lower=True): 247 | ext = os.path.splitext(path)[1] 248 | ext = ext if dot else ext[1:] 249 | return ext.lower() if lower else ext 250 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyTorch pretrained BigGAN 2 | An op-for-op PyTorch reimplementation of DeepMind's BigGAN model with the pre-trained weights from DeepMind. 3 | 4 | ## Introduction 5 | 6 | This repository contains an op-for-op PyTorch reimplementation of DeepMind's BigGAN that was released with the paper [Large Scale GAN Training for High Fidelity Natural Image Synthesis](https://openreview.net/forum?id=B1xsqj09Fm) by Andrew Brock, Jeff Donahue and Karen Simonyan. 7 | 8 | This PyTorch implementation of BigGAN is provided with the [pretrained 128x128, 256x256 and 512x512 models by DeepMind](https://tfhub.dev/deepmind/biggan-deep-128/1). We also provide the scripts used to download and convert these models from the TensorFlow Hub models. 9 | 10 | This reimplementation was done from the raw computation graph of the Tensorflow version and behave similarly to the TensorFlow version (variance of the output difference of the order of 1e-5). 11 | 12 | This implementation currently only contains the generator as the weights of the discriminator were not released (although the structure of the discriminator is very similar to the generator so it could be added pretty easily. Tell me if you want to do a PR on that, I would be happy to help.) 13 | 14 | ## Installation 15 | 16 | This repo was tested on Python 3.6 and PyTorch 1.0.1 17 | 18 | PyTorch pretrained BigGAN can be installed from pip as follows: 19 | ```bash 20 | pip install pytorch-pretrained-biggan 21 | ``` 22 | 23 | If you simply want to play with the GAN this should be enough. 24 | 25 | If you want to use the conversion scripts and the imagenet utilities, additional requirements are needed, in particular TensorFlow and NLTK. To install all the requirements please use the `full_requirements.txt` file: 26 | ```bash 27 | git clone https://github.com/huggingface/pytorch-pretrained-BigGAN.git 28 | cd pytorch-pretrained-BigGAN 29 | pip install -r full_requirements.txt 30 | ``` 31 | 32 | ## Models 33 | 34 | This repository provide direct and simple access to the pretrained "deep" versions of BigGAN for 128, 256 and 512 pixels resolutions as described in the [associated publication](https://openreview.net/forum?id=B1xsqj09Fm). 35 | Here are some details on the models: 36 | 37 | - `BigGAN-deep-128`: a 50.4M parameters model generating 128x128 pixels images, the model dump weights 201 MB, 38 | - `BigGAN-deep-256`: a 55.9M parameters model generating 256x256 pixels images, the model dump weights 224 MB, 39 | - `BigGAN-deep-512`: a 56.2M parameters model generating 512x512 pixels images, the model dump weights 225 MB. 40 | 41 | Please refer to Appendix B of the paper for details on the architectures. 42 | 43 | All models comprise pre-computed batch norm statistics for 51 truncation values between 0 and 1 (see Appendix C.1 in the paper for details). 44 | 45 | ## Usage 46 | 47 | Here is a quick-start example using `BigGAN` with a pre-trained model. 48 | 49 | See the [doc section](#doc) below for details on these classes and methods. 50 | 51 | ```python 52 | import torch 53 | from pytorch_pretrained_biggan import (BigGAN, one_hot_from_names, truncated_noise_sample, 54 | save_as_images, display_in_terminal) 55 | 56 | # OPTIONAL: if you want to have more information on what's happening, activate the logger as follows 57 | import logging 58 | logging.basicConfig(level=logging.INFO) 59 | 60 | # Load pre-trained model tokenizer (vocabulary) 61 | model = BigGAN.from_pretrained('biggan-deep-256') 62 | 63 | # Prepare a input 64 | truncation = 0.4 65 | class_vector = one_hot_from_names(['soap bubble', 'coffee', 'mushroom'], batch_size=3) 66 | noise_vector = truncated_noise_sample(truncation=truncation, batch_size=3) 67 | 68 | # All in tensors 69 | noise_vector = torch.from_numpy(noise_vector) 70 | class_vector = torch.from_numpy(class_vector) 71 | 72 | # If you have a GPU, put everything on cuda 73 | noise_vector = noise_vector.to('cuda') 74 | class_vector = class_vector.to('cuda') 75 | model.to('cuda') 76 | 77 | # Generate an image 78 | with torch.no_grad(): 79 | output = model(noise_vector, class_vector, truncation) 80 | 81 | # If you have a GPU put back on CPU 82 | output = output.to('cpu') 83 | 84 | # If you have a sixtel compatible terminal you can display the images in the terminal 85 | # (see https://github.com/saitoha/libsixel for details) 86 | display_in_terminal(output) 87 | 88 | # Save results as png images 89 | save_as_images(output) 90 | ``` 91 | 92 | ![output_0](assets/output_0.png) 93 | ![output_1](assets/output_1.png) 94 | ![output_2](assets/output_2.png) 95 | 96 | ## Doc 97 | 98 | ### Loading DeepMind's pre-trained weights 99 | 100 | To load one of DeepMind's pre-trained models, instantiate a `BigGAN` model with `from_pretrained()` as: 101 | 102 | ```python 103 | model = BigGAN.from_pretrained(PRE_TRAINED_MODEL_NAME_OR_PATH, cache_dir=None) 104 | ``` 105 | 106 | where 107 | 108 | - `PRE_TRAINED_MODEL_NAME_OR_PATH` is either: 109 | 110 | - the shortcut name of a Google AI's or OpenAI's pre-trained model selected in the list: 111 | 112 | - `biggan-deep-128`: 12-layer, 768-hidden, 12-heads, 110M parameters 113 | - `biggan-deep-256`: 24-layer, 1024-hidden, 16-heads, 340M parameters 114 | - `biggan-deep-512`: 12-layer, 768-hidden, 12-heads , 110M parameters 115 | 116 | - a path or url to a pretrained model archive containing: 117 | 118 | - `config.json`: a configuration file for the model, and 119 | - `pytorch_model.bin` a PyTorch dump of a pre-trained instance of `BigGAN` (saved with the usual `torch.save()`). 120 | 121 | If `PRE_TRAINED_MODEL_NAME_OR_PATH` is a shortcut name, the pre-trained weights will be downloaded from AWS S3 (see the links [here](pytorch_pretrained_biggan/model.py)) and stored in a cache folder to avoid future download (the cache folder can be found at `~/.pytorch_pretrained_biggan/`). 122 | - `cache_dir` can be an optional path to a specific directory to download and cache the pre-trained model weights. 123 | 124 | ### Configuration 125 | 126 | `BigGANConfig` is a class to store and load BigGAN configurations. It's defined in [`config.py`](./pytorch_pretrained_biggan/config.py). 127 | 128 | Here are some details on the attributes: 129 | 130 | - `output_dim`: output resolution of the GAN (128, 256 or 512) for the pre-trained models, 131 | - `z_dim`: size of the noise vector (128 for the pre-trained models). 132 | - `class_embed_dim`: size of the class embedding vectors (128 for the pre-trained models). 133 | - `channel_width`: size of each channel (128 for the pre-trained models). 134 | - `num_classes`: number of classes in the training dataset, like imagenet (1000 for the pre-trained models). 135 | - `layers`: A list of layers definition. Each definition for a layer is a triple of [up-sample in the layer ? (bool), number of input channels (int), number of output channels (int)] 136 | - `attention_layer_position`: Position of the self-attention layer in the layer hierarchy (8 for the pre-trained models). 137 | - `eps`: epsilon value to use for spectral and batch normalization layers (1e-4 for the pre-trained models). 138 | - `n_stats`: number of pre-computed statistics for the batch normalization layers associated to various truncation values between 0 and 1 (51 for the pre-trained models). 139 | 140 | ### Model 141 | 142 | `BigGAN` is a PyTorch model (`torch.nn.Module`) of BigGAN defined in [`model.py`](./pytorch_pretrained_biggan/model.py). This model comprises the class embeddings (a linear layer) and the generator with a series of convolutions and conditional batch norms. The discriminator is currently not implemented since pre-trained weights have not been released for it. 143 | 144 | The inputs and output are **identical to the TensorFlow model inputs and outputs**. 145 | 146 | We detail them here. 147 | 148 | `BigGAN` takes as *inputs*: 149 | 150 | - `z`: a torch.FloatTensor of shape [batch_size, config.z_dim] with noise sampled from a truncated normal distribution, and 151 | - `class_label`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to a `sentence B` token (see BERT paper for more details). 152 | - `truncation`: a float between 0 (not comprised) and 1. The truncation of the truncated normal used for creating the noise vector. This truncation value is used to selecte between a set of pre-computed statistics (means and variances) for the batch norm layers. 153 | 154 | `BigGAN` *outputs* an array of shape [batch_size, 3, resolution, resolution] where resolution is 128, 256 or 512 depending of the model: 155 | 156 | ### Utilities: Images, Noise, Imagenet classes 157 | 158 | We provide a few utility method to use the model. They are defined in [`utils.py`](./pytorch_pretrained_biggan/utils.py). 159 | 160 | Here are some details on these methods: 161 | 162 | - `truncated_noise_sample(batch_size=1, dim_z=128, truncation=1., seed=None)`: 163 | 164 | Create a truncated noise vector. 165 | - Params: 166 | - batch_size: batch size. 167 | - dim_z: dimension of z 168 | - truncation: truncation value to use 169 | - seed: seed for the random generator 170 | - Output: 171 | array of shape (batch_size, dim_z) 172 | 173 | - `convert_to_images(obj)`: 174 | 175 | Convert an output tensor from BigGAN in a list of images. 176 | - Params: 177 | - obj: tensor or numpy array of shape (batch_size, channels, height, width) 178 | - Output: 179 | - list of Pillow Images of size (height, width) 180 | 181 | - `save_as_images(obj, file_name='output')`: 182 | 183 | Convert and save an output tensor from BigGAN in a list of saved images. 184 | - Params: 185 | - obj: tensor or numpy array of shape (batch_size, channels, height, width) 186 | - file_name: path and beggingin of filename to save. 187 | Images will be saved as `file_name_{image_number}.png` 188 | 189 | - `display_in_terminal(obj)`: 190 | 191 | Convert and display an output tensor from BigGAN in the terminal. This function use `libsixel` and will only work in a libsixel-compatible terminal. Please refer to https://github.com/saitoha/libsixel for more details. 192 | - Params: 193 | - obj: tensor or numpy array of shape (batch_size, channels, height, width) 194 | - file_name: path and beggingin of filename to save. 195 | Images will be saved as `file_name_{image_number}.png` 196 | 197 | - `one_hot_from_int(int_or_list, batch_size=1)`: 198 | 199 | Create a one-hot vector from a class index or a list of class indices. 200 | - Params: 201 | - int_or_list: int, or list of int, of the imagenet classes (between 0 and 999) 202 | - batch_size: batch size. 203 | - If int_or_list is an int create a batch of identical classes. 204 | - If int_or_list is a list, we should have `len(int_or_list) == batch_size` 205 | - Output: 206 | - array of shape (batch_size, 1000) 207 | 208 | - `one_hot_from_names(class_name, batch_size=1)`: 209 | 210 | Create a one-hot vector from the name of an imagenet class ('tennis ball', 'daisy', ...). We use NLTK's wordnet search to try to find the relevant synset of ImageNet and take the first one. If we can't find it direcly, we look at the hyponyms and hypernyms of the class name. 211 | - Params: 212 | - class_name: string containing the name of an imagenet object. 213 | - Output: 214 | - array of shape (batch_size, 1000) 215 | 216 | ## Download and conversion scripts 217 | 218 | Scripts to download and convert the TensorFlow models from TensorFlow Hub are provided in [./scripts](./scripts/). 219 | 220 | The scripts can be used directly as: 221 | ```bash 222 | ./scripts/download_tf_hub_models.sh 223 | ./scripts/convert_tf_hub_models.sh 224 | ``` 225 | -------------------------------------------------------------------------------- /pytorch_pretrained_biggan/model.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """ BigGAN PyTorch model. 3 | From "Large Scale GAN Training for High Fidelity Natural Image Synthesis" 4 | By Andrew Brocky, Jeff Donahuey and Karen Simonyan. 5 | https://openreview.net/forum?id=B1xsqj09Fm 6 | 7 | PyTorch version implemented from the computational graph of the TF Hub module for BigGAN. 8 | Some part of the code are adapted from https://github.com/brain-research/self-attention-gan 9 | 10 | This version only comprises the generator (since the discriminator's weights are not released). 11 | This version only comprises the "deep" version of BigGAN (see publication). 12 | """ 13 | from __future__ import (absolute_import, division, print_function, unicode_literals) 14 | 15 | import os 16 | import logging 17 | import math 18 | 19 | import numpy as np 20 | import torch 21 | import torch.nn as nn 22 | import torch.nn.functional as F 23 | 24 | from .config import BigGANConfig 25 | from .file_utils import cached_path 26 | 27 | logger = logging.getLogger(__name__) 28 | 29 | PRETRAINED_MODEL_ARCHIVE_MAP = { 30 | 'biggan-deep-128': "https://s3.amazonaws.com/models.huggingface.co/biggan/biggan-deep-128-pytorch_model.bin", 31 | 'biggan-deep-256': "https://s3.amazonaws.com/models.huggingface.co/biggan/biggan-deep-256-pytorch_model.bin", 32 | 'biggan-deep-512': "https://s3.amazonaws.com/models.huggingface.co/biggan/biggan-deep-512-pytorch_model.bin", 33 | } 34 | 35 | PRETRAINED_CONFIG_ARCHIVE_MAP = { 36 | 'biggan-deep-128': "https://s3.amazonaws.com/models.huggingface.co/biggan/biggan-deep-128-config.json", 37 | 'biggan-deep-256': "https://s3.amazonaws.com/models.huggingface.co/biggan/biggan-deep-256-config.json", 38 | 'biggan-deep-512': "https://s3.amazonaws.com/models.huggingface.co/biggan/biggan-deep-512-config.json", 39 | } 40 | 41 | WEIGHTS_NAME = 'pytorch_model.bin' 42 | CONFIG_NAME = 'config.json' 43 | 44 | 45 | def snconv2d(eps=1e-12, **kwargs): 46 | return nn.utils.spectral_norm(nn.Conv2d(**kwargs), eps=eps) 47 | 48 | def snlinear(eps=1e-12, **kwargs): 49 | return nn.utils.spectral_norm(nn.Linear(**kwargs), eps=eps) 50 | 51 | def sn_embedding(eps=1e-12, **kwargs): 52 | return nn.utils.spectral_norm(nn.Embedding(**kwargs), eps=eps) 53 | 54 | class SelfAttn(nn.Module): 55 | """ Self attention Layer""" 56 | def __init__(self, in_channels, eps=1e-12): 57 | super(SelfAttn, self).__init__() 58 | self.in_channels = in_channels 59 | self.snconv1x1_theta = snconv2d(in_channels=in_channels, out_channels=in_channels//8, 60 | kernel_size=1, bias=False, eps=eps) 61 | self.snconv1x1_phi = snconv2d(in_channels=in_channels, out_channels=in_channels//8, 62 | kernel_size=1, bias=False, eps=eps) 63 | self.snconv1x1_g = snconv2d(in_channels=in_channels, out_channels=in_channels//2, 64 | kernel_size=1, bias=False, eps=eps) 65 | self.snconv1x1_o_conv = snconv2d(in_channels=in_channels//2, out_channels=in_channels, 66 | kernel_size=1, bias=False, eps=eps) 67 | self.maxpool = nn.MaxPool2d(2, stride=2, padding=0) 68 | self.softmax = nn.Softmax(dim=-1) 69 | self.gamma = nn.Parameter(torch.zeros(1)) 70 | 71 | def forward(self, x): 72 | _, ch, h, w = x.size() 73 | # Theta path 74 | theta = self.snconv1x1_theta(x) 75 | theta = theta.view(-1, ch//8, h*w) 76 | # Phi path 77 | phi = self.snconv1x1_phi(x) 78 | phi = self.maxpool(phi) 79 | phi = phi.view(-1, ch//8, h*w//4) 80 | # Attn map 81 | attn = torch.bmm(theta.permute(0, 2, 1), phi) 82 | attn = self.softmax(attn) 83 | # g path 84 | g = self.snconv1x1_g(x) 85 | g = self.maxpool(g) 86 | g = g.view(-1, ch//2, h*w//4) 87 | # Attn_g - o_conv 88 | attn_g = torch.bmm(g, attn.permute(0, 2, 1)) 89 | attn_g = attn_g.view(-1, ch//2, h, w) 90 | attn_g = self.snconv1x1_o_conv(attn_g) 91 | # Out 92 | out = x + self.gamma*attn_g 93 | return out 94 | 95 | 96 | class BigGANBatchNorm(nn.Module): 97 | """ This is a batch norm module that can handle conditional input and can be provided with pre-computed 98 | activation means and variances for various truncation parameters. 99 | 100 | We cannot just rely on torch.batch_norm since it cannot handle 101 | batched weights (pytorch 1.0.1). We computate batch_norm our-self without updating running means and variances. 102 | If you want to train this model you should add running means and variance computation logic. 103 | """ 104 | def __init__(self, num_features, condition_vector_dim=None, n_stats=51, eps=1e-4, conditional=True): 105 | super(BigGANBatchNorm, self).__init__() 106 | self.num_features = num_features 107 | self.eps = eps 108 | self.conditional = conditional 109 | 110 | # We use pre-computed statistics for n_stats values of truncation between 0 and 1 111 | self.register_buffer('running_means', torch.zeros(n_stats, num_features)) 112 | self.register_buffer('running_vars', torch.ones(n_stats, num_features)) 113 | self.step_size = 1.0 / (n_stats - 1) 114 | 115 | if conditional: 116 | assert condition_vector_dim is not None 117 | self.scale = snlinear(in_features=condition_vector_dim, out_features=num_features, bias=False, eps=eps) 118 | self.offset = snlinear(in_features=condition_vector_dim, out_features=num_features, bias=False, eps=eps) 119 | else: 120 | self.weight = torch.nn.Parameter(torch.Tensor(num_features)) 121 | self.bias = torch.nn.Parameter(torch.Tensor(num_features)) 122 | 123 | def forward(self, x, truncation, condition_vector=None): 124 | # Retreive pre-computed statistics associated to this truncation 125 | coef, start_idx = math.modf(truncation / self.step_size) 126 | start_idx = int(start_idx) 127 | if coef != 0.0: # Interpolate 128 | running_mean = self.running_means[start_idx] * coef + self.running_means[start_idx + 1] * (1 - coef) 129 | running_var = self.running_vars[start_idx] * coef + self.running_vars[start_idx + 1] * (1 - coef) 130 | else: 131 | running_mean = self.running_means[start_idx] 132 | running_var = self.running_vars[start_idx] 133 | 134 | if self.conditional: 135 | running_mean = running_mean.unsqueeze(0).unsqueeze(-1).unsqueeze(-1) 136 | running_var = running_var.unsqueeze(0).unsqueeze(-1).unsqueeze(-1) 137 | 138 | weight = 1 + self.scale(condition_vector).unsqueeze(-1).unsqueeze(-1) 139 | bias = self.offset(condition_vector).unsqueeze(-1).unsqueeze(-1) 140 | 141 | out = (x - running_mean) / torch.sqrt(running_var + self.eps) * weight + bias 142 | else: 143 | out = F.batch_norm(x, running_mean, running_var, self.weight, self.bias, 144 | training=False, momentum=0.0, eps=self.eps) 145 | 146 | return out 147 | 148 | 149 | class GenBlock(nn.Module): 150 | def __init__(self, in_size, out_size, condition_vector_dim, reduction_factor=4, up_sample=False, 151 | n_stats=51, eps=1e-12): 152 | super(GenBlock, self).__init__() 153 | self.up_sample = up_sample 154 | self.drop_channels = (in_size != out_size) 155 | middle_size = in_size // reduction_factor 156 | 157 | self.bn_0 = BigGANBatchNorm(in_size, condition_vector_dim, n_stats=n_stats, eps=eps, conditional=True) 158 | self.conv_0 = snconv2d(in_channels=in_size, out_channels=middle_size, kernel_size=1, eps=eps) 159 | 160 | self.bn_1 = BigGANBatchNorm(middle_size, condition_vector_dim, n_stats=n_stats, eps=eps, conditional=True) 161 | self.conv_1 = snconv2d(in_channels=middle_size, out_channels=middle_size, kernel_size=3, padding=1, eps=eps) 162 | 163 | self.bn_2 = BigGANBatchNorm(middle_size, condition_vector_dim, n_stats=n_stats, eps=eps, conditional=True) 164 | self.conv_2 = snconv2d(in_channels=middle_size, out_channels=middle_size, kernel_size=3, padding=1, eps=eps) 165 | 166 | self.bn_3 = BigGANBatchNorm(middle_size, condition_vector_dim, n_stats=n_stats, eps=eps, conditional=True) 167 | self.conv_3 = snconv2d(in_channels=middle_size, out_channels=out_size, kernel_size=1, eps=eps) 168 | 169 | self.relu = nn.ReLU() 170 | 171 | def forward(self, x, cond_vector, truncation): 172 | x0 = x 173 | 174 | x = self.bn_0(x, truncation, cond_vector) 175 | x = self.relu(x) 176 | x = self.conv_0(x) 177 | 178 | x = self.bn_1(x, truncation, cond_vector) 179 | x = self.relu(x) 180 | if self.up_sample: 181 | x = F.interpolate(x, scale_factor=2, mode='nearest') 182 | x = self.conv_1(x) 183 | 184 | x = self.bn_2(x, truncation, cond_vector) 185 | x = self.relu(x) 186 | x = self.conv_2(x) 187 | 188 | x = self.bn_3(x, truncation, cond_vector) 189 | x = self.relu(x) 190 | x = self.conv_3(x) 191 | 192 | if self.drop_channels: 193 | new_channels = x0.shape[1] // 2 194 | x0 = x0[:, :new_channels, ...] 195 | if self.up_sample: 196 | x0 = F.interpolate(x0, scale_factor=2, mode='nearest') 197 | 198 | out = x + x0 199 | return out 200 | 201 | class Generator(nn.Module): 202 | def __init__(self, config): 203 | super(Generator, self).__init__() 204 | self.config = config 205 | ch = config.channel_width 206 | condition_vector_dim = config.z_dim * 2 207 | 208 | self.gen_z = snlinear(in_features=condition_vector_dim, 209 | out_features=4 * 4 * 16 * ch, eps=config.eps) 210 | 211 | layers = [] 212 | for i, layer in enumerate(config.layers): 213 | if i == config.attention_layer_position: 214 | layers.append(SelfAttn(ch*layer[1], eps=config.eps)) 215 | layers.append(GenBlock(ch*layer[1], 216 | ch*layer[2], 217 | condition_vector_dim, 218 | up_sample=layer[0], 219 | n_stats=config.n_stats, 220 | eps=config.eps)) 221 | self.layers = nn.ModuleList(layers) 222 | 223 | self.bn = BigGANBatchNorm(ch, n_stats=config.n_stats, eps=config.eps, conditional=False) 224 | self.relu = nn.ReLU() 225 | self.conv_to_rgb = snconv2d(in_channels=ch, out_channels=ch, kernel_size=3, padding=1, eps=config.eps) 226 | self.tanh = nn.Tanh() 227 | 228 | def forward(self, cond_vector, truncation): 229 | z = self.gen_z(cond_vector) 230 | 231 | # We use this conversion step to be able to use TF weights: 232 | # TF convention on shape is [batch, height, width, channels] 233 | # PT convention on shape is [batch, channels, height, width] 234 | z = z.view(-1, 4, 4, 16 * self.config.channel_width) 235 | z = z.permute(0, 3, 1, 2).contiguous() 236 | 237 | for i, layer in enumerate(self.layers): 238 | if isinstance(layer, GenBlock): 239 | z = layer(z, cond_vector, truncation) 240 | else: 241 | z = layer(z) 242 | 243 | z = self.bn(z, truncation) 244 | z = self.relu(z) 245 | z = self.conv_to_rgb(z) 246 | z = z[:, :3, ...] 247 | z = self.tanh(z) 248 | return z 249 | 250 | class BigGAN(nn.Module): 251 | """BigGAN Generator.""" 252 | 253 | @classmethod 254 | def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): 255 | if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP: 256 | model_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path] 257 | config_file = PRETRAINED_CONFIG_ARCHIVE_MAP[pretrained_model_name_or_path] 258 | else: 259 | model_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME) 260 | config_file = os.path.join(pretrained_model_name_or_path, CONFIG_NAME) 261 | 262 | try: 263 | resolved_model_file = cached_path(model_file, cache_dir=cache_dir) 264 | resolved_config_file = cached_path(config_file, cache_dir=cache_dir) 265 | except EnvironmentError: 266 | logger.error("Wrong model name, should be a valid path to a folder containing " 267 | "a {} file and a {} file or a model name in {}".format( 268 | WEIGHTS_NAME, CONFIG_NAME, PRETRAINED_MODEL_ARCHIVE_MAP.keys())) 269 | raise 270 | 271 | logger.info("loading model {} from cache at {}".format(pretrained_model_name_or_path, resolved_model_file)) 272 | 273 | # Load config 274 | config = BigGANConfig.from_json_file(resolved_config_file) 275 | logger.info("Model config {}".format(config)) 276 | 277 | # Instantiate model. 278 | model = cls(config, *inputs, **kwargs) 279 | state_dict = torch.load(resolved_model_file, map_location='cpu' if not torch.cuda.is_available() else None) 280 | model.load_state_dict(state_dict, strict=False) 281 | return model 282 | 283 | def __init__(self, config): 284 | super(BigGAN, self).__init__() 285 | self.config = config 286 | self.embeddings = nn.Linear(config.num_classes, config.z_dim, bias=False) 287 | self.generator = Generator(config) 288 | 289 | def forward(self, z, class_label, truncation): 290 | assert 0 < truncation <= 1 291 | 292 | embed = self.embeddings(class_label) 293 | cond_vector = torch.cat((z, embed), dim=1) 294 | 295 | z = self.generator(cond_vector, truncation) 296 | return z 297 | 298 | 299 | if __name__ == "__main__": 300 | import PIL 301 | from .utils import truncated_noise_sample, save_as_images, one_hot_from_names 302 | from .convert_tf_to_pytorch import load_tf_weights_in_biggan 303 | 304 | load_cache = False 305 | cache_path = './saved_model.pt' 306 | config = BigGANConfig() 307 | model = BigGAN(config) 308 | if not load_cache: 309 | model = load_tf_weights_in_biggan(model, config, './models/model_128/', './models/model_128/batchnorms_stats.bin') 310 | torch.save(model.state_dict(), cache_path) 311 | else: 312 | model.load_state_dict(torch.load(cache_path)) 313 | 314 | model.eval() 315 | 316 | truncation = 0.4 317 | noise = truncated_noise_sample(batch_size=2, truncation=truncation) 318 | label = one_hot_from_names('diver', batch_size=2) 319 | 320 | # Tests 321 | # noise = np.zeros((1, 128)) 322 | # label = [983] 323 | 324 | noise = torch.tensor(noise, dtype=torch.float) 325 | label = torch.tensor(label, dtype=torch.float) 326 | with torch.no_grad(): 327 | outputs = model(noise, label, truncation) 328 | print(outputs.shape) 329 | 330 | save_as_images(outputs) 331 | -------------------------------------------------------------------------------- /pytorch_pretrained_biggan/convert_tf_to_pytorch.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """ 3 | Convert a TF Hub model for BigGAN in a PT one. 4 | """ 5 | from __future__ import (absolute_import, division, print_function, unicode_literals) 6 | 7 | from itertools import chain 8 | 9 | import os 10 | import argparse 11 | import logging 12 | import numpy as np 13 | import torch 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | from torch.nn.functional import normalize 17 | 18 | from .model import BigGAN, WEIGHTS_NAME, CONFIG_NAME 19 | from .config import BigGANConfig 20 | 21 | logger = logging.getLogger(__name__) 22 | 23 | 24 | def extract_batch_norm_stats(tf_model_path, batch_norm_stats_path=None): 25 | try: 26 | import numpy as np 27 | import tensorflow as tf 28 | import tensorflow_hub as hub 29 | except ImportError: 30 | raise ImportError("Loading a TensorFlow models in PyTorch, requires TensorFlow and TF Hub to be installed. " 31 | "Please see https://www.tensorflow.org/install/ for installation instructions for TensorFlow. " 32 | "And see https://github.com/tensorflow/hub for installing Hub. " 33 | "Probably pip install tensorflow tensorflow-hub") 34 | tf.reset_default_graph() 35 | logger.info('Loading BigGAN module from: {}'.format(tf_model_path)) 36 | module = hub.Module(tf_model_path) 37 | inputs = {k: tf.placeholder(v.dtype, v.get_shape().as_list(), k) 38 | for k, v in module.get_input_info_dict().items()} 39 | output = module(inputs) 40 | 41 | initializer = tf.global_variables_initializer() 42 | sess = tf.Session() 43 | stacks = sum(((i*10 + 1, i*10 + 3, i*10 + 6, i*10 + 8) for i in range(50)), ()) 44 | numpy_stacks = [] 45 | for i in stacks: 46 | logger.info("Retrieving module_apply_default/stack_{}".format(i)) 47 | try: 48 | stack_var = tf.get_default_graph().get_tensor_by_name("module_apply_default/stack_%d:0" % i) 49 | except KeyError: 50 | break # We have all the stats 51 | numpy_stacks.append(sess.run(stack_var)) 52 | 53 | if batch_norm_stats_path is not None: 54 | torch.save(numpy_stacks, batch_norm_stats_path) 55 | else: 56 | return numpy_stacks 57 | 58 | 59 | def build_tf_to_pytorch_map(model, config): 60 | """ Build a map from TF variables to PyTorch modules. """ 61 | tf_to_pt_map = {} 62 | 63 | # Embeddings and GenZ 64 | tf_to_pt_map.update({'linear/w/ema_0.9999': model.embeddings.weight, 65 | 'Generator/GenZ/G_linear/b/ema_0.9999': model.generator.gen_z.bias, 66 | 'Generator/GenZ/G_linear/w/ema_0.9999': model.generator.gen_z.weight_orig, 67 | 'Generator/GenZ/G_linear/u0': model.generator.gen_z.weight_u}) 68 | 69 | # GBlock blocks 70 | model_layer_idx = 0 71 | for i, (up, in_channels, out_channels) in enumerate(config.layers): 72 | if i == config.attention_layer_position: 73 | model_layer_idx += 1 74 | layer_str = "Generator/GBlock_%d/" % i if i > 0 else "Generator/GBlock/" 75 | layer_pnt = model.generator.layers[model_layer_idx] 76 | for i in range(4): # Batchnorms 77 | batch_str = layer_str + ("BatchNorm_%d/" % i if i > 0 else "BatchNorm/") 78 | batch_pnt = getattr(layer_pnt, 'bn_%d' % i) 79 | for name in ('offset', 'scale'): 80 | sub_module_str = batch_str + name + "/" 81 | sub_module_pnt = getattr(batch_pnt, name) 82 | tf_to_pt_map.update({sub_module_str + "w/ema_0.9999": sub_module_pnt.weight_orig, 83 | sub_module_str + "u0": sub_module_pnt.weight_u}) 84 | for i in range(4): # Convolutions 85 | conv_str = layer_str + "conv%d/" % i 86 | conv_pnt = getattr(layer_pnt, 'conv_%d' % i) 87 | tf_to_pt_map.update({conv_str + "b/ema_0.9999": conv_pnt.bias, 88 | conv_str + "w/ema_0.9999": conv_pnt.weight_orig, 89 | conv_str + "u0": conv_pnt.weight_u}) 90 | model_layer_idx += 1 91 | 92 | # Attention block 93 | layer_str = "Generator/attention/" 94 | layer_pnt = model.generator.layers[config.attention_layer_position] 95 | tf_to_pt_map.update({layer_str + "gamma/ema_0.9999": layer_pnt.gamma}) 96 | for pt_name, tf_name in zip(['snconv1x1_g', 'snconv1x1_o_conv', 'snconv1x1_phi', 'snconv1x1_theta'], 97 | ['g/', 'o_conv/', 'phi/', 'theta/']): 98 | sub_module_str = layer_str + tf_name 99 | sub_module_pnt = getattr(layer_pnt, pt_name) 100 | tf_to_pt_map.update({sub_module_str + "w/ema_0.9999": sub_module_pnt.weight_orig, 101 | sub_module_str + "u0": sub_module_pnt.weight_u}) 102 | 103 | # final batch norm and conv to rgb 104 | layer_str = "Generator/BatchNorm/" 105 | layer_pnt = model.generator.bn 106 | tf_to_pt_map.update({layer_str + "offset/ema_0.9999": layer_pnt.bias, 107 | layer_str + "scale/ema_0.9999": layer_pnt.weight}) 108 | layer_str = "Generator/conv_to_rgb/" 109 | layer_pnt = model.generator.conv_to_rgb 110 | tf_to_pt_map.update({layer_str + "b/ema_0.9999": layer_pnt.bias, 111 | layer_str + "w/ema_0.9999": layer_pnt.weight_orig, 112 | layer_str + "u0": layer_pnt.weight_u}) 113 | return tf_to_pt_map 114 | 115 | 116 | def load_tf_weights_in_biggan(model, config, tf_model_path, batch_norm_stats_path=None): 117 | """ Load tf checkpoints and standing statistics in a pytorch model 118 | """ 119 | try: 120 | import numpy as np 121 | import tensorflow as tf 122 | except ImportError: 123 | raise ImportError("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " 124 | "https://www.tensorflow.org/install/ for installation instructions.") 125 | # Load weights from TF model 126 | checkpoint_path = tf_model_path + "/variables/variables" 127 | init_vars = tf.train.list_variables(checkpoint_path) 128 | from pprint import pprint 129 | pprint(init_vars) 130 | 131 | # Extract batch norm statistics from model if needed 132 | if batch_norm_stats_path: 133 | stats = torch.load(batch_norm_stats_path) 134 | else: 135 | logger.info("Extracting batch norm stats") 136 | stats = extract_batch_norm_stats(tf_model_path) 137 | 138 | # Build TF to PyTorch weights loading map 139 | tf_to_pt_map = build_tf_to_pytorch_map(model, config) 140 | 141 | tf_weights = {} 142 | for name in tf_to_pt_map.keys(): 143 | array = tf.train.load_variable(checkpoint_path, name) 144 | tf_weights[name] = array 145 | # logger.info("Loading TF weight {} with shape {}".format(name, array.shape)) 146 | 147 | # Load parameters 148 | with torch.no_grad(): 149 | pt_params_pnt = set() 150 | for name, pointer in tf_to_pt_map.items(): 151 | array = tf_weights[name] 152 | if pointer.dim() == 1: 153 | if pointer.dim() < array.ndim: 154 | array = np.squeeze(array) 155 | elif pointer.dim() == 2: # Weights 156 | array = np.transpose(array) 157 | elif pointer.dim() == 4: # Convolutions 158 | array = np.transpose(array, (3, 2, 0, 1)) 159 | else: 160 | raise "Wrong dimensions to adjust: " + str((pointer.shape, array.shape)) 161 | if pointer.shape != array.shape: 162 | raise ValueError("Wrong dimensions: " + str((pointer.shape, array.shape))) 163 | logger.info("Initialize PyTorch weight {} with shape {}".format(name, pointer.shape)) 164 | pointer.data = torch.from_numpy(array) if isinstance(array, np.ndarray) else torch.tensor(array) 165 | tf_weights.pop(name, None) 166 | pt_params_pnt.add(pointer.data_ptr()) 167 | 168 | # Prepare SpectralNorm buffers by running one step of Spectral Norm (no need to train the model): 169 | for module in model.modules(): 170 | for n, buffer in module.named_buffers(): 171 | if n == 'weight_v': 172 | weight_mat = module.weight_orig 173 | weight_mat = weight_mat.reshape(weight_mat.size(0), -1) 174 | u = module.weight_u 175 | 176 | v = normalize(torch.mv(weight_mat.t(), u), dim=0, eps=config.eps) 177 | buffer.data = v 178 | pt_params_pnt.add(buffer.data_ptr()) 179 | 180 | u = normalize(torch.mv(weight_mat, v), dim=0, eps=config.eps) 181 | module.weight_u.data = u 182 | pt_params_pnt.add(module.weight_u.data_ptr()) 183 | 184 | # Load batch norm statistics 185 | index = 0 186 | for layer in model.generator.layers: 187 | if not hasattr(layer, 'bn_0'): 188 | continue 189 | for i in range(4): # Batchnorms 190 | bn_pointer = getattr(layer, 'bn_%d' % i) 191 | pointer = bn_pointer.running_means 192 | if pointer.shape != stats[index].shape: 193 | raise "Wrong dimensions: " + str((pointer.shape, stats[index].shape)) 194 | pointer.data = torch.from_numpy(stats[index]) 195 | pt_params_pnt.add(pointer.data_ptr()) 196 | 197 | pointer = bn_pointer.running_vars 198 | if pointer.shape != stats[index+1].shape: 199 | raise "Wrong dimensions: " + str((pointer.shape, stats[index].shape)) 200 | pointer.data = torch.from_numpy(stats[index+1]) 201 | pt_params_pnt.add(pointer.data_ptr()) 202 | 203 | index += 2 204 | 205 | bn_pointer = model.generator.bn 206 | pointer = bn_pointer.running_means 207 | if pointer.shape != stats[index].shape: 208 | raise "Wrong dimensions: " + str((pointer.shape, stats[index].shape)) 209 | pointer.data = torch.from_numpy(stats[index]) 210 | pt_params_pnt.add(pointer.data_ptr()) 211 | 212 | pointer = bn_pointer.running_vars 213 | if pointer.shape != stats[index+1].shape: 214 | raise "Wrong dimensions: " + str((pointer.shape, stats[index].shape)) 215 | pointer.data = torch.from_numpy(stats[index+1]) 216 | pt_params_pnt.add(pointer.data_ptr()) 217 | 218 | remaining_params = list(n for n, t in chain(model.named_parameters(), model.named_buffers()) \ 219 | if t.data_ptr() not in pt_params_pnt) 220 | 221 | logger.info("TF Weights not copied to PyTorch model: {} -".format(', '.join(tf_weights.keys()))) 222 | logger.info("Remanining parameters/buffers from PyTorch model: {} -".format(', '.join(remaining_params))) 223 | 224 | return model 225 | 226 | 227 | BigGAN128 = BigGANConfig(output_dim=128, z_dim=128, class_embed_dim=128, channel_width=128, num_classes=1000, 228 | layers=[(False, 16, 16), 229 | (True, 16, 16), 230 | (False, 16, 16), 231 | (True, 16, 8), 232 | (False, 8, 8), 233 | (True, 8, 4), 234 | (False, 4, 4), 235 | (True, 4, 2), 236 | (False, 2, 2), 237 | (True, 2, 1)], 238 | attention_layer_position=8, eps=1e-4, n_stats=51) 239 | 240 | BigGAN256 = BigGANConfig(output_dim=256, z_dim=128, class_embed_dim=128, channel_width=128, num_classes=1000, 241 | layers=[(False, 16, 16), 242 | (True, 16, 16), 243 | (False, 16, 16), 244 | (True, 16, 8), 245 | (False, 8, 8), 246 | (True, 8, 8), 247 | (False, 8, 8), 248 | (True, 8, 4), 249 | (False, 4, 4), 250 | (True, 4, 2), 251 | (False, 2, 2), 252 | (True, 2, 1)], 253 | attention_layer_position=8, eps=1e-4, n_stats=51) 254 | 255 | BigGAN512 = BigGANConfig(output_dim=512, z_dim=128, class_embed_dim=128, channel_width=128, num_classes=1000, 256 | layers=[(False, 16, 16), 257 | (True, 16, 16), 258 | (False, 16, 16), 259 | (True, 16, 8), 260 | (False, 8, 8), 261 | (True, 8, 8), 262 | (False, 8, 8), 263 | (True, 8, 4), 264 | (False, 4, 4), 265 | (True, 4, 2), 266 | (False, 2, 2), 267 | (True, 2, 1), 268 | (False, 1, 1), 269 | (True, 1, 1)], 270 | attention_layer_position=8, eps=1e-4, n_stats=51) 271 | 272 | 273 | def main(): 274 | parser = argparse.ArgumentParser(description="Convert a BigGAN TF Hub model in a PyTorch model") 275 | parser.add_argument("--model_type", type=str, default="", required=True, 276 | help="BigGAN model type (128, 256, 512)") 277 | parser.add_argument("--tf_model_path", type=str, default="", required=True, 278 | help="Path of the downloaded TF Hub model") 279 | parser.add_argument("--pt_save_path", type=str, default="", 280 | help="Folder to save the PyTorch model (default: Folder of the TF Hub model)") 281 | parser.add_argument("--batch_norm_stats_path", type=str, default="", 282 | help="Path of previously extracted batch norm statistics") 283 | args = parser.parse_args() 284 | 285 | logging.basicConfig(level=logging.INFO) 286 | 287 | if not args.pt_save_path: 288 | args.pt_save_path = args.tf_model_path 289 | 290 | if args.model_type == "128": 291 | config = BigGAN128 292 | elif args.model_type == "256": 293 | config = BigGAN256 294 | elif args.model_type == "512": 295 | config = BigGAN512 296 | else: 297 | raise ValueError("model_type should be one of 128, 256 or 512") 298 | 299 | model = BigGAN(config) 300 | model = load_tf_weights_in_biggan(model, config, args.tf_model_path, args.batch_norm_stats_path) 301 | 302 | model_save_path = os.path.join(args.pt_save_path, WEIGHTS_NAME) 303 | config_save_path = os.path.join(args.pt_save_path, CONFIG_NAME) 304 | 305 | logger.info("Save model dump to {}".format(model_save_path)) 306 | torch.save(model.state_dict(), model_save_path) 307 | logger.info("Save configuration file to {}".format(config_save_path)) 308 | with open(config_save_path, "w", encoding="utf-8") as f: 309 | f.write(config.to_json_string()) 310 | 311 | if __name__ == "__main__": 312 | main() 313 | -------------------------------------------------------------------------------- /pytorch_pretrained_biggan/utils.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """ BigGAN utilities to prepare truncated noise samples and convert/save/display output images. 3 | Also comprise ImageNet utilities to prepare one hot input vectors for ImageNet classes. 4 | We use Wordnet so you can just input a name in a string and automatically get a corresponding 5 | imagenet class if it exists (or a hypo/hypernym exists in imagenet). 6 | """ 7 | from __future__ import absolute_import, division, print_function, unicode_literals 8 | 9 | import json 10 | import logging 11 | from io import BytesIO 12 | 13 | import numpy as np 14 | from scipy.stats import truncnorm 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | NUM_CLASSES = 1000 19 | 20 | 21 | def truncated_noise_sample(batch_size=1, dim_z=128, truncation=1., seed=None): 22 | """ Create a truncated noise vector. 23 | Params: 24 | batch_size: batch size. 25 | dim_z: dimension of z 26 | truncation: truncation value to use 27 | seed: seed for the random generator 28 | Output: 29 | array of shape (batch_size, dim_z) 30 | """ 31 | state = None if seed is None else np.random.RandomState(seed) 32 | values = truncnorm.rvs(-2, 2, size=(batch_size, dim_z), random_state=state).astype(np.float32) 33 | return truncation * values 34 | 35 | 36 | def convert_to_images(obj): 37 | """ Convert an output tensor from BigGAN in a list of images. 38 | Params: 39 | obj: tensor or numpy array of shape (batch_size, channels, height, width) 40 | Output: 41 | list of Pillow Images of size (height, width) 42 | """ 43 | try: 44 | import PIL 45 | except ImportError: 46 | raise ImportError("Please install Pillow to use images: pip install Pillow") 47 | 48 | if not isinstance(obj, np.ndarray): 49 | obj = obj.detach().numpy() 50 | 51 | obj = obj.transpose((0, 2, 3, 1)) 52 | obj = np.clip(((obj + 1) / 2.0) * 256, 0, 255) 53 | 54 | img = [] 55 | for i, out in enumerate(obj): 56 | out_array = np.asarray(np.uint8(out), dtype=np.uint8) 57 | img.append(PIL.Image.fromarray(out_array)) 58 | return img 59 | 60 | 61 | def save_as_images(obj, file_name='output'): 62 | """ Convert and save an output tensor from BigGAN in a list of saved images. 63 | Params: 64 | obj: tensor or numpy array of shape (batch_size, channels, height, width) 65 | file_name: path and beggingin of filename to save. 66 | Images will be saved as `file_name_{image_number}.png` 67 | """ 68 | img = convert_to_images(obj) 69 | 70 | for i, out in enumerate(img): 71 | current_file_name = file_name + '_%d.png' % i 72 | logger.info("Saving image to {}".format(current_file_name)) 73 | out.save(current_file_name, 'png') 74 | 75 | 76 | def display_in_terminal(obj): 77 | """ Convert and display an output tensor from BigGAN in the terminal. 78 | This function use `libsixel` and will only work in a libsixel-compatible terminal. 79 | Please refer to https://github.com/saitoha/libsixel for more details. 80 | 81 | Params: 82 | obj: tensor or numpy array of shape (batch_size, channels, height, width) 83 | file_name: path and beggingin of filename to save. 84 | Images will be saved as `file_name_{image_number}.png` 85 | """ 86 | try: 87 | import PIL 88 | from libsixel import (sixel_output_new, sixel_dither_new, sixel_dither_initialize, 89 | sixel_dither_set_palette, sixel_dither_set_pixelformat, 90 | sixel_dither_get, sixel_encode, sixel_dither_unref, 91 | sixel_output_unref, SIXEL_PIXELFORMAT_RGBA8888, 92 | SIXEL_PIXELFORMAT_RGB888, SIXEL_PIXELFORMAT_PAL8, 93 | SIXEL_PIXELFORMAT_G8, SIXEL_PIXELFORMAT_G1) 94 | except ImportError: 95 | raise ImportError("Display in Terminal requires Pillow, libsixel " 96 | "and a libsixel compatible terminal. " 97 | "Please read info at https://github.com/saitoha/libsixel " 98 | "and install with pip install Pillow libsixel-python") 99 | 100 | s = BytesIO() 101 | 102 | images = convert_to_images(obj) 103 | widths, heights = zip(*(i.size for i in images)) 104 | 105 | output_width = sum(widths) 106 | output_height = max(heights) 107 | 108 | output_image = PIL.Image.new('RGB', (output_width, output_height)) 109 | 110 | x_offset = 0 111 | for im in images: 112 | output_image.paste(im, (x_offset,0)) 113 | x_offset += im.size[0] 114 | 115 | try: 116 | data = output_image.tobytes() 117 | except NotImplementedError: 118 | data = output_image.tostring() 119 | output = sixel_output_new(lambda data, s: s.write(data), s) 120 | 121 | try: 122 | if output_image.mode == 'RGBA': 123 | dither = sixel_dither_new(256) 124 | sixel_dither_initialize(dither, data, output_width, output_height, SIXEL_PIXELFORMAT_RGBA8888) 125 | elif output_image.mode == 'RGB': 126 | dither = sixel_dither_new(256) 127 | sixel_dither_initialize(dither, data, output_width, output_height, SIXEL_PIXELFORMAT_RGB888) 128 | elif output_image.mode == 'P': 129 | palette = output_image.getpalette() 130 | dither = sixel_dither_new(256) 131 | sixel_dither_set_palette(dither, palette) 132 | sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_PAL8) 133 | elif output_image.mode == 'L': 134 | dither = sixel_dither_get(SIXEL_BUILTIN_G8) 135 | sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_G8) 136 | elif output_image.mode == '1': 137 | dither = sixel_dither_get(SIXEL_BUILTIN_G1) 138 | sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_G1) 139 | else: 140 | raise RuntimeError('unexpected output_image mode') 141 | try: 142 | sixel_encode(data, output_width, output_height, 1, dither, output) 143 | print(s.getvalue().decode('ascii')) 144 | finally: 145 | sixel_dither_unref(dither) 146 | finally: 147 | sixel_output_unref(output) 148 | 149 | 150 | def one_hot_from_int(int_or_list, batch_size=1): 151 | """ Create a one-hot vector from a class index or a list of class indices. 152 | Params: 153 | int_or_list: int, or list of int, of the imagenet classes (between 0 and 999) 154 | batch_size: batch size. 155 | If int_or_list is an int create a batch of identical classes. 156 | If int_or_list is a list, we should have `len(int_or_list) == batch_size` 157 | Output: 158 | array of shape (batch_size, 1000) 159 | """ 160 | if isinstance(int_or_list, int): 161 | int_or_list = [int_or_list] 162 | 163 | if len(int_or_list) == 1 and batch_size > 1: 164 | int_or_list = [int_or_list[0]] * batch_size 165 | 166 | assert batch_size == len(int_or_list) 167 | 168 | array = np.zeros((batch_size, NUM_CLASSES), dtype=np.float32) 169 | for i, j in enumerate(int_or_list): 170 | array[i, j] = 1.0 171 | return array 172 | 173 | 174 | def one_hot_from_names(class_name_or_list, batch_size=1): 175 | """ Create a one-hot vector from the name of an imagenet class ('tennis ball', 'daisy', ...). 176 | We use NLTK's wordnet search to try to find the relevant synset of ImageNet and take the first one. 177 | If we can't find it direcly, we look at the hyponyms and hypernyms of the class name. 178 | 179 | Params: 180 | class_name_or_list: string containing the name of an imagenet object or a list of such strings (for a batch). 181 | Output: 182 | array of shape (batch_size, 1000) 183 | """ 184 | try: 185 | from nltk.corpus import wordnet as wn 186 | except ImportError: 187 | raise ImportError("You need to install nltk to use this function") 188 | 189 | if not isinstance(class_name_or_list, (list, tuple)): 190 | class_name_or_list = [class_name_or_list] 191 | else: 192 | batch_size = max(batch_size, len(class_name_or_list)) 193 | 194 | classes = [] 195 | for class_name in class_name_or_list: 196 | class_name = class_name.replace(" ", "_") 197 | 198 | original_synsets = wn.synsets(class_name) 199 | original_synsets = list(filter(lambda s: s.pos() == 'n', original_synsets)) # keep only names 200 | if not original_synsets: 201 | return None 202 | 203 | possible_synsets = list(filter(lambda s: s.offset() in IMAGENET, original_synsets)) 204 | if possible_synsets: 205 | classes.append(IMAGENET[possible_synsets[0].offset()]) 206 | else: 207 | # try hypernyms and hyponyms 208 | possible_synsets = sum([s.hypernyms() + s.hyponyms() for s in original_synsets], []) 209 | possible_synsets = list(filter(lambda s: s.offset() in IMAGENET, possible_synsets)) 210 | if possible_synsets: 211 | classes.append(IMAGENET[possible_synsets[0].offset()]) 212 | 213 | return one_hot_from_int(classes, batch_size=batch_size) 214 | 215 | 216 | IMAGENET = {1440764: 0, 1443537: 1, 1484850: 2, 1491361: 3, 1494475: 4, 1496331: 5, 1498041: 6, 1514668: 7, 1514859: 8, 1518878: 9, 1530575: 10, 1531178: 11, 1532829: 12, 1534433: 13, 1537544: 14, 1558993: 15, 1560419: 16, 1580077: 17, 1582220: 18, 1592084: 19, 1601694: 20, 1608432: 21, 1614925: 22, 1616318: 23, 1622779: 24, 1629819: 25, 1630670: 26, 1631663: 27, 1632458: 28, 1632777: 29, 1641577: 30, 1644373: 31, 1644900: 32, 1664065: 33, 1665541: 34, 1667114: 35, 1667778: 36, 1669191: 37, 1675722: 38, 1677366: 39, 1682714: 40, 1685808: 41, 1687978: 42, 1688243: 43, 1689811: 44, 1692333: 45, 1693334: 46, 1694178: 47, 1695060: 48, 1697457: 49, 1698640: 50, 1704323: 51, 1728572: 52, 1728920: 53, 1729322: 54, 1729977: 55, 1734418: 56, 1735189: 57, 1737021: 58, 1739381: 59, 1740131: 60, 1742172: 61, 1744401: 62, 1748264: 63, 1749939: 64, 1751748: 65, 1753488: 66, 1755581: 67, 1756291: 68, 1768244: 69, 1770081: 70, 1770393: 71, 1773157: 72, 1773549: 73, 1773797: 74, 1774384: 75, 1774750: 76, 1775062: 77, 1776313: 78, 1784675: 79, 1795545: 80, 1796340: 81, 1797886: 82, 1798484: 83, 1806143: 84, 1806567: 85, 1807496: 86, 1817953: 87, 1818515: 88, 1819313: 89, 1820546: 90, 1824575: 91, 1828970: 92, 1829413: 93, 1833805: 94, 1843065: 95, 1843383: 96, 1847000: 97, 1855032: 98, 1855672: 99, 1860187: 100, 1871265: 101, 1872401: 102, 1873310: 103, 1877812: 104, 1882714: 105, 1883070: 106, 1910747: 107, 1914609: 108, 1917289: 109, 1924916: 110, 1930112: 111, 1943899: 112, 1944390: 113, 1945685: 114, 1950731: 115, 1955084: 116, 1968897: 117, 1978287: 118, 1978455: 119, 1980166: 120, 1981276: 121, 1983481: 122, 1984695: 123, 1985128: 124, 1986214: 125, 1990800: 126, 2002556: 127, 2002724: 128, 2006656: 129, 2007558: 130, 2009229: 131, 2009912: 132, 2011460: 133, 2012849: 134, 2013706: 135, 2017213: 136, 2018207: 137, 2018795: 138, 2025239: 139, 2027492: 140, 2028035: 141, 2033041: 142, 2037110: 143, 2051845: 144, 2056570: 145, 2058221: 146, 2066245: 147, 2071294: 148, 2074367: 149, 2077923: 150, 2085620: 151, 2085782: 152, 2085936: 153, 2086079: 154, 2086240: 155, 2086646: 156, 2086910: 157, 2087046: 158, 2087394: 159, 2088094: 160, 2088238: 161, 2088364: 162, 2088466: 163, 2088632: 164, 2089078: 165, 2089867: 166, 2089973: 167, 2090379: 168, 2090622: 169, 2090721: 170, 2091032: 171, 2091134: 172, 2091244: 173, 2091467: 174, 2091635: 175, 2091831: 176, 2092002: 177, 2092339: 178, 2093256: 179, 2093428: 180, 2093647: 181, 2093754: 182, 2093859: 183, 2093991: 184, 2094114: 185, 2094258: 186, 2094433: 187, 2095314: 188, 2095570: 189, 2095889: 190, 2096051: 191, 2096177: 192, 2096294: 193, 2096437: 194, 2096585: 195, 2097047: 196, 2097130: 197, 2097209: 198, 2097298: 199, 2097474: 200, 2097658: 201, 2098105: 202, 2098286: 203, 2098413: 204, 2099267: 205, 2099429: 206, 2099601: 207, 2099712: 208, 2099849: 209, 2100236: 210, 2100583: 211, 2100735: 212, 2100877: 213, 2101006: 214, 2101388: 215, 2101556: 216, 2102040: 217, 2102177: 218, 2102318: 219, 2102480: 220, 2102973: 221, 2104029: 222, 2104365: 223, 2105056: 224, 2105162: 225, 2105251: 226, 2105412: 227, 2105505: 228, 2105641: 229, 2105855: 230, 2106030: 231, 2106166: 232, 2106382: 233, 2106550: 234, 2106662: 235, 2107142: 236, 2107312: 237, 2107574: 238, 2107683: 239, 2107908: 240, 2108000: 241, 2108089: 242, 2108422: 243, 2108551: 244, 2108915: 245, 2109047: 246, 2109525: 247, 2109961: 248, 2110063: 249, 2110185: 250, 2110341: 251, 2110627: 252, 2110806: 253, 2110958: 254, 2111129: 255, 2111277: 256, 2111500: 257, 2111889: 258, 2112018: 259, 2112137: 260, 2112350: 261, 2112706: 262, 2113023: 263, 2113186: 264, 2113624: 265, 2113712: 266, 2113799: 267, 2113978: 268, 2114367: 269, 2114548: 270, 2114712: 271, 2114855: 272, 2115641: 273, 2115913: 274, 2116738: 275, 2117135: 276, 2119022: 277, 2119789: 278, 2120079: 279, 2120505: 280, 2123045: 281, 2123159: 282, 2123394: 283, 2123597: 284, 2124075: 285, 2125311: 286, 2127052: 287, 2128385: 288, 2128757: 289, 2128925: 290, 2129165: 291, 2129604: 292, 2130308: 293, 2132136: 294, 2133161: 295, 2134084: 296, 2134418: 297, 2137549: 298, 2138441: 299, 2165105: 300, 2165456: 301, 2167151: 302, 2168699: 303, 2169497: 304, 2172182: 305, 2174001: 306, 2177972: 307, 2190166: 308, 2206856: 309, 2219486: 310, 2226429: 311, 2229544: 312, 2231487: 313, 2233338: 314, 2236044: 315, 2256656: 316, 2259212: 317, 2264363: 318, 2268443: 319, 2268853: 320, 2276258: 321, 2277742: 322, 2279972: 323, 2280649: 324, 2281406: 325, 2281787: 326, 2317335: 327, 2319095: 328, 2321529: 329, 2325366: 330, 2326432: 331, 2328150: 332, 2342885: 333, 2346627: 334, 2356798: 335, 2361337: 336, 2363005: 337, 2364673: 338, 2389026: 339, 2391049: 340, 2395406: 341, 2396427: 342, 2397096: 343, 2398521: 344, 2403003: 345, 2408429: 346, 2410509: 347, 2412080: 348, 2415577: 349, 2417914: 350, 2422106: 351, 2422699: 352, 2423022: 353, 2437312: 354, 2437616: 355, 2441942: 356, 2442845: 357, 2443114: 358, 2443484: 359, 2444819: 360, 2445715: 361, 2447366: 362, 2454379: 363, 2457408: 364, 2480495: 365, 2480855: 366, 2481823: 367, 2483362: 368, 2483708: 369, 2484975: 370, 2486261: 371, 2486410: 372, 2487347: 373, 2488291: 374, 2488702: 375, 2489166: 376, 2490219: 377, 2492035: 378, 2492660: 379, 2493509: 380, 2493793: 381, 2494079: 382, 2497673: 383, 2500267: 384, 2504013: 385, 2504458: 386, 2509815: 387, 2510455: 388, 2514041: 389, 2526121: 390, 2536864: 391, 2606052: 392, 2607072: 393, 2640242: 394, 2641379: 395, 2643566: 396, 2655020: 397, 2666196: 398, 2667093: 399, 2669723: 400, 2672831: 401, 2676566: 402, 2687172: 403, 2690373: 404, 2692877: 405, 2699494: 406, 2701002: 407, 2704792: 408, 2708093: 409, 2727426: 410, 2730930: 411, 2747177: 412, 2749479: 413, 2769748: 414, 2776631: 415, 2777292: 416, 2782093: 417, 2783161: 418, 2786058: 419, 2787622: 420, 2788148: 421, 2790996: 422, 2791124: 423, 2791270: 424, 2793495: 425, 2794156: 426, 2795169: 427, 2797295: 428, 2799071: 429, 2802426: 430, 2804414: 431, 2804610: 432, 2807133: 433, 2808304: 434, 2808440: 435, 2814533: 436, 2814860: 437, 2815834: 438, 2817516: 439, 2823428: 440, 2823750: 441, 2825657: 442, 2834397: 443, 2835271: 444, 2837789: 445, 2840245: 446, 2841315: 447, 2843684: 448, 2859443: 449, 2860847: 450, 2865351: 451, 2869837: 452, 2870880: 453, 2871525: 454, 2877765: 455, 2879718: 456, 2883205: 457, 2892201: 458, 2892767: 459, 2894605: 460, 2895154: 461, 2906734: 462, 2909870: 463, 2910353: 464, 2916936: 465, 2917067: 466, 2927161: 467, 2930766: 468, 2939185: 469, 2948072: 470, 2950826: 471, 2951358: 472, 2951585: 473, 2963159: 474, 2965783: 475, 2966193: 476, 2966687: 477, 2971356: 478, 2974003: 479, 2977058: 480, 2978881: 481, 2979186: 482, 2980441: 483, 2981792: 484, 2988304: 485, 2992211: 486, 2992529: 487, 2999410: 488, 3000134: 489, 3000247: 490, 3000684: 491, 3014705: 492, 3016953: 493, 3017168: 494, 3018349: 495, 3026506: 496, 3028079: 497, 3032252: 498, 3041632: 499, 3042490: 500, 3045698: 501, 3047690: 502, 3062245: 503, 3063599: 504, 3063689: 505, 3065424: 506, 3075370: 507, 3085013: 508, 3089624: 509, 3095699: 510, 3100240: 511, 3109150: 512, 3110669: 513, 3124043: 514, 3124170: 515, 3125729: 516, 3126707: 517, 3127747: 518, 3127925: 519, 3131574: 520, 3133878: 521, 3134739: 522, 3141823: 523, 3146219: 524, 3160309: 525, 3179701: 526, 3180011: 527, 3187595: 528, 3188531: 529, 3196217: 530, 3197337: 531, 3201208: 532, 3207743: 533, 3207941: 534, 3208938: 535, 3216828: 536, 3218198: 537, 3220513: 538, 3223299: 539, 3240683: 540, 3249569: 541, 3250847: 542, 3255030: 543, 3259280: 544, 3271574: 545, 3272010: 546, 3272562: 547, 3290653: 548, 3291819: 549, 3297495: 550, 3314780: 551, 3325584: 552, 3337140: 553, 3344393: 554, 3345487: 555, 3347037: 556, 3355925: 557, 3372029: 558, 3376595: 559, 3379051: 560, 3384352: 561, 3388043: 562, 3388183: 563, 3388549: 564, 3393912: 565, 3394916: 566, 3400231: 567, 3404251: 568, 3417042: 569, 3424325: 570, 3425413: 571, 3443371: 572, 3444034: 573, 3445777: 574, 3445924: 575, 3447447: 576, 3447721: 577, 3450230: 578, 3452741: 579, 3457902: 580, 3459775: 581, 3461385: 582, 3467068: 583, 3476684: 584, 3476991: 585, 3478589: 586, 3481172: 587, 3482405: 588, 3483316: 589, 3485407: 590, 3485794: 591, 3492542: 592, 3494278: 593, 3495258: 594, 3496892: 595, 3498962: 596, 3527444: 597, 3529860: 598, 3530642: 599, 3532672: 600, 3534580: 601, 3535780: 602, 3538406: 603, 3544143: 604, 3584254: 605, 3584829: 606, 3590841: 607, 3594734: 608, 3594945: 609, 3595614: 610, 3598930: 611, 3599486: 612, 3602883: 613, 3617480: 614, 3623198: 615, 3627232: 616, 3630383: 617, 3633091: 618, 3637318: 619, 3642806: 620, 3649909: 621, 3657121: 622, 3658185: 623, 3661043: 624, 3662601: 625, 3666591: 626, 3670208: 627, 3673027: 628, 3676483: 629, 3680355: 630, 3690938: 631, 3691459: 632, 3692522: 633, 3697007: 634, 3706229: 635, 3709823: 636, 3710193: 637, 3710637: 638, 3710721: 639, 3717622: 640, 3720891: 641, 3721384: 642, 3724870: 643, 3729826: 644, 3733131: 645, 3733281: 646, 3733805: 647, 3742115: 648, 3743016: 649, 3759954: 650, 3761084: 651, 3763968: 652, 3764736: 653, 3769881: 654, 3770439: 655, 3770679: 656, 3773504: 657, 3775071: 658, 3775546: 659, 3776460: 660, 3777568: 661, 3777754: 662, 3781244: 663, 3782006: 664, 3785016: 665, 3786901: 666, 3787032: 667, 3788195: 668, 3788365: 669, 3791053: 670, 3792782: 671, 3792972: 672, 3793489: 673, 3794056: 674, 3796401: 675, 3803284: 676, 3804744: 677, 3814639: 678, 3814906: 679, 3825788: 680, 3832673: 681, 3837869: 682, 3838899: 683, 3840681: 684, 3841143: 685, 3843555: 686, 3854065: 687, 3857828: 688, 3866082: 689, 3868242: 690, 3868863: 691, 3871628: 692, 3873416: 693, 3874293: 694, 3874599: 695, 3876231: 696, 3877472: 697, 3877845: 698, 3884397: 699, 3887697: 700, 3888257: 701, 3888605: 702, 3891251: 703, 3891332: 704, 3895866: 705, 3899768: 706, 3902125: 707, 3903868: 708, 3908618: 709, 3908714: 710, 3916031: 711, 3920288: 712, 3924679: 713, 3929660: 714, 3929855: 715, 3930313: 716, 3930630: 717, 3933933: 718, 3935335: 719, 3937543: 720, 3938244: 721, 3942813: 722, 3944341: 723, 3947888: 724, 3950228: 725, 3954731: 726, 3956157: 727, 3958227: 728, 3961711: 729, 3967562: 730, 3970156: 731, 3976467: 732, 3976657: 733, 3977966: 734, 3980874: 735, 3982430: 736, 3983396: 737, 3991062: 738, 3992509: 739, 3995372: 740, 3998194: 741, 4004767: 742, 4005630: 743, 4008634: 744, 4009552: 745, 4019541: 746, 4023962: 747, 4026417: 748, 4033901: 749, 4033995: 750, 4037443: 751, 4039381: 752, 4040759: 753, 4041544: 754, 4044716: 755, 4049303: 756, 4065272: 757, 4067472: 758, 4069434: 759, 4070727: 760, 4074963: 761, 4081281: 762, 4086273: 763, 4090263: 764, 4099969: 765, 4111531: 766, 4116512: 767, 4118538: 768, 4118776: 769, 4120489: 770, 4125021: 771, 4127249: 772, 4131690: 773, 4133789: 774, 4136333: 775, 4141076: 776, 4141327: 777, 4141975: 778, 4146614: 779, 4147183: 780, 4149813: 781, 4152593: 782, 4153751: 783, 4154565: 784, 4162706: 785, 4179913: 786, 4192698: 787, 4200800: 788, 4201297: 789, 4204238: 790, 4204347: 791, 4208210: 792, 4209133: 793, 4209239: 794, 4228054: 795, 4229816: 796, 4235860: 797, 4238763: 798, 4239074: 799, 4243546: 800, 4251144: 801, 4252077: 802, 4252225: 803, 4254120: 804, 4254680: 805, 4254777: 806, 4258138: 807, 4259630: 808, 4263257: 809, 4264628: 810, 4265275: 811, 4266014: 812, 4270147: 813, 4273569: 814, 4275548: 815, 4277352: 816, 4285008: 817, 4286575: 818, 4296562: 819, 4310018: 820, 4311004: 821, 4311174: 822, 4317175: 823, 4325704: 824, 4326547: 825, 4328186: 826, 4330267: 827, 4332243: 828, 4335435: 829, 4336792: 830, 4344873: 831, 4346328: 832, 4347754: 833, 4350905: 834, 4355338: 835, 4355933: 836, 4356056: 837, 4357314: 838, 4366367: 839, 4367480: 840, 4370456: 841, 4371430: 842, 4371774: 843, 4372370: 844, 4376876: 845, 4380533: 846, 4389033: 847, 4392985: 848, 4398044: 849, 4399382: 850, 4404412: 851, 4409515: 852, 4417672: 853, 4418357: 854, 4423845: 855, 4428191: 856, 4429376: 857, 4435653: 858, 4442312: 859, 4443257: 860, 4447861: 861, 4456115: 862, 4458633: 863, 4461696: 864, 4462240: 865, 4465501: 866, 4467665: 867, 4476259: 868, 4479046: 869, 4482393: 870, 4483307: 871, 4485082: 872, 4486054: 873, 4487081: 874, 4487394: 875, 4493381: 876, 4501370: 877, 4505470: 878, 4507155: 879, 4509417: 880, 4515003: 881, 4517823: 882, 4522168: 883, 4523525: 884, 4525038: 885, 4525305: 886, 4532106: 887, 4532670: 888, 4536866: 889, 4540053: 890, 4542943: 891, 4548280: 892, 4548362: 893, 4550184: 894, 4552348: 895, 4553703: 896, 4554684: 897, 4557648: 898, 4560804: 899, 4562935: 900, 4579145: 901, 4579432: 902, 4584207: 903, 4589890: 904, 4590129: 905, 4591157: 906, 4591713: 907, 4592741: 908, 4596742: 909, 4597913: 910, 4599235: 911, 4604644: 912, 4606251: 913, 4612504: 914, 4613696: 915, 6359193: 916, 6596364: 917, 6785654: 918, 6794110: 919, 6874185: 920, 7248320: 921, 7565083: 922, 7579787: 923, 7583066: 924, 7584110: 925, 7590611: 926, 7613480: 927, 7614500: 928, 7615774: 929, 7684084: 930, 7693725: 931, 7695742: 932, 7697313: 933, 7697537: 934, 7711569: 935, 7714571: 936, 7714990: 937, 7715103: 938, 7716358: 939, 7716906: 940, 7717410: 941, 7717556: 942, 7718472: 943, 7718747: 944, 7720875: 945, 7730033: 946, 7734744: 947, 7742313: 948, 7745940: 949, 7747607: 950, 7749582: 951, 7753113: 952, 7753275: 953, 7753592: 954, 7754684: 955, 7760859: 956, 7768694: 957, 7802026: 958, 7831146: 959, 7836838: 960, 7860988: 961, 7871810: 962, 7873807: 963, 7875152: 964, 7880968: 965, 7892512: 966, 7920052: 967, 7930864: 968, 7932039: 969, 9193705: 970, 9229709: 971, 9246464: 972, 9256479: 973, 9288635: 974, 9332890: 975, 9399592: 976, 9421951: 977, 9428293: 978, 9468604: 979, 9472597: 980, 9835506: 981, 10148035: 982, 10565667: 983, 11879895: 984, 11939491: 985, 12057211: 986, 12144580: 987, 12267677: 988, 12620546: 989, 12768682: 990, 12985857: 991, 12998815: 992, 13037406: 993, 13040303: 994, 13044778: 995, 13052670: 996, 13054560: 997, 13133613: 998, 15075141: 999} 217 | --------------------------------------------------------------------------------