python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Evaluation library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import flags from absl import logging from compare_gan import datasets from compare_gan import eval_utils from compare_gan import utils import gin import numpy as np from six.moves import range import tensorflow as tf import tensorflow_hub as hub FLAGS = flags.FLAGS # Special value returned when a fake image generated by a GAN has NaNs. NAN_DETECTED = 31337.0 @gin.configurable("eval_z", blacklist=["shape", "name"]) def z_generator(shape, distribution_fn=tf.random.uniform, minval=-1.0, maxval=1.0, stddev=1.0, name=None): """Random noise distributions as TF op. Args: shape: A 1-D integer Tensor or Python array. distribution_fn: Function that create a Tensor. If the function has any of the arguments 'minval', 'maxval' or 'stddev' these are passed to it. minval: The lower bound on the range of random values to generate. maxval: The upper bound on the range of random values to generate. stddev: The standard deviation of a normal distribution. name: A name for the operation. Returns: Tensor with the given shape and dtype tf.float32. """ return utils.call_with_accepted_args( distribution_fn, shape=shape, minval=minval, maxval=maxval, stddev=stddev, name=name) def _update_bn_accumulators(sess, generated, num_accu_examples): """Returns True if the accumlators for batch norm were updated. Args: sess: `tf.Session` object. Checkpoint should already be loaded. generated: Output tensor of the generator. num_accu_examples: How many examples should be used to update accumulators. Returns: True if there were accumlators. """ # Create update ops for batch statistic updates for each batch normalization # with accumlators. update_accu_switches = [v for v in tf.global_variables() if "accu/update_accus" in v.name] logging.info("update_accu_switches: %s", update_accu_switches) if not update_accu_switches: return False sess.run([tf.assign(v, 1) for v in update_accu_switches]) batch_size = generated.shape[0].value num_batches = num_accu_examples // batch_size for i in range(num_batches): if i % 500 == 0: logging.info("Updating BN accumulators %d/%d steps.", i, num_batches) sess.run(generated) sess.run([tf.assign(v, 0) for v in update_accu_switches]) logging.info("Done updating BN accumulators.") return True def evaluate_tfhub_module(module_spec, eval_tasks, use_tpu, num_averaging_runs): """Evaluate model at given checkpoint_path. Args: module_spec: string, path to a TF hub module. eval_tasks: List of objects that inherit from EvalTask. use_tpu: Whether to use TPUs. num_averaging_runs: Determines how many times each metric is computed. Returns: Dict[Text, float] with all the computed results. Raises: NanFoundError: If generator output has any NaNs. """ # Make sure that the same latent variables are used for each evaluation. np.random.seed(42) dataset = datasets.get_dataset() num_test_examples = dataset.eval_test_samples batch_size = 64 num_batches = int(np.ceil(num_test_examples / batch_size)) # Load and update the generator. result_dict = {} fake_dsets = [] with tf.Graph().as_default(): tf.set_random_seed(42) with tf.Session() as sess: if use_tpu: sess.run(tf.contrib.tpu.initialize_system()) def sample_from_generator(): """Create graph for sampling images.""" generator = hub.Module( module_spec, name="gen_module", tags={"gen", "bs{}".format(batch_size)}) logging.info("Generator inputs: %s", generator.get_input_info_dict()) z_dim = generator.get_input_info_dict()["z"].get_shape()[1].value z = z_generator(shape=[batch_size, z_dim]) if "labels" in generator.get_input_info_dict(): # Conditional GAN. assert dataset.num_classes labels = tf.random.uniform( [batch_size], maxval=dataset.num_classes, dtype=tf.int32) inputs = dict(z=z, labels=labels) else: # Unconditional GAN. assert "labels" not in generator.get_input_info_dict() inputs = dict(z=z) return generator(inputs=inputs, as_dict=True)["generated"] if use_tpu: generated = tf.contrib.tpu.rewrite(sample_from_generator) else: generated = sample_from_generator() tf.global_variables_initializer().run() if _update_bn_accumulators(sess, generated, num_accu_examples=204800): saver = tf.train.Saver() save_path = os.path.join(module_spec, "model-with-accu.ckpt") checkpoint_path = saver.save( sess, save_path=save_path) logging.info("Exported generator with accumulated batch stats to " "%s.", checkpoint_path) if not eval_tasks: logging.error("Task list is empty, returning.") return for i in range(num_averaging_runs): logging.info("Generating fake data set %d/%d.", i+1, num_averaging_runs) fake_dset = eval_utils.EvalDataSample( eval_utils.sample_fake_dataset(sess, generated, num_batches)) fake_dsets.append(fake_dset) logging.info("Computing inception features for generated data %d/%d.", i+1, num_averaging_runs) activations, logits = eval_utils.inception_transform_np( fake_dset.images, batch_size) fake_dset.set_inception_features( activations=activations, logits=logits) fake_dset.set_num_examples(num_test_examples) if i != 0: # Free up some memory by releasing additional fake data samples. # For ImageNet128 50k images are ~9 GiB. This will blow up metrics # (such as fractal dimension) if num_averaging_runs > 1. fake_dset.discard_images() real_dset = eval_utils.EvalDataSample( eval_utils.get_real_images( dataset=dataset, num_examples=num_test_examples)) logging.info("Getting Inception features for real images.") real_dset.activations, _ = eval_utils.inception_transform_np( real_dset.images, batch_size) real_dset.set_num_examples(num_test_examples) # Run all the tasks and update the result dictionary with the task statistics. result_dict = {} for task in eval_tasks: task_results_dicts = [ task.run_after_session(fake_dset, real_dset) for fake_dset in fake_dsets ] # Average the score for each key. result_statistics = {} for key in task_results_dicts[0].keys(): scores_for_key = np.array([d[key] for d in task_results_dicts]) mean, std = np.mean(scores_for_key), np.std(scores_for_key) scores_as_string = "_".join([str(x) for x in scores_for_key]) result_statistics[key + "_mean"] = mean result_statistics[key + "_std"] = std result_statistics[key + "_list"] = scores_as_string logging.info("Computed results for task %s: %s", task, result_statistics) result_dict.update(result_statistics) return result_dict
compare_gan-master
compare_gan/eval_gan_lib.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Binary to train and evaluate one GAN configuration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os # pylint: disable=unused-import from absl import app from absl import flags from absl import logging from compare_gan import datasets from compare_gan import runner_lib # Import GAN types so that they can be used in Gin configs without module names. from compare_gan.gans.modular_gan import ModularGAN from compare_gan.gans.s3gan import S3GAN from compare_gan.gans.ssgan import SSGAN # Required import to configure core TF classes and functions. import gin import gin.tf.external_configurables import tensorflow as tf FLAGS = flags.FLAGS flags.DEFINE_string("model_dir", None, "Where to store files.") flags.DEFINE_string( "schedule", "train", "Schedule to run. Options: train, continuous_eval.") flags.DEFINE_multi_string( "gin_config", [], "List of paths to the config files.") flags.DEFINE_multi_string( "gin_bindings", [], "Newline separated list of Gin parameter bindings.") flags.DEFINE_string( "score_filename", "scores.csv", "Name of the CSV file with evaluation results model_dir.") flags.DEFINE_integer( "num_eval_averaging_runs", 3, "How many times to average FID and IS") flags.DEFINE_integer( "eval_every_steps", 5000, "Evaluate only checkpoints whose step is divisible by this integer") flags.DEFINE_bool("use_tpu", None, "Whether running on TPU or not.") def _get_cluster(): if not FLAGS.use_tpu: # pylint: disable=unreachable return None if "TPU_NAME" not in os.environ: raise ValueError("Could not find a TPU. Set TPU_NAME.") return tf.contrib.cluster_resolver.TPUClusterResolver( tpu=os.environ["TPU_NAME"], zone=os.environ.get("TPU_ZONE", None)) @gin.configurable("run_config") def _get_run_config(tf_random_seed=None, single_core=False, iterations_per_loop=1000, save_checkpoints_steps=5000, keep_checkpoint_max=1000): """Return `RunConfig` for TPUs.""" tpu_config = tf.contrib.tpu.TPUConfig( num_shards=1 if single_core else None, # None = all cores. iterations_per_loop=iterations_per_loop) return tf.contrib.tpu.RunConfig( model_dir=FLAGS.model_dir, tf_random_seed=tf_random_seed, save_checkpoints_steps=save_checkpoints_steps, keep_checkpoint_max=keep_checkpoint_max, cluster=_get_cluster(), tpu_config=tpu_config) def _get_task_manager(): """Returns a TaskManager for this experiment.""" score_file = os.path.join(FLAGS.model_dir, FLAGS.score_filename) return runner_lib.TaskManagerWithCsvResults( model_dir=FLAGS.model_dir, score_file=score_file) def main(unused_argv): logging.info("Gin config: %s\nGin bindings: %s", FLAGS.gin_config, FLAGS.gin_bindings) gin.parse_config_files_and_bindings(FLAGS.gin_config, FLAGS.gin_bindings) if FLAGS.use_tpu is None: FLAGS.use_tpu = bool(os.environ.get("TPU_NAME", "")) if FLAGS.use_tpu: logging.info("Found TPU %s.", os.environ["TPU_NAME"]) run_config = _get_run_config() task_manager = _get_task_manager() options = runner_lib.get_options_dict() runner_lib.run_with_schedule( schedule=FLAGS.schedule, run_config=run_config, task_manager=task_manager, options=options, use_tpu=FLAGS.use_tpu, num_eval_averaging_runs=FLAGS.num_eval_averaging_runs, eval_every_steps=FLAGS.eval_every_steps) logging.info("I\"m done with my work, ciao!") if __name__ == "__main__": flags.mark_flag_as_required("model_dir") app.run(main)
compare_gan-master
compare_gan/main.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data-related utility functions. Includes: - A helper class to hold images and Inception features for evaluation. - A method to load a dataset as NumPy array. - Sample from the generator and return the data as a NumPy array. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging import numpy as np from six.moves import range import tensorflow as tf import tensorflow_gan as tfgan # Special value returned when fake image generated by GAN has nans. NAN_DETECTED = 31337.0 INCEPTION_URL = "http://download.tensorflow.org/models/frozen_inception_v1_2015_12_05.tar.gz" INCEPTION_FROZEN_GRAPH = "inceptionv1_for_inception_score.pb" def get_inception_graph_def(): return tfgan.eval.get_graph_def_from_url_tarball( # pylint: disable=unreachable url=INCEPTION_URL, filename=INCEPTION_FROZEN_GRAPH, tar_filename=os.path.basename(INCEPTION_URL)) class NanFoundError(Exception): """Exception thrown, when the Nans are present in the output.""" class EvalDataSample(object): """Helper class to hold images and Inception features for evaluation. All properties are tensors. Images are in [0, 255]. """ def __init__(self, images): self.images = images self.activations = None self.logits = None def discard_images(self): logging.info("Deleting references to images: %s", self.images.shape) del self.images def set_inception_features(self, activations, logits): self.activations = activations self.logits = logits def set_num_examples(self, num_examples): if self.images is not None: assert self.images.shape[0] >= num_examples self.images = self.images[:num_examples] if self.activations is not None: assert self.activations.shape[0] >= num_examples self.activations = self.activations[:num_examples] if self.logits is not None: assert self.logits.shape[0] >= num_examples self.logits = self.logits[:num_examples] def get_real_images(dataset, num_examples, split=None, failure_on_insufficient_examples=True): """Get num_examples images from the given dataset/split. Args: dataset: `ImageDataset` object. num_examples: Number of images to read. split: Split of the dataset to use. If None will use the default split for eval defined by the dataset. failure_on_insufficient_examples: If True raise an exception if the dataset/split does not images. Otherwise will log to error and return fewer images. Returns: 4-D NumPy array with images with values in [0, 256]. Raises: ValueError: If the dataset/split does not of the number of requested number requested images and `failure_on_insufficient_examples` is True. """ logging.info("Start loading real data.") with tf.Graph().as_default(): ds = dataset.eval_input_fn(split=split) # Get real images from the dataset. In the case of a 1-channel # dataset (like MNIST) convert it to 3 channels. next_batch = ds.make_one_shot_iterator().get_next()[0] shape = [num_examples] + next_batch.shape.as_list() is_single_channel = shape[-1] == 1 if is_single_channel: shape[-1] = 3 real_images = np.empty(shape, dtype=np.float32) with tf.Session() as sess: for i in range(num_examples): try: b = sess.run(next_batch) b *= 255.0 if is_single_channel: b = np.tile(b, [1, 1, 3]) real_images[i] = b except tf.errors.OutOfRangeError: logging.error("Reached the end of dataset. Read: %d samples.", i) break if real_images.shape[0] != num_examples: if failure_on_insufficient_examples: raise ValueError("Not enough examples in the dataset %s: %d / %d" % (dataset, real_images.shape[0], num_examples)) else: logging.error("Not enough examples in the dataset %s: %d / %d", dataset, real_images.shape[0], num_examples) logging.info("Done loading real data.") return real_images def sample_fake_dataset(sess, generator, num_batches): """Returns a generated data set as a NumPy array.""" logging.info("Generating a fake data set.") samples = [] for _ in range(num_batches): x = sess.run(generator) # If NaNs were generated, ignore this checkpoint and assign a very high # FID score which we handle specially later. if np.isnan(x).any(): logging.error("Detected NaN in fake_images! Returning NaN.") raise NanFoundError("Detected NaN in fake images.") samples.append(x) fake_images = np.concatenate(samples, axis=0) fake_images *= 255.0 # Convert 1-channel datasets (like MNIST) to 3 channels. if fake_images.shape[3] == 1: fake_images = np.tile(fake_images, [1, 1, 1, 3]) logging.info("Done sampling a generated data set.") return fake_images def inception_transform(inputs): with tf.control_dependencies([ tf.assert_greater_equal(inputs, 0.0), tf.assert_less_equal(inputs, 255.0)]): inputs = tf.identity(inputs) preprocessed_inputs = tf.map_fn( fn=tfgan.eval.preprocess_image, elems=inputs, back_prop=False) return tfgan.eval.run_inception( preprocessed_inputs, graph_def=get_inception_graph_def(), output_tensor=["pool_3:0", "logits:0"]) def inception_transform_np(inputs, batch_size): """Computes the inception features and logits for a given NumPy array. The inputs are first preprocessed to match the input shape required for Inception. Args: inputs: NumPy array of shape [-1, H, W, 3]. batch_size: Batch size. Returns: A tuple of NumPy arrays with Inception features and logits for each input. """ with tf.Session(graph=tf.Graph()) as sess: inputs_placeholder = tf.placeholder( dtype=tf.float32, shape=[None] + list(inputs[0].shape)) features_and_logits = inception_transform(inputs_placeholder) features = [] logits = [] num_batches = int(np.ceil(inputs.shape[0] / batch_size)) for i in range(num_batches): input_batch = inputs[i * batch_size:(i + 1) * batch_size] x = sess.run( features_and_logits, feed_dict={inputs_placeholder: input_batch}) features.append(x[0]) logits.append(x[1]) features = np.vstack(features) logits = np.vstack(logits) return features, logits
compare_gan-master
compare_gan/eval_utils.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Image Similarity Metrics in TensorFlow. This file contains various image similarity metrics that can be used for monitoring how various models learn to reconstruct images or may be used directly as the final objective to be optimized. How to use these metrics: * MS-SSIM: For GANS, MS-SSIM can be used to detect mode collapse by looking at the similarity between samples and comparing it with the similarity inside the dataset. Often, this is done for class conditional models, where per class samples are being compared. In the unconditional setting, it can be done for datasets where the data has the same modality ( for example, CelebA). For more information, see the following papers: * https://arxiv.org/abs/1610.09585 * https://arxiv.org/abs/1706.04987 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import range from six.moves import zip import tensorflow as tf def verify_compatible_shapes(img1, img2): """Checks if two image tensors are compatible for metric computation. This function checks if two sets of images have ranks at least 3, and if the last three dimensions match. Args: img1: The first images tensor. img2: The second images tensor. Returns: A tuple of the first tensor shape, the second tensor shape, and a list of tf.Assert() implementing the checks. Raises: ValueError: when static shape check fails. """ shape1 = img1.get_shape().with_rank_at_least(3) shape2 = img2.get_shape().with_rank_at_least(3) shape1[-3:].assert_is_compatible_with(shape2[-3:]) if shape1.ndims is not None and shape2.ndims is not None: for dim1, dim2 in zip(reversed(shape1[:-3]), reversed(shape2[:-3])): if not (dim1 == 1 or dim2 == 1 or dim1.is_compatible_with(dim2)): raise ValueError( 'Two images are not compatible: %s and %s' % (shape1, shape2)) # Now assign shape tensors. shape1, shape2 = tf.shape_n([img1, img2]) checks = [] checks.append(tf.Assert(tf.greater_equal(tf.size(shape1), 3), [shape1, shape2], summarize=10)) checks.append(tf.Assert(tf.reduce_all(tf.equal(shape1[-3:], shape2[-3:])), [shape1, shape2], summarize=10)) return shape1, shape2, checks _SSIM_K1 = 0.01 _SSIM_K2 = 0.03 def _ssim_helper(x, y, reducer, max_val, compensation=1.0): r"""Helper function to SSIM. SSIM estimates covariances with weighted sums, e.g., normalized Gaussian blur. Like the unbiased covariance estimator has normalization factor of n-1 instead of n, naive covariance estimations with weighted sums are biased estimators. Suppose `reducer` is a weighted sum, then the mean estimators are mu_x = \sum_i w_i x_i, mu_y = \sum_i w_i y_i, where w_i's are the weighted-sum weights, and covariance estimator is cov_xy = \sum_i w_i (x_i - mu_x) (y_i - mu_y) with assumption \sum_i w_i = 1. This covariance estimator is biased, since E cov_xy = (1 - \sum_i w_i ** 2) Cov(X, Y). For SSIM measure with unbiased covariance estimators, pass as `compensation` argument (1 - \sum_i w_i ** 2). Arguments: x: first set of images. y: first set of images. reducer: Function that computes 'local' averages from set of images. For non-covolutional version, this is usually tf.reduce_mean(x, [1, 2]), and for convolutional version, this is usually tf.nn.avg_pool or tf.nn.conv2d with weighted-sum kernel. max_val: The dynamic range (i.e., the difference between the maximum possible allowed value and the minimum allowed value). compensation: Compensation factor. See above. Returns: A pair containing the luminance measure and the contrast-structure measure. """ c1 = (_SSIM_K1 * max_val) ** 2 c2 = (_SSIM_K2 * max_val) ** 2 # SSIM luminance measure is # (2 * mu_x * mu_y + c1) / (mu_x ** 2 + mu_y ** 2 + c1). mean0 = reducer(x) mean1 = reducer(y) num0 = mean0 * mean1 * 2.0 den0 = tf.square(mean0) + tf.square(mean1) luminance = (num0 + c1) / (den0 + c1) # SSIM contrast-structure measure is # (2 * cov_xy + c2) / (cov_xx + cov_yy + c2). # Note that `reducer` is a weighted sum with weight w_k, \sum_i w_i = 1, then # cov_xy = \sum_i w_i (x_i - mu_x) (y_i - mu_y) # = \sum_i w_i x_i y_i - (\sum_i w_i x_i) (\sum_j w_j y_j). num1 = reducer(x * y) * 2.0 den1 = reducer(tf.square(x) + tf.square(y)) c2 *= compensation cs = (num1 - num0 + c2) / (den1 - den0 + c2) # SSIM score is the product of the luminance and contrast-structure measures. return luminance, cs def f_special_gauss(size, sigma): """Function to mimic the 'fspecial' gaussian MATLAB function.""" size = tf.convert_to_tensor(size, tf.int32) sigma = tf.convert_to_tensor(sigma) coords = tf.cast(tf.range(size), sigma.dtype) coords -= tf.cast(size - 1, sigma.dtype) / 2.0 g = tf.square(coords) g *= -0.5 / tf.square(sigma) g = tf.reshape(g, shape=[1, -1]) + tf.reshape(g, shape=[-1, 1]) g = tf.reshape(g, shape=[1, -1]) # For tf.nn.softmax(). g = tf.nn.softmax(g) return tf.reshape(g, shape=[size, size, 1, 1]) def _ssim_index_per_channel( img1, img2, filter_size, filter_width, max_val=255.0): """Computes SSIM index between img1 and img2 per color channel. This function matches the standard SSIM implementation found at: https://ece.uwaterloo.ca/~z70wang/research/ssim/ssim_index.m Details: - To reproduce a 11x11 Gaussian filter of width 1.5 is used. - k1 = 0.01, k2 = 0.03 as in the original paper. Args: img1: First RGB image batch. img2: Second RGB image batch. filter_size: An integer, the filter size of the Gaussian kernel used. filter_width: A float, the filter width of the Gaussian kernel used. max_val: the dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values). Returns: A pair of tensors containing batch-wise and channel-wise SSIM and contrast-structure measure. The shape is [..., channels]. """ filter_size = tf.constant(filter_size, dtype=tf.int32) filter_sigma = tf.constant(filter_width, dtype=img1.dtype) shape1, shape2 = tf.shape_n([img1, img2]) filter_size = tf.reduce_min( tf.concat([tf.expand_dims(filter_size, axis=0), shape1[-3:-1], shape2[-3:-1]], axis=0)) kernel = f_special_gauss(filter_size, filter_sigma) kernel = tf.tile(kernel, multiples=[1, 1, shape1[-1], 1]) # The correct compensation factor is `1.0 - tf.reduce_sum(tf.square(kernel))`, # but to match MATLAB implementation of MS-SSIM, we use 1.0 instead. compensation = 1.0 def reducer(x): # pylint: disable=invalid-name shape = tf.shape(x) x = tf.reshape(x, shape=tf.concat([[-1], shape[-3:]], 0)) y = tf.nn.depthwise_conv2d(x, kernel, strides=[1] * 4, padding='VALID') return tf.reshape(y, tf.concat([shape[:-3], tf.shape(y)[1:]], 0)) luminance, cs = _ssim_helper(img1, img2, reducer, max_val, compensation) # Average over the second and the third from the last: height, width. axes = tf.constant([-3, -2], dtype=tf.int32) ssim = tf.reduce_mean(luminance * cs, axes) cs = tf.reduce_mean(cs, axes) return ssim, cs # This must be a tuple (not a list) because tuples are immutable and we don't # want these to accidentally change. _MSSSIM_WEIGHTS = (.0448, 0.2856, 0.3001, 0.2363, 0.1333) def multiscale_ssim( img1, img2, filter_size=11, filter_width=1.5, max_val=255.0): """Computes MS-SSIM with power factors from Wang paper.""" return _multiscale_ssim_helper(img1, img2, filter_size=filter_size, filter_width=filter_width, max_val=max_val, power_factors=_MSSSIM_WEIGHTS) def multiscale_ssim_unweighted( img1, img2, filter_size=11, filter_width=1.5, max_val=255.0): """Computes unweighted MS-SSIM with power factors from Zhao paper.""" return _multiscale_ssim_helper(img1, img2, filter_size=filter_size, filter_width=filter_width, max_val=max_val, power_factors=[1, 1, 1, 1, 1]) def _multiscale_ssim_helper( img1, img2, filter_size, filter_width, power_factors, max_val=255.0): """Computes the MS-SSIM between img1 and img2. This function assumes that `img1` and `img2` are image batches, i.e. the last three dimensions are [row, col, channels]. Arguments: img1: First RGB image batch. img2: Second RGB image batch. Must have the same rank as img1. filter_size: An integer, the filter size of the Gaussian kernel used. filter_width: A float, the filter width of the Gaussian kernel used. power_factors: iterable of weightings for each of the scales. The number of scales used is the length of the list. Index 0 is the unscaled resolution's weighting and each increasing scale corresponds to the image being downsampled by 2. max_val: the dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values). Returns: A tensor containing batch-wise MS-SSIM measure. MS-SSIM has range [0, 1]. The shape is broadcast(img1.shape[:-3], img2.shape[:-3]). """ # Shape checking. shape1 = img1.get_shape().with_rank_at_least(3) shape2 = img2.get_shape().with_rank_at_least(3) shape1[-3:].merge_with(shape2[-3:]) with tf.name_scope(None, 'MS-SSIM', [img1, img2]): shape1, shape2, checks = verify_compatible_shapes(img1, img2) with tf.control_dependencies(checks): img1 = tf.identity(img1) imgs = [img1, img2] shapes = [shape1, shape2] # img1 and img2 are assumed to be a (multi-dimensional) batch of # 3-dimensional images (height, width, channels). `heads` contain the batch # dimensions, and `tails` contain the image dimensions. heads = [s[:-3] for s in shapes] tails = [s[-3:] for s in shapes] divisor = [1, 2, 2, 1] divisor_tensor = tf.constant(divisor[1:], dtype=tf.int32) def do_pad(images, remainder): # pylint: disable=invalid-name padding = tf.expand_dims(remainder, -1) padding = tf.pad(padding, [[1, 0], [1, 0]]) return [tf.pad(x, padding, mode='SYMMETRIC') for x in images] mcs = [] for k in range(len(power_factors)): with tf.name_scope(None, 'Scale%d' % k, imgs): if k > 0: # Avg pool takes rank 4 tensors. Flatten leading dimensions. flat_imgs = [ tf.reshape(x, tf.concat([[-1], t], 0)) for x, t in zip(imgs, tails) ] remainder = tails[0] % divisor_tensor need_padding = tf.reduce_any(tf.not_equal(remainder, 0)) # pylint: disable=cell-var-from-loop padded = tf.cond(need_padding, lambda: do_pad(flat_imgs, remainder), lambda: flat_imgs) # pylint: enable=cell-var-from-loop downscaled = [ tf.nn.avg_pool( x, ksize=divisor, strides=divisor, padding='VALID') for x in padded ] tails = [x[1:] for x in tf.shape_n(downscaled)] imgs = [ tf.reshape(x, tf.concat([h, t], 0)) for x, h, t in zip(downscaled, heads, tails) ] # Overwrite previous ssim value since we only need the last one. ssim, cs = _ssim_index_per_channel( *imgs, filter_size=filter_size, filter_width=filter_width, max_val=max_val) mcs.append(tf.nn.relu(cs)) # Remove the cs score for the last scale. In the MS-SSIM calculation, # we use the l(p) at the highest scale. l(p) * cs(p) is ssim(p). mcs.pop() # Remove the cs score for the last scale. mcs_and_ssim = tf.stack(mcs + [tf.nn.relu(ssim)], axis=-1) # Take weighted geometric mean across the scale axis. ms_ssim = tf.reduce_prod(tf.pow(mcs_and_ssim, power_factors), [-1]) ms_ssim = tf.reduce_mean(ms_ssim, [-1]) # Average over color channels. return ms_ssim
compare_gan-master
compare_gan/metrics/image_similarity.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the FID score.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.metrics import fid_score as fid_score_lib import numpy as np import tensorflow as tf class FIDScoreTest(tf.test.TestCase): def test_fid_computation(self): real_data = np.ones((100, 2)) real_data[:50, 0] = 2 gen_data = np.ones((100, 2)) * 9 gen_data[50:, 0] = 2 # mean(real_data) = [1.5, 1] # Cov(real_data) = [[ 0.2525, 0], [0, 0]] # mean(gen_data) = [5.5, 9] # Cov(gen_data) = [[12.37, 0], [0, 0]] result = fid_score_lib.compute_fid_from_activations(real_data, gen_data) self.assertNear(result, 89.091, 1e-4) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/metrics/fid_score_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Precision and recall computation based on samples from two distributions. Given a sample from the true and the fake distribution embedded in some feature space (say, Inception), it computes the precision and recall via the algorithm presented in "Assessing Generative Models via Precision and Recall", Sajjadi et al. [https://arxiv.org/abs/1806.00035]. Finally, one can plot the resulting curves for different models. Typical usage example: import prd prd_data_1 = prd.compute_prd_from_embedding(eval_feats_1, ref_feats_1) prd_data_2 = prd.compute_prd_from_embedding(eval_feats_2, ref_feats_2) prd.plot([prd_data_1, prd_data_2], ['GAN_1', 'GAN_2']) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from matplotlib import pyplot as plt import numpy as np import sklearn.cluster def compute_prd(eval_dist, ref_dist, num_angles=1001, epsilon=1e-10): """Computes the PRD curve for discrete distributions. This function computes the PRD curve for the discrete distribution eval_dist with respect to the reference distribution ref_dist. This implements the algorithm in [arxiv.org/abs/1806.2281349]. The PRD will be computed for an equiangular grid of num_angles values between [0, pi/2]. Args: eval_dist: 1D NumPy array or list of floats with the probabilities of the different states under the distribution to be evaluated. ref_dist: 1D NumPy array or list of floats with the probabilities of the different states under the reference distribution. num_angles: Number of angles for which to compute PRD. Must be in [3, 1e6]. The default value is 1001. epsilon: Angle for PRD computation in the edge cases 0 and pi/2. The PRD will be computes for epsilon and pi/2-epsilon, respectively. The default value is 1e-10. Returns: precision: NumPy array of shape [num_angles] with the precision for the different ratios. recall: NumPy array of shape [num_angles] with the recall for the different ratios. Raises: ValueError: If not 0 < epsilon <= 0.1. ValueError: If num_angles < 3. """ if not (epsilon > 0 and epsilon < 0.1): raise ValueError('epsilon must be in (0, 0.1] but is %s.' % str(epsilon)) if not (num_angles >= 3 and num_angles <= 1e6): raise ValueError('num_angles must be in [3, 1e6] but is %d.' % num_angles) # Compute slopes for linearly spaced angles between [0, pi/2] angles = np.linspace(epsilon, np.pi/2 - epsilon, num=num_angles) slopes = np.tan(angles) # Broadcast slopes so that second dimension will be states of the distribution slopes_2d = np.expand_dims(slopes, 1) # Broadcast distributions so that first dimension represents the angles ref_dist_2d = np.expand_dims(ref_dist, 0) eval_dist_2d = np.expand_dims(eval_dist, 0) # Compute precision and recall for all angles in one step via broadcasting precision = np.minimum(ref_dist_2d*slopes_2d, eval_dist_2d).sum(axis=1) recall = precision / slopes return precision, recall def _cluster_into_bins(eval_data, ref_data, num_clusters): """Clusters the union of the data points and returns the cluster distribution. Clusters the union of eval_data and ref_data into num_clusters using minibatch k-means. Then, for each cluster, it computes the number of points from eval_data and ref_data. Args: eval_data: NumPy array of data points from the distribution to be evaluated. ref_data: NumPy array of data points from the reference distribution. num_clusters: Number of cluster centers to fit. Returns: Two NumPy arrays, each of size num_clusters, where i-th entry represents the number of points assigned to the i-th cluster. """ cluster_data = np.vstack([eval_data, ref_data]) kmeans = sklearn.cluster.MiniBatchKMeans(n_clusters=num_clusters, n_init=10) labels = kmeans.fit(cluster_data).labels_ eval_labels = labels[:len(eval_data)] ref_labels = labels[len(eval_data):] eval_bins = np.histogram(eval_labels, bins=num_clusters, range=[0, num_clusters], density=True)[0] ref_bins = np.histogram(ref_labels, bins=num_clusters, range=[0, num_clusters], density=True)[0] return eval_bins, ref_bins def compute_prd_from_embedding(eval_data, ref_data, num_clusters=20, num_angles=1001, num_runs=10, enforce_balance=True): """Computes PRD data from sample embeddings. The points from both distributions are mixed and then clustered. This leads to a pair of histograms of discrete distributions over the cluster centers on which the PRD algorithm is executed. The number of points in eval_data and ref_data must be equal since unbalanced distributions bias the clustering towards the larger dataset. The check can be disabled by setting the enforce_balance flag to False (not recommended). Args: eval_data: NumPy array of data points from the distribution to be evaluated. ref_data: NumPy array of data points from the reference distribution. num_clusters: Number of cluster centers to fit. The default value is 20. num_angles: Number of angles for which to compute PRD. Must be in [3, 1e6]. The default value is 1001. num_runs: Number of independent runs over which to average the PRD data. enforce_balance: If enabled, throws exception if eval_data and ref_data do not have the same length. The default value is True. Returns: precision: NumPy array of shape [num_angles] with the precision for the different ratios. recall: NumPy array of shape [num_angles] with the recall for the different ratios. Raises: ValueError: If len(eval_data) != len(ref_data) and enforce_balance is set to True. """ if enforce_balance and len(eval_data) != len(ref_data): raise ValueError( 'The number of points in eval_data %d is not equal to the number of ' 'points in ref_data %d. To disable this exception, set enforce_balance ' 'to False (not recommended).' % (len(eval_data), len(ref_data))) eval_data = np.array(eval_data, dtype=np.float64) ref_data = np.array(ref_data, dtype=np.float64) precisions = [] recalls = [] for _ in range(num_runs): eval_dist, ref_dist = _cluster_into_bins(eval_data, ref_data, num_clusters) precision, recall = compute_prd(eval_dist, ref_dist, num_angles) precisions.append(precision) recalls.append(recall) precision = np.mean(precisions, axis=0) recall = np.mean(recalls, axis=0) return precision, recall def _prd_to_f_beta(precision, recall, beta=1, epsilon=1e-10): """Computes F_beta scores for the given precision/recall values. The F_beta scores for all precision/recall pairs will be computed and returned. For precision p and recall r, the F_beta score is defined as: F_beta = (1 + beta^2) * (p * r) / ((beta^2 * p) + r) Args: precision: 1D NumPy array of precision values in [0, 1]. recall: 1D NumPy array of precision values in [0, 1]. beta: Beta parameter. Must be positive. The default value is 1. epsilon: Small constant to avoid numerical instability caused by division by 0 when precision and recall are close to zero. Returns: NumPy array of same shape as precision and recall with the F_beta scores for each pair of precision/recall. Raises: ValueError: If any value in precision or recall is outside of [0, 1]. ValueError: If beta is not positive. """ if not ((precision >= 0).all() and (precision <= 1).all()): raise ValueError('All values in precision must be in [0, 1].') if not ((recall >= 0).all() and (recall <= 1).all()): raise ValueError('All values in recall must be in [0, 1].') if beta <= 0: raise ValueError('Given parameter beta %s must be positive.' % str(beta)) return (1 + beta**2) * (precision * recall) / ( (beta**2 * precision) + recall + epsilon) def prd_to_max_f_beta_pair(precision, recall, beta=8): """Computes max. F_beta and max. F_{1/beta} for precision/recall pairs. Computes the maximum F_beta and maximum F_{1/beta} score over all pairs of precision/recall values. This is useful to compress a PRD plot into a single pair of values which correlate with precision and recall. For precision p and recall r, the F_beta score is defined as: F_beta = (1 + beta^2) * (p * r) / ((beta^2 * p) + r) Args: precision: 1D NumPy array or list of precision values in [0, 1]. recall: 1D NumPy array or list of precision values in [0, 1]. beta: Beta parameter. Must be positive. The default value is 8. Returns: f_beta: Maximum F_beta score. f_beta_inv: Maximum F_{1/beta} score. Raises: ValueError: If beta is not positive. """ if not ((precision >= 0).all() and (precision <= 1).all()): raise ValueError('All values in precision must be in [0, 1].') if not ((recall >= 0).all() and (recall <= 1).all()): raise ValueError('All values in recall must be in [0, 1].') if beta <= 0: raise ValueError('Given parameter beta %s must be positive.' % str(beta)) f_beta = np.max(_prd_to_f_beta(precision, recall, beta)) f_beta_inv = np.max(_prd_to_f_beta(precision, recall, 1/beta)) return f_beta, f_beta_inv def plot(precision_recall_pairs, labels=None, out_path=None, legend_loc='lower left', dpi=150): """Plots precision recall curves for distributions. Creates the PRD plot for the given data and stores the plot in a given path. Args: precision_recall_pairs: List of prd_data to plot. Each item in this list is a 2D array of precision and recall values for the same number of ratios. labels: Optional list of labels of same length as list_of_prd_data. The default value is None. out_path: Output path for the resulting plot. If None, the plot will be opened via plt.show(). The default value is None. legend_loc: Location of the legend. The default value is 'lower left'. dpi: Dots per inch (DPI) for the figure. The default value is 150. Raises: ValueError: If labels is a list of different length than list_of_prd_data. """ if labels is not None and len(labels) != len(precision_recall_pairs): raise ValueError( 'Length of labels %d must be identical to length of ' 'precision_recall_pairs %d.' % (len(labels), len(precision_recall_pairs))) fig = plt.figure(figsize=(3.5, 3.5), dpi=dpi) plot_handle = fig.add_subplot(111) plot_handle.tick_params(axis='both', which='major', labelsize=12) for i in range(len(precision_recall_pairs)): precision, recall = precision_recall_pairs[i] label = labels[i] if labels is not None else None plt.plot(recall, precision, label=label, alpha=0.5, linewidth=3) if labels is not None: plt.legend(loc=legend_loc) plt.xlim([0, 1]) plt.ylim([0, 1]) plt.xlabel('Recall', fontsize=12) plt.ylabel('Precision', fontsize=12) plt.tight_layout() if out_path is None: plt.show() else: plt.savefig(out_path, bbox_inches='tight', dpi=dpi) plt.close()
compare_gan-master
compare_gan/metrics/prd_score.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Testing precision and recall computation on synthetic data.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest from compare_gan.metrics import prd_score as prd import numpy as np class PRDTest(unittest.TestCase): def test_compute_prd_no_overlap(self): eval_dist = [0, 1] ref_dist = [1, 0] result = np.ravel(prd.compute_prd(eval_dist, ref_dist)) np.testing.assert_almost_equal(result, 0) def test_compute_prd_perfect_overlap(self): eval_dist = [1, 0] ref_dist = [1, 0] result = prd.compute_prd(eval_dist, ref_dist, num_angles=11) np.testing.assert_almost_equal([result[0][5], result[1][5]], [1, 1]) def test_compute_prd_low_precision_high_recall(self): eval_dist = [0.5, 0.5] ref_dist = [1, 0] result = prd.compute_prd(eval_dist, ref_dist, num_angles=11) np.testing.assert_almost_equal(result[0][5], 0.5) np.testing.assert_almost_equal(result[1][5], 0.5) np.testing.assert_almost_equal(result[0][10], 0.5) np.testing.assert_almost_equal(result[1][1], 1) def test_compute_prd_high_precision_low_recall(self): eval_dist = [1, 0] ref_dist = [0.5, 0.5] result = prd.compute_prd(eval_dist, ref_dist, num_angles=11) np.testing.assert_almost_equal([result[0][5], result[1][5]], [0.5, 0.5]) np.testing.assert_almost_equal(result[1][1], 0.5) np.testing.assert_almost_equal(result[0][10], 1) def test_compute_prd_bad_epsilon(self): with self.assertRaises(ValueError): prd.compute_prd([1], [1], epsilon=0) with self.assertRaises(ValueError): prd.compute_prd([1], [1], epsilon=1) with self.assertRaises(ValueError): prd.compute_prd([1], [1], epsilon=-1) def test_compute_prd_bad_num_angles(self): with self.assertRaises(ValueError): prd.compute_prd([1], [1], num_angles=0) with self.assertRaises(ValueError): prd.compute_prd([1], [1], num_angles=1) with self.assertRaises(ValueError): prd.compute_prd([1], [1], num_angles=-1) with self.assertRaises(ValueError): prd.compute_prd([1], [1], num_angles=1e6+1) with self.assertRaises(ValueError): prd.compute_prd([1], [1], num_angles=2.5) def test__cluster_into_bins(self): eval_data = np.zeros([5, 4]) ref_data = np.ones([5, 4]) result = prd._cluster_into_bins(eval_data, ref_data, 3) self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 3) self.assertEqual(len(result[1]), 3) np.testing.assert_almost_equal(sum(result[0]), 1) np.testing.assert_almost_equal(sum(result[1]), 1) def test_compute_prd_from_embedding_mismatch_num_samples_should_fail(self): # Mismatch in number of samples with enforce_balance set to True with self.assertRaises(ValueError): prd.compute_prd_from_embedding( np.array([[0], [0], [1]]), np.array([[0], [1]]), num_clusters=2, enforce_balance=True) def test_compute_prd_from_embedding_mismatch_num_samples_should_work(self): # Mismatch in number of samples with enforce_balance set to False try: prd.compute_prd_from_embedding( np.array([[0], [0], [1]]), np.array([[0], [1]]), num_clusters=2, enforce_balance=False) except ValueError: self.fail( 'compute_prd_from_embedding should not raise a ValueError when ' 'enforce_balance is set to False.') def test__prd_to_f_beta_correct_computation(self): precision = np.array([1, 1, 0, 0, 0.5, 1, 0.5]) recall = np.array([1, 0, 1, 0, 0.5, 0.5, 1]) expected = np.array([1, 0, 0, 0, 0.5, 2/3, 2/3]) with np.errstate(invalid='ignore'): result = prd._prd_to_f_beta(precision, recall, beta=1) np.testing.assert_almost_equal(result, expected) expected = np.array([1, 0, 0, 0, 0.5, 5/9, 5/6]) with np.errstate(invalid='ignore'): result = prd._prd_to_f_beta(precision, recall, beta=2) np.testing.assert_almost_equal(result, expected) expected = np.array([1, 0, 0, 0, 0.5, 5/6, 5/9]) with np.errstate(invalid='ignore'): result = prd._prd_to_f_beta(precision, recall, beta=1/2) np.testing.assert_almost_equal(result, expected) result = prd._prd_to_f_beta(np.array([]), np.array([]), beta=1) expected = np.array([]) np.testing.assert_almost_equal(result, expected) def test__prd_to_f_beta_bad_beta(self): with self.assertRaises(ValueError): prd._prd_to_f_beta(np.ones(1), np.ones(1), beta=0) with self.assertRaises(ValueError): prd._prd_to_f_beta(np.ones(1), np.ones(1), beta=-3) def test__prd_to_f_beta_bad_precision_or_recall(self): with self.assertRaises(ValueError): prd._prd_to_f_beta(-np.ones(1), np.ones(1), beta=1) with self.assertRaises(ValueError): prd._prd_to_f_beta(np.ones(1), -np.ones(1), beta=1) def test_plot_not_enough_labels(self): with self.assertRaises(ValueError): prd.plot(np.zeros([3, 2, 5]), labels=['1', '2']) def test_plot_too_many_labels(self): with self.assertRaises(ValueError): prd.plot(np.zeros([1, 2, 5]), labels=['1', '2', '3']) if __name__ == '__main__': unittest.main()
compare_gan-master
compare_gan/metrics/prd_score_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the fractal dimension metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.metrics import eval_task import numpy as np import scipy.spatial class FractalDimensionTask(eval_task.EvalTask): """Fractal dimension metric.""" _LABEL = "fractal_dimension" def run_after_session(self, options, eval_data_fake, eval_data_real=None): print(eval_data_fake) score = compute_fractal_dimension(eval_data_fake.images) return {self._LABEL: score} def compute_fractal_dimension(fake_images, num_fd_seeds=100, n_bins=1000, scale=0.1): """Compute Fractal Dimension of fake_images. Args: fake_images: an np array of datapoints, the dimensionality and scaling of images can be arbitrary num_fd_seeds: number of random centers from which fractal dimension computation is performed n_bins: number of bins to split the range of distance values into scale: the scale of the y interval in the log-log plot for which we apply a linear regression fit Returns: fractal dimension of the dataset. """ assert len(fake_images.shape) >= 2 assert fake_images.shape[0] >= num_fd_seeds num_images = fake_images.shape[0] # In order to apply scipy function we need to flatten the number of dimensions # to 2 fake_images = np.reshape(fake_images, (num_images, -1)) fake_images_subset = fake_images[np.random.randint( num_images, size=num_fd_seeds)] distances = scipy.spatial.distance.cdist(fake_images, fake_images_subset).flatten() min_distance = np.min(distances[np.nonzero(distances)]) max_distance = np.max(distances) buckets = min_distance * ( (max_distance / min_distance)**np.linspace(0, 1, n_bins)) # Create a table where first column corresponds to distances r # and second column corresponds to number of points N(r) that lie # within distance r from the random seeds fd_result = np.zeros((n_bins - 1, 2)) fd_result[:, 0] = buckets[1:] fd_result[:, 1] = np.sum(np.less.outer(distances, buckets[1:]), axis=0) # We compute the slope of the log-log plot at the middle y value # which is stored in y_val; the linear regression fit is computed on # the part of the plot that corresponds to an interval around y_val # whose size is 2*scale*(total width of the y axis) max_y = np.log(num_images * num_fd_seeds) min_y = np.log(num_fd_seeds) x = np.log(fd_result[:, 0]) y = np.log(fd_result[:, 1]) y_width = max_y - min_y y_val = min_y + 0.5 * y_width start = np.argmax(y > y_val - scale * y_width) end = np.argmax(y > y_val + scale * y_width) slope = np.linalg.lstsq( a=np.vstack([x[start:end], np.ones(end - start)]).transpose(), b=y[start:end].reshape(end - start, 1))[0][0][0] return slope
compare_gan-master
compare_gan/metrics/fractal_dimension.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8
compare_gan-master
compare_gan/metrics/__init__.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the MS-SSIM metric. The details on the application of this metric to GANs can be found in Section 5.3 of "Many Paths to Equilibrium: GANs Do Not Need to Decrease a Divergence At Every Step", Fedus*, Rosca* et al. [https://arxiv.org/abs/1710.08446]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan.metrics import eval_task from compare_gan.metrics import image_similarity import numpy as np from six.moves import range import tensorflow as tf class MultiscaleSSIMTask(eval_task.EvalTask): """Task that computes MSSIMScore for generated images.""" _LABEL = "ms_ssim" def run_after_session(self, options, eval_data_fake, eval_data_real=None): del options, eval_data_real score = _compute_multiscale_ssim_score(eval_data_fake.images) return {self._LABEL: score} def _compute_multiscale_ssim_score(fake_images): """Compute ms-ssim score .""" batch_size = 64 with tf.Graph().as_default(): fake_images_batch = tf.train.shuffle_batch( [tf.convert_to_tensor(fake_images, dtype=tf.float32)], capacity=16*batch_size, min_after_dequeue=8*batch_size, num_threads=4, enqueue_many=True, batch_size=batch_size) # Following section 5.3 of https://arxiv.org/pdf/1710.08446.pdf, we only # evaluate 5 batches of the generated images. eval_fn = compute_msssim( generated_images=fake_images_batch, num_batches=5) with tf.train.MonitoredTrainingSession() as sess: score = eval_fn(sess) return score def compute_msssim(generated_images, num_batches): """Get a fn returning the ms ssim score for generated images. Args: generated_images: TF Tensor of shape [batch_size, dim, dim, 3] which evaluates to a batch of generated images. Should be in range [0..255]. num_batches: Number of batches to consider. Returns: eval_fn: a function which takes a session as an argument and returns the average ms ssim score among all the possible image pairs from generated_images. """ batch_size = int(generated_images.get_shape()[0]) assert batch_size > 1 # Generate all possible image pairs from input set of imgs. pair1 = tf.tile(generated_images, [batch_size, 1, 1, 1]) pair2 = tf.reshape( tf.tile(generated_images, [1, batch_size, 1, 1]), [ batch_size * batch_size, generated_images.shape[1], generated_images.shape[2], generated_images.shape[3] ]) # Compute the mean of the scores (but ignore the 'identical' images - which # should get 1.0 from the MultiscaleSSIM) score = tf.reduce_sum(image_similarity.multiscale_ssim(pair1, pair2)) score -= batch_size score = tf.div(score, batch_size * batch_size - batch_size) # Define a function which wraps some session.run calls to generate a large # number of images and compute multiscale ssim metric on them. def _eval_fn(session): """Function which wraps session.run calls to compute given metric.""" logging.info("Computing MS-SSIM score...") scores = [] for _ in range(num_batches): scores.append(session.run(score)) result = np.mean(scores) return result return _eval_fn
compare_gan-master
compare_gan/metrics/ms_ssim_score.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the Jacobian Conditioning metrics. The details can be found in "Is Generator Conditioning Causally Related to GAN Performance?", Odena et al. [https://arxiv.org/abs/1802.08768]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.metrics import eval_task import numpy as np import tensorflow as tf class GeneratorConditionNumberTask(eval_task.EvalTask): """Computes the generator condition number. Computes the condition number for metric Tensor of the generator Jacobian. This condition number is computed locally for each z sample in a minibatch. Returns the mean log condition number and standard deviation across the minibatch. Follows the methods in https://arxiv.org/abs/1802.08768. """ _CONDITION_NUMBER_COUNT = "log_condition_number_count" _CONDITION_NUMBER_MEAN = "log_condition_number_mean" _CONDITION_NUMBER_STD = "log_condition_number_std" def metric_list(self): return frozenset([ self._CONDITION_NUMBER_COUNT, self._CONDITION_NUMBER_MEAN, self._CONDITION_NUMBER_STD ]) def run_in_session(self, options, sess, gan, real_images): del options, real_images result_dict = {} result = compute_generator_condition_number(sess, gan) result_dict[self._CONDITION_NUMBER_COUNT] = len(result) result_dict[self._CONDITION_NUMBER_MEAN] = np.mean(result) result_dict[self._CONDITION_NUMBER_STD] = np.std(result) return result_dict def compute_generator_condition_number(sess, gan): """Computes the generator condition number. Computes the Jacobian of the generator in session, then postprocesses to get the condition number. Args: sess: tf.Session object. gan: AbstractGAN object, that is already present in the current tf.Graph. Returns: A list of length gan.batch_size. Each element is the condition number computed at a single z sample within a minibatch. """ shape = gan.fake_images.get_shape().as_list() flat_generator_output = tf.reshape( gan.fake_images, [gan.batch_size, np.prod(shape[1:])]) tf_jacobian = compute_jacobian( xs=gan.z, fx=flat_generator_output) z_sample = gan.z_generator(gan.batch_size, gan.z_dim) np_jacobian = sess.run(tf_jacobian, feed_dict={gan.z: z_sample}) result_dict = analyze_jacobian(np_jacobian) return result_dict["metric_tensor"]["log_condition_number"] def compute_jacobian(xs, fx): """Computes df/dx matrix. We assume x and fx are both batched, so the shape of the Jacobian is: [fx.shape[0]] + fx.shape[1:] + xs.shape[1:] This function computes the grads inside a TF loop so that we don't end up storing many extra copies of the function we are taking the Jacobian of. Args: xs: input tensor(s) of arbitrary shape. fx: f(x) tensor of arbitrary shape. Returns: df/dx tensor of shape [fx.shape[0], fx.shape[1], xs.shape[1]]. """ # Declares an iterator and tensor array loop variables for the gradients. n = fx.get_shape().as_list()[1] loop_vars = [tf.constant(0, tf.int32), tf.TensorArray(xs.dtype, n)] def accumulator(j, result): return (j + 1, result.write(j, tf.gradients(fx[:, j], xs)[0])) # Iterates over all elements of the gradient and computes all partial # derivatives. _, df_dxs = tf.while_loop(lambda j, _: j < n, accumulator, loop_vars) df_dx = df_dxs.stack() df_dx = tf.transpose(df_dx, perm=[1, 0, 2]) return df_dx def _analyze_metric_tensor(metric_tensor): """Analyzes a metric tensor. Args: metric_tensor: A numpy array of shape [batch, dim, dim] Returns: A dict containing spectral statstics. """ # eigenvalues will have shape [batch, dim]. eigenvalues, _ = np.linalg.eig(metric_tensor) # Shape [batch,]. condition_number = np.linalg.cond(metric_tensor) log_condition_number = np.log(condition_number) (_, logdet) = np.linalg.slogdet(metric_tensor) return { "eigenvalues": eigenvalues, "logdet": logdet, "log_condition_number": log_condition_number } def analyze_jacobian(jacobian_array): """Computes eigenvalue statistics of the Jacobian. Computes the eigenvalues and condition number of the metric tensor for the Jacobian evaluated at each element of the batch and the mean metric tensor across the batch. Args: jacobian_array: A numpy array holding the Jacobian. Returns: A dict of spectral statistics with two elements, one containing stats for every metric tensor in the batch, another for the mean metric tensor. """ # Shape [batch, x_dim, fx_dim]. jacobian_transpose = np.transpose(jacobian_array, [0, 2, 1]) # Shape [batch, x_dim, x_dim]. metric_tensor = np.matmul(jacobian_transpose, jacobian_array) mean_metric_tensor = np.mean(metric_tensor, 0) # Reshapes to have a dummy batch dimension. mean_metric_tensor = np.reshape(mean_metric_tensor, (1,) + metric_tensor.shape[1:]) return { "metric_tensor": _analyze_metric_tensor(metric_tensor), "mean_metric_tensor": _analyze_metric_tensor(mean_metric_tensor) }
compare_gan-master
compare_gan/metrics/jacobian_conditioning.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the fractal dimension metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.metrics import fractal_dimension as fractal_dimension_lib import numpy as np import tensorflow as tf class FractalDimensionTest(tf.test.TestCase): def test_straight_line(self): """The fractal dimension of a 1D line must lie near 1.0.""" self.assertAllClose( fractal_dimension_lib.compute_fractal_dimension( np.random.uniform(size=(10000, 1))), 1.0, atol=0.05) def test_square(self): """The fractal dimension of a 2D square must lie near 2.0.""" self.assertAllClose( fractal_dimension_lib.compute_fractal_dimension( np.random.uniform(size=(10000, 2))), 2.0, atol=0.1)
compare_gan-master
compare_gan/metrics/fractal_dimension_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implements GILBO score functions. Details are available in "GILBO: One Metric to Measure Them All", Alemi and Fisher [https://arxiv.org/abs/1802.04874]. Changelist: (6 Feb 2019): Removed VAE. (5 Jan 2019): The code is not supported in latest compare_gan due to the major interface changes. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from compare_gan import datasets from compare_gan.metrics import eval_task import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top import numpy as np from pstar import plist import scipy.misc import six.moves.cPickle as pickle import tensorflow as tf import tensorflow_probability as tfp layers = tf.layers ds = tfp.distributions class GILBOTask(eval_task.EvalTask): """Compute GILBO metric and related consistency metrics.""" def __init__(self, outdir, task_workdir, dataset_name): self.outdir = outdir self.task_workdir = task_workdir self.dataset = dataset_name def metric_list(self): return frozenset([ "gilbo", "gilbo_train_consistency", "gilbo_eval_consistency", "gilbo_self_consistency", ]) def run_in_session(self, options, sess, gan, eval_data_real): del eval_data_real result_dict = {} if options.get("compute_gilbo", False): (gilbo, gilbo_train_consistency, gilbo_eval_consistency, gilbo_self_consistency) = train_gilbo( gan, sess, self.outdir, self.task_workdir, self.dataset, options) result_dict["gilbo"] = gilbo result_dict["gilbo_train_consistency"] = gilbo_train_consistency result_dict["gilbo_eval_consistency"] = gilbo_eval_consistency result_dict["gilbo_self_consistency"] = gilbo_self_consistency return result_dict def _build_regressor(x, z_dim=64): """Make the GILBO regressor, which is based off of the GAN discriminator.""" net = tf.cast(x, tf.float32) net = layers.conv2d(net, 64, 4, 2, activation=tf.nn.leaky_relu) net = layers.conv2d(net, 128, 4, 2, activation=tf.nn.leaky_relu) net = layers.flatten(net) net = layers.dense(net, 1024, activation=tf.nn.leaky_relu) net = layers.dense(net, 2 * z_dim) # a and b correspond to the alpha beta parameters of the Beta distribution. a, b = net[..., :z_dim], net[..., z_dim:2 * z_dim] a = 1 + tf.nn.softplus(a - 5) b = 1 + tf.nn.softplus(b - 5) dist = ds.Independent(ds.Beta(a, b), 1) bijector = ds.bijectors.Affine(-1.0, 2.0) tdist = ds.TransformedDistribution(distribution=dist, bijector=bijector) return tdist def train_gilbo(gan, sess, outdir, checkpoint_path, dataset, options): """Build and train GILBO model. Args: gan: GAN object. sess: tf.Session. outdir: Output directory. A pickle file will be written there. checkpoint_path: Path where gan"s checkpoints are written. Only used to ensure that GILBO files are written to a unique subdirectory of outdir. dataset: Name of dataset used to train the GAN. options: Options dictionary. Returns: mean_eval_info: Mean GILBO computed over a large number of images generated by the trained GAN mean_train_consistency: Mean consistency of the trained GILBO model with data from the training set. mean_eval_consistency: Same consistency measure for the trained model with data from the validation set. mean_self_consistency: Same consistency measure for the trained model with data generated by the trained model itself. See the GILBO paper for an explanation of these metrics. Raises: ValueError: If the GAN has uninitialized variables. """ uninitialized = sess.run(tf.report_uninitialized_variables()) if uninitialized: raise ValueError("Model has uninitialized variables!\n%r" % uninitialized) outdir = os.path.join(outdir, checkpoint_path.replace("/", "_")) tf.gfile.MakeDirs(outdir) with tf.variable_scope("gilbo"): ones = tf.ones((gan.batch_size, gan.z_dim)) # Get a distribution for the prior. z_dist = ds.Independent(ds.Uniform(-ones, ones), 1) z_sample = z_dist.sample() epsneg = np.finfo("float32").epsneg # Clip samples from the GAN uniform prior because the Beta distribution # doesn"t include the top endpoint and has issues with the bottom endpoint. ganz_clip = tf.clip_by_value(gan.z, -(1 - epsneg), 1 - epsneg) # Get generated images from the model. fake_images = gan.fake_images # Build the regressor distribution that encodes images back to predicted # samples from the prior. with tf.variable_scope("regressor"): z_pred_dist = _build_regressor(fake_images, gan.z_dim) # Capture the parameters of the distributions for later analysis. dist_p1 = z_pred_dist.distribution.distribution.concentration0 dist_p2 = z_pred_dist.distribution.distribution.concentration1 # info and avg_info compute the GILBO. info = z_pred_dist.log_prob(ganz_clip) - z_dist.log_prob(ganz_clip) avg_info = tf.reduce_mean(info) # Set up training of the GILBO model. lr = options.get("gilbo_learning_rate", 4e-4) learning_rate = tf.get_variable( "learning_rate", initializer=lr, trainable=False) gilbo_step = tf.get_variable("gilbo_step", dtype=tf.int32, initializer=0, trainable=False) opt = tf.train.AdamOptimizer(learning_rate) regressor_vars = tf.contrib.framework.get_variables("gilbo/regressor") train_op = opt.minimize(-info, var_list=regressor_vars) # Initialize the variables we just created. uninitialized = plist(tf.report_uninitialized_variables().eval()) uninitialized_vars = uninitialized.apply( tf.contrib.framework.get_variables_by_name)._[0] tf.variables_initializer(uninitialized_vars).run() saver = tf.train.Saver(uninitialized_vars, max_to_keep=1) try: checkpoint_path = tf.train.latest_checkpoint(outdir) saver.restore(sess, checkpoint_path) except ValueError: # Failing to restore just indicates that we don"t have a valid checkpoint, # so we will just start training a fresh GILBO model. pass _train_gilbo(sess, gan, saver, learning_rate, gilbo_step, z_sample, avg_info, z_pred_dist, train_op, outdir, options) mean_eval_info = _eval_gilbo(sess, gan, z_sample, avg_info, dist_p1, dist_p2, fake_images, outdir, options) # Collect encoded distributions on the training and eval set in order to do # kl-nearest-neighbors on generated samples and measure consistency. dataset = datasets.get_dataset(dataset) x_train = dataset.load_dataset(split_name="train", num_threads=1) x_train = x_train.batch(gan.batch_size, drop_remainder=True) x_train = x_train.make_one_shot_iterator().get_next()[0] x_train = tf.reshape(x_train, fake_images.shape) x_eval = dataset.load_dataset(split_name="test", num_threads=1) x_eval = x_eval.batch(gan.batch_size, drop_remainder=True) x_eval = x_eval.make_one_shot_iterator().get_next()[0] x_eval = tf.reshape(x_eval, fake_images.shape) mean_train_consistency = _run_gilbo_consistency( x_train, "train", extract_input_images=0, save_consistency_images=20, num_batches=5, **locals()) mean_eval_consistency = _run_gilbo_consistency( x_eval, "eval", extract_input_images=0, save_consistency_images=20, num_batches=5, **locals()) mean_self_consistency = _run_gilbo_consistency( fake_images, "self", extract_input_images=20, save_consistency_images=20, num_batches=5, **locals()) return (mean_eval_info, mean_train_consistency, mean_eval_consistency, mean_self_consistency) def _train_gilbo(sess, gan, saver, learning_rate, gilbo_step, z_sample, avg_info, z_pred_dist, train_op, outdir, options): """Run the training process.""" lr_scale = options.get("gilbo_lr_scale", 0.5) min_lr = options.get("gilbo_min_lr", 1e-8) min_ai_step_scale = options.get("gilbo_min_ai_step_scale", 0.75) min_ai_step_value = options.get("gilbo_min_ai_step_value", 0.5) max_train_cycles = options.get("gilbo_max_train_cycles", 50) train_steps_per_cycle = options.get("gilbo_train_steps_per_cycle", 10000) ais = [0.0] # average gilbos (i is for info) min_ai = -2.0 lr, i = sess.run([learning_rate, gilbo_step]) for i in range(i, max_train_cycles): if lr < min_lr: break _save_gilbo(saver, sess, learning_rate, gilbo_step, i, lr, outdir) ai = 0.0 for j in range(train_steps_per_cycle): if j % (train_steps_per_cycle // 10) == 0: tf.logging.info("step:%d, gilbo:%.3f" % (j, ai)) samp = sess.run(z_sample) _, z_info = sess.run( [train_op, avg_info], feed_dict={gan.z: samp, learning_rate: lr}) ai += (z_info - ai) / (j + 1) tf.logging.info("cycle:%d gilbo:%.3f min next gilbo:%.3f learning rate:%.3f" % (i, ai, min_ai, lr)) if ai < min_ai: lr *= lr_scale if lr < min_lr: break if np.isnan(ai): tf.logging.info("NaN GILBO at cycle %d, stopping training early." % i) break ais.append(ai) # min_ai is the minimum next GILBO for the training algorithm to consider # that progress is being made. GILBO is a lower bound that we are maximizing # so we want it to increase during each training cycle. min_ai = max(min_ai, ai + max(0.0, min(min_ai_step_value, (ai - ais[-2]) * min_ai_step_scale) ) ) _save_gilbo(saver, sess, learning_rate, gilbo_step, i, lr, outdir) _save_z_histograms(gan, z_sample, z_pred_dist, outdir, i) def _eval_gilbo(sess, gan, z_sample, avg_info, dist_p1, dist_p2, fake_images, outdir, options): """Evaluate GILBO on new data from the generative model. Args: sess: tf.Session. gan: GAN object. z_sample: Tensor sampling from the prior. avg_info: Tensor that computes the per-batch GILBO. dist_p1: Tensor for the first parameter of the distribution (e.g., concentration1 for a Beta distribution). dist_p2: Tensor for the second parameter of the distribution (e.g., concentration2 for a Beta distribution). fake_images: Tensor of images sampled from the GAN. outdir: Output directory. A pickle file will be written there. options: Options dictionary. Returns: The mean GILBO on the evaluation set. Also writes a pickle file saving distribution parameters and generated images for later analysis. """ eval_steps = options.get("gilbo_eval_steps", 10000) z_infos = np.zeros(eval_steps, np.float32) z_dist_p1s, z_dist_p2s, z_fake_images = [], [], [] mean_eval_info = 0 for i in range(eval_steps): samp = sess.run(z_sample) if i * gan.batch_size < 1000: # Save the first 1000 distribution parameters and generated images for # separate data processing. z_infos[i], z_dist_p1, z_dist_p2, images = sess.run( [avg_info, dist_p1, dist_p2, fake_images], feed_dict={gan.z: samp}) z_dist_p1s.append(z_dist_p1) z_dist_p2s.append(z_dist_p2) z_fake_images.append(images) else: z_infos[i] = sess.run(avg_info, feed_dict={gan.z: samp}) if i % (eval_steps // 10) == 0: tf.logging.info("eval step:%d gilbo:%3.1f" % (i, z_infos[i])) if eval_steps: mean_eval_info = np.mean(np.nan_to_num(z_infos)) eval_dists = dict( dist_p1=np.array(z_dist_p1s).reshape([-1, 64]), dist_p2=np.array(z_dist_p2s).reshape([-1, 64]), images=np.array(z_fake_images).reshape( [-1] + list(z_fake_images[0].shape[1:]))) with tf.gfile.Open(os.path.join(outdir, "eval_dists.p"), "w") as f: pickle.dump(eval_dists, f) tf.logging.info("eval gilbo:%3.1f" % mean_eval_info) return mean_eval_info def _run_gilbo_consistency( input_images, mode, dist_p1, dist_p2, z_pred_dist, z_sample, gan, sess, outdir, dataset, extract_input_images=0, save_consistency_images=0, num_batches=3000, **unused_kw): """Measure consistency of the gilbo estimator with the GAN or VAE. Arguments without documentation are variables from the calling function needed here. Pass them with **locals(). Args: input_images: Tensor. Dataset images, or images generated by the GAN or VAE. mode: "train", "eval", or "self". Which consistency measure to compute. dist_p1: dist_p2: z_pred_dist: z_sample: gan: sess: outdir: dataset: extract_input_images: Number of batches to extract, -1 for all. Default: 0. save_consistency_images: Num batches to save, -1 for all. Default: 0. num_batches: Number of batches to run. Default: 3000. **unused_kw: Unused extra keyword args. Returns: Symmetric consistency KL. Additionally saves distribution parameters as a pickle as well as any requested images as pngs to outdir. """ with tf.variable_scope("gilbo"): with tf.variable_scope("regressor", reuse=True): z_pred_dist_train = _build_regressor(input_images, gan.z_dim) z_sample_train = z_pred_dist_train.sample() dist_p1_ph = tf.placeholder(tf.float32, dist_p1.shape) dist_p2_ph = tf.placeholder(tf.float32, dist_p2.shape) consist_dist_p1_ph = tf.placeholder(tf.float32, dist_p1.shape) consist_dist_p2_ph = tf.placeholder(tf.float32, dist_p2.shape) dist_p1 = z_pred_dist_train.distribution.distribution.concentration0 dist_p2 = z_pred_dist_train.distribution.distribution.concentration1 consist_z_dist_p1 = z_pred_dist.distribution.distribution.concentration0 consist_z_dist_p2 = z_pred_dist.distribution.distribution.concentration1 base_dist = ds.Beta kl_dist_p = ds.Independent(base_dist(dist_p1_ph, dist_p2_ph), 1) kl_dist_q = ds.Independent( base_dist(consist_dist_p1_ph, consist_dist_p2_ph), 1) consistency_kl = kl_dist_p.kl_divergence(kl_dist_q) consistency_rkl = kl_dist_q.kl_divergence(kl_dist_p) z_dist_p1s, z_dist_p2s = [], [] consist_z_dist_p1s, consist_z_dist_p2s = [], [] consistency_kls, consistency_rkls, consistency_skls = [], [], [] i = 0 while i < num_batches: try: samp = sess.run(z_sample) z_dist_p1, z_dist_p2, images, train_samp = sess.run( [dist_p1, dist_p2, input_images, z_sample_train], feed_dict={gan.z: samp}) z_dist_p1s.append(z_dist_p1) z_dist_p2s.append(z_dist_p2) (consist_z_dist_p1_out, consist_z_dist_p2_out, consistency_images) = sess.run( [consist_z_dist_p1, consist_z_dist_p2, gan.fake_images], feed_dict={gan.z: train_samp}) consist_z_dist_p1s.append(consist_z_dist_p1_out) consist_z_dist_p2s.append(consist_z_dist_p2_out) consist_kls, consist_rkls = sess.run( [consistency_kl, consistency_rkl], feed_dict={ dist_p1_ph: z_dist_p1, dist_p2_ph: z_dist_p2, consist_dist_p1_ph: consist_z_dist_p1_out, consist_dist_p2_ph: consist_z_dist_p2_out, }) consistency_kls.append(consist_kls) consistency_rkls.append(consist_rkls) consistency_skls.append((consist_kls + consist_rkls) / 2.0) if save_consistency_images: save_consistency_images -= 1 filename = os.path.join( outdir, "consistency_image_%s_%06d_%06d.png" % (mode, i * gan.batch_size, (i + 1) * gan.batch_size - 1)) img = consistency_images.reshape( [gan.batch_size * consistency_images.shape[1], consistency_images.shape[2], -1]) _save_image(img, filename) if extract_input_images: extract_input_images -= 1 if mode == "self": filename = os.path.join( outdir, "%s_image_%06d_%06d.png" % (mode, i * gan.batch_size, (i + 1) * gan.batch_size - 1)) img = images.reshape( [gan.batch_size * consistency_images.shape[1], consistency_images.shape[2], -1]) _save_image(img, filename) else: for j in range(gan.batch_size): filename = os.path.join( outdir, "..", dataset, "%s_image_%06d.png" % (mode, i * gan.batch_size + j)) _save_image(images[j], filename) if i % 100 == 0: tf.logging.info( "%s: step:%d consistency KL:%3.1f" % (mode, i, np.mean(consistency_skls))) i += 1 except tf.errors.OutOfRangeError: break out_dists = dict( dist_p1=np.reshape(z_dist_p1s, [-1, gan.batch_size]), dist_p2=np.reshape(z_dist_p2s, [-1, gan.batch_size]), consist_dist_p1=np.reshape(consist_z_dist_p1s, [-1, gan.batch_size]), consist_dist_p2=np.reshape(consist_z_dist_p2s, [-1, gan.batch_size]), consistency_kl=np.reshape(consistency_kls, [-1, gan.batch_size]), consistency_rkl=np.reshape(consistency_rkls, [-1, gan.batch_size]), consistency_skl=np.reshape(consistency_skls, [-1, gan.batch_size]), ) with tf.gfile.Open( os.path.join(outdir, "%s_consistency_dists.p" % mode), "w") as f: pickle.dump(out_dists, f) return np.mean(consistency_skls) def _save_image(img, filename): # If img is [H W] or [H W 1], stack into [H W 3] for scipy"s api. if len(img.shape) == 2 or img.shape[-1] == 1: img = np.stack((img.squeeze(),) * 3, -1) with tf.gfile.Open(filename, "w") as f: scipy.misc.toimage(img, cmin=0.0, cmax=1.0).save(f) def _save_z_histograms(gan, z_sample, z_pred_dist, outdir, step): """Save a histogram for each z dimension as an png in outdir.""" fig, axs = plt.subplots(8, 8, figsize=(15, 10)) pk = 0 bins = np.linspace(-1, 1, 70) samp = z_sample.eval() z_pred_samp = z_pred_dist.sample(10000).eval({gan.z: samp}) try: for j in range(64): axs.flat[j].hist(z_pred_samp[:, pk, j], bins, histtype="stepfilled", normed=True) axs.flat[j].vlines(samp[pk, j], 0, 1.0, linestyle="dashed") plt.tight_layout() filename = os.path.join(outdir, "z_hist_%03d.png" % step) tf.logging.info("Saving z histogram: %s" % filename) with tf.gfile.Open(filename, "w") as f: fig.savefig(f, dpi="figure") except Exception as e: # pylint: disable=broad-except tf.logging.info("Caught %r while rendering chart. Ignoring.\n%s\n" % (type(e), str(e))) def _save_gilbo(saver, sess, learning_rate, gilbo_step, step, lr, outdir): """Save GILBO model checkpoints, including the current step and lr. Args: saver: tf.train.Saver. sess: tf.Session. learning_rate: tf.Variable for the learning rate. gilbo_step: tf.Variable for the current training step. step: integer for the current step, to be saved in the checkpoint. lr: float for the current learning rate, to be saved in the checkpoint. outdir: output directory. """ # Save the current learning rate and gilbo training step with the checkpoint. learning_rate.assign(lr).eval() gilbo_step.assign(step).eval() filename = os.path.join(outdir, "gilbo_model") saver.save(sess, filename, global_step=step)
compare_gan-master
compare_gan/metrics/gilbo.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for Jacobian Conditioning metrics.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.metrics import jacobian_conditioning import mock import numpy as np from six.moves import range import tensorflow as tf _BATCH_SIZE = 32 def SlowJacobian(xs, fx): """Computes df/dx matrix. As jacobian_conditioning.compute_jacobian, but explicitly loops over dimensions of f. Args: xs: input tensor(s) of arbitrary shape. fx: f(x) tensor of arbitrary shape. Returns: df/dx tensor. """ fxs = tf.unstack(fx, axis=-1) grads = [tf.gradients(fx_i, xs) for fx_i in fxs] grads = [grad[0] for grad in grads] df_dx = tf.stack(grads, axis=1) return df_dx class JacobianConditioningTest(tf.test.TestCase): def test_jacobian_simple_case(self): x = tf.random_normal([_BATCH_SIZE, 2]) W = tf.constant([[2., -1.], [1.5, 1.]]) # pylint: disable=invalid-name f = tf.matmul(x, W) j_tensor = jacobian_conditioning.compute_jacobian(xs=x, fx=f) with tf.Session() as sess: jacobian = sess.run(j_tensor) # Transpose of W in 'expected' is expected because in vector notation # f = W^T * x. expected = tf.tile([[[2, 1.5], [-1, 1]]], [_BATCH_SIZE, 1, 1]) self.assertAllClose(jacobian, expected) def test_jacobian_against_slow_version(self): x = tf.random_normal([_BATCH_SIZE, 2]) h1 = tf.contrib.layers.fully_connected(x, 20) h2 = tf.contrib.layers.fully_connected(h1, 20) f = tf.contrib.layers.fully_connected(h2, 10) j_slow_tensor = SlowJacobian(xs=x, fx=f) j_fast_tensor = jacobian_conditioning.compute_jacobian(xs=x, fx=f) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) j_fast, j_slow = sess.run([j_fast_tensor, j_slow_tensor]) self.assertAllClose(j_fast, j_slow) def test_jacobian_numerically(self): x = tf.random_normal([_BATCH_SIZE, 2]) h1 = tf.contrib.layers.fully_connected(x, 20) h2 = tf.contrib.layers.fully_connected(h1, 20) f = tf.contrib.layers.fully_connected(h2, 10) j_tensor = jacobian_conditioning.compute_jacobian(xs=x, fx=f) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) x_np = sess.run(x) jacobian = sess.run(j_tensor, feed_dict={x: x_np}) # Test 10 random elements. for _ in range(10): # Pick a random element of Jacobian to test. batch_idx = np.random.randint(_BATCH_SIZE) x_idx = np.random.randint(2) f_idx = np.random.randint(10) # Test with finite differences. epsilon = 1e-4 x_plus = x_np.copy() x_plus[batch_idx, x_idx] += epsilon f_plus = sess.run(f, feed_dict={x: x_plus})[batch_idx, f_idx] x_minus = x_np.copy() x_minus[batch_idx, x_idx] -= epsilon f_minus = sess.run(f, feed_dict={x: x_minus})[batch_idx, f_idx] self.assertAllClose( jacobian[batch_idx, f_idx, x_idx], (f_plus - f_minus) / (2. * epsilon), rtol=1e-3, atol=1e-3) def test_analyze_metric_tensor(self): # Assumes NumPy works, just tests that output shapes are as expected. jacobian = np.random.normal(0, 1, (_BATCH_SIZE, 2, 10)) metric_tensor = np.matmul(np.transpose(jacobian, [0, 2, 1]), jacobian) result_dict = jacobian_conditioning._analyze_metric_tensor(metric_tensor) self.assertAllEqual(result_dict['eigenvalues'].shape, [_BATCH_SIZE, 10]) self.assertAllEqual(result_dict['logdet'].shape, [_BATCH_SIZE]) self.assertAllEqual(result_dict['log_condition_number'].shape, [_BATCH_SIZE]) def test_analyze_jacobian(self): m = mock.patch.object( jacobian_conditioning, '_analyze_metric_tensor', new=lambda x: x) m.start() jacobian = np.array([[[1, 2], [3, 4]], [[2, 4], [6, 8]]]) result_dict = jacobian_conditioning.analyze_jacobian(jacobian) self.assertAllEqual(result_dict['metric_tensor'], [[[10, 14], [14, 20]], [[40, 56], [56, 80]]]) self.assertAllEqual(result_dict['mean_metric_tensor'], [[[25, 35], [35, 50]]]) m.stop() if __name__ == '__main__': tf.test.main()
compare_gan-master
compare_gan/metrics/jacobian_conditioning_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Abstract class that describes a single evaluation task. The tasks can be run in or after session. Each task can result in a set of metrics. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from absl import flags import six import tensorflow as tf FLAGS = flags.FLAGS @six.add_metaclass(abc.ABCMeta) class EvalTask(object): """Class that describes a single evaluation task. For example: compute inception score or compute accuracy. The classes that inherit from it, should implement the methods below. """ _LABEL = None def metric_list(self): """List of metrics that this class generates. These are the only keys that RunXX methods can return in their output maps. Returns: frozenset of strings, which are the names of the metrics that task computes. """ return frozenset(self._LABEL) def _create_session(self): try: target = FLAGS.master except AttributeError: return tf.Session() return tf.Session(target) @abc.abstractmethod def run_after_session(self, fake_dset, real_dset): """Runs the task after all the generator calls, after session was closed. WARNING: the images here, are in 0..255 range, with 3 color channels. Args: fake_dset: `EvalDataSample` with fake images and inception features. real_dset: `EvalDataSample` with real images and inception features. Returns: Dict with metric values. The keys must be contained in the set that "MetricList" method above returns. """
compare_gan-master
compare_gan/metrics/eval_task.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the Inception Score. Implemented as a wrapper around the tensorflow_gan library. The details can be found in "Improved Techniques for Training GANs", Salimans et al. [https://arxiv.org/abs/1606.03498]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan.metrics import eval_task import tensorflow as tf import tensorflow_gan as tfgan class InceptionScoreTask(eval_task.EvalTask): """Task that computes inception score for the generated images.""" _LABEL = "inception_score" def run_after_session(self, fake_dset, real_dest): del real_dest logging.info("Computing inception score.") with tf.Graph().as_default(): fake_logits = tf.convert_to_tensor(fake_dset.logits) inception_score = tfgan.eval.classifier_score_from_logits(fake_logits) with self._create_session() as sess: inception_score = sess.run(inception_score) logging.info("Inception score: %.3f", inception_score) return {self._LABEL: inception_score}
compare_gan-master
compare_gan/metrics/inception_score.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the KID score. The details can be found in "Demystifying MMD GANs", Binkowski et al. [https://arxiv.org/abs/1801.01401]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from compare_gan.metrics import eval_task import numpy as np import tensorflow as tf class KIDScoreTask(eval_task.EvalTask): """Evaluation task for the KID score.""" _LABEL = "kid_score" def run_after_session(self, fake_dset, real_dset): score = kid(fake_dset.activations, real_dset.activations) return {self._LABEL: score} def kid(fake_activations, real_activations, max_batch_size=1024, dtype=None, return_stderr=False): """Unbiased estimator of the Kernel Inception Distance. As defined by https://arxiv.org/abs/1801.01401. If return_stderr, also returns an estimate of the standard error, i.e. the standard deviation of the KID estimator. Returns nan if the number of batches is too small (< 5); for more reliable estimates, one could use the asymptotic variance estimate given in https://arxiv.org/abs/1611.04488. Uses a block estimator, as in https://arxiv.org/abs/1307.1954, with blocks no larger than max_batch_size. This is slightly different than the authors' provided code, but is also unbiased (and provides more-valid a variance estimate). NOTE: the blocking code assumes that real_activations and fake_activations are in random order. If real_activations is sorted in a meaningful order, the estimator will be biased. Args: fake_activations: [batch, num_features] tensor with inception features. real_activations: [batch, num_features] tensor with inception features. max_batch_size: Batches to compute the KID. dtype: Type used by the computations. return_stderr: If true, also returns the std_error from the KID computation. Returns: KID score (and optionally std error). """ real_activations.get_shape().assert_has_rank(2) fake_activations.get_shape().assert_has_rank(2) # need to know dimension for the kernel, and batch size to split things real_activations.get_shape().assert_is_fully_defined() fake_activations.get_shape().assert_is_fully_defined() n_real, dim = real_activations.get_shape().as_list() n_gen, dim2 = fake_activations.get_shape().as_list() assert dim2 == dim # tensorflow_gan forces doubles for FID, but I don't think we need that here if dtype is None: dtype = real_activations.dtype assert fake_activations.dtype == dtype else: real_activations = tf.cast(real_activations, dtype) fake_activations = tf.cast(fake_activations, dtype) # split into largest approximately-equally-sized blocks n_bins = int(math.ceil(max(n_real, n_gen) / max_batch_size)) bins_r = np.full(n_bins, int(math.ceil(n_real / n_bins))) bins_g = np.full(n_bins, int(math.ceil(n_gen / n_bins))) bins_r[:(n_bins * bins_r[0]) - n_real] -= 1 bins_g[:(n_bins * bins_r[0]) - n_gen] -= 1 assert bins_r.min() >= 2 assert bins_g.min() >= 2 inds_r = tf.constant(np.r_[0, np.cumsum(bins_r)]) inds_g = tf.constant(np.r_[0, np.cumsum(bins_g)]) dim_ = tf.cast(dim, dtype) def get_kid_batch(i): """Computes KID on a given batch of features. Takes real_activations[ind_r[i] : ind_r[i+1]] and fake_activations[ind_g[i] : ind_g[i+1]]. Args: i: is the index of the batch. Returns: KID for the given batch. """ r_s = inds_r[i] r_e = inds_r[i + 1] r = real_activations[r_s:r_e] m = tf.cast(r_e - r_s, dtype) g_s = inds_g[i] g_e = inds_g[i + 1] g = fake_activations[g_s:g_e] n = tf.cast(r_e - r_s, dtype) # Could probably do this a bit faster... k_rr = (tf.matmul(r, r, transpose_b=True) / dim_ + 1)**3 k_rg = (tf.matmul(r, g, transpose_b=True) / dim_ + 1)**3 k_gg = (tf.matmul(g, g, transpose_b=True) / dim_ + 1)**3 return ( -2 * tf.reduce_mean(k_rg) + (tf.reduce_sum(k_rr) - tf.trace(k_rr)) / (m * (m - 1)) + (tf.reduce_sum(k_gg) - tf.trace(k_gg)) / (n * (n - 1))) ests = tf.map_fn( get_kid_batch, np.arange(n_bins), dtype=dtype, back_prop=False) if return_stderr: if n_bins < 5: return tf.reduce_mean(ests), np.nan mn, var = tf.nn.moments(ests, [0]) return mn, tf.sqrt(var / n_bins) else: return tf.reduce_mean(ests)
compare_gan-master
compare_gan/metrics/kid_score.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Discriminator accuracy. Computes the discrimionator's accuracy on (a subset) of the training dataset, test dataset, and a generated data set. The score is averaged over several multiple generated data sets and subsets of the training data. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan import datasets from compare_gan import eval_utils from compare_gan.metrics import eval_task import numpy as np class AccuracyTask(eval_task.EvalTask): """Evaluation Task for computing and reporting accuracy.""" def metric_list(self): return frozenset([ "train_accuracy", "test_accuracy", "fake_accuracy", "train_d_loss", "test_d_loss" ]) def run_in_session(self, options, sess, gan, real_images): del options return compute_accuracy_loss(sess, gan, real_images) def compute_accuracy_loss(sess, gan, test_images, max_train_examples=50000, num_repeat=5): """Compute discriminator's accuracy and loss on a given dataset. Args: sess: Tf.Session object. gan: Any AbstractGAN instance. test_images: numpy array with test images. max_train_examples: How many "train" examples to get from the dataset. In each round, some of them will be randomly selected to evaluate train set accuracy. num_repeat: How many times to repreat the computation. The mean of all the results is reported. Returns: Dict[Text, float] with all the computed scores. Raises: ValueError: If the number of test_images is greater than the number of training images returned by the dataset. """ logging.info("Evaluating training and test accuracy...") train_images = eval_utils.get_real_images( dataset=datasets.get_dataset(), num_examples=max_train_examples, split="train", failure_on_insufficient_examples=False) if train_images.shape[0] < test_images.shape[0]: raise ValueError("num_train %d must be larger than num_test %d." % (train_images.shape[0], test_images.shape[0])) num_batches = int(np.floor(test_images.shape[0] / gan.batch_size)) if num_batches * gan.batch_size < test_images.shape[0]: logging.error("Ignoring the last batch with %d samples / %d epoch size.", test_images.shape[0] - num_batches * gan.batch_size, gan.batch_size) ret = { "train_accuracy": [], "test_accuracy": [], "fake_accuracy": [], "train_d_loss": [], "test_d_loss": [] } for _ in range(num_repeat): idx = np.random.choice(train_images.shape[0], test_images.shape[0]) bs = gan.batch_size train_subset = [train_images[i] for i in idx] train_predictions, test_predictions, fake_predictions = [], [], [] train_d_losses, test_d_losses = [], [] for i in range(num_batches): z_sample = gan.z_generator(gan.batch_size, gan.z_dim) start_idx = i * bs end_idx = start_idx + bs test_batch = test_images[start_idx : end_idx] train_batch = train_subset[start_idx : end_idx] test_prediction, test_d_loss, fake_images = sess.run( [gan.discriminator_output, gan.d_loss, gan.fake_images], feed_dict={ gan.inputs: test_batch, gan.z: z_sample }) train_prediction, train_d_loss = sess.run( [gan.discriminator_output, gan.d_loss], feed_dict={ gan.inputs: train_batch, gan.z: z_sample }) fake_prediction = sess.run( gan.discriminator_output, feed_dict={gan.inputs: fake_images})[0] train_predictions.append(train_prediction[0]) test_predictions.append(test_prediction[0]) fake_predictions.append(fake_prediction) train_d_losses.append(train_d_loss) test_d_losses.append(test_d_loss) train_predictions = [x >= 0.5 for x in train_predictions] test_predictions = [x >= 0.5 for x in test_predictions] fake_predictions = [x < 0.5 for x in fake_predictions] ret["train_accuracy"].append(np.array(train_predictions).mean()) ret["test_accuracy"].append(np.array(test_predictions).mean()) ret["fake_accuracy"].append(np.array(fake_predictions).mean()) ret["train_d_loss"].append(np.mean(train_d_losses)) ret["test_d_loss"].append(np.mean(test_d_losses)) for key in ret: ret[key] = np.mean(ret[key]) return ret
compare_gan-master
compare_gan/metrics/accuracy.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the Frechet Inception Distance. Implemented as a wrapper around the tf.contrib.gan library. The details can be found in "GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium", Heusel et al. [https://arxiv.org/abs/1706.08500]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan.metrics import eval_task import tensorflow as tf import tensorflow_gan as tfgan # Special value returned when FID code returned exception. FID_CODE_FAILED = 4242.0 class FIDScoreTask(eval_task.EvalTask): """Evaluation task for the FID score.""" _LABEL = "fid_score" def run_after_session(self, fake_dset, real_dset): logging.info("Calculating FID.") with tf.Graph().as_default(): fake_activations = tf.convert_to_tensor(fake_dset.activations) real_activations = tf.convert_to_tensor(real_dset.activations) fid = tfgan.eval.frechet_classifier_distance_from_activations( real_activations=real_activations, generated_activations=fake_activations) with self._create_session() as sess: fid = sess.run(fid) logging.info("Frechet Inception Distance: %.3f.", fid) return {self._LABEL: fid} def compute_fid_from_activations(fake_activations, real_activations): """Returns the FID based on activations. Args: fake_activations: NumPy array with fake activations. real_activations: NumPy array with real activations. Returns: A float, the Frechet Inception Distance. """ logging.info("Computing FID score.") assert fake_activations.shape == real_activations.shape with tf.Session(graph=tf.Graph()) as sess: fake_activations = tf.convert_to_tensor(fake_activations) real_activations = tf.convert_to_tensor(real_activations) fid = tfgan.eval.frechet_classifier_distance_from_activations( real_activations=real_activations, generated_activations=fake_activations) return sess.run(fid)
compare_gan-master
compare_gan/metrics/fid_score.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the MS-SSIM score.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.metrics import ms_ssim_score import tensorflow as tf class MsSsimScoreTest(tf.test.TestCase): def test_on_one_vs_07_vs_zero_images(self): """Computes the SSIM value for 3 simple images.""" with tf.Graph().as_default(): generated_images = tf.stack([ tf.ones([64, 64, 3]), tf.ones([64, 64, 3]) * 0.7, tf.zeros([64, 64, 3]), ]) metric = ms_ssim_score.compute_msssim(generated_images, 1) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result = metric(sess) self.assertNear(result, 0.989989, 0.001) if __name__ == '__main__': tf.test.main()
compare_gan-master
compare_gan/metrics/ms_ssim_score_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for neural architectures.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized from compare_gan.architectures import dcgan from compare_gan.architectures import infogan from compare_gan.architectures import resnet30 from compare_gan.architectures import resnet5 from compare_gan.architectures import resnet_biggan from compare_gan.architectures import resnet_cifar from compare_gan.architectures import resnet_stl from compare_gan.architectures import sndcgan import tensorflow as tf class ArchitectureTest(parameterized.TestCase, tf.test.TestCase): def assertArchitectureBuilds(self, gen, disc, image_shape, z_dim=120): with tf.Graph().as_default(): batch_size = 2 num_classes = 10 # Prepare inputs z = tf.random.normal((batch_size, z_dim), name="z") y = tf.one_hot(tf.range(batch_size), num_classes) # Run check output shapes for G and D. x = gen(z=z, y=y, is_training=True, reuse=False) self.assertAllEqual(x.shape.as_list()[1:], image_shape) out, _, _ = disc( x, y=y, is_training=True, reuse=False) self.assertAllEqual(out.shape.as_list(), (batch_size, 1)) # Check that G outputs valid pixel values (we use [0, 1] everywhere) and # D outputs a probablilty. with self.session() as sess: sess.run(tf.global_variables_initializer()) image, pred = sess.run([x, out]) self.assertAllGreaterEqual(image, 0) self.assertAllLessEqual(image, 1) self.assertAllGreaterEqual(pred, 0) self.assertAllLessEqual(pred, 1) @parameterized.parameters( {"image_shape": (28, 28, 1)}, {"image_shape": (32, 32, 1)}, {"image_shape": (32, 32, 3)}, {"image_shape": (64, 64, 3)}, {"image_shape": (128, 128, 3)}, ) def testDcGan(self, image_shape): self.assertArchitectureBuilds( gen=dcgan.Generator(image_shape=image_shape), disc=dcgan.Discriminator(), image_shape=image_shape) @parameterized.parameters( {"image_shape": (28, 28, 1)}, {"image_shape": (32, 32, 1)}, {"image_shape": (32, 32, 3)}, {"image_shape": (64, 64, 3)}, {"image_shape": (128, 128, 3)}, ) def testInfoGan(self, image_shape): self.assertArchitectureBuilds( gen=infogan.Generator(image_shape=image_shape), disc=infogan.Discriminator(), image_shape=image_shape) def testResNet30(self, image_shape=(128, 128, 3)): self.assertArchitectureBuilds( gen=resnet30.Generator(image_shape=image_shape), disc=resnet30.Discriminator(), image_shape=image_shape) @parameterized.parameters( {"image_shape": (32, 32, 1)}, {"image_shape": (32, 32, 3)}, {"image_shape": (64, 64, 3)}, {"image_shape": (128, 128, 3)}, ) def testResNet5(self, image_shape): self.assertArchitectureBuilds( gen=resnet5.Generator(image_shape=image_shape), disc=resnet5.Discriminator(), image_shape=image_shape) @parameterized.parameters( {"image_shape": (32, 32, 3)}, {"image_shape": (64, 64, 3)}, {"image_shape": (128, 128, 3)}, {"image_shape": (256, 256, 3)}, {"image_shape": (512, 512, 3)}, ) def testResNet5BigGan(self, image_shape): if image_shape[0] == 512: z_dim = 160 elif image_shape[0] == 256: z_dim = 140 else: z_dim = 120 # Use channel multiplier 4 to avoid OOM errors. self.assertArchitectureBuilds( gen=resnet_biggan.Generator(image_shape=image_shape, ch=16), disc=resnet_biggan.Discriminator(ch=16), image_shape=image_shape, z_dim=z_dim) @parameterized.parameters( {"image_shape": (32, 32, 1)}, {"image_shape": (32, 32, 3)}, ) def testResNetCifar(self, image_shape): self.assertArchitectureBuilds( gen=resnet_cifar.Generator(image_shape=image_shape), disc=resnet_cifar.Discriminator(), image_shape=image_shape) @parameterized.parameters( {"image_shape": (48, 48, 1)}, {"image_shape": (48, 48, 3)}, ) def testResNetStl(self, image_shape): self.assertArchitectureBuilds( gen=resnet_stl.Generator(image_shape=image_shape), disc=resnet_stl.Discriminator(), image_shape=image_shape) @parameterized.parameters( {"image_shape": (28, 28, 1)}, {"image_shape": (32, 32, 1)}, {"image_shape": (32, 32, 3)}, {"image_shape": (64, 64, 3)}, {"image_shape": (128, 128, 3)}, ) def testSnDcGan(self, image_shape): self.assertArchitectureBuilds( gen=sndcgan.Generator(image_shape=image_shape), disc=sndcgan.Discriminator(), image_shape=image_shape) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/architectures_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for custom architecture operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import arch_ops import numpy as np import tensorflow as tf class ArchOpsTest(tf.test.TestCase): def testBatchNorm(self): with tf.Graph().as_default(): # 4 images with resolution 2x1 and 3 channels. x1 = tf.constant([[[5, 7, 2]], [[5, 8, 8]]], dtype=tf.float32) x2 = tf.constant([[[1, 2, 0]], [[4, 0, 4]]], dtype=tf.float32) x3 = tf.constant([[[6, 2, 6]], [[5, 0, 5]]], dtype=tf.float32) x4 = tf.constant([[[2, 4, 2]], [[6, 4, 1]]], dtype=tf.float32) x = tf.stack([x1, x2, x3, x4]) self.assertAllEqual(x.shape.as_list(), [4, 2, 1, 3]) core_bn = tf.layers.batch_normalization(x, training=True) contrib_bn = tf.contrib.layers.batch_norm(x, is_training=True) custom_bn = arch_ops.batch_norm(x, is_training=True) with self.session() as sess: sess.run(tf.global_variables_initializer()) core_bn, contrib_bn, custom_bn = sess.run( [core_bn, contrib_bn, custom_bn]) tf.logging.info("core_bn: %s", core_bn[0]) tf.logging.info("contrib_bn: %s", contrib_bn[0]) tf.logging.info("custom_bn: %s", custom_bn[0]) self.assertAllClose(core_bn, contrib_bn) self.assertAllClose(custom_bn, contrib_bn) expected_values = np.asarray( [[[[0.4375205, 1.30336881, -0.58830315]], [[0.4375205, 1.66291881, 1.76490951]]], [[[-1.89592218, -0.49438119, -1.37270737]], [[-0.14584017, -1.21348119, 0.19610107]]], [[[1.02088118, -0.49438119, 0.98050523]], [[0.4375205, -1.21348119, 0.58830321]]], [[[-1.31256151, 0.22471881, -0.58830315]], [[1.02088118, 0.22471881, -0.98050523]]]], dtype=np.float32) self.assertAllClose(custom_bn, expected_values) def testAccumulatedMomentsDuringTraing(self): with tf.Graph().as_default(): mean_in = tf.placeholder(tf.float32, shape=[2]) variance_in = tf.placeholder(tf.float32, shape=[2]) mean, variance = arch_ops._accumulated_moments_for_inference( mean=mean_in, variance=variance_in, is_training=True) variables_by_name = {v.op.name: v for v in tf.global_variables()} tf.logging.error(variables_by_name) accu_mean = variables_by_name["accu/accu_mean"] accu_variance = variables_by_name["accu/accu_variance"] accu_counter = variables_by_name["accu/accu_counter"] with self.session() as sess: sess.run(tf.global_variables_initializer()) m1, v1 = sess.run( [mean, variance], feed_dict={mean_in: [1.0, 2.0], variance_in: [3.0, 4.0]}) self.assertAllClose(m1, [1.0, 2.0]) self.assertAllClose(v1, [3.0, 4.0]) m2, v2 = sess.run( [mean, variance], feed_dict={mean_in: [5.0, 6.0], variance_in: [7.0, 8.0]}) self.assertAllClose(m2, [5.0, 6.0]) self.assertAllClose(v2, [7.0, 8.0]) am, av, ac = sess.run([accu_mean, accu_variance, accu_counter]) self.assertAllClose(am, [0.0, 0.0]) self.assertAllClose(av, [0.0, 0.0]) self.assertAllClose([ac], [0.0]) def testAccumulatedMomentsDuringEal(self): with tf.Graph().as_default(): mean_in = tf.placeholder(tf.float32, shape=[2]) variance_in = tf.placeholder(tf.float32, shape=[2]) mean, variance = arch_ops._accumulated_moments_for_inference( mean=mean_in, variance=variance_in, is_training=False) variables_by_name = {v.op.name: v for v in tf.global_variables()} tf.logging.error(variables_by_name) accu_mean = variables_by_name["accu/accu_mean"] accu_variance = variables_by_name["accu/accu_variance"] accu_counter = variables_by_name["accu/accu_counter"] update_accus = variables_by_name["accu/update_accus"] with self.session() as sess: sess.run(tf.global_variables_initializer()) # Fill accumulators. sess.run(tf.assign(update_accus, 1)) m1, v1 = sess.run( [mean, variance], feed_dict={mean_in: [1.0, 2.0], variance_in: [3.0, 4.0]}) self.assertAllClose(m1, [1.0, 2.0]) self.assertAllClose(v1, [3.0, 4.0]) m2, v2 = sess.run( [mean, variance], feed_dict={mean_in: [5.0, 6.0], variance_in: [7.0, 8.0]}) self.assertAllClose(m2, [3.0, 4.0]) self.assertAllClose(v2, [5.0, 6.0]) # Check accumulators. am, av, ac = sess.run([accu_mean, accu_variance, accu_counter]) self.assertAllClose(am, [6.0, 8.0]) self.assertAllClose(av, [10.0, 12.0]) self.assertAllClose([ac], [2.0]) # Use accumulators. sess.run(tf.assign(update_accus, 0)) m3, v3 = sess.run( [mean, variance], feed_dict={mean_in: [2.0, 2.0], variance_in: [3.0, 3.0]}) self.assertAllClose(m3, [3.0, 4.0]) self.assertAllClose(v3, [5.0, 6.0]) am, av, ac = sess.run([accu_mean, accu_variance, accu_counter]) self.assertAllClose(am, [6.0, 8.0]) self.assertAllClose(av, [10.0, 12.0]) self.assertAllClose([ac], [2.0]) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/arch_ops_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of SNDCGAN generator and discriminator architectures.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import abstract_arch from compare_gan.architectures.arch_ops import conv2d from compare_gan.architectures.arch_ops import deconv2d from compare_gan.architectures.arch_ops import linear from compare_gan.architectures.arch_ops import lrelu import numpy as np import tensorflow as tf def conv_out_size_same(size, stride): return int(np.ceil(float(size) / float(stride))) class Generator(abstract_arch.AbstractGenerator): """SNDCGAN generator. Details are available at https://openreview.net/pdf?id=B1QRgziT-. """ def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] of one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ batch_size = z.shape[0].value s_h, s_w, colors = self._image_shape s_h2, s_w2 = conv_out_size_same(s_h, 2), conv_out_size_same(s_w, 2) s_h4, s_w4 = conv_out_size_same(s_h2, 2), conv_out_size_same(s_w2, 2) s_h8, s_w8 = conv_out_size_same(s_h4, 2), conv_out_size_same(s_w4, 2) net = linear(z, s_h8 * s_w8 * 512, scope="g_fc1") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn1") net = tf.nn.relu(net) net = tf.reshape(net, [batch_size, s_h8, s_w8, 512]) net = deconv2d(net, [batch_size, s_h4, s_w4, 256], 4, 4, 2, 2, name="g_dc2") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn2") net = tf.nn.relu(net) net = deconv2d(net, [batch_size, s_h2, s_w2, 128], 4, 4, 2, 2, name="g_dc3") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn3") net = tf.nn.relu(net) net = deconv2d(net, [batch_size, s_h, s_w, 64], 4, 4, 2, 2, name="g_dc4") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn4") net = tf.nn.relu(net) net = deconv2d( net, [batch_size, s_h, s_w, colors], 3, 3, 1, 1, name="g_dc5") out = tf.tanh(net) # This normalization from [-1, 1] to [0, 1] is introduced for consistency # with other models. out = tf.div(out + 1.0, 2.0) return out class Discriminator(abstract_arch.AbstractDiscriminator): """SNDCGAN discriminator. Details are available at https://openreview.net/pdf?id=B1QRgziT-. """ def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ del is_training, y use_sn = self._spectral_norm # In compare gan framework, the image preprocess normalize image pixel to # range [0, 1], while author used [-1, 1]. Apply this trick to input image # instead of changing our preprocessing function. x = x * 2.0 - 1.0 net = conv2d(x, 64, 3, 3, 1, 1, name="d_conv1", use_sn=use_sn) net = lrelu(net, leak=0.1) net = conv2d(net, 128, 4, 4, 2, 2, name="d_conv2", use_sn=use_sn) net = lrelu(net, leak=0.1) net = conv2d(net, 128, 3, 3, 1, 1, name="d_conv3", use_sn=use_sn) net = lrelu(net, leak=0.1) net = conv2d(net, 256, 4, 4, 2, 2, name="d_conv4", use_sn=use_sn) net = lrelu(net, leak=0.1) net = conv2d(net, 256, 3, 3, 1, 1, name="d_conv5", use_sn=use_sn) net = lrelu(net, leak=0.1) net = conv2d(net, 512, 4, 4, 2, 2, name="d_conv6", use_sn=use_sn) net = lrelu(net, leak=0.1) net = conv2d(net, 512, 3, 3, 1, 1, name="d_conv7", use_sn=use_sn) net = lrelu(net, leak=0.1) batch_size = x.shape.as_list()[0] net = tf.reshape(net, [batch_size, -1]) out_logit = linear(net, 1, scope="d_fc1", use_sn=use_sn) out = tf.nn.sigmoid(out_logit) return out, out_logit, net
compare_gan-master
compare_gan/architectures/sndcgan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A deep neural architecture with residual blocks and skip connections. Based on Table 5 from "Spectral Normalization for Generative Adversarial Networks", Miyato T. et al., 2018. [https://arxiv.org/pdf/1802.05957.pdf]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import arch_ops as ops from compare_gan.architectures import resnet_ops from six.moves import range import tensorflow as tf class Generator(resnet_ops.ResNetGenerator): """ResNet generator, 3 blocks, supporting 48x48 resolution.""" def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size, 32, 32, colors] with values in [0, 1]. """ ch = 64 colors = self._image_shape[2] batch_size = z.get_shape().as_list()[0] magic = [(8, 4), (4, 2), (2, 1)] output = ops.linear(z, 6 * 6 * 512, scope="fc_noise") output = tf.reshape(output, [batch_size, 6, 6, 512], name="fc_reshaped") for block_idx in range(3): block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=ch * magic[block_idx][0], out_channels=ch * magic[block_idx][1], scale="up") output = block(output, z=z, y=y, is_training=is_training) output = self.batch_norm( output, z=z, y=y, is_training=is_training, scope="final_norm") output = tf.nn.relu(output) output = ops.conv2d(output, output_dim=colors, k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv") return tf.nn.sigmoid(output) class Discriminator(resnet_ops.ResNetDiscriminator): """ResNet discriminator, 4 blocks, suports 48x48 resolution.""" def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, 32, 32, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ resnet_ops.validate_image_inputs(x, validate_power2=False) colors = x.shape[-1].value if colors not in [1, 3]: raise ValueError("Number of color channels unknown: %s" % colors) ch = 64 block = self._resnet_block( name="B0", in_channels=colors, out_channels=ch, scale="down") output = block(x, z=None, y=y, is_training=is_training) magic = [(1, 2), (2, 4), (4, 8), (8, 16)] for block_idx in range(4): block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=ch * magic[block_idx][0], out_channels=ch * magic[block_idx][1], scale="down" if block_idx < 3 else "none") output = block(output, z=None, y=y, is_training=is_training) output = tf.nn.relu(output) pre_logits = tf.reduce_mean(output, axis=[1, 2]) out_logit = ops.linear(pre_logits, 1, scope="disc_final_fc", use_sn=self._spectral_norm) out = tf.nn.sigmoid(out_logit) return out, out_logit, pre_logits
compare_gan-master
compare_gan/architectures/resnet_stl.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Re-implementation of BigGAN architecture. Disclaimer: We note that this is our best-effort re-implementation and stress that even minor implementation differences may lead to large differences in trained models due to sensitivity of GANs to optimization hyperparameters and details of neural architectures. That being said, this code suffices to reproduce the reported FID on ImageNet 128x128. Based on "Large Scale GAN Training for High Fidelity Natural Image Synthesys", Brock A. et al., 2018 [https://arxiv.org/abs/1809.11096]. Supported resolutions: 32, 64, 128, 256, 512. The location of the self-attention block must be set in the Gin config. See below. Notable differences to resnet5.py: - Much wider layers by default. - 1x1 convs for shortcuts in D and G blocks. - Last BN in G is unconditional. - tanh activation in G. - No shortcut in D block if in_channels == out_channels. - sum pooling instead of mean pooling in D. - Last block in D does not downsample. Information related to parameter counts and Gin configuration: 128x128 ------- Number of parameters: (D) 87,982,370 (G) 70,433,988 Required Gin settings: options.z_dim = 120 resnet_biggan.Generator.blocks_with_attention = "B4" resnet_biggan.Discriminator.blocks_with_attention = "B1" 256x256 ------- Number of parameters: (D) 98,635,298 (G) 82,097,604 Required Gin settings: options.z_dim = 140 resnet_biggan.Generator.blocks_with_attention = "B5" resnet_biggan.Discriminator.blocks_with_attention = "B2" 512x512 ------- Number of parameters: (D) 98,801,378 (G) 82,468,068 Required Gin settings: options.z_dim = 160 resnet_biggan.Generator.blocks_with_attention = "B4" resnet_biggan.Discriminator.blocks_with_attention = "B3" """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan.architectures import abstract_arch from compare_gan.architectures import arch_ops as ops from compare_gan.architectures import resnet_ops import gin from six.moves import range import tensorflow as tf @gin.configurable class BigGanResNetBlock(resnet_ops.ResNetBlock): """ResNet block with options for various normalizations. This block uses a 1x1 convolution for the (optional) shortcut connection. """ def __init__(self, add_shortcut=True, **kwargs): """Constructs a new ResNet block for BigGAN. Args: add_shortcut: Whether to add a shortcut connection. **kwargs: Additional arguments for ResNetBlock. """ super(BigGanResNetBlock, self).__init__(**kwargs) self._add_shortcut = add_shortcut def apply(self, inputs, z, y, is_training): """"ResNet block containing possible down/up sampling, shared for G / D. Args: inputs: a 3d input tensor of feature map. z: the latent vector for potential self-modulation. Can be None if use_sbn is set to False. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, whether or notthis is called during the training. Returns: output: a 3d output tensor of feature map. """ if inputs.shape[-1].value != self._in_channels: raise ValueError( "Unexpected number of input channels (expected {}, got {}).".format( self._in_channels, inputs.shape[-1].value)) with tf.variable_scope(self._name, values=[inputs]): outputs = inputs outputs = self.batch_norm( outputs, z=z, y=y, is_training=is_training, name="bn1") if self._layer_norm: outputs = ops.layer_norm(outputs, is_training=is_training, scope="ln1") outputs = tf.nn.relu(outputs) outputs = self._get_conv( outputs, self._in_channels, self._out_channels, self._scale1, suffix="conv1") outputs = self.batch_norm( outputs, z=z, y=y, is_training=is_training, name="bn2") if self._layer_norm: outputs = ops.layer_norm(outputs, is_training=is_training, scope="ln2") outputs = tf.nn.relu(outputs) outputs = self._get_conv( outputs, self._out_channels, self._out_channels, self._scale2, suffix="conv2") # Combine skip-connection with the convolved part. if self._add_shortcut: shortcut = self._get_conv( inputs, self._in_channels, self._out_channels, self._scale, kernel_size=(1, 1), suffix="conv_shortcut") outputs += shortcut logging.info("[Block] %s (z=%s, y=%s) -> %s", inputs.shape, None if z is None else z.shape, None if y is None else y.shape, outputs.shape) return outputs @gin.configurable class Generator(abstract_arch.AbstractGenerator): """ResNet-based generator supporting resolutions 32, 64, 128, 256, 512.""" def __init__(self, ch=96, blocks_with_attention="B4", hierarchical_z=True, embed_z=False, embed_y=True, embed_y_dim=128, embed_bias=False, **kwargs): """Constructor for BigGAN generator. Args: ch: Channel multiplier. blocks_with_attention: Comma-separated list of blocks that are followed by a non-local block. hierarchical_z: Split z into chunks and only give one chunk to each. Each chunk will also be concatenated to y, the one hot encoded labels. embed_z: If True use a learnable embedding of z that is used instead. The embedding will have the length of z. embed_y: If True use a learnable embedding of y that is used instead. embed_y_dim: Size of the embedding of y. embed_bias: Use bias with for the embedding of z and y. **kwargs: additional arguments past on to ResNetGenerator. """ super(Generator, self).__init__(**kwargs) self._ch = ch self._blocks_with_attention = set(blocks_with_attention.split(",")) self._hierarchical_z = hierarchical_z self._embed_z = embed_z self._embed_y = embed_y self._embed_y_dim = embed_y_dim self._embed_bias = embed_bias def _resnet_block(self, name, in_channels, out_channels, scale): """ResNet block for the generator.""" if scale not in ["up", "none"]: raise ValueError( "Unknown generator ResNet block scaling: {}.".format(scale)) return BigGanResNetBlock( name=name, in_channels=in_channels, out_channels=out_channels, scale=scale, is_gen_block=True, spectral_norm=self._spectral_norm, batch_norm=self.batch_norm) def _get_in_out_channels(self): resolution = self._image_shape[0] if resolution == 512: channel_multipliers = [16, 16, 8, 8, 4, 2, 1, 1] elif resolution == 256: channel_multipliers = [16, 16, 8, 8, 4, 2, 1] elif resolution == 128: channel_multipliers = [16, 16, 8, 4, 2, 1] elif resolution == 64: channel_multipliers = [16, 16, 8, 4, 2] elif resolution == 32: channel_multipliers = [4, 4, 4, 4] else: raise ValueError("Unsupported resolution: {}".format(resolution)) in_channels = [self._ch * c for c in channel_multipliers[:-1]] out_channels = [self._ch * c for c in channel_multipliers[1:]] return in_channels, out_channels def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ shape_or_none = lambda t: None if t is None else t.shape logging.info("[Generator] inputs are z=%s, y=%s", z.shape, shape_or_none(y)) # Each block upscales by a factor of 2. seed_size = 4 z_dim = z.shape[1].value in_channels, out_channels = self._get_in_out_channels() num_blocks = len(in_channels) if self._embed_z: z = ops.linear(z, z_dim, scope="embed_z", use_sn=False, use_bias=self._embed_bias) if self._embed_y: y = ops.linear(y, self._embed_y_dim, scope="embed_y", use_sn=False, use_bias=self._embed_bias) y_per_block = num_blocks * [y] if self._hierarchical_z: z_per_block = tf.split(z, num_blocks + 1, axis=1) z0, z_per_block = z_per_block[0], z_per_block[1:] if y is not None: y_per_block = [tf.concat([zi, y], 1) for zi in z_per_block] else: z0 = z z_per_block = num_blocks * [z] logging.info("[Generator] z0=%s, z_per_block=%s, y_per_block=%s", z0.shape, [str(shape_or_none(t)) for t in z_per_block], [str(shape_or_none(t)) for t in y_per_block]) # Map noise to the actual seed. net = ops.linear( z0, in_channels[0] * seed_size * seed_size, scope="fc_noise", use_sn=self._spectral_norm) # Reshape the seed to be a rank-4 Tensor. net = tf.reshape( net, [-1, seed_size, seed_size, in_channels[0]], name="fc_reshaped") for block_idx in range(num_blocks): name = "B{}".format(block_idx + 1) block = self._resnet_block( name=name, in_channels=in_channels[block_idx], out_channels=out_channels[block_idx], scale="up") net = block( net, z=z_per_block[block_idx], y=y_per_block[block_idx], is_training=is_training) if name in self._blocks_with_attention: logging.info("[Generator] Applying non-local block to %s", net.shape) net = ops.non_local_block(net, "non_local_block", use_sn=self._spectral_norm) # Final processing of the net. # Use unconditional batch norm. logging.info("[Generator] before final processing: %s", net.shape) net = ops.batch_norm(net, is_training=is_training, name="final_norm") net = tf.nn.relu(net) net = ops.conv2d(net, output_dim=self._image_shape[2], k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv", use_sn=self._spectral_norm) logging.info("[Generator] after final processing: %s", net.shape) net = (tf.nn.tanh(net) + 1.0) / 2.0 return net @gin.configurable class Discriminator(abstract_arch.AbstractDiscriminator): """ResNet-based discriminator supporting resolutions 32, 64, 128, 256, 512.""" def __init__(self, ch=96, blocks_with_attention="B1", blocks_with_quantization=None, project_y=True, **kwargs): """Constructor for BigGAN discriminator. Args: ch: Channel multiplier. blocks_with_attention: Comma-separated list of blocks that are followed by a non-local block. project_y: Add an embedding of y in the output layer. **kwargs: additional arguments past on to ResNetDiscriminator. """ super(Discriminator, self).__init__(**kwargs) self._ch = ch self._blocks_with_attention = set(blocks_with_attention.split(",")) self._project_y = project_y self._blocks_with_quantization = [] if blocks_with_quantization is None else set(blocks_with_quantization.split(",")) self._quantize_loss = None def _resnet_block(self, name, in_channels, out_channels, scale): """ResNet block for the generator.""" if scale not in ["down", "none"]: raise ValueError( "Unknown discriminator ResNet block scaling: {}.".format(scale)) return BigGanResNetBlock( name=name, in_channels=in_channels, out_channels=out_channels, scale=scale, is_gen_block=False, add_shortcut=in_channels != out_channels, layer_norm=self._layer_norm, spectral_norm=self._spectral_norm, batch_norm=self.batch_norm) def _get_in_out_channels(self, colors, resolution): if colors not in [1, 3]: raise ValueError("Unsupported color channels: {}".format(colors)) if resolution == 512: channel_multipliers = [1, 1, 2, 4, 8, 8, 16, 16] elif resolution == 256: channel_multipliers = [1, 2, 4, 8, 8, 16, 16] elif resolution == 128: channel_multipliers = [1, 2, 4, 8, 16, 16] elif resolution == 64: channel_multipliers = [2, 4, 8, 16, 16] elif resolution == 32: channel_multipliers = [2, 2, 2, 2] else: raise ValueError("Unsupported resolution: {}".format(resolution)) out_channels = [self._ch * c for c in channel_multipliers] in_channels = [colors] + out_channels[:-1] return in_channels, out_channels def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ logging.info("[Discriminator] inputs are x=%s, y=%s", x.shape, None if y is None else y.shape) resnet_ops.validate_image_inputs(x) in_channels, out_channels = self._get_in_out_channels( colors=x.shape[-1].value, resolution=x.shape[1].value) num_blocks = len(in_channels) net = x if len(self._blocks_with_quantization) > 0: self._quantize_loss = 0 for block_idx in range(num_blocks): name = "B{}".format(block_idx + 1) is_last_block = block_idx == num_blocks - 1 block = self._resnet_block( name=name, in_channels=in_channels[block_idx], out_channels=out_channels[block_idx], scale="none" if is_last_block else "down") net = block(net, z=None, y=y, is_training=is_training) if name in self._blocks_with_attention: logging.info("[Discriminator] Applying non-local block to %s", net.shape) net = ops.non_local_block(net, "non_local_block", use_sn=self._spectral_norm) if name in self._blocks_with_quantization: net, q_loss = ops.vector_quantize( net, "V{}".format(block_idx + 1), is_training = is_training, embedding_dim = out_channels[block_idx] ) self._quantize_loss += tf.reduce_mean(q_loss) # Final part logging.info("[Discriminator] before final processing: %s", net.shape) net = tf.nn.relu(net) h = tf.math.reduce_sum(net, axis=[1, 2]) out_logit = ops.linear(h, 1, scope="final_fc", use_sn=self._spectral_norm) logging.info("[Discriminator] after final processing: %s", net.shape) if self._project_y: if y is None: raise ValueError("You must provide class information y to project.") with tf.variable_scope("embedding_fc"): y_embedding_dim = out_channels[-1] # We do not use ops.linear() below since it does not have an option to # override the initializer. kernel = tf.get_variable( "kernel", [y.shape[1], y_embedding_dim], tf.float32, initializer=tf.initializers.glorot_normal()) if self._spectral_norm: kernel = ops.spectral_norm(kernel) embedded_y = tf.matmul(y, kernel) logging.info("[Discriminator] embedded_y for projection: %s", embedded_y.shape) out_logit += tf.reduce_sum(embedded_y * h, axis=1, keepdims=True) out = tf.nn.sigmoid(out_logit) return out, out_logit, h
compare_gan-master
compare_gan/architectures/resnet_biggan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests batch normalizations using ResNet5 CIFAR.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan.architectures import arch_ops from compare_gan.architectures import resnet_cifar from six.moves import zip import tensorflow as tf class ResNetNormTest(tf.test.TestCase): def testDefaultGenerator(self): with tf.Graph().as_default(): # batch size 8, 32x32x3 images, 10 classes. z = tf.zeros((8, 128)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 10) generator = resnet_cifar.Generator(image_shape=(32, 32, 3)) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [8, 32, 32, 3]) expected_variables = [ # Name and shape. ("generator/fc_noise/kernel:0", [128, 4096]), ("generator/fc_noise/bias:0", [4096]), ("generator/B1/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv_shortcut/bias:0", [256]), ("generator/B1/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv1/bias:0", [256]), ("generator/B1/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B1/same_conv2/bias:0", [256]), ("generator/B2/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv_shortcut/bias:0", [256]), ("generator/B2/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv1/bias:0", [256]), ("generator/B2/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B2/same_conv2/bias:0", [256]), ("generator/B3/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv_shortcut/bias:0", [256]), ("generator/B3/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv1/bias:0", [256]), ("generator/B3/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B3/same_conv2/bias:0", [256]), ("generator/final_conv/kernel:0", [3, 3, 256, 3]), ("generator/final_conv/bias:0", [3]), ] actual_variables = [(v.name, v.shape.as_list()) for v in tf.trainable_variables()] for a, e in zip(actual_variables, expected_variables): logging.info("actual: %s, expected: %s", a, e) self.assertEqual(a, e) self.assertEqual(len(actual_variables), len(expected_variables)) def testDefaultDiscriminator(self): with tf.Graph().as_default(): # batch size 8, 32x32x3 images, 10 classes. x = tf.zeros((8, 32, 32, 3)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 10) discriminator = resnet_cifar.Discriminator() _ = discriminator(x, y=y, is_training=True, reuse=False) expected_variables = [ # Name and shape. ("discriminator/B1/down_conv_shortcut/kernel:0", [3, 3, 3, 128]), ("discriminator/B1/down_conv_shortcut/bias:0", [128]), ("discriminator/B1/same_conv1/kernel:0", [3, 3, 3, 128]), ("discriminator/B1/same_conv1/bias:0", [128]), ("discriminator/B1/down_conv2/kernel:0", [3, 3, 128, 128]), ("discriminator/B1/down_conv2/bias:0", [128]), ("discriminator/B2/down_conv_shortcut/kernel:0", [3, 3, 128, 128]), ("discriminator/B2/down_conv_shortcut/bias:0", [128]), ("discriminator/B2/same_conv1/kernel:0", [3, 3, 128, 128]), ("discriminator/B2/same_conv1/bias:0", [128]), ("discriminator/B2/down_conv2/kernel:0", [3, 3, 128, 128]), ("discriminator/B2/down_conv2/bias:0", [128]), ("discriminator/B3/same_conv_shortcut/kernel:0", [3, 3, 128, 128]), ("discriminator/B3/same_conv_shortcut/bias:0", [128]), ("discriminator/B3/same_conv1/kernel:0", [3, 3, 128, 128]), ("discriminator/B3/same_conv1/bias:0", [128]), ("discriminator/B3/same_conv2/kernel:0", [3, 3, 128, 128]), ("discriminator/B3/same_conv2/bias:0", [128]), ("discriminator/B4/same_conv_shortcut/kernel:0", [3, 3, 128, 128]), ("discriminator/B4/same_conv_shortcut/bias:0", [128]), ("discriminator/B4/same_conv1/kernel:0", [3, 3, 128, 128]), ("discriminator/B4/same_conv1/bias:0", [128]), ("discriminator/B4/same_conv2/kernel:0", [3, 3, 128, 128]), ("discriminator/B4/same_conv2/bias:0", [128]), ("discriminator/disc_final_fc/kernel:0", [128, 1]), ("discriminator/disc_final_fc/bias:0", [1]), ] actual_variables = [(v.name, v.shape.as_list()) for v in tf.trainable_variables()] for a, e in zip(actual_variables, expected_variables): logging.info("actual: %s, expected: %s", a, e) self.assertEqual(a, e) self.assertEqual(len(actual_variables), len(expected_variables)) def testDefaultGeneratorWithBatchNorm(self): with tf.Graph().as_default(): # batch size 8, 32x32x3 images, 10 classes. z = tf.zeros((8, 128)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 10) generator = resnet_cifar.Generator( image_shape=(32, 32, 3), batch_norm_fn=arch_ops.batch_norm) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [8, 32, 32, 3]) expected_variables = [ # Name and shape. ("generator/fc_noise/kernel:0", [128, 4096]), ("generator/fc_noise/bias:0", [4096]), ("generator/B1/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv_shortcut/bias:0", [256]), ("generator/B1/bn1/gamma:0", [256]), ("generator/B1/bn1/beta:0", [256]), ("generator/B1/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv1/bias:0", [256]), ("generator/B1/bn2/gamma:0", [256]), ("generator/B1/bn2/beta:0", [256]), ("generator/B1/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B1/same_conv2/bias:0", [256]), ("generator/B2/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv_shortcut/bias:0", [256]), ("generator/B2/bn1/gamma:0", [256]), ("generator/B2/bn1/beta:0", [256]), ("generator/B2/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv1/bias:0", [256]), ("generator/B2/bn2/gamma:0", [256]), ("generator/B2/bn2/beta:0", [256]), ("generator/B2/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B2/same_conv2/bias:0", [256]), ("generator/B3/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv_shortcut/bias:0", [256]), ("generator/B3/bn1/gamma:0", [256]), ("generator/B3/bn1/beta:0", [256]), ("generator/B3/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv1/bias:0", [256]), ("generator/B3/bn2/gamma:0", [256]), ("generator/B3/bn2/beta:0", [256]), ("generator/B3/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B3/same_conv2/bias:0", [256]), ("generator/final_norm/gamma:0", [256]), ("generator/final_norm/beta:0", [256]), ("generator/final_conv/kernel:0", [3, 3, 256, 3]), ("generator/final_conv/bias:0", [3]), ] actual_variables = [(v.name, v.shape.as_list()) for v in tf.trainable_variables()] for a in actual_variables: logging.info(a) for a, e in zip(actual_variables, expected_variables): logging.info("actual: %s, expected: %s", a, e) self.assertEqual(a, e) self.assertEqual(len(actual_variables), len(expected_variables)) def testDefaultGeneratorWithConditionalBatchNorm(self): with tf.Graph().as_default(): # Batch size 8, 32x32x3 images, 10 classes. z = tf.zeros((8, 128)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 10) generator = resnet_cifar.Generator( image_shape=(32, 32, 3), batch_norm_fn=arch_ops.conditional_batch_norm) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [8, 32, 32, 3]) expected_variables = [ # Name and shape. ("generator/fc_noise/kernel:0", [128, 4096]), ("generator/fc_noise/bias:0", [4096]), ("generator/B1/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv_shortcut/bias:0", [256]), ("generator/B1/bn1/condition/gamma/kernel:0", [10, 256]), ("generator/B1/bn1/condition/beta/kernel:0", [10, 256]), ("generator/B1/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv1/bias:0", [256]), ("generator/B1/bn2/condition/gamma/kernel:0", [10, 256]), ("generator/B1/bn2/condition/beta/kernel:0", [10, 256]), ("generator/B1/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B1/same_conv2/bias:0", [256]), ("generator/B2/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv_shortcut/bias:0", [256]), ("generator/B2/bn1/condition/gamma/kernel:0", [10, 256]), ("generator/B2/bn1/condition/beta/kernel:0", [10, 256]), ("generator/B2/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv1/bias:0", [256]), ("generator/B2/bn2/condition/gamma/kernel:0", [10, 256]), ("generator/B2/bn2/condition/beta/kernel:0", [10, 256]), ("generator/B2/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B2/same_conv2/bias:0", [256]), ("generator/B3/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv_shortcut/bias:0", [256]), ("generator/B3/bn1/condition/gamma/kernel:0", [10, 256]), ("generator/B3/bn1/condition/beta/kernel:0", [10, 256]), ("generator/B3/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv1/bias:0", [256]), ("generator/B3/bn2/condition/gamma/kernel:0", [10, 256]), ("generator/B3/bn2/condition/beta/kernel:0", [10, 256]), ("generator/B3/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B3/same_conv2/bias:0", [256]), ("generator/final_norm/condition/gamma/kernel:0", [10, 256]), ("generator/final_norm/condition/beta/kernel:0", [10, 256]), ("generator/final_conv/kernel:0", [3, 3, 256, 3]), ("generator/final_conv/bias:0", [3]), ] actual_variables = [(v.name, v.shape.as_list()) for v in tf.trainable_variables()] for a in actual_variables: logging.info(a) for a, e in zip(actual_variables, expected_variables): logging.info("actual: %s, expected: %s", a, e) self.assertEqual(a, e) self.assertEqual(len(actual_variables), len(expected_variables)) def testDefaultGeneratorWithSelfModulatedBatchNorm(self): with tf.Graph().as_default(): # Batch size 8, 32x32x3 images, 10 classes. z = tf.zeros((8, 128)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 10) generator = resnet_cifar.Generator( image_shape=(32, 32, 3), batch_norm_fn=arch_ops.self_modulated_batch_norm) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [8, 32, 32, 3]) expected_variables = [ # Name and shape. ("generator/fc_noise/kernel:0", [128, 4096]), ("generator/fc_noise/bias:0", [4096]), ("generator/B1/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv_shortcut/bias:0", [256]), ("generator/B1/bn1/sbn/hidden/kernel:0", [128, 32]), ("generator/B1/bn1/sbn/hidden/bias:0", [32]), ("generator/B1/bn1/sbn/gamma/kernel:0", [32, 256]), ("generator/B1/bn1/sbn/gamma/bias:0", [256]), ("generator/B1/bn1/sbn/beta/kernel:0", [32, 256]), ("generator/B1/bn1/sbn/beta/bias:0", [256]), ("generator/B1/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv1/bias:0", [256]), ("generator/B1/bn2/sbn/hidden/kernel:0", [128, 32]), ("generator/B1/bn2/sbn/hidden/bias:0", [32]), ("generator/B1/bn2/sbn/gamma/kernel:0", [32, 256]), ("generator/B1/bn2/sbn/gamma/bias:0", [256]), ("generator/B1/bn2/sbn/beta/kernel:0", [32, 256]), ("generator/B1/bn2/sbn/beta/bias:0", [256]), ("generator/B1/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B1/same_conv2/bias:0", [256]), ("generator/B2/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv_shortcut/bias:0", [256]), ("generator/B2/bn1/sbn/hidden/kernel:0", [128, 32]), ("generator/B2/bn1/sbn/hidden/bias:0", [32]), ("generator/B2/bn1/sbn/gamma/kernel:0", [32, 256]), ("generator/B2/bn1/sbn/gamma/bias:0", [256]), ("generator/B2/bn1/sbn/beta/kernel:0", [32, 256]), ("generator/B2/bn1/sbn/beta/bias:0", [256]), ("generator/B2/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv1/bias:0", [256]), ("generator/B2/bn2/sbn/hidden/kernel:0", [128, 32]), ("generator/B2/bn2/sbn/hidden/bias:0", [32]), ("generator/B2/bn2/sbn/gamma/kernel:0", [32, 256]), ("generator/B2/bn2/sbn/gamma/bias:0", [256]), ("generator/B2/bn2/sbn/beta/kernel:0", [32, 256]), ("generator/B2/bn2/sbn/beta/bias:0", [256]), ("generator/B2/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B2/same_conv2/bias:0", [256]), ("generator/B3/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv_shortcut/bias:0", [256]), ("generator/B3/bn1/sbn/hidden/kernel:0", [128, 32]), ("generator/B3/bn1/sbn/hidden/bias:0", [32]), ("generator/B3/bn1/sbn/gamma/kernel:0", [32, 256]), ("generator/B3/bn1/sbn/gamma/bias:0", [256]), ("generator/B3/bn1/sbn/beta/kernel:0", [32, 256]), ("generator/B3/bn1/sbn/beta/bias:0", [256]), ("generator/B3/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv1/bias:0", [256]), ("generator/B3/bn2/sbn/hidden/kernel:0", [128, 32]), ("generator/B3/bn2/sbn/hidden/bias:0", [32]), ("generator/B3/bn2/sbn/gamma/kernel:0", [32, 256]), ("generator/B3/bn2/sbn/gamma/bias:0", [256]), ("generator/B3/bn2/sbn/beta/kernel:0", [32, 256]), ("generator/B3/bn2/sbn/beta/bias:0", [256]), ("generator/B3/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B3/same_conv2/bias:0", [256]), ("generator/final_norm/sbn/hidden/kernel:0", [128, 32]), ("generator/final_norm/sbn/hidden/bias:0", [32]), ("generator/final_norm/sbn/gamma/kernel:0", [32, 256]), ("generator/final_norm/sbn/gamma/bias:0", [256]), ("generator/final_norm/sbn/beta/kernel:0", [32, 256]), ("generator/final_norm/sbn/beta/bias:0", [256]), ("generator/final_conv/kernel:0", [3, 3, 256, 3]), ("generator/final_conv/bias:0", [3]), ] actual_variables = [(v.name, v.shape.as_list()) for v in tf.trainable_variables()] for a in actual_variables: logging.info(a) for a, e in zip(actual_variables, expected_variables): logging.info("actual: %s, expected: %s", a, e) self.assertEqual(a, e) self.assertEqual(len(actual_variables), len(expected_variables)) def testDefaultGeneratorWithSpectralNorm(self): with tf.Graph().as_default(): # Batch size 8, 32x32x3 images, 10 classes. z = tf.zeros((8, 128)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 10) generator = resnet_cifar.Generator( image_shape=(32, 32, 3), spectral_norm=True) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [8, 32, 32, 3]) expected_variables = [ # Name and shape. ("generator/fc_noise/kernel:0", [128, 4096]), ("generator/fc_noise/kernel/u_var:0", [128, 1]), ("generator/fc_noise/bias:0", [4096]), ("generator/B1/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv_shortcut/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B1/up_conv_shortcut/bias:0", [256]), ("generator/B1/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B1/up_conv1/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B1/up_conv1/bias:0", [256]), ("generator/B1/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B1/same_conv2/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B1/same_conv2/bias:0", [256]), ("generator/B2/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv_shortcut/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B2/up_conv_shortcut/bias:0", [256]), ("generator/B2/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B2/up_conv1/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B2/up_conv1/bias:0", [256]), ("generator/B2/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B2/same_conv2/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B2/same_conv2/bias:0", [256]), ("generator/B3/up_conv_shortcut/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv_shortcut/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B3/up_conv_shortcut/bias:0", [256]), ("generator/B3/up_conv1/kernel:0", [3, 3, 256, 256]), ("generator/B3/up_conv1/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B3/up_conv1/bias:0", [256]), ("generator/B3/same_conv2/kernel:0", [3, 3, 256, 256]), ("generator/B3/same_conv2/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/B3/same_conv2/bias:0", [256]), ("generator/final_conv/kernel:0", [3, 3, 256, 3]), ("generator/final_conv/kernel/u_var:0", [3 * 3 * 256, 1]), ("generator/final_conv/bias:0", [3]), ] actual_variables = [(v.name, v.shape.as_list()) for v in tf.global_variables()] for a in actual_variables: logging.info(a) for a, e in zip(actual_variables, expected_variables): logging.info("actual: %s, expected: %s", a, e) self.assertEqual(a, e) self.assertEqual(len(actual_variables), len(expected_variables)) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/resnet_norm_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of InfoGAN generator and discriminator architectures. Details are available in https://arxiv.org/pdf/1606.03657.pdf. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import abstract_arch from compare_gan.architectures.arch_ops import batch_norm from compare_gan.architectures.arch_ops import conv2d from compare_gan.architectures.arch_ops import deconv2d from compare_gan.architectures.arch_ops import linear from compare_gan.architectures.arch_ops import lrelu import tensorflow as tf class Generator(abstract_arch.AbstractGenerator): """Generator architecture based on InfoGAN.""" def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ del y h, w, c = self._image_shape bs = z.shape.as_list()[0] net = linear(z, 1024, scope="g_fc1") net = lrelu(batch_norm(net, is_training=is_training, name="g_bn1")) net = linear(net, 128 * (h // 4) * (w // 4), scope="g_fc2") net = lrelu(batch_norm(net, is_training=is_training, name="g_bn2")) net = tf.reshape(net, [bs, h // 4, w // 4, 128]) net = deconv2d(net, [bs, h // 2, w // 2, 64], 4, 4, 2, 2, name="g_dc3") net = lrelu(batch_norm(net, is_training=is_training, name="g_bn3")) net = deconv2d(net, [bs, h, w, c], 4, 4, 2, 2, name="g_dc4") out = tf.nn.sigmoid(net) return out class Discriminator(abstract_arch.AbstractDiscriminator): """Discriminator architecture based on InfoGAN.""" def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ use_sn = self._spectral_norm batch_size = x.shape.as_list()[0] # Resulting shape: [bs, h/2, w/2, 64]. net = lrelu(conv2d(x, 64, 4, 4, 2, 2, name="d_conv1", use_sn=use_sn)) # Resulting shape: [bs, h/4, w/4, 128]. net = conv2d(net, 128, 4, 4, 2, 2, name="d_conv2", use_sn=use_sn) net = self.batch_norm(net, y=y, is_training=is_training, name="d_bn2") net = lrelu(net) # Resulting shape: [bs, h * w * 8]. net = tf.reshape(net, [batch_size, -1]) # Resulting shape: [bs, 1024]. net = linear(net, 1024, scope="d_fc3", use_sn=use_sn) net = self.batch_norm(net, y=y, is_training=is_training, name="d_bn3") net = lrelu(net) # Resulting shape: [bs, 1]. out_logit = linear(net, 1, scope="d_fc4", use_sn=use_sn) out = tf.nn.sigmoid(out_logit) return out, out_logit, net
compare_gan-master
compare_gan/architectures/infogan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A deep neural architecture with residual blocks and skip connections. It contains 5 residual blocks in both the generator and discriminator and supports 128x128 resolution. Details can be found in "Improved Training of Wasserstein GANs", Gulrajani I. et al. 2017. The related code is available at https://github.com/igul222/improved_wgan_training/blob/master/gan_64x64.py. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import arch_ops as ops from compare_gan.architectures import resnet_ops import numpy as np from six.moves import range import tensorflow as tf class Generator(resnet_ops.ResNetGenerator): """ResNet generator consisting of 5 blocks, outputs 128x128x3 resolution.""" def __init__(self, ch=64, channels=(8, 8, 4, 4, 2, 1), **kwargs): super(Generator, self).__init__(**kwargs) self._ch = ch self._channels = channels def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ # Each block upscales by a factor of 2. seed_size = 4 image_size = self._image_shape[0] # Map noise to the actual seed. net = ops.linear( z, self._ch * self._channels[0] * seed_size * seed_size, scope="fc_noise") # Reshape the seed to be a rank-4 Tensor. net = tf.reshape( net, [-1, seed_size, seed_size, self._ch * self._channels[0]], name="fc_reshaped") up_layers = np.log2(float(image_size) / seed_size) if not up_layers.is_integer(): raise ValueError("log2({}/{}) must be an integer.".format( image_size, seed_size)) if up_layers < 0 or up_layers > 5: raise ValueError("Invalid image_size {}.".format(image_size)) up_layers = int(up_layers) for block_idx in range(5): block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=self._ch * self._channels[block_idx], out_channels=self._ch * self._channels[block_idx + 1], scale="up" if block_idx < up_layers else "none") net = block(net, z=z, y=y, is_training=is_training) net = self.batch_norm( net, z=z, y=y, is_training=is_training, name="final_norm") net = tf.nn.relu(net) net = ops.conv2d(net, output_dim=self._image_shape[2], k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv") net = tf.nn.sigmoid(net) return net class Discriminator(resnet_ops.ResNetDiscriminator): """ResNet5 discriminator, 5 blocks, supporting 128x128x3 and 128x128x1.""" def __init__(self, ch=64, channels=(1, 2, 4, 4, 8, 8), **kwargs): super(Discriminator, self).__init__(**kwargs) self._ch = ch self._channels = channels def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ resnet_ops.validate_image_inputs(x) colors = x.shape[3].value if colors not in [1, 3]: raise ValueError("Number of color channels not supported: {}".format( colors)) block = self._resnet_block( name="B0", in_channels=colors, out_channels=self._ch, scale="down") output = block(x, z=None, y=y, is_training=is_training) for block_idx in range(5): block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=self._ch * self._channels[block_idx], out_channels=self._ch * self._channels[block_idx + 1], scale="down") output = block(output, z=None, y=y, is_training=is_training) output = tf.nn.relu(output) pre_logits = tf.reduce_mean(output, axis=[1, 2]) out_logit = ops.linear(pre_logits, 1, scope="disc_final_fc", use_sn=self._spectral_norm) out = tf.nn.sigmoid(out_logit) return out, out_logit, pre_logits
compare_gan-master
compare_gan/architectures/resnet5.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests weight initialization ops using ResNet5 architecture.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import resnet5 from compare_gan.gans import consts import gin import tensorflow as tf class ResNetInitTest(tf.test.TestCase): def setUp(self): super(ResNetInitTest, self).setUp() gin.clear_config() def testInitializersOldDefault(self): valid_initalizer = [ "kernel/Initializer/random_normal", "bias/Initializer/Const", # truncated_normal is the old default for conv2d. "kernel/Initializer/truncated_normal", "bias/Initializer/Const", "beta/Initializer/zeros", "gamma/Initializer/ones", ] valid_op_names = "/({}):0$".format("|".join(valid_initalizer)) with tf.Graph().as_default(): z = tf.zeros((2, 128)) fake_image = resnet5.Generator(image_shape=(128, 128, 3))( z, y=None, is_training=True) resnet5.Discriminator()(fake_image, y=None, is_training=True) for var in tf.trainable_variables(): op_name = var.initializer.inputs[1].name self.assertRegex(op_name, valid_op_names) def testInitializersRandomNormal(self): gin.bind_parameter("weights.initializer", consts.NORMAL_INIT) valid_initalizer = [ "kernel/Initializer/random_normal", "bias/Initializer/Const", "kernel/Initializer/random_normal", "bias/Initializer/Const", "beta/Initializer/zeros", "gamma/Initializer/ones", ] valid_op_names = "/({}):0$".format("|".join(valid_initalizer)) with tf.Graph().as_default(): z = tf.zeros((2, 128)) fake_image = resnet5.Generator(image_shape=(128, 128, 3))( z, y=None, is_training=True) resnet5.Discriminator()(fake_image, y=None, is_training=True) for var in tf.trainable_variables(): op_name = var.initializer.inputs[1].name self.assertRegex(op_name, valid_op_names) def testInitializersTruncatedNormal(self): gin.bind_parameter("weights.initializer", consts.TRUNCATED_INIT) valid_initalizer = [ "kernel/Initializer/truncated_normal", "bias/Initializer/Const", "kernel/Initializer/truncated_normal", "bias/Initializer/Const", "beta/Initializer/zeros", "gamma/Initializer/ones", ] valid_op_names = "/({}):0$".format("|".join(valid_initalizer)) with tf.Graph().as_default(): z = tf.zeros((2, 128)) fake_image = resnet5.Generator(image_shape=(128, 128, 3))( z, y=None, is_training=True) resnet5.Discriminator()(fake_image, y=None, is_training=True) for var in tf.trainable_variables(): op_name = var.initializer.inputs[1].name self.assertRegex(op_name, valid_op_names) def testGeneratorInitializersOrthogonal(self): gin.bind_parameter("weights.initializer", consts.ORTHOGONAL_INIT) valid_initalizer = [ "kernel/Initializer/mul_1", "bias/Initializer/Const", "kernel/Initializer/mul_1", "bias/Initializer/Const", "beta/Initializer/zeros", "gamma/Initializer/ones", ] valid_op_names = "/({}):0$".format("|".join(valid_initalizer)) with tf.Graph().as_default(): z = tf.zeros((2, 128)) fake_image = resnet5.Generator(image_shape=(128, 128, 3))( z, y=None, is_training=True) resnet5.Discriminator()(fake_image, y=None, is_training=True) for var in tf.trainable_variables(): op_name = var.initializer.inputs[1].name self.assertRegex(op_name, valid_op_names) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/resnet_init_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Resnet generator and discriminator for CIFAR. Based on Table 4 from "Spectral Normalization for Generative Adversarial Networks", Miyato T. et al., 2018. [https://arxiv.org/pdf/1802.05957.pdf]. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import arch_ops as ops from compare_gan.architectures import resnet_ops import gin from six.moves import range import tensorflow as tf @gin.configurable class Generator(resnet_ops.ResNetGenerator): """ResNet generator, 4 blocks, supporting 32x32 resolution.""" def __init__(self, hierarchical_z=False, embed_z=False, embed_y=False, **kwargs): """Constructor for the ResNet Cifar generator. Args: hierarchical_z: Split z into chunks and only give one chunk to each. Each chunk will also be concatenated to y, the one hot encoded labels. embed_z: If True use a learnable embedding of z that is used instead. The embedding will have the length of z. embed_y: If True use a learnable embedding of y that is used instead. The embedding will have the length of z (not y!). **kwargs: additional arguments past on to ResNetGenerator. """ super(Generator, self).__init__(**kwargs) self._hierarchical_z = hierarchical_z self._embed_z = embed_z self._embed_y = embed_y def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size, 32, 32, colors] with values in [0, 1]. """ assert self._image_shape[0] == 32 assert self._image_shape[1] == 32 num_blocks = 3 z_dim = z.shape[1].value if self._embed_z: z = ops.linear(z, z_dim, scope="embed_z", use_sn=self._spectral_norm) if self._embed_y: y = ops.linear(y, z_dim, scope="embed_y", use_sn=self._spectral_norm) y_per_block = num_blocks * [y] if self._hierarchical_z: z_per_block = tf.split(z, num_blocks + 1, axis=1) z0, z_per_block = z_per_block[0], z_per_block[1:] if y is not None: y_per_block = [tf.concat([zi, y], 1) for zi in z_per_block] else: z0 = z z_per_block = num_blocks * [z] output = ops.linear(z0, 4 * 4 * 256, scope="fc_noise", use_sn=self._spectral_norm) output = tf.reshape(output, [-1, 4, 4, 256], name="fc_reshaped") for block_idx in range(3): block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=256, out_channels=256, scale="up") output = block( output, z=z_per_block[block_idx], y=y_per_block[block_idx], is_training=is_training) # Final processing of the output. output = self.batch_norm( output, z=z, y=y, is_training=is_training, name="final_norm") output = tf.nn.relu(output) output = ops.conv2d(output, output_dim=self._image_shape[2], k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv", use_sn=self._spectral_norm,) return tf.nn.sigmoid(output) @gin.configurable class Discriminator(resnet_ops.ResNetDiscriminator): """ResNet discriminator, 4 blocks, supporting 32x32 with 1 or 3 colors.""" def __init__(self, project_y=False, **kwargs): super(Discriminator, self).__init__(**kwargs) self._project_y = project_y def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, 32, 32, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ resnet_ops.validate_image_inputs(x) colors = x.shape[3].value if colors not in [1, 3]: raise ValueError("Number of color channels not supported: {}".format( colors)) output = x for block_idx in range(4): block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=colors if block_idx == 0 else 128, out_channels=128, scale="down" if block_idx <= 1 else "none") output = block(output, z=None, y=y, is_training=is_training) # Final part - ReLU output = tf.nn.relu(output) h = tf.reduce_mean(output, axis=[1, 2]) out_logit = ops.linear(h, 1, scope="disc_final_fc", use_sn=self._spectral_norm) if self._project_y: if y is None: raise ValueError("You must provide class information y to project.") embedded_y = ops.linear(y, 128, use_bias=False, scope="embedding_fc", use_sn=self._spectral_norm) out_logit += tf.reduce_sum(embedded_y * h, axis=1, keepdims=True) out = tf.nn.sigmoid(out_logit) return out, out_logit, h
compare_gan-master
compare_gan/architectures/resnet_cifar.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines interfaces for generator and discriminator networks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from compare_gan import utils import gin import six import tensorflow as tf @six.add_metaclass(abc.ABCMeta) class _Module(object): """Base class for architectures. Long term this will be replaced by `tf.Module` in TF 2.0. """ def __init__(self, name): self._name = name @property def name(self): return self._name @property def trainable_variables(self): return [var for var in tf.trainable_variables() if self._name in var.name] @gin.configurable("G", blacklist=["name", "image_shape"]) class AbstractGenerator(_Module): """Interface for generator architectures.""" def __init__(self, name="generator", image_shape=None, batch_norm_fn=None, spectral_norm=False): """Constructor for all generator architectures. Args: name: Scope name of the generator. image_shape: Image shape to be generated, [height, width, colors]. batch_norm_fn: Function for batch normalization or None. spectral_norm: If True use spectral normalization for all weights. """ super(AbstractGenerator, self).__init__(name=name) self._name = name self._image_shape = image_shape self._batch_norm_fn = batch_norm_fn self._spectral_norm = spectral_norm def __call__(self, z, y, is_training, reuse=tf.AUTO_REUSE): with tf.variable_scope(self.name, values=[z, y], reuse=reuse): outputs = self.apply(z=z, y=y, is_training=is_training) return outputs def batch_norm(self, inputs, **kwargs): if self._batch_norm_fn is None: return inputs args = kwargs.copy() args["inputs"] = inputs if "use_sn" not in args: args["use_sn"] = self._spectral_norm return utils.call_with_accepted_args(self._batch_norm_fn, **args) @abc.abstractmethod def apply(self, z, y, is_training): """Apply the generator on a input. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Generated images of shape [batch_size] + self.image_shape. """ @gin.configurable("D", blacklist=["name"]) class AbstractDiscriminator(_Module): """Interface for discriminator architectures.""" def __init__(self, name="discriminator", batch_norm_fn=None, layer_norm=False, spectral_norm=False): super(AbstractDiscriminator, self).__init__(name=name) self._name = name self._batch_norm_fn = batch_norm_fn self._layer_norm = layer_norm self._spectral_norm = spectral_norm def __call__(self, x, y, is_training, reuse=tf.AUTO_REUSE): with tf.variable_scope(self.name, values=[x, y], reuse=reuse): outputs = self.apply(x=x, y=y, is_training=is_training) return outputs def batch_norm(self, inputs, **kwargs): if self._batch_norm_fn is None: return inputs args = kwargs.copy() args["inputs"] = inputs if "use_sn" not in args: args["use_sn"] = self._spectral_norm return utils.call_with_accepted_args(self._batch_norm_fn, **args) @abc.abstractmethod def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """
compare_gan-master
compare_gan/architectures/abstract_arch.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8
compare_gan-master
compare_gan/architectures/__init__.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ResNet specific operations. Defines the default ResNet generator and discriminator blocks and some helper operations such as unpooling. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from compare_gan.architectures import abstract_arch from compare_gan.architectures import arch_ops as ops from six.moves import range import tensorflow as tf def unpool(value, name="unpool"): """Unpooling operation. N-dimensional version of the unpooling operation from https://www.robots.ox.ac.uk/~vgg/rg/papers/Dosovitskiy_Learning_to_Generate_2015_CVPR_paper.pdf Taken from: https://github.com/tensorflow/tensorflow/issues/2169 Args: value: a Tensor of shape [b, d0, d1, ..., dn, ch] name: name of the op Returns: A Tensor of shape [b, 2*d0, 2*d1, ..., 2*dn, ch] """ with tf.name_scope(name) as scope: sh = value.get_shape().as_list() dim = len(sh[1:-1]) out = (tf.reshape(value, [-1] + sh[-dim:])) for i in range(dim, 0, -1): out = tf.concat([out, tf.zeros_like(out)], i) out_size = [-1] + [s * 2 for s in sh[1:-1]] + [sh[-1]] out = tf.reshape(out, out_size, name=scope) return out def validate_image_inputs(inputs, validate_power2=True): inputs.get_shape().assert_has_rank(4) inputs.get_shape()[1:3].assert_is_fully_defined() if inputs.get_shape()[1] != inputs.get_shape()[2]: raise ValueError("Input tensor does not have equal width and height: ", inputs.get_shape()[1:3]) width = inputs.get_shape().as_list()[1] if validate_power2 and math.log(width, 2) != int(math.log(width, 2)): raise ValueError("Input tensor `width` is not a power of 2: ", width) class ResNetBlock(object): """ResNet block with options for various normalizations.""" def __init__(self, name, in_channels, out_channels, scale, is_gen_block, layer_norm=False, spectral_norm=False, batch_norm=None): """Constructs a new ResNet block. Args: name: Scope name for the resent block. in_channels: Integer, the input channel size. out_channels: Integer, the output channel size. scale: Whether or not to scale up or down, choose from "up", "down" or "none". is_gen_block: Boolean, deciding whether this is a generator or discriminator block. layer_norm: Apply layer norm before both convolutions. spectral_norm: Use spectral normalization for all weights. batch_norm: Function for batch normalization. """ assert scale in ["up", "down", "none"] self._name = name self._in_channels = in_channels self._out_channels = out_channels self._scale = scale # In SN paper, if they upscale in generator they do this in the first conv. # For discriminator downsampling happens after second conv. self._scale1 = scale if is_gen_block else "none" self._scale2 = "none" if is_gen_block else scale self._layer_norm = layer_norm self._spectral_norm = spectral_norm self.batch_norm = batch_norm def __call__(self, inputs, z, y, is_training): return self.apply(inputs=inputs, z=z, y=y, is_training=is_training) def _get_conv(self, inputs, in_channels, out_channels, scale, suffix, kernel_size=(3, 3), strides=(1, 1)): """Performs a convolution in the ResNet block.""" if inputs.get_shape().as_list()[-1] != in_channels: raise ValueError("Unexpected number of input channels.") if scale not in ["up", "down", "none"]: raise ValueError( "Scale: got {}, expected 'up', 'down', or 'none'.".format(scale)) outputs = inputs if scale == "up": outputs = unpool(outputs) outputs = ops.conv2d( outputs, output_dim=out_channels, k_h=kernel_size[0], k_w=kernel_size[1], d_h=strides[0], d_w=strides[1], use_sn=self._spectral_norm, name="{}_{}".format("same" if scale == "none" else scale, suffix)) if scale == "down": outputs = tf.nn.pool(outputs, [2, 2], "AVG", "SAME", strides=[2, 2], name="pool_%s" % suffix) return outputs def apply(self, inputs, z, y, is_training): """"ResNet block containing possible down/up sampling, shared for G / D. Args: inputs: a 3d input tensor of feature map. z: the latent vector for potential self-modulation. Can be None if use_sbn is set to False. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, whether or notthis is called during the training. Returns: output: a 3d output tensor of feature map. """ if inputs.get_shape().as_list()[-1] != self._in_channels: raise ValueError("Unexpected number of input channels.") with tf.variable_scope(self._name, values=[inputs]): output = inputs shortcut = self._get_conv( output, self._in_channels, self._out_channels, self._scale, suffix="conv_shortcut") output = self.batch_norm( output, z=z, y=y, is_training=is_training, name="bn1") if self._layer_norm: output = ops.layer_norm(output, is_training=is_training, scope="ln1") output = tf.nn.relu(output) output = self._get_conv( output, self._in_channels, self._out_channels, self._scale1, suffix="conv1") output = self.batch_norm( output, z=z, y=y, is_training=is_training, name="bn2") if self._layer_norm: output = ops.layer_norm(output, is_training=is_training, scope="ln2") output = tf.nn.relu(output) output = self._get_conv( output, self._out_channels, self._out_channels, self._scale2, suffix="conv2") # Combine skip-connection with the convolved part. output += shortcut return output class ResNetGenerator(abstract_arch.AbstractGenerator): """Abstract base class for generators based on the ResNet architecture.""" def _resnet_block(self, name, in_channels, out_channels, scale): """ResNet block for the generator.""" if scale not in ["up", "none"]: raise ValueError( "Unknown generator ResNet block scaling: {}.".format(scale)) return ResNetBlock( name=name, in_channels=in_channels, out_channels=out_channels, scale=scale, is_gen_block=True, spectral_norm=self._spectral_norm, batch_norm=self.batch_norm) class ResNetDiscriminator(abstract_arch.AbstractDiscriminator): """Abstract base class for discriminators based on the ResNet architecture.""" def _resnet_block(self, name, in_channels, out_channels, scale): """ResNet block for the generator.""" if scale not in ["down", "none"]: raise ValueError( "Unknown discriminator ResNet block scaling: {}.".format(scale)) return ResNetBlock( name=name, in_channels=in_channels, out_channels=out_channels, scale=scale, is_gen_block=False, layer_norm=self._layer_norm, spectral_norm=self._spectral_norm, batch_norm=self.batch_norm)
compare_gan-master
compare_gan/architectures/resnet_ops.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test whether resnet_biggan matches the original BigGAN architecture. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan import utils from compare_gan.architectures import arch_ops from compare_gan.architectures import resnet_biggan import gin import numpy as np import tensorflow as tf def guess_initializer(var, graph=None): """Helper function to guess the initializer of a variable. The function looks at the operations in the initializer name space for the variable (e.g. my_scope/my_var_name/Initializer/*). The TF core initializers have characteristic sets of operations that can be used to determine the initializer. Args: var: `tf.Variable`. The function will use the name to look for initializer operations in the same scope. graph: Optional `tf.Graph` that contains the variable. If None the default graph is used. Returns: Tuple of the name of the guessed initializer. """ if graph is None: graph = tf.get_default_graph() prefix = var.op.name + "/Initializer" ops = [op for op in graph.get_operations() if op.name.startswith(prefix)] assert ops, "No operations found for prefix {}".format(prefix) op_names = [op.name[len(prefix) + 1:] for op in ops] if len(op_names) == 1: if op_names[0] == "Const": value = ops[0].get_attr("value").float_val[0] if value == 0.0: return "zeros" if np.isclose(value, 1.0): return "ones" return "constant" return op_names[0] # ones or zeros if "Qr" in op_names and "DiagPart" in op_names: return "orthogonal" if "random_uniform" in op_names: return "glorot_uniform" stddev_ops = [op for op in ops if op.name.endswith("stddev")] if stddev_ops: assert len(stddev_ops) == 1 stddev = stddev_ops[0].get_attr("value").float_val[0] else: stddev = None if "random_normal" in op_names: return "random_normal" if "truncated_normal" in op_names: if len(str(stddev)) > 5: return "glorot_normal" return "truncated_normal" class ResNet5BigGanTest(tf.test.TestCase): def setUp(self): super(ResNet5BigGanTest, self).setUp() gin.clear_config() def testNumberOfParameters(self): with tf.Graph().as_default(): batch_size = 16 z = tf.zeros((batch_size, 120)) y = tf.one_hot(tf.ones((batch_size,), dtype=tf.int32), 1000) generator = resnet_biggan.Generator( image_shape=(128, 128, 3), batch_norm_fn=arch_ops.conditional_batch_norm) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [batch_size, 128, 128, 3]) discriminator = resnet_biggan.Discriminator() predictions = discriminator(fake_images, y, is_training=True) self.assertLen(predictions, 3) t_vars = tf.trainable_variables() g_vars = [var for var in t_vars if "generator" in var.name] d_vars = [var for var in t_vars if "discriminator" in var.name] g_param_overview = utils.get_parameter_overview(g_vars, limit=None) d_param_overview = utils.get_parameter_overview(d_vars, limit=None) logging.info("Generator variables:\n%s", g_param_overview) logging.info("Discriminator variables:\n%s", d_param_overview) for v in g_vars: parts = v.op.name.split("/") layer, var_name = parts[-2], parts[-1] layers_with_bias = {"fc_noise", "up_conv_shortcut", "up_conv1", "same_conv2", "final_conv"} # No biases in conditional BN or self-attention. if layer not in layers_with_bias: self.assertNotEqual(var_name, "bias", msg=str(v)) # Batch norm variables. if parts[-3] == "condition": if parts[-4] == "final_bn": self.assertEqual(var_name, "kernel", msg=str(v)) self.assertEqual(v.shape.as_list(), [1, 1, 1, 96], msg=str(v)) else: self.assertEqual(var_name, "kernel", msg=str(v)) self.assertEqual(v.shape[0].value, 148, msg=str(v)) # Embedding layer. if layer == "embed_y": self.assertEqual(var_name, "kernel", msg=str(v)) self.assertAllEqual(v.shape.as_list(), [1000, 128], msg=str(v)) # Shortcut connections use 1x1 convolution. if layer == "up_conv_shortcut" and var_name == "kernel": self.assertEqual(v.shape.as_list()[:2], [1, 1], msg=str(v)) g_num_weights = sum([v.get_shape().num_elements() for v in g_vars]) self.assertEqual(g_num_weights, 70433988) for v in d_vars: parts = v.op.name.split("/") layer, var_name = parts[-2], parts[-1] layers_with_bias = {"down_conv_shortcut", "same_conv1", "down_conv2", "same_conv_shortcut", "same_conv2", "final_fc"} # No biases in conditional BN or self-attention. if layer not in layers_with_bias: self.assertNotEqual(var_name, "bias", msg=str(v)) # no Shortcut in last block. if parts[-3] == "B6": self.assertNotEqual(layer, "same_shortcut", msg=str(v)) d_num_weights = sum([v.get_shape().num_elements() for v in d_vars]) self.assertEqual(d_num_weights, 87982370) def testInitializers(self): gin.bind_parameter("weights.initializer", "orthogonal") with tf.Graph().as_default(): z = tf.zeros((8, 120)) y = tf.one_hot(tf.ones((8,), dtype=tf.int32), 1000) generator = resnet_biggan.Generator( image_shape=(128, 128, 3), batch_norm_fn=arch_ops.conditional_batch_norm) fake_images = generator(z, y=y, is_training=True, reuse=False) discriminator = resnet_biggan.Discriminator() discriminator(fake_images, y, is_training=True) for v in tf.trainable_variables(): parts = v.op.name.split("/") layer, var_name = parts[-2], parts[-1] initializer_name = guess_initializer(v) logging.info("%s => %s", v.op.name, initializer_name) if layer == "embedding_fc" and var_name == "kernel": self.assertEqual(initializer_name, "glorot_normal") elif layer == "non_local_block" and var_name == "sigma": self.assertEqual(initializer_name, "zeros") elif layer == "final_norm" and var_name == "gamma": self.assertEqual(initializer_name, "ones") elif layer == "final_norm" and var_name == "beta": self.assertEqual(initializer_name, "zeros") elif var_name == "kernel": self.assertEqual(initializer_name, "orthogonal") elif var_name == "bias": self.assertEqual(initializer_name, "zeros") else: self.fail("Unknown variables {}".format(v)) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/resnet_biggan_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of DCGAN generator and discriminator architectures. Details are available in https://arxiv.org/abs/1511.06434. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import abstract_arch from compare_gan.architectures.arch_ops import conv2d from compare_gan.architectures.arch_ops import deconv2d from compare_gan.architectures.arch_ops import linear from compare_gan.architectures.arch_ops import lrelu import numpy as np import tensorflow as tf def conv_out_size_same(size, stride): return int(np.ceil(float(size) / float(stride))) class Generator(abstract_arch.AbstractGenerator): """DCGAN generator. Details are available at https://arxiv.org/abs/1511.06434. Notable changes include BatchNorm in the generator, ReLu instead of LeakyReLu and ReLu in the generator, except for output which uses tanh. """ def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ gf_dim = 64 # Dimension of filters in first convolutional layer. bs = z.shape[0].value s_h, s_w, colors = self._image_shape s_h2, s_w2 = conv_out_size_same(s_h, 2), conv_out_size_same(s_w, 2) s_h4, s_w4 = conv_out_size_same(s_h2, 2), conv_out_size_same(s_w2, 2) s_h8, s_w8 = conv_out_size_same(s_h4, 2), conv_out_size_same(s_w4, 2) s_h16, s_w16 = conv_out_size_same(s_h8, 2), conv_out_size_same(s_w8, 2) net = linear(z, gf_dim * 8 *s_h16 * s_w16, scope="g_fc1") net = tf.reshape(net, [-1, s_h16, s_w16, gf_dim * 8]) net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn1") net = tf.nn.relu(net) net = deconv2d(net, [bs, s_h8, s_w8, gf_dim*4], 5, 5, 2, 2, name="g_dc1") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn2") net = tf.nn.relu(net) net = deconv2d(net, [bs, s_h4, s_w4, gf_dim*2], 5, 5, 2, 2, name="g_dc2") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn3") net = tf.nn.relu(net) net = deconv2d(net, [bs, s_h2, s_w2, gf_dim*1], 5, 5, 2, 2, name="g_dc3") net = self.batch_norm(net, z=z, y=y, is_training=is_training, name="g_bn4") net = tf.nn.relu(net) net = deconv2d(net, [bs, s_h, s_w, colors], 5, 5, 2, 2, name="g_dc4") net = 0.5 * tf.nn.tanh(net) + 0.5 return net class Discriminator(abstract_arch.AbstractDiscriminator): """DCGAN discriminator. Details are available at https://arxiv.org/abs/1511.06434. Notable changes include BatchNorm in the discriminator and LeakyReLU for all layers. """ def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ bs = x.shape[0].value df_dim = 64 # Dimension of filters in the first convolutional layer. net = lrelu(conv2d(x, df_dim, 5, 5, 2, 2, name="d_conv1", use_sn=self._spectral_norm)) net = conv2d(net, df_dim * 2, 5, 5, 2, 2, name="d_conv2", use_sn=self._spectral_norm) net = self.batch_norm(net, y=y, is_training=is_training, name="d_bn1") net = lrelu(net) net = conv2d(net, df_dim * 4, 5, 5, 2, 2, name="d_conv3", use_sn=self._spectral_norm) net = self.batch_norm(net, y=y, is_training=is_training, name="d_bn2") net = lrelu(net) net = conv2d(net, df_dim * 8, 5, 5, 2, 2, name="d_conv4", use_sn=self._spectral_norm) net = self.batch_norm(net, y=y, is_training=is_training, name="d_bn3") net = lrelu(net) out_logit = linear( tf.reshape(net, [bs, -1]), 1, scope="d_fc4", use_sn=self._spectral_norm) out = tf.nn.sigmoid(out_logit) return out, out_logit, net
compare_gan-master
compare_gan/architectures/dcgan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides a library of custom architecture-related operations. It currently provides the following operations: - linear, conv2d, deconv2d, lrelu - batch norm, conditional batch norm, self-modulation - spectral norm, weight norm, layer norm - self-attention block - various weight initialization schemes These operations are supported on both GPUs and TPUs. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from absl import logging from compare_gan.gans import consts from compare_gan.tpu import tpu_ops import gin from six.moves import range import tensorflow as tf from tensorflow.contrib.tpu.python.tpu import tpu_function from tensorflow.python.training import moving_averages # pylint: disable=g-direct-tensorflow-import @gin.configurable("weights") def weight_initializer(initializer=consts.NORMAL_INIT, stddev=0.02): """Returns the initializer for the given name. Args: initializer: Name of the initalizer. Use one in consts.INITIALIZERS. stddev: Standard deviation passed to initalizer. Returns: Initializer from `tf.initializers`. """ if initializer == consts.NORMAL_INIT: return tf.initializers.random_normal(stddev=stddev) if initializer == consts.TRUNCATED_INIT: return tf.initializers.truncated_normal(stddev=stddev) if initializer == consts.ORTHOGONAL_INIT: return tf.initializers.orthogonal() raise ValueError("Unknown weight initializer {}.".format(initializer)) def _moving_moments_for_inference(mean, variance, is_training, decay): """Use moving averages of moments during inference. Args: mean: Tensor of shape [num_channels] with the mean of the current batch. variance: Tensor of shape [num_channels] with the variance of the current batch. is_training: Boolean, wheather to construct ops for training or inference graph. decay: Decay rate to use for moving averages. Returns: Tuple of (mean, variance) to use. This can the same as the inputs. """ # Create the moving average variables and add them to the appropriate # collections. variable_collections = [ tf.GraphKeys.MOVING_AVERAGE_VARIABLES, tf.GraphKeys.MODEL_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES, ] # Disable partition setting for moving_mean and moving_variance # as assign_moving_average op below doesn"t support partitioned variable. moving_mean = tf.get_variable( "moving_mean", shape=mean.shape, initializer=tf.zeros_initializer(), trainable=False, partitioner=None, collections=variable_collections) moving_variance = tf.get_variable( "moving_variance", shape=variance.shape, initializer=tf.ones_initializer(), trainable=False, partitioner=None, collections=variable_collections) if is_training: logging.debug("Adding update ops for moving averages of mean and variance.") # Update variables for mean and variance during training. update_moving_mean = moving_averages.assign_moving_average( moving_mean, tf.cast(mean, moving_mean.dtype), decay, zero_debias=False) update_moving_variance = moving_averages.assign_moving_average( moving_variance, tf.cast(variance, moving_variance.dtype), decay, zero_debias=False) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_moving_mean) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_moving_variance) return mean, variance logging.debug("Using moving mean and variance.") return moving_mean, moving_variance def _accumulated_moments_for_inference(mean, variance, is_training): """Use accumulated statistics for moments during inference. After training the user is responsible for filling the accumulators with the actual values. See _UpdateBnAccumulators() in eval_gan_lib.py for an example. Args: mean: Tensor of shape [num_channels] with the mean of the current batch. variance: Tensor of shape [num_channels] with the variance of the current batch. is_training: Boolean, wheather to construct ops for training or inference graph. Returns: Tuple of (mean, variance) to use. This can the same as the inputs. """ variable_collections = [ tf.GraphKeys.MODEL_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES, ] with tf.variable_scope("accu", values=[mean, variance]): # Create variables for accumulating batch statistic and use them during # inference. The ops for filling the accumulators must be created and run # before eval. See docstring above. accu_mean = tf.get_variable( "accu_mean", shape=mean.shape, initializer=tf.zeros_initializer(), trainable=False, collections=variable_collections) accu_variance = tf.get_variable( "accu_variance", shape=variance.shape, initializer=tf.zeros_initializer(), trainable=False, collections=variable_collections) accu_counter = tf.get_variable( "accu_counter", shape=[], initializer=tf.initializers.constant(1e-12), trainable=False, collections=variable_collections) update_accus = tf.get_variable( "update_accus", shape=[], dtype=tf.int32, initializer=tf.zeros_initializer(), trainable=False, collections=variable_collections) mean = tf.identity(mean, "mean") variance = tf.identity(variance, "variance") if is_training: return mean, variance logging.debug("Using accumulated moments.") # Return the accumulated batch statistics and add current batch statistics # to accumulators if update_accus variables equals 1. def update_accus_fn(): return tf.group([ tf.assign_add(accu_mean, mean), tf.assign_add(accu_variance, variance), tf.assign_add(accu_counter, 1), ]) dep = tf.cond( tf.equal(update_accus, 1), update_accus_fn, tf.no_op) with tf.control_dependencies([dep]): return accu_mean / accu_counter, accu_variance / accu_counter @gin.configurable(whitelist=["decay", "epsilon", "use_cross_replica_mean", "use_moving_averages"]) def standardize_batch(inputs, is_training, decay=0.999, epsilon=1e-3, data_format="NHWC", use_moving_averages=True, use_cross_replica_mean=None): """Adds TPU-enabled batch normalization layer. This version does not apply trainable scale or offset! It normalizes a tensor by mean and variance. Details on Batch Normalization can be found in "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift", Ioffe S. and Szegedy C. 2015 [http://arxiv.org/abs/1502.03167]. Note #1: This method computes the batch statistic across all TPU replicas, thus simulating the true batch norm in the distributed setting. If one wants to avoid the cross-replica communication set use_cross_replica_mean=False. Note #2: When is_training is True the moving_mean and moving_variance need to be updated in each training step. By default, the update_ops are placed in `tf.GraphKeys.UPDATE_OPS` and they need to be added as a dependency to the `train_op`. For example: update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) if update_ops: updates = tf.group(*update_ops) total_loss = control_flow_ops.with_dependencies([updates], total_loss) Note #3: Reasonable values for `decay` are close to 1.0, typically in the multiple-nines range: 0.999, 0.99, 0.9, etc. Lower the `decay` value (trying `decay`=0.9) if model experiences reasonably good training performance but poor validation and/or test performance. Args: inputs: A tensor with 2 or 4 dimensions, where the first dimension is `batch_size`. The normalization is over all but the last dimension if `data_format` is `NHWC`, and the second dimension if `data_format` is `NCHW`. is_training: Whether or not the layer is in training mode. In training mode it would accumulate the statistics of the moments into the `moving_mean` and `moving_variance` using an exponential moving average with the given `decay`. When is_training=False, these variables are not updated, and the precomputed values are used verbatim. decay: Decay for the moving averages. See notes above for reasonable values. epsilon: Small float added to variance to avoid dividing by zero. data_format: Input data format. NHWC or NCHW. use_moving_averages: If True keep moving averages of mean and variance that are used during inference. Otherwise use accumlators. use_cross_replica_mean: If True add operations to do computes batch norm statistics across all TPU cores. These ops are not compatible with other platforms. The default (None) will only add the operations if running on TPU. Returns: The normalized tensor with the same type and shape as `inputs`. """ if data_format not in {"NCHW", "NHWC"}: raise ValueError( "Invalid data_format {}. Allowed: NCHW, NHWC.".format(data_format)) if use_cross_replica_mean is None: # Default to global batch norm only on TPUs. use_cross_replica_mean = ( tpu_function.get_tpu_context().number_of_shards is not None) logging.debug("Automatically determined use_cross_replica_mean=%s.", use_cross_replica_mean) inputs = tf.convert_to_tensor(inputs) inputs_dtype = inputs.dtype inputs_shape = inputs.get_shape() num_channels = inputs.shape[-1].value if num_channels is None: raise ValueError("`C` dimension must be known but is None") inputs_rank = inputs_shape.ndims if inputs_rank is None: raise ValueError("Inputs %s has undefined rank" % inputs.name) elif inputs_rank not in [2, 4]: raise ValueError( "Inputs %s has unsupported rank." " Expected 2 or 4 but got %d" % (inputs.name, inputs_rank)) # Bring 2-D inputs into 4-D format. if inputs_rank == 2: new_shape = [-1, 1, 1, num_channels] if data_format == "NCHW": new_shape = [-1, num_channels, 1, 1] inputs = tf.reshape(inputs, new_shape) # Execute a distributed batch normalization axis = 1 if data_format == "NCHW" else 3 inputs = tf.cast(inputs, tf.float32) reduction_axes = [i for i in range(4) if i != axis] if use_cross_replica_mean: mean, variance = tpu_ops.cross_replica_moments(inputs, reduction_axes) else: counts, mean_ss, variance_ss, _ = tf.nn.sufficient_statistics( inputs, reduction_axes, keep_dims=False) mean, variance = tf.nn.normalize_moments( counts, mean_ss, variance_ss, shift=None) if use_moving_averages: mean, variance = _moving_moments_for_inference( mean=mean, variance=variance, is_training=is_training, decay=decay) else: mean, variance = _accumulated_moments_for_inference( mean=mean, variance=variance, is_training=is_training) outputs = tf.nn.batch_normalization( inputs, mean=mean, variance=variance, offset=None, scale=None, variance_epsilon=epsilon) outputs = tf.cast(outputs, inputs_dtype) # Bring 2-D inputs back into 2-D format. if inputs_rank == 2: outputs = tf.reshape(outputs, [-1] + inputs_shape[1:].as_list()) outputs.set_shape(inputs_shape) return outputs @gin.configurable(blacklist=["inputs"]) def no_batch_norm(inputs): return inputs @gin.configurable( blacklist=["inputs", "is_training", "center", "scale", "name"]) def batch_norm(inputs, is_training, center=True, scale=True, name="batch_norm"): """Performs the vanilla batch normalization with trainable scaling and offset. Args: inputs: A tensor with 2 or 4 dimensions, where the first dimension is `batch_size`. The normalization is over all but the last dimension if `data_format` is `NHWC`, and the second dimension if `data_format` is `NCHW`. is_training: Whether or not the layer is in training mode. center: If True, add offset of beta to normalized tensor. scale: If True, multiply by gamma. When the next layer is linear this can be disabled since the scaling will be done by the next layer. name: Name of the variable scope. Returns: The normalized tensor with the same type and shape as `inputs`. """ with tf.variable_scope(name, values=[inputs]): outputs = standardize_batch(inputs, is_training=is_training) num_channels = inputs.shape[-1].value # Allocate parameters for the trainable variables. collections = [tf.GraphKeys.MODEL_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES] if scale: gamma = tf.get_variable( "gamma", [num_channels], collections=collections, initializer=tf.ones_initializer()) outputs *= gamma if center: beta = tf.get_variable( "beta", [num_channels], collections=collections, initializer=tf.zeros_initializer()) outputs += beta return outputs @gin.configurable(whitelist=["num_hidden"]) def self_modulated_batch_norm(inputs, z, is_training, use_sn, center=True, scale=True, name="batch_norm", num_hidden=32): """Performs a self-modulated batch normalization. Details can be found in "On Self Modulation for Generative Adversarial Networks", Chen T. et al., 2018. [https://arxiv.org/abs/1810.01365] Like a normal batch normalization but the scale and offset are trainable transformation of `z`. Args: inputs: A tensor with 2 or 4 dimensions, where the first dimension is `batch_size`. The normalization is over all but the last dimension if `data_format` is `NHWC`, and the second dimension if `data_format` is `NCHW`. z: 2-D tensor with shape [batch_size, ?] with the latent code. is_training: Whether or not the layer is in training mode. use_sn: Whether to apply spectral normalization to the weights of the hidden layer and the linear transformations. center: If True, add offset of beta to normalized tensor. scale: If True, multiply by gamma. When the next layer is linear this can be disabled since the scaling will be done by the next layer. name: Name of the variable scope. num_hidden: Number of hidden units in the hidden layer. If 0 the scale and offset are simple linear transformations of `z`. Returns: """ if z is None: raise ValueError("You must provide z for self modulation.") with tf.variable_scope(name, values=[inputs]): outputs = standardize_batch(inputs, is_training=is_training) num_channels = inputs.shape[-1].value with tf.variable_scope("sbn", values=[inputs, z]): h = z if num_hidden > 0: h = linear(h, num_hidden, scope="hidden", use_sn=use_sn) h = tf.nn.relu(h) if scale: gamma = linear(h, num_channels, scope="gamma", bias_start=1.0, use_sn=use_sn) gamma = tf.reshape(gamma, [-1, 1, 1, num_channels]) outputs *= gamma if center: beta = linear(h, num_channels, scope="beta", use_sn=use_sn) beta = tf.reshape(beta, [-1, 1, 1, num_channels]) outputs += beta return outputs # evonorm functions def evonorm_s0(inputs, is_training, data_format="NHWC", nonlinearity=True, name="evonorm-s0"): with tf.variable_scope(name, values=[inputs]): if data_format not in {"NCHW", "NHWC"}: raise ValueError( "Invalid data_format {}. Allowed: NCHW, NHWC.".format(data_format)) inputs = tf.convert_to_tensor(inputs) inputs_dtype = inputs.dtype inputs_shape = inputs.get_shape() num_channels = inputs.shape[-1].value if num_channels is None: raise ValueError("`C` dimension must be known but is None") inputs_rank = inputs_shape.ndims if inputs_rank is None: raise ValueError("Inputs %s has undefined rank" % inputs.name) elif inputs_rank not in [2, 4]: raise ValueError( "Inputs %s has unsupported rank." " Expected 2 or 4 but got %d" % (inputs.name, inputs_rank)) if inputs_rank == 2: new_shape = [-1, 1, 1, num_channels] if data_format == "NCHW": new_shape = [-1, num_channels, 1, 1] inputs = tf.reshape(inputs, new_shape) with tf.variable_scope("evonorm-s0", values=[inputs]): collections = [tf.GraphKeys.MODEL_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES] gamma = tf.get_variable( "gamma", [num_channels], collections=collections, initializer=tf.ones_initializer()) beta = tf.get_variable( "beta", [num_channels], collections=collections, initializer=tf.zeros_initializer()) if nonlinearity: v = trainable_variable_ones(shape=gamma.shape) num = inputs * tf.nn.sigmoid(v * inputs) outputs = num / group_std(inputs) * gamma + beta else: outputs = inputs * gamma + beta outputs = tf.cast(outputs, inputs_dtype) return outputs def instance_std(x, eps=1e-5): _, var = tf.nn.moments(x, axes=[1, 2], keepdims=True) return tf.sqrt(var + eps) def group_std(x, groups=32, eps=1e-5): N, H, W, C = x.shape x = tf.reshape(x, [N, H, W, groups, C // groups]) _, var = tf.nn.moments(x, [1, 2, 4], keepdims=True) std = tf.sqrt(var + eps) std = tf.broadcast_to(std, x.shape) return tf.reshape(std, [N, H, W, C]) def trainable_variable_ones(shape, name="v"): return tf.get_variable(name, shape=shape, initializer=tf.ones_initializer()) #/ evonorm functions @gin.configurable(whitelist=["use_bias"]) def conditional_batch_norm(inputs, y, is_training, use_sn, center=True, scale=True, name="batch_norm", use_bias=False): """Conditional batch normalization.""" if y is None: raise ValueError("You must provide y for conditional batch normalization.") if y.shape.ndims != 2: raise ValueError("Conditioning must have rank 2.") with tf.variable_scope(name, values=[inputs]): outputs = standardize_batch(inputs, is_training=is_training) num_channels = inputs.shape[-1].value with tf.variable_scope("condition", values=[inputs, y]): if scale: gamma = linear(y, num_channels, scope="gamma", use_sn=use_sn, use_bias=use_bias) gamma = tf.reshape(gamma, [-1, 1, 1, num_channels]) outputs *= gamma if center: beta = linear(y, num_channels, scope="beta", use_sn=use_sn, use_bias=use_bias) beta = tf.reshape(beta, [-1, 1, 1, num_channels]) outputs += beta return outputs def layer_norm(input_, is_training, scope): return tf.contrib.layers.layer_norm( input_, trainable=is_training, scope=scope) @gin.configurable(blacklist=["inputs"]) def spectral_norm(inputs, epsilon=1e-12, singular_value="left"): """Performs Spectral Normalization on a weight tensor. Details of why this is helpful for GAN's can be found in "Spectral Normalization for Generative Adversarial Networks", Miyato T. et al., 2018. [https://arxiv.org/abs/1802.05957]. Args: inputs: The weight tensor to normalize. epsilon: Epsilon for L2 normalization. singular_value: Which first singular value to store (left or right). Use "auto" to automatically choose the one that has fewer dimensions. Returns: The normalized weight tensor. """ if len(inputs.shape) < 2: raise ValueError( "Spectral norm can only be applied to multi-dimensional tensors") # The paper says to flatten convnet kernel weights from (C_out, C_in, KH, KW) # to (C_out, C_in * KH * KW). Our Conv2D kernel shape is (KH, KW, C_in, C_out) # so it should be reshaped to (KH * KW * C_in, C_out), and similarly for other # layers that put output channels as last dimension. This implies that w # here is equivalent to w.T in the paper. w = tf.reshape(inputs, (-1, inputs.shape[-1])) # Choose whether to persist the first left or first right singular vector. # As the underlying matrix is PSD, this should be equivalent, but in practice # the shape of the persisted vector is different. Here one can choose whether # to maintain the left or right one, or pick the one which has the smaller # dimension. We use the same variable for the singular vector if we switch # from normal weights to EMA weights. var_name = inputs.name.replace("/ExponentialMovingAverage", "").split("/")[-1] var_name = var_name.split(":")[0] + "/u_var" if singular_value == "auto": singular_value = "left" if w.shape[0] <= w.shape[1] else "right" u_shape = (w.shape[0], 1) if singular_value == "left" else (1, w.shape[-1]) u_var = tf.get_variable( var_name, shape=u_shape, dtype=w.dtype, initializer=tf.random_normal_initializer(), trainable=False) u = u_var # Use power iteration method to approximate the spectral norm. # The authors suggest that one round of power iteration was sufficient in the # actual experiment to achieve satisfactory performance. power_iteration_rounds = 1 for _ in range(power_iteration_rounds): if singular_value == "left": # `v` approximates the first right singular vector of matrix `w`. v = tf.math.l2_normalize( tf.matmul(tf.transpose(w), u), axis=None, epsilon=epsilon) u = tf.math.l2_normalize(tf.matmul(w, v), axis=None, epsilon=epsilon) else: v = tf.math.l2_normalize(tf.matmul(u, w, transpose_b=True), epsilon=epsilon) u = tf.math.l2_normalize(tf.matmul(v, w), epsilon=epsilon) # Update the approximation. with tf.control_dependencies([tf.assign(u_var, u, name="update_u")]): u = tf.identity(u) # The authors of SN-GAN chose to stop gradient propagating through u and v # and we maintain that option. u = tf.stop_gradient(u) v = tf.stop_gradient(v) if singular_value == "left": norm_value = tf.matmul(tf.matmul(tf.transpose(u), w), v) else: norm_value = tf.matmul(tf.matmul(v, w), u, transpose_b=True) norm_value.shape.assert_is_fully_defined() norm_value.shape.assert_is_compatible_with([1, 1]) w_normalized = w / norm_value # Deflate normalized weights to match the unnormalized tensor. w_tensor_normalized = tf.reshape(w_normalized, inputs.shape) return w_tensor_normalized def linear(inputs, output_size, scope=None, stddev=0.02, bias_start=0.0, use_sn=False, use_bias=True): """Linear layer without the non-linear activation applied.""" shape = inputs.get_shape().as_list() with tf.variable_scope(scope or "linear"): kernel = tf.get_variable( "kernel", [shape[1], output_size], initializer=weight_initializer(stddev=stddev)) if use_sn: kernel = spectral_norm(kernel) outputs = tf.matmul(inputs, kernel) if use_bias: bias = tf.get_variable( "bias", [output_size], initializer=tf.constant_initializer(bias_start)) outputs += bias return outputs def conv2d(inputs, output_dim, k_h, k_w, d_h, d_w, stddev=0.02, name="conv2d", use_sn=False, use_bias=True): """Performs 2D convolution of the input.""" with tf.variable_scope(name): w = tf.get_variable( "kernel", [k_h, k_w, inputs.shape[-1].value, output_dim], initializer=weight_initializer(stddev=stddev)) if use_sn: w = spectral_norm(w) outputs = tf.nn.conv2d(inputs, w, strides=[1, d_h, d_w, 1], padding="SAME") if use_bias: bias = tf.get_variable( "bias", [output_dim], initializer=tf.constant_initializer(0.0)) outputs += bias return outputs conv1x1 = functools.partial(conv2d, k_h=1, k_w=1, d_h=1, d_w=1) def deconv2d(inputs, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name="deconv2d", use_sn=False): """Performs transposed 2D convolution of the input.""" with tf.variable_scope(name): w = tf.get_variable( "kernel", [k_h, k_w, output_shape[-1], inputs.get_shape()[-1]], initializer=weight_initializer(stddev=stddev)) if use_sn: w = spectral_norm(w) deconv = tf.nn.conv2d_transpose( inputs, w, output_shape=output_shape, strides=[1, d_h, d_w, 1]) bias = tf.get_variable( "bias", [output_shape[-1]], initializer=tf.constant_initializer(0.0)) return tf.reshape(tf.nn.bias_add(deconv, bias), tf.shape(deconv)) def lrelu(inputs, leak=0.2, name="lrelu"): """Performs leaky-ReLU on the input.""" return tf.maximum(inputs, leak * inputs, name=name) def weight_norm_linear(input_, output_size, init=False, init_scale=1.0, name="wn_linear", initializer=tf.truncated_normal_initializer, stddev=0.02): """Linear layer with Weight Normalization (Salimans, Kingma '16).""" with tf.variable_scope(name): if init: v = tf.get_variable("V", [int(input_.get_shape()[1]), output_size], tf.float32, initializer(0, stddev), trainable=True) v_norm = tf.nn.l2_normalize(v.initialized_value(), [0]) x_init = tf.matmul(input_, v_norm) m_init, v_init = tf.nn.moments(x_init, [0]) scale_init = init_scale / tf.sqrt(v_init + 1e-10) g = tf.get_variable("g", dtype=tf.float32, initializer=scale_init, trainable=True) b = tf.get_variable("b", dtype=tf.float32, initializer= -m_init*scale_init, trainable=True) x_init = tf.reshape(scale_init, [1, output_size]) * ( x_init - tf.reshape(m_init, [1, output_size])) return x_init else: # Note that the original implementation uses Polyak averaging. v = tf.get_variable("V") g = tf.get_variable("g") b = tf.get_variable("b") tf.assert_variables_initialized([v, g, b]) x = tf.matmul(input_, v) scaler = g / tf.sqrt(tf.reduce_sum(tf.square(v), [0])) x = tf.reshape(scaler, [1, output_size]) * x + tf.reshape( b, [1, output_size]) return x def weight_norm_conv2d(input_, output_dim, k_h, k_w, d_h, d_w, init, init_scale, stddev=0.02, name="wn_conv2d", initializer=tf.truncated_normal_initializer): """Performs convolution with Weight Normalization.""" with tf.variable_scope(name): if init: v = tf.get_variable( "V", [k_h, k_w] + [int(input_.get_shape()[-1]), output_dim], tf.float32, initializer(0, stddev), trainable=True) v_norm = tf.nn.l2_normalize(v.initialized_value(), [0, 1, 2]) x_init = tf.nn.conv2d(input_, v_norm, strides=[1, d_h, d_w, 1], padding="SAME") m_init, v_init = tf.nn.moments(x_init, [0, 1, 2]) scale_init = init_scale / tf.sqrt(v_init + 1e-8) g = tf.get_variable( "g", dtype=tf.float32, initializer=scale_init, trainable=True) b = tf.get_variable( "b", dtype=tf.float32, initializer=-m_init*scale_init, trainable=True) x_init = tf.reshape(scale_init, [1, 1, 1, output_dim]) * ( x_init - tf.reshape(m_init, [1, 1, 1, output_dim])) return x_init else: v = tf.get_variable("V") g = tf.get_variable("g") b = tf.get_variable("b") tf.assert_variables_initialized([v, g, b]) w = tf.reshape(g, [1, 1, 1, output_dim]) * tf.nn.l2_normalize( v, [0, 1, 2]) x = tf.nn.bias_add( tf.nn.conv2d(input_, w, [1, d_h, d_w, 1], padding="SAME"), b) return x def weight_norm_deconv2d(x, output_dim, k_h, k_w, d_h, d_w, init=False, init_scale=1.0, stddev=0.02, name="wn_deconv2d", initializer=tf.truncated_normal_initializer): """Performs Transposed Convolution with Weight Normalization.""" xs = x.get_shape().as_list() target_shape = [xs[0], xs[1] * d_h, xs[2] * d_w, output_dim] with tf.variable_scope(name): if init: v = tf.get_variable( "V", [k_h, k_w] + [output_dim, int(x.get_shape()[-1])], tf.float32, initializer(0, stddev), trainable=True) v_norm = tf.nn.l2_normalize(v.initialized_value(), [0, 1, 3]) x_init = tf.nn.conv2d_transpose(x, v_norm, target_shape, [1, d_h, d_w, 1], padding="SAME") m_init, v_init = tf.nn.moments(x_init, [0, 1, 2]) scale_init = init_scale/tf.sqrt(v_init + 1e-8) g = tf.get_variable("g", dtype=tf.float32, initializer=scale_init, trainable=True) b = tf.get_variable("b", dtype=tf.float32, initializer=-m_init*scale_init, trainable=True) x_init = tf.reshape(scale_init, [1, 1, 1, output_dim]) * ( x_init - tf.reshape(m_init, [1, 1, 1, output_dim])) return x_init else: v = tf.get_variable("v") g = tf.get_variable("g") b = tf.get_variable("b") tf.assert_variables_initialized([v, g, b]) w = tf.reshape(g, [1, 1, output_dim, 1]) * tf.nn.l2_normalize( v, [0, 1, 3]) x = tf.nn.conv2d_transpose(x, w, target_shape, strides=[1, d_h, d_w, 1], padding="SAME") x = tf.nn.bias_add(x, b) return x def non_local_block(x, name, use_sn): """Self-attention (non-local) block. This method is used to exactly reproduce SAGAN and ignores Gin settings on weight initialization and spectral normalization. Args: x: Input tensor of shape [batch, h, w, c]. name: Name of the variable scope. use_sn: Apply spectral norm to the weights. Returns: A tensor of the same shape after self-attention was applied. """ def _spatial_flatten(inputs): shape = inputs.shape return tf.reshape(inputs, (-1, shape[1] * shape[2], shape[3])) with tf.variable_scope(name): h, w, num_channels = x.get_shape().as_list()[1:] num_channels_attn = num_channels // 8 num_channels_g = num_channels // 2 # Theta path theta = conv1x1(x, num_channels_attn, name="conv2d_theta", use_sn=use_sn, use_bias=False) theta = _spatial_flatten(theta) # Phi path phi = conv1x1(x, num_channels_attn, name="conv2d_phi", use_sn=use_sn, use_bias=False) phi = tf.layers.max_pooling2d(inputs=phi, pool_size=[2, 2], strides=2) phi = _spatial_flatten(phi) attn = tf.matmul(theta, phi, transpose_b=True) attn = tf.nn.softmax(attn) # G path g = conv1x1(x, num_channels_g, name="conv2d_g", use_sn=use_sn, use_bias=False) g = tf.layers.max_pooling2d(inputs=g, pool_size=[2, 2], strides=2) g = _spatial_flatten(g) attn_g = tf.matmul(attn, g) attn_g = tf.reshape(attn_g, [-1, h, w, num_channels_g]) sigma = tf.get_variable("sigma", [], initializer=tf.zeros_initializer()) attn_g = conv1x1(attn_g, num_channels, name="conv2d_attn_g", use_sn=use_sn, use_bias=False) return x + sigma * attn_g # vector quantize function @gin.configurable(blacklist=["inputs", "name", "is_training"]) def vector_quantize(inputs, name = 'vector_quantize', is_training=True, embedding_dim=512, num_embeddings=2**8, decay=0.8, commitment_cost=1.0, epsilon=1e-5, **_kwargs): _embedding_dim = embedding_dim _num_embeddings = num_embeddings _decay = decay _commitment_cost = commitment_cost _epsilon = epsilon # w is a matrix with an embedding in each column. When training, the # embedding is assigned to be the average of all inputs assigned to that # embedding. embedding_shape = [embedding_dim, num_embeddings] with tf.variable_scope(name): _w = tf.get_variable( 'embedding', embedding_shape, initializer=tf.variance_scaling_initializer(), use_resource=True) _ema_cluster_size = tf.get_variable( 'ema_cluster_size', [num_embeddings], initializer=tf.constant_initializer(0), use_resource=True) _ema_w = tf.get_variable( 'ema_dw', initializer=_w.initialized_value(), use_resource=True) inputs.set_shape([None, None, None, embedding_dim]) def quantize(encoding_indices): with tf.control_dependencies([encoding_indices]): w = tf.transpose(_w.read_value(), [1, 0]) return tf.nn.embedding_lookup(w, encoding_indices, validate_indices=False) with tf.control_dependencies([inputs]): w = _w.read_value() input_shape = tf.shape(inputs) with tf.control_dependencies([ tf.Assert(tf.equal(input_shape[-1], _embedding_dim), [input_shape])]): flat_inputs = tf.reshape(inputs, [-1, _embedding_dim]) distances = (tf.reduce_sum(flat_inputs ** 2, 1, keepdims=True) - 2 * tf.matmul(flat_inputs, w) + tf.reduce_sum(w ** 2, 0, keepdims=True)) encoding_indices = tf.argmax(- distances, 1) encodings = tf.one_hot(encoding_indices, _num_embeddings) encoding_indices = tf.reshape(encoding_indices, tf.shape(inputs)[:-1]) quantized = quantize(encoding_indices) e_latent_loss = tf.reduce_mean((tf.stop_gradient(quantized) - inputs) ** 2, axis=[1, 2, 3]) if is_training: updated_ema_cluster_size = moving_averages.assign_moving_average( _ema_cluster_size, tf.reduce_sum(encodings, 0), _decay) dw = tf.matmul(flat_inputs, encodings, transpose_a=True) updated_ema_w = moving_averages.assign_moving_average(_ema_w, dw, _decay) n = tf.reduce_sum(updated_ema_cluster_size) updated_ema_cluster_size = ( (updated_ema_cluster_size + _epsilon) / (n + _num_embeddings * _epsilon) * n) # print('here') normalised_updated_ema_w = ( updated_ema_w / tf.reshape(updated_ema_cluster_size, [1, -1])) with tf.control_dependencies([e_latent_loss]): update_w = tf.assign(_w, normalised_updated_ema_w) with tf.control_dependencies([update_w]): loss = _commitment_cost * e_latent_loss else: loss = _commitment_cost * e_latent_loss quantized = inputs + tf.stop_gradient(quantized - inputs) avg_probs = tf.reduce_mean(encodings, 0) perplexity = tf.exp(- tf.reduce_sum(avg_probs * tf.log(avg_probs + 1e-10))) return quantized, loss
compare_gan-master
compare_gan/architectures/arch_ops.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A 30-block resnet. It contains 6 "super-blocks" and each such block contains 5 residual blocks in both the generator and discriminator. It supports the 128x128 resolution. Details can be found in "Improved Training of Wasserstein GANs", Gulrajani I. et al. 2017. The related code is available at https://github.com/igul222/improved_wgan_training/blob/master/gan_64x64.py. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.architectures import arch_ops as ops from compare_gan.architectures import resnet_ops from six.moves import range import tensorflow as tf class Generator(resnet_ops.ResNetGenerator): """ResNet30 generator, 30 blocks, generates images of resolution 128x128. Trying to match the architecture defined in [1]. Difference is that there the final resolution is 64x64, while here we have 128x128. """ def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ z_shape = z.get_shape().as_list() if len(z_shape) != 2: raise ValueError("Expected shape [batch_size, z_dim], got %s." % z_shape) ch = 64 colors = self._image_shape[2] # Map noise to the actual seed. output = ops.linear(z, 4 * 4 * 8 * ch, scope="fc_noise") # Reshape the seed to be a rank-4 Tensor. output = tf.reshape(output, [-1, 4, 4, 8 * ch], name="fc_reshaped") in_channels = 8 * ch out_channels = 4 * ch for superblock in range(6): for i in range(5): block = self._resnet_block( name="B_{}_{}".format(superblock, i), in_channels=in_channels, out_channels=in_channels, scale="none") output = block(output, z=z, y=y, is_training=is_training) # We want to upscale 5 times. if superblock < 5: block = self._resnet_block( name="B_{}_up".format(superblock), in_channels=in_channels, out_channels=out_channels, scale="up") output = block(output, z=z, y=y, is_training=is_training) in_channels /= 2 out_channels /= 2 output = ops.conv2d( output, output_dim=colors, k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv") output = tf.nn.sigmoid(output) return output class Discriminator(resnet_ops.ResNetDiscriminator): """ResNet discriminator, 30 blocks, 128x128x3 and 128x128x1 resolution.""" def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ resnet_ops.validate_image_inputs(x) colors = x.get_shape().as_list()[-1] assert colors in [1, 3] ch = 64 output = ops.conv2d( x, output_dim=ch // 4, k_h=3, k_w=3, d_h=1, d_w=1, name="color_conv") in_channels = ch // 4 out_channels = ch // 2 for superblock in range(6): for i in range(5): block = self._resnet_block( name="B_{}_{}".format(superblock, i), in_channels=in_channels, out_channels=in_channels, scale="none") output = block(output, z=None, y=y, is_training=is_training) # We want to downscale 5 times. if superblock < 5: block = self._resnet_block( name="B_{}_up".format(superblock), in_channels=in_channels, out_channels=out_channels, scale="down") output = block(output, z=None, y=y, is_training=is_training) in_channels *= 2 out_channels *= 2 # Final part output = tf.reshape(output, [-1, 4 * 4 * 8 * ch]) out_logit = ops.linear(output, 1, scope="disc_final_fc", use_sn=self._spectral_norm) out = tf.nn.sigmoid(out_logit) return out, out_logit, output
compare_gan-master
compare_gan/architectures/resnet30.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for custom architecture operations on TPUs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan.architectures import arch_ops import gin import numpy as np import tensorflow as tf class ArchOpsTpuTest(tf.test.TestCase): def setUp(self): # Construct input for batch norm tests: # 4 images with resolution 2x1 and 3 channels. x1 = np.asarray([[[5, 7, 2]], [[5, 8, 8]]], dtype=np.float32) x2 = np.asarray([[[1, 2, 0]], [[4, 0, 4]]], dtype=np.float32) x3 = np.asarray([[[6, 2, 6]], [[5, 0, 5]]], dtype=np.float32) x4 = np.asarray([[[2, 4, 2]], [[6, 4, 1]]], dtype=np.float32) self._inputs = np.stack([x1, x2, x3, x4]) self.assertAllEqual(self._inputs.shape, [4, 2, 1, 3]) # And the expected output for applying batch norm (without additional # scaling/shifting). self._expected_outputs = np.asarray( [[[[0.4375205, 1.30336881, -0.58830315]], [[0.4375205, 1.66291881, 1.76490951]]], [[[-1.89592218, -0.49438119, -1.37270737]], [[-0.14584017, -1.21348119, 0.19610107]]], [[[1.02088118, -0.49438119, 0.98050523]], [[0.4375205, -1.21348119, 0.58830321]]], [[[-1.31256151, 0.22471881, -0.58830315]], [[1.02088118, 0.22471881, -0.98050523]]]], dtype=np.float32) self.assertAllEqual(self._expected_outputs.shape, [4, 2, 1, 3]) def testRunsOnTpu(self): """Verify that the test cases runs on a TPU chip and has 2 cores.""" expected_device_names = [ "/job:localhost/replica:0/task:0/device:CPU:0", "/job:localhost/replica:0/task:0/device:TPU:0", "/job:localhost/replica:0/task:0/device:TPU:1", "/job:localhost/replica:0/task:0/device:TPU_SYSTEM:0", ] with self.session() as sess: devices = sess.list_devices() tf.logging.info("devices:\n%s", "\n".join([str(d) for d in devices])) self.assertAllEqual([d.name for d in devices], expected_device_names) def testBatchNormOneCore(self): def computation(x): core_bn = tf.layers.batch_normalization(x, training=True) contrib_bn = tf.contrib.layers.batch_norm(x, is_training=True) custom_bn = arch_ops.batch_norm(x, is_training=True) tf.logging.info("custom_bn tensor: %s", custom_bn) return core_bn, contrib_bn, custom_bn with tf.Graph().as_default(): x = tf.constant(self._inputs) core_bn, contrib_bn, custom_bn = tf.contrib.tpu.batch_parallel( computation, [x], num_shards=1) with self.session() as sess: sess.run(tf.contrib.tpu.initialize_system()) sess.run(tf.global_variables_initializer()) core_bn, contrib_bn, custom_bn = sess.run( [core_bn, contrib_bn, custom_bn]) logging.info("core_bn: %s", core_bn) logging.info("contrib_bn: %s", contrib_bn) logging.info("custom_bn: %s", custom_bn) self.assertAllClose(core_bn, self._expected_outputs) self.assertAllClose(contrib_bn, self._expected_outputs) self.assertAllClose(custom_bn, self._expected_outputs) def testBatchNormTwoCoresCoreAndContrib(self): def computation(x): core_bn = tf.layers.batch_normalization(x, training=True) contrib_bn = tf.contrib.layers.batch_norm(x, is_training=True) return core_bn, contrib_bn with tf.Graph().as_default(): x = tf.constant(self._inputs) core_bn, contrib_bn = tf.contrib.tpu.batch_parallel( computation, [x], num_shards=2) with self.session() as sess: sess.run(tf.contrib.tpu.initialize_system()) sess.run(tf.global_variables_initializer()) core_bn, contrib_bn = sess.run([core_bn, contrib_bn]) logging.info("core_bn: %s", core_bn) logging.info("contrib_bn: %s", contrib_bn) self.assertNotAllClose(core_bn, self._expected_outputs) self.assertNotAllClose(contrib_bn, self._expected_outputs) def testBatchNormTwoCoresCustom(self): def computation(x): custom_bn = arch_ops.batch_norm(x, is_training=True, name="custom_bn") gin.bind_parameter("cross_replica_moments.parallel", False) custom_bn_seq = arch_ops.batch_norm(x, is_training=True, name="custom_bn_seq") return custom_bn, custom_bn_seq with tf.Graph().as_default(): x = tf.constant(self._inputs) custom_bn, custom_bn_seq = tf.contrib.tpu.batch_parallel( computation, [x], num_shards=2) with self.session() as sess: sess.run(tf.contrib.tpu.initialize_system()) sess.run(tf.global_variables_initializer()) custom_bn, custom_bn_seq = sess.run( [custom_bn, custom_bn_seq]) logging.info("custom_bn: %s", custom_bn) logging.info("custom_bn_seq: %s", custom_bn_seq) self.assertAllClose(custom_bn, self._expected_outputs) self.assertAllClose(custom_bn_seq, self._expected_outputs) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/arch_ops_tpu_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Re-implementation of BigGAN-Deep architecture. Disclaimer: We note that this is our best-effort re-implementation and stress that even minor implementation differences may lead to large differences in trained models due to sensitivity of GANs to optimization hyperparameters and details of neural architectures. That being said, this code suffices to reproduce the reported FID on ImageNet 128x128. Based on "Large Scale GAN Training for High Fidelity Natural Image Synthesys", Brock A. et al., 2018 [https://arxiv.org/abs/1809.11096]. Supported resolutions: 32, 64, 128, 256, 512. Differences to original BigGAN: - The self-attention block is always applied at a resolution of 64x64. - Each batch norm gets the concatenation of the z and the class embedding. z is not chunked. - The channel width multiplier defaults to 128 instead of 96. - Double amount of ResNet blocks: - Residual blocks have bottlenecks: - 1x1 convolution reduces number of channels before the 3x3 convolutions. - After the 3x3 convolutions a 1x1 creates the desired number of out channels. - Skip connections in residual connections preserve identity (no 1x1 conv). - In G, to reduce the number of channels, drop additional chhannels. - In D add more channels by doing a 1x1 convolution. - Mean instead of sum pooling in D after the final ReLU. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from absl import logging from compare_gan.architectures import abstract_arch from compare_gan.architectures import arch_ops as ops from compare_gan.architectures import resnet_ops import gin from six.moves import range import tensorflow as tf @gin.configurable class BigGanDeepResNetBlock(object): """ResNet block with bottleneck and identity preserving skip connections.""" def __init__(self, name, in_channels, out_channels, scale, spectral_norm=False, batch_norm=None): """Constructs a new ResNet block with bottleneck. Args: name: Scope name for the resent block. in_channels: Integer, the input channel size. out_channels: Integer, the output channel size. scale: Whether or not to scale up or down, choose from "up", "down" or "none". spectral_norm: Use spectral normalization for all weights. batch_norm: Function for batch normalization. """ assert scale in ["up", "down", "none"] self._name = name self._in_channels = in_channels self._out_channels = out_channels self._scale = scale self._spectral_norm = spectral_norm self.batch_norm = batch_norm def __call__(self, inputs, z, y, is_training): return self.apply(inputs=inputs, z=z, y=y, is_training=is_training) def _shortcut(self, inputs): """Constructs a skip connection from inputs.""" with tf.variable_scope("shortcut", values=[inputs]): shortcut = inputs num_channels = inputs.shape[-1].value if num_channels > self._out_channels: assert self._scale == "up" # Drop redundant channels. logging.info("[Shortcut] Dropping %d channels in shortcut.", num_channels - self._out_channels) shortcut = shortcut[:, :, :, :self._out_channels] if self._scale == "up": shortcut = resnet_ops.unpool(shortcut) if self._scale == "down": shortcut = tf.nn.pool(shortcut, [2, 2], "AVG", "SAME", strides=[2, 2], name="pool") if num_channels < self._out_channels: assert self._scale == "down" # Increase number of channels if necessary. num_missing = self._out_channels - num_channels logging.info("[Shortcut] Adding %d channels in shortcut.", num_missing) added = ops.conv1x1(shortcut, num_missing, name="add_channels", use_sn=self._spectral_norm) shortcut = tf.concat([shortcut, added], axis=-1) return shortcut def apply(self, inputs, z, y, is_training): """"ResNet block containing possible down/up sampling, shared for G / D. Args: inputs: a 3d input tensor of feature map. z: the latent vector for potential self-modulation. Can be None if use_sbn is set to False. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, whether or notthis is called during the training. Returns: output: a 3d output tensor of feature map. """ if inputs.shape[-1].value != self._in_channels: raise ValueError( "Unexpected number of input channels (expected {}, got {}).".format( self._in_channels, inputs.shape[-1].value)) bottleneck_channels = max(self._in_channels, self._out_channels) // 4 bn = functools.partial(self.batch_norm, z=z, y=y, is_training=is_training) conv1x1 = functools.partial(ops.conv1x1, use_sn=self._spectral_norm) conv3x3 = functools.partial(ops.conv2d, k_h=3, k_w=3, d_h=1, d_w=1, use_sn=self._spectral_norm) with tf.variable_scope(self._name, values=[inputs]): outputs = inputs with tf.variable_scope("conv1", values=[outputs]): outputs = bn(outputs, name="bn") outputs = tf.nn.relu(outputs) outputs = conv1x1(outputs, bottleneck_channels, name="1x1_conv") with tf.variable_scope("conv2", values=[outputs]): outputs = bn(outputs, name="bn") outputs = tf.nn.relu(outputs) if self._scale == "up": outputs = resnet_ops.unpool(outputs) outputs = conv3x3(outputs, bottleneck_channels, name="3x3_conv") with tf.variable_scope("conv3", values=[outputs]): outputs = bn(outputs, name="bn") outputs = tf.nn.relu(outputs) outputs = conv3x3(outputs, bottleneck_channels, name="3x3_conv") with tf.variable_scope("conv4", values=[outputs]): outputs = bn(outputs, name="bn") outputs = tf.nn.relu(outputs) if self._scale == "down": outputs = tf.nn.pool(outputs, [2, 2], "AVG", "SAME", strides=[2, 2], name="avg_pool") outputs = conv1x1(outputs, self._out_channels, name="1x1_conv") # Add skip-connection. outputs += self._shortcut(inputs) logging.info("[Block] %s (z=%s, y=%s) -> %s", inputs.shape, None if z is None else z.shape, None if y is None else y.shape, outputs.shape) return outputs @gin.configurable class Generator(abstract_arch.AbstractGenerator): """ResNet-based generator supporting resolutions 32, 64, 128, 256, 512.""" def __init__(self, ch=128, embed_y=True, embed_y_dim=128, experimental_fast_conv_to_rgb=False, **kwargs): """Constructor for BigGAN generator. Args: ch: Channel multiplier. embed_y: If True use a learnable embedding of y that is used instead. embed_y_dim: Size of the embedding of y. experimental_fast_conv_to_rgb: If True optimize the last convolution to sacrifize memory for better speed. **kwargs: additional arguments past on to ResNetGenerator. """ super(Generator, self).__init__(**kwargs) self._ch = ch self._embed_y = embed_y self._embed_y_dim = embed_y_dim self._experimental_fast_conv_to_rgb = experimental_fast_conv_to_rgb def _resnet_block(self, name, in_channels, out_channels, scale): """ResNet block for the generator.""" if scale not in ["up", "none"]: raise ValueError( "Unknown generator ResNet block scaling: {}.".format(scale)) return BigGanDeepResNetBlock( name=name, in_channels=in_channels, out_channels=out_channels, scale=scale, spectral_norm=self._spectral_norm, batch_norm=self.batch_norm) def _get_in_out_channels(self): # See Table 7-9. resolution = self._image_shape[0] if resolution == 512: channel_multipliers = 4 * [16] + 4 * [8] + [4, 4, 2, 2, 1, 1, 1] elif resolution == 256: channel_multipliers = 4 * [16] + 4 * [8] + [4, 4, 2, 2, 1] elif resolution == 128: channel_multipliers = 4 * [16] + 2 * [8] + [4, 4, 2, 2, 1] elif resolution == 64: channel_multipliers = 4 * [16] + 2 * [8] + [4, 4, 2] elif resolution == 32: channel_multipliers = 8 * [4] else: raise ValueError("Unsupported resolution: {}".format(resolution)) in_channels = [self._ch * c for c in channel_multipliers[:-1]] out_channels = [self._ch * c for c in channel_multipliers[1:]] return in_channels, out_channels def apply(self, z, y, is_training): """Build the generator network for the given inputs. Args: z: `Tensor` of shape [batch_size, z_dim] with latent code. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: boolean, are we in train or eval model. Returns: A tensor of size [batch_size] + self._image_shape with values in [0, 1]. """ shape_or_none = lambda t: None if t is None else t.shape logging.info("[Generator] inputs are z=%s, y=%s", z.shape, shape_or_none(y)) seed_size = 4 if self._embed_y: y = ops.linear(y, self._embed_y_dim, scope="embed_y", use_sn=False, use_bias=False) if y is not None: y = tf.concat([z, y], axis=1) z = y in_channels, out_channels = self._get_in_out_channels() num_blocks = len(in_channels) # Map noise to the actual seed. net = ops.linear( z, in_channels[0] * seed_size * seed_size, scope="fc_noise", use_sn=self._spectral_norm) # Reshape the seed to be a rank-4 Tensor. net = tf.reshape( net, [-1, seed_size, seed_size, in_channels[0]], name="fc_reshaped") for block_idx in range(num_blocks): scale = "none" if block_idx % 2 == 0 else "up" block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=in_channels[block_idx], out_channels=out_channels[block_idx], scale=scale) net = block(net, z=z, y=y, is_training=is_training) # At resolution 64x64 there is a self-attention block. if scale == "up" and net.shape[1].value == 64: logging.info("[Generator] Applying non-local block to %s", net.shape) net = ops.non_local_block(net, "non_local_block", use_sn=self._spectral_norm) # Final processing of the net. # Use unconditional batch norm. logging.info("[Generator] before final processing: %s", net.shape) net = ops.batch_norm(net, is_training=is_training, name="final_norm") net = tf.nn.relu(net) colors = self._image_shape[2] if self._experimental_fast_conv_to_rgb: net = ops.conv2d(net, output_dim=128, k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv", use_sn=self._spectral_norm) net = net[:, :, :, :colors] else: net = ops.conv2d(net, output_dim=colors, k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv", use_sn=self._spectral_norm) logging.info("[Generator] after final processing: %s", net.shape) net = (tf.nn.tanh(net) + 1.0) / 2.0 return net @gin.configurable class Discriminator(abstract_arch.AbstractDiscriminator): """ResNet-based discriminator supporting resolutions 32, 64, 128, 256, 512.""" def __init__(self, ch=128, blocks_with_attention="B1", project_y=True, **kwargs): """Constructor for BigGAN discriminator. Args: ch: Channel multiplier. blocks_with_attention: Comma-separated list of blocks that are followed by a non-local block. project_y: Add an embedding of y in the output layer. **kwargs: additional arguments past on to ResNetDiscriminator. """ super(Discriminator, self).__init__(**kwargs) self._ch = ch self._blocks_with_attention = set(blocks_with_attention.split(",")) self._project_y = project_y def _resnet_block(self, name, in_channels, out_channels, scale): """ResNet block for the generator.""" if scale not in ["down", "none"]: raise ValueError( "Unknown discriminator ResNet block scaling: {}.".format(scale)) return BigGanDeepResNetBlock( name=name, in_channels=in_channels, out_channels=out_channels, scale=scale, spectral_norm=self._spectral_norm, batch_norm=self.batch_norm) def _get_in_out_channels(self, colors, resolution): # See Table 7-9. if colors not in [1, 3]: raise ValueError("Unsupported color channels: {}".format(colors)) if resolution == 512: channel_multipliers = [1, 1, 1, 2, 2, 4, 4] + 4 * [8] + 4 * [16] elif resolution == 256: channel_multipliers = [1, 2, 2, 4, 4] + 4 * [8] + 4 * [16] elif resolution == 128: channel_multipliers = [1, 2, 2, 4, 4] + 2 * [8] + 4 * [16] elif resolution == 64: channel_multipliers = [2, 4, 4] + 2 * [8] + 4 * [16] elif resolution == 32: channel_multipliers = 8 * [2] else: raise ValueError("Unsupported resolution: {}".format(resolution)) in_channels = [self._ch * c for c in channel_multipliers[:-1]] out_channels = [self._ch * c for c in channel_multipliers[1:]] return in_channels, out_channels def apply(self, x, y, is_training): """Apply the discriminator on a input. Args: x: `Tensor` of shape [batch_size, ?, ?, ?] with real or fake images. y: `Tensor` of shape [batch_size, num_classes] with one hot encoded labels. is_training: Boolean, whether the architecture should be constructed for training or inference. Returns: Tuple of 3 Tensors, the final prediction of the discriminator, the logits before the final output activation function and logits form the second last layer. """ logging.info("[Discriminator] inputs are x=%s, y=%s", x.shape, None if y is None else y.shape) resnet_ops.validate_image_inputs(x) in_channels, out_channels = self._get_in_out_channels( colors=x.shape[-1].value, resolution=x.shape[1].value) num_blocks = len(in_channels) net = ops.conv2d(x, output_dim=in_channels[0], k_h=3, k_w=3, d_h=1, d_w=1, name="initial_conv", use_sn=self._spectral_norm) for block_idx in range(num_blocks): scale = "down" if block_idx % 2 == 0 else "none" block = self._resnet_block( name="B{}".format(block_idx + 1), in_channels=in_channels[block_idx], out_channels=out_channels[block_idx], scale=scale) net = block(net, z=None, y=y, is_training=is_training) # At resolution 64x64 there is a self-attention block. if scale == "none" and net.shape[1].value == 64: logging.info("[Discriminator] Applying non-local block to %s", net.shape) net = ops.non_local_block(net, "non_local_block", use_sn=self._spectral_norm) # Final part logging.info("[Discriminator] before final processing: %s", net.shape) net = tf.nn.relu(net) h = tf.math.reduce_sum(net, axis=[1, 2]) out_logit = ops.linear(h, 1, scope="final_fc", use_sn=self._spectral_norm) logging.info("[Discriminator] after final processing: %s", net.shape) if self._project_y: if y is None: raise ValueError("You must provide class information y to project.") with tf.variable_scope("embedding_fc"): y_embedding_dim = out_channels[-1] # We do not use ops.linear() below since it does not have an option to # override the initializer. kernel = tf.get_variable( "kernel", [y.shape[1], y_embedding_dim], tf.float32, initializer=tf.initializers.glorot_normal()) if self._spectral_norm: kernel = ops.spectral_norm(kernel) embedded_y = tf.matmul(y, kernel) logging.info("[Discriminator] embedded_y for projection: %s", embedded_y.shape) out_logit += tf.reduce_sum(embedded_y * h, axis=1, keepdims=True) out = tf.nn.sigmoid(out_logit) return out, out_logit, h
compare_gan-master
compare_gan/architectures/resnet_biggan_deep.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test number of parameters for the BigGAN-Deep architecture.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from compare_gan import utils from compare_gan.architectures import arch_ops from compare_gan.architectures import resnet_biggan_deep import tensorflow as tf class ResNet5BigGanDeepTest(tf.test.TestCase): def testNumberOfParameters(self): with tf.Graph().as_default(): batch_size = 2 z = tf.zeros((batch_size, 128)) y = tf.one_hot(tf.ones((batch_size,), dtype=tf.int32), 1000) generator = resnet_biggan_deep.Generator( image_shape=(128, 128, 3), batch_norm_fn=arch_ops.conditional_batch_norm) fake_images = generator(z, y=y, is_training=True, reuse=False) self.assertEqual(fake_images.shape.as_list(), [batch_size, 128, 128, 3]) discriminator = resnet_biggan_deep.Discriminator() predictions = discriminator(fake_images, y, is_training=True) self.assertLen(predictions, 3) t_vars = tf.trainable_variables() g_vars = [var for var in t_vars if "generator" in var.name] d_vars = [var for var in t_vars if "discriminator" in var.name] g_param_overview = utils.get_parameter_overview(g_vars, limit=None) d_param_overview = utils.get_parameter_overview(d_vars, limit=None) g_param_overview = g_param_overview.split("\n") logging.info("Generator variables:") for i in range(0, len(g_param_overview), 80): logging.info("\n%s", "\n".join(g_param_overview[i:i + 80])) logging.info("Discriminator variables:\n%s", d_param_overview) g_num_weights = sum([v.get_shape().num_elements() for v in g_vars]) self.assertEqual(g_num_weights, 50244484) d_num_weights = sum([v.get_shape().num_elements() for v in d_vars]) self.assertEqual(d_num_weights, 34590210) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/architectures/resnet_biggan_deep_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow operations specific to TPUs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gin from six.moves import range import tensorflow as tf from tensorflow.contrib.tpu.python.tpu import tpu_function def cross_replica_concat(value, replica_id, num_replicas): """Reduce a concatenation of the `value` across TPU replicas. Args: value: Tensor to concatenate. replica_id: Integer tensor that indicates the index of the replica. num_replicas: Python integer, total number of replicas. Returns: Tensor of the same rank as value with first dimension `num_replicas` times larger. Raises: ValueError: If `value` is a scalar. """ if value.shape.ndims < 1: raise ValueError("Value must have at least rank 1 but got {}.".format( value.shape.ndims)) if num_replicas <= 1: return value with tf.name_scope(None, "tpu_cross_replica_concat"): # Mask is one hot encoded position of the core_index. mask = tf.to_float(tf.equal(tf.range(num_replicas), replica_id)) # Expand dims with 1's to match rank of value. mask = tf.reshape(mask, [num_replicas] + [1] * value.shape.ndims) if value.dtype in {tf.bfloat16, tf.float32}: result = mask * value else: result = mask * tf.to_float(value) # Thanks to broadcasting now result is set only in the position pointed by # replica_id, the rest of the vector is set to 0's. # All these steps are basically implementing tf.scatter_nd which is missing # in TPU's backend since it doesn't support sparse operations. # Merge first 2 dimensions. # This is equivalent to (value.shape[0].value * num_replicas). # Using [-1] trick to support also scalar input. result = tf.reshape(result, [-1] + result.shape.as_list()[2:]) # Each core set the "results" in position pointed by replica_id. When we now # sum across replicas we exchange the information and fill in local 0's with # values from other cores. result = tf.contrib.tpu.cross_replica_sum(result) # Now all the cores see exactly the same data. return tf.cast(result, dtype=value.dtype) def cross_replica_mean(inputs, group_size=None): """Calculates the average value of inputs tensor across TPU replicas.""" num_replicas = tpu_function.get_tpu_context().number_of_shards if not group_size: group_size = num_replicas if group_size == 1: return inputs if group_size != num_replicas: group_assignment = [] assert num_replicas % group_size == 0 for g in range(num_replicas // group_size): replica_ids = [g * group_size + i for i in range(group_size)] group_assignment.append(replica_ids) else: group_assignment = None return tf.contrib.tpu.cross_replica_sum(inputs, group_assignment) / tf.cast( group_size, inputs.dtype) @gin.configurable(blacklist=["inputs", "axis"]) def cross_replica_moments(inputs, axis, parallel=True, group_size=None): """Compute mean and variance of the inputs tensor across TPU replicas. Args: inputs: A tensor with 2 or more dimensions. axis: Array of ints. Axes along which to compute mean and variance. parallel: Use E[x^2] - (E[x])^2 to compute variance. Then can be done in parallel to computing the mean and reducing the communication overhead. group_size: Integer, the number of replicas to compute moments arcoss. None or 0 will use all replicas (global). Returns: Two tensors with mean and variance. """ # Compute local mean and then average across replicas. mean = tf.math.reduce_mean(inputs, axis=axis) mean = cross_replica_mean(mean) if parallel: # Compute variance using the E[x^2] - (E[x])^2 formula. This is less # numerically stable than the E[(x-E[x])^2] formula, but allows the two # cross-replica sums to be computed in parallel, saving communication # overhead. mean_of_squares = tf.reduce_mean(tf.square(inputs), axis=axis) mean_of_squares = cross_replica_mean(mean_of_squares, group_size=group_size) mean_squared = tf.square(mean) variance = mean_of_squares - mean_squared else: variance = tf.math.reduce_mean( tf.math.square(inputs - mean), axis=axis) variance = cross_replica_mean(variance, group_size=group_size) return mean, variance
compare_gan-master
compare_gan/tpu/tpu_ops.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provide methods for generating deterministic pseudorandom values. Random number generators in `tf.random` ignore the seed values on TPUs. An alternative are the stateless random number generators in `tf.contrib.stateless` which are deterministic but do not keep the a state. To get different but reproducible random values at each training step the user needs to provide a seed (a tensor of shape (2,)) that should change in every step. This small library handles this for the user by decomposing the seed into two values: a per operation seed and a global offset The per operation seed is fixed for each random generator in the graph and computed from the name of the operation (incl. name scope). The global offset is passed in as in integer from in the input function and thus changes every step. This guarantees that is different every step and always different between TPU cores within a step. Usage: - In your `input_fn` call `add_random_offset_to_features` and use the returned dataset. - At the beginning of your `model_fn` call `set_random_offset_from_features`. - Use the random number generators defined in this module. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib from absl import logging import tensorflow as tf _RANDOM_OFFSET_FEATURE_KEY = "_RANDOM_OFFSET" _RANDOM_OFFSET_TENSOR = None def add_random_offset_to_features(dataset, start=1): """Add a random offset to the dataset. Args: dataset: `tf.data.Dataset` object that contains tuples (features, labels), where `features` is a Python dictionary. start: A starting value for the global offset. Optional. Returns: A new `tf.data.Dataset` object with a extra feature for the random offset. """ dataset = dataset.apply(tf.data.experimental.enumerate_dataset(start=start)) def map_fn(offset, data): offset = tf.cast(offset, tf.int32) if isinstance(data, tuple) and len(data) == 2 and isinstance(data[0], dict): # Data is a tuple (features, labels) as expected by the Estimator # interface. logging.info("Passing random offset: %s with data %s.", offset, data) features, labels = data features[_RANDOM_OFFSET_FEATURE_KEY] = offset return features, labels raise ValueError("Data in dataset must be a tuple (features, labels) and " "features must be a Python dictionary. data was {}".format( data)) return dataset.map(map_fn) def set_random_offset_from_features(features): """Set the global random offset from the random offset feature.""" # Take the first index in case the TPU core got multiple examples. global _RANDOM_OFFSET_TENSOR _RANDOM_OFFSET_TENSOR = features.pop(_RANDOM_OFFSET_FEATURE_KEY)[0] logging.info("Got global random offset: %s", _RANDOM_OFFSET_TENSOR) def _get_seed(name=None): """Get a deterministic random seed for stateless generators. Args: name: Name of the operation that will use the seed. If None a unique name will be determined. Returns: An integer`Tensor` of shape (2,) with the seed for this op and the global random offset. """ if _RANDOM_OFFSET_TENSOR is None: raise ValueError("_RANDOM_OFFSET_TENSOR is None. Did you call " "set_random_offset_from_features() in your model_fn?") # Get a seed from the hash name of a dummy operation. This seed will only # depend on the name of the operation (incl. the scope name). It will be # unique within the graph and only change if the name of operation changes. with tf.name_scope("dummy_for_seed"): dummy_op = tf.no_op(name) # Using SHA-512 gives us a non-negative and uniformly distributed seed in the # interval [0, 2**512). This is consistent with TensorFlow, as TensorFlow # operations internally use the residue of the given seed modulo `2**31 - 1` # (see`tensorflow/python/framework/random_seed.py`). op_seed = int(hashlib.sha512(dummy_op.name.encode("utf-8")).hexdigest(), 16) op_seed = tf.constant(op_seed % (2**31 - 1)) logging.info("Using op_seed %s for operation %s.", op_seed, dummy_op.name) return tf.stack([op_seed, _RANDOM_OFFSET_TENSOR]) def uniform(shape, name=None): """Outputs pseudorandom random values from a uniform distribution. If the _RANDOM_OFFSET_TENSOR is set these output is deterministic based on the seed and the `name` of this operation. If `name` is None this will use the index in the graph instead. There is no `dtype` parameter since the underlying tf.contrib.stateless.stateless_random_uniform only supports tf.half, tf.float32 and tf.float64 and we do not care about tf.half and tf.float64. Patches welcome. Args: shape: A Tensor. Must be one of the following types: int32, int64. The shape of the output tensor. name: A name for the operation (optional). Returns: A Tensor. """ if _RANDOM_OFFSET_TENSOR is None: logging.warning("No global random offset set, falling back to " "un-deterministic pseudorandom numbers for operation %s.", name) return tf.random.uniform(shape, name=name) return tf.contrib.stateless.stateless_random_uniform( shape=shape, seed=_get_seed(name), name=name) def normal(shape, name=None): if _RANDOM_OFFSET_TENSOR is None: logging.warning("No global random offset set, falling back to " "un-deterministic pseudorandom numbers for operation %s.", name) return tf.random.normal(shape, name=name) return tf.contrib.stateless.stateless_random_normal( shape=shape, seed=_get_seed(name), name=name)
compare_gan-master
compare_gan/tpu/tpu_random.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests custom TensorFlow operations for TPU.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from absl.testing import parameterized from compare_gan.tpu import tpu_ops import numpy as np import tensorflow as tf class TpuOpsTpuTest(parameterized.TestCase, tf.test.TestCase): def testRunsOnTpu(self): """Verify that the test cases runs on a TPU chip and has 2 cores.""" expected_device_names = [ "/job:localhost/replica:0/task:0/device:CPU:0", "/job:localhost/replica:0/task:0/device:TPU:0", "/job:localhost/replica:0/task:0/device:TPU:1", "/job:localhost/replica:0/task:0/device:TPU_SYSTEM:0", ] with self.session() as sess: devices = sess.list_devices() logging.info("devices:\n%s", "\n".join([str(d) for d in devices])) self.assertAllEqual([d.name for d in devices], expected_device_names) def testCrossReplicaConcat(self): def computation(x, replica_id): logging.info("x: %s\nreplica_id: %s", x, replica_id[0]) return tpu_ops.cross_replica_concat(x, replica_id[0], num_replicas=2) inputs = np.asarray([[3, 4], [1, 5]]) expected_output = np.asarray([[3, 4], [1, 5], [3, 4], [1, 5]]) with tf.Graph().as_default(): x = tf.constant(inputs) replica_ids = tf.constant([0, 1], dtype=tf.int32) x_concat, = tf.contrib.tpu.batch_parallel( computation, [x, replica_ids], num_shards=2) self.assertAllEqual(x.shape.as_list(), [2, 2]) self.assertAllEqual(x_concat.shape.as_list(), [4, 2]) with self.session() as sess: sess.run(tf.contrib.tpu.initialize_system()) sess.run(tf.global_variables_initializer()) x_concat = sess.run(x_concat) logging.info("x_concat: %s", x_concat) self.assertAllClose(x_concat, expected_output) # Test with group size 2 (test case has 2 cores, so this global batch norm). @parameterized.parameters( {"group_size": None}, # Defaults to number of TPU cores. {"group_size": 0}, # Defaults to number of TPU cores. {"group_size": 2}, ) def testCrossReplicaMean(self, group_size): # Verify that we average across replicas by feeding 2 vectors to the system. # Each replica should get one vector which is then averaged across # all replicas and simply returned. # After that each replica has the same vector and since the outputs gets # concatenated we see the same vector twice. inputs = np.asarray( [[0.55, 0.70, -1.29, 0.502], [0.57, 0.90, 1.290, 0.202]], dtype=np.float32) expected_output = np.asarray( [[0.56, 0.8, 0.0, 0.352], [0.56, 0.8, 0.0, 0.352]], dtype=np.float32) def computation(x): self.assertAllEqual(x.shape.as_list(), [1, 4]) return tpu_ops.cross_replica_mean(x, group_size=group_size) with tf.Graph().as_default(): # Note: Using placeholders for feeding TPUs is discouraged but fine for # a simple test case. x = tf.placeholder(name="x", dtype=tf.float32, shape=inputs.shape) y = tf.contrib.tpu.batch_parallel(computation, inputs=[x], num_shards=2) with self.session() as sess: sess.run(tf.contrib.tpu.initialize_system()) # y is actually a list with one tensor. computation would be allowed # to return multiple tensors (and ops). actual_output = sess.run(y, {x: inputs})[0] self.assertAllEqual(actual_output.shape, (2, 4)) self.assertAllClose(actual_output, expected_output) def testCrossReplicaMeanGroupSizeOne(self, group_size=1): # Since the group size is 1 we only average over 1 replica. inputs = np.asarray( [[0.55, 0.70, -1.29, 0.502], [0.57, 0.90, 1.290, 0.202]], dtype=np.float32) expected_output = np.asarray( [[0.55, 0.7, -1.29, 0.502], [0.57, 0.9, 1.290, 0.202]], dtype=np.float32) def computation(x): self.assertAllEqual(x.shape.as_list(), [1, 4]) return tpu_ops.cross_replica_mean(x, group_size=group_size) with tf.Graph().as_default(): # Note: Using placeholders for feeding TPUs is discouraged but fine for # a simple test case. x = tf.placeholder(name="x", dtype=tf.float32, shape=inputs.shape) y = tf.contrib.tpu.batch_parallel(computation, inputs=[x], num_shards=2) with self.session() as sess: sess.run(tf.contrib.tpu.initialize_system()) # y is actually a list with one tensor. computation would be allowed # to return multiple tensors (and ops). actual_output = sess.run(y, {x: inputs})[0] self.assertAllEqual(actual_output.shape, (2, 4)) self.assertAllClose(actual_output, expected_output) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/tpu/tpu_ops_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8
compare_gan-master
compare_gan/tpu/__init__.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provide a helper class for using summaries on TPU via a host call. TPUEstimator does not support writing TF summaries out of the box and TPUs can't perform operations that write files to disk. To monitor tensor values during training you can copy the tensors back to the CPU of the host machine via a host call function. This small library provides a convienent API to do this. Example: from compare_gan.tpu import tpu_summaries def model_fn(features, labels, params, mode): summary = tpu_summries.TpuSummaries(my_model_dir) summary.scalar("my_scalar_summary", tensor1) summary.scalar("my_counter", tensor2, reduce_fn=tf.math.reduce_sum) return TPUEstimatorSpec( host_call=summary.get_host_call(), ...) Warning: The host call function will run every step. Writing large tensors to summaries can slow down your training. High ranking outfeed operations in your XProf profile can be an indication for this. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from absl import logging import tensorflow as tf summary = tf.contrib.summary # TensorFlow Summary API v2. TpuSummaryEntry = collections.namedtuple( "TpuSummaryEntry", "summary_fn name tensor reduce_fn") class TpuSummaries(object): """Class to simplify TF summaries on TPU. An instance of the class provides simple methods for writing summaries in the similar way to tf.summary. The difference is that each summary entry must provide a reduction function that is used to reduce the summary values from all the TPU cores. """ def __init__(self, log_dir, save_summary_steps=250): self._log_dir = log_dir self._entries = [] # While False no summary entries will be added. On TPU we unroll the graph # and don't want to add multiple summaries per step. self.record = True self._save_summary_steps = save_summary_steps def image(self, name, tensor, reduce_fn): """Add a summary for images. Tensor must be of 4-D tensor.""" if not self.record: return self._entries.append( TpuSummaryEntry(summary.image, name, tensor, reduce_fn)) def scalar(self, name, tensor, reduce_fn=tf.math.reduce_mean): """Add a summary for a scalar tensor.""" if not self.record: return tensor = tf.convert_to_tensor(tensor) if tensor.shape.ndims == 0: tensor = tf.expand_dims(tensor, 0) self._entries.append( TpuSummaryEntry(summary.scalar, name, tensor, reduce_fn)) def get_host_call(self): """Returns the tuple (host_call_fn, host_call_args) for TPUEstimatorSpec.""" # All host_call_args must be tensors with batch dimension. # All tensors are streamed to the host machine (mind the band width). global_step = tf.train.get_or_create_global_step() host_call_args = [tf.expand_dims(global_step, 0)] host_call_args.extend([e.tensor for e in self._entries]) logging.info("host_call_args: %s", host_call_args) return (self._host_call_fn, host_call_args) def _host_call_fn(self, step, *args): """Function that will run on the host machine.""" # Host call receives values from all tensor cores (concatenate on the # batch dimension). Step is the same for all cores. step = step[0] logging.info("host_call_fn: args=%s", args) with summary.create_file_writer(self._log_dir).as_default(): with summary.record_summaries_every_n_global_steps( self._save_summary_steps, step): for i, e in enumerate(self._entries): value = e.reduce_fn(args[i]) e.summary_fn(e.name, value, step=step) return summary.all_summary_ops()
compare_gan-master
compare_gan/tpu/tpu_summaries.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for deterministic TensorFlow operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import flags from absl import logging from absl.testing import parameterized from compare_gan.tpu import tpu_random import numpy as np from six.moves import range import tensorflow as tf FLAGS = flags.FLAGS class TpuRandomTest(parameterized.TestCase, tf.test.TestCase): def _run_graph_op_in_estimator(self, create_op_fn, model_dir, use_tpu, training_steps=4): """Helper function to test an operation within a Estimator. Args: create_op_fn: Function that will be called from within the model_fn. The returned op will be run as part of the training step. model_dir: Directory for saving checkpoints. use_tpu: Whether to use TPU. training_steps: Number of trainings steps. """ def input_fn(params): features = {"x": np.ones((8, 3), dtype=np.float32)} labels = np.ones((8, 1), dtype=np.float32) dataset = tf.data.Dataset.from_tensor_slices((features, labels)) # Add a feature for the random offset of operations in tpu_random.py. dataset = tpu_random.add_random_offset_to_features(dataset) return dataset.repeat().batch(params["batch_size"], drop_remainder=True) def model_fn(features, labels, mode, params): # Set the random offset tensor for operations in tpu_random.py. tpu_random.set_random_offset_from_features(features) test_op = create_op_fn() predictions = tf.layers.dense(features["x"], 1) loss = tf.losses.mean_squared_error(labels, predictions) optimizer = tf.train.GradientDescentOptimizer(0.01) if params["use_tpu"]: optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) with tf.control_dependencies([test_op]): train_op = optimizer.minimize( loss, global_step=tf.train.get_or_create_global_step()) return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=loss, train_op=train_op) if tf.gfile.Exists(model_dir): tf.gfile.DeleteRecursively(model_dir) run_config = tf.contrib.tpu.RunConfig( model_dir=model_dir, save_checkpoints_steps=1, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) estimator = tf.contrib.tpu.TPUEstimator( config=run_config, use_tpu=use_tpu, model_fn=model_fn, train_batch_size=2) estimator.train(input_fn, steps=training_steps) @parameterized.parameters( {"use_tpu": False}, {"use_tpu": True}, ) def testIsDeterministic(self, use_tpu): def create_op_fn(): z = tf.get_variable("z", (3,), tf.float32) random_z = tpu_random.uniform((3,), name="random_z") if use_tpu: random_z = tf.contrib.tpu.cross_replica_sum(random_z) return tf.assign(z, random_z).op model_dir_1 = os.path.join(FLAGS.test_tmpdir, "1") self._run_graph_op_in_estimator(create_op_fn, model_dir_1, use_tpu=use_tpu) model_dir_2 = os.path.join(FLAGS.test_tmpdir, "2") self._run_graph_op_in_estimator(create_op_fn, model_dir_2, use_tpu=use_tpu) for step in range(1, 5): self.assertTrue(tf.gfile.Exists( os.path.join(model_dir_1, "model.ckpt-{}.index".format(step)))) ckpt_1 = tf.train.load_checkpoint( os.path.join(model_dir_1, "model.ckpt-{}".format(step))) ckpt_2 = tf.train.load_checkpoint( os.path.join(model_dir_2, "model.ckpt-{}".format(step))) z_1 = ckpt_1.get_tensor("z") z_2 = ckpt_2.get_tensor("z") logging.info("step=%d, z_1=%s, z_2=%s", step, z_1, z_2) # Both runs are the same. self.assertAllClose(z_1, z_2) @parameterized.parameters( {"use_tpu": False}, {"use_tpu": True}, ) def testIsDifferentAcrossSteps(self, use_tpu): def create_op_fn(): z = tf.get_variable("z", (3,), tf.float32) random_z = tpu_random.uniform((3,), name="random_z") if use_tpu: random_z = tf.contrib.tpu.cross_replica_sum(random_z) return tf.assign(z, random_z).op model_dir = os.path.join(FLAGS.test_tmpdir, "1") self._run_graph_op_in_estimator(create_op_fn, model_dir, use_tpu=use_tpu) previous_z = None for step in range(1, 5): self.assertTrue(tf.gfile.Exists( os.path.join(model_dir, "model.ckpt-{}.index".format(step)))) ckpt = tf.train.load_checkpoint( os.path.join(model_dir, "model.ckpt-{}".format(step))) z = ckpt.get_tensor("z") logging.info("step=%d, z=%s", step, z) # Different to previous run. if previous_z is not None: self.assertNotAllClose(previous_z, z) previous_z = z def testIsDifferentAcrossCores(self): def create_op_fn(): z_sum = tf.get_variable("z_sum", (3,), tf.float32) z_first_core = tf.get_variable("z_first_core", (3,), tf.float32) random_z = tpu_random.uniform((3,), name="random_z") random_z_sum = tf.contrib.tpu.cross_replica_sum(random_z) return tf.group(tf.assign(z_sum, random_z_sum).op, tf.assign(z_first_core, random_z)) model_dir = os.path.join(FLAGS.test_tmpdir, "1") self._run_graph_op_in_estimator(create_op_fn, model_dir, use_tpu=True) for step in range(1, 5): self.assertTrue(tf.gfile.Exists( os.path.join(model_dir, "model.ckpt-{}.index".format(step)))) ckpt = tf.train.load_checkpoint( os.path.join(model_dir, "model.ckpt-{}".format(step))) z_sum = ckpt.get_tensor("z_sum") z_first_core = ckpt.get_tensor("z_first_core") logging.info("step=%d, z_sum=%s, z_first_core=%s", step, z_sum, z_first_core) # Sum is not the first core times 2. self.assertNotAllClose(z_sum, 2 * z_first_core) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/tpu/tpu_random_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides ModularGAN for GAN models with penalty loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import itertools from absl import flags from absl import logging from compare_gan import test_utils from compare_gan import utils from compare_gan.architectures import dcgan from compare_gan.architectures import infogan from compare_gan.architectures import resnet30 from compare_gan.architectures import resnet5 from compare_gan.architectures import resnet_biggan from compare_gan.architectures import resnet_biggan_deep from compare_gan.architectures import resnet_cifar from compare_gan.architectures import resnet_stl from compare_gan.architectures import sndcgan from compare_gan.gans import consts as c from compare_gan.gans import loss_lib from compare_gan.gans import penalty_lib from compare_gan.gans.abstract_gan import AbstractGAN from compare_gan.tpu import tpu_random from compare_gan.tpu import tpu_summaries import gin import numpy as np from six.moves import range import tensorflow as tf import tensorflow_gan as tfgan import tensorflow_hub as hub FLAGS = flags.FLAGS # pylint: disable=not-callable @gin.configurable(blacklist=["dataset", "parameters", "model_dir"]) class ModularGAN(AbstractGAN): """Base class for GANs models that support the Estimator API.""" def __init__(self, dataset, parameters, model_dir, deprecated_split_disc_calls=False, experimental_joint_gen_for_disc=False, experimental_force_graph_unroll=False, g_use_ema=False, ema_decay=0.9999, ema_start_step=40000, g_optimizer_fn=tf.train.AdamOptimizer, d_optimizer_fn=None, g_lr=0.0002, d_lr=None, conditional=False, fit_label_distribution=False): """ModularGAN is a Gin configurable implementation of AbstractGAN. Graph Unrolling: For better performance TPUs perform multiple training steps in a single session run call. To utilize this we perform both D and G training in a single training step. The inputs to model_fn are split into multiple sub-steps: One sub-step for each discriminator training step (disc_iters) and a separate sub-step (with new inputs) for the generator training step. The configured batch size is the batch size used in a sub-step. Warning: Graph unrolling can increase the memory requirement and load to memory issues on GPUs. Therefore it is turned off when running on GPUs, but can be forced to be on with experimental_force_graph_unroll. Args: dataset: `ImageDataset` object. If `conditional` the dataset must provide labels and the number of classes bust known. parameters: Legacy Python dictionary with additional parameters. This must have the keys 'architecture', 'z_dim' and 'lambda'. model_dir: Directory path for storing summary files. deprecated_split_disc_calls: If True pass fake and real images separately through the discriminator network. experimental_joint_gen_for_disc: If True generate fake images for all D iterations jointly. This increase the batch size in G when generating fake images for D. The G step is stays the same. experimental_force_graph_unroll: Force unrolling of the graph as described above. When running on TPU the graph is always unrolled. g_use_ema: If True keep moving averages for weights in G and use them in the TF-Hub module. ema_decay: Decay rate for moving averages for G's weights. ema_start_step: Start step for keeping moving averages. Before this the decay rate is 0. g_optimizer_fn: Function (or constructor) to return an optimizer for G. d_optimizer_fn: Function (or constructor) to return an optimizer for D. If None will call `g_optimizer_fn`. g_lr: Learning rate for G. d_lr: Learning rate for D. Defaults to `g_lr`. conditional: Whether the GAN is conditional. If True both G and Y will get passed labels. fit_label_distribution: Whether to fit the label distribution. """ super(ModularGAN, self).__init__( dataset=dataset, parameters=parameters, model_dir=model_dir) self._deprecated_split_disc_calls = deprecated_split_disc_calls self._experimental_joint_gen_for_disc = experimental_joint_gen_for_disc self._experimental_force_graph_unroll = experimental_force_graph_unroll self._g_use_ema = g_use_ema self._ema_decay = ema_decay self._ema_start_step = ema_start_step self._g_optimizer_fn = g_optimizer_fn self._d_optimizer_fn = d_optimizer_fn if self._d_optimizer_fn is None: self._d_optimizer_fn = g_optimizer_fn self._g_lr = g_lr self._d_lr = g_lr if d_lr is None else d_lr if conditional and not self._dataset.num_classes: raise ValueError( "Option 'conditional' selected but dataset {} does not have " "labels".format(self._dataset.name)) self._conditional = conditional self._fit_label_distribution = fit_label_distribution self._tpu_summary = tpu_summaries.TpuSummaries(model_dir) # Parameters that have not been ported to Gin. self._architecture = parameters["architecture"] self._z_dim = parameters["z_dim"] self._lambda = parameters["lambda"] # Number of discriminator iterations per one iteration of the generator. self._disc_iters = parameters.get("disc_iters", 1) self._force_graph_unroll = parameters.get("force_graph_unroll") # Will be set by create_loss(). self.d_loss = None self.g_loss = None self.penalty_loss = None # Cache for discriminator and generator objects. self._discriminator = None self._generator = None def _get_num_sub_steps(self, unroll_graph): if unroll_graph: return self._disc_iters + 1 return 1 @property def conditional(self): return self._conditional @property def generator(self): if self._generator is None: architecture_fns = { c.DCGAN_ARCH: dcgan.Generator, c.DUMMY_ARCH: test_utils.Generator, c.INFOGAN_ARCH: infogan.Generator, c.RESNET5_ARCH: resnet5.Generator, c.RESNET30_ARCH: resnet30.Generator, c.RESNET_BIGGAN_ARCH: resnet_biggan.Generator, c.RESNET_BIGGAN_DEEP_ARCH: resnet_biggan_deep.Generator, c.RESNET_CIFAR_ARCH: resnet_cifar.Generator, c.RESNET_STL_ARCH: resnet_stl.Generator, c.SNDCGAN_ARCH: sndcgan.Generator, } if self._architecture not in architecture_fns: raise NotImplementedError( "Generator architecture {} not implemented.".format( self._architecture)) self._generator = architecture_fns[self._architecture]( image_shape=self._dataset.image_shape) return self._generator @property def discriminator(self): """Returns an instantiation of `AbstractDiscriminator`.""" if self._discriminator is None: architecture_fns = { c.DCGAN_ARCH: dcgan.Discriminator, c.DUMMY_ARCH: test_utils.Discriminator, c.INFOGAN_ARCH: infogan.Discriminator, c.RESNET5_ARCH: resnet5.Discriminator, c.RESNET30_ARCH: resnet30.Discriminator, c.RESNET_BIGGAN_ARCH: resnet_biggan.Discriminator, c.RESNET_BIGGAN_DEEP_ARCH: resnet_biggan_deep.Discriminator, c.RESNET_CIFAR_ARCH: resnet_cifar.Discriminator, c.RESNET_STL_ARCH: resnet_stl.Discriminator, c.SNDCGAN_ARCH: sndcgan.Discriminator, } if self._architecture not in architecture_fns: raise NotImplementedError( "Discriminator architecture {} not implemented.".format( self._architecture)) self._discriminator = architecture_fns[self._architecture]() return self._discriminator def as_estimator(self, run_config, batch_size, use_tpu): """Returns a TPUEstimator for this GAN.""" unroll_graph = self._experimental_force_graph_unroll or use_tpu num_sub_steps = self._get_num_sub_steps(unroll_graph=unroll_graph) return tf.contrib.tpu.TPUEstimator( config=run_config, use_tpu=use_tpu, model_fn=self.model_fn, train_batch_size=batch_size * num_sub_steps) def _module_fn(self, model, batch_size): """Module Function to create a TF Hub module spec. Args: model: `tf.estimator.ModeKeys` value. batch_size: batch size. """ if model not in {"gen", "disc"}: raise ValueError("Model {} not support in module_fn()".format(model)) placeholder_fn = tf.placeholder if batch_size is None else tf.zeros is_training = False inputs = {} y = None if model == "gen": inputs["z"] = placeholder_fn( shape=(batch_size, self._z_dim), dtype=tf.float32, name="z_for_eval") elif model == "disc": inputs["images"] = placeholder_fn( shape=[batch_size] + list(self._dataset.image_shape), dtype=tf.float32, name="images_for_eval") if self.conditional: inputs["labels"] = placeholder_fn( shape=(batch_size,), dtype=tf.int32, name="labels_for_eval") y = self._get_one_hot_labels(inputs["labels"]) else: y = None logging.info("Creating module for model %s with inputs %s and y=%s", model, inputs, y) outputs = {} if model == "disc": outputs["prediction"], _, _ = self.discriminator( inputs["images"], y=y, is_training=is_training) else: z = inputs["z"] generated = self.generator(z=z, y=y, is_training=is_training) if self._g_use_ema: g_vars = [var for var in tf.trainable_variables() if "generator" in var.name] ema = tf.train.ExponentialMovingAverage(decay=self._ema_decay) # Create the variables that will be loaded from the checkpoint. ema.apply(g_vars) def ema_getter(getter, name, *args, **kwargs): var = getter(name, *args, **kwargs) ema_var = ema.average(var) if ema_var is None: var_names_without_ema = {"u_var", "accu_mean", "accu_variance", "accu_counter", "update_accus"} if name.split("/")[-1] not in var_names_without_ema: logging.warning("Could not find EMA variable for %s.", name) return var return ema_var with tf.variable_scope("", values=[z, y], reuse=True, custom_getter=ema_getter): ema_generated = self.generator(z, y=y, is_training=is_training) if not is_training: generated = ema_generated else: outputs["generated_ema_for_tensorboard"] = ema_generated outputs["generated"] = generated hub.add_signature(inputs=inputs, outputs=outputs) def as_module_spec(self): """Returns the generator network as TFHub module spec.""" models = ["gen", "disc"] default_batch_size = 64 batch_sizes = [8, 16, 32, 64] if "resnet" in self._architecture: # Only ResNet architectures support dynamic batch size. batch_sizes.append(None) default_batch_size = None tags_and_args = [ (set(), {"model": "gen", "batch_size": default_batch_size})] for model, bs in itertools.product(models, batch_sizes): tags = {model, "bs{}".format(bs)} args = {"model": model, "batch_size": bs} tags_and_args.append((tags, args)) return hub.create_module_spec( self._module_fn, tags_and_args=tags_and_args, drop_collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES]) def _grid_shape(self, num_summary_images): """Returns the shape for a rectangle grid with `num_summarry_images`.""" if num_summary_images & (num_summary_images - 1) != 0: raise ValueError( "Number of summary images must be a power of 2 to create a grid of " "images but was {}.".format(num_summary_images)) # Since b = 2^c we can use x = 2^(floor(c/2)) and y = 2^(ceil(c/2)). x = 2 ** int(np.log2(num_summary_images) / 2) y = num_summary_images // x return x, y def _add_images_to_summary(self, images, summary_name, params): """Called from model_fn() to add a grid of images as summary.""" # All summary tensors are synced to host 0 on every step. To avoid sending # more images then needed we transfer at most `sampler_per_replica` to # create a 8x8 image grid. batch_size_per_replica = images.shape[0].value num_replicas = params["context"].num_replicas if "context" in params else 1 total_num_images = batch_size_per_replica * num_replicas if total_num_images >= 64: grid_shape = (8, 8) # This can be more than 64. We slice all_images below. samples_per_replica = int(np.ceil(64 / num_replicas)) else: grid_shape = self._grid_shape(total_num_images) samples_per_replica = batch_size_per_replica def _merge_images_to_grid(all_images): logging.info("Creating images summary for fake images: %s", all_images) return tfgan.eval.image_grid( all_images[:np.prod(grid_shape)], grid_shape=grid_shape, image_shape=self._dataset.image_shape[:2], num_channels=self._dataset.image_shape[2]) self._tpu_summary.image(summary_name, images[:samples_per_replica], reduce_fn=_merge_images_to_grid) def _check_variables(self): """Check that every variable belongs to either G or D.""" t_vars = tf.trainable_variables() g_vars = self.generator.trainable_variables d_vars = self.discriminator.trainable_variables shared_vars = set(d_vars) & set(g_vars) if shared_vars: logging.info("g_vars: %s", g_vars) logging.info("d_vars: %s", d_vars) raise ValueError("Shared trainable variables: %s" % shared_vars) unused_vars = set(t_vars) - set(d_vars) - set(g_vars) if unused_vars: raise ValueError("Unused trainable variables: %s" % unused_vars) def _get_one_hot_labels(self, labels): if not self.conditional: raise ValueError( "_get_one_hot_labels() called but GAN is not conditional.") return tf.one_hot(labels, self._dataset.num_classes) @gin.configurable("z", blacklist=["shape", "name"]) def z_generator(self, shape, distribution_fn=tf.random.uniform, minval=-1.0, maxval=1.0, stddev=1.0, name=None): """Random noise distributions as TF op. Args: shape: A 1-D integer Tensor or Python array. distribution_fn: Function that create a Tensor. If the function has any of the arguments 'minval', 'maxval' or 'stddev' these are passed to it. minval: The lower bound on the range of random values to generate. maxval: The upper bound on the range of random values to generate. stddev: The standard deviation of a normal distribution. name: A name for the operation. Returns: Tensor with the given shape and dtype tf.float32. """ return utils.call_with_accepted_args( distribution_fn, shape=shape, minval=minval, maxval=maxval, stddev=stddev, name=name) def label_generator(self, shape, name=None): if not self.conditional: raise ValueError("label_generator() called but GAN is not conditional.") # Assume uniform label distribution. return tf.random.uniform(shape, minval=0, maxval=self._dataset.num_classes, dtype=tf.int32, name=name) def _preprocess_fn(self, images, labels, seed=None): """Creates the feature dictionary with images and z.""" logging.info("_preprocess_fn(): images=%s, labels=%s, seed=%s", images, labels, seed) tf.set_random_seed(seed) features = { "images": images, "z": self.z_generator([self._z_dim], name="z"), } if self.conditional: if self._fit_label_distribution: features["sampled_labels"] = labels else: features["sampled_labels"] = self.label_generator( shape=[], name="sampled_labels") return features, labels def input_fn(self, params, mode): """Input function that retuns a `tf.data.Dataset` object. This function will be called once for each host machine. Args: params: Python dictionary with parameters given to TPUEstimator. Additional TPUEstimator will set the key `batch_size` with the batch size for this host machine and `tpu_contextu` with a TPUContext object. mode: `tf.estimator.MoedeKeys` value. Returns: A `tf.data.Dataset` object with batched features and labels. """ return self._dataset.input_fn(mode=mode, params=params, preprocess_fn=self._preprocess_fn) def _split_inputs_and_generate_samples(self, features, labels, num_sub_steps): # Encode labels. if self.conditional: assert "sampled_labels" in features features["sampled_y"] = self._get_one_hot_labels( features["sampled_labels"]) # Split inputs for sub-steps. fs = [(k, tf.split(features[k], num_sub_steps)) for k in features] fs = [{k: v[i] for k, v in fs} for i in range(num_sub_steps)] ls = tf.split(labels, num_sub_steps) total_batch_size = features["z"].shape[0].value assert total_batch_size % num_sub_steps == 0 batch_size = total_batch_size // num_sub_steps if self._experimental_joint_gen_for_disc: # Generate samples from G for D steps. with tf.name_scope("gen_for_disc"): # Only the last sub-step changes the generator weights. Thus we can # combine all forward passes through G to achieve better efficiency. # The forward pass for G's step needs to be separated since compute # gradients for it. z = features["z"][:batch_size * self._disc_iters] sampled_y = None if self.conditional: sampled_y = features["sampled_y"][:batch_size * self._disc_iters] generated = self.generator(z, y=sampled_y, is_training=True) generated = tf.split(generated, self._disc_iters) for i in range(self._disc_iters): fs[i]["generated"] = generated[i] # Generate samples from G for G step. with tf.name_scope("gen_for_gen"): sampled_y = fs[-1].get("sampled_y", None) fs[-1]["generated"] = self.generator( fs[-1]["z"], y=sampled_y, is_training=True) else: for f in fs: sampled_y = f.get("sampled_y", None) f["generated"] = self.generator(f["z"], y=sampled_y, is_training=True) return fs, ls def _train_discriminator(self, features, labels, step, optimizer, params): features = features.copy() features["generated"] = tf.stop_gradient(features["generated"]) # Set the random offset tensor for operations in tpu_random.py. tpu_random.set_random_offset_from_features(features) # create_loss will set self.d_loss. self.create_loss(features, labels, params=params) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize( self.d_loss, var_list=self.discriminator.trainable_variables, global_step=step) with tf.control_dependencies([train_op]): return tf.identity(self.d_loss) def _train_generator(self, features, labels, step, optimizer, params): # Set the random offset tensor for operations in tpu_random.py. tpu_random.set_random_offset_from_features(features) # create_loss will set self.g_loss. self.create_loss(features, labels, params=params) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize( self.g_loss, var_list=self.generator.trainable_variables, global_step=step) if self._g_use_ema: g_vars = self.generator.trainable_variables with tf.name_scope("generator_ema"): logging.info("Creating moving averages of weights: %s", g_vars) # The decay value is set to 0 if we're before the moving-average start # point, so that the EMA vars will be the normal vars. decay = self._ema_decay * tf.cast( tf.greater_equal(step, self._ema_start_step), tf.float32) ema = tf.train.ExponentialMovingAverage(decay=decay) with tf.control_dependencies([train_op]): train_op = ema.apply(g_vars) with tf.control_dependencies([train_op]): return tf.identity(self.g_loss) def model_fn(self, features, labels, params, mode): """Constructs the model for the given features and mode. Args: features: A dictionary with the feature tensors. labels: Tensor will labels. Will be None if mode is PREDICT. params: Dictionary with hyperparameters passed to TPUEstimator. Additional TPUEstimator will set 3 keys: `batch_size`, `use_tpu`, `tpu_context`. `batch_size` is the batch size for this core. mode: `tf.estimator.ModeKeys` value (TRAIN, EVAL, PREDICT). The mode should be passed to the TPUEstimatorSpec and your model should be build this mode. Returns: A `tf.contrib.tpu.TPUEstimatorSpec`. """ logging.info("model_fn(): features=%s, labels=%s,mode=%s, params=%s", features, labels, mode, params) if mode != tf.estimator.ModeKeys.TRAIN: raise ValueError("Only training mode is supported.") use_tpu = params["use_tpu"] unroll_graph = self._experimental_force_graph_unroll or use_tpu num_sub_steps = self._get_num_sub_steps(unroll_graph=unroll_graph) if unroll_graph: logging.warning("Graph will be unrolled.") if self._experimental_joint_gen_for_disc and not unroll_graph: raise ValueError("Joining G forward passes is only supported for ", "unrolled graphs.") # Clean old summaries from previous calls to model_fn(). self._tpu_summary = tpu_summaries.TpuSummaries(self._model_dir) # Get features for each sub-step. fs, ls = self._split_inputs_and_generate_samples( features, labels, num_sub_steps=num_sub_steps) disc_optimizer = self.get_disc_optimizer(params["use_tpu"]) disc_step = tf.get_variable( "global_step_disc", [], dtype=tf.int32, trainable=False) train_disc_fn = functools.partial( self._train_discriminator, step=disc_step, optimizer=disc_optimizer, params=params) gen_optimizer = self.get_gen_optimizer(params["use_tpu"]) gen_step = tf.train.get_or_create_global_step() train_gen_fn = functools.partial( self._train_generator, features=fs[-1], labels=ls[-1], step=gen_step, optimizer=gen_optimizer, params=params) if not unroll_graph and self._disc_iters != 1: train_fn = train_gen_fn train_gen_fn = lambda: tf.cond( tf.equal(disc_step % self._disc_iters, 0), train_fn, lambda: 0.0) # Train D. d_losses = [] d_steps = self._disc_iters if unroll_graph else 1 for i in range(d_steps): with tf.name_scope("disc_step_{}".format(i + 1)): with tf.control_dependencies(d_losses): d_losses.append(train_disc_fn(features=fs[i], labels=ls[i])) # Train G. with tf.control_dependencies(d_losses): with tf.name_scope("gen_step"): g_loss = train_gen_fn() for i, d_loss in enumerate(d_losses): self._tpu_summary.scalar("loss/d_{}".format(i), d_loss) self._tpu_summary.scalar("loss/g", g_loss) self._add_images_to_summary(fs[0]["generated"], "fake_images", params) self._add_images_to_summary(fs[0]["images"], "real_images", params) self._check_variables() utils.log_parameter_overview(self.generator.trainable_variables, msg="Generator variables:") utils.log_parameter_overview(self.discriminator.trainable_variables, msg="Discriminator variables:") return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, host_call=self._tpu_summary.get_host_call(), # Estimator requires a loss which gets displayed on TensorBoard. # The given Tensor is evaluated but not used to create gradients. loss=d_losses[0], train_op=g_loss.op) def get_disc_optimizer(self, use_tpu=True): opt = self._d_optimizer_fn(self._d_lr, name="d_opt") if use_tpu: opt = tf.contrib.tpu.CrossShardOptimizer(opt) return opt def get_gen_optimizer(self, use_tpu=True): opt = self._g_optimizer_fn(self._g_lr, name="g_opt") if use_tpu: opt = tf.contrib.tpu.CrossShardOptimizer(opt) return opt def create_loss(self, features, labels, params, is_training=True): """Build the loss tensors for discriminator and generator. This method will set self.d_loss and self.g_loss. Args: features: Optional dictionary with inputs to the model ("images" should contain the real images and "z" the noise for the generator). labels: Tensor will labels. Use self._get_one_hot_labels(labels) to get a one hot encoded tensor. params: Dictionary with hyperparameters passed to TPUEstimator. Additional TPUEstimator will set 3 keys: `batch_size`, `use_tpu`, `tpu_context`. `batch_size` is the batch size for this core. is_training: If True build the model in training mode. If False build the model for inference mode (e.g. use trained averages for batch norm). Raises: ValueError: If set of meta/hyper parameters is not supported. """ images = features["images"] # Real images. generated = features["generated"] # Fake images. if self.conditional: y = self._get_one_hot_labels(labels) sampled_y = self._get_one_hot_labels(features["sampled_labels"]) all_y = tf.concat([y, sampled_y], axis=0) else: y = None sampled_y = None all_y = None if self._deprecated_split_disc_calls: with tf.name_scope("disc_for_real"): d_real, d_real_logits, _ = self.discriminator( images, y=y, is_training=is_training) with tf.name_scope("disc_for_fake"): d_fake, d_fake_logits, _ = self.discriminator( generated, y=sampled_y, is_training=is_training) else: # Compute discriminator output for real and fake images in one batch. all_images = tf.concat([images, generated], axis=0) d_all, d_all_logits, _ = self.discriminator( all_images, y=all_y, is_training=is_training) d_real, d_fake = tf.split(d_all, 2) d_real_logits, d_fake_logits = tf.split(d_all_logits, 2) self.d_loss, _, _, self.g_loss = loss_lib.get_losses( d_real=d_real, d_fake=d_fake, d_real_logits=d_real_logits, d_fake_logits=d_fake_logits) penalty_loss = penalty_lib.get_penalty_loss( x=images, x_fake=generated, y=y, is_training=is_training, discriminator=self.discriminator) self.d_loss += self._lambda * penalty_loss if hasattr(self.discriminator, '_quantize_loss') and self.discriminator._quantize_loss is not None: self.d_loss += self.discriminator._quantize_loss
compare_gan-master
compare_gan/gans/modular_gan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for GANs with different regularizers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.gans import consts as c from compare_gan.gans import loss_lib from compare_gan.gans import penalty_lib from compare_gan.gans.modular_gan import ModularGAN import gin import tensorflow as tf FLAGS = flags.FLAGS TEST_ARCHITECTURES = [c.RESNET5_ARCH, c.RESNET_BIGGAN_ARCH, c.RESNET_CIFAR_ARCH] TEST_LOSSES = [loss_lib.non_saturating, loss_lib.wasserstein, loss_lib.least_squares, loss_lib.hinge] TEST_PENALTIES = [penalty_lib.no_penalty, penalty_lib.dragan_penalty, penalty_lib.wgangp_penalty, penalty_lib.l2_penalty] class ModularGANConditionalTest(parameterized.TestCase, test_utils.CompareGanTestCase): def _runSingleTrainingStep(self, architecture, loss_fn, penalty_fn, labeled_dataset): parameters = { "architecture": architecture, "lambda": 1, "z_dim": 120, } with gin.unlock_config(): gin.bind_parameter("penalty.fn", penalty_fn) gin.bind_parameter("loss.fn", loss_fn) model_dir = self._get_empty_model_dir() run_config = tf.contrib.tpu.RunConfig( model_dir=model_dir, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, conditional=True, model_dir=model_dir) estimator = gan.as_estimator(run_config, batch_size=2, use_tpu=False) estimator.train(gan.input_fn, steps=1) @parameterized.parameters(TEST_ARCHITECTURES) def testSingleTrainingStepArchitectures(self, architecture): self._runSingleTrainingStep(architecture, loss_lib.hinge, penalty_lib.no_penalty, True) @parameterized.parameters(TEST_LOSSES) def testSingleTrainingStepLosses(self, loss_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_fn, penalty_lib.no_penalty, labeled_dataset=True) @parameterized.parameters(TEST_PENALTIES) def testSingleTrainingStepPenalties(self, penalty_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_lib.hinge, penalty_fn, labeled_dataset=True) def testUnlabledDatasetRaisesError(self): parameters = { "architecture": c.RESNET_CIFAR_ARCH, "lambda": 1, "z_dim": 120, } with gin.unlock_config(): gin.bind_parameter("loss.fn", loss_lib.hinge) # Use dataset without labels. dataset = datasets.get_dataset("celeb_a") model_dir = self._get_empty_model_dir() with self.assertRaises(ValueError): gan = ModularGAN( dataset=dataset, parameters=parameters, conditional=True, model_dir=model_dir) del gan if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/gans/modular_gan_conditional_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Interface for GAN models that can be trained using the Estimator API.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six import tensorflow as tf @six.add_metaclass(abc.ABCMeta) class AbstractGAN(object): """Interface for GAN models that can be training using the Estimator API.""" def __init__(self, dataset, parameters, model_dir): super(AbstractGAN, self).__init__() self._dataset = dataset self._parameters = parameters self._model_dir = model_dir def as_estimator(self, run_config, batch_size, use_tpu): """Returns a TPUEstimator for this GAN.""" return tf.contrib.tpu.TPUEstimator( config=run_config, use_tpu=use_tpu, model_fn=self.model_fn, train_batch_size=batch_size) @abc.abstractmethod def as_module_spec(self, params, mode): """Returns the generator network as TFHub module spec.""" @abc.abstractmethod def input_fn(self, params, mode): """Input function that retuns a `tf.data.Dataset` object. This function will be called once for each host machine. Args: params: Python dictionary with parameters given to TPUEstimator. Additional TPUEstimator will set the key `batch_size` with the batch size for this host machine and `tpu_contextu` with a TPUContext object. mode: `tf.estimator.MoedeKeys` value. Returns: A `tf.data.Dataset` object with batched features and labels. """ @abc.abstractmethod def model_fn(self, features, labels, params, mode): """Constructs the model for the given features and mode. This interface only requires implementing the TRAIN mode. On TPUs the model_fn should construct a graph for a single TPU core. Wrap the optimizer with a `tf.contrib.tpu.CrossShardOptimizer` to do synchronous training with all TPU cores.c Args: features: A dictionary with the feature tensors. labels: Tensor will labels. Will be None if mode is PREDICT. params: Dictionary with hyperparameters passed to TPUEstimator. Additional TPUEstimator will set 3 keys: `batch_size`, `use_tpu`, `tpu_context`. `batch_size` is the batch size for this core. mode: `tf.estimator.ModeKeys` value (TRAIN, EVAL, PREDICT). The mode should be passed to the TPUEstimatorSpec and your model should be build this mode. Returns: A `tf.contrib.tpu.TPUEstimatorSpec`. """
compare_gan-master
compare_gan/gans/abstract_gan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8
compare_gan-master
compare_gan/gans/__init__.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for SSGANs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.architectures.arch_ops import evonorm_s0 from compare_gan.gans import consts as c from compare_gan.gans import loss_lib from compare_gan.gans import penalty_lib from compare_gan.gans.clgan import CLGAN import gin import tensorflow as tf FLAGS = flags.FLAGS TEST_ARCHITECTURES = [c.RESNET_CIFAR_ARCH, c.SNDCGAN_ARCH, c.RESNET5_ARCH] TEST_LOSSES = [loss_lib.non_saturating, loss_lib.hinge] TEST_PENALTIES = [penalty_lib.no_penalty, penalty_lib.wgangp_penalty] class CLGANTest(parameterized.TestCase, test_utils.CompareGanTestCase): def _runSingleTrainingStep(self, architecture, loss_fn, penalty_fn): parameters = { "architecture": architecture, "lambda": 1, "z_dim": 128, } with gin.unlock_config(): gin.bind_parameter("penalty.fn", penalty_fn) gin.bind_parameter("loss.fn", loss_fn) gin.bind_parameter("G.batch_norm_fn", evonorm_s0) model_dir = self._get_empty_model_dir() run_config = tf.contrib.tpu.RunConfig( model_dir=model_dir, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) dataset = datasets.get_dataset("cifar10") gan = CLGAN( dataset=dataset, parameters=parameters, model_dir=model_dir, g_optimizer_fn=tf.train.AdamOptimizer, g_lr=0.0002, ) estimator = gan.as_estimator(run_config, batch_size=2, use_tpu=False) estimator.train(gan.input_fn, steps=1) @parameterized.parameters(TEST_ARCHITECTURES) def testSingleTrainingStepArchitectures(self, architecture): self._runSingleTrainingStep(architecture, loss_lib.hinge, penalty_lib.no_penalty) @parameterized.parameters(TEST_LOSSES) def testSingleTrainingStepLosses(self, loss_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_fn, penalty_lib.no_penalty) @parameterized.parameters(TEST_PENALTIES) def testSingleTrainingStepPenalties(self, penalty_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_lib.hinge, penalty_fn) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/gans/clgan_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of popular GAN penalties.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan import utils from compare_gan.gans import ops import gin import tensorflow as tf @gin.configurable def no_penalty(): return tf.constant(0.0) @gin.configurable(whitelist=[]) def dragan_penalty(discriminator, x, y, is_training): """Returns the DRAGAN gradient penalty. Args: discriminator: Instance of `AbstractDiscriminator`. x: Samples from the true distribution, shape [bs, h, w, channels]. y: Encoded class embedding for the samples. None for unsupervised models. is_training: boolean, are we in train or eval model. Returns: A tensor with the computed penalty. """ with tf.name_scope("dragan_penalty"): _, var = tf.nn.moments(x, axes=list(range(len(x.get_shape())))) std = tf.sqrt(var) x_noisy = x + std * (ops.random_uniform(x.shape) - 0.5) x_noisy = tf.clip_by_value(x_noisy, 0.0, 1.0) logits = discriminator(x_noisy, y=y, is_training=is_training, reuse=True)[1] gradients = tf.gradients(logits, [x_noisy])[0] slopes = tf.sqrt(0.0001 + tf.reduce_sum( tf.square(gradients), reduction_indices=[1, 2, 3])) gradient_penalty = tf.reduce_mean(tf.square(slopes - 1.0)) return gradient_penalty @gin.configurable(whitelist=[]) def wgangp_penalty(discriminator, x, x_fake, y, is_training): """Returns the WGAN gradient penalty. Args: discriminator: Instance of `AbstractDiscriminator`. x: samples from the true distribution, shape [bs, h, w, channels]. x_fake: samples from the fake distribution, shape [bs, h, w, channels]. y: Encoded class embedding for the samples. None for unsupervised models. is_training: boolean, are we in train or eval model. Returns: A tensor with the computed penalty. """ with tf.name_scope("wgangp_penalty"): alpha = ops.random_uniform(shape=[x.shape[0].value, 1, 1, 1], name="alpha") interpolates = x + alpha * (x_fake - x) logits = discriminator( interpolates, y=y, is_training=is_training, reuse=True)[1] gradients = tf.gradients(logits, [interpolates])[0] slopes = tf.sqrt(0.0001 + tf.reduce_sum( tf.square(gradients), reduction_indices=[1, 2, 3])) gradient_penalty = tf.reduce_mean(tf.square(slopes - 1.0)) return gradient_penalty @gin.configurable(whitelist=[]) def l2_penalty(discriminator): """Returns the L2 penalty for each matrix/vector excluding biases. Assumes a specific tensor naming followed throughout the compare_gan library. We penalize all fully connected, conv2d, and deconv2d layers. Args: discriminator: Instance of `AbstractDiscriminator`. Returns: A tensor with the computed penalty. """ with tf.name_scope("l2_penalty"): d_weights = [v for v in discriminator.trainable_variables if v.name.endswith("/kernel:0")] return tf.reduce_mean( [tf.nn.l2_loss(i) for i in d_weights], name="l2_penalty") @gin.configurable("penalty", whitelist=["fn"]) def get_penalty_loss(fn=no_penalty, **kwargs): """Returns the penalty loss.""" return utils.call_with_accepted_args(fn, **kwargs)
compare_gan-master
compare_gan/gans/penalty_lib.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines constants used across the code base.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function NORMAL_INIT = "normal" TRUNCATED_INIT = "truncated" ORTHOGONAL_INIT = "orthogonal" INITIALIZERS = [NORMAL_INIT, TRUNCATED_INIT, ORTHOGONAL_INIT] DCGAN_ARCH = "dcgan_arch" DUMMY_ARCH = "dummy_arch" INFOGAN_ARCH = "infogan_arch" RESNET5_ARCH = "resnet5_arch" RESNET30_ARCH = "resnet30_arch" RESNET_BIGGAN_ARCH = "resnet_biggan_arch" RESNET_BIGGAN_DEEP_ARCH = "resnet_biggan_deep_arch" RESNET_CIFAR_ARCH = "resnet_cifar_arch" RESNET_STL_ARCH = "resnet_stl_arch" SNDCGAN_ARCH = "sndcgan_arch" ARCHITECTURES = [INFOGAN_ARCH, DCGAN_ARCH, RESNET5_ARCH, RESNET30_ARCH, RESNET_BIGGAN_ARCH, RESNET_BIGGAN_DEEP_ARCH, RESNET_CIFAR_ARCH, RESNET_STL_ARCH, SNDCGAN_ARCH]
compare_gan-master
compare_gan/gans/consts.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of Self-Supervised GAN with auxiliary rotation loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl import logging from compare_gan.architectures import arch_ops as ops from compare_gan.gans import loss_lib from compare_gan.gans import modular_gan from compare_gan.gans import utils import gin import numpy as np import tensorflow as tf FLAGS = flags.FLAGS NUM_ROTATIONS = 4 # pylint: disable=not-callable @gin.configurable(blacklist=["kwargs"]) class S3GAN(modular_gan.ModularGAN): """S3GAN which enables auxiliary heads for the modular GAN.""" def __init__(self, self_supervision="rotation", rotated_batch_fraction=gin.REQUIRED, weight_rotation_loss_d=1.0, weight_rotation_loss_g=0.2, project_y=False, use_predictor=False, use_soft_pred=False, weight_class_loss=1.0, use_soft_labels=False, **kwargs): """Instantiates the S3GAN. Args: self_supervision: One of [rotation_gan, None]. rotated_batch_fraction: This must be a divisor of the total batch size. rotations of each images on each TPU core. For GPU training #CORES is 1. weight_rotation_loss_d: Weight for the rotation loss for the discriminator on real images. weight_rotation_loss_g: Weight for the rotation loss for the generator on fake images. project_y: Boolean, whether an embedding layer as in variant 1) should be used. use_predictor: Boolean, whether a predictor (classifier) should be used. use_soft_pred: Boolean, whether soft labels should be used for the predicted label vectors in 1). weight_class_loss: weight of the (predictor) classification loss added to the discriminator loss. use_soft_labels: Boolean, if true assumes the labels passed for real examples are soft labels and accordingly does not transform **kwargs: Additional arguments passed to `ModularGAN` constructor. """ super(S3GAN, self).__init__(**kwargs) if use_predictor and not project_y: raise ValueError("Using predictor requires projection.") assert self_supervision in {"none", "rotation"} self._self_supervision = self_supervision self._rotated_batch_fraction = rotated_batch_fraction self._weight_rotation_loss_d = weight_rotation_loss_d self._weight_rotation_loss_g = weight_rotation_loss_g self._project_y = project_y self._use_predictor = use_predictor self._use_soft_pred = use_soft_pred self._weight_class_loss = weight_class_loss self._use_soft_labels = use_soft_labels # To safe memory ModularGAN supports feeding real and fake samples # separately through the discriminator. S3GAN does not support this to # avoid additional additional complexity in create_loss(). assert not self._deprecated_split_disc_calls, \ "Splitting discriminator calls is not supported in S3GAN." def discriminator_with_additonal_heads(self, x, y, is_training): """Discriminator architecture with additional heads. Possible heads built on top of feature representation of the discriminator: (1) Classify the image to the correct class. (2) Classify the rotation of the image. Args: x: An input image tensor. y: One-hot encoded label. Passing all zeros implies no label was passed. is_training: boolean, whether or not it is a training call. Returns: Tuple of 5 Tensors: (1) discriminator predictions (in [0, 1]), (2) the corresponding logits, (3) predictions (logits) of the rotation of x from the auxiliary head, (4) logits of the class prediction from the auxiliary head, (5) Indicator vector identifying whether y contained a label or -1. """ d_probs, d_logits, x_rep = self.discriminator( x, y=y, is_training=is_training) use_sn = self.discriminator._spectral_norm # pylint: disable=protected-access is_label_available = tf.cast(tf.cast( tf.reduce_sum(y, axis=1, keepdims=True), tf.float32) > 0.5, tf.float32) assert x_rep.shape.ndims == 2, x_rep.shape # Predict the rotation of the image. rotation_logits = None if "rotation" in self._self_supervision: with tf.variable_scope("discriminator_rotation", reuse=tf.AUTO_REUSE): rotation_logits = ops.linear( x_rep, NUM_ROTATIONS, scope="score_classify", use_sn=use_sn) logging.info("[Discriminator] rotation head %s -> %s", x_rep.shape, rotation_logits) if not self._project_y: return d_probs, d_logits, rotation_logits, None, is_label_available # Predict the class of the image. aux_logits = None if self._use_predictor: with tf.variable_scope("discriminator_predictor", reuse=tf.AUTO_REUSE): aux_logits = ops.linear(x_rep, y.shape[1], use_bias=True, scope="predictor_linear", use_sn=use_sn) # Apply the projection discriminator if needed. if self._use_soft_pred: y_predicted = tf.nn.softmax(aux_logits) else: y_predicted = tf.one_hot( tf.arg_max(aux_logits, 1), aux_logits.shape[1]) y = (1.0 - is_label_available) * y_predicted + is_label_available * y y = tf.stop_gradient(y) logging.info("[Discriminator] %s -> aux_logits=%s, y_predicted=%s", aux_logits.shape, aux_logits.shape, y_predicted.shape) class_embedding = self.get_class_embedding( y=y, embedding_dim=x_rep.shape[-1].value, use_sn=use_sn) d_logits += tf.reduce_sum(class_embedding * x_rep, axis=1, keepdims=True) d_probs = tf.nn.sigmoid(d_logits) return d_probs, d_logits, rotation_logits, aux_logits, is_label_available def get_class_embedding(self, y, embedding_dim, use_sn): with tf.variable_scope("discriminator_projection", reuse=tf.AUTO_REUSE): # We do not use ops.linear() below since it does not have an option to # override the initializer. kernel = tf.get_variable( "kernel", [y.shape[1], embedding_dim], tf.float32, initializer=tf.initializers.glorot_normal()) if use_sn: kernel = ops.spectral_norm(kernel) embedded_y = tf.matmul(y, kernel) logging.info("[Discriminator] embedded_y for projection: %s", embedded_y.shape) return embedded_y def merge_with_rotation_data(self, real, fake, real_labels, fake_labels, num_rot_examples): """Returns the original data concatenated with the rotated version.""" # Put all rotation angles in a single batch, the first batch_size are # the original up-right images, followed by rotated_batch_size * 3 # rotated images with 3 different angles. For NUM_ROTATIONS=4 and # num_rot_examples=2 we have labels_rotated [0, 0, 1, 1, 2, 2, 3, 3]. real_to_rot, fake_to_rot = ( real[-num_rot_examples:], fake[-num_rot_examples:]) real_rotated = utils.rotate_images(real_to_rot, rot90_scalars=(1, 2, 3)) fake_rotated = utils.rotate_images(fake_to_rot, rot90_scalars=(1, 2, 3)) all_features = tf.concat([real, real_rotated, fake, fake_rotated], 0) all_labels = None if self.conditional: real_rotated_labels = tf.tile(real_labels[-num_rot_examples:], [3, 1]) fake_rotated_labels = tf.tile(fake_labels[-num_rot_examples:], [3, 1]) all_labels = tf.concat([real_labels, real_rotated_labels, fake_labels, fake_rotated_labels], 0) return all_features, all_labels def create_loss(self, features, labels, params, is_training=True): """Build the loss tensors for discriminator and generator. This method will set self.d_loss and self.g_loss. Args: features: Optional dictionary with inputs to the model ("images" should contain the real images and "z" the noise for the generator). labels: Tensor will labels. These are class indices. Use self._get_one_hot_labels(labels) to get a one hot encoded tensor. params: Dictionary with hyperparameters passed to TPUEstimator. Additional TPUEstimator will set 3 keys: `batch_size`, `use_tpu`, `tpu_context`. `batch_size` is the batch size for this core. is_training: If True build the model in training mode. If False build the model for inference mode (e.g. use trained averages for batch norm). Raises: ValueError: If set of meta/hyper parameters is not supported. """ real_images = features["images"] if self.conditional: if self._use_soft_labels: assert labels.shape[1] == self._dataset.num_classes, \ ("Need soft labels of dimension {} but got dimension {}".format( self._dataset.num_classes, labels.shape[1])) real_labels = labels else: real_labels = self._get_one_hot_labels(labels) fake_labels = self._get_one_hot_labels(features["sampled_labels"]) if self._experimental_joint_gen_for_disc: assert "generated" in features fake_images = features["generated"] else: logging.warning("Computing fake images for every sub step separately.") fake_images = self.generator( features["z"], y=fake_labels, is_training=is_training) bs = real_images.shape[0].value if self._self_supervision: assert bs % self._rotated_batch_fraction == 0, ( "Rotated batch fraction is invalid: %d doesn't divide %d" % self._rotated_batch_fraction, bs) rotated_bs = bs // self._rotated_batch_fraction num_rot_examples = rotated_bs // NUM_ROTATIONS logging.info("bs=%s, rotated_bs=%s, num_rot_examples=%s", bs, rotated_bs, num_rot_examples) assert num_rot_examples > 0 # Append the data obtained by rotating the last 'num_rotated_samples' # from the true and the fake data. if self._self_supervision == "rotation": assert num_rot_examples <= bs, (num_rot_examples, bs) all_features, all_labels = self.merge_with_rotation_data( real_images, fake_images, real_labels, fake_labels, num_rot_examples) else: all_features = tf.concat([real_images, fake_images], 0) all_labels = None if self.conditional: all_labels = tf.concat([real_labels, fake_labels], axis=0) d_predictions, d_logits, rot_logits, aux_logits, is_label_available = ( self.discriminator_with_additonal_heads( x=all_features, y=all_labels, is_training=is_training)) expected_batch_size = 2 * bs if self._self_supervision == "rotation": expected_batch_size += 2 * (NUM_ROTATIONS - 1) * num_rot_examples if d_logits.shape[0].value != expected_batch_size: raise ValueError("Batch size unexpected: got %r expected %r" % ( d_logits.shape[0].value, expected_batch_size)) prob_real, prob_fake = tf.split(d_predictions, 2) prob_real, prob_fake = prob_real[:bs], prob_fake[:bs] logits_real, logits_fake = tf.split(d_logits, 2) logits_real, logits_fake = logits_real[:bs], logits_fake[:bs] # Get the true/fake GAN loss. self.d_loss, _, _, self.g_loss = loss_lib.get_losses( d_real=prob_real, d_fake=prob_fake, d_real_logits=logits_real, d_fake_logits=logits_fake) # At this point we have the classic GAN loss with possible regularization. # We now add the rotation loss and summaries if required. if self._self_supervision == "rotation": # Extract logits for the rotation task. rot_real_logits, rot_fake_logits = tf.split(rot_logits, 2) rot_real_logits = rot_real_logits[-rotated_bs:] rot_fake_logits = rot_fake_logits[-rotated_bs:] labels_rotated = tf.constant(np.repeat( np.arange(NUM_ROTATIONS, dtype=np.int32), num_rot_examples)) rot_onehot = tf.one_hot(labels_rotated, NUM_ROTATIONS) rot_real_logp = tf.log(tf.nn.softmax(rot_real_logits) + 1e-10) rot_fake_logp = tf.log(tf.nn.softmax(rot_fake_logits) + 1e-10) real_loss = -tf.reduce_mean(tf.reduce_sum(rot_onehot * rot_real_logp, 1)) fake_loss = -tf.reduce_mean(tf.reduce_sum(rot_onehot * rot_fake_logp, 1)) self.d_loss += real_loss * self._weight_rotation_loss_d self.g_loss += fake_loss * self._weight_rotation_loss_g rot_real_labels = tf.one_hot( tf.arg_max(rot_real_logits, 1), NUM_ROTATIONS) rot_fake_labels = tf.one_hot( tf.arg_max(rot_fake_logits, 1), NUM_ROTATIONS) accuracy_real = tf.metrics.accuracy(rot_onehot, rot_real_labels) accuracy_fake = tf.metrics.accuracy(rot_onehot, rot_fake_labels) self._tpu_summary.scalar("loss/real_loss", real_loss) self._tpu_summary.scalar("loss/fake_loss", fake_loss) self._tpu_summary.scalar("accuracy/real", accuracy_real) self._tpu_summary.scalar("accuracy/fake", accuracy_fake) # Training the predictor on the features of real data and real labels. if self._use_predictor: real_aux_logits, _ = tf.split(aux_logits, 2) real_aux_logits = real_aux_logits[:bs] is_label_available, _ = tf.split(is_label_available, 2) is_label_available = tf.squeeze(is_label_available[:bs]) class_loss_real = tf.losses.softmax_cross_entropy( real_labels, real_aux_logits, weights=is_label_available) # Add the loss to the discriminator self.d_loss += self._weight_class_loss * class_loss_real self._tpu_summary.scalar("loss/class_loss_real", class_loss_real) self._tpu_summary.scalar("label_frac", tf.reduce_mean(is_label_available))
compare_gan-master
compare_gan/gans/s3gan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Customized TensorFlow operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan.tpu import tpu_random random_uniform = tpu_random.uniform random_normal = tpu_random.normal
compare_gan-master
compare_gan/gans/ops.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for SSGANs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.gans import consts as c from compare_gan.gans import loss_lib from compare_gan.gans import penalty_lib from compare_gan.gans.ssgan import SSGAN import gin import tensorflow as tf FLAGS = flags.FLAGS TEST_ARCHITECTURES = [c.RESNET_CIFAR_ARCH, c.SNDCGAN_ARCH, c.RESNET5_ARCH] TEST_LOSSES = [loss_lib.non_saturating, loss_lib.hinge] TEST_PENALTIES = [penalty_lib.no_penalty, penalty_lib.wgangp_penalty] class SSGANTest(parameterized.TestCase, test_utils.CompareGanTestCase): def _runSingleTrainingStep(self, architecture, loss_fn, penalty_fn): parameters = { "architecture": architecture, "lambda": 1, "z_dim": 128, } with gin.unlock_config(): gin.bind_parameter("penalty.fn", penalty_fn) gin.bind_parameter("loss.fn", loss_fn) model_dir = self._get_empty_model_dir() run_config = tf.contrib.tpu.RunConfig( model_dir=model_dir, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) dataset = datasets.get_dataset("cifar10") gan = SSGAN( dataset=dataset, parameters=parameters, model_dir=model_dir, g_optimizer_fn=tf.train.AdamOptimizer, g_lr=0.0002, rotated_batch_size=4) estimator = gan.as_estimator(run_config, batch_size=2, use_tpu=False) estimator.train(gan.input_fn, steps=1) @parameterized.parameters(TEST_ARCHITECTURES) def testSingleTrainingStepArchitectures(self, architecture): self._runSingleTrainingStep(architecture, loss_lib.hinge, penalty_lib.no_penalty) @parameterized.parameters(TEST_LOSSES) def testSingleTrainingStepLosses(self, loss_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_fn, penalty_lib.no_penalty) @parameterized.parameters(TEST_PENALTIES) def testSingleTrainingStepPenalties(self, penalty_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_lib.hinge, penalty_fn) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/gans/ssgan_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for S3GANs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.gans import consts as c from compare_gan.gans import loss_lib from compare_gan.gans.s3gan import S3GAN import gin import tensorflow as tf FLAGS = flags.FLAGS class S3GANTest(parameterized.TestCase, test_utils.CompareGanTestCase): @parameterized.parameters( {"use_predictor": False, "project_y": False}, # unsupervised. {"use_predictor": False}, # fully supervised. {"use_predictor": True}, # only oracle. {"use_predictor": True, "self_supervision": "rotation"}, # oracle + SS. {"use_predictor": False, "self_supervision": "rotation"}, # only SS. ) def testSingleTrainingStepArchitectures( self, use_predictor, project_y=True, self_supervision="none"): parameters = { "architecture": c.RESNET_BIGGAN_ARCH, "lambda": 1, "z_dim": 120, } with gin.unlock_config(): gin.bind_parameter("ModularGAN.conditional", True) gin.bind_parameter("loss.fn", loss_lib.hinge) gin.bind_parameter("S3GAN.use_predictor", use_predictor) gin.bind_parameter("S3GAN.project_y", project_y) gin.bind_parameter("S3GAN.self_supervision", self_supervision) # Fake ImageNet dataset by overriding the properties. dataset = datasets.get_dataset("imagenet_128") model_dir = self._get_empty_model_dir() run_config = tf.contrib.tpu.RunConfig( model_dir=model_dir, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) gan = S3GAN( dataset=dataset, parameters=parameters, model_dir=model_dir, g_optimizer_fn=tf.train.AdamOptimizer, g_lr=0.0002, rotated_batch_fraction=2) estimator = gan.as_estimator(run_config, batch_size=8, use_tpu=False) estimator.train(gan.input_fn, steps=1) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/gans/s3gan_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy.misc import tensorflow as tf def check_folder(log_dir): if not tf.gfile.IsDirectory(log_dir): tf.gfile.MakeDirs(log_dir) return log_dir def save_images(images, image_path): with tf.gfile.Open(image_path, "wb") as f: scipy.misc.imsave(f, images * 255.0) def rotate_images(images, rot90_scalars=(0, 1, 2, 3)): """Return the input image and its 90, 180, and 270 degree rotations.""" images_rotated = [ images, # 0 degree tf.image.flip_up_down(tf.image.transpose_image(images)), # 90 degrees tf.image.flip_left_right(tf.image.flip_up_down(images)), # 180 degrees tf.image.transpose_image(tf.image.flip_up_down(images)) # 270 degrees ] results = tf.stack([images_rotated[i] for i in rot90_scalars]) results = tf.reshape(results, [-1] + images.get_shape().as_list()[1:]) return results def gaussian(batch_size, n_dim, mean=0., var=1.): return np.random.normal(mean, var, (batch_size, n_dim)).astype(np.float32)
compare_gan-master
compare_gan/gans/utils.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test various (unconditional) configurations of ModularGAN.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import os from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.gans import consts as c from compare_gan.gans import loss_lib from compare_gan.gans import penalty_lib from compare_gan.gans.modular_gan import ModularGAN import gin import numpy as np from six.moves import range import tensorflow as tf FLAGS = flags.FLAGS TEST_ARCHITECTURES = [c.INFOGAN_ARCH, c.DCGAN_ARCH, c.RESNET_CIFAR_ARCH, c.SNDCGAN_ARCH, c.RESNET5_ARCH] TEST_LOSSES = [loss_lib.non_saturating, loss_lib.wasserstein, loss_lib.least_squares, loss_lib.hinge] TEST_PENALTIES = [penalty_lib.no_penalty, penalty_lib.dragan_penalty, penalty_lib.wgangp_penalty, penalty_lib.l2_penalty] GENERATOR_TRAINED_IN_STEPS = [ # disc_iters=1. [True, True, True], # disc_iters=2. [True, False, True], # disc_iters=3. [True, False, False], ] class ModularGanTest(parameterized.TestCase, test_utils.CompareGanTestCase): def setUp(self): super(ModularGanTest, self).setUp() self.model_dir = self._get_empty_model_dir() self.run_config = tf.contrib.tpu.RunConfig( model_dir=self.model_dir, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) def _runSingleTrainingStep(self, architecture, loss_fn, penalty_fn): parameters = { "architecture": architecture, "lambda": 1, "z_dim": 128, } with gin.unlock_config(): gin.bind_parameter("penalty.fn", penalty_fn) gin.bind_parameter("loss.fn", loss_fn) dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, model_dir=self.model_dir, conditional="biggan" in architecture) estimator = gan.as_estimator(self.run_config, batch_size=2, use_tpu=False) estimator.train(gan.input_fn, steps=1) @parameterized.parameters(TEST_ARCHITECTURES) def testSingleTrainingStepArchitectures(self, architecture): self._runSingleTrainingStep(architecture, loss_lib.hinge, penalty_lib.no_penalty) @parameterized.parameters(TEST_LOSSES) def testSingleTrainingStepLosses(self, loss_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_fn, penalty_lib.no_penalty) @parameterized.parameters(TEST_PENALTIES) def testSingleTrainingStepPenalties(self, penalty_fn): self._runSingleTrainingStep(c.RESNET_CIFAR_ARCH, loss_lib.hinge, penalty_fn) def testSingleTrainingStepWithJointGenForDisc(self): parameters = { "architecture": c.DUMMY_ARCH, "lambda": 1, "z_dim": 120, "disc_iters": 2, } dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, model_dir=self.model_dir, experimental_joint_gen_for_disc=True, experimental_force_graph_unroll=True, conditional=True) estimator = gan.as_estimator(self.run_config, batch_size=2, use_tpu=False) estimator.train(gan.input_fn, steps=1) @parameterized.parameters([1, 2, 3]) def testSingleTrainingStepDiscItersWithEma(self, disc_iters): parameters = { "architecture": c.DUMMY_ARCH, "lambda": 1, "z_dim": 128, "dics_iters": disc_iters, } gin.bind_parameter("ModularGAN.g_use_ema", True) dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, model_dir=self.model_dir) estimator = gan.as_estimator(self.run_config, batch_size=2, use_tpu=False) estimator.train(gan.input_fn, steps=1) # Check for moving average variables in checkpoint. checkpoint_path = tf.train.latest_checkpoint(self.model_dir) ema_vars = sorted([v[0] for v in tf.train.list_variables(checkpoint_path) if v[0].endswith("ExponentialMovingAverage")]) tf.logging.info("ema_vars=%s", ema_vars) expected_ema_vars = sorted([ "generator/fc_noise/kernel/ExponentialMovingAverage", "generator/fc_noise/bias/ExponentialMovingAverage", ]) self.assertAllEqual(ema_vars, expected_ema_vars) @parameterized.parameters( itertools.product([1, 2, 3], [False, True]) ) def testDiscItersIsUsedCorrectly(self, disc_iters, use_tpu): parameters = { "architecture": c.DUMMY_ARCH, "disc_iters": disc_iters, "lambda": 1, "z_dim": 128, } run_config = tf.contrib.tpu.RunConfig( model_dir=self.model_dir, save_checkpoints_steps=1, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, model_dir=self.model_dir) estimator = gan.as_estimator(run_config, batch_size=2, use_tpu=use_tpu) estimator.train(gan.input_fn, steps=3) disc_step_values = [] gen_step_values = [] for step in range(4): basename = os.path.join(self.model_dir, "model.ckpt-{}".format(step)) self.assertTrue(tf.gfile.Exists(basename + ".index")) ckpt = tf.train.load_checkpoint(basename) disc_step_values.append(ckpt.get_tensor("global_step_disc")) gen_step_values.append(ckpt.get_tensor("global_step")) expected_disc_steps = np.arange(4) * disc_iters self.assertAllEqual(disc_step_values, expected_disc_steps) self.assertAllEqual(gen_step_values, [0, 1, 2, 3]) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/gans/modular_gan_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests TPU specfic parts of ModularGAN.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized from compare_gan import datasets from compare_gan import test_utils from compare_gan.gans import consts as c from compare_gan.gans.modular_gan import ModularGAN import tensorflow as tf FLAGS = flags.FLAGS class ModularGanTpuTest(parameterized.TestCase, test_utils.CompareGanTestCase): def setUp(self): super(ModularGanTpuTest, self).setUp() self.model_dir = self._get_empty_model_dir() self.run_config = tf.contrib.tpu.RunConfig( model_dir=self.model_dir, tpu_config=tf.contrib.tpu.TPUConfig(iterations_per_loop=1)) @parameterized.parameters([1, 2, 5]) def testBatchSize(self, disc_iters, use_tpu=True): parameters = { "architecture": c.DUMMY_ARCH, "lambda": 1, "z_dim": 128, "disc_iters": disc_iters, } batch_size = 16 dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, model_dir=self.model_dir) estimator = gan.as_estimator(self.run_config, batch_size=batch_size, use_tpu=True) estimator.train(gan.input_fn, steps=1) gen_args = gan.generator.call_arg_list disc_args = gan.discriminator.call_arg_list self.assertLen(gen_args, disc_iters + 1) # D steps, G step. self.assertLen(disc_args, disc_iters + 1) # D steps, G step. for args in gen_args: self.assertAllEqual(args["z"].shape.as_list(), [8, 128]) for args in disc_args: self.assertAllEqual(args["x"].shape.as_list(), [16, 32, 32, 3]) @parameterized.parameters([1, 2, 5]) def testBatchSizeSplitDiscCalls(self, disc_iters): parameters = { "architecture": c.DUMMY_ARCH, "lambda": 1, "z_dim": 128, "disc_iters": disc_iters, } batch_size = 16 dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, deprecated_split_disc_calls=True, model_dir=self.model_dir) estimator = gan.as_estimator(self.run_config, batch_size=batch_size, use_tpu=True) estimator.train(gan.input_fn, steps=1) gen_args = gan.generator.call_arg_list disc_args = gan.discriminator.call_arg_list self.assertLen(gen_args, disc_iters + 1) # D steps, G step. # Each D and G step calls discriminator twice: for real and fake images. self.assertLen(disc_args, 2 * (disc_iters + 1)) for args in gen_args: self.assertAllEqual(args["z"].shape.as_list(), [8, 128]) for args in disc_args: self.assertAllEqual(args["x"].shape.as_list(), [8, 32, 32, 3]) @parameterized.parameters([1, 2, 5]) def testBatchSizeExperimentalJointGenForDisc(self, disc_iters): parameters = { "architecture": c.DUMMY_ARCH, "lambda": 1, "z_dim": 128, "disc_iters": disc_iters, } batch_size = 16 dataset = datasets.get_dataset("cifar10") gan = ModularGAN( dataset=dataset, parameters=parameters, experimental_joint_gen_for_disc=True, model_dir=self.model_dir) estimator = gan.as_estimator(self.run_config, batch_size=batch_size, use_tpu=True) estimator.train(gan.input_fn, steps=1) gen_args = gan.generator.call_arg_list disc_args = gan.discriminator.call_arg_list self.assertLen(gen_args, 2) self.assertLen(disc_args, disc_iters + 1) self.assertAllEqual(gen_args[0]["z"].shape.as_list(), [8 * disc_iters, 128]) self.assertAllEqual(gen_args[1]["z"].shape.as_list(), [8, 128]) for args in disc_args: self.assertAllEqual(args["x"].shape.as_list(), [16, 32, 32, 3]) if __name__ == "__main__": tf.test.main()
compare_gan-master
compare_gan/gans/modular_gan_tpu_test.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of popular GAN losses.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from compare_gan import utils import gin import tensorflow as tf def check_dimensions(d_real, d_fake, d_real_logits, d_fake_logits): """Checks the shapes and ranks of logits and prediction tensors. Args: d_real: prediction for real points, values in [0, 1], shape [batch_size, 1]. d_fake: prediction for fake points, values in [0, 1], shape [batch_size, 1]. d_real_logits: logits for real points, shape [batch_size, 1]. d_fake_logits: logits for fake points, shape [batch_size, 1]. Raises: ValueError: if the ranks or shapes are mismatched. """ def _check_pair(a, b): if a != b: raise ValueError("Shape mismatch: %s vs %s." % (a, b)) if len(a) != 2 or len(b) != 2: raise ValueError("Rank: expected 2, got %s and %s" % (len(a), len(b))) if (d_real is not None) and (d_fake is not None): _check_pair(d_real.shape.as_list(), d_fake.shape.as_list()) if (d_real_logits is not None) and (d_fake_logits is not None): _check_pair(d_real_logits.shape.as_list(), d_fake_logits.shape.as_list()) if (d_real is not None) and (d_real_logits is not None): _check_pair(d_real.shape.as_list(), d_real_logits.shape.as_list()) @gin.configurable(whitelist=[]) def non_saturating(d_real_logits, d_fake_logits, d_real=None, d_fake=None): """Returns the discriminator and generator loss for Non-saturating loss. Args: d_real_logits: logits for real points, shape [batch_size, 1]. d_fake_logits: logits for fake points, shape [batch_size, 1]. d_real: ignored. d_fake: ignored. Returns: A tuple consisting of the discriminator loss, discriminator's loss on the real samples and fake samples, and the generator's loss. """ with tf.name_scope("non_saturating_loss"): check_dimensions(d_real, d_fake, d_real_logits, d_fake_logits) d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=d_real_logits, labels=tf.ones_like(d_real_logits), name="cross_entropy_d_real")) d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=d_fake_logits, labels=tf.zeros_like(d_fake_logits), name="cross_entropy_d_fake")) d_loss = d_loss_real + d_loss_fake g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=d_fake_logits, labels=tf.ones_like(d_fake_logits), name="cross_entropy_g")) return d_loss, d_loss_real, d_loss_fake, g_loss @gin.configurable(whitelist=[]) def wasserstein(d_real_logits, d_fake_logits, d_real=None, d_fake=None): """Returns the discriminator and generator loss for Wasserstein loss. Args: d_real_logits: logits for real points, shape [batch_size, 1]. d_fake_logits: logits for fake points, shape [batch_size, 1]. d_real: ignored. d_fake: ignored. Returns: A tuple consisting of the discriminator loss, discriminator's loss on the real samples and fake samples, and the generator's loss. """ with tf.name_scope("wasserstein_loss"): check_dimensions(d_real, d_fake, d_real_logits, d_fake_logits) d_loss_real = -tf.reduce_mean(d_real_logits) d_loss_fake = tf.reduce_mean(d_fake_logits) d_loss = d_loss_real + d_loss_fake g_loss = -d_loss_fake return d_loss, d_loss_real, d_loss_fake, g_loss @gin.configurable(whitelist=[]) def least_squares(d_real, d_fake, d_real_logits=None, d_fake_logits=None): """Returns the discriminator and generator loss for the least-squares loss. Args: d_real: prediction for real points, values in [0, 1], shape [batch_size, 1]. d_fake: prediction for fake points, values in [0, 1], shape [batch_size, 1]. d_real_logits: ignored. d_fake_logits: ignored. Returns: A tuple consisting of the discriminator loss, discriminator's loss on the real samples and fake samples, and the generator's loss. """ with tf.name_scope("least_square_loss"): check_dimensions(d_real, d_fake, d_real_logits, d_fake_logits) d_loss_real = tf.reduce_mean(tf.square(d_real - 1.0)) d_loss_fake = tf.reduce_mean(tf.square(d_fake)) d_loss = 0.5 * (d_loss_real + d_loss_fake) g_loss = 0.5 * tf.reduce_mean(tf.square(d_fake - 1.0)) return d_loss, d_loss_real, d_loss_fake, g_loss @gin.configurable(whitelist=[]) def hinge(d_real_logits, d_fake_logits, d_real=None, d_fake=None): """Returns the discriminator and generator loss for the hinge loss. Args: d_real_logits: logits for real points, shape [batch_size, 1]. d_fake_logits: logits for fake points, shape [batch_size, 1]. d_real: ignored. d_fake: ignored. Returns: A tuple consisting of the discriminator loss, discriminator's loss on the real samples and fake samples, and the generator's loss. """ with tf.name_scope("hinge_loss"): check_dimensions(d_real, d_fake, d_real_logits, d_fake_logits) d_loss_real = tf.reduce_mean(tf.nn.relu(1.0 - d_real_logits)) d_loss_fake = tf.reduce_mean(tf.nn.relu(1.0 + d_fake_logits)) d_loss = d_loss_real + d_loss_fake g_loss = - tf.reduce_mean(d_fake_logits) return d_loss, d_loss_real, d_loss_fake, g_loss @gin.configurable("loss", whitelist=["fn"]) def get_losses(fn=non_saturating, **kwargs): """Returns the losses for the discriminator and generator.""" return utils.call_with_accepted_args(fn, **kwargs)
compare_gan-master
compare_gan/gans/loss_lib.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of Self-Supervised GAN with auxiliary rotation loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl import logging from compare_gan.architectures.arch_ops import linear from compare_gan.gans import loss_lib from compare_gan.gans import modular_gan from compare_gan.gans import penalty_lib from compare_gan.gans import utils import gin import numpy as np import tensorflow as tf FLAGS = flags.FLAGS NUM_ROTATIONS = 4 # pylint: disable=not-callable @gin.configurable(blacklist=["kwargs"]) class SSGAN(modular_gan.ModularGAN): """Self-Supervised GAN. http://arxiv.org/abs/1811.11212 """ def __init__(self, self_supervision="rotation_gan", rotated_batch_size=gin.REQUIRED, weight_rotation_loss_d=1.0, weight_rotation_loss_g=0.2, **kwargs): """Creates a new Self-Supervised GAN. Args: self_supervision: One of [rotation_gan, rotation_only, None]. When it is rotation_only, no GAN loss is used, degenerates to a pure rotation model. rotated_batch_size: The total number images per batch for the rotation loss. This must be a multiple of (4 * #CORES) since we consider 4 rotations of each images on each TPU core. For GPU training #CORES is 1. weight_rotation_loss_d: Weight for the rotation loss for the discriminator on real images. weight_rotation_loss_g: Weight for the rotation loss for the generator on fake images. **kwargs: Additional arguments passed to `ModularGAN` constructor. """ super(SSGAN, self).__init__(**kwargs) self._self_supervision = self_supervision self._rotated_batch_size = rotated_batch_size self._weight_rotation_loss_d = weight_rotation_loss_d self._weight_rotation_loss_g = weight_rotation_loss_g # To safe memory ModularGAN supports feeding real and fake samples # separately through the discriminator. SSGAN does not support this to # avoid additional additional complexity in create_loss(). assert not self._deprecated_split_disc_calls, \ "Splitting discriminator calls is not supported in SSGAN." def discriminator_with_rotation_head(self, x, y, is_training): """Discriminator network with augmented auxiliary predictions. Args: x: an input image tensor. y: Tensor with label indices. is_training: boolean, whether or not it is a training call. Returns: real_probs: the [0, 1] probability tensor of x being real images. real_scores: the unbounded score tensor of x being real images. rotation_scores: the categorical probablity of x being rotated in one of the four directions. """ real_probs, real_scores, final = self.discriminator( x=x, y=y, is_training=is_training) use_sn = self._discriminator._spectral_norm # pylint: disable=protected-access with tf.variable_scope("discriminator_rotation", reuse=tf.AUTO_REUSE): rotation_scores = linear(tf.reshape(final, (tf.shape(x)[0], -1)), NUM_ROTATIONS, scope="score_classify", use_sn=use_sn) return real_probs, real_scores, rotation_scores def create_loss(self, features, labels, params, is_training=True): """Build the loss tensors for discriminator and generator. This method will set self.d_loss and self.g_loss. Args: features: Optional dictionary with inputs to the model ("images" should contain the real images and "z" the noise for the generator). labels: Tensor will labels. These are class indices. Use self._get_one_hot_labels(labels) to get a one hot encoded tensor. params: Dictionary with hyperparameters passed to TPUEstimator. Additional TPUEstimator will set 3 keys: `batch_size`, `use_tpu`, `tpu_context`. `batch_size` is the batch size for this core. is_training: If True build the model in training mode. If False build the model for inference mode (e.g. use trained averages for batch norm). Raises: ValueError: If set of meta/hyper parameters is not supported. """ images = features["images"] # Input images. generated = features["generated"] # Fake images. if self.conditional: y = self._get_one_hot_labels(labels) sampled_y = self._get_one_hot_labels(features["sampled_labels"]) else: y = None sampled_y = None all_y = None # Batch size per core. bs = images.shape[0].value num_replicas = params["context"].num_replicas if "context" in params else 1 assert self._rotated_batch_size % num_replicas == 0 # Rotated batch size per core. rotated_bs = self._rotated_batch_size // num_replicas assert rotated_bs % 4 == 0 # Number of images to rotate. Each images gets rotated 3 times. num_rotated_examples = rotated_bs // 4 logging.info("num_replicas=%s, bs=%s, rotated_bs=%s, " "num_rotated_examples=%s, params=%s", num_replicas, bs, rotated_bs, num_rotated_examples, params) # Augment the images with rotation. if "rotation" in self._self_supervision: # Put all rotation angles in a single batch, the first batch_size are # the original up-right images, followed by rotated_batch_size * 3 # rotated images with 3 different angles. assert num_rotated_examples <= bs, (num_rotated_examples, bs) images_rotated = utils.rotate_images( images[-num_rotated_examples:], rot90_scalars=(1, 2, 3)) generated_rotated = utils.rotate_images( generated[-num_rotated_examples:], rot90_scalars=(1, 2, 3)) # Labels for rotation loss (unrotated and 3 rotated versions). For # NUM_ROTATIONS=4 and num_rotated_examples=2 this is: # [0, 0, 1, 1, 2, 2, 3, 3] rotate_labels = tf.constant( np.repeat(np.arange(NUM_ROTATIONS, dtype=np.int32), num_rotated_examples)) rotate_labels_onehot = tf.one_hot(rotate_labels, NUM_ROTATIONS) all_images = tf.concat([images, images_rotated, generated, generated_rotated], 0) if self.conditional: y_rotated = tf.tile(y[-num_rotated_examples:], [3, 1]) sampled_y_rotated = tf.tile(y[-num_rotated_examples:], [3, 1]) all_y = tf.concat([y, y_rotated, sampled_y, sampled_y_rotated], 0) else: all_images = tf.concat([images, generated], 0) if self.conditional: all_y = tf.concat([y, sampled_y], axis=0) # Compute discriminator output for real and fake images in one batch. d_all, d_all_logits, c_all_logits = self.discriminator_with_rotation_head( all_images, y=all_y, is_training=is_training) d_real, d_fake = tf.split(d_all, 2) d_real_logits, d_fake_logits = tf.split(d_all_logits, 2) c_real_logits, c_fake_logits = tf.split(c_all_logits, 2) # Separate the true/fake scores from whole rotation batch. d_real_logits = d_real_logits[:bs] d_fake_logits = d_fake_logits[:bs] d_real = d_real[:bs] d_fake = d_fake[:bs] self.d_loss, _, _, self.g_loss = loss_lib.get_losses( d_real=d_real, d_fake=d_fake, d_real_logits=d_real_logits, d_fake_logits=d_fake_logits) penalty_loss = penalty_lib.get_penalty_loss( x=images, x_fake=generated, y=y, is_training=is_training, discriminator=self.discriminator, architecture=self._architecture) self.d_loss += self._lambda * penalty_loss # Add rotation augmented loss. if "rotation" in self._self_supervision: # We take an even pieces for all rotation angles assert len(c_real_logits.shape.as_list()) == 2, c_real_logits.shape assert len(c_fake_logits.shape.as_list()) == 2, c_fake_logits.shape c_real_logits = c_real_logits[- rotated_bs:] c_fake_logits = c_fake_logits[- rotated_bs:] preds_onreal = tf.cast(tf.argmax(c_real_logits, -1), rotate_labels.dtype) accuracy = tf.reduce_mean( tf.cast(tf.equal(rotate_labels, preds_onreal), tf.float32)) c_real_probs = tf.nn.softmax(c_real_logits) c_fake_probs = tf.nn.softmax(c_fake_logits) c_real_loss = - tf.reduce_mean( tf.reduce_sum(rotate_labels_onehot * tf.log(c_real_probs + 1e-10), 1)) c_fake_loss = - tf.reduce_mean( tf.reduce_sum(rotate_labels_onehot * tf.log(c_fake_probs + 1e-10), 1)) if self._self_supervision == "rotation_only": self.d_loss *= 0.0 self.g_loss *= 0.0 self.d_loss += c_real_loss * self._weight_rotation_loss_d self.g_loss += c_fake_loss * self._weight_rotation_loss_g else: c_real_loss = 0.0 c_fake_loss = 0.0 accuracy = tf.zeros([]) self._tpu_summary.scalar("loss/c_real_loss", c_real_loss) self._tpu_summary.scalar("loss/c_fake_loss", c_fake_loss) self._tpu_summary.scalar("accuracy/d_rotation", accuracy) self._tpu_summary.scalar("loss/penalty", penalty_loss)
compare_gan-master
compare_gan/gans/ssgan.py
# coding=utf-8 # Copyright 2018 Google LLC & Hwalsuk Lee. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of Self-Supervised GAN with contrastive loss.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl import logging from compare_gan.architectures.arch_ops import linear from compare_gan.gans import loss_lib from compare_gan.gans import modular_gan from compare_gan.gans import penalty_lib from compare_gan.gans import utils import gin import numpy as np import random import tensorflow as tf FLAGS = flags.FLAGS # augmentation functions # augment def random_crop_and_resize(images, ratio=0.8): b, h, w, c = images.get_shape().as_list() ch, cw = map(lambda x: int(x * ratio), (h, w)) crop = tf.random_crop(images, size=[b, ch, cw, 3]) crop = tf.image.resize(crop, [h, w]) return crop def random_apply(fn, image, prob=1.): b, *_ = image.get_shape().as_list() chance = tf.less(tf.random_uniform([b], 0, 1.0), prob) return tf.where(chance, fn(image), tf.identity(image)) def color_distortion(image, s=1.0): lower, upper, x = (1 - 0.8 * s), (1 + 0.8 * s), image x = tf.image.random_brightness(x, max_delta=0.8*s) x = tf.image.random_contrast(x, lower=lower, upper=upper) x = tf.image.random_saturation(x, lower=lower, upper=upper) x = tf.image.random_hue(x, max_delta=0.2*s) x = tf.clip_by_value(x, 0, 1) return x def color_drop(image): image = tf.image.rgb_to_grayscale(image) image = tf.tile(image, [1, 1, 1, 3]) return image # pylint: disable=not-callable @gin.configurable(blacklist=["kwargs"]) class CLGAN(modular_gan.ModularGAN): """Self-Supervised GAN with Contrastive Loss""" def __init__(self, aug_color_jitter_prob=0.8, aug_color_drop_prob=0.0, weight_contrastive_loss_d=2.0, **kwargs): """Creates a new Self-Supervised GAN using Contrastive Loss. Args: self_supervised_batch_size: The total number images per batch for the self supervised loss. weight_contrastive_loss_d: Weight for the contrastive loss for the self supervised learning on real images **kwargs: Additional arguments passed to `ModularGAN` constructor. """ super(CLGAN, self).__init__(**kwargs) self._weight_contrastive_loss_d = weight_contrastive_loss_d self._aug_color_jitter_prob = aug_color_jitter_prob self._aug_color_drop_prob = aug_color_drop_prob # To safe memory ModularGAN supports feeding real and fake samples # separately through the discriminator. CLGAN does not support this to # avoid additional additional complexity in create_loss(). assert not self._deprecated_split_disc_calls, \ "Splitting discriminator calls is not supported in CLGAN." def _latent_projections(self, latents): bs, dim = latents.get_shape().as_list() with tf.variable_scope("discriminator_z_projection", reuse=tf.AUTO_REUSE) as scope: k1 = tf.get_variable("kernel1", [dim, dim * 4]) k2 = tf.get_variable("kernel2", [dim * 4, dim]) z_proj = tf.matmul(tf.nn.leaky_relu(tf.matmul(latents, k1), name=scope.name), k2) z_proj = z_proj / tf.reshape(tf.norm(z_proj, ord=2, axis=-1), [bs, 1]) return z_proj def create_loss(self, features, labels, params, is_training=True): """Build the loss tensors for discriminator and generator. This method will set self.d_loss and self.g_loss. Args: features: Optional dictionary with inputs to the model ("images" should contain the real images and "z" the noise for the generator). labels: Tensor will labels. These are class indices. Use self._get_one_hot_labels(labels) to get a one hot encoded tensor. params: Dictionary with hyperparameters passed to TPUEstimator. Additional TPUEstimator will set 3 keys: `batch_size`, `use_tpu`, `tpu_context`. `batch_size` is the batch size for this core. is_training: If True build the model in training mode. If False build the model for inference mode (e.g. use trained averages for batch norm). Raises: ValueError: If set of meta/hyper parameters is not supported. """ images = features["images"] # Input images. generated = features["generated"] # Fake images. if self.conditional: y = self._get_one_hot_labels(labels) sampled_y = self._get_one_hot_labels(features["sampled_labels"]) else: y = None sampled_y = None all_y = None # Batch size per core. bs = images.shape[0].value def augment(imgs): imgs = random_crop_and_resize(imgs) imgs = random_apply(color_distortion, imgs, self._aug_color_jitter_prob) imgs = random_apply(color_drop, imgs, self._aug_color_drop_prob) return tf.stop_gradient(imgs) aug_images, aug_generated = augment(images), augment(generated) # concat all images all_images = tf.concat([images, generated, aug_images, aug_generated], 0) if self.conditional: all_y = tf.concat([y, sampled_y, y, sampled_y], axis=0) # Compute discriminator output for real and fake images in one batch. d_all, d_all_logits, d_latents = self.discriminator( x=all_images, y=all_y, is_training=is_training) z_projs = self._latent_projections(d_latents) d_real, d_fake, _, _ = tf.split(d_all, 4) d_real_logits, d_fake_logits, _, _ = tf.split(d_all_logits, 4) z_projs_real, z_projs_fake, z_aug_projs_real, z_aug_projs_fake = tf.split(z_projs, 4) self.d_loss, _, _, self.g_loss = loss_lib.get_losses( d_real=d_real, d_fake=d_fake, d_real_logits=d_real_logits, d_fake_logits=d_fake_logits) penalty_loss = penalty_lib.get_penalty_loss( x=images, x_fake=generated, y=y, is_training=is_training, discriminator=self.discriminator, architecture=self._architecture) self.d_loss += self._lambda * penalty_loss z_projs = tf.concat([z_projs_real, z_projs_fake], 0) z_aug_projs = tf.concat([z_aug_projs_real, z_aug_projs_fake], 0) sims_logits = tf.matmul(z_projs, z_aug_projs, transpose_b=True) logits_max = tf.reduce_max(sims_logits,1) sims_logits = sims_logits - tf.reshape(logits_max, [-1, 1]) sims_probs = tf.nn.softmax(sims_logits) sim_labels = tf.constant(np.arange(bs * 2, dtype=np.int32)) sims_onehot = tf.one_hot(sim_labels, bs * 2) c_real_loss = - tf.reduce_mean( tf.reduce_sum(sims_onehot * tf.log(sims_probs + 1e-10), 1)) self.d_loss += c_real_loss * self._weight_contrastive_loss_d self._tpu_summary.scalar("loss/c_real_loss", c_real_loss) self._tpu_summary.scalar("loss/penalty", penalty_loss)
compare_gan-master
compare_gan/gans/clgan.py
# Welcome to the PyTorch setup.py. # # Environment variables you are probably interested in: # # DEBUG # build with -O0 and -g (debug symbols) # # REL_WITH_DEB_INFO # build with optimizations and -g (debug symbols) # # MAX_JOBS # maximum number of compile jobs we should use to compile your code # # USE_CUDA=0 # disables CUDA build # # CFLAGS # flags to apply to both C and C++ files to be compiled (a quirk of setup.py # which we have faithfully adhered to in our build system is that CFLAGS # also applies to C++ files (unless CXXFLAGS is set), in contrast to the # default behavior of autogoo and cmake build systems.) # # CC # the C/C++ compiler to use # # Environment variables for feature toggles: # # USE_CUDNN=0 # disables the cuDNN build # # USE_FBGEMM=0 # disables the FBGEMM build # # USE_KINETO=0 # disables usage of libkineto library for profiling # # USE_NUMPY=0 # disables the NumPy build # # BUILD_TEST=0 # disables the test build # # USE_MKLDNN=0 # disables use of MKLDNN # # USE_MKLDNN_ACL # enables use of Compute Library backend for MKLDNN on Arm; # USE_MKLDNN must be explicitly enabled. # # MKLDNN_CPU_RUNTIME # MKL-DNN threading mode: TBB or OMP (default) # # USE_STATIC_MKL # Prefer to link with MKL statically - Unix only # USE_ITT=0 # disable use of Intel(R) VTune Profiler's ITT functionality # # USE_NNPACK=0 # disables NNPACK build # # USE_QNNPACK=0 # disables QNNPACK build (quantized 8-bit operators) # # USE_DISTRIBUTED=0 # disables distributed (c10d, gloo, mpi, etc.) build # # USE_TENSORPIPE=0 # disables distributed Tensorpipe backend build # # USE_GLOO=0 # disables distributed gloo backend build # # USE_MPI=0 # disables distributed MPI backend build # # USE_SYSTEM_NCCL=0 # disables use of system-wide nccl (we will use our submoduled # copy in third_party/nccl) # # BUILD_CAFFE2_OPS=0 # disable Caffe2 operators build # # BUILD_CAFFE2=0 # disable Caffe2 build # # USE_IBVERBS # toggle features related to distributed support # # USE_OPENCV # enables use of OpenCV for additional operators # # USE_OPENMP=0 # disables use of OpenMP for parallelization # # USE_FFMPEG # enables use of ffmpeg for additional operators # # USE_LEVELDB # enables use of LevelDB for storage # # USE_LMDB # enables use of LMDB for storage # # BUILD_BINARY # enables the additional binaries/ build # # ATEN_AVX512_256=TRUE # ATen AVX2 kernels can use 32 ymm registers, instead of the default 16. # This option can be used if AVX512 doesn't perform well on a machine. # The FBGEMM library also uses AVX512_256 kernels on Xeon D processors, # but it also has some (optimized) assembly code. # # PYTORCH_BUILD_VERSION # PYTORCH_BUILD_NUMBER # specify the version of PyTorch, rather than the hard-coded version # in this file; used when we're building binaries for distribution # # TORCH_CUDA_ARCH_LIST # specify which CUDA architectures to build for. # ie `TORCH_CUDA_ARCH_LIST="6.0;7.0"` # These are not CUDA versions, instead, they specify what # classes of NVIDIA hardware we should generate PTX for. # # PYTORCH_ROCM_ARCH # specify which AMD GPU targets to build for. # ie `PYTORCH_ROCM_ARCH="gfx900;gfx906"` # # ONNX_NAMESPACE # specify a namespace for ONNX built here rather than the hard-coded # one in this file; needed to build with other frameworks that share ONNX. # # BLAS # BLAS to be used by Caffe2. Can be MKL, Eigen, ATLAS, FlexiBLAS, or OpenBLAS. If set # then the build will fail if the requested BLAS is not found, otherwise # the BLAS will be chosen based on what is found on your system. # # MKL_THREADING # MKL threading mode: SEQ, TBB or OMP (default) # # USE_REDIS # Whether to use Redis for distributed workflows (Linux only) # # USE_ZSTD # Enables use of ZSTD, if the libraries are found # # Environment variables we respect (these environment variables are # conventional and are often understood/set by other software.) # # CUDA_HOME (Linux/OS X) # CUDA_PATH (Windows) # specify where CUDA is installed; usually /usr/local/cuda or # /usr/local/cuda-x.y # CUDAHOSTCXX # specify a different compiler than the system one to use as the CUDA # host compiler for nvcc. # # CUDA_NVCC_EXECUTABLE # Specify a NVCC to use. This is used in our CI to point to a cached nvcc # # CUDNN_LIB_DIR # CUDNN_INCLUDE_DIR # CUDNN_LIBRARY # specify where cuDNN is installed # # MIOPEN_LIB_DIR # MIOPEN_INCLUDE_DIR # MIOPEN_LIBRARY # specify where MIOpen is installed # # NCCL_ROOT # NCCL_LIB_DIR # NCCL_INCLUDE_DIR # specify where nccl is installed # # NVTOOLSEXT_PATH (Windows only) # specify where nvtoolsext is installed # # ACL_ROOT_DIR # specify where Compute Library is installed # # LIBRARY_PATH # LD_LIBRARY_PATH # we will search for libraries in these paths # # ATEN_THREADING # ATen parallel backend to use for intra- and inter-op parallelism # possible values: # OMP - use OpenMP for intra-op and native backend for inter-op tasks # NATIVE - use native thread pool for both intra- and inter-op tasks # TBB - using TBB for intra- and native thread pool for inter-op parallelism # # USE_TBB # enable TBB support # # USE_SYSTEM_TBB # Use system-provided Intel TBB. # # USE_SYSTEM_LIBS (work in progress) # Use system-provided libraries to satisfy the build dependencies. # When turned on, the following cmake variables will be toggled as well: # USE_SYSTEM_CPUINFO=ON USE_SYSTEM_SLEEF=ON BUILD_CUSTOM_PROTOBUF=OFF # This future is needed to print Python2 EOL message from __future__ import print_function import sys if sys.version_info < (3,): print("Python 2 has reached end-of-life and is no longer supported by PyTorch.") sys.exit(-1) if sys.platform == 'win32' and sys.maxsize.bit_length() == 31: print("32-bit Windows Python runtime is not supported. Please switch to 64-bit Python.") sys.exit(-1) import platform python_min_version = (3, 7, 0) python_min_version_str = '.'.join(map(str, python_min_version)) if sys.version_info < python_min_version: print("You are using Python {}. Python >={} is required.".format(platform.python_version(), python_min_version_str)) sys.exit(-1) from setuptools import setup, Extension, find_packages from collections import defaultdict from setuptools.dist import Distribution import setuptools.command.build_ext import setuptools.command.install import setuptools.command.sdist import filecmp import shutil import subprocess import os import json import glob import importlib import time import sysconfig from tools.build_pytorch_libs import build_caffe2 from tools.setup_helpers.env import (IS_WINDOWS, IS_DARWIN, IS_LINUX, build_type) from tools.setup_helpers.cmake import CMake from tools.generate_torch_version import get_torch_version ################################################################################ # Parameters parsed from environment ################################################################################ VERBOSE_SCRIPT = True RUN_BUILD_DEPS = True # see if the user passed a quiet flag to setup.py arguments and respect # that in our parts of the build EMIT_BUILD_WARNING = False RERUN_CMAKE = False CMAKE_ONLY = False filtered_args = [] for i, arg in enumerate(sys.argv): if arg == '--cmake': RERUN_CMAKE = True continue if arg == '--cmake-only': # Stop once cmake terminates. Leave users a chance to adjust build # options. CMAKE_ONLY = True continue if arg == 'rebuild' or arg == 'build': arg = 'build' # rebuild is gone, make it build EMIT_BUILD_WARNING = True if arg == "--": filtered_args += sys.argv[i:] break if arg == '-q' or arg == '--quiet': VERBOSE_SCRIPT = False if arg in ['clean', 'egg_info', 'sdist']: RUN_BUILD_DEPS = False filtered_args.append(arg) sys.argv = filtered_args if VERBOSE_SCRIPT: def report(*args): print(*args) else: def report(*args): pass # Make distutils respect --quiet too setuptools.distutils.log.warn = report # Constant known variables used throughout this file cwd = os.path.dirname(os.path.abspath(__file__)) lib_path = os.path.join(cwd, "torch", "lib") third_party_path = os.path.join(cwd, "third_party") caffe2_build_dir = os.path.join(cwd, "build") # CMAKE: full path to python library if IS_WINDOWS: cmake_python_library = "{}/libs/python{}.lib".format( sysconfig.get_config_var("prefix"), sysconfig.get_config_var("VERSION")) # Fix virtualenv builds if not os.path.exists(cmake_python_library): cmake_python_library = "{}/libs/python{}.lib".format( sys.base_prefix, sysconfig.get_config_var("VERSION")) else: cmake_python_library = "{}/{}".format( sysconfig.get_config_var("LIBDIR"), sysconfig.get_config_var("INSTSONAME")) cmake_python_include_dir = sysconfig.get_path("include") ################################################################################ # Version, create_version_file, and package_name ################################################################################ package_name = os.getenv('TORCH_PACKAGE_NAME', 'torch') package_type = os.getenv('PACKAGE_TYPE', 'wheel') version = get_torch_version() report("Building wheel {}-{}".format(package_name, version)) cmake = CMake() def get_submodule_folders(): git_modules_path = os.path.join(cwd, ".gitmodules") default_modules_path = [os.path.join(third_party_path, name) for name in [ "gloo", "cpuinfo", "tbb", "onnx", "foxi", "QNNPACK", "fbgemm" ]] if not os.path.exists(git_modules_path): return default_modules_path with open(git_modules_path) as f: return [os.path.join(cwd, line.split("=", 1)[1].strip()) for line in f.readlines() if line.strip().startswith("path")] def check_submodules(): def check_for_files(folder, files): if not any(os.path.exists(os.path.join(folder, f)) for f in files): report("Could not find any of {} in {}".format(", ".join(files), folder)) report("Did you run 'git submodule update --init --recursive --jobs 0'?") sys.exit(1) def not_exists_or_empty(folder): return not os.path.exists(folder) or (os.path.isdir(folder) and len(os.listdir(folder)) == 0) if bool(os.getenv("USE_SYSTEM_LIBS", False)): return folders = get_submodule_folders() # If none of the submodule folders exists, try to initialize them if all(not_exists_or_empty(folder) for folder in folders): try: print(' --- Trying to initialize submodules') start = time.time() subprocess.check_call(["git", "submodule", "update", "--init", "--recursive"], cwd=cwd) end = time.time() print(' --- Submodule initialization took {:.2f} sec'.format(end - start)) except Exception: print(' --- Submodule initalization failed') print('Please run:\n\tgit submodule update --init --recursive --jobs 0') sys.exit(1) for folder in folders: check_for_files(folder, ["CMakeLists.txt", "Makefile", "setup.py", "LICENSE", "LICENSE.md", "LICENSE.txt"]) check_for_files(os.path.join(third_party_path, 'fbgemm', 'third_party', 'asmjit'), ['CMakeLists.txt']) check_for_files(os.path.join(third_party_path, 'onnx', 'third_party', 'benchmark'), ['CMakeLists.txt']) # Windows has very bad support for symbolic links. # Instead of using symlinks, we're going to copy files over def mirror_files_into_torchgen(): # (new_path, orig_path) # Directories are OK and are recursively mirrored. paths = [ ('torchgen/packaged/ATen/native/native_functions.yaml', 'aten/src/ATen/native/native_functions.yaml'), ('torchgen/packaged/ATen/native/tags.yaml', 'aten/src/ATen/native/tags.yaml'), ('torchgen/packaged/ATen/templates', 'aten/src/ATen/templates'), ] for new_path, orig_path in paths: # Create the dirs involved in new_path if they don't exist if not os.path.exists(new_path): os.makedirs(os.path.dirname(new_path), exist_ok=True) # Copy the files from the orig location to the new location if os.path.isfile(orig_path): shutil.copyfile(orig_path, new_path) continue if os.path.isdir(orig_path): if os.path.exists(new_path): # copytree fails if the tree exists already, so remove it. shutil.rmtree(new_path) shutil.copytree(orig_path, new_path) continue raise RuntimeError("Check the file paths in `mirror_files_into_torchgen()`") # all the work we need to do _before_ setup runs def build_deps(): report('-- Building version ' + version) check_submodules() check_pydep('yaml', 'pyyaml') build_caffe2(version=version, cmake_python_library=cmake_python_library, build_python=True, rerun_cmake=RERUN_CMAKE, cmake_only=CMAKE_ONLY, cmake=cmake) if CMAKE_ONLY: report('Finished running cmake. Run "ccmake build" or ' '"cmake-gui build" to adjust build options and ' '"python setup.py install" to build.') sys.exit() # Use copies instead of symbolic files. # Windows has very poor support for them. sym_files = [ 'tools/shared/_utils_internal.py', 'torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h', 'torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h', ] orig_files = [ 'torch/_utils_internal.py', 'third_party/valgrind-headers/callgrind.h', 'third_party/valgrind-headers/valgrind.h', ] for sym_file, orig_file in zip(sym_files, orig_files): same = False if os.path.exists(sym_file): if filecmp.cmp(sym_file, orig_file): same = True else: os.remove(sym_file) if not same: shutil.copyfile(orig_file, sym_file) ################################################################################ # Building dependent libraries ################################################################################ # the list of runtime dependencies required by this built package install_requires = [ 'typing_extensions', ] missing_pydep = ''' Missing build dependency: Unable to `import {importname}`. Please install it via `conda install {module}` or `pip install {module}` '''.strip() def check_pydep(importname, module): try: importlib.import_module(importname) except ImportError: raise RuntimeError(missing_pydep.format(importname=importname, module=module)) class build_ext(setuptools.command.build_ext.build_ext): # Copy libiomp5.dylib inside the wheel package on OS X def _embed_libiomp(self): lib_dir = os.path.join(self.build_lib, 'torch', 'lib') libtorch_cpu_path = os.path.join(lib_dir, 'libtorch_cpu.dylib') if not os.path.exists(libtorch_cpu_path): return # Parse libtorch_cpu load commands otool_cmds = subprocess.check_output(['otool', '-l', libtorch_cpu_path]).decode('utf-8').split('\n') rpaths, libs = [], [] for idx, line in enumerate(otool_cmds): if line.strip() == 'cmd LC_LOAD_DYLIB': lib_name = otool_cmds[idx + 2].strip() assert lib_name.startswith('name ') libs.append(lib_name.split(' ', 1)[1].rsplit('(', 1)[0][:-1]) if line.strip() == 'cmd LC_RPATH': rpath = otool_cmds[idx + 2].strip() assert rpath.startswith('path ') rpaths.append(rpath.split(' ', 1)[1].rsplit('(', 1)[0][:-1]) omp_lib_name = 'libiomp5.dylib' if os.path.join('@rpath', omp_lib_name) not in libs: return # Copy libiomp5 from rpath locations for rpath in rpaths: source_lib = os.path.join(rpath, omp_lib_name) if not os.path.exists(source_lib): continue target_lib = os.path.join(self.build_lib, 'torch', 'lib', omp_lib_name) self.copy_file(source_lib, target_lib) break def run(self): # Report build options. This is run after the build completes so # `CMakeCache.txt` exists and we can get an # accurate report on what is used and what is not. cmake_cache_vars = defaultdict(lambda: False, cmake.get_cmake_cache_variables()) if cmake_cache_vars['USE_NUMPY']: report('-- Building with NumPy bindings') else: report('-- NumPy not found') if cmake_cache_vars['USE_CUDNN']: report('-- Detected cuDNN at ' + cmake_cache_vars['CUDNN_LIBRARY'] + ', ' + cmake_cache_vars['CUDNN_INCLUDE_DIR']) else: report('-- Not using cuDNN') if cmake_cache_vars['USE_CUDA']: report('-- Detected CUDA at ' + cmake_cache_vars['CUDA_TOOLKIT_ROOT_DIR']) else: report('-- Not using CUDA') if cmake_cache_vars['USE_MKLDNN']: report('-- Using MKLDNN') if cmake_cache_vars['USE_MKLDNN_ACL']: report('-- Using Compute Library for the Arm architecture with MKLDNN') else: report('-- Not using Compute Library for the Arm architecture with MKLDNN') if cmake_cache_vars['USE_MKLDNN_CBLAS']: report('-- Using CBLAS in MKLDNN') else: report('-- Not using CBLAS in MKLDNN') else: report('-- Not using MKLDNN') if cmake_cache_vars['USE_NCCL'] and cmake_cache_vars['USE_SYSTEM_NCCL']: report('-- Using system provided NCCL library at {}, {}'.format(cmake_cache_vars['NCCL_LIBRARIES'], cmake_cache_vars['NCCL_INCLUDE_DIRS'])) elif cmake_cache_vars['USE_NCCL']: report('-- Building NCCL library') else: report('-- Not using NCCL') if cmake_cache_vars['USE_DISTRIBUTED']: if IS_WINDOWS: report('-- Building without distributed package') else: report('-- Building with distributed package: ') report(' -- USE_TENSORPIPE={}'.format(cmake_cache_vars['USE_TENSORPIPE'])) report(' -- USE_GLOO={}'.format(cmake_cache_vars['USE_GLOO'])) report(' -- USE_MPI={}'.format(cmake_cache_vars['USE_OPENMPI'])) else: report('-- Building without distributed package') if cmake_cache_vars['STATIC_DISPATCH_BACKEND']: report('-- Using static dispatch with backend {}'.format(cmake_cache_vars['STATIC_DISPATCH_BACKEND'])) if cmake_cache_vars['USE_LIGHTWEIGHT_DISPATCH']: report('-- Using lightweight dispatch') if cmake_cache_vars['USE_ITT']: report('-- Using ITT') else: report('-- Not using ITT') # Do not use clang to compile extensions if `-fstack-clash-protection` is defined # in system CFLAGS c_flags = str(os.getenv('CFLAGS', '')) if IS_LINUX and '-fstack-clash-protection' in c_flags and 'clang' in os.environ.get('CC', ''): os.environ['CC'] = str(os.environ['CC']) # It's an old-style class in Python 2.7... setuptools.command.build_ext.build_ext.run(self) if IS_DARWIN and package_type != 'conda': self._embed_libiomp() # Copy the essential export library to compile C++ extensions. if IS_WINDOWS: build_temp = self.build_temp ext_filename = self.get_ext_filename('_C') lib_filename = '.'.join(ext_filename.split('.')[:-1]) + '.lib' export_lib = os.path.join( build_temp, 'torch', 'csrc', lib_filename).replace('\\', '/') build_lib = self.build_lib target_lib = os.path.join( build_lib, 'torch', 'lib', '_C.lib').replace('\\', '/') # Create "torch/lib" directory if not exists. # (It is not created yet in "develop" mode.) target_dir = os.path.dirname(target_lib) if not os.path.exists(target_dir): os.makedirs(target_dir) self.copy_file(export_lib, target_lib) def build_extensions(self): self.create_compile_commands() # The caffe2 extensions are created in # tmp_install/lib/pythonM.m/site-packages/caffe2/python/ # and need to be copied to build/lib.linux.... , which will be a # platform dependent build folder created by the "build" command of # setuptools. Only the contents of this folder are installed in the # "install" command by default. # We only make this copy for Caffe2's pybind extensions caffe2_pybind_exts = [ 'caffe2.python.caffe2_pybind11_state', 'caffe2.python.caffe2_pybind11_state_gpu', 'caffe2.python.caffe2_pybind11_state_hip', ] i = 0 while i < len(self.extensions): ext = self.extensions[i] if ext.name not in caffe2_pybind_exts: i += 1 continue fullname = self.get_ext_fullname(ext.name) filename = self.get_ext_filename(fullname) report("\nCopying extension {}".format(ext.name)) relative_site_packages = sysconfig.get_path('purelib').replace(sysconfig.get_path('data'), '').lstrip(os.path.sep) src = os.path.join("torch", relative_site_packages, filename) if not os.path.exists(src): report("{} does not exist".format(src)) del self.extensions[i] else: dst = os.path.join(os.path.realpath(self.build_lib), filename) report("Copying {} from {} to {}".format(ext.name, src, dst)) dst_dir = os.path.dirname(dst) if not os.path.exists(dst_dir): os.makedirs(dst_dir) self.copy_file(src, dst) i += 1 setuptools.command.build_ext.build_ext.build_extensions(self) def get_outputs(self): outputs = setuptools.command.build_ext.build_ext.get_outputs(self) outputs.append(os.path.join(self.build_lib, "caffe2")) report("setup.py::get_outputs returning {}".format(outputs)) return outputs def create_compile_commands(self): def load(filename): with open(filename) as f: return json.load(f) ninja_files = glob.glob('build/*compile_commands.json') cmake_files = glob.glob('torch/lib/build/*/compile_commands.json') all_commands = [entry for f in ninja_files + cmake_files for entry in load(f)] # cquery does not like c++ compiles that start with gcc. # It forgets to include the c++ header directories. # We can work around this by replacing the gcc calls that python # setup.py generates with g++ calls instead for command in all_commands: if command['command'].startswith("gcc "): command['command'] = "g++ " + command['command'][4:] new_contents = json.dumps(all_commands, indent=2) contents = '' if os.path.exists('compile_commands.json'): with open('compile_commands.json', 'r') as f: contents = f.read() if contents != new_contents: with open('compile_commands.json', 'w') as f: f.write(new_contents) class concat_license_files(): """Merge LICENSE and LICENSES_BUNDLED.txt as a context manager LICENSE is the main PyTorch license, LICENSES_BUNDLED.txt is auto-generated from all the licenses found in ./third_party/. We concatenate them so there is a single license file in the sdist and wheels with all of the necessary licensing info. """ def __init__(self, include_files=False): self.f1 = 'LICENSE' self.f2 = 'third_party/LICENSES_BUNDLED.txt' self.include_files = include_files def __enter__(self): """Concatenate files""" old_path = sys.path sys.path.append(third_party_path) try: from build_bundled import create_bundled finally: sys.path = old_path with open(self.f1, 'r') as f1: self.bsd_text = f1.read() with open(self.f1, 'a') as f1: f1.write('\n\n') create_bundled(os.path.relpath(third_party_path), f1, include_files=self.include_files) def __exit__(self, exception_type, exception_value, traceback): """Restore content of f1""" with open(self.f1, 'w') as f: f.write(self.bsd_text) try: from wheel.bdist_wheel import bdist_wheel except ImportError: # This is useful when wheel is not installed and bdist_wheel is not # specified on the command line. If it _is_ specified, parsing the command # line will fail before wheel_concatenate is needed wheel_concatenate = None else: # Need to create the proper LICENSE.txt for the wheel class wheel_concatenate(bdist_wheel): """ check submodules on sdist to prevent incomplete tarballs """ def run(self): with concat_license_files(include_files=True): super().run() class install(setuptools.command.install.install): def run(self): super().run() class clean(setuptools.Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import glob import re with open('.gitignore', 'r') as f: ignores = f.read() pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?') for wildcard in filter(None, ignores.split('\n')): match = pat.match(wildcard) if match: if match.group(1): # Marker is found and stop reading .gitignore. break # Ignore lines which begin with '#'. else: for filename in glob.glob(wildcard): try: os.remove(filename) except OSError: shutil.rmtree(filename, ignore_errors=True) class sdist(setuptools.command.sdist.sdist): def run(self): with concat_license_files(): super().run() def configure_extension_build(): r"""Configures extension build options according to system environment and user's choice. Returns: The input to parameters ext_modules, cmdclass, packages, and entry_points as required in setuptools.setup. """ try: cmake_cache_vars = defaultdict(lambda: False, cmake.get_cmake_cache_variables()) except FileNotFoundError: # CMakeCache.txt does not exist. Probably running "python setup.py clean" over a clean directory. cmake_cache_vars = defaultdict(lambda: False) ################################################################################ # Configure compile flags ################################################################################ library_dirs = [] extra_install_requires = [] if IS_WINDOWS: # /NODEFAULTLIB makes sure we only link to DLL runtime # and matches the flags set for protobuf and ONNX extra_link_args = ['/NODEFAULTLIB:LIBCMT.LIB'] # /MD links against DLL runtime # and matches the flags set for protobuf and ONNX # /EHsc is about standard C++ exception handling # /DNOMINMAX removes builtin min/max functions # /wdXXXX disables warning no. XXXX extra_compile_args = ['/MD', '/EHsc', '/DNOMINMAX', '/wd4267', '/wd4251', '/wd4522', '/wd4522', '/wd4838', '/wd4305', '/wd4244', '/wd4190', '/wd4101', '/wd4996', '/wd4275'] else: extra_link_args = [] extra_compile_args = [ '-Wall', '-Wextra', '-Wno-strict-overflow', '-Wno-unused-parameter', '-Wno-missing-field-initializers', '-Wno-write-strings', '-Wno-unknown-pragmas', # This is required for Python 2 declarations that are deprecated in 3. '-Wno-deprecated-declarations', # Python 2.6 requires -fno-strict-aliasing, see # http://legacy.python.org/dev/peps/pep-3123/ # We also depend on it in our code (even Python 3). '-fno-strict-aliasing', # Clang has an unfixed bug leading to spurious missing # braces warnings, see # https://bugs.llvm.org/show_bug.cgi?id=21629 '-Wno-missing-braces', ] library_dirs.append(lib_path) main_compile_args = [] main_libraries = ['torch_python'] main_link_args = [] main_sources = ["torch/csrc/stub.c"] if cmake_cache_vars['USE_CUDA']: library_dirs.append( os.path.dirname(cmake_cache_vars['CUDA_CUDA_LIB'])) if build_type.is_debug(): if IS_WINDOWS: extra_compile_args.append('/Z7') extra_link_args.append('/DEBUG:FULL') else: extra_compile_args += ['-O0', '-g'] extra_link_args += ['-O0', '-g'] if build_type.is_rel_with_deb_info(): if IS_WINDOWS: extra_compile_args.append('/Z7') extra_link_args.append('/DEBUG:FULL') else: extra_compile_args += ['-g'] extra_link_args += ['-g'] # Cross-compile for M1 if IS_DARWIN: macos_target_arch = os.getenv('CMAKE_OSX_ARCHITECTURES', '') if macos_target_arch in ['arm64', 'x86_64']: macos_sysroot_path = os.getenv('CMAKE_OSX_SYSROOT') if macos_sysroot_path is None: macos_sysroot_path = subprocess.check_output([ 'xcrun', '--show-sdk-path', '--sdk', 'macosx' ]).decode('utf-8').strip() extra_compile_args += ['-arch', macos_target_arch, '-isysroot', macos_sysroot_path] extra_link_args += ['-arch', macos_target_arch] def make_relative_rpath_args(path): if IS_DARWIN: return ['-Wl,-rpath,@loader_path/' + path] elif IS_WINDOWS: return [] else: return ['-Wl,-rpath,$ORIGIN/' + path] ################################################################################ # Declare extensions and package ################################################################################ extensions = [] packages = find_packages(exclude=('tools', 'tools.*')) C = Extension("torch._C", libraries=main_libraries, sources=main_sources, language='c', extra_compile_args=main_compile_args + extra_compile_args, include_dirs=[], library_dirs=library_dirs, extra_link_args=extra_link_args + main_link_args + make_relative_rpath_args('lib')) C_flatbuffer = Extension("torch._C_flatbuffer", libraries=main_libraries, sources=["torch/csrc/stub_with_flatbuffer.c"], language='c', extra_compile_args=main_compile_args + extra_compile_args, include_dirs=[], library_dirs=library_dirs, extra_link_args=extra_link_args + main_link_args + make_relative_rpath_args('lib')) extensions.append(C) extensions.append(C_flatbuffer) if not IS_WINDOWS: DL = Extension("torch._dl", sources=["torch/csrc/dl.c"], language='c') extensions.append(DL) # These extensions are built by cmake and copied manually in build_extensions() # inside the build_ext implementation if cmake_cache_vars['BUILD_CAFFE2']: extensions.append( Extension( name=str('caffe2.python.caffe2_pybind11_state'), sources=[]), ) if cmake_cache_vars['USE_CUDA']: extensions.append( Extension( name=str('caffe2.python.caffe2_pybind11_state_gpu'), sources=[]), ) if cmake_cache_vars['USE_ROCM']: extensions.append( Extension( name=str('caffe2.python.caffe2_pybind11_state_hip'), sources=[]), ) cmdclass = { 'bdist_wheel': wheel_concatenate, 'build_ext': build_ext, 'clean': clean, 'install': install, 'sdist': sdist, } entry_points = { 'console_scripts': [ 'convert-caffe2-to-onnx = caffe2.python.onnx.bin.conversion:caffe2_to_onnx', 'convert-onnx-to-caffe2 = caffe2.python.onnx.bin.conversion:onnx_to_caffe2', 'torchrun = torch.distributed.run:main', ] } return extensions, cmdclass, packages, entry_points, extra_install_requires # post run, warnings, printed at the end to make them more visible build_update_message = """ It is no longer necessary to use the 'build' or 'rebuild' targets To install: $ python setup.py install To develop locally: $ python setup.py develop To force cmake to re-generate native build files (off by default): $ python setup.py develop --cmake """ def print_box(msg): lines = msg.split('\n') size = max(len(l) + 1 for l in lines) print('-' * (size + 2)) for l in lines: print('|{}{}|'.format(l, ' ' * (size - len(l)))) print('-' * (size + 2)) if __name__ == '__main__': # Parse the command line and check the arguments before we proceed with # building deps and setup. We need to set values so `--help` works. dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = sys.argv[1:] try: dist.parse_command_line() except setuptools.distutils.errors.DistutilsArgError as e: print(e) sys.exit(1) mirror_files_into_torchgen() if RUN_BUILD_DEPS: build_deps() extensions, cmdclass, packages, entry_points, extra_install_requires = configure_extension_build() install_requires += extra_install_requires # Read in README.md for our long_description with open(os.path.join(cwd, "README.md"), encoding="utf-8") as f: long_description = f.read() version_range_max = max(sys.version_info[1], 9) + 1 setup( name=package_name, version=version, description=("Tensors and Dynamic neural networks in " "Python with strong GPU acceleration"), long_description=long_description, long_description_content_type="text/markdown", ext_modules=extensions, cmdclass=cmdclass, packages=packages, entry_points=entry_points, install_requires=install_requires, package_data={ 'torch': [ 'py.typed', 'bin/*', 'test/*', '_C/*.pyi', '_C_flatbuffer/*.pyi', 'cuda/*.pyi', 'optim/*.pyi', 'autograd/*.pyi', 'utils/data/*.pyi', 'nn/*.pyi', 'nn/modules/*.pyi', 'nn/parallel/*.pyi', 'utils/data/*.pyi', 'lib/*.so*', 'lib/*.dylib*', 'lib/*.dll', 'lib/*.lib', 'lib/*.pdb', 'lib/torch_shm_manager', 'lib/*.h', 'include/ATen/*.h', 'include/ATen/cpu/*.h', 'include/ATen/cpu/vec/vec256/*.h', 'include/ATen/cpu/vec/vec512/*.h', 'include/ATen/cpu/vec/*.h', 'include/ATen/core/*.h', 'include/ATen/cuda/*.cuh', 'include/ATen/cuda/*.h', 'include/ATen/cuda/detail/*.cuh', 'include/ATen/cuda/detail/*.h', 'include/ATen/cudnn/*.h', 'include/ATen/ops/*.h', 'include/ATen/hip/*.cuh', 'include/ATen/hip/*.h', 'include/ATen/hip/detail/*.cuh', 'include/ATen/hip/detail/*.h', 'include/ATen/hip/impl/*.h', 'include/ATen/detail/*.h', 'include/ATen/native/*.h', 'include/ATen/native/cpu/*.h', 'include/ATen/native/cuda/*.h', 'include/ATen/native/cuda/*.cuh', 'include/ATen/native/hip/*.h', 'include/ATen/native/hip/*.cuh', 'include/ATen/native/quantized/*.h', 'include/ATen/native/quantized/cpu/*.h', 'include/ATen/quantized/*.h', 'include/caffe2/utils/*.h', 'include/caffe2/utils/**/*.h', 'include/c10/*.h', 'include/c10/macros/*.h', 'include/c10/core/*.h', 'include/ATen/core/boxing/*.h', 'include/ATen/core/boxing/impl/*.h', 'include/ATen/core/dispatch/*.h', 'include/ATen/core/op_registration/*.h', 'include/c10/core/impl/*.h', 'include/c10/util/*.h', 'include/c10/cuda/*.h', 'include/c10/cuda/impl/*.h', 'include/c10/hip/*.h', 'include/c10/hip/impl/*.h', 'include/c10d/*.h', 'include/c10d/*.hpp', 'include/caffe2/**/*.h', 'include/torch/*.h', 'include/torch/csrc/*.h', 'include/torch/csrc/api/include/torch/*.h', 'include/torch/csrc/api/include/torch/data/*.h', 'include/torch/csrc/api/include/torch/data/dataloader/*.h', 'include/torch/csrc/api/include/torch/data/datasets/*.h', 'include/torch/csrc/api/include/torch/data/detail/*.h', 'include/torch/csrc/api/include/torch/data/samplers/*.h', 'include/torch/csrc/api/include/torch/data/transforms/*.h', 'include/torch/csrc/api/include/torch/detail/*.h', 'include/torch/csrc/api/include/torch/detail/ordered_dict.h', 'include/torch/csrc/api/include/torch/nn/*.h', 'include/torch/csrc/api/include/torch/nn/functional/*.h', 'include/torch/csrc/api/include/torch/nn/options/*.h', 'include/torch/csrc/api/include/torch/nn/modules/*.h', 'include/torch/csrc/api/include/torch/nn/modules/container/*.h', 'include/torch/csrc/api/include/torch/nn/parallel/*.h', 'include/torch/csrc/api/include/torch/nn/utils/*.h', 'include/torch/csrc/api/include/torch/optim/*.h', 'include/torch/csrc/api/include/torch/optim/schedulers/*.h', 'include/torch/csrc/api/include/torch/serialize/*.h', 'include/torch/csrc/autograd/*.h', 'include/torch/csrc/autograd/functions/*.h', 'include/torch/csrc/autograd/generated/*.h', 'include/torch/csrc/autograd/utils/*.h', 'include/torch/csrc/cuda/*.h', 'include/torch/csrc/deploy/*.h', 'include/torch/csrc/deploy/interpreter/*.h', 'include/torch/csrc/deploy/interpreter/*.hpp', 'include/torch/csrc/distributed/c10d/exception.h', 'include/torch/csrc/distributed/rpc/*.h', 'include/torch/csrc/jit/*.h', 'include/torch/csrc/jit/backends/*.h', 'include/torch/csrc/jit/generated/*.h', 'include/torch/csrc/jit/passes/*.h', 'include/torch/csrc/jit/passes/quantization/*.h', 'include/torch/csrc/jit/passes/utils/*.h', 'include/torch/csrc/jit/runtime/*.h', 'include/torch/csrc/jit/ir/*.h', 'include/torch/csrc/jit/frontend/*.h', 'include/torch/csrc/jit/api/*.h', 'include/torch/csrc/jit/serialization/*.h', 'include/torch/csrc/jit/python/*.h', 'include/torch/csrc/jit/mobile/*.h', 'include/torch/csrc/jit/testing/*.h', 'include/torch/csrc/jit/tensorexpr/*.h', 'include/torch/csrc/jit/tensorexpr/operators/*.h', 'include/torch/csrc/jit/codegen/cuda/*.h', 'include/torch/csrc/jit/codegen/cuda/ops/*.h', 'include/torch/csrc/jit/codegen/cuda/scheduler/*.h', 'include/torch/csrc/onnx/*.h', 'include/torch/csrc/profiler/*.h', 'include/torch/csrc/utils/*.h', 'include/torch/csrc/tensor/*.h', 'include/torch/csrc/lazy/backend/*.h', 'include/torch/csrc/lazy/core/*.h', 'include/torch/csrc/lazy/core/internal_ops/*.h', 'include/torch/csrc/lazy/core/ops/*.h', 'include/torch/csrc/lazy/ts_backend/*.h', 'include/pybind11/*.h', 'include/pybind11/detail/*.h', 'include/TH/*.h*', 'include/TH/generic/*.h*', 'include/THC/*.cuh', 'include/THC/*.h*', 'include/THC/generic/*.h', 'include/THH/*.cuh', 'include/THH/*.h*', 'include/THH/generic/*.h', 'share/cmake/ATen/*.cmake', 'share/cmake/Caffe2/*.cmake', 'share/cmake/Caffe2/public/*.cmake', 'share/cmake/Caffe2/Modules_CUDA_fix/*.cmake', 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/*.cmake', 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/*.cmake', 'share/cmake/Gloo/*.cmake', 'share/cmake/Tensorpipe/*.cmake', 'share/cmake/Torch/*.cmake', 'utils/benchmark/utils/*.cpp', 'utils/benchmark/utils/valgrind_wrapper/*.cpp', 'utils/benchmark/utils/valgrind_wrapper/*.h', 'utils/model_dump/skeleton.html', 'utils/model_dump/code.js', 'utils/model_dump/*.mjs', ], 'torchgen': [ # Recursive glob doesn't work in setup.py, # https://github.com/pypa/setuptools/issues/1806 # To make this robust we should replace it with some code that # returns a list of everything under packaged/ 'packaged/ATen/*', 'packaged/ATen/native/*', 'packaged/ATen/templates/*', ], 'caffe2': [ 'python/serialized_test/data/operator_test/*.zip', ], }, url='https://pytorch.org/', download_url='https://github.com/pytorch/pytorch/tags', author='PyTorch Team', author_email='packages@pytorch.org', python_requires='>={}'.format(python_min_version_str), # PyPI package information. classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: C++', 'Programming Language :: Python :: 3', ] + ['Programming Language :: Python :: 3.{}'.format(i) for i in range(python_min_version[1], version_range_max)], license='BSD-3', keywords='pytorch, machine learning', ) if EMIT_BUILD_WARNING: print_box(build_update_message)
pytorch-master
setup.py
#!/usr/bin/env python3 import json from pathlib import Path def main() -> None: folder = Path(".vscode") recommended = json.loads((folder / "settings_recommended.json").read_text()) path = folder / "settings.json" try: current = json.loads(path.read_text()) except Exception: current = {} with open(path, "w") as f: json.dump({**current, **recommended}, f, indent=2) f.write("\n") if __name__ == "__main__": main()
pytorch-master
tools/vscode_settings.py
#!/usr/bin/env python3 import argparse import re import sys from pathlib import Path from typing import Any, Dict, Optional import yaml from typing_extensions import TypedDict Step = Dict[str, Any] class Script(TypedDict): extension: str script: str def extract(step: Step) -> Optional[Script]: run = step.get("run") # https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#using-a-specific-shell shell = step.get("shell", "bash") extension = { "bash": ".sh", "pwsh": ".ps1", "python": ".py", "sh": ".sh", "cmd": ".cmd", "powershell": ".ps1", }.get(shell) is_gh_script = step.get("uses", "").startswith("actions/github-script@") gh_script = step.get("with", {}).get("script") if run is not None and extension is not None: script = { "bash": f"#!/usr/bin/env bash\nset -eo pipefail\n{run}", "sh": f"#!/usr/bin/env sh\nset -e\n{run}", }.get(shell, run) return {"extension": extension, "script": script} elif is_gh_script and gh_script is not None: return {"extension": ".js", "script": gh_script} else: return None def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--out", required=True) args = parser.parse_args() out = Path(args.out) if out.exists(): sys.exit(f"{out} already exists; aborting to avoid overwriting") gha_expressions_found = False for p in Path(".github/workflows").iterdir(): with open(p, "rb") as f: workflow = yaml.safe_load(f) for job_name, job in workflow["jobs"].items(): job_dir = out / p / job_name if "steps" not in job: continue steps = job["steps"] index_chars = len(str(len(steps) - 1)) for i, step in enumerate(steps, start=1): extracted = extract(step) if extracted: script = extracted["script"] step_name = step.get("name", "") if "${{" in script: gha_expressions_found = True print( f"{p} job `{job_name}` step {i}: {step_name}", file=sys.stderr, ) job_dir.mkdir(parents=True, exist_ok=True) sanitized = re.sub( "[^a-zA-Z_]+", "_", f"_{step_name}", ).rstrip("_") extension = extracted["extension"] filename = f"{i:0{index_chars}}{sanitized}{extension}" (job_dir / filename).write_text(script) if gha_expressions_found: sys.exit( "Each of the above scripts contains a GitHub Actions " "${{ <expression> }} which must be replaced with an `env` variable" " for security reasons." ) if __name__ == "__main__": main()
pytorch-master
tools/extract_scripts.py
"""Tool to fix the nvcc's dependecy file output Usage: python nvcc_fix_deps.py nvcc [nvcc args]... This wraps nvcc to ensure that the dependency file created by nvcc with the -MD flag always uses absolute paths. nvcc sometimes outputs relative paths, which ninja interprets as an unresolved dependency, so it triggers a rebuild of that file every time. The easiest way to use this is to define: CMAKE_CUDA_COMPILER_LAUNCHER="python;tools/nvcc_fix_deps.py;ccache" """ import subprocess import sys from pathlib import Path from typing import List, Optional, TextIO def resolve_include(path: Path, include_dirs: List[Path]) -> Path: for include_path in include_dirs: abs_path = include_path / path if abs_path.exists(): return abs_path paths = "\n ".join(str(d / path) for d in include_dirs) raise RuntimeError( f""" ERROR: Failed to resolve dependency: {path} Tried the following paths, but none existed: {paths} """ ) def repair_depfile(depfile: TextIO, include_dirs: List[Path]) -> None: changes_made = False out = "" for line in depfile.readlines(): if ":" in line: colon_pos = line.rfind(":") out += line[: colon_pos + 1] line = line[colon_pos + 1 :] line = line.strip() if line.endswith("\\"): end = " \\" line = line[:-1].strip() else: end = "" path = Path(line) if not path.is_absolute(): changes_made = True path = resolve_include(path, include_dirs) out += f" {path}{end}\n" # If any paths were changed, rewrite the entire file if changes_made: depfile.seek(0) depfile.write(out) depfile.truncate() PRE_INCLUDE_ARGS = ["-include", "--pre-include"] POST_INCLUDE_ARGS = ["-I", "--include-path", "-isystem", "--system-include"] def extract_include_arg(include_dirs: List[Path], i: int, args: List[str]) -> None: def extract_one(name: str, i: int, args: List[str]) -> Optional[str]: arg = args[i] if arg == name: return args[i + 1] if arg.startswith(name): arg = arg[len(name) :] return arg[1:] if arg[0] == "=" else arg return None for name in PRE_INCLUDE_ARGS: path = extract_one(name, i, args) if path is not None: include_dirs.insert(0, Path(path).resolve()) return for name in POST_INCLUDE_ARGS: path = extract_one(name, i, args) if path is not None: include_dirs.append(Path(path).resolve()) return if __name__ == "__main__": ret = subprocess.run( sys.argv[1:], stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr ) depfile_path = None include_dirs = [] # Parse only the nvcc arguments we care about args = sys.argv[2:] for i, arg in enumerate(args): if arg == "-MF": depfile_path = Path(args[i + 1]) elif arg == "-c": # Include the base path of the cuda file include_dirs.append(Path(args[i + 1]).resolve().parent) else: extract_include_arg(include_dirs, i, args) if depfile_path is not None and depfile_path.exists(): with depfile_path.open("r+") as f: repair_depfile(f, include_dirs) sys.exit(ret.returncode)
pytorch-master
tools/nvcc_fix_deps.py
import argparse import os import os.path if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--input-file") parser.add_argument("--output-file") parser.add_argument("--install_dir") parser.add_argument("--replace", action="append", nargs=2) options = parser.parse_args() with open(options.input_file, "r") as f: contents = f.read() output_file = os.path.join(options.install_dir, options.output_file) os.makedirs(os.path.dirname(output_file), exist_ok=True) for old, new in options.replace: contents = contents.replace(old, new) with open(output_file, "w") as f: f.write(contents)
pytorch-master
tools/substitute.py
#!/usr/bin/env python3 import argparse import array import glob import os import re import sys import subprocess from torchgen.code_template import CodeTemplate H_NAME = "spv.h" CPP_NAME = "spv.cpp" DEFAULT_ENV = {"precision": "highp", "format": "rgba32f"} def getName(filePath): return os.path.basename(filePath).replace("/", "_").replace(".", "_") def isDescriptorLine(lineStr): descriptorLineId = r"^layout\(set" return re.search(descriptorLineId, lineStr) typeIdMapping = { r"image[123]D\b": "VK_DESCRIPTOR_TYPE_STORAGE_IMAGE", r"sampler[123]D\b": "VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER", r"\bbuffer\b": "VK_DESCRIPTOR_TYPE_STORAGE_BUFFER", r"\buniform\b.*\bBlock\b": "VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER", } def determineDescriptorType(lineStr): for identifier, typeNum in typeIdMapping.items(): if re.search(identifier, lineStr): return typeNum raise Exception("Could not identify descriptor type of line: {}".format(lineStr)) def getLayout(srcFilePath): layout = [] with open(srcFilePath, 'r') as srcFile: for line in srcFile: if isDescriptorLine(line): layout.append(determineDescriptorType(line)) return layout def genCppH(hFilePath, cppFilePath, srcDirPath, glslcPath, tmpDirPath, env): print("hFilePath:{} cppFilePath:{} srcDirPath:{} glslcPath:{} tmpDirPath:{}".format( hFilePath, cppFilePath, srcDirPath, glslcPath, tmpDirPath)) vexs = glob.glob(os.path.join(srcDirPath, '**', '*.glsl'), recursive=True) templateSrcPaths = [] for f in vexs: if len(f) > 1: templateSrcPaths.append(f) templateSrcPaths.sort() print("templateSrcPaths:{}".format(templateSrcPaths)) spvPaths = {} for templateSrcPath in templateSrcPaths: print("templateSrcPath {}".format(templateSrcPath)) name = getName(templateSrcPath).replace("_glsl", "") print("name {}".format(name)) codeTemplate = CodeTemplate.from_file(templateSrcPath) srcPath = tmpDirPath + "/" + name + ".glsl" content = codeTemplate.substitute(env) with open(srcPath, 'w') as f: f.write(content) spvPath = tmpDirPath + "/" + name + ".spv" print("spvPath {}".format(spvPath)) cmd = [ glslcPath, "-fshader-stage=compute", srcPath, "-o", spvPath, "--target-env=vulkan1.0", "-Werror" ] print("\nglslc cmd:", cmd) subprocess.check_call(cmd) spvPaths[spvPath] = templateSrcPath h = "#pragma once\n" h += "#include <stdint.h>\n" h += "#include <vector>\n" h += "#include <ATen/native/vulkan/api/vk_api.h>" nsbegin = "\nnamespace at {\nnamespace native {\nnamespace vulkan {\n" nsend = "\n}\n}\n} //namespace at::native::vulkan\n" h += nsbegin cpp = "#include <ATen/native/vulkan/{}>".format(H_NAME) cpp += nsbegin for spvPath, srcPath in spvPaths.items(): name = getName(spvPath) name_len = name + "_len" h += "extern const uint32_t {}[];\n".format(name) h += "extern const uint32_t {};\n".format(name_len) layout = getLayout(srcPath) name_layout = name + "_layout" h += "extern const std::vector<VkDescriptorType> {};\n".format(name_layout) cpp += "const uint32_t " + name + "[] = {\n" sizeBytes = 0 print("spvPath:{}".format(spvPath)) with open(spvPath, 'rb') as f: for word in array.array('I', f.read()): cpp += "{},\n".format(word) sizeBytes += 4 cpp += "};\n" cpp += "const uint32_t {} = {};\n".format(name_len, sizeBytes) # Add layout cpp += "const std::vector<VkDescriptorType> {} = {{\n".format(name_layout) for descriptor in layout: cpp += " {},\n".format(descriptor) cpp += "};\n" cpp += nsend h += nsend with open(hFilePath, "w") as f: f.write(h) with open(cppFilePath, "w") as f: f.write(cpp) def parse_arg_env(items): d = {} if items: for item in items: tokens = item.split("=") key = tokens[0].strip() value = tokens[1].strip() d[key] = value return d def main(argv): parser = argparse.ArgumentParser(description='') parser.add_argument( '-i', '--glsl-path', help='', default='.') parser.add_argument( '-c', '--glslc-path', required=True, help='') parser.add_argument( '-t', '--tmp-dir-path', required=True, help='/tmp') parser.add_argument( '-o', '--output-path', required=True, help='') parser.add_argument( "--env", metavar="KEY=VALUE", nargs='*', help="Set a number of key-value pairs") options = parser.parse_args() env = DEFAULT_ENV for key, value in parse_arg_env(options.env).items(): env[key] = value if not os.path.exists(options.output_path): os.makedirs(options.output_path) if not os.path.exists(options.tmp_dir_path): os.makedirs(options.tmp_dir_path) genCppH( hFilePath=options.output_path + "/spv.h", cppFilePath=options.output_path + "/spv.cpp", srcDirPath=options.glsl_path, glslcPath=options.glslc_path, tmpDirPath=options.tmp_dir_path, env=env) if __name__ == '__main__': sys.exit(main(sys.argv))
pytorch-master
tools/gen_vulkan_spv.py
pytorch-master
tools/__init__.py
#!/usr/bin/env python3 import argparse import os from typing import Any, List, Union try: from junitparser import ( # type: ignore[import] Error, Failure, JUnitXml, TestCase, TestSuite, ) except ImportError: raise ImportError( "junitparser not found, please install with 'pip install junitparser'" ) try: import rich except ImportError: print("rich not found, for color output use 'pip install rich'") def parse_junit_reports(path_to_reports: str) -> List[TestCase]: # type: ignore[no-any-unimported] def parse_file(path: str) -> List[TestCase]: # type: ignore[no-any-unimported] try: return convert_junit_to_testcases(JUnitXml.fromfile(path)) except Exception as err: rich.print( f":Warning: [yellow]Warning[/yellow]: Failed to read {path}: {err}" ) return [] if not os.path.exists(path_to_reports): raise FileNotFoundError(f"Path '{path_to_reports}', not found") # Return early if the path provided is just a file if os.path.isfile(path_to_reports): return parse_file(path_to_reports) ret_xml = [] if os.path.isdir(path_to_reports): for root, _, files in os.walk(path_to_reports): for fname in [f for f in files if f.endswith("xml")]: ret_xml += parse_file(os.path.join(root, fname)) return ret_xml def convert_junit_to_testcases(xml: Union[JUnitXml, TestSuite]) -> List[TestCase]: # type: ignore[no-any-unimported] testcases = [] for item in xml: if isinstance(item, TestSuite): testcases.extend(convert_junit_to_testcases(item)) else: testcases.append(item) return testcases def render_tests(testcases: List[TestCase]) -> None: # type: ignore[no-any-unimported] num_passed = 0 num_skipped = 0 num_failed = 0 for testcase in testcases: if not testcase.result: num_passed += 1 continue for result in testcase.result: if isinstance(result, Error): icon = ":rotating_light: [white on red]ERROR[/white on red]:" num_failed += 1 elif isinstance(result, Failure): icon = ":x: [white on red]Failure[/white on red]:" num_failed += 1 else: num_skipped += 1 continue rich.print( f"{icon} [bold red]{testcase.classname}.{testcase.name}[/bold red]" ) print(f"{result.text}") rich.print(f":white_check_mark: {num_passed} [green]Passed[green]") rich.print(f":dash: {num_skipped} [grey]Skipped[grey]") rich.print(f":rotating_light: {num_failed} [grey]Failed[grey]") def parse_args() -> Any: parser = argparse.ArgumentParser( description="Render xunit output for failed tests", ) parser.add_argument( "report_path", help="Base xunit reports (single file or directory) to compare to", ) return parser.parse_args() def main() -> None: options = parse_args() testcases = parse_junit_reports(options.report_path) render_tests(testcases) if __name__ == "__main__": main()
pytorch-master
tools/render_junit.py
import argparse import sys from os.path import abspath, dirname # By appending pytorch_root to sys.path, this module can import other torch # modules even when run as a standalone script. i.e., it's okay either you # do `python build_libtorch.py` or `python -m tools.build_libtorch`. pytorch_root = dirname(dirname(abspath(__file__))) sys.path.append(pytorch_root) from tools.build_pytorch_libs import build_caffe2 from tools.setup_helpers.cmake import CMake if __name__ == "__main__": # Placeholder for future interface. For now just gives a nice -h. parser = argparse.ArgumentParser(description="Build libtorch") parser.add_argument("--rerun-cmake", action="store_true", help="rerun cmake") parser.add_argument( "--cmake-only", action="store_true", help="Stop once cmake terminates. Leave users a chance to adjust build options", ) options = parser.parse_args() build_caffe2( version=None, cmake_python_library=None, build_python=False, rerun_cmake=options.rerun_cmake, cmake_only=options.cmake_only, cmake=CMake(), )
pytorch-master
tools/build_libtorch.py
"""This script updates the file torch/_masked/_docs.py that contains the generated doc-strings for various masked operations. The update should be triggered whenever a new masked operation is introduced to torch._masked package. Running the script requires that torch package is functional. """ import os def main() -> None: target = os.path.join("torch", "_masked", "_docs.py") try: import torch except ImportError as msg: print(f"Failed to import torch required to build {target}: {msg}") return if os.path.isfile(target): with open(target) as _f: current_content = _f.read() else: current_content = "" _new_content = [] _new_content.append( """\ # -*- coding: utf-8 -*- # This file is generated, do not modify it! # # To update this file, run the update masked docs script as follows: # # python tools/update_masked_docs.py # # The script must be called from an environment where the development # version of torch package can be imported and is functional. # """ ) for func_name in sorted(torch._masked.__all__): func = getattr(torch._masked, func_name) func_doc = torch._masked._generate_docstring(func) _new_content.append(f'{func_name}_docstring = """{func_doc}"""\n') new_content = "\n".join(_new_content) if new_content == current_content: print(f"Nothing to update in {target}") return with open(target, "w") as _f: _f.write(new_content) print(f"Successfully updated {target}") if __name__ == "__main__": main()
pytorch-master
tools/update_masked_docs.py
import argparse import os import re import subprocess from pathlib import Path from typing import Optional, Union from setuptools import distutils # type: ignore[import] UNKNOWN = "Unknown" RELEASE_PATTERN = re.compile(r"/v[0-9]+(\.[0-9]+)*(-rc[0-9]+)?/") def get_sha(pytorch_root: Union[str, Path]) -> str: try: return ( subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=pytorch_root) .decode("ascii") .strip() ) except Exception: return UNKNOWN def get_tag(pytorch_root: Union[str, Path]) -> str: try: tag = ( subprocess.check_output( ["git", "describe", "--tags", "--exact"], cwd=pytorch_root ) .decode("ascii") .strip() ) if RELEASE_PATTERN.match(tag): return tag else: return UNKNOWN except Exception: return UNKNOWN def get_torch_version(sha: Optional[str] = None) -> str: pytorch_root = Path(__file__).parent.parent version = open(pytorch_root / "version.txt", "r").read().strip() if os.getenv("PYTORCH_BUILD_VERSION"): assert os.getenv("PYTORCH_BUILD_NUMBER") is not None build_number = int(os.getenv("PYTORCH_BUILD_NUMBER", "")) version = os.getenv("PYTORCH_BUILD_VERSION", "") if build_number > 1: version += ".post" + str(build_number) elif sha != UNKNOWN: if sha is None: sha = get_sha(pytorch_root) version += "+git" + sha[:7] return version if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generate torch/version.py from build and environment metadata." ) parser.add_argument( "--is_debug", type=distutils.util.strtobool, help="Whether this build is debug mode or not.", ) parser.add_argument("--cuda_version", type=str) parser.add_argument("--hip_version", type=str) args = parser.parse_args() assert args.is_debug is not None args.cuda_version = None if args.cuda_version == "" else args.cuda_version args.hip_version = None if args.hip_version == "" else args.hip_version pytorch_root = Path(__file__).parent.parent version_path = pytorch_root / "torch" / "version.py" # Attempt to get tag first, fall back to sha if a tag was not found tagged_version = get_tag(pytorch_root) sha = get_sha(pytorch_root) if tagged_version == UNKNOWN: version = get_torch_version(sha) else: version = tagged_version with open(version_path, "w") as f: f.write("__version__ = '{}'\n".format(version)) # NB: This is not 100% accurate, because you could have built the # library code with DEBUG, but csrc without DEBUG (in which case # this would claim to be a release build when it's not.) f.write("debug = {}\n".format(repr(bool(args.is_debug)))) f.write("cuda = {}\n".format(repr(args.cuda_version))) f.write("git_version = {}\n".format(repr(sha))) f.write("hip = {}\n".format(repr(args.hip_version)))
pytorch-master
tools/generate_torch_version.py
import argparse import gzip import os import sys from urllib.error import URLError from urllib.request import urlretrieve MIRRORS = [ "http://yann.lecun.com/exdb/mnist/", "https://ossci-datasets.s3.amazonaws.com/mnist/", ] RESOURCES = [ "train-images-idx3-ubyte.gz", "train-labels-idx1-ubyte.gz", "t10k-images-idx3-ubyte.gz", "t10k-labels-idx1-ubyte.gz", ] def report_download_progress( chunk_number: int, chunk_size: int, file_size: int, ) -> None: if file_size != -1: percent = min(1, (chunk_number * chunk_size) / file_size) bar = "#" * int(64 * percent) sys.stdout.write("\r0% |{:<64}| {}%".format(bar, int(percent * 100))) def download(destination_path: str, resource: str, quiet: bool) -> None: if os.path.exists(destination_path): if not quiet: print("{} already exists, skipping ...".format(destination_path)) else: for mirror in MIRRORS: url = mirror + resource print("Downloading {} ...".format(url)) try: hook = None if quiet else report_download_progress urlretrieve(url, destination_path, reporthook=hook) except (URLError, ConnectionError) as e: print("Failed to download (trying next):\n{}".format(e)) continue finally: if not quiet: # Just a newline. print() break else: raise RuntimeError("Error downloading resource!") def unzip(zipped_path: str, quiet: bool) -> None: unzipped_path = os.path.splitext(zipped_path)[0] if os.path.exists(unzipped_path): if not quiet: print("{} already exists, skipping ... ".format(unzipped_path)) return with gzip.open(zipped_path, "rb") as zipped_file: with open(unzipped_path, "wb") as unzipped_file: unzipped_file.write(zipped_file.read()) if not quiet: print("Unzipped {} ...".format(zipped_path)) def main() -> None: parser = argparse.ArgumentParser( description="Download the MNIST dataset from the internet" ) parser.add_argument( "-d", "--destination", default=".", help="Destination directory" ) parser.add_argument( "-q", "--quiet", action="store_true", help="Don't report about progress" ) options = parser.parse_args() if not os.path.exists(options.destination): os.makedirs(options.destination) try: for resource in RESOURCES: path = os.path.join(options.destination, resource) download(path, resource, options.quiet) unzip(path, options.quiet) except KeyboardInterrupt: print("Interrupted") if __name__ == "__main__": main()
pytorch-master
tools/download_mnist.py
import os import platform import shutil from glob import glob from typing import Dict, Optional from setuptools import distutils # type: ignore[import] from .setup_helpers.cmake import CMake, USE_NINJA from .setup_helpers.env import check_negative_env_flag, IS_64BIT, IS_WINDOWS def _overlay_windows_vcvars(env: Dict[str, str]) -> Dict[str, str]: vc_arch = "x64" if IS_64BIT else "x86" if platform.machine() == "ARM64": vc_arch = "x64_arm64" # First Win11 Windows on Arm build version that supports x64 emulation # is 10.0.22000. win11_1st_version = (10, 0, 22000) current_win_version = tuple( int(version_part) for version_part in platform.version().split(".") ) if current_win_version < win11_1st_version: vc_arch = "x86_arm64" print( "Warning: 32-bit toolchain will be used, but 64-bit linker " "is recommended to avoid out-of-memory linker error!" ) print( "Warning: Please consider upgrading to Win11, where x64 " "emulation is enabled!" ) vc_env: Dict[str, str] = distutils._msvccompiler._get_vc_env(vc_arch) # Keys in `_get_vc_env` are always lowercase. # We turn them into uppercase before overlaying vcvars # because OS environ keys are always uppercase on Windows. # https://stackoverflow.com/a/7797329 vc_env = {k.upper(): v for k, v in vc_env.items()} for k, v in env.items(): uk = k.upper() if uk not in vc_env: vc_env[uk] = v return vc_env def _create_build_env() -> Dict[str, str]: # XXX - our cmake file sometimes looks at the system environment # and not cmake flags! # you should NEVER add something to this list. It is bad practice to # have cmake read the environment my_env = os.environ.copy() if ( "CUDA_HOME" in my_env ): # Keep CUDA_HOME. This env variable is still used in other part. my_env["CUDA_BIN_PATH"] = my_env["CUDA_HOME"] elif IS_WINDOWS: # we should eventually make this as part of FindCUDA. cuda_win = glob("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*") if len(cuda_win) > 0: my_env["CUDA_BIN_PATH"] = cuda_win[0] if IS_WINDOWS and USE_NINJA: # When using Ninja under Windows, the gcc toolchain will be chosen as # default. But it should be set to MSVC as the user's first choice. my_env = _overlay_windows_vcvars(my_env) my_env.setdefault("CC", "cl") my_env.setdefault("CXX", "cl") return my_env def build_caffe2( version: Optional[str], cmake_python_library: Optional[str], build_python: bool, rerun_cmake: bool, cmake_only: bool, cmake: CMake, ) -> None: my_env = _create_build_env() build_test = not check_negative_env_flag("BUILD_TEST") cmake.generate( version, cmake_python_library, build_python, build_test, my_env, rerun_cmake ) if cmake_only: return cmake.build(my_env) if build_python: caffe2_proto_dir = os.path.join(cmake.build_dir, "caffe2", "proto") for proto_file in glob(os.path.join(caffe2_proto_dir, "*.py")): if proto_file != os.path.join(caffe2_proto_dir, "__init__.py"): shutil.copy(proto_file, os.path.join("caffe2", "proto"))
pytorch-master
tools/build_pytorch_libs.py
#!/usr/bin/env python3 # Much of the logging code here was forked from https://github.com/ezyang/ghstack # Copyright (c) Edward Z. Yang <ezyang@mit.edu> """Checks out the nightly development version of PyTorch and installs pre-built binaries into the repo. You can use this script to check out a new nightly branch with the following:: $ ./tools/nightly.py checkout -b my-nightly-branch $ conda activate pytorch-deps Or if you would like to re-use an existing conda environment, you can pass in the regular environment parameters (--name or --prefix):: $ ./tools/nightly.py checkout -b my-nightly-branch -n my-env $ conda activate my-env You can also use this tool to pull the nightly commits into the current branch as well. This can be done with $ ./tools/nightly.py pull -n my-env $ conda activate my-env Pulling will reinstalle the conda dependencies as well as the nightly binaries into the repo directory. """ import contextlib import datetime import functools import glob import json import logging import os import re import shutil import subprocess import sys import tempfile import time import uuid from argparse import ArgumentParser from ast import literal_eval from typing import ( Any, Callable, cast, Dict, Generator, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, TypeVar, ) LOGGER: Optional[logging.Logger] = None URL_FORMAT = "{base_url}/{platform}/{dist_name}.tar.bz2" DATETIME_FORMAT = "%Y-%m-%d_%Hh%Mm%Ss" SHA1_RE = re.compile("([0-9a-fA-F]{40})") USERNAME_PASSWORD_RE = re.compile(r":\/\/(.*?)\@") LOG_DIRNAME_RE = re.compile( r"(\d{4}-\d\d-\d\d_\d\dh\d\dm\d\ds)_" r"[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}" ) SPECS_TO_INSTALL = ("pytorch", "mypy", "pytest", "hypothesis", "ipython", "sphinx") class Formatter(logging.Formatter): redactions: Dict[str, str] def __init__(self, fmt: Optional[str] = None, datefmt: Optional[str] = None): super().__init__(fmt, datefmt) self.redactions = {} # Remove sensitive information from URLs def _filter(self, s: str) -> str: s = USERNAME_PASSWORD_RE.sub(r"://<USERNAME>:<PASSWORD>@", s) for needle, replace in self.redactions.items(): s = s.replace(needle, replace) return s def formatMessage(self, record: logging.LogRecord) -> str: if record.levelno == logging.INFO or record.levelno == logging.DEBUG: # Log INFO/DEBUG without any adornment return record.getMessage() else: # I'm not sure why, but formatMessage doesn't show up # even though it's in the typeshed for Python >3 return super().formatMessage(record) def format(self, record: logging.LogRecord) -> str: return self._filter(super().format(record)) def redact(self, needle: str, replace: str = "<REDACTED>") -> None: """Redact specific strings; e.g., authorization tokens. This won't retroactively redact stuff you've already leaked, so make sure you redact things as soon as possible. """ # Don't redact empty strings; this will lead to something # that looks like s<REDACTED>t<REDACTED>r<REDACTED>... if needle == "": return self.redactions[needle] = replace @functools.lru_cache() def logging_base_dir() -> str: meta_dir = os.getcwd() base_dir = os.path.join(meta_dir, "nightly", "log") os.makedirs(base_dir, exist_ok=True) return base_dir @functools.lru_cache() def logging_run_dir() -> str: cur_dir = os.path.join( logging_base_dir(), "{}_{}".format(datetime.datetime.now().strftime(DATETIME_FORMAT), uuid.uuid1()), ) os.makedirs(cur_dir, exist_ok=True) return cur_dir @functools.lru_cache() def logging_record_argv() -> None: s = subprocess.list2cmdline(sys.argv) with open(os.path.join(logging_run_dir(), "argv"), "w") as f: f.write(s) def logging_record_exception(e: BaseException) -> None: with open(os.path.join(logging_run_dir(), "exception"), "w") as f: f.write(type(e).__name__) def logging_rotate() -> None: log_base = logging_base_dir() old_logs = os.listdir(log_base) old_logs.sort(reverse=True) for stale_log in old_logs[1000:]: # Sanity check that it looks like a log if LOG_DIRNAME_RE.fullmatch(stale_log) is not None: shutil.rmtree(os.path.join(log_base, stale_log)) @contextlib.contextmanager def logging_manager(*, debug: bool = False) -> Generator[logging.Logger, None, None]: """Setup logging. If a failure starts here we won't be able to save the user in a reasonable way. Logging structure: there is one logger (the root logger) and in processes all events. There are two handlers: stderr (INFO) and file handler (DEBUG). """ formatter = Formatter(fmt="%(levelname)s: %(message)s", datefmt="") root_logger = logging.getLogger("conda-pytorch") root_logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() if debug: console_handler.setLevel(logging.DEBUG) else: console_handler.setLevel(logging.INFO) console_handler.setFormatter(formatter) root_logger.addHandler(console_handler) log_file = os.path.join(logging_run_dir(), "nightly.log") file_handler = logging.FileHandler(log_file) file_handler.setFormatter(formatter) root_logger.addHandler(file_handler) logging_record_argv() try: logging_rotate() print(f"log file: {log_file}") yield root_logger except Exception as e: logging.exception("Fatal exception") logging_record_exception(e) print(f"log file: {log_file}") sys.exit(1) except BaseException as e: # You could logging.debug here to suppress the backtrace # entirely, but there is no reason to hide it from technically # savvy users. logging.info("", exc_info=True) logging_record_exception(e) print(f"log file: {log_file}") sys.exit(1) def check_in_repo() -> Optional[str]: """Ensures that we are in the PyTorch repo.""" if not os.path.isfile("setup.py"): return "Not in root-level PyTorch repo, no setup.py found" with open("setup.py") as f: s = f.read() if "PyTorch" not in s: return "Not in PyTorch repo, 'PyTorch' not found in setup.py" return None def check_branch(subcommand: str, branch: Optional[str]) -> Optional[str]: """Checks that the branch name can be checked out.""" if subcommand != "checkout": return None # first make sure actual branch name was given if branch is None: return "Branch name to checkout must be supplied with '-b' option" # next check that the local repo is clean cmd = ["git", "status", "--untracked-files=no", "--porcelain"] p = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, universal_newlines=True, ) if p.stdout.strip(): return "Need to have clean working tree to checkout!\n\n" + p.stdout # next check that the branch name doesn't already exist cmd = ["git", "show-ref", "--verify", "--quiet", "refs/heads/" + branch] p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) # type: ignore[assignment] if not p.returncode: return f"Branch {branch!r} already exists" return None @contextlib.contextmanager def timer(logger: logging.Logger, prefix: str) -> Iterator[None]: """Timed context manager""" start_time = time.time() yield logger.info(f"{prefix} took {time.time() - start_time:.3f} [s]") F = TypeVar("F", bound=Callable[..., Any]) def timed(prefix: str) -> Callable[[F], F]: """Decorator for timing functions""" def dec(f: F) -> F: @functools.wraps(f) def wrapper(*args: Any, **kwargs: Any) -> Any: global LOGGER logger = cast(logging.Logger, LOGGER) logger.info(prefix) with timer(logger, prefix): return f(*args, **kwargs) return cast(F, wrapper) return dec def _make_channel_args( channels: Iterable[str] = ("pytorch-nightly",), override_channels: bool = False, ) -> List[str]: args = [] for channel in channels: args.append("--channel") args.append(channel) if override_channels: args.append("--override-channels") return args @timed("Solving conda environment") def conda_solve( name: Optional[str] = None, prefix: Optional[str] = None, channels: Iterable[str] = ("pytorch-nightly",), override_channels: bool = False, ) -> Tuple[List[str], str, str, bool, List[str]]: """Performs the conda solve and splits the deps from the package.""" # compute what environment to use if prefix is not None: existing_env = True env_opts = ["--prefix", prefix] elif name is not None: existing_env = True env_opts = ["--name", name] else: # create new environment existing_env = False env_opts = ["--name", "pytorch-deps"] # run solve if existing_env: cmd = [ "conda", "install", "--yes", "--dry-run", "--json", ] cmd.extend(env_opts) else: cmd = [ "conda", "create", "--yes", "--dry-run", "--json", "--name", "__pytorch__", ] channel_args = _make_channel_args( channels=channels, override_channels=override_channels ) cmd.extend(channel_args) cmd.extend(SPECS_TO_INSTALL) p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) # parse solution solve = json.loads(p.stdout) link = solve["actions"]["LINK"] deps = [] for pkg in link: url = URL_FORMAT.format(**pkg) if pkg["name"] == "pytorch": pytorch = url platform = pkg["platform"] else: deps.append(url) return deps, pytorch, platform, existing_env, env_opts @timed("Installing dependencies") def deps_install(deps: List[str], existing_env: bool, env_opts: List[str]) -> None: """Install dependencies to deps environment""" if not existing_env: # first remove previous pytorch-deps env cmd = ["conda", "env", "remove", "--yes"] + env_opts p = subprocess.run(cmd, check=True) # install new deps inst_opt = "install" if existing_env else "create" cmd = ["conda", inst_opt, "--yes", "--no-deps"] + env_opts + deps p = subprocess.run(cmd, check=True) @timed("Installing pytorch nightly binaries") def pytorch_install(url: str) -> "tempfile.TemporaryDirectory[str]": """ "Install pytorch into a temporary directory""" pytdir = tempfile.TemporaryDirectory() cmd = ["conda", "create", "--yes", "--no-deps", "--prefix", pytdir.name, url] p = subprocess.run(cmd, check=True) return pytdir def _site_packages(dirname: str, platform: str) -> str: if platform.startswith("win"): template = os.path.join(dirname, "Lib", "site-packages") else: template = os.path.join(dirname, "lib", "python*.*", "site-packages") spdir = glob.glob(template)[0] return spdir def _ensure_commit(git_sha1: str) -> None: """Make sure that we actually have the commit locally""" cmd = ["git", "cat-file", "-e", git_sha1 + "^{commit}"] p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) if p.returncode == 0: # we have the commit locally return # we don't have the commit, must fetch cmd = ["git", "fetch", "https://github.com/pytorch/pytorch.git", git_sha1] p = subprocess.run(cmd, check=True) def _nightly_version(spdir: str) -> str: # first get the git version from the installed module version_fname = os.path.join(spdir, "torch", "version.py") with open(version_fname) as f: lines = f.read().splitlines() for line in lines: if not line.startswith("git_version"): continue git_version = literal_eval(line.partition("=")[2].strip()) break else: raise RuntimeError(f"Could not find git_version in {version_fname}") print(f"Found released git version {git_version}") # now cross reference with nightly version _ensure_commit(git_version) cmd = ["git", "show", "--no-patch", "--format=%s", git_version] p = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, universal_newlines=True, ) m = SHA1_RE.search(p.stdout) if m is None: raise RuntimeError( f"Could not find nightly release in git history:\n {p.stdout}" ) nightly_version = m.group(1) print(f"Found nightly release version {nightly_version}") # now checkout nightly version _ensure_commit(nightly_version) return nightly_version @timed("Checking out nightly PyTorch") def checkout_nightly_version(branch: str, spdir: str) -> None: """Get's the nightly version and then checks it out.""" nightly_version = _nightly_version(spdir) cmd = ["git", "checkout", "-b", branch, nightly_version] p = subprocess.run(cmd, check=True) @timed("Pulling nightly PyTorch") def pull_nightly_version(spdir: str) -> None: """Fetches the nightly version and then merges it .""" nightly_version = _nightly_version(spdir) cmd = ["git", "merge", nightly_version] p = subprocess.run(cmd, check=True) def _get_listing_linux(source_dir: str) -> List[str]: listing = glob.glob(os.path.join(source_dir, "*.so")) listing.extend(glob.glob(os.path.join(source_dir, "lib", "*.so"))) return listing def _get_listing_osx(source_dir: str) -> List[str]: # oddly, these are .so files even on Mac listing = glob.glob(os.path.join(source_dir, "*.so")) listing.extend(glob.glob(os.path.join(source_dir, "lib", "*.dylib"))) return listing def _get_listing_win(source_dir: str) -> List[str]: listing = glob.glob(os.path.join(source_dir, "*.pyd")) listing.extend(glob.glob(os.path.join(source_dir, "lib", "*.lib"))) listing.extend(glob.glob(os.path.join(source_dir, "lib", "*.dll"))) return listing def _glob_pyis(d: str) -> Set[str]: search = os.path.join(d, "**", "*.pyi") pyis = {os.path.relpath(p, d) for p in glob.iglob(search)} return pyis def _find_missing_pyi(source_dir: str, target_dir: str) -> List[str]: source_pyis = _glob_pyis(source_dir) target_pyis = _glob_pyis(target_dir) missing_pyis = [os.path.join(source_dir, p) for p in (source_pyis - target_pyis)] missing_pyis.sort() return missing_pyis def _get_listing(source_dir: str, target_dir: str, platform: str) -> List[str]: if platform.startswith("linux"): listing = _get_listing_linux(source_dir) elif platform.startswith("osx"): listing = _get_listing_osx(source_dir) elif platform.startswith("win"): listing = _get_listing_win(source_dir) else: raise RuntimeError(f"Platform {platform!r} not recognized") listing.extend(_find_missing_pyi(source_dir, target_dir)) listing.append(os.path.join(source_dir, "version.py")) listing.append(os.path.join(source_dir, "testing", "_internal", "generated")) listing.append(os.path.join(source_dir, "bin")) listing.append(os.path.join(source_dir, "include")) return listing def _remove_existing(trg: str, is_dir: bool) -> None: if os.path.exists(trg): if is_dir: shutil.rmtree(trg) else: os.remove(trg) def _move_single( src: str, source_dir: str, target_dir: str, mover: Callable[[str, str], None], verb: str, ) -> None: is_dir = os.path.isdir(src) relpath = os.path.relpath(src, source_dir) trg = os.path.join(target_dir, relpath) _remove_existing(trg, is_dir) # move over new files if is_dir: os.makedirs(trg, exist_ok=True) for root, dirs, files in os.walk(src): relroot = os.path.relpath(root, src) for name in files: relname = os.path.join(relroot, name) s = os.path.join(src, relname) t = os.path.join(trg, relname) print(f"{verb} {s} -> {t}") mover(s, t) for name in dirs: relname = os.path.join(relroot, name) os.makedirs(os.path.join(trg, relname), exist_ok=True) else: print(f"{verb} {src} -> {trg}") mover(src, trg) def _copy_files(listing: List[str], source_dir: str, target_dir: str) -> None: for src in listing: _move_single(src, source_dir, target_dir, shutil.copy2, "Copying") def _link_files(listing: List[str], source_dir: str, target_dir: str) -> None: for src in listing: _move_single(src, source_dir, target_dir, os.link, "Linking") @timed("Moving nightly files into repo") def move_nightly_files(spdir: str, platform: str) -> None: """Moves PyTorch files from temporary installed location to repo.""" # get file listing source_dir = os.path.join(spdir, "torch") target_dir = os.path.abspath("torch") listing = _get_listing(source_dir, target_dir, platform) # copy / link files if platform.startswith("win"): _copy_files(listing, source_dir, target_dir) else: try: _link_files(listing, source_dir, target_dir) except Exception: _copy_files(listing, source_dir, target_dir) def _available_envs() -> Dict[str, str]: cmd = ["conda", "env", "list"] p = subprocess.run( cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, ) lines = p.stdout.splitlines() envs = {} for line in map(str.strip, lines): if not line or line.startswith("#"): continue parts = line.split() if len(parts) == 1: # unnamed env continue envs[parts[0]] = parts[-1] return envs @timed("Writing pytorch-nightly.pth") def write_pth(env_opts: List[str], platform: str) -> None: """Writes Python path file for this dir.""" env_type, env_dir = env_opts if env_type == "--name": # have to find directory envs = _available_envs() env_dir = envs[env_dir] spdir = _site_packages(env_dir, platform) pth = os.path.join(spdir, "pytorch-nightly.pth") s = ( "# This file was autogenerated by PyTorch's tools/nightly.py\n" "# Please delete this file if you no longer need the following development\n" "# version of PyTorch to be importable\n" f"{os.getcwd()}\n" ) with open(pth, "w") as f: f.write(s) def install( *, logger: logging.Logger, subcommand: str = "checkout", branch: Optional[str] = None, name: Optional[str] = None, prefix: Optional[str] = None, channels: Iterable[str] = ("pytorch-nightly",), override_channels: bool = False, ) -> None: """Development install of PyTorch""" deps, pytorch, platform, existing_env, env_opts = conda_solve( name=name, prefix=prefix, channels=channels, override_channels=override_channels ) if deps: deps_install(deps, existing_env, env_opts) pytdir = pytorch_install(pytorch) spdir = _site_packages(pytdir.name, platform) if subcommand == "checkout": checkout_nightly_version(cast(str, branch), spdir) elif subcommand == "pull": pull_nightly_version(spdir) else: raise ValueError(f"Subcommand {subcommand} must be one of: checkout, pull.") move_nightly_files(spdir, platform) write_pth(env_opts, platform) pytdir.cleanup() logger.info( "-------\nPyTorch Development Environment set up!\nPlease activate to " f"enable this environment:\n $ conda activate {env_opts[1]}" ) def make_parser() -> ArgumentParser: p = ArgumentParser("nightly") # subcommands subcmd = p.add_subparsers(dest="subcmd", help="subcommand to execute") co = subcmd.add_parser("checkout", help="checkout a new branch") co.add_argument( "-b", "--branch", help="Branch name to checkout", dest="branch", default=None, metavar="NAME", ) pull = subcmd.add_parser( "pull", help="pulls the nightly commits into the current branch" ) # general arguments subps = [co, pull] for subp in subps: subp.add_argument( "-n", "--name", help="Name of environment", dest="name", default=None, metavar="ENVIRONMENT", ) subp.add_argument( "-p", "--prefix", help="Full path to environment location (i.e. prefix)", dest="prefix", default=None, metavar="PATH", ) subp.add_argument( "-v", "--verbose", help="Provide debugging info", dest="verbose", default=False, action="store_true", ) subp.add_argument( "--override-channels", help="Do not search default or .condarc channels.", dest="override_channels", default=False, action="store_true", ) subp.add_argument( "-c", "--channel", help="Additional channel to search for packages. 'pytorch-nightly' will always be prepended to this list.", dest="channels", action="append", metavar="CHANNEL", ) return p def main(args: Optional[Sequence[str]] = None) -> None: """Main entry point""" global LOGGER p = make_parser() ns = p.parse_args(args) ns.branch = getattr(ns, "branch", None) status = check_in_repo() status = status or check_branch(ns.subcmd, ns.branch) if status: sys.exit(status) channels = ["pytorch-nightly"] if ns.channels: channels.extend(ns.channels) with logging_manager(debug=ns.verbose) as logger: LOGGER = logger install( subcommand=ns.subcmd, branch=ns.branch, name=ns.name, prefix=ns.prefix, logger=logger, channels=channels, override_channels=ns.override_channels, ) if __name__ == "__main__": main()
pytorch-master
tools/nightly.py
import textwrap from typing import Any import gdb # type: ignore[import] class DisableBreakpoints: """ Context-manager to temporarily disable all gdb breakpoints, useful if there is a risk to hit one during the evaluation of one of our custom commands """ def __enter__(self) -> None: self.disabled_breakpoints = [] for b in gdb.breakpoints(): if b.enabled: b.enabled = False self.disabled_breakpoints.append(b) def __exit__(self, etype: Any, evalue: Any, tb: Any) -> None: for b in self.disabled_breakpoints: b.enabled = True class TensorRepr(gdb.Command): # type: ignore[misc, no-any-unimported] """ Print a human readable representation of the given at::Tensor. Usage: torch-tensor-repr EXP at::Tensor instances do not have a C++ implementation of a repr method: in pytoch, this is done by pure-Python code. As such, torch-tensor-repr internally creates a Python wrapper for the given tensor and call repr() on it. """ __doc__ = textwrap.dedent(__doc__).strip() def __init__(self) -> None: gdb.Command.__init__( self, "torch-tensor-repr", gdb.COMMAND_USER, gdb.COMPLETE_EXPRESSION ) def invoke(self, args: str, from_tty: bool) -> None: args = gdb.string_to_argv(args) if len(args) != 1: print("Usage: torch-tensor-repr EXP") return name = args[0] with DisableBreakpoints(): res = gdb.parse_and_eval("torch::gdb::tensor_repr(%s)" % name) print("Python-level repr of %s:" % name) print(res.string()) # torch::gdb::tensor_repr returns a malloc()ed buffer, let's free it gdb.parse_and_eval("(void)free(%s)" % int(res)) TensorRepr()
pytorch-master
tools/gdb/pytorch-gdb.py
import re import sys QUOTE_INCLUDE_RE = re.compile(r'^#include "(.*)"') ANGLE_INCLUDE_RE = re.compile(r"^#include <(.*)>") # By default iwyu will pick the C include, but we prefer the C++ headers STD_C_HEADER_MAP = { "<assert.h>": "<cassert>", "<complex.h>": "<ccomplex>", "<ctype.h>": "<cctype>", "<errno.h>": "<cerrno>", "<fenv.h>": "<cfenv>", "<float.h>": "<cfloat>", "<inttypes.h>": "<cinttypes>", "<iso646.h>": "<ciso646>", "<limits.h>": "<climits>", "<locale.h>": "<clocale>", "<math.h>": "<cmath>", "<setjmp.h>": "<csetjmp>", "<signal.h>": "<csignal>", "<stdalign.h>": "<cstdalign>", "<stdarg.h>": "<cstdarg>", "<stdbool.h>": "<cstdbool>", "<stddef.h>": "<cstddef>", "<stdint.h>": "<cstdint>", "<stdio.h>": "<cstdio>", "<stdlib.h>": "<cstdlib>", "<string.h>": "<cstring>", "<tgmath.h>": "<ctgmath>", "<time.h>": "<ctime>", "<uchar.h>": "<cuchar>", "<wchar.h>": "<cwchar>", "<wctype.h>": "<cwctype>", } def main() -> None: for line in sys.stdin: # Convert all quoted includes to angle brackets match = QUOTE_INCLUDE_RE.match(line) if match is not None: print(f"#include <{match.group(1)}>{line[match.end(0):]}", end="") continue match = ANGLE_INCLUDE_RE.match(line) if match is not None: path = f"<{match.group(1)}>" new_path = STD_C_HEADER_MAP.get(path, path) tail = line[match.end(0) :] if len(tail) > 1: tail = " " + tail print(f"#include {new_path}{tail}", end="") continue print(line, end="") if __name__ == "__main__": main()
pytorch-master
tools/iwyu/fixup.py
import itertools import re import shlex import unittest from typing import List, Optional from tools.stats import test_history from typing_extensions import TypedDict class Example(TypedDict): cmd: str args: List[str] lines: List[str] def parse_block(block: List[str]) -> Optional[Example]: if block: match = re.match(r"^\$ ([^ ]+) (.*)$", block[0]) if match: cmd, first = match.groups() args = [] for i, line in enumerate([first] + block[1:]): if line.endswith("\\"): args.append(line[:-1]) else: args.append(line) break return { "cmd": cmd, "args": shlex.split("".join(args)), "lines": block[i + 1 :], } return None def parse_description(description: str) -> List[Example]: examples: List[Example] = [] for block in description.split("\n\n"): matches = [re.match(r"^ (.*)$", line) for line in block.splitlines()] if all(matches): lines = [] for match in matches: assert match (line,) = match.groups() lines.append(line) example = parse_block(lines) if example: examples.append(example) return examples @unittest.skip("Skipping as this test is fragile, issue #73083") class TestTestHistory(unittest.TestCase): maxDiff = None def test_help_examples(self) -> None: examples = parse_description(test_history.description()) self.assertEqual(len(examples), 3) for i, example in enumerate(examples): with self.subTest(i=i): self.assertTrue(test_history.__file__.endswith(example["cmd"])) expected = example["lines"] actual = list( itertools.islice( test_history.run(example["args"]), len(expected), ) ) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_test_history.py
import random import unittest from typing import Dict, List, Tuple from tools.testing.test_selections import calculate_shards class TestCalculateShards(unittest.TestCase): tests: List[str] = [ "super_long_test", "long_test1", "long_test2", "normal_test1", "normal_test2", "normal_test3", "short_test1", "short_test2", "short_test3", "short_test4", "short_test5", ] test_times: Dict[str, float] = { "super_long_test": 55, "long_test1": 22, "long_test2": 18, "normal_test1": 9, "normal_test2": 7, "normal_test3": 5, "short_test1": 1, "short_test2": 0.6, "short_test3": 0.4, "short_test4": 0.3, "short_test5": 0.01, } def assert_shards_equal( self, expected_shards: List[Tuple[float, List[str]]], actual_shards: List[Tuple[float, List[str]]], ) -> None: for expected, actual in zip(expected_shards, actual_shards): self.assertAlmostEqual(expected[0], actual[0]) self.assertListEqual(expected[1], actual[1]) def test_calculate_2_shards_with_complete_test_times(self) -> None: expected_shards = [ (60, ["super_long_test", "normal_test3"]), ( 58.31, [ "long_test1", "long_test2", "normal_test1", "normal_test2", "short_test1", "short_test2", "short_test3", "short_test4", "short_test5", ], ), ] self.assert_shards_equal( expected_shards, calculate_shards(2, self.tests, self.test_times) ) def test_calculate_1_shard_with_complete_test_times(self) -> None: expected_shards = [ ( 118.31, [ "super_long_test", "long_test1", "long_test2", "normal_test1", "normal_test2", "normal_test3", "short_test1", "short_test2", "short_test3", "short_test4", "short_test5", ], ), ] self.assert_shards_equal( expected_shards, calculate_shards(1, self.tests, self.test_times) ) def test_calculate_5_shards_with_complete_test_times(self) -> None: expected_shards = [ (55.0, ["super_long_test"]), ( 22.0, [ "long_test1", ], ), ( 18.0, [ "long_test2", ], ), ( 11.31, [ "normal_test1", "short_test1", "short_test2", "short_test3", "short_test4", "short_test5", ], ), (12.0, ["normal_test2", "normal_test3"]), ] self.assert_shards_equal( expected_shards, calculate_shards(5, self.tests, self.test_times) ) def test_calculate_2_shards_with_incomplete_test_times(self) -> None: incomplete_test_times = { k: v for k, v in self.test_times.items() if "test1" in k } expected_shards = [ ( 22.0, [ "long_test1", "long_test2", "normal_test3", "short_test3", "short_test5", ], ), ( 10.0, [ "normal_test1", "short_test1", "super_long_test", "normal_test2", "short_test2", "short_test4", ], ), ] self.assert_shards_equal( expected_shards, calculate_shards(2, self.tests, incomplete_test_times) ) def test_calculate_5_shards_with_incomplete_test_times(self) -> None: incomplete_test_times = { k: v for k, v in self.test_times.items() if "test1" in k } expected_shards = [ (22.0, ["long_test1", "normal_test2", "short_test5"]), (9.0, ["normal_test1", "normal_test3"]), (1.0, ["short_test1", "short_test2"]), (0.0, ["super_long_test", "short_test3"]), (0.0, ["long_test2", "short_test4"]), ] self.assert_shards_equal( expected_shards, calculate_shards(5, self.tests, incomplete_test_times) ) def test_calculate_2_shards_against_optimal_shards(self) -> None: for _ in range(100): random.seed(120) random_times = {k: random.random() * 10 for k in self.tests} # all test times except first two rest_of_tests = [ i for k, i in random_times.items() if k != "super_long_test" and k != "long_test1" ] sum_of_rest = sum(rest_of_tests) random_times["super_long_test"] = max(sum_of_rest / 2, max(rest_of_tests)) random_times["long_test1"] = sum_of_rest - random_times["super_long_test"] # An optimal sharding would look like the below, but we don't need to compute this for the test: # optimal_shards = [ # (sum_of_rest, ['super_long_test', 'long_test1']), # (sum_of_rest, [i for i in self.tests if i != 'super_long_test' and i != 'long_test1']), # ] calculated_shards = calculate_shards(2, self.tests, random_times) max_shard_time = max(calculated_shards[0][0], calculated_shards[1][0]) if sum_of_rest != 0: # The calculated shard should not have a ratio worse than 7/6 for num_shards = 2 self.assertGreaterEqual(7.0 / 6.0, max_shard_time / sum_of_rest) sorted_tests = sorted(self.tests) sorted_shard_tests = sorted( calculated_shards[0][1] + calculated_shards[1][1] ) # All the tests should be represented by some shard self.assertEqual(sorted_tests, sorted_shard_tests) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_test_selections.py
import unittest from torchgen.utils import NamespaceHelper class TestNamespaceHelper(unittest.TestCase): def test_create_from_namespaced_tuple(self) -> None: helper = NamespaceHelper.from_namespaced_entity("aten::add") self.assertEqual(helper.entity_name, "add") self.assertEqual(helper.get_cpp_namespace(), "aten") def test_default_namespace(self) -> None: helper = NamespaceHelper.from_namespaced_entity("add") self.assertEqual(helper.entity_name, "add") self.assertEqual(helper.get_cpp_namespace(), "") self.assertEqual(helper.get_cpp_namespace("default"), "default") def test_namespace_levels_more_than_max(self) -> None: with self.assertRaises(AssertionError): NamespaceHelper( namespace_str="custom_1::custom_2", entity_name="", max_level=1 )
pytorch-master
tools/test/test_utils.py
# -*- coding: utf-8 -*- import unittest from typing import Dict, List from tools.stats import print_test_stats from tools.stats.s3_stat_parser import ( Commit, Report, ReportMetaMeta, Status, Version1Case, Version1Report, Version2Case, Version2Report, ) def fakehash(char: str) -> str: return char * 40 def dummy_meta_meta() -> ReportMetaMeta: return { "build_pr": "", "build_tag": "", "build_sha1": "", "build_base_commit": "", "build_branch": "", "build_job": "", "build_workflow_id": "", "build_start_time_epoch": "", } def makecase( name: str, seconds: float, *, errored: bool = False, failed: bool = False, skipped: bool = False, ) -> Version1Case: return { "name": name, "seconds": seconds, "errored": errored, "failed": failed, "skipped": skipped, } def make_report_v1(tests: Dict[str, List[Version1Case]]) -> Version1Report: suites = { suite_name: { "total_seconds": sum(case["seconds"] for case in cases), "cases": cases, } for suite_name, cases in tests.items() } return { **dummy_meta_meta(), # type: ignore[misc] "total_seconds": sum(s["total_seconds"] for s in suites.values()), "suites": suites, } def make_case_v2(seconds: float, status: Status = None) -> Version2Case: return { "seconds": seconds, "status": status, } def make_report_v2( tests: Dict[str, Dict[str, Dict[str, Version2Case]]] ) -> Version2Report: files = {} for file_name, file_suites in tests.items(): suites = { suite_name: { "total_seconds": sum(case["seconds"] for case in cases.values()), "cases": cases, } for suite_name, cases in file_suites.items() } files[file_name] = { "suites": suites, "total_seconds": sum(suite["total_seconds"] for suite in suites.values()), # type: ignore[type-var] } return { **dummy_meta_meta(), # type: ignore[misc] "format_version": 2, "total_seconds": sum(s["total_seconds"] for s in files.values()), "files": files, } maxDiff = None class TestPrintTestStats(unittest.TestCase): version1_report: Version1Report = make_report_v1( { # input ordering of the suites is ignored "Grault": [ # not printed: status same and time similar makecase("test_grault0", 4.78, failed=True), # status same, but time increased a lot makecase("test_grault2", 1.473, errored=True), ], # individual tests times changed, not overall suite "Qux": [ # input ordering of the test cases is ignored makecase("test_qux1", 0.001, skipped=True), makecase("test_qux6", 0.002, skipped=True), # time in bounds, but status changed makecase("test_qux4", 7.158, failed=True), # not printed because it's the same as before makecase("test_qux7", 0.003, skipped=True), makecase("test_qux5", 11.968), makecase("test_qux3", 23.496), ], # new test suite "Bar": [ makecase("test_bar2", 3.742, failed=True), makecase("test_bar1", 50.447), ], # overall suite time changed but no individual tests "Norf": [ makecase("test_norf1", 3), makecase("test_norf2", 3), makecase("test_norf3", 3), makecase("test_norf4", 3), ], # suite doesn't show up if it doesn't change enough "Foo": [ makecase("test_foo1", 42), makecase("test_foo2", 56), ], } ) version2_report: Version2Report = make_report_v2( { "test_a": { "Grault": { "test_grault0": make_case_v2(4.78, "failed"), "test_grault2": make_case_v2(1.473, "errored"), }, "Qux": { "test_qux1": make_case_v2(0.001, "skipped"), "test_qux6": make_case_v2(0.002, "skipped"), "test_qux4": make_case_v2(7.158, "failed"), "test_qux7": make_case_v2(0.003, "skipped"), "test_qux8": make_case_v2(11.968), "test_qux3": make_case_v2(23.496), }, }, "test_b": { "Bar": { "test_bar2": make_case_v2(3.742, "failed"), "test_bar1": make_case_v2(50.447), }, # overall suite time changed but no individual tests "Norf": { "test_norf1": make_case_v2(3), "test_norf2": make_case_v2(3), "test_norf3": make_case_v2(3), "test_norf4": make_case_v2(3), }, }, "test_c": { "Foo": { "test_foo1": make_case_v2(42), "test_foo2": make_case_v2(56), }, }, } ) def test_simplify(self) -> None: self.assertEqual( { "": { "Bar": { "test_bar1": {"seconds": 50.447, "status": None}, "test_bar2": {"seconds": 3.742, "status": "failed"}, }, "Foo": { "test_foo1": {"seconds": 42, "status": None}, "test_foo2": {"seconds": 56, "status": None}, }, "Grault": { "test_grault0": {"seconds": 4.78, "status": "failed"}, "test_grault2": {"seconds": 1.473, "status": "errored"}, }, "Norf": { "test_norf1": {"seconds": 3, "status": None}, "test_norf3": {"seconds": 3, "status": None}, "test_norf2": {"seconds": 3, "status": None}, "test_norf4": {"seconds": 3, "status": None}, }, "Qux": { "test_qux1": {"seconds": 0.001, "status": "skipped"}, "test_qux3": {"seconds": 23.496, "status": None}, "test_qux4": {"seconds": 7.158, "status": "failed"}, "test_qux5": {"seconds": 11.968, "status": None}, "test_qux6": {"seconds": 0.002, "status": "skipped"}, "test_qux7": {"seconds": 0.003, "status": "skipped"}, }, }, }, print_test_stats.simplify(self.version1_report), ) self.assertEqual( { "test_a": { "Grault": { "test_grault0": {"seconds": 4.78, "status": "failed"}, "test_grault2": {"seconds": 1.473, "status": "errored"}, }, "Qux": { "test_qux1": {"seconds": 0.001, "status": "skipped"}, "test_qux3": {"seconds": 23.496, "status": None}, "test_qux4": {"seconds": 7.158, "status": "failed"}, "test_qux6": {"seconds": 0.002, "status": "skipped"}, "test_qux7": {"seconds": 0.003, "status": "skipped"}, "test_qux8": {"seconds": 11.968, "status": None}, }, }, "test_b": { "Bar": { "test_bar1": {"seconds": 50.447, "status": None}, "test_bar2": {"seconds": 3.742, "status": "failed"}, }, "Norf": { "test_norf1": {"seconds": 3, "status": None}, "test_norf2": {"seconds": 3, "status": None}, "test_norf3": {"seconds": 3, "status": None}, "test_norf4": {"seconds": 3, "status": None}, }, }, "test_c": { "Foo": { "test_foo1": {"seconds": 42, "status": None}, "test_foo2": {"seconds": 56, "status": None}, }, }, }, print_test_stats.simplify(self.version2_report), ) def test_analysis(self) -> None: head_report = self.version1_report base_reports: Dict[Commit, List[Report]] = { # bbbb has no reports, so base is cccc instead fakehash("b"): [], fakehash("c"): [ make_report_v1( { "Baz": [ makecase("test_baz2", 13.605), # no recent suites have & skip this test makecase("test_baz1", 0.004, skipped=True), ], "Foo": [ makecase("test_foo1", 43), # test added since dddd makecase("test_foo2", 57), ], "Grault": [ makecase("test_grault0", 4.88, failed=True), makecase("test_grault1", 11.967, failed=True), makecase("test_grault2", 0.395, errored=True), makecase("test_grault3", 30.460), ], "Norf": [ makecase("test_norf1", 2), makecase("test_norf2", 2), makecase("test_norf3", 2), makecase("test_norf4", 2), ], "Qux": [ makecase("test_qux3", 4.978, errored=True), makecase("test_qux7", 0.002, skipped=True), makecase("test_qux2", 5.618), makecase("test_qux4", 7.766, errored=True), makecase("test_qux6", 23.589, failed=True), ], } ), ], fakehash("d"): [ make_report_v1( { "Foo": [ makecase("test_foo1", 40), # removed in cccc makecase("test_foo3", 17), ], "Baz": [ # not skipped, so not included in stdev makecase("test_baz1", 3.14), ], "Qux": [ makecase("test_qux7", 0.004, skipped=True), makecase("test_qux2", 6.02), makecase("test_qux4", 20.932), ], "Norf": [ makecase("test_norf1", 3), makecase("test_norf2", 3), makecase("test_norf3", 3), makecase("test_norf4", 3), ], "Grault": [ makecase("test_grault0", 5, failed=True), makecase("test_grault1", 14.325, failed=True), makecase("test_grault2", 0.31, errored=True), ], } ), ], fakehash("e"): [], fakehash("f"): [ make_report_v1( { "Foo": [ makecase("test_foo3", 24), makecase("test_foo1", 43), ], "Baz": [ makecase("test_baz2", 16.857), ], "Qux": [ makecase("test_qux2", 6.422), makecase("test_qux4", 6.382, errored=True), ], "Norf": [ makecase("test_norf1", 0.9), makecase("test_norf3", 0.9), makecase("test_norf2", 0.9), makecase("test_norf4", 0.9), ], "Grault": [ makecase("test_grault0", 4.7, failed=True), makecase("test_grault1", 13.146, failed=True), makecase("test_grault2", 0.48, errored=True), ], } ), ], } simpler_head = print_test_stats.simplify(head_report) simpler_base = {} for commit, reports in base_reports.items(): simpler_base[commit] = [print_test_stats.simplify(r) for r in reports] analysis = print_test_stats.analyze( head_report=simpler_head, base_reports=simpler_base, ) self.assertEqual( """\ - class Baz: - # was 15.23s ± 2.30s - - def test_baz1: ... - # was 0.004s (skipped) - - def test_baz2: ... - # was 15.231s ± 2.300s class Grault: # was 48.86s ± 1.19s # now 6.25s - def test_grault1: ... - # was 13.146s ± 1.179s (failed) - def test_grault3: ... - # was 30.460s class Qux: # was 41.66s ± 1.06s # now 42.63s - def test_qux2: ... - # was 6.020s ± 0.402s ! def test_qux3: ... ! # was 4.978s (errored) ! # now 23.496s ! def test_qux4: ... ! # was 7.074s ± 0.979s (errored) ! # now 7.158s (failed) ! def test_qux6: ... ! # was 23.589s (failed) ! # now 0.002s (skipped) + def test_qux1: ... + # now 0.001s (skipped) + def test_qux5: ... + # now 11.968s + class Bar: + # now 54.19s + + def test_bar1: ... + # now 50.447s + + def test_bar2: ... + # now 3.742s (failed) """, print_test_stats.anomalies(analysis), ) def test_graph(self) -> None: # HEAD is on master self.assertEqual( """\ Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | * aaaaaaaaaa (HEAD) total time 502.99s * bbbbbbbbbb (base) 1 report, total time 47.84s * cccccccccc 1 report, total time 332.50s * dddddddddd 0 reports | : """, print_test_stats.graph( head_sha=fakehash("a"), head_seconds=502.99, base_seconds={ fakehash("b"): [47.84], fakehash("c"): [332.50], fakehash("d"): [], }, on_master=True, ), ) self.assertEqual( """\ Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | | * aaaaaaaaaa (HEAD) total time 9988.77s |/ * bbbbbbbbbb (base) 121 reports, total time 7654.32s ± 55.55s * cccccccccc 20 reports, total time 5555.55s ± 253.19s * dddddddddd 1 report, total time 1234.56s | : """, print_test_stats.graph( head_sha=fakehash("a"), head_seconds=9988.77, base_seconds={ fakehash("b"): [7598.77] * 60 + [7654.32] + [7709.87] * 60, fakehash("c"): [5308.77] * 10 + [5802.33] * 10, fakehash("d"): [1234.56], }, on_master=False, ), ) self.assertEqual( """\ Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | | * aaaaaaaaaa (HEAD) total time 25.52s | | | : (5 commits) |/ * bbbbbbbbbb 0 reports * cccccccccc 0 reports * dddddddddd (base) 15 reports, total time 58.92s ± 25.82s | : """, print_test_stats.graph( head_sha=fakehash("a"), head_seconds=25.52, base_seconds={ fakehash("b"): [], fakehash("c"): [], fakehash("d"): [52.25] * 14 + [152.26], }, on_master=False, ancestry_path=5, ), ) self.assertEqual( """\ Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | | * aaaaaaaaaa (HEAD) total time 0.08s |/| | : (1 commit) | * bbbbbbbbbb 0 reports * cccccccccc (base) 1 report, total time 0.09s * dddddddddd 3 reports, total time 0.10s ± 0.05s | : """, print_test_stats.graph( head_sha=fakehash("a"), head_seconds=0.08, base_seconds={ fakehash("b"): [], fakehash("c"): [0.09], fakehash("d"): [0.05, 0.10, 0.15], }, on_master=False, other_ancestors=1, ), ) self.assertEqual( """\ Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | | * aaaaaaaaaa (HEAD) total time 5.98s | | | : (1 commit) |/| | : (7 commits) | * bbbbbbbbbb (base) 2 reports, total time 6.02s ± 1.71s * cccccccccc 0 reports * dddddddddd 10 reports, total time 5.84s ± 0.92s | : """, print_test_stats.graph( head_sha=fakehash("a"), head_seconds=5.98, base_seconds={ fakehash("b"): [4.81, 7.23], fakehash("c"): [], fakehash("d"): [4.97] * 5 + [6.71] * 5, }, on_master=False, ancestry_path=1, other_ancestors=7, ), ) def test_regression_info(self) -> None: self.assertEqual( """\ ----- Historic stats comparison result ------ job: foo_job commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | | * aaaaaaaaaa (HEAD) total time 3.02s |/ * bbbbbbbbbb (base) 1 report, total time 41.00s * cccccccccc 1 report, total time 43.00s | : Removed (across 1 suite) 1 test, totaling - 1.00s Modified (across 1 suite) 1 test, totaling - 41.48s ± 2.12s Added (across 1 suite) 1 test, totaling + 3.00s """, print_test_stats.regression_info( head_sha=fakehash("a"), head_report=make_report_v1( { "Foo": [ makecase("test_foo", 0.02, skipped=True), makecase("test_baz", 3), ] } ), base_reports={ fakehash("b"): [ make_report_v1( { "Foo": [ makecase("test_foo", 40), makecase("test_bar", 1), ], } ), ], fakehash("c"): [ make_report_v1( { "Foo": [ makecase("test_foo", 43), ], } ), ], }, job_name="foo_job", on_master=False, ancestry_path=0, other_ancestors=0, ), ) def test_regression_info_new_job(self) -> None: self.assertEqual( """\ ----- Historic stats comparison result ------ job: foo_job commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Commit graph (base is most recent master ancestor with at least one S3 report): : (master) | | * aaaaaaaaaa (HEAD) total time 3.02s | | | : (3 commits) |/| | : (2 commits) | * bbbbbbbbbb 0 reports * cccccccccc 0 reports | : Removed (across 0 suites) 0 tests, totaling 0.00s Modified (across 0 suites) 0 tests, totaling 0.00s Added (across 1 suite) 2 tests, totaling + 3.02s """, print_test_stats.regression_info( head_sha=fakehash("a"), head_report=make_report_v1( { "Foo": [ makecase("test_foo", 0.02, skipped=True), makecase("test_baz", 3), ] } ), base_reports={ fakehash("b"): [], fakehash("c"): [], }, job_name="foo_job", on_master=False, ancestry_path=3, other_ancestors=2, ), ) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_stats.py
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import unittest from gen_operators_yaml import make_filter_from_options, verify_all_specified_present class GenOperatorsYAMLTest(unittest.TestCase): def setUp(self): pass def test_filter_creation(self): filter_func = make_filter_from_options( model_name="abc", model_versions=["100", "101"], model_assets=None, model_backends=None, ) config = [ { "model": { "name": "abc", "version": 100, "asset": "asset-1", "backend": "CPU", }, "root_operators": [], "traced_operators": [], }, { "model": { "name": "abc", "version": 102, "asset": "asset-1", "backend": "CPU", }, "root_operators": [], }, { "model": { "name": "abcd", "version": 100, "asset": "asset-1", "backend": "CPU", }, "root_operators": [], "traced_operators": [], }, { "model": { "name": "abc", "version": 101, "asset": "asset-2", "backend": "CPU", }, "root_operators": [], }, ] filtered_configs = list(filter(filter_func, config)) assert ( len(filtered_configs) == 2 ), "Expected 2 elements in filtered_configs, but got {}".format( len(filtered_configs) ) def test_verification_success(self): filter_func = make_filter_from_options( model_name="abc", model_versions=["100", "101"], model_assets=["asset-1", "asset-2"], model_backends=None, ) config = [ { "model": { "name": "abc", "version": 100, "asset": "asset-1", "backend": "CPU", }, "root_operators": [], "traced_operators": [], }, { "model": { "name": "abc", "version": 101, "asset": "asset-2", "backend": "CPU", }, "root_operators": [], }, ] filtered_configs = list(filter(filter_func, config)) try: verify_all_specified_present( model_assets=["asset-1", "asset-2"], model_versions=["100", "101"], selected_models_yaml=filtered_configs, rule_name="test", model_name="abc", new_style_rule=True, ) except Exception: self.fail( "expected verify_all_specified_present to succeed instead it raised an exception" ) def test_verification_fail(self): config = [ { "model": { "name": "abc", "version": 100, "asset": "asset-1", "backend": "CPU", }, "root_operators": [], "traced_operators": [], }, { "model": { "name": "abc", "version": 101, "asset": "asset-2", "backend": "CPU", }, "root_operators": [], }, ] good_assets = ["asset-1", "asset-2"] good_versions = ["100", "101"] good_name = "abc" # Test bad asset filter_func_bad_asset = make_filter_from_options( model_name=good_name, model_versions=good_versions, model_assets=["asset-1", "asset-2", "asset-3"], model_backends=None, ) filtered_configs_asset = list(filter(filter_func_bad_asset, config)) with self.assertRaises(RuntimeError): verify_all_specified_present( model_assets=["asset-1", "asset-2", "asset-3"], model_versions=good_versions, selected_models_yaml=filtered_configs_asset, rule_name="test", model_name=good_name, new_style_rule=True, ) # Test bad version filter_func_bad_version = make_filter_from_options( model_name=good_name, model_versions=["100", "101", "102"], model_assets=good_assets, model_backends=None, ) filtered_configs_version = list(filter(filter_func_bad_version, config)) with self.assertRaises(RuntimeError): verify_all_specified_present( model_assets=good_assets, model_versions=["100", "101", "102"], selected_models_yaml=filtered_configs_version, rule_name="test", model_name=good_name, new_style_rule=True, ) # Test bad name filter_func_bad_name = make_filter_from_options( model_name="abcd", model_versions=good_versions, model_assets=good_assets, model_backends=None, ) filtered_configs_name = list(filter(filter_func_bad_name, config)) with self.assertRaises(RuntimeError): verify_all_specified_present( model_assets=good_assets, model_versions=good_versions, selected_models_yaml=filtered_configs_name, rule_name="test", model_name="abcd", new_style_rule=True, )
pytorch-master
tools/test/gen_operators_yaml_test.py
# Owner(s): ["module: codegen"] import os import tempfile import unittest import expecttest from torchgen.gen import _GLOBAL_PARSE_NATIVE_YAML_CACHE # noqa: F401 from torchgen.gen_backend_stubs import run path = os.path.dirname(os.path.realpath(__file__)) gen_backend_stubs_path = os.path.join(path, "../torchgen/gen_backend_stubs.py") # gen_backend_stubs.py is an integration point that is called directly by external backends. # The tests here are to confirm that badly formed inputs result in reasonable error messages. class TestGenBackendStubs(expecttest.TestCase): def setUp(self) -> None: global _GLOBAL_PARSE_NATIVE_YAML_CACHE _GLOBAL_PARSE_NATIVE_YAML_CACHE.clear() def assert_success_from_gen_backend_stubs(self, yaml_str: str) -> None: with tempfile.NamedTemporaryFile(mode="w") as fp: fp.write(yaml_str) fp.flush() run(fp.name, "", True) def get_errors_from_gen_backend_stubs(self, yaml_str: str) -> str: with tempfile.NamedTemporaryFile(mode="w") as fp: fp.write(yaml_str) fp.flush() try: run(fp.name, "", True) except AssertionError as e: # Scrub out the temp file name from any error messages to simplify assertions. return str(e).replace(fp.name, "") self.fail( "Expected gen_backend_stubs to raise an AssertionError, but it did not." ) def test_valid_single_op(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - abs""" self.assert_success_from_gen_backend_stubs(yaml_str) def test_valid_multiple_ops(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - add.Tensor - abs""" self.assert_success_from_gen_backend_stubs(yaml_str) def test_valid_zero_ops(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported:""" self.assert_success_from_gen_backend_stubs(yaml_str) def test_valid_zero_ops_doesnt_require_backend_dispatch_key(self) -> None: yaml_str = """\ backend: BAD_XLA cpp_namespace: torch_xla supported:""" # External codegen on a yaml file with no operators is effectively a no-op, # so there's no reason to parse the backend self.assert_success_from_gen_backend_stubs(yaml_str) def test_valid_with_autograd_ops(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - abs autograd: - add.Tensor""" # External codegen on a yaml file with no operators is effectively a no-op, # so there's no reason to parse the backend self.assert_success_from_gen_backend_stubs(yaml_str) def test_missing_backend(self) -> None: yaml_str = """\ cpp_namespace: torch_xla supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, '''You must provide a value for "backend"''' ) def test_empty_backend(self) -> None: yaml_str = """\ backend: cpp_namespace: torch_xla supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, '''You must provide a value for "backend"''' ) def test_backend_invalid_dispatch_key(self) -> None: yaml_str = """\ backend: NOT_XLA cpp_namespace: torch_xla supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """\ unknown dispatch key NOT_XLA The provided value for "backend" must be a valid DispatchKey, but got NOT_XLA.""", ) # noqa: B950 def test_missing_cpp_namespace(self) -> None: yaml_str = """\ backend: XLA supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, '''You must provide a value for "cpp_namespace"''' ) def test_whitespace_cpp_namespace(self) -> None: yaml_str = """\ backend: XLA cpp_namespace:\t supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, '''You must provide a value for "cpp_namespace"''' ) # supported is a single item (it should be a list) def test_nonlist_supported(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """expected "supported" to be a list, but got: abs (of type <class 'str'>)""", ) # supported contains an op that isn't in native_functions.yaml def test_supported_invalid_op(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - abs_BAD""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """Found an invalid operator name: abs_BAD""" ) # The backend is valid, but doesn't have a valid autograd key. They can't override autograd kernels in that case. # Only using Vulkan here because it has a valid backend key but not an autograd key- if this changes we can update the test. def test_backend_has_no_autograd_key_but_provides_entries(self) -> None: yaml_str = """\ backend: Vulkan cpp_namespace: torch_vulkan supported: - add autograd: - sub""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """Found an invalid operator name: add""" ) # noqa: B950 # in an operator group, currently all operators must either be registered to the backend or autograd kernel. # Here, functional and out mismatch def test_backend_autograd_kernel_mismatch_out_functional(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - add.Tensor autograd: - add.out""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """Currently, all variants of an op must either be registered to a backend key, or to a backend's autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! add is listed under "supported", but add_out is listed under "autograd".""", # noqa: B950 ) # in an operator group, currently all operators must either be registered to the backend or autograd kernel. # Here, functional and inplace mismatch def test_backend_autograd_kernel_mismatch_functional_inplace(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - add.Tensor autograd: - add_.Tensor""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """Currently, all variants of an op must either be registered to a backend key, or to a backend's autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! add is listed under "supported", but add_ is listed under "autograd".""", # noqa: B950 ) # Currently, the same operator can't be listed under both 'supported' and 'autograd', which would # involve registering the same kernel to both the XLA and AutogradXLA keys. # If we need that functionality in the future, we'll need to augment the codegen. def test_op_appears_in_supported_and_autograd_lists(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - add.Tensor autograd: - add.Tensor""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """Currently, all variants of an op must either be registered to a backend key, or to a backend's autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! add is listed under "supported", but add is listed under "autograd".""", # noqa: B950 ) # unrecognized extra yaml key def test_unrecognized_key(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla supported: - abs invalid_key: invalid_val""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """ contains unexpected keys: invalid_key. Only the following keys are supported: backend, class_name, cpp_namespace, extra_headers, supported, autograd, full_codegen, non_native, ir_gen""", # noqa: B950 ) # if use_out_as_primary is provided, it must be a bool def test_use_out_as_primary_non_bool(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla use_out_as_primary: frue supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """You must provide either True or False for use_out_as_primary. Provided: frue""", ) # noqa: B950 # if device_guard is provided, it must be a bool def test_device_guard_non_bool(self) -> None: yaml_str = """\ backend: XLA cpp_namespace: torch_xla device_guard: frue supported: - abs""" output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline( output_error, """You must provide either True or False for device_guard. Provided: frue""", ) # noqa: B950 if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_gen_backend_stubs.py
from __future__ import absolute_import, division, print_function, unicode_literals import unittest from torchgen.selective_build.operator import * from torchgen.model import Location, NativeFunction from torchgen.selective_build.selector import ( combine_selective_builders, SelectiveBuilder, ) class TestSelectiveBuild(unittest.TestCase): def test_selective_build_operator(self): op = SelectiveBuildOperator( "aten::add.int", is_root_operator=True, is_used_for_training=False, include_all_overloads=False, _debug_info=None, ) self.assertTrue(op.is_root_operator) self.assertFalse(op.is_used_for_training) self.assertFalse(op.include_all_overloads) def test_selector_factory(self): yaml_config_v1 = """ debug_info: - model1@v100 - model2@v51 operators: aten::add: is_used_for_training: No is_root_operator: Yes include_all_overloads: Yes aten::add.int: is_used_for_training: Yes is_root_operator: No include_all_overloads: No aten::mul.int: is_used_for_training: Yes is_root_operator: No include_all_overloads: No """ yaml_config_v2 = """ debug_info: - model1@v100 - model2@v51 operators: aten::sub: is_used_for_training: No is_root_operator: Yes include_all_overloads: No debug_info: - model1@v100 aten::sub.int: is_used_for_training: Yes is_root_operator: No include_all_overloads: No """ yaml_config_all = "include_all_operators: Yes" yaml_config_invalid = "invalid:" selector1 = SelectiveBuilder.from_yaml_str(yaml_config_v1) self.assertTrue(selector1.is_operator_selected("aten::add")) self.assertTrue(selector1.is_operator_selected("aten::add.int")) # Overload name is not used for checking in v1. self.assertTrue(selector1.is_operator_selected("aten::add.float")) def gen(): return SelectiveBuilder.from_yaml_str(yaml_config_invalid) self.assertRaises(Exception, gen) selector_all = SelectiveBuilder.from_yaml_str(yaml_config_all) self.assertTrue(selector_all.is_operator_selected("aten::add")) self.assertTrue(selector_all.is_operator_selected("aten::sub")) self.assertTrue(selector_all.is_operator_selected("aten::sub.int")) self.assertTrue(selector_all.is_kernel_dtype_selected("add_kernel", "int32")) selector2 = SelectiveBuilder.from_yaml_str(yaml_config_v2) self.assertFalse(selector2.is_operator_selected("aten::add")) self.assertTrue(selector2.is_operator_selected("aten::sub")) self.assertTrue(selector2.is_operator_selected("aten::sub.int")) selector_legacy_v1 = SelectiveBuilder.from_legacy_op_registration_allow_list( ["aten::add", "aten::add.int", "aten::mul.int"], False, False, ) self.assertTrue(selector_legacy_v1.is_operator_selected("aten::add.float")) self.assertTrue(selector_legacy_v1.is_operator_selected("aten::add")) self.assertTrue(selector_legacy_v1.is_operator_selected("aten::add.int")) self.assertFalse(selector_legacy_v1.is_operator_selected("aten::sub")) self.assertFalse(selector_legacy_v1.is_root_operator("aten::add")) self.assertFalse( selector_legacy_v1.is_operator_selected_for_training("aten::add") ) selector_legacy_v1 = SelectiveBuilder.from_legacy_op_registration_allow_list( ["aten::add", "aten::add.int", "aten::mul.int"], True, False, ) self.assertTrue(selector_legacy_v1.is_root_operator("aten::add")) self.assertFalse( selector_legacy_v1.is_operator_selected_for_training("aten::add") ) self.assertTrue(selector_legacy_v1.is_root_operator("aten::add.float")) self.assertFalse( selector_legacy_v1.is_operator_selected_for_training("aten::add.float") ) selector_legacy_v1 = SelectiveBuilder.from_legacy_op_registration_allow_list( ["aten::add", "aten::add.int", "aten::mul.int"], False, True, ) self.assertFalse(selector_legacy_v1.is_root_operator("aten::add")) self.assertTrue( selector_legacy_v1.is_operator_selected_for_training("aten::add") ) self.assertFalse(selector_legacy_v1.is_root_operator("aten::add.float")) self.assertTrue( selector_legacy_v1.is_operator_selected_for_training("aten::add.float") ) def test_operator_combine(self): op1 = SelectiveBuildOperator( "aten::add.int", is_root_operator=True, is_used_for_training=False, include_all_overloads=False, _debug_info=None, ) op2 = SelectiveBuildOperator( "aten::add.int", is_root_operator=False, is_used_for_training=False, include_all_overloads=False, _debug_info=None, ) op3 = SelectiveBuildOperator( "aten::add", is_root_operator=True, is_used_for_training=False, include_all_overloads=False, _debug_info=None, ) op4 = SelectiveBuildOperator( "aten::add.int", is_root_operator=True, is_used_for_training=True, include_all_overloads=False, _debug_info=None, ) op5 = combine_operators(op1, op2) self.assertTrue(op5.is_root_operator) self.assertFalse(op5.is_used_for_training) op6 = combine_operators(op1, op4) self.assertTrue(op6.is_root_operator) self.assertTrue(op6.is_used_for_training) def gen_new_op(): return combine_operators(op1, op3) self.assertRaises(Exception, gen_new_op) def test_training_op_fetch(self): yaml_config = """ operators: aten::add.int: is_used_for_training: No is_root_operator: Yes include_all_overloads: No aten::add: is_used_for_training: Yes is_root_operator: No include_all_overloads: Yes """ selector = SelectiveBuilder.from_yaml_str(yaml_config) self.assertTrue(selector.is_operator_selected_for_training("aten::add.int")) self.assertTrue(selector.is_operator_selected_for_training("aten::add")) def test_kernel_dtypes(self): yaml_config = """ kernel_metadata: add_kernel: - int8 - int32 sub_kernel: - int16 - int32 add/sub_kernel: - float - complex """ selector = SelectiveBuilder.from_yaml_str(yaml_config) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int32")) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int8")) self.assertFalse(selector.is_kernel_dtype_selected("add_kernel", "int16")) self.assertFalse(selector.is_kernel_dtype_selected("add1_kernel", "int32")) self.assertFalse(selector.is_kernel_dtype_selected("add_kernel", "float")) self.assertTrue(selector.is_kernel_dtype_selected("add/sub_kernel", "float")) self.assertTrue(selector.is_kernel_dtype_selected("add/sub_kernel", "complex")) self.assertFalse(selector.is_kernel_dtype_selected("add/sub_kernel", "int16")) self.assertFalse(selector.is_kernel_dtype_selected("add/sub_kernel", "int32")) def test_merge_kernel_dtypes(self): yaml_config1 = """ kernel_metadata: add_kernel: - int8 add/sub_kernel: - float - complex - none mul_kernel: - int8 """ yaml_config2 = """ kernel_metadata: add_kernel: - int32 sub_kernel: - int16 - int32 add/sub_kernel: - float - complex """ selector1 = SelectiveBuilder.from_yaml_str(yaml_config1) selector2 = SelectiveBuilder.from_yaml_str(yaml_config2) selector = combine_selective_builders(selector1, selector2) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int32")) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int8")) self.assertFalse(selector.is_kernel_dtype_selected("add_kernel", "int16")) self.assertFalse(selector.is_kernel_dtype_selected("add1_kernel", "int32")) self.assertFalse(selector.is_kernel_dtype_selected("add_kernel", "float")) self.assertTrue(selector.is_kernel_dtype_selected("add/sub_kernel", "float")) self.assertTrue(selector.is_kernel_dtype_selected("add/sub_kernel", "complex")) self.assertTrue(selector.is_kernel_dtype_selected("add/sub_kernel", "none")) self.assertFalse(selector.is_kernel_dtype_selected("add/sub_kernel", "int16")) self.assertFalse(selector.is_kernel_dtype_selected("add/sub_kernel", "int32")) self.assertTrue(selector.is_kernel_dtype_selected("mul_kernel", "int8")) self.assertFalse(selector.is_kernel_dtype_selected("mul_kernel", "int32")) def test_all_kernel_dtypes_selected(self): yaml_config = """ include_all_non_op_selectives: True """ selector = SelectiveBuilder.from_yaml_str(yaml_config) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int32")) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int8")) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "int16")) self.assertTrue(selector.is_kernel_dtype_selected("add1_kernel", "int32")) self.assertTrue(selector.is_kernel_dtype_selected("add_kernel", "float")) def test_custom_namespace_selected_correctly(self): yaml_config = """ operators: aten::add.int: is_used_for_training: No is_root_operator: Yes include_all_overloads: No custom::add: is_used_for_training: Yes is_root_operator: No include_all_overloads: Yes """ selector = SelectiveBuilder.from_yaml_str(yaml_config) native_function, _ = NativeFunction.from_yaml( {"func": "custom::add() -> Tensor"}, loc=Location(__file__, 1), valid_tags=set(), ) self.assertTrue(selector.is_native_function_selected(native_function))
pytorch-master
tools/test/test_selective_build.py
import os import unittest from tools.stats.upload_test_stats import get_tests, summarize_test_cases IN_CI = os.environ.get("CI") class TestUploadTestStats(unittest.TestCase): @unittest.skipIf( IN_CI, "don't run in CI as this does a lot of network calls and uses up GH API rate limit", ) def test_existing_job(self) -> None: """Run on a known-good job and make sure we don't error and get basically okay reults.""" test_cases, _ = get_tests(2561394934, 1) self.assertEqual(len(test_cases), 609873) summary = summarize_test_cases(test_cases) self.assertEqual(len(summary), 5068) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_upload_test_stats.py
# Owner(s): ["module: codegen"] import textwrap import unittest from typing import cast import expecttest import torchgen.dest as dest import torchgen.gen as gen import yaml from torchgen.gen import LineLoader, parse_native_yaml_struct from torchgen.model import CustomClassType, DispatchKey, NativeFunctionsGroup, Type class TestCodegenModel(expecttest.TestCase): def assertParseErrorInline(self, yaml_str: str, expect: str) -> None: es = yaml.load(yaml_str, Loader=LineLoader) try: parse_native_yaml_struct(es, set()) except AssertionError as e: # hack to strip out the context msg, _ = str(e).split(" in ", 2) self.assertExpectedInline("\n".join(textwrap.wrap(msg)), expect, skip=1) return self.fail(msg="Did not raise when expected to") def assertUfuncErrorInline(self, yaml_str: str, expect: str) -> None: # parse a single structured group out of the yaml to g es = yaml.load(yaml_str, Loader=LineLoader) parsed_yaml = parse_native_yaml_struct(es, set()) native_functions, backend_indices = ( parsed_yaml.native_functions, parsed_yaml.backend_indices, ) grouped_native_functions = gen.get_grouped_native_functions(native_functions) assert len(grouped_native_functions) == 1 g = grouped_native_functions[0] assert isinstance(g, NativeFunctionsGroup) assert g.out.ufunc_inner_loop # this is not ufunc codegen per se, but it does some basic sanity tests for # ufunc generation gen.compute_meta_function_declaration(g) dest.compute_native_function_declaration(g, backend_indices[DispatchKey.CPU]) dest.compute_native_function_declaration(g, backend_indices[DispatchKey.CUDA]) try: # the real kahuna dest.compute_ufunc_cpu(g) dest.compute_ufunc_cpu_kernel(g) dest.compute_ufunc_cuda(g) except AssertionError as e: # hack to strip out the context msg, _ = str(e).split(" in ", 2) self.assertExpectedInline("\n".join(textwrap.wrap(msg)), expect, skip=1) return self.fail(msg="Did not raise when expected to") # NB: indent is hardcoded to be two here, so format your yaml accordingly binop_out = ( "func: binop.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)" ) ti_binop_out = f"""{binop_out} structured: True structured_inherits: TensorIteratorBase""" ti_binop = """func: binop(Tensor self, Tensor other) -> Tensor structured_delegate: binop.out """ ti_unop_out = """func: unop.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) structured: True structured_inherits: TensorIteratorBase""" ti_unop = """func: unop(Tensor self) -> Tensor structured_delegate: unop.out """ def test_nonstructured_ufunc(self) -> None: yaml_str = f"""\ - {self.binop_out} ufunc_inner_loop: Generic: binop (Bool) """ self.assertParseErrorInline( yaml_str, """\ ufunc must be structured""", ) def test_overlapping_ufunc_and_dispatch(self) -> None: yaml_str = f"""\ - {self.ti_binop_out} ufunc_inner_loop: Generic: binop (Bool) dispatch: CPU: binop_cpu """ self.assertParseErrorInline( yaml_str, """\ ufunc should not have explicit dispatch entry for CPU""", ) # See https://github.com/pytorch/pytorch/pull/65851#discussion_r810238456 @unittest.expectedFailure def test_scalaronly_shadowed(self) -> None: yaml_str = f"""\ - {self.ti_binop_out} ufunc_inner_loop: Generic: binop (Bool) ScalarOnly: binop (Bool) """ self.assertParseErrorInline( yaml_str, """\ """, ) def test_conflicting_ufunc(self) -> None: yaml_str = f"""\ - {self.ti_binop_out} ufunc_inner_loop: Generic: binop (Bool) ScalarOnly: binop_scalar (Bool) - {self.ti_binop} """ self.assertUfuncErrorInline( yaml_str, """\ ScalarOnly and Generic must have same ufunc name""", ) def test_invalid_cudafunctoronself_for_binary_op(self) -> None: yaml_str = f"""\ - {self.ti_unop_out} ufunc_inner_loop: Generic: unop (All) CUDAFunctorOnSelf: unop_self_cuda (All) - {self.ti_unop} """ self.assertUfuncErrorInline( yaml_str, """\ cannot use CUDAFunctorOnSelf on non-binary function""", ) def test_parse_custom_class_type(self) -> None: custom_class_name = "namespace_foo.class_bar" custom_class_name_with_prefix = f"__torch__.torch.classes.{custom_class_name}" custom_class_type = cast( CustomClassType, Type.parse(custom_class_name_with_prefix) ) self.assertTrue(isinstance(custom_class_type, CustomClassType)) self.assertEqual(custom_class_name, custom_class_type.class_name) self.assertEqual(custom_class_name_with_prefix, str(custom_class_type)) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_codegen_model.py
import os import unittest from typing import List from unittest.mock import patch from tools.stats.import_test_stats import get_disabled_issues class TestGetDisabledIssues(unittest.TestCase): def run_assert_disabled_issues( self, pr_body: str, commit_messages: str, expected: List[str] ) -> None: with patch.dict( os.environ, {"PR_BODY": pr_body, "COMMIT_MESSAGES": commit_messages} ): disabled_issues = get_disabled_issues() self.assertEqual(disabled_issues, expected) # test variations of close in PR_BODY def test_closes_pr_body(self) -> None: pr_body = "closes #123 Close #143 ClOsE #345 closed #10283" self.run_assert_disabled_issues(pr_body, "", ["123", "143", "345", "10283"]) # test variations of fix in COMMIT_MESSAGES def test_fixes_commit_messages(self) -> None: commit_messages = "fix #123 FixEd #143 fixes #345 FiXeD #10283" self.run_assert_disabled_issues( "", commit_messages, ["123", "143", "345", "10283"] ) # test variations of resolve in PR_BODY and COMMIT_MESSAGES def test_resolves_pr_commits(self) -> None: pr_body = "resolve #123 resolveS #143" commit_messages = "REsolved #345 RESOLVES #10283" self.run_assert_disabled_issues( pr_body, commit_messages, ["123", "143", "345", "10283"] ) # test links def test_issue_links(self) -> None: pr_body = "closes https://github.com/pytorch/pytorch/issues/75198 fixes https://github.com/pytorch/pytorch/issues/75123" self.run_assert_disabled_issues(pr_body, "", ["75198", "75123"]) # test strange spacing def test_spacing(self) -> None: pr_body = "resolve #123,resolveS #143Resolved #345\nRESOLVES #10283" commit_messages = "Fixed #2348fixes https://github.com/pytorch/pytorch/issues/75123resolveS #2134" self.run_assert_disabled_issues( pr_body, commit_messages, ["123", "143", "345", "10283", "2348", "75123", "2134"], ) # test bad things def test_not_accepted(self) -> None: pr_body = ( "fixes189 fixeshttps://github.com/pytorch/pytorch/issues/75123 " "closedhttps://githubcom/pytorch/pytorch/issues/75123" ) commit_messages = ( "fix 234, fixes # 45, fixing #123, close 234, closes#45, closing #123 resolve 234, " "resolves #45, resolving #123" ) self.run_assert_disabled_issues(pr_body, commit_messages, []) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_import_test_stats.py
import contextlib import os import typing import unittest import unittest.mock from typing import Iterator, Optional, Sequence import tools.setup_helpers.cmake import tools.setup_helpers.env # noqa: F401 unused but resolves circular import T = typing.TypeVar("T") class TestCMake(unittest.TestCase): @unittest.mock.patch("multiprocessing.cpu_count") def test_build_jobs(self, mock_cpu_count: unittest.mock.MagicMock) -> None: """Tests that the number of build jobs comes out correctly.""" mock_cpu_count.return_value = 13 cases = [ # MAX_JOBS, USE_NINJA, IS_WINDOWS, want (("8", True, False), ["-j", "8"]), # noqa: E201,E241 ((None, True, False), None), # noqa: E201,E241 (("7", False, False), ["-j", "7"]), # noqa: E201,E241 ((None, False, False), ["-j", "13"]), # noqa: E201,E241 (("6", True, True), ["-j", "6"]), # noqa: E201,E241 ((None, True, True), None), # noqa: E201,E241 (("11", False, True), ["/p:CL_MPCount=11"]), # noqa: E201,E241 ((None, False, True), ["/p:CL_MPCount=13"]), # noqa: E201,E241 ] for (max_jobs, use_ninja, is_windows), want in cases: with self.subTest( MAX_JOBS=max_jobs, USE_NINJA=use_ninja, IS_WINDOWS=is_windows ): with contextlib.ExitStack() as stack: stack.enter_context(env_var("MAX_JOBS", max_jobs)) stack.enter_context( unittest.mock.patch.object( tools.setup_helpers.cmake, "USE_NINJA", use_ninja ) ) stack.enter_context( unittest.mock.patch.object( tools.setup_helpers.cmake, "IS_WINDOWS", is_windows ) ) cmake = tools.setup_helpers.cmake.CMake() with unittest.mock.patch.object(cmake, "run") as cmake_run: cmake.build({}) cmake_run.assert_called_once() (call,) = cmake_run.mock_calls build_args, _ = call.args if want is None: self.assertNotIn("-j", build_args) else: self.assert_contains_sequence(build_args, want) @staticmethod def assert_contains_sequence( sequence: Sequence[T], subsequence: Sequence[T] ) -> None: """Raises an assertion if the subsequence is not contained in the sequence.""" if len(subsequence) == 0: return # all sequences contain the empty subsequence # Iterate over all windows of len(subsequence). Stop if the # window matches. for i in range(len(sequence) - len(subsequence) + 1): candidate = sequence[i : i + len(subsequence)] assert len(candidate) == len(subsequence) # sanity check if candidate == subsequence: return # found it raise AssertionError(f"{subsequence} not found in {sequence}") @contextlib.contextmanager def env_var(key: str, value: Optional[str]) -> Iterator[None]: """Sets/clears an environment variable within a Python context.""" # Get the previous value and then override it. previous_value = os.environ.get(key) set_env_var(key, value) try: yield finally: # Restore to previous value. set_env_var(key, previous_value) def set_env_var(key: str, value: Optional[str]) -> None: """Sets/clears an environment variable.""" if value is None: os.environ.pop(key, None) else: os.environ[key] = value if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_cmake.py
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import unittest from unittest.mock import MagicMock from gen_oplist import throw_if_any_op_includes_overloads class GenOplistTest(unittest.TestCase): def setUp(self): pass def test_throw_if_any_op_includes_overloads(self): selective_builder = MagicMock() selective_builder.operators = MagicMock() selective_builder.operators.items.return_value = [ ("op1", MagicMock(include_all_overloads=True)), ("op2", MagicMock(include_all_overloads=False)), ("op3", MagicMock(include_all_overloads=True)), ] self.assertRaises( Exception, throw_if_any_op_includes_overloads, selective_builder ) selective_builder.operators.items.return_value = [ ("op1", MagicMock(include_all_overloads=False)), ("op2", MagicMock(include_all_overloads=False)), ("op3", MagicMock(include_all_overloads=False)), ] # Here we do not expect it to throw an exception since none of the ops # include all overloads. throw_if_any_op_includes_overloads(selective_builder)
pytorch-master
tools/test/gen_oplist_test.py
import dataclasses import typing import unittest from collections import defaultdict from typing import Dict, List import torchgen.model import yaml from tools.autograd import gen_autograd_functions, load_derivatives from torchgen.gen import ( get_native_function_declarations, get_native_function_schema_registrations, LineLoader, ) from torchgen.model import ( BackendIndex, BackendMetadata, DispatchKey, Location, NativeFunction, OperatorName, ) from torchgen.native_function_generation import add_generated_native_functions from torchgen.selective_build.selector import SelectiveBuilder class TestCreateDerivative(unittest.TestCase): def test_named_grads(self) -> None: schema = torchgen.model.FunctionSchema.parse( "func(Tensor a, Tensor b) -> (Tensor x, Tensor y)" ) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) derivative = load_derivatives.create_derivative( native_function, formula="func_backward(grad_x, grad_y)", var_names=(), available_named_gradients=["grad_x", "grad_y"], ) self.assertSetEqual(derivative.named_gradients, {"grad_x", "grad_y"}) def test_non_differentiable_output(self) -> None: specification = "func(Tensor a, Tensor b) -> (Tensor x, bool y, Tensor z)" schema = torchgen.model.FunctionSchema.parse(specification) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) _, differentiability_info = load_derivatives.create_differentiability_info( defn_dict={ "name": specification, "dispatch": {"Default": {"a": "grads[0]", "b": "grads[2]"}}, }, functions_by_signature={schema.signature(): [native_function]}, functions_by_schema={specification: native_function}, op_counter=typing.Counter[str](), used_dispatch_keys=set(), ) self.assertSequenceEqual( differentiability_info["Default"].available_named_gradients, # grad_y is not present because y is a # bool and thus not differentiable. ["grad_x", "grad_z"], ) def test_indexed_grads(self) -> None: schema = torchgen.model.FunctionSchema.parse( "func(Tensor a, Tensor b) -> (Tensor x, Tensor y)" ) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) derivative = load_derivatives.create_derivative( native_function, formula="func_backward(grads[0], grads[1])", var_names=(), available_named_gradients=["grad_x", "grad_y"], ) self.assertSetEqual(derivative.named_gradients, set()) def test_named_grads_and_indexed_grads(self) -> None: specification = "func(Tensor a, Tensor b) -> (Tensor x, Tensor y)" schema = torchgen.model.FunctionSchema.parse(specification) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) with self.assertRaisesRegex( RuntimeError, 'illegally mixes use of "grad_RETURN_NAME"' ): load_derivatives.create_differentiability_info( defn_dict={ "name": specification, # Uh-oh, the derivatives reference gradients by # name and by index. "dispatch": { "Default": { "a": "grad_x", "b": "grads[1]", } }, }, functions_by_signature={schema.signature(): [native_function]}, functions_by_schema={specification: native_function}, op_counter=typing.Counter[str](), used_dispatch_keys=set(), ) class TestGenAutogradFunctions(unittest.TestCase): def test_non_differentiable_output_invalid_type(self) -> None: specification = "func(Tensor a, Tensor b) -> (Tensor x, bool y, Tensor z)" schema = torchgen.model.FunctionSchema.parse(specification) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) _, differentiability_info = load_derivatives.create_differentiability_info( defn_dict={ "name": specification, "dispatch": { "Default": { "a": "grad_x", "b": "grad_z", } }, }, functions_by_signature={schema.signature(): [native_function]}, functions_by_schema={specification: native_function}, op_counter=typing.Counter[str](), used_dispatch_keys=set(), ) definition = gen_autograd_functions.process_function( differentiability_info["Default"], gen_autograd_functions.FUNCTION_DEFINITION, ) # grad_z should map to grads[1], not grads[2] because output 1 # (y) is not differentiable. assert "grad_z = grads[2]" not in definition assert "grad_z = grads[1]" in definition def test_non_differentiable_output_output_differentiability(self) -> None: specification = "func(Tensor a, Tensor b) -> (Tensor x, Tensor y, Tensor z)" schema = torchgen.model.FunctionSchema.parse(specification) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) _, differentiability_info = load_derivatives.create_differentiability_info( defn_dict={ "name": specification, "dispatch": { "Default": { "a": "grad_x", "b": "grad_z", }, "AutogradNestedTensor": { "a": "grad_z", "b": "grad_x", }, }, "output_differentiability": [True, False, True], }, functions_by_signature={schema.signature(): [native_function]}, functions_by_schema={specification: native_function}, op_counter=typing.Counter[str](), used_dispatch_keys=set(), ) default_definition = gen_autograd_functions.process_function( differentiability_info["Default"], gen_autograd_functions.FUNCTION_DEFINITION, ) # grad_z should map to grads[1], not grads[2] because output 1 # (y) is not differentiable. assert "grad_z = grads[2]" not in default_definition assert "grad_z = grads[1]" in default_definition nested_tensor_definition = gen_autograd_functions.process_function( differentiability_info["AutogradNestedTensor"], gen_autograd_functions.FUNCTION_DEFINITION, ) assert "grad_z = grads[2]" not in nested_tensor_definition assert "grad_z = grads[1]" in nested_tensor_definition def test_register_bogus_dispatch_key(self) -> None: specification = "func(Tensor a, Tensor b) -> (Tensor x, bool y, Tensor z)" schema = torchgen.model.FunctionSchema.parse(specification) native_function = dataclasses.replace(DEFAULT_NATIVE_FUNCTION, func=schema) with self.assertRaisesRegex( RuntimeError, "Invalid dispatch key AutogradRandomTensor in derivatives.yaml for", ): load_derivatives.create_differentiability_info( defn_dict={ "name": specification, "dispatch": { "Default": { "a": "grad_x", "b": "grad_z", }, "AutogradRandomTensor": { "a": "grad_x", "b": "grad_z", }, }, }, functions_by_signature={schema.signature(): [native_function]}, functions_by_schema={specification: native_function}, op_counter=typing.Counter[str](), used_dispatch_keys=set(), ) class TestGenSchemaRegistration(unittest.TestCase): def setUp(self) -> None: self.selector = SelectiveBuilder.get_nop_selector() self.custom_native_function, _ = torchgen.model.NativeFunction.from_yaml( {"func": "custom::func() -> bool"}, loc=torchgen.model.Location(__file__, 1), valid_tags=set(), ) def test_default_namespace_schema_registration_code_valid(self) -> None: native_functions = [DEFAULT_NATIVE_FUNCTION] registrations, _ = get_native_function_schema_registrations( native_functions=native_functions, schema_selector=self.selector, ) self.assertEqual(registrations, ['m.def("func() -> bool", {});\n']) def test_custom_namespace_schema_registration_code_valid(self) -> None: _, registrations = get_native_function_schema_registrations( native_functions=[self.custom_native_function], schema_selector=self.selector, ) self.assertEqual( registrations, """ TORCH_LIBRARY(custom, m) { m.def("func() -> bool", {}); };""", ) def test_mixed_namespace_schema_registration_code_valid(self) -> None: ( aten_registrations, custom_registrations, ) = get_native_function_schema_registrations( native_functions=[DEFAULT_NATIVE_FUNCTION, self.custom_native_function], schema_selector=self.selector, ) self.assertEqual(aten_registrations, ['m.def("func() -> bool", {});\n']) self.assertEqual( custom_registrations, """ TORCH_LIBRARY(custom, m) { m.def("func() -> bool", {}); };""", ) def test_3_namespaces_schema_registration_code_invalid(self) -> None: custom2_native_function, _ = torchgen.model.NativeFunction.from_yaml( {"func": "custom2::func() -> bool"}, loc=torchgen.model.Location(__file__, 1), valid_tags=set(), ) with self.assertRaises(AssertionError): get_native_function_schema_registrations( native_functions=[ DEFAULT_NATIVE_FUNCTION, self.custom_native_function, custom2_native_function, ], schema_selector=self.selector, ) class TestGenNativeFunctionDeclaration(unittest.TestCase): def setUp(self) -> None: self.op_1_native_function, op_1_backend_index = NativeFunction.from_yaml( {"func": "op_1() -> bool", "dispatch": {"CPU": "kernel_1"}}, loc=torchgen.model.Location(__file__, 1), valid_tags=set(), ) self.op_2_native_function, op_2_backend_index = NativeFunction.from_yaml( { "func": "op_2() -> bool", "dispatch": {"CPU": "kernel_2", "QuantizedCPU": "custom::kernel_3"}, }, loc=torchgen.model.Location(__file__, 1), valid_tags=set(), ) backend_indices: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = { DispatchKey.CPU: {}, DispatchKey.QuantizedCPU: {}, } BackendIndex.grow_index(backend_indices, op_1_backend_index) BackendIndex.grow_index(backend_indices, op_2_backend_index) self.backend_indices = { k: BackendIndex( dispatch_key=k, use_out_as_primary=True, external=False, device_guard=False, index=backend_indices[k], ) for k in backend_indices } def test_native_function_declaration_1_op_2_ns_error(self) -> None: with self.assertRaises(AssertionError): get_native_function_declarations( grouped_native_functions=[ self.op_1_native_function, self.op_2_native_function, ], backend_indices=self.backend_indices, ) def test_native_function_declaration_1_op_1_ns_valid(self) -> None: self.assertIsInstance(self.op_1_native_function, NativeFunction) declaration = get_native_function_declarations( grouped_native_functions=[ self.op_1_native_function, ], backend_indices=self.backend_indices, ) target = """ namespace at { namespace native { TORCH_API bool kernel_1(); } // namespace native } // namespace at """ self.assertEqual("\n".join(declaration), target) # Test for native_function_generation class TestNativeFunctionGeneratrion(unittest.TestCase): def setUp(self) -> None: self.native_functions: List[NativeFunction] = [] self.backend_indices: Dict[ DispatchKey, Dict[OperatorName, BackendMetadata] ] = defaultdict(dict) yaml_entry = """ - func: op(Tensor self) -> Tensor dispatch: CompositeExplicitAutograd: op autogen: op.out """ es = yaml.load(yaml_entry, Loader=LineLoader) self.one_return_func, m = NativeFunction.from_yaml( es[0], loc=Location(__file__, 1), valid_tags=set() ) BackendIndex.grow_index(self.backend_indices, m) self.two_returns_func, two_returns_backend_index = NativeFunction.from_yaml( { "func": "op_2() -> (Tensor, Tensor)", "dispatch": {"CPU": "kernel_1"}, "autogen": "op_2.out", }, loc=torchgen.model.Location(__file__, 1), valid_tags=set(), ) BackendIndex.grow_index(self.backend_indices, two_returns_backend_index) def test_functional_variant_autogen_out_variant(self) -> None: native_functions = [self.one_return_func] add_generated_native_functions(native_functions, self.backend_indices) self.assertEqual(len(native_functions), 2) self.assertEqual( str(native_functions[1].func), "op.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)", ) op_name = native_functions[1].func.name backend_metadata = self.backend_indices[DispatchKey.CompositeExplicitAutograd][ op_name ] self.assertEqual(backend_metadata.kernel, "op_out") def test_functional_variant_autogen_out_variant_two_returns(self) -> None: native_functions = [self.two_returns_func] add_generated_native_functions(native_functions, self.backend_indices) self.assertEqual(len(native_functions), 2) self.assertEqual( str(native_functions[1].func), "op_2.out(*, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))", ) op_name = native_functions[1].func.name backend_metadata = self.backend_indices[DispatchKey.CompositeExplicitAutograd][ op_name ] self.assertEqual(backend_metadata.kernel, "op_2_out") # Represents the most basic NativeFunction. Use dataclasses.replace() # to edit for use. DEFAULT_NATIVE_FUNCTION, _ = torchgen.model.NativeFunction.from_yaml( {"func": "func() -> bool"}, loc=torchgen.model.Location(__file__, 1), valid_tags=set(), ) if __name__ == "__main__": unittest.main()
pytorch-master
tools/test/test_codegen.py
#!/usr/bin/env python3 """Updates the default value of opset_version. The current policy is that the default should be set to the latest released version as of 18 months ago. Usage: Run with no arguments. """ import datetime import os import pathlib import re import subprocess import sys from subprocess import DEVNULL pytorch_dir = pathlib.Path(__file__).parent.parent.parent.resolve() onnx_dir = pytorch_dir / "third_party" / "onnx" os.chdir(onnx_dir) date = datetime.datetime.now() - datetime.timedelta(days=18 * 30) onnx_commit = subprocess.check_output( ("git", "log", f"--until={date}", "--max-count=1", "--format=%H"), encoding="utf-8" ).strip() onnx_tags = subprocess.check_output( ("git", "tag", "--list", f"--contains={onnx_commit}"), encoding="utf-8" ) tag_tups = [] semver_pat = re.compile(r"v(\d+)\.(\d+)\.(\d+)") for tag in onnx_tags.splitlines(): match = semver_pat.match(tag) if match: tag_tups.append(tuple(int(x) for x in match.groups())) version_str = "{}.{}.{}".format(*min(tag_tups)) print("Using ONNX release", version_str) head_commit = subprocess.check_output( ("git", "log", "--max-count=1", "--format=%H", "HEAD"), encoding="utf-8" ).strip() new_default = None subprocess.check_call( ("git", "checkout", f"v{version_str}"), stdout=DEVNULL, stderr=DEVNULL ) try: from onnx import helper # type: ignore[import] for version in helper.VERSION_TABLE: if version[0] == version_str: new_default = version[2] print("found new default opset_version", new_default) break if not new_default: sys.exit( f"failed to find version {version_str} in onnx.helper.VERSION_TABLE at commit {onnx_commit}" ) finally: subprocess.check_call( ("git", "checkout", head_commit), stdout=DEVNULL, stderr=DEVNULL ) os.chdir(pytorch_dir) def read_sub_write(path: str, prefix_pat: str) -> None: with open(path, encoding="utf-8") as f: content_str = f.read() content_str = re.sub(prefix_pat, r"\g<1>{}".format(new_default), content_str) with open(path, "w", encoding="utf-8") as f: f.write(content_str) print("modified", path) read_sub_write( os.path.join("torch", "onnx", "_constants.py"), r"(onnx_default_opset = )\d+", ) read_sub_write( os.path.join("torch", "onnx", "__init__.py"), r"(opset_version \(int, default )\d+" ) print("Updating operator .expect files") subprocess.check_call(("python", "setup.py", "develop"), stdout=DEVNULL, stderr=DEVNULL) subprocess.check_call( ("python", os.path.join("test", "onnx", "test_operators.py"), "--accept"), stdout=DEVNULL, stderr=DEVNULL, )
pytorch-master
tools/onnx/update_default_opset_version.py
#!/usr/bin/env python3 import argparse import asyncio import collections import csv import hashlib import itertools import os import pathlib import re import shlex import shutil import subprocess import sys import time from typing import Awaitable, cast, DefaultDict, Dict, List, Match, Optional, Set from typing_extensions import TypedDict help_msg = """fast_nvcc [OPTION]... -- [NVCC_ARG]... Run the commands given by nvcc --dryrun, in parallel. All flags for this script itself (see the "optional arguments" section of --help) must be passed before the first "--". Everything after that first "--" is passed directly to nvcc, with the --dryrun argument added. This script only works with the "normal" execution path of nvcc, so for instance passing --help (after "--") doesn't work since the --help execution path doesn't compile anything, so adding --dryrun there gives nothing in stderr. """ parser = argparse.ArgumentParser(help_msg) parser.add_argument( "--faithful", action="store_true", help="don't modify the commands given by nvcc (slower)", ) parser.add_argument( "--graph", metavar="FILE.gv", help="write Graphviz DOT file with execution graph", ) parser.add_argument( "--nvcc", metavar="PATH", default="nvcc", help='path to nvcc (default is just "nvcc")', ) parser.add_argument( "--save", metavar="DIR", help="copy intermediate files from each command into DIR", ) parser.add_argument( "--sequential", action="store_true", help="sequence commands instead of using the graph (slower)", ) parser.add_argument( "--table", metavar="FILE.csv", help="write CSV with times and intermediate file sizes", ) parser.add_argument( "--verbose", metavar="FILE.txt", help="like nvcc --verbose, but expanded and into a file", ) default_config = parser.parse_args([]) # docs about temporary directories used by NVCC url_base = "https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html" url_vars = f"{url_base}#keeping-intermediate-phase-files" # regex for temporary file names re_tmp = r"(?<![\w\-/])(?:/tmp/)?(tmp[^ \"\'\\]+)" def fast_nvcc_warn(warning: str) -> None: """ Warn the user about something regarding fast_nvcc. """ print(f"warning (fast_nvcc): {warning}", file=sys.stderr) def warn_if_windows() -> None: """ Warn the user that using fast_nvcc on Windows might not work. """ # use os.name instead of platform.system() because there is a # platform.py file in this directory, making it very difficult to # import the platform module from the Python standard library if os.name == "nt": fast_nvcc_warn("untested on Windows, might not work; see this URL:") fast_nvcc_warn(url_vars) def warn_if_tmpdir_flag(args: List[str]) -> None: """ Warn the user that using fast_nvcc with some flags might not work. """ file_path_specs = "file-and-path-specifications" guiding_driver = "options-for-guiding-compiler-driver" scary_flags = { "--objdir-as-tempdir": file_path_specs, "-objtemp": file_path_specs, "--keep": guiding_driver, "-keep": guiding_driver, "--keep-dir": guiding_driver, "-keep-dir": guiding_driver, "--save-temps": guiding_driver, "-save-temps": guiding_driver, } for arg in args: for flag, frag in scary_flags.items(): if re.match(rf"^{re.escape(flag)}(?:=.*)?$", arg): fast_nvcc_warn(f"{flag} not supported since it interacts with") fast_nvcc_warn("TMPDIR, so fast_nvcc may break; see this URL:") fast_nvcc_warn(f"{url_base}#{frag}") class DryunData(TypedDict): env: Dict[str, str] commands: List[str] exit_code: int def nvcc_dryrun_data(binary: str, args: List[str]) -> DryunData: """ Return parsed environment variables and commands from nvcc --dryrun. """ result = subprocess.run( # type: ignore[call-overload] [binary, "--dryrun"] + args, capture_output=True, encoding="ascii", # this is just a guess ) print(result.stdout, end="") env = {} commands = [] for line in result.stderr.splitlines(): match = re.match(r"^#\$ (.*)$", line) if match: (stripped,) = match.groups() mapping = re.match(r"^(\w+)=(.*)$", stripped) if mapping: name, val = mapping.groups() env[name] = val else: commands.append(stripped) else: print(line, file=sys.stderr) return {"env": env, "commands": commands, "exit_code": result.returncode} def warn_if_tmpdir_set(env: Dict[str, str]) -> None: """ Warn the user that setting TMPDIR with fast_nvcc might not work. """ if os.getenv("TMPDIR") or "TMPDIR" in env: fast_nvcc_warn("TMPDIR is set, might not work; see this URL:") fast_nvcc_warn(url_vars) def contains_non_executable(commands: List[str]) -> bool: for command in commands: # This is to deal with special command dry-run result from NVCC such as: # ``` # #$ "/lib64/ccache"/c++ -std=c++11 -E -x c++ -D__CUDACC__ -D__NVCC__ -fPIC -fvisibility=hidden -O3 \ # -I ... -m64 "reduce_scatter.cu" > "/tmp/tmpxft_0037fae3_00000000-5_reduce_scatter.cpp4.ii # #$ -- Filter Dependencies -- > ... pytorch/build/nccl/obj/collectives/device/reduce_scatter.dep.tmp # ``` if command.startswith("--"): return True return False def module_id_contents(command: List[str]) -> str: """ Guess the contents of the .module_id file contained within command. """ if command[0] == "cicc": path = command[-3] elif command[0] == "cudafe++": path = command[-1] middle = pathlib.PurePath(path).name.replace("-", "_").replace(".", "_") # this suffix is very wrong (the real one is far less likely to be # unique), but it seems difficult to find a rule that reproduces the # real suffixes, so here's one that, while inaccurate, is at least # hopefully as straightforward as possible suffix = hashlib.md5(str.encode(middle)).hexdigest()[:8] return f"_{len(middle)}_{middle}_{suffix}" def unique_module_id_files(commands: List[str]) -> List[str]: """ Give each command its own .module_id filename instead of sharing. """ module_id = None uniqueified = [] for i, line in enumerate(commands): arr = [] def uniqueify(s: Match[str]) -> str: filename = re.sub(r"\-(\d+)", r"-\1-" + str(i), s.group(0)) arr.append(filename) return filename line = re.sub(re_tmp + r".module_id", uniqueify, line) line = re.sub(r"\s*\-\-gen\_module\_id\_file\s*", " ", line) if arr: (filename,) = arr if not module_id: module_id = module_id_contents(shlex.split(line)) uniqueified.append(f"echo -n '{module_id}' > '{filename}'") uniqueified.append(line) return uniqueified def make_rm_force(commands: List[str]) -> List[str]: """ Add --force to all rm commands. """ return [f"{c} --force" if c.startswith("rm ") else c for c in commands] def print_verbose_output( *, env: Dict[str, str], commands: List[List[str]], filename: str, ) -> None: """ Human-readably write nvcc --dryrun data to stderr. """ padding = len(str(len(commands) - 1)) with open(filename, "w") as f: for name, val in env.items(): print(f'#{" "*padding}$ {name}={val}', file=f) for i, command in enumerate(commands): prefix = f"{str(i).rjust(padding)}$ " print(f"#{prefix}{command[0]}", file=f) for part in command[1:]: print(f'#{" "*len(prefix)}{part}', file=f) Graph = List[Set[int]] def straight_line_dependencies(commands: List[str]) -> Graph: """ Return a straight-line dependency graph. """ return [({i - 1} if i > 0 else set()) for i in range(len(commands))] def files_mentioned(command: str) -> List[str]: """ Return fully-qualified names of all tmp files referenced by command. """ return [f"/tmp/{match.group(1)}" for match in re.finditer(re_tmp, command)] def nvcc_data_dependencies(commands: List[str]) -> Graph: """ Return a list of the set of dependencies for each command. """ # fatbin needs to be treated specially because while the cicc steps # do refer to .fatbin.c files, they do so through the # --include_file_name option, since they're generating files that # refer to .fatbin.c file(s) that will later be created by the # fatbinary step; so for most files, we make a data dependency from # the later step to the earlier step, but for .fatbin.c files, the # data dependency is sort of flipped, because the steps that use the # files generated by cicc need to wait for the fatbinary step to # finish first tmp_files: Dict[str, int] = {} fatbins: DefaultDict[int, Set[str]] = collections.defaultdict(set) graph = [] for i, line in enumerate(commands): deps = set() for tmp in files_mentioned(line): if tmp in tmp_files: dep = tmp_files[tmp] deps.add(dep) if dep in fatbins: for filename in fatbins[dep]: if filename in tmp_files: deps.add(tmp_files[filename]) if tmp.endswith(".fatbin.c") and not line.startswith("fatbinary"): fatbins[i].add(tmp) else: tmp_files[tmp] = i if line.startswith("rm ") and not deps: deps.add(i - 1) graph.append(deps) return graph def is_weakly_connected(graph: Graph) -> bool: """ Return true iff graph is weakly connected. """ if not graph: return True neighbors: List[Set[int]] = [set() for _ in graph] for node, predecessors in enumerate(graph): for pred in predecessors: neighbors[pred].add(node) neighbors[node].add(pred) # assume nonempty graph stack = [0] found = {0} while stack: node = stack.pop() for neighbor in neighbors[node]: if neighbor not in found: found.add(neighbor) stack.append(neighbor) return len(found) == len(graph) def warn_if_not_weakly_connected(graph: Graph) -> None: """ Warn the user if the execution graph is not weakly connected. """ if not is_weakly_connected(graph): fast_nvcc_warn("execution graph is not (weakly) connected") def print_dot_graph( *, commands: List[List[str]], graph: Graph, filename: str, ) -> None: """ Print a DOT file displaying short versions of the commands in graph. """ def name(k: int) -> str: return f'"{k} {os.path.basename(commands[k][0])}"' with open(filename, "w") as f: print("digraph {", file=f) # print all nodes, in case it's disconnected for i in range(len(graph)): print(f" {name(i)};", file=f) for i, deps in enumerate(graph): for j in deps: print(f" {name(j)} -> {name(i)};", file=f) print("}", file=f) class Result(TypedDict, total=False): exit_code: int stdout: bytes stderr: bytes time: float files: Dict[str, int] async def run_command( command: str, *, env: Dict[str, str], deps: Set[Awaitable[Result]], gather_data: bool, i: int, save: Optional[str], ) -> Result: """ Run the command with the given env after waiting for deps. """ for task in deps: dep_result = await task # abort if a previous step failed if "exit_code" not in dep_result or dep_result["exit_code"] != 0: return {} if gather_data: t1 = time.monotonic() proc = await asyncio.create_subprocess_shell( command, env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await proc.communicate() code = cast(int, proc.returncode) results: Result = {"exit_code": code, "stdout": stdout, "stderr": stderr} if gather_data: t2 = time.monotonic() results["time"] = t2 - t1 sizes = {} for tmp_file in files_mentioned(command): if os.path.exists(tmp_file): sizes[tmp_file] = os.path.getsize(tmp_file) else: sizes[tmp_file] = 0 results["files"] = sizes if save: dest = pathlib.Path(save) / str(i) dest.mkdir() for src in map(pathlib.Path, files_mentioned(command)): if src.exists(): shutil.copy2(src, dest / (src.name)) return results async def run_graph( *, env: Dict[str, str], commands: List[str], graph: Graph, gather_data: bool = False, save: Optional[str] = None, ) -> List[Result]: """ Return outputs/errors (and optionally time/file info) from commands. """ tasks: List[Awaitable[Result]] = [] for i, (command, indices) in enumerate(zip(commands, graph)): deps = {tasks[j] for j in indices} tasks.append( asyncio.create_task( run_command( # type: ignore[attr-defined] command, env=env, deps=deps, gather_data=gather_data, i=i, save=save, ) ) ) return [await task for task in tasks] def print_command_outputs(command_results: List[Result]) -> None: """ Print captured stdout and stderr from commands. """ for result in command_results: sys.stdout.write(result.get("stdout", b"").decode("ascii")) sys.stderr.write(result.get("stderr", b"").decode("ascii")) def write_log_csv( command_parts: List[List[str]], command_results: List[Result], *, filename: str, ) -> None: """ Write a CSV file of the times and /tmp file sizes from each command. """ tmp_files: List[str] = [] for result in command_results: tmp_files.extend(result.get("files", {}).keys()) with open(filename, "w", newline="") as csvfile: fieldnames = ["command", "seconds"] + list(dict.fromkeys(tmp_files)) writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i, result in enumerate(command_results): command = f"{i} {os.path.basename(command_parts[i][0])}" row = {"command": command, "seconds": result.get("time", 0)} writer.writerow({**row, **result.get("files", {})}) def exit_code(results: List[Result]) -> int: """ Aggregate individual exit codes into a single code. """ for result in results: code = result.get("exit_code", 0) if code != 0: return code return 0 def wrap_nvcc( args: List[str], config: argparse.Namespace = default_config, ) -> int: return subprocess.call([config.nvcc] + args) def fast_nvcc( args: List[str], *, config: argparse.Namespace = default_config, ) -> int: """ Emulate the result of calling the given nvcc binary with args. Should run faster than plain nvcc. """ warn_if_windows() warn_if_tmpdir_flag(args) dryrun_data = nvcc_dryrun_data(config.nvcc, args) env = dryrun_data["env"] warn_if_tmpdir_set(env) commands = dryrun_data["commands"] if not config.faithful: commands = make_rm_force(unique_module_id_files(commands)) if contains_non_executable(commands): return wrap_nvcc(args, config) command_parts = list(map(shlex.split, commands)) if config.verbose: print_verbose_output( env=env, commands=command_parts, filename=config.verbose, ) graph = nvcc_data_dependencies(commands) warn_if_not_weakly_connected(graph) if config.graph: print_dot_graph( commands=command_parts, graph=graph, filename=config.graph, ) if config.sequential: graph = straight_line_dependencies(commands) results = asyncio.run( run_graph( # type: ignore[attr-defined] env=env, commands=commands, graph=graph, gather_data=bool(config.table), save=config.save, ) ) print_command_outputs(results) if config.table: write_log_csv(command_parts, results, filename=config.table) return exit_code([dryrun_data] + results) # type: ignore[arg-type, operator] def our_arg(arg: str) -> bool: return arg != "--" if __name__ == "__main__": argv = sys.argv[1:] us = list(itertools.takewhile(our_arg, argv)) them = list(itertools.dropwhile(our_arg, argv)) sys.exit(fast_nvcc(them[1:], config=parser.parse_args(us)))
pytorch-master
tools/fast_nvcc/fast_nvcc.py
pytorch-master
tools/linter/__init__.py
import argparse import concurrent.futures import json import logging import os import re import subprocess import time from enum import Enum from typing import List, NamedTuple, Optional, Pattern LINTER_CODE = "ACTIONLINT" class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" class LintMessage(NamedTuple): path: Optional[str] line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] RESULTS_RE: Pattern[str] = re.compile( r"""(?mx) ^ (?P<file>.*?): (?P<line>\d+): (?P<char>\d+): \s(?P<message>.*) \s(?P<code>\[.*\]) $ """ ) def run_command( args: List[str], ) -> "subprocess.CompletedProcess[bytes]": logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) finally: end_time = time.monotonic() logging.debug("took %dms", (end_time - start_time) * 1000) def check_file( binary: str, file: str, ) -> List[LintMessage]: try: proc = run_command([binary, file]) except OSError as err: return [ LintMessage( path=None, line=None, char=None, code=LINTER_CODE, severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=(f"Failed due to {err.__class__.__name__}:\n{err}"), ) ] stdout = str(proc.stdout, "utf-8").strip() return [ LintMessage( path=match["file"], name=match["code"], description=match["message"], line=int(match["line"]), char=int(match["char"]), code=LINTER_CODE, severity=LintSeverity.ERROR, original=None, replacement=None, ) for match in RESULTS_RE.finditer(stdout) ] if __name__ == "__main__": parser = argparse.ArgumentParser( description="actionlint runner", fromfile_prefix_chars="@", ) parser.add_argument( "--binary", required=True, help="actionlint binary path", ) parser.add_argument( "filenames", nargs="+", help="paths to lint", ) args = parser.parse_args() if not os.path.exists(args.binary): err_msg = LintMessage( path="<none>", line=None, char=None, code=LINTER_CODE, severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=( f"Could not find actionlint binary at {args.binary}," " you may need to run `lintrunner init`." ), ) print(json.dumps(err_msg._asdict()), flush=True) exit(0) with concurrent.futures.ThreadPoolExecutor( max_workers=os.cpu_count(), thread_name_prefix="Thread", ) as executor: futures = { executor.submit( check_file, args.binary, filename, ): filename for filename in args.filenames } for future in concurrent.futures.as_completed(futures): try: for lint_message in future.result(): print(json.dumps(lint_message._asdict()), flush=True) except Exception: logging.critical('Failed at "%s".', futures[future]) raise
pytorch-master
tools/linter/adapters/actionlint_linter.py
""" Generic linter that greps for a pattern and optionally suggests replacements. """ import argparse import json import logging import os import subprocess import sys import time from enum import Enum from typing import Any, List, NamedTuple, Optional IS_WINDOWS: bool = os.name == "nt" def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, flush=True, **kwargs) class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" class LintMessage(NamedTuple): path: Optional[str] line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] def as_posix(name: str) -> str: return name.replace("\\", "/") if IS_WINDOWS else name def run_command( args: List[str], ) -> "subprocess.CompletedProcess[bytes]": logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) finally: end_time = time.monotonic() logging.debug("took %dms", (end_time - start_time) * 1000) def lint_file( matching_line: str, allowlist_pattern: str, replace_pattern: str, linter_name: str, error_name: str, error_description: str, ) -> Optional[LintMessage]: # matching_line looks like: # tools/linter/clangtidy_linter.py:13:import foo.bar.baz split = matching_line.split(":") filename = split[0] if allowlist_pattern: try: proc = run_command(["grep", "-nEHI", allowlist_pattern, filename]) except Exception as err: return LintMessage( path=None, line=None, char=None, code=linter_name, severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=( f"Failed due to {err.__class__.__name__}:\n{err}" if not isinstance(err, subprocess.CalledProcessError) else ( "COMMAND (exit code {returncode})\n" "{command}\n\n" "STDERR\n{stderr}\n\n" "STDOUT\n{stdout}" ).format( returncode=err.returncode, command=" ".join(as_posix(x) for x in err.cmd), stderr=err.stderr.decode("utf-8").strip() or "(empty)", stdout=err.stdout.decode("utf-8").strip() or "(empty)", ) ), ) # allowlist pattern was found, abort lint if proc.returncode == 0: return None original = None replacement = None if replace_pattern: with open(filename, "r") as f: original = f.read() try: proc = run_command(["sed", "-r", replace_pattern, filename]) replacement = proc.stdout.decode("utf-8") except Exception as err: return LintMessage( path=None, line=None, char=None, code=linter_name, severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=( f"Failed due to {err.__class__.__name__}:\n{err}" if not isinstance(err, subprocess.CalledProcessError) else ( "COMMAND (exit code {returncode})\n" "{command}\n\n" "STDERR\n{stderr}\n\n" "STDOUT\n{stdout}" ).format( returncode=err.returncode, command=" ".join(as_posix(x) for x in err.cmd), stderr=err.stderr.decode("utf-8").strip() or "(empty)", stdout=err.stdout.decode("utf-8").strip() or "(empty)", ) ), ) return LintMessage( path=split[0], line=int(split[1]) if len(split) > 1 else None, char=None, code=linter_name, severity=LintSeverity.ERROR, name=error_name, original=original, replacement=replacement, description=error_description, ) def main() -> None: parser = argparse.ArgumentParser( description="grep wrapper linter.", fromfile_prefix_chars="@", ) parser.add_argument( "--pattern", required=True, help="pattern to grep for", ) parser.add_argument( "--allowlist-pattern", help="if this pattern is true in the file, we don't grep for pattern", ) parser.add_argument( "--linter-name", required=True, help="name of the linter", ) parser.add_argument( "--match-first-only", action="store_true", help="only match the first hit in the file", ) parser.add_argument( "--error-name", required=True, help="human-readable description of what the error is", ) parser.add_argument( "--error-description", required=True, help="message to display when the pattern is found", ) parser.add_argument( "--replace-pattern", help=( "the form of a pattern passed to `sed -r`. " "If specified, this will become proposed replacement text." ), ) parser.add_argument( "--verbose", action="store_true", help="verbose logging", ) parser.add_argument( "filenames", nargs="+", help="paths to lint", ) args = parser.parse_args() logging.basicConfig( format="<%(threadName)s:%(levelname)s> %(message)s", level=logging.NOTSET if args.verbose else logging.DEBUG if len(args.filenames) < 1000 else logging.INFO, stream=sys.stderr, ) files_with_matches = [] if args.match_first_only: files_with_matches = ["--files-with-matches"] try: proc = run_command( ["grep", "-nEHI", *files_with_matches, args.pattern, *args.filenames] ) except Exception as err: err_msg = LintMessage( path=None, line=None, char=None, code=args.linter_name, severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=( f"Failed due to {err.__class__.__name__}:\n{err}" if not isinstance(err, subprocess.CalledProcessError) else ( "COMMAND (exit code {returncode})\n" "{command}\n\n" "STDERR\n{stderr}\n\n" "STDOUT\n{stdout}" ).format( returncode=err.returncode, command=" ".join(as_posix(x) for x in err.cmd), stderr=err.stderr.decode("utf-8").strip() or "(empty)", stdout=err.stdout.decode("utf-8").strip() or "(empty)", ) ), ) print(json.dumps(err_msg._asdict()), flush=True) exit(0) lines = proc.stdout.decode().splitlines() for line in lines: lint_message = lint_file( line, args.allowlist_pattern, args.replace_pattern, args.linter_name, args.error_name, args.error_description, ) if lint_message is not None: print(json.dumps(lint_message._asdict()), flush=True) if __name__ == "__main__": main()
pytorch-master
tools/linter/adapters/grep_linter.py
import argparse import concurrent.futures import json import logging import os import re import subprocess import time from enum import Enum from typing import List, NamedTuple, Optional, Pattern LINTER_CODE = "CMAKE" class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" class LintMessage(NamedTuple): path: Optional[str] line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] # CMakeLists.txt:901: Lines should be <= 80 characters long [linelength] RESULTS_RE: Pattern[str] = re.compile( r"""(?mx) ^ (?P<file>.*?): (?P<line>\d+): \s(?P<message>.*) \s(?P<code>\[.*\]) $ """ ) def run_command( args: List[str], ) -> "subprocess.CompletedProcess[bytes]": logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) finally: end_time = time.monotonic() logging.debug("took %dms", (end_time - start_time) * 1000) def check_file( filename: str, config: str, ) -> List[LintMessage]: try: proc = run_command( ["cmakelint", f"--config={config}", filename], ) except OSError as err: return [ LintMessage( path=None, line=None, char=None, code=LINTER_CODE, severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=(f"Failed due to {err.__class__.__name__}:\n{err}"), ) ] stdout = str(proc.stdout, "utf-8").strip() return [ LintMessage( path=match["file"], name=match["code"], description=match["message"], line=int(match["line"]), char=None, code=LINTER_CODE, severity=LintSeverity.ERROR, original=None, replacement=None, ) for match in RESULTS_RE.finditer(stdout) ] if __name__ == "__main__": parser = argparse.ArgumentParser( description="cmakelint runner", fromfile_prefix_chars="@", ) parser.add_argument( "--config", required=True, help="location of cmakelint config", ) parser.add_argument( "filenames", nargs="+", help="paths to lint", ) args = parser.parse_args() with concurrent.futures.ThreadPoolExecutor( max_workers=os.cpu_count(), thread_name_prefix="Thread", ) as executor: futures = { executor.submit( check_file, filename, args.config, ): filename for filename in args.filenames } for future in concurrent.futures.as_completed(futures): try: for lint_message in future.result(): print(json.dumps(lint_message._asdict()), flush=True) except Exception: logging.critical('Failed at "%s".', futures[future]) raise
pytorch-master
tools/linter/adapters/cmake_linter.py
"""Checks for consistency of jobs between different GitHub workflows. Any job with a specific `sync-tag` must match all other jobs with the same `sync-tag`. """ import argparse import itertools import json from collections import defaultdict from enum import Enum from pathlib import Path from typing import Any, Dict, Iterable, NamedTuple, Optional from yaml import CSafeLoader, dump, load class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" class LintMessage(NamedTuple): path: Optional[str] line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] def glob_yamls(path: Path) -> Iterable[Path]: return itertools.chain(path.glob("**/*.yml"), path.glob("**/*.yaml")) def load_yaml(path: Path) -> Any: with open(path) as f: return load(f, CSafeLoader) def is_workflow(yaml: Any) -> bool: return yaml.get("jobs") is not None def print_lint_message(path: Path, job: Dict[str, Any], sync_tag: str) -> None: job_id = list(job.keys())[0] with open(path) as f: lines = f.readlines() for i, line in enumerate(lines): if f"{job_id}:" in line: line_number = i + 1 lint_message = LintMessage( path=str(path), line=line_number, char=None, code="WORKFLOWSYNC", severity=LintSeverity.ERROR, name="workflow-inconsistency", original=None, replacement=None, description=f"Job doesn't match other jobs with sync-tag: '{sync_tag}'", ) print(json.dumps(lint_message._asdict()), flush=True) if __name__ == "__main__": parser = argparse.ArgumentParser( description="workflow consistency linter.", fromfile_prefix_chars="@", ) parser.add_argument( "filenames", nargs="+", help="paths to lint", ) args = parser.parse_args() # Go through the provided files, aggregating jobs with the same sync tag tag_to_jobs = defaultdict(list) for path in args.filenames: workflow = load_yaml(Path(path)) jobs = workflow["jobs"] for job_id, job in jobs.items(): try: sync_tag = job["with"]["sync-tag"] except KeyError: continue # remove the "if" field, which we allow to be different between jobs # (since you might have different triggering conditions on pull vs. # trunk, say.) if "if" in job: del job["if"] tag_to_jobs[sync_tag].append((path, {job_id: job})) # For each sync tag, check that all the jobs have the same code. for sync_tag, path_and_jobs in tag_to_jobs.items(): baseline_path, baseline_dict = path_and_jobs.pop() baseline_str = dump(baseline_dict) printed_baseline = False for path, job_dict in path_and_jobs: job_str = dump(job_dict) if baseline_str != job_str: print_lint_message(path, job_dict, sync_tag) if not printed_baseline: print_lint_message(baseline_path, baseline_dict, sync_tag) printed_baseline = True
pytorch-master
tools/linter/adapters/workflow_consistency_linter.py
import argparse import concurrent.futures import json import logging import os import subprocess import sys import time from enum import Enum from typing import Any, BinaryIO, List, NamedTuple, Optional IS_WINDOWS: bool = os.name == "nt" def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, flush=True, **kwargs) class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" class LintMessage(NamedTuple): path: Optional[str] line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] def as_posix(name: str) -> str: return name.replace("\\", "/") if IS_WINDOWS else name def _run_command( args: List[str], *, stdin: BinaryIO, timeout: int, ) -> "subprocess.CompletedProcess[bytes]": logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=IS_WINDOWS, # So batch scripts are found. timeout=timeout, check=True, ) finally: end_time = time.monotonic() logging.debug("took %dms", (end_time - start_time) * 1000) def run_command( args: List[str], *, stdin: BinaryIO, retries: int, timeout: int, ) -> "subprocess.CompletedProcess[bytes]": remaining_retries = retries while True: try: return _run_command(args, stdin=stdin, timeout=timeout) except subprocess.TimeoutExpired as err: if remaining_retries == 0: raise err remaining_retries -= 1 logging.warning( "(%s/%s) Retrying because command failed with: %r", retries - remaining_retries, retries, err, ) time.sleep(1) def check_file( filename: str, retries: int, timeout: int, ) -> List[LintMessage]: try: with open(filename, "rb") as f: original = f.read() with open(filename, "rb") as f: proc = run_command( [sys.executable, "-mblack", "--stdin-filename", filename, "-"], stdin=f, retries=retries, timeout=timeout, ) except subprocess.TimeoutExpired: return [ LintMessage( path=filename, line=None, char=None, code="BLACK", severity=LintSeverity.ERROR, name="timeout", original=None, replacement=None, description=( "black timed out while trying to process a file. " "Please report an issue in pytorch/pytorch with the " "label 'module: lint'" ), ) ] except (OSError, subprocess.CalledProcessError) as err: return [ LintMessage( path=filename, line=None, char=None, code="BLACK", severity=LintSeverity.ADVICE, name="command-failed", original=None, replacement=None, description=( f"Failed due to {err.__class__.__name__}:\n{err}" if not isinstance(err, subprocess.CalledProcessError) else ( "COMMAND (exit code {returncode})\n" "{command}\n\n" "STDERR\n{stderr}\n\n" "STDOUT\n{stdout}" ).format( returncode=err.returncode, command=" ".join(as_posix(x) for x in err.cmd), stderr=err.stderr.decode("utf-8").strip() or "(empty)", stdout=err.stdout.decode("utf-8").strip() or "(empty)", ) ), ) ] replacement = proc.stdout if original == replacement: return [] return [ LintMessage( path=filename, line=None, char=None, code="BLACK", severity=LintSeverity.WARNING, name="format", original=original.decode("utf-8"), replacement=replacement.decode("utf-8"), description="Run `lintrunner -a` to apply this patch.", ) ] def main() -> None: parser = argparse.ArgumentParser( description="Format files with black.", fromfile_prefix_chars="@", ) parser.add_argument( "--retries", default=3, type=int, help="times to retry timed out black", ) parser.add_argument( "--timeout", default=90, type=int, help="seconds to wait for black", ) parser.add_argument( "--verbose", action="store_true", help="verbose logging", ) parser.add_argument( "filenames", nargs="+", help="paths to lint", ) args = parser.parse_args() logging.basicConfig( format="<%(threadName)s:%(levelname)s> %(message)s", level=logging.NOTSET if args.verbose else logging.DEBUG if len(args.filenames) < 1000 else logging.INFO, stream=sys.stderr, ) with concurrent.futures.ThreadPoolExecutor( max_workers=os.cpu_count(), thread_name_prefix="Thread", ) as executor: futures = { executor.submit(check_file, x, args.retries, args.timeout): x for x in args.filenames } for future in concurrent.futures.as_completed(futures): try: for lint_message in future.result(): print(json.dumps(lint_message._asdict()), flush=True) except Exception: logging.critical('Failed at "%s".', futures[future]) raise if __name__ == "__main__": main()
pytorch-master
tools/linter/adapters/black_linter.py