code
stringlengths
17
6.64M
class CelebA5bit(object): LOC = 'data/celebahq64_5bit/celeba_full_64x64_5bit.pth' def __init__(self, train=True, transform=None): self.dataset = torch.load(self.LOC).float().div(31) if (not train): self.dataset = self.dataset[:5000] self.transform = transform def __le...
class CelebAHQ(Dataset): TRAIN_LOC = 'data/celebahq/celeba256_train.pth' TEST_LOC = 'data/celebahq/celeba256_validation.pth' def __init__(self, train=True, transform=None): return super(CelebAHQ, self).__init__((self.TRAIN_LOC if train else self.TEST_LOC), transform)
class Imagenet32(Dataset): TRAIN_LOC = 'data/imagenet32/train_32x32.pth' TEST_LOC = 'data/imagenet32/valid_32x32.pth' def __init__(self, train=True, transform=None): return super(Imagenet32, self).__init__((self.TRAIN_LOC if train else self.TEST_LOC), transform)
class Imagenet64(Dataset): TRAIN_LOC = 'data/imagenet64/train_64x64.pth' TEST_LOC = 'data/imagenet64/valid_64x64.pth' def __init__(self, train=True, transform=None): return super(Imagenet64, self).__init__((self.TRAIN_LOC if train else self.TEST_LOC), transform, in_mem=False)
class ActNormNd(nn.Module): def __init__(self, num_features, eps=1e-12): super(ActNormNd, self).__init__() self.num_features = num_features self.eps = eps self.weight = Parameter(torch.Tensor(num_features)) self.bias = Parameter(torch.Tensor(num_features)) self.reg...
class ActNorm1d(ActNormNd): @property def shape(self): return [1, (- 1)]
class ActNorm2d(ActNormNd): @property def shape(self): return [1, (- 1), 1, 1]
class Identity(nn.Module): def forward(self, x): return x
class FullSort(nn.Module): def forward(self, x): return torch.sort(x, 1)[0]
class MaxMin(nn.Module): def forward(self, x): (b, d) = x.shape max_vals = torch.max(x.view(b, (d // 2), 2), 2)[0] min_vals = torch.min(x.view(b, (d // 2), 2), 2)[0] return torch.cat([max_vals, min_vals], 1)
class LipschitzCube(nn.Module): def forward(self, x): return ((((x >= 1).to(x) * (x - (2 / 3))) + ((x <= (- 1)).to(x) * (x + (2 / 3)))) + ((((x > (- 1)) * (x < 1)).to(x) * (x ** 3)) / 3))
class SwishFn(torch.autograd.Function): @staticmethod def forward(ctx, x, beta): beta_sigm = torch.sigmoid((beta * x)) output = (x * beta_sigm) ctx.save_for_backward(x, output, beta) return (output / 1.1) @staticmethod def backward(ctx, grad_output): (x, outpu...
class Swish(nn.Module): def __init__(self): super(Swish, self).__init__() self.beta = nn.Parameter(torch.tensor([0.5])) def forward(self, x): return (x * torch.sigmoid_((x * F.softplus(self.beta)))).div_(1.1)
class SpectralNormLinear(nn.Module): def __init__(self, in_features, out_features, bias=True, coeff=0.97, n_iterations=None, atol=None, rtol=None, **unused_kwargs): del unused_kwargs super(SpectralNormLinear, self).__init__() self.in_features = in_features self.out_features = out_...
class SpectralNormConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True, coeff=0.97, n_iterations=None, atol=None, rtol=None, **unused_kwargs): del unused_kwargs super(SpectralNormConv2d, self).__init__() self.in_channels = in_channels ...
class LopLinear(nn.Linear): 'Lipschitz constant defined using operator norms.' def __init__(self, in_features, out_features, bias=True, coeff=0.97, domain=float('inf'), codomain=float('inf'), local_constraint=True, **unused_kwargs): del unused_kwargs super(LopLinear, self).__init__(in_feature...
class LopConv2d(nn.Conv2d): 'Lipschitz constant defined using operator norms.' def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True, coeff=0.97, domain=float('inf'), codomain=float('inf'), local_constraint=True, **unused_kwargs): del unused_kwargs super(LopCon...
class LipNormLinear(nn.Linear): 'Lipschitz constant defined using operator norms.' def __init__(self, in_features, out_features, bias=True, coeff=0.97, domain=float('inf'), codomain=float('inf'), local_constraint=True, **unused_kwargs): del unused_kwargs super(LipNormLinear, self).__init__(in...
class LipNormConv2d(nn.Conv2d): 'Lipschitz constant defined using operator norms.' def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True, coeff=0.97, domain=float('inf'), codomain=float('inf'), local_constraint=True, **unused_kwargs): del unused_kwargs super(Li...
def _logit(p): p = torch.max((torch.ones(1) * 0.1), torch.min((torch.ones(1) * 0.9), p)) return (torch.log((p + 1e-10)) + torch.log(((1 - p) + 1e-10)))
def _norm_except_dim(w, norm_type, dim): if ((norm_type == 1) or (norm_type == 2)): return torch.norm_except_dim(w, norm_type, dim) elif (norm_type == float('inf')): return _max_except_dim(w, dim)
def _max_except_dim(input, dim): maxed = input for axis in range((input.ndimension() - 1), dim, (- 1)): (maxed, _) = maxed.max(axis, keepdim=True) for axis in range((dim - 1), (- 1), (- 1)): (maxed, _) = maxed.max(axis, keepdim=True) return maxed
def operator_norm_settings(domain, codomain): if ((domain == 1) and (codomain == 1)): max_across_input_dims = True norm_type = 1 elif ((domain == 1) and (codomain == 2)): max_across_input_dims = True norm_type = 2 elif ((domain == 1) and (codomain == float('inf'))): ...
def get_linear(in_features, out_features, bias=True, coeff=0.97, domain=None, codomain=None, **kwargs): _linear = InducedNormLinear if (domain == 1): if (codomain in [1, 2, float('inf')]): _linear = LopLinear elif (codomain == float('inf')): if (domain in [2, float('inf')]): ...
def get_conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=True, coeff=0.97, domain=None, codomain=None, **kwargs): _conv2d = InducedNormConv2d if (domain == 1): if (codomain in [1, 2, float('inf')]): _conv2d = LopConv2d elif (codomain == float('inf')): if (do...
class InducedNormLinear(nn.Module): def __init__(self, in_features, out_features, bias=True, coeff=0.97, domain=2, codomain=2, n_iterations=None, atol=None, rtol=None, zero_init=False, **unused_kwargs): del unused_kwargs super(InducedNormLinear, self).__init__() self.in_features = in_feat...
class InducedNormConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True, coeff=0.97, domain=2, codomain=2, n_iterations=None, atol=None, rtol=None, **unused_kwargs): del unused_kwargs super(InducedNormConv2d, self).__init__() self.in_chann...
def projmax_(v): 'Inplace argmax on absolute value.' ind = torch.argmax(torch.abs(v)) v.zero_() v[ind] = 1 return v
def normalize_v(v, domain, out=None): if ((not torch.is_tensor(domain)) and (domain == 2)): v = F.normalize(v, p=2, dim=0, out=out) elif (domain == 1): v = projmax_(v) else: vabs = torch.abs(v) vph = (v / vabs) vph[torch.isnan(vph)] = 1 vabs = (vabs / torch....
def normalize_u(u, codomain, out=None): if ((not torch.is_tensor(codomain)) and (codomain == 2)): u = F.normalize(u, p=2, dim=0, out=out) elif (codomain == float('inf')): u = projmax_(u) else: uabs = torch.abs(u) uph = (u / uabs) uph[torch.isnan(uph)] = 1 ua...
def vector_norm(x, p): x = x.view((- 1)) return (torch.sum((x ** p)) ** (1 / p))
def leaky_elu(x, a=0.3): return ((a * x) + ((1 - a) * F.elu(x)))
def asym_squash(x): return ((torch.tanh((- leaky_elu(((- x) + 0.5493061829986572)))) * 2) + 3)
def _ntuple(n): def parse(x): if isinstance(x, container_abcs.Iterable): return x return tuple(repeat(x, n)) return parse
def _ntuple(n): def parse(x): if isinstance(x, container_abcs.Iterable): return x return tuple(repeat(x, n)) return parse
class SequentialFlow(nn.Module): 'A generalized nn.Sequential container for normalizing flows.\n ' def __init__(self, layersList): super(SequentialFlow, self).__init__() self.chain = nn.ModuleList(layersList) def forward(self, x, logpx=None): if (logpx is None): fo...
class Inverse(nn.Module): def __init__(self, flow): super(Inverse, self).__init__() self.flow = flow def forward(self, x, logpx=None): return self.flow.inverse(x, logpx) def inverse(self, y, logpy=None): return self.flow.forward(y, logpy)
class InvertibleLinear(nn.Module): def __init__(self, dim): super(InvertibleLinear, self).__init__() self.dim = dim self.weight = nn.Parameter(torch.eye(dim)[torch.randperm(dim)]) def forward(self, x, logpx=None): y = F.linear(x, self.weight) if (logpx is None): ...
class InvertibleConv2d(nn.Module): def __init__(self, dim): super(InvertibleConv2d, self).__init__() self.dim = dim self.weight = nn.Parameter(torch.eye(dim)[torch.randperm(dim)]) def forward(self, x, logpx=None): y = F.conv2d(x, self.weight.view(self.dim, self.dim, 1, 1)) ...
class MovingBatchNormNd(nn.Module): def __init__(self, num_features, eps=0.0001, decay=0.1, bn_lag=0.0, affine=True): super(MovingBatchNormNd, self).__init__() self.num_features = num_features self.affine = affine self.eps = eps self.decay = decay self.bn_lag = bn_...
class MovingBatchNorm1d(MovingBatchNormNd): @property def shape(self): return [1, (- 1)]
class MovingBatchNorm2d(MovingBatchNormNd): @property def shape(self): return [1, (- 1), 1, 1]
class SqueezeLayer(nn.Module): def __init__(self, downscale_factor): super(SqueezeLayer, self).__init__() self.downscale_factor = downscale_factor def forward(self, x, logpx=None): squeeze_x = squeeze(x, self.downscale_factor) if (logpx is None): return squeeze_x ...
def unsqueeze(input, upscale_factor=2): return torch.pixel_shuffle(input, upscale_factor)
def squeeze(input, downscale_factor=2): '\n [:, C, H*r, W*r] -> [:, C*r^2, H, W]\n ' (batch_size, in_channels, in_height, in_width) = input.shape out_channels = (in_channels * (downscale_factor ** 2)) out_height = (in_height // downscale_factor) out_width = (in_width // downscale_factor) ...
class CosineAnnealingWarmRestarts(_LRScheduler): 'Set the learning rate of each parameter group using a cosine annealing\n schedule, where :math:`\\eta_{max}` is set to the initial lr, :math:`T_{cur}`\n is the number of epochs since the last restart and :math:`T_{i}` is the number\n of epochs between two...
class Adam(Optimizer): 'Implements Adam algorithm.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1...
class Adamax(Optimizer): 'Implements Adamax algorithm (a variant of Adam based on infinity norm).\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`__.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n ...
class RMSprop(Optimizer): 'Implements RMSprop algorithm.\n\n Proposed by G. Hinton in his\n `course <http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf>`_.\n\n The centered version first appears in `Generating Sequences\n With Recurrent Neural Networks <https://arxiv.org/pdf/1308....
def makedirs(dirname): if (not os.path.exists(dirname)): os.makedirs(dirname)
def get_logger(logpath, filepath, package_files=[], displaying=True, saving=True, debug=False): logger = logging.getLogger() if debug: level = logging.DEBUG else: level = logging.INFO logger.setLevel(level) if saving: info_file_handler = logging.FileHandler(logpath, mode='a...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
class RunningAverageMeter(object): 'Computes and stores the average and current value' def __init__(self, momentum=0.99): self.momentum = momentum self.reset() def reset(self): self.val = None self.avg = 0 def update(self, val): if (self.val is None): ...
def inf_generator(iterable): 'Allows training with DataLoaders in a single infinite loop:\n for i, (x, y) in enumerate(inf_generator(train_loader)):\n ' iterator = iterable.__iter__() while True: try: (yield iterator.__next__()) except StopIteration: itera...
def save_checkpoint(state, save, epoch, last_checkpoints=None, num_checkpoints=None): if (not os.path.exists(save)): os.makedirs(save) filename = os.path.join(save, ('checkpt-%04d.pth' % epoch)) torch.save(state, filename) if ((last_checkpoints is not None) and (num_checkpoints is not None)): ...
def isnan(tensor): return (tensor != tensor)
def logsumexp(value, dim=None, keepdim=False): 'Numerically stable implementation of the operation\n value.exp().sum(dim, keepdim).log()\n ' if (dim is not None): (m, _) = torch.max(value, dim=dim, keepdim=True) value0 = (value - m) if (keepdim is False): m = m.squeez...
class ExponentialMovingAverage(object): def __init__(self, module, decay=0.999): 'Initializes the model when .apply() is called the first time.\n This is to take into account data-dependent initialization that occurs in the first iteration.' self.module = module self.decay = decay ...
def count_parameters(model): return sum((p.numel() for p in model.parameters() if p.requires_grad))
def standard_normal_sample(size): return torch.randn(size)
def standard_normal_logprob(z): logZ = ((- 0.5) * math.log((2 * math.pi))) return (logZ - (z.pow(2) / 2))
def compute_loss(args, model, batch_size=None, beta=1.0): if (batch_size is None): batch_size = args.batch_size x = toy_data.inf_train_gen(args.data, batch_size=batch_size) x = torch.from_numpy(x).type(torch.float32).to(device) zero = torch.zeros(x.shape[0], 1).to(x) (z, delta_logp) = mode...
def parse_vnorms(): ps = [] for p in args.vnorms: if (p == 'f'): ps.append(float('inf')) else: ps.append(float(p)) return (ps[:(- 1)], ps[1:])
def compute_p_grads(model): scales = 0.0 nlayers = 0 for m in model.modules(): if (isinstance(m, base_layers.InducedNormConv2d) or isinstance(m, base_layers.InducedNormLinear)): scales = (scales + m.compute_one_iter()) nlayers += 1 scales.mul((1 / nlayers)).mul(0.01).ba...
def build_nnet(dims, activation_fn=torch.nn.ReLU): nnet = [] (domains, codomains) = parse_vnorms() if args.learn_p: if args.mixed: domains = [torch.nn.Parameter(torch.tensor(0.0)) for _ in domains] else: domains = ([torch.nn.Parameter(torch.tensor(0.0))] * len(domai...
def update_lipschitz(model, n_iterations): for m in model.modules(): if (isinstance(m, base_layers.SpectralNormConv2d) or isinstance(m, base_layers.SpectralNormLinear)): m.compute_weight(update=True, n_iterations=n_iterations) if (isinstance(m, base_layers.InducedNormConv2d) or isinsta...
def get_ords(model): ords = [] for m in model.modules(): if (isinstance(m, base_layers.InducedNormConv2d) or isinstance(m, base_layers.InducedNormLinear)): (domain, codomain) = m.compute_domain_codomain() if torch.is_tensor(domain): domain = domain.item() ...
def pretty_repr(a): return (('[[' + ','.join(list(map((lambda i: f'{i:.2f}'), a)))) + ']]')
class BSDS300(): '\n A dataset of patches from BSDS300.\n ' class Data(): '\n Constructs the dataset.\n ' def __init__(self, data): self.x = data[:] self.N = self.x.shape[0] def __init__(self): f = h5py.File((datasets.root + 'BSDS300/B...
class GAS(): class Data(): def __init__(self, data): self.x = data.astype(np.float32) self.N = self.x.shape[0] def __init__(self): file = (datasets.root + 'gas/ethylene_CO.pickle') (trn, val, tst) = load_data_and_clean_and_split(file) self.trn = self....
def load_data(file): data = pd.read_pickle(file) data.drop('Meth', axis=1, inplace=True) data.drop('Eth', axis=1, inplace=True) data.drop('Time', axis=1, inplace=True) return data
def get_correlation_numbers(data): C = data.corr() A = (C > 0.98) B = A.as_matrix().sum(axis=1) return B
def load_data_and_clean(file): data = load_data(file) B = get_correlation_numbers(data) while np.any((B > 1)): col_to_remove = np.where((B > 1))[0][0] col_name = data.columns[col_to_remove] data.drop(col_name, axis=1, inplace=True) B = get_correlation_numbers(data) data...
def load_data_and_clean_and_split(file): data = load_data_and_clean(file).as_matrix() N_test = int((0.1 * data.shape[0])) data_test = data[(- N_test):] data_train = data[0:(- N_test)] N_validate = int((0.1 * data_train.shape[0])) data_validate = data_train[(- N_validate):] data_train = dat...
class MINIBOONE(): class Data(): def __init__(self, data): self.x = data.astype(np.float32) self.N = self.x.shape[0] def __init__(self): file = (datasets.root + 'miniboone/data.npy') (trn, val, tst) = load_data_normalised(file) self.trn = self.Data(tr...
def load_data(root_path): data = np.load(root_path) N_test = int((0.1 * data.shape[0])) data_test = data[(- N_test):] data = data[0:(- N_test)] N_validate = int((0.1 * data.shape[0])) data_validate = data[(- N_validate):] data_train = data[0:(- N_validate)] return (data_train, data_val...
def load_data_normalised(root_path): (data_train, data_validate, data_test) = load_data(root_path) data = np.vstack((data_train, data_validate)) mu = data.mean(axis=0) s = data.std(axis=0) data_train = ((data_train - mu) / s) data_validate = ((data_validate - mu) / s) data_test = ((data_te...
class POWER(): class Data(): def __init__(self, data): self.x = data.astype(np.float32) self.N = self.x.shape[0] def __init__(self): (trn, val, tst) = load_data_normalised() self.trn = self.Data(trn) self.val = self.Data(val) self.tst = self.D...
def load_data(): return np.load((datasets.root + 'power/data.npy'))
def load_data_split_with_noise(): rng = np.random.RandomState(42) data = load_data() rng.shuffle(data) N = data.shape[0] data = np.delete(data, 3, axis=1) data = np.delete(data, 1, axis=1) voltage_noise = (0.01 * rng.rand(N, 1)) gap_noise = (0.001 * rng.rand(N, 1)) sm_noise = rng.r...
def load_data_normalised(): (data_train, data_validate, data_test) = load_data_split_with_noise() data = np.vstack((data_train, data_validate)) mu = data.mean(axis=0) s = data.std(axis=0) data_train = ((data_train - mu) / s) data_validate = ((data_validate - mu) / s) data_test = ((data_tes...
def get_losses(filename): with open(filename, 'r') as f: lines = f.readlines() losses = [] for line in lines: w = re.findall('Bit/dim [^|(]*\\([0-9\\.]*\\)', line) if w: w = re.findall('\\([0-9\\.]*\\)', w[0]) if w: w = re.findall('[0-9\\.]+', w[0]) ...
def get_values(filename): with open(filename, 'r') as f: lines = f.readlines() losses = [] nfes = [] for line in lines: w = re.findall('Steps [^|(]*\\([0-9\\.]*\\)', line) if w: w = re.findall('\\([0-9\\.]*\\)', w[0]) if w: w = re.findall('[0-9\\...
def construct_discrete_model(): chain = [] for i in range(args.depth): if args.glow: chain.append(layers.BruteForceLayer(2)) chain.append(layers.CouplingLayer(2, swap=((i % 2) == 0))) return layers.SequentialFlow(chain)
def get_transforms(model): def sample_fn(z, logpz=None): if (logpz is not None): return model(z, logpz, reverse=True) else: return model(z, reverse=True) def density_fn(x, logpx=None): if (logpx is not None): return model(x, logpx, reverse=False) ...
def get_values(filename): with open(filename, 'r') as f: lines = f.readlines() losses = [] nfes = [] for line in lines: w = re.findall('Steps [^|(]*\\([0-9\\.]*\\)', line) if w: w = re.findall('\\([0-9\\.]*\\)', w[0]) if w: w = re.findall('[0-9\\...
def log_to_csv(log_filename, csv_filename): with open(log_filename, 'r') as f: lines = f.readlines() with open(csv_filename, 'w', newline='') as csvfile: fieldnames = None writer = None for line in lines: if line.startswith('Iter'): quants = _line_to...
def _line_to_dict(line): line = re.sub(':', '', line) line = re.sub('\\([^)]*\\)', '', line) quants = {} for quant_str in line.split('|'): quant_str = quant_str.strip() (key, val) = quant_str.split(' ') quants[key] = val return quants
def plot_pairplot(csv_filename, fig_filename, top=None): import seaborn as sns import pandas as pd sns.set(style='ticks', color_codes=True) quants = pd.read_csv(csv_filename) if (top is not None): quants = quants[:top] g = sns.pairplot(quants, kind='reg', diag_kind='kde', markers='.') ...
def add_noise(x): '\n [0, 1] -> [0, 255] -> add noise -> [0, 1]\n ' noise = x.new().resize_as_(x).uniform_() x = ((x * 255) + noise) x = (x / 256) return x
def get_dataset(args): trans = (lambda im_size: tforms.Compose([tforms.Resize(im_size), tforms.ToTensor(), add_noise])) if (args.data == 'mnist'): im_dim = 1 im_size = (28 if (args.imagesize is None) else args.imagesize) train_set = dset.MNIST(root='./data', train=True, transform=trans...
def add_spectral_norm(model): def recursive_apply_sn(parent_module): for child_name in list(parent_module._modules.keys()): child_module = parent_module._modules[child_name] classname = child_module.__class__.__name__ if ((classname.find('Conv') != (- 1)) and ('weight'...
def build_model(args, state_dict): (train_loader, test_loader, data_shape) = get_dataset(args) hidden_dims = tuple(map(int, args.dims.split(','))) strides = tuple(map(int, args.strides.split(','))) if args.autoencode: def build_cnf(): autoencoder_diffeq = layers.AutoencoderDiffEqN...
class Adam(Optimizer): 'Implements Adam algorithm.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1...
class Dataset(object): def __init__(self, loc, transform=None): self.dataset = torch.load(loc).float().div(255) self.transform = transform def __len__(self): return self.dataset.size(0) @property def ndim(self): return self.dataset.size(1) def __getitem__(self, ...
class CelebA(Dataset): TRAIN_LOC = 'data/celeba/celeba_train.pth' VAL_LOC = 'data/celeba/celeba_val.pth' def __init__(self, train=True, transform=None): return super(CelebA, self).__init__((self.TRAIN_LOC if train else self.VAL_LOC), transform)
class CNF(nn.Module): def __init__(self, odefunc, T=1.0, train_T=False, regularization_fns=None, solver='dopri5', atol=1e-05, rtol=1e-05): super(CNF, self).__init__() if train_T: self.register_parameter('sqrt_end_time', nn.Parameter(torch.sqrt(torch.tensor(T)))) else: ...
def _flip(x, dim): indices = ([slice(None)] * x.dim()) indices[dim] = torch.arange((x.size(dim) - 1), (- 1), (- 1), dtype=torch.long, device=x.device) return x[tuple(indices)]
class SequentialFlow(nn.Module): 'A generalized nn.Sequential container for normalizing flows.\n ' def __init__(self, layersList): super(SequentialFlow, self).__init__() self.chain = nn.ModuleList(layersList) def forward(self, x, logpx=None, reverse=False, inds=None): if (inds...
class SequentialDiffEq(nn.Module): 'A container for a sequential chain of layers. Supports both regular and diffeq layers.\n ' def __init__(self, *layers): super(SequentialDiffEq, self).__init__() self.layers = nn.ModuleList([diffeq_wrapper(layer) for layer in layers]) def forward(sel...