code
stringlengths
101
5.91M
class UNetMidBlock2D(nn.Module): def __init__(self, in_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, attn_groups: Optional[int]=None, resnet_pre_norm: bool=True, add_attent...
def normalize(x, stats): if (stats is None): return x return ((x - stats.mean) / stats.std)
def get_file_size(filename): size_in_mb = (os.path.getsize(filename) / float((1024 ** 2))) return size_in_mb
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('dataset_loader', type=str) parser.add_argument('dataset_path', type=str) parser.add_argument('--video_names', type=str, nargs='+', help='Only generate training data for a subset of videos. If not set, will include al...
def format_str_one(v, float_prec=6, int_pad=1): if (isinstance(v, torch.Tensor) and (v.numel() == 1)): v = v.item() if isinstance(v, float): return (('{:.' + str(float_prec)) + 'f}').format(v) if (isinstance(v, int) and int_pad): return (('{:0' + str(int_pad)) + 'd}').format(v) r...
def create_vocabulary_from_data(datasets: DatasetDict, word_delimiter_token: Optional[str]=None, unk_token: Optional[str]=None, pad_token: Optional[str]=None): def extract_all_chars(batch): all_text = ' '.join(batch['target_text']) vocab = list(set(all_text)) return {'vocab': [vocab], 'all_t...
def train_val_test_generate(dataframe, model_params): (train_val_test_x, train_val_test_y, len_x_samples, len_before_x_samples) = pad_all_cases(dataframe, dataframe['NO3'].values, model_params, model_params['min_before'], model_params['max_before'], model_params['min_after'], model_params['max_after'], model_params...
def main(): parser = argparse.ArgumentParser(description='Tool to average the params of input checkpoints to produce a new checkpoint') parser.add_argument('--inputs', required=True, nargs='+', help='Input checkpoint file paths.') parser.add_argument('--output', required=True, metavar='FILE', help='Write th...
def plot_dimension_interval(ax, cmap, dim_: int, x_box: List[float], y_box: List[float], x_color='#FFB570', y_color='#67AB9F', label=False): if (not label): ax.hlines(dim_, x_box[0], x_box[1], x_color, lw=10) ax.hlines(dim_, y_box[0], y_box[1], y_color, lw=7) else: ax.hlines(dim_, x_box[...
def register_all_cityscapes(root='datasets'): for (key, (image_dir, gt_dir)) in _RAW_CITYSCAPES_SPLITS.items(): meta = _get_builtin_metadata('cityscapes') image_dir = os.path.join(root, image_dir) gt_dir = os.path.join(root, gt_dir) inst_key = key.format(task='instance_seg') ...
class Boco(): def __init__(self, name): self.name = name def validate(self): assert self.computeLoss, 'You need to specify a function to compute the loss'
def get_video_loader(use_petrel_backend: bool=True, enable_mc: bool=True, conf_path: str=None): if (petrel_backend_imported and use_petrel_backend): _client = Client(conf_path=conf_path, enable_mc=enable_mc) else: _client = None def _loader(video_path): if ((_client is not None) and ...
def create_split_mesh(cat_desc, edge_length_threshold, overwrite=False, start_threshold=None): from shapenet.core import cat_desc_to_id from shapenet.core.meshes.config import get_mesh_config from template_ffd.templates.ids import get_template_ids cat_id = cat_desc_to_id(cat_desc) example_ids = get_...
class LevelsFilter(logging.Filter): def __init__(self, levels): self.levels = [getattr(logging, level) for level in levels] def filter(self, record): return (record.levelno in self.levels)
def reorder_image(img, input_order='HWC'): if (input_order not in ['HWC', 'CHW']): raise ValueError(f"Wrong input_order {input_order}. Supported input_orders are 'HWC' and 'CHW'") if (len(img.shape) == 2): img = img[(..., None)] return img if (input_order == 'CHW'): img = img...
def update_config_from_file(filename, base_cfg=None): exp_config = None with open(filename) as f: exp_config = edict(yaml.safe_load(f)) if (base_cfg is not None): _update_config(base_cfg, exp_config) else: _update_config(cfg, exp_config)
class ADFF(nn.Module): def __init__(self, block_channel, adff_num_features=1280, rpd_num_features=2048): super(ADFF, self).__init__() rpd_num_features = (rpd_num_features // 2) print('block_channel:', block_channel) self.upsample_scale1to5 = _UpProjection(num_input_features=block_cha...
def __median_wilcoxon_to_latex(indicator_name: str, wilcoxon_data: pd.DataFrame, caption: str, label): indicator_data = wilcoxon_data[(wilcoxon_data['Indicator'] == indicator_name)] problems = pd.unique(indicator_data['Problem']) algorithms = pd.unique(indicator_data['Algorithm']) num_columns = len(algo...
class TFFlaubertForTokenClassification(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def ResNet50(include_top=False, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, **kwargs): def stack_fn(x): x = stack1(x, 64, 3, stride1=1, name='conv2') x = stack1(x, 128, 4, name='conv3') x = stack1(x, 256, 6, name='conv4') x = stack1(x, 512, 3,...
def maybe_dict_from_checkpoint(ckpt_path=None, ckpt_dict=None): assert ((ckpt_path is not None) or (ckpt_dict is not None)) if (ckpt_dict is None): ckpt_dict = load_dict_from_checkpoint(ckpt_path) return ckpt_dict
class IntLinear(nn.Module): def __init__(self, in_features, out_features, bias=True, p=0, update_step=3000, bits=8, method='histogram'): super(IntLinear, self).__init__() self.in_features = int(in_features) self.out_features = int(out_features) self.weight = torch.nn.Parameter(torch....
def hook_adapavgpool2d(m, x, y): x = x[0] out_size = _pair(m.output_size) k = (torch.Tensor(list(x.size()[2:])) / torch.Tensor(out_size)) k = torch.prod(torch.ceil(k)).item() flops_per_ele = k flops = (flops_per_ele * y.numel()) return int(flops)
def set_seed(seed): import random import tensorflow as tf seed %= random.seed(seed) np.random.seed(seed) tf.compat.v1.set_random_seed(seed) print(('using seed %s' % str(seed)))
class ContinuousMctsPolicies(AbstractMctsPolicies): def __init__(self, sample=None, initialize=None, score_c=1.0, pw_C=1.0, pw_alpha=0.25, *args, **kwargs): super(ContinuousMctsPolicies, self).__init__(*args, score=ContinuousRaveScore(score_c), widen=ProgressiveWiden(pw_C, pw_alpha), extract=MostVisitedExtr...
class UP(TDAgent): def __init__(self, eval_points=10000, leverage=1.0, W=None): super(UP, self).__init__() self.eval_points = eval_points self.leverage = leverage self.W = W def init_portfolio(self, X): m = X.shape[1] self.W = np.matrix(mc_simplex((m - 1), self.ev...
def makeGraph(root): g = nx.DiGraph() nid = 0 (name, nid) = get_name(root, nid) g.add_node(name) good = [] bad = [] mid = [name] for child in root.children: nid = add_to_graph(g, name, child, good, bad, mid, nid) return (g, good, bad, mid)
def get_model(): model = Sequential() model.add(Conv2D(64, (3, 3), activation='relu', input_shape=(80, 80, 3))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64, activa...
class SemiNet(torch.nn.Module): def __init__(self, in_channels=3, taskcla=None): super(SemiNet, self).__init__() self.conv1 = torch.nn.Conv2d(in_channels, 32, kernel_size=3, stride=1, padding=1) self.GN1 = torch.nn.GroupNorm(32, 32) self.BN1 = torch.nn.BatchNorm2d(32) self.co...
def unset_hook(f: Callable[([Any], Any)]) -> Callable[([Any], Any)]: (f) def unset_hook_wrapper(self, **kwargs): f(self, **kwargs) self.attribution_model.is_hooked = False return unset_hook_wrapper
def gen_convs(inchannel, outchannel, bn=False): (yield nn.Conv2d(inchannel, outchannel, 3, padding=1)) if bn: (yield nn.BatchNorm2d(outchannel)) (yield nn.ReLU(inplace=True))
def lazily_load_dataset(corpus_type, opt): assert (corpus_type in ['train', 'valid']) def _lazy_dataset_loader(pt_file, corpus_type): dataset = torch.load(pt_file) logger.info(('Loading %s dataset from %s, number of examples: %d' % (corpus_type, pt_file, len(dataset)))) return dataset ...
class LlamaTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, unk_token='<unk>', bos_token='<s>', eos_token='</s>', sp_model_kwargs: Optional[Dict...
class PPM(nn.ModuleList): def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg, act_cfg, align_corners, **kwargs): super(PPM, self).__init__() self.pool_scales = pool_scales self.align_corners = align_corners self.in_channels = in_channels self.channels =...
def get_connected_molecules(molecules): connected = [] for mol in molecules: if is_connected(mol): connected.append(mol) return connected
def test_parse_dimensions(): valid_examples = [('3x3', (3, 3)), ('4x2', (4, 2))] for (inp, expect) in valid_examples: out = parse_dimensions(inp) assert (out == expect), (out, '!=', expect)
_materialize('tensorflow') class NHWCConv2dValidPad(NHWCConv2d): def __init__(self, out_channels: Union[(int, z3.ExprRef)], stride: Union[(int, z3.ExprRef)], dilation_h: Union[(int, z3.ExprRef)], dilation_w: Union[(int, z3.ExprRef)]): super().__init__(out_channels, stride, dilation_h, dilation_w, 'VALID')
def set_log_dir(root_dir, exp_name): path_dict = {} os.makedirs(root_dir, exist_ok=True) exp_path = os.path.join(root_dir, exp_name) now = datetime.now(dateutil.tz.tzlocal()) timestamp = now.strftime('%Y_%m_%d_%H_%M_%S') prefix = ((exp_path + '_') + timestamp) os.makedirs(prefix) path_di...
def load_config(path='configs/default.yaml') -> dict: with open(path, 'r') as ymlfile: cfg = yaml.safe_load(ymlfile) return cfg
def handle_signal(signum, frame) -> None: log.info(f'Received interrupt signal {signum}') if waiting: sys.exit(1) global abort abort = True
def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument('--work_dir', help='the dir to save logs and models') parser.add_argument('--resume_from', help='the checkpoint file to resume from') pa...
def grad(y, x, create_graph=True, keepdim=False): N = (y.size(0) if (len(y.size()) == 2) else 1) Ny = y.size((- 1)) Nx = x.size((- 1)) z = torch.ones_like(y[(..., 0)]) dy = [] for i in range(Ny): dy.append(torch.autograd.grad(y[(..., i)], x, grad_outputs=z, create_graph=create_graph)[0])...
def is_time(token): without_time = re.sub('(\\d)*(\\d):(\\d\\d)([aA][mM]|[pP][Mm])', '', token).strip() return (not without_time)
class TaskDataCollatorForSeq2Seq(DataCollatorForSeq2Seq): def check_uniqueness(self, samples): assert (len(np.unique(samples)) == 1) def __call__(self, features): print('#### COLLATOR DEBUG #$$$$') print(features[0].keys()) print('') tasks = [d.pop('task') for d in featur...
def get_permutations(num_images): permutations = [] for i in range(num_images): for j in range(num_images): if (i != j): permutations.append((i, j)) return np.array(permutations)
class BN(PlainNetBasicBlockClass): def __init__(self, out_channels=None, copy_from=None, no_create=False, **kwargs): super(BN, self).__init__(**kwargs) self.no_create = no_create if (copy_from is not None): assert isinstance(copy_from, nn.BatchNorm2d) self.in_channels...
class SeparableConv2d_same(nn.Module): def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False): super(SeparableConv2d_same, self).__init__() self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, 0, dilation, groups=inplanes, bias=bias) self.pointwise =...
class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=(- 1)): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.da...
class ResNetConvBackbone(nn.Module): def __init__(self, num_layers: int, pretrained: bool) -> None: super(ResNetConvBackbone, self).__init__() self.resnet = get_vanilla_resnet_model(num_layers, pretrained) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.resnet.conv1(x) ...
def get_bt_sentences(train_path): pkl_path = Path(train_path).parent.joinpath(f'train_aug_bt_data.pkl') sentence_to_aug_sentence = get_backtrans_data_dict(pkl_path, train_path) return sentence_to_aug_sentence
def create_data_loader(root_dir, batch_size, nproc): dir_path = os.path.realpath(root_dir) data_transform = transforms.Compose([transforms.Resize(256), transforms.ColorJitter(), transforms.RandomCrop(224), transforms.RandomHorizontalFlip(), transforms.Resize(128), transforms.ToTensor()]) catdogs = ImageFold...
def make_module(sym_model, ctx, input_desc): assert (isinstance(sym_model, tuple) and isinstance(sym_model[0], mx.symbol.Symbol)) (symnet, args, auxs) = sym_model mod = mx.module.module.Module(symbol=symnet, data_names=[d.name for d in input_desc], label_names=None, context=ctx) mod.bind(input_desc, for...
class ANY(): def __init__(self, _type): self._type = _type def __eq__(self, other): return isinstance(other, self._type) def __repr__(self): return f'ANY({self._type.__name__})'
def main(_): RANDOM_SEED = 66 np.random.seed(RANDOM_SEED) output_dir = os.path.join(FLAGS.output_dir, FLAGS.category) sample_dir = os.path.join(output_dir, 'synthesis') log_dir = os.path.join(output_dir, 'log') model_dir = os.path.join(output_dir, 'checkpoints') if tf.gfile.Exists(log_dir): ...
def find_similar_token(token, tokens): token = re.sub('-\\d\\d$', '', token) for (i, t) in enumerate(tokens): if (token == t): return tokens[i] return None
class ConvertCommand(BaseTransformersCLICommand): def register_subcommand(parser: ArgumentParser): train_parser = parser.add_parser('convert', help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.') train_parser.add_argument('--model_type', type=st...
class SimilarityClient(): def __init__(self, stub): self.stub = stub def search(self, id, k): request = recall_pb2.Query(userID=id, k=k) try: candidates = self.stub.searchCandidates(request) return candidates.candidate except Exception as e: lo...
def load_model_from_config(config, sd): model = instantiate_from_config(config) model.load_state_dict(sd, strict=False) model.cuda() model.eval() return model
class LowRankAdapter(nn.Module): def __init__(self, config): super().__init__() self.config = config self.input_dim = config.input_dim self.down_sample_size = (self.input_dim // config.reduction_factor) self.activation = Activations(config.non_linearity.lower()) self....
def relevant_clauses(clauses, object_pair_list, converter): def _relevant(c): for l in c: triple = converter.num2triple(abs(l)) for obj_pair in object_pair_list: if ((obj_pair == [triple[1], triple[2]]) or (obj_pair == [triple[2], triple[1]])): ret...
class Option(NetOption): def __init__(self, conf_path, args): super(Option, self).__init__() self.conf = ConfigFactory.parse_file(conf_path) self.save_path = self.conf['save_path'] self.dataPath = self.conf['dataPath'] self.dataset = self.conf['dataset'] self.nGPU = s...
def Align_LC(mjd, mjd2, data, data2, error, error2): if (len(data2) > len(data)): new_data2 = [] new_error2 = [] new_mjd2 = [] new_mjd = np.copy(mjd) new_error = np.copy(error) new_data = np.copy(data) count = 0 for index in xrange(len(data)): ...
def test_classifier(P, model, loader, criterion, steps, logger=None): metric_logger = MetricLogger(delimiter=' ') if (logger is None): log_ = print else: log_ = logger.log mode = model.training model.eval() acc = 0.0 acc_ema = 0.0 if hasattr(P, 'moving_inner_lr'): ...
def train(dataset='mnist', model_name='sl', batch_size=128, epochs=50, noise_ratio=0, asym=False, alpha=1.0, beta=1.0): print(('Dataset: %s, model: %s, batch: %s, epochs: %s, noise ratio: %s%%, asymmetric: %s, alpha: %s, beta: %s' % (dataset, model_name, batch_size, epochs, noise_ratio, asym, alpha, beta))) (X_...
def _shufflenetv2_mpncov(arch, pretrained, progress, *args, **kwargs): model = ShuffleNetV2_MPNCOV(*args, **kwargs) if pretrained: model_url = model_urls[arch] if (model_url is None): raise NotImplementedError('pretrained {} is not supported as of now'.format(arch)) else: ...
class RandomGaussianNoise(object): def __init__(self, p=0.5, noise_variance=(0, 0.5)): super().__init__() self.p = p self.noise_variance = noise_variance def __call__(self, img_and_mask: Tuple[(np.ndarray, np.ndarray, np.ndarray)]) -> Tuple[(np.ndarray, np.ndarray, np.ndarray)]: ...
def validate(data_path, device, model, word2idx, entity2idx, model_name, return_hits_at_k): model.eval() data = process_text_file(data_path) answers = [] data_gen = data_generator(data=data, word2ix=word2idx, entity2idx=entity2idx) total_correct = 0 error_count = 0 hit_at_1 = 0 hit_at_5 ...
def test_global_context_block_1d(): N = 10 C = 128 reduction = 16 data = torch.randn(N, C, 7) model = GlobalContextBlock1D(in_channels=C, reduction=reduction) print(model) outputs = model(data) print(outputs.shape) assert (outputs.shape == (N, C, 7))
def clean_html_one_sample(sample): roles = ['human', 'gpt'] if (len(sample['conversations']) <= 1): return (sample, 1) if (sample['conversations'][0]['from'] != 'human'): sample['conversations'] = sample['conversations'][1:] if (len(sample['conversations']) <= 1): return (sample,...
class SetupArgs(): def __init__(self, sampler_cls, sampler_args, seed): self.sampler_cls = sampler_cls self.sampler_args = sampler_args self.seed = seed
class Bow(BaseBow): def __init__(self): super().__init__('bow', weight=30, damage=D.Dice.from_str('d2'), material=M.Wood, hit=0)
def common_config(parser): parser.add_argument('--percentage', '-pc', type=int, default=100, help='% of samples to use for % experiment, defaults to 100 for no experiment') parser.add_argument('--shuffle', '-sh', type=str_to_bool, default=True, help='shuffle test set (after splitting)') parser.add_argument(...
def get_texts(texts: List[str], already_processed: Optional[bool]=False, n_cpus: Optional[int]=None) -> List[List[str]]: num_cpus = (n_cpus if (n_cpus is not None) else os.cpu_count()) if (not already_processed): processed_texts = [' '.join(simple_preprocess(t)) for t in texts] else: process...
class SharedMemoryWriter(StorageWriter): def __init__(self, shm_handler: SharedMemoryHandler) -> None: super().__init__() self.file_name = '' self.shm_handler = shm_handler self.metadata: Dict[(str, object)] = {} def set_up_storage_writer(self, is_coordinator: bool) -> None: ...
def main(args, local_rank): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) vocabs = dict() vocabs['src'] = Vocab(args.src_vocab, 0, [BOS, EOS]) vocabs['tgt'] = Vocab(args.tgt_vocab, 0, [BOS, EOS]) if ((args.world_...
class TemporalCenterCrop(object): def __init__(self, size, padding=True, pad_method='loop'): self.size = size self.padding = padding self.pad_method = pad_method def __call__(self, frame_indices): center_index = (len(frame_indices) // 2) begin_index = max(0, (center_index...
_model_architecture('hf_gpt2', 'hf_gpt2_medium') def hf_gpt2_medium(args): args.embed_dim = getattr(args, 'embed_dim', 1024) args.num_attention_heads = getattr(args, 'num_attention_heads', 16) args.num_layers = getattr(args, 'num_layers', 24) default_architecture(args)
def get_paths(path): files = os.listdir(path) if ((LOG_FILE_NAME in files) or any([('seed' in f) for f in files])): return [path] else: return sum([get_paths(os.path.join(path, f)) for f in files], start=[])
('(float32[:], float32[:])', device=True, inline=True) def rbbox_to_corners(corners, rbbox): angle = rbbox[4] a_cos = math.cos(angle) a_sin = math.sin(angle) center_x = rbbox[0] center_y = rbbox[1] x_d = rbbox[2] y_d = rbbox[3] corners_x = cuda.local.array((4,), dtype=numba.float32) ...
def matrix_for_bone_from_parent(bone, ao): eb1 = ao.data.bones[bone.name] E = eb1.matrix_local ebp = ao.data.bones[bone.name].parent E_p = ebp.matrix_local return (E_p.inverted() E)
class HiResCAM(BaseCAM): def __init__(self, model, target_layers, reshape_transform=None): super(HiResCAM, self).__init__(model, target_layers, reshape_transform) def get_cam_image(self, input_tensor, target_layer, target_category, activations, grads, eigen_smooth): elementwise_activations = (gr...
def dfscode_to_tensor(dfscode, feature_map): (max_nodes, max_edges) = (feature_map['max_nodes'], feature_map['max_edges']) (node_forward_dict, edge_forward_dict) = (feature_map['node_forward'], feature_map['edge_forward']) (num_nodes_feat, num_edges_feat) = (len(feature_map['node_forward']), len(feature_map...
class TensorFlowWrapper(): def __init__(self, embedding_layer_hub_name: str) -> None: g = tensorflow.Graph() with g.as_default(): embedding_layer = tensorflow_hub.Module(embedding_layer_hub_name) self._sts_input1 = tensorflow.placeholder(tensorflow.string, shape=None) ...
def get_default_sess_config(mem_fraction=0.99): conf = tf.ConfigProto() conf.gpu_options.per_process_gpu_memory_fraction = mem_fraction conf.gpu_options.allocator_type = 'BFC' conf.gpu_options.allow_growth = True conf.allow_soft_placement = True return conf
def early_stopping(loss, patience): if (len(loss) < patience): return False loss = loss[(patience * (- 1)):] last = sys.float_info.min for l in loss: if (l < last): return False last = l return True
class NatPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): line = clean_lines.lines[linenum] if Search('printf\\s*\\(.*".*%[-+ ]?\\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search('print...
def ReadFile(filename, print_error=True): try: fp = open(filename) try: return fp.read() finally: fp.close() except IOError: if print_error: print(('Error reading %s: %s' % (filename, sys.exc_info()[1]))) return None
def adjust_upper_plane(x0, y0, x_minus, x_plus, y_minus, y_plus, lr=0.01, max_iter=100, print_info=True): x0 = x0.detach() y0 = y0.detach() x1 = ((x0 + x_minus) / 2).data.clone() y1 = ((y0 + y_minus) / 2).data.clone() x2 = ((x0 + x_minus) / 2).data.clone() y2 = ((y0 + y_plus) / 2).data.clone() ...
def parameter_net_file(): with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: f.write("name: 'pythonnet' force_backward: true\n input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }\n layer { type: 'Python' name: 'layer' bottom: 'data' top: 'top'\n python_param { module: 'te...
def _metric_max_over_ground_truths(metric_fn, prediction, ground_truths): scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(score) return max(scores_for_ground_truths)
def nchw_to_nlc(x): assert (len(x.shape) == 4) return x.flatten(2).transpose(1, 2).contiguous()
def shared_single(dim=2): shp = tuple(([1] * dim)) return theano.shared(numpy.zeros(shp, dtype='float32'))
def get_path_iterator(root, tsv, nshard, rank, audio_col_name): with open(tsv) as f: reader = csv.DictReader(f, delimiter='\t', quotechar=None, doublequote=False, lineterminator='\n', quoting=csv.QUOTE_NONE) subpaths = [op.join(root, e[audio_col_name]) for e in reader] (start, end) = get_sha...
def main(args): (model, dataset) = (args.model, args.dataset) model_name = ClipModel.get_model_name_by_index(model) dataset_name = ImageTextData.get_data_name_by_index(dataset) args.log_file = (os.getcwd() + '/log/{}_{}_{}.txt'.format(args.mode, model_name, dataset_name)) logger = get_logger(args.lo...
def make_mlp_model(latent_dim, output_dim, num_layers, activation=tf.nn.relu, l2_regularizer_weight=0.01, bias_init_stddev=0.1): layers = ([latent_dim] * (num_layers - 1)) layers.append(output_dim) return snt.Sequential([snt.nets.MLP(layers, activation=activation, initializers={'w': tf.initializers.glorot_n...
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10, soft=False): super(ResNet, self).__init__() self.in_planes = 64 self.soft = soft self.downsample = nn.MaxPool2d(2) self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) ...
class VOTLTVideo(Video): def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect, load_img=False): super(VOTLTVideo, self).__init__(name, root, video_dir, init_rect, img_names, gt_rect, None, load_img) self.gt_traj = [([0] if np.isnan(bbox[0]) else bbox) for bbox in self.gt_traj] ...
def MFM(x, name): with tf.variable_scope(name): shape = x.get_shape().as_list() res = tf.reshape(x, [(- 1), shape[1], shape[2], 2, (shape[(- 1)] // 2)]) res = tf.reduce_max(res, axis=[3]) return res
def zero_last_layer(encoder): encoder.model_z[4].weight.data.fill_(0.0) encoder.model_z[4].bias.data.fill_(0.0) return encoder