code
stringlengths
101
5.91M
def dynamic_load(pkg_name, pkg_dict, model_name): assert (model_name in pkg_dict.keys()) module_path = f'{pkg_name}.{pkg_dict[model_name][0]}' module = import_module(module_path) return getattr(module, pkg_dict[model_name][1])
def get_downstream_svhn(args): training_file_name = 'train.npz' testing_file_name = 'test.npz' if (args.encoder_usage_info == 'cifar10'): print('test_transform_cifar10') test_transform = test_transform_cifar10 elif (args.encoder_usage_info == 'stl10'): print('test_transform_stl10...
class Conv2d(nn.Conv2d): def __init__(self, in_channels: int, out_channels: int, output_dim: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: Union[(str, _size_2_t)]=0, dilation: _size_2_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros', layer_config: dict=None): super(Conv2d, self)._...
def report_func(epoch, batch, num_batches, progress_step, start_time, lr, report_stats): if ((batch % opt.report_every) == ((- 1) % opt.report_every)): report_stats.output(epoch, (batch + 1), num_batches, start_time) if opt.exp_host: report_stats.log('progress', experiment, lr) i...
class ResNeXt101_32x4d(nn.Module): def __init__(self, nb_classes=1000): super(ResNeXt101_32x4d, self).__init__() self.features = resnext101_32x4d_features self.avgpool = nn.AvgPool2d((7, 7), (1, 1)) self.fc = nn.Linear(2048, nb_classes) def forward(self, input): x = self....
.parametrize('spec', spec_list) def test_env_semantics(spec): logger.warn('Skipping this test. Existing hashes were generated in a bad way') return with open(ROLLOUT_FILE) as data_file: rollout_dict = json.load(data_file) if (spec.id not in rollout_dict): if (not spec.nondeterministic): ...
class LayoutLMTokenizerFast(BertTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION model_input_names = ['attention_m...
class GroupRandomCrop(object): def __init__(self, size): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size def __call__(self, img_group): (w, h) = img_group[0].size (th, tw) = self.size out_images = list...
class FuseMatMulRequantizeTransformer(GraphRewriterBase): def __init__(self, model, device='cpu'): super().__init__(model) self.device = device self.graph_analyzer = GraphAnalyzer() self.graph_analyzer.graph = self.model self.eps = 1e-05 self.graph_info = self.graph_a...
def get_cpu_qusub_script(name, hostname, queue, out_dir, script_to_execute, memory=20): s = '#!/bin/bash\n#\n#$ -N {}\n#\n## otherwise the default shell would be used\n#$ -S /bin/bash\n\n## demand gpu resource\n#$ -l hostname={}\n\n## <= 1h is short queue, <= 6h is middle queue, <= 48 h is long queue\n#$ -q {}.*\n\...
def init_appid_apikey(appid_user, apikey_user): global appid global apikey appid = appid_user apikey = apikey_user
def test_5_digits_suffix_version_new(): ref_line = u'{any prefix}1310.12345v9 [physics.ins-det]{any postfix}' r = tag_arxiv(ref_line) assert (r.strip(': ') == u'{any prefix}<cds.ARXIV>arXiv:1310.12345 [physics.ins-det]</cds.ARXIV>{any postfix}')
def load_text_from_file(path: Union[(Path, str)], text_name: str='', open_text: bool=False) -> None: path = zpy.files.verify_path(path) if (bpy.data.texts.get(text_name, None) is None): _text = bpy.data.texts.load(str(path), internal=True) _text.name = text_name else: bpy.data.texts[...
def test_module_converter_convert_dummy_net_copy_weights(dummy_net_constructor, mode_types): for mode in mode_types: dummy_net = dummy_net_constructor() layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1} w1 = dummy_net.conv1.weight.data w2 = dummy_net.fc....
class ValidationDatapoint(utils.JsonSerializable): n_parse_success: int n_comp_success: int n_test_success: int total_time_consumed: float gen_datapoint: GenerationDatapoint def compilable_by_parsable(self) -> float: return (self.n_comp_success / self.n_parse_success) def plausible_b...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('label_dir', type=str, help='Path to the SoccerNetV2 labels') parser.add_argument('frame_dir', type=str, help='Path to extracted video frames') parser.add_argument('-o', '--out_dir', type=str, help='Path to output parsed dataset') ...
_model def gluon_senet154(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['gluon_senet154'] block_args = dict(attn_layer=SEModule) model = ResNet(Bottleneck, [3, 8, 36, 3], cardinality=64, base_width=4, stem_type='deep', down_kernel_size=3, block_reduce_first=2, num_cla...
def parse_resume_step_from_filename(filename): if (filename[(- 3):] == '.pt'): return int(filename[(- 9):(- 3)]) else: return 0
def collate_eval(batch): indice = [b[0] for b in batch] image = torch.stack([b[1] for b in batch]) label = torch.stack([b[2] for b in batch]) return (indice, image, label)
class StitchWidget(DOMWidget): _model_name = Unicode('StitchModel').tag(sync=True) _model_module = Unicode(module_name).tag(sync=True) _model_module_version = Unicode(module_version).tag(sync=True) _view_name = Unicode('StitchView').tag(sync=True) _view_module = Unicode(module_name).tag(sync=True) ...
def get_host_info(): host_info = {} for (k, v) in host_info_gatherers.items(): try: host_info[k] = v() except IgnoreHostInfo: pass return host_info
_register_to_config class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin): sample_size: int = 32 in_channels: int = 4 down_block_types: Tuple[str] = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D') only_cross_attention: Union[(bool, Tuple[bool])] = Fals...
_torch class TrainerCallbackTest(unittest.TestCase): def setUp(self): self.output_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.output_dir) def get_trainer(self, a=0, b=0, train_len=64, eval_len=64, callbacks=None, disable_tqdm=False, **kwargs): train_dataset = Regr...
def bottleNeck(nin, nmid): return nn.Sequential(nn.BatchNorm2d(nin), nn.ReLU(), nn.Conv2d(nin, nmid, kernel_size=1, stride=1, padding=0), nn.BatchNorm2d(nmid), nn.ReLU(), nn.Conv2d(nmid, nmid, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(nmid), nn.ReLU(), nn.Conv2d(nmid, (nmid * 4), kernel_size=1, stride=1, ...
class Accuracy(nn.Module): def __init__(self, topk=(1,)): super().__init__() self.topk = topk def forward(self, pred, target): return accuracy(pred, target, self.topk)
class NNBase(nn.Module): def __init__(self, recurrent: bool, recurrent_input_size: int, hidden_size: int): super().__init__() self._hidden_size = hidden_size self._recurrent = recurrent if recurrent: self.gru = nn.GRU(recurrent_input_size, hidden_size) for (na...
class _scaledL2(Function): def forward(ctx, X, C, S): if X.is_cuda: SL = lib.gpu.scaled_l2_forward(X, C, S) else: raise NotImplemented ctx.save_for_backward(X, C, S, SL) return SL def backward(ctx, gradSL): (X, C, S, SL) = ctx.saved_variables ...
_dataset_obj('svhn2mnist') class Svhn2MNIST(CycleGANDataset): def __init__(self, root, train=True, transform=None, target_transform=None, download=False): if (not train): print('No test set for svhn2mnist.') self.image_paths = [] else: super(Svhn2MNIST, self).__in...
def EfficientNetB7(include_top=True, input_tensor=None, input_shape=None, pooling=None, classes=1000, dropout_rate=0.5, drop_connect_rate=0.2, **kwargs): return EfficientNet(2.0, 3.1, 600, model_name='efficientnet-b7', include_top=include_top, input_tensor=input_tensor, input_shape=input_shape, pooling=pooling, cla...
def inspect_all_records(valid_list: list, invalid_list: list, sym_list: list, tree: ArithExpTree, sign: str) -> bool: for inputs in valid_list: val = [] for argNum in sym_list: val.append(inputs[argNum]) res = eval(f'tree.evaluate(val) {sign} 0') if (not res): ...
class GPTSanJapaneseForConditionalGeneration(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test_digits_cosine_greedi_ll_sparse(): model = SaturatedCoverageSelection(100, 'precomputed', optimizer='greedi', optimizer_kwds={'optimizer1': 'lazy', 'optimizer2': 'lazy'}, random_state=0) model.fit(X_digits_cosine_sparse) assert_array_equal(model.ranking[:2], digits_cosine_greedi_ranking[:2]) ass...
def mkdirs(paths): if (isinstance(paths, list) and (not isinstance(paths, str))): for path in paths: mkdir(path) else: mkdir(paths)
class ImageNetBase(Dataset): def __init__(self, config=None): self.config = (config or OmegaConf.create()) if (not (type(self.config) == dict)): self.config = OmegaConf.to_container(self.config) self.keep_orig_class_label = self.config.get('keep_orig_class_label', False) ...
class TestTridentRoIHead(TestCase): def setUp(self): register_all_modules() self.roi_head_cfg = get_roi_head_cfg('tridentnet/tridentnet_r50-caffe_1x_coco.py') def test_init(self): roi_head = MODELS.build(self.roi_head_cfg) self.assertTrue(roi_head.with_bbox) self.assertTr...
class ImageFileTrain(ImageFile): def __init__(self, alpha_dir='train_alpha', fg_dir='train_fg', bg_dir='train_bg', alpha_ext='.jpg', fg_ext='.jpg', bg_ext='.jpg'): super(ImageFileTrain, self).__init__(phase='train') self.alpha_dir = alpha_dir self.fg_dir = fg_dir self.bg_dir = bg_dir...
def upsampleSum(x, conv, filters=128, ratio=0.5, activation=ACTIVATION, name=None): with tf.name_scope(name) as scope: x_up = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='nearest')(x) p = (((1.0 - ratio) * x_up) + (ratio * conv2DBatchNorm(conv, filters=filters, kernel_size=(1, 1), name=(...
def test_detector(args): os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu model = Detector(args) model = model.cuda() model.load_state_dict(torch.load(args.model_path)) model.eval() velodyne_dir = os.path.join(args.data_dir, 'sequences', args.test_seq, 'velodyne_txt') velodyne_names = os.listdi...
class UniNorm2d(_UniNorm): def _check_input_dim(self, input): if (input.dim() != 4): raise ValueError('expected 4D input (got {}D input)'.format(input.dim()))
def prepare_dataset(voxel_size): print(':: Load two point clouds and disturb initial pose.') demo_icp_pcds = o3d.data.DemoICPPointClouds() source = o3d.io.read_point_cloud(demo_icp_pcds.paths[0]) target = o3d.io.read_point_cloud(demo_icp_pcds.paths[1]) trans_init = np.asarray([[0.0, 0.0, 1.0, 0.0], ...
class LiltPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def load_n2d(encoder_id, manifold_id): man = pickle.load(open(manifold_id, 'rb')) out = n2d(10, man) out.encoder = load_model(encoder_id, compile=False) return out
def parse_args(): parser = argparse.ArgumentParser(description='Goes through all the inline-links in markdown files and reports the breakages') parser.add_argument('--num-threads', type=int, default=100, help='Number of processes to confirm the link') parser.add_argument('-- type=str, help=' proxy') par...
class SoftEntropy(nn.Module): def __init__(self): super(SoftEntropy, self).__init__() self.logsoftmax = nn.LogSoftmax(dim=1).cuda() def forward(self, inputs, targets): log_probs = self.logsoftmax(inputs) loss = ((- F.softmax(targets, dim=1).detach()) * log_probs).mean(0).sum() ...
def rouge_n(eval_sentences, ref_sentences, n=2): f1_scores = [] for (eval_sentence, ref_sentence) in zip(eval_sentences, ref_sentences): eval_ngrams = _get_ngrams(n, eval_sentence) ref_ngrams = _get_ngrams(n, ref_sentence) ref_count = len(ref_ngrams) eval_count = len(eval_ngrams)...
def test_minesweeper__does_not_smoke(minesweeper_env: Minesweeper) -> None: check_env_does_not_smoke(env=minesweeper_env)
def sum_logits(args, mask=None, name=None): with tf.name_scope((name or 'sum_logits')): if ((args is None) or (nest.is_sequence(args) and (not args))): raise ValueError('`args` must be specified') if (not nest.is_sequence(args)): args = [args] rank = len(args[0].get_s...
class experiment(): _init_args def __init__(self, config, experiments_prefix, logfile_name='log'): all_defaults = {} for key in vars(config): all_defaults[key] = get_base_parser().get_default(key) self.default_config = all_defaults config.resume = False if (no...
def test_multiplicity(precision='d'): from phcpy.solutions import make_solution pols = ['x**2+y-3;', 'x+0.125*y**2-1.5;'] sol = make_solution(['x', 'y'], [1, 2]) if (precision == 'd'): mul = standard_multiplicity(pols, sol, verbose=True) elif (precision == 'dd'): mul = dobldobl_multi...
def main(_): if (not FLAGS.dataset_dir): raise ValueError('You must supply the dataset directory with --dataset_dir') tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default(): deploy_config = model_deploy.DeploymentConfig(num_clones=FLAGS.num_clones, clone_on_cpu=FLAGS.clone_on...
def main(): warnings.filterwarnings('ignore') args = get_args() with open(args.prompts_description, 'r') as fin: original_continuations = json.loads(fin.read()) sequence2length = [(k, v[0]) for (k, v) in original_continuations.items()] assert all(((float(v) >= 6.0) for (_, v) in sequence2len...
class OA(nn.Module): def __init__(self, features, disable_gen1=False, disable_gen2=False, bn=True, relu=False, refl_pad=True): super().__init__() self.disable_gen1 = disable_gen1 self.disable_gen2 = disable_gen2 if relu: act_func = nn.ReLU else: act_fu...
def aggregate_graph(g_intermediate: nx.DiGraph, city: str, cutoff: int=9) -> nx.Graph: g_aggr = nx.Graph() coarse_nodes = [n for n in g_intermediate.nodes if (len(n) == 3)] for source in coarse_nodes: outgoing_edges = [(source, n_fine) for n_fine in g_intermediate.predecessors(source)] g_int...
def ReadFileSL(x_axis, tthread, batchInterval, NUM_ITEMS, deposit_ratio, key_skewness, overlap_ratio, abort_ratio, txn_length, isCyclic, complexity): (w, h) = (2, len(x_axis)) y = [[] for _ in range(w)] for batchInterval in x_axis: inputEvents = (tthread * batchInterval) op_gs_path = getPath...
class nnUNetTrainerV2_DA2(nnUNetTrainerV2): def setup_DA_params(self): super().setup_DA_params() self.data_aug_params['independent_scale_factor_for_each_axis'] = True if self.threeD: self.data_aug_params['rotation_p_per_axis'] = 0.5 else: self.data_aug_params[...
def fetch_data(data, count, idx_batch, vocab_size, params, labels=None): batch_size = len(idx_batch) data_batch = np.zeros((batch_size, vocab_size)) if labels: if params.multilabel: label_batch = ([([0] * params.num_labels)] * batch_size) else: label_batch = (- np.one...
class Slice(Sentence): def __init__(self, *args, **kwargs): self._start = kwargs.pop('start', 0) Sentence.__init__(self, *args, **kwargs) def start(self): return self._start def stop(self): return (self._start + len(self.words))
_model def tresnet_m_448(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['tresnet_m_448'] model = TResNet(layers=[3, 4, 11, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, defaul...
def init(name: str, sim: str=None, dataset: str=None, config: Dict=None, api_key: str=None) -> None: if (api_key is None): raise PermissionError('please input zpy api_key') global logger logger = logging.getLogger(__name__) exp = Experiment(name=name, sim=sim, dataset=dataset, config=config, api...
def test_uniform_dequantizer_returns_correct_shape(): (init_fun, bijector_info) = UniformDequantizer([1, 3, 4]) (params, forward_fun, inverse_fun) = init_fun(random.PRNGKey(0), x.shape[(- 1)]) conditions = jnp.zeros((3, 1)) (fwd_outputs, fwd_log_det) = forward_fun(params, x, conditions=conditions) a...
def test_setattr(): cfg = Config() cfg.item1 = [1, 2] cfg.item2 = {'a': 0} cfg['item5'] = {'a': {'b': None}} assert (cfg._cfg_dict['item1'] == [1, 2]) assert (cfg.item1 == [1, 2]) assert (cfg._cfg_dict['item2'] == {'a': 0}) assert (cfg.item2.a == 0) assert (cfg._cfg_dict['item5'] == ...
class PoissonProcess(PointProcess): def __init__(self, intensity: float, seed=43): super().__init__(seed) self.init_params(intensity) def init_params(self, intensity: float): if (not (intensity > 0)): raise ValueError('parameters must be positive.') self.params = Para...
def compare_graphs_undirected(true_graph, estimated_graph): num_edges = len(true_graph[np.where((true_graph != 0.0))]) tam = np.array([[(1 if (x != 0.0) else 0.0) for x in y] for y in true_graph]) tam_undir = (tam + tam.T) tam_undir = np.array([[(1 if (x != 0.0) else 0.0) for x in y] for y in tam_undir]...
def stack_states(rssm_states: list, dim): return RSSMState(torch.stack([state.mean for state in rssm_states], dim=dim), torch.stack([state.std for state in rssm_states], dim=dim), torch.stack([state.stoch for state in rssm_states], dim=dim), torch.stack([state.deter for state in rssm_states], dim=dim))
def generate_trees(source, tree_reader=ptb_read_tree, max_sents=(- 1), return_empty=False, allow_empty_labels=False, allow_empty_words=False): if (type(source) == type('')): source = open(source) count = 0 while True: tree = tree_reader(source, return_empty, allow_empty_labels, allow_empty_w...
class SupervisedTrainer(object): def __init__(self, model, data_loader, optimizer=None, criterion=None): self.global_step = 0 self.model = model.to(tt.arg.device) self.data_loader = data_loader self.optimizer = (optimizer or optim.Adam(model.parameters())) self.criterion = (c...
def train_and_eval(model, train_loader, eval_loader, tb_log, ckpt_dir, log_f): model.cuda() optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) def lr_lbmd(cur_epoch): cur_decay = 1 for decay_step in args.decay_step_list: if (cur_epoch >= decay_...
def _create_learning_rate(learning_rate_config, global_summaries, global_step): learning_rate = None learning_rate_type = learning_rate_config.WhichOneof('learning_rate') if (learning_rate_type == 'constant_learning_rate'): config = learning_rate_config.constant_learning_rate learning_rate =...
def get_model_file(model_name, local_model_store_dir_path=os.path.join('~', '.torch', 'models')): (error, sha1_hash, repo_release_tag) = get_model_name_suffix_data(model_name) short_sha1 = sha1_hash[:8] file_name = '{name}-{error}-{short_sha1}.pth'.format(name=model_name, error=error, short_sha1=short_sha1)...
class PPO_BLIP(): def __init__(self, actor_critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, use_clipped_value_loss=True): self.actor_critic = actor_critic self.clip_param = clip_param self.ppo_epoch = ppo_epoch self....
class BertweetTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, merges_file, normalization=False, bos_token='<s>', eos_token='</s>', s...
def query(string, service=GOOGLE, **kwargs): service = service.lower() if (service in (GOOGLE, 'google', 'g')): engine = Google if (service in (YAHOO, 'yahoo', 'y!')): engine = Yahoo if (service in (BING, 'bing')): engine = Bing if (service in (DUCKDUCKGO, 'duckduckgo', 'ddg'...
_config def merge_mlp(): cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'merge_method': 'merge_operators.MLP'}}}
def train(args, model, train_loader, optimizer, epoch): model.train() iteration = 0 loss_cum = 0 with tqdm(enumerate(train_loader), total=len(train_loader)) as t: for (idx, batch) in t: iteration += 1 (conv_seq, label_seq, sentence_index, token_type_seq, input_mask) = bat...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task') parser.add_argument('--task_name', type=str, default=None, help='The name of the glue task to train on.', choices=list(task_to_keys.keys())) parser.add_argument('--train_file', type=...
def SEResNeXt101(input_shape=None, input_tensor=None, weights=None, classes=1000, include_top=False, stride_size=2, init_filters=64, repetitions=(3, 4, 23, 3), **kwargs): return SENet(MODELS_PARAMS['seresnext101'], input_shape=input_shape, input_tensor=input_tensor, include_top=include_top, classes=classes, weights...
class BERTScorer(): PENALTY_SIGMA = 6.0 def __init__(self, refs=None, model_type=None, num_layers=None, verbose=False, idf=False, batch_size=16, nthreads=2, all_layers=False, lang=None, rescale_with_baseline=False, penalty=False): assert ((lang is not None) or (model_type is not None)), 'Either lang or ...
def get_coo_indexes(lil): rows = [] cols = [] for (i, el) in enumerate(lil): if (type(el) != list): el = [el] for j in el: rows.append(i) cols.append(j) return (rows, cols)
def get_scores(trainer, problems): t = time.time() (metrics, logging) = trainer.run_validation_epoch(trainer.training_state, problems) jax.tree_map((lambda x: x.block_until_ready()), metrics) metrics['total_time'] = (time.time() - t) if (trainer.config.num_devices > 1): metrics = reduce_from...
_torch class TestConversionUtils(unittest.TestCase): def test_renaming_multilingual(self): old_names = ['opus-mt-cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh-fi', 'opus-mt-cmn+cn-fi', 'opus-mt-en-de', 'opus-mt-en-de'] expected = ['opus-mt-ZH-fi', 'opus-mt-cmn_cn-fi', 'opus-mt-en-...
def get_poi_xy(): poi2xy = {} f_i = open('poi2_xy') readlines = f_i.readlines() f_i.close() for line in readlines: new_line = line.strip().split('\t') poi = int(new_line[0]) x = float(new_line[1]) y = float(new_line[2]) poi2xy[poi] = [x, y] return poi2xy
class CAPEval(object): def __init__(self, taskpath, seed=1111): logging.debug('***** Transfer task : Coreference Arc Prediction binary Classification*****') self.seed = seed logging.debug('***** Task path: {}*****\n\n'.format(taskpath)) train = self.loadFile(os.path.join(taskpath, 't...
class TFBytesDataset(TFDataset): def get_num_partitions(self): return self.train_rdd.getNumPartitions() def __init__(self, string_rdd, batch_size, batch_per_thread, hard_code_batch_size=False, validation_string_rdd=None, sequential_order=False, shuffle=True): import tensorflow as tf tens...
def parse_sum_group_component(component, line, line_buffer): line = consume_token(component, line) line = consume_token('<Sizes>', line) sizes = line.strip().strip('[]').strip().replace(' ', ',') return {'<Sizes>': sizes}
(scope='module') def lapicque_reset_none_instance(): return snn.Lapicque(beta=0.5, reset_mechanism='none')
def save_df(data: pd.DataFrame, filename: str) -> None: if filename.lower().endswith('csv'): data.to_csv(filename) elif filename.lower().endswith('parquet'): data.to_parquet(filename) else: raise ValueError(f'DataFrame {filename} is an unsupported type')
def plasma_data_creator(meta_data, object_store_address, workers_per_node=1, batch_size=1): def create_plasma_dataloader(config): dataset = PlasmaNDArrayDataset(meta_data, object_store_address, workers_per_node, batch_size) loader = DataLoader(dataset, batch_size=None, shuffle=False, collate_fn=None...
def main(): flags = initialize() logging.debug(f'Loading from {flags.in_path}') a = np.load(flags.in_path, allow_pickle=True) all_results_3d = {} for (image_path, coords3d_pred) in zip(a['image_path'], a['coords3d_pred_world']): image_path = image_path.decode('utf8') all_results_3d.s...
def load_image(image_file: Union[(PurePath, str)], target_size: Tuple[(int, int)]=None, grayscale: bool=False, img_formats: List[str]=IMG_FORMATS) -> np.ndarray: try: img = Image.open(image_file) if (img.format not in img_formats): logger.warning(f'Invalid image format {img.format}!') ...
def _cast_if_autocast_enabled(*args): if (not torch.is_autocast_enabled()): return args else: return torch.cuda.amp.autocast_mode._cast(args, torch.get_autocast_gpu_dtype())
def step(params, X, y, opt_state): loss = mll_loss(params, X, y) grads = dloss(params, X, y) opt_state = opt_update(0, grads, opt_state) params = get_params(opt_state) return (params, opt_state, loss)
class MPTTSModelForCausalLM(TSModelForCausalLM): def forward(self, input_ids: torch.LongTensor=None, attention_mask: Optional[torch.FloatTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, **kwargs) -> CausalLMOutputWithPast: if (attention_mask is None): attention_mask = to...
def set_degree_of_denominator(deg, vrblvl=0): if (vrblvl > 0): print('in set_degree_of_denominator, deg :', deg) return set_parameter_value(3, deg, vrblvl)
class LRN2D(ZooKerasLayer): def __init__(self, alpha=0.0001, k=1.0, beta=0.75, n=5, dim_ordering='th', input_shape=None, **kwargs): super(LRN2D, self).__init__(None, float(alpha), float(k), float(beta), n, dim_ordering, (list(input_shape) if input_shape else None), **kwargs)
_arg_scope def stack_blocks_dense_split(net, blocks, n_branches=1, split_at_block=3, output_stride=None, store_non_strided_activations=False, outputs_collections=None): current_strides = [1] rates = [1] nets = [net] for (i_block, block) in enumerate(blocks): if (i_block == split_at_block): ...
def resolve_rval_symbols(node: Union[(str, ast.AST)], should_update_usage_info: bool=True) -> Set[Symbol]: if isinstance(node, str): node = ast.parse(node).body[0] if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)): node = node.value rval_symbols = ResolveRvalSymbols(should_upda...
def test_wrap_experiment_builds_git_archive_deleted_files(): prefix = 'wrap_exp_test_builds_git_archive_deleted_files' exp_path = pathlib.Path(os.getcwd(), 'data/local', prefix) _hard_rmtree(exp_path) expected_path = ((exp_path / 'test_exp') / 'launch_archive.tar.xz') with tempfile.TemporaryDirector...
class BACE(MoleculeCSVDataset): def __init__(self, smiles_to_graph=smiles_2_dgl, load=False, log_every=1000, cache_file_path='./bace_dglgraph.bin', n_jobs=1): self._url = 'dataset/bace.zip' data_path = (get_download_dir() + '/bace.zip') dir_path = (get_download_dir() + '/bace') downl...
def load_model_from_config(config, ckpt): print(f'Loading model from {ckpt}') pl_sd = torch.load(ckpt) sd = pl_sd['state_dict'] model = instantiate_from_config(config.model) (m, u) = model.load_state_dict(sd, strict=False) model.cuda() model.eval() return model
def test_predict_2_classes(): check_predictions(LogisticRegression(), X, Y1) check_predictions(LogisticRegression(), X_sp, Y1) check_predictions(LogisticRegression(lambda_1=0.001), X, Y1) check_predictions(LogisticRegression(lambda_1=0.001), X_sp, Y1) check_predictions(LogisticRegression(fit_interce...