code
stringlengths
17
6.64M
class BallQuery(Function): @staticmethod def forward(ctx, radius, nsample, xyz, new_xyz): '\n\n Parameters\n ----------\n radius : float\n radius of the balls\n nsample : int\n maximum number of features in the balls\n xyz : torch.Tensor\n ...
class QueryAndGroup(nn.Module): '\n Groups with a ball query of radius\n\n Parameters\n ---------\n radius : float32\n Radius of ball\n nsample : int32\n Maximum number of features to gather in the ball\n ' def __init__(self, radius, nsample, use_xyz=True): super(Query...
class GroupAll(nn.Module): '\n Groups all features\n\n Parameters\n ---------\n ' def __init__(self, use_xyz=True): super(GroupAll, self).__init__() self.use_xyz = use_xyz def forward(self, xyz, new_xyz, features=None): '\n Parameters\n ----------\n ...
class HiddenPrints(): def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout
def multiprocess(func): p = Pool(80) p.map(func, idx_list) p.close() p.join()
def pds(idx): if 1: print(os.path.join(save_path_list[idx], ('%d.npy' % num_point)), ' is preparing.') ms_set = pymeshlab.MeshSet() ms_set.load_new_mesh(os.path.join(os.path.join(path_list[idx], 'scaled_model.off'))) ms_set.generate_sampling_poisson_disk(samplenum=int((num_point / ...
class HiddenPrints(): def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout
def multiprocess(func): p = Pool(20) p.map(func, idx_list) p.close() p.join()
def sample(idx): mesh = trimesh.load(os.path.join(path_list[idx], 'scaled_model.off')) points = mesh.sample(int(num_sample)) if (not os.path.exists(save_path_list[idx])): os.makedirs(os.path.join(save_path_list[idx])) np.save(os.path.join(save_path_list[idx], 'points.npy'), points.astype(np.fl...
class HiddenPrints(): def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout
def multiprocess(func): p = Pool(20) p.map(func, idx_list) p.close() p.join()
def sample(idx): if 1: boundary_points_list = [] df_list = [] closest_points_list = [] for i in range(3): ratio = ratio_list[i] std = std_list[i] mesh = trimesh.load(os.path.join(path_list[idx], 'scaled_model.off')) points = mesh.samp...
def as_mesh(scene_or_mesh): '\n Convert a possible scene to a mesh.\n\n If conversion occurs, the returned mesh has only vertex and face data.\n Suggested by https://github.com/mikedh/trimesh/issues/507\n ' if isinstance(scene_or_mesh, trimesh.Scene): if (len(scene_or_mesh.geometry) == 0):...
def scalled_off(idx): input = trimesh.load(os.path.join(base_path_1[idx], 'isosurf.obj')) mesh = as_mesh(input) total_size = (mesh.bounds[1] - mesh.bounds[0]).max() centers = ((mesh.bounds[1] + mesh.bounds[0]) / 2) mesh.apply_translation((- centers)) mesh.apply_scale((1 / total_size)) if (...
def multiprocess(func): p = Pool(16) p.map(func, idx_list) p.close() p.join()
def split(x): return x.lower().split()
def length(sequence): used = tf.sign(tf.reduce_max(tf.abs(sequence), reduction_indices=2)) length = tf.reduce_sum(used, reduction_indices=1) length = tf.cast(length, tf.int32) return length
def cost(output, target): cross_entropy = (target * tf.log(output)) cross_entropy = (- tf.reduce_sum(cross_entropy, reduction_indices=2)) mask = tf.sign(tf.reduce_max(tf.abs(target), reduction_indices=2)) cross_entropy *= mask cross_entropy = tf.reduce_sum(cross_entropy, reduction_indices=1) c...
def activate(outputs, weight_shape, bias_shape, activation=tf.nn.softmax): dim_str = {3: 'ijk,kl->ijl', 2: 'ij,jk->ik'} weights = tf.get_variable('weights', shape=weight_shape, initializer=tf.random_normal_initializer()) biases = tf.get_variable('biases', shape=bias_shape, initializer=tf.constant_initiali...
def rmse_loss(outputs, targets): return tf.sqrt(tf.reduce_mean(tf.square(tf.sub(targets, outputs))))
def pad(x, max_length, pad_constant=(- 1)): x = list(x) for i in range(len(x)): x[i] += ([pad_constant] * (max_length - len(x[i]))) x[i] = np.array(x[i]) return x
def get_batch_pos(obj, size=5): idx = np.random.choice(range(len(obj.sent)), size=size, replace=False) p = pad(obj.pos[idx], obj.max_length, (- 1)) s = pad(obj.sent[idx], obj.max_length, (obj.vec.shape[0] - 1)) c = pad(obj.chun[idx], obj.max_length, (- 1)) return (s, p, c)
def get_batch_sent(obj, size=5): idx = np.random.choice(range(len(obj.sent1)), size=size, replace=False) s1 = pad(obj.sent1[idx], obj.max_length, (obj.vec.shape[0] - 1)) s2 = pad(obj.sent2[idx], obj.max_length, (obj.vec.shape[0] - 1)) r = obj.rel[idx] e = obj.ent[idx] return (s1, s2, r.values,...
class JMT(): def __init__(self, dim, reg_lambda, lr=0.01): self.dim = dim self.reg_lambda = reg_lambda self.lr = lr def load_data(self): data = np.load('data/data.npz')['data'].item() self.sent = data['word_level']['sent'].values self.pos = data['word_level'][...
class MyLSTM(tf.nn.rnn_cell.BasicLSTMCell): def __call__(self, inputs, state, scope=None): 'LSTM as mentioned in paper.' with vs.variable_scope((scope or 'basic_lstm_cell')): if self._state_is_tuple: (c, h) = state else: (c, h) = array_ops.s...
class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.lin0 = nn.Linear(3, nf[0]) self.resnet_block11 = HarmonicResNetBlock(nf[0], nf[0], max_order, n_rings, prev_order=0) self.resnet_block12 = HarmonicResNetBlock(nf[0], nf[0], max_order, n_rings) ...
def train(epoch): model.train() if (epoch == 60): for param_group in optimizer.param_groups: param_group['lr'] = 0.001 for data in progressbar.progressbar(train_loader): data = data.to(device) optimizer.zero_grad() F.nll_loss(model(data), target).backward() ...
def test(): model.eval() correct = 0 for (i, data) in progressbar.progressbar(enumerate(test_loader)): pred = model(data.to(device)).max(1)[1] correct += pred.eq(target).sum().item() return (correct / (len(test_dataset) * num_nodes))
class FAUST(InMemoryDataset): 'The FAUST humans dataset from the `"FAUST: Dataset and Evaluation for\n 3D Mesh Registration"\n <http://files.is.tue.mpg.de/black/papers/FAUST2014.pdf>`_ paper,\n containing 100 watertight meshes representing 10 different poses for 10\n different subjects.\n\n .. note...
class FAUSTRemeshed(InMemoryDataset): 'The remeshed FAUST humans dataset from the paper `Multi-directional\n Geodesic Neural Networks via Equivariant Convolution`\n containing 100 watertight meshes representing 10 different poses for 10\n different subjects.\n\n .. note::\n\n Data objects hold ...
class ShapeSeg(InMemoryDataset): 'The Shape Segmentation dataset proposed by Maron et al. in\n "Convolutional neural networks on surfaces via seamless toric covers"\n <https://dl.acm.org/citation.cfm?id=3073616>`_ ,\n containing meshes from Adobe, SCAPE, FAUST, and MIT for training\n and SHREC shapes ...
class Shrec16(InMemoryDataset): 'The shrec classification dataset.\n\n This is the remeshed version from MeshCNN.\n\n .. note::\n\n Data objects hold mesh faces instead of edge indices.\n To convert the mesh to a graph, use the\n :obj:`torch_geometric.transforms.FaceToEdge` as :obj:`pre...
class ComplexLin(nn.Module): 'A linear layer applied to complex feature vectors\n The result is a linear combination of the complex input features\n\n Args:\n in_channels (int): number of input features\n out_channels (int): number of output features\n ' def __init__(self, in_channels,...
class ComplexNonLin(nn.Module): 'Adds a learned bias and applies the nonlinearity\n given by fnc to the radial component of complex features\n\n Args:\n num_features (int): number of input features\n fnc (torch.nn.Module): non-linearity function\n ' def __init__(self, in_channels, fnc=...
class HarmonicResNetBlock(torch.nn.Module): '\n ResNet block with convolutions, linearities, and non-linearities\n as described in Harmonic Surface Networks\n\n Args:\n in_channels (int): number of input features\n out_channels (int): number of output features\n prev_order (int, opti...
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = HarmonicConv(1, nf[0], max_order, n_rings, prev_order=0) self.nonlin1 = ComplexNonLin(nf[0]) self.conv2 = HarmonicConv(nf[0], nf[0], max_order, n_rings) self.bn1 = nn.BatchNorm1d(((max_order...
def train(epoch): model.train() for param_group in optimizer.param_groups: param_group['lr'] = (param_group['lr'] * np.power(0.1, (epoch / 50))) for data in train_loader: optimizer.zero_grad() F.nll_loss(model(data.to(device)), data.y).backward() optimizer.step()
def test(): model.eval() correct = 0 for data in progressbar.progressbar(test_loader): data = data.to(device) pred = model(data).max(1)[1] correct += pred.eq(data.y).sum().item() return (correct / len(test_dataset))
class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.lin0 = nn.Linear(3, nf[0]) self.resnet_block11 = HarmonicResNetBlock(nf[0], nf[0], max_order, n_rings, prev_order=0) self.pool = ParallelTransportPool(1, scale1_transform) self.resnet_block21 ...
def train(epoch): model.train() if (epoch > 30): for param_group in optimizer.param_groups: param_group['lr'] = 0.001 for data in train_loader: optimizer.zero_grad() F.nll_loss(model(data.to(device)), data.y).backward() optimizer.step()
def test(): model.eval() correct = 0 total_num = 0 for (i, data) in enumerate(test_loader): pred = model(data.to(device)).max(1)[1] correct += pred.eq(data.y).sum().item() total_num += 1 return (correct / total_num)
class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.lin0 = nn.Linear(3, nf[0]) self.resnet_block11 = HarmonicResNetBlock(nf[0], nf[0], max_order, n_rings, prev_order=0) self.resnet_block12 = HarmonicResNetBlock(nf[0], nf[0], max_order, n_rings) ...
def train(epoch): model.train() if (epoch > 20): for param_group in optimizer.param_groups: param_group['lr'] = 0.001 for data in progressbar.progressbar(train_loader): optimizer.zero_grad() F.nll_loss(model(data.to(device)), data.y).backward() optimizer.step()
def test(): model.eval() correct = 0 total_num = 0 for (i, data) in enumerate(test_loader): pred = model(data.to(device)).max(1)[1] correct += pred.eq(data.y).sum().item() total_num += data.y.size(0) return (correct / total_num)
class MultiscaleRadiusGraph(object): 'Creates a radius graph for multiple pooling levels.\n The nodes and adjacency matrix for each pooling level can be accessed by masking\n tensors with values for nodes and edges with data.node_mask and data.edge_mask, respectively.\n\n Edges can belong to multiple lev...
class NormalizeArea(object): 'Centers shapes and normalizes their surface area.\n ' def __init__(self): return def __call__(self, data): data.pos = (data.pos - ((torch.max(data.pos, dim=0)[0] + torch.min(data.pos, dim=0)[0]) / 2)) (pos_vh, face_vh) = (data.pos.cpu().numpy(), d...
class Subsample(object): 'Samples only the positions and descriptors that are set in data.sample_idx.\n ' def __init__(self): return def __call__(self, data): assert hasattr(data, 'sample_idx') sample_idx = data.sample_idx data.pos = data.pos[sample_idx] if has...
def write_ply(file, data, pred, features): ' \n Creates a ply file with the mesh,\n given predictions on each vertex and features from inside the network\n Can be used to visualize features in other software\n\n :param file: file name to write to\n :param data: mesh object with positions and faces ...
class CMakeExtension(Extension): def __init__(self, name, sourcedir=''): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir)
class CMakeBuild(build_ext): def run(self): try: out = subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError(('CMake must be installed to build the following extensions: ' + ', '.join((e.name for e in self.extensions)))) if (platform.sy...
def evaluate(j, e, solver, scores1, scores2, data_loader, logdir, reference_point, split, result_dict): '\n Do one forward pass through the dataloader and log the scores.\n ' assert (split in ['train', 'val', 'test']) mode = 'pf' if (mode == 'pf'): assert (len(scores1) == len(scores2) <=...
def eval(settings): '\n The full evaluation loop. Generate scores for all checkpoints found in the directory specified above.\n\n Uses the same ArgumentParser as main.py to determine the method and dataset.\n ' settings['batch_size'] = 2048 print('start evaluation with settings', settings) lo...
class HyperVolume(): '\n Hypervolume computation based on variant 3 of the algorithm in the paper:\n C. M. Fonseca, L. Paquete, and M. Lopez-Ibanez. An improved dimension-sweep\n algorithm for the hypervolume indicator. In IEEE Congress on Evolutionary\n Computation, pages 1157-1163, Vancouver, Canada...
class MultiList(): 'A special data structure needed by FonsecaHyperVolume. \n \n It consists of several doubly linked lists that share common nodes. So, \n every node has multiple predecessors and successors, one in every list.\n\n ' class Node(): def __init__(self, numberLists, cargo=No...
def load_dataset(path, s_label): data = pd.read_csv(path) data['workclass'] = data['workclass'].replace('?', 'Private') data['occupation'] = data['occupation'].replace('?', 'Prof-specialty') data['native-country'] = data['native-country'].replace('?', 'United-States') data.education = data.educati...
class ADULT(data.Dataset): def __init__(self, root='data/adult', split='train', sensible_attribute='gender', **kwargs): assert (split in ['train', 'val', 'test']) path = os.path.join(root, 'adult.csv') (x, y, s) = load_dataset(path, sensible_attribute) x = torch.from_numpy(x).floa...
def load_dataset(root, s_label): raw_data = pd.read_csv(os.path.join(root, 'compas-scores-two-years.csv')) data = raw_data[(((((raw_data['days_b_screening_arrest'] <= 30) & (raw_data['days_b_screening_arrest'] >= (- 30))) & (raw_data['is_recid'] != (- 1))) & (raw_data['c_charge_degree'] != 'O')) & (raw_data['...
class Compas(torch.utils.data.Dataset): def __init__(self, split, root='data/compas', sensible_attribute='sex', **kwargs): assert (split in ['train', 'val', 'test']) (x, y, s) = load_dataset(root, sensible_attribute) x = torch.from_numpy(x).float() y = torch.from_numpy(y).long() ...
def load_dataset(root, s_label): data = pd.read_csv(os.path.join(root, 'UCI_Credit_Card.csv')) to_categorical = ['EDUCATION', 'MARRIAGE', 'PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6'] for column in to_categorical: data[column] = data[column].astype('category') data.SEX = data.SEX.repla...
class Credit(torch.utils.data.Dataset): def __init__(self, split, root='data/credit', sensible_attribute='SEX', **kwargs): assert (split in ['train', 'val', 'test']) (x, y, s) = load_dataset(root, sensible_attribute) x = torch.from_numpy(x).float() y = torch.from_numpy(y).long() ...
def method_from_name(method, **kwargs): if (method == 'ParetoMTL'): return ParetoMTLMethod(**kwargs) elif ('cosmos' in method): return COSMOSMethod(**kwargs) elif (method == 'SingleTask'): return SingleTaskMethod(**kwargs) elif ('hyper' in method): return HypernetMethod...
def evaluate(j, e, method, scores, data_loader, logdir, reference_point, split, result_dict): assert (split in ['train', 'val', 'test']) global volume_max global epoch_max score_values = np.array([]) for batch in data_loader: batch = utils.dict_to_cuda(batch) s = [] for l i...
def main(settings): print('start processig with settings', settings) utils.set_seed(settings['seed']) global elapsed_time logdir = os.path.join(settings['logdir'], settings['method'], settings['dataset'], utils.get_runname(settings)) pathlib.Path(logdir).mkdir(parents=True, exist_ok=True) trai...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--dataset', '-d', default='mm', help='The dataset to run on.') parser.add_argument('--method', '-m', default='cosmos', help='The method to generate the Pareto front.') parser.add_argument('--seed', '-s', default=1, type=int, hel...
class BaseMethod(): def model_params(self): return list(self.model.parameters()) def new_epoch(self, e): self.model.train() @abstractmethod def step(self, batch): raise NotImplementedError() def log(self): return {} @abstractmethod def eval_step(self, b...
class Upsampler(nn.Module): def __init__(self, K, child_model, input_dim): '\n In case of tabular data: append the sampled rays to the data instances (no upsampling)\n In case of image data: use a transposed CNN for the sampled rays.\n ' super().__init__() if (len(inp...
class COSMOSMethod(BaseMethod): def __init__(self, objectives, alpha, lamda, dim, n_test_rays, **kwargs): '\n Instanciate the cosmos solver.\n\n Args:\n objectives: A list of objectives\n alpha: Dirichlet sampling parameter (list or float)\n lamda: Cosine si...
class MGDAMethod(BaseMethod): def __init__(self, objectives, approximate_norm_solution, normalization_type, **kwargs) -> None: super().__init__() self.objectives = objectives self.approximate_norm_solution = approximate_norm_solution self.normalization_type = normalization_type ...
class PHNHyper(nn.Module): 'Hypernetwork\n ' def __init__(self, kernel_size: List[int], ray_hidden_dim=100, out_dim=10, target_hidden_dim=50, n_kernels=10, n_conv_layers=2, n_hidden=1, n_tasks=2): super().__init__() self.n_conv_layers = n_conv_layers self.n_hidden = n_hidden ...
class PHNTarget(nn.Module): 'Target network\n ' def __init__(self, kernel_size, n_kernels=10, out_dim=10, target_hidden_dim=50, n_conv_layers=2, n_tasks=2): super().__init__() assert (len(kernel_size) == n_conv_layers), 'kernel_size is list with same dim as number of conv layers holding ke...
class LeNetPHNHyper(PHNHyper): pass
class LeNetPHNTargetWrapper(PHNTarget): def forward(self, x, weights=None): logits = super().forward(x, weights) return dict(logits_l=logits[0], logits_r=logits[1])
class FCPHNHyper(nn.Module): def __init__(self, dim, ray_hidden_dim=100, n_tasks=2): super().__init__() self.feature_dim = dim[0] self.ray_mlp = nn.Sequential(nn.Linear(n_tasks, ray_hidden_dim), nn.ReLU(inplace=True), nn.Linear(ray_hidden_dim, ray_hidden_dim), nn.ReLU(inplace=True), nn.Li...
class FCPHNTarget(nn.Module): def forward(self, x, weights): x = F.linear(x, weight=weights['fc0.weights'], bias=weights['fc0.bias']) x = F.relu(x) x = F.linear(x, weight=weights['fc1.weights'], bias=weights['fc1.bias']) x = F.relu(x) x = F.linear(x, weight=weights['fc2.we...
class HypernetMethod(BaseMethod): def __init__(self, objectives, dim, n_test_rays, alpha, internal_solver, **kwargs): self.objectives = objectives self.n_test_rays = n_test_rays self.alpha = alpha self.K = len(objectives) if (len(dim) == 1): hnet = FCPHNHyper(d...
class Solver(): def __init__(self, n_tasks): super().__init__() self.n_tasks = n_tasks @abstractmethod def get_weighted_loss(self, losses, ray, parameters=None, **kwargs): pass def __call__(self, losses, ray, parameters, **kwargs): return self.get_weighted_loss(losse...
class LinearScalarizationSolver(Solver): 'For LS we use the preference ray to weigh the losses\n ' def __init__(self, n_tasks): super().__init__(n_tasks) def get_weighted_loss(self, losses, ray, parameters=None, **kwargs): return (losses * ray).sum()
class EPOSolver(Solver): 'Wrapper over EPO\n ' def __init__(self, n_tasks, n_params): super().__init__(n_tasks) self.solver = EPO(n_tasks=n_tasks, n_params=n_params) def get_weighted_loss(self, losses, ray, parameters=None, **kwargs): assert (parameters is not None) re...
class EPO(): def __init__(self, n_tasks, n_params): self.n_tasks = n_tasks self.n_params = n_params def __call__(self, losses, ray, parameters): return self.get_weighted_loss(losses, ray, parameters) @staticmethod def _flattening(grad): return torch.cat(tuple((g.resh...
class ExactParetoLP(object): 'modifications of the code in https://github.com/dbmptr/EPOSearch\n ' def __init__(self, m, n, r, eps=0.0001): cvxopt.glpk.options['msg_lev'] = 'GLP_MSG_OFF' self.m = m self.n = n self.r = r self.eps = eps self.last_move = None ...
def mu(rl, normed=False): if len(np.where((rl < 0))[0]): raise ValueError(f'''rl<0 rl={rl}''') m = len(rl) l_hat = (rl if normed else (rl / rl.sum())) eps = np.finfo(rl.dtype).eps l_hat = l_hat[(l_hat > eps)] return np.sum((l_hat * np.log((l_hat * m))))
def adjustments(l, r=1): m = len(l) rl = (r * l) l_hat = (rl / rl.sum()) mu_rl = mu(l_hat, normed=True) a = (r * (np.log((l_hat * m)) - mu_rl)) return (rl, mu_rl, a)
def get_d_paretomtl_init(grads, losses, preference_vectors, pref_idx): ' \n calculate the gradient direction for ParetoMTL initialization \n\n Args:\n grads: flattened gradients for each task\n losses: values of the losses for each task\n preference_vectors: all preference vectors u\n ...
def get_d_paretomtl(grads, losses, preference_vectors, pref_idx): '\n calculate the gradient direction for ParetoMTL \n \n Args:\n grads: flattened gradients for each task\n losses: values of the losses for each task\n preference_vectors: all preference vectors u\n pref_idx: w...
class ParetoMTLMethod(BaseMethod): def __init__(self, objectives, num_starts, **kwargs): assert (len(objectives) <= 2) self.objectives = objectives self.num_pareto_points = num_starts self.init_solution_found = False self.model = model_from_dataset(method='paretoMTL', **kw...
class SingleTaskMethod(BaseMethod): def __init__(self, objectives, num_starts, **kwargs): self.objectives = objectives if (num_starts > 1): self.task = (- 1) assert ('task_id' not in kwargs) else: assert (num_starts == 1) print(objectives) ...
class UniformScalingMethod(BaseMethod): def __init__(self, objectives, **kwargs): self.objectives = objectives self.J = len(objectives) self.model = model_from_dataset(method='uniform_scaling', **kwargs).cuda() def model_params(self): return list(self.model.parameters()) ...
class MBConvBlock(nn.Module): 'Mobile Inverted Residual Bottleneck Block.\n Args:\n block_args (namedtuple): BlockArgs, defined in utils.py.\n global_params (namedtuple): GlobalParam, defined in utils.py.\n image_size (tuple or list): [image_height, image_width].\n References:\n ...
class EfficientNet(nn.Module): "EfficientNet model.\n Most easily loaded with the .from_name or .from_pretrained methods.\n Args:\n blocks_args (list[namedtuple]): A list of BlockArgs to construct blocks.\n global_params (namedtuple): A set of GlobalParams shared between blocks.\n Refere...
class Swish(nn.Module): def forward(self, x): return (x * torch.sigmoid(x))
class SwishImplementation(torch.autograd.Function): @staticmethod def forward(ctx, i): result = (i * torch.sigmoid(i)) ctx.save_for_backward(i) return result @staticmethod def backward(ctx, grad_output): i = ctx.saved_tensors[0] sigmoid_i = torch.sigmoid(i) ...
class MemoryEfficientSwish(nn.Module): def forward(self, x): return SwishImplementation.apply(x)
def round_filters(filters, global_params): 'Calculate and round number of filters based on width multiplier.\n Use width_coefficient, depth_divisor and min_depth of global_params.\n Args:\n filters (int): Filters number to be calculated.\n global_params (namedtuple): Global params of the mo...
def round_repeats(repeats, global_params): "Calculate module's repeat number of a block based on depth multiplier.\n Use depth_coefficient of global_params.\n Args:\n repeats (int): num_repeat to be calculated.\n global_params (namedtuple): Global params of the model.\n Returns:\n ...
def drop_connect(inputs, p, training): 'Drop connect.\n Args:\n input (tensor: BCWH): Input of this structure.\n p (float: 0.0~1.0): Probability of drop connection.\n training (bool): The running mode.\n Returns:\n output: Output after drop connection.\n ' assert (0 <= p <...
def get_width_and_height_from_size(x): 'Obtain height and width from x.\n Args:\n x (int, tuple or list): Data size.\n Returns:\n size: A tuple or list (H,W).\n ' if isinstance(x, int): return (x, x) if (isinstance(x, list) or isinstance(x, tuple)): return x else...
def calculate_output_image_size(input_image_size, stride): "Calculates the output image size when using Conv2dSamePadding with a stride.\n Necessary for static padding. Thanks to mannatsingh for pointing this out.\n Args:\n input_image_size (int, tuple or list): Size of input image.\n strid...
def get_same_padding_conv2d(image_size=None): 'Chooses static padding if you have specified an image size, and dynamic padding otherwise.\n Static padding is necessary for ONNX exporting of models.\n Args:\n image_size (int or tuple): Size of the image.\n Returns:\n Conv2dDynamicSamePadd...
class Conv2dDynamicSamePadding(nn.Conv2d): '2D Convolutions like TensorFlow, for a dynamic image size.\n The padding is operated in forward function by calculating dynamically.\n ' def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True): super()....
class Conv2dStaticSamePadding(nn.Conv2d): "2D Convolutions like TensorFlow's 'SAME' mode, with the given input image size.\n The padding mudule is calculated in construction function, then used in forward.\n " def __init__(self, in_channels, out_channels, kernel_size, stride=1, image_size=None, **kw...