code
stringlengths
101
5.91M
class DummyArmController(): def __init__(self, _): self.state = 'idle' self.gripper_state = 'open' self.target_ee_pos = None self.arm_heading = 0 self.queue = Queue() def disconnect(self): pass def execute_command(self, command): self.queue.put(command...
_flax class FlaxAutoModelTest(unittest.TestCase): def test_bert_from_pretrained(self): for model_name in ['bert-base-cased', 'bert-large-uncased']: with self.subTest(model_name): config = AutoConfig.from_pretrained(model_name) self.assertIsNotNone(config) ...
def evaluate(gold_ud, system_ud, deprel_weights=None): class Score(): def __init__(self, gold_total, system_total, correct, aligned_total=None): self.precision = ((correct / system_total) if system_total else 0.0) self.recall = ((correct / gold_total) if gold_total else 0.0) ...
class TestBoxMode(unittest.TestCase): def _convert_xy_to_wh(self, x): return BoxMode.convert(x, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS) def _convert_xywha_to_xyxy(self, x): return BoxMode.convert(x, BoxMode.XYWHA_ABS, BoxMode.XYXY_ABS) def _convert_xywh_to_xywha(self, x): return BoxMode....
def train_new_models(dir, iter, srand, num_jobs, num_archives_processed, num_archives, raw_model_string, egs_dir, apply_deriv_weights, min_deriv_time, max_deriv_time_relative, l2_regularize, xent_regularize, leaky_hmm_coefficient, momentum, max_param_change, shuffle_buffer_size, num_chunk_per_minibatch_str, frame_subsa...
def gaussian(window_size, sigma): gauss = torch.Tensor([exp(((- ((x - (window_size // 2)) ** 2)) / float((2 * (sigma ** 2))))) for x in range(window_size)]) return (gauss / gauss.sum())
class Vocabulary(): def __init__(self, excluds_stopwords=True, wordfreq_threshold=10): self.vocas = [] self.vocas_id = dict() self.wordfreq = [] self.excluds_stopwords = excluds_stopwords self.wordfreq_threshold = wordfreq_threshold def gen_vocabs(self, corpus, prev_voca,...
class PrefetchOnGPUs(PrefetchDataZMQ): def __init__(self, ds, gpus, pipedir=None): self.gpus = gpus super(PrefetchOnGPUs, self).__init__(ds, len(gpus), pipedir) def start_processes(self): with mask_sigint(): for (gpu, proc) in zip(self.gpus, self.procs): with ...
def write_tf_session_graph(sess, model_name='model.pb', output_name='sr_output'): graph_def = sess.graph.as_graph_def() for node in graph_def.node: node.device = '' constant_graph = tf.graph_util.convert_variables_to_constants(sess, graph_def, output_node_names=[output_name]) tf.io.write_graph(c...
def n_colors(lowcolor, highcolor, n_colors): diff_0 = float((highcolor[0] - lowcolor[0])) incr_0 = (diff_0 / (n_colors - 1)) diff_1 = float((highcolor[1] - lowcolor[1])) incr_1 = (diff_1 / (n_colors - 1)) diff_2 = float((highcolor[2] - lowcolor[2])) incr_2 = (diff_2 / (n_colors - 1)) color_t...
def test_early_stopping_restore_weights_with_state(): wide = Wide(np.unique(X_wide).shape[0], 1) deeptabular = TabMlp(column_idx=column_idx, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):], mlp_hidden_dims=[16, 8]) model = WideDeep(wide=wide, deeptabular=deeptabular) fpath = 'tests/test_mo...
def _fix_wst(ex): def _fix_span_text(k): text = ex[(k + '_text')] index = ex[(k + '_index')] if (text in ex['text']): return if (text in ('Kamenev and Zinoviev', 'Kamenev, Zinoviev, and Stalin')): return if ('theyscold' in text): ex['text']...
def tensors_to_numpy(tensors, dtype=None): if isinstance(dtype, tf.DType): dtype = dtype.as_numpy_dtype if isinstance(tensors, (list, tuple)): return type(tensors)((tensors_to_numpy(tensor, dtype) for tensor in tensors)) elif isinstance(tensors, dict): return {key: tensors_to_numpy(v...
def apogeeFieldPath(dr=None): if (dr is None): dr = _default_dr() if ((dr == '11') or (dr == '12')): platename = 'apogeeField.fits' elif ((int(dr) > 13) & (int(dr) <= 15)): platename = 'apogee2Field.fits' elif (int(dr) >= 16): platename = 'allField.fits' else: ...
def parse_subset_size_0to1(dataset_name): if re.search('cifar([\\d]+)', dataset_name): percent_str = re.search('cifar([\\d]+)', dataset_name).group(0).split('cifar')[(- 1)] assert (len(percent_str) >= 2), 'require to has length at least 2' percent_float = (int(percent_str) / (10 ** len(perce...
def _graph_network_no_edge_update(graph_tuple): update_node_fn = (lambda n, se, re, g: n) update_edge_fn = None update_global_fn = (lambda gn, ge, g: g) net = nn.GraphNetwork(update_edge_fn, update_node_fn, update_global_fn) return net(graph_tuple)
class LSTMModel(Model): def __init__(self, output_dim, hidden_dim, name=None, hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), recurrent_nonlinearity=tf.nn.sigmoid, recurrent_w_init=tf.initializers.glorot_uni...
def compute_classification_metric(p: EvalPrediction): predictions = p.predictions.argmax(axis=1) references = p.label_ids metric = accuracy(predictions=predictions, references=references) metric.update(precision(predictions=predictions, references=references)) metric.update(recall(predictions=predic...
class Decoder(Generic[Action], ABC): def action_space(self) -> gym.Space: def decode(self, ctx: Context, action: Action) -> List[Tuple[(AgentID, MsgPayload)]]: def chain(self, others: Iterable['Decoder']) -> 'ChainedDecoder': return ChainedDecoder(flatten([self, others])) def reset(self): de...
def save_videos_grid_pil(videos: List[PIL.Image.Image], path: str, rescale=False, n_rows=4, fps=8): videos = rearrange(videos, 'b c t h w -> t b c h w') outputs = [] for x in videos: x = torchvision.utils.make_grid(x, nrow=n_rows) x = x.transpose(0, 1).transpose(1, 2).squeeze((- 1)) ...
_model def resnetv2_50x3_bitm_in21k(pretrained=False, **kwargs): return _create_resnetv2_bit('resnetv2_50x3_bitm_in21k', pretrained=pretrained, num_classes=kwargs.pop('num_classes', 21843), layers=[3, 4, 6, 3], width_factor=3, **kwargs)
def read_images_from_disk2(input_queue, size1=64): label = input_queue[2] fn = input_queue[0] file_contents = tf.read_file(input_queue[0]) file_contents2 = tf.read_file(input_queue[1]) example = tf.image.decode_jpeg(file_contents, channels=3) example2 = tf.image.decode_jpeg(file_contents2, chann...
def stats(criterion, a, y, mask): if (mask is not None): (_, preds) = t.max(a.data, 2) (batch, sLen, c) = a.size() loss = criterion(a.view((- 1), c), y.view((- 1))) m = t.sum(mask) mask = _sequence_mask(mask, sLen) acc = (t.sum((mask.data.float() * (y.data == preds).f...
def prepare_ref(lines: List[str], ltp_tokenizer: LTP, bert_tokenizer: BertTokenizer): ltp_res = [] for i in range(0, len(lines), 100): res = ltp_tokenizer.seg(lines[i:(i + 100)])[0] res = [get_chinese_word(r) for r in res] ltp_res.extend(res) assert (len(ltp_res) == len(lines)) b...
def get_remote_dir_to_local(remote_dir, local_dir, over_write=False): file_list = get_file_list(remote_dir) [get_remote_file_to_local(file, os.path.join(local_dir, os.path.basename(file)), over_write=over_write) for file in file_list]
class BatchInput(collections.namedtuple('BatchInput', ('key_input', 'val_input', 'input_lens', 'target_input', 'target_output', 'output_lens', 'group', 'group_lens', 'group_cnt', 'target_type', 'target_type_lens', 'text', 'slens', 'category'))): pass
class Wav2Vec2CTCTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, bos_token='...
class DataLoader(): max_time_num: int full_node_list: list node2idx_dict: dict node_num: int has_cuda: bool def __init__(self, node_list, max_time_num, has_cuda=False): self.max_time_num = max_time_num self.full_node_list = node_list self.node_num = len(self.full_node_lis...
class EnglishSpellingNormalizer(): def __init__(self): mapping_path = os.path.join(os.path.dirname(__file__), 'english.json') self.mapping = json.load(open(mapping_path)) def __call__(self, s: str): return ' '.join((self.mapping.get(word, word) for word in s.split()))
class FLSampler(Sampler): def __init__(self, indices_partition: List[List], num_round, data_per_client, client_selection, client_per_round=None): self.sequence = [] num_partition = len(indices_partition) range_partition = list(range(num_partition)) copy_list_ind = deepcopy(indices_pa...
def split_ds(ds, split=[0.8, 0.2, 0.0], shuffle=True): split_sum = sum(split) if (split_sum == 0): raise Exception('Split cannot sum to 0.') split = np.array(split) split /= split_sum ds_len = len(ds) inds = np.arange(ds_len) if shuffle: np.random.shuffle(inds) start_idx ...
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_...
class PolySineTX(PolyGenerator): def help(self): return 'Used for Hamiltonian simultion for time tau. Error is epsilon' def generate(self, tau=10.0, epsilon=0.1, return_coef=True, ensure_bounded=True, return_scale=False): r = scipy.optimize.fsolve((lambda r: ((((np.e * np.abs(tau)) / (2 * r)) **...
class ImprovementEmitter(EmitterBase): def __init__(self, archive, x0, sigma0, selection_rule='filter', restart_rule='no_improvement', weight_rule='truncation', bounds=None, batch_size=None, seed=None): self._rng = np.random.default_rng(seed) self._batch_size = batch_size self._x0 = np.array...
_function('ger') class AutogradGer(AutogradFunction): def forward(ctx, input, other): ctx.save_multiple_for_backward([input, other]) return input.ger(other) def backward(ctx, grad_output): (input, other) = ctx.saved_tensors return (grad_output.matmul(other), input.matmul(grad_out...
class SparseBasicBlock(BasicBlock, spconv.SparseModule): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, conv_cfg=None, norm_cfg=None): spconv.SparseModule.__init__(self) BasicBlock.__init__(self, inplanes, planes, stride=stride, downsample=downsample, conv_cfg=conv...
def add_noise(input): ns = torch.normal(mean=torch.zeros(input.shape[0], input.shape[1], config.noise_res, config.noise_res), std=config.noise_std).to(config.device) ns = F.interpolate(ns, size=config.image_size, mode='bilinear', align_corners=True) roll_x = random.choice(range(config.image_size)) roll_...
def val_epoch(model, val_loader, val_transform, criterion): if (args.dataset == 'ICBHI'): TP = [0, 0, 0, 0] GT = [0, 0, 0, 0] elif (args.dataset == 'SPRS'): TP = [0, 0, 0, 0, 0, 0, 0] GT = [0, 0, 0, 0, 0, 0, 0] epoch_loss = 0.0 model.eval() with torch.no_grad(): ...
class IGCV3(nn.Module): def __init__(self, channels, init_block_channels, final_block_channels, in_channels=3, in_size=(224, 224), num_classes=1000): super(IGCV3, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() self.featu...
_model def resnet26(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['resnet26'] model = ResNet(Bottleneck, [2, 2, 2, 2], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, ...
def test_add_edges_max(g1, g2): assert (g1.num_e == 2) g1.add_edges((3, 2), e_weight=0.5, merge_op='max') assert (g1.num_e == 3) assert ((2, 3) in g1.e[0]) assert ((3, 2) not in g1.e[0]) assert (g1.A[(3, 2)] == 0.5) assert (g2.num_e == 3) g2.add_edges(((1, 2), (1, 3)), e_weight=[0.1, 0.2...
def double_double_cascade_step(dim, embsys, esols, tasks=0): from phcpy.phcpy2c3 import py2c_copy_dobldobl_container_to_start_system from phcpy.phcpy2c3 import py2c_copy_dobldobl_container_to_start_solutions from phcpy.phcpy2c3 import py2c_dobldobl_cascade_homotopy from phcpy.phcpy2c3 import py2c_solve_...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None, TCP_module=None): super(ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d ...
def _create_skresnet(variant, pretrained=False, **kwargs): return build_model_with_cfg(ResNet, variant, pretrained, default_cfg=default_cfgs[variant], **kwargs)
def get_strategy(load_strategy): status = True data = None if isinstance(load_strategy, str): try: with open(load_strategy, 'rb') as fp: data = fp.read() except Exception as e: logger.error(e) status = False elif isinstance(load_strateg...
def is_cudnn_snafu(exception): return (isinstance(exception, RuntimeError) and (len(exception.args) == 1) and ('cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.' in exception.args[0]))
def _f_p_r_2(l, m, n): r = ((l / m) if (m > 0) else 0.0) p = ((l / n) if (n > 0) else 0.0) beta = (p / (r + 1e-12)) num = (((1 + (beta ** 2)) * r) * p) denom = (r + ((beta ** 2) * p)) f = (num / (denom + 1e-12)) return (f, p, r)
_DENSEPOSE_HEAD_REGISTRY.register() class DensePoseDeepLabHead(nn.Module): def __init__(self, cfg: CfgNode, input_channels: int): super(DensePoseDeepLabHead, self).__init__() hidden_dim = cfg.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_DIM kernel_size = cfg.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_KERNEL ...
class LoggerHook(Hook): __metaclass__ = ABCMeta def __init__(self, interval=10, ignore_last=True, reset_flag=False, by_epoch=True): self.interval = interval self.ignore_last = ignore_last self.reset_flag = reset_flag self.by_epoch = by_epoch def log(self, runner): pas...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--eval_model', type=str, default='', help='evaluation model path') parser.add_argument('--data_dir', type=str, default='./data', help='data directory') args = parser.parse_args() logging.root.handlers = [] logging.basicConfig(le...
def desirable(tag): return ((tag[0] in ['paragraph', '-', '[']) or ((tag[1] in ['CD']) and tag[0].isdigit()))
def test_env_supertype_in_env_bad(): with pytest.raises(Exception): MockEnv(env_supertype={'xxx': 0.0})
class DataToTensor(): def __init__(self, dtype=None): if (dtype is None): dtype = torch.float self.dtype = dtype def __call__(self, data): return torch.tensor(data, dtype=self.dtype)
def project_real_images(network_pkl, dataset_name, data_dir, num_images, num_snapshots): print(('Loading networks from "%s"...' % network_pkl)) (_G, _D, Gs) = pretrained_networks.load_networks(network_pkl) proj = projector.Projector() proj.set_network(Gs) print(('Loading images from "%s"...' % datas...
def _get_train_test_by_character(plays, test_fraction=0.2): skipped_characters = 0 all_train_examples = collections.defaultdict(list) all_test_examples = collections.defaultdict(list) def add_examples(example_dict, example_tuple_list): for (play, character, sound_bite) in example_tuple_list: ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--input_corpus_path', type=str, required=True, help='Path to corpus, each line separated by tab, and the first element is id.') parser.add_argument('--input_query_path', type=str, required=True, help='Path to queries, each line separated by...
class IMDBProcessor(DataProcessor): def get_train_examples(self, data_dir): return self._create_examples(self._read_corpus(os.path.join(data_dir, 'train_tok.csv'), MR=True, clean=False, shuffle=True), 'train') def get_dev_examples(self, data_dir): return self._create_examples(self._read_corpus(o...
def plot_final_scores(): font = {'size': 12} mpl.rc('font', **font) (fig, ax) = plt.subplots(nrows=1, ncols=1, figsize=(7, 4)) outfiles = [(RESULT_DIR + 'seq2seq_sample_imagenet_%s_iter_20000.json'), (RESULT_DIR + 'seq2seq_teacher_imagenet_%s_iter_5000.json'), (RESULT_DIR + '%s_stop_agent.json'), (RESUL...
class ResultWriter(): extension: str def __init__(self, output_dir: str): self.output_dir = output_dir def __call__(self, result: dict, audio_path: str, options: dict): audio_basename = os.path.basename(audio_path) audio_basename = os.path.splitext(audio_basename)[0] output_p...
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, cover=False): output_dir = Path(args.output_dir) epoch_name = str(epoch) if (loss_scaler is not None): if cover: checkpoint_paths = [(output_dir / 'checkpoint.pth')] else: checkpoint_paths =...
def test_pieri_problem(vrblvl=0): if (vrblvl > 0): print('making a real problem ...') planes = real_osculating_planes(2, 2, 0, vrblvl) pols = make_pieri_system(2, 2, 0, planes, is_real=True, vrblvl=vrblvl) if (vrblvl > 0): for pol in pols: print(pol) if (vrblvl > 0): ...
class model(): def __init__(self, config, data, test=False): self.device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) self.config = config self.training_opt = self.config['training_opt'] self.memory = self.config['memory'] self.data = data self.t...
class Map(list): def __init__(self, function=(lambda x: x), items=[]): self._f = function self._a = items def items(self): return self._a def __repr__(self): return repr(list(iter(self))) def __getitem__(self, i): return self._f(self._a[i]) def __len__(self): ...
def mobilenet_wd4(**kwargs): return get_mobilenet(version='orig', width_scale=0.25, model_name='mobilenet_wd4', **kwargs)
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input_file', required=True, type=str) parser.add_argument('-n', '--repeat_times', required=True, type=int) parser.add_argument('-o', '--output_file', required=False, type=str) args = parser.parse_args() stream = (open(ar...
def update_loss_qf(algo, tensors, v, obs_flat, actions_flat, next_obs_flat, dones_flat, rewards_flat, policy): with torch.no_grad(): alpha = algo.log_alpha.param.exp() q1_pred = algo.qf1(obs_flat, actions_flat).flatten() q2_pred = algo.qf2(obs_flat, actions_flat).flatten() (next_action_dists_fla...
def main_MVSA(): global args, best_prec1, use_gpu args = parser.parse_args() use_gpu = torch.cuda.is_available() emb_path = os.path.join(args.data_root_path, 'glove_embedding', 'glove_embedding_{}.pkl'.format(args.text_min_count)) if os.path.exists(emb_path): print('The glove_embedding has b...
class ReadSaveImage(object): def __init__(self): super(ReadSaveImage, self).__init__() def check_path(self, fullpath): (path, filename) = os.path.split(fullpath) if (not os.path.exists(path)): os.makedirs(path)
('/savedArticles', methods=['GET']) def savedArticles(): return render_template('saves.html', endpoint='articles.savedArticles', **genArticleList(db.getSavedArticles))
def cached_path(url_or_filename: Union[(str, Path)], cache_dir: Union[(str, Path)]=None) -> str: if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if isinstance(url_or_filename, Path): url_or_filename = str(url_or_filename) if isinstance(cache_dir, Path): cache_dir = ...
def resume_model(model, cfg, pretrained_path=None): pretrained_path = (os.path.join(cfg.ckpt_dir, os.path.join(cfg.run_name, '_ckpt_latest.pth')) if (pretrained_path is None) else pretrained_path) if (not os.path.exists(pretrained_path)): logging.info(f'[RESUME INFO] no checkpoint file from path {pretra...
_model def regnety_016(pretrained=False, **kwargs): return _regnet('regnety_016', pretrained, **kwargs)
class TFPredictor(): def __init__(self, sess, outputs, inputs=None, dataset=None): if (inputs is None): (dataset, inputs) = TFPredictor._get_datasets_and_inputs(outputs) self.sess = sess self.dataset = dataset self.inputs = inputs self.tfnet = TFNet.from_session(s...
class FieldEntrySelector(EntrySelector): _SPEC_DELIM = ',' _TYPE_DELIM = ':' _RANGE_DELIM = '-' _EQUAL = '=' _ERROR_PREFIX = 'Invalid field selector specifier' class _FieldEntryValuePredicate(object): def __init__(self, name: str, typespec: str, value: str): import builtins ...
def copy_dtypes_for_restore(images, force_list=False): if ia.is_np_array(images): if force_list: return [images.dtype for _ in sm.xrange(len(images))] else: return images.dtype else: return [image.dtype for image in images]
def preprocess_data_to_merge(input_standoff_folder_gold, output_conll_folder_gold, output_conll_file_gold, input_standoff_folder_pred, output_conll_folder_pred, output_conll_file_pred): anntoconll_wlp.convert_standoff_conll_single_file(input_standoff_folder_gold, output_conll_folder_gold, output_conll_file_gold) ...
class PeriodicCheckpointerWithEval(HookBase): def __init__(self, eval_period, eval_function, checkpointer, checkpoint_period, max_to_keep=5): self.eval = hooks.EvalHook(eval_period, eval_function) self.checkpointer = hooks.PeriodicCheckpointer(checkpointer, checkpoint_period, max_to_keep=max_to_keep...
def weak_tp(guess_entities, gold_entities): tp = 0 for pred in guess_entities: for gold in gold_entities: if ((pred[0] == gold[0]) and ((gold[1] <= pred[1] <= (gold[1] + gold[2])) or (gold[1] <= (pred[1] + pred[2]) <= (gold[1] + gold[2]))) and (pred[3] == gold[3])): tp += 1 ...
class VariableGenomeDecoder(ChannelBasedDecoder): RESIDUAL = 0 PREACT_RESIDUAL = 1 DENSE = 2 def __init__(self, list_genome, channels, repeats=None): phase_types = [gene.pop() for gene in list_genome] genome_copy = copy(list_genome) super().__init__(list_genome, channels, repeats...
class NLISentenceReader(NLIReader): def read_sentences(self, filename): sentences = [] extra = {} example_ids = [] with open(filename) as f: for line in tqdm(f, desc='read'): smap = self.read_line(line) if (smap is None): ...
class Sparse(Initializer): def __init__(self, sparsity=0.1, std=0.01): self.sparsity = sparsity self.std = std def sample(self, shape): if (len(shape) != 2): raise RuntimeError('sparse initializer only works with shapes of length 2') w = floatX(np.zeros(shape)) ...
def prepare_run(args): os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(args.tf_log_level) run_name = (args.name or args.model) log_dir = os.path.join(args.base_dir, 'logs-{}'.format(run_name)) os.makedirs(log_dir, exist_ok=True) infolog.init(os.path.join(log_dir, 'Terminal_train_log'), run_name, args.slack...
class Synthesizer(Generator): def __init__(self, params=None, samprate=48000): self.gtype = 'synth' self.preset = getattr(presets, self.gtype).load_preset() self.preset['ranges'] = getattr(presets, self.gtype).load_ranges() super().__init__(params, samprate) self.setup_oscill...
def get_pretraining_cifar10(data_dir): train_data = CIFAR10Pair(numpy_file=(data_dir + 'train.npz'), class_type=classes, transform=train_transform) memory_data = CIFAR10Mem(numpy_file=(data_dir + 'train.npz'), class_type=classes, transform=test_transform_cifar10) test_data = CIFAR10Mem(numpy_file=(data_dir ...
def train_nxdo_best_response(br_player: int, scenario_name: str, nxdo_manager_port: int, nxdo_manager_host: str, print_train_results: bool=True, previous_br_checkpoint_path=None): scenario: NXDOScenario = scenario_catalog.get(scenario_name=scenario_name) if (not isinstance(scenario, NXDOScenario)): rais...
def response_function(hgf, response_function_parameters): responses = response_function_parameters[0] beliefs = hgf.node_trajectories[1]['expected_mean'] return jnp.sum(jnp.where(responses, (- jnp.log(beliefs)), (- jnp.log((1.0 - beliefs)))))
class MfbExpand(nn.Module): def __init__(self, img_feat_dim, txt_emb_dim, hidden_dim, dropout): super(MfbExpand, self).__init__() self.lc_image = nn.Linear(in_features=img_feat_dim, out_features=hidden_dim) self.lc_ques = nn.Linear(in_features=txt_emb_dim, out_features=hidden_dim) se...
def tokenize_queries(args, tokenizer): for mode in ['dev']: query_output = f'{args.output_dir}/queries.{mode}.json' tokenize_file(tokenizer, f'{args.msmarco_dir}/queries.{mode}.tsv', query_output)
class TFGPT2LMHeadModel(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def _merge_a_into_b(a, b): if (type(a) is not edict): return for (k, v) in a.iteritems(): if (not b.has_key(k)): raise KeyError('{} is not a valid config key'.format(k)) if (type(b[k]) is not type(v)): raise ValueError('Type mismatch ({} vs. {}) for config key: {}...
def random_hyperplane(vars): cf0 = str(random_complex()) tf0 = cf0.replace('j', '*i') result = tf0 for var in vars: cff = str(random_complex()) tcf = cff.replace('j', '*i') result = ((((result + '+') + tcf) + '*') + var) return (result + ';')
class CSL(CLSProcessor): def __init__(self): super().__init__(labels_origin=['0', '1'], labels_mapped=['', '']) def get_examples(self, data_dir, split): path = os.path.join(data_dir, f'{split}.json') with open(path, encoding='utf8') as f: for line in f: exampl...
def register_func(func_name, f=None, override=False): if callable(func_name): f = func_name func_name = f.__name__ if (not isinstance(func_name, str)): raise ValueError('expect string function name') ioverride = ctypes.c_int(override) def register(myf): if (not isinstance...
def _test(): import torch pretrained = False models = [airnet50_1x64d_r2, airnet50_1x64d_r16, airnet101_1x64d_r2] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) ...
def CheckArgs(args): if (args.stats_file == '-'): args.stats_file_handle = sys.stdin else: args.stats_file_handle = open(args.stats_file) if (args.filter_lexicon is not ''): if (args.filter_lexicon == '-'): args.filter_lexicon_handle = sys.stdout else: ...
_loss('nll_loss') class NLLLoss(nn.Module): def __init__(self): super().__init__() def forward(self, sample_list, model_output): scores = model_output['scores'] targets = sample_list['targets'] (_, idx) = targets.max(dim=1) loss = F.nll_loss(scores, idx, reduction='mean')...
def process(args): out_root = Path(args.output_root).absolute() out_root.mkdir(exist_ok=True) feature_root = (out_root / 'fbank80') feature_root.mkdir(exist_ok=True) for split in SPLITS: print(f'Fetching split {split}...') dataset = LIBRISPEECH(out_root.as_posix(), url=split, downloa...
def normalize(s): s = s.strip() s = re.sub('\t', ' ', s) s = _unicode_normalize('0-9A-Za-z-', s) def _maketrans(f, t): return {ord(x): ord(y) for (x, y) in zip(f, t)} s = re.sub('[]+', '-', s) s = re.sub('[--]+', '', s) s = re.sub('[~~]+', '', s) s = s.translate(_maketrans('!"#$%...
def main(): args = parser.parse_args() assert (args.dataset == 'imagenet') args.num_classes = 1000 args.IMAGE_SIZE = 224 if (args.train_url and (not os.path.exists(args.train_url))): os.makedirs(args.train_url) model = eval(args.model)(args) assert (args.convert_from is not None), 'P...
def main(): args = parse_args() accelerator = Accelerator() logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger.info(accelerator.state) logger.setLevel((logging.INFO if accelerator.is_local_main_process else loggi...