code
stringlengths
17
6.64M
def _unsqueeze_ft(tensor): 'add new dementions at the front and the tail' return tensor.unsqueeze(0).unsqueeze((- 1))
class _SynchronizedBatchNorm(_BatchNorm): def __init__(self, num_features, eps=1e-05, momentum=0.001, affine=True): super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine) self._sync_master = SyncMaster(self._data_parallel_master) self._is_par...
class SynchronizedBatchNorm1d(_SynchronizedBatchNorm): "Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a\n mini-batch.\n\n .. math::\n\n y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n\n This module differs from the built-in PyTorch BatchNorm1d...
class SynchronizedBatchNorm2d(_SynchronizedBatchNorm): "Applies Batch Normalization over a 4d input that is seen as a mini-batch\n of 3d inputs\n\n .. math::\n\n y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n\n This module differs from the built-in PyTorch BatchNorm2d as the...
class SynchronizedBatchNorm3d(_SynchronizedBatchNorm): "Applies Batch Normalization over a 5d input that is seen as a mini-batch\n of 4d inputs\n\n .. math::\n\n y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n\n This module differs from the built-in PyTorch BatchNorm3d as the...
class FutureResult(object): 'A thread-safe future implementation. Used only as one-to-one pipe.' def __init__(self): self._result = None self._lock = threading.Lock() self._cond = threading.Condition(self._lock) def put(self, result): with self._lock: assert (...
class SlavePipe(_SlavePipeBase): 'Pipe for master-slave communication.' def run_slave(self, msg): self.queue.put((self.identifier, msg)) ret = self.result.get() self.queue.put(True) return ret
class SyncMaster(object): 'An abstract `SyncMaster` object.\n\n - During the replication, as the data parallel will trigger an callback of each module, all slave devices should\n call `register(id)` and obtain an `SlavePipe` to communicate with the master.\n - During the forward pass, master device invok...
class CallbackContext(object): pass
def execute_replication_callbacks(modules): '\n Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.\n\n The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`\n\n Note that, as all modules are isomorphism, we assig...
class DataParallelWithCallback(DataParallel): '\n Data Parallel with a replication callback.\n\n An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by\n original `replicate` function.\n The callback will be invoked with arguments `__data_parallel_r...
def patch_replication_callback(data_parallel): '\n Monkey-patch an existing `DataParallel` object. Add the replication callback.\n Useful when you have customized `DataParallel` implementation.\n\n Examples:\n > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)\n > sync_bn = Dat...
def handy_var(a, unbias=True): n = a.size(0) asum = a.sum(dim=0) as_sum = (a ** 2).sum(dim=0) sumvar = (as_sum - ((asum * asum) / n)) if unbias: return (sumvar / (n - 1)) else: return (sumvar / n)
class NumericTestCase(TorchTestCase): def testNumericBatchNorm(self): a = torch.rand(16, 10) bn = nn.BatchNorm2d(10, momentum=1, eps=1e-05, affine=False) bn.train() a_var1 = Variable(a, requires_grad=True) b_var1 = bn(a_var1) loss1 = b_var1.sum() loss1.back...
def handy_var(a, unbias=True): n = a.size(0) asum = a.sum(dim=0) as_sum = (a ** 2).sum(dim=0) sumvar = (as_sum - ((asum * asum) / n)) if unbias: return (sumvar / (n - 1)) else: return (sumvar / n)
def _find_bn(module): for m in module.modules(): if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, SynchronizedBatchNorm1d, SynchronizedBatchNorm2d)): return m
class SyncTestCase(TorchTestCase): def _syncParameters(self, bn1, bn2): bn1.reset_parameters() bn2.reset_parameters() if (bn1.affine and bn2.affine): bn2.weight.data.copy_(bn1.weight.data) bn2.bias.data.copy_(bn1.bias.data) def _checkBatchNormResult(self, bn1,...
def as_numpy(v): if isinstance(v, Variable): v = v.data return v.cpu().numpy()
class TorchTestCase(unittest.TestCase): def assertTensorClose(self, a, b, atol=0.001, rtol=0.001): (npa, npb) = (as_numpy(a), as_numpy(b)) self.assertTrue(np.allclose(npa, npb, atol=atol), 'Tensor close check failed\n{}\n{}\nadiff={}, rdiff={}'.format(a, b, np.abs((npa - npb)).max(), np.abs(((npa...
def async_copy_to(obj, dev, main_stream=None): if torch.is_tensor(obj): v = obj.cuda(dev, non_blocking=True) if (main_stream is not None): v.data.record_stream(main_stream) return v elif isinstance(obj, collections.Mapping): return {k: async_copy_to(o, dev, main_str...
def dict_gather(outputs, target_device, dim=0): '\n Gathers variables from different GPUs on a specified device\n (-1 means the CPU), with dictionary support.\n ' def gather_map(outputs): out = outputs[0] if torch.is_tensor(out): if (out.dim() == 0): out...
class DictGatherDataParallel(nn.DataParallel): def gather(self, outputs, output_device): return dict_gather(outputs, output_device, dim=self.dim)
class UserScatteredDataParallel(DictGatherDataParallel): def scatter(self, inputs, kwargs, device_ids): assert (len(inputs) == 1) inputs = inputs[0] inputs = _async_copy_stream(inputs, device_ids) inputs = [[i] for i in inputs] assert (len(kwargs) == 0) kwargs = [{...
def user_scattered_collate(batch): return batch
def _async_copy(inputs, device_ids): nr_devs = len(device_ids) assert (type(inputs) in (tuple, list)) assert (len(inputs) == nr_devs) outputs = [] for (i, dev) in zip(inputs, device_ids): with cuda.device(dev): outputs.append(async_copy_to(i, dev)) return tuple(outputs)
def _async_copy_stream(inputs, device_ids): nr_devs = len(device_ids) assert (type(inputs) in (tuple, list)) assert (len(inputs) == nr_devs) outputs = [] streams = [_get_stream(d) for d in device_ids] for (i, dev, stream) in zip(inputs, device_ids, streams): with cuda.device(dev): ...
def _get_stream(device): 'Gets a background stream for copying between CPU and GPU' global _streams if (device == (- 1)): return None if (_streams is None): _streams = ([None] * cuda.device_count()) if (_streams[device] is None): _streams[device] = cuda.Stream(device) r...
class ExceptionWrapper(object): 'Wraps an exception plus traceback to communicate across threads' def __init__(self, exc_info): self.exc_type = exc_info[0] self.exc_msg = ''.join(traceback.format_exception(*exc_info))
def _worker_loop(dataset, index_queue, data_queue, collate_fn, seed, init_fn, worker_id): global _use_shared_memory _use_shared_memory = True _set_worker_signal_handlers() torch.set_num_threads(1) torch.manual_seed(seed) np.random.seed(seed) if (init_fn is not None): init_fn(worker...
def _worker_manager_loop(in_queue, out_queue, done_event, pin_memory, device_id): if pin_memory: torch.cuda.set_device(device_id) while True: try: r = in_queue.get() except Exception: if done_event.is_set(): return raise if (r...
def default_collate(batch): 'Puts each data field into a tensor with outer dimension batch size' error_msg = 'batch must contain tensors, numbers, dicts or lists; found {}' elem_type = type(batch[0]) if torch.is_tensor(batch[0]): out = None if _use_shared_memory: numel = su...
def pin_memory_batch(batch): if torch.is_tensor(batch): return batch.pin_memory() elif isinstance(batch, string_classes): return batch elif isinstance(batch, collections.Mapping): return {k: pin_memory_batch(sample) for (k, sample) in batch.items()} elif isinstance(batch, colle...
def _set_SIGCHLD_handler(): if (sys.platform == 'win32'): return if (not isinstance(threading.current_thread(), threading._MainThread)): return global _SIGCHLD_handler_set if _SIGCHLD_handler_set: return previous_handler = signal.getsignal(signal.SIGCHLD) if (not callab...
class DataLoaderIter(object): "Iterates once over the DataLoader's dataset, as specified by the sampler" def __init__(self, loader): self.dataset = loader.dataset self.collate_fn = loader.collate_fn self.batch_sampler = loader.batch_sampler self.num_workers = loader.num_worker...
class DataLoader(object): "\n Data loader. Combines a dataset and a sampler, and provides\n single- or multi-process iterators over the dataset.\n\n Arguments:\n dataset (Dataset): dataset from which to load the data.\n batch_size (int, optional): how many samples per batch to load\n ...
class Dataset(object): 'An abstract class representing a Dataset.\n\n All other datasets should subclass it. All subclasses should override\n ``__len__``, that provides the size of the dataset, and ``__getitem__``,\n supporting integer indexing in range from 0 to len(self) exclusive.\n ' def __ge...
class TensorDataset(Dataset): 'Dataset wrapping data and target tensors.\n\n Each sample will be retrieved by indexing both tensors along the first\n dimension.\n\n Arguments:\n data_tensor (Tensor): contains sample data.\n target_tensor (Tensor): contains sample targets (labels).\n ' ...
class ConcatDataset(Dataset): '\n Dataset to concatenate multiple datasets.\n Purpose: useful to assemble different existing datasets, possibly\n large-scale datasets as the concatenation operation is done in an\n on-the-fly manner.\n\n Arguments:\n datasets (iterable): List of datasets to b...
class Subset(Dataset): def __init__(self, dataset, indices): self.dataset = dataset self.indices = indices def __getitem__(self, idx): return self.dataset[self.indices[idx]] def __len__(self): return len(self.indices)
def random_split(dataset, lengths): '\n Randomly split a dataset into non-overlapping new datasets of given lengths\n ds\n\n Arguments:\n dataset (Dataset): Dataset to be split\n lengths (iterable): lengths of splits to be produced\n ' if (sum(lengths) != len(dataset)): raise...
class DistributedSampler(Sampler): 'Sampler that restricts data loading to a subset of the dataset.\n\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n and l...
class Sampler(object): 'Base class for all Samplers.\n\n Every Sampler subclass has to provide an __iter__ method, providing a way\n to iterate over indices of dataset elements, and a __len__ method that\n returns the length of the returned iterators.\n ' def __init__(self, data_source): ...
class SequentialSampler(Sampler): 'Samples elements sequentially, always in the same order.\n\n Arguments:\n data_source (Dataset): dataset to sample from\n ' def __init__(self, data_source): self.data_source = data_source def __iter__(self): return iter(range(len(self.data_...
class RandomSampler(Sampler): 'Samples elements randomly, without replacement.\n\n Arguments:\n data_source (Dataset): dataset to sample from\n ' def __init__(self, data_source): self.data_source = data_source def __iter__(self): return iter(torch.randperm(len(self.data_sour...
class SubsetRandomSampler(Sampler): 'Samples elements randomly from a given list of indices, without replacement.\n\n Arguments:\n indices (list): a list of indices\n ' def __init__(self, indices): self.indices = indices def __iter__(self): return (self.indices[i] for i in t...
class WeightedRandomSampler(Sampler): 'Samples elements from [0,..,len(weights)-1] with given probabilities (weights).\n\n Arguments:\n weights (list) : a list of weights, not necessary summing up to one\n num_samples (int): number of samples to draw\n replacement (bool): if ``True``, sa...
class BatchSampler(object): 'Wraps another sampler to yield a mini-batch of indices.\n\n Args:\n sampler (Sampler): Base sampler.\n batch_size (int): Size of mini-batch.\n drop_last (bool): If ``True``, the sampler will drop the last batch if\n its size would be less than ``batc...
def as_variable(obj): if isinstance(obj, Variable): return obj if isinstance(obj, collections.Sequence): return [as_variable(v) for v in obj] elif isinstance(obj, collections.Mapping): return {k: as_variable(v) for (k, v) in obj.items()} else: return Variable(obj)
def as_numpy(obj): if isinstance(obj, collections.Sequence): return [as_numpy(v) for v in obj] elif isinstance(obj, collections.Mapping): return {k: as_numpy(v) for (k, v) in obj.items()} elif isinstance(obj, Variable): return obj.data.cpu().numpy() elif torch.is_tensor(obj): ...
def mark_volatile(obj): if torch.is_tensor(obj): obj = Variable(obj) if isinstance(obj, Variable): obj.no_grad = True return obj elif isinstance(obj, collections.Mapping): return {k: mark_volatile(o) for (k, o) in obj.items()} elif isinstance(obj, collections.Sequence):...
def make_evaluator(kind='default', ssim=True, lpips=True, fid=True, integral_kind=None, **kwargs): logging.info(f'Make evaluator {kind}') metrics = {} if ssim: metrics['ssim'] = SSIMScore() if lpips: metrics['lpips'] = LPIPSScore() if fid: metrics['fid'] = FIDScore() if...
def load_image(fname, mode='RGB', return_orig=False): img = np.array(Image.open(fname).convert(mode)) if (img.ndim == 3): img = np.transpose(img, (2, 0, 1)) out_img = (img.astype('float32') / 255) if return_orig: return (out_img, img) else: return out_img
def ceil_modulo(x, mod): if ((x % mod) == 0): return x return (((x // mod) + 1) * mod)
def pad_img_to_modulo(img, mod): (channels, height, width) = img.shape out_height = ceil_modulo(height, mod) out_width = ceil_modulo(width, mod) return np.pad(img, ((0, 0), (0, (out_height - height)), (0, (out_width - width))), mode='symmetric')
def pad_tensor_to_modulo(img, mod): (batch_size, channels, height, width) = img.shape out_height = ceil_modulo(height, mod) out_width = ceil_modulo(width, mod) return F.pad(img, pad=(0, (out_width - width), 0, (out_height - height)), mode='reflect')
def scale_image(img, factor, interpolation=cv2.INTER_AREA): if (img.shape[0] == 1): img = img[0] else: img = np.transpose(img, (1, 2, 0)) img = cv2.resize(img, dsize=None, fx=factor, fy=factor, interpolation=interpolation) if (img.ndim == 2): img = img[(None, ...)] else: ...
class InpaintingDataset(Dataset): def __init__(self, datadir, img_suffix='.jpg', pad_out_to_modulo=None, scale_factor=None): self.datadir = datadir self.mask_filenames = sorted(list(glob.glob(os.path.join(self.datadir, '**', '*mask*.png'), recursive=True))) self.img_filenames = [(fname.rs...
class OurInpaintingDataset(Dataset): def __init__(self, datadir, img_suffix='.jpg', pad_out_to_modulo=None, scale_factor=None): self.datadir = datadir self.mask_filenames = sorted(list(glob.glob(os.path.join(self.datadir, 'mask', '**', '*mask*.png'), recursive=True))) self.img_filenames =...
class PrecomputedInpaintingResultsDataset(InpaintingDataset): def __init__(self, datadir, predictdir, inpainted_suffix='_inpainted.jpg', **kwargs): super().__init__(datadir, **kwargs) if (not datadir.endswith('/')): datadir += '/' self.predictdir = predictdir self.pred...
class OurPrecomputedInpaintingResultsDataset(OurInpaintingDataset): def __init__(self, datadir, predictdir, inpainted_suffix='png', **kwargs): super().__init__(datadir, **kwargs) if (not datadir.endswith('/')): datadir += '/' self.predictdir = predictdir self.pred_file...
class InpaintingEvalOnlineDataset(Dataset): def __init__(self, indir, mask_generator, img_suffix='.jpg', pad_out_to_modulo=None, scale_factor=None, **kwargs): self.indir = indir self.mask_generator = mask_generator self.img_filenames = sorted(list(glob.glob(os.path.join(self.indir, '**', ...
class InpaintingEvaluator(): def __init__(self, dataset, scores, area_grouping=True, bins=10, batch_size=32, device='cuda', integral_func=None, integral_title=None, clamp_image_range=None): '\n :param dataset: torch.utils.data.Dataset which contains images and masks\n :param scores: dict {s...
def ssim_fid100_f1(metrics, fid_scale=100): ssim = metrics[('ssim', 'total')]['mean'] fid = metrics[('fid', 'total')]['mean'] fid_rel = (max(0, (fid_scale - fid)) / fid_scale) f1 = (((2 * ssim) * fid_rel) / ((ssim + fid_rel) + 0.001)) return f1
def lpips_fid100_f1(metrics, fid_scale=100): neg_lpips = (1 - metrics[('lpips', 'total')]['mean']) fid = metrics[('fid', 'total')]['mean'] fid_rel = (max(0, (fid_scale - fid)) / fid_scale) f1 = (((2 * neg_lpips) * fid_rel) / ((neg_lpips + fid_rel) + 0.001)) return f1
class InpaintingEvaluatorOnline(nn.Module): def __init__(self, scores, bins=10, image_key='image', inpainted_key='inpainted', integral_func=None, integral_title=None, clamp_image_range=None): '\n :param scores: dict {score_name: EvaluatorScore object}\n :param bins: number of groups, partit...
def get_groupings(groups): '\n :param groups: group numbers for respective elements\n :return: dict of kind {group_idx: indices of the corresponding group elements}\n ' (label_groups, count_groups) = np.unique(groups, return_counts=True) indices = np.argsort(groups) grouping = dict() cur_...
class EvaluatorScore(nn.Module): @abstractmethod def forward(self, pred_batch, target_batch, mask): pass @abstractmethod def get_value(self, groups=None, states=None): pass @abstractmethod def reset(self): pass
class PairwiseScore(EvaluatorScore, ABC): def __init__(self): super().__init__() self.individual_values = None def get_value(self, groups=None, states=None): "\n :param groups:\n :return:\n total_results: dict of kind {'mean': score mean, 'std': score std}\n ...
class SSIMScore(PairwiseScore): def __init__(self, window_size=11): super().__init__() self.score = SSIM(window_size=window_size, size_average=False).eval() self.reset() def forward(self, pred_batch, target_batch, mask=None): batch_values = self.score(pred_batch, target_batch...
class LPIPSScore(PairwiseScore): def __init__(self, model='net-lin', net='vgg', model_path=None, use_gpu=True): super().__init__() self.score = PerceptualLoss(model=model, net=net, model_path=model_path, use_gpu=use_gpu, spatial=False).eval() self.reset() def forward(self, pred_batch...
def fid_calculate_activation_statistics(act): mu = np.mean(act, axis=0) sigma = np.cov(act, rowvar=False) return (mu, sigma)
def calculate_frechet_distance(activations_pred, activations_target, eps=1e-06): (mu1, sigma1) = fid_calculate_activation_statistics(activations_pred) (mu2, sigma2) = fid_calculate_activation_statistics(activations_target) diff = (mu1 - mu2) (covmean, _) = linalg.sqrtm(sigma1.dot(sigma2), disp=False) ...
class FIDScore(EvaluatorScore): def __init__(self, dims=2048, eps=1e-06): LOGGER.info('FIDscore init called') super().__init__() if (getattr(FIDScore, '_MODEL', None) is None): block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] FIDScore._MODEL = InceptionV3([block_id...
class SegmentationAwareScore(EvaluatorScore): def __init__(self, weights_path): super().__init__() self.segm_network = SegmentationModule(weights_path=weights_path, use_default_normalization=True).eval() self.target_class_freq_by_image_total = [] self.target_class_freq_by_image_ma...
def distribute_values_to_classes(target_class_freq_by_image_mask, values, idx2name): assert ((target_class_freq_by_image_mask.ndim == 2) and (target_class_freq_by_image_mask.shape[0] == values.shape[0])) total_class_freq = target_class_freq_by_image_mask.sum(0) distr_values = (target_class_freq_by_image_m...
def get_segmentation_idx2name(): return {(i - 1): name for (i, name) in segm_options['classes'].set_index('Idx', drop=True)['Name'].to_dict().items()}
class SegmentationAwarePairwiseScore(SegmentationAwareScore): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.individual_values = [] self.segm_idx2name = get_segmentation_idx2name() def forward(self, pred_batch, target_batch, mask): cur_class_stats...
class SegmentationClassStats(SegmentationAwarePairwiseScore): def calc_score(self, pred_batch, target_batch, mask): return 0 def get_value(self, groups=None, states=None): "\n :param groups:\n :return:\n total_results: dict of kind {'mean': score mean, 'std': score s...
class SegmentationAwareSSIM(SegmentationAwarePairwiseScore): def __init__(self, *args, window_size=11, **kwargs): super().__init__(*args, **kwargs) self.score_impl = SSIM(window_size=window_size, size_average=False).eval() def calc_score(self, pred_batch, target_batch, mask): return ...
class SegmentationAwareLPIPS(SegmentationAwarePairwiseScore): def __init__(self, *args, model='net-lin', net='vgg', model_path=None, use_gpu=True, **kwargs): super().__init__(*args, **kwargs) self.score_impl = PerceptualLoss(model=model, net=net, model_path=model_path, use_gpu=use_gpu, spatial=Fa...
def calculade_fid_no_img(img_i, activations_pred, activations_target, eps=1e-06): activations_pred = activations_pred.copy() activations_pred[img_i] = activations_target[img_i] return calculate_frechet_distance(activations_pred, activations_target, eps=eps)
class SegmentationAwareFID(SegmentationAwarePairwiseScore): def __init__(self, *args, dims=2048, eps=1e-06, n_jobs=(- 1), **kwargs): super().__init__(*args, **kwargs) if (getattr(FIDScore, '_MODEL', None) is None): block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] FIDScore....
def get_activations(files, model, batch_size=50, dims=2048, cuda=False, verbose=False, keep_size=False): 'Calculates the activations of the pool_3 layer for all images.\n\n Params:\n -- files : List of image files paths\n -- model : Instance of inception model\n -- batch_size : Batch size...
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-06): "Numpy implementation of the Frechet Distance.\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n\n Stable v...
def calculate_activation_statistics(files, model, batch_size=50, dims=2048, cuda=False, verbose=False, keep_size=False): 'Calculation of the statistics used by the FID.\n Params:\n -- files : List of image files paths\n -- model : Instance of inception model\n -- batch_size : The images n...
def _compute_statistics_of_path(path, model, batch_size, dims, cuda): if path.endswith('.npz'): f = np.load(path) (m, s) = (f['mu'][:], f['sigma'][:]) f.close() else: path = pathlib.Path(path) files = (list(path.glob('*.jpg')) + list(path.glob('*.png'))) (m, s) ...
def _compute_statistics_of_images(images, model, batch_size, dims, cuda, keep_size=False): if isinstance(images, list): (m, s) = calculate_activation_statistics(images, model, batch_size, dims, cuda, keep_size=keep_size) return (m, s) else: raise ValueError
def calculate_fid_given_paths(paths, batch_size, cuda, dims): 'Calculates the FID of two paths' for p in paths: if (not os.path.exists(p)): raise RuntimeError(('Invalid path: %s' % p)) block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] model = InceptionV3([block_idx]) if cuda: ...
def calculate_fid_given_images(images, batch_size, cuda, dims, use_globals=False, keep_size=False): if use_globals: global FID_MODEL for imgs in images: if (isinstance(imgs, list) and isinstance(imgs[0], (Image.Image, JpegImagePlugin.JpegImageFile))): pass else: ...
class InceptionV3(nn.Module): 'Pretrained InceptionV3 network returning feature maps' DEFAULT_BLOCK_INDEX = 3 BLOCK_INDEX_BY_DIM = {64: 0, 192: 1, 768: 2, 2048: 3} def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=T...
def fid_inception_v3(): "Build pretrained Inception model for FID computation\n\n The Inception model for FID computation uses a different set of weights\n and has a slightly different structure than torchvision's Inception.\n\n This method first constructs torchvision's Inception and then patches the\n ...
class FIDInceptionA(models.inception.InceptionA): 'InceptionA block patched for FID computation' def __init__(self, in_channels, pool_features): super(FIDInceptionA, self).__init__(in_channels, pool_features) def forward(self, x): branch1x1 = self.branch1x1(x) branch5x5 = self.br...
class FIDInceptionC(models.inception.InceptionC): 'InceptionC block patched for FID computation' def __init__(self, in_channels, channels_7x7): super(FIDInceptionC, self).__init__(in_channels, channels_7x7) def forward(self, x): branch1x1 = self.branch1x1(x) branch7x7 = self.bran...
class FIDInceptionE_1(models.inception.InceptionE): 'First InceptionE block patched for FID computation' def __init__(self, in_channels): super(FIDInceptionE_1, self).__init__(in_channels) def forward(self, x): branch1x1 = self.branch1x1(x) branch3x3 = self.branch3x3_1(x) ...
class FIDInceptionE_2(models.inception.InceptionE): 'Second InceptionE block patched for FID computation' def __init__(self, in_channels): super(FIDInceptionE_2, self).__init__(in_channels) def forward(self, x): branch1x1 = self.branch1x1(x) branch3x3 = self.branch3x3_1(x) ...
class SSIM(torch.nn.Module): 'SSIM. Modified from:\n https://github.com/Po-Hsun-Su/pytorch-ssim/blob/master/pytorch_ssim/__init__.py\n ' def __init__(self, window_size=11, size_average=True): super().__init__() self.window_size = window_size self.size_average = size_average ...
def countless5(a, b, c, d, e): "First stage of generalizing from countless2d. \n\n You have five slots: A, B, C, D, E\n\n You can decide if something is the winner by first checking for \n matches of three, then matches of two, then picking just one if \n the other two tries fail. In countless2d, you just che...
def countless8(a, b, c, d, e, f, g, h): 'Extend countless5 to countless8. Same deal, except we also\n need to check for matches of length 4.' sections = [a, b, c, d, e, f, g, h] p2 = (lambda q, r: (q * (q == r))) p3 = (lambda q, r, s: (q * ((q == r) & (r == s)))) p4 = (lambda p, q, r, s: (p * (...
def dynamic_countless3d(data): 'countless8 + dynamic programming. ~2x faster' sections = [] data += 1 factor = (2, 2, 2) for offset in np.ndindex(factor): part = data[tuple((np.s_[o::f] for (o, f) in zip(offset, factor)))] sections.append(part) pick = (lambda a, b: (a * (a == b...
def countless3d(data): 'Now write countless8 in such a way that it could be used\n to process an image.' sections = [] data += 1 factor = (2, 2, 2) for offset in np.ndindex(factor): part = data[tuple((np.s_[o::f] for (o, f) in zip(offset, factor)))] sections.append(part) p2 = ...