code
stringlengths
101
5.91M
def dense_layer(inp: int, out: int, activation: str, p: float, bn: bool, linear_first: bool): act_fn = get_activation_fn(activation) layers = ([nn.BatchNorm1d((out if linear_first else inp))] if bn else []) if (p != 0): layers.append(nn.Dropout(p)) lin = [nn.Linear(inp, out, bias=(not bn)), act_...
def shared_convl1_lrelu(shape, nb_filters, kernel, stride=(1, 1), **kwargs): c = Convolution2D(nb_filters, kernel, padding='same', kernel_initializer='he_uniform', kernel_regularizer=l1(0.01), strides=(stride, stride), input_shape=shape) l = LeakyReLU() return Sequential([c, l], **kwargs)
class MostVisitedPositiveExtract(AbstractExtract): def __call__(self, node): nodes = [node] while ((not node.terminal) and (len(node.children) > 0)): if (max([child.avg_reward for child in node.children]) > 0): allowed = (lambda child: (child.avg_reward > 0)) ...
def parse_args(): parser = argparse.ArgumentParser(description='TangoBERT') parser.add_argument('--task_name', type=str, help='Name of the GLUE task.', choices=list(task_to_keys.keys()), required=True) parser.add_argument('--small_model_name_or_path', type=str, help='Path to the small pretrained model or mo...
def y_pred_header(outcome, underscore=False): return ((str(outcome) + ('_' if underscore else '-')) + 'y_pred1')
class HypergraphConv(MessagePassing): def __init__(self, in_channels, out_channels, symdegnorm=False, use_attention=False, heads=1, concat=True, negative_slope=0.2, dropout=0, bias=True, **kwargs): kwargs.setdefault('aggr', 'add') super(HypergraphConv, self).__init__(node_dim=0, **kwargs) se...
def train_epoch(encoder, classifier, classifiers, batch_trains, dev, test, optimizer_encoder, optimizer_classifier, start, I): all_time = dev_time = all_tagged = this_tagged = this_loss = 0 mtl_criterion = nn.CrossEntropyLoss() moe_criterion = nn.NLLLoss() domain_encs = None for (ind, batch) in enum...
def densenet161(num_classes=1000, pretrained='imagenet'): model = models.densenet161(pretrained=False) if (pretrained is not None): settings = pretrained_settings['densenet161'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
class EffiInvResUnit(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, expansion_factor, bn_eps, activation, tf_mode): super(EffiInvResUnit, self).__init__() self.kernel_size = kernel_size self.stride = stride self.tf_mode = tf_mode self.residual ...
def matching_cascade(distance_metric, max_distance, cascade_depth, tracks, detections, track_indices=None, detection_indices=None): if (track_indices is None): track_indices = list(range(len(tracks))) if (detection_indices is None): detection_indices = list(range(len(detections))) unmatched_...
def convert_tokens_seq(eval_file, qa_id, symbols, probs, id2word, map_to_orig): def _get_penalty(syms): trigrams = [tuple(syms[i:(i + 3)]) for i in range((len(syms) - 2))] repeat_trigram = (list(filter((lambda x: (x > 1)), list(Counter(trigrams).values()))) != []) return repeat_trigram a...
def test_hash(): class Hashable(object): def __init__(self, value): self.value = value def __hash__(self): return self.value class Unhashable(object): __hash__ = None assert (m.hash_function(Hashable(42)) == 42) with pytest.raises(TypeError): m.has...
def build_batchers(data_dir, batch_size): def coll(batch): (art_batch, abs_batch) = unzip(batch) art_sents = list(filter(bool, map(tokenize(None), art_batch))) abs_sents = list(filter(bool, map(tokenize(None), abs_batch))) return (art_sents, abs_sents) loader = DataLoader(RLDatas...
def parser_sample(parser): parser.add_argument('-in', '--input_img', type=str, required=True, help='path of input image') parser.add_argument('--sigma', type=float, default=0.75, required=False, help='noise level to adjust the variatonality of the new sample. default is 0.75 (float)') parser.add_argument('-...
def fit(model, loss, opt, train_dataset, epochs, train_batch_size, max_steps=None): pbar = tqdm(train_dataset) for (i, batch) in enumerate(pbar): with tf.GradientTape() as tape: (inputs, targets) = batch outputs = model(batch) loss_value = loss(targets, outputs.logits...
class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): if (record.levelno == logging.INFO): return str(record.getMessage()) return logging.Formatter.format(self, record)
def test_nasfcos_fpn(): NASFCOS_FPN(in_channels=[8, 16, 32, 64], out_channels=8, start_level=0, end_level=3, num_outs=4) NASFCOS_FPN(in_channels=[8, 16, 32, 64], out_channels=8, start_level=0, end_level=(- 1), num_outs=4) with pytest.raises(AssertionError): NASFCOS_FPN(in_channels=[8, 16, 32, 64], o...
def generate_configs(base_config, dest_dir, embeddings, grid, refresh, ckpts_path, target): with open(base_config, 'r') as f: base = json.load(f) with open(ckpts_path, 'r') as f: ckpts = json.load(f) model_family = {'smallnet': {'preproc': {'crop': 15, 'imwidth': 100}, 'name': 'SmallNet'}, '...
def test_funcall_kwarg(): run_cell('\n def f(y):\n return 2 * y + 8\n ') run_cell('x = 7') run_cell('z = f(y=x)') run_cell('x = 8') run_cell('logging.info(z)') assert_detected('`z` depends on stale `x`')
def check_models_are_tested(module, test_file): defined_models = get_models(module) tested_models = find_tested_models(test_file) if (tested_models is None): if (test_file in TEST_FILES_WITH_NO_COMMON_TESTS): return return [((f'{test_file} should define `all_model_classes` to app...
class InfoGen(nn.Module): def __init__(self, t_emb, output_size): super(InfoGen, self).__init__() self.tconv1 = nn.ConvTranspose2d(t_emb, 512, 3, 2, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(512) self.tconv2 = nn.ConvTranspose2d(512, 128, 3, 2, padding=1, bias=False) s...
class Hadron(Ion): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) assert self.is_hadron()
def get_datasets(): result = [] for items in CONFIG_GROUPS.values(): result += items['datasets'] return result
.parametrize('spin, spin_angle, launch_angle, launch_direction_angle, expected', [(0, 1, 1, 1, (0, 0, 0))]) def test_spin_components(spin, spin_angle, launch_angle, launch_direction_angle, expected): (wx, wy, wz) = spin_components(spin, spin_angle, launch_angle, launch_direction_angle) for (a, b) in zip((wx, wy...
def imagenet_vgg16_pretrained(output_dim): model = torchvision.models.vgg16(pretrained=True) return _vgg_replace_fc(model, output_dim)
class InitiateNewTrainStage(BaseCallback): def __init__(self, n_envs: int=1, treshhold_type: str='succ', upper_threshold: float=0, lower_threshold: float=0, task_mode: str='staged', verbose=0): super(InitiateNewTrainStage, self).__init__(verbose=verbose) self.n_envs = n_envs self.threshhold_...
def ChunkedSourceIterator(source_items: List, num_instances: int=1, instance_rank: int=0): chunk_size = math.ceil((len(source_items) / num_instances)) chunk = source_items[(instance_rank * chunk_size):((instance_rank + 1) * chunk_size)] return NativeCheckpointableIterator(chunk)
class keypoint_outputs(nn.Module): def __init__(self, dim_in): super().__init__() self.upsample_heatmap = (cfg.KRCNN.UP_SCALE > 1) if cfg.KRCNN.USE_DECONV: self.deconv = nn.ConvTranspose2d(dim_in, cfg.KRCNN.DECONV_DIM, cfg.KRCNN.DECONV_KERNEL, 2, padding=(int((cfg.KRCNN.DECONV_KE...
class TestClassAssociationRule(unittest.TestCase): def test_compare(self): row1 = [1, 1, 0] header1 = ['A', 'B', 'C'] transaction1 = Transaction(row1, header1, ('Class', 0)) item1 = Item('A', 1) item2 = Item('B', 1) item3 = Item('C', 0) item4 = Item('B', 5) ...
class SparseMM(torch.autograd.Function): def forward(self, matrix1, matrix2): self.save_for_backward(matrix1, matrix2) return torch.mm(matrix1, matrix2) def backward(self, grad_output): (matrix1, matrix2) = self.saved_tensors grad_matrix1 = grad_matrix2 = None if self.nee...
def test_chroma_cqt(waveform): chroma_cqt = waveform.chroma_cqt() assert isinstance(chroma_cqt, np.ndarray)
def train(model): model = model.cuda() optimizer = torch.optim.Adam(model.parameters(), lr=0.0001) criterion = nn.L1Loss().cuda() losses = [] for _ in range(500): (x, y) = gen_data(batch_size=(2 ** 10), max_length=10) (x, y) = (torch.from_numpy(x).float().cuda(), torch.from_numpy(y)....
class AttrDict(dict): IMMUTABLE = '__immutable__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__dict__[AttrDict.IMMUTABLE] = False def __getattr__(self, name): if (name in self.__dict__): return self.__dict__[name] elif (name in sel...
class SingleLinearClassifier(nn.Module): def __init__(self, hidden_size, num_label): super(SingleLinearClassifier, self).__init__() self.num_label = num_label self.classifier = nn.Linear(hidden_size, num_label) def forward(self, input_features): features_output = self.classifier(...
def _groupByClip(dict_text: Dict[(str, str)]): sentence_ids = list(dict_text.keys()) sentence_ids.sort(key=natural_keys) dict_text_video = {} for utt_id in sentence_ids: if (utt_id[:11] in dict_text_video): dict_text_video[utt_id[:11]] += dict_text[utt_id].replace('\n', ' ') ...
class ConcatLayer(MergeLayer): def __init__(self, incomings, axis=1, cropping=None, **kwargs): super(ConcatLayer, self).__init__(incomings, **kwargs) self.axis = axis if (cropping is not None): cropping = list(cropping) cropping[axis] = None self.cropping = cr...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, shortcut, bn_aff, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(BasicBlock, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d if ((gro...
(allow_output_mutation=True) def load_models(): if LOAD_DENSE_INDEX: qar_tokenizer = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased') qar_model = AutoModel.from_pretrained('yjernite/retribert-base-uncased').to('cuda:0') _ = qar_model.eval() else: (qar_tokenizer, q...
class DPTImageProcessingTester(unittest.TestCase): def __init__(self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]): size = (size if (size is not None) else {'he...
def adb_devices(): serialnos = [] p = re.compile('(\\S+)\\s+device') for line in split_stdout(sh.adb('devices')): m = p.match(line) if m: serialnos.append(m.group(1)) return serialnos
class PrefixConstrainedLogitsProcessor(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def get_view_a2j_parser(): parser = argparse.ArgumentParser() parser.add_argument('--seed', default=0, type=int) parser.add_argument('--dataset', default='nyu') parser.add_argument('--phase', default='train') parser.add_argument('--split', default=1, type=int, help='Divide the train dataset into s p...
_model def nfnet_f7s(pretrained=False, **kwargs): return _create_normfreenet('nfnet_f7s', pretrained=pretrained, **kwargs)
def main(): parser = get_parser() args = parser.parse_args() source_path = osp.join(args.source, args.split) data_poth = ((source_path + '_unfiltered') if args.unfiltered else source_path) print(f'data path: {data_poth}') features = np.load((data_poth + '.npy'), mmap_mode='r') pca_A = torch....
def write_uchars(fd, values, fmt='>{:d}B'): fd.write(struct.pack(fmt.format(len(values)), *values)) return (len(values) * 1)
def print_stats(args, epoch, num_samples, trainloader, metrics): if ((num_samples % args.log_interval) == 1): print('Epoch:{:2d}\tSample:{:5d}/{:5d}\tLoss:{:.4f}\tAccuracy:{:.2f}\tPPV:{:.3f}\tsensitivity{:.3f}'.format(epoch, num_samples, (len(trainloader) * args.batch_size), metrics.avg('loss'), metrics.avg...
class DataLoader(object): def __init__(self, batch_size, seq_len, dataset_name, task_name, data_dir, tokenizer_dir): self.batch_size = batch_size dataset = load_dataset(dataset_name, cache_dir=data_dir, split='validation') tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir) self...
def get_confusion_matrix(correct_seg, segmentation, elements=None): (height, width) = correct_seg.shape if (elements is None): elements = set(np.unique(correct_seg)) elements = elements.union(set(np.unique(segmentation))) logging.debug('elements parameter not given to get_confusion_matri...
def get_l32_config(): config = get_l16_config() config.patches.size = (32, 32) return config
_LAYERS.register_module() class ExampleConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, norm_cfg=None): super(ExampleConv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels ...
def at_hat_loss(model, x, y, optimizer, step_size=0.007, epsilon=0.031, perturb_steps=10, h=3.5, beta=1.0, gamma=1.0, attack='linf-pgd', hr_model=None, label_smoothing=0.1): criterion_ce_smooth = SmoothCrossEntropyLoss(reduction='mean', smoothing=label_smoothing) criterion_ce = nn.CrossEntropyLoss() model.t...
.mujoco .no_cover .timeout(30) def test_maml_vpg(): assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'torch/maml_vpg_half_cheetah_dir.py')), '--epochs', '1', '--rollouts_per_task', '1', '--meta_batch_size', '1'], check=False).returncode == 0)
class Linear(torch.nn.Linear): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 5))): out_shape = [x.shape[0], self.out_features] empty = NewEmptyTensorOp.apply(x, out_shape) if self.training: dummy = (sum((x.view((-...
class WideBasic(nn.Module): def __init__(self, in_planes, planes, stride=1): super(WideBasic, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.dropout = nn.Dropout(p=P) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, bias=True) self.bn2 = nn.Batc...
def circle_path(obs_all, radius, k): global tracked global direction global old_distance if (k == 1): tracked = False direction = (- 1) actions = np.array([[[]]]) for obs_env in obs_all: for obs in obs_env: agent_pos = np.matrix([obs[2], obs[3]]).T ...
def evaluate(features, support, labels, mask, placeholders): t_test = time.time() feed_dict_val = construct_feed_dict(features, support, labels, mask, placeholders) outs_val = sess.run([model.loss, model.accuracy], feed_dict=feed_dict_val) return (outs_val[0], outs_val[1], (time.time() - t_test))
def frame_generator(frame_duration_ms, audio, sample_rate): n = int(((sample_rate * (frame_duration_ms / 1000.0)) * 2)) offset = 0 timestamp = 0.0 duration = ((float(n) / sample_rate) / 2.0) while ((offset + n) < len(audio)): (yield Frame(audio[offset:(offset + n)], timestamp, duration)) ...
def _run_process(children, report_queue, global_t, is_stopped, is_paused, env_fn): try: if ((not hasattr(children, 'create_env')) or (children.create_env is None)): children.create_env = env_fn(children) if hasattr(children, 'initialize'): children.initialize() def _p...
class IfTimeout(): def __init__(self, timeout): self.start_time = time.time() self.ignored_time = 0.0 if (timeout is None): self.target_time = None else: self.target_time = (self.start_time + timeout) self.interval = None def is_timeout(self): ...
def convert_examples_to_features(examples, label2id, max_seq_length, tokenizer, special_tokens, mode='text'): def get_special_token(w): if (w not in special_tokens): special_tokens[w] = ('[unused%d]' % (len(special_tokens) + 1)) return special_tokens[w] num_tokens = 0 num_fit_exa...
class ModelArguments(): save_adapter_weights: bool = field(default=True, metadata={'help': 'Save the weights for the task-specific adapter.'}) load_adapter_weights: bool = field(default=False, metadata={'help': 'Load the weights used to task-sepcific adapters.'}) adapter_dir: str = field(default=None, metad...
class DIV2K(multiscalesrdata.SRData): def __init__(self, args, name='DIV2K', train=True, benchmark=False): super(DIV2K, self).__init__(args, name=name, train=train, benchmark=benchmark) def _scan(self): (names_hr, names_lr) = super(DIV2K, self)._scan() names_hr = names_hr[(self.begin - 1...
class NCBIDataset(BaseDataset): def __init__(self, dataset): super().__init__(dataset=dataset)
class UnrolledAdam(UnrolledOptimizer): 'The Adam optimizer defined in _State = collections.namedtuple('State', ['t', 'm', 'u']) def __init__(self, lr=0.1, lr_fn=None, beta1=0.9, beta2=0.999, epsilon=1e-09, colocate_gradients_with_ops=False): super(UnrolledAdam, self).__init__(colocate_gradients_wit...
_methods class Model(HPOMixin, tf.keras.Model): def __init__(self, **kwargs): super().__init__() self.model_class = tf.keras.Model self.kwargs = kwargs self.lazyinputs_ = kwargs.get('inputs', None) self.lazyoutputs_ = kwargs.get('outputs', None) def _model_init_args(self,...
def _get_nerf_inner(hparams: Namespace, appearance_count: int, layer_dim: int, xyz_dim: int, weight_key: str) -> nn.Module: if (hparams.container_path is not None): container = torch.jit.load(hparams.container_path, map_location='cpu') if (xyz_dim == 3): return MegaNeRF([getattr(containe...
def make_cosine_lr_schedule(init_lr, total_steps): def schedule(step): t = (step / total_steps) return ((0.5 * init_lr) * (1 + jnp.cos((t * onp.pi)))) return schedule
def reduce_tensor(tensor, n_gpus): rt = tensor.clone() dist.all_reduce(rt, op=dist.reduce_op.SUM) rt /= n_gpus return rt
def eval_nmi(pred, gold): from sklearn.metrics import normalized_mutual_info_score res = dict() res['nmi'] = normalized_mutual_info_score(pred, gold) return res
def get_chamfer_average(model_id, pre_sampled=True, cat_desc=None, **kwargs): import os from shapenet.core import cat_desc_to_id manager = get_chamfer_manager(model_id, pre_sampled, **kwargs) values = None if os.path.isfile(manager.path): with manager.get_saving_dataset('r') as ds: ...
class WideResNet(nn.Module): def __init__(self, conv_layer, linear_layer, depth=34, num_classes=10, widen_factor=10, dropRate=0.0): super(WideResNet, self).__init__() nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)] assert (((depth - 4) % 6) == 0) n = (...
def DistributedFairseqModel(args, model): assert isinstance(model, BaseFairseqModel) if (args.ddp_backend == 'c10d'): ddp_class = parallel.DistributedDataParallel init_kwargs = dict(module=model, device_ids=[args.device_id], output_device=args.device_id, broadcast_buffers=False, bucket_cap_mb=ar...
def make_position_amplitude_gaussian_proposal(model_apply: ModelApply[P], get_std_move: Callable[([PositionAmplitudeData], chex.Scalar)]) -> Callable[([P, PositionAmplitudeData, PRNGKey], Tuple[(PositionAmplitudeData, PRNGKey)])]: def proposal_fn(params: P, data: PositionAmplitudeData, key: PRNGKey): std_mo...
def data_to_extract(username, args): labels = {} labels['title'] = 'PPI Link Prediction' labels['x_label'] = 'Iterations' labels['y_label'] = 'Percent' if args.local: param_str = 'Local' else: param_str = 'Global' labels['train_metric_auc'] = (('Train_' + param_str) + '_Graph...
def shufflenet_v2_mpncov_x2_0(pretrained=False, progress=True, **kwargs): return _shufflenetv2_mpncov('shufflenetv2_mpncov_x2.0', pretrained, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs)
def season_game_logs(season): GH_TOKEN = os.getenv('GH_TOKEN', '') g = Github(GH_TOKEN) repo = g.get_repo('chadwickbureau/retrosheet') gamelogs = [f.path[(f.path.rfind('/') + 1):] for f in repo.get_contents('gamelog')] file_name = f'GL{season}.TXT' if (file_name not in gamelogs): raise V...
def find_average_velocity(df): df['vbar'] = three_comp_average(df['vxbar'], df['vybar'], df['vzbar']) return df
def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): batch_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.eval() end = time.time() last_idx = (len(loader) - 1) with torch.no_grad(): for (batch_i...
class CustomJSONEncoder(JSONEncoder): def default(self, obj): try: if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') iterable = iter(obj) except TypeEr...
class BaseEncoder(nn.Module): def __init__(self): super(BaseEncoder, self).__init__() def forward(self, inputs, inputs_mask, **kargs): raise NotImplementedError def inference(self, inputs, inputs_mask, cache=None, **kargs): raise NotImplementedError
class IBNConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, use_ibn=False, activate=True): super(IBNConvBlock, self).__init__() self.activate = activate self.use_ibn = use_ibn self.conv = nn.Conv2d(in_ch...
def _renorm(x, dim=0, inplace=False, eps=1e-12): if (not inplace): x = x.clone() return x.div_(_norm_exclude_dim(x, dim, keepdim=True))
def plot_acc(acc, val_acc, epochs, val_epochs, save_path, plot_name): plt.figure() plt.plot(epochs, acc, label='training') plt.plot(val_epochs, val_acc, label='validation') plt.title('Training and validation acc') plt.ylabel('acc') plt.xlabel('epoch') plt.xlim(min(epochs), max(epochs)) p...
def data_type_dict(): return {'float16': torch.float16, 'float32': torch.float32, 'float64': torch.float64, 'uint8': torch.uint8, 'int8': torch.int8, 'int16': torch.int16, 'int32': torch.int32, 'int64': torch.int64, 'bool': torch.bool}
class KNNSearch(torch.nn.Module): def __init__(self, metric='L2', ignore_query_point=False, return_distances=False, index_dtype=torch.int32, **kwargs): self.metric = metric self.ignore_query_point = ignore_query_point self.return_distances = return_distances assert (index_dtype in [t...
def pyramidnet110_a270_cifar100(num_classes=100, **kwargs): return get_pyramidnet_cifar(num_classes=num_classes, blocks=110, alpha=270, bottleneck=False, model_name='pyramidnet110_a270_cifar100', **kwargs)
class DebertaTokenizeTransform(TokenizeTransform): def __init__(self, train): super().__init__(tokenizer=DebertaV2Tokenizer.from_pretrained('microsoft/deberta-v3-base')) del train
def make_mirror(src_module, dst_module): def setattr_recursive(mod, key, value): (key, *next_key) = key.split('.', maxsplit=1) if (not next_key): setattr(mod, key, value) else: setattr_recursive(getattr(mod, key), next_key[0], value) for (name, param) in src_modul...
def _add_file_handler(logger, path, level='INFO'): for h in logger.handlers: if isinstance(h, logging.FileHandler): if (os.path.abspath(path) == h.baseFilename): return if os.path.exists(path): assert os.path.isfile(path) warnings.warn('log already exists in {...
class SampleCountingLoader(): def __init__(self, loader): self.loader = loader def __iter__(self): it = iter(self.loader) storage = get_event_storage() while True: try: batch = next(it) num_inst_per_dataset = {} for data...
def test_run_emits_events_if_successful(run): run() observer = run.observers[0] assert observer.started_event.called assert observer.heartbeat_event.called assert observer.completed_event.called assert (not observer.interrupted_event.called) assert (not observer.failed_event.called)
def torch_nn_conv1d(self, input): l_in = input.shape[(- 1)] shape = None padding = self.padding if (padding == 'valid'): padding = (0, 0) if (padding == 'same'): shape = list(input.shape) if (shape is None): shape = list(input.shape) l_out = math.floor((((((l_in +...
def create_model(model_type: str, deterministic: bool, enc_blocks: int, conv_type: str, dataset_type: str, decoder: str, r: float, temperature: float, *args: Any, **kwargs: Any): if (dataset_type in ['mnist', 'bdp', 'pbt']): if (model_type == 'euclidean'): return FeedForwardVAE(*args, **kwargs) ...
def get_input_data(input_file, seq_length, batch_size, num_labels): def parser(record): name_to_features = {'input_ids': tf.FixedLenFeature([seq_length], tf.int64), 'input_mask': tf.FixedLenFeature([seq_length], tf.int64), 'segment_ids': tf.FixedLenFeature([seq_length], tf.int64), 'label_ids': tf.FixedLenFe...
class SpatialEncoder(nn.Module): def __init__(self, backbone='resnet18', pretrained=True, num_layers=3, index_interp='bilinear', index_padding='zeros', upsample_interp='bilinear', feature_scale=1.0, use_first_pool=True, norm_type='batch'): super().__init__() if (norm_type != 'batch'): as...
def proxylessnas_cpu(**kwargs): return get_proxylessnas(version='cpu', model_name='proxylessnas_cpu', **kwargs)
def get_site(): m = re.search('([^.]+)\\.brainpp\\.cn$', socket.getfqdn()) if m: return m.group(1)
def GetService(name, config_class): service = None while (service is None): rospy.wait_for_service(name) service = rospy.ServiceProxy(name, config_class) return service
def board8x8() -> Board: board = jnp.array([[2, 1, 1, 0, 2, 1, 1, 0], [2, 3, 1, 2, 2, 1, 1, 0], [2, 3, 1, 2, 2, 1, 1, 0], [2, 3, 0, 0, 2, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1, 2], [0, 1, 1, 2, 2, 3, 0, 0], [1, 0, 0, 2, 1, 2, 3, 5], [2, 0, 0, 0, 2, 1, 1, 5]]) return board
def inception_v2(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, min_depth=16, depth_multiplier=1.0, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV2'): if (depth_multiplier <= 0): raise ValueError('depth_multiplier is not greater than zero.') with tf.v...