code
stringlengths
101
5.91M
class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_cha...
class Sentence(): def __init__(self, tokens, default_date): self.tokens = tuple(tokens) self.vector = (sum([t.vector for t in tokens]) / len(tokens)) self.date = default_date self.time_span = 'd' for t in tokens: if t.date: self.date = t.date ...
def translate(pat): (i, n) = (0, len(pat)) res = '' while (i < n): c = pat[i] i = (i + 1) if (c == '*'): res = (res + '(.*)') elif (c == '?'): res = (res + '(.)') elif (c == '['): j = i if ((j < n) and (pat[j] == '!')): ...
def GetPageRankMP_PDirNet(Graph, PRankH, C=0.85, Eps=0.0001, MaxIter=100): return _snap.GetPageRankMP_PDirNet(Graph, PRankH, C, Eps, MaxIter)
def load_sparse_csr(filename): loader = np.load(filename, allow_pickle=True) matrix = sp.csr_matrix((loader['data'], loader['indices'], loader['indptr']), shape=loader['shape']) return (matrix, (loader['metadata'].item(0) if ('metadata' in loader) else None))
(**njit_dict_no_parallel) def move_r_packet(r_packet, distance, time_explosion, numba_estimator): doppler_factor = get_doppler_factor(r_packet.r, r_packet.mu, time_explosion) r = r_packet.r if (distance > 0.0): new_r = np.sqrt((((r * r) + (distance * distance)) + (((2.0 * r) * distance) * r_packet.m...
def require_pyctcdecode(test_case): if (not is_pyctcdecode_available()): return unittest.skip('test requires pyctcdecode')(test_case) else: return test_case
def load_options(args, options): varargs = vars(args) name = [] for o in options: with open(o) as f: new_opts = yaml.safe_load(f) for (k, v) in new_opts.items(): if (k not in varargs): raise ValueError(f'Option {k}={v} doesnt exist!') varargs.u...
def test_log_softmax_translation(log_softmax_x, log_softmax_expected): x = (log_softmax_x + 100) expected = log_softmax_expected assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
def get_mol(smiles_or_mol): if isinstance(smiles_or_mol, str): if (len(smiles_or_mol) == 0): return None mol = Chem.MolFromSmiles(smiles_or_mol) if (mol is None): return None try: Chem.SanitizeMol(mol) except ValueError: return ...
def split_text(text, n=100, character=' '): text = text.split(character) return [character.join(text[i:(i + n)]).strip() for i in range(0, len(text), n)]
def merge_features_into_file(directory, postfix): feat_subf = os.listdir(directory) feat_subf = list(filter((lambda x: os.path.isdir(os.path.join(directory, x))), feat_subf)) users = os.listdir(os.path.join(directory, feat_subf[0])) users = list(filter((lambda x: os.path.isdir(os.path.join(directory, fe...
def skip_exception_type(exc_type): try: (yield) except exc_type as e: raise unittest.SkipTest(f'not implemented: {e}') from e
class EpilogueThreadMap(): def __init__(self, threads, elements_per_access, element_size_bits, shape, iterations, delta, count): self.threads = threads self.elements_per_access = elements_per_access self.element_size_bits = element_size_bits self.shape = shape self.iterations...
def min_linear_barrier(x: sf.Scalar, x_nominal: sf.Scalar, error_nominal: sf.Scalar, dist_zero_to_nominal: sf.Scalar) -> sf.Scalar: return min_power_barrier(x=x, x_nominal=x_nominal, error_nominal=error_nominal, dist_zero_to_nominal=dist_zero_to_nominal, power=1)
_metric def fid50k_trans(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) fid = frechet_inception_distance.compute_fid_trans(opts, max_real=None, num_gen=10000) return dict(fid50k_trans=fid)
def cvt_to_coco_json(img_infos, classes): image_id = 0 coco = dict() coco['images'] = [] coco['type'] = 'instance' coco['categories'] = [] coco['annotations'] = [] image_set = set() for (category_id, name) in enumerate(classes): category_item = dict() category_item['super...
class SimpleCategoricalLSTMModel(SimpleLSTMModel): def __init__(self, output_dim, hidden_dim, name, *args, **kwargs): super().__init__(output_dim, hidden_dim, name) def network_output_spec(self): return ['all_output', 'step_output', 'step_hidden', 'step_cell', 'init_hidden', 'init_cell', 'dist']...
def model_fn_builder(bert_config, init_checkpoint, use_tpu, use_one_hot_embeddings): def model_fn(features, labels, mode, params): input_ids = features['input_ids'] input_mask = features['input_mask'] input_type_ids = features['input_type_ids'] model = modeling.BertModel(config=bert_...
class ListObjsCommand(BaseUserCommand): def tabulate(self, rows: List[List[Union[(str, int)]]], headers: List[str]) -> str: col_widths = [max((len(str(x)) for x in col)) for col in zip(*rows, headers)] row_format = ('{{:{}}} ' * len(headers)).format(*col_widths) lines = [] lines.appe...
class KLEnergy(object): def __init__(self, dist): self._dist = dist assert (self._dist.covariance_type == 'spherical') def _params_from_indices(self, i, j): mu_i = self._dist.mu[i] mu_j = self._dist.mu[j] Sigma_i = self._dist.Sigma[i] Sigma_j = self._dist.Sigma[j]...
def cdp_delta(rho, eps): assert (rho >= 0) assert (eps >= 0) if (rho == 0): return 0 amin = 1.01 amax = (((eps + 1) / (2 * rho)) + 2) for i in range(1000): alpha = ((amin + amax) / 2) derivative = (((((2 * alpha) - 1) * rho) - eps) + math.log1p(((- 1.0) / alpha))) ...
def main(): global args parser = arg_parser() args = parser.parse_args() cfg = setup_cfg(args) train_split = cfg.DATASET.TRAIN_SPLIT val_split = cfg.DATASET.VAL_SPLIT val_gzsl_split = cfg.DATASET.VAL_GZSL_SPLIT train_dataset = build_dataset(cfg, train_split, cfg.DATASET.ZS_TRAIN) tra...
def notebook2script(fname): fname = Path(fname) fname_out = f"nb_{fname.stem.split('_')[0]}.py" main_dic = json.load(open(fname, 'r')) code_cells = [c for c in main_dic['cells'] if is_export(c)] module = f''' ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### # file to edit: dev_nb/{fname.name} ''' ...
class BatchSquareDiagonal(nn.Module): def __init__(self, vector_size): super().__init__() self.vector_size = vector_size self.diag_mask = ptu.Variable(torch.diag(torch.ones(vector_size)), requires_grad=False) def forward(self, vector, diag_values): M = ptu.batch_diag(diag_values=...
def test(): print('SDFG memlet lifetime validation test') N = dp.symbol('N') N.set(20) input = dp.ndarray([N], dp.int32) output = dp.ndarray([N], dp.int32) input[:] = dp.int32(5) output[:] = dp.int32(0) sdfg1 = SDFG('shouldntwork1') state = sdfg1.add_state() A = state.add_array('...
def config_log(log_dir, filename='log.txt'): log_dir = ('logs/' + log_dir) os.makedirs(log_dir, exist_ok=True) logging.basicConfig(filename=os.path.join(log_dir, filename), level=logging.INFO, format='%(asctime)s - %(message)s')
def LinearActivation(d_input, d_output, bias=True, zero_bias_init=False, transposed=False, initializer=None, activation=None, activate=False, weight_norm=False, **kwargs): linear_cls = (TransposedLinear if transposed else nn.Linear) if ((activation is not None) and activation.startswith('glu')): d_outpu...
def get_model_space(out_filters=64, num_layers=9): model_space = ModelSpace() num_pool = 4 expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)] for i in range(num_layers): model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kernel...
class ModelCard(): def __init__(self, **kwargs): warnings.warn('The class `ModelCard` is deprecated and will be removed in version 5 of Transformers', FutureWarning) self.model_details = kwargs.pop('model_details', {}) self.intended_use = kwargs.pop('intended_use', {}) self.factors =...
def mean_drop_logit(i: int) -> Callable: return (lambda x: torch.mean(x[i].drop_logits, dim=0).view((- 1)))
class DglPCQM4Mv2Dataset(object): def __init__(self, root='dataset', smiles2graph=smiles2graph): self.original_root = root self.smiles2graph = smiles2graph self.folder = osp.join(root, 'pcqm4m-v2') self.version = 1 self.url = ' if (osp.isdir(self.folder) and (not osp....
class SG(Enum): PL_gather_d1coor = 0 PL_gather_d2coor = 1 PL_gather_rec = 2 PL_scatter_d1coor = 3 PL_scatter_d2coor = 4 PE_S_gather_d1coor = 5 PE_S_scatter_d1coor = 6 PE_M_gather_d1coor = 7 PE_S_mask_select = 8 PE_S_nonzero = 9 PE_S_scatter_pp_d1coor = 10 PE_S_gather_hzd ...
def cli_main(): parser = rerank_options.get_reranking_parser() args = options.parse_args_and_arch(parser) rerank(args)
def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--eval_list', help='Text file containing names of videos to be evaluated on.', type=argparse.FileType('r'), required=True) parser.add_argument('-s', '--score_list', help='Text file containing paths of input prediction .pt f...
class CARDDictionary(): def __init__(self, card_path: str, umls: UMLS, class_map: Mapping[(str, int)]): self.card_path = card_path self.umls = umls self.class_map = class_map def get_words(self) -> Dict[(int, Dict[(str, List[str])])]: vabbr: Dict[(int, Dict[(str, List[str])])] = ...
def test_deepfill_dec(): decoder = DeepFillDecoder(128, out_act_cfg=None) assert (not decoder.with_out_activation) decoder = DeepFillDecoder(128) x = torch.randn((2, 128, 64, 64)) input_dict = dict(out=x) res = decoder(input_dict) assert (res.shape == (2, 3, 256, 256)) assert (decoder.de...
def create_model(session, vocab_size, forward_only): model = nlc_model.NLCModel(vocab_size, FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size, FLAGS.learning_rate, FLAGS.learning_rate_decay_factor, FLAGS.dropout, forward_only=forward_only) ckpt = tf.train.get_checkpoint_state(FLAGS.train_d...
def ResNeXt29(cardinality, base_width, num_classes=10): Block = partial(ResNeXtBottleneck, cardinality=cardinality, base_width=base_width) Block.__name__ = ResNeXtBottleneck.__name__ Block.expansion = ResNeXtBottleneck.expansion return ResNet(Block, layers=[3, 3, 3], filters=[64, 128, 256], num_classes=...
class dual_softmax_loss(nn.Module): def __init__(self): super(dual_softmax_loss, self).__init__() def forward(self, sim_matrix, temp=1000): sim_matrix = ((sim_matrix * F.softmax((sim_matrix / temp), dim=0)) * len(sim_matrix)) logpt = F.log_softmax(sim_matrix, dim=(- 1)) logpt = t...
class HerTd3(HER, TD3): def __init__(self, *args, td3_kwargs, her_kwargs, base_kwargs, **kwargs): HER.__init__(self, **her_kwargs) TD3.__init__(self, *args, **kwargs, **td3_kwargs, **base_kwargs) assert (isinstance(self.replay_buffer, SimpleHerReplayBuffer) or isinstance(self.replay_buffer, ...
class GatherEnv(Env, Serializable): MODEL_CLASS = None ORI_IND = None ('n_apples', type=int, help='Number of apples in each episode') ('n_bombs', type=int, help='Number of bombs in each episode') ('activity_range', type=float, help='The span for generating objects (x, y in [-range, range])') ('r...
def test_moreau_yosida_regularization(): u.vector().vec().set(1000.0) u.vector().apply('') y_bar = 0.1 y_low = 0.01 gamma = 1000.0 reg = cashocs._utils.moreau_yosida_regularization(y, gamma, dx, upper_threshold=y_bar, lower_threshold=y_low) max = cashocs._utils.max_ min = cashocs._utils....
def get_non_root_control_flow_distance(result: ExecutionResult, predicate_id: int, value: bool, tracer: ExecutionTracer) -> ControlFlowDistance: trace = result.execution_trace code_object_id = tracer.get_subject_properties().existing_predicates[predicate_id].code_object_id distance = ControlFlowDistance() ...
.parametrize('sampling_strategy, err_msg', [({0: (- 100), 1: 50, 2: 50}, 'in a class cannot be negative'), ({0: 10, 1: 70}, 'should be less or equal to the original')]) def test_make_imbalance_error(iris, sampling_strategy, err_msg): (X, y) = iris with pytest.raises(ValueError, match=err_msg): make_imba...
def styblinski_tang(ind): return ((sum(((((x ** 4.0) - (16.0 * (x ** 2.0))) + (5.0 * x)) for x in ind)) / 2.0),)
class AlgoTrainer(BaseAlgo): def __init__(self, algo_init, args): super(AlgoTrainer, self).__init__(args) self.vae = algo_init['vae']['net'] self.vae_opt = algo_init['vae']['opt'] self.actor = algo_init['actor']['net'] self.actor_opt = algo_init['actor']['opt'] self.c...
class Mixed_4f(nn.Module): def __init__(self): super(Mixed_4f, self).__init__() self.branch0 = nn.Sequential(BasicConv3d(528, 256, kernel_size=1, stride=1)) self.branch1 = nn.Sequential(BasicConv3d(528, 160, kernel_size=1, stride=1), SepConv3d(160, 320, kernel_size=3, stride=1, padding=1)) ...
def test_fortran_frontend_maxval_double(): test_string = '\n PROGRAM minval_test\n implicit none\n double precision, dimension(7) :: d\n double precision, dimension(4) :: res\n CALL minval_test_function(d, res)\n ...
class TransitionModel(object): def __init__(self, gridspec, eps=0.2): self.gs = gridspec self.eps = eps def get_aprobs(self, s, a): legal_moves = self.__get_legal_moves(s) p = np.zeros(len(ACT_DICT)) p[list(legal_moves)] = (self.eps / len(legal_moves)) if (a in le...
def kaiming_init(module: nn.Module, a: float=0, mode: str='fan_out', nonlinearity: str='relu', bias: float=0, distribution: str='normal') -> None: assert (distribution in ['uniform', 'normal']) if (hasattr(module, 'weight') and (module.weight is not None)): if (distribution == 'uniform'): nn...
def cli_main(): parser = options.get_validation_parser() add_distributed_training_args(parser) args = options.parse_args_and_arch(parser) override_parser = options.get_validation_parser() add_distributed_training_args(override_parser) override_args = options.parse_args_and_arch(override_parser, ...
def get_video_frames_perturbed(video_dir, batch_size): def get_key(x): return int(x.split('/')[(- 1)].split('_')[0]) landmark_paths = sorted(glob(f'{video_dir}/*_landmarks.npz'), key=(lambda x: get_key(x))) index = random.randint(0, max(5, ((len(landmark_paths) - batch_size) - 1))) source_landma...
def write_shards(dns_folder_path: pathlib.Path, shards_path: pathlib.Path, seed: int, samples_per_shard: int, min_dur: float): shards_path.mkdir(parents=True, exist_ok=True) audio_files = sorted([f for f in dns_folder_path.rglob('*.wav')]) data_tuples = [] all_language_ids = set() sample_keys_per_la...
_grad() def test(model, device, loader, evaluator): model.eval() (y_pred, y_true) = ([], []) for (x, y) in tqdm(loader): x = x.to(device) out = model(x) y_pred.append(torch.argmax(out, dim=1, keepdim=True).cpu()) y_true.append(y) return evaluator.eval({'y_true': torch.cat...
def test_orderedset_reversed(): ordered = OrderedSet([1, 2, 3]) assert (tuple(reversed(ordered)) == (3, 2, 1))
def existing_file(file_name): try: with open(file_name, 'r') as file: return file.read() except Exception: raise argparse.ArgumentTypeError('The file provided could not be opened.')
def kaldi_env(kaldi_root): kaldi_root = kaldi_root.strip() os.environ['KALDI_ROOT'] = kaldi_root os.environ['PATH'] = ((os.popen('echo $KALDI_ROOT/src/bin:$KALDI_ROOT/tools/openfst/bin:$KALDI_ROOT/src/fstbin/:$KALDI_ROOT/src/gmmbin/:$KALDI_ROOT/src/featbin/:$KALDI_ROOT/src/lm/:$KALDI_ROOT/src/sgmmbin/:$KALD...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) .parametrize('prob', [0.7, 1.0]) .parametrize('area_ratios', [(0.02, 0.04)]) .parametrize('aspect_ratios', [(0.3, 3.3333)]) .parametrize('replacements', [(2.0, 2.0), (3.0, 4.0)]) .parametrize('n', [1, 3]) .parametrize('share', [True, False]) .parametrize(...
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15): to_dir = os.path.abspath(to_dir) try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen tgz_name = ('distribute-%s.tar.gz' % version) url = (downl...
def main(): args = ArgParser().parse_args() args.eval_filter = (not args.no_eval_filter) if args.neg_deg_sample_eval: assert (not args.eval_filter), "if negative sampling based on degree, we can't filter positive edges." assert os.path.exists(args.model_path), 'No existing model_path: {}'.format...
def _sage_getsourcelines_name_with_dot(obj): if ('.' in obj.__name__): splitted_name = obj.__name__.split('.') elif hasattr(obj, '__qualname__'): splitted_name = obj.__qualname__.split('.') else: splitted_name = obj.__name__ path = (obj.__module__.split('.') + splitted_name[:(- 1...
def make_divisible(v: int, divisor: int=8, min_value: int=None): min_value = (min_value or divisor) new_v = max(min_value, ((int((v + (divisor / 2))) // divisor) * divisor)) if (new_v < (0.9 * v)): new_v += divisor return new_v
def bond_features(bond, use_chirality=True): bt = bond.GetBondType() bond_feats = [(bt == Chem.rdchem.BondType.SINGLE), (bt == Chem.rdchem.BondType.DOUBLE), (bt == Chem.rdchem.BondType.TRIPLE), (bt == Chem.rdchem.BondType.AROMATIC), bond.GetIsConjugated(), bond.IsInRing()] if use_chirality: bond_fea...
def find_before(ctx, pos, substr, offsets=(0, 0)): new_pos = ctx.source[:pos].rindex(substr) return ctx.make_raw_range((new_pos + offsets[0]), ((new_pos + len(substr)) + offsets[1]))
_task('speech_text_joint_to_text') class SpeechTextJointToTextTask(SpeechToTextTask): def add_args(cls, parser): super(SpeechTextJointToTextTask, cls).add_args(parser) parser.add_argument('--parallel-text-data', default='', help='path to parallel text data directory') parser.add_argument('--...
def _parse_line(line: str, split_on=' ') -> List[int]: return list(map(int, map(str.strip, line.split(split_on))))
class COVIDDialogScenario(Scenario): SOURCE_URL_TEMPLATE: str = ' name = 'covid_dialog' description = 'Medical dialogue dataset of conversations between doctors and patients on their COVID-19 concerns' tags = ['dialogue', 'biomedical'] def get_instances(self, output_path: str) -> List[Instance]: ...
_module class TextLoggerHook(LoggerHook): def __init__(self, by_epoch=True, interval=200, ignore_last=True, reset_flag=False, interval_exp_name=1000): super(TextLoggerHook, self).__init__(interval, ignore_last, reset_flag, by_epoch) self.by_epoch = by_epoch self.time_sec_tot = 0 self...
def osnet_ain_x1_0(num_classes=1000, pretrained=True, loss='softmax', **kwargs): model = OSNet(num_classes, blocks=[[OSBlockINv1, OSBlockINv1], [OSBlock, OSBlockINv1], [OSBlockINv1, OSBlock]], layers=[2, 2, 2], channels=[64, 256, 384, 512], loss=loss, conv1_IN=True, **kwargs) return model
def alphanumeric_key(s): k = [(int(c) if c.isdigit() else c) for c in re.split('([0-9]+)', s)] return k
def _print_alignment_header(wer_details, file=sys.stdout): print(('=' * 80), file=file) print('{key}, %WER {WER:.2f} [ {num_edits} / {num_ref_tokens}, {insertions} ins, {deletions} del, {substitutions} sub ]'.format(**wer_details), file=file)
def test_eb_constraints(): def f(x): return (((x[0] ** 3) + (x[1] ** 2)) + (x[2] * x[3])) def cfun(x): return ((((x[0] + x[1]) + x[2]) + x[3]) - 40) constraints = [{'type': 'ineq', 'fun': cfun}] bounds = ([(0, 20)] * 4) bounds[1] = (5, 5) optimize.minimize(f, x0=[1, 2, 3, 4], met...
def postprocess_train(all_features, sample_level): all_features = {k: [postprocess_train_row(row, sample_level) for row in class_dt] for (k, class_dt) in all_features.items()} return all_features
def dump(data, stream=None, Dumper=Dumper, **kwds): return dump_all([data], stream, Dumper=Dumper, **kwds)
def try_touch_shape(array: Any): if isinstance(array, TypeTracerArray): array.touch_shape()
def get_model_bn(num_channels, nfs, kss, l2regfactors, alpha, dropout_factor, num_dense): inp_tensor1 = Input(shape=(288, 288, num_channels)) inp_tensor2 = Input(shape=(288, 288, num_channels)) n_img1 = normalize_tensor_image(inp_tensor1) n_img2 = normalize_tensor_image(inp_tensor2) total_inp_1 = n_...
def run_training(args): all_X = np.eye(args.d, args.d, dtype=np.float32) all_sup_Nary_Y = np.random.randint(0, args.k, args.d) all_sup_Y = np.zeros((args.d, args.k), dtype=np.float32) for j in range(args.d): all_sup_Y[(j, all_sup_Nary_Y[j])] = 1 with tf.Graph().as_default(): session ...
def get_optimizer_scheduler(args, model, t_total): no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [{'params': [p for (n, p) in model.named_parameters() if (not any(((nd in n) for nd in no_decay)))], 'weight_decay': args.weight_decay}, {'params': [p for (n, p) in model.named_parameters() ...
class BasePartitioner(metaclass=abc.ABCMeta): def __init__(self, num_partitions: Optional[int]=None, model_parallel_submesh: Optional[HardwareMesh]=None, params_on_devices: bool=True, backend: Optional[str]=None): if ((not num_partitions) and (not model_parallel_submesh)): raise ValueError('At l...
def conll09_srl_eval_tf(predictions, targets, predicate_predictions, words, mask, predicate_targets, reverse_maps, gold_srl_eval_file, pred_srl_eval_file, pos_predictions, pos_targets, parse_head_targets, parse_head_predictions, parse_label_targets, parse_label_predictions): with tf.name_scope('conll_srl_eval'): ...
def test_check_feature_names_error(): X = np.random.randn(10, 3) feature_names = ['a', 'b', 'c', 'a'] msg = 'feature_names should not contain duplicates.' with pytest.raises(ValueError, match=msg): _check_feature_names(X, feature_names)
def test_compute_fractal_dimension_convergence(): fractal_dimension_test('convergence.png', 1.83)
def get_text_prompts(label): return [f'a photo of {label}.', f'a photo of the small {label}.', f'a low resolution photo of a {label}.', f'a photo of many {label}.']
class InfinityType(object): def __repr__(self): return 'Infinity' def __hash__(self): return hash(repr(self)) def __lt__(self, other): return False def __le__(self, other): return False def __eq__(self, other): return isinstance(other, self.__class__) def ...
class TestEvaluationMetrics(): def setup_method(self): self.ground = [1, 2, 3] self.prediction_a = [1, 2, 3] self.prediction_b = [2, 2, 2] self.prediction_c = [3, 2, 1] def test_r_squared(self): assert (sk.r_squared(self.ground, self.prediction_a) == 1) assert (sk...
def resnet18(pretrained_path=None): model = ResNet(BasicBlock, [2, 2, 2, 2]) if (pretrained_path is not None): model.load_state_dict(torch.load(pretrained_path)) print('Loaded pre-trained weights') return model
def omegaconf_to_dict(omegaconf, name): return {((name + '_') + k): v for (k, v) in omegaconf.to_dict()}
def to_local_command(params, python_command='python', script=osp.join(config.PROJECT_PATH, 'scripts/run_experiment.py'), use_gpu=False): command = ((python_command + ' ') + script) if (use_gpu and (not config.USE_TF)): command = ("THEANO_FLAGS='device=gpu,dnn.enabled=auto' " + command) for (k, v) in...
def main(): args = parse_args() assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"' if (args.eval and ar...
def kernel3(a, mat): mat_type = ti.types.matrix(mat.n, mat.m, ti.i32) def kernel(u: ti.i32, v: mat_type) -> mat_type: return (u * v) return kernel(a, mat)
def write_plotting_data(arch_str, data_obj): plotting_dir = os.path.join('..', 'plotting_data', arch_str) if (not os.path.isdir(plotting_dir)): os.makedirs(plotting_dir) write_loc = os.path.join(plotting_dir, 'data.json') json_data = json.dumps(data_obj, indent=4) print('Writing') with o...
class BasicTransformerBlock(nn.Module): def __init__(self, dim, n_heads, d_head, dropout=0.0, context_dim=None, gated_ff=True, checkpoint=False): super().__init__() self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) self.ff = FeedForward(dim, dropout=...
class Normalize(object): def __init__(self, mean, std, inplace=False): self.mean = mean self.std = std self.inplace = inplace def __call__(self, img, mask): return (F.normalize(img, self.mean, self.std, self.inplace), mask)
def test_date_time(): numpy_array = np.array(['2020-07-27T10:41:11', '2019-01-01', '2020-01-01'], 'datetime64[s]') array = ak.highlevel.Array(numpy_array) assert (str(array.type) == '3 * datetime64[s]') assert (array.to_list() == [np.datetime64('2020-07-27T10:41:11'), np.datetime64('2019-01-01T00:00:00'...
def obj_centened_camera_pos(dist, azimuth_deg, elevation_deg): phi = ((float(elevation_deg) / 180) * math.pi) theta = ((float(azimuth_deg) / 180) * math.pi) x = ((dist * math.cos(theta)) * math.cos(phi)) y = ((dist * math.sin(theta)) * math.cos(phi)) z = (dist * math.sin(phi)) return (x, y, z)
class SynchronizedSeedDataset(SynchronizedDataset): def __getitem__(self, idx): self.sync_once() return torch.initial_seed()
def main(): parser = argparse.ArgumentParser() register_args(parser) args = parser.parse_args() if (os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and (not args.overwrite_output_dir)): raise ValueError('Output directory ({}) already exists and is not empty. Use...
def collate_dicts(batch: List[Batch]) -> Batch: X_batch: Dict[(str, Any)] = defaultdict(list) Y_batch: Dict[(str, Any)] = defaultdict(list) for (x_dict, y_dict) in batch: for (field_name, value) in x_dict.items(): X_batch[field_name].append(value) for (label_name, value) in y_dic...
class DataGenerator(Dataset): def __init__(self, img_dir, split_file, transform): self.img_name_list = [] self.img_label_list = [] self.transform = transform with open(split_file, 'r') as split_name: img_and_label_list = split_name.readlines() for index in img_and...